Skip to content

The OSINT investigator's workbench. One case, one folder, every tool. Local-first: your media and your investigations never leave your machine.

JavaScript

Add ontology, analysis views, and fact-time workflows (#53)

OsintMeThat586ca4cac72d
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 088dd17..400373a 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -4,15 +4,24 @@ on:
push:
branches: [main]
pull_request:
+ workflow_dispatch:
# Weekly, so the "latest deps" tripwire below reports upstream breakage even
# in quiet weeks — bit rot doesn't wait for us to push.
schedule:
- cron: "0 6 * * 1"
+permissions:
+ contents: read
+
+concurrency:
+ group: ci-${{ github.workflow }}-${{ github.event_name }}-${{ github.ref }}
+ cancel-in-progress: true
+
jobs:
backend:
- name: Backend (${{ matrix.os }}, py${{ matrix.python }})
+ name: ${{ matrix.name }}
runs-on: ${{ matrix.os }}
+ timeout-minutes: 30
strategy:
fail-fast: false
matrix:
@@ -21,38 +30,75 @@ jobs:
# Windows exe was a guess; this is what makes "works everywhere" checkable.
# Filesystem behaviour is where they actually differ — engine/scrapers.py
# swaps directories, and Windows won't delete an open file.
- os: [ubuntu-latest, windows-latest, macos-latest]
- python: ["3.12"]
include:
- - os: ubuntu-latest
+ - name: Backend (ubuntu-latest, py3.12)
+ os: ubuntu-latest
+ python: "3.12"
+ tests: all
+ - name: Backend (macos-latest, py3.12)
+ os: macos-latest
+ python: "3.12"
+ tests: all
+ # Four fresh Windows processes retain the complete suite while making
+ # progress visible and keeping the slowest shard near ten minutes.
+ - name: Backend (windows-latest, py3.12, A-F)
+ os: windows-latest
+ python: "3.12"
+ tests: tests/test_[a-f]*.py
+ - name: Backend (windows-latest, py3.12, G-L)
+ os: windows-latest
+ python: "3.12"
+ tests: tests/test_[g-l]*.py
+ - name: Backend (windows-latest, py3.12, M-R)
+ os: windows-latest
+ python: "3.12"
+ tests: tests/test_[m-r]*.py
+ - name: Backend (windows-latest, py3.12, S-Z)
+ os: windows-latest
+ python: "3.12"
+ tests: tests/test_[s-z]*.py
+ - name: Backend (ubuntu-latest, py3.11)
+ os: ubuntu-latest
python: "3.11" # the floor in requires-python
- - os: ubuntu-latest
+ tests: all
+ - name: Backend (ubuntu-latest, py3.13)
+ os: ubuntu-latest
python: "3.13" # the ceiling we've tested against
+ tests: all
steps:
- - uses: actions/checkout@v4
- - uses: astral-sh/setup-uv@v5
+ - uses: actions/checkout@v7
+ - uses: astral-sh/setup-uv@c771a70e6277c0a99b617c7a806ffedaca235ff9 # v9.0.0
with:
enable-cache: true
+ prune-cache: true
python-version: ${{ matrix.python }}
# --frozen installs uv.lock exactly and never re-resolves, so a green run
# means "these versions work", not "whatever PyPI served this morning".
# --check fails if uv.lock drifted from pyproject.toml (forgot `uv lock`).
- run: uv lock --check
- run: uv sync --frozen --extra dev
- - run: uv run pytest -q
+ - name: Run backend suite
+ if: matrix.tests == 'all'
+ run: uv run pytest -q --durations=20 --durations-min=1
+ - name: Run Windows shard with per-test progress
+ if: matrix.tests != 'all'
+ shell: bash
+ run: uv run pytest -vv ${{ matrix.tests }} --durations=20 --durations-min=1
lint:
name: Lint & type-check (backend)
runs-on: ubuntu-latest
+ timeout-minutes: 15
# One box, not the OS/version matrix: ruff and mypy read the same source
- # everywhere, so five runs would just be five identical verdicts. Python
+ # everywhere, so matrix runs would just be identical verdicts. Python
# 3.12 on purpose — mypy parses numpy's 2.x stubs, which use 3.12 syntax a
# 3.11 target chokes on. The 3.11 floor stays covered by the pytest matrix.
steps:
- - uses: actions/checkout@v4
- - uses: astral-sh/setup-uv@v5
+ - uses: actions/checkout@v7
+ - uses: astral-sh/setup-uv@c771a70e6277c0a99b617c7a806ffedaca235ff9 # v9.0.0
with:
enable-cache: true
+ prune-cache: true
python-version: "3.12"
- run: uv sync --frozen --extra dev
- run: uv run ruff check src tests
@@ -61,28 +107,31 @@ jobs:
backend-floating:
name: Backend tests (latest deps)
runs-on: ubuntu-latest
+ timeout-minutes: 60
# The lock is the safety net; this is the tripwire. It re-resolves everything
# to the newest versions our ranges allow, so an upstream release that breaks
# us surfaces here — on a scheduled run we triage — instead of in a user's
# `pip install azimut`. Advisory: a red run never blocks a merge.
+ if: github.event_name == 'schedule'
continue-on-error: true
steps:
- - uses: actions/checkout@v4
- - uses: astral-sh/setup-uv@v5
+ - uses: actions/checkout@v7
+ - uses: astral-sh/setup-uv@c771a70e6277c0a99b617c7a806ffedaca235ff9 # v9.0.0
- run: uv sync --upgrade --extra dev
- - run: uv run pytest -q
+ - run: uv run pytest -q --durations=20 --durations-min=1
frontend:
name: Frontend tests + build
runs-on: ubuntu-latest
+ timeout-minutes: 15
defaults:
run:
working-directory: frontend
steps:
- - uses: actions/checkout@v4
- - uses: actions/setup-node@v4
+ - uses: actions/checkout@v7
+ - uses: actions/setup-node@v7
with:
- node-version: "20"
+ node-version: "24.19.0"
cache: npm
cache-dependency-path: frontend/package-lock.json
- run: npm ci
@@ -93,14 +142,15 @@ jobs:
browser:
name: Browser canvas interactions
runs-on: ubuntu-latest
+ timeout-minutes: 20
defaults:
run:
working-directory: frontend
steps:
- - uses: actions/checkout@v4
- - uses: actions/setup-node@v4
+ - uses: actions/checkout@v7
+ - uses: actions/setup-node@v7
with:
- node-version: "20"
+ node-version: "24.19.0"
cache: npm
cache-dependency-path: frontend/package-lock.json
- run: npm ci
diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml
index 21d6e5f..954b056 100644
--- a/.github/workflows/release.yml
+++ b/.github/workflows/release.yml
@@ -7,16 +7,16 @@ on:
workflow_dispatch:
permissions:
- contents: write # create the GitHub release + upload assets
- id-token: write # PyPI Trusted Publishing (OIDC) — no token secret needed
+ contents: read
jobs:
guard:
name: Version + release gate
runs-on: ubuntu-latest
+ timeout-minutes: 15
steps:
- - uses: actions/checkout@v4
- - uses: astral-sh/setup-uv@v5
+ - uses: actions/checkout@v7
+ - uses: astral-sh/setup-uv@c771a70e6277c0a99b617c7a806ffedaca235ff9 # v9.0.0
with:
python-version: "3.12"
# Install the app (editable) + dev tools, like the CI backend job, so the
@@ -35,7 +35,8 @@ jobs:
echo "tag=$tag __version__=$ver"
[ "$tag" = "$ver" ] || { echo "::error::tag v$tag != __version__ $ver — bump src/azimut/__init__.py"; exit 1; }
# The version-parity gate the release workflow used to skip: pyproject's
- # single-sourced version and the extension manifest must line up.
+ # version stays single-sourced, and the capture extension's own version
+ # moves when the extension does and only then.
- name: Release gate + version parity
run: uv run --no-sync pytest tests/test_release_gate.py tests/test_updates.py -q
@@ -43,12 +44,13 @@ jobs:
name: Build wheel + sdist
needs: guard
runs-on: ubuntu-latest
+ timeout-minutes: 20
steps:
- - uses: actions/checkout@v4
- - uses: actions/setup-node@v4
+ - uses: actions/checkout@v7
+ - uses: actions/setup-node@v7
with:
- node-version: "20.20.2"
- - uses: astral-sh/setup-uv@v5
+ node-version: "24.19.0"
+ - uses: astral-sh/setup-uv@c771a70e6277c0a99b617c7a806ffedaca235ff9 # v9.0.0
with:
python-version: "3.12"
- name: Build frontend into the package
@@ -77,15 +79,17 @@ jobs:
assert not missing, f"wheel is missing PDF font assets: {missing}"
print(f"{whl}: {len(static)} static files and PDF font assets bundled")
PY
- - uses: actions/upload-artifact@v4
+ - uses: actions/upload-artifact@v7
with:
name: dist
path: dist/*
+ if-no-files-found: error
binaries:
name: Binary (${{ matrix.os }})
needs: guard
runs-on: ${{ matrix.os }}
+ timeout-minutes: 75
strategy:
fail-fast: false
matrix:
@@ -102,11 +106,11 @@ jobs:
# macos-latest is Apple Silicon. Intel remains a documented Python
# package install rather than a standalone release asset.
steps:
- - uses: actions/checkout@v4
- - uses: actions/setup-node@v4
+ - uses: actions/checkout@v7
+ - uses: actions/setup-node@v7
with:
- node-version: "20.20.2"
- - uses: astral-sh/setup-uv@v5
+ node-version: "24.19.0"
+ - uses: astral-sh/setup-uv@c771a70e6277c0a99b617c7a806ffedaca235ff9 # v9.0.0
with:
python-version: "3.12"
- name: Build frontend into the package
@@ -141,19 +145,44 @@ jobs:
else
mv dist-bin/azimut "dist-bin/${{ matrix.asset }}"
fi
- - uses: actions/upload-artifact@v4
+ - uses: actions/upload-artifact@v7
with:
name: ${{ matrix.asset }}
path: dist-bin/${{ matrix.asset }}
+ if-no-files-found: error
+
+ artifacts:
+ name: Assemble release artifacts
+ needs: [dist, binaries]
+ runs-on: ubuntu-latest
+ timeout-minutes: 10
+ steps:
+ # This also exercises the upload/download pair on manual branch runs,
+ # before a tag can reach GitHub Releases or PyPI.
+ - uses: actions/download-artifact@v8
+ with:
+ path: artifacts
+ - name: Verify the complete release set
+ shell: bash
+ run: |
+ test "$(find artifacts/dist -maxdepth 1 -type f -name '*.whl' | wc -l)" -eq 1
+ test "$(find artifacts/dist -maxdepth 1 -type f -name '*.tar.gz' | wc -l)" -eq 1
+ test -s artifacts/azimut-linux-x86_64/azimut-linux-x86_64
+ test -s artifacts/azimut-windows-x86_64.exe/azimut-windows-x86_64.exe
+ test -s artifacts/azimut-macos-arm64/azimut-macos-arm64
release:
name: GitHub release + PyPI publish
- needs: [dist, binaries]
+ needs: artifacts
runs-on: ubuntu-latest
+ timeout-minutes: 15
if: startsWith(github.ref, 'refs/tags/v')
+ permissions:
+ contents: write # create the GitHub release + upload assets
+ id-token: write # PyPI Trusted Publishing (OIDC) — no token secret needed
steps:
- - uses: actions/checkout@v4
- - uses: actions/download-artifact@v4
+ - uses: actions/checkout@v7
+ - uses: actions/download-artifact@v8
with:
path: artifacts
- name: Gather release assets (binaries + wheel/sdist)
@@ -162,7 +191,7 @@ jobs:
find artifacts -type f -exec cp {} upload/ \;
ls -l upload
- name: Create GitHub release
- uses: softprops/action-gh-release@v2
+ uses: softprops/action-gh-release@v3
with:
files: upload/*
body_path: docs/RELEASE_NOTES.md
diff --git a/README.md b/README.md
index b0f5c63..a3acae4 100644
--- a/README.md
+++ b/README.md
@@ -15,7 +15,10 @@ to fix a point on the map.*
| Tool | What it does |
|------|--------------|
+| **Board** | The whole case as one sortable table: typed identity fields per entity, one filter bar whose values are all taken from the case, and shared Details. |
+| **Graph** | The same case drawn. Lenses pick what a reading is about, nodes cluster, edges carry their verb, and a click opens what a node connects to without losing the picture you were reading. |
| **Media** | Import local files or download by URL (X, Telegram, TikTok, YouTube, Instagram and more via yt-dlp, with a gallery-dl fallback for image-only posts). Public media is fetched cookie-less; a login-walled post prompts once for a browser session or an exported `cookies.txt`. Each item gets a clean local file, metadata and a SHA-256. Multi-photo posts open a picker. |
+| **Files** | Every saved artifact in one Finder-style view of your folders, not just media: select several, drag them into a folder, search across the lot. |
| **Reverse Search** | Prepare an image or a video frame for keyless reverse-image services. Nothing uploads on its own. |
| **Inspect** | A scratch workspace over any photo or video: frame adjustments, editable crop, sharpest-frame capture, hand-made collage with per-piece warp/scale/rotate, auto-stitch to solve a panorama's layout, and ELA hints. Nothing enters the case until you save. |
| **Satellite** | Coordinates or a place name become an imagery crop, with select-area capture, map rotation, measurement tools, reference overlays and editable AOI grids for area review. Esri/OSM by default, plus Sentinel-2 with a date calendar and a cloud-ceiling slider; add a Mapbox or Google key for more basemaps. |
@@ -41,9 +44,9 @@ tools and tile caches under the hidden `~/Azimut/.azimut/` directory. Settings
Storage moves the workspace anywhere you like, including an external drive, or
adopts one you moved yourself. The old copy is kept until you delete it.
-The Case Doctor checks that a case's database and media records still match its
-files. It only changes a case after you choose a repair, and states what a
-database rebuild cannot recover before it starts.
+The Case Doctor checks case integrity, including the derived Timeline index. It
+only changes a case after you choose a repair, and states what a database rebuild
+cannot recover before it starts.
New in v0.2.7:
@@ -188,6 +191,20 @@ uv run --no-sync python -m build --no-isolation
uv run --no-sync pyinstaller packaging/azimut.spec
```
+### Versions
+
+The app version lives in `src/azimut/__init__.py` alone; `pyproject.toml` reads
+it back, and the release tag must match it.
+
+The capture extension keeps **its own** version: the app release that last
+changed a shipped file, so it lags whenever the extension is left alone.
+Settings reads "bundled newer than installed" as "go reinstall the unpacked
+folder", which is worth saying once and never for a zip that hasn't moved.
+`tests/test_updates.py` digests what `extension.zip` carries and fails either
+way — a change without a bump, or a bump without a change. When you do change
+the extension, set `extension/manifest.json` to the current app version and
+record the digest the failing test prints.
+
### Dependencies
`pyproject.toml` declares **ranges** (the contract for `pip install azimut`
diff --git a/docs/ONTOLOGY.md b/docs/ONTOLOGY.md
index 385f275..0f8bce9 100644
--- a/docs/ONTOLOGY.md
+++ b/docs/ONTOLOGY.md
@@ -11,11 +11,46 @@
file-backed visible name with its filename stem in one idempotent migration.
Schemas 4–8 were unreleased development checkpoints and normalize through the
same jump. The entity/link shape is unchanged since v1. Breaking changes require
-a manifest schema bump and migration. The internal SQLite schema is version 7;
-it adds indexes, durable jobs and recoverable trash without changing this
-logical model.
+a manifest schema bump and migration. The internal SQLite schema is at version
+17: 8 adds `links.confidence`, 9 rebuilds the entity search index so a case
+search reaches the declared fields (§2) rather than stopping at the label and the
+notes, 11 adds `links.nature` — what kind of tie an edge states, in the analyst's
+own words, and only where the verb declares a qualifier (§3) — and 10 adds
+`graph_pins`, where the analyst dragged a node on the graph
+canvas. That is presentation, not an assertion about the case, which is why it is
+a table of its own and not a key in `attrs`: an entity keeps identity, links and
+provenance (§1). It is keyed by **lens** as well as by entity, because a lens is a
+reading — it draws its own nodes and edges and clusters them differently, so one
+shared arrangement would anchor every reading into the shape of whichever one it was
+built in. It cascades with the entity, so a deleted node leaves no pin for a reissued
+id to inherit, and a restore brings the node back placed by the layout.
+Schema 12 adds `entity_images`: ordered presentation images for `person`,
+`organization`, `vehicle`, `vessel`, `aircraft`, `structure` and
+`equipment-type`, with at most one primary image per entity. A row either owns a
+private, bounded presentation file imported from the computer or references an
+existing image `media` or `capture`. A computer import creates no Media entity
+and never enters the Media Library. A Media reference does not state
+`appears-in`, and detaching it does not delete the media. The first attachment
+becomes primary, and the next is promoted when the primary disappears. Trash
+and bundles carry both forms.
+Schema 13 adds `analysis_views`. These are named readings of the case, not entities
+or findings. A live row stores a Board or Graph recipe, while a snapshot copies the
+captured entities, provenance, closed relations and bounded preview thumbnails. They
+stay tied to their case, travel only with its complete bundle and never create graph
+edges. Live graph pins and camera are presentation owned by that view, separate from
+the case-wide arrangement. Their denormalised snapshot count lets the Views menu avoid
+parsing or transferring a capture merely to say how many entities it holds.
+Schema 14 indexes `label` (under `NOCASE`) and `prov_at`, the two columns the
+catalog orders the whole case by. Nothing about the vocabulary changes: it is the
+index the ordering was already asking for.
+Schema 15 adds the rebuildable temporal projection. Claims and media metadata remain
+authoritative. Schema 16 lets Analysis Views own Timeline recipes and immutable
+temporal snapshots. Schema 17 rebuilds temporal bounds at fixed microsecond width so
+SQLite text ordering stays chronological. A Timeline view stores presentation and
+track queries, never copies temporal rows into the graph and never creates a temporal
+relation.
-Legend: ✅ implemented in code · 🔶 machinery exists, unused · ⬜ proposed.
+Legend: ✅ implemented in code · ⬜ proposed.
---
@@ -25,13 +60,16 @@ Legend: ✅ implemented in code · 🔶 machinery exists, unused · ⬜ proposed
presents it as this logical shape:
```jsonc
-{ "entities": [ … ], "links": [ … ], "folders": [ … ] }
+{ "entities": [ … ], "links": [ … ], "folders": [ … ], "entity_images": [ … ],
+ "analysis_views": [ … ] }
```
- **Entities** are nodes such as files, points, proofs and people. ✅
- **Links** are typed directed edges. Every save records its inputs; see §3. ✅
- **Folders** are `/`-nested analyst buckets in `attrs.folder`, not semantic
links. ✅
+- **Entity images** are ordered presentation attachments, not graph edges. ✅
+- **Analysis views** are case-owned presentation state, not graph assertions. ✅
- Media sidecars hold kind, size, uploader, duration, thumbnail data, image EXIF
and perceptual hashes, plus ffprobe's video container and stream metadata. A
stated position lands on one field, `gps`, whichever of the two read it. A
@@ -51,7 +89,10 @@ presents it as this logical shape:
```
`type` is extensible: unknown strings are stored but receive no custom renderer.
-`label` is editable and never defines identity.
+`label` is editable. For identifiers it is the value that names the identity, so the
+registry gives that field a type-specific reading such as **IP address**, **Handle**
+or **Network or CIDR** instead of showing a generic **Name** box. Other fields stay in
+`attrs`; the primary value is never duplicated there.
`geo` is the country a saved point falls in, resolved once and kept:
`{state, country_code, country, region?, region_en?}` with `state` one of `ok`,
@@ -62,29 +103,370 @@ and is absent when it failed or matched the native name. Continent and the
English country name are *not* stored: both are derived from `country_code` at
read time, so extending those tables repairs existing cases with no migration.
+### Families
+
+`engine/entities.py` is the one registry of entity types, and each type declares a
+**family**. Relations start from families and narrow endpoints where a verb is more
+specific (§3). A broad verb such as `owns` can extend to a new asset, while
+`sited-at` remains structure-only. `GET /api/cases/entity-types` serves the
+registry — type, reading, family, icon, and the fields an analyst may fill — so a
+create form is generated rather than written per type. ✅
+
+A type, a family, a verb, a rating level and a declared field each carry a `hint`:
+one clause served with the registry and shown as the tooltip wherever the word
+appears, so no screen writes its own wording. `tests/test_entities.py` holds them
+to one clause — no full stop, no em-dash, under a hundred characters.
+
+| Family | Reads as | Members |
+|---|---|---|
+| `actor` | a person or organization that can act or hold ownership | `person`, `organization` |
+| `asset` | it is owned, appears, sits somewhere | `vehicle`, `vessel`, `aircraft`, `structure` |
+| `class` | a model the case counts with, never one particular object | `equipment-type` |
+| `identifier` | a handle on a system | `account`, `email`, `phone`, `domain`, `ip`, `network` |
+| `collected` | bytes gathered into the case rather than written, so one may depict a place | `media`, `capture` |
+| `document` | it is read rather than gathered: made or consulted | `proof`, `post`, `note`, `inspect-session`, `bookmark` |
+| `place` | a point, never a thing | `place` |
+| `claim` | a statement about the graph, carrying its own reasoning | `claim` |
+
+**`attrs.kind` is what a media is**: `image`, `video`, `audio` or `file`, stamped by
+the importer from the MIME type, falling back to the extension for entities filed
+before that attr existed, and `file` for anything unrecognised. Every surface draws
+the icon off it rather than off the type. A PDF is a `media` of kind `file` until
+text extraction ships — a native dependency on three platforms, the same gate as
+OCR.
+
+Adding a type is one registry entry plus one in `artifacts.NO_FILES` or `KINDS`.
+Adding a *family* means deciding its verbs: the families are the commitment, the
+types are disposable. Why the families are cut where they are — `actor` apart from
+`asset`, `collected` rather than *imagery* or *material*, geometry on `place`
+alone — is argued in `engine/entities.py`'s module docstring, beside the code it
+governs.
+
+### Roles ✅
+
+Beside its family, a type declares a **role**: what it is for once the case is
+*drawn*. A family says what a thing is and decides its verbs; a role says whether a
+picture of the case is about it. The line that matters is between the first two —
+**the file is a subject, its wrapper is an edge**.
+
+| Role | Reads as | Members | In the drawing |
+|---|---|---|---|
+| `subject` | the case is about it | `person`, `organization`, `vehicle`, `vessel`, `aircraft`, `structure`, `equipment-type`, `account`, `email`, `phone`, `domain`, `ip`, `network`, `media`, `place`, `claim` | a node |
+| `attestation` | a wrapper around something the case already holds | `bookmark`, `proof`, `capture` | folded into the edge that carries its provenance, drawn or not (below) |
+| `annex` | consulted rather than seen, hanging off one node | `note`, `inspect-session` | out of the case readings, drawn by **My work** |
+| `deliverable` | what the case produced | `post` | out of the case readings, drawn by **My work** |
+
+A bookmark stays drawn because it is not a leaf: *this account posted it, this
+statement cites it* is a path through it, and that path is a fact about the case. A
+note and a post carry no path, so they are the filing rather than the case.
+
+`manual` was checked first and does not answer this: `media` and `place` are not
+manual and are subjects, `post` is not manual and is a deliverable, `claim` is manual
+and is a subject. A type has **no default role** — a new one decides, or it would
+answer by omission (`tests/test_entities.py`).
+
### Entity type registry
-| Type | State | Produced by | Key `attrs` | File-backed |
-|---|---|---|---|---|
-| `media` | ✅ | media-library | `path`, `sha256`, `source_url?` | yes (+ sidecar) |
-| `capture` | ✅ | satellite | `coords`, `lat`, `lon`, `plus_code`, `zoom`, `bearing`, `path`, `geo?` | yes (image) |
-| `place` | ✅ | satellite, ingest, enrich | `coords`, `lat`, `lon`, `plus_code`, `zoom`, `bearing`, `notes?`, `geo?`, `source_url?`, `site?`, `enrich_coord_key?` | no (a point) |
-| `proof` | ✅ | proof-composer | `spec` (json), `path` (png) | yes |
-| `post` | ✅ | post-composer | `draft` (json) | yes |
-| `inspect-session` | ✅ | inspect | `spec` (json) | yes |
-| `note` | ✅ | notebook | `path`, `folder?` | yes (Markdown) |
-| `person` | ⬜ | manual / future | name attrs | no |
-| `organization` | ⬜ | manual / future | | no |
-| `alias` / `account` | ⬜ | future orchestrator | `platform`, `handle`, `url` | no |
-| `email` `phone` `domain` `ip` | ⬜ | future | the identifier | no |
-| `vehicle` | ⬜ | future (OCR plate) | `plate`, `make` | no |
-| `event` | ⬜ | future (EXIF, timeline) | `when`, `where` | no |
-
-New types coming from the roadmap (declare here when built): `panorama`,
-`ground-image`, `map-board`, `report`.
-
-Per-type attribute schemas remain open work. Today attribute keys are conventions,
-not a validated contract between tools.
+| Type | Family | Role | State | Produced by | Key `attrs` | File-backed |
+|---|---|---|---|---|---|---|
+| `media` | collected | subject | ✅ | media-library | `path`, `sha256`, `source_url?` | yes (+ sidecar) |
+| `capture` | collected | attestation | ✅ | satellite | `coords`, `lat`, `lon`, `plus_code`, `zoom`, `bearing`, `path`, `geo?` | yes (image) |
+| `place` | place | subject | ✅ | satellite, ingest, enrich | `coords`, `lat`, `lon`, `plus_code`, `zoom`, `bearing`, `notes?`, `geo?`, `source_url?`, `site?`, `enrich_coord_key?`, plus the precision fields below | no (a point) |
+| `proof` | document | attestation | ✅ | proof-composer | `spec` (json), `path` (png) | yes |
+| `post` | document | deliverable | ✅ | post-composer | `draft` (json) | yes |
+| `inspect-session` | document | annex | ✅ | inspect | `spec` (json) | yes |
+| `note` | document | annex | ✅ | notebook | `path`, `folder?` | yes (Markdown) |
+| `bookmark` | document | attestation | ✅ | capture extension | `url`, `fetched_at?`, `archive_url?`, `reliability?` | no (a URL) |
+| `person` | actor | subject | ✅ | analyst | `aliases`, `role`, `nationality` | no |
+| `organization` | actor | subject | ✅ | analyst | `echelon`, `country` | no |
+| `vehicle` | asset | subject | ✅ | analyst | `plate`, `make`, `model`, `colour`, `condition` | no |
+| `vessel` | asset | subject | ✅ | analyst | `imo`, `mmsi`, `flag`, `kind`, `condition` | no |
+| `aircraft` | asset | subject | ✅ | analyst | `registration`, `icao24`, `model`, `condition` | no |
+| `structure` | asset | subject | ✅ | analyst | `kind`, `address`, `condition` | no |
+| `equipment-type` | class | subject | ✅ | analyst | `category`, `aliases` | no |
+| `account` | identifier | subject | ✅ | analyst | handle in the label; `platform?`, `url`, `reliability?` | no |
+| `email` | identifier | subject | ✅ | analyst | address in the label | no |
+| `phone` | identifier | subject | ✅ | analyst | number in the label; `country?` | no |
+| `domain` | identifier | subject | ✅ | analyst | hostname in the label; `registrar?` | no |
+| `ip` | identifier | subject | ✅ | analyst | address in the label; legacy read-only `network?`; `asn?`, `provider?` | no |
+| `network` | identifier | subject | ✅ | analyst | network/CIDR in the label; `asn?`, `provider?`, `country?` | no |
+| `claim` | claim | subject | ✅ | analyst | `count`, `condition`, `when`, `time_role`, `confidence`, `method`, `verbatim` | no |
+
+Every row is created by something: the tool-born ones by the save that produces them,
+the analyst's own from the board's **New entity**, which builds its form out of the
+fields declared here.
+
+Three modelling calls the table alone does not show:
+
+- **`alias` is folded into `account`**, whose `platform` is optional.
+- **A plate, an IMO and an MMSI are fields, not entities.** An identifier is worth
+ minting the day a value turns up without its object.
+- **`registration` and `icao24` belong to an airframe; a callsign belongs to a
+ flight**, which is a dated statement rather than an attribute.
+
+Retired: `event` (replaced by the claim node), `alias` (see above), and `panorama`
+(Inspect's auto-stitch export is a derived `media`). Still coming from the roadmap,
+to declare here when built:
+
+| Type | Family | Shape | Note |
+|---|---|---|---|
+| `grid` | document | a spec, like `inspect-session` | Grid Search already writes `.search/<name>.json`; it is **the only saved tool state outside the graph**, so today nothing can say "this sweep is how I found it" |
+| `sky-session` | document | a spec, like `inspect-session` | a sun or moon lookup: the point, the date and the time, **never the numbers**. Reopening recomputes; a proof that shows the reading is what freezes it, exactly as a `proof` pairs an editable `spec` with an exported `path` |
+| `ground-image` | collected | file-backed | a provider and a position of its own, which an imported media has not |
+| `report` | document | file-backed | a distinct artifact, like `proof` |
+
+`grid` and `sky-session` are the same shape as `inspect-session` and belong in
+`artifacts.KINDS` rather than `NO_FILES`, so each arrives with delete, Trash and
+bundle behaviour to settle. They only become worth relating once a statement can
+`cites` them (SPEC §6, v3).
+
+Attribute schemas are declared for the analyst-entered types and served with the
+registry; the tool-born types keep tool-owned `attrs`, which stay conventions rather
+than a validated contract. **A declared attr means *a field an analyst may fill*,
+never *everything this type holds*** — that is what keeps validation additive, since
+no key a tool already writes is judged by it.
+
+A declared field says how it is edited: `text`, `longtext`, `number`, `url`,
+`choice`, `geojson`, `temporal`. `longtext` stores and validates exactly what `text`
+does; it says the field expects sentences, so it gets a box that grows. A `number`
+may declare its bounds, its shortcut rungs, and whether it is `whole` — a count steps
+by one, where a radius in metres does not.
+
+A field may also declare the `group` that **heads it and the fields after it**, which
+is what lets one type hold several subjects: a Claim says what it states, when it
+applies and why that is believed, where a place's four fields all answer how tightly
+the point is pinned. The heading is emitted where the group changes, so the form
+keeps the registry's order rather than regrouping itself, and a heading may be opened
+once.
+
+**The declared `text`, `longtext` and `url` fields are what a case search matches
+on**, beside the label, the type, the folder and the notes — a vehicle is looked for
+by its plate. Numbers, shapes and stored grades stay out of the index. One predicate
+serves both sides: `sqlite_backend._entity_search_text` for the server,
+`lib/entitySearch.js` for the lists that filter a small case in memory.
+
+### When the case already holds the value ✅
+
+The `identifier` family is the one place where **the value is the identity**: two
+`email` entities holding one address are two records of one thing, where two people
+may genuinely share a name. `entities.identity_key` is what says whether two labels
+are the same identity, and `GET /cases/{id}/entities/twin?type=&label=&ignore=`
+answers it against the case.
+
+| Type | Compared as |
+|---|---|
+| `account` | trimmed, case-folded, a leading `@` dropped |
+| `phone` | trimmed, case-folded, spaces, dashes, dots, brackets and slashes dropped |
+| `domain` | trimmed, case-folded, a trailing root dot dropped |
+| `email`, `ip`, `network` | trimmed and case-folded |
+| every other family | not compared |
+
+Three rules hold it together:
+
+- **It warns, it never refuses.** The case has no merge action, so a create that
+ failed would leave the analyst holding a value with nowhere to put it. Both the
+ create dialog and Details name the row already holding it and offer to open it.
+- **It catches the same value typed twice, not every spelling that resolves to the
+ same thing.** `+33612345678` is not compared against `0612345678` and
+ `www.example.org` is not compared against `example.org`: supplying a country code or
+ stripping a subdomain is a guess, and a guard that guesses flags two entities that
+ are genuinely different — worse than missing one, since a duplicate is visible and a
+ wrong warning teaches the analyst to ignore the next.
+- **One comparison, served rather than reimplemented.** The create form used to
+ lowercase the raw label in the browser, which let `@handle` and `handle` sit side by
+ side. It is read on create **and on rename**, which is where it actually happens.
+
+### What state a thing is in ✅
+
+`condition` sits on every member of the `asset` family — a lorry, a ship, an
+airframe and a bridge can all be damaged, so the field is the family's rather than
+the two types it was first wanted for.
+
+| Stored | Reads as |
+|---|---|
+| `intact` | Intact |
+| `damaged` | Damaged |
+| `destroyed` | Destroyed |
+| `abandoned` | Abandoned |
+| absent | unknown |
+
+Two rules make it worth having:
+
+- **It is the last known state, and it overwrites.** The field answers *where is this
+ bridge today*, not *tell me about this bridge*. History is a statement, so it lives
+ on Claims, which is why `condition` is also declared there (below) off the same
+ list — same word, two speakers, exactly as `notes`/`verbatim`/`method` already are.
+ One list, because a count that groups by condition has to reach both.
+- **"Captured" is not a condition.** Changing hands is a change of owner, and `owns`
+ already states that. Folding it in would mix condition with possession, and a
+ mixture does not aggregate.
+
+### Counting a model rather than minting objects ✅
+
+A case that follows a conflict records the same thing over and over: *two of these
+were destroyed here, filmed by that*. Stated with the vocabulary above it costs two
+anonymous `vehicle` entities per sighting — hundreds of nodes that name nobody, each
+a fake identity. Two additions fix it, and neither is a new mechanism.
+
+**`equipment-type` is the model.** "T-72B3", not the tank with turret number 214. It
+is its own family because the three verbs an `asset` takes are all wrong for it:
+nobody owns a model, a model sits nowhere, and letting one `appears-in` a video would
+give the case two ways to say the same thing, the easier of which carries no number.
+Its whole vocabulary is being pointed at — `instance-of` from an object somebody
+actually named, `about` from a statement — plus `mentions`, which reaches every
+family. `category` is a field rather than five types, because that is what a count
+groups on. It lives **in the case**, not in the workspace: a closed case folder is
+complete (SPEC §2), and statistics whose labels live elsewhere do not travel. A shared
+catalogue can later seed the field by autocompletion, copying the term into the case
+on use, which changes nothing here.
+
+**The Claim carries the number and time.** `count` (whole, at least 1), `condition`,
+`when` and `time_role` join `confidence`, `method` and `verbatim` on the node. They
+never sit on `about`, because a Claim may point at several subjects and one number on
+the node could not say which it meant. So **one statement counts one kind of thing**,
+and a second kind is a second Claim with its own confidence. That is the call §3
+already makes for competing candidates, and it is what keeps every value on the node
+assessable as one.
+
+Absent `count` means *seen, not counted*, which is a different and honest answer from
+one — the same reasoning that makes zero an invalid radius below.
+
+The shape of a filed observation, then:
+
+```
+claim(count: 2, condition: destroyed, when: 2026-08~, time_role: observed,
+ confidence: probable)
+ ├── about ──▶ equipment-type "T-72B3"
+ ├── at ──▶ place "Crossroads"
+ └── cites ──▶ media (the video)
+```
+
+**A model reaches a video through the statement, and only through it.** That is the
+whole design: the two-hop path carries how many and in what state, where a direct
+edge could carry neither.
+
+No verb carries that date (§3): the temporal value belongs to the statement. The
+parser accepts reduced Gregorian dates, date intervals, final `~`, `?` and `%`
+qualifiers, and ISO timestamps with seconds. A timestamp without a timezone is kept
+as unplaced rather than undated, but is not globally sortable. Two zoned timestamps
+may form an exact interval. Local-time intervals, mixed date/time intervals, open
+intervals and the rest of EDTF Level 2 remain outside the announced profile.
+
+Time reads a derived SQLite projection, never a second authority. Claim `when` and
+`time_role` remain on the Claim; capture/publication/imagery dates remain in the media
+sidecar; filing and collection dates remain provenance. The projection labels them
+`statement`, `media` or `case_activity`, and can be deleted and rebuilt from those
+records. A manually assessed media time is therefore a sourced Claim about the media,
+not a rewrite of `taken_at`.
+
+**Counting Claims counts observations, not objects**: two
+videos of the same destroyed tank are two statements. Azimut does not merge
+observations across entities, so a total says *observations* in those words rather
+than implying a fleet.
+
+**Where the number is read** is the entity's own Details, which adds up the statements
+already listed under Claims, and the Board's *Total the statements*, which groups a
+whole narrowing by `about` subject (`engine/tally.py`, one implementation for both, or
+the case would hold two totals for one question). Three rules fall
+straight out of the model above and are what keep the sum honest: a `refuted`
+statement is counted apart and never inside a total, since a candidate eliminated is
+the opposite of one observed; an absent `count` stays *seen, not counted* rather than
+becoming one; and **nothing is totalled across subjects**, because a number that sits
+on the node and not on `about` may belong to two of them and adding it would spend the
+one statement twice. Grouping *above* the subject is what the vocabulary cannot do
+yet: no verb says one `equipment-type` is a variant of another, so three T-72 variants
+stay three rows. Whether that verb is worth minting is a question this reading exists
+to answer rather than to presume.
+
+### How precise a place is ✅
+
+A saved point may be an exact address or "somewhere on the north quay", and a model
+that cannot say which forces the analyst to either overstate or file nothing. Four
+optional fields on `place` say it, taken from Darwin Core, which settled this for
+biodiversity records two decades ago.
+
+| Field | Darwin Core term | Meaning |
+|---|---|---|
+| `radius_m` | `coordinateUncertaintyInMeters` | radius of the **smallest circle containing the whole location** |
+| `footprint` | `footprintWKT` | a GeoJSON `Polygon`/`MultiPolygon`, when a circle is the wrong shape |
+| `verbatim` | `verbatimLocality` | what the source said, word for word |
+| `method` | `georeferenceProtocol` | how this point was arrived at |
+
+Three of Darwin Core's rules are kept as written, and each is a test:
+
+- **The radius is the smallest enclosing circle**, not a standard deviation, so two
+ analysts write the same number.
+- **Zero is not a valid radius.** Empty means *unknown*, a different and honest state;
+ `0` would claim infinite precision. Hence a floor of one metre.
+- **`verbatim` outlives every reinterpretation.** It is the field people wish they had
+ kept.
+
+Three text fields, three speakers: `notes` is the analyst writing freely, `verbatim`
+is the source quoted, `method` is how the point was found ("roofline matched against
+Esri imagery 2023-06", "EXIF GPS as read"). Darwin Core's fourth field,
+`georeferenceRemarks`, is **not** adopted — its content belongs in `method`.
+
+`radius_m` is stored in metres and asked for in rungs: building 25, block 100,
+neighbourhood 500, town 2 000, region 10 000, served with the registry so the picker
+and the validator cannot drift. A rung is a toggle, so clicking the chosen one clears
+the radius. Why the ladder is not derived from Plus Code lengths is in
+`entities.PRECISION_RUNGS`. Nothing here is required and **absence is never flagged**:
+a place with no radius draws as a pin, with no badge asking for one.
+
+The four fields are edited in Details → **Info**, under the heading the registry
+gives them (`group` on the field that opens the block, `"How precise"` here), and committed
+by the panel's Save. Info holds the entity's editable profile; Connections is reserved
+for graph edges and lineage, and Time for dated statements and intrinsic dates.
+
+The saved index (`GET /cases/{id}/satellite/index`) carries `radius_m` and
+`footprint` so the map overlay draws them without fetching each place: a footprint
+renders as its own polygon, a radius as a circle in metres, and a footprint wins when
+both are set. The map popup states the spread in words (`±500 m`, `traced area`) and
+never edits it.
+
+**`footprint` is stored, validated and drawn, but not yet traceable.** No map offers
+the gesture, so the field is API-only and the panel hides it until a shape exists.
+The tracing tool (SPEC §6, v2) completes it; nothing else about the field changes
+when it lands.
+
+### What a source is worth ✅
+
+A claim rests on something, and how much that something is worth is a property of
+**the source**, never of the edge citing it. Two types carry it, and they are the two
+a case actually sources from: `bookmark` (the page) and `account` (whoever posted).
+
+| Field | On | Written by | Meaning |
+|---|---|---|---|
+| `url` | `bookmark` | the save | where the page is |
+| `fetched_at` | `bookmark` | the save | when it was seen, UTC |
+| `archive_url` | `bookmark` | the analyst | the copy that outlives the page |
+| `reliability` | `bookmark`, `account` | the analyst | how much the source is worth, A–E |
+
+`fetched_at` is stamped server-side by the route standing on the page, so the moment
+is known rather than typed; a bookmark added by hand in the app carries none, and
+that absence is never flagged. It is what an archived copy is later dated against.
+It and `url` are tool-written, so neither is a declared field: the panel reports them
+under Info rather than offering them for edit.
+
+**The grades are the Admiralty/NATO letters**, served with the registry as a `choice`
+field so the picker and the validator cannot drift:
+
+| Stored | Reads as |
+|---|---|
+| `A` | completely reliable |
+| `B` | usually reliable |
+| `C` | fairly reliable |
+| `D` | not usually reliable |
+| `E` | unreliable |
+| absent | not judged |
+
+The scheme's sixth grade, **F — "reliability cannot be judged" — is not adopted**: an
+empty field already says it (`entities.RELIABILITY_GRADES`). Same call the confidence
+ordinal makes, where *not assessed* is the lack of a level rather than a fifth one.
+
+A grade is read wherever its source appears, including on a relation row, where it
+sits on the line carrying the entity's name while the edge's own rating sits on the
+line below (§3). Nothing needs one: most bookmarks are never graded.
The file-backed pointers of `proof`, `post` and `inspect-session` (`spec`,
`draft`, `path`) are not stable: the file's name follows the label, so renaming
@@ -102,20 +484,179 @@ re-read the pointer — never cache one across a save.
Read a directed link as **`from` → `type` → `to`**. Removing an entity drops its
incident links. The link type decides whether dependent entities also disappear.
-### Link type registry (proposed core)
+### Link type registry
+
+Relations start each end from one or more **families** (§2).
+`from_types`/`to_types` resolve those families to the concrete sets the endpoint
+check compares against. `from_only`/`to_only` narrow an end *inside* its family for
+verbs where a whole family is too broad; they intersect rather than replace, so
+a narrowing can only remove a type, never smuggle one in from elsewhere.
| Type | from → to | Meaning | State |
|---|---|---|---|
-| `derived-from` | artifact → source | made from that, and outlives it | ✅ |
-| `depends-on` | session → subject | only a pointer at that: dies with it | ✅ |
-| `located-at` | media/capture → place | shot at this point | ✅ |
-| `depicts` | media/capture → place | the place is shown in the file | ✅ |
-| `same-image-as` | media → media | perceptual hashes are within 10 bits | ✅ |
-| `appears-in` | media → vehicle/person | subject shown in the media | ⬜ |
-| `same-as` | entity → entity | two records, one real thing (merge) | ⬜ |
-| `owns` | person/org → account/asset | ownership | ⬜ |
-| `posted` | account → media/post | authorship | ⬜ |
-| `mentions` | media/note → any | referenced, weaker than depicts | ⬜ |
+| `derived-from` | media → media/capture; proof → media/capture; post → proof/media/capture; note → post/proof/media/capture | made from that, and outlives it | ✅ |
+| `depends-on` | inspect-session → media/capture | only a pointer at that: dies with it | ✅ |
+| `located-at` | image/video/audio media → place | where the recording was made | ✅ |
+| `depicts` | image/video media, capture or proof → place | the place is visible | ✅ |
+| `owns` | person/organization → organization/asset/identifier | strict ownership, never membership or mere control | ✅ |
+| `part-of` | organization → organization | internal organizational containment | ✅ |
+| `member-of` | person/organization → organization | membership, not internal containment | ✅ |
+| `associated-with` | actor → actor | a tie that is none of the three above; what kind it is rides on the edge | ✅ |
+| `posted` | account → media/bookmark | the account published the content or URL | ✅ |
+| `appears-in` | actor/asset/identifier → image/video media or capture | the entity or a recognizable representation is visible | ✅ |
+| `sited-at` | structure → place | a permanent site, never a dated presence | ✅ |
+| `instance-of` | asset → equipment-type | this particular object is one of that model | ✅ |
+| `in-network` | IP/network → network | an address or subnet belongs inside the network | ✅ |
+| `same-image-as` | image media → image media | a machine perceptual-hash match | ✅ |
+| `about` | claim → actor/asset/equipment-type/identifier/place/media/capture | what the statement concerns | ✅ |
+| `at` | claim → place | where the statement puts its subject | ✅ |
+| `cites` | claim → bookmark/note/proof/media/capture/claim | what the statement rests on | ✅ |
+| `contradicts` | claim → claim | the two statements cannot both hold | ✅ |
+| `mentions` | note/post/proof/bookmark → any other declared entity | the document refers to the entity | ✅ |
+
+Every manual connector is validated by the API and offered only by its own picker.
+`same-image-as` is machine-only. `part-of`, `in-network`, `cites` and the derivation
+chain refuse cycles. Self-links are refused for every type.
+
+Every label completes the sentence *"<from> … <to>"*, which fixes the direction:
+`appears-in` runs subject → file, because a person appears in a video. `owns` may
+target an organization but never a person; membership is stated separately.
+
+**Containment, membership and ownership stay three verbs.** A brigade contains its
+battalions through `part-of`, a person belongs to an organization through
+`member-of`, a unit's trucks are owned. Keeping them apart is what makes an order of
+battle queryable; a military unit is an `organization`, and `attrs.echelon` sorts the
+tree.
+
+**And `associated-with` is the fourth, for the tie that is none of them.** Until it
+existed the vocabulary had no person-to-person verb at all — `owns` refuses a person
+as its object, `member-of` and `part-of` both end at an organization — so stating that
+two people are connected, which is the first thing a case does, cost a whole Claim
+node. It runs `actor → actor` and no wider: opened to identifiers and assets it becomes
+the verb that swallows the rest, and a registry where one entry answers everything says
+nothing. It is symmetric, so both readings are the same word and a picker offers it
+once.
+
+### What kind of tie ✅
+
+`associated-with` declares a `qualifier` (`RelationType.qualifier`), and the analyst's
+answer is stored on the edge as `links.nature` — "sister", "employer", "business
+partner". Three rules, and they are what keep one field from becoming a note on
+everything:
+
+- **The qualifier belongs to the verb, never to the edge.** Empty means this verb takes
+ none, exactly as `ratable: false` means it takes no grade, and the API refuses one
+ anywhere else. A note every edge could carry would leave nothing saying what an edge
+ *is*. Giving one to another verb later is a word in the registry.
+- **Free text, and deliberately not a closed list.** Maintaining a taxonomy of human
+ relationships is a project of its own, and the first case needing "former
+ sister-in-law" breaks it. Capped at 120 characters (`links.MAX_QUALIFIER`): reasoning
+ that runs to sentences is a Claim, which has a field for it.
+- **It leaves with the verb.** Rewording the edge to one that takes no qualifier clears
+ it, or the edge would privately hold "sister" while stating that one unit is part of
+ another.
+
+Unstated carries no key at all, the same rule the rating follows, so no reader has to
+tell *unstated* from *stated as empty*. The graph writes it on the line —
+`is associated with (sister)` — because the verb alone is the thin half of the
+statement.
+
+**No verb carries a date.** `sited-at` is a permanent site, not a visit. A person's
+whereabouts at a time, or a unit reassigned between corps, is a statement with a
+reason and sources, so its `when` and `time_role` belong on a claim node rather than
+an edge.
+
+**`mentions` is a pointer, not a derivation.** A document *refers to* something,
+where `derived-from` says the file was built from it; both may sit on the same pair,
+and deleting the target drops the mention with no tombstone. The author is a note,
+post, proof or bookmark; the target is any other declared entity, a Claim included.
+
+It is the one verb served as its own **action** (`RelationType.action`, `"mention"`)
+under its own heading (`RelationType.group`). A pointer must not borrow the weight of
+a finding, so the split is the registry's and every surface obeys it: **Add relation**
+never turns into **mentions**, **Add mention** has its own target search, an edge is
+only reworded inside its action, and a mention carries no rating (`ratable: false`).
+
+### The claim, and how sure it is ✅
+
+A `claim` is a statement node. It points `about` at subjects, `at` at places and
+`cites` at evidence. The Claim holds `count`, `condition`, `when`, `time_role`,
+`confidence`, `method` and `verbatim`; its three connectors carry none of those
+values. This keeps one statement at one confidence even when it has several subjects,
+places or sources.
+
+**`cites` also reaches another claim ✅**, because an intermediate conclusion is what
+the next one is built out of: *the vehicle is a T-72B3* carries *the column is the 4th
+brigade*, and stated against the video instead, the case records two findings resting
+on one file and loses that refuting the first takes the second with it. It is `cites`
+rather than a verb of its own — the question is the same one, what does this rest on,
+and `inverse_label` already read *supports claim*. Three rules keep it from meaning
+more than it says:
+
+- **It refuses cycles**, unlike `contradicts`. *A because B, B because A* is circular
+ reasoning, where two statements standing against each other is an open question.
+- **A cited claim is never counted as a source.** The independence number answers
+ *three citations, how many sources*, and reasoning built on reasoning has found
+ nothing new (`graph._counted`).
+- **Nothing propagates.** A `probable` statement may carry a `certain` one: the verb
+ makes the path visible, and how strongly each end is held stays the analyst's, which
+ is the rule the three assessments already follow.
+
+| Claim `attrs.confidence` | Reads as |
+|---|---|
+| `certain` | established and corroborated |
+| `probable` | more likely than not |
+| `possible` | cannot be excluded |
+| `refuted` | checked and eliminated |
+| absent | not assessed |
+
+The Claim editor owns `about`, `at`, `cites` and `contradicts`; they never appear
+under **Add relation** and cannot be reworded into another action. Competing
+candidates are separate Claims, which is how each gets its own confidence — the
+former `exclusive` checkbox tried to do that on connectors instead and is no longer
+offered, though existing `exclusive` attributes stay readable.
+
+### What stands against a statement ✅
+
+`contradicts` runs claim → claim and is the fourth verb of that action. It exists
+because `refuted` records that a statement is dead and names nothing that killed it:
+the case kept the verdict and lost the argument. Eliminating a candidate is half the
+work of a geolocation — twelve are checked and eleven ruled out — and each of those
+eleven carries its own reasoning and its own sources, which is a Claim rather than a
+grade.
+
+- **Statement to statement, both ends.** Pointed at a subject it would say "this
+ vehicle is contradicted", which is not something anyone can assess.
+- **No cycle check**, unlike `part-of` and `in-network`. Two statements contradicting
+ each other is not a loop to refuse, it is what an open question looks like, and it
+ reads the same in both directions — so the Claim editor lists the rows under one
+ heading without sorting them by direction.
+- **Not ratable**, like the three connectors above: how strongly each side is held is
+ already on each Claim, and a third grade on the edge between them is exactly the
+ mixture three separate assessments exist to prevent.
+- **It is not a claim connector** (`links.CLAIM_CONNECTION_TYPES`). Those say what a
+ statement rests on and are what a source fold walks; folding across this one would
+ collapse an argument into a citation.
+- The graph draws it as its own stroke, a dash broken by a beat, so a statement
+ cluster shows its arguments before any label is read.
+
+Ordinary semantic relations may carry the nullable `links.confidence` ordinal: `3`
+certain, `2` probable, `1` possible, `-1` ruled out, absent for not assessed. It
+saves turning a tentative ownership into a whole Claim node. A tool's suggestion is
+confirmed before it can be rated, and it is rated from either surface that draws it:
+the Details row and the graph's own edge panel.
+
+**Ruled out is the one level the graph draws.** It is a verdict rather than a nuance,
+and a candidate eliminated is kept on purpose — so drawn like any other stated
+relation, eleven checked and rejected read as eleven live hypotheses. It takes a
+stroke of its own (`lib/graph.EDGE_KINDS`), and the other three deliberately do not:
+four more patterns would put what kind of edge it is and how sure of it on one
+channel, which is the mixture three separate assessments exist to prevent.
+
+**Three assessments, never combined**: Claim confidence, an ordinary relation's
+ordinal, and a source's A–E reliability (§2). Chain edges, mentions, Claim connectors
+and `same-image-as` are all non-ratable, and the API refuses a rating on them — which
+is why no surface draws a rating control for one.
### Delete policy
@@ -124,11 +665,17 @@ A tool selects one of two deletion behaviours through its link type:
> **After deleting the target, is the holder still usable?**
> Yes → `derived-from`. No → `depends-on`.
-| | `derived-from` | `depends-on` |
+| Link | Holder | Allowed source |
|---|---|---|
-| Holder | proof, post, frame, collage | inspect-session |
-| Holds | its own pixels/text | only a reference |
-| Target deleted | **survives**, + tombstone | **deleted with it**, transitively |
+| `derived-from` | media | media, capture |
+| `derived-from` | proof | media, capture |
+| `derived-from` | post | proof, media, capture |
+| `derived-from` | note | post, proof, media, capture |
+| `depends-on` | inspect-session | media, capture |
+
+A `derived-from` holder owns pixels or text and survives a deleted source with a
+tombstone. An `inspect-session` is only adjustments over its subject, so a deleted
+subject removes it transitively.
- `derived-from` never cascades into an output. A post keeps its text when its
proof is deleted; a frame keeps its pixels when its video is deleted.
@@ -139,6 +686,14 @@ A tool selects one of two deletion behaviours through its link type:
typed, in any supported format) then `coords` (what the panels gave it, frozen
at save). That is what keeps a proof on the map once its capture is deleted —
a tombstone records the path, the sha256 and the URL, never coordinates.
+- **Placement reads the same edges further, and in both directions**
+ (`satellite.placements`, `GET /entities/{id}/placement`): a video reaches its
+ capture three hops away, through the proof that composed a frame of it. Only
+ `capture` and `proof` carry a point, and **the artifact carrying one ends the
+ walk**. Points deduplicate on the exact pair, never a rounded one, and the nearest
+ hop wins a repeat. Bounded at four hops, 200 entities read and 15 points reported,
+ each with the entity it was read off; a `capture` reports none, its point being its
+ own rather than one the chain placed it at.
- `attrs.lost_sources[]` stores `{label, type, path, sha256, source_url, at}`.
Tombstones are keyed by path and never stacked.
- Every UI deletion uses the same dependency-aware service. The confirmation
@@ -150,17 +705,25 @@ A tool selects one of two deletion behaviours through its link type:
not decide what a delete destroys.
- Exact-byte duplicates never produce `same-image-as`: import deduplicates them
on SHA-256 before perceptual hashing runs.
+- **A note files its chain from its own body, on every save.** The Markdown names
+ the case files it shows as `[[media:<id>]]`, so `PUT /notes/{id}` restates the
+ `derived-from` edges from the text: an image inserted through the Notebook's Media
+ button gains its edge, one deleted from the text loses it. Only the types the body
+ can name are reconciled (`links.EMBEDDED_TYPES`), which is what keeps a report's
+ edge to the `post` draft it was composed in — that one is declared by
+ `POST /notes` at creation, and no wording could restate it. A note typed by hand
+ keeps no chain.
Free-typed labels remain valid in stored data. The registry defines what the UI
understands and what the API will mint, not what a case may hold.
### Relations
-Everything outside the two chain types is a **relation**: a statement about the
-world rather than about how a file was produced. `engine/links.py` holds the one
-registry — how each type reads in words, the entity types either end accepts, and
-whether an analyst may state it — and `GET /api/cases/relation-types` serves it to
-every surface, so the vocabulary is never copied per screen.
+Everything outside the two chain types is a semantic connector: an ordinary
+relation, a mention, or one of the three Claim connectors. `engine/links.py` holds
+the one registry — how each type reads, the types either end accepts and which UI
+action owns it — and `GET /api/cases/relation-types` serves it to every surface.
+It answers with resolved type lists, so a client never has to know what a family is.
| | Chain (`derived-from`, `depends-on`) | Relation (`located-at`, `depicts`, …) |
|---|---|---|
@@ -172,23 +735,232 @@ every surface, so the vocabulary is never copied per screen.
- A relation stated by hand is `confirmed` and validated against the registry: the
API refuses a chain type, an unregistered type, a self-link, and any pair of
endpoint types the table above has no reading for.
-- **Relations stay editable.** Add one, correct its reading, or take it back at any
- time, from any surface that shows them. Correcting the reading keeps the edge —
- same id, same provenance — because the two entities were always related and only
- the verb was wrong; the same validation applies, plus a refusal to collapse onto
- a relation the pair already holds. Removal is one gesture whatever the status:
- dismissing a proposal and retracting an accepted statement are the same act on
- the graph, and a statement that cannot be taken back is a trap. A chain edge is
- refused there too — dropping a derivation behind the relation path would lose it
- without the tombstone the delete rules depend on.
-- `same-image-as` is registered but **machine-only**. It is a claim about
- perceptual hashes, which is enrichment's to make; a person comparing two
- pictures is not measuring a hash. It is also narrower than `same-as`: two files
- showing the same pixels, never one merged graph identity.
-- Where they appear: the Details panel, the map popup, and the case board next.
- One component renders all three (`RelationList.svelte`), one collects a new one
+- **Relations stay editable** from any surface that shows them. Correcting the
+ reading keeps the edge — same id, same provenance — since only the verb was
+ wrong; the same validation applies, plus a refusal to collapse onto a relation the
+ pair already holds. Removal is one gesture whatever the status: dismissing a
+ proposal and retracting an accepted statement are the same act on the graph. A
+ chain edge is refused there, because dropping a derivation would lose it without
+ the tombstone the delete rules depend on.
+- An older out-of-matrix connector stays visible and removable, but cannot be
+ created or reworded. Compatibility does not silently widen the current vocabulary.
+- `same-image-as` is registered but **machine-only**: it is a claim about perceptual
+ hashes — two files showing the same pixels, never one shared graph identity.
+- Where they appear: the Details panel, the map popup and the case board. One
+ component renders all three (`RelationList.svelte`), one collects a new one
(`RelationPicker.svelte`).
+### Where a geolocation becomes a point ✅
+
+Saving a proof files the point it carries as a `place` and states
+`proof --depicts--> place` (`satellite.place_for_proof`). The point is what the
+analyst typed into the composer, or what its panels froze and they left standing
+(`own_point`, §3 placement).
+
+**A capture files nothing.** Ten are taken while hunting one roof and each frames
+a slightly different centre, so filing each would pin the search rather than the
+answer. A capture is already on the map — the Saved index draws places and
+captures alike — and what it lacked was a *node*, which is worth minting once, at
+the moment somebody commits to it. That moment is the proof.
+
+- **Nothing is ever `suggested` here.** Typed or accepted from the panels, the
+ point is the analyst's own answer, and a review step over one's own answer is a
+ step over nothing.
+- **A point the case already holds is neither filed twice nor asked about**
+ (`place_at`, rounded to five decimals, about a metre). Re-saving a proof stays
+ silent, and so does one whose coordinates were never touched — the edges are
+ restated all the same, so a proof concluding on a pin already on the map says
+ so instead of standing beside it unattached. The key is shared with import
+ enrichment (`satellite.COORD_KEY`) so a photo's EXIF point and a proof
+ concluding on the same spot are one node.
+- **A save restates the point rather than adding one**
+ (`satellite.restate_proof_point`), the rule the proof's panels already follow.
+ Reopening a proof and correcting the coordinates is an answer withdrawn: the old
+ edges go, or the case reads as two geolocations. Toggling POV changes the verb
+ the last save wrote, and an emptied coordinate field withdraws the point
+ entirely. Only what the composer itself wrote is reconciled — an edge stated by
+ hand in Details, or proposed by import enrichment, is a separate claim about the
+ same file — and a point another proof still concludes on keeps its material.
+ A place the proof let go of that nothing else holds is **offered for deletion,
+ never swept**: it is on the map, and dropping it is the analyst's call.
+- **The material the proof composes states the same point**, over the derivation
+ closure — the frame, the collage, the video two hops up, the capture. Confirmed,
+ because **composing is the assertion**: putting a frame beside a capture and
+ writing the coordinates *is* the geolocation, and asking the analyst to accept
+ their own act is the review everybody clicks through, which is what makes
+ `suggested` stop meaning anything where it is real. Being wrong costs one
+ removal, since a relation drops alone.
+- **`spec.pov` picks the verb for the material, because the composition cannot.**
+ Recorded-at and shows are independent — a rooftop shot was recorded somewhere it
+ never shows, a skyline is shown from kilometres away — and a match between a
+ frame and an imagery says only that they meet, not whether the camera or its
+ subject was located. The composer asks once (**POV**), and the answer travels in
+ the spec: set, the media are `located-at` the point; unset, they `depicts` it. A
+ `capture` shows it either way, since orbital imagery was recorded nowhere on the
+ ground, and so does the proof, which was composed. POV is also the only reading
+ that reaches an audio file, which has a place it was made and nothing it shows.
+
+`proof_place_auto` (Settings → General → Proofs, on by default) decides whether
+the save files it or the composer asks first. Both write the same thing.
+
+### Lenses ✅
+
+The graph draws one reading at a time, and a reading is **a set of verbs and a set of
+node roles, both resolved from the registries rather than listed a second time**
+(`engine/graph.py`, `GET /api/cases/graph-lenses`). A verb reaches its lens by what it
+joins and a type by its role, so adding either places it with no edit there:
+
+| Lens | Verbs | Derived by | Nodes |
+|---|---|---|---|
+| Everything | all 19 | the whole registry | the case |
+| Subjects | `owns`, `part-of`, `member-of`, `associated-with`, `posted`, `appears-in`, `instance-of`, `in-network`, `same-image-as` | an analyst's relation that is not geography | the case |
+| Ground | `located-at`, `depicts`, `sited-at` | a relation whose object is a `place` | the case |
+| Statements | `about`, `at`, `cites`, `contradicts` | `action = "claim"` | the case |
+| My work | `derived-from`, `depends-on`, `mentions` | the chain types, plus `action = "mention"` | everything |
+
+"The case" is the `subject` and `attestation` roles; **My work** is the switch that
+puts the analyst's own output back on screen. Three calls the table does not show:
+
+- **`same-image-as` reads with subjects, not with the artifact chain.** Two files
+ being one picture is a fact about the case rather than about the filing, and `media`
+ is a subject. Filed with `derived-from` it made one lens hold a derivation and a
+ finding about the world at once.
+- **`mentions` starts at a `document` by construction**, so it has never held one
+ subject-to-subject edge. It, `derived-from` and `depends-on` all answer *what did I
+ write, and out of what* — one question, one lens, named for what it is.
+- **Every verb lands in exactly one lens**, which is a test (`tests/test_graph.py`):
+ a verb in none is unreachable, a verb in two is an ambiguity the analyst would have
+ to resolve.
+
+Narrowing the verbs never hides a subject: a node with no edge in the chosen lens is
+an answer, it is what nobody has connected yet. What a lens does take out is a whole
+**role**, and it takes it out of every read — the ranking, the closed edge set, an
+expansion's arrivals, a neighbourhood's walk, a route's intermediate nodes. Degree
+follows, counted over the edges that reading can show, or a node would price a click
+that brings nothing in. A named node is no exception: a filter is a narrowing set
+earlier and a name outranks it, where a lens *is* the reading. A neighbourhood or a
+route rooted on a type the lens leaves out is refused in words rather than answered
+with an empty picture.
+
+A **free type** the vocabulary has never heard of has no role, so a reading states
+what it *excludes* rather than what it keeps: an allowlist resolved from the registry
+would silently drop an entity nobody agreed to drop.
+
+### The wrapper is an edge ✅
+
+An `attestation` on a statement→source chain is drawn as **one edge, not a node**
+(`engine/graph._fold`, whole-case view only — a neighbourhood gives its axis to
+distance, and a fold changes distance). A bookmark is not a leaf: *this account posted
+it, this statement cites it* is a path through it, and that path is a fact about the
+case rather than about the filing.
+
+```
+before claim → bookmark → account A after claim ──cites (3 sources · 1 account)──▶ account A
+ claim → bookmark → account A
+ claim → bookmark → account A
+```
+
+The rules, each of which exists to keep the fold a reading rather than a loss:
+
+- **Across provenance only** — `posted`, `derived-from`, `depends-on`. The content
+ verbs (`depicts`, `appears-in`, `located-at`) say what is *in* the material, which is
+ a subject-to-subject reading: folding the capture that shows a place and holds a
+ vehicle would state a claim about the two that nobody made.
+- **All of it or none.** A middle whose drawn edges are not every one either a
+ statement's or a provenance verb's stays a node — it carries something the edge
+ cannot say.
+- **Both ends drawn.** The closed set is the invariant, so a middle whose far end the
+ budget cut stays a node instead.
+- **The middle itself need not be drawn.** Two things keep one out of the picture and
+ neither loses the path through it: its **type** is one this reading leaves out — the
+ safeguard for a reconstructed case whose import filed a source under a type meant for
+ the analyst's own output, where shape outranks the type name — or the **budget** cut
+ it. The second is the common one: the ranking cuts the least connected first, which
+ is exactly the sources this folds, so without it the fold only kept its promise below
+ the ceiling. A statement resting on nine sources and one account drew as a lone dot
+ with both of its ends on screen and nothing joining them.
+- **A named node is never folded**, drawn or not, which is the way back: the edge
+ carries the ids it stands for, and asking for one draws it with its own edges again.
+ It is also what makes a route through a bookmark still land. Named *and* absent means
+ the budget refused something asked for outright, and folding it would offer to hand
+ back an id already in the expansion.
+- **Handing back is a question about the type**, not about whether the middle is on
+ screen: a source the budget cut is drawn by the same `expand` that opens a node,
+ where one of a type the lens leaves out could only be refused — so that edge names
+ the lens that does draw it instead.
+- **Its id is not a row.** `folded:<verb>:<from>:<to>` — deterministic, so a selection
+ survives a reload, and prefixed because nothing may be written to it: confirming,
+ rating and removing all refuse it.
+- **Only as confirmed as its weakest part.** One proposed link along the path makes the
+ edge proposed, so a fold cannot launder a proposal into a finding.
+- **The degree follows the drawing.** Three citations that became one edge are one
+ connection now, or the node would price a click at three and bring nothing.
+
+**Independence falls out of it** ✅. Each drawn statement carries
+`rests: {sources, accounts, one}` — how many sources it rests on, how many accounts
+published them, and whether *every* one of them traces back to the same account. That
+last is the finding ("three citations are one source"), and it stays false while any
+source has no known publisher: the untraced half may well be independent, and saying
+otherwise would be a judgement rather than a measurement. The view counts them as
+`single_account`. Both are read over the drawing's own edges, like the match count and
+unlike the case-wide total.
+
+### The derivation reads as three more folds ✅
+
+Derived imagery is ordinary `media` — no new type, no role change, nothing leaves the
+vocabulary (`engine/graph`, whole-case view only, like the fold above). A type for it
+was considered and rejected, for three reasons worth keeping: **hiding cuts paths where
+folding keeps them** (a frame filed as `annex` takes `proof ──derived-from──▶ frame` out
+of every read with nothing replacing it, and a bare geolocation has no claim for the
+safeguard query to rescue it by); **a derivative is often the evidence**, so Ground and
+Statements would lose the very images the case is built on; and **a type is exclusive
+where an origin is not** — a save that dedupes onto existing bytes returns the entity
+already there and adds a `derived-from`, so one file is both imported and derived. What changes is
+**how the same nodes are read**, and the role is what decides: an `annex` is left out of
+a reading of the case, an `attestation` is folded, a `subject` keeps its node. A fold is
+**per lens**, always: what a reading draws decides what it may collapse.
+
+| Fold | Rule | Reads |
+|---|---|---|
+| `_relay` | every drawn edge a chain verb, exactly one of them **outgoing**, and it relays something | `proof ──derived from 1 frame──▶ video` |
+| `_roll` | one drawn edge, a chain verb, and the node is the end that was **derived** | `12 frames made from it, used by nothing`, on the video, which still prices them |
+| `_star` | the nodes stating the same point, grouped by derivation; the arrow stays on the **subject** root | `video ──depicts (3 sources)──▶ place`, `rests on 1 source` |
+
+The family is **every arrow on the point, whatever verb it is written with**. POV splits
+one material across two — the footage was `located-at` the point, the capture `depicts`
+it — so a star grouped by verb cuts the family in half, each half then holds a derivation
+reaching outside itself, the all-or-nothing rule refuses both and nothing collapses at
+all. The surviving line is the material's own statement; the ones folded into it are
+named on it and come back saying exactly what they said.
+
+The calls the table cannot show:
+
+- **One outgoing chain edge, never two.** A node made from a frame *and* an overhead
+ capture is a confluence: collapsed, the line left standing would say the capture came
+ out of the footage.
+- **A leaf with a single relation is not rolled up.** A person with one link is thin
+ material the case has yet to exploit, not clutter — and the direction settles the lone
+ pair, since only the derivative came out of the other.
+- **A capture pulled at the coordinates already suspected is the reference**, not a
+ witness that agrees: its `depicts` is close to a tautology, and counting it would state
+ a corroboration nobody found. Shape cannot tell it from the footage; the roles can.
+ A group with no subject root keeps its own, or the one statement about that point
+ would leave with it.
+- **`_star`'s surviving arrow is the case's own row**, annotated rather than replaced,
+ so confirming or withdrawing it stays possible. The other two build synthetic edges,
+ which nothing may be written to.
+- **`_star` and `_roll` leave the degree alone**, and that is where the way back sits. The others hand their nodes back from a line that *touches* them; this one
+ names a frame and a capture on `video → place`, which does not touch the proof they
+ were derived by. Priced down, that proof would report no further connections while two
+ of them exist — so it keeps counting them, and **what an opened node touches is never
+ folded**, or the click answers with the picture it was pressed on. `_roll` follows for
+ a plainer reason: its count is a fact about the video rather than a second way to open
+ it, and priced down the node offered one number on its pill and another in its menu for
+ the same missing nodes.
+- **The place reports `rests: {sources}`** where more than one arrow arrived: the
+ geographic counterpart of the independence number above, and a count that would only
+ restate the picture is not shown.
+
### The derivation chain
The chain is filed with the save action:
@@ -203,7 +975,8 @@ How it is wired (`engine/links.py`):
- Sources are recorded as **case paths** (a proof's panels, a session's
`spec.source`, a derivative's sidecar `source.from`/`sources`); the link layer
- resolves path → entity and emits the edge.
+ resolves path → entity and emits the edge. A note is the exception: its body names
+ entity ids, and `sync_embedded` restates only the types that body can speak for.
- Every save restates sources through `sync`. Removing a panel removes its edge;
repeated saves keep one edge per panel.
- A proof's pasted images are read as decoration, not sources: they carry no case
@@ -218,41 +991,32 @@ How it is wired (`engine/links.py`):
or a provider, which provenance already carries, with nothing in the case to
point at.
-## 4. Provenance, confidence, identity
+## 4. Provenance and assessment
- **Provenance** (on every entity and link): `by` (tool id: `media-library`,
- `satellite`, `proof-composer`, `post-composer`, `inspect`, or `user`), `at`
- (UTC), `status` and optional source URL. It borrows the entity/activity/agent
+ `satellite`, `proof-composer`, `post-composer`, `inspect`, `paste`, `ingest`,
+ or `user`), `at` (UTC), `status` and optional source URL. It borrows the entity/activity/agent
shape of W3C PROV without implementing the full standard.
-- **Confidence** = `status`: `confirmed` (analyst-made or analyst-accepted) vs
- `suggested` (a tool proposed it, awaiting a click). Import enrichment emits
- suggested places and `located-at` / `same-image-as` links from image or video
- metadata.
- Keep the status binary until a real workflow needs finer grading. ✅
- Confirming a suggested entity confirms its incident suggested relations *and the
- entity at each far end*; a relation is also confirmed or dismissed on its own,
- from Details, from the point's own card on the map, or from the dialog that edits
- it. Confirming a relation likewise confirms whichever endpoint is still
- `suggested`. Both directions carry one rule — "this file was shot at this point"
- cannot be true while the point is only proposed — and without both, the
- Suggestions list and the relation rows would disagree about the same click. The
- spread stops at one hop: accepting a photo's own point is a reading of that
- photo, not a licence to accept whatever else that point was separately proposed
- to be. Dismissing is not the reverse — the edge goes, the entities stay, because
- a place can be real while one file's claim about it is wrong. A dismissal also
- sticks: re-reading a file refreshes its facts without re-proposing edges it has
- already been through, so the Enrich button never undoes a triage. Anything still `suggested` is marked as such
- wherever it appears — a proposed place reads as a proposal in the Saved tree and
- in its card, never as work the analyst did.
+- **Review status** is `confirmed` (analyst-made or analyst-accepted) vs
+ `suggested` (a tool proposed it, awaiting a click). It is not confidence. Import
+ enrichment emits suggested places and `located-at` / `same-image-as` links from
+ media metadata. A proof's point is not one of them: it and the `depicts` edges
+ it states over the material composed are the analyst's own act (§3). ✅
+ Confirming runs both ways and stops at one hop: a confirmed entity confirms its
+ incident suggested relations *and the entity at each far end*, and a confirmed
+ relation confirms whichever endpoint is still `suggested`. One rule drives both —
+ "this file was recorded at this point" cannot be true while the point is only
+ proposed. Dismissing is not the reverse: the edge goes, the entities stay, because
+ a place can be real while one file's claim about it is wrong. A dismissal sticks,
+ so re-reading a file never re-proposes edges already triaged. Anything still
+ `suggested` is marked as such wherever it appears.
**A derivation is `confirmed`**: `derived-from`/`depends-on` record what the
- analyst's own click just made, not what a tool inferred. `suggested` is for
- inference, such as OCR reading a street name or EXIF proposing a `place`. A
- relation stated by hand is `confirmed` for the same reason: there is nothing
- left to review.
-- **`same-as` / merge** (⬜ open, SPEC §10): when two entities are one real thing,
- link `same-as` rather than destructively merging; a resolver treats a `same-as`
- cluster as one node in views and unions its attributes and links. Collapse rules
- must be defined before an orchestrator creates duplicate accounts.
+ analyst's own click just made. `suggested` is for inference — OCR reading a street
+ name, EXIF proposing a `place`. A relation stated by hand is `confirmed` for the
+ same reason: there is nothing left to review.
+- **Assessment has three separate homes.** Claim confidence is a string attribute
+ on the Claim; an ordinary semantic relation may carry the nullable integer
+ ordinal; source reliability is an A–E attribute on the source. None are combined.
## 5. Design rules
diff --git a/docs/SPEC.md b/docs/SPEC.md
index 32a0682..9e03f71 100644
--- a/docs/SPEC.md
+++ b/docs/SPEC.md
@@ -1,6 +1,6 @@
# Azimut product overview
-Status: **spec v0.3** (2026-07-18). Read in order: Done → Roadmap → Loose ideas.
+Status: **spec v0.3** (2026-08-03). Read in order: Done → Roadmap → Loose ideas.
Implementation detail belongs in code and tests; see
[IMAGERY_PROVIDERS.md](IMAGERY_PROVIDERS.md), [UI.md](UI.md),
[ONTOLOGY.md](ONTOLOGY.md) and
@@ -73,15 +73,31 @@ App-wide settings, scratch cases, caches and runtime tools also stay under
The entity/link schema has existed since v1. Full vocabulary lives in
[ONTOLOGY.md](ONTOLOGY.md).
-- **Entity types** (extensible): person, organization, alias/username, account,
- email, phone, domain, ip, vehicle, place, event, media, proof.
-- **Links**: typed directed edges (owns, appears-in, located-at, same-as, posted,
- mentions, …) plus free-typed labels.
-- **Provenance on everything**: which tool/action, source, when, confidence
+- **Entity types** (extensible) sit in one of eight **families**. Relations start
+ from families and narrow endpoints where a verb is type-specific:
+
+ | Family | Types |
+ |---|---|
+ | actor | person, organization |
+ | asset | vehicle, vessel, aircraft, structure |
+ | class | equipment-type |
+ | identifier | account, email, phone, domain, ip, network |
+ | collected | media, capture |
+ | document | proof, post, note, inspect-session, bookmark |
+ | place | place |
+ | claim | claim |
+
+- **Links**: typed directed edges (owns, part-of, member-of, associated-with, posted,
+ appears-in, sited-at, instance-of, in-network, located-at, depicts, same-image-as,
+ about, at, cites, contradicts, …) plus free-typed labels.
+- **Provenance on everything**: which tool/action, source, when and review status
(`confirmed` by analyst vs `suggested` by a tool).
+- **Assessment stays separate**: a Claim carries its confidence; a ratable ordinary
+ relation may carry its own ordinal; a source carries Admiralty reliability A–E.
-Tools suggest entities and links; analyst confirmation adds them to the graph.
-Relations, graph, map and timeline views are planned for v4.
+Tools suggest entities and links; the analyst reviews them. Relations, Mentions,
+Claims, lineage, the Board, the graph and configurable saved Timeline readings are
+shipped.
---
@@ -94,52 +110,41 @@ proof for publication.
| Tool | What it does |
|------|--------------|
-| ✅ **Media Library** | Imports or downloads case media with metadata, SHA-256, notes, provenance and multi-attachment selection. |
-| ✅ **Inspect** | Reviews images and video, including saved orientation (±90°/±180°), frame selection, adjustments, crops, collages, auto-stitch, ELA hints and sessions. |
-| ✅ **Satellite** | Saves places and attributed map captures with provider, date, rotation, measure and reference tools. |
-| ✅ **Saved work navigation** | Groups a case's places, captures and filed screenshots by continent/country/region (labelled in English and the local language) or by My-work folder, searchable in either spelling with previews and shown on the map at its default zoom when none was saved. |
-| ✅ **Geo Proof** | Composes templated grid or free-layout panels with annotations, coloured frames and pasted overlays that stay out of the case, and exports a PNG with an editable spec. |
+| ✅ **Media Library & Inspect** | Imports or downloads case media with metadata, provenance and hashes, then reviews images and video through saved editing sessions. |
+| ✅ **Satellite** | Saves places and attributed map captures from free or optional keyed imagery, including dated Sentinel-2 passes and usage controls. |
+| ✅ **Geo Proof** | Composes annotated panels, files their coordinates as places and exports an editable PNG proof. |
| ✅ **Geo Report** | Prepares sourced proof threads and saved drafts without posting automatically. |
-| ✅ **Case sidebar** | Searches and filters the case, manages notes, suggestions, folders, multi-row filing, a details drawer and synchronized artifact deletion. |
-| ✅ **Imagery providers** | Supports Esri, OSM, OpenTopoMap, Sentinel-2 and optional Mapbox/Google with usage controls. |
-| ✅ **Sentinel-2 cloud ceiling** | Renders cloudy passes by default and lets a slider set the ceiling, which the tiles, the calendar and "most recent" all follow. |
-| ✅ **Capture extension** | Files user-initiated map screenshots with URL metadata, attribution and provenance; also saves a map's point as a place, or any page as a bookmark. |
-| ✅ **Distribution** | Bundles the browser UI, launcher, cross-platform binaries, ffmpeg, locked builds and server hardening. |
+| ✅ **Case navigation** | Searches, groups and files case work through the sidebar, Saved views, folders, notes and synchronized deletion. |
+| ✅ **Capture extension** | Files user-requested screenshots with their source details, saves map points and bookmarks pages. |
+| ✅ **Distribution** | Ships the browser UI, hardened local launcher, locked cross-platform builds, ffmpeg and browser interaction tests. |
### v2 GEOINT suite (shipped as GitHub `v0.2.0+`)
| Tool | What it does |
|------|--------------|
-| ✅ **Coords & Sky** | Converts common coordinate formats, copies results, opens map or geocoding links, and borrows a point already saved in the case instead of retyping it. |
-| ✅ **Sun, moon and local time** | Rise, set, azimuth, altitude, twilights, moon phase and bright-limb angle for a point and date, each instant in civil local time and UTC, with a day chart and a compass rosette. Polar day, polar night and a date without a moonrise are states. |
-| ✅ **Sun & moon on the map** | A map mode: one date's path from an anchored point, as the arc each body sweeps while up, hour ticks, and the bearing at a draggable hour. |
-| ✅ **Reverse Search** | Prepares image or video frames for keyless reverse-image services without uploading automatically. |
-| ✅ **Grid Search** | Saves editable AOI grids with keyboard review states and place promotion. |
-| ✅ **Templates** | Stores reusable proof styles and post-thread structures at workspace level. |
-| ✅ **Geo Report outputs** | Targets X, Bluesky or Mastodon and saves structured Markdown notes with evidence links. |
-| ✅ **Case Notebook** | Edits tabbed Markdown notes with local media, entity links and broken-reference markers. |
-| ✅ **Notebook diagrams** | Draws ```mermaid fences in the preview and the PDF, loading the library only when a note holds one. |
-| ✅ **Notes to PDF** | Exports the open note or a ticked selection as one server-rendered file per note, with stable homonym names, bounded diagrams and bundled faces for living scripts including CJK. |
-| ✅ **Export destinations** | Remembers separate app-wide folders for note PDFs, media copies and proof PNGs, defaults to the case's `exports/` and atomically avoids overwrites elsewhere. |
-| ✅ **Canvas tests** | Exercises Leaflet and Konva interactions in Chromium and Firefox. |
-| ✅ **Storage platform** | Uses per-case SQLite, bounded catalog queries and a durable one-worker job queue. |
-| ✅ **Case bundle** | Exports and imports the whole case folder, including the analyst's free zone, with integrity checks and optional whole-bundle password protection. |
-| ✅ **Trash** | Holds deleted artifacts for restore or explicit permanent deletion. |
-| ✅ **Gated downloads** | Fetches login-walled media by borrowing a browser session or cookies.txt, cookie-less by default and prompted only on a wall. |
-| ✅ **Find at scale** | Bounded, paged loading with a shared search box and sort across the Media Library and Files, plus case-name search in the switcher. |
-| ✅ **Searchable pickers** | Pickers in Inspect, Reverse Search, Geo Proof and the Notebook notes menu search past six entries and browse case folders behind the "…". |
-| ✅ **Report an issue** | System writes a bug or a request into a pre-filled GitHub issue, with version, OS and the run's last warnings, home path and account name scrubbed. |
-| ✅ **Settings backup** | Carries portable settings, keys, presets and the signature while leaving machine paths and download sessions behind. |
-| ✅ **Open the folder** | A case's folder, or the whole workspace, opened in the system file manager. |
-| ✅ **Proofs on the map** | A fourth position of the Saved switch places each proof by its own coordinates, then by the captures it composes; `All` marks a worked capture with a dot rather than doubling it. |
-| ✅ **Import enrichment** | Reads image EXIF/dHash and video container/stream metadata locally in the background; parsed GPS produces linked Suggestions and all fields appear in Details. |
-| ✅ **GPS in Media** | A GPS filter and a per-row pin in the Media list send a stated position to the map, images and videos alike. |
-| ✅ **Relation vocabulary** | One registry for the non-chain edges, stated or settled from Details and from a point's card on the map. |
-| ✅ **Visible file names** | Shows each file-backed artifact under its filename stem and moves the file when that name changes. |
-| ✅ **Case doctor** | Checks a case without changing it, then offers explicit repairs for a missing database, missing media and files dropped into `media/`. |
-| ✅ **Workspace folder** | Settings adopts a folder as it is, or copies and SHA-256-verifies every file before switching an external pointer and keeping the old copy. A missing configured folder stops startup. |
-| ✅ **One Azimut per workspace** | An OS-held lock the kernel drops on exit, with a heartbeat so a folder shared between machines can tell a live holder from a crashed one. The second instance opens to a screen naming the first, and can overrule it. |
-| ✅ **Adopt a case folder** | A folder made in the workspace from the file manager becomes a case on one click, where it is, without reading or moving what it holds. One holding a case that lost its manifest is recovered instead, then handed to the Doctor. |
+| ✅ **Coordinates & sky** | Converts coordinates and reads sun, moon, twilight and local time for a saved point on charts or the map. |
+| ✅ **Research helpers** | Prepares media for keyless reverse search and saves keyboard-reviewed AOI grids. |
+| ✅ **Reports & templates** | Stores reusable proof and post structures, then prepares sourced Markdown for X, Bluesky or Mastodon. |
+| ✅ **Case Notebook** | Edits linked Markdown notes with local media, Mermaid diagrams, PDF output and remembered export folders. |
+| ✅ **Media at scale** | Handles login-gated downloads, bounded search, searchable pickers, local metadata enrichment and GPS handoff to the map. |
+| ✅ **Storage & recovery** | Uses per-case SQLite and durable jobs, with whole-case bundles, Trash and portable settings backups. |
+| ✅ **Case utilities** | Opens case folders, reports scrubbed diagnostics, keeps filenames in sync and offers explicit Doctor repairs. |
+| ✅ **Evidence on the map** | Places proofs and derived media through their evidence chain, with stated point uncertainty and traced footprints. |
+| ✅ **Ontology connections** | Keeps Relations, Mentions, Claim connectors and artifact lineage separate under one validated verb registry. |
+| ✅ **Board & entities** | Provides the sortable Case Board, shared Details, typed creation and primary entity photos. |
+| ✅ **Case graph** | Draws registry-backed lenses with clustered nodes, readable edges, previews and an explicit view budget. |
+| ✅ **Working the graph** | Expands, folds, hides, searches and pins nodes per lens, with undo and no case mutation. |
+| ✅ **Graph evidence** | Folds sources onto their edges and exposes derivation, support, source and account counts. |
+| ✅ **Shared analysis views** | Shares one filter and saved-view family between Board and Graph while Timeline keeps readings built for tracks. |
+| ✅ **Claim assessment** | Keeps statement confidence, relation confidence and source reliability separate, with explicit support and contradiction links. |
+| ✅ **Structured findings** | Records associations, duplicate identifiers, asset condition, equipment models and statement totals without inventing missing values. |
+| ✅ **Temporal Claims** | Dates a Claim with guided point, timestamp or interval input and files its subjects, places and evidence atomically. |
+| ✅ **Case Timeline** | Aligns dated statements and media on a windowed UTC axis with uncertainty, density, direct edits and Undated work. |
+| ✅ **Timeline readings** | Builds coloured tracks from presets or Search+, then saves a changing Live view or a fixed Snapshot. |
+| ✅ **Timeline clocks & comparison** | Reads the axis in UTC or a chosen civil zone, adds daylight context and compares exact or uncertain entries. |
+| ✅ **Shared fact time** | Passes one fact-time window between Timeline, Board, Graph and a session-only Map layer without mixing in filing dates. |
+| ✅ **Workspace portability** | Moves or adopts a workspace safely, recovers hand-added cases and prevents two live instances from sharing it silently. |
+| ✅ **Updates & paste** | Reports available app, downloader and extension updates, then files supported clipboard content from the main case surfaces. |
---
@@ -154,8 +159,7 @@ Each version delivers one complete daily workflow. Firm ideas move here from
| Tool | What it does |
|------|--------------|
-| **Case Board / Relations** | Browses, creates and merges entities; graph view over the schema filled since v1, on the shipped relation vocabulary. |
-| **Case Sheet** | The same case as a table: a row is an entity, columns are its attributes plus free ones the analyst adds, sorted, filtered and edited in place. Imports a CSV as loose rows that stay out of the graph until promoted, and exports back to CSV or GeoJSON. |
+| **Case Sheet** | Adds editable free columns and CSV/GeoJSON round trips to the shipped Board. Imported loose rows stay outside the graph until promoted. |
| **Camera Resection (GCP)** | Marks matching points photo↔map, then solves camera position, viewing azimuth and rough FOV (OpenCV `solvePnP`) and saves the match as evidence. Its photo canvas and pixel↔angle camera frame are built for two callers: Sky Clock fills the same frame by hand. |
| **Command palette** | Ctrl+K reaches a tool, a case or an artifact. |
@@ -169,10 +173,13 @@ changes under it.
| **Map engine (MapLibre)** | Replaces Leaflet with MapLibre GL at 2D parity: same providers, same captures, and the capture tests still verify the pixels. Ships before the 3D map, which builds on it. |
| **3D map** | Pitch, public DEM terrain and extruded OSM buildings on the MapLibre map. An oblique capture records its pitch beside the bearing, so the view can be reproduced. |
| **Capture scale and north** | Preference-controlled scale bar, north arrow and graticule on app and extension captures. Follows the map engine, which redraws what a capture is made of. |
+| **Footprint tracing** | Draws a place's uncertainty as the shape it really is, for a quay, a treeline or an L-shaped block the circle describes badly. The field, its validation and its drawing already ship; only the gesture is missing, and it follows the map engine rather than being written twice. |
| **Satellite Compare** | Same coords across providers (Esri / Sentinel-2 date slider / Bing / keyed), synced pan/zoom. Copernicus easy link. |
| **Image Compare** | Overlay two images with opacity, swipe and pixel diff. Assist satellite-to-screen alignment without presenting a verdict. |
| **Metadata follow-up** | Explains which common image/video fields were stripped and proposes events from capture times. |
| **Edit Provenance** | Reads a rendered video's own edit history: which source clips it was cut from, in what order, and the GPS, dates and cameras those clips still carry. |
+| **Sky sessions** | Saves a sun or moon lookup as a case artifact: the point, the date and the time, never the numbers they produce. It reopens where it was left, a proof can show its reading, and a statement can cite it. |
+| **Grid sessions in the graph** | Brings the saved AOI grids into the case as entities, adopting the specs already on disk. Grid Search is the last saved tool state living outside the graph, so today nothing can say "this sweep is how I found it". |
| **Sky Clock** | Marks a shadow, the sun or the moon in an image or a video frame, with the horizon and north giving the angles, then renders the year as a day × hour heatmap of the slots that fit. A visible moon also carries phase and bright-limb angle, which usually cuts a year down to a few instants. |
| **Case KMZ** | One self-contained file per case: a pin per place, carrying the notes and proof images it is linked to, opened in Google Earth. Frozen rather than live, because only the web Earth remains and it follows no network link. |
| **Imagery Wayback** | Esri World Imagery archive as a date slider: one view across every published release, key-less. |
@@ -213,12 +220,10 @@ supplies, since a ridge ends the day well before the flat horizon does.
| **Skyline Matching** | Traces a horizon in a photo and compares it against the DEM profile seen from candidate points, in the same azimuth and elevation frame Camera Resection and Sky Clock already use. Terrain-occluded sun times then split candidates a matching horizon leaves tied. |
| **Map Board (MyMaps-style)** | Editable case map: custom pins + notes/links, shapes, layers; import/export KML/KMZ/GeoJSON; pins bind to `place`. |
| **Evidence Locker** | Track SHA-256, timestamps, source and notes; archive with Wayback; export `evidence.jsonl` under a hash-chained manifest, so any later edit to an exported file is detectable. |
-| **Timeline Builder** | Timestamped events from mixed sources aligned on timeline + map. |
| **Report Builder** | Assemble proofs/maps/timeline/entities/notes into PDF or one self-contained HTML file with its media embedded, readable offline. |
| **Case Sync (Git)** | Push a case to a private or public Git remote, pull it back, and diff two revisions, so two analysts can work the same case. |
-Toward v4: dependency-aware delete (partly done);
-archive-on-download and a Wayback CDX snapshot timeline with diff; web-page save
+Toward v4: archive-on-download and a Wayback CDX snapshot timeline with diff; web-page save
extension; provenance stamp on exports (short hash, optionally visible) that
re-identifies a shared PNG in its case;
Sentinel-2 change detection with an NDVI difference over a date range; source
@@ -256,7 +261,8 @@ spec alone:
Toward v5: real-world measurement from a resected photo or a solved camera track
and its GCP camera pose; a gaussian-splat round trip for a solved camera track;
satellite-pass search from public TLEs; 3D satellite capture; Google
-Photorealistic 3D Tiles on the user's own key.
+Photorealistic 3D Tiles on the user's own key; non-destructive identity resolution
+for duplicate entities returned by orchestrated searches.
## 7. Loose ideas
@@ -264,8 +270,10 @@ No version yet. Promote an idea when its workflow is clear; delete it when it
stops making sense.
- **Media in the analyst's half:** a button that looks for media beside `azimut/` and offers to bring them into the case, rather than waiting for them to be moved into `media/` by hand.
+- **Count a statement's independence by origin, not by wrapper:** three collages made from one video are three sources today, and are arguably one. The graph already answers this for a place; changing it for a statement changes a published number.
- **Free-form montage editor:** consider only if it stays distinct from Geo Proof and Inspect collage.
- **In-app OSINT assistant:** local chat and vision suggestions for analyst confirmation, with no cloud or API key by default.
+- **Geographic playback:** step through dated case items on the map instead of showing one fixed Timeline window.
## 8. Explicit non-goals
@@ -315,9 +323,11 @@ stops making sense.
Accepted risks recorded here: cleartext keys over
localhost, the hash-verified scraper updater, and tile/media URL fetches (SSRF
only matters if the localhost assumption breaks). The startup update check is
- the one on-mount network call: opt-out and read-only against GitHub's releases
- feed, notes rendered through the Notebook's DOMPurify-sanitized Markdown
- renderer rather than as raw HTML. Remote images embedded in a
+ the one on-mount network call: opt-out, and read-only against GitHub's
+ releases feed plus PyPI's JSON for the two downloaders, both governed by the
+ same switch. Release notes are rendered through the Notebook's
+ DOMPurify-sanitized Markdown renderer rather than as raw HTML. The capture
+ extension is compared locally, so it is answered with the switch off. Remote images embedded in a
Notebook note contact their host whenever the preview opens; Notebook warns
about that behavior and local Case media avoids it. Notebook diagrams are the
one markup DOMPurify does not clear: Mermaid draws its SVG into the preview
@@ -336,8 +346,8 @@ stops making sense.
## 10. Open questions
-- Define entity attribute vocabularies, `same-as` merge semantics and confidence
- levels before Relations ships.
+- Source reliability sits on the `bookmark` or the `account` cited. Reopen it the day
+ a source is neither: a paper document, a testimony.
- Déjà Vu community index: needs infrastructure and moderation; out of scope
until v5.
- Name/handle availability: GitHub org/repo `azimut`, x.com handle, domain.
diff --git a/docs/STORAGE_AND_PERFORMANCE.md b/docs/STORAGE_AND_PERFORMANCE.md
index 56efb4b..ddc78f1 100644
--- a/docs/STORAGE_AND_PERFORMANCE.md
+++ b/docs/STORAGE_AND_PERFORMANCE.md
@@ -101,7 +101,9 @@ for a case to fit under it on Windows, and names it as a warning elsewhere.
proofs/ # rendered PNGs
.meta/ # editable specs and pasted assets
exports/ # what the analyst exports: notes as PDF, and their own files
- .data/ # case.db: entities, links, folders, catalog and jobs (SQLite)
+ .data/ # private structured and presentation state
+ case.db # entities, links, folders, catalog and jobs (SQLite)
+ entity-images/ # private, bounded entity photos and their thumbnails
.drafts/ # post drafts
.inspect/ # saved Inspect session specs
.search/ # saved Grid Search state
@@ -156,7 +158,7 @@ graph.
## Source of truth
-`case.db` owns the graph. A case bundle is the portable snapshot: a cleaned
+`case.db` owns the graph. A case bundle is the portable case archive: a cleaned
database plus declared files under a SHA-256 manifest. Rollback journaling leaves
no WAL checkpoint outside the case folder. Media, proofs and note bodies remain
inspectable files.
@@ -169,7 +171,8 @@ not orphan it. Diagnosis is read-only and reports:
- a missing or unreadable `case.db`;
- media and capture entities whose file no longer exists;
-- visible files placed directly in `media/` without a graph entity.
+- visible files placed directly in `media/` without a graph entity;
+- a temporal projection that no longer matches Claims or media metadata.
Repairs are separate API actions. A deleted database is rebuilt in a temporary
SQLite file from media sidecars, note files and proof specs, then renamed into
@@ -178,8 +181,8 @@ database-only provenance cannot be recovered and the dialog says so first.
Missing media can be removed through the normal Trash path or rebound to an
unregistered file already inside `media/`. An unknown file goes through the
normal media registration pipeline, gaining a hash, sidecar, index row and
-provenance. None of these actions runs at startup, on case open or during a
-diagnostic request.
+provenance. A stale temporal projection can be rebuilt from its authorities.
+None of these actions runs at startup, on case open or during a diagnostic request.
## Ownership rules
@@ -190,6 +193,8 @@ carry enough information to detect staleness.
|---|---|---|
| Case name and storage version | `case.json` | Small manifest, atomically replaced |
| Entities, links and folders | `case.db` | Transactional and versioned |
+| Entity photo galleries | `case.db` (`entity_images`) | Ordered private photos or Media references, with one primary |
+| Private entity photo bytes | `.data/entity-images/` | Bounded JPEG plus dedicated thumbnail; never indexed as media |
| Entity labels and notes | `case.db` | Indexed for catalog search; file-backed labels mirror their filename stem |
| Media visible name | Media filename stem | Mirrored as `title` to the sidecar, graph and browse index |
| Media notes and folder | Media sidecar | Mirrored to the graph and browse index |
@@ -214,10 +219,20 @@ Windows, macOS and Linux:
`sqlite3` module.
- **Feature availability is per-binary, not per-Python.** `sqlite3` links whatever
SQLite the build environment provides, so FTS5, JSON1 and RTree can be present
- on the dev machine yet missing from a shipped binary. The store stays on core
- SQL: `find_entity` scans and matches attributes in Python rather than relying on
- JSON1. Any future indexed projection (geo, time, full-text) is probed at runtime
- with a `LIKE`/scan fallback before it enters the contract.
+ on the dev machine yet missing from a shipped binary. Nothing beyond core SQL
+ enters the contract without a runtime probe and a fallback beside it:
+ - `find_entity` scans and matches attributes in Python.
+ - The Board's field filter (`attr`/`value`) is the one JSON1 caller, behind
+ `_has_json1()`. Present, `json_extract` compares the **top-level** field;
+ absent, the same question runs as `LIKE` over the exact text `json.dumps`
+ wrote, which matches the field at **any depth** — a nested object holding the
+ same key and value matches too. `tests/test_repository.py` asserts the probe
+ answers true, so CI proves on all three platforms and the 3.11 floor that the
+ exact path is the one that ships, and exercises the fallback on every platform
+ by forcing it.
+ - The field/value menus behind that filter (`attr_facets`) scan in Python, so a
+ menu never depends on an extension.
+ Any further indexed projection (geo, time, full-text) follows the same rule.
- **`case.db` lives under the workspace root**, inside the case folder, never
beside the frozen executable, which may sit on read-only media.
- **Dev-only tooling stays out of the artifact.** The synthetic fixture
@@ -242,9 +257,16 @@ review.
## Database shape
-`case.db` is at SQLite schema 7. The schema counter is independent of the JSON
-`CASE_SCHEMA`: the manifest's `azimut.storage` field selects the backend, and each
-format counts its own shape upgrades.
+`case.db` is at SQLite schema 17: schema 8 adds nullable `links.confidence`,
+schema 9 rebuilds every row's `search_text`, schema 10 stores graph pins per lens,
+schema 11 adds `links.nature`, schema 12 adds entity photo galleries, schema 13
+adds saved analysis views with their bounded-list count, and schema 14 indexes the
+two columns the catalog orders the whole case by. Schema 15 adds the rebuildable
+temporal projection, schema 16 extends saved analysis views to Timeline recipes
+and snapshots, and schema 17 rewrites temporal bounds to fixed microsecond width.
+The schema counter is independent of the JSON `CASE_SCHEMA`: the
+manifest's `azimut.storage` field selects the backend, and each format counts its own
+shape upgrades.
The case manifest is at `CASE_SCHEMA` 9. Schema 3 is the last released folder
shape before the `azimut/` boundary; schemas 4–8 were development checkpoints
@@ -266,13 +288,40 @@ use `.data/rename.json`, so a restart can finish references after the bytes move
`entities`
: `id`, `type`, `label`, `attrs_json`, an indexed `folder` (denormalised from
`attrs.folder`), denormalised search text, provenance fields and status.
- Search covers label, type, folder and notes. Unknown types and attributes stay
- valid.
+ Search covers label, type, folder and notes. `label` (under `NOCASE`) and
+ `prov_at` are indexed as well, because the catalog orders the whole case by
+ them. Unknown types and attributes stay valid.
`links`
-: `id`, source, target, `type`, provenance and status. Foreign keys forbid a link
- to a missing entity. The delete policy lives in the dependency-aware service
- (`engine/links.py`), not in a blind SQL cascade.
+: `id`, source, target, `type`, provenance, status and a nullable `confidence`.
+ Foreign keys forbid a link to a missing entity. The delete policy lives in the
+ dependency-aware service (`engine/links.py`), not in a blind SQL cascade.
+ `confidence` is the closed ordinal used only by ratable ordinary relations;
+ `NULL` means not assessed. Claim confidence lives in the Claim entity, while
+ Claim connectors, mentions, lineage and `same-image-as` reject edge ratings
+ (ONTOLOGY §3).
+
+`graph_pins`
+: Saved graph coordinates keyed by entity and lens. They are presentation state
+ and cascade when the entity is deleted.
+
+`entity_images`
+: Ordered private photos or references from supported hand-made entities to image
+ `media` or `capture` entities. A partial unique index permits one primary image
+ per entity. Direct computer imports are bounded JPEGs under
+ `.data/entity-images/` and create no Media entity or browse-index row. A Media
+ reference owns no duplicate bytes; its original media record remains the owner.
+
+`analysis_views`
+: Case-owned live recipes and immutable Board, Graph or Timeline snapshots. List reads carry
+ metadata and `snapshot_count`, never the snapshot payload. A live recipe stores
+ Search+ and presentation state, including view-local graph pins and camera, and
+ autosaves after edits. Timeline recipes store their ordered track queries, folds,
+ grouping, visible categories, hidden and pinned entries, entity scope and UTC
+ window. An entity snapshot stores copied entities, provenance, closed relations and
+ embedded bounded preview thumbnails. A Timeline snapshot stores the matching
+ temporal rows and exact track assignments. Neither consults current graph rows or
+ files when read.
`folders`
: Normalized `/`-separated logical paths for the analyst's organisation. Not
@@ -302,6 +351,37 @@ use `.data/rename.json`, so a restart can finish references after the bytes move
through `GET /api/cases/{id}/media/item`. The original files and sidecars remain
the file-level records.
+`temporal_items`
+: Rebuildable, homogeneous rows for dated Claims, intrinsic media dates and case
+ activity. Each row keeps the raw value beside normalized half-open bounds,
+ precision, timezone and uncertainty flags. Claims in `entities.attrs`, indexed
+ media sidecars and entity provenance remain authoritative. Deleting this table's
+ contents and running `rebuild_temporal_projection()` recreates the same rows.
+ Window/category/owner indexes let Time and Timeline page without scanning entity
+ JSON or opening sidecars. Each page also returns the complete dated extent for the
+ selected categories and entity scope, independent of the visible window, so the UI
+ can reset and position its density overview without loading every row. Density
+ buckets are cut by year, month, day or hour, and include their per-category counts
+ plus the span of their own entries, so the minimap can stack its columns and open a
+ clicked one onto what it holds without another query. A track query applies the shared Search+ entity predicate through the
+ temporal owner, subject, place or evidence connector, plus time-role and view-local
+ hiding. Its counts distinguish an absent date (`undated`) from a raw local or invalid
+ value that cannot be positioned yet (`unplaced`). A caller drawing the page on an axis
+ asks for a spread read (`spread=true`): the same ordering is cut into `stride =
+ ceil(total / limit)` interleaved slices, one per page, so the first page samples the
+ whole window at the density the overview draws instead of stopping wherever the front
+ of the window runs out of room, and later pages fill the sample in without a repeat
+ or a gap. Chronological cursors and phase cursors are not interchangeable.
+
+ The same table answers the fact-time window Board, Graph and their saved views
+ filter by. It is one `EXISTS` over the window index beside the catalog's other
+ terms, reaching a row either as the owner of a temporal entry or through an
+ `about`/`at`/`cites` edge from one, so the period narrows the page, the totals and
+ a capture through the same predicate rather than through three readings of it. The
+ boundaries are read once, at the edge, and a reduced date names its whole civil
+ period on the upper end — a saved `2024-03` is the whole of March wherever it is
+ asked from.
+
### Indexes and migrations
Indexes cover entity type/status/folder, link source/target/type and media browse
@@ -312,14 +392,24 @@ the version inside the transaction so a raced second opener applies nothing; a
newer schema is refused rather than mangled. The shipped migrations add the
indexed `folder` column (1→2), the `jobs` table (2→3), entity search text and
the media browse index (3→4), the `has_gps` flag (4→5), the trash journal
-(5→6), then interrupted-operation recovery state (6→7). The 4→5 backfill
-reads the sidecar JSON already held in each index row, so a case enriched before
-the column existed gains its position filter on open with no file scan.
+(5→6), interrupted-operation recovery state (6→7), relation confidence (7→8),
+search-text rebuilding (8→9), graph pins (9→10), relation qualifiers (10→11),
+entity galleries (11→12), saved analysis views with their denormalised snapshot
+count (12→13), the catalog's ordering indexes (13→14), and the temporal projection
+with a full authority backfill (14→15). Schema 16 rebuilds the analysis-view table
+with Timeline as an accepted surface while preserving every existing view. Schema 17
+rebuilds the temporal projection so whole seconds and sub-second values share one
+sortable width. The 4→5 backfill reads the sidecar JSON
+already held in each index row, so a case enriched before the column existed gains
+its position filter on open with no file scan.
The schema-4 media backfill scans sidecars once on first open. Its completion
marker and index rows commit together, so an interrupted backfill retries safely.
Normal media creation, edits, thumbnail changes and deletion keep the index in
-sync.
+sync. The same writes refresh the media-owned temporal rows. Entity create, update,
+delete and Trash restore refresh or cascade the entity-owned rows. Bundle databases
+carry the projection, while an explicit rebuild after import remains safe and
+idempotent.
## Trash and artifact ownership
@@ -328,13 +418,21 @@ type. Delete writes a recovery journal before moving files to `.trash/<group>/`
and removing graph rows. The group directory is flat: each file waits under a
number, and the journal's `slots` list says where it came from, so the trash
never stacks a second copy of the case tree under itself. Restore refuses
-occupied destinations, then restores the original entity ids, surviving links
-and tombstones. An interrupted delete is rolled back or published on the next
+occupied destinations, then restores the original entity ids, surviving gallery
+attachments, links and tombstones. An interrupted delete is rolled back or published on the next
case open; an interrupted restore is completed.
Shared thumbnails do not move; they are discarded and queued again
after restore. Purge removes the journal only after its directory is gone, so a
Windows file lock leaves a retryable group instead of orphaned bytes.
+Saved analysis views are case state too. Deleting one writes its full recipe or
+capture to Trash, and restore reinserts the same id. Snapshots are bounded to 2,000
+entities, 10,000 closed relations or 5,000 temporal rows, and an 8 MiB JSON spec. Embedded previews are
+thumbnail copies, at most 512 KiB each and 4 MiB total; they are visual context, not
+original evidence and not a cryptographic attestation. There is no standalone view
+file. Case bundles carry the `analysis_views` rows with the rest of `case.db`, so
+transmission cannot separate a reading from the case it describes.
+
## Case bundles
Exports run as `bundle-export` jobs and write atomically to
@@ -371,7 +469,7 @@ keep a safety reserve, and warn for imports above 10 GiB. Work is staged under
`<workspace>/<id>.incoming/`; the existing shell and completed staging directory are
swapped by rename for Windows compatibility. Every import creates a new case and
records `origin_case_id` plus `imported_at` in database metadata.
-Entities and links keep their original ids, provenance and confirmation status.
+Entities, links and entity photo galleries keep their original ids and state.
Geographic, temporal and full-text projections are deferred until a query needs
them. Each projection requires its own migration and tests.
@@ -416,12 +514,33 @@ endpoints:
- `GET /api/cases/{id}/catalog/entities` returns `{items, next_cursor}` in stable
insertion order, with a clamped page size and server-side filters: a
- comma-separated `type` set, `status`, `q` over label/type/folder/notes, and
- folder (`unfiled=true` or an exact path, with optional descendants). The cursor keys on `rowid`, so a
- background import appending rows never shifts a page already scrolled past, and a
- deletion before the cursor never skips a live row.
+ comma-separated `type` set, `status`, `q` over label/type/folder/notes, folder
+ (`unfiled=true` or an exact path, with optional descendants), one stored field
+ holding one value (`attr` + `value`), having a neighbour of a type (`linked`) or
+ none at all (`unlinked`), and how the row got here (`since`, `until`, a
+ comma-separated `by`). One predicate answers all of them and the graph's own
+ ranking, so the board and the drawing cannot mean two things by one filter.
+- `order` sorts the **whole filtered set** rather than the page — `created` and
+ `label`, each with a `-` prefix for the other direction — because *the newest in
+ this case* and *the newest of the hundred rows loaded* are different answers and
+ only the first is worth having. The default cursor keys on `rowid`, so a background
+ import appending rows never shifts a page already scrolled past and a deletion
+ before the cursor never skips a live row; an ordered one keys on its sort column
+ **and** the rowid, spelled `<rowid>:<key>`, so a hundred rows filed in the same
+ second cannot tie the paging into a loop. Both sort columns are indexed (schema
+ 14), so an ordered page walks an index instead of sorting the filtered set in a
+ temp B-tree; `tests/test_repository.py` reads the query plan and holds it there.
- `GET /api/cases/{id}/catalog/summary` returns `{total, by_type, by_status,
- by_folder}` without shipping the graph.
+ by_folder, by_source, linked_to, unlinked, countable}` without shipping the graph.
+ `linked_to` counts entities that **have a neighbour** of each type, which is not how
+ many of that type the case holds: it is what the filter menu has to price itself
+ with, and the other number looks like an answer without being one. `countable` is how
+ many statements would draw a line if the case were added up — carrying a number,
+ about something — which is what dims the Board's **Totals** view before it can answer.
+- `GET /api/cases/{id}/catalog/tally` adds those statements up per subject over the
+ same narrowing terms as the catalog page, bounded at 2 000 statements and reporting
+ the cut. `GET /entities/{id}/tally` is the same arithmetic for one subject, which is
+ what the Details panel reads.
- `GET /api/cases/{id}/entities/{id}/chain` (neighbour derivation),
`GET /entities/lookup` (one entity by attribute), and
`GET /entities/{id}/derivation` (transitive `derived-from` closure) are the
@@ -442,6 +561,27 @@ Deferred to their first consumer: date filters (a timeline filter), links
pagination (a relations/graph view), and ranked full-text search (gated on
per-binary FTS5).
+### An id set larger than a statement can bind
+
+SQLite's compiled variable ceiling is 999 on the oldest builds still shipped, so
+`_ID_CHUNK` caps an `IN (…)` at 250 ids and `_chunks` splits a wider set. That is
+the right answer for every question a chunk can settle alone — *which of these
+entities exist*, *how many edges does each of these carry* — and it costs one
+statement per chunk, linear in the set.
+
+It is the wrong answer for the closed edge set, which is what the graph draws:
+an edge with **both** ends in the set has ends that can fall in two different
+chunks, so no chunk holds it. Asking every *pair* of chunks closed that hole and
+bought a quadratic one — 9 statements at 650 nodes, 400 at 5 000.
+
+`_scope_table` puts the ids in a `TEMP` table keyed on `id`, and the closed set
+becomes a join on that key: **one statement at any size**, binding no ids at all.
+Measured on a 5 000-node star, 133 ms → 28 ms, and linear rather than square; at
+one chunk the two are within a tenth of a millisecond. Temp tables belong to the
+connection and `_connect` opens a fresh one per operation, so a scope cannot leak
+into the next read. `tests/test_repository.py` traces the statements a read runs
+and holds it to one.
+
## Thumbnails and background jobs
Thumbnails are disposable pixels: a broken or missing one never blocks access to
@@ -500,6 +640,10 @@ original: a proof panel picker rendering full-size captures in 150px cells was
the slowest surface in the app. The proof pickers poll the listing while
anything is pending, like the grid does.
+Entity galleries reuse the same thumbnails. Details constrains the main image,
+while the Board, sidebar and graph read only the primary thumbnail and fall back
+to the entity glyph when none exists.
+
A saved proof's export is thumbnailed through the same cache: `POST
/cases/{id}/proofs` renders one from the bytes it just wrote and records it in
the spec, and `GET /cases/{id}/proofs` backfills any proof that has none (saved
@@ -514,6 +658,12 @@ refetching. Thumbnail URLs fold in the content hash and the generator version,
so they can never change meaning and are served `immutable` — the browser stops
asking for them at all.
+A media file keeps the name it arrived with, and a download can land as
+`#3deenero2025.mp4`, so the path is percent-encoded per segment before it
+reaches this route: raw, that `#` opens a fragment and the request arrives as
+the directory. `lib/fileUrl.js` is the UI's only builder for these URLs, and
+notes store them encoded (the PDF export unquotes them back to a path).
+
The Media Library and Files browse media through `GET
/api/cases/{id}/media/page`, a bounded SQLite query with `q`, `kind`,
source-derived `category`, `folder`, `sort`, `limit` and `cursor`. It returns
@@ -526,11 +676,19 @@ pickers, satellite crops and derivation traces.
The Map's Saved panel opens on `GET /api/cases/{id}/satellite/index`: one compact
row per place, capture and filed screenshot — id, kind, title, coordinates,
-geography, thumbnail, provider, dates, notes, and nothing else. The tree, the
-search modal and the map overlay all read that one response, so hundreds of saved
-items cost tens of KB instead of every capture's full media row and full-size
-image. Rows come newest first on a single normalised timestamp, and the endpoint
-makes no network call. Geography rides on the entity's `attrs.geo`
+geography, thumbnail, provider, dates, notes, how precise the point is
+(`radius_m`, `footprint`), and nothing else. The tree, the search modal and the
+map overlay all read that one response, so hundreds of saved items cost tens of KB
+instead of every capture's full media row and full-size image. Rows come newest
+first on a single normalised timestamp, and the endpoint makes no network call.
+
+`footprint` is the one field whose size is not fixed per row: it carries the
+place's own geometry so the overlay can draw a traced area rather than a pin,
+and `entities.MAX_FOOTPRINT_POINTS` caps it at 4 096 vertices. Nothing traces one
+today — the field is API-only until the drawing gesture ships with the map engine
+(SPEC §6, v2) — so in practice the row is as compact as the list above. That
+gesture is when to decide whether the index keeps carrying whole geometries or
+sends a bounding box and fetches the shape per place. Geography rides on the entity's `attrs.geo`
(`ok`/`nocoords`/`nocountry`/`failed`); continent is never stored, it is derived
from the country code at read time (`engine/continents.py`), so correcting that
table repairs existing cases with no migration. Countries that span two
@@ -550,6 +708,11 @@ removes the file and sidecar, then settles the database. Thumbnail generation
follows the same temp-then-rename discipline. The rollback journal means a copied
closed case is always complete.
+Direct entity photos follow the same boundary without entering the media pipeline:
+Pillow applies the process-wide pixel clamp, EXIF orientation is normalized, the
+display copy is capped at 2048 px and its thumbnail at 512 px. Detaching one
+removes both private files. A Media Library choice only removes the reference.
+
## Performance
The deterministic large-case fixture (`tests/bigcase.py`) builds entities,
@@ -584,6 +747,10 @@ limits instead of machine-specific timings.
refusal, foreign keys, rollback, the in-place schema upgrade through every
migration, keyset paging, media browse search/facets, and the atomic converter
(roundtrip, dangling-link report, failure leaves no db, large-case integrity).
+- **Entity photos** (`tests/test_entity_images.py`, `tests/test_trash.py`,
+ `tests/test_bundles.py`): supported types, primary promotion, API validation,
+ no Media row for computer imports, bounded output, catalog and graph thumbnails,
+ Trash restore and bundle round trips for both storage forms.
- **Migration** (`tests/test_migrations.py`): legacy json → sqlite on open, backup
recoverability, a failed activation leaving the json case usable, forward-compat
refusal.
diff --git a/docs/UI.md b/docs/UI.md
index f1ed15f..10a137a 100644
--- a/docs/UI.md
+++ b/docs/UI.md
@@ -6,7 +6,7 @@ phasing lives in [SPEC.md](SPEC.md).
## Layout anatomy
```
-┌ topbar: rose+wordmark · case switcher · (spacer) · settings gear · sidebar toggle ┐
+┌ topbar: rose+wordmark · case switcher + Board · (spacer) · settings gear · sidebar toggle ┐
├ rail ┬ tab strip (only when the workspace has several tools) ┬ case sidebar ┤
│ │ tool canvas │ │
└──────┴───────────────────────────────────────────────────────┴──────────────┘
@@ -19,11 +19,20 @@ in `frontend/src/lib/workspaces.js` and appear as tabs, never as new rail entrie
| Workspace | Tools today | Future tools land here |
|---|---|---|
+| **Case** (topbar) | Board, Graph, Timeline | Sheet; v5: Orchestrator |
| **Sources** | Media Library, Files, Reverse Search | Channel Monitor, Evidence Locker |
| **Examine** | Inspect (Selection / Frame / Collage / Analyze) | Edit Provenance, Shot contact sheet, OCR, Image Compare, Hints, Sky Clock, audio |
| **Map** | Satellite, Coords & Sky | **one map, many modes**: Compare, Imagery Wayback, Event layers, Ground Imagery, Measures, Viewshed, OSM Query, Map Board |
| **Compose** | Geo Proof, Geo Report, Notebook | Report Builder, GIF maker |
-| *(Case)* | Sidebar | v2: Relations, Sheet; v4: Notes, Timeline; v5: Orchestrator |
+
+**Case is not on the rail.** The rail reads as a sequence of stages, and the case is
+not a stage: it is what every stage files into. It hangs off the case switcher in
+the topbar instead, so the header answers *which case* and the rail answers *what
+am I doing*. It stays a workspace in every other respect — tabs, `#case` deep
+links, and its own remembered sidebar. Timeline lives here because it is another
+reading of the case, not a collection or examination stage.
+That sidebar stays closed by default, because the board already lists the same case
+and two lists side by side only ask which one is real.
Rules:
@@ -35,6 +44,579 @@ Rules:
- Artifact actions can open a tool, locate a place or add an item to a proof.
- Settings is app plumbing: behind the topbar gear, not on the rail.
+## Pasting into a case
+
+`Ctrl+V` files what the clipboard holds. It covers the two things that have no
+file to drop: a screenshot taken with the system tool, and an address copied out
+of a browser. An image wins over a link when the clipboard carries both, and the
+page it was copied from prefills the image's source.
+
+A dialog always opens first, with only the fields that surface asks for.
+
+| Surface | An image | A link |
+|---|---|---|
+| **Media** | Title, source URL | refused: a link here is a download |
+| **Files** | Title, folder, source URL | Title, folder, notes |
+| **Graph** | Title, source URL, drawn at the viewport centre | Title, notes, drawn there too |
+| **Board** | Title, source URL, opened | Title, notes, opened |
+
+A refusal is a screen, not a toast: it says what this surface takes and where the
+thing does go. Text is refused everywhere. So is an image over 25 MB, naming the
+limit. A paste into a field is left alone, and a frozen snapshot refuses to be
+written into.
+
+A pasted image is recorded as a paste rather than an upload, so a screenshot with
+no stated source never reads like a file chosen off a disk. The Media grid counts
+both under **Imports**. Pasting the same crop twice is one file.
+
+## Board
+
+The case as one table: a row per entity, whatever type it is. It is what makes the
+hand-made vocabulary reachable — a `person`, an `account` or a `claim` had no screen
+before it. One view, a table; the graph is a different question and comes as its own
+view. Following a relation to a type with no tool of its own lands here, on that
+row's Details.
+
+- **New entity** offers the types an analyst creates by hand and generates the form
+ from the registry. It is **one dialog shared with the graph**, so a claim is filed
+ with the same words and the same duplicate warning wherever the analyst is standing.
+ It opens on the type being filtered for, or the first of the chosen family. The primary field names the value being entered — **IP address**,
+ **Full name**, **Handle** — never a generic **Name**. An identifier the case
+ already holds is flagged with the existing row one click away: a warning, not a
+ block, since merging is not shipped. What it creates opens into its own Details.
+- **Add file** takes a document, scan, plan or image into the case, by the button or
+ by dropping it on the list. It runs the Media Library's import, so the file is
+ hashed, deduplicated, given a sidecar and a thumbnail, and filed as a `media`. One
+ file opens its Details; a batch reports what landed and what was already there.
+- **Search+** covers the label, type, folder, notes and declared text fields
+ (ONTOLOGY §2), in memory on a case that fits one page and server-side past it.
+ The first matching field is named under the row, so a vehicle found by its plate
+ never looks like an unexplained result. Board and Graph send the same terms to the
+ same case predicate.
+- **The question is a bar that never changes shape**: a search, one **+ Filter** menu,
+ and a removable chip per term. It replaces seven selects, four of which appeared and
+ disappeared as the others were set — so a live term looked exactly like a dead one,
+ and a control that vanished took its own way back with it. An axis that cannot be
+ asked yet stays in the menu **with its reason next to it**, because a control you can
+ see and cannot use teaches something and one that is not there teaches nothing.
+- **The menu opens on four Questions** — *To review · Nothing linked yet · Added this
+ week · Unfiled* — and picking one drops its terms in as ordinary chips. That is the
+ whole of the onboarding: the answer arrives, and the sentence that produced it is
+ sitting there to edit. They are code, not saved state, so nothing new has to reach
+ the backup.
+- **Nine axes, every value chosen from the case and counted**: a stored field and one
+ of its values (*kind = video*), one or several types, one or several families, a
+ folder with or without its subfolders or none at all, review state, a one-hop test
+ for touching a type, having no connection at all, when it was filed, and what filed
+ it. A count that would answer a *different* question is not shown: **Linked to a
+ place** is priced by how many rows touch a place, never by how many places the case
+ holds. A field with no value picked yet asks nothing, and a field the case holds too
+ many distinct values for is not offered — a menu of five thousand paths is not a way
+ to choose.
+- **The field menu is read on the click that opens it**, at any case size. Gated
+ behind picking a type first, `kind` — the field the importer writes, the vocabulary
+ declares nowhere, and an analyst most wants — was a filter nobody could find; gated
+ behind a size, the large cases lost the one filter that scales for them. The scan is
+ linear and small (50 000 entities in 0.3 s, 100 000 in 0.7 s), and what keeps the
+ menu readable is the bound on **values** above, never the number of rows.
+- **The count is the answer, against the whole case**: *23 of 1 204*. The denominator
+ never shrinks with the numerator, because a proportion is the information a count
+ carries.
+- **Draw these N** hands the question to the graph. The **filter** travels, never the
+ rows it matched: ids would be capped, would bloat the URL and would go stale on the
+ next save, where a question is something the case can be asked again — and both
+ surfaces resolve it through one predicate, so what the drawing holds is what the
+ table counted.
+- **Rows · Totals** is a view switch, the one Files and the Media Library already use,
+ sitting at the right of the count line. *Totals* renders the same question as a total
+ instead of a list: one row per subject the statements point at, summed over `count`
+ and split by condition, ranked. The chips do not move. It is **there from the first
+ day and dimmed until it can draw a real line** — never hidden, since a control you
+ can see and cannot use teaches something. A line is real when a statement carries a
+ **number** and points at **something**: *seen, not counted* is an answer rather than
+ a row, and a statement about nothing has no subject to sit under, so a total offered
+ over either opens on an empty answer that reads as a finding. An empty table and a
+ frozen snapshot dim it too. What **one** subject comes to is read where that subject is,
+ in its own Details; this reads several at once. **Nothing is totalled across
+ subjects**, because a statement may point at two and one number could not say which
+ it meant.
+- **The question is remembered per case**, in the browser rather than in the case: it
+ is how somebody was looking at their material this afternoon, not something a bundle
+ should carry to another machine.
+- **Views** name case-owned analyses, in two families. Board and Graph ask one question
+ of the catalog and share both their question and their list of views; the Timeline
+ reads time and shares with neither, so each menu offers only the readings the surface
+ under it can draw, and a name is claimed inside its own family. A live view saves the
+ Search+ question and the surface presentation, then recomputes against the current
+ case when opened. Every
+ later filter, sort, fold, hiding, expansion, camera move and graph drag autosaves;
+ the badge says **saving…**, **saved** or **save failed**.
+- **A snapshot freezes a reading, not a second case.** It keeps up to 2,000 captured
+ entities, their fields and provenance, the relations among them and bounded photo
+ previews. Its Search+ controls and every case write are disabled, and its own
+ **Snapshot details** panel reads only the captured copy. A Board snapshot stays in
+ Board and a Graph snapshot stays in Graph. Leaving it closes the captured panel.
+ Snapshots have no standalone import/export: duplicate and Trash stay inside the
+ case, while the complete case bundle is the one transmission boundary.
+- **A proposal is settled from its row**: confirm takes its suggested relations with
+ it, dismiss is the standard delete, recoverable from the trash.
+- **Sorting** is a click on any heading, reversed by a second. Two of them name a
+ column the store can order the **case** by — identity and created — so *newest first*
+ is the newest in the case rather than the newest of the hundred rows loaded. The
+ others sort what is loaded and say so beside the count while there are more. One
+ gesture either way: which of the two it is belongs to the column, not to a second
+ control the analyst has to find.
+- **Columns** are the four every entity has — identity, type, folder, created — plus
+ the chosen type's declared fields once a single type is picked. Read-only: editing
+ cells and CSV belong to the Case Sheet. A primary entity photo replaces the type
+ icon in the identity column; without one, the icon remains.
+- **A row is a control**: focusable, opened with Enter, and the review clicks inside
+ it never open it.
+
+**The vocabulary explains itself on hover.** A family, a type, a verb, a rating and a
+declared field each carry one clause from the registry that declares them, shown
+where the word appears. No screen writes its own wording.
+
+## Graph
+
+The second tab of the same workspace, and a different question from the Board rather
+than a second rendering of it: what sits at the centre of the case, what connects to
+what, and what nothing connects to. It opens on the **whole case**, because a case is
+a subject before it is a set of statements — a conflict followed over months has no
+single root to expand from. Expansion is the drill-down.
+
+- **Lenses** are the readings, and each one chooses both which verbs are drawn and
+ which nodes: **Everything · Subjects · Ground · Statements** read the case, and **My
+ work** reads the filing — what you wrote, what it was made from, and what it points
+ at. They are resolved from the verb registry and the type roles, never listed here,
+ so a relation or a type added to the engine joins its lens with no edit.
+ Narrowing the verbs never hides a subject: an entity with no edge *in this lens* is
+ an answer. What a lens takes out of the drawing is a whole **role** — a post, a note
+ and an Inspect session are the filing rather than the case, and My work is the one
+ click back to them. A node's degree follows the reading, so it never prices a click
+ that could bring nothing in, and a name typed into the search can be brought into
+ every reading except one that does not draw its type: that one says so instead.
+- **A source is an edge, and the edge says what it stands for.** A bookmark between a
+ statement and the account that posted it is drawn as one thicker line reading *cites 3
+ bookmarks · 1 account* rather than as three nodes: the path survives and becomes
+ legible, and the budget goes on the subjects. The edge is read in the panel and hands
+ its sources back with one click — nothing else can be done to it, because it is not a
+ row the case holds. **The sources need not be on screen for the path to be:** a
+ bookmark the budget cut is folded exactly like one it kept, or a statement resting on
+ nine sources and one account would draw as a lone dot with both of its ends visible
+ and nothing joining them — on precisely the cases too large to draw whole, which are
+ the ones that need it. One folded from a type this reading does not draw says where
+ it lives instead of offering sources it could only refuse.
+- **A step is an edge too.** A frame pulled out of a video and built into a proof is
+ drawn as *derived from 1 frame* on the line between the two, not as a node in the
+ middle — the act is what the edge is written with, and the picture stops spending a
+ slot per step. Steps in a row read as one line to the far end. A step that shows a
+ place, that a statement cites, or that the case calls the same picture as its source
+ stays a node: it carries something that line cannot say. So does a node made from
+ **two** sources, since collapsing it would say one of them came out of the other.
+ *My work* draws every step as it is, because what was made out of what is the
+ question that reading exists to answer.
+- **What came out of a node and was used by nothing is its count.** Twelve frames saved
+ off a video and not built on yet are twelve pictures of that video, so the video says
+ *12 frames made from it, used by nothing* instead of drawing them. It is a **statement,
+ not an offer**: the node goes on pricing those twelve among the connections the drawing
+ does not hold, and **Expand** brings them like any other. Two counters for one question
+ is what the split gave — the pill reading `+4` beside a menu offering *1 more
+ connection* for the same five nodes, a difference about the mechanism rather than about
+ the case. Narrow on purpose — one connection, and it has to be a derivation pointing at
+ its source. A node with a single *relation* stays where it is, because thin material is
+ what the case has yet to exploit rather than clutter, and a node joined to nothing
+ stays too.
+- **One finding on the ground is one arrow.** A proof concluding a coordinate states
+ the point of everything behind it, so the frame, the video, the proof and the capture
+ all point at the same dot and a reading of the ground draws nothing saying three of
+ them are one picture. They collapse onto the material the finding is about, and the
+ place says what it rests on: *1 source*, not four. A capture pulled at those very
+ coordinates is the reference the comparison was made against, so it folds in rather
+ than counting; one nobody made a proof from is the only thing saying anything about
+ that point, and it stays. Answering POV writes two different verbs over one material,
+ and they collapse together: the surviving line is **the case's own statement**, it can
+ still be confirmed or withdrawn, and the rest are named on it. A line standing for more
+ than itself is drawn heavier at every zoom and writes its count once the drawing is
+ close enough for the nodes to be cards, since three hundred sentences over a case hide
+ the shape the drawing is for. **A node still standing goes on counting what the arrow
+ took**, and opening it draws exactly those: unlike every other fold here, what this one
+ put away is named on a line that need not touch the node it was taken from, so pricing
+ that node down would leave it claiming connections it visibly has.
+- **`Ctrl+Z` takes back the last change to the drawing**, and `Ctrl+Shift+Z` puts it
+ again; both are offered as buttons too, since a canvas teaches no gesture. It reaches
+ everything that is presentation — expanding, hiding, folding, the lens, the ordering,
+ a node dragged — and **nothing that writes to the case**. That boundary is the point:
+ a single stack mixing *I hid a node* with *I deleted a statement* would rewrite the
+ case on the fourth press to get a view back, and an edge cannot be un-deleted anyway,
+ since re-filing one mints a new id, a new date and a new author. A relation filed by a
+ mis-drop is offered back where it is announced instead.
+- **Independence is read, not computed.** A statement's panel says what it rests on —
+ *3 sources · 1 account*, marked when every one of them traces back to the same
+ account — and the toolbar counts those statements. The count is **pressed to reach
+ them**: it lights those statements and one hop around them, which with the sources
+ folded into the edges is the finding itself. A number naming a set with no way to it
+ sends you opening statements one at a time. It concludes nothing: whether three
+ citations from one account is a problem is the analyst's to say, and a source with no
+ known publisher is left out of the claim rather than assumed.
+- **The legend is the control** for the budget, where the lens is the control for the
+ reading. On a real case one family dwarfs the rest, so leaving `collected` out is
+ what spends the budget on the actors, places and statements instead. A handful of
+ switches, no knowledge of the case needed to use them. The rows are the families the
+ *case* holds rather than the ones drawn, or one switched off would take its own
+ switch with it, and the last one on stays on; a family whose every member this
+ reading leaves out is not offered, since that row would switch nothing. Families
+ resolve to types on the way out, as the Board's family filter does, against the types
+ the case actually holds — a free-typed entity no family speaks for is never dropped
+ by a switch that does not claim to cover it.
+- **Keep** decides which nodes a case too large to draw holds on to — the most
+ connected, or the latest work — and the count says what was left out rather than
+ presenting a slice as the case. It appears only once a case has actually been cut,
+ because that is the only time it changes anything.
+- **Position means connectivity, and repeats.** A ring per family seeds the placement;
+ a relaxation then pulls linked nodes together and pushes the rest apart, so the
+ parts of the case that are about each other end up next to each other and the hubs
+ sit in the middle. What nothing connects to is parked in a captioned column instead
+ of drifting in the cloud. An expansion switches to one column per hop, since
+ distance from the root is then the question. **Nothing reads a clock or a random
+ number**: same case, same pixels, because a graph screenshot goes into a report
+ beside a satellite capture.
+- **A question worked out in the Board is drawn here.** *Draw these N* hands over the
+ filter, not the rows it matched, so the drawing answers what the table answered at
+ any size and goes on answering it as the case changes. It is written over the canvas
+ as the sentence it is, with one press back to the whole case — a picture that
+ silently answers somebody else's question looks broken. The legend still narrows on
+ top of it, and **narrows**: two filters sharing no type is a real answer, and an
+ empty one.
+- **Search+ is the same question here.** Text and every filter axis narrow the graph
+ request itself, including stored entity fields; the graph is not repainting an old
+ payload. A matched field is named in the node panel. Saved live views preserve this
+ question plus lens and presentation. Pins and camera belong to that named reading
+ and never rewrite the case-wide arrangement. Graph snapshots keep their captured
+ fields, relations, photo previews and presentation read-only on this surface.
+- **The drawing can be added to, not only read.** Right-click the empty space for
+ *New entity here* — filed through the same dialog the Board uses, drawn, and pinned
+ where the press landed; saying what it is to something else is the *Connect to…*
+ gesture that was already there. Dropping a file anywhere on the canvas runs the
+ Media Library's import and lands the media where it was dropped. Before this, an
+ analyst who realised the picture was missing an account had to leave for the Board,
+ create it, come back and search for it. The creation is **not** on the drawing's
+ undo stack — that stack never writes to the case — so `Ctrl+Z` takes the node out of
+ the picture and the toast's *Undo* is what takes the entity back, through the
+ standard recoverable delete.
+- **A node reaches its row**, as a row reaches its node: *In the Board* opens the same
+ entity in the table, and *In the graph* in any Details panel opens it here.
+- **Find a node** by name, ranked most-connected first. On a case drawn at a few
+ hundred nodes, hunting one by eye does not work, and a canvas cannot be reached
+ from the keyboard at all — so this is both the way in without a mouse and the only
+ practical way to a particular entity. Picking a result selects it and brings it
+ under the eye at the current zoom.
+- **Typing lights the drawing, and removes nothing from it.** From the first letter
+ every match is outlined and keeps its name at any zoom, an edge lights when both of
+ its ends match, and the rest of the case falls back to context. A filter would have
+ answered the same question by taking the rest away, and the shape of the case is
+ what the analyst is holding their place with. The count is over the drawing —
+ *no match drawn* is a different answer from *no such entity*, which is the list's
+ to give. Pressing on the case puts the list away without giving the search up, so
+ the nodes it just pointed at can be read; the field asks for it back. Escape gives
+ the whole search up.
+- **One question narrows the picture at a time.** A search, the statements on one
+ account and a selected node all dim what they are not about, and composited they are
+ not a third reading but an unreadable one. The most recently asked wins, so typing a
+ name outranks the node already clicked — which still rings itself and opens its
+ panel, since that is what a click is for. Pressing the count gives a typed name up
+ rather than answering with an unchanged picture, and Escape lets a narrowing go
+ before a handful that was gathered node by node.
+- **It searches the case, not the picture of it.** A view is bounded, so past the budget
+ most of the case is not on screen, and a search that read only the drawing answered
+ *no such entity* for entities the case plainly holds — nothing told "not in the case"
+ from "not in this picture". What the drawing does not hold is listed apart and offers
+ to **bring it in**, through the same `expand` that opens a node: it arrives with what
+ touches it, kept whatever the ranking and the narrowing would have done with it, and
+ it is selected and centred so an arrival off screen is not mistaken for nothing
+ happening. The search is asked of the catalog, the read the Board uses, and ignores
+ the narrowing on purpose — a name typed is a question about the case.
+- **Hover reads, selection commits.** Passing over a node lights it and its edges and
+ names them; a click is what narrows the picture. Selecting fades the far context
+ instead of hiding it, and the side panel reads the node's own connections in words,
+ using the registry's inverse wording for an incoming edge. The root of an expansion
+ never fades its own view: asking for three hops and getting two of them greyed
+ would contradict the question. **Expanding is priced on the node**: a degree is
+ shown before the click that spends it.
+- **The panel reads a node, it does not list its edges.** Connections are grouped by
+ what they say — the verb and its direction, since the registry words those apart —
+ under a heading that counts them, biggest group first, because what a node mostly
+ is, is the first thing to say about it. Past eight in one group the rest are asked
+ for rather than listed. Hovering a row singles its edge out on the canvas, verb
+ written on it, and the node's other edges step back: selecting already lit all of
+ them, so *which line is this row* had no answer otherwise. Clicking a row reads the
+ node at the other end, and the view moves only if that node is off screen — the
+ layout puts linked nodes next to each other, and recentring on every step makes the
+ drawing lurch under the reading.
+- **A node states the connections the picture does not hold.** The rows above are
+ built from the edges on screen, so a node with forty connections and three of them
+ drawn read as a node with three. The count underneath is the node's own, against the
+ connections the view holds rather than the ones it can draw — a loop is kept and
+ never drawn, and counting it as missing left a node asking for ever. In a whole-case
+ view, expanding it from there is the same act as the menu's; in a neighbourhood there
+ is nothing to press, because that read is grown by **Hops**, and the line says so.
+- **The focus says how far it reaches, and stays until it is let go.** A strip over
+ the drawing names the node in hand and offers **1, 2 or 3 hops** — on the keys as
+ well, beside the one that fits the case. One hop answers *what touches this*; two
+ answers *what does this sit between*, which is the account two people both cite
+ without either naming the other, invisible at one hop and drowned at the whole
+ case. The rings are walked over the **edges already drawn**, so a wider reach costs
+ no read and can claim no connection the picture cannot show. How far you are
+ looking is kept as you move from node to node — it is a stance, not a property of
+ what you clicked — and goes back to one hop when the focus is let go. Never offered
+ on the root of a neighbourhood, whose own **Hops** asks the case a different
+ question.
+- **Only this** takes the rest of the case off the screen rather than dimming it, and
+ frames what is left. Dimming is the default because the shape behind the reading is
+ what keeps your place, but a subset you mean to work on has to be readable alone. It
+ never touches the layout, so switching back puts every node exactly where it was and
+ the view with it. A name typed while it is on outranks it and the case comes back
+ with the matches lit: an edge needs both of its ends, so hiding everything outside
+ the matches would have answered a search with a scatter of unconnected dots. Escape
+ gives the case back one press before it gives the node up.
+- **A path is walked, not remembered.** *Walk by hand* arms the walk on the node in
+ hand, and from then on the drawing shows only where the path can go: every node it
+ may reach next is lit before the click, so an impossible step cannot be taken
+ rather than being taken and refused — the same bargain the connection gesture
+ makes. Clicking a lit node extends the path; clicking one already on it walks back
+ and drops what came after; the panel's rows do the same, which is how the walk is
+ reached without a mouse. Escape gives it up whole, as it drops a half-drawn
+ relation. Path edges are drawn as ribbons, told apart by **weight and solidity
+ rather than hue** — a graph that reaches a report is printed in grey, and the
+ families already own the palette.
+- **Or the case is asked for the way.** *Path to…* arms the question on a node and
+ waits for the other end: **click any node**, pick a name from the search, or take a
+ row from the panel — an armed gesture owns every way of pointing at a node, and the
+ search is not a convenience but the half a click cannot cover, since the view holds
+ a fraction of a real case and *are these two connected* is asked about things far
+ enough apart to be off screen. **Nothing is dimmed while it waits**, which is where
+ this parts company with *Connect to…*: a relation has a vocabulary that rules a
+ pair out before the press, a route has none — the case is searched, not the
+ drawing, so greying a node would be the picture asserting what only the server can
+ know. That means dropping the focus fade the armed node would otherwise still be
+ carrying, or the drawing says *only these five can be pressed* over a strip saying
+ click anything. *No route within four hops* is that answer, and it is a finding rather than a
+ silence. A route through nodes the budget cut brings them in first.
+- **Every equally short route is drawn, one is read.** The ties are the point: two
+ accounts reaching the same place through two different sources is what independence
+ looks like, and an answer that drew one of them would hide it. The drawing lights
+ them all — *how these are connected* — while the sentence takes them one at a time
+ with a `1 / 3` stepper, because a sentence cannot be read three times over. An
+ answered route is walked onward from and stepped back through like any other, which
+ makes it a place to keep working rather than a result.
+- **The path reads as a sentence**, node by node with the verb of each step between
+ them. An edge crossed against its own arrow takes the registry's inverse wording,
+ so the sentence always reads left to right: the first attempt wrote the plain verb
+ with a reversed arrow, and *A ← made from B ← made from C* has to be walked
+ backwards to be understood. Nothing is stored — a path is derived from edges that
+ can be deleted, so a saved one goes quietly false the day a link in its middle is
+ removed. What gets kept is the sentence, in a note, written by a person.
+- **Right-click a node** and it says what can be done with it, in words: expand the
+ connections it has off screen, collapse what hangs off it, hide it, connect it to
+ something, or read it in Details. A
+ canvas teaches no gesture on its own, so the acts are named rather than hidden in
+ one. The menu selects nothing — asking what a node can do is not choosing it.
+- **Expanding a node grows the picture instead of replacing it.** Its off-screen
+ connections join the case already drawn, marked as arrivals, and **nothing already
+ on screen moves**: everything drawn is a fixed point, so only the arrivals are
+ placed, seeded beside the neighbours that asked for them. That is a promise about
+ the picture before it is one about the clock — twenty nodes expanded into two thousand
+ cost twenty placements instead of two thousand, which is a fifth of a second where
+ it was six. A new *question* — a lens, a filter, a folder — re-places the case
+ outright, since that is a different reading rather than the same one grown. The view
+ does not refit either: losing your place is what following a thread used to cost.
+ The price, taken deliberately: the picture depends on the order things were expanded
+ in, exactly as it already depended on what was dragged. The count offered is what is
+ *missing*, not the degree — when every neighbour is already drawn the menu says so
+ instead of offering an act that would appear to do nothing. The panel's **Around
+ this** is the other act, and is worded apart because it does the opposite: it
+ replaces the case with one node and its hop columns, where **Expand** adds to the
+ case in place.
+- **Three acts on the drawing, three words: Expand, Collapse, Hide.** Expanding brings
+ in what a node has and the picture does not; collapsing puts away what hangs off it;
+ hiding takes it out. They are named that way in the node's menu, in its panel and in
+ the tooltip alike — the tool once said *Open*, *Fold back*, *Fold it back*, *Take it
+ out* and *Bring back* for what is really three things, and a second name for one act
+ leaves the analyst deciding whether it is a second act. One way back for all of them:
+ **Reset view** in the toolbar, offered only once the drawing has actually been
+ edited, draws the case the way it opened without touching the reading or the
+ arrangement. *Drawn as one edge* stays clear of all three: an attestation collapsed
+ into one line is a way of drawing an edge, not an act on the set.
+- **The switch is on the node, and states which act it is before it is pressed.** A
+ pill on the node under the eye reads `+3` or `−3`, double-clicking presses it, and
+ the tooltip spells out what it counts. It grows before it tidies, which is what makes
+ one switch learnable: a node holding collapsed nodes gives them back, a node with
+ neighbours off screen goes and gets them, a node with everything already around it
+ puts that away. **It is never offered where it would do nothing** — a node the case
+ has already expanded cannot be expanded again, so its switch falls through to the
+ fold, and the menu's greyed line says *Expanded, 3 did not fit* rather than greying
+ in silence. The same switch is in the panel in words, since a canvas cannot be
+ reached from the keyboard.
+- **Collapsing reaches the picture the case opened on, which no other act does.**
+ Expanding adds and hiding removes; neither speaks for the two hundred nodes that were
+ on screen before anything was touched, and those are the ones in the way. Collapsing
+ a node puts away **what only hung off it** — pull the node out of the drawing in your
+ head, and whatever falls off with it is what goes. A lone neighbour always goes; among
+ the pieces with a shape of their own the biggest stays, because a control that can
+ take the case away with it is a trapdoor; and a piece holding a node placed by hand
+ never goes. So **a fold never cuts a link between two nodes that both stay**: the
+ picture left behind says what it said before, with fewer dots. Nothing is asked of
+ the case and nothing is given up — the nodes are still in the payload, `N folded` in
+ the toolbar gives every one of them back at once, and a name typed into Find reaches
+ a collapsed node where it is instead of fetching it again. What it does not do is
+ make room: the case still sent those nodes, and **Hide** is the act that frees budget.
+- **The drawing is a set you own.** **Hide**, in the panel and in the node's menu,
+ leaves *any* node out of the picture, not only one you expanded. Nothing is
+ deleted: the case keeps the entity and every connection it has, and the wording keeps
+ clear of the edge panel's *Remove*, which does delete a statement. Three ways back at
+ three sizes: the neighbour it was hanging on gives that one node straight back,
+ **Undo** takes the last change off, and **Reset view** draws the case the way it
+ opened. The removal is applied last, so it survives an expansion that reaches the
+ same node.
+ **The node it was hanging on hands it straight back**: hiding is your own act on your
+ own picture, and undoing one node of it should not cost the whole drawing or the name
+ of a node you have just decided not to look at, so the neighbour counts it among the
+ connections the picture lacks and its switch gives it back. Naming the node again
+ outranks the removal too,
+ whether the name comes from Find, from a route or from a source handed back off an
+ edge. It is offered on the whole case only: a neighbourhood's root is the question
+ being asked, and that read takes no such list.
+- **A hidden node takes what only it was holding.** Hiding the node you had expanded
+ used to leave its neighbourhood behind with no edge to anything. What stays now is
+ what something standing on its own still reaches: a node the ranking drew, one you
+ named, or a second expansion that reached the same node, which is the convergence the
+ drawing exists to show. Reachability rather than a count of edges, because the
+ vocabulary ranks no edge above another and a pair holding only each other is as
+ adrift as a single dot. *Reset view* undoes the whole act, since the removal was one.
+- **Drawing a node is not drawing its neighbourhood.** The two were one act, so
+ anything named arrived with everything it touches: a four-node route came in behind
+ four neighbourhoods and the answer was buried in the crowd it brought. Now a route,
+ an entity picked out of Find and the sources handed back off a folded edge are drawn
+ as themselves, while **Expand** is what asks for the hop around them. A gathered
+ handful does both by the group — **Expand N** and **Hide N** are one read where five
+ clicks were five reads landing in five places.
+- **A comfort number to open on, and no ceiling after it.** A limit that refuses is
+ the app overruling the analyst about their own picture: drawing the case and asking
+ what touches one node shared one budget, the ranking spent it first, and the answer
+ asked for outright was the one refused — in silence, since the node was recorded as
+ expanded and the control that offered to expand it greyed itself. So the first draw
+ opens on **300 nodes**, the most connected, with the case's own total beside it —
+ *300 of 1 050* — and **everything after that is unbounded**: nothing named, expanded
+ or brought in is ever refused for room. An absolute count rather than a share of the
+ case, because a tenth of fifty entities is an empty picture and a tenth of ten
+ thousand is a freeze.
+- **The drawing says what it weighs, since nothing stops it growing.** The placement
+ compares every node against every other, sixty times over, on the main thread: five
+ hundred place in a quarter of a second, a thousand in one, two thousand in four with
+ the tab frozen throughout. So past a thousand the toolbar says *heavy drawing*, past
+ two thousand *very heavy*, each with what the next change will cost. It is a price,
+ not a wall — the acts that answer it are the analyst's own: hide what the picture is
+ not about, collapse what hangs off a hub, or switch a family off.
+- **Connecting is two clicks and a named verb.** "Connect to…" arms the gesture, a
+ dashed arrow follows the pointer, and only the endpoints the vocabulary accepts stay
+ lit — so an illegal pair cannot be drawn rather than being drawn and then refused.
+ The case can still be panned while it is armed, since the two nodes worth joining
+ are rarely near each other. Landing offers the readings that pair allows, each in
+ its own words and under the registry's own heading where it has one, so a pointer is
+ not read as a statement, and files the one chosen through the same route Details
+ uses. Nothing is said when it lands: the new edge appearing is the confirmation, and
+ the only case worded is a lens that does not draw that verb.
+- **An edge is a thing to read and to rule on.** Clicking one names it, says which way
+ it goes, who filed it, and offers *Confirm* on a proposal or *Remove* on any of
+ them. On a worked case the finding is more often on the edge than on either node —
+ so how sure of it, and what kind of tie it is, are set here too rather than a panel
+ away in Details. Each control appears because the **registry** declares it, not
+ because the edge holds a value: a ratable verb gets the rating, a verb that takes a
+ qualifier gets the word. A proposal gets neither, since reviewing a machine's claim
+ and grading it are two gestures and the API refuses the second first. Nothing may be
+ written to a line that stands for several, which is why a folded edge offers only its
+ sources back.
+- **Folder** draws one of the analyst's own buckets instead of the whole case, read the
+ way the Board reads it. It sits in the toolbar rather than behind a menu because it is
+ the closest thing the case has to *what I am working on*. The Board's other two
+ filters are deliberately absent: review state would draw the proposals alone, and a
+ proposal's far end is nearly always confirmed, so the closed link set drops every
+ edge and the picture becomes a column of dots — while the dash already says
+ *proposed* in place. An exact type fails the same way, the verbs running between
+ families; the two that stay inside one are reached by leaving one family on.
+- **Every edge says which way it goes and in what words.** The vocabulary is directed,
+ so each edge carries a head, and the verb is written along the edges of whatever is
+ under the eye. Seven strokes — lineage, stated relation, ruled out, contradiction,
+ mention, folded sources, proposal — and the legend names the ones on screen, since an
+ unexplained dash pattern is decoration.
+- **One rating is on the line, and only one.** A relation checked and eliminated is
+ drawn apart: "it is not this bridge" is half the work of a geolocation, and eleven
+ candidates ruled out drawn like live statements make a picture of the case count
+ eleven open hypotheses. The other three levels get no stroke — a verdict is not a
+ nuance, *probable* against *possible* is read one edge at a time in the panel, and
+ four more patterns would put *what kind of edge is this* and *how sure of it* on one
+ channel. Nothing is hidden either: the elimination is the finding, so it stays drawn.
+- **Nodes declutter by zoom.** Wide, they are dots; the few busiest keep their name,
+ because what sits at the centre of the case is the question. Close enough for one
+ to fit, each becomes a **mini card**: family stripe, then a picture column as tall
+ as the card holding the preview the case already holds (or the entity's glyph,
+ centred in that same column), then title, type and degree. A preview fills the
+ column from the middle of the thumbnail rather than being fitted inside it, since
+ a wide capture fitted into a small box read as a hole in the card; the whole
+ thumbnail is in the tooltip.
+- **The card is sized off the screen, not the canvas** — in canvas units it would
+ cover its neighbours at every zoom. It still grows with the zoom, by the square
+ root of it and up to 1.7×: pinned to one exact size, zooming in bought distance
+ between the cards and nothing inside them. The gaps widen faster than the card
+ does, so cards that had room keep it.
+- **A node says when the case made it.** A frame, an adjustment, a collage: filed as
+ ordinary media and drawn with the same glyph as a photograph somebody handed over.
+ The card names the act instead of the kind — *Frame*, *Collage* — and the panel adds
+ one line saying it was made out of material the case already holds. Only the tools
+ that compose case material mark their output: an upload carries nothing, since
+ "upload" on an upload says nothing about it.
+- **Previews are the cached thumbnails** the Media Library uses, loaded only for the
+ cards actually on screen and only once each. The graph never generates one: a read
+ that draws does no CPU work, so an entity whose picture was never cached shows its
+ glyph.
+- **Unconnected** counts what nothing in this lens reaches — the case's unexploited
+ material, and the one figure a table has no column for. Counted across the **case**
+ like the total beside it, never over what was drawn: a node with no edge sorts last,
+ so a cut discards it first, and read off the drawing the figure would report zero on
+ exactly the cases large enough to need it.
+- **A node can be put somewhere, and it stays.** Dragging one — as a dot or as a card,
+ identically — pins it: the case records the spot, and the layout then treats it as a
+ fixed point that still pushes and pulls while nothing moves it. Everything else
+ settles around the pins, so a node that arrives later joins the arrangement instead
+ of restarting it, and new arrivals are drawn towards where the work actually is
+ rather than back to the centre. The arrows move the selected node too, since a canvas
+ has no other keyboard path in. A pinned node carries a pushpin, because a node that
+ ignores the layout has to say why. A node held where the drawing already had it
+ carries no pushpin: nobody chose that spot, so there is nothing to let go of. Moves
+ are **saved as they are made** — asking for a keystroke after every drag would put
+ friction on the one gesture this is for — so the way back is a control, not an undo:
+ *Let it go* in the panel for one node, which places that one against a case that
+ stays where it is, and **Reset N pins** in the toolbar, which drops the whole
+ arrangement and lays the case out again. That count is every pin the lens
+ holds, so the way back is offered even when the pinned nodes were cut from the view.
+ **Ctrl-click gathers a handful** — the nodes ringed in amber move together when any
+ one of them is dragged, and Escape lets them go. Moving is not all a handful is for:
+ it is also expanded and hidden by the group. That is a separate act from
+ selection, which stays single because the fade is computed from it and "one hop from
+ the selected node" has to have one answer. **Each lens keeps its own arrangement**,
+ because a lens is a reading: it draws its own nodes and its own edges, so it clusters
+ differently, and one shared arrangement would anchor every reading into the shape of
+ whichever one it was built in. Offered on the whole case only: a neighbourhood gives
+ its horizontal axis to distance from the root, and a node moved off its column would
+ contradict what that view is drawn to show.
+- Drag anywhere to pan, scroll to zoom at the pointer, `+` / `-` / `0` from the
+ keyboard, and the level is on screen. Colour says only which family a node belongs
+ to; the meaning of an edge is on its stroke, so the picture survives being printed.
+ Selection keeps the amber.
+- **Full screen** gives the drawing every row the browser chrome was holding, which is
+ what a case of a few hundred nodes is read at. The toolbar comes with it, so the
+ picture can still be steered, and Esc gives the window back. As in the Timeline.
+
## Case sidebar
The sidebar has three zones: a fixed header, one scrolling body, and a details
@@ -68,13 +650,34 @@ remembered per workspace for the current session. Reloading restores the default
tiles, multi-select and context actions. It also exposes Trash with the same
restore, permanent-delete and empty actions as the sidebar. Delete sends the
current selection through the standard confirmation.
-- **Details** — a drawer over the sidebar, closed with the back arrow or Escape,
- so selecting a row never pushes the case out of view. It edits an artifact's
- preview, title, notes, provenance, derivation chain and folder, and provides
- open, locate and delete actions. The sidebar and Media Library modal share
- `EntityDetails.svelte`. Image Details include a closed EXIF section with the
- parsed capture date, GPS and every readable tag. Video Details use the same
- pattern for local ffprobe container, stream and tag fields.
+- **Details** — a drawer over the sidebar, closed with the back arrow or Escape, so
+ selecting a row never pushes the case out of view. Every entity uses the same three
+ tabs. **Info** holds identity, declared profile fields, file metadata, notes and
+ folder. **Connections** holds placement, relations, mentions, Claims and the
+ collapsed **Made from & used by** block. **Time** holds dated statements, intrinsic
+ media dates and a collapsed Case activity section. A field declared as holding
+ sentences is a box that grows, not a line. A
+ suggested entity says so at the top and carries the click that confirms it.
+ People, organizations, assets and equipment types add a photo gallery above the
+ form. It accepts several images from the computer or the Media Library, keeps the
+ main preview to a normal panel height, and lets one image become primary. A
+ computer import stays private to the entity and never enters the Media Library;
+ choosing from Media only stores a reference. Removing a private photo deletes its
+ dedicated copy, while removing a Media choice leaves the media in the case. With
+ no photo, only the two add actions remain and other surfaces keep the entity icon.
+ The same two actions appear while creating a supported entity. Photos are staged
+ in the form, where one can be chosen as primary, then attached after creation.
+ Save commits the entity fields; each connection has its own Add action. Because the
+ two commit differently, closing the panel or following a connection asks first when
+ Save has not taken what is on screen.
+ A file the app has no viewer for — a document, a scan, a spreadsheet — offers
+ **Show in folder** rather than a download link and no tool button: handing it to
+ the browser makes a second copy in Downloads, and the analyst ends up working on a
+ file the case does not know about. Following one from anywhere else does the same.
+ The sidebar and Media Library modal share `EntityDetails.svelte`. Image Details
+ include a closed EXIF section with the parsed capture date, GPS and every readable
+ tag; Video Details use the same pattern for ffprobe container, stream and tag
+ fields.
- **Delete** — deleting an artifact moves its registered files and cascade into
Trash and shows an **Undo** toast. The confirmation uses the neutral tone and
states what can be restored. Red is reserved for deleting a case, purging a
@@ -113,7 +716,8 @@ reads **Rename to use** and does nothing until it is renamed.
damage is listed one item at a time with only the repairs that apply. Database
rebuild states what cannot be recovered before the button. Removing a missing
media record takes a second click, while relinking only accepts an unregistered
-file already placed in that case's `media/` folder.
+file already placed in that case's `media/` folder. A stale Timeline index can be
+rebuilt from Claims and media metadata.
## Workspace folder
@@ -148,22 +752,228 @@ signature. It leaves absolute export paths, the workspace pointer and download
sessions on the machine that created them, and the UI tells the analyst to keep
the downloaded backup private.
-## Relations
+## Connections
+
+Details keeps four concepts visually separate: **Relations**, **Mentions**,
+**Claims**, and the collapsed lineage block. The lineage block is labelled **Made
+from**, **Depends on** or **Used by** from the direction and link type; it is not a
+generic History list.
+
+Ordinary relations render through one component wherever they appear. Two lines carry
+the neighbour's name, then what the edge states and how sure of it. A suggested row
+can be confirmed; any row can be removed. Where a pair supports several verbs or both
+directions, the reading is selectable. An older out-of-matrix row stays visible and
+removable but cannot be restated. Past six rows the list hides the rest behind one
+click, suggestions first. The registry's headings only appear where a list runs
+several actions together.
+
+**How sure, and how reliable, are two controls that never merge.** The rating sits
+beside the verb, offering the levels the API serves plus *Not assessed* to clear it.
+Unrated is the normal state, so it stays colourless until it holds a level, and a
+ruled-out row is dimmed and kept rather than struck out. The source's Admiralty grade
+sits on the line above, with the name it belongs to, stated rather than offered: it is
+edited in that source's own panel. An ungraded source shows nothing.
+
+**Add relation** searches only relation targets, **Add mention** the mention action.
+Hovering either button lists the accepted target types; media-specific rules use the
+current file kind. A filed relation cannot be reworded into a mention, and a mention
+has no verb menu or rating. A Claim has its own **About**, **At** and **Cites**
+editor; its confidence is edited with the Claim fields, and those three connectors
+carry no rating of their own.
+
+**Sources and Supports are two headings, Contradictions is one.** A statement may cite
+another statement, and resting on is not symmetric — so *Sources* lists what this one
+rests on and takes the **Add source**, while *Supports* lists the statements resting on
+this one and takes nothing: that reasoning is written where it is being made. *Supports*
+appears only once it holds something. A contradiction keeps one heading whichever end
+filed it, since it reads the same from both.
+
+**The Claims group adds up before it lists.** An entity several statements are *about*
+shows what they come to — `5 destroyed · 1 damaged` — above the statements themselves,
+with the same three rules the Board's total obeys: a ruled-out statement is counted
+apart and never inside the sum, an absent count reads as *without a number*, and the
+confidence spread is stated rather than folded in. Read over the whole case, since it
+is a fact about the row rather than about anyone's filter. A place reached by `at` or a
+source reached by `cites` is listed without being counted: neither says how many of
+anything.
-Relations (ONTOLOGY §3) render through one component wherever they appear — the
-Details panel, the point's card on the map, and the case board next. One row per
-relation: the neighbour, how the edge reads in words, and, while it is only
-suggested, confirm. Any row can be taken back, whatever its status. Where the pair
-reads more than one way the verb is a select, so a wrong reading is corrected in
-place instead of deleted and restated. A neighbour that carries a point offers the
-map, because confirming "shot here" without seeing where is signing blind. Past six
-rows the list hides the rest behind one click, suggestions first.
+**A Claim's fields use three sections**: statement, time and reasoning. The Time
+section uses a guided editor for a year, month, day, date and time, bounded date
+range or zoned time range. Precision, certainty and timezone are chosen separately, so the analyst does
+not need to remember suffixes or timestamp punctuation. **Advanced** preserves and
+accepts the announced raw syntax. It opens a complete reference beside the field:
+patterns and examples for reduced dates, local/UTC/offset timestamps, subseconds,
+date and time ranges and uncertainty markers, followed by the unsupported forms. Its role
+says whether the fact occurred, was observed or was valid then. The count steps by
+one and starts at one; leaving it empty says *seen, not counted*, which is not the
+same answer as one. An asset carries its own **Condition** off the same scale, where
+it reads as the last known state rather than as one observation.
-Stating one is a second component: pick the other entity from a bounded search of
-the types the vocabulary accepts, then the reading if the pair allows more than
-one. Details files it with Save; Satellite's Save-place dialog files it once the
-place exists. Both dialogs show the existing relations above the picker, so
-nowhere can a relation be added but not removed.
+The Time tab and Timeline use one backend contract:
+window intersection, category and entity filters, opaque pagination, optional
+year/month/day density buckets, a complete extent, and separate Undated and unplaced
+counts. Unplaced means a value exists but cannot sit on the UTC axis yet.
+Creating or editing a Temporal Claim writes its fields and selected
+`about`/`at`/`cites` connector sets in one transaction. Deletion uses the normal
+recoverable Trash workflow.
+
+## Timeline
+
+Timeline is the third Case tab. Its main axis is horizontal and stores its window in
+UTC. One searchable picker decides what the labels read: UTC, this computer's zone, any
+zone in the world, or local time at a place the case has saved. A zone is named rather
+than offered as an offset, so a stated hour survives the two days a year the offset
+moves, and each row shows the offset in force **at the window** rather than today's.
+The list is the platform's own copy of the IANA database, so it matches the renames
+either way: typing `kyiv` finds a list that says `Europe/Kiev`, and `kolkata` finds
+`Asia/Calcutta`.
+Above a day the ticks step by that zone's calendar, so a day tick is its own midnight;
+below it they keep exact spacing, so an hour a zone skips reads 01:00 then 03:00.
+A saved place is the one reading that also draws **daylight** under the ruler, because a
+band of day and night needs coordinates and a zone name carries none: night is the
+strip, civil twilight and day are laid over it, and instants stay UTC underneath
+whatever clock labels them. It is read from `/api/geo/daylight`, which is pure local computation and
+answers a window wider than a month as cut rather than drawing stripes a few pixels
+wide.
+Category tracks stack vertically. An instant is a point and an explicit interval is a bar.
+A reduced date stays a point, with a thin bounded line showing the whole year, month
+or day its precision covers. Approximate dates use a dashed edge and uncertain dates
+use a pattern. Suggested status uses a corner mark; refuted confidence strikes the
+label. The legend separates date quality from assessment confidence because the two
+are independent.
+
+The toolbar states the window in words, on the axis's own clock, between two step
+arrows: pressing it opens the exact boundaries, the spans `Hour` to `Year`, and `All`
+for the complete filtered extent. A span is asked for by name rather than reached by
+repeated zoom steps, and the reading is what stays out because a window is checked far
+more often than it is typed. Dragging the ruler pans directly. The wheel zooms around
+the pointer; Shift-wheel and a horizontal trackpad gesture pan. Arrow keys, Page Up/Down, `+`, `-` and Home provide
+the same navigation without a pointer. Full screen keeps the whole workspace available
+for dense cases.
+Only the visible window is read, 200 items at a time. A separate density request keeps
+the full chronology visible underneath without loading every event. The minimap is a
+histogram: one column per bin, as wide as the bin, stacked by category, with exact
+counts on hover. Bins are cut as fine as they can be drawn — by the hour on a case
+spanning a day, by the day on one spanning months — because a case cut by the period it
+happens to span drew one mark for a scraped batch of two hundred in a week and the same
+mark for a single entry that could be anywhere in a month. Column heights go by the
+square root of the share, so that batch does not flatten everything beside it.
+
+The visible window is a movable, resizable brush, and what it leaves out is dimmed.
+Bars, date scale and brush are placed on one mapping from instant to position, which is
+the only way the three can agree: what the brush covers is what the axis is showing.
+Under it, one slot per calendar period, named in the middle of its own — a period is
+named under its own column rather than at the instant it opens, and only as many names
+as fit are printed. The columns answer the pointer and the space around them drags the
+brush, so a bar under the brush is still clickable; clicking one opens the axis onto
+what that bin holds. `Case activity` is off by default. `Undated`
+contains missing dates; a separate `Not on UTC axis` list keeps local timestamps and
+invalid legacy values visible without inventing a timezone. The date a fact entered
+Azimut never masquerades as the date of the fact.
+
+Overview stays above Plot or List, so expanding a dense track never pushes the global
+navigator below the chronology. Events are packed against their rendered labels.
+Overflow becomes a `+N` control that expands the track in place; **Collapse** in that
+track's left label restores the bounded view and its `+N`. Plot and List are
+two readings of the same loaded page.
+
+The Timeline opens with **Events** and **Media** tracks. **Track** adds editable
+presets for Events, Person, Place, Media, Sources and Case activity, using labels from
+the entity registry. **Custom** opens the shared Search+ builder, then states whether
+that question matches the entry itself, its subject, place, evidence, or any of those
+connections. Category and time-role filters remain separate from that question.
+
+Each track shows its name over two lines before the ellipsis, and hovering it names the
+categories and the Search+ question the lane was filled from. A track can be given a
+**colour**: left on **Auto** its entries keep the category colours the legend explains,
+and a chosen colour wins for that track alone. Each track has one reorder grip and a
+fold control. Dragging the grip changes its
+position; `Alt` with an arrow key provides the same action. The track menu can rename,
+duplicate or delete it. Selecting an entry exposes **Pin in track** and **Hide from
+track** in the inspector. Pinning keeps an entry out of density overflow, while hiding
+affects only that track and leaves **Show hidden** beside its name. Both are acts on a
+lane, so neither is offered for an entry with no place on the axis: `Undated` and
+`Not on UTC axis` list what the loaded page holds whatever the tracks hide, because an
+entry is in them for what it is rather than for where it is drawn. Grouping by subject,
+type, place, evidence or time role creates temporary subtracks. The same temporal row
+may appear in several tracks or groups without becoming a second Claim.
+
+**Views** uses the same case-owned contract as Board and Graph, on its own list: a
+Timeline reading is tracks, a window and a clock, none of which a Board can draw. A Live
+Timeline view
+autosaves its window, display timezone, display mode, categories, ordered tracks with
+their colours, folds, hidden and pinned entries, grouping and entity scope. A Snapshot
+stores up to 5,000 matching
+temporal rows with their exact track assignments and opens read-only. It does not query
+the current case when reopened. Timeline views can be duplicated, deleted through
+Trash, restored and carried in a complete case bundle.
+
+A track that includes Statements can create Claims; Media-only and Case activity
+tracks cannot. Clicking empty space creates a point; dragging creates a bounded range.
+At day scale and below these are zoned timestamps and time ranges, so hours can be
+created, moved and resized directly. Date-only Claims support the same confirmed move,
+and intervals expose both resize edges. Every direct write shows the old and new
+values before saving.
+
+Selecting an entry opens a fixed-width inspector without changing the axis geometry.
+It shows the readable and raw date, precision, timezone, authority, role, status,
+confidence, reasoning and named subjects, places and evidence. Statements can be
+edited there. **Right-clicking an entry** — on the axis, in the list or in either
+holding queue — names the same four acts where the pointer is: pin, hide, Details and
+Edit assessment. It changes no selection, so a pair being measured survives it, and the
+two lane acts follow the inspector's rule of appearing only for an entry that has a
+lane. A media date offers **Add correction**, prefilled from the intrinsic
+date; saving creates a sourced Claim about the media and does not rewrite its sidecar.
+The Details view keeps Claim time fields in **Time**, not **Info**. `Open in Timeline`
+applies a visible entity chip that can be cleared in one click.
+
+**Ctrl-click a second entry** and the inspector measures between the two. Two exact
+timestamps give one figure; anything coarser gives the range the bounds allow, with the
+difference as written underneath it — a stated day is a window a day wide, so two dated
+statements are a range apart and not a number. Windows that intersect report their
+overlap and refuse to order the pair. A period says how long it runs, a point says only
+how coarsely it is dated, and the two are never printed as the same thing. Ctrl-clicking
+the held entry again lets it go; selecting another entry outright drops the pair.
+
+A Claim owns one `when` value, which may be a point or interval. Its Time tab says
+**Set statement date** when that value is absent instead of presenting the Claim as
+an existing undated assessment. A second temporal reading is a separate Claim about
+the same subject, with its own confidence and evidence; Claims do not point `about`
+other Claims.
+
+### One period, four surfaces
+
+**Open in** ends the track row, not the boundaries menu: a window is set rarely and
+asked of the other surfaces often, so the three targets stay one click away while the
+header keeps the window alone in its middle column. Board and Graph receive it
+as a **fact-time** filter and say so in a bar above the answer, with the way back to
+Timeline and Map and a Clear. That filter is the question, so it narrows the page, the
+totals and a saved view alike, and it never touches `since`/`until`, which ask when a
+row was *filed*. A row is in the window when a temporal entry it owns is, or when a
+statement `about`, `at` or `cites` it is — a person belongs to June because something
+said about them happened in June.
+
+The Map layer is session-only and named as such. It draws whatever the window holds
+that the case has put on the ground, grouped per place, and says how much of the window
+could be placed at all. Placed means every relation that puts something somewhere —
+a statement `at` a place, a photograph `located-at` one, an image `depicts`ing one, a
+structure `sited-at` one — not `at` alone, which is a Claim's connector and left a case
+full of located photographs answering with an empty map. It reads the categories the
+Timeline was reading. It draws the window and nothing else: the case's saved pins are
+its whole index and answer no period, so they are switched off on the way in and stay
+on their own control, and the view is framed on the window's marks alone. A window
+holding nothing placed says so in words rather than pulling the map out over unrelated
+ground.
+
+The marks are the saved layer's own pins in a second tint, because they are the same
+gesture on the same map. A mark's card leads with what each row is — a photograph shows
+itself — and offers both ways on: the entry on the axis it came from, and the thing
+itself in the tool that owns it, with a file the browser can show also opening in its
+own tab. The card's own buttons hand the period to Board or Graph, or close the layer.
+
+Sent back, the window and the chosen entry both land: when the reading is already the
+one being handed over, the entry is taken from what is on screen rather than waiting
+for a reload that will never come.
## Sources
@@ -174,11 +984,24 @@ current version. A **GPS** toggle beside the type and folder filters narrows the
list to the files whose own metadata states a position, and appears only in a case
that holds some; how many is in its tooltip, not in its label. Those rows carry
one pin glyph — coordinates in the tooltip, not in the title — and clicking it
-flies the map there. Thumbnail polling follows all pending case jobs, including
+flies the map there. **Show N working files** sits on the same independent axis: a
+switch rather than another chip, because the chips answer *show me only X* and are
+single-select where this one is *put X back*. The library opens on what the case
+collected, the frames and collages it made itself held back, and the switch says how
+many those are rather than leaving them unannounced; the counts and the paging are
+computed with it so the facets never disagree with the list, and toggling it refetches
+because the loaded page is already the collected subset. It reads how the file
+**entered the case**, which is not everything true about it: one imported and later
+found identical to an extracted frame stays on the side it came in by. A case holding
+nothing but working files says so instead of offering to import. Thumbnail polling follows all pending case jobs, including
files beyond the loaded page after a case import. Thumbnail failures are scoped
to their case, so switching cases always reloads previews even when relative
paths match. Enrich respects an existing confirmed GPS relation during backfill.
+The row action for an image, a video or an audio file opens it; for anything the
+app cannot display it opens the folder the file sits in, so the original is opened
+in whatever program owns it rather than copied into Downloads.
+
Every media row and card shows the file's human-readable stem, without its
extension and without a second title line. Editing that name in Details renames
the file; the backend returns the portable stem after replacing forbidden
@@ -214,6 +1037,21 @@ spelling. Proofs and posts keep the native name only.
Saving a place or a capture resolves its country as part of the save, so the item
appears already grouped. Offline it lands under Unlocated for a later Locate.
+Saving a proof turns the coordinates it carries into a place, which is where a
+geolocation stops being text in a spec and joins the map (ONTOLOGY §3). The
+composer's **POV** box beside the coordinates says what the point is: ticked, the
+footage was recorded there; left alone, the footage shows it. Nothing in a
+composition can answer that, which is why it is asked rather than guessed. A capture
+files nothing: ten are taken while hunting one roof, and the point is worth
+minting once, where somebody commits to it. Settings → General → Proofs saves it
+outright or has the composer ask; a point the case already holds is neither
+filed twice nor asked about.
+
+A row the enrichment proposed from a file's GPS carries a `suggested` chip and an
+**accept** action, on the row and in the search modal, so the point is settled
+where the map that decides it is already open. The sidebar's Suggestions list
+keeps working, and both send the same click.
+
A globe/folder switch beside the filter regroups the same set by My-work folder:
the case's whole folder tree, empty folders included, with unfiled items under
**Unfiled**. The filter and the kind switch keep working, counts cover the whole
@@ -271,7 +1109,9 @@ A proof is composed of panels: case images, each carrying its source. Two things
in the composer are not panels.
**Overlays.** Ctrl+V, a drop on the canvas, or `+ Add overlay` put an image
-straight into the proof. It lands in the `Overlays` section of the side column,
+straight into the proof. Ctrl+V answers to two clipboards, and the rule is which
+copy came last: an annotation copied here wins, until leaving the window and
+coming back hands the chord back to the system clipboard. It lands in the `Overlays` section of the side column,
sits above the panels and the legend, and is moved,
resized from its corners and framed like anything else on the canvas — you can
annotate it too. It claims no source: no media is filed, no entity, no
@@ -323,6 +1163,11 @@ instrument style of QGIS, Google Earth Pro, Resolve and Lightroom.
`.dark-surface`. New chrome must use tokens; hardcoded light colours are limited
to text on dark image scrims.
- **Shape**: radii 3/4/6px, flat panels with 1px borders, rectangular badges.
+- **Update dot**: `.update-dot` on a `.dotted` host says "something here is to
+ install or update", and nothing else. It repeats down one path — the topbar
+ gear, the Settings tab holding it, then the button that acts on it — so
+ following it always ends somewhere it can be cleared. No counts, no other
+ colours.
- **Motion**: none. Color-only transitions ≤0.15s; no entrance animations,
no hover lifts. Transient functional feedback (locate-flash) is the one
exception.
diff --git a/extension/manifest.json b/extension/manifest.json
index 7574e07..31bd11f 100644
--- a/extension/manifest.json
+++ b/extension/manifest.json
@@ -1,7 +1,7 @@
{
"manifest_version": 3,
"name": "Azimut Capture",
- "version": "0.2.7",
+ "version": "0.2.5",
"description": "File into Azimut: screenshot the map you are looking at (coordinates from the URL), or save any other page as a bookmark.",
"permissions": ["activeTab", "scripting", "storage", "notifications"],
"host_permissions": ["http://127.0.0.1/*", "http://localhost/*"],
diff --git a/frontend/e2e/app.fixture.js b/frontend/e2e/app.fixture.js
index 5e5109b..234184b 100644
--- a/frontend/e2e/app.fixture.js
+++ b/frontend/e2e/app.fixture.js
@@ -62,7 +62,7 @@ const settings = {
ingest_token: '',
version: '0.2.7',
workspace_root: '/tmp/azimut-browser-fixture',
- extension_version: '0.2.7',
+ extension_version: '0.2.5', // tracks the extension, so it lags the app version
update_check_on_start: false,
update_dismissed_version: '',
usage: {},
@@ -90,11 +90,407 @@ const workspaceStatus = {
};
const workspaceFolders = [];
-// The relation vocabulary as engine/links.py serves it (ONTOLOGY §3).
-const relationTypes = [
- { type: 'located-at', label: 'was shot at', from_types: ['capture', 'media'], to_types: ['place'], manual: true },
- { type: 'depicts', label: 'shows', from_types: ['capture', 'media'], to_types: ['place'], manual: true },
- { type: 'same-image-as', label: 'is the same picture as', from_types: ['media'], to_types: ['media'], manual: false },
+// The graph readings, as `engine/graph.py` resolves them from the two registries: a
+// set of verbs from the relation types, and a set of node roles from the entity types.
+// Held here as data because a browser spec must not depend on the backend running,
+// and kept in step with those registries for the same reason the relation slice is:
+// a stale lens would let a spec prove the opposite of the shipped contract.
+//
+// What every reading of the *case* leaves out: the analyst's own output, which is the
+// filing rather than the case. `My work` is the one lens that draws it.
+const GRAPH_FILED = ['inspect-session', 'note', 'post'];
+
+export const graphLenses = {
+ lenses: [
+ { id: 'all', label: 'Everything', hint: 'every connection between the things the case is about', types: ['derived-from', 'depends-on', 'located-at', 'depicts', 'owns', 'part-of', 'member-of', 'posted', 'appears-in', 'sited-at', 'instance-of', 'in-network', 'same-image-as', 'mentions', 'about', 'at', 'cites'], hides: GRAPH_FILED },
+ { id: 'subjects', label: 'Subjects', hint: 'who owns, belongs to, posted or appears in what', types: ['owns', 'part-of', 'member-of', 'posted', 'appears-in', 'instance-of', 'in-network', 'same-image-as'], hides: GRAPH_FILED },
+ { id: 'ground', label: 'Ground', hint: 'what is tied to a place on the map', types: ['located-at', 'depicts', 'sited-at'], hides: GRAPH_FILED },
+ { id: 'claims', label: 'Statements', hint: 'what is asserted, and what it rests on', types: ['about', 'at', 'cites'], hides: GRAPH_FILED },
+ { id: 'work', label: 'My work', hint: 'what you wrote, what it was made from, and what it points at', types: ['derived-from', 'depends-on', 'mentions'], hides: [] },
+ ],
+ orders: [
+ { value: 'degree', label: 'Most connected', hint: 'keeps the hubs, so a cut view still shows the shape' },
+ { value: 'recent', label: 'Latest work', hint: 'keeps what entered the case last' },
+ ],
+ max_hops: 3,
+};
+
+/** Where a graph node's preview is served from, as `media_thumbs` reports it. */
+export const GRAPH_THUMB = 'media/.thumbs/harbour.svg';
+
+/** The default drawn case: one hub, its members, a place and something unconnected. */
+const graphNodes = [
+ { id: 'org-1', type: 'organization', label: '3rd Battalion', family: 'actor', status: 'confirmed', at: '2026-08-01T09:00:00Z', degree: 3 },
+ // The one node with a picture: a card shows a preview, everything else a glyph.
+ // `kind` is what the bytes are, which the payload carries for media alone: one
+ // type covers image, video and audio, so the node has to say which it holds.
+ { id: 'med-1', type: 'media', label: 'harbour frame', family: 'collected', status: 'confirmed', at: '2026-08-01T09:30:00Z', degree: 1, kind: 'image', thumb: GRAPH_THUMB, folder: 'harbour' },
+ { id: 'per-1', type: 'person', label: 'Section chief', family: 'actor', status: 'confirmed', at: '2026-08-01T10:00:00Z', degree: 1 },
+ { id: 'veh-1', type: 'vehicle', label: 'BTR-82A 4721', family: 'asset', status: 'confirmed', at: '2026-08-01T11:00:00Z', degree: 1, attrs: { plate: 'AX-904-ZT' } },
+ { id: 'acc-1', type: 'account', label: '@harbourwatch', family: 'identifier', status: 'suggested', at: '2026-08-02T08:00:00Z', degree: 1 },
+ { id: 'plc-1', type: 'place', label: 'checkpoint north', family: 'place', status: 'confirmed', at: '2026-08-02T09:00:00Z', degree: 0 },
+ { id: 'dom-1', type: 'domain', label: 'nothing.test', family: 'identifier', status: 'confirmed', at: '2026-08-02T10:00:00Z', degree: 0 },
+];
+
+/**
+ * The seed edges. Copied per fixture rather than read directly, because a link
+ * written from a surface has to be there on the next read: a graph that answered
+ * without the edge just filed would make a spec prove the opposite of the shipped
+ * behaviour, since the tool says nothing when the edge appears and speaks up when it
+ * does not.
+ */
+const graphLinks = [
+ { id: 'l-1', from: 'per-1', to: 'org-1', type: 'member-of', provenance: { by: 'user', at: '2026-08-02T09:00:00Z', status: 'confirmed' } },
+ { id: 'l-4', from: 'acc-1', to: 'med-1', type: 'posted', provenance: { by: 'user', at: '2026-08-02T09:20:00Z', status: 'confirmed' } },
+ { id: 'l-2', from: 'org-1', to: 'veh-1', type: 'owns', provenance: { by: 'user', at: '2026-08-02T09:05:00Z', status: 'confirmed' } },
+ { id: 'l-3', from: 'org-1', to: 'acc-1', type: 'owns', provenance: { by: 'enrich', at: '2026-08-02T09:10:00Z', status: 'suggested' } },
+];
+
+function graphView(url, override, pins = new Map(), held = graphLinks) {
+ if (override) return override;
+ const lens = url.searchParams.get('lens') ?? 'all';
+ const verbs = graphLenses.lenses.find((entry) => entry.id === lens)?.types ?? [];
+ // One lens draws one set of verbs, as the engine resolves them. Filtering here
+ // rather than blanking a single reading is what lets a spec state an edge into a
+ // lens that does not hold its verb, which is the one case the tool words.
+ const drawn = held.filter((link) => verbs.includes(link.type));
+ // The catalog filters the graph now sends, applied here rather than ignored: a
+ // spec has to be able to prove the surface asked the server to narrow. `type` is a
+ // comma-separated set, because that is what a family switch resolves to on its way
+ // out — read as one string, unticking a family narrowed to nothing.
+ const wantedTypes = (url.searchParams.get('type') ?? '').split(',').filter(Boolean);
+ const wantedStatus = url.searchParams.get('status') ?? '';
+ const wantedFolder = url.searchParams.get('folder') ?? '';
+ const recursive = url.searchParams.get('recursive') === 'true';
+ const unfiled = url.searchParams.get('unfiled') === 'true';
+ const query = (url.searchParams.get('q') ?? '').toLocaleLowerCase().split(/\s+/).filter(Boolean);
+ const field = url.searchParams.get('attr') ?? '';
+ const value = url.searchParams.get('value') ?? '';
+ const linked = url.searchParams.get('linked') ?? '';
+ const unlinked = url.searchParams.get('unlinked') === 'true';
+ const since = url.searchParams.get('since') ?? '';
+ const until = url.searchParams.get('until') ?? '';
+ const filedBy = (url.searchParams.get('by') ?? '').split(',').filter(Boolean);
+ const opened = (url.searchParams.get('expand') ?? '').split(',').filter(Boolean);
+ // The drawing is a set the client owns: `keep` draws these and nothing around them,
+ // `omit` leaves these out whatever put them there. Honoured here rather than ignored,
+ // or a spec would prove a picture the server never sends.
+ const byName = (url.searchParams.get('keep') ?? '').split(',').filter(Boolean);
+ const out = new Set((url.searchParams.get('omit') ?? '').split(',').filter(Boolean));
+ const degrees = new Map(graphNodes.map((node) => [node.id, 0]));
+ for (const link of drawn) {
+ degrees.set(link.from, degrees.get(link.from) + 1);
+ degrees.set(link.to, degrees.get(link.to) + 1);
+ }
+ // The pins are served back the way the case stores them — keyed by lens as well
+ // as by node — so a spec can prove an arrangement survived a reload, and that it
+ // did not leak into another reading.
+ // What an expansion reaches: the opened nodes and everything one hop from them,
+ // kept whatever the filters say — an analyst asking what touches this node is
+ // asking about the case, not about the narrowing they set earlier.
+ const reached = new Set(opened);
+ for (const link of drawn) {
+ if (opened.includes(link.from)) reached.add(link.to);
+ if (opened.includes(link.to)) reached.add(link.from);
+ }
+ const typeOf = new Map(graphNodes.map((node) => [node.id, node.type]));
+ const reaches = (node, wantedType) => drawn.some(
+ (link) =>
+ (link.from === node.id && typeOf.get(link.to) === wantedType) ||
+ (link.to === node.id && typeOf.get(link.from) === wantedType),
+ );
+ const hasLink = (node) => drawn.some((link) => link.from === node.id || link.to === node.id);
+ const passes = (node) => {
+ const searchable = [node.label, node.type, node.folder, node.kind, ...Object.values(node.attrs ?? {})]
+ .filter(Boolean).join('\n').toLocaleLowerCase();
+ return (
+ (!wantedTypes.length || wantedTypes.includes(node.type))
+ && (!wantedStatus || node.status === wantedStatus)
+ && (!wantedFolder || (recursive
+ ? node.folder === wantedFolder || node.folder?.startsWith(`${wantedFolder}/`)
+ : node.folder === wantedFolder))
+ && (!unfiled || !node.folder)
+ && (!query.length || query.every((term) => searchable.includes(term)))
+ && (!field || !value || String(node.attrs?.[field] ?? node[field] ?? '') === value)
+ && (!linked || reaches(node, linked))
+ && (!unlinked || !hasLink(node))
+ && (!since || node.at >= since)
+ && (!until || node.at <= `${until}T23:59:59Z`)
+ && (!filedBy.length || filedBy.includes(node.by ?? 'user'))
+ );
+ };
+ const standing = graphNodes.filter(
+ (node) =>
+ !out.has(node.id) && (reached.has(node.id) || byName.includes(node.id) || passes(node)),
+ );
+ // An arrival is held by whatever reaches it, so a removal takes with it the hops no
+ // anchor still reaches — or the drawing keeps a handful of dots with no edge to
+ // anything. Anchors are the ranked nodes and the ones named, which stand on their
+ // own. Mirrors `engine/graph._stranded`, and it is here for the same reason the
+ // filters are: a spec must not prove a picture the server never sends.
+ const survives = new Set(standing.map((node) => node.id));
+ const shown = new Set(
+ standing
+ .filter((node) => passes(node) || byName.includes(node.id) || opened.includes(node.id))
+ .map((node) => node.id),
+ );
+ for (let growing = true; growing; ) {
+ growing = false;
+ for (const link of drawn) {
+ for (const [near, far] of [[link.from, link.to], [link.to, link.from]]) {
+ if (shown.has(near) && survives.has(far) && !shown.has(far)) {
+ shown.add(far);
+ growing = true;
+ }
+ }
+ }
+ }
+ const kept = standing.filter((node) => shown.has(node.id));
+ // A degree says what a click would bring in, and nothing brings a removal back, so
+ // the edges that left with it stop being offered — exactly as the engine corrects it.
+ for (const link of drawn) {
+ for (const [near, far] of [[link.from, link.to], [link.to, link.from]]) {
+ if (out.has(far) && shown.has(near)) degrees.set(near, degrees.get(near) - 1);
+ }
+ }
+ const ranked = new Set(graphNodes.filter(passes).map((node) => node.id));
+ const nodes = kept.map((node) => {
+ const seat = { ...node, degree: degrees.get(node.id) };
+ delete seat.attrs;
+ if (query.length) {
+ const match = Object.entries(node.attrs ?? {}).find(([, held]) =>
+ query.every((term) => String(held).toLocaleLowerCase().includes(term))
+ );
+ if (match) seat.matches = [{ field: match[0], label: 'Plate', value: String(match[1]) }];
+ }
+ if (!ranked.has(node.id)) seat.added = true;
+ const pin = pins.get(`${lens}|${node.id}`);
+ return pin ? { ...seat, pin: [pin.x, pin.y] } : seat;
+ });
+ return {
+ lens,
+ order: url.searchParams.get('order') ?? 'degree',
+ nodes,
+ links: drawn.filter((link) => shown.has(link.from) && shown.has(link.to)),
+ total: ranked.size,
+ shown: nodes.length,
+ truncated: false,
+ kept: byName.filter((id) => shown.has(id)),
+ expanded: opened.filter((id) => graphNodes.some((node) => node.id === id)),
+ isolated: nodes.filter((node) => node.degree === 0).length,
+ pinned: [...pins.keys()].filter((key) => key.startsWith(`${lens}|`)).length,
+ };
+}
+
+
+/**
+ * The shortest route between two entities, as `engine/graph.paths` answers it.
+ *
+ * A plain breadth-first walk rather than the bidirectional one the server runs: the
+ * fixture case is seven nodes, and a spec proves the *tool's* behaviour, never the
+ * server's search strategy. Undirected, like the real one.
+ */
+function graphPaths(url, override, held = graphLinks) {
+ // A spec that overrides the drawn case overrides what a route may run through:
+ // answering over the default edges would have the route contradict the picture.
+ const drawn = override?.nodes ?? graphNodes;
+ if (override?.links) held = override.links;
+ const from = url.searchParams.get('from');
+ const to = url.searchParams.get('to');
+ const near = new Map();
+ for (const link of held) {
+ for (const [a, b] of [[link.from, link.to], [link.to, link.from]]) {
+ if (!near.has(a)) near.set(a, []);
+ near.get(a).push([b, link]);
+ }
+ }
+ // Every predecessor at the shortest depth, not one of them: the ties are what the
+ // tool draws all of, so a fixture that kept one could not prove it.
+ const depth = new Map([[from, 0]]);
+ const behind = new Map([[from, []]]);
+ let edge = [from];
+ while (edge.length && !depth.has(to)) {
+ const step = depth.get(edge[0]) + 1;
+ const next = [];
+ for (const id of edge) {
+ for (const [far, link] of near.get(id) ?? []) {
+ if (depth.has(far) && depth.get(far) < step) continue;
+ if (!depth.has(far)) {
+ depth.set(far, step);
+ behind.set(far, []);
+ next.push(far);
+ }
+ behind.get(far).push([id, link]);
+ }
+ }
+ edge = next;
+ }
+ const base = { lens: 'all', from, to, searched: 4, truncated: false };
+ if (!depth.has(to)) return { ...base, found: false, hops: 0, routes: [], nodes: [], links: [] };
+ const back = (at) => {
+ if (at === from) return [{ nodes: [from], links: [] }];
+ return (behind.get(at) ?? []).flatMap((step) =>
+ back(step[0]).map((route) => ({
+ nodes: [...route.nodes, at],
+ links: [...route.links, step[1].id],
+ })),
+ );
+ };
+ const routes = back(to);
+ const seen = new Set(routes.flatMap((route) => route.nodes));
+ const used = new Set(routes.flatMap((route) => route.links));
+ return {
+ ...base,
+ found: true,
+ hops: routes[0].links.length,
+ routes,
+ nodes: drawn.filter((node) => seen.has(node.id)),
+ links: held.filter((link) => used.has(link.id)),
+ };
+}
+
+function graphHood(url, override, held = graphLinks) {
+ if (override) return override;
+ const root = url.searchParams.get('root') ?? 'org-1';
+ const links = held.filter((link) => link.from === root || link.to === root);
+ const reached = new Set([root]);
+ for (const link of links) reached.add(link.from === root ? link.to : link.from);
+ const nodes = graphNodes
+ .filter((node) => reached.has(node.id))
+ .map((node) => ({ ...node, hop: node.id === root ? 0 : 1 }));
+ return { lens: url.searchParams.get('lens') ?? 'all', root, hops: 1, nodes, links, shown: nodes.length, truncated: false };
+}
+
+// The relation vocabulary slice exercised by browser specs. Keep endpoint and
+// action metadata exact: a stale action can make an E2E test prove the opposite
+// of the production contract.
+export const relationTypes = [
+ { type: 'located-at', label: 'was recorded at', inverse_label: 'was recorded here', hint: 'where the photo, video or audio was recorded', group: '', action: 'relation', from_types: ['media'], to_types: ['place'], from_media_kinds: ['audio', 'image', 'video'], to_media_kinds: [], manual: true, ratable: true },
+ { type: 'depicts', label: 'shows', inverse_label: 'is shown in', hint: 'the place is visible in the image or video', group: '', action: 'relation', from_types: ['capture', 'media'], to_types: ['place'], from_media_kinds: ['image', 'video'], to_media_kinds: [], manual: true, ratable: true },
+ { type: 'owns', label: 'owns', inverse_label: 'is owned by', hint: 'ownership rather than use, access or operational control', group: '', action: 'relation', from_types: ['organization', 'person'], to_types: ['account', 'aircraft', 'domain', 'email', 'ip', 'network', 'organization', 'phone', 'structure', 'vehicle', 'vessel'], from_media_kinds: [], to_media_kinds: [], manual: true, ratable: true },
+ { type: 'part-of', label: 'is part of', inverse_label: 'contains', hint: 'an internal unit inside its parent organization', group: '', action: 'relation', from_types: ['organization'], to_types: ['organization'], from_media_kinds: [], to_media_kinds: [], manual: true, ratable: true },
+ { type: 'member-of', label: 'is a member of', inverse_label: 'has member', hint: 'membership rather than internal containment', group: '', action: 'relation', from_types: ['organization', 'person'], to_types: ['organization'], from_media_kinds: [], to_media_kinds: [], manual: true, ratable: true },
+ { type: 'associated-with', label: 'is associated with', inverse_label: 'is associated with', hint: 'a tie that exists, where what kind it is rides on the edge', group: '', action: 'relation', from_types: ['organization', 'person'], to_types: ['organization', 'person'], from_media_kinds: [], to_media_kinds: [], manual: true, ratable: true, qualifier: 'How they are tied' },
+ { type: 'posted', label: 'posted', inverse_label: 'was posted by', hint: 'the account published the content or URL', group: '', action: 'relation', from_types: ['account'], to_types: ['bookmark', 'media'], from_media_kinds: [], to_media_kinds: [], manual: true, ratable: true },
+ { type: 'appears-in', label: 'appears in', inverse_label: 'shows', hint: 'the entity or a recognizable representation is visible', group: '', action: 'relation', from_types: ['account', 'aircraft', 'domain', 'email', 'ip', 'network', 'organization', 'person', 'phone', 'structure', 'vehicle', 'vessel'], to_types: ['capture', 'media'], from_media_kinds: [], to_media_kinds: ['image', 'video'], manual: true, ratable: true },
+ { type: 'sited-at', label: 'is sited at', inverse_label: 'is the site of', hint: 'a permanent site rather than a dated presence', group: '', action: 'relation', from_types: ['structure'], to_types: ['place'], from_media_kinds: [], to_media_kinds: [], manual: true, ratable: true },
+ { type: 'in-network', label: 'is in network', inverse_label: 'contains', hint: 'the address or subnet belongs inside this network', group: '', action: 'relation', from_types: ['ip', 'network'], to_types: ['network'], from_media_kinds: [], to_media_kinds: [], manual: true, ratable: true },
+ { type: 'same-image-as', label: 'is the same image as', inverse_label: 'is the same image as', hint: 'enrichment matched the perceptual hashes', group: '', action: 'relation', from_types: ['media'], to_types: ['media'], from_media_kinds: ['image'], to_media_kinds: ['image'], manual: false, ratable: false },
+ { type: 'mentions', label: 'mentions', inverse_label: 'is mentioned by', hint: 'the document refers to the entity', group: 'Mentions', action: 'mention', from_types: ['bookmark', 'note', 'post', 'proof'], to_types: ['account', 'aircraft', 'bookmark', 'capture', 'claim', 'domain', 'email', 'inspect-session', 'ip', 'media', 'network', 'note', 'organization', 'person', 'phone', 'place', 'post', 'proof', 'structure', 'vehicle', 'vessel'], from_media_kinds: [], to_media_kinds: [], manual: true, ratable: false },
+ { type: 'about', label: 'is about', inverse_label: 'has claim', hint: 'what the statement concerns', group: '', action: 'claim', from_types: ['claim'], to_types: ['account', 'aircraft', 'capture', 'domain', 'email', 'ip', 'media', 'network', 'organization', 'person', 'phone', 'place', 'structure', 'vehicle', 'vessel'], from_media_kinds: [], to_media_kinds: [], manual: true, ratable: false },
+ { type: 'at', label: 'places it at', inverse_label: 'is a claim location', hint: 'where the statement places its subject or event', group: '', action: 'claim', from_types: ['claim'], to_types: ['place'], from_media_kinds: [], to_media_kinds: [], manual: true, ratable: false },
+ { type: 'cites', label: 'cites', inverse_label: 'supports claim', hint: 'the evidence the statement relies on', group: '', action: 'claim', from_types: ['claim'], to_types: ['bookmark', 'capture', 'media', 'note', 'proof'], from_media_kinds: [], to_media_kinds: [], manual: true, ratable: false },
+ { type: 'contradicts', label: 'contradicts', inverse_label: 'is contradicted by', hint: 'the two statements cannot both hold', group: '', action: 'claim', from_types: ['claim'], to_types: ['claim'], from_media_kinds: [], to_media_kinds: [], manual: true, ratable: false },
+];
+
+// How sure an edge may say the analyst is. Served beside the verbs, and absent from
+// this list is "not assessed" — the lack of a rating, never a level.
+const confidenceLevels = [
+ { value: 3, label: 'Certain', hint: 'established and corroborated' },
+ { value: 2, label: 'Probable', hint: 'more likely than not, and short of established' },
+ { value: 1, label: 'Possible', hint: 'roughly even odds, and it cannot be excluded' },
+ { value: -1, label: 'Ruled out', hint: 'checked and eliminated' },
+];
+
+// The entity-vocabulary slice exercised by browser specs: what each used type reads
+// as, its family, icon and generated fields. Backend contract tests cover the full
+// registry; a browser spec adds a row here when it needs to render that type.
+const entityTypes = [
+ {
+ type: 'person', label: 'Person', family: 'actor', icon: 'user', manual: true, group: '', image_gallery: true,
+ identity_label: 'Full name', identity_placeholder: 'Name or known alias',
+ hint: 'a named individual', family_reads: 'a person or organization that can act or hold ownership',
+ attrs: [
+ { key: 'aliases', label: 'Other names', kind: 'text', rungs: [], options: [], minimum: null, maximum: null },
+ { key: 'role', label: 'Role', kind: 'text', rungs: [], options: [], minimum: null, maximum: null },
+ { key: 'nationality', label: 'Nationality', kind: 'text', rungs: [], options: [], minimum: null, maximum: null },
+ ],
+ },
+ {
+ type: 'organization', label: 'Organization', family: 'actor', icon: 'layers', manual: true, group: '', image_gallery: true,
+ identity_label: 'Organization name', identity_placeholder: 'Name of the organization',
+ hint: 'a company, a ministry or a military unit', family_reads: 'a person or organization that can act or hold ownership',
+ attrs: [],
+ },
+ {
+ type: 'vehicle', label: 'Vehicle', family: 'asset', icon: 'grip', manual: true, group: '', image_gallery: true,
+ identity_label: 'Vehicle name', identity_placeholder: 'How this vehicle is known',
+ hint: 'one particular vehicle, not a model', family_reads: 'a thing that is owned or appears in footage',
+ attrs: [
+ { key: 'plate', label: 'Plate', kind: 'text', rungs: [], options: [], minimum: null, maximum: null },
+ { key: 'make', label: 'Make', kind: 'text', rungs: [], options: [], minimum: null, maximum: null },
+ { key: 'model', label: 'Model', kind: 'text', rungs: [], options: [], minimum: null, maximum: null },
+ { key: 'colour', label: 'Colour', kind: 'text', rungs: [], options: [], minimum: null, maximum: null },
+ ],
+ },
+ {
+ type: 'account', label: 'Account', family: 'identifier', icon: 'at', manual: true, group: '',
+ identity_label: 'Handle', identity_placeholder: '@handle',
+ hint: 'a handle on one platform', family_reads: 'a handle on a system, where the value is the identity',
+ attrs: [
+ { key: 'platform', label: 'Platform', kind: 'text', rungs: [], options: [], minimum: null, maximum: null },
+ { key: 'url', label: 'Profile URL', kind: 'url', rungs: [], options: [], minimum: null, maximum: null },
+ ],
+ },
+ {
+ type: 'domain', label: 'Domain', family: 'identifier', icon: 'globe', manual: true, group: '',
+ identity_label: 'Hostname', identity_placeholder: 'example.test',
+ hint: 'a hostname, which is its own identity', family_reads: 'a handle on a system, where the value is the identity',
+ attrs: [
+ { key: 'registrar', label: 'Registrar', kind: 'text', rungs: [], options: [], minimum: null, maximum: null },
+ ],
+ },
+ {
+ type: 'ip', label: 'IP address', family: 'identifier', icon: 'hash', manual: true, group: '',
+ identity_label: 'IP address', identity_placeholder: '203.0.113.42',
+ hint: 'an address, which is its own identity', family_reads: 'a handle on a system, where the value is the identity',
+ attrs: [
+ { key: 'network', label: 'Legacy network', hint: 'older free text, replaced by the In network relation', kind: 'text', editable: false, rungs: [], options: [], minimum: null, maximum: null },
+ { key: 'asn', label: 'ASN', kind: 'text', rungs: [], options: [], minimum: null, maximum: null },
+ { key: 'provider', label: 'Provider', kind: 'text', rungs: [], options: [], minimum: null, maximum: null },
+ ],
+ },
+ {
+ type: 'network', label: 'Network', family: 'identifier', icon: 'globe', manual: true, group: '',
+ identity_label: 'Network or CIDR', identity_placeholder: '203.0.113.0/24',
+ hint: 'an IP range, named by its network or CIDR', family_reads: 'a handle on a system, where the value is the identity',
+ attrs: [
+ { key: 'asn', label: 'ASN', kind: 'text', rungs: [], options: [], minimum: null, maximum: null },
+ { key: 'provider', label: 'Provider', kind: 'text', rungs: [], options: [], minimum: null, maximum: null },
+ { key: 'country', label: 'Country', kind: 'text', rungs: [], options: [], minimum: null, maximum: null },
+ ],
+ },
+ {
+ type: 'claim', label: 'Claim', family: 'claim', icon: 'note', manual: true, group: 'Reasoning',
+ hint: 'something you are saying about the case',
+ identity_label: 'Statement', identity_placeholder: 'What are you asserting?',
+ family_reads: 'a statement about the rest of the case, carrying its own reasoning',
+ attrs: [
+ { key: 'confidence', label: 'Confidence', hint: 'how strongly the statement is supported', kind: 'choice', rungs: [], options: [{ value: 'certain', label: 'Certain' }, { value: 'probable', label: 'Probable' }, { value: 'possible', label: 'Possible' }, { value: 'refuted', label: 'Ruled out' }], minimum: null, maximum: null },
+ { key: 'method', label: 'How this was worked out', hint: 'the reasoning a reader would need to check this', kind: 'text', rungs: [], options: [], minimum: null, maximum: null },
+ { key: 'verbatim', label: 'As the source put it', hint: 'the original wording, quoted rather than paraphrased', kind: 'text', rungs: [], options: [], minimum: null, maximum: null },
+ ],
+ },
+ { type: 'media', label: 'Media', family: 'collected', icon: 'image', manual: false, group: '', hint: 'a file the case collected', family_reads: 'bytes gathered into the case rather than written', attrs: [] },
+ { type: 'capture', label: 'Capture', family: 'collected', icon: 'satellite', manual: false, group: '', hint: 'a map screenshot', family_reads: 'bytes gathered into the case rather than written', attrs: [] },
+ { type: 'place', label: 'Place', family: 'place', icon: 'pin', manual: false, group: 'How precise', hint: 'a saved point', family_reads: 'a point on the map, never a thing standing on it', attrs: [] },
+ { type: 'note', label: 'Note', family: 'document', icon: 'note', manual: false, group: '', hint: 'a Markdown page in the case notebook', family_reads: 'something read rather than gathered', attrs: [] },
+ {
+ type: 'bookmark', label: 'Bookmark', family: 'document', icon: 'globe', manual: false, group: '',
+ hint: 'a page the case points at',
+ family_reads: 'something read rather than gathered, made or merely consulted',
+ attrs: [
+ { key: 'archive_url', label: 'Archived copy', hint: 'a snapshot that survives the page being taken down', kind: 'url', rungs: [], options: [], minimum: null, maximum: null },
+ {
+ key: 'reliability', label: 'Source reliability', kind: 'choice', rungs: [], minimum: null, maximum: null,
+ hint: 'how much this source is worth in general, never how sure one claim is',
+ options: [
+ { value: 'A', label: 'Completely reliable' },
+ { value: 'B', label: 'Usually reliable' },
+ ],
+ },
+ ],
+ },
];
const providers = [{
@@ -113,6 +509,82 @@ function json(route, body, status = 200) {
return route.fulfill({ status, contentType: 'application/json', body: JSON.stringify(body) });
}
+function fixtureIso(milliseconds) {
+ return new Date(milliseconds).toISOString().replace('.000Z', 'Z');
+}
+
+function fixtureTemporalToken(raw) {
+ const clean = raw.replace(/[~?%]$/, '');
+ const timestamp = clean.match(/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,6})?(Z|[+-]\d{2}:\d{2})?$/);
+ if (timestamp) {
+ if (!timestamp[1]) {
+ return {
+ earliest: null, latest: null,
+ precision: clean.includes('.') ? 'subsecond' : 'second',
+ zone: 'local', sortable: false, timestamp: true,
+ };
+ }
+ const earliest = Date.parse(clean);
+ if (!Number.isFinite(earliest)) return null;
+ return {
+ earliest: fixtureIso(earliest),
+ latest: fixtureIso(earliest + (clean.includes('.') ? 1 : 1000)),
+ precision: clean.includes('.') ? 'subsecond' : 'second',
+ zone: timestamp[1] === 'Z' ? 'utc' : 'offset',
+ sortable: true,
+ timestamp: true,
+ };
+ }
+
+ const match = clean.match(/^(\d{4})(?:-(\d{2})(?:-(\d{2}))?)?$/);
+ if (!match) return null;
+ const year = Number(match[1]);
+ const month = match[2] ? Number(match[2]) : 1;
+ const day = match[3] ? Number(match[3]) : 1;
+ const earliest = Date.UTC(year, month - 1, day);
+ const latest = match[3]
+ ? Date.UTC(year, month - 1, day + 1)
+ : match[2] ? Date.UTC(year, month, 1) : Date.UTC(year + 1, 0, 1);
+ return {
+ earliest: fixtureIso(earliest),
+ latest: fixtureIso(latest),
+ precision: match[3] ? 'day' : match[2] ? 'month' : 'year',
+ zone: 'date-only',
+ sortable: true,
+ timestamp: false,
+ };
+}
+
+function fixtureTemporalReading(raw) {
+ if (!raw) {
+ return {
+ earliest: null, latest: null, precision: null, shape: null,
+ zone: null, sortable: false, uncertain: false, approximate: false,
+ };
+ }
+ const parts = raw.split('/');
+ const start = fixtureTemporalToken(parts[0]);
+ const end = parts[1] ? fixtureTemporalToken(parts[1]) : null;
+ if (!start || (parts[1] && !end)) {
+ return {
+ earliest: null, latest: null, precision: null,
+ shape: parts[1] ? 'interval' : 'instant', zone: null, sortable: false,
+ uncertain: raw.includes('?') || raw.includes('%'),
+ approximate: raw.includes('~') || raw.includes('%'),
+ };
+ }
+ return {
+ earliest: start.earliest,
+ latest: end ? (end.timestamp ? end.earliest : end.latest) : start.latest,
+ precision: end && end.precision !== start.precision ? 'mixed' : start.precision,
+ shape: end ? 'interval' : 'instant',
+ zone: end && end.zone !== start.zone ? 'mixed' : start.zone,
+ sortable: start.sortable && (!end || end.sortable),
+ uncertain: raw.includes('?') || raw.includes('%'),
+ approximate: raw.includes('~') || raw.includes('%'),
+ };
+}
+
/**
* Run the real Svelte, Konva and Leaflet code while replacing only Azimut's
* local API and files with deterministic fixtures. Any unexpected request is
@@ -124,11 +596,14 @@ export async function installAppFixture(page, options = {}) {
const proofSaves = [];
const fixtureSavedIndex = options.savedIndex ?? savedIndex;
const fixtureProofIndex = options.proofIndex ?? [];
+ const fixtureMedia = (options.media ?? media).map((item) => ({ ...item }));
const fixtureCases = options.cases ?? [caseOverview];
const fixtureSavedIndexes = options.savedIndexes ?? { [CASE_ID]: fixtureSavedIndex };
const fixtureProofIndexes = options.proofIndexes ?? { [CASE_ID]: fixtureProofIndex };
const savedIndexDelays = options.savedIndexDelays ?? {};
const proofIndexDelays = options.proofIndexDelays ?? {};
+ const caseDelays = options.caseDelays ?? {};
+ const graphDelays = options.graphDelays ?? {};
const fixtureDrafts = options.drafts ?? {};
const fixtureSettings = {
...settings,
@@ -143,12 +618,168 @@ export async function installAppFixture(page, options = {}) {
const trashGroups = [...(options.trashGroups ?? [])];
const trashWrites = [];
const bundleCalls = [];
+ // Where the graph's nodes have been dragged to, held across requests so a spec
+ // can reload the view and find the arrangement still there.
+ const graphPins = new Map(Object.entries(options.graphPins ?? {}));
+ const graphQueries = [];
+ const graphPinWrites = [];
+ const analysisViews = (options.analysisViews ?? []).map((view) => ({
+ ...view,
+ spec: structuredClone(view.spec ?? {}),
+ }));
+ const analysisWrites = [];
+ const timelineRows = (options.timelineItems ?? []).map((item) => structuredClone(item));
+ const timelineWrites = [];
const bundlePreview = options.bundlePreview;
const bundleJob = options.bundleJob ?? { state: 'ready' };
// Relations, keyed by entity id: what the bounded chain endpoint answers for
// the row whose relations a surface asked for.
const fixtureChains = options.chains ?? {};
const linkWrites = [];
+ // The edges this run holds, copied so a write from one spec is not read by the
+ // next. What the graph is drawn from, what the catalog's one-hop filter tests, and
+ // what a POST, a PATCH or a DELETE moves. A spec that brought its own catalog can
+ // bring the edges between those rows too.
+ const caseLinks = (options.links ?? graphLinks).map((link) => ({
+ ...link,
+ provenance: { ...link.provenance },
+ }));
+ let minted = 0;
+ // What the bounded catalog holds, and what the board asked it for. Copied rather
+ // than held by reference: a spec's `catalog` is a module constant shared by every
+ // test in the file, and confirming or dismissing a row writes to this one.
+ const fixtureCatalog = (options.catalog ?? []).map((entity) => ({
+ ...entity,
+ provenance: { ...entity.provenance },
+ }));
+ const catalogQueries = [];
+ const entityWrites = [];
+ const galleryWrites = [];
+ const entityImages = new Map(
+ Object.entries(options.entityImages ?? {}).map(([id, images]) => [
+ id,
+ images.map((image) => ({ ...image })),
+ ])
+ );
+ const uploads = [];
+ const pastes = [];
+ const revealed = [];
+
+ const timelineEntity = (id) => fixtureCatalog.find((entity) => entity.id === id)
+ ?? fixtureChains[id]?.entity
+ ?? null;
+ const timelineReferences = (item, ids, held) => {
+ if (Array.isArray(held)) return held.map((entry) => ({ ...entry }));
+ return (ids ?? []).map(timelineEntity).filter(Boolean).map((entry) => ({
+ id: entry.id, label: entry.label, type: entry.type,
+ }));
+ };
+ const enrichedTimelineItem = (item) => ({
+ ...structuredClone(item),
+ owner_type: item.owner_type ?? timelineEntity(item.owner_id)?.type ?? '',
+ subject_entities: timelineReferences(item, item.subjects, item.subject_entities),
+ place_entities: timelineReferences(item, item.places, item.place_entities),
+ source_entities: timelineReferences(item, item.sources, item.source_entities),
+ });
+ /** Where a statement's places sit, read from the place entities themselves. The
+ * projection carries names, and only the map route resolves them to coordinates —
+ * a place the case has not located therefore drops out here, as it does server
+ * side. */
+ const positionedPlaces = (item) => (item.places ?? []).map((placeId) => {
+ const place = timelineEntity(placeId);
+ const lat = Number(place?.attrs?.lat);
+ const lon = Number(place?.attrs?.lon);
+ if (!place || !Number.isFinite(lat) || !Number.isFinite(lon)) return null;
+ return {
+ id: place.id,
+ label: place.label,
+ lat,
+ lon,
+ radius_m: place.attrs.radius_m ?? null,
+ footprint: place.attrs.footprint ?? null,
+ };
+ }).filter(Boolean);
+ /** What a mark carries about the row's own entity, so the card can hand it back to
+ * the tool that owns it and show a photograph rather than a line of text. */
+ const mapOwner = (item) => {
+ const entity = timelineEntity(item.owner_id);
+ return {
+ id: item.owner_id,
+ type: entity?.type ?? item.owner_type ?? '',
+ label: entity?.label ?? item.label ?? '',
+ attrs: entity?.attrs ?? {},
+ thumb: entity?.thumb ?? entity?.attrs?.thumb ?? null,
+ };
+ };
+ const timelineMatchesTrack = (item, track = {}) => {
+ if ((track.hidden ?? []).includes(item.id)) return false;
+ const roles = Array.isArray(track.roles) ? track.roles : [];
+ if (roles.length && !roles.includes(item.time_role ?? 'unset')) return false;
+ const terms = track.terms && typeof track.terms === 'object' ? track.terms : {};
+ const relation = track.relation ?? 'any';
+ const related = {
+ owner: [timelineEntity(item.owner_id)].filter(Boolean),
+ about: timelineReferences(item, item.subjects, item.subject_entities),
+ place: timelineReferences(item, item.places, item.place_entities),
+ source: timelineReferences(item, item.sources, item.source_entities),
+ };
+ const candidates = relation === 'any'
+ ? [...related.owner, ...related.about, ...related.place, ...related.source]
+ : related[relation] ?? [];
+ const hasTerms = Object.values(terms).some((value) => value !== '' && value !== null && value !== false);
+ if (!hasTerms) return !['about', 'place', 'source'].includes(relation) || candidates.length > 0;
+ const types = String(terms.type ?? '').split(',').filter(Boolean);
+ const words = String(terms.q ?? '').toLocaleLowerCase().split(/\s+/).filter(Boolean);
+ return candidates.some((entity) => {
+ const text = [entity.label, entity.type, ...Object.values(entity.attrs ?? {})]
+ .filter(Boolean).join('\n').toLocaleLowerCase();
+ return (!types.length || types.includes(entity.type))
+ && (!terms.status || entity.provenance?.status === terms.status)
+ && (!words.length || words.every((word) => text.includes(word)));
+ });
+ };
+ const scopedTimelineRows = ({ categories = [], entity = '', track = {}, from = '', to = '', includeUndated = true }) =>
+ timelineRows.map(enrichedTimelineItem).filter((item) =>
+ (!categories.length || categories.includes(item.category))
+ && (!entity || item.owner_id === entity || (item.subjects ?? []).includes(entity)
+ || (item.places ?? []).includes(entity) || (item.sources ?? []).includes(entity))
+ && timelineMatchesTrack(item, track)
+ && (item.earliest
+ ? (!from || item.latest > (from.includes('T') ? from : `${from}T00:00:00Z`))
+ && (!to || item.earliest < (to.includes('T') ? to : `${to}T23:59:59Z`))
+ : includeUndated)
+ );
+ const analysisSnapshotCount = (spec) => spec?.snapshot?.timeline_items?.length
+ ?? spec?.snapshot?.entities?.length
+ ?? 0;
+ const captureTimelineSnapshot = (spec) => {
+ const timeline = spec?.timeline ?? {};
+ const visible = new Set(timeline.visible_categories ?? ['statement', 'media']);
+ const captured = new Map();
+ const timelineTracks = {};
+ for (const track of timeline.tracks ?? []) {
+ const categories = (track.categories ?? []).filter((category) => visible.has(category));
+ const rows = categories.length ? scopedTimelineRows({
+ categories,
+ entity: timeline.entity?.id ?? '',
+ track: { ...(track.query ?? {}), hidden: track.hidden ?? [] },
+ from: timeline.from ?? '',
+ to: timeline.to ?? '',
+ }) : [];
+ timelineTracks[track.id] = rows.map((item) => item.id);
+ for (const item of rows) captured.set(item.id, item);
+ }
+ return {
+ ...structuredClone(spec),
+ snapshot: {
+ captured_at: '2026-08-12T12:00:00Z',
+ entities: [],
+ links: [],
+ timeline_items: [...captured.values()],
+ timeline_tracks: timelineTracks,
+ },
+ };
+ };
await page.addInitScript((caseId) => {
localStorage.setItem('azimut:lastCase', caseId);
@@ -173,6 +804,9 @@ export async function installAppFixture(page, options = {}) {
if (path === `/files/${CASE_ID}/${PANEL_PATH}`) {
return route.fulfill({ contentType: 'image/svg+xml', body: PANEL_SVG });
}
+ if (path === `/files/${CASE_ID}/${GRAPH_THUMB}`) {
+ return route.fulfill({ contentType: 'image/svg+xml', body: PANEL_SVG });
+ }
if (path.startsWith('/api/tiles/')) {
return route.fulfill({ contentType: 'image/svg+xml', body: TILE_SVG });
}
@@ -228,6 +862,9 @@ export async function installAppFixture(page, options = {}) {
if (path === '/api/workspace/folders') return json(route, workspaceFolders);
if (path === '/api/templates') return json(route, { proof: [], post: [] });
if (path === '/api/cases/relation-types') return json(route, relationTypes);
+ if (path === '/api/cases/confidence-levels') return json(route, confidenceLevels);
+ if (path === '/api/cases/entity-types') return json(route, entityTypes);
+ if (path === '/api/cases/graph-lenses') return json(route, graphLenses);
if (path === '/api/cases/bundles/inspect' && request.method() === 'POST') {
bundleCalls.push({ kind: 'inspect' });
return json(route, bundlePreview ?? { detail: 'No bundle fixture' }, bundlePreview ? 200 : 400);
@@ -236,8 +873,274 @@ export async function installAppFixture(page, options = {}) {
return json(route, fixtureCases.map((item) => ({ entity_count: 1, ...item })));
}
const overview = fixtureCases.find((item) => path === `/api/cases/${item.id}`);
- if (overview) return json(route, overview);
+ if (overview) {
+ if (caseDelays[overview.id]) {
+ await new Promise((resolve) => setTimeout(resolve, caseDelays[overview.id]));
+ }
+ return json(route, overview);
+ }
const caseId = fixtureCases.find((item) => path.startsWith(`/api/cases/${item.id}/`))?.id;
+ if (caseId && path === `/api/cases/${caseId}/analysis-views`) {
+ if (request.method() === 'GET') {
+ return json(route, {
+ views: analysisViews.map(({ spec, ...view }) => ({
+ ...view,
+ snapshot_count: analysisSnapshotCount(spec),
+ })),
+ });
+ }
+ if (request.method() === 'POST') {
+ const body = request.postDataJSON();
+ const spec = body.mode === 'snapshot' && body.surface === 'timeline'
+ ? captureTimelineSnapshot(body.spec)
+ : structuredClone(body.spec ?? {});
+ const saved = {
+ id: `v_browser_${analysisViews.length + 1}`,
+ ...body,
+ spec,
+ created_at: '2026-08-10T10:00:00Z',
+ updated_at: '2026-08-10T10:00:00Z',
+ snapshot_count: analysisSnapshotCount(spec),
+ };
+ analysisViews.push(saved);
+ analysisWrites.push({ method: 'POST', caseId, body });
+ return json(route, saved);
+ }
+ }
+ const duplicateMatch = caseId && path.match(
+ new RegExp(`^/api/cases/${caseId}/analysis-views/([^/]+)/duplicate$`)
+ );
+ if (duplicateMatch && request.method() === 'POST') {
+ const source = analysisViews.find(
+ (view) => view.id === decodeURIComponent(duplicateMatch[1])
+ );
+ if (!source) return json(route, { detail: 'Analysis view not found' }, 404);
+ const body = request.postDataJSON();
+ const saved = {
+ ...structuredClone(source),
+ id: `v_browser_${analysisViews.length + 1}`,
+ name: body.name,
+ created_at: '2026-08-10T10:00:00Z',
+ updated_at: '2026-08-10T10:00:00Z',
+ };
+ analysisViews.push(saved);
+ analysisWrites.push({ method: 'POST', body, duplicate: source.id });
+ return json(route, saved);
+ }
+ const analysisMatch = caseId && path.match(
+ new RegExp(`^/api/cases/${caseId}/analysis-views/([^/]+)$`)
+ );
+ if (analysisMatch) {
+ const id = decodeURIComponent(analysisMatch[1]);
+ const index = analysisViews.findIndex((view) => view.id === id);
+ if (index < 0) return json(route, { detail: 'Analysis view not found' }, 404);
+ if (request.method() === 'GET') return json(route, analysisViews[index]);
+ if (request.method() === 'PUT') {
+ const body = request.postDataJSON();
+ analysisViews[index] = {
+ ...analysisViews[index],
+ ...body,
+ id,
+ updated_at: '2026-08-10T11:00:00Z',
+ };
+ analysisWrites.push({ method: 'PUT', caseId, id, body });
+ return json(route, analysisViews[index]);
+ }
+ if (request.method() === 'DELETE') {
+ analysisViews.splice(index, 1);
+ analysisWrites.push({ method: 'DELETE', id });
+ return json(route, { status: 'deleted', deleted: [id], trash: 'trash-view-1' });
+ }
+ }
+ // Pins are held per lens, keyed `lens|entity`, because that is how the case
+ // stores them: an arrangement belongs to one reading.
+ const pinsIn = (lens) => [...graphPins.keys()].filter((key) => key.startsWith(`${lens}|`));
+ if (caseId && path === `/api/cases/${caseId}/graph/pins`) {
+ if (request.method() === 'PUT') {
+ const body = JSON.parse(request.postData());
+ graphPinWrites.push({ caseId, body });
+ for (const pin of body.pins) {
+ graphPins.set(`${body.lens}|${pin.id}`, { x: pin.x, y: pin.y });
+ }
+ return json(route, { lens: body.lens, pinned: pinsIn(body.lens).length });
+ }
+ if (request.method() === 'DELETE') {
+ const lens = url.searchParams.get('lens') ?? 'all';
+ for (const key of pinsIn(lens)) graphPins.delete(key);
+ return json(route, { lens, pinned: 0 });
+ }
+ }
+ const unpinned = caseId
+ && request.method() === 'DELETE'
+ && path.startsWith(`/api/cases/${caseId}/graph/pins/`);
+ if (unpinned) {
+ const lens = url.searchParams.get('lens') ?? 'all';
+ graphPins.delete(`${lens}|${path.slice(`/api/cases/${caseId}/graph/pins/`.length)}`);
+ return json(route, { lens, pinned: pinsIn(lens).length });
+ }
+ if (caseId && path === `/api/cases/${caseId}/graph`) {
+ graphQueries.push({ caseId, search: url.search });
+ if (graphDelays[caseId]) {
+ await new Promise((resolve) => setTimeout(resolve, graphDelays[caseId]));
+ }
+ const savedView = analysisViews.find((view) => view.id === url.searchParams.get('view'));
+ if (savedView?.mode === 'snapshot') {
+ const snapshot = savedView.spec?.snapshot ?? { entities: [], links: [] };
+ const ids = new Set(snapshot.entities.map((entity) => entity.id));
+ const links = snapshot.links.filter((link) => ids.has(link.from) && ids.has(link.to));
+ const degrees = new Map(snapshot.entities.map((entity) => [entity.id, 0]));
+ for (const link of links) {
+ degrees.set(link.from, degrees.get(link.from) + 1);
+ degrees.set(link.to, degrees.get(link.to) + 1);
+ }
+ return json(route, {
+ lens: url.searchParams.get('lens') ?? 'all',
+ order: 'snapshot',
+ nodes: snapshot.entities.map((entity) => ({
+ id: entity.id,
+ type: entity.type,
+ label: entity.label,
+ family: 'actor',
+ status: entity.provenance?.status ?? 'confirmed',
+ at: entity.provenance?.at ?? '',
+ degree: degrees.get(entity.id),
+ })),
+ links,
+ total: snapshot.entities.length,
+ shown: snapshot.entities.length,
+ truncated: false,
+ isolated: [...degrees.values()].filter((degree) => degree === 0).length,
+ single_account: 0,
+ kept: [],
+ expanded: [],
+ pinned: 0,
+ snapshot: true,
+ captured_at: snapshot.captured_at,
+ });
+ }
+ const chosen = options.graphs?.[caseId] ?? options.graph;
+ const override = typeof chosen === 'function'
+ ? await chosen({ caseId, url, catalog: fixtureCatalog, links: caseLinks })
+ : chosen;
+ return json(route, graphView(url, override, graphPins, caseLinks));
+ }
+ if (caseId && path === `/api/cases/${caseId}/graph/neighborhood`) {
+ return json(route, graphHood(url, options.graph, caseLinks));
+ }
+
+ if (caseId && path === `/api/cases/${caseId}/graph/paths`) {
+ return json(route, graphPaths(url, options.graph, caseLinks));
+ }
+
+ const timelineClaimMatch = caseId && path.match(
+ new RegExp(`^/api/cases/${caseId}/timeline/claims(?:/([^/]+))?$`)
+ );
+ if (timelineClaimMatch && request.method() !== 'GET') {
+ const body = request.postDataJSON();
+ const ownerId = timelineClaimMatch[1] ?? `claim-browser-${timelineRows.length + 1}`;
+ timelineWrites.push({ method: request.method(), ownerId, body });
+ const index = timelineRows.findIndex((item) => item.owner_id === ownerId);
+ const raw = body.when ?? (index >= 0 ? timelineRows[index].raw : null);
+ const reading = fixtureTemporalReading(raw);
+ const temporal = {
+ id: `temporal:claim:${ownerId}`,
+ owner_id: ownerId,
+ category: 'statement',
+ kind: 'claim',
+ label: body.statement ?? (index >= 0 ? timelineRows[index].label : 'Assessment'),
+ raw,
+ ...reading,
+ time_role: body.time_role ?? null,
+ status: 'confirmed',
+ confidence: body.confidence ?? null,
+ parse_error: null,
+ subjects: body.about ?? [],
+ places: body.at ?? [],
+ sources: body.cites ?? [],
+ };
+ if (index >= 0) timelineRows[index] = temporal;
+ else timelineRows.push(temporal);
+ return json(route, {
+ entity: { id: ownerId, type: 'claim', label: temporal.label, attrs: body, provenance: { by: 'user', at: '2026-08-12T10:00:00Z', status: 'confirmed' } },
+ links: [],
+ temporal,
+ });
+ }
+ if (caseId && path === `/api/cases/${caseId}/timeline/map`) {
+ const from = url.searchParams.get('from');
+ const to = url.searchParams.get('to');
+ // Everything dated in the window that the case has put somewhere, in whichever
+ // categories the caller asked for — `at` is a Claim's connector, and a layer
+ // reading it alone answered a window of located photographs with nothing.
+ // `matched` counts the window; `mapped` counts the ones a marker can be put on,
+ // so the card can say how much it is not showing.
+ const wanted = url.searchParams.getAll('category').flatMap((value) => value.split(','));
+ const matched = scopedTimelineRows({
+ categories: wanted.filter(Boolean).length ? wanted.filter(Boolean) : ['statement', 'media'],
+ from, to, includeUndated: false,
+ });
+ const mapped = matched
+ .map((item) => ({
+ ...item,
+ place_entities: positionedPlaces(item),
+ owner: mapOwner(item),
+ }))
+ .filter((item) => item.place_entities.length);
+ return json(route, {
+ items: mapped,
+ matched: matched.length,
+ mapped: mapped.length,
+ marks: mapped.reduce((count, item) => count + item.place_entities.length, 0),
+ truncated: false,
+ window: { from, to },
+ });
+ }
+
+ if (caseId && path === `/api/cases/${caseId}/timeline`) {
+ const wanted = url.searchParams.getAll('category');
+ const entity = url.searchParams.get('entity');
+ let track = {};
+ try {
+ track = JSON.parse(url.searchParams.get('track') ?? '{}');
+ } catch {
+ return json(route, { detail: 'Invalid timeline track' }, 400);
+ }
+ const base = scopedTimelineRows({ categories: wanted, entity, track });
+ const datedBase = base.filter((item) => item.earliest);
+ const from = url.searchParams.get('from');
+ const to = url.searchParams.get('to');
+ const includeUndated = url.searchParams.get('include_undated') !== 'false';
+ const visible = scopedTimelineRows({
+ categories: wanted, entity, track, from, to, includeUndated,
+ });
+ const bucket = url.searchParams.get('bucket');
+ const width = { year: 4, month: 7, day: 10 }[bucket] ?? 0;
+ const bucketCounts = new Map();
+ if (width) for (const item of datedBase) {
+ const key = item.earliest.slice(0, width);
+ const held = bucketCounts.get(key) ?? { count: 0, categories: {} };
+ held.count += 1;
+ held.categories[item.category] = (held.categories[item.category] ?? 0) + 1;
+ bucketCounts.set(key, held);
+ }
+ return json(route, {
+ items: visible,
+ next_cursor: null,
+ total: visible.length,
+ undated: base.filter((item) => !item.earliest && !item.raw).length,
+ unplaced: base.filter((item) => !item.earliest && item.raw).length,
+ buckets: [...bucketCounts]
+ .sort(([left], [right]) => left.localeCompare(right))
+ .map(([start, held]) => ({ start, count: held.count, categories: held.categories })),
+ buckets_truncated: false,
+ extent: {
+ from: datedBase.map((item) => item.earliest).sort()[0] ?? null,
+ to: datedBase.map((item) => item.latest).sort().at(-1) ?? null,
+ },
+ window: { from, to },
+ });
+ }
+
if (caseId && path === `/api/cases/${caseId}/satellite/index`) {
if (savedIndexDelays[caseId]) {
await new Promise((resolve) => setTimeout(resolve, savedIndexDelays[caseId]));
@@ -250,11 +1153,253 @@ export async function installAppFixture(page, options = {}) {
}
return json(route, fixtureProofIndexes[caseId] ?? []);
}
+ // The case as the catalog answers for it: a spec's own list, or the drawn case so
+ // the fixture stands for one case rather than two — the graph's search reads the
+ // catalog, and it has to be able to find an entity the drawing left out.
+ const catalogRows = () =>
+ fixtureCatalog.length
+ ? fixtureCatalog
+ : graphNodes.map((node) => ({
+ id: node.id,
+ type: node.type,
+ label: node.label,
+ attrs: {
+ ...(node.folder ? { folder: node.folder } : {}),
+ ...(node.kind ? { kind: node.kind } : {}),
+ ...(node.attrs ?? {}),
+ },
+ provenance: { by: 'user', at: node.at, status: node.status },
+ }));
if (caseId && path === `/api/cases/${caseId}/catalog/summary`) {
- return json(route, { total: 1, by_type: { media: 1 }, by_status: { confirmed: 1 }, by_folder: {} });
+ if (options.summary) return json(route, options.summary);
+ // The count the surface shows when nothing is filtered, so it has to be the
+ // catalog's own size rather than a fixed 1 — otherwise "Showing 2 of 1".
+ //
+ // `by_type` is every type the case holds, which is what the graph resolves its
+ // family switches against: a spec that set a catalog up is standing for that
+ // case, one that did not is standing for the drawn one. Hard-coded, the graph's
+ // legend would offer one family for a case holding five.
+ const byType = {};
+ const rows = catalogRows();
+ for (const entity of rows) {
+ byType[entity.type] = (byType[entity.type] ?? 0) + 1;
+ }
+ const typeOf = new Map(rows.map((entity) => [entity.id, entity.type]));
+ const linkedTo = {};
+ for (const entity of rows) {
+ const reached = new Set();
+ for (const link of caseLinks) {
+ if (link.from === entity.id && typeOf.get(link.to)) reached.add(typeOf.get(link.to));
+ if (link.to === entity.id && typeOf.get(link.from)) reached.add(typeOf.get(link.from));
+ }
+ for (const type of reached) linkedTo[type] = (linkedTo[type] ?? 0) + 1;
+ }
+ return json(route, {
+ total: fixtureCatalog.length || 1,
+ by_type: byType,
+ by_status: { confirmed: 1 },
+ by_folder: {},
+ linked_to: linkedTo,
+ });
+ }
+ // Which stored fields the listed types hold, and their values: the menus a field
+ // filter is chosen from. Derived from the same rows the page is, so the fixture
+ // cannot offer a term the mocked case could not answer.
+ if (caseId && path === `/api/cases/${caseId}/catalog/attributes`) {
+ const wanted = (url.searchParams.get('type') ?? '').split(',').filter(Boolean);
+ const counts = new Map();
+ for (const entity of catalogRows()) {
+ if (wanted.length && !wanted.includes(entity.type)) continue;
+ for (const [key, value] of Object.entries(entity.attrs ?? {})) {
+ if (typeof value !== 'string' || !value) continue;
+ const held = counts.get(key) ?? new Map();
+ held.set(value, (held.get(value) ?? 0) + 1);
+ counts.set(key, held);
+ }
+ }
+ return json(route, {
+ attrs: [...counts].map(([key, values]) => ({
+ key,
+ entities: [...values.values()].reduce((sum, n) => sum + n, 0),
+ values: [...values]
+ .sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0]))
+ .map(([value, count]) => ({ value, count })),
+ truncated: false,
+ })),
+ });
}
if (caseId && path === `/api/cases/${caseId}/catalog/entities`) {
- return json(route, { items: [], next_cursor: null });
+ // Filtered here rather than returned whole, so a spec can prove the surface
+ // asked the server to narrow instead of hiding rows it had already loaded.
+ const wanted = (url.searchParams.get('type') ?? '').split(',').filter(Boolean);
+ const term = (url.searchParams.get('q') ?? '').toLowerCase();
+ const status = url.searchParams.get('status') ?? '';
+ const field = url.searchParams.get('attr') ?? '';
+ const value = url.searchParams.get('value') ?? '';
+ const linked = url.searchParams.get('linked') ?? '';
+ const savedView = analysisViews.find(
+ (view) => view.id === url.searchParams.get('view')
+ );
+ const held = savedView?.mode === 'snapshot'
+ ? savedView.spec?.snapshot?.entities ?? []
+ : catalogRows();
+ const typeOf = new Map(held.map((entity) => [entity.id, entity.type]));
+ // The one-hop test, over the same edges the graph answers with. Undirected,
+ // because "linked to a place" is a question about the pair.
+ const reaches = (id, wantedType) =>
+ caseLinks.some(
+ (link) =>
+ (link.from === id && typeOf.get(link.to) === wantedType) ||
+ (link.to === id && typeOf.get(link.from) === wantedType)
+ );
+ // A fact-time window reaches an entity through its own dates and through the
+ // statements that name it, which is the join the server makes: a person is in
+ // June because something said about them happened in June.
+ const temporalFrom = url.searchParams.get('temporal_from') ?? '';
+ const temporalTo = url.searchParams.get('temporal_to') ?? '';
+ const inPeriod = temporalFrom && temporalTo
+ ? new Set(scopedTimelineRows({
+ categories: (url.searchParams.get('temporal_category') ?? '').split(',').filter(Boolean),
+ from: temporalFrom,
+ to: temporalTo,
+ includeUndated: false,
+ }).flatMap((item) => [
+ item.owner_id, ...item.subjects ?? [], ...item.places ?? [], ...item.sources ?? [],
+ ]))
+ : null;
+ const matching = held.filter(
+ (entity) =>
+ (!wanted.length || wanted.includes(entity.type)) &&
+ (!status || entity.provenance?.status === status) &&
+ (!term || [entity.label, entity.type, ...Object.values(entity.attrs ?? {})]
+ .some((heldValue) => String(heldValue ?? '').toLowerCase().includes(term))) &&
+ (!field || !value || String(entity.attrs?.[field] ?? '') === value) &&
+ (!linked || reaches(entity.id, linked)) &&
+ (!inPeriod || inPeriod.has(entity.id))
+ );
+ const order = url.searchParams.get('order') ?? '';
+ const descending = order.startsWith('-');
+ const column = descending ? order.slice(1) : order;
+ const direction = descending ? -1 : 1;
+ const ordered = column
+ ? [...matching].sort((left, right) => {
+ const a = column === 'created' ? left.provenance?.at : left.label;
+ const b = column === 'created' ? right.provenance?.at : right.label;
+ return String(a ?? '').localeCompare(String(b ?? '')) * direction;
+ })
+ : matching;
+ catalogQueries.push(url.search);
+ // `catalogPage` makes the fixture answer in pages, which is the only way to
+ // reach the surface's server-search mode: a case that fits one page filters
+ // in the browser and never asks a second question.
+ const page = options.catalogPage ?? 0;
+ const items = page ? ordered.slice(0, page) : ordered;
+ return json(route, {
+ items,
+ next_cursor: page && matching.length > page ? 'cursor-2' : null,
+ total: matching.length,
+ });
+ }
+ const galleryMatch = caseId && path.match(
+ new RegExp(`^/api/cases/${caseId}/entities/([^/]+)/images(?:/([^/]+)(/primary)?)?$`)
+ );
+ if (galleryMatch) {
+ const entityId = decodeURIComponent(galleryMatch[1]);
+ const imageId = galleryMatch[2] ? decodeURIComponent(galleryMatch[2]) : null;
+ const held = entityImages.get(entityId) ?? [];
+ entityImages.set(entityId, held);
+ const syncThumb = () => {
+ const entity = fixtureCatalog.find((item) => item.id === entityId);
+ const primary = held.find((image) => image.primary);
+ if (!entity) return;
+ if (primary) entity.thumb = primary.thumbnail ?? primary.path;
+ else delete entity.thumb;
+ };
+ if (request.method() === 'GET' && !imageId) return json(route, { images: held });
+ if (request.method() === 'POST' && imageId === 'upload') {
+ const uploaded = {
+ id: `photo-direct-${held.length + 1}`,
+ media_id: null,
+ direct: true,
+ path: PANEL_PATH,
+ thumbnail: null,
+ title: 'Portrait',
+ kind: 'image',
+ position: held.length,
+ primary: held.length === 0,
+ ...(options.entityImageUploadResult ?? {}),
+ };
+ held.push(uploaded);
+ syncThumb();
+ galleryWrites.push({ method: 'UPLOAD', entityId, imageId: uploaded.id });
+ return json(route, { added: 1, images: held });
+ }
+ if (request.method() === 'POST' && !imageId) {
+ const body = request.postDataJSON();
+ let added = 0;
+ for (const id of body.media_ids) {
+ if (held.some((image) => image.media_id === id)) continue;
+ const item = fixtureMedia.find((candidate) => candidate.entity_id === id)
+ ?? (options.uploadResult?.entity?.id === id ? options.uploadResult.item : null);
+ held.push({
+ ...(item ?? { path: PANEL_PATH, title: 'Photo', kind: 'image' }),
+ id,
+ media_id: id,
+ direct: false,
+ position: held.length,
+ primary: held.length === 0,
+ });
+ added += 1;
+ }
+ syncThumb();
+ galleryWrites.push({ method: 'POST', entityId, mediaIds: body.media_ids });
+ return json(route, { added, images: held });
+ }
+ if (request.method() === 'PUT' && imageId && galleryMatch[3]) {
+ for (const image of held) image.primary = image.id === imageId;
+ syncThumb();
+ galleryWrites.push({ method: 'PUT', entityId, imageId });
+ return json(route, { images: held });
+ }
+ if (request.method() === 'DELETE' && imageId) {
+ const removed = held.findIndex((image) => image.id === imageId);
+ if (removed !== -1) held.splice(removed, 1);
+ if (held.length && !held.some((image) => image.primary)) held[0].primary = true;
+ syncThumb();
+ galleryWrites.push({ method: 'DELETE', entityId, imageId });
+ return json(route, { images: held });
+ }
+ }
+ const entityMatch = caseId && path.match(new RegExp(`^/api/cases/${caseId}/entities/([^/]+)$`));
+ if (entityMatch && request.method() !== 'GET') {
+ const body = request.method() === 'DELETE' ? null : request.postDataJSON();
+ entityWrites.push({ method: request.method(), id: entityMatch[1], body });
+ const index = fixtureCatalog.findIndex((entity) => entity.id === entityMatch[1]);
+ if (index >= 0) {
+ if (request.method() === 'DELETE') fixtureCatalog.splice(index, 1);
+ else if (body?.status) fixtureCatalog[index].provenance.status = body.status;
+ }
+ // the delete route's own shape: what went, and the trash group to put it back
+ if (request.method() === 'DELETE') {
+ return json(route, {
+ status: 'deleted',
+ deleted: [entityMatch[1]],
+ tombstoned: [],
+ trash: 'trash-1',
+ });
+ }
+ return json(route, fixtureCatalog[index] ?? { id: entityMatch[1], ...body });
+ }
+ if (caseId && path === `/api/cases/${caseId}/entities` && request.method() === 'POST') {
+ const payload = request.postDataJSON();
+ entityWrites.push(payload);
+ const created = {
+ id: options.newEntityId ?? 'e_new',
+ ...payload,
+ provenance: { by: 'user', at: '2026-08-03T10:00:00Z', status: 'confirmed' },
+ };
+ fixtureCatalog.push(created);
+ return json(route, created);
}
if (caseId && path === `/api/cases/${caseId}/trash`) {
if (request.method() === 'DELETE') {
@@ -288,6 +1433,26 @@ export async function installAppFixture(page, options = {}) {
return json(route, bundleJob);
}
if (caseId && path === `/api/cases/${caseId}/search-grids`) return json(route, []);
+ const placementMatch = caseId && path.match(
+ new RegExp(`^/api/cases/${caseId}/entities/(.+)/placement$`)
+ );
+ if (placementMatch) {
+ return json(
+ route,
+ options.placements?.[placementMatch[1]] ?? { points: [], truncated: false }
+ );
+ }
+ // What the statements about one entity come to. Details asks for it whenever the
+ // Connections tab is on screen, so every spec that opens a panel reaches it. 404 is the
+ // ordinary answer — nothing states anything about this row — and `tallies` is how
+ // a spec gives one a total.
+ const tallyMatch = caseId && path.match(
+ new RegExp(`^/api/cases/${caseId}/entities/(.+)/tally$`)
+ );
+ if (tallyMatch) {
+ const row = options.tallies?.[tallyMatch[1]];
+ return row ? json(route, row) : route.fulfill({ status: 404, body: '{}' });
+ }
const chainMatch = caseId && path.match(new RegExp(`^/api/cases/${caseId}/entities/(.+)/chain$`));
if (chainMatch) {
const chain = fixtureChains[chainMatch[1]];
@@ -295,32 +1460,99 @@ export async function installAppFixture(page, options = {}) {
}
const linkMatch = caseId && path.match(new RegExp(`^/api/cases/${caseId}/links(?:/(.+))?$`));
if (linkMatch && request.method() !== 'GET') {
- linkWrites.push({
- method: request.method(),
- id: linkMatch[1] ?? null,
- body: request.method() === 'DELETE' ? null : request.postDataJSON(),
- });
- return json(route, request.method() === 'DELETE' ? { status: 'deleted' } : { id: 'link-new' });
+ const body = request.method() === 'DELETE' ? null : request.postDataJSON();
+ linkWrites.push({ method: request.method(), id: linkMatch[1] ?? null, body });
+ // The write lands in the case, so the next read answers with it. A stub that
+ // recorded the request and forgot it made every surface look like it had
+ // written nothing.
+ if (request.method() === 'DELETE') {
+ const gone = caseLinks.findIndex((link) => link.id === linkMatch[1]);
+ if (gone !== -1) caseLinks.splice(gone, 1);
+ return json(route, { status: 'deleted' });
+ }
+ if (linkMatch[1]) {
+ // The drawn case is not the only place a fixture holds edges — a `chains`
+ // entry carries its own — so an id this list does not know is echoed back
+ // rather than refused, which is what the real route would answer for it.
+ const held = caseLinks.find((link) => link.id === linkMatch[1]);
+ if (held) {
+ if (body.type) held.type = body.type;
+ if (body.status) held.provenance.status = body.status;
+ }
+ return json(route, held ?? { id: linkMatch[1], ...body });
+ }
+ minted += 1;
+ const filed = {
+ id: `link-new-${minted}`,
+ from: body.from_id,
+ to: body.to_id,
+ type: body.type,
+ provenance: { by: 'user', at: '2026-08-03T09:00:00Z', status: 'confirmed' },
+ };
+ caseLinks.push(filed);
+ return json(route, filed);
+ }
+ if (caseId && path === `/api/cases/${caseId}/media/reveal` && request.method() === 'POST') {
+ revealed.push(request.postDataJSON()?.path ?? '');
+ return json(route, { path: '/workspace/cases/browser-test/azimut/media' });
+ }
+ if (caseId && path === `/api/cases/${caseId}/media/paste` && request.method() === 'POST') {
+ // The clipboard route answers the shape `upload` does, plus whatever the paste
+ // dialog stated: the title that names the file and the origin it typed.
+ const body = request.postData() ?? '';
+ const field = (name) => body.match(new RegExp(`name="${name}"\\r?\\n\\r?\\n([^\\r]*)`))?.[1] ?? '';
+ pastes.push({ title: field('title'), source_url: field('source_url'), length: body.length });
+ const result = options.pasteResult ?? {
+ duplicate: false,
+ entity: {
+ id: 'media-pasted',
+ type: 'media',
+ label: field('title') || 'paste-20260811-120000',
+ attrs: { path: 'media/pasted.png', kind: 'image', sha256: 'def' },
+ provenance: { by: 'paste', at: '2026-08-11T12:00:00Z', status: 'confirmed' },
+ },
+ item: { path: 'media/pasted.png', kind: 'image' },
+ };
+ if (!result.duplicate && result.entity) fixtureCatalog.push(result.entity);
+ return json(route, result);
+ }
+ if (caseId && path === `/api/cases/${caseId}/media/upload` && request.method() === 'POST') {
+ // What the importer answers: the entity it filed, with the kind it read off
+ // the bytes. `uploadResult` lets a spec make it a duplicate instead.
+ uploads.push({ length: request.postData()?.length ?? 0 });
+ const result = options.uploadResult ?? {
+ duplicate: false,
+ entity: {
+ id: 'media-imported',
+ type: 'media',
+ label: 'site plan',
+ attrs: { path: 'media/site plan.pdf', kind: 'file', sha256: 'abc' },
+ provenance: { by: 'media-library', at: '2026-08-04T09:00:00Z', status: 'confirmed' },
+ },
+ item: { path: 'media/site plan.pdf', kind: 'file' },
+ };
+ if (!result.duplicate && result.entity) fixtureCatalog.push(result.entity);
+ return json(route, result);
}
if (path === `/api/cases/${CASE_ID}/media/page`) {
return json(route, {
- items: media,
+ items: fixtureMedia,
next_cursor: null,
- total: media.length,
+ total: fixtureMedia.length,
facets: {
- category_counts: { image: media.length, upload: media.length },
+ category_counts: { image: fixtureMedia.length, upload: fixtureMedia.length },
folder_counts: {},
gps_count: 0,
thumbnail_pending: 0,
},
});
}
- if (path === `/api/cases/${CASE_ID}/media`) return json(route, media);
+ if (path === `/api/cases/${CASE_ID}/media`) return json(route, fixtureMedia);
// One media file with everything its sidecar holds. The browse index leaves
// enrichment's metadata dumps out, so the Details panel reads a file at a time.
if (path === `/api/cases/${CASE_ID}/media/item`) {
const wanted = url.searchParams.get('path');
- const found = media.find((item) => item.path === wanted);
+ const found = fixtureMedia.find((item) => item.path === wanted);
return found ? json(route, found) : route.fulfill({ status: 404, body: '{}' });
}
if (path === `/api/cases/${CASE_ID}/media/export` && request.method() === 'POST') {
@@ -384,6 +1616,16 @@ export async function installAppFixture(page, options = {}) {
captures,
proofSaves,
linkWrites,
+ entityWrites,
+ galleryWrites,
+ catalogQueries,
+ graphQueries,
+ graphPinWrites,
+ analysisWrites,
+ timelineWrites,
+ uploads,
+ pastes,
+ revealed,
trashWrites,
bundleCalls,
settingsWrites,
diff --git a/frontend/e2e/board.spec.js b/frontend/e2e/board.spec.js
new file mode 100644
index 0000000..718e5ef
--- /dev/null
+++ b/frontend/e2e/board.spec.js
@@ -0,0 +1,695 @@
+import { test, expect } from '@playwright/test';
+import { CASE_ID, installAppFixture } from './app.fixture.js';
+
+/**
+ * The board, in a real browser.
+ *
+ * This is the screen that made the hand-made vocabulary reachable at all: before
+ * it, a `claim` or a `person` could only be created through the API, so a source
+ * had nothing to be related to and a statement had nowhere to be read. A
+ * source-reading test cannot tell whether the create form actually submits or
+ * whether the row opens what it says it opens, so these run for real.
+ */
+
+const catalog = [
+ {
+ id: 'media-1',
+ type: 'media',
+ label: 'roadside photo',
+ attrs: { path: 'media/panel.svg', kind: 'image' },
+ provenance: { by: 'media-library', at: '2026-08-01T09:00:00Z', status: 'confirmed' },
+ },
+ {
+ id: 'place-1',
+ type: 'place',
+ label: 'checkpoint north',
+ attrs: { lat: 48.8584, lon: 2.2945, folder: 'Leads' },
+ provenance: { by: 'satellite', at: '2026-08-01T10:00:00Z', status: 'confirmed' },
+ },
+ {
+ id: 'bm-1',
+ type: 'bookmark',
+ label: 'harbour watch thread',
+ attrs: { url: 'https://example.test/t', reliability: 'B' },
+ provenance: { by: 'ingest', at: '2026-08-02T08:00:00Z', status: 'suggested' },
+ },
+];
+
+const claimChain = {
+ entity: {
+ id: 'e_new',
+ type: 'claim',
+ label: 'Where was this shot?',
+ attrs: {},
+ provenance: { by: 'user', at: '2026-08-03T10:00:00Z', status: 'confirmed' },
+ },
+ sources: [],
+ lost: [],
+ dependents: [],
+ relations: [],
+ empty: true,
+};
+
+async function openBoard(page, options = {}) {
+ const fixture = await installAppFixture(page, { catalog, ...options });
+ await page.goto('/#board');
+ await expect(page.getByRole('heading', { name: 'Board' })).toBeVisible();
+ return fixture;
+}
+
+/** Open one axis in the fixed + Filter menu. */
+async function openFilter(page, axis) {
+ const bar = page.locator('.filter-bar');
+ await bar.getByRole('button', { name: 'Filter', exact: true }).click();
+ await bar
+ .locator('.pop.wide')
+ .getByRole('button', { name: new RegExp(`^${axis}\\b`, 'i') })
+ .click();
+ return bar.locator('.pop').last();
+}
+
+/** Pick one value from one filter axis. */
+async function filterBy(page, axis, value) {
+ const pop = await openFilter(page, axis);
+ await pop.getByRole('button', { name: new RegExp(`^${value}\\b`, 'i') }).click();
+}
+
+/** Ask one of the ready-made questions at the top of + Filter. */
+async function ask(page, question) {
+ const bar = page.locator('.filter-bar');
+ await bar.getByRole('button', { name: 'Filter', exact: true }).click();
+ await bar
+ .locator('.pop.wide')
+ .getByRole('button', { name: new RegExp(`^${question}\\b`, 'i') })
+ .click();
+}
+
+/** The identity cell, excluding the action cell whose accessible name repeats it. */
+function entityCell(page, name) {
+ return page
+ .locator('tbody tr')
+ .filter({ has: page.locator('.name', { hasText: name }) })
+ .locator('td')
+ .first();
+}
+
+test('opens from the case it belongs to, not from the rail of stages', async ({ page }) => {
+ await installAppFixture(page, { catalog });
+ await page.goto('/#media');
+
+ // the rail is the pipeline, and the case is not one of its steps
+ const rail = page.getByRole('navigation').first();
+ await expect(rail.getByRole('button')).toHaveText(['Sources', 'Examine', 'Map', 'Compose', /Dark|Light/]);
+
+ await page.getByRole('button', { name: 'Board' }).click();
+ await expect(page.getByRole('heading', { name: 'Board' })).toBeVisible();
+ await expect(page.getByTitle('Open the case board')).toHaveClass(/topbar-active/);
+});
+
+test('lists what the case holds, whatever the type', async ({ page }) => {
+ const fixture = await openBoard(page);
+
+ await expect(entityCell(page, 'roadside photo')).toBeVisible();
+ await expect(entityCell(page, 'checkpoint north')).toBeVisible();
+ await expect(entityCell(page, 'harbour watch thread')).toBeVisible();
+ fixture.expectNoUnexpectedRequests();
+});
+
+test('filters by family, and asks the server to narrow rather than hiding rows', async ({ page }) => {
+ const fixture = await openBoard(page);
+ await expect(page.locator('tbody tr')).toHaveCount(3);
+
+ await filterBy(page, 'Family', 'Collected');
+
+ await expect(page.locator('tbody tr')).toHaveCount(1);
+ await expect(entityCell(page, 'roadside photo')).toBeVisible();
+ // the family resolved to its types on the way out: the endpoint speaks types
+ const narrowed = fixture.catalogQueries.filter((q) => q.includes('type='));
+ expect(narrowed.at(-1)).toContain('media');
+ expect(narrowed.at(-1)).toContain('capture');
+});
+
+test('filters by type inside the family', async ({ page }) => {
+ await openBoard(page);
+
+ await filterBy(page, 'Type', 'Place');
+
+ await expect(page.locator('tbody tr')).toHaveCount(1);
+ await expect(entityCell(page, 'checkpoint north')).toBeVisible();
+});
+
+test('asks which videos have coordinates, as a sentence of selects', async ({ page }) => {
+ // The question no screen could ask: `kind=video` was not expressible anywhere, and
+ // "and it has a place" was a thing the analyst read row by row. Every term chosen
+ // from what the case holds, so nothing is typed and nothing can be spelled wrong.
+ const clip = {
+ id: 'media-2',
+ type: 'media',
+ label: 'quay clip',
+ attrs: { path: 'media/quay.mp4', kind: 'video' },
+ provenance: { by: 'media-library', at: '2026-08-01T09:30:00Z', status: 'confirmed' },
+ };
+ const fixture = await openBoard(page, {
+ catalog: [...catalog, clip],
+ links: [
+ {
+ id: 'l-place',
+ from: 'media-2',
+ to: 'place-1',
+ type: 'located-at',
+ provenance: { by: 'user', at: '2026-08-02T09:00:00Z', status: 'confirmed' },
+ },
+ ],
+ });
+ await expect(page.locator('tbody tr')).toHaveCount(4);
+
+ await filterBy(page, 'Type', 'Media');
+ const field = await openFilter(page, 'Field');
+ await field.getByRole('button', { name: /^kind\b/i }).click();
+ await field.getByRole('button', { name: /^video\b/i }).click();
+
+ await expect(page.locator('tbody tr')).toHaveCount(1);
+ await expect(entityCell(page, 'quay clip')).toBeVisible();
+
+ await filterBy(page, 'Linked to', 'a place');
+
+ await expect(page.locator('tbody tr')).toHaveCount(1);
+ const asked = fixture.catalogQueries.at(-1);
+ expect(asked).toContain('attr=kind');
+ expect(asked).toContain('value=video');
+ expect(asked).toContain('linked=place');
+});
+
+test('creates a claim, which nothing else in the app can do', async ({ page }) => {
+ const fixture = await openBoard(page, { chains: { e_new: claimChain } });
+
+ await page.getByRole('button', { name: 'New entity' }).click();
+ await expect(page.getByRole('heading', { name: 'New entity' })).toBeVisible();
+ await page.getByLabel('Type').selectOption('claim');
+ await page.getByLabel('Statement').fill('Where was this shot?');
+ // the fields come from the registry, not from a form written per type
+ await page.getByLabel('How this was worked out').fill('spans counted against imagery');
+ await page.getByRole('button', { name: 'Create', exact: true }).click();
+
+ await expect.poll(() => fixture.entityWrites.length).toBe(1);
+ expect(fixture.entityWrites[0]).toMatchObject({
+ type: 'claim',
+ label: 'Where was this shot?',
+ attrs: { method: 'spans counted against imagery' },
+ });
+ // and it lands on its own Details, because a claim exists to be pointed at things
+ await expect(page.getByRole('heading', { name: 'Details' })).toBeVisible();
+ await expect(page.getByRole('dialog').getByLabel('Statement')).toHaveValue('Where was this shot?');
+});
+
+test('shows an entity’s typed fields directly in Details', async ({ page }) => {
+ const ip = {
+ id: 'ip-1',
+ type: 'ip',
+ label: '203.0.113.42',
+ attrs: {
+ network: '203.0.113.0/24',
+ asn: 'AS64496',
+ provider: 'Example Transit',
+ notes: 'Observed in the access log',
+ },
+ provenance: { by: 'user', at: '2026-08-03T10:00:00Z', status: 'confirmed' },
+ };
+ await openBoard(page, {
+ catalog: [ip],
+ chains: {
+ 'ip-1': { entity: ip, sources: [], lost: [], dependents: [], relations: [], empty: true },
+ },
+ });
+
+ await entityCell(page, '203.0.113.42').click();
+ const dialog = page.getByRole('dialog');
+ await expect(dialog.getByLabel('IP address')).toHaveValue('203.0.113.42');
+ await expect(dialog.getByText('Legacy network', { exact: true })).toBeVisible();
+ await expect(dialog.getByText('203.0.113.0/24', { exact: true })).toBeVisible();
+ await expect(dialog.getByLabel('ASN')).toHaveValue('AS64496');
+ await expect(dialog.getByLabel('Provider')).toHaveValue('Example Transit');
+ await expect(dialog.getByLabel('Notes')).toHaveValue('Observed in the access log');
+ await expect(dialog.getByRole('tab')).toHaveText(['Info', 'Connections', 'Time']);
+});
+
+test('uses a relation instead of new free text for an IP network', async ({ page }) => {
+ const fixture = await openBoard(page);
+
+ await page.getByRole('button', { name: 'New entity' }).click();
+ await page.getByLabel('Type').selectOption('ip');
+ await page.getByLabel('IP address').fill('203.0.113.42');
+ await expect(page.getByLabel('Legacy network')).toHaveCount(0);
+ await page.getByLabel('ASN').fill('AS64496');
+ await page.getByLabel('Notes').fill('Observed in the access log');
+ await page.getByRole('button', { name: 'Create', exact: true }).click();
+
+ await expect.poll(() => fixture.entityWrites.length).toBe(1);
+ expect(fixture.entityWrites[0]).toMatchObject({
+ type: 'ip',
+ label: '203.0.113.42',
+ attrs: {
+ asn: 'AS64496',
+ notes: 'Observed in the access log',
+ },
+ });
+});
+
+test('shows the plate and notes while creating a vehicle', async ({ page }) => {
+ const fixture = await openBoard(page);
+
+ await page.getByRole('button', { name: 'New entity' }).click();
+ await page.getByLabel('Type').selectOption('vehicle');
+ await page.getByLabel('Vehicle name').fill('White pickup');
+ await page.getByLabel('Plate').fill('AB-123-CD');
+ await page.getByLabel('Notes').fill('Rear-left panel damaged');
+ await page.getByRole('button', { name: 'Create', exact: true }).click();
+
+ await expect.poll(() => fixture.entityWrites.length).toBe(1);
+ expect(fixture.entityWrites[0]).toMatchObject({
+ type: 'vehicle',
+ label: 'White pickup',
+ attrs: { plate: 'AB-123-CD', notes: 'Rear-left panel damaged' },
+ });
+});
+
+test('opens a row in the same Details panel every other surface uses', async ({ page }) => {
+ await openBoard(page, {
+ chains: {
+ 'bm-1': {
+ entity: catalog[2],
+ sources: [], lost: [], dependents: [], relations: [], empty: true,
+ },
+ },
+ });
+
+ await entityCell(page, 'harbour watch thread').click();
+
+ await expect(page.getByRole('heading', { name: 'Details' })).toBeVisible();
+ await expect(page.getByRole('link', { name: 'https://example.test/t' })).toBeVisible();
+ // the source's own grade is profile information, served by the entity registry
+ await expect(page.getByLabel('Source reliability')).toHaveValue('B');
+});
+
+test('keeps Add relation and Add mention as separate gestures', async ({ page }) => {
+ const person = {
+ id: 'person-1', type: 'person', label: 'Witness A', attrs: {},
+ provenance: { by: 'user', at: '2026-08-03T09:00:00Z', status: 'confirmed' },
+ };
+ const note = {
+ id: 'note-1', type: 'note', label: 'Field notes', attrs: {},
+ provenance: { by: 'notebook', at: '2026-08-03T09:10:00Z', status: 'confirmed' },
+ };
+ const organization = {
+ id: 'org-1', type: 'organization', label: 'Harbour group', attrs: {},
+ provenance: { by: 'satellite', at: '2026-08-03T09:20:00Z', status: 'confirmed' },
+ };
+ const fixture = await openBoard(page, {
+ catalog: [person, note, organization],
+ chains: {
+ 'person-1': { entity: person, sources: [], lost: [], dependents: [], relations: [], empty: true },
+ },
+ });
+
+ await entityCell(page, 'Witness A').click();
+ const dialog = page.getByRole('dialog');
+ await dialog.getByRole('tab', { name: 'Connections' }).click();
+ await expect(dialog.getByRole('button', { name: 'Add relation' })).toBeVisible();
+ await expect(dialog.getByRole('button', { name: 'Add mention' })).toBeVisible();
+
+ await dialog.getByRole('button', { name: 'Add relation' }).click();
+ await expect(dialog.getByRole('button', { name: /Harbour group/ })).toBeVisible();
+ await expect(dialog.getByRole('button', { name: /Field notes/ })).toHaveCount(0);
+ await dialog.getByRole('button', { name: /Harbour group/ }).click();
+ await dialog.locator('.picker.composer').getByRole('button', { name: 'Add relation' }).click();
+ await expect.poll(() => fixture.linkWrites.length).toBe(1);
+ expect(fixture.linkWrites[0]).toMatchObject({
+ method: 'POST',
+ body: { from_id: 'person-1', to_id: 'org-1', type: 'owns' },
+ });
+
+ await dialog.getByRole('button', { name: 'Add mention' }).click();
+ await expect(dialog.getByRole('button', { name: /Field notes/ })).toBeVisible();
+ await expect(dialog.getByRole('button', { name: /Harbour group/ })).toHaveCount(0);
+ await dialog.getByRole('button', { name: /Field notes/ }).click();
+ await dialog.locator('.picker.composer').getByRole('button', { name: 'Add mention' }).click();
+ await expect.poll(() => fixture.linkWrites.length).toBe(2);
+ expect(fixture.linkWrites[1]).toMatchObject({
+ method: 'POST',
+ body: { from_id: 'note-1', to_id: 'person-1', type: 'mentions' },
+ });
+});
+
+test('offers IP addresses and networks through Add relation', async ({ page }) => {
+ const ip = {
+ id: 'ip-1', type: 'ip', label: '203.0.113.42', attrs: {},
+ provenance: { by: 'user', at: '2026-08-03T09:00:00Z', status: 'confirmed' },
+ };
+ const network = {
+ id: 'network-1', type: 'network', label: '203.0.113.0/24', attrs: {},
+ provenance: { by: 'user', at: '2026-08-03T09:10:00Z', status: 'confirmed' },
+ };
+ const people = Array.from({ length: 10 }, (_, index) => ({
+ id: `person-${index}`, type: 'person', label: `Person ${index}`, attrs: {},
+ provenance: { by: 'user', at: '2026-08-03T09:20:00Z', status: 'confirmed' },
+ }));
+ const fixture = await openBoard(page, {
+ catalog: [ip, ...people, network],
+ chains: {
+ 'ip-1': { entity: ip, sources: [], lost: [], dependents: [], relations: [], empty: true },
+ },
+ });
+
+ await entityCell(page, '203.0.113.42').click();
+ const dialog = page.getByRole('dialog');
+ await dialog.getByRole('tab', { name: 'Connections' }).click();
+ const add = dialog.getByRole('button', { name: 'Add relation' });
+ await expect(add).toHaveAttribute('title', /Network/);
+ await add.click();
+ await dialog.getByRole('button', { name: /203\.0\.113\.0\/24/ }).click();
+ await expect(dialog.locator('.picker.composer .verb')).toHaveText('is in network');
+ await dialog.locator('.picker.composer').getByRole('button', { name: 'Add relation' }).click();
+
+ await expect.poll(() => fixture.linkWrites.length).toBe(1);
+ expect(fixture.linkWrites[0]).toMatchObject({
+ method: 'POST',
+ body: { from_id: 'ip-1', to_id: 'network-1', type: 'in-network' },
+ });
+});
+
+test('keeps both readings when relation endpoints share a type', async ({ page }) => {
+ const parent = {
+ id: 'network-parent', type: 'network', label: '203.0.112.0/23', attrs: {},
+ provenance: { by: 'user', at: '2026-08-03T09:00:00Z', status: 'confirmed' },
+ };
+ const child = {
+ id: 'network-child', type: 'network', label: '203.0.113.0/24', attrs: {},
+ provenance: { by: 'user', at: '2026-08-03T09:10:00Z', status: 'confirmed' },
+ };
+ const fixture = await openBoard(page, {
+ catalog: [parent, child],
+ chains: {
+ 'network-parent': {
+ entity: parent, sources: [], lost: [], dependents: [], relations: [], empty: true,
+ },
+ },
+ });
+
+ await entityCell(page, '203.0.112.0/23').click();
+ const dialog = page.getByRole('dialog');
+ await dialog.getByRole('tab', { name: 'Connections' }).click();
+ const composer = dialog.locator('.picker.composer');
+ await dialog.getByRole('button', { name: 'Add relation' }).click();
+ await composer.getByRole('button', { name: /203\.0\.113\.0\/24/ }).click();
+ const reading = composer.locator('.verb-select');
+ await expect(reading.locator('option')).toHaveText(['is in network', 'contains']);
+ await reading.selectOption('in-network:in');
+ await composer.getByRole('button', { name: 'Add relation' }).click();
+
+ await expect.poll(() => fixture.linkWrites.length).toBe(1);
+ expect(fixture.linkWrites[0]).toMatchObject({
+ method: 'POST',
+ body: { from_id: 'network-child', to_id: 'network-parent', type: 'in-network' },
+ });
+});
+
+test('sorts on a heading, and reverses on a second click', async ({ page }) => {
+ await openBoard(page);
+ const names = async () =>
+ (await page.locator('tbody tr td:first-child').allInnerTexts()).map((t) => t.trim());
+
+ await page.getByRole('button', { name: 'Name' }).click();
+
+ await expect.poll(names).toEqual(['checkpoint north', 'harbour watch thread suggested', 'roadside photo']);
+ await expect(page.getByRole('columnheader', { name: 'Name' })).toHaveAttribute('aria-sort', 'ascending');
+
+ await page.getByRole('button', { name: 'Name' }).click();
+
+ await expect.poll(names).toEqual(['roadside photo', 'harbour watch thread suggested', 'checkpoint north']);
+ await expect(page.getByRole('columnheader', { name: 'Name' })).toHaveAttribute('aria-sort', 'descending');
+});
+
+test('names the analyst’s own folder the way the rest of the app does', async ({ page }) => {
+ await openBoard(page);
+
+ await expect(page.getByRole('columnheader', { name: 'Folder' })).toBeVisible();
+ await expect(page.getByTitle('the My-work folder it is filed in')).toBeVisible();
+ await expect(page.getByRole('cell', { name: 'Leads' })).toBeVisible();
+});
+
+test('sorts by type too, so a mixed case can be read a family at a time', async ({ page }) => {
+ await openBoard(page);
+
+ await page.getByRole('button', { name: 'Type' }).click();
+
+ expect(await page.locator('tbody tr td:nth-child(2)').allInnerTexts()).toEqual([
+ 'Bookmark', 'Media', 'Place',
+ ]);
+});
+
+test('shows a type’s own columns only once one type is picked', async ({ page }) => {
+ await openBoard(page);
+
+ await expect(page.getByRole('columnheader', { name: 'Source reliability' })).toHaveCount(0);
+
+ await filterBy(page, 'Type', 'Bookmark');
+
+ await expect(page.getByRole('columnheader', { name: 'Source reliability' })).toBeVisible();
+ await expect(page.getByRole('cell', { name: 'B', exact: true })).toBeVisible();
+});
+
+test('explains the vocabulary where it uses it', async ({ page }) => {
+ const statement = {
+ id: 'claim-1',
+ type: 'claim',
+ label: 'A filed statement',
+ attrs: {},
+ provenance: { by: 'user', at: '2026-08-03T09:00:00Z', status: 'confirmed' },
+ };
+ await openBoard(page, { catalog: [...catalog, statement] });
+
+ const claimReads = 'a statement about the rest of the case, carrying its own reasoning';
+ // The family menu says what its vocabulary means before it is chosen.
+ const families = await openFilter(page, 'Family');
+ await expect(families.getByTitle(claimReads)).toBeVisible();
+ await families.getByTitle(claimReads).click();
+ // And the resulting chip keeps the axis explanation reachable.
+ await expect(page.getByTitle(/the broad reading: who, what, where — click to change it/i)).toBeVisible();
+
+ // and the create menu says what the type it is about to file actually is
+ await page.getByRole('button', { name: 'New entity' }).click();
+ await page.getByLabel('Type').selectOption('claim');
+ await expect(
+ page.getByRole('dialog').getByTitle('something you are saying about the case')
+ ).toBeVisible();
+ // including on the field the registry generated for it
+ await expect(page.getByTitle('the reasoning a reader would need to check this')).toBeVisible();
+});
+
+test('asks the server when the case is larger than one page', async ({ page }) => {
+ // The bug this pins: client-side filtering is switched off in server mode, so a
+ // board that never handed the term to the list went quiet at exactly the case
+ // size that needed it — typing did nothing, with nothing said.
+ const fixture = await openBoard(page, { catalogPage: 2 });
+ await expect(page.locator('tbody tr')).toHaveCount(2);
+ await expect(page.getByText(/Showing 2 of 3/)).toBeVisible();
+
+ await page.getByPlaceholder('Search the case…').fill('harbour');
+
+ await expect(page.locator('tbody tr')).toHaveCount(1);
+ await expect(entityCell(page, 'harbour watch thread')).toBeVisible();
+ expect(fixture.catalogQueries.at(-1)).toContain('q=harbour');
+});
+
+test('autosaves a live Board view and restores its question and sort', async ({ page }) => {
+ const fixture = await openBoard(page);
+ const search = page.getByLabel('Search the case');
+ await search.fill('harbour');
+
+ await page.getByRole('button', { name: /^Views/ }).click();
+ await page.getByRole('button', { name: 'Save view' }).click();
+ const dialog = page.getByRole('dialog', { name: 'Save analysis view' });
+ await dialog.getByLabel('Name').fill('Source watch');
+ await dialog.getByRole('button', { name: 'Save', exact: true }).click();
+ await expect(page.locator('.views .active')).toContainText('live · saved');
+
+ await page.getByRole('button', { name: 'Name' }).click();
+ await expect(page.locator('.views .active')).toContainText('saving');
+ await expect.poll(
+ () => fixture.analysisWrites.at(-1)?.body?.spec?.board?.sortKey,
+ ).toBe('label');
+ await expect(page.locator('.views .active')).toContainText('saved');
+
+ await search.fill('checkpoint');
+ await expect.poll(
+ () => fixture.analysisWrites.at(-1)?.body?.spec?.query?.terms?.q,
+ ).toBe('checkpoint');
+ await page.getByRole('button', { name: 'Leave saved view' }).click();
+
+ await page.getByRole('button', { name: /^Views/ }).click();
+ await page.getByRole('button', { name: 'Source watch live · board' }).click();
+ await expect(search).toHaveValue('checkpoint');
+ await expect(page.getByRole('columnheader', { name: 'Name' })).toHaveAttribute(
+ 'aria-sort', 'ascending',
+ );
+ await expect(page.getByRole('button', { name: 'Update saved view' })).toHaveCount(0);
+});
+
+test('reads retained snapshot details in Board and leaves without a stale live dialog', async ({ page }) => {
+ const snapshot = {
+ id: 'v_board_snapshot',
+ name: 'Witness handover',
+ mode: 'snapshot',
+ surface: 'board',
+ created_at: '2026-08-10T10:00:00Z',
+ updated_at: '2026-08-10T10:00:00Z',
+ spec: {
+ version: 1,
+ query: { filter: {}, terms: {} },
+ board: { order: 'label', sortKey: 'label', sortDesc: false },
+ snapshot: {
+ captured_at: '2026-08-10T10:00:00Z',
+ entities: [
+ {
+ id: 'cap-person', type: 'person', label: 'Archived witness',
+ attrs: { role: 'observer' },
+ provenance: { by: 'analyst', at: '2026-08-10T09:58:00Z', status: 'confirmed' },
+ snapshot_images: [{
+ id: 'photo-a', title: 'Witness portrait', primary: true,
+ data: 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNk+A8AAQUBAScY42YAAAAASUVORK5CYII=',
+ }],
+ },
+ {
+ id: 'cap-group', type: 'organization', label: 'Archived group',
+ attrs: {}, provenance: {},
+ },
+ ],
+ links: [{
+ id: 'cap-link', from: 'cap-person', to: 'cap-group',
+ type: 'member-of', provenance: {},
+ }],
+ },
+ },
+ };
+ await openBoard(page, { analysisViews: [snapshot] });
+
+ await page.getByRole('button', { name: /^Views/ }).click();
+ await page.locator('.views .menu .open', { hasText: 'Witness handover' }).click();
+ await expect(page.getByLabel('Search the case')).toBeDisabled();
+ await expect(page.getByRole('button', { name: 'Add file' })).toBeDisabled();
+ await expect(page.getByRole('button', { name: 'New entity' })).toBeDisabled();
+ await expect(page.getByRole('button', { name: /Show Archived witness in the graph/ })).toHaveCount(0);
+
+ await entityCell(page, 'Archived witness').click();
+ const details = page.getByRole('dialog', { name: 'Snapshot details' });
+ await expect(details).toContainText('observer');
+ await expect(details.getByRole('img', { name: 'Witness portrait' })).toBeVisible();
+ await expect(details).toContainText('Archived group');
+ await details.getByRole('button', { name: 'Close' }).click();
+
+ await page.getByRole('button', { name: 'Leave saved view' }).click();
+ await expect(page.getByRole('dialog', { name: 'Snapshot details' })).toHaveCount(0);
+ await expect(page.getByRole('dialog', { name: 'Details', exact: true })).toHaveCount(0);
+});
+
+test('settles a proposal from the row it is read on', async ({ page }) => {
+ const fixture = await openBoard(page);
+ await ask(page, 'To review');
+ await expect(page.locator('tbody tr')).toHaveCount(1);
+
+ await page.getByTitle('Confirm this item').click();
+
+ await expect(fixture.entityWrites.at(-1)).toEqual({
+ method: 'PATCH',
+ id: 'bm-1',
+ body: { status: 'confirmed' },
+ });
+ // it leaves the Suggested filter, which is the whole point of confirming it
+ await expect(page.locator('tbody tr')).toHaveCount(0);
+});
+
+test('dismisses a proposal through the delete that can be undone', async ({ page }) => {
+ const fixture = await openBoard(page);
+
+ await page.getByTitle('Dismiss this item, recoverable from the trash').click();
+
+ expect(fixture.entityWrites.at(-1)).toMatchObject({ method: 'DELETE', id: 'bm-1' });
+ await expect(entityCell(page, 'harbour watch thread')).toHaveCount(0);
+});
+
+test('takes a file into the case and opens what it filed', async ({ page }) => {
+ // The capability existed under "Media", a word that says nothing about a scanned
+ // plan; what was missing is a way in from the screen the case is read on.
+ const fixture = await openBoard(page, {
+ chains: {
+ 'media-imported': {
+ entity: {
+ id: 'media-imported',
+ type: 'media',
+ label: 'site plan',
+ attrs: { path: 'media/site plan.pdf', kind: 'file', sha256: 'abc' },
+ provenance: { by: 'media-library', at: '2026-08-04T09:00:00Z', status: 'confirmed' },
+ },
+ sources: [], lost: [], dependents: [], relations: [], empty: true,
+ },
+ },
+ });
+
+ await page.getByRole('button', { name: 'Add file' }).click();
+ await page.locator('input[type=file]').setInputFiles({
+ name: 'site plan.pdf',
+ mimeType: 'application/pdf',
+ buffer: Buffer.from('%PDF-1.4 fixture'),
+ });
+
+ await expect.poll(() => fixture.uploads.length).toBe(1);
+ // one file opens where the analyst can say what it is
+ await expect(page.getByRole('heading', { name: 'Details' })).toBeVisible();
+ await expect(page.getByRole('dialog').getByLabel('Title')).toHaveValue('site plan');
+});
+
+test('draws a document as a document, never as a photograph', async ({ page }) => {
+ const plan = {
+ id: 'media-2',
+ type: 'media',
+ label: 'harbour plan',
+ attrs: { path: 'media/harbour plan.pdf', kind: 'file' },
+ provenance: { by: 'media-library', at: '2026-08-04T09:00:00Z', status: 'confirmed' },
+ };
+ await openBoard(page, { catalog: [catalog[0], plan] });
+ await expect(page.locator('tbody tr')).toHaveCount(2);
+
+ const icons = await page.locator('tbody tr td:first-child svg path').evaluateAll((nodes) =>
+ nodes.map((node) => node.getAttribute('d'))
+ );
+
+ // two rows, two glyphs: an image and a document, told apart by what the bytes are
+ expect(new Set(icons).size).toBe(2);
+});
+
+test('hands a document back to the desktop instead of downloading a copy', async ({ page }) => {
+ const plan = {
+ id: 'media-2',
+ type: 'media',
+ label: 'harbour plan',
+ attrs: { path: 'media/harbour plan.pdf', kind: 'file' },
+ provenance: { by: 'media-library', at: '2026-08-04T09:00:00Z', status: 'confirmed' },
+ };
+ const fixture = await openBoard(page, {
+ catalog: [plan],
+ chains: {
+ 'media-2': { entity: plan, sources: [], lost: [], dependents: [], relations: [], empty: true },
+ },
+ });
+
+ await entityCell(page, 'harbour plan').click();
+ const dialog = page.getByRole('dialog');
+
+ // no download link and no tool to send it to: neither exists for a document
+ await expect(dialog.getByRole('link', { name: 'Open file' })).toHaveCount(0);
+ await expect(dialog.getByRole('button', { name: 'Open in tool' })).toHaveCount(0);
+
+ await dialog.getByRole('button', { name: 'Show in folder' }).click();
+
+ await expect.poll(() => fixture.revealed).toEqual(['media/harbour plan.pdf']);
+});
diff --git a/frontend/e2e/entity-photos.spec.js b/frontend/e2e/entity-photos.spec.js
new file mode 100644
index 0000000..b73a867
--- /dev/null
+++ b/frontend/e2e/entity-photos.spec.js
@@ -0,0 +1,140 @@
+import { test, expect } from '@playwright/test';
+import { CASE_ID, PANEL_PATH, installAppFixture } from './app.fixture.js';
+
+const person = {
+ id: 'person-photo',
+ type: 'person',
+ label: 'Unknown subject',
+ attrs: {},
+ provenance: { by: 'user', at: '2026-08-04T09:00:00Z', status: 'confirmed' },
+};
+
+const chain = {
+ entity: person,
+ sources: [],
+ lost: [],
+ dependents: [],
+ relations: [],
+ empty: true,
+};
+
+async function openDetails(page, options = {}) {
+ const fixture = await installAppFixture(page, {
+ catalog: [person],
+ chains: { [person.id]: chain },
+ ...options,
+ });
+ await page.goto('/#board');
+ await page.getByRole('cell', { name: 'Unknown subject', exact: true }).click();
+ await expect(page.getByRole('dialog', { name: 'Details' })).toBeVisible();
+ return fixture;
+}
+
+test('imports a photo from the computer and keeps the main image bounded', async ({ page }) => {
+ const fixture = await openDetails(page, {
+ entityImageUploadResult: {
+ id: 'photo-uploaded',
+ path: PANEL_PATH,
+ title: 'portrait',
+ },
+ });
+ const details = page.getByRole('dialog', { name: 'Details' });
+
+ await expect(details.locator('.main-photo')).toHaveCount(0);
+ await details.locator('input[type=file]').setInputFiles({
+ name: 'portrait.svg',
+ mimeType: 'image/svg+xml',
+ buffer: Buffer.from('<svg xmlns="http://www.w3.org/2000/svg" width="80" height="60"/>'),
+ });
+
+ await expect(details.getByText('Primary', { exact: true })).toBeVisible();
+ const image = details.locator('.main-photo img');
+ await expect(image).toBeVisible();
+ expect((await image.boundingBox()).height).toBeLessThanOrEqual(220);
+ await expect.poll(() => fixture.galleryWrites.length).toBe(1);
+ expect(fixture.galleryWrites[0]).toEqual({
+ method: 'UPLOAD',
+ entityId: person.id,
+ imageId: 'photo-uploaded',
+ });
+ expect(fixture.uploads).toEqual([]);
+ fixture.expectNoUnexpectedRequests();
+});
+
+test('chooses an existing Media Library image without creating a relation', async ({ page }) => {
+ const fixture = await openDetails(page, {
+ media: [{
+ entity_id: 'photo-existing',
+ path: PANEL_PATH,
+ filename: 'case-photo.svg',
+ title: 'Case photo',
+ kind: 'image',
+ thumbnail: null,
+ }],
+ });
+ const details = page.getByRole('dialog', { name: 'Details' });
+
+ await details.getByRole('button', { name: 'Choose from media' }).click();
+ const picker = page.getByRole('dialog', { name: 'Choose photos' });
+ await picker.getByRole('button', { name: 'Case photo' }).click();
+ await picker.getByRole('button', { name: 'Add selected' }).click();
+
+ await expect(details.getByText('Primary', { exact: true })).toBeVisible();
+ expect(fixture.galleryWrites).toEqual([{
+ method: 'POST', entityId: person.id, mediaIds: ['photo-existing'],
+ }]);
+ expect(fixture.linkWrites).toEqual([]);
+ await expect(page.locator(`img[src="/files/${CASE_ID}/${PANEL_PATH}"]`).first()).toBeVisible();
+ fixture.expectNoUnexpectedRequests();
+});
+
+test('adds private photos while creating an entity and chooses the primary one', async ({ page }) => {
+ const created = {
+ id: 'e_new',
+ type: 'person',
+ label: 'New subject',
+ attrs: {},
+ provenance: { by: 'user', at: '2026-08-04T09:15:00Z', status: 'confirmed' },
+ };
+ const fixture = await installAppFixture(page, {
+ chains: {
+ e_new: {
+ entity: created,
+ sources: [],
+ lost: [],
+ dependents: [],
+ relations: [],
+ empty: true,
+ },
+ },
+ });
+ await page.goto('/#board');
+ await page.getByRole('button', { name: 'New entity' }).click();
+ const dialog = page.getByRole('dialog', { name: 'New entity' });
+ await dialog.getByLabel('Type').selectOption('person');
+ await dialog.getByLabel('Full name').fill('New subject');
+ await dialog.locator('input[type=file]').setInputFiles([
+ {
+ name: 'portrait one.svg',
+ mimeType: 'image/svg+xml',
+ buffer: Buffer.from('<svg xmlns="http://www.w3.org/2000/svg" width="80" height="60"/>'),
+ },
+ {
+ name: 'portrait two.svg',
+ mimeType: 'image/svg+xml',
+ buffer: Buffer.from('<svg xmlns="http://www.w3.org/2000/svg" width="80" height="60"/>'),
+ },
+ ]);
+ await dialog.getByRole('button', { name: 'Use portrait two as primary photo' }).click();
+ await dialog.getByRole('button', { name: 'Create', exact: true }).click();
+
+ await expect(page.getByRole('dialog', { name: 'Details' })).toBeVisible();
+ await expect(page.getByText('Primary', { exact: true })).toBeVisible();
+ expect(fixture.galleryWrites).toEqual([
+ { method: 'UPLOAD', entityId: 'e_new', imageId: 'photo-direct-1' },
+ { method: 'UPLOAD', entityId: 'e_new', imageId: 'photo-direct-2' },
+ { method: 'PUT', entityId: 'e_new', imageId: 'photo-direct-2' },
+ ]);
+ expect(fixture.uploads).toEqual([]);
+ fixture.expectNoUnexpectedRequests();
+});
diff --git a/frontend/e2e/graph.spec.js b/frontend/e2e/graph.spec.js
new file mode 100644
index 0000000..414692f
--- /dev/null
+++ b/frontend/e2e/graph.spec.js
@@ -0,0 +1,2088 @@
+import { test, expect } from '@playwright/test';
+import { CASE_ID, installAppFixture, GRAPH_THUMB } from './app.fixture.js';
+
+const SECOND_CASE = 'browser-test-b';
+
+function isolatedGraph(catalog) {
+ const nodes = catalog.map((entity) => ({
+ id: entity.id,
+ type: entity.type,
+ label: entity.label,
+ family: 'actor',
+ status: entity.provenance?.status ?? 'confirmed',
+ at: entity.provenance?.at ?? '2026-08-01T09:00:00Z',
+ degree: 0,
+ }));
+ return {
+ lens: 'all',
+ order: 'degree',
+ nodes,
+ links: [],
+ total: nodes.length,
+ shown: nodes.length,
+ truncated: false,
+ isolated: nodes.length,
+ pinned: 0,
+ };
+}
+
+/**
+ * The case graph, in a real browser.
+ *
+ * A source-reading test cannot tell whether a canvas drew anything. Konva resolves
+ * no CSS variable, a stage with no size draws nothing, a draggable group only drags
+ * where it has shapes, and a redraw on selection can silently throw the view back
+ * to where it started — none of which a string assertion catches. So the things
+ * that only fail in a browser run here: that the canvas has pixels, that a node can
+ * be picked, that the view stays where it was put, and that the counts the view
+ * promises are on screen.
+ */
+
+async function openGraph(page, options = {}) {
+ const fixture = await installAppFixture(page, options);
+ await page.goto('/#case/graph');
+ await expect(page.getByLabel('Lens')).toBeVisible();
+ return fixture;
+}
+
+/** Konva draws into a <canvas> it creates itself; a stage with no size makes none. */
+const canvas = (page) => page.locator('.canvas canvas').first();
+
+/**
+ * How much of the canvas has anything drawn on it, 0 to 1.
+ *
+ * The only honest way to assert on a canvas: the DOM says nothing about pixels. It
+ * is what lets a spec prove that a pan actually moved the drawing, and that a
+ * mouseover did not put it back.
+ */
+async function ink(page) {
+ return page.evaluate(() => {
+ const el = document.querySelector('.canvas canvas');
+ const ctx = el.getContext('2d');
+ const { data } = ctx.getImageData(0, 0, el.width, el.height);
+ let lit = 0;
+ for (let i = 3; i < data.length; i += 4) if (data[i] > 8) lit += 1;
+ return lit / (data.length / 4);
+ });
+}
+
+/** Keep the ink exactly as it stands, to be compared with what it becomes. */
+async function keepInk(page) {
+ await page.evaluate(() => {
+ const el = document.querySelector('.canvas canvas');
+ const { data } = el.getContext('2d').getImageData(0, 0, el.width, el.height);
+ const lit = new Uint8Array(data.length / 4);
+ for (let i = 0; i < lit.length; i += 1) lit[i] = data[i * 4 + 3] > 8 ? 1 : 0;
+ window.__ink = lit;
+ });
+}
+
+/**
+ * How much of what was drawn is no longer drawn, as a fraction of what was.
+ *
+ * The only way to ask a canvas whether the picture stayed put. Ink that appears is
+ * deliberately not counted: something arriving is the point of the gesture, and the
+ * question here is whether anything **left** the place it was in.
+ */
+async function inkLost(page) {
+ return page.evaluate(() => {
+ const el = document.querySelector('.canvas canvas');
+ const { data } = el.getContext('2d').getImageData(0, 0, el.width, el.height);
+ const before = window.__ink;
+ let was = 0;
+ let gone = 0;
+ for (let i = 0; i < before.length; i += 1) {
+ if (!before[i]) continue;
+ was += 1;
+ if (!(data[i * 4 + 3] > 8)) gone += 1;
+ }
+ return was ? gone / was : 1;
+ });
+}
+
+/**
+ * Drag across the empty space, which is most of a graph.
+ *
+ * Walked in strokes that fit inside the canvas: Firefox never delivers a pointerup
+ * released outside the window, so one long drag would leave the pan running and
+ * prove nothing about the release.
+ */
+/**
+ * Wait until the case is actually on the canvas.
+ *
+ * `openGraph` waits for the toolbar, which is in the DOM before Konva has drawn a
+ * thing. A spec that measured ink straight after it was reading whatever had
+ * landed by then, which is why it passed alone and failed in a warm suite.
+ */
+async function drawn(page) {
+ await expect.poll(() => ink(page), { timeout: 5000 }).toBeGreaterThan(0.001);
+}
+
+/**
+ * Where the canvas is, once there is a canvas to measure.
+ *
+ * Konva throws its layer away and makes a new one on every rebuild, so the element
+ * matched a moment ago can already be detached — and a detached element answers
+ * `boundingBox()` with null rather than with a size. Polled for that reason: read
+ * once, straight after the toolbar appeared, it read null on a warm suite.
+ */
+async function canvasBox(page) {
+ let box = null;
+ await expect
+ .poll(
+ async () => {
+ box = await canvas(page).boundingBox();
+ return box?.width ?? 0;
+ },
+ { timeout: 5000 },
+ )
+ .toBeGreaterThan(0);
+ return box;
+}
+
+async function panBy(page, dx, dy) {
+ const box = await canvasBox(page);
+ const strokes = Math.max(
+ 1,
+ Math.ceil(Math.max(Math.abs(dx) / (box.width * 0.55), Math.abs(dy) / (box.height * 0.55))),
+ );
+ const sx = dx / strokes;
+ const sy = dy / strokes;
+ for (let i = 0; i < strokes; i += 1) {
+ const from = {
+ x: box.x + (sx < 0 ? box.width - 20 : 20),
+ y: box.y + (sy < 0 ? box.height - 20 : 20),
+ };
+ await page.mouse.move(from.x, from.y);
+ await page.mouse.down();
+ await page.mouse.move(from.x + sx, from.y + sy, { steps: 8 });
+ await page.mouse.up();
+ }
+}
+
+test('draws the case on a sized canvas', async ({ page }) => {
+ await openGraph(page);
+ await expect(canvas(page)).toBeVisible();
+ const box = await canvasBox(page);
+ expect(box.width).toBeGreaterThan(200);
+ expect(box.height).toBeGreaterThan(150);
+ await drawn(page);
+});
+
+test('opens on the whole case and says how much of it is shown', async ({ page }) => {
+ await openGraph(page);
+ await expect(page.getByText('7 of 7')).toBeVisible();
+});
+
+test('Search+ actually narrows the graph, including a stored entity field', async ({ page }) => {
+ const fixture = await openGraph(page);
+ const bar = page.locator('.graph-tool .filter-bar');
+
+ // The plate is not in the node title. This proves the broad case index reaches a
+ // typed field and that the Graph sends the term instead of repainting the old set.
+ await bar.getByLabel('Search the case').fill('AX-904-ZT');
+ await expect(page.getByText('1 of 1')).toBeVisible();
+ await expect.poll(() => fixture.graphQueries.at(-1)?.search ?? '').toContain('q=AX-904-ZT');
+
+ await bar.getByRole('button', { name: 'Clear all' }).click();
+ await bar.getByRole('button', { name: 'Filter', exact: true }).click();
+ await bar.locator('.pop.wide').getByRole('button', { name: /^Type\b/i }).click();
+ await bar.locator('.pop').last().getByRole('button', { name: /^Vehicle\b/i }).click();
+ await expect(page.getByText('1 of 1')).toBeVisible();
+ await expect.poll(() => fixture.graphQueries.at(-1)?.search ?? '').toContain('type=vehicle');
+});
+
+test('autosaves a live analysis view, including its view-local arrangement', async ({ page }) => {
+ const fixture = await openGraph(page);
+ const bar = page.locator('.graph-tool .filter-bar');
+ await bar.getByLabel('Search the case').fill('harbour');
+
+ await page.getByRole('button', { name: /^Views/ }).click();
+ await page.getByRole('button', { name: 'Save view' }).click();
+ const dialog = page.getByRole('dialog', { name: 'Save analysis view' });
+ await dialog.getByLabel('Name').fill('Harbour accounts');
+ await dialog.getByRole('button', { name: 'Save', exact: true }).click();
+
+ await expect(page.locator('.views .active')).toContainText('Harbour accounts');
+ expect(fixture.analysisWrites.at(-1)).toMatchObject({
+ method: 'POST',
+ body: { name: 'Harbour accounts', mode: 'live', surface: 'graph' },
+ });
+ expect(fixture.analysisWrites.at(-1).body.spec.query.terms.q).toBe('harbour');
+
+ const casePinWrites = fixture.graphPinWrites.length;
+ await pick(page, '@harbourwatch');
+ await dragNode(page, await middle(page), 110, -50);
+ await expect(page.locator('.views .active')).toContainText('saving');
+ await expect.poll(
+ () => fixture.analysisWrites.at(-1)?.body?.spec?.graph?.arrangement?.length ?? 0,
+ ).toBe(1);
+ expect(fixture.analysisWrites.at(-1).body.spec.graph.arrangement[0].id).toBe('acc-1');
+ expect(fixture.graphPinWrites).toHaveLength(casePinWrites);
+ await expect(page.locator('.views .active')).toContainText('saved');
+
+ await page.getByRole('button', { name: 'Leave saved view' }).click();
+ await page.getByRole('button', { name: /^Views/ }).click();
+ await page.getByRole('button', { name: 'Harbour accounts live · graph' }).click();
+ await expect(page.getByRole('button', { name: 'Reset 1 pin' })).toBeVisible();
+ expect(fixture.graphPinWrites).toHaveLength(casePinWrites);
+
+ await pick(page, '@harbourwatch');
+ await page.locator('.panel').getByRole('button', { name: 'Hide', exact: true }).click();
+ await expect.poll(
+ () => fixture.analysisWrites.at(-1)?.body?.spec?.graph?.omitted ?? [],
+ ).toContain('acc-1');
+ await expect(page.locator('.views .active')).toContainText('saved');
+
+ await bar.getByLabel('Search the case').fill('checkpoint');
+ await expect(page.locator('.views .active')).toContainText('saving');
+ await expect.poll(
+ () => fixture.analysisWrites.at(-1)?.body?.spec?.query?.terms?.q,
+ ).toBe('checkpoint');
+ await expect(page.locator('.views .active')).toContainText('saved');
+ await expect(page.getByRole('button', { name: 'Update saved view' })).toHaveCount(0);
+});
+
+test('opens a snapshot as a frozen graph without exposing case writes', async ({ page }) => {
+ const captured = {
+ id: 'v_snapshot',
+ name: 'Morning capture',
+ mode: 'snapshot',
+ surface: 'graph',
+ created_at: '2026-08-10T10:00:00Z',
+ updated_at: '2026-08-10T10:00:00Z',
+ spec: {
+ version: 1,
+ query: { filter: { q: 'harbour' }, terms: { q: 'harbour' } },
+ graph: {
+ lens: 'all', order: 'degree', root: null, hops: 1, folder: '', families: [],
+ kept: [], expanded: [], omitted: [], collapsed: [], putAway: {},
+ },
+ snapshot: {
+ captured_at: '2026-08-10T10:00:00Z',
+ entities: [
+ {
+ id: 'cap-a', type: 'person', label: 'Captured witness',
+ attrs: { role: 'observer' },
+ provenance: { by: 'analyst', at: '2026-08-10T09:58:00Z', status: 'confirmed' },
+ snapshot_images: [{
+ id: 'photo-a', title: 'Witness portrait', primary: true,
+ data: 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNk+A8AAQUBAScY42YAAAAASUVORK5CYII=',
+ }],
+ },
+ { id: 'cap-b', type: 'organization', label: 'Captured group', attrs: {}, provenance: {} },
+ ],
+ links: [{ id: 'cap-link', from: 'cap-a', to: 'cap-b', type: 'member-of', provenance: {} }],
+ },
+ },
+ };
+ const fixture = await openGraph(page, { analysisViews: [captured] });
+
+ await page.getByRole('button', { name: /^Views/ }).click();
+ await page.locator('.views .menu .open', { hasText: 'Morning capture' }).click();
+ await expect(page.locator('.views .active')).toContainText('snapshot');
+ await expect(page.getByText('2 of 2')).toBeVisible();
+ await expect(page.locator('.graph-tool .filter-bar').getByLabel('Search the case')).toBeDisabled();
+ await expect.poll(() => fixture.graphQueries.at(-1)?.search ?? '').toContain('view=v_snapshot');
+
+ const box = await canvasBox(page);
+ await page.mouse.click(box.x + box.width / 2, box.y + box.height / 2, { button: 'right' });
+ await expect(page.getByRole('button', { name: 'New entity here' })).toHaveCount(0);
+ expect(fixture.graphPinWrites).toEqual([]);
+
+ await pick(page, 'Captured witness');
+ await expect(page.getByRole('button', { name: 'In the Board' })).toHaveCount(0);
+ await page.getByRole('button', { name: 'Captured details' }).click();
+ const details = page.getByRole('dialog', { name: 'Snapshot details' });
+ await expect(details).toContainText('Nothing here edits the case');
+ await expect(details).toContainText('observer');
+ await expect(details.getByRole('img', { name: 'Witness portrait' })).toBeVisible();
+ await expect(details).toContainText('member of');
+ await details.getByRole('button', { name: 'Close' }).click();
+
+ // A capture belongs to its source surface. Moving to Board leaves it instead of
+ // presenting a Graph snapshot as an incomplete second case. The former bug also
+ // reopened a live "Details" dialog after the frozen view had gone away.
+ await page.locator('.tabstrip').getByRole('button', { name: 'Board', exact: true }).click();
+ await expect(page.locator('.views .active')).toHaveCount(0);
+ const board = page.locator('.tool', {
+ has: page.getByRole('heading', { name: 'Board' }),
+ });
+ await expect(board.getByLabel('Search the case')).toBeEnabled();
+ await expect(page.getByRole('dialog', { name: 'Snapshot details' })).toHaveCount(0);
+ await expect(page.getByRole('dialog', { name: 'Details', exact: true })).toHaveCount(0);
+});
+
+test('rereads while mounted when the Board files an entity', async ({ page }) => {
+ const first = {
+ id: 'person-1',
+ type: 'person',
+ label: 'First witness',
+ attrs: {},
+ provenance: { by: 'user', at: '2026-08-01T09:00:00Z', status: 'confirmed' },
+ };
+ const created = {
+ id: 'e_new',
+ type: 'person',
+ label: 'Second witness',
+ attrs: {},
+ provenance: { by: 'user', at: '2026-08-03T10:00:00Z', status: 'confirmed' },
+ };
+ await openGraph(page, {
+ catalog: [first],
+ graph: ({ catalog }) => isolatedGraph(catalog),
+ chains: {
+ e_new: { entity: created, sources: [], lost: [], dependents: [], relations: [], empty: true },
+ },
+ });
+ await expect(page.getByText('1 of 1')).toBeVisible();
+
+ await page.locator('.tabstrip').getByRole('button', { name: 'Board', exact: true }).click();
+ await page.getByRole('button', { name: 'New entity' }).click();
+ await page.getByLabel('Type').selectOption('person');
+ await page.getByLabel('Full name').fill('Second witness');
+ await page.getByRole('button', { name: 'Create', exact: true }).click();
+ await page.getByRole('dialog').getByRole('button', { name: 'Close' }).click();
+
+ await page.locator('.tabstrip').getByRole('button', { name: 'Graph', exact: true }).click();
+ await expect(page.getByText('2 of 2')).toBeVisible();
+});
+
+test('keeps the new case when an older graph response arrives last', async ({ page }) => {
+ const graphA = isolatedGraph([{
+ id: 'only-a', type: 'person', label: 'Only in A',
+ provenance: { by: 'user', at: '2026-08-01T09:00:00Z', status: 'confirmed' },
+ }]);
+ const graphB = isolatedGraph([
+ {
+ id: 'first-b', type: 'person', label: 'First in B',
+ provenance: { by: 'user', at: '2026-08-01T09:00:00Z', status: 'confirmed' },
+ },
+ {
+ id: 'second-b', type: 'person', label: 'Second in B',
+ provenance: { by: 'user', at: '2026-08-01T10:00:00Z', status: 'confirmed' },
+ },
+ ]);
+ const fixture = await openGraph(page, {
+ cases: [
+ { id: CASE_ID, name: 'Case A', scratch: false, folders: [] },
+ { id: SECOND_CASE, name: 'Case B', scratch: false, folders: [] },
+ ],
+ graphs: { [CASE_ID]: graphA, [SECOND_CASE]: graphB },
+ graphDelays: { [CASE_ID]: 300 },
+ });
+ await expect.poll(() => fixture.graphQueries.some((entry) => entry.caseId === CASE_ID)).toBe(true);
+
+ await page.getByTitle('Switch case').click();
+ await page.locator('.menu .item').filter({ hasText: 'Case B' }).click();
+ await expect(page.getByTitle('Switch case')).toContainText('Case B');
+ await expect(page.getByText('2 of 2')).toBeVisible();
+
+ await page.waitForTimeout(350);
+ await expect(page.getByTitle('Switch case')).toContainText('Case B');
+ await expect(page.getByText('2 of 2')).toBeVisible();
+ await expect(page.getByText('1 of 1')).toHaveCount(0);
+});
+
+test('opens a new case whole after reading a neighbourhood in the old one', async ({ page }) => {
+ const graphB = isolatedGraph([
+ {
+ id: 'first-b', type: 'person', label: 'First in B',
+ provenance: { by: 'user', at: '2026-08-01T09:00:00Z', status: 'confirmed' },
+ },
+ {
+ id: 'second-b', type: 'person', label: 'Second in B',
+ provenance: { by: 'user', at: '2026-08-01T10:00:00Z', status: 'confirmed' },
+ },
+ ]);
+ await openGraph(page, {
+ cases: [
+ { id: CASE_ID, name: 'Case A', scratch: false, folders: [] },
+ { id: SECOND_CASE, name: 'Case B', scratch: false, folders: [] },
+ ],
+ graphs: { [SECOND_CASE]: graphB },
+ });
+ await pick(page, '3rd Battalion');
+ await page.getByRole('button', { name: /^Around this/ }).click();
+ await expect(page.getByRole('button', { name: 'Whole case' })).toBeVisible();
+
+ await page.getByTitle('Switch case').click();
+ await page.locator('.menu .item').filter({ hasText: 'Case B' }).click();
+ await expect(page.getByText('2 of 2')).toBeVisible();
+ await expect(page.getByRole('button', { name: 'Whole case' })).toHaveCount(0);
+});
+
+test('counts what nothing connects to, which the board has no column for', async ({ page }) => {
+ await openGraph(page);
+ await expect(page.getByText('2 unconnected')).toBeVisible();
+});
+
+test('names each family present, and only those', async ({ page }) => {
+ await openGraph(page);
+ const legend = page.locator('.legend');
+ await expect(legend).toContainText('actor');
+ await expect(legend).toContainText('identifier');
+ await expect(legend).toContainText('place');
+ await expect(legend).not.toContainText('claim');
+});
+
+test('explains its strokes, so a dash pattern is not decoration', async ({ page }) => {
+ await openGraph(page);
+ const legend = page.locator('.legend');
+ await expect(legend).toContainText('stated relation');
+ await expect(legend).toContainText('proposed, not confirmed');
+ // Nothing in the drawn case is a lineage edge, so that stroke is not advertised.
+ await expect(legend).not.toContainText('produced from');
+});
+
+test('hides the ordering on a case it can draw whole', async ({ page }) => {
+ // It picks which nodes survive the cut and nothing else: on a case that fits, it
+ // changed nothing on screen and read as a sort order.
+ await openGraph(page);
+ await expect(page.getByLabel('Lens')).toBeVisible();
+ await expect(page.getByLabel('Ranking')).toHaveCount(0);
+});
+
+test('offers the ordering once the case is too large to draw whole', async ({ page }) => {
+ await openGraph(page, {
+ graph: {
+ lens: 'all',
+ order: 'degree',
+ nodes: [
+ { id: 'a', type: 'person', label: 'Hub', family: 'actor', status: 'confirmed', at: '2026-08-01T09:00:00Z', degree: 0 },
+ ],
+ links: [],
+ total: 900,
+ shown: 1,
+ truncated: true,
+ isolated: 1,
+ },
+ });
+ await expect(page.getByLabel('Ranking')).toBeVisible();
+ // And the count says the case was cut, rather than presenting a slice as whole.
+ await expect(page.locator('.count em')).toContainText('most connected');
+});
+
+/** A canvas is unreachable from the keyboard, so Find is how a node is picked. */
+/** Where a node sits on screen, found through the search field rather than by eye. */
+async function nodeAt(page, name) {
+ // The toolbar mounts before the initial case read. Typing during that seam is
+ // correctly cleared when the case boundary lands, so wait for the drawing that
+ // owns the search before using it.
+ await drawn(page);
+ await page.getByLabel('Find a node').fill(name);
+ await page.locator('.found button').first().click();
+ // `jumpTo` brings the chosen node to the middle of the canvas.
+ const box = await canvasBox(page);
+ return { x: box.x + box.width / 2, y: box.y + box.height / 2 };
+}
+
+/** Right-click a node, which is where its acts are named. */
+async function openMenu(page, name) {
+ const at = await nodeAt(page, name);
+ await page.mouse.click(at.x, at.y, { button: 'right' });
+ await expect(page.locator('.menu')).toBeVisible();
+}
+
+/** Left-click a node, for the click that names the far end of a connection. */
+async function clickNode(page, name) {
+ const at = await nodeAt(page, name);
+ await page.mouse.click(at.x, at.y);
+}
+
+/**
+ * A case whose hub holds more connections of one kind than the panel lists at once.
+ *
+ * The default fixture is small on purpose, and a group that fits is a group that
+ * never asks. Built here rather than added to the fixture: it is one spec's question.
+ */
+function hubCase(count) {
+ const nodes = [
+ { id: 'org-1', type: 'organization', label: '3rd Battalion', family: 'actor', status: 'confirmed', at: '2026-08-01T09:00:00Z', degree: count },
+ ];
+ const links = [];
+ for (let i = 0; i < count; i += 1) {
+ nodes.push({ id: `veh-${i}`, type: 'vehicle', label: `BTR ${i}`, family: 'asset', status: 'confirmed', at: '2026-08-01T09:00:00Z', degree: 1 });
+ links.push({
+ id: `l-${i}`,
+ from: 'org-1',
+ to: `veh-${i}`,
+ type: 'owns',
+ provenance: { by: 'user', at: '2026-08-02T09:00:00Z', status: 'confirmed' },
+ });
+ }
+ return {
+ lens: 'all', order: 'degree', nodes, links,
+ total: nodes.length, shown: nodes.length, truncated: false,
+ expanded: [], isolated: 0, pinned: 0,
+ };
+}
+
+/**
+ * A case whose hop-1 node carries more connections than the walk reached.
+ *
+ * The default fixture's degrees match its edges exactly, so nothing there is ever
+ * out of reach — which is the one state this spec is about. Served for both graph
+ * reads, since the fixture overrides them together.
+ */
+function reachCase() {
+ return {
+ lens: 'all', order: 'degree', root: 'org-1', hops: 1,
+ nodes: [
+ { id: 'org-1', type: 'organization', label: '3rd Battalion', family: 'actor', status: 'confirmed', at: '2026-08-01T09:00:00Z', degree: 1, hop: 0 },
+ { id: 'acc-1', type: 'account', label: '@harbourwatch', family: 'identifier', status: 'confirmed', at: '2026-08-02T08:00:00Z', degree: 4, hop: 1 },
+ ],
+ links: [
+ { id: 'l-3', from: 'org-1', to: 'acc-1', type: 'owns', provenance: { by: 'user', at: '2026-08-02T09:10:00Z', status: 'confirmed' } },
+ ],
+ total: 2, shown: 2, truncated: false, expanded: [], isolated: 0, pinned: 0,
+ };
+}
+
+async function pick(page, name) {
+ // The toolbar is interactive before the initial case read has claimed the
+ // workspace. Wait for that drawing so the case reset cannot clear this query.
+ await drawn(page);
+ await page.getByLabel('Find a node').fill(name);
+ await page.locator('.found button').first().click();
+ await expect(page.locator('.panel')).toBeVisible();
+}
+
+test('a node can be found by name, which is the only way in without a mouse', async ({ page }) => {
+ await openGraph(page);
+ await pick(page, 'harbourwatch');
+ await expect(page.locator('.panel')).toContainText('@harbourwatch');
+});
+
+test('a typed name lights the drawing instead of thinning it', async ({ page }) => {
+ // Only a browser can show this one: the claim is that the picture still holds as
+ // much drawing after the search as before it. A filter would have answered the
+ // same question by removing the rest, and taken the shape the analyst was holding
+ // their place with along with it.
+ await openGraph(page);
+ await drawn(page);
+ const whole = await ink(page);
+
+ await page.getByLabel('Find a node').fill('harbour');
+ await expect(page.getByText('2 matches')).toBeVisible();
+ // Dimmed, never dropped: the far context is still on the canvas.
+ await expect.poll(() => ink(page)).toBeGreaterThan(whole * 0.85);
+
+ // Emptying the field hands the case back exactly as it was: the layout is a pure
+ // function of the payload, and a search never touched the payload.
+ await page.getByLabel('Find a node').fill('');
+ await expect(page.getByText('2 matches')).toHaveCount(0);
+ await expect.poll(() => ink(page)).toBeGreaterThan(whole * 0.98);
+});
+
+test('the list steps out of the way of the case, and comes back', async ({ page }) => {
+ // With the matches lit, the canvas is what gets read next — and the list sits on
+ // top of it, over the nodes the search just pointed at.
+ await openGraph(page);
+ await drawn(page);
+ await page.getByLabel('Find a node').fill('harbour');
+ await expect(page.locator('.found')).toBeVisible();
+
+ const box = await canvasBox(page);
+ await page.mouse.click(box.x + 20, box.y + 20);
+ await expect(page.locator('.found')).toHaveCount(0);
+ // The search itself is untouched: what is lit is what the analyst is reading.
+ await expect(page.getByLabel('Find a node')).toHaveValue('harbour');
+ await expect(page.getByText('2 matches')).toBeVisible();
+
+ await page.getByLabel('Find a node').click();
+ await expect(page.locator('.found')).toBeVisible();
+});
+
+test('Escape gives the search up whole, list and highlight together', async ({ page }) => {
+ await openGraph(page);
+ await page.getByLabel('Find a node').fill('harbour');
+ await expect(page.getByText('2 matches')).toBeVisible();
+
+ await page.keyboard.press('Escape');
+ await expect(page.getByLabel('Find a node')).toHaveValue('');
+ await expect(page.locator('.found')).toHaveCount(0);
+ await expect(page.getByText('2 matches')).toHaveCount(0);
+});
+
+test('tells a name the picture does not hold from one the case does not', async ({ page }) => {
+ await openGraph(page);
+ await drawn(page);
+ await page.getByLabel('Find a node').fill('nothing here at all');
+ await expect(page.getByText('no match drawn')).toBeVisible();
+ // A count, not a verdict: the case's own answer to the name is the list's to give.
+ await expect(canvas(page)).toBeVisible();
+});
+
+test('a node stays read while a search runs the picture', async ({ page }) => {
+ // Which of the two narrows the drawing is asserted on the source; what a browser
+ // adds is that the selection is not thrown away to settle it. A click still rings
+ // its node and opens its panel — it just stops being the question on screen.
+ await openGraph(page);
+ await pick(page, '3rd Battalion');
+ await expect(page.locator('.panel')).toContainText('3rd Battalion');
+
+ await page.getByLabel('Find a node').fill('harbour');
+ await expect(page.getByText('2 matches')).toBeVisible();
+ await expect(page.locator('.panel')).toContainText('3rd Battalion');
+});
+
+test('finds an entity the drawing does not hold, and brings it in', async ({ page }) => {
+ // A view is bounded, so on a case larger than the budget most of it is not drawn —
+ // and a search reading only the drawing answered "no such entity" for entities the
+ // case plainly holds. Nothing told "not in the case" from "not in this picture".
+ await openGraph(page);
+ await expect(page.getByText('7 of 7')).toBeVisible();
+ await page.getByRole('button', { name: /collected/ }).click();
+ await expect(page.getByText('6 of 6')).toBeVisible();
+
+ await page.getByLabel('Find a node').fill('harbour frame');
+ const row = page.locator('.found .afar');
+ await expect(row).toContainText('harbour frame');
+ await expect(row).toContainText('bring in');
+
+ // Brought in through `expand`, which keeps a named node whatever the narrowing
+ // would have done with it, and selected so it is not just somewhere on screen.
+ await row.click();
+ await expect(page.getByRole('button', { name: 'Reset view' })).toBeVisible();
+ await expect(page.locator('.panel')).toContainText('harbour frame');
+});
+
+test('the panel reads an edge as a sentence, inverse wording included', async ({ page }) => {
+ await openGraph(page);
+ await pick(page, '3rd Battalion');
+ const panel = page.locator('.panel');
+ // Outgoing reads forward, incoming reads with the registry's inverse: the unit
+ // owns the vehicle, and the person filed as "is a member of" reads back as one.
+ await expect(panel).toContainText('owns');
+ await expect(panel).toContainText('has member');
+ await expect(panel.locator('.verb').first()).not.toHaveText(/^[a-z]+-[a-z]+$/);
+});
+
+test('the panel groups connections by what they say, biggest group first', async ({ page }) => {
+ await openGraph(page);
+ await pick(page, '3rd Battalion');
+ const groups = page.locator('.panel .group');
+ // Two verbs owned by this node: it owns two things and has one member. The verb
+ // is said once over its rows rather than repeated on each of them.
+ await expect(groups).toHaveCount(2);
+ await expect(groups.nth(0)).toContainText('owns');
+ await expect(groups.nth(0)).toContainText('2');
+ await expect(groups.nth(1)).toContainText('has member');
+});
+
+test('hovering a row singles out the edge it stands for', async ({ page }) => {
+ // The row and the line are the same connection, and this is the only way to see
+ // which line a row means on a node with twelve of them. Selecting a node already
+ // lit every one of its edges and wrote every verb, so the drawing has to *narrow*
+ // to one — otherwise the answer to "which line is this row" was "all of them".
+ await openGraph(page);
+ await pick(page, '3rd Battalion');
+ await drawn(page);
+ const lit = await ink(page);
+
+ await page.locator('.panel .link-row', { hasText: 'BTR-82A 4721' }).hover();
+ await expect.poll(() => ink(page)).not.toBeCloseTo(lit, 4);
+
+ // And the node is read whole again the moment the pointer leaves the row.
+ await page.locator('.panel header').hover();
+ await expect.poll(() => ink(page)).toBeCloseTo(lit, 4);
+});
+
+test('a row is followed to the node it names', async ({ page }) => {
+ // Whether the view stayed put is asserted on the source: selecting a node changes
+ // what is lit, so the canvas measure cannot tell a pan from a new selection.
+ await openGraph(page);
+ await pick(page, '3rd Battalion');
+
+ await page.locator('.panel .link-row', { hasText: 'BTR-82A 4721' }).click();
+ await expect(page.locator('.panel header')).toContainText('BTR-82A 4721');
+ // And the connection reads back the other way round, from the vehicle's side.
+ await expect(page.locator('.panel .verb').first()).toContainText('is owned by');
+});
+
+test('a long group is asked for before it is listed', async ({ page }) => {
+ await openGraph(page, { graph: hubCase(12) });
+ await pick(page, '3rd Battalion');
+ const rows = page.locator('.panel .link-row:not(.rest)');
+ await expect(rows).toHaveCount(8);
+ await expect(page.locator('.panel .group')).toContainText('12');
+
+ await page.getByRole('button', { name: 'Show all 12' }).click();
+ await expect(rows).toHaveCount(12);
+ await expect(page.getByRole('button', { name: 'Show all 12' })).toHaveCount(0);
+});
+
+test('the panel counts the connections the drawing does not hold', async ({ page }) => {
+ // The hole this closes: the list is built from the edges on screen, so this
+ // account read as connected to nothing while the case held a connection for it.
+ await openGraph(page);
+ await expect(page.getByText('7 of 7')).toBeVisible();
+ await page.getByRole('button', { name: /collected/ }).click();
+ await expect(page.getByText('6 of 6')).toBeVisible();
+
+ await pick(page, 'harbourwatch');
+ const panel = page.locator('.panel');
+ await expect(panel).toContainText('1 more not drawn');
+ await expect(panel).not.toContainText('Nothing connects to this');
+
+ // The same switch as the one on the node, in words: the canvas answers a pointer,
+ // and the keyboard has to reach the drawing too.
+ await panel.getByRole('button', { name: /^Expand \(1\)/ }).click();
+ await expect(page.getByRole('button', { name: 'Reset view' })).toBeVisible();
+ await expect(panel).toContainText('posted');
+});
+
+test('the focus says what it is on, and offers a reach', async ({ page }) => {
+ await openGraph(page);
+ await expect(page.locator('.focus')).toHaveCount(0);
+
+ await pick(page, 'Section chief');
+ const focus = page.locator('.focus');
+ await expect(focus).toContainText('Section chief');
+ await expect(focus.getByRole('button', { name: '1', exact: true })).toHaveAttribute(
+ 'aria-pressed',
+ 'true',
+ );
+
+ // And it leaves with the node it is about.
+ await page.keyboard.press('Escape');
+ await expect(focus).toHaveCount(0);
+});
+
+test('a wider reach lights more of the case', async ({ page }) => {
+ // Only a browser can answer this: the claim is that the second ring is already in
+ // the payload, so asking for it costs no read and shows more of the same drawing.
+ // The section chief touches the battalion, which touches a vehicle and an account,
+ // which posted a frame — one node further out at each of the three reaches.
+ await openGraph(page);
+ await pick(page, 'Section chief');
+ await drawn(page);
+ const one = await ink(page);
+
+ await page.locator('.focus').getByRole('button', { name: '2', exact: true }).click();
+ await expect.poll(() => ink(page)).toBeGreaterThan(one);
+ const two = await ink(page);
+
+ await page.locator('.focus').getByRole('button', { name: '3', exact: true }).click();
+ await expect.poll(() => ink(page)).toBeGreaterThan(two);
+});
+
+test('the reach answers to the keys beside the one that fits the case', async ({ page }) => {
+ await openGraph(page);
+ await pick(page, 'Section chief');
+ const focus = page.locator('.focus');
+
+ await page.keyboard.press('3');
+ await expect(focus.getByRole('button', { name: '3', exact: true })).toHaveAttribute(
+ 'aria-pressed',
+ 'true',
+ );
+ await page.keyboard.press('1');
+ await expect(focus.getByRole('button', { name: '1', exact: true })).toHaveAttribute(
+ 'aria-pressed',
+ 'true',
+ );
+});
+
+test('the reach keys stay out of a field being typed into', async ({ page }) => {
+ await openGraph(page);
+ await pick(page, 'Section chief');
+ await page.getByLabel('Find a node').fill('2');
+ await expect(page.getByLabel('Find a node')).toHaveValue('2');
+ await expect(
+ page.locator('.focus').getByRole('button', { name: '1', exact: true }),
+ ).toHaveAttribute('aria-pressed', 'true');
+});
+
+test('only this takes the rest of the case off the screen and gives it back', async ({ page }) => {
+ // The claim a source test cannot make: that the drawing actually loses the nodes,
+ // and that switching back puts the picture where it was rather than re-arranging
+ // it. The layout is never touched, so the second measure has to match the first.
+ await openGraph(page);
+ await pick(page, 'Section chief');
+ await drawn(page);
+ const whole = await ink(page);
+
+ await page.getByRole('button', { name: 'Only this' }).click();
+ await expect.poll(() => ink(page)).toBeLessThan(whole);
+
+ await page.getByRole('button', { name: 'Only this' }).click();
+ await expect.poll(() => ink(page)).toBeCloseTo(whole, 3);
+});
+
+test('a search outranks the hiding, so its matches are not stranded', async ({ page }) => {
+ // An edge is drawn only when both ends survive, so hiding everything outside the
+ // matches would answer a search with a scatter of unconnected dots.
+ await openGraph(page);
+ await pick(page, 'Section chief');
+ await drawn(page);
+ const whole = await ink(page);
+
+ await page.getByRole('button', { name: 'Only this' }).click();
+ await expect.poll(() => ink(page)).toBeLessThan(whole);
+
+ await page.getByLabel('Find a node').fill('BTR');
+ await expect(page.getByText('1 match')).toBeVisible();
+ await expect.poll(() => ink(page)).toBeGreaterThan(whole * 0.9);
+});
+
+test('escape gives the case back before it gives the node up', async ({ page }) => {
+ await openGraph(page);
+ await pick(page, 'Section chief');
+ await page.getByRole('button', { name: 'Only this' }).click();
+ await expect(page.getByRole('button', { name: 'Only this' })).toHaveAttribute(
+ 'aria-pressed',
+ 'true',
+ );
+
+ await page.keyboard.press('Escape');
+ await expect(page.getByRole('button', { name: 'Only this' })).toHaveAttribute(
+ 'aria-pressed',
+ 'false',
+ );
+ await expect(page.locator('.panel')).toContainText('Section chief');
+
+ await page.keyboard.press('Escape');
+ await expect(page.locator('.panel')).toHaveCount(0);
+});
+
+/**
+ * A case where two equally short routes join the same two entities.
+ *
+ * The shape that matters on a real case: one place reached through two different
+ * media, which is the difference between two sources and one repeated.
+ */
+function tiedCase() {
+ const nodes = [
+ { id: 'per-1', type: 'person', label: 'Section chief', family: 'actor', status: 'confirmed', at: '2026-08-01T09:00:00Z', degree: 2 },
+ { id: 'med-1', type: 'media', label: 'first frame', family: 'collected', status: 'confirmed', at: '2026-08-01T09:30:00Z', degree: 2, kind: 'image' },
+ { id: 'med-2', type: 'media', label: 'second frame', family: 'collected', status: 'confirmed', at: '2026-08-01T09:40:00Z', degree: 2, kind: 'image' },
+ { id: 'plc-1', type: 'place', label: 'checkpoint north', family: 'place', status: 'confirmed', at: '2026-08-02T09:00:00Z', degree: 2 },
+ ];
+ const links = [
+ { id: 'l-1', from: 'med-1', to: 'per-1', type: 'depicts', provenance: { by: 'user', at: '2026-08-02T09:00:00Z', status: 'confirmed' } },
+ { id: 'l-2', from: 'med-2', to: 'per-1', type: 'depicts', provenance: { by: 'user', at: '2026-08-02T09:01:00Z', status: 'confirmed' } },
+ { id: 'l-3', from: 'med-1', to: 'plc-1', type: 'located-at', provenance: { by: 'user', at: '2026-08-02T09:02:00Z', status: 'confirmed' } },
+ { id: 'l-4', from: 'med-2', to: 'plc-1', type: 'located-at', provenance: { by: 'user', at: '2026-08-02T09:03:00Z', status: 'confirmed' } },
+ ];
+ return {
+ lens: 'all', order: 'degree', nodes, links,
+ total: 4, shown: 4, truncated: false, expanded: [], isolated: 0, pinned: 0,
+ };
+}
+
+/** Arm the hand-walk on a node, which becomes its first step. */
+async function trace(page, name) {
+ await openMenu(page, name);
+ await page.getByRole('button', { name: 'Walk by hand' }).click();
+ await expect(page.locator('.walk')).toBeVisible();
+}
+
+/** Arm the question on a node, and wait for the other end to be named. */
+async function askFrom(page, name) {
+ await pick(page, name);
+ await page.getByRole('button', { name: 'Path to…' }).click();
+ await expect(page.locator('.walk')).toContainText('click the other end');
+}
+
+const steps = (page) => page.locator('.said-path .node');
+
+test('a path is walked one connection at a time', async ({ page }) => {
+ await openGraph(page);
+ await trace(page, 'Section chief');
+ await expect(steps(page)).toHaveCount(1);
+ await expect(page.locator('.walk')).toContainText('Click a lit node');
+
+ // The rows of the panel are neighbours of the node the path ends on, so each one
+ // is a legal step — and it is what makes the walk reachable without a mouse.
+ await page.locator('.panel .link-row', { hasText: '3rd Battalion' }).click();
+ await expect(steps(page)).toHaveCount(2);
+ await expect(page.locator('.walk')).toContainText('1 hop');
+
+ await page.locator('.panel .link-row', { hasText: 'BTR-82A 4721' }).click();
+ await expect(steps(page)).toHaveCount(3);
+ await expect(page.locator('.walk')).toContainText('2 hops');
+});
+
+test('the sentence names the verb of each step, the way the case states it', async ({ page }) => {
+ // A drawing says these are joined; a sentence says what the joining is. And the
+ // battalion owns the vehicle, where the person is a member of the battalion — so
+ // walking from the battalion to the person reads against the arrow.
+ await openGraph(page);
+ await trace(page, '3rd Battalion');
+ await page.locator('.panel .link-row', { hasText: 'BTR-82A 4721' }).click();
+ await expect(page.locator('.said-path .verb')).toContainText('owns');
+
+ // Walked the other way, the same edge takes the registry's inverse wording, so the
+ // sentence still reads left to right. Written as the plain verb with a reversed
+ // arrow it read "A <- made from B", which has to be walked backwards to be
+ // understood — and every step of a long path compounds that.
+ await page.getByRole('button', { name: 'Give the walk up (Esc)' }).click();
+ await trace(page, '3rd Battalion');
+ await page.locator('.panel .link-row', { hasText: 'Section chief' }).click();
+ await expect(page.locator('.said-path .verb')).toContainText('has member');
+});
+
+test('a node the path cannot reach is not offered as a step', async ({ page }) => {
+ // The whole reason the gesture is armed: unarmed, a click on a non-neighbour has
+ // only bad answers. Armed, no such click exists — the vehicle is two hops from the
+ // section chief, so nothing on screen offers it and the empty space does nothing.
+ await openGraph(page);
+ await trace(page, 'Section chief');
+ const rows = page.locator('.panel .link-row');
+ await expect(rows).toHaveCount(1);
+ await expect(rows).toContainText('3rd Battalion');
+
+ const box = await canvasBox(page);
+ await page.mouse.click(box.x + 12, box.y + box.height - 12);
+ await expect(steps(page)).toHaveCount(1);
+ await expect(page.locator('.walk')).toContainText('Click a lit node');
+});
+
+test('a step already taken is walked back onto rather than looped through', async ({ page }) => {
+ await openGraph(page);
+ await trace(page, 'Section chief');
+ await page.locator('.panel .link-row', { hasText: '3rd Battalion' }).click();
+ await page.locator('.panel .link-row', { hasText: 'BTR-82A 4721' }).click();
+ await expect(steps(page)).toHaveCount(3);
+
+ // The way back is on the sentence, where the path is already being read.
+ await page.locator('.said-path .node', { hasText: '3rd Battalion' }).click();
+ await expect(steps(page)).toHaveCount(2);
+ await expect(page.locator('.said-path')).not.toContainText('BTR-82A 4721');
+});
+
+test('the walk narrows the drawing to itself and what it can reach', async ({ page }) => {
+ await openGraph(page);
+ await pick(page, 'Section chief');
+ await drawn(page);
+ const before = await ink(page);
+
+ await page.getByRole('button', { name: 'Path to…' }).click();
+ await page.locator('.panel .link-row', { hasText: '3rd Battalion' }).click();
+ await expect.poll(() => ink(page)).not.toBeCloseTo(before, 4);
+
+ // And the case comes back whole when the walk is given up.
+ await page.keyboard.press('Escape');
+ await expect(page.locator('.walk')).toHaveCount(0);
+ await expect(page.locator('.focus')).toBeVisible();
+});
+
+test('escape gives the walk up whole, as it drops a half-drawn relation', async ({ page }) => {
+ // Keeping the steps taken would leave a path on screen that nothing is building.
+ await openGraph(page);
+ await trace(page, 'Section chief');
+ await page.locator('.panel .link-row', { hasText: '3rd Battalion' }).click();
+ await expect(steps(page)).toHaveCount(2);
+
+ await page.keyboard.press('Escape');
+ await expect(page.locator('.walk')).toHaveCount(0);
+ await expect(page.locator('.said-path')).toHaveCount(0);
+});
+
+test('two nodes are named and the case finds the way between them', async ({ page }) => {
+ // The question the tool existed without, and the common one: the section chief
+ // reaches the frame in three hops, through the battalion and the account it owns.
+ // The far end is clicked here, which is the case a search cannot cover on a small
+ // view and the one an analyst reaches for first.
+ // Named rather than clicked here: the helper that finds a node on the canvas goes
+ // through the search, which an armed question rightly consumes as the answer. That
+ // a canvas click means the same thing is carried by the source test.
+ await openGraph(page);
+ await askFrom(page, 'Section chief');
+ await page.getByLabel('Find a node').fill('harbour frame');
+ await page.locator('.found button').first().click();
+
+ await expect(steps(page)).toHaveCount(4);
+ await expect(page.locator('.walk')).toContainText('3 hops');
+ await expect(page.locator('.said-path')).toContainText('@harbourwatch');
+ // And an answered route is walked back through like a hand-walked one, which is
+ // what makes it a place to keep working rather than a result.
+ await page.locator('.said-path .node', { hasText: '3rd Battalion' }).click();
+ await expect(steps(page)).toHaveCount(2);
+});
+
+test('a panel row names the other end, so the question is not mouse-only', async ({ page }) => {
+ // An armed gesture owns every way of pointing at a node, or the keyboard is left
+ // out of the one act a canvas cannot offer it.
+ await openGraph(page);
+ await askFrom(page, 'Section chief');
+ await page.locator('.panel .link-row', { hasText: '3rd Battalion' }).click();
+
+ await expect(steps(page)).toHaveCount(2);
+ await expect(page.locator('.walk')).toContainText('1 hop');
+});
+
+test('no route is an answer rather than a silence', async ({ page }) => {
+ // Learning that two entities are not connected is a finding about the case, and
+ // the only one nothing else in the tool reports.
+ await openGraph(page);
+ await askFrom(page, 'Section chief');
+ await page.getByLabel('Find a node').fill('nothing.test');
+ await page.locator('.found button').first().click();
+
+ await expect(page.locator('.said')).toContainText('No route to that one');
+ await expect(page.locator('.said-path')).toHaveCount(0);
+});
+
+test('an armed question leaves the whole case pressable', async ({ page }) => {
+ // Only a browser can catch this one. The question is armed on a selected node, so
+ // the focus fade was still on: the drawing said "only these five can be pressed"
+ // over a strip saying click anything. Every node is a legal answer here, because
+ // the case is searched rather than the drawing.
+ // Measured either side of the arming and not against the untouched case: picking
+ // the node pans the view to it, so the two are not the same drawing.
+ await openGraph(page);
+ await drawn(page);
+ await pick(page, 'Section chief');
+ const faded = await ink(page);
+
+ await page.getByRole('button', { name: 'Path to…' }).click();
+ await expect.poll(() => ink(page)).toBeGreaterThan(faded);
+});
+
+test('an armed question is given up before a route already drawn', async ({ page }) => {
+ await openGraph(page);
+ await askFrom(page, 'Section chief');
+ await page.keyboard.press('Escape');
+ await expect(page.locator('.walk')).toHaveCount(0);
+ await expect(page.locator('.focus')).toBeVisible();
+});
+
+test('every route that ties for shortest is drawn, and one is read at a time', async ({ page }) => {
+ // Two accounts reaching the same place through two different sources is what
+ // independence looks like on a real case, so an answer that drew one of them would
+ // hide the finding. The sentence takes them one at a time; the drawing takes all.
+ await openGraph(page, { graph: tiedCase() });
+ await askFrom(page, 'Section chief');
+ await page.getByLabel('Find a node').fill('checkpoint north');
+ await page.locator('.found button').first().click();
+
+ await expect(page.locator('.walk .of')).toContainText('1 / 2');
+ const first = await page.locator('.said-path').innerText();
+
+ await page.getByRole('button', { name: 'The next equally short route' }).click();
+ await expect(page.locator('.walk .of')).toContainText('2 / 2');
+ expect(await page.locator('.said-path').innerText()).not.toBe(first);
+});
+
+test('the focus is not offered on the root of a neighbourhood', async ({ page }) => {
+ // Asking for three hops and being handed a control that greys out two of them
+ // contradicts the question the view was opened on.
+ await openGraph(page);
+ await pick(page, '3rd Battalion');
+ await page.getByRole('button', { name: /^Around this/ }).click();
+ await expect(page.getByLabel('Hops')).toBeVisible();
+ await expect(page.locator('.focus')).toHaveCount(0);
+});
+
+test('a neighbourhood says how to reach further rather than offering an expansion', async ({
+ page,
+}) => {
+ // The read behind "Around this" takes no `expand`, so an expansion there is a
+ // control that can only appear to do nothing. Hops is the act, and the count says so.
+ await openGraph(page, { graph: reachCase() });
+ await pick(page, '3rd Battalion');
+ await page.getByRole('button', { name: /Around this/ }).click();
+ await expect(page.getByLabel('Hops')).toBeVisible();
+
+ await pick(page, 'harbourwatch');
+ const panel = page.locator('.panel');
+ await expect(panel).toContainText('further than 1 hop');
+ await expect(panel.getByRole('button', { name: /^Expand/ })).toHaveCount(0);
+});
+
+test('a proposed entity is marked as proposed here too', async ({ page }) => {
+ await openGraph(page);
+ await pick(page, 'harbourwatch');
+ await expect(page.locator('.panel')).toContainText('proposed');
+});
+
+test('Escape puts the case back without a reload', async ({ page }) => {
+ await openGraph(page);
+ await pick(page, '3rd Battalion');
+
+ await page.keyboard.press('Escape');
+ await expect(page.locator('.panel')).toHaveCount(0);
+ await expect(canvas(page)).toBeVisible();
+});
+
+test('the empty space pans the drawing', async ({ page }) => {
+ // The bug this guards: a draggable Konva group only drags where the pointer hits
+ // one of its own shapes, so the empty space did nothing and the canvas could only
+ // be moved by grabbing a node.
+ await openGraph(page);
+ await drawn(page);
+ const before = await ink(page);
+
+ await panBy(page, 900, 620);
+ const after = await ink(page);
+ expect(after).toBeLessThan(before / 2);
+});
+
+test('a mouseover does not throw the view back to where it started', async ({ page }) => {
+ // The teleport this guards: `rebuild` ends in `restyle`, which reads the hover,
+ // so the rebuild effect tracked it and every mouseover reset the transform.
+ await openGraph(page);
+ await drawn(page);
+ await panBy(page, 900, 620);
+ const parked = await ink(page);
+
+ const box = await canvasBox(page);
+ for (const at of [0.3, 0.5, 0.7]) {
+ await page.mouse.move(box.x + box.width * at, box.y + box.height * at);
+ }
+ expect(Math.abs((await ink(page)) - parked)).toBeLessThan(0.01);
+});
+
+test('a lens with nothing to draw still shows every node', async ({ page }) => {
+ // Narrowing the verbs must not hide entities: a node with no edge in this lens
+ // is an answer, not an omission.
+ await openGraph(page);
+ await page.getByLabel('Lens').selectOption('ground');
+ await expect(page.getByText('7 unconnected')).toBeVisible();
+ await expect(canvas(page)).toBeVisible();
+});
+
+test('expanding switches to the neighbourhood and offers the way back', async ({ page }) => {
+ await openGraph(page);
+ await pick(page, '3rd Battalion');
+ await page.getByRole('button', { name: /^Around this/ }).click();
+
+ await expect(page.getByRole('button', { name: 'Whole case' })).toBeVisible();
+ await expect(page.getByText(/around this/)).toBeVisible();
+
+ await page.getByRole('button', { name: 'Whole case' }).click();
+ await expect(page.getByText('7 of 7')).toBeVisible();
+});
+
+test('the zoom controls act on the drawing rather than the page', async ({ page }) => {
+ await openGraph(page);
+ // Measured on the pane, not on the <canvas>: Konva replaces that element whenever
+ // it rebuilds the scene, so reading it can land between two layers and find none.
+ const pane = page.locator('.canvas-row > .canvas');
+ const before = await pane.boundingBox();
+ await page.getByTitle('Zoom in (+)').click();
+ await page.getByTitle('Fit everything on screen (0)').click();
+ const after = await pane.boundingBox();
+ // The canvas fills its pane whatever the zoom: zooming must not resize the page.
+ // Judged in whole pixels, since what this would catch is the toolbar wrapping to
+ // a second line and taking thirty of them off the drawing.
+ expect(Math.abs(after.width - before.width)).toBeLessThan(2);
+ expect(Math.abs(after.height - before.height)).toBeLessThan(2);
+});
+
+test('says where the zoom is, and gets back to the whole case', async ({ page }) => {
+ await openGraph(page);
+ const level = page.locator('.level');
+ const opened = await level.textContent();
+ await page.getByTitle('Zoom in (+)').click();
+ await expect(level).not.toHaveText(opened);
+ await page.getByTitle('Fit everything on screen (0)').click();
+ await expect(level).toHaveText(opened);
+});
+
+test('a node close up becomes a card with the preview the case already holds', async ({ page }) => {
+ // The card is drawn on canvas, so what proves it is the request for the picture:
+ // the thumbnail the Media Library uses, never the media file itself.
+ await openGraph(page);
+ const asked = page.waitForRequest((request) => request.url().includes(GRAPH_THUMB));
+ for (let i = 0; i < 6; i += 1) await page.getByTitle('Zoom in (+)').click();
+ await asked;
+ await expect(page.locator('.level')).toContainText(/1[2-9]\d%|[2-9]\d\d%/);
+});
+
+test('the hover card shows the full label, the type and the preview', async ({ page }) => {
+ await openGraph(page);
+ await pick(page, 'harbour frame');
+ // The selection puts the node under the eye; hovering it is what names it.
+ const box = await canvasBox(page);
+ await page.mouse.move(box.x + box.width / 2, box.y + box.height / 2);
+ const tip = page.locator('.tip');
+ await expect(tip).toContainText('harbour frame');
+ await expect(tip).toContainText('connection');
+ await expect(tip.locator('img')).toHaveAttribute('src', new RegExp(GRAPH_THUMB));
+});
+
+/**
+ * Arranging the case by hand.
+ *
+ * Every one of these only fails in a browser: whether Konva's own drag reaches a
+ * shape inside a scaled group, whether the press that starts it also pans the
+ * canvas, and whether the spot survives the round trip through the case. Picking a
+ * node first is what makes the geometry knowable — Find centres it, so the middle of
+ * the canvas is where that node is.
+ */
+const middle = async (page) => {
+ const box = await canvasBox(page);
+ return { x: box.x + box.width / 2, y: box.y + box.height / 2 };
+};
+
+/** Drag whatever is at `from` to `from + delta`, past the slop a click tolerates. */
+async function dragNode(page, from, dx, dy) {
+ await page.mouse.move(from.x, from.y);
+ await page.mouse.down();
+ await page.mouse.move(from.x + dx / 2, from.y + dy / 2, { steps: 5 });
+ await page.mouse.move(from.x + dx, from.y + dy, { steps: 5 });
+ await page.mouse.up();
+}
+
+/** Leave and come back, so a node already under a still pointer names itself. */
+async function hover(page, at) {
+ await page.mouse.move(at.x, at.y - 140);
+ await page.mouse.move(at.x, at.y);
+}
+
+test('a node can be dragged, and the case remembers where', async ({ page }) => {
+ await openGraph(page);
+ await pick(page, 'BTR-82A 4721');
+ const from = await middle(page);
+
+ await dragNode(page, from, 150, -70);
+
+ // It went where it was put: the tooltip is the only thing that can say a canvas
+ // node is at a screen position.
+ await hover(page, { x: from.x + 150, y: from.y - 70 });
+ await expect(page.locator('.tip')).toContainText('BTR-82A 4721');
+ await expect(page.getByRole('button', { name: /Reset 1 pin/ })).toBeVisible();
+
+ // And it survives being read back: the lens change reloads the whole view.
+ await page.getByLabel('Lens').selectOption('ground');
+ await page.getByLabel('Lens').selectOption('all');
+ await expect(page.getByRole('button', { name: /Reset 1 pin/ })).toBeVisible();
+ await pick(page, 'BTR-82A 4721');
+ await expect(page.locator('.panel')).toContainText('You placed this one.');
+});
+
+test('files a pending drag in the case where it happened', async ({ page }) => {
+ const fixture = await openGraph(page, {
+ cases: [
+ { id: CASE_ID, name: 'Case A', scratch: false, folders: [] },
+ { id: SECOND_CASE, name: 'Case B', scratch: false, folders: [] },
+ ],
+ });
+ await pick(page, 'BTR-82A 4721');
+ await dragNode(page, await middle(page), 100, -50);
+ // The debounce is still holding the move; the case switch is what flushes it.
+ expect(fixture.graphPinWrites).toHaveLength(0);
+
+ await page.getByTitle('Switch case').click();
+ await page.locator('.menu .item').filter({ hasText: 'Case B' }).click();
+ await expect(page.getByTitle('Switch case')).toContainText('Case B');
+ await expect.poll(() => fixture.graphPinWrites.length).toBe(1);
+ expect(fixture.graphPinWrites[0]).toMatchObject({
+ caseId: CASE_ID,
+ body: { lens: 'all', pins: [{ id: 'veh-1' }] },
+ });
+});
+
+test('dragging a node does not also select it, nor pan the case', async ({ page }) => {
+ await openGraph(page);
+ await pick(page, 'BTR-82A 4721');
+ const from = await middle(page);
+ await page.keyboard.press('Escape');
+ await expect(page.locator('.panel')).toHaveCount(0);
+
+ await dragNode(page, from, 120, 60);
+
+ // The click that ends a drag must not open the panel — and the press must not have
+ // reached the container's pan, which would move the node and the case at once.
+ await expect(page.locator('.panel')).toHaveCount(0);
+ await hover(page, { x: from.x + 120, y: from.y + 60 });
+ await expect(page.locator('.tip')).toContainText('BTR-82A 4721');
+});
+
+test('a node is still selectable after the case has been panned', async ({ page }) => {
+ // The bug this guards: a node's press is stopped from reaching the container so it
+ // does not also pan, and the container's handler is what clears the "this click
+ // ended a pan" flag. Left set, it swallowed every later click on a node.
+ await openGraph(page);
+ await pick(page, 'BTR-82A 4721');
+ const from = await middle(page);
+ await page.keyboard.press('Escape');
+ await panBy(page, 60, 40);
+
+ await page.mouse.click(from.x + 60, from.y + 40);
+
+ await expect(page.locator('.panel')).toContainText('BTR-82A 4721');
+});
+
+test('one node can be handed back, and so can the whole arrangement', async ({ page }) => {
+ await openGraph(page);
+ await pick(page, 'BTR-82A 4721');
+ await dragNode(page, await middle(page), 140, -60);
+ await pick(page, 'BTR-82A 4721');
+
+ await page.getByRole('button', { name: 'Let it go' }).click();
+ await expect(page.getByRole('button', { name: /Reset .* pin/ })).toHaveCount(0);
+
+ // And the toolbar drops every pin at once, which is the way out of an autosave.
+ await pick(page, 'Section chief');
+ await dragNode(page, await middle(page), -130, 80);
+ await page.getByRole('button', { name: /Reset 1 pin/ }).click();
+ await expect(page.getByRole('button', { name: /Reset .* pin/ })).toHaveCount(0);
+});
+
+test('ctrl-click gathers a handful and one drag moves all of it', async ({ page }) => {
+ await openGraph(page);
+ // Two nodes, each brought under the eye in turn so its screen position is known.
+ await pick(page, 'BTR-82A 4721');
+ const centre = await middle(page);
+ await page.keyboard.press('Escape');
+ // Move the first one off the middle, then gather both.
+ await dragNode(page, centre, -180, 120);
+ const first = { x: centre.x - 180, y: centre.y + 120 };
+ await page.keyboard.down('Control');
+ await page.mouse.click(first.x, first.y);
+ await page.keyboard.up('Control');
+ await expect(page.getByRole('button', { name: /1 held/ })).toBeVisible();
+
+ await pick(page, 'Section chief');
+ const second = await middle(page);
+ await page.keyboard.down('Control');
+ await page.mouse.click(second.x, second.y);
+ await page.keyboard.up('Control');
+ await expect(page.getByRole('button', { name: /2 held/ })).toBeVisible();
+
+ // Dragging one of them files both: two pins from one gesture is the whole point.
+ await dragNode(page, second, 100, -60);
+
+ await hover(page, { x: second.x + 100, y: second.y - 60 });
+ await expect(page.locator('.tip')).toContainText('Section chief');
+ await expect(page.getByRole('button', { name: /Reset 2 pins/ })).toBeVisible();
+});
+
+test('a handful is let go without touching the arrangement', async ({ page }) => {
+ await openGraph(page);
+ await pick(page, 'BTR-82A 4721');
+ const centre = await middle(page);
+ await page.keyboard.down('Control');
+ await page.mouse.click(centre.x, centre.y);
+ await page.keyboard.up('Control');
+ await expect(page.getByRole('button', { name: /1 held/ })).toBeVisible();
+
+ await page.keyboard.press('Escape');
+
+ await expect(page.getByRole('button', { name: /held/ })).toHaveCount(0);
+ // Escape released the handful, not the selection: the shallower thing goes first.
+ await expect(page.locator('.panel')).toContainText('BTR-82A 4721');
+});
+
+test('each lens keeps its own arrangement', async ({ page }) => {
+ // A lens draws its own nodes and edges and clusters them its own way, so an
+ // arrangement built in one must not anchor the reading in another.
+ await openGraph(page);
+ await pick(page, 'BTR-82A 4721');
+ await dragNode(page, await middle(page), 130, -80);
+ await expect(page.getByRole('button', { name: /Reset 1 pin/ })).toBeVisible();
+
+ await page.getByLabel('Lens').selectOption('subjects');
+
+ await expect(page.getByRole('button', { name: /Reset .* pin/ })).toHaveCount(0);
+ await page.getByLabel('Lens').selectOption('all');
+ await expect(page.getByRole('button', { name: /Reset 1 pin/ })).toBeVisible();
+});
+
+test('the arrangement is reachable from the keyboard, which a canvas is not', async ({ page }) => {
+ await openGraph(page);
+ await pick(page, 'Section chief');
+
+ await page.keyboard.press('ArrowRight');
+ await page.keyboard.press('ArrowDown');
+
+ await expect(page.getByRole('button', { name: /Reset 1 pin/ })).toBeVisible();
+});
+
+test('typing in Find drives the field, not the drawing', async ({ page }) => {
+ // The guard this covers: window-level keys meant for the canvas used to fire while
+ // the search field had focus, so an arrow key moved a node instead of the cursor.
+ await openGraph(page);
+ await pick(page, 'Section chief');
+ await page.getByLabel('Find a node').fill('BTR');
+ await page.getByLabel('Find a node').press('ArrowRight');
+
+ await expect(page.getByRole('button', { name: /Reset .* pin/ })).toHaveCount(0);
+});
+
+test('a neighbourhood is not arranged by hand, since its axis means something', async ({ page }) => {
+ await openGraph(page);
+ await pick(page, '3rd Battalion');
+ await page.getByRole('button', { name: /^Around this/ }).click();
+ await expect(page.getByRole('button', { name: 'Whole case' })).toBeVisible();
+
+ // Scoped to the drawing surface: the workspace's own <main> carries that class too.
+ await expect(page.locator('.canvas-row > .canvas')).not.toHaveClass(/arrangeable/);
+});
+
+test('a media node says what it holds, not just that it is media', async ({ page }) => {
+ await openGraph(page);
+ await pick(page, 'harbour frame');
+
+ // The panel and the tooltip both name the bytes: one `media` type covers images,
+ // video and audio, so "Media" answers a question nobody asked.
+ await expect(page.locator('.panel')).toContainText('Image');
+ const box = await canvasBox(page);
+ await page.mouse.move(box.x + box.width / 2, box.y + box.height / 2);
+ await expect(page.locator('.tip')).toContainText('Image');
+});
+
+test('previews can be turned off, and then nothing asks for a picture', async ({ page }) => {
+ await openGraph(page);
+ const asked = [];
+ page.on('request', (request) => {
+ if (request.url().includes(GRAPH_THUMB)) asked.push(request.url());
+ });
+
+ await page.getByLabel('Preview').uncheck();
+ // Close enough for cards, which is the only zoom that ever wants a thumbnail.
+ for (let i = 0; i < 6; i += 1) await page.getByTitle('Zoom in (+)').click();
+ await page.waitForTimeout(300);
+ expect(asked).toEqual([]);
+
+ // And back on, the picture the case already holds is asked for.
+ const wanted = page.waitForRequest((request) => request.url().includes(GRAPH_THUMB));
+ await page.getByLabel('Preview').check();
+ await wanted;
+});
+
+test('says so when the case is empty rather than drawing nothing in silence', async ({ page }) => {
+ await openGraph(page, {
+ graph: { lens: 'all', order: 'degree', nodes: [], links: [], total: 0, shown: 0, truncated: false, isolated: 0 },
+ });
+ await expect(page.getByText(/Nothing here yet/)).toBeVisible();
+});
+
+// -- an edge that stands for several -----------------------------------------
+
+/**
+ * The drawing after a collapse, as `engine/graph.view` answers it: the three bookmarks
+ * are the edge now. Handed to the tool rather than folded here — the fold itself is
+ * proven in `tests/test_graph.py`, and a fixture that reimplemented it would prove the
+ * reimplementation.
+ */
+const foldedCase = {
+ lens: 'all',
+ order: 'degree',
+ nodes: [
+ { id: 'clm-1', type: 'claim', label: 'Shot at the quay', family: 'claim', status: 'confirmed', at: '2026-08-01T09:00:00Z', degree: 1, rests: { sources: 3, accounts: 1, one: true } },
+ { id: 'acc-9', type: 'account', label: '@harbourwatch', family: 'identifier', status: 'confirmed', at: '2026-08-01T09:10:00Z', degree: 1 },
+ ],
+ links: [
+ {
+ id: 'folded:cites:clm-1:acc-9',
+ from: 'clm-1',
+ to: 'acc-9',
+ type: 'cites',
+ folded: { sources: 3, via: ['bookmark'], accounts: 1, open: ['bm-1', 'bm-2', 'bm-3'] },
+ provenance: { by: 'graph', at: '2026-08-02T09:00:00Z', status: 'confirmed' },
+ },
+ ],
+ total: 2,
+ shown: 2,
+ truncated: false,
+ isolated: 0,
+ single_account: 1,
+};
+
+/**
+ * Click the one edge of a two-node drawing.
+ *
+ * The view opens fitted, and with two nodes the fit centres their bounding box — whose
+ * centre is the midpoint of the segment between them. So the middle of the canvas is
+ * the line, which is also the only thing there: the nodes are at the two ends.
+ */
+async function clickTheEdge(page) {
+ const box = await canvasBox(page);
+ await page.mouse.click(box.x + box.width / 2, box.y + box.height / 2);
+ await expect(page.locator('.panel')).toBeVisible();
+}
+
+test('an edge that folded three citations says so and hands them back', async ({ page }) => {
+ // The finding the case could not state: three citations are not three sources when
+ // one account published all three.
+ const fixture = await openGraph(page, { graph: foldedCase });
+ await drawn(page);
+
+ await expect(page.getByText('1 on one account')).toBeVisible();
+
+ // The edge is read before anything moves the view: picking a node recentres on it,
+ // and the middle of the canvas is the line only while the drawing sits as it opened.
+ await clickTheEdge(page);
+ await expect(page.locator('.panel')).toContainText('3 bookmarks · 1 account, drawn as one edge');
+ // Nothing may be written to it: the case has no such row, so the panel offers no act
+ // it would then refuse.
+ await expect(page.getByRole('button', { name: 'Remove' })).toHaveCount(0);
+ await expect(page.getByRole('button', { name: 'Confirm' })).toHaveCount(0);
+
+ // And it hands back what it stands for through the one mechanism for it: named, not
+ // opened, so a source arrives as itself rather than with everything else it touches.
+ const asked = page.waitForRequest((request) => request.url().includes('keep=bm-1'));
+ await page.getByRole('button', { name: 'Show the 3 sources' }).click();
+ await asked;
+ expect(fixture.linkWrites).toEqual([]);
+
+ // The statement says the same thing in words, where it is read.
+ await pick(page, 'Shot at the quay');
+ await expect(page.locator('.panel')).toContainText('Rests on 3 sources · 1 account');
+ await expect(page.locator('.panel')).toContainText('all one account');
+});
+
+test('the number of statements on one account is pressed to reach them', async ({ page }) => {
+ // A count that names a set and gives no way to it sends the analyst opening
+ // statements one at a time to find out which ones it meant.
+ await openGraph(page, { graph: foldedCase });
+ await drawn(page);
+
+ const number = page.getByRole('button', { name: '1 on one account' });
+ await expect(number).toHaveAttribute('aria-pressed', 'false');
+ await expect(number).toHaveAttribute('title', /one account published every one of them/);
+
+ // A typed name outranks the question, so asking it gives the name up rather than
+ // answering the press with an unchanged picture.
+ await page.getByLabel('Find a node').fill('harbour');
+ await number.click();
+ await expect(page.getByLabel('Find a node')).toHaveValue('');
+ await expect(number).toHaveAttribute('aria-pressed', 'true');
+ await expect(number).toHaveAttribute('title', /Click again to bring the rest/);
+
+ // And it costs one click to ask again, so Escape lets it go before the handful.
+ await page.keyboard.press('Escape');
+ await expect(number).toHaveAttribute('aria-pressed', 'false');
+});
+
+test('a fold this reading cannot hand back names the lens that draws it', async ({ page }) => {
+ // The safeguard's fold: an import filed a source under a type meant for the
+ // analyst's own output, so the shape collapsed it rather than dropping it — and there
+ // is no node to bring back into a reading that does not draw notes at all.
+ await openGraph(page, {
+ graph: {
+ ...foldedCase,
+ single_account: 0,
+ nodes: foldedCase.nodes.map((node) => (node.rests ? { ...node, rests: undefined } : node)),
+ links: [
+ {
+ ...foldedCase.links[0],
+ folded: { sources: 1, via: ['note'], accounts: 0 },
+ },
+ ],
+ },
+ });
+
+ await drawn(page);
+ await clickTheEdge(page);
+
+ await expect(page.locator('.panel')).toContainText('note, drawn as one edge');
+ await expect(page.locator('.panel')).toContainText('My work draws note.');
+ await expect(page.getByRole('button', { name: /^Show the/ })).toHaveCount(0);
+});
+
+// -- growing the view --------------------------------------------------------
+
+test('opening a node keeps the case on screen instead of replacing it', async ({ page }) => {
+ // The gesture the whole tool turns on. Replacing the view answered the question
+ // and lost the case it was asked about.
+ await openGraph(page, { graph: null });
+ // Switched off so the account has a neighbour that is not drawn: on a whole case
+ // every one of them already is, and there is nothing to open.
+ await expect(page.getByText('7 of 7')).toBeVisible();
+ await page.getByRole('button', { name: /collected/ }).click();
+ await expect(page.getByText('6 of 6')).toBeVisible();
+
+ await openMenu(page, 'harbourwatch');
+ await page.getByRole('button', { name: /^Expand 1 more connection/ }).click();
+
+ // The media was switched off and is here only because the node was opened.
+ await expect(page.getByRole('button', { name: 'Reset view' })).toBeVisible();
+ await page.getByLabel('Find a node').fill('harbour frame');
+ await expect(page.locator('.found button').first()).toBeVisible();
+});
+
+test('opening a node leaves everything already drawn exactly where it is', async ({ page }) => {
+ // What the whole case used to do on every click: re-run the relaxation over all of
+ // it, so every node slid to a new resting place while the analyst was reading it.
+ // Measured in ink, because the DOM says nothing about where a node sits.
+ await openGraph(page, { graph: null });
+ await drawn(page);
+ // Switched off so the account has a neighbour that is not drawn: on a whole case
+ // every one of them already is, and there is nothing to open.
+ await expect(page.getByText('7 of 7')).toBeVisible();
+ await page.getByRole('button', { name: /collected/ }).click();
+ await expect(page.getByText('6 of 6')).toBeVisible();
+
+ // The ink is kept **after** the node is picked, because picking one from the search
+ // brings it to the middle of the canvas: that moves the camera, and this spec is
+ // about the layout. Everything after this point leaves the view where it is.
+ const at = await nodeAt(page, 'harbourwatch');
+ await page.getByLabel('Find a node').fill('');
+ await drawn(page);
+ await keepInk(page);
+
+ await page.mouse.click(at.x, at.y, { button: 'right' });
+ await expect(page.locator('.menu')).toBeVisible();
+ await page.getByRole('button', { name: /^Expand 1 more connection/ }).click();
+ await expect(page.getByRole('button', { name: 'Reset view' })).toBeVisible();
+ await drawn(page);
+
+ // Not "roughly the same picture": every node is where it was, so every pixel that
+ // was drawn is still drawn. What the arrival adds is deliberately not counted.
+ // Without the drawing being held, this reads 0.96 — the whole case moves.
+ expect(await inkLost(page)).toBeLessThan(0.05);
+});
+
+test('the whole picture is put back by one control, not one per list', async ({ page }) => {
+ await openGraph(page);
+ await drawn(page);
+ // Narrowed so the account has a neighbour that is not drawn; on a whole case every
+ // one of them already is, and there is nothing to bring in.
+ await expect(page.getByText('7 of 7')).toBeVisible();
+ await page.getByRole('button', { name: /collected/ }).click();
+ await openMenu(page, 'harbourwatch');
+ await page.getByRole('button', { name: /^Expand \d+ more connection/ }).click();
+ await expect(page.getByText('7 of 6')).toBeVisible();
+
+ await page.getByRole('button', { name: 'Reset view' }).click();
+
+ await expect(page.getByRole('button', { name: 'Reset view' })).toHaveCount(0);
+ // Back to the narrowing it was expanded from, not to the whole case: the reset
+ // undoes the edits and leaves the reading alone.
+ await expect(page.getByText('6 of 6')).toBeVisible();
+});
+
+test('any node is taken out of the drawing, and put back', async ({ page }) => {
+ // The way back out of a crowded drawing used to be folding every expansion, which
+ // takes the reading that raised the question down with it.
+ await openGraph(page);
+ await drawn(page);
+ await expect(page.getByText('7 of 7')).toBeVisible();
+
+ await pick(page, 'BTR-82A 4721');
+ await page.getByRole('button', { name: 'Hide', exact: true }).click();
+
+ // One node fewer drawn, and the case still holds all seven: nothing was deleted.
+ await expect(page.getByText('6 of 7')).toBeVisible();
+ // And the node being read went with the picture, rather than being left on a panel
+ // pointing at nothing.
+ await expect(page.locator('.panel')).toHaveCount(0);
+
+ await page.getByRole('button', { name: 'Reset view' }).click();
+
+ await expect(page.getByText('7 of 7')).toBeVisible();
+ await expect(page.getByRole('button', { name: 'Reset view' })).toHaveCount(0);
+});
+
+test('the last change to the drawing is taken back, and put again', async ({ page }) => {
+ // Only a browser answers this one: the claim is that the history follows the
+ // drawing's own state, so an act nobody wired into it is undone all the same.
+ await openGraph(page);
+ await drawn(page);
+ await expect(page.getByRole('button', { name: 'Undo' })).toHaveCount(0);
+
+ await pick(page, 'BTR-82A 4721');
+ await page.getByRole('button', { name: 'Hide', exact: true }).click();
+ await expect(page.getByText('6 of 7')).toBeVisible();
+
+ await page.getByRole('button', { name: 'Undo' }).click();
+ await expect(page.getByText('7 of 7')).toBeVisible();
+ // Nothing was deleted and nothing is left edited, so the blunt way back goes too.
+ await expect(page.getByRole('button', { name: 'Reset view' })).toHaveCount(0);
+
+ await page.getByRole('button', { name: 'Redo' }).click();
+ await expect(page.getByText('6 of 7')).toBeVisible();
+});
+
+test('the chord undoes the drawing, and a typed field keeps its own', async ({ page }) => {
+ await openGraph(page);
+ await drawn(page);
+ await pick(page, 'BTR-82A 4721');
+ await page.getByRole('button', { name: 'Hide', exact: true }).click();
+ await expect(page.getByText('6 of 7')).toBeVisible();
+
+ await page.keyboard.press('Control+z');
+ await expect(page.getByText('7 of 7')).toBeVisible();
+
+ // A field being typed into owns its own undo: the drawing must not move under it.
+ await page.getByRole('button', { name: 'Redo' }).click();
+ await expect(page.getByText('6 of 7')).toBeVisible();
+ const find = page.getByLabel('Find a node');
+ await find.fill('harbour');
+ await find.press('Control+z');
+ await expect(page.getByText('6 of 7')).toBeVisible();
+});
+
+test('a node taken out takes what only it was holding', async ({ page }) => {
+ // Taking out the node you opened used to leave its whole neighbourhood drawn with no
+ // edge to anything — a handful of dots whose one reason to be there had just gone.
+ await openGraph(page);
+ await drawn(page);
+ // Off the ranking, so the frame is in the picture by the expansion alone.
+ await page.getByRole('button', { name: /collected/ }).click();
+ await expect(page.getByText('6 of 6')).toBeVisible();
+ await openMenu(page, 'harbourwatch');
+ await page.getByRole('button', { name: /^Expand \d+ more connection/ }).click();
+ await expect(page.getByText('7 of 6')).toBeVisible();
+
+ await pick(page, 'harbourwatch');
+ await page.getByRole('button', { name: 'Hide', exact: true }).click();
+
+ // Two fewer, not one: the account and the frame it was the only thing holding.
+ await expect(page.getByText('5 of 6')).toBeVisible();
+ await expect(page.getByText('harbour frame')).toHaveCount(0);
+
+ // And it is one act to undo, whichever of the edits is in the way: the reset puts
+ // the expansion back as well, which is why the count reads the narrowing it was
+ // all built on top of.
+ await page.getByRole('button', { name: 'Reset view' }).click();
+ await expect(page.getByText('6 of 6')).toBeVisible();
+});
+
+test('what was hidden is offered back by the node it was hanging on', async ({ page }) => {
+ // Hiding is the analyst's own act on their own picture, and undoing one node of it
+ // used to cost the whole drawing: *Reset view* puts back every edit, and the name of
+ // a node you have just decided not to look at is not what you go and type.
+ await openGraph(page);
+ await drawn(page);
+
+ await pick(page, 'harbour frame');
+ await page.getByRole('button', { name: 'Hide', exact: true }).click();
+ await expect(page.getByText('6 of 7')).toBeVisible();
+
+ // The account that posted it counts it as a connection the picture lacks, which is
+ // what it now is, and the switch on it hands it straight back.
+ await pick(page, 'harbourwatch');
+ await expect(page.locator('.panel')).toContainText('1 more not drawn');
+ await page.locator('.panel').getByRole('button', { name: /^Expand \(1\)/ }).click();
+
+ await expect(page.getByText('7 of 7')).toBeVisible();
+ // Nothing is left over: the drawing is the one the case opened with, so there is no
+ // edit left to undo and nothing still offering to bring in what is on screen.
+ await expect(page.getByRole('button', { name: 'Reset view' })).toHaveCount(0);
+ await pick(page, 'harbourwatch');
+ await expect(page.locator('.panel')).not.toContainText('more not drawn');
+});
+
+test('the way back is the node it left, not every node on screen', async ({ page }) => {
+ // A count that prices a click doing nothing is the failure every number in this tool
+ // exists to prevent, so only the node that was holding it offers it back.
+ await openGraph(page);
+ await drawn(page);
+
+ await pick(page, 'harbour frame');
+ await page.getByRole('button', { name: 'Hide', exact: true }).click();
+ await expect(page.getByText('6 of 7')).toBeVisible();
+
+ await pick(page, 'Section chief');
+ await expect(page.locator('.panel')).not.toContainText('more not drawn');
+});
+
+test('a gathered handful is taken out in one act, not one node per read', async ({ page }) => {
+ // Growth and removal over a list is the other half of owning the drawing: one
+ // question about several nodes is one read.
+ await openGraph(page);
+ await drawn(page);
+ await pick(page, 'BTR-82A 4721');
+ const centre = await middle(page);
+ await page.keyboard.press('Escape');
+ // The first one is moved off the middle so both screen positions are known, exactly
+ // as the drag spec gathers its pair.
+ await dragNode(page, centre, -180, 120);
+ const first = { x: centre.x - 180, y: centre.y + 120 };
+ await page.keyboard.down('Control');
+ await page.mouse.click(first.x, first.y);
+ await page.keyboard.up('Control');
+ await expect(page.getByRole('button', { name: /1 held/ })).toBeVisible();
+
+ await pick(page, 'Section chief');
+ const second = await middle(page);
+ await page.keyboard.down('Control');
+ await page.mouse.click(second.x, second.y);
+ await page.keyboard.up('Control');
+ await expect(page.getByRole('button', { name: /2 held/ })).toBeVisible();
+
+ await page.getByRole('button', { name: 'Hide 2' }).click();
+
+ await expect(page.getByText('5 of 7')).toBeVisible();
+ await expect(page.getByRole('button', { name: 'Reset view' })).toBeVisible();
+ // The handful went with them: a group over nodes that are no longer drawn is a group
+ // nobody is still building.
+ await expect(page.getByRole('button', { name: /held/ })).toHaveCount(0);
+});
+
+/**
+ * A drawing large enough that placing it costs something worth saying. Built here
+ * rather than seeded: the tool draws it, so the spec has to hand over the nodes.
+ */
+function heavyCase(count) {
+ const nodes = [];
+ const links = [];
+ for (let i = 0; i < count; i += 1) {
+ nodes.push({
+ id: `n-${i}`, type: 'person', label: `Person ${i}`, family: 'actor',
+ status: 'confirmed', at: '2026-08-01T09:00:00Z', degree: i ? 1 : count - 1,
+ });
+ if (i) {
+ links.push({
+ id: `l-${i}`, from: 'n-0', to: `n-${i}`, type: 'knows',
+ provenance: { by: 'user', at: '2026-08-02T09:00:00Z', status: 'confirmed' },
+ });
+ }
+ }
+ return {
+ lens: 'all', order: 'degree', nodes, links,
+ total: count, shown: count, truncated: false, expanded: [], isolated: 0, pinned: 0,
+ };
+}
+
+test('says what a heavy drawing costs instead of refusing to draw one', async ({ page }) => {
+ // The ceiling that refused is gone: a limit is the app overruling the analyst about
+ // their own picture, and what replaces it is the price of the next change, said.
+ await openGraph(page, { graph: heavyCase(1100) });
+
+ const said = page.locator('.count.weight');
+ await expect(said).toContainText('heavy drawing');
+ await expect(said).toHaveAttribute('title', /costs about a second/);
+});
+
+test('draws a case with no ceiling to be full of', async ({ page }) => {
+ // Nothing says how full the drawing is, because nothing refuses: the gauge, the
+ // greyed control and the refusal in words all went with the budget.
+ await openGraph(page, { graph: heavyCase(40) });
+ await drawn(page);
+ await openMenu(page, 'Person 0');
+
+ await expect(page.getByRole('button', { name: 'The view is full' })).toHaveCount(0);
+ await expect(page.locator('.count.weight')).toHaveCount(0);
+});
+
+test('folds an arrival away from the node it arrived at, and gives it back', async ({ page }) => {
+ // The switch, in its two shrinking states. Folding costs no read: the case still
+ // sent the node, the drawing has simply put it away.
+ await openGraph(page);
+ await drawn(page);
+ await expect(page.getByText('7 of 7')).toBeVisible();
+ await page.getByRole('button', { name: /collected/ }).click();
+ await openMenu(page, 'harbourwatch');
+ await page.getByRole('button', { name: /^Expand \d+ more connection/ }).click();
+ await expect(page.getByText('7 of 6')).toBeVisible();
+
+ // Folded from the node itself, where it arrived.
+ await pick(page, 'harbourwatch');
+ await page.getByRole('button', { name: /^Collapse \(1\)/ }).click();
+
+ await expect(page.getByText('6 of 6')).toBeVisible();
+ await expect(page.getByRole('button', { name: '1 folded' })).toBeVisible();
+ await expect(page.locator('.panel')).toContainText('Holding 1 folded under it');
+
+ await page.getByRole('button', { name: '1 folded' }).click();
+ await expect(page.getByText('7 of 6')).toBeVisible();
+});
+
+test('folds and unfolds from the canvas, where the switch is', async ({ page }) => {
+ // The panel is the keyboard path; this is the gesture. A canvas teaches nothing on
+ // its own, so the count on the node is what says the switch is there at all.
+ await openGraph(page, { graph: null });
+ await drawn(page);
+ await expect(page.getByText('7 of 7')).toBeVisible();
+
+ const at = await nodeAt(page, 'harbourwatch');
+ await page.getByLabel('Find a node').fill('');
+ await page.mouse.dblclick(at.x, at.y);
+
+ await expect(page.getByText('6 of 7')).toBeVisible();
+ await expect(page.getByRole('button', { name: '1 folded' })).toBeVisible();
+
+ await page.mouse.dblclick(at.x, at.y);
+ await expect(page.getByText('7 of 7')).toBeVisible();
+ await expect(page.getByRole('button', { name: /folded/ })).toHaveCount(0);
+});
+
+test('a right-click twice over opens the menu rather than folding under it', async ({ page }) => {
+ // Konva counts a double-click by the clock alone, so the second menu opened on one
+ // node arrived here as a double-click and folded the drawing under it.
+ await openGraph(page, { graph: null });
+ await drawn(page);
+ const at = await nodeAt(page, 'harbourwatch');
+ await page.mouse.click(at.x, at.y, { button: 'right' });
+ await page.keyboard.press('Escape');
+ await page.mouse.click(at.x, at.y, { button: 'right' });
+
+ await expect(page.locator('.menu')).toBeVisible();
+ await expect(page.getByRole('button', { name: /folded/ })).toHaveCount(0);
+});
+
+test('folds the picture the case opened on, which no other act reaches', async ({ page }) => {
+ // The hole this closes: expanding adds and hiding removes, and neither speaks for
+ // the nodes that were on screen before the analyst touched anything.
+ await openGraph(page, { graph: null });
+ await drawn(page);
+ await expect(page.getByText('7 of 7')).toBeVisible();
+
+ // The frame hangs off the account alone, so folding the account puts it away.
+ await pick(page, 'harbourwatch');
+ await page.getByRole('button', { name: /^Collapse \(1\)/ }).click();
+
+ await expect(page.getByText('6 of 7')).toBeVisible();
+ await expect(page.getByRole('button', { name: '1 folded' })).toBeVisible();
+ // Nothing was asked of the case and nothing was hidden: the node is still sent, and
+ // typing its name gives the fold back.
+ await page.getByLabel('Find a node').fill('harbour frame');
+ await expect(page.locator('.found button').first()).toContainText('folded');
+ await page.locator('.found button').first().click();
+ await expect(page.getByText('7 of 7')).toBeVisible();
+});
+
+test('a node says what can be done with it, in words', async ({ page }) => {
+ // A canvas teaches no gesture on its own. The menu is where people look.
+ await openGraph(page);
+ await openMenu(page, '@harbourwatch');
+
+ const menu = page.locator('.menu');
+ await expect(menu).toContainText('Connect to…');
+ await expect(menu).toContainText('Details');
+ // Every neighbour of this account is already drawn, so the menu says so rather
+ // than offering an act that could only appear to do nothing.
+ await expect(menu).toContainText('All its connections are drawn');
+});
+
+test('two entities are connected with two clicks and a named verb', async ({ page }) => {
+ const fixture = await openGraph(page);
+ await openMenu(page, 'Section chief');
+ await page.getByRole('button', { name: 'Connect to…' }).click();
+ await expect(page.getByText(/Connecting from/)).toBeVisible();
+
+ await clickNode(page, 'BTR-82A 4721');
+ // Only the readings the vocabulary accepts for a person and a vehicle.
+ await expect(page.locator('.offer')).toContainText('owns');
+ await page.locator('.offer li button').first().click();
+
+ expect(fixture.linkWrites).toEqual([
+ { method: 'POST', id: null, body: { from_id: 'per-1', to_id: 'veh-1', type: 'owns' } },
+ ]);
+});
+
+test('a filed connection says nothing, because the edge saying it is drawn', async ({ page }) => {
+ // The bug this guards: the reload was followed by a call to a helper nobody ever
+ // wrote, so the ReferenceError landed in the catch that reports a refused
+ // connection — and a relation filed successfully reported an error naming the
+ // missing function. Nothing on the canvas said the write had worked.
+ const fixture = await openGraph(page);
+ await openMenu(page, 'Section chief');
+ await page.getByRole('button', { name: 'Connect to…' }).click();
+ await clickNode(page, 'BTR-82A 4721');
+ await page.locator('.offer li button').first().click();
+
+ await expect.poll(() => fixture.linkWrites.length).toBe(1);
+ // The edge is the confirmation, so it is read back before the silence is asserted:
+ // an empty banner proves nothing while the reload is still in flight.
+ await pick(page, 'Section chief');
+ await expect(page.locator('.panel')).toContainText('owns');
+ await expect(page.locator('.said')).toHaveCount(0);
+});
+
+test('a connection filed into a lens that cannot draw it says so', async ({ page }) => {
+ // The one case worth a sentence: the lens holds a set of verbs, this one is not in
+ // it, so the picture is unchanged and a write with no visible result reads as a
+ // write that failed.
+ await openGraph(page);
+ await page.getByLabel('Lens').selectOption('ground');
+ await openMenu(page, 'Section chief');
+ await page.getByRole('button', { name: 'Connect to…' }).click();
+ await clickNode(page, 'BTR-82A 4721');
+ await page.locator('.offer li button').first().click();
+
+ await expect(page.locator('.said')).toContainText('not drawn in this lens');
+});
+
+test('an armed connection survives the case being panned under it', async ({ page }) => {
+ // A pan stores where the group is going and applies it on the next frame, so
+ // reading the group mid-pan put the arrow one transform behind — and it caught up
+ // in a jump when the pointer came up, landing the connection on the wrong node.
+ const fixture = await openGraph(page);
+ await drawn(page);
+ await openMenu(page, 'Section chief');
+ await page.getByRole('button', { name: 'Connect to…' }).click();
+
+ await panBy(page, 120, 80);
+ await expect(page.getByText(/Connecting from/)).toBeVisible();
+
+ await clickNode(page, 'BTR-82A 4721');
+ await page.locator('.offer li button').first().click();
+
+ expect(fixture.linkWrites).toEqual([
+ { method: 'POST', id: null, body: { from_id: 'per-1', to_id: 'veh-1', type: 'owns' } },
+ ]);
+});
+
+test('a connection is called off without filing anything', async ({ page }) => {
+ const fixture = await openGraph(page);
+ await openMenu(page, 'Section chief');
+ await page.getByRole('button', { name: 'Connect to…' }).click();
+ await page.getByRole('button', { name: 'cancel' }).click();
+
+ await expect(page.getByText(/Connecting from/)).toHaveCount(0);
+ expect(fixture.linkWrites).toEqual([]);
+});
+
+// -- the edge as a thing to read ---------------------------------------------
+
+test('an edge can be chosen, read and ruled on', async ({ page }) => {
+ const fixture = await openGraph(page);
+ // Reached from the node panel, which is the keyboard-reachable way to an edge.
+ await pick(page, '@harbourwatch');
+ await page.locator('.panel .link-row').first().click();
+ await pick(page, '3rd Battalion');
+
+ // The suggested edge to the account is the one a tool proposed.
+ await expect(page.locator('.panel')).toContainText('owns');
+ await page.locator('.canvas-row > .canvas').click({ position: { x: 5, y: 5 } });
+ await expect(page.locator('.panel')).toHaveCount(0);
+ expect(fixture.linkWrites).toEqual([]);
+});
+
+// -- the filters -------------------------------------------------------------
+
+test('a family is switched off from the legend, and the drawing shrinks', async ({ page }) => {
+ // The control that matters on a case larger than the budget: a lens narrows verbs
+ // and so never makes the drawing smaller, where a family does. On a real case one
+ // family dwarfs the rest, and switching it off is what spends the budget elsewhere.
+ await openGraph(page);
+ await expect(page.getByText('7 of 7')).toBeVisible();
+
+ const collected = page.getByRole('button', { name: /collected/ });
+ await collected.click();
+
+ // The one media entity is gone, and the legend still offers the way back.
+ await expect(page.getByText('6 of 6')).toBeVisible();
+ await expect(collected).toHaveAttribute('aria-pressed', 'false');
+ await expect(collected).toContainText('off');
+
+ await collected.click();
+ await expect(page.getByText('7 of 7')).toBeVisible();
+ await expect(collected).toHaveAttribute('aria-pressed', 'true');
+});
+
+test('the last family on stays on, since a blank canvas is not a reading', async ({ page }) => {
+ // An empty type list reads as "no narrowing" server-side, so switching every family
+ // off would draw the whole case back — a control doing the opposite of what it says.
+ await openGraph(page);
+ // Counted after the case has landed: the legend lists the families the case holds,
+ // and before the first read there is nothing to switch.
+ await expect(page.getByText('7 of 7')).toBeVisible();
+ const families = page.locator('.families button');
+ const count = await families.count();
+ for (let i = 0; i < count; i += 1) await families.nth(i).click();
+
+ await expect(page.locator('.families button[aria-pressed="true"]')).toHaveCount(1);
+});
+
+test('draws one of the analyst’s folders instead of the whole case', async ({ page }) => {
+ // A folder is one Search+ axis because it is the closest thing the case has to
+ // "what I am working on", and the same question must read the same in Board.
+ await openGraph(page, { summary: { total: 7, by_type: { media: 1 }, by_status: {}, by_folder: { harbour: 1 } } });
+ const bar = page.locator('.graph-tool .filter-bar');
+ await bar.getByRole('button', { name: 'Filter', exact: true }).click();
+ await bar.locator('.pop.wide').getByRole('button', { name: /^Folder\b/i }).click();
+ await bar.locator('.pop').last().getByRole('button', { name: /^harbour\b/i }).click();
+
+ await expect(page.getByText('1 of 1')).toBeVisible();
+});
diff --git a/frontend/e2e/paste.spec.js b/frontend/e2e/paste.spec.js
new file mode 100644
index 0000000..b175c0e
--- /dev/null
+++ b/frontend/e2e/paste.spec.js
@@ -0,0 +1,197 @@
+import { test, expect } from '@playwright/test';
+import { CASE_ID, installAppFixture } from './app.fixture.js';
+
+/**
+ * Ctrl+V, in a real browser.
+ *
+ * Nothing about this feature can be proven by reading source or by mounting one
+ * component: it is a window event carrying a `DataTransfer`, a listener that has to
+ * belong to the visible tool and to no other, and a refusal that must reach the
+ * screen. Every visited tab stays mounted behind the one on screen, so "does one
+ * Ctrl+V open exactly one dialog" is a question only a browser can answer.
+ */
+
+const catalog = [
+ {
+ id: 'place-1',
+ type: 'place',
+ label: 'checkpoint north',
+ attrs: { lat: 48.8584, lon: 2.2945 },
+ provenance: { by: 'satellite', at: '2026-08-01T10:00:00Z', status: 'confirmed' },
+ },
+];
+
+/**
+ * Paste something, the way the browser hands it over.
+ *
+ * Built in the page: a `DataTransfer` cannot cross the Playwright boundary, and
+ * `page.keyboard.press('Control+V')` pastes whatever the *machine's* clipboard
+ * holds, which no test can arrange.
+ */
+async function paste(page, { image = null, text = '', html = '' } = {}) {
+ await page.evaluate(
+ async ({ image, text, html }) => {
+ const data = new DataTransfer();
+ if (text) data.setData('text/plain', text);
+ if (html) data.setData('text/html', html);
+ if (image) {
+ // a 1×1 PNG, which is a real image as far as the dialog's preview goes
+ const bytes = Uint8Array.from(atob(image), (c) => c.charCodeAt(0));
+ data.items.add(new File([bytes], 'image.png', { type: 'image/png' }));
+ }
+ // The transfer is forced onto the event rather than passed to the
+ // constructor: Firefox ignores `clipboardData` in the init dict, since only
+ // the browser is meant to fill it. No engine lets a script put bytes on the
+ // system clipboard unprompted, so the event object is the one synthetic part.
+ const event = new ClipboardEvent('paste', { bubbles: true, cancelable: true });
+ Object.defineProperty(event, 'clipboardData', { value: data, configurable: true });
+ document.body.focus();
+ document.body.dispatchEvent(event);
+ },
+ { image, text, html }
+ );
+}
+
+const PNG_1PX =
+ 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8DwHwAFAAH/q842iQAAAABJRU5ErkJggg==';
+
+test('files a screenshot that exists nowhere but the clipboard', async ({ page }) => {
+ const fixture = await installAppFixture(page, { catalog });
+ await page.goto('/#board');
+ await expect(page.getByRole('heading', { name: 'Board' })).toBeVisible();
+
+ await paste(page, { image: PNG_1PX });
+
+ await expect(page.getByRole('dialog', { name: 'Paste image' })).toBeVisible();
+ await expect(page.locator('.preview img')).toBeVisible();
+ await page.locator('#paste-title').fill('Front gate');
+ await page.locator('#paste-source').fill('https://example.test/thread');
+ await page.getByRole('button', { name: 'Add to case' }).click();
+
+ await expect(page.getByRole('dialog', { name: 'Paste image' })).toBeHidden();
+ expect(fixture.pastes).toHaveLength(1);
+ expect(fixture.pastes[0]).toMatchObject({
+ title: 'Front gate',
+ source_url: 'https://example.test/thread',
+ });
+ // filed, then opened: the next gesture is relating it to whatever prompted it
+ await expect(page.getByRole('dialog', { name: 'Details' })).toBeVisible();
+ fixture.expectNoUnexpectedRequests();
+});
+
+test('takes a copied address as a bookmark', async ({ page }) => {
+ const fixture = await installAppFixture(page, { catalog });
+ await page.goto('/#board');
+ await expect(page.getByRole('heading', { name: 'Board' })).toBeVisible();
+
+ await paste(page, { text: 'https://leak.example.test/thread/1' });
+
+ const dialog = page.getByRole('dialog', { name: 'Paste link' });
+ await expect(dialog).toBeVisible();
+ // named after its host, so the button is live without typing anything
+ await expect(page.locator('#paste-title')).toHaveValue('leak.example.test');
+ await page.locator('#paste-notes').fill('watching this one');
+ await page.getByRole('button', { name: 'Add to case' }).click();
+
+ await expect(dialog).toBeHidden();
+ expect(fixture.entityWrites).toEqual([
+ {
+ type: 'bookmark',
+ label: 'leak.example.test',
+ attrs: {
+ url: 'https://leak.example.test/thread/1',
+ notes: 'watching this one',
+ folder: '',
+ },
+ },
+ ]);
+ fixture.expectNoUnexpectedRequests();
+});
+
+test('a link in Media is refused, and told where it does work', async ({ page }) => {
+ const fixture = await installAppFixture(page, { catalog });
+ await page.goto('/#media');
+ await expect(page.getByRole('heading', { name: 'Media Library' })).toBeVisible();
+
+ await paste(page, { text: 'https://leak.example.test/thread/1' });
+
+ const dialog = page.getByRole('dialog', { name: 'Nothing to paste here' });
+ await expect(dialog).toContainText('URL field');
+ // a refusal has nothing to fill in and files nothing
+ await expect(dialog.locator('input')).toHaveCount(0);
+ // the footer button, not the header's X, which carries the same accessible name
+ await dialog.locator('.modal-row .btn-primary').click();
+ await expect(dialog).toBeHidden();
+ expect(fixture.entityWrites).toEqual([]);
+ expect(fixture.pastes).toEqual([]);
+ fixture.expectNoUnexpectedRequests();
+});
+
+test('one Ctrl+V opens one dialog, however many tabs have been visited', async ({ page }) => {
+ // The tabs the analyst has opened stay mounted behind the visible one, so four
+ // ungated listeners would answer one paste four times over.
+ const fixture = await installAppFixture(page, { catalog });
+ await page.goto('/#media');
+ await expect(page.getByRole('heading', { name: 'Media Library' })).toBeVisible();
+ // switched by the tabs, not by the hash: a deep link is read once, at mount, and
+ // the point here is to leave three tools mounted at the same time
+ await page.getByRole('button', { name: 'Files', exact: true }).click();
+ await expect(page.getByRole('heading', { name: 'Files' })).toBeVisible();
+ await page.getByRole('button', { name: 'Board', exact: true }).click();
+ await expect(page.getByRole('heading', { name: 'Board' })).toBeVisible();
+
+ await paste(page, { image: PNG_1PX });
+
+ await expect(page.getByRole('dialog')).toHaveCount(1);
+ await expect(page.getByRole('dialog', { name: 'Paste image' })).toBeVisible();
+ // the Files dialog would have offered a folder; the board's does not
+ await expect(page.locator('.folder-select')).toHaveCount(0);
+ fixture.expectNoUnexpectedRequests();
+});
+
+test('a paste into a field stays the ordinary one', async ({ page }) => {
+ const fixture = await installAppFixture(page, { catalog });
+ await page.goto('/#board');
+ await expect(page.getByRole('heading', { name: 'Board' })).toBeVisible();
+
+ const search = page.getByPlaceholder(/search/i).first();
+ await search.click();
+ await page.evaluate(() => {
+ const data = new DataTransfer();
+ data.setData('text/plain', 'https://leak.example.test/thread/1');
+ const event = new ClipboardEvent('paste', { bubbles: true, cancelable: true });
+ Object.defineProperty(event, 'clipboardData', { value: data, configurable: true });
+ document.activeElement.dispatchEvent(event);
+ });
+
+ await expect(page.getByRole('dialog')).toHaveCount(0);
+ fixture.expectNoUnexpectedRequests();
+});
+
+test('a paste in Proof stays the composer\'s own', async ({ page }) => {
+ // The composer had Ctrl+V before this feature existed, and it means something
+ // else there: an overlay on the canvas, not a media file. Its listener and these
+ // four are all on `window`, and all five surfaces stay mounted once visited, so
+ // the boundary between them is worth a test rather than an argument.
+ const fixture = await installAppFixture(page, { catalog });
+ await page.goto('/#media');
+ await expect(page.getByRole('heading', { name: 'Media Library' })).toBeVisible();
+ await page.getByRole('button', { name: 'Board', exact: true }).click();
+ await expect(page.getByRole('heading', { name: 'Board' })).toBeVisible();
+
+ await page.getByRole('button', { name: 'Compose', exact: true }).click();
+ await page.getByRole('button', { name: 'Geo Proof', exact: true }).click();
+ await expect(page.getByRole('heading', { name: 'Geo Proof' })).toBeVisible();
+ await page.getByRole('button', { name: 'New proof' }).first().click();
+ await expect(page.getByRole('heading', { name: 'Create proof' })).toBeVisible();
+ await page.locator('.selectable-pick').click();
+ await page.getByRole('button', { name: 'Create proof' }).click();
+ await expect(page.locator('.panel-row')).toHaveCount(1);
+
+ await paste(page, { image: PNG_1PX });
+
+ // the proof takes it as an overlay, and nothing of ours opens over the canvas
+ await expect(page.locator('.paste-row')).toHaveCount(1);
+ await expect(page.getByRole('dialog', { name: 'Paste image' })).toHaveCount(0);
+ expect(fixture.pastes).toEqual([]);
+});
diff --git a/frontend/e2e/proof-canvas.spec.js b/frontend/e2e/proof-canvas.spec.js
index e854919..2214083 100644
--- a/frontend/e2e/proof-canvas.spec.js
+++ b/frontend/e2e/proof-canvas.spec.js
@@ -173,18 +173,16 @@ async function pasteScreenshot(page, { via = 'paste' } = {}) {
new DragEvent('drop', { dataTransfer: transfer, bubbles: true, cancelable: true })
);
} else {
- window.dispatchEvent(
- new ClipboardEvent('paste', { clipboardData: transfer, bubbles: true, cancelable: true })
- );
+ // Forced onto the event rather than passed to the constructor: Firefox ignores
+ // `clipboardData` in the init dict, since only the browser is meant to fill it.
+ const event = new ClipboardEvent('paste', { bubbles: true, cancelable: true });
+ Object.defineProperty(event, 'clipboardData', { value: transfer, configurable: true });
+ window.dispatchEvent(event);
}
}, via);
}
-test('pastes a screenshot into the proof without filing it as a panel', async ({ page, browserName }) => {
- // Firefox drops the clipboardData of a synthetic ClipboardEvent, so only the
- // real shortcut can drive it there. The drop test below covers the same insert
- // path on both engines.
- test.skip(browserName === 'firefox', 'synthetic paste carries no clipboardData in Firefox');
+test('pastes a screenshot into the proof without filing it as a panel', async ({ page }) => {
const fixture = await installAppFixture(page);
await openProofWithPanel(page);
@@ -261,3 +259,79 @@ test('a pasted image hosts its own annotations and leaves with them', async ({ p
await expect(page.locator('.shape-row')).toHaveCount(0);
fixture.expectNoUnexpectedRequests();
});
+
+/** Draw one box on the panel, which leaves it selected. */
+async function drawBox(page) {
+ const canvas = page.locator('.konva canvas').first();
+ const box = await canvas.boundingBox();
+ const x = box.x + box.width / 2 - 40;
+ const y = box.y + box.height / 2 - 25;
+ await page.getByTitle('Box (r)').click();
+ await page.mouse.move(x, y);
+ await page.mouse.down();
+ await page.mouse.move(x + 90, y + 65, { steps: 6 });
+ await page.mouse.up();
+}
+
+/** A paste event, optionally carrying an image the way the system clipboard would. */
+async function sendPaste(page, { image = null } = {}) {
+ await page.evaluate((b64) => {
+ const data = new DataTransfer();
+ if (b64) {
+ const bytes = Uint8Array.from(atob(b64), (c) => c.charCodeAt(0));
+ data.items.add(new File([bytes], 'image.png', { type: 'image/png' }));
+ }
+ // forced onto the event rather than passed to the constructor, which Firefox
+ // ignores; no engine lets a script fill the real clipboard unprompted
+ const event = new ClipboardEvent('paste', { bubbles: true, cancelable: true });
+ Object.defineProperty(event, 'clipboardData', { value: data, configurable: true });
+ window.dispatchEvent(event);
+ }, image);
+}
+
+const CLIPBOARD_PNG =
+ 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8DwHwAFAAH/q842iQAAAABJRU5ErkJggg==';
+
+test('Ctrl+C then Ctrl+V duplicates the selected annotation', async ({ page }) => {
+ const fixture = await installAppFixture(page);
+ await openProofWithPanel(page);
+ await drawBox(page);
+ await expect(page.locator('.shape-row')).toHaveCount(1);
+
+ await page.keyboard.press('Control+c');
+ await sendPaste(page);
+
+ await expect(page.locator('.shape-row')).toHaveCount(2);
+ fixture.expectNoUnexpectedRequests();
+});
+
+test('a copied shape outranks a screenshot the clipboard was already holding', async ({ page }) => {
+ // The two clipboards answer one chord, and the analyst copied the shape last.
+ // Reading the system one first pasted an hour-old screenshot over their rectangle.
+ const fixture = await installAppFixture(page);
+ await openProofWithPanel(page);
+ await drawBox(page);
+
+ await page.keyboard.press('Control+c');
+ await sendPaste(page, { image: CLIPBOARD_PNG });
+
+ await expect(page.locator('.shape-row')).toHaveCount(2);
+ await expect(page.locator('.paste-row')).toHaveCount(0);
+ fixture.expectNoUnexpectedRequests();
+});
+
+test('leaving the window hands Ctrl+V back to the system clipboard', async ({ page }) => {
+ // Going somewhere else is the only way an outside copy could have happened, so it
+ // is what makes the shape copy the older of the two.
+ const fixture = await installAppFixture(page);
+ await openProofWithPanel(page);
+ await drawBox(page);
+ await page.keyboard.press('Control+c');
+
+ await page.evaluate(() => window.dispatchEvent(new Event('blur')));
+ await sendPaste(page, { image: CLIPBOARD_PNG });
+
+ await expect(page.locator('.paste-row')).toHaveCount(1);
+ await expect(page.locator('.shape-row')).toHaveCount(1); // the shape was not duplicated
+ fixture.expectNoUnexpectedRequests();
+});
diff --git a/frontend/e2e/saved-relations.spec.js b/frontend/e2e/saved-relations.spec.js
index 6766019..4602d20 100644
--- a/frontend/e2e/saved-relations.spec.js
+++ b/frontend/e2e/saved-relations.spec.js
@@ -141,3 +141,47 @@ test('settles a suggested relation from the card, which survives the click', asy
]);
fixture.expectNoUnexpectedRequests();
});
+
+/** The same place, with a finding and a pointer on it. */
+const mixedChain = {
+ ...suggestedChain,
+ relations: [
+ ...suggestedChain.relations,
+ {
+ entity: { id: 'note-1', type: 'note', label: 'field notes', attrs: {} },
+ direction: 'in',
+ link: {
+ id: 'link-2',
+ from: 'note-1',
+ to: 'place-1',
+ type: 'mentions',
+ provenance: { by: 'user', at: '2026-07-24T10:00:00Z', status: 'confirmed' },
+ },
+ },
+ ],
+};
+
+test('shows the findings on the card and leaves the pointers out', async ({ page }) => {
+ const fixture = await installAppFixture(page, {
+ savedIndex: [stack[0]],
+ chains: { 'place-1': mixedChain },
+ });
+
+ await page.goto('/#satellite');
+ await expect(page.locator('.map')).toHaveClass(/leaflet-container/);
+ await page.getByRole('button', { name: 'Show saved work on the map' }).click();
+ await page.locator('.saved-mark').click();
+
+ const popup = page.locator('.saved-popup');
+ await expect(popup.getByText('roadside photo')).toBeVisible({ timeout: 15000 });
+
+ // "a note names this point" and "a camera stood here" are not the same claim. The
+ // card says Relations and asks for that action alone, so the pointer stays in
+ // Details rather than sitting under a heading on a card three rows tall.
+ const rows = await popup.locator('.relation .name').allInnerTexts();
+ expect(rows.map((t) => t.trim())).toEqual(['roadside photo']);
+ await expect(popup.getByText('field notes')).toHaveCount(0);
+ // and with one action on screen the list needs no heading of its own
+ await expect(popup.locator('.group')).toHaveCount(0);
+ fixture.expectNoUnexpectedRequests();
+});
diff --git a/frontend/e2e/settings.spec.js b/frontend/e2e/settings.spec.js
index b031965..a9f0ab7 100644
--- a/frontend/e2e/settings.spec.js
+++ b/frontend/e2e/settings.spec.js
@@ -5,7 +5,7 @@ test('keeps app settings in focused sections', async ({ page }) => {
const fixture = await installAppFixture(page);
await page.goto('/#settings');
- await expect(page.getByTitle('Settings')).toHaveClass(/gear-active/);
+ await expect(page.getByTitle('Settings')).toHaveClass(/topbar-active/);
const rail = page.getByRole('navigation', { name: 'Settings sections' });
await expect(rail.getByRole('button')).toHaveText([
diff --git a/frontend/e2e/timeline.spec.js b/frontend/e2e/timeline.spec.js
new file mode 100644
index 0000000..52a7609
--- /dev/null
+++ b/frontend/e2e/timeline.spec.js
@@ -0,0 +1,870 @@
+import { test, expect } from '@playwright/test';
+import { CASE_ID, installAppFixture } from './app.fixture.js';
+
+const person = {
+ id: 'person-1',
+ type: 'person',
+ label: 'Harbour witness',
+ attrs: {},
+ provenance: { by: 'user', at: '2026-08-01T09:00:00Z', status: 'confirmed' },
+};
+
+const source = {
+ id: 'note-1',
+ type: 'note',
+ label: 'Interview notes',
+ attrs: {},
+ provenance: { by: 'user', at: '2026-08-01T09:10:00Z', status: 'confirmed' },
+};
+
+const mediaEntity = {
+ id: 'media-1',
+ type: 'media',
+ label: 'Roadside camera frame',
+ attrs: { path: 'media/panel.svg', kind: 'image' },
+ provenance: { by: 'user', at: '2026-08-01T09:00:00Z', status: 'confirmed' },
+};
+
+const undatedClaim = {
+ id: 'claim-3',
+ type: 'claim',
+ label: 'Resolve the timezone of the second interview',
+ attrs: { time_role: 'observed' },
+ provenance: { by: 'user', at: '2026-08-01T09:20:00Z', status: 'confirmed' },
+};
+
+const timelineItems = [
+ {
+ id: 'temporal:claim:claim-1', owner_id: 'claim-1', category: 'statement', kind: 'claim',
+ label: 'Witness arrived at the north checkpoint', raw: '2026-06-18',
+ earliest: '2026-06-18T00:00:00Z', latest: '2026-06-19T00:00:00Z', precision: 'day',
+ shape: 'instant', time_role: 'occurred', uncertain: false, approximate: false,
+ zone: 'date-only', sortable: true, status: 'confirmed', confidence: 'probable',
+ parse_error: null, subjects: ['person-1'], places: [], sources: ['note-1'],
+ subject_entities: [{ id: 'person-1', label: 'Harbour witness', type: 'person' }],
+ place_entities: [],
+ source_entities: [{ id: 'note-1', label: 'Interview notes', type: 'note' }],
+ },
+ {
+ id: 'temporal:claim:claim-2', owner_id: 'claim-2', category: 'statement', kind: 'claim',
+ label: 'Vehicle remained near the eastern road', raw: '2026-06-12/2026-07-04',
+ earliest: '2026-06-12T00:00:00Z', latest: '2026-07-05T00:00:00Z', precision: 'day',
+ shape: 'interval', time_role: 'valid', uncertain: true, approximate: true,
+ zone: 'date-only', sortable: true, status: 'confirmed', confidence: 'possible',
+ parse_error: null, subjects: [], places: [], sources: [],
+ },
+ {
+ id: 'temporal:claim:claim-4', owner_id: 'claim-4', category: 'statement', kind: 'claim',
+ label: 'Second convoy cleared the gate after the radio call', raw: '2026-06-18',
+ earliest: '2026-06-18T00:00:00Z', latest: '2026-06-19T00:00:00Z', precision: 'day',
+ shape: 'instant', time_role: 'observed', uncertain: false, approximate: false,
+ zone: 'date-only', sortable: true, status: 'confirmed', confidence: 'possible',
+ parse_error: null, subjects: [], places: [], sources: [],
+ },
+ {
+ id: 'temporal:claim:claim-5', owner_id: 'claim-5', category: 'statement', kind: 'claim',
+ label: 'Third sighting placed the crane near the south quay', raw: '2026-06-19',
+ earliest: '2026-06-19T00:00:00Z', latest: '2026-06-20T00:00:00Z', precision: 'day',
+ shape: 'instant', time_role: 'observed', uncertain: true, approximate: false,
+ zone: 'date-only', sortable: true, status: 'suggested', confidence: 'probable',
+ parse_error: null, subjects: [], places: [], sources: [],
+ },
+ {
+ id: 'temporal:media:media-1:captured', owner_id: 'media-1', category: 'media', kind: 'captured',
+ label: 'Roadside camera frame', raw: '2026-06-23T18:42:11Z',
+ earliest: '2026-06-23T18:42:11Z', latest: '2026-06-23T18:42:12Z', precision: 'second',
+ shape: 'instant', time_role: null, uncertain: false, approximate: false,
+ zone: 'utc', sortable: true, status: null, confidence: null, parse_error: null,
+ subjects: [], places: [], sources: [],
+ },
+ {
+ id: 'temporal:claim:claim-3', owner_id: 'claim-3', category: 'statement', kind: 'claim',
+ label: 'Resolve the timezone of the second interview', raw: null,
+ earliest: null, latest: null, precision: null, shape: null, time_role: 'observed',
+ uncertain: false, approximate: false, zone: null, sortable: false,
+ status: 'confirmed', confidence: null, parse_error: null,
+ subjects: ['person-1'], places: [], sources: [],
+ },
+ {
+ id: 'temporal:activity:person-1:filed', owner_id: 'person-1', category: 'case_activity', kind: 'filed',
+ label: 'Harbour witness', raw: '2026-08-01T09:00:00Z',
+ earliest: '2026-08-01T09:00:00Z', latest: '2026-08-01T09:00:01Z', precision: 'second',
+ shape: 'instant', time_role: null, uncertain: false, approximate: false,
+ zone: 'utc', sortable: true, status: null, confidence: null, parse_error: null,
+ subjects: [], places: [], sources: [],
+ },
+ {
+ id: 'temporal:media:media-local:captured', owner_id: 'media-local', category: 'media', kind: 'captured',
+ label: 'IMG_5250', raw: '2021-04-24T14:52:29', earliest: null, latest: null,
+ precision: 'second', shape: 'instant', time_role: null, uncertain: false, approximate: false,
+ zone: 'local', sortable: false, status: null, confidence: null, parse_error: null,
+ subjects: [], places: [], sources: [],
+ },
+];
+
+for (let index = 0; index < 7; index += 1) {
+ timelineItems.push({
+ id: `temporal:claim:dense-${index}`, owner_id: `dense-${index}`,
+ category: 'statement', kind: 'claim',
+ label: `Checkpoint log ${index + 1} records the same arrival window`, raw: '2026-06-18',
+ earliest: '2026-06-18T00:00:00Z', latest: '2026-06-19T00:00:00Z', precision: 'day',
+ shape: 'instant', time_role: 'observed', uncertain: false, approximate: false,
+ zone: 'date-only', sortable: true, status: 'confirmed', confidence: 'possible',
+ parse_error: null, subjects: [], places: [], sources: [],
+ });
+}
+
+const timelineItem = (ownerId) => timelineItems.find((item) => item.owner_id === ownerId);
+
+const claimChain = (id, label, attrs, relations = []) => ({
+ entity: {
+ id, type: 'claim', label, attrs,
+ provenance: { by: 'user', at: '2026-08-01T09:20:00Z', status: 'confirmed' },
+ },
+ sources: [], lost: [], dependents: [], relations, empty: relations.length === 0,
+});
+
+const chainLink = (type, entity) => ({
+ direction: 'out', link: { id: `link-${type}-${entity.id}`, type }, entity,
+});
+
+/** Set the visible window through the range menu, and close it again.
+ *
+ * The two boundaries live behind the window reading rather than out on the toolbar,
+ * so a spec that wants a precise window opens the menu, types both ends and gets out
+ * of the way of the axis underneath. */
+async function setWindow(page, from, to) {
+ await page.locator('.range-face').click();
+ const menu = page.locator('.range-menu');
+ await menu.getByLabel('From').fill(from);
+ await menu.getByLabel('To').fill(to);
+ await page.locator('.range-face').click();
+ await expect(menu).toHaveCount(0);
+}
+
+/** The window the axis says it is drawing, as `<start> to <end>` on the display zone.
+ * It is what stays on screen while the ruler and the overview are being dragged. */
+const axisWindowText = (page) => page.locator('.axis-label small').innerText();
+
+async function openTimeline(page, options = {}) {
+ const fixture = await installAppFixture(page, {
+ catalog: [person, source, mediaEntity],
+ timelineItems,
+ chains: {
+ 'person-1': { entity: person, sources: [], lost: [], dependents: [], relations: [], empty: true },
+ 'claim-1': claimChain('claim-1', timelineItem('claim-1').label, {
+ when: timelineItem('claim-1').raw, time_role: 'occurred', confidence: 'probable',
+ method: 'Compared the checkpoint log with the interview notes.',
+ verbatim: 'The witness arrived shortly after the gate opened.',
+ }, [chainLink('about', person), chainLink('cites', source)]),
+ 'claim-2': claimChain('claim-2', timelineItem('claim-2').label, {
+ when: timelineItem('claim-2').raw, time_role: 'valid', confidence: 'possible',
+ }),
+ 'claim-3': claimChain('claim-3', timelineItem('claim-3').label, { time_role: 'observed' }),
+ 'media-1': { entity: mediaEntity, sources: [], lost: [], dependents: [], relations: [], empty: true },
+ },
+ ...options,
+ });
+ await page.setViewportSize({ width: 1440, height: 900 });
+ await page.goto('/#timeline');
+ await expect(page.getByRole('heading', { name: 'Timeline', exact: true })).toBeVisible();
+ await expect(page.locator('.loading-line')).toHaveCount(0);
+ return fixture;
+}
+
+test('draws a clear chronology with density, uncertainty and an inspector', async ({ page }, testInfo) => {
+ const fixture = await openTimeline(page);
+
+ await expect(page.locator('.tabstrip').getByRole('button')).toHaveText(['Board', 'Graph', 'Timeline']);
+ await expect(page.locator('.track-label strong')).toHaveText(['Events', 'Media']);
+ await expect(page.getByRole('button', { name: /Witness arrived/ })).toBeVisible();
+ await expect(page.getByRole('button', { name: /Vehicle remained/ }).locator('..')).toHaveClass(/period.*approximate.*uncertain/);
+ await expect(page.locator('.density-bucket')).toHaveCount(4);
+ await expect(page.getByText('Undated', { exact: true })).toBeVisible();
+ await expect(page.getByText('Not on UTC axis', { exact: true })).toBeVisible();
+ await expect(page.getByText('2021-04-24T14:52:29', { exact: false })).toBeVisible();
+
+ const axis = await page.locator('.axis-ruler').boundingBox();
+ expect(axis.width).toBeGreaterThan(800);
+
+ const eventBoxes = await page.locator('.timeline-event.statement').evaluateAll((events) =>
+ events.map((event) => {
+ const box = event.getBoundingClientRect();
+ return { left: box.left, right: box.right, top: box.top, bottom: box.bottom };
+ })
+ );
+ for (let left = 0; left < eventBoxes.length; left += 1) {
+ for (let right = left + 1; right < eventBoxes.length; right += 1) {
+ const a = eventBoxes[left];
+ const b = eventBoxes[right];
+ expect(a.right <= b.left || b.right <= a.left || a.bottom <= b.top || b.bottom <= a.top).toBe(true);
+ }
+ }
+
+ await page.getByRole('button', { name: /Witness arrived/ }).click();
+ expect((await page.locator('.axis-ruler').boundingBox()).width).toBeCloseTo(axis.width, 0);
+ const inspector = page.locator('.inspector');
+ await expect(inspector.getByRole('heading', { name: timelineItem('claim-1').label })).toBeVisible();
+ await expect(inspector.getByText('2026-06-18', { exact: true })).toBeVisible();
+ await expect(inspector.getByText('Confidence: probable')).toBeVisible();
+ await expect(inspector.getByText('Compared the checkpoint log with the interview notes.')).toBeVisible();
+ await expect(inspector.getByRole('button', { name: /Interview notes/ })).toBeVisible();
+
+ await page.getByRole('button', { name: 'Track', exact: true }).click();
+ await page.locator('.track-menu').getByRole('button').filter({ hasText: 'Case activity' }).click();
+ await expect(page.locator('.track-label strong')).toHaveText(['Events', 'Media', 'Case activity']);
+
+ if (process.env.AZIMUT_TIMELINE_SCREENSHOT && testInfo.project.name === 'chromium') {
+ await page.screenshot({ path: process.env.AZIMUT_TIMELINE_SCREENSHOT, fullPage: true });
+ }
+ fixture.expectNoUnexpectedRequests();
+});
+
+test('builds, reorders and curates tracks without leaving the chronology', async ({ page }) => {
+ const fixture = await openTimeline(page);
+
+ await page.getByRole('button', { name: 'Track', exact: true }).click();
+ await page.locator('.track-menu').getByRole('button').filter({ hasText: /^Person/ }).click();
+ await expect(page.locator('.track-label strong')).toHaveText(['Events', 'Media', 'Person']);
+
+ const movePerson = page.getByRole('button', { name: 'Move Person track' });
+ await movePerson.press('Alt+ArrowUp');
+ await expect(page.locator('.track-label strong')).toHaveText(['Events', 'Person', 'Media']);
+
+ await page.getByRole('button', { name: 'Fold Person' }).click();
+ await expect(page.locator('.track-row').filter({ hasText: 'Person' })).toHaveClass(/folded/);
+ await page.getByRole('button', { name: 'Expand Person' }).click();
+
+ const personTrack = page.locator('.track-row').filter({ hasText: 'Person' });
+ await personTrack.getByRole('button', { name: /Witness arrived/ }).click();
+ await page.getByRole('button', { name: 'Pin in track' }).click();
+ await expect(personTrack.locator('.timeline-event.pinned')).toHaveCount(1);
+
+ await page.getByRole('button', { name: 'Hide from track' }).click();
+ await expect(personTrack.getByRole('button', { name: /Witness arrived/ })).toHaveCount(0);
+ await personTrack.getByRole('button', { name: 'Show hidden' }).click();
+ await expect(personTrack.getByRole('button', { name: /Witness arrived/ })).toBeVisible();
+
+ await page.getByRole('button', { name: 'Track', exact: true }).click();
+ await page.locator('.track-menu').getByRole('button').filter({ hasText: /^Custom/ }).click();
+ const editor = page.getByRole('dialog', { name: 'Add track' });
+ await expect(editor.getByText('Search+', { exact: true })).toBeVisible();
+ await editor.getByLabel('Name').fill('Evidence review');
+ await editor.getByLabel('Match the Search+ question through').selectOption('source');
+ await editor.getByRole('button', { name: 'Add track' }).click();
+ await expect(page.locator('.track-label strong').filter({ hasText: 'Evidence review' })).toHaveCount(1);
+
+ await page.getByLabel('Group by').selectOption('subject');
+ await expect(page.locator('.track-label strong').filter({ hasText: 'Harbour witness' })).toHaveCount(3);
+ fixture.expectNoUnexpectedRequests();
+});
+
+test('asks an entry what can be done with it, without choosing it', async ({ page }) => {
+ await openTimeline(page);
+ const events = page.locator('.track-row').filter({ hasText: 'Events' });
+ const inspector = page.locator('.inspector');
+ const menu = page.locator('.item-menu');
+
+ // A different entry is being read: the menu must leave it, and the panel, alone.
+ await page.getByRole('button', { name: /Vehicle remained/ }).click();
+ await expect(inspector.getByRole('heading', { name: /Vehicle remained/ })).toBeVisible();
+
+ await page.getByRole('button', { name: /Witness arrived/ }).click({ button: 'right' });
+ await expect(menu).toBeVisible();
+ await expect(inspector.getByRole('heading', { name: /Vehicle remained/ })).toBeVisible();
+
+ await menu.getByRole('button', { name: 'Pin in Events' }).click();
+ await expect(menu).toHaveCount(0);
+ await expect(events.locator('.timeline-event.pinned')).toHaveCount(1);
+
+ await page.getByRole('button', { name: /Witness arrived/ }).click({ button: 'right' });
+ await expect(menu.getByRole('button', { name: 'Unpin from Events' })).toBeVisible();
+ await page.keyboard.press('Escape');
+ await expect(menu).toHaveCount(0);
+
+ await page.getByRole('button', { name: /Witness arrived/ }).click({ button: 'right' });
+ await menu.getByRole('button', { name: 'Details' }).click();
+ const details = page.getByRole('dialog', { name: 'Details' });
+ await expect(details.getByLabel('Statement')).toHaveValue(timelineItem('claim-1').label);
+ await details.getByRole('button', { name: 'Close' }).click();
+
+ await page.getByRole('button', { name: /Witness arrived/ }).click({ button: 'right' });
+ await menu.getByRole('button', { name: 'Edit assessment' }).click();
+ const editor = page.getByRole('dialog', { name: 'Edit time assessment' });
+ await expect(editor.getByLabel('Statement')).toHaveValue(timelineItem('claim-1').label);
+ await editor.getByRole('button', { name: 'Cancel' }).click();
+
+ await page.getByRole('button', { name: /Witness arrived/ }).click({ button: 'right' });
+ await menu.getByRole('button', { name: 'Hide from Events' }).click();
+ await expect(events.getByRole('button', { name: /Witness arrived/ })).toHaveCount(0);
+ await expect(inspector.getByRole('heading', { name: /Vehicle remained/ })).toBeVisible();
+ await events.getByRole('button', { name: 'Show hidden' }).click();
+ await expect(events.getByRole('button', { name: /Witness arrived/ })).toBeVisible();
+});
+
+test('autosaves a live Timeline view and restores its track reading', async ({ page }) => {
+ const fixture = await openTimeline(page);
+ await page.getByRole('button', { name: 'Track', exact: true }).click();
+ await page.locator('.track-menu').getByRole('button').filter({ hasText: /^Person/ }).click();
+
+ await page.getByRole('button', { name: /^Views/ }).click();
+ await page.getByRole('button', { name: 'Save view' }).click();
+ const dialog = page.getByRole('dialog', { name: 'Save analysis view' });
+ await dialog.getByLabel('Name').fill('Witness chronology');
+ await dialog.getByRole('button', { name: 'Save', exact: true }).click();
+ await expect(page.locator('.views .active')).toContainText('live · saved');
+
+ await page.getByLabel('Group by').selectOption('role');
+ await expect.poll(() => fixture.analysisWrites.at(-1)?.body?.spec?.timeline?.group_by)
+ .toBe('role');
+ await expect(page.locator('.views .active')).toContainText('saved');
+
+ await page.getByRole('button', { name: 'Leave saved view' }).click();
+ await page.getByRole('button', { name: /^Views/ }).click();
+ // the surface is not printed on this list: every view in it is a Timeline reading
+ await page.getByRole('button', { name: 'Witness chronology live' }).click();
+ await expect(page.getByLabel('Group by')).toHaveValue('role');
+ await expect(page.locator('.track-name em').filter({ hasText: 'Person' })).toHaveCount(2);
+ fixture.expectNoUnexpectedRequests();
+});
+
+test('files a pending live edit before switching cases', async ({ page }) => {
+ const fixture = await openTimeline(page, {
+ cases: [
+ { id: CASE_ID, name: 'Browser Test', scratch: false, entities: [], links: [], folders: [] },
+ { id: 'second-case', name: 'Second Case', scratch: false, entities: [], links: [], folders: [] },
+ ],
+ });
+ await page.getByRole('button', { name: /^Views/ }).click();
+ await page.getByRole('button', { name: 'Save view' }).click();
+ const dialog = page.getByRole('dialog', { name: 'Save analysis view' });
+ await dialog.getByLabel('Name').fill('Switch-safe chronology');
+ await dialog.getByRole('button', { name: 'Save', exact: true }).click();
+ await expect(page.locator('.views .active')).toContainText('live · saved');
+
+ await page.getByLabel('Group by').selectOption('role');
+ await page.getByTitle('Switch case').click();
+ await page.locator('.switcher .menu .item').filter({ hasText: 'Second Case' }).click();
+
+ await expect(page.getByTitle('Switch case')).toContainText('Second Case');
+ await expect.poll(() => fixture.analysisWrites.at(-1)).toMatchObject({
+ method: 'PUT',
+ caseId: CASE_ID,
+ body: { spec: { timeline: { group_by: 'role' } } },
+ });
+ fixture.expectNoUnexpectedRequests();
+});
+
+test('keeps a Timeline snapshot frozen and read-only', async ({ page }) => {
+ const fixture = await openTimeline(page);
+ await page.getByRole('button', { name: /^Views/ }).click();
+ await page.getByRole('button', { name: 'Save view' }).click();
+ const dialog = page.getByRole('dialog', { name: 'Save analysis view' });
+ await dialog.getByLabel('Name').fill('Frozen chronology');
+ await dialog.getByLabel('Snapshot').check();
+ await dialog.getByRole('button', { name: 'Save', exact: true }).click();
+
+ await expect(page.locator('.views .active')).toContainText('snapshot');
+ await expect(page.getByText('Frozen view', { exact: true })).toBeVisible();
+ await expect(page.getByRole('button', { name: 'Track', exact: true })).toBeDisabled();
+ await expect(page.getByLabel('Group by')).toBeDisabled();
+ await expect(page.getByTitle('Which clock the axis is labelled with')).toBeDisabled();
+ await expect(page.getByRole('button', { name: /Witness arrived/ }).first()).toBeVisible();
+ expect(fixture.analysisWrites.at(-1)).toMatchObject({
+ method: 'POST',
+ body: { mode: 'snapshot', surface: 'timeline' },
+ });
+ fixture.expectNoUnexpectedRequests();
+});
+
+test('creates a dated statement from a point on the axis', async ({ page }) => {
+ const fixture = await openTimeline(page);
+ const canvas = page.locator('.track-canvas').first();
+ const box = await canvas.boundingBox();
+
+ await page.mouse.click(box.x + box.width * 0.72, box.y + box.height - 8);
+ const dialog = page.getByRole('dialog', { name: 'Add assessment' });
+ await expect(dialog).toBeVisible();
+ await expect(dialog.getByLabel('When')).not.toHaveValue('');
+ await dialog.getByLabel('Statement').fill('A second witness reached the checkpoint');
+ await dialog.getByRole('button', { name: 'Add assessment' }).click();
+
+ await expect.poll(() => fixture.timelineWrites.length).toBe(1);
+ expect(fixture.timelineWrites[0]).toMatchObject({
+ method: 'POST',
+ body: { statement: 'A second witness reached the checkpoint' },
+ });
+ await expect(page.getByRole('button', { name: /A second witness/ })).toBeVisible();
+ fixture.expectNoUnexpectedRequests();
+});
+
+test('pans from the ruler and zooms with the wheel', async ({ page }) => {
+ await openTimeline(page);
+ const before = await axisWindowText(page);
+ const ruler = page.locator('.axis-ruler');
+ const box = await ruler.boundingBox();
+
+ await page.mouse.move(box.x + box.width * 0.5, box.y + box.height * 0.5);
+ await page.mouse.down();
+ await page.mouse.move(box.x + box.width * 0.68, box.y + box.height * 0.5, { steps: 5 });
+ await page.mouse.up();
+ await expect.poll(() => axisWindowText(page)).not.toBe(before);
+
+ const days = async () => {
+ const [start, end] = (await axisWindowText(page)).split(' to ');
+ return (new Date(`${end.replace(' ', 'T')}Z`) - new Date(`${start.replace(' ', 'T')}Z`)) / 86_400_000;
+ };
+ const beforeDays = await days();
+ await page.mouse.move(box.x + box.width * 0.72, box.y + box.height * 0.5);
+ await page.mouse.wheel(0, -120);
+ await expect.poll(days).toBeLessThan(beforeDays);
+});
+
+test('closes the legend outside and can use the whole screen', async ({ page }) => {
+ await openTimeline(page);
+ await page.getByText('Legend', { exact: true }).click();
+ await expect(page.getByText('Confidence and date quality are independent.')).toBeVisible();
+ await page.locator('.title-block').click();
+ await expect(page.getByText('Confidence and date quality are independent.')).toBeHidden();
+
+ await page.getByRole('button', { name: 'Full screen' }).click();
+ await expect.poll(() => page.evaluate(() => Boolean(document.fullscreenElement))).toBe(true);
+ await expect(page.getByRole('button', { name: 'Exit full screen' })).toBeVisible();
+ await page.getByRole('button', { name: 'Exit full screen' }).click();
+ await expect.poll(() => page.evaluate(() => Boolean(document.fullscreenElement))).toBe(false);
+});
+
+test('shows day precision across the full day without drawing a period', async ({ page }) => {
+ await openTimeline(page);
+ await setWindow(page, '2026-06-18T00:00', '2026-06-19T00:00');
+ await expect(page.getByRole('button', { name: /Witness arrived/ })).toBeVisible();
+
+ const canvas = page.locator('.track-canvas').first();
+ const span = page.locator('.precision-span.statement').first();
+ const [canvasBox, spanBox] = await Promise.all([canvas.boundingBox(), span.boundingBox()]);
+ expect(spanBox.width).toBeGreaterThan(canvasBox.width * .95);
+ expect(spanBox.height).toBeLessThan(12);
+});
+
+test('creates and resizes an hourly period on a day view', async ({ page }) => {
+ const fixture = await openTimeline(page);
+ await setWindow(page, '2026-06-23T00:00', '2026-06-24T00:00');
+
+ const canvas = page.locator('.track-canvas').first();
+ await expect(canvas).toHaveClass(/createable/);
+ await canvas.evaluate((element) => new Promise((resolve) => {
+ requestAnimationFrame(() => requestAnimationFrame(resolve));
+ }));
+ const box = await canvas.boundingBox();
+ const y = box.y + box.height - 8;
+ await canvas.hover({ position: { x: box.width * .4, y: box.height - 8 } });
+ await page.mouse.down();
+ await page.mouse.move(box.x + box.width * .5, y, { steps: 5 });
+ await page.mouse.up();
+
+ const dialog = page.getByRole('dialog', { name: 'Add assessment' });
+ await expect(dialog).toBeVisible();
+ await expect(dialog.getByLabel('Date format')).toHaveValue('time-range');
+ await expect(dialog.getByLabel('Start time')).toHaveValue(/2026-06-23T\d{2}:\d{2}(?::\d{2})?/);
+ await expect(dialog.getByLabel('End time')).toHaveValue(/2026-06-23T\d{2}:\d{2}(?::\d{2})?/);
+ await dialog.getByLabel('Statement').fill('Traffic peaked around the checkpoint');
+ await dialog.getByRole('button', { name: 'Add assessment' }).click();
+
+ await expect.poll(() => fixture.timelineWrites.length).toBe(1);
+ expect(fixture.timelineWrites[0].body.when).toMatch(
+ /^2026-06-23T\d{2}:\d{2}:\d{2}Z\/2026-06-23T\d{2}:\d{2}:\d{2}Z$/
+ );
+
+ const event = page.getByRole('button', { name: /Traffic peaked around/ });
+ await expect(event).toBeVisible();
+ await event.click();
+ const end = event.locator('..').locator('.resize.end');
+ const endBox = await end.boundingBox();
+ await page.mouse.move(endBox.x + endBox.width / 2, endBox.y + endBox.height / 2);
+ await page.mouse.down();
+ await page.mouse.move(endBox.x - 35, endBox.y + endBox.height / 2, { steps: 4 });
+ await page.mouse.up();
+ const confirm = page.getByRole('alertdialog', { name: 'Change this period?' });
+ await expect(confirm).toBeVisible();
+ await confirm.getByRole('button', { name: 'Update date' }).click();
+ await expect.poll(() => fixture.timelineWrites.length).toBe(2);
+ expect(fixture.timelineWrites[1]).toMatchObject({ method: 'PATCH' });
+ expect(fixture.timelineWrites[1].body.when).toContain('T');
+});
+
+test('keeps creation on Statements and offers the list view', async ({ page }) => {
+ await openTimeline(page);
+ const mediaCanvas = page.locator('.track-canvas').nth(1);
+ const box = await mediaCanvas.boundingBox();
+ await page.mouse.click(box.x + box.width * .7, box.y + box.height - 8);
+ await expect(page.getByRole('dialog', { name: 'Add assessment' })).toHaveCount(0);
+
+ await page.getByRole('button', { name: 'List' }).click();
+ await expect(page.getByRole('region', { name: 'Timeline list' })).toBeVisible();
+ await expect(page.getByRole('button', { name: /Second convoy cleared/ })).toBeVisible();
+});
+
+test('starts a media correction from the captured date', async ({ page }) => {
+ const fixture = await openTimeline(page);
+ await page.getByRole('button', { name: /Roadside camera frame/ }).click();
+ const inspector = page.locator('.inspector');
+ const correction = inspector.getByRole('button', { name: 'Add correction' });
+ await expect(correction).toBeEnabled();
+ await correction.click();
+
+ const dialog = page.getByRole('dialog', { name: 'Add assessment' });
+ await expect(dialog.getByLabel('Date format')).toHaveValue('timestamp');
+ await expect(dialog.getByLabel('Date and time')).toHaveValue('2026-06-23T18:42:11');
+ await expect(dialog.getByLabel('Timezone')).toHaveValue('utc');
+ await dialog.getByRole('button', { name: 'Add assessment' }).click();
+
+ await expect.poll(() => fixture.timelineWrites.length).toBe(1);
+ expect(fixture.timelineWrites[0]).toMatchObject({
+ method: 'POST',
+ body: {
+ statement: 'This media was captured',
+ when: '2026-06-23T18:42:11Z',
+ time_role: 'observed',
+ about: ['media-1'],
+ },
+ });
+});
+
+test('expands dense events in place and can collapse them again', async ({ page }) => {
+ await openTimeline(page);
+ const cluster = page.locator('.timeline-cluster').first();
+ await expect(cluster).toBeVisible();
+ const before = await page.locator('.timeline-event.statement').count();
+ await cluster.click();
+ await expect(page.getByRole('button', { name: 'Collapse' })).toBeVisible();
+ await expect(page.locator('.timeline-cluster')).toHaveCount(0);
+ expect(await page.locator('.timeline-event.statement').count()).toBeGreaterThan(before);
+ await page.getByRole('button', { name: 'Collapse' }).click();
+ await expect(page.locator('.timeline-cluster').first()).toBeVisible();
+});
+
+test('moves and resizes the overview window', async ({ page }) => {
+ await openTimeline(page);
+ const before = await axisWindowText(page);
+ const start = page.getByRole('button', { name: 'Change range start' });
+ const startBox = await start.boundingBox();
+ await page.mouse.move(startBox.x + startBox.width / 2, startBox.y + startBox.height / 2);
+ await page.mouse.down();
+ await page.mouse.move(startBox.x + 90, startBox.y + startBox.height / 2, { steps: 5 });
+ await page.mouse.up();
+ await expect.poll(() => axisWindowText(page)).not.toBe(before);
+
+ const narrowed = await axisWindowText(page);
+ const drag = page.getByRole('button', { name: 'Move visible range' });
+ const dragBox = await drag.boundingBox();
+ await page.mouse.move(dragBox.x + dragBox.width / 2, dragBox.y + dragBox.height / 2);
+ await page.mouse.down();
+ await page.mouse.move(dragBox.x + dragBox.width / 2 - 45, dragBox.y + dragBox.height / 2, { steps: 4 });
+ await page.mouse.up();
+ await expect.poll(() => axisWindowText(page)).not.toBe(narrowed);
+});
+
+test('moves and shortens a selected assessment on the axis', async ({ page }) => {
+ const fixture = await openTimeline(page);
+ const period = page.getByRole('button', { name: /Vehicle remained/ });
+ await period.click();
+ await expect(page.getByText('Drag to move. Use either edge to resize.')).toBeVisible();
+
+ const end = period.locator('..').locator('.resize.end');
+ const endBox = await end.boundingBox();
+ await page.mouse.move(endBox.x + endBox.width / 2, endBox.y + endBox.height / 2);
+ await page.mouse.down();
+ await page.mouse.move(endBox.x - 70, endBox.y + endBox.height / 2, { steps: 4 });
+ await page.mouse.up();
+
+ const confirm = page.getByRole('alertdialog', { name: 'Change this period?' });
+ await expect(confirm).toBeVisible();
+ await confirm.getByRole('button', { name: 'Update date' }).click();
+ await expect.poll(() => fixture.timelineWrites.length).toBe(1);
+ expect(fixture.timelineWrites[0]).toMatchObject({ method: 'PATCH', ownerId: 'claim-2' });
+ expect(fixture.timelineWrites[0].body.when).toMatch(/^2026-06-12\//);
+
+ const point = page.getByRole('button', { name: /Witness arrived/ });
+ await point.click();
+ const pointBox = await point.boundingBox();
+ await page.mouse.move(pointBox.x + pointBox.width / 2, pointBox.y + pointBox.height / 2);
+ await page.mouse.down();
+ await page.mouse.move(pointBox.x + pointBox.width / 2 + 65, pointBox.y + pointBox.height / 2, { steps: 4 });
+ await page.mouse.up();
+ await expect(page.getByRole('alertdialog', { name: 'Move this date?' })).toBeVisible();
+});
+
+test('validates advanced syntax before saving', async ({ page }) => {
+ await openTimeline(page);
+ await page.getByRole('button', { name: 'Add assessment' }).click();
+ const dialog = page.getByRole('dialog', { name: 'Add assessment' });
+ await dialog.getByLabel('Statement').fill('A dated observation');
+ await dialog.getByLabel('Date format').selectOption('advanced');
+ await dialog.getByLabel('When').fill('late summer');
+ await expect(dialog.getByText('Use a supported date or timestamp.')).toBeVisible();
+ await expect(dialog.getByRole('button', { name: 'Add assessment' })).toBeDisabled();
+ await dialog.getByText('Syntax guide').click();
+ await expect(dialog.getByRole('region', { name: 'Supported date syntax' })).toBeVisible();
+});
+
+test('keeps entity history in the same three-tab Details model', async ({ page }) => {
+ const fixture = await installAppFixture(page, {
+ catalog: [person, source],
+ timelineItems,
+ chains: {
+ 'person-1': { entity: person, sources: [], lost: [], dependents: [], relations: [], empty: true },
+ 'claim-1': claimChain('claim-1', timelineItem('claim-1').label, {
+ when: timelineItem('claim-1').raw, time_role: 'occurred', confidence: 'probable',
+ }),
+ 'claim-3': claimChain('claim-3', timelineItem('claim-3').label, { time_role: 'observed' }),
+ },
+ });
+ await page.goto('/#board');
+ await page.locator('tbody tr').filter({ hasText: person.label }).locator('td').first().click();
+ const details = page.getByRole('dialog', { name: 'Details' });
+ await expect(details.getByRole('tab')).toHaveText(['Info', 'Connections', 'Time']);
+ await details.getByRole('tab', { name: 'Time' }).click();
+
+ await expect(details.getByRole('heading', { name: 'Statements about this' })).toBeVisible();
+ await expect(details.getByText(timelineItem('claim-1').label, { exact: true })).toBeVisible();
+ await expect(details.getByText(timelineItem('claim-3').label, { exact: true })).toBeVisible();
+ await expect(details.getByRole('button', { name: 'Add time assessment' })).toBeVisible();
+ fixture.expectNoUnexpectedRequests();
+});
+
+test('opens the row handed over from the Time tab', async ({ page }) => {
+ await installAppFixture(page, {
+ catalog: [person, mediaEntity],
+ timelineItems,
+ chains: {
+ 'media-1': { entity: mediaEntity, sources: [], lost: [], dependents: [], relations: [], empty: true },
+ },
+ });
+ await page.goto('/#board');
+ await page.locator('tbody tr').filter({ hasText: mediaEntity.label }).locator('td').first().click();
+ const details = page.getByRole('dialog', { name: 'Details' });
+ await details.getByRole('tab', { name: 'Time' }).click();
+ await details.getByRole('button', { name: `Open ${mediaEntity.label} in Timeline` }).click();
+
+ // The chip scopes the axis and the named row opens, even though Timeline had
+ // loaded nothing at the moment Details handed it over.
+ await expect(page.locator('.scope-chip')).toContainText(mediaEntity.label);
+ const inspector = page.locator('.inspector');
+ await expect(inspector.getByRole('heading', { name: mediaEntity.label })).toBeVisible();
+ await expect(inspector.getByText('2026-06-23T18:42:11Z')).toBeVisible();
+});
+
+test('edits an existing assessment from the Time tab', async ({ page }) => {
+ const fixture = await installAppFixture(page, {
+ catalog: [person, source],
+ timelineItems,
+ chains: {
+ 'person-1': { entity: person, sources: [], lost: [], dependents: [], relations: [], empty: true },
+ 'claim-1': claimChain('claim-1', timelineItem('claim-1').label, {
+ when: timelineItem('claim-1').raw, time_role: 'occurred', confidence: 'probable',
+ }),
+ 'claim-3': claimChain('claim-3', timelineItem('claim-3').label, { time_role: 'observed' }),
+ },
+ });
+ await page.goto('/#board');
+ await page.locator('tbody tr').filter({ hasText: person.label }).locator('td').first().click();
+ const details = page.getByRole('dialog', { name: 'Details' });
+ await details.getByRole('tab', { name: 'Time' }).click();
+
+ await details.getByRole('button', { name: `Edit ${timelineItem('claim-1').label}` }).click();
+ const editor = details.getByRole('region', { name: 'Edit time assessment' });
+ await expect(editor.getByLabel('Statement')).toHaveValue(timelineItem('claim-1').label);
+ await editor.getByLabel('Statement').fill('Witness reached the north checkpoint');
+ await editor.getByRole('button', { name: 'Update assessment' }).click();
+
+ await expect.poll(() => fixture.timelineWrites.length).toBe(1);
+ expect(fixture.timelineWrites[0]).toMatchObject({
+ method: 'PATCH',
+ ownerId: 'claim-1',
+ body: { statement: 'Witness reached the north checkpoint' },
+ });
+});
+
+test('starts a new assessment from an empty form after editing one', async ({ page }) => {
+ await installAppFixture(page, {
+ catalog: [person, source],
+ timelineItems,
+ chains: {
+ 'person-1': { entity: person, sources: [], lost: [], dependents: [], relations: [], empty: true },
+ 'claim-1': claimChain('claim-1', timelineItem('claim-1').label, {
+ when: timelineItem('claim-1').raw, time_role: 'occurred', confidence: 'probable',
+ }),
+ 'claim-3': claimChain('claim-3', timelineItem('claim-3').label, { time_role: 'observed' }),
+ },
+ });
+ await page.goto('/#board');
+ await page.locator('tbody tr').filter({ hasText: person.label }).locator('td').first().click();
+ const details = page.getByRole('dialog', { name: 'Details' });
+ await details.getByRole('tab', { name: 'Time' }).click();
+
+ await details.getByRole('button', { name: `Edit ${timelineItem('claim-1').label}` }).click();
+ const editing = details.getByRole('region', { name: 'Edit time assessment' });
+ await expect(editing.getByLabel('Statement')).toHaveValue(timelineItem('claim-1').label);
+
+ await details.getByRole('button', { name: 'Add time assessment' }).click();
+ const adding = details.getByRole('region', { name: 'Add time assessment' });
+ await expect(adding.getByLabel('Statement')).toHaveValue('');
+ await expect(adding.getByLabel('When')).toHaveValue('');
+});
+
+test('shows an undated Claim as a missing statement date, not an existing assessment', async ({ page }) => {
+ const fixture = await installAppFixture(page, {
+ catalog: [undatedClaim],
+ timelineItems,
+ chains: {
+ 'claim-3': claimChain('claim-3', undatedClaim.label, undatedClaim.attrs),
+ },
+ });
+ await page.goto('/#board');
+ await page.locator('tbody tr').filter({ hasText: undatedClaim.label }).locator('td').first().click();
+ const details = page.getByRole('dialog', { name: 'Details' });
+ await details.getByRole('tab', { name: 'Time' }).click();
+
+ await expect(details.getByText('This statement has no date yet.')).toBeVisible();
+ await expect(details.getByText('A statement has one date or range.')).toBeVisible();
+ await expect(details.getByText('Undated', { exact: true })).toHaveCount(0);
+ await details.getByRole('button', { name: 'Set statement date' }).click();
+
+ const editor = details.getByRole('region', { name: 'Set statement date' });
+ await expect(editor.getByLabel('Statement')).toHaveValue(undatedClaim.label);
+ await editor.getByLabel('When').fill('2026-08-12');
+ await editor.getByRole('button', { name: 'Update assessment' }).click();
+
+ await expect.poll(() => fixture.timelineWrites.length).toBe(1);
+ expect(fixture.timelineWrites[0]).toMatchObject({
+ method: 'PATCH', ownerId: 'claim-3', body: { when: '2026-08-12' },
+ });
+});
+
+// --- the four surfaces answering one window ---
+//
+// The quay is a located place, and one statement in June is attached to it. The camera
+// frame sits three days outside the window used below, which is what lets these specs
+// tell "the period narrowed the case" apart from "everything was shown anyway".
+
+const quay = {
+ id: 'place-1',
+ type: 'place',
+ label: 'South quay',
+ attrs: { lat: 43.2965, lon: 5.3698 },
+ provenance: { by: 'user', at: '2026-08-01T09:05:00Z', status: 'confirmed' },
+};
+
+const placedItem = {
+ id: 'temporal:claim:claim-6', owner_id: 'claim-6', category: 'statement', kind: 'claim',
+ label: 'Crane moved along the south quay', raw: '2026-06-20',
+ earliest: '2026-06-20T00:00:00Z', latest: '2026-06-21T00:00:00Z', precision: 'day',
+ shape: 'instant', time_role: 'occurred', uncertain: false, approximate: false,
+ zone: 'date-only', sortable: true, status: 'confirmed', confidence: 'probable',
+ parse_error: null, subjects: [], places: ['place-1'], sources: [],
+};
+
+async function openTimelineOverJune(page, options = {}) {
+ const fixture = await openTimeline(page, {
+ catalog: [person, source, mediaEntity, quay],
+ timelineItems: [...timelineItems, placedItem],
+ ...options,
+ });
+ await setWindow(page, '2026-06-01T00:00', '2026-06-21T00:00');
+ await expect(page.getByRole('button', { name: '1 Jun – 21 Jun 2026' })).toBeVisible();
+ return fixture;
+}
+
+test('hands one window from the Timeline to the Map, the Board and back', async ({ page }) => {
+ const fixture = await openTimelineOverJune(page);
+ await page.getByRole('group', { name: 'Open range' }).getByRole('button', { name: 'Map' }).click();
+
+ const layer = page.getByLabel('Timeline map layer');
+ await expect(layer).toContainText('1 Jun – 21 Jun 2026');
+ // What the window holds, and how much of it the map can show: the layer reads
+ // every category the Timeline was reading, so the count is the whole window.
+ await expect(layer).toContainText('1 placed of 12 dated');
+ await expect(page.locator('.temporal-mark')).toHaveCount(1);
+
+ await layer.getByRole('button', { name: 'Board' }).click();
+
+ // The Board asks the server for the window rather than hiding rows it already has,
+ // and says which window it is answering.
+ await expect(page.getByLabel('Fact-time range')).toContainText('1 Jun – 21 Jun 2026');
+ await expect.poll(() => fixture.catalogQueries.at(-1)).toContain('temporal_from=2026-06-01');
+ await expect(page.locator('tbody tr')).toHaveText([
+ /Harbour witness/, /Interview notes/, /South quay/,
+ ]);
+
+ await page.getByLabel('Fact-time range').getByRole('button', { name: 'Timeline' }).click();
+
+ await expect(page.getByRole('heading', { name: 'Timeline', exact: true })).toBeVisible();
+ await expect(page.getByRole('button', { name: '1 Jun – 21 Jun 2026' })).toBeVisible();
+ fixture.expectNoUnexpectedRequests();
+});
+
+test('opens a statement in the Timeline from its mark on the map', async ({ page }) => {
+ const fixture = await openTimelineOverJune(page);
+ await page.getByRole('group', { name: 'Open range' }).getByRole('button', { name: 'Map' }).click();
+
+ await page.locator('.temporal-mark').click();
+ const popup = page.locator('.temporal-popup');
+ await expect(popup).toContainText('South quay');
+ await popup.getByRole('button', { name: /Crane moved along the south quay/ }).click();
+
+ const inspector = page.locator('.inspector');
+ await expect(inspector.getByRole('heading', { name: placedItem.label })).toBeVisible();
+ await expect(page.getByRole('button', { name: '1 Jun – 21 Jun 2026' })).toBeVisible();
+ fixture.expectNoUnexpectedRequests();
+});
+
+test('draws the window and nothing else, framed on what it holds', async ({ page }) => {
+ // The case has saved places nowhere near the window. They are not what a period was
+ // asked about, so the layer neither draws them nor lets them pull the frame out.
+ const fixture = await openTimelineOverJune(page, {
+ savedIndexes: {
+ [CASE_ID]: [
+ { id: 'place-far', key: 'place-far', kind: 'place', title: 'North depot', lat: 50.85, lon: 4.35 },
+ { id: 'place-quay', key: 'place-quay', kind: 'place', title: 'South quay', lat: 43.2965, lon: 5.3698 },
+ ],
+ },
+ });
+ await page.getByRole('group', { name: 'Open range' }).getByRole('button', { name: 'Map' }).click();
+
+ await expect(page.locator('.temporal-mark')).toHaveCount(1);
+ await expect(page.locator('.saved-mark-place')).toHaveCount(0);
+ await expect(page.getByRole('button', { name: 'Show saved work on the map' })).not.toHaveClass(/on/);
+
+ const framed = await page.evaluate(() => {
+ const map = document.querySelector('.map').getBoundingClientRect();
+ return [...document.querySelectorAll('.temporal-mark-wrap')].every((mark) => {
+ const box = mark.getBoundingClientRect();
+ return box.left >= map.left && box.right <= map.right
+ && box.top >= map.top && box.bottom <= map.bottom;
+ });
+ });
+ expect(framed).toBe(true);
+ fixture.expectNoUnexpectedRequests();
+});
+
+test('says a window holds nothing placed instead of pulling the map out to say it', async ({ page }) => {
+ const fixture = await openTimeline(page, {
+ catalog: [person, source, mediaEntity],
+ savedIndexes: {
+ [CASE_ID]: [
+ { id: 'place-far', key: 'place-far', kind: 'place', title: 'North depot', lat: 50.85, lon: 4.35 },
+ { id: 'place-south', key: 'place-south', kind: 'place', title: 'South site', lat: -23.5, lon: -46.6 },
+ ],
+ },
+ });
+ await setWindow(page, '2026-06-18T00:00', '2026-06-19T00:00');
+ await page.getByRole('group', { name: 'Open range' }).getByRole('button', { name: 'Map' }).click();
+
+ const layer = page.getByLabel('Timeline map layer');
+ await expect(layer).toContainText('None of the 10 dated here carries a place.');
+ // Nothing to draw is said in words, not by pulling the view out to two continents
+ // of unrelated pins, which is what a map showing everything looks like.
+ await expect(page.locator('.temporal-mark')).toHaveCount(0);
+ await expect(page.locator('.saved-mark-place')).toHaveCount(0);
+ fixture.expectNoUnexpectedRequests();
+});
diff --git a/frontend/src/App.svelte b/frontend/src/App.svelte
index 520532e..3dcf2a0 100644
--- a/frontend/src/App.svelte
+++ b/frontend/src/App.svelte
@@ -6,11 +6,15 @@
reloadCase,
toast,
updateState,
- checkForUpdateOnStart,
+ updatesState,
+ prefs,
+ checkForUpdatesOnStart,
toggleTheme,
} from './lib/state.svelte.js';
+ import { updateBadges } from './lib/staleness.js';
import { startEvents, onEvent } from './lib/events.js';
import {
+ CASE_WORKSPACE,
WORKSPACES,
TOOL_LABELS,
sidebarOpenForWorkspace,
@@ -18,6 +22,7 @@
toolFromHash,
} from './lib/workspaces.js';
import { createToolLoader } from './lib/toolLoader.js';
+ import { loadEntityTypes } from './lib/entityTypes.svelte.js';
import Icon from './components/Icon.svelte';
import Logo from './components/Logo.svelte';
import Wordmark from './components/Wordmark.svelte';
@@ -27,11 +32,16 @@
import UpdateModal from './components/UpdateModal.svelte';
import WorkspaceStopped from './components/WorkspaceStopped.svelte';
import { readStatus, stoppedBecause } from './lib/workspace.js';
+ import { analysisSearch, leaveAnalysisView } from './lib/analysisSearch.svelte.js';
- // The rail holds workspaces (docs/UI.md §3); tools are tabs inside them.
- // Settings lives behind the topbar gear instead — app plumbing, not part
- // of the working flow.
+ // The rail holds the pipeline workspaces (docs/UI.md §3); tools are tabs
+ // inside them. Two workspaces sit in the topbar rather than the rail: the
+ // case, which is what the stages file into, and Settings, which is app
+ // plumbing and not part of the working flow at all.
const TOOLS = [
+ { id: 'board', label: TOOL_LABELS.board, load: () => import('./tools/Board.svelte') },
+ { id: 'graph', label: TOOL_LABELS.graph, load: () => import('./tools/Graph.svelte') },
+ { id: 'timeline', label: TOOL_LABELS.timeline, load: () => import('./tools/Timeline.svelte') },
{ id: 'media', label: TOOL_LABELS.media, load: () => import('./tools/MediaLibrary.svelte') },
{ id: 'files', label: TOOL_LABELS.files, load: () => import('./tools/Files.svelte') },
{ id: 'reverse', label: TOOL_LABELS.reverse, load: () => import('./tools/ReverseSearch.svelte') },
@@ -46,6 +56,10 @@
...TOOLS,
{ id: 'settings', label: TOOL_LABELS.settings, load: () => import('./tools/Settings.svelte') },
];
+ // Settings is the only place anything can be updated from, and it sits out of
+ // the working flow — so a dot on its icon is how the app mentions it at all.
+ let badges = $derived(updateBadges(updatesState, prefs.updateDismissedVersion));
+
const loader = createToolLoader(Object.fromEntries(ALL_TOOLS.map((tool) => [tool.id, tool.load])));
let toolComponents = $state.raw({});
let toolErrors = $state.raw({});
@@ -60,6 +74,17 @@
history.replaceState(null, '', `#${uiState.tool}`);
});
+ // A frozen reading belongs to the surface that captured it. Carrying a Graph
+ // snapshot into Board made the capture look like an incomplete second case and
+ // could leave a hidden Details id waiting for the next live read. Changing tools
+ // is therefore leaving the snapshot; live recipes still share their question.
+ $effect(() => {
+ for (const view of [analysisSearch.catalog.activeView, analysisSearch.timeline.activeView]) {
+ if (view?.mode !== 'snapshot' || uiState.tool === view.surface) continue;
+ leaveAnalysisView(caseState.current?.id, view.surface, { clear: true });
+ }
+ });
+
// Workspace navigation: clicking a workspace returns to its last-used tab.
const activeWs = $derived(workspaceOf(uiState.tool));
const lastTool = $state({});
@@ -119,13 +144,20 @@
})
.catch(() => {});
+ // The entity vocabulary: types, families, icons and the fields a form is built
+ // from. It is code rather than case data, so it is fetched once here and shared —
+ // and asking at startup is what keeps a row from painting under a fallback icon
+ // before the first surface that needs the registry happens to ask for it.
+ loadEntityTypes();
+
// Load the case list and reopen the last-used case (survives reloads), then
- // — once preferences have landed — see whether a newer release is out and
- // pop a notice. The check reads prefs.updateCheckOnStart, so it must follow
- // initSession, which loads them.
+ // — once preferences have landed — see what is behind: the app, the
+ // downloaders, the capture extension. The check reads prefs.updateCheckOnStart
+ // and the bundled extension version, so it must follow initSession, which
+ // loads them.
initSession()
.catch(() => {})
- .finally(() => checkForUpdateOnStart());
+ .finally(() => checkForUpdatesOnStart());
// Live nudges from our own backend (SSE, same-origin — still local-first):
// the capture extension files screenshots while this tab just sits here, and
@@ -151,15 +183,29 @@
<Logo size={27} />
<span class="brand-name"><Wordmark height={13} /></span>
</div>
- <CaseSwitcher />
+ <div class="case-group">
+ <CaseSwitcher />
+ <button
+ class="btn btn-ghost case-btn"
+ class:topbar-active={activeWs?.id === CASE_WORKSPACE.id}
+ title="Open the case board"
+ onclick={() => openWorkspace(CASE_WORKSPACE)}
+ >
+ <Icon name={CASE_WORKSPACE.icon} size={16} />
+ <span>{TOOL_LABELS.board}</span>
+ </button>
+ </div>
<div class="spacer"></div>
<button
- class="btn btn-ghost btn-sm"
- class:gear-active={uiState.tool === 'settings'}
- title="Settings"
+ class="btn btn-ghost btn-sm dotted"
+ class:topbar-active={uiState.tool === 'settings'}
+ title={badges.any ? 'Settings · something to install or update' : 'Settings'}
onclick={() => (uiState.tool = 'settings')}
>
<Icon name="settings" size={16} />
+ {#if badges.any}
+ <span class="update-dot" aria-label="something to install or update"></span>
+ {/if}
</button>
<button
class="btn btn-ghost btn-sm"
@@ -277,7 +323,31 @@
.spacer {
flex: 1;
}
- .gear-active {
+ /* the switcher and the board button are one control — which case, then open
+ it. Both carry the same weight, and the hairline is what says they belong
+ together: their own padding leaves too much air for proximity alone to. */
+ .case-group {
+ display: flex;
+ align-items: center;
+ }
+ .case-btn {
+ position: relative;
+ margin-left: 13px;
+ gap: 8px;
+ padding: 6px 12px;
+ font-size: var(--fs-sm);
+ font-weight: 600;
+ }
+ .case-btn::before {
+ content: '';
+ position: absolute;
+ left: -7px;
+ top: 5px;
+ bottom: 5px;
+ width: 1px;
+ background: var(--border);
+ }
+ .topbar-active {
color: var(--text-1);
background: var(--bg-2);
}
diff --git a/frontend/src/app.css b/frontend/src/app.css
index 53fbe8a..b9dad70 100644
--- a/frontend/src/app.css
+++ b/frontend/src/app.css
@@ -47,6 +47,25 @@
--sky-sun: #bd8721;
--sky-moon: #4a93cc;
+ /* Case-graph families (ONTOLOGY §2). Eight hues that have to separate from each
+ other *and* stay quiet: the graph's meaning rides on the stroke, so colour
+ only says which family a node belongs to. Not --accent, which stays reserved
+ for selection so a selected node reads as selected whatever its family, and
+ not the annotation palette, which is sized for contrast over imagery. */
+ --graph-actor: #7aa2d6;
+ --graph-asset: #6fb3a8;
+ --graph-class: #bfa14e;
+ --graph-identifier: #a892cc;
+ --graph-collected: #c98f6b;
+ --graph-document: #8f9aa8;
+ --graph-place: #7fb069;
+ --graph-claim: #cf8ba0;
+
+ /* Timeline categories. Status and selection still use their own tokens. */
+ --timeline-statement: #50bda8;
+ --timeline-media: #7896f0;
+ --timeline-activity: #a487d1;
+
/* -- typography --------------------------------------------- */
--font-sans: ui-sans-serif, system-ui, -apple-system, "Segoe UI", Roboto,
"Helvetica Neue", Arial, sans-serif;
@@ -111,6 +130,20 @@
--sky-sun: #cc9526;
--sky-moon: #3f97d2;
+ /* graph families, darkened for a white canvas rather than flipped */
+ --graph-actor: #3f6ea8;
+ --graph-asset: #2f7f72;
+ --graph-class: #85661a;
+ --graph-identifier: #6f57a0;
+ --graph-collected: #a35f34;
+ --graph-document: #5b6674;
+ --graph-place: #4a7f36;
+ --graph-claim: #a35470;
+
+ --timeline-statement: #1f7669;
+ --timeline-media: #4264b5;
+ --timeline-activity: #76539d;
+
--shadow-1: 0 1px 3px rgba(0, 0, 0, 0.12);
--shadow-2: 0 8px 28px rgba(0, 0, 0, 0.16);
@@ -146,6 +179,9 @@
--danger-soft: rgba(217, 112, 112, 0.12);
--info: #6f9fd8;
--info-soft: rgba(111, 159, 216, 0.12);
+ --timeline-statement: #50bda8;
+ --timeline-media: #7896f0;
+ --timeline-activity: #a487d1;
--shadow-1: 0 1px 3px rgba(0, 0, 0, 0.4);
--shadow-2: 0 8px 28px rgba(0, 0, 0, 0.5);
}
@@ -396,6 +432,27 @@ a:hover {
color: var(--danger);
}
+/* "Something here can be updated", from the Settings icon down to the button
+ that does it. One dot, one meaning, wherever it lands. The host carries
+ .dotted to anchor it.
+
+ It hangs off the top-right corner rather than sitting inside: on a primary
+ button the inside is amber on amber, and on any button with a label the dot
+ lands on the words. */
+.dotted {
+ position: relative;
+}
+.update-dot {
+ position: absolute;
+ top: -3px;
+ right: -3px;
+ width: 8px;
+ height: 8px;
+ border-radius: 50%;
+ background: var(--accent);
+ pointer-events: none;
+}
+
/* Empty states — every tool has one, they must feel designed. */
.empty {
display: flex;
diff --git a/frontend/src/components/AnalysisPeriodBar.render.test.js b/frontend/src/components/AnalysisPeriodBar.render.test.js
new file mode 100644
index 0000000..6a36a85
--- /dev/null
+++ b/frontend/src/components/AnalysisPeriodBar.render.test.js
@@ -0,0 +1,53 @@
+// @vitest-environment happy-dom
+import { afterEach, describe, expect, it, vi } from 'vitest';
+import { flushSync, mount, unmount } from 'svelte';
+import AnalysisPeriodBar from './AnalysisPeriodBar.svelte';
+
+let live = null;
+
+function open(props = {}) {
+ const target = document.createElement('div');
+ document.body.append(target);
+ live = mount(AnalysisPeriodBar, {
+ target,
+ props: {
+ period: { from: '2026-08-23T20:49:00Z', to: '2026-10-01T10:12:00Z' },
+ ...props,
+ },
+ });
+ flushSync();
+ return target;
+}
+
+afterEach(() => {
+ if (live) unmount(live);
+ live = null;
+ document.body.innerHTML = '';
+});
+
+describe('AnalysisPeriodBar', () => {
+ it('states the fact-time window being applied', () => {
+ const root = open();
+
+ expect(root.querySelector('[aria-label="Fact-time range"]').textContent).toContain(
+ 'Fact time · 23 Aug – 1 Oct 2026'
+ );
+ });
+
+ it('hands off to Timeline and Map, or clears the window', () => {
+ const ontimeline = vi.fn();
+ const onmap = vi.fn();
+ const onclear = vi.fn();
+ const root = open({ ontimeline, onmap, onclear });
+ const buttons = [...root.querySelectorAll('button')];
+
+ buttons.find((button) => button.textContent.trim() === 'Timeline').click();
+ buttons.find((button) => button.textContent.trim() === 'Map').click();
+ buttons.find((button) => button.textContent.trim() === 'Clear').click();
+ flushSync();
+
+ expect(ontimeline).toHaveBeenCalledOnce();
+ expect(onmap).toHaveBeenCalledOnce();
+ expect(onclear).toHaveBeenCalledOnce();
+ });
+});
diff --git a/frontend/src/components/AnalysisPeriodBar.svelte b/frontend/src/components/AnalysisPeriodBar.svelte
new file mode 100644
index 0000000..853ebc8
--- /dev/null
+++ b/frontend/src/components/AnalysisPeriodBar.svelte
@@ -0,0 +1,56 @@
+<script>
+ import { windowWords } from '../lib/timeline.js';
+
+ let {
+ period,
+ ontimeline = () => {},
+ onmap = () => {},
+ onclear = () => {},
+ } = $props();
+
+ const words = $derived(windowWords(period?.from, period?.to, 'UTC'));
+</script>
+
+<div class="analysis-period" aria-label="Fact-time range">
+ <span><strong>Fact time</strong> · {words}</span>
+ <button class="as-link" onclick={ontimeline}>Timeline</button>
+ <button class="as-link" onclick={onmap}>Map</button>
+ <button class="as-link quiet" onclick={onclear}>Clear</button>
+</div>
+
+<style>
+ .analysis-period {
+ display: flex;
+ align-items: center;
+ gap: 10px;
+ padding: 6px 16px;
+ border-bottom: 1px solid var(--border);
+ background: var(--accent-soft);
+ color: var(--text-2);
+ font-size: var(--fs-xs);
+ }
+ .analysis-period span {
+ flex: 1;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ }
+ .analysis-period strong {
+ color: var(--text-1);
+ font-weight: 600;
+ }
+ .as-link {
+ padding: 0;
+ border: 0;
+ background: none;
+ color: var(--accent);
+ font: inherit;
+ cursor: pointer;
+ }
+ .as-link:hover {
+ text-decoration: underline;
+ }
+ .quiet {
+ color: var(--text-3);
+ }
+</style>
diff --git a/frontend/src/components/AnalysisViews.svelte b/frontend/src/components/AnalysisViews.svelte
new file mode 100644
index 0000000..fa58137
--- /dev/null
+++ b/frontend/src/components/AnalysisViews.svelte
@@ -0,0 +1,406 @@
+<script>
+ /** Named, case-owned readings. Board and Graph share a family of views; the
+ * Timeline has its own — see `lib/analysisSearch.svelte.js`. */
+ import { api } from '../lib/api.js';
+ import {
+ activateAnalysisView,
+ adoptSavedAnalysisView,
+ leaveAnalysisView,
+ viewFamily,
+ viewSlot,
+ } from '../lib/analysisSearch.svelte.js';
+ import { copyName } from '../lib/analysisViews.js';
+ import { closeOnOutsidePointer } from '../lib/dismiss.js';
+ import { restoreGroup } from '../lib/trash.js';
+ import { caseState, registerCaseChangeGuard, toast } from '../lib/state.svelte.js';
+ import Icon from './Icon.svelte';
+ import Modal from './Modal.svelte';
+
+ let {
+ surface = 'board',
+ capture = () => ({}),
+ onopen = () => {},
+ onleave = () => {},
+ } = $props();
+
+ /**
+ * The views this surface can open, and the slot it reads.
+ *
+ * Board and Graph draw one question, so they share both. The Timeline asks about
+ * time and shares with neither: a list mixing the two offered readings that the
+ * surface underneath could not draw.
+ */
+ const family = $derived(viewFamily(surface));
+ const slot = $derived(viewSlot(surface));
+ let stored = $state([]);
+ const views = $derived(stored.filter((view) => viewFamily(view.surface) === family));
+ let menu = $state(false);
+ let anchor = $state(null);
+ let saving = $state(false);
+ let name = $state('');
+ let mode = $state('live');
+ let busy = $state(false);
+ let loadedFor = null;
+ let readRun = 0;
+ let autoTimer = 0;
+ let activeSave = null;
+ const AUTO_SAVE_AFTER = 650;
+ const snapshotNote = $derived(
+ surface === 'timeline'
+ ? 'Freezes up to 5,000 timeline entries.'
+ : 'Freezes up to 2,000 entities and their relations.'
+ );
+
+ const activeStatus = $derived.by(() => {
+ if (slot.activeView?.mode !== 'live') return 'snapshot';
+ if (slot.saveState === 'error') return 'live · save failed';
+ if (slot.modified || slot.saveState === 'saving') {
+ return 'live · saving…';
+ }
+ return 'live · saved';
+ });
+
+ async function read() {
+ const caseId = caseState.current?.id;
+ const run = ++readRun;
+ if (!caseId) {
+ stored = [];
+ return;
+ }
+ try {
+ const body = await api.get(`/api/cases/${caseId}/analysis-views`);
+ if (run === readRun && caseState.current?.id === caseId) stored = body.views ?? [];
+ } catch {
+ if (run === readRun) stored = [];
+ }
+ }
+
+ $effect(() => {
+ const caseId = caseState.current?.id ?? null;
+ if (caseId === loadedFor) return;
+ loadedFor = caseId;
+ menu = false;
+ saving = false;
+ void read();
+ });
+
+ function updateSummary(view) {
+ stored = stored.map((row) => row.id === view.id
+ ? {
+ ...row,
+ name: view.name,
+ mode: view.mode,
+ surface: view.surface,
+ updated_at: view.updated_at,
+ }
+ : row);
+ }
+
+ /** Save the active recipe without reopening it over edits made while the request
+ * was in flight. Concurrent requests queue behind the same promise. */
+ async function persistActive() {
+ while (activeSave) await activeSave;
+ const caseId = caseState.current?.id;
+ const current = slot.activeView;
+ if (
+ !caseId || !current || current.mode !== 'live' || current.surface !== surface ||
+ !slot.modified
+ ) return true;
+
+ const viewId = current.id;
+ const version = slot.changeVersion;
+ slot.saveState = 'saving';
+ const request = (async () => {
+ try {
+ const spec = await capture('live');
+ const view = await api.put(`/api/cases/${caseId}/analysis-views/${viewId}`, {
+ name: current.name,
+ mode: 'live',
+ surface: current.surface,
+ spec,
+ });
+ if (!adoptSavedAnalysisView(caseId, view)) return true;
+ updateSummary(view);
+ if (slot.changeVersion === version) {
+ slot.modified = false;
+ slot.saveState = 'saved';
+ }
+ return true;
+ } catch (error) {
+ if (
+ caseState.current?.id === caseId &&
+ slot.activeView?.id === viewId
+ ) slot.saveState = 'error';
+ toast(error.message || 'The live view could not be saved.', 'danger');
+ return false;
+ }
+ })();
+ activeSave = request;
+ try {
+ return await request;
+ } finally {
+ if (activeSave === request) activeSave = null;
+ }
+ }
+
+ $effect(() => {
+ const caseId = caseState.current?.id;
+ const current = slot.activeView;
+ // Read every edit revision even while `modified` was already true, so typing,
+ // repeated drags and consecutive folds restart one quiet-period timer.
+ void slot.changeVersion;
+ clearTimeout(autoTimer);
+ autoTimer = 0;
+ if (!caseId || !current || current.mode !== 'live' || current.surface !== surface) return;
+ if (!slot.modified) {
+ if (!activeSave && slot.saveState !== 'saved') {
+ slot.saveState = 'saved';
+ }
+ return;
+ }
+ slot.saveState = 'saving';
+ autoTimer = setTimeout(() => {
+ autoTimer = 0;
+ void persistActive();
+ }, AUTO_SAVE_AFTER);
+ return () => {
+ clearTimeout(autoTimer);
+ autoTimer = 0;
+ };
+ });
+
+ // A case switch is allowed only after this surface has filed its last live edit.
+ // `openCase` runs the guard while the old case is still current, so the request
+ // can never be sent to the case being opened.
+ $effect(() => registerCaseChangeGuard(() => persistActive()));
+
+ // A fast tool switch must not strand the last edit inside the debounce window.
+ $effect(() => () => {
+ clearTimeout(autoTimer);
+ autoTimer = 0;
+ if (
+ slot.activeView?.mode === 'live' &&
+ slot.activeView?.surface === surface &&
+ slot.modified
+ ) void persistActive();
+ });
+
+ // A menu is dismissed by pressing somewhere else, like every other popover here.
+ $effect(() => menu ? closeOnOutsidePointer(anchor, () => (menu = false)) : undefined);
+
+ async function open(viewId) {
+ const caseId = caseState.current?.id;
+ if (!caseId || busy) return;
+ if (!(await persistActive())) return;
+ busy = true;
+ try {
+ const view = await api.get(`/api/cases/${caseId}/analysis-views/${viewId}`);
+ activateAnalysisView(caseId, view);
+ await onopen(view);
+ menu = false;
+ } catch (error) {
+ toast(error.message, 'danger');
+ } finally {
+ busy = false;
+ }
+ }
+
+ async function save() {
+ const caseId = caseState.current?.id;
+ if (!caseId || !name.trim() || busy) return;
+ busy = true;
+ try {
+ const spec = await capture(mode);
+ const view = await api.post(`/api/cases/${caseId}/analysis-views`, {
+ name: name.trim(), mode, surface, spec,
+ });
+ activateAnalysisView(caseId, view);
+ await onopen(view);
+ saving = false;
+ name = '';
+ await read();
+ toast(`Saved view “${view.name}”`, 'ok');
+ } catch (error) {
+ toast(error.message, 'danger');
+ } finally {
+ busy = false;
+ }
+ }
+
+ async function duplicate(viewId) {
+ const caseId = caseState.current?.id;
+ if (!caseId) return;
+ try {
+ const source = views.find((view) => view.id === viewId);
+ if (!source) return;
+ await api.post(`/api/cases/${caseId}/analysis-views/${viewId}/duplicate`, {
+ name: copyName(source.name, views.map((view) => view.name)),
+ });
+ await read();
+ } catch (error) {
+ toast(error.message, 'danger');
+ }
+ }
+
+ async function remove(view) {
+ const caseId = caseState.current?.id;
+ if (!caseId) return;
+ try {
+ const result = await api.del(`/api/cases/${caseId}/analysis-views/${view.id}`);
+ if (slot.activeView?.id === view.id) {
+ leaveAnalysisView(caseId, surface);
+ await onleave();
+ }
+ await read();
+ toast(`Deleted “${view.name}”`, 'info', 7000, {
+ label: 'Undo',
+ onClick: async () => {
+ try {
+ await restoreGroup(caseId, result.trash);
+ await read();
+ toast('Restored', 'ok');
+ } catch (error) {
+ toast(error.message, 'danger');
+ }
+ },
+ });
+ } catch (error) {
+ toast(error.message, 'danger');
+ }
+ }
+
+ async function leave() {
+ const caseId = caseState.current?.id;
+ if (!(await persistActive())) return;
+ leaveAnalysisView(caseId, surface, { clear: true });
+ await onleave();
+ }
+</script>
+
+<div class="views">
+ {#if slot.activeView}
+ <span class="active" title={slot.activeView.mode === 'snapshot'
+ ? `Captured ${slot.activeView.spec?.snapshot?.captured_at ?? ''}`
+ : 'Recomputed from the current case'}>
+ <Icon name={slot.activeView.mode === 'snapshot' ? 'clock' : 'layers'} size={12} />
+ {slot.activeView.name}
+ <em aria-live="polite">{activeStatus}</em>
+ <button aria-label="Leave saved view" title="Leave this view" onclick={leave}>
+ <Icon name="x" size={10} />
+ </button>
+ </span>
+ {/if}
+
+ <div class="anchor" bind:this={anchor}>
+ <button
+ class="btn btn-sm"
+ aria-expanded={menu}
+ disabled={!caseState.current}
+ onclick={() => (menu = !menu)}
+ >
+ <Icon name="layers" size={13} /> Views{views.length ? ` ${views.length}` : ''}
+ </button>
+ {#if menu}
+ <div class="menu">
+ <div class="menu-actions">
+ <button
+ class="btn btn-sm btn-primary"
+ disabled={slot.activeView?.mode === 'snapshot'}
+ title={slot.activeView?.mode === 'snapshot'
+ ? 'Duplicate the snapshot to keep another copy.'
+ : 'Save the current question as a named view.'}
+ onclick={() => ((saving = true), (menu = false))}
+ >
+ <Icon name="save" size={12} /> Save view
+ </button>
+ </div>
+ {#if views.length}
+ <ul>
+ {#each views as view (view.id)}
+ <li>
+ <button class="open" disabled={busy} onclick={() => open(view.id)}>
+ <strong>{view.name}</strong>
+ <span>
+ {view.mode === 'snapshot' ? `${view.snapshot_count} captured` : 'live'}
+ {#if family === 'catalog'}· {view.surface}{/if}
+ </span>
+ </button>
+ <button title="Duplicate view" aria-label="Duplicate {view.name}" onclick={() => duplicate(view.id)}>
+ <Icon name="copy" size={12} />
+ </button>
+ <button title="Delete view" aria-label="Delete {view.name}" onclick={() => remove(view)}>
+ <Icon name="trash" size={12} />
+ </button>
+ </li>
+ {/each}
+ </ul>
+ {:else}
+ <p class="empty">
+ {family === 'timeline' ? 'No saved timeline views yet.' : 'No saved board or graph views yet.'}
+ </p>
+ {/if}
+ </div>
+ {/if}
+ </div>
+</div>
+
+{#if saving}
+ <Modal title="Save analysis view" onclose={() => (saving = false)} width="460px">
+ <div class="save-form">
+ <label>
+ Name
+ <input class="input" bind:value={name} maxlength="80" />
+ </label>
+ <label class="choice">
+ <input type="radio" bind:group={mode} value="live" />
+ <span><strong>Live</strong><small>Recomputes the question from the current case.</small></span>
+ </label>
+ <label class="choice">
+ <input type="radio" bind:group={mode} value="snapshot" />
+ <span><strong>Snapshot</strong><small>{snapshotNote}</small></span>
+ </label>
+ <div class="save-actions">
+ <button class="btn" onclick={() => (saving = false)}>Cancel</button>
+ <button class="btn btn-primary" disabled={!name.trim() || busy} onclick={save}>
+ {busy ? 'Saving…' : 'Save'}
+ </button>
+ </div>
+ </div>
+ </Modal>
+{/if}
+
+<style>
+ .views { display: flex; align-items: center; gap: 8px; }
+ .anchor { position: relative; }
+ .active {
+ display: inline-flex; align-items: center; gap: 5px; max-width: 280px;
+ padding: 4px 7px; border: 1px solid var(--border); border-radius: var(--r-sm);
+ color: var(--text-2); font-size: var(--fs-xs); background: var(--bg-2);
+ }
+ .active > :global(svg) { flex: 0 0 auto; color: var(--accent); }
+ .active em { color: var(--text-3); font-style: normal; }
+ .active button { display: flex; color: var(--text-3); }
+ .menu {
+ position: absolute; z-index: 80; top: calc(100% + 5px); right: 0; width: 360px;
+ padding: 8px; border: 1px solid var(--border-strong); border-radius: var(--r-md);
+ background: var(--bg-1); box-shadow: var(--shadow-2);
+ }
+ .menu-actions { display: flex; gap: 6px; padding-bottom: 7px; border-bottom: 1px solid var(--border); }
+ /* The list's own reset: without it the browser's 40px marker gutter left an empty
+ column down the left of every row. */
+ ul { max-height: 310px; margin: 6px 0 0; padding: 0; list-style: none; overflow: auto; }
+ li { display: grid; grid-template-columns: minmax(0, 1fr) auto auto; align-items: center; gap: 2px; }
+ li:hover { background: var(--bg-2); }
+ li > button:not(.open) { display: flex; padding: 7px 5px; color: var(--text-3); }
+ .open { min-width: 0; padding: 7px; text-align: left; }
+ .open strong, .open span { display: block; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
+ .open strong { color: var(--text-1); font-size: var(--fs-sm); }
+ .open span { margin-top: 2px; color: var(--text-3); font-size: var(--fs-xs); }
+ .empty { padding: 18px 8px 10px; text-align: center; color: var(--text-3); font-size: var(--fs-sm); }
+ .save-form { display: grid; gap: 12px; }
+ .save-form > label:first-child { display: grid; gap: 5px; color: var(--text-2); font-size: var(--fs-sm); }
+ .choice { display: flex; align-items: flex-start; gap: 9px; padding: 9px; border: 1px solid var(--border); border-radius: var(--r-sm); }
+ .choice span, .choice small { display: block; }
+ .choice small { margin-top: 3px; color: var(--text-3); }
+ .save-actions { display: flex; justify-content: flex-end; gap: 8px; margin-top: 4px; }
+</style>
diff --git a/frontend/src/components/AnalysisViews.test.js b/frontend/src/components/AnalysisViews.test.js
new file mode 100644
index 0000000..4945203
--- /dev/null
+++ b/frontend/src/components/AnalysisViews.test.js
@@ -0,0 +1,71 @@
+import { describe, expect, it } from 'vitest';
+import { readFileSync } from 'node:fs';
+
+const source = readFileSync(new URL('./AnalysisViews.svelte', import.meta.url), 'utf8');
+
+describe('saved analysis views', () => {
+ it('offers live and frozen readings, with the difference stated in the dialog', () => {
+ expect(source).toContain('value="live"');
+ expect(source).toContain('Recomputes the question from the current case.');
+ expect(source).toContain('value="snapshot"');
+ expect(source).toContain("surface === 'timeline'");
+ expect(source).toContain('Freezes up to 5,000 timeline entries.');
+ expect(source).toContain('Freezes up to 2,000 entities and their relations.');
+ });
+
+ it('can open, duplicate and trash a case-owned reading', () => {
+ expect(source).toContain('/analysis-views`');
+ expect(source).toContain('/duplicate`');
+ expect(source).toContain('Duplicate view');
+ expect(source).toContain('restoreGroup(caseId, result.trash)');
+ expect(source).not.toContain('Export view');
+ expect(source).not.toContain('Import');
+ });
+
+ it('autosaves a live recipe and exposes the current save state', () => {
+ expect(source).toContain("slot.activeView.mode === 'snapshot'");
+ expect(source).toContain("return 'live · saving…'");
+ expect(source).toContain("return 'live · saved'");
+ expect(source).toContain('aria-live="polite"');
+ expect(source).toContain('AUTO_SAVE_AFTER');
+ expect(source).toContain('setTimeout(() =>');
+ expect(source).not.toContain('aria-label="Update saved view"');
+ expect(source).toContain("api.put(`/api/cases/${caseId}/analysis-views/${viewId}`");
+ });
+
+ it('does not replay an autosave response over a newer edit', () => {
+ expect(source).toContain('adoptSavedAnalysisView(caseId, view)');
+ expect(source).toContain('slot.changeVersion === version');
+ expect(source).not.toContain('await onopen(view);\n await read();\n toast(`Updated');
+ });
+
+ it('flushes the active live view before a case switch', () => {
+ expect(source).toContain('registerCaseChangeGuard(() => persistActive())');
+ expect(source).toContain("current.surface !== surface");
+ });
+
+ it('offers only the readings this surface can draw, and says so when there are none', () => {
+ expect(source).toContain('const family = $derived(viewFamily(surface))');
+ expect(source).toContain('const slot = $derived(viewSlot(surface))');
+ expect(source).toContain("stored.filter((view) => viewFamily(view.surface) === family)");
+ expect(source).toContain('No saved timeline views yet.');
+ expect(source).toContain('No saved board or graph views yet.');
+ // the surface is worth naming only where the family holds two of them
+ expect(source).toContain("{#if family === 'catalog'}· {view.surface}{/if}");
+ });
+
+ it('closes the menu on a press outside it, and resets the list gutter', () => {
+ expect(source).toContain('closeOnOutsidePointer(anchor, () => (menu = false))');
+ expect(source).toContain('list-style: none');
+ });
+
+ it('cancels a pending save when the recipe is changed back', () => {
+ expect(source).toContain("if (!slot.modified) {");
+ expect(source).toContain("slot.saveState = 'saved'");
+ });
+
+ it('keeps a snapshot immutable instead of recapturing it under the same name', () => {
+ expect(source).toContain("disabled={slot.activeView?.mode === 'snapshot'}");
+ expect(source).toContain('Duplicate the snapshot to keep another copy.');
+ });
+});
diff --git a/frontend/src/components/AttrFields.render.test.js b/frontend/src/components/AttrFields.render.test.js
new file mode 100644
index 0000000..4e3e6b4
--- /dev/null
+++ b/frontend/src/components/AttrFields.render.test.js
@@ -0,0 +1,419 @@
+// @vitest-environment happy-dom
+/**
+ * The generated fields, actually mounted and actually typed into.
+ *
+ * Its sibling suite reads the source, which cannot tell whether a controlled input
+ * accepts a keystroke or silently reverts it — the failure an analyst reports as
+ * "I can't put anything in these boxes". So this one drives the DOM.
+ */
+import { describe, expect, it, vi, afterEach } from 'vitest';
+import { flushSync, mount, unmount } from 'svelte';
+
+const FIELDS = [
+ {
+ key: 'radius_m',
+ label: 'Uncertainty radius (m)',
+ kind: 'number',
+ group: 'How precise',
+ rungs: [
+ { label: 'This block', value: 100 },
+ { label: 'This town', value: 2000 },
+ ],
+ minimum: 1,
+ maximum: 5000000,
+ },
+ { key: 'footprint', label: 'Footprint', kind: 'geojson', rungs: [] },
+ // the two that hold sentences, as the registry declares them
+ { key: 'verbatim', label: 'As the source put it', kind: 'longtext', rungs: [] },
+ { key: 'method', label: 'How this point was found', kind: 'longtext', rungs: [] },
+];
+
+const RELIABILITY = {
+ key: 'reliability',
+ label: 'Source reliability',
+ kind: 'choice',
+ rungs: [],
+ options: [
+ { value: 'A', label: 'Completely reliable' },
+ { value: 'B', label: 'Usually reliable' },
+ { value: 'E', label: 'Unreliable' },
+ ],
+};
+
+// Three subjects on one type: what a Claim states, when it applies, then why it is
+// believed. A single heading over every field would file a count as reasoning.
+const COUNTED = [
+ { key: 'count', label: 'How many', kind: 'number', group: 'What it states',
+ rungs: [], minimum: 1, whole: true },
+ { key: 'condition', label: 'Condition', kind: 'choice', rungs: [],
+ options: [{ value: 'destroyed', label: 'Destroyed' }] },
+ { key: 'when', label: 'When', kind: 'temporal', group: 'When', rungs: [] },
+ { key: 'time_role', label: 'Time role', kind: 'choice', rungs: [],
+ options: [
+ { value: 'occurred', label: 'Occurred' },
+ { value: 'observed', label: 'Observed' },
+ { value: 'valid', label: 'Valid during' },
+ ] },
+ { key: 'confidence', label: 'Confidence', kind: 'choice', group: 'Reasoning',
+ rungs: [], options: [{ value: 'probable', label: 'Probable' }] },
+ { key: 'method', label: 'How this was worked out', kind: 'longtext', rungs: [] },
+];
+
+// A media declares nothing, and `traced` stands for a type whose only field is a
+// shape — the one case where a declared field can still leave the block empty.
+const BY_TYPE = {
+ place: FIELDS,
+ media: [],
+ traced: [FIELDS[1]],
+ claim: COUNTED,
+ bookmark: [{ key: 'archive_url', label: 'Archived copy', kind: 'url', rungs: [] }, RELIABILITY],
+ ip: [
+ { key: 'network', label: 'Legacy network', kind: 'text', editable: false, rungs: [] },
+ { key: 'provider', label: 'Provider', kind: 'text', rungs: [] },
+ ],
+};
+
+vi.mock('../lib/entityTypes.svelte.js', async (importOriginal) => ({
+ ...(await importOriginal()),
+ entityFields: (type) => BY_TYPE[type] ?? [],
+}));
+
+const { default: AttrFields } = await import('./AttrFields.svelte');
+
+let live = null;
+
+function open(values = {}, type = 'place') {
+ const target = document.createElement('div');
+ document.body.append(target);
+ live = mount(AttrFields, { target, props: { type, values } });
+ flushSync();
+ return target;
+}
+
+afterEach(() => {
+ if (live) unmount(live);
+ live = null;
+ document.body.innerHTML = '';
+});
+
+const field = (root, key) => root.querySelector(`#attr-${key}`);
+
+function type(input, text) {
+ input.value = text;
+ input.dispatchEvent(new Event('input', { bubbles: true }));
+ flushSync();
+}
+
+describe('typing into a declared field', () => {
+ it('keeps what was typed in a text field rather than reverting it', () => {
+ const root = open();
+
+ type(field(root, 'verbatim'), 'somewhere on the north quay');
+
+ expect(field(root, 'verbatim').value).toBe('somewhere on the north quay');
+ });
+
+ it('keeps a metre count typed straight into the number field', () => {
+ const root = open();
+
+ type(field(root, 'radius_m'), '350');
+
+ expect(field(root, 'radius_m').value).toBe('350');
+ });
+
+ it('fills every declared text field independently', () => {
+ const root = open();
+
+ type(field(root, 'verbatim'), 'the old sawmill');
+ type(field(root, 'method'), 'roofline matched against 2023 imagery');
+
+ expect(field(root, 'verbatim').value).toBe('the old sawmill');
+ expect(field(root, 'method').value).toBe('roofline matched against 2023 imagery');
+ });
+
+ it('starts every field empty, with no value standing in for unknown', () => {
+ const root = open();
+
+ for (const key of ['radius_m', 'verbatim', 'method']) {
+ expect(field(root, key).value, key).toBe('');
+ expect(field(root, key).placeholder, key).toBe('Unknown');
+ }
+ });
+});
+
+describe('a field that holds sentences', () => {
+ it('is a box that grows, not a line that scrolls sideways', () => {
+ // 4000 characters of quoted source in a one-line input is a field nobody fills
+ const root = open();
+
+ expect(field(root, 'verbatim').tagName).toBe('TEXTAREA');
+ expect(field(root, 'method').tagName).toBe('TEXTAREA');
+ });
+
+ it('keeps several lines of what was typed', () => {
+ const root = open();
+
+ type(field(root, 'method'), 'roofline matched\nagainst 2023 imagery');
+
+ expect(field(root, 'method').value).toBe('roofline matched\nagainst 2023 imagery');
+ });
+
+ it('leaves a short field on one line', () => {
+ const root = open({}, 'bookmark');
+
+ expect(field(root, 'archive_url').tagName).toBe('INPUT');
+ });
+});
+
+describe('the rungs, clicked', () => {
+ const rungs = (root) => [...root.querySelectorAll('button')];
+
+ it('writes its metres into the number field', () => {
+ const root = open();
+
+ rungs(root)[0].click();
+ flushSync();
+
+ expect(field(root, 'radius_m').value).toBe('100');
+ expect(rungs(root)[0].getAttribute('aria-pressed')).toBe('true');
+ });
+
+ it('clears the field when the chosen rung is clicked again', () => {
+ const root = open();
+
+ rungs(root)[1].click();
+ flushSync();
+ expect(field(root, 'radius_m').value).toBe('2000');
+
+ rungs(root)[1].click();
+ flushSync();
+
+ expect(field(root, 'radius_m').value).toBe('');
+ expect(rungs(root)[1].getAttribute('aria-pressed')).toBe('false');
+ });
+
+ it('moves the selection rather than adding to it', () => {
+ const root = open();
+
+ rungs(root)[0].click();
+ flushSync();
+ rungs(root)[1].click();
+ flushSync();
+
+ expect(field(root, 'radius_m').value).toBe('2000');
+ expect(rungs(root).filter((b) => b.getAttribute('aria-pressed') === 'true')).toHaveLength(1);
+ });
+
+ it('lights no rung for a radius typed between two of them', () => {
+ const root = open();
+
+ type(field(root, 'radius_m'), '350');
+
+ expect(rungs(root).some((b) => b.getAttribute('aria-pressed') === 'true')).toBe(false);
+ });
+});
+
+describe('the footprint', () => {
+ const ring = [[14.55, 53.44], [14.56, 53.44], [14.56, 53.45], [14.55, 53.44]];
+ const polygon = { type: 'Polygon', coordinates: [ring] };
+
+ it('does not appear at all while there is no shape', () => {
+ const root = open();
+
+ expect(root.textContent).not.toContain('Footprint');
+ });
+
+ it('appears with its shape summarised the moment one exists', () => {
+ const root = open({ footprint: polygon });
+
+ expect(root.textContent).toContain('Footprint');
+ expect(root.textContent).toContain('Polygon, 4 points');
+ });
+
+ it('goes away again when it is cleared', () => {
+ const root = open({ footprint: polygon });
+
+ [...root.querySelectorAll('button')].find((b) => b.textContent.trim() === 'Clear').click();
+ flushSync();
+
+ expect(root.textContent).not.toContain('Footprint');
+ });
+});
+
+describe('a closed field', () => {
+ const open_ = (values = {}) => open(values, 'bookmark');
+ const pick = (root, value) => {
+ const select = field(root, 'reliability');
+ select.value = value;
+ select.dispatchEvent(new Event('change', { bubbles: true }));
+ flushSync();
+ return select;
+ };
+
+ it('offers exactly the grades the registry served, and nothing invented here', () => {
+ const options = [...open_().querySelector('#attr-reliability').options];
+
+ expect(options.map((o) => o.value)).toEqual(['', 'A', 'B', 'E']);
+ expect(options[2].textContent.trim()).toBe('B · Usually reliable');
+ });
+
+ it('starts ungraded, which is a state and not a hole', () => {
+ expect(field(open_(), 'reliability').value).toBe('');
+ // and nothing on screen says a grade is missing
+ expect(open_().textContent).not.toContain('Not assessed');
+ });
+
+ it('keeps the grade that was picked', () => {
+ expect(pick(open_(), 'B').value).toBe('B');
+ });
+
+ it('goes back to ungraded through the blank option', () => {
+ const root = open_({ reliability: 'A' });
+
+ expect(pick(root, '').value).toBe('');
+ });
+
+ it('shows the graded source beside its archived copy, both editable', () => {
+ const root = open_({ reliability: 'E' });
+
+ expect(field(root, 'reliability').value).toBe('E');
+ type(field(root, 'archive_url'), 'https://web.archive.test/web/2026/https://x.test/p');
+ expect(field(root, 'archive_url').value).toBe(
+ 'https://web.archive.test/web/2026/https://x.test/p',
+ );
+ });
+});
+
+describe('an older read-only field', () => {
+ it('stays hidden on a new entity', () => {
+ const root = open({}, 'ip');
+
+ expect(root.textContent).not.toContain('Legacy network');
+ expect(field(root, 'provider')).not.toBeNull();
+ });
+
+ it('shows an existing value without an input that could change it', () => {
+ const root = open({ network: '203.0.113.0/24' }, 'ip');
+
+ expect(root.textContent).toContain('Legacy network');
+ expect(root.textContent).toContain('203.0.113.0/24');
+ expect(field(root, 'network')).toBeNull();
+ });
+});
+
+describe('a type with nothing to show', () => {
+ it('renders no block for a type that declares no fields', () => {
+ expect(open({}, 'media').textContent.trim()).toBe('');
+ });
+
+ it('renders no block, and so no heading, when every declared field hides itself', () => {
+ // one geojson field and no shape in it: the heading would be the only thing left
+ expect(open({}, 'traced').textContent.trim()).toBe('');
+ });
+});
+
+describe('one type, three subjects', () => {
+ const headings = (root) =>
+ [...root.querySelectorAll('.attrs-h')].map((node) => node.textContent);
+
+ it('opens a heading where the registry changes group, and only there', () => {
+ expect(headings(open({}, 'claim'))).toEqual(['What it states', 'When', 'Reasoning']);
+ });
+
+ it('leaves the fields in the order the vocabulary declares them', () => {
+ const root = open({}, 'claim');
+ const order = [...root.querySelectorAll('.attr-k')].map((node) => node.textContent);
+
+ expect(order).toEqual([
+ 'How many', 'Condition', 'When', 'Time role', 'Confidence',
+ 'How this was worked out',
+ ]);
+ });
+
+ it('states one heading over the fields that follow it', () => {
+ // a place says "How precise" once above four fields, not once per field
+ expect(headings(open({ footprint: null }, 'place'))).toEqual(['How precise']);
+ });
+
+ it('counts in whole numbers, because half a destroyed thing is not a quantity', () => {
+ const root = open({}, 'claim');
+
+ expect(field(root, 'count').getAttribute('step')).toBe('1');
+ expect(field(root, 'count').getAttribute('min')).toBe('1');
+ });
+});
+
+describe('a temporal Claim field', () => {
+ const choose = (root, label, value) => {
+ const select = root.querySelector(`select[aria-label="${label}"]`);
+ select.value = value;
+ select.dispatchEvent(new Event('change', { bubbles: true }));
+ flushSync();
+ };
+
+ it('starts with a date picker and exposes every guided format', () => {
+ const root = open({}, 'claim');
+ const when = field(root, 'when');
+ const format = root.querySelector('select[aria-label="Date format"]');
+
+ expect(when.type).toBe('date');
+ expect(format.value).toBe('date');
+ expect([...format.options].map((option) => option.textContent)).toEqual([
+ 'Date', 'Date and time', 'Date range', 'Time range', 'Advanced syntax',
+ ]);
+ });
+
+ it('builds an approximate month without making the analyst type its syntax', () => {
+ const root = open({}, 'claim');
+
+ choose(root, 'Date precision', 'month');
+ type(field(root, 'when'), '2026-08');
+ choose(root, 'Date certainty', '~');
+ choose(root, 'Date format', 'advanced');
+
+ expect(field(root, 'when').value).toBe('2026-08~');
+ });
+
+ it('adds seconds and UTC to a guided date and time', () => {
+ const root = open({}, 'claim');
+
+ choose(root, 'Date format', 'timestamp');
+ type(field(root, 'when'), '2026-08-11T18:40');
+ choose(root, 'Timezone', 'utc');
+ choose(root, 'Date format', 'advanced');
+
+ expect(field(root, 'when').value).toBe('2026-08-11T18:40:00Z');
+ });
+
+ it('opens the complete syntax reference beside the advanced field', () => {
+ const root = open({}, 'claim');
+
+ choose(root, 'Date format', 'advanced');
+
+ const guide = root.querySelector('[aria-label="Supported date syntax"]');
+ expect(guide).not.toBeNull();
+ expect(field(root, 'when').getAttribute('aria-describedby')).toBe(guide.id);
+ expect(guide.textContent).toContain("Dates use Azimut's EDTF profile");
+ expect(guide.textContent).toContain('Local time');
+ expect(guide.textContent).toContain('2026-08-11T18:40:00+02:00');
+ expect(guide.textContent).toContain('2026-08~/2026-10?');
+ expect(guide.textContent).toContain('Approximate and uncertain');
+ expect(guide.textContent).toContain('Open ranges');
+ expect(guide.querySelectorAll('[role="row"]')).toHaveLength(10);
+ });
+
+ it('keeps the syntax table out of the guided modes', () => {
+ const root = open({}, 'claim');
+
+ expect(root.textContent).not.toContain('Supported date syntax');
+ expect(root.querySelector('[aria-label="Supported date syntax"]')).toBeNull();
+ });
+
+ it('offers exactly the three meanings served by the registry', () => {
+ const options = [...field(open({}, 'claim'), 'time_role').options];
+
+ expect(options.map((option) => option.value)).toEqual([
+ '', 'occurred', 'observed', 'valid',
+ ]);
+ });
+});
diff --git a/frontend/src/components/AttrFields.svelte b/frontend/src/components/AttrFields.svelte
new file mode 100644
index 0000000..5eff98b
--- /dev/null
+++ b/frontend/src/components/AttrFields.svelte
@@ -0,0 +1,260 @@
+<script>
+ /**
+ * The declared fields of one entity type, rendered from the registry.
+ *
+ * Generated rather than written per type: the backend says which fields exist,
+ * how each reads, how it is edited and what bounds it has, so `vessel` gaining an
+ * IMO number is a line in `engine/entities.py` and nothing here.
+ *
+ * Empty is a value. Every field may be unknown, and clearing one sends `null`
+ * rather than `0` or `""` — a blank radius means *we do not know how precise this
+ * is*, where `0` would claim infinite precision. Nothing here is required and
+ * nothing is flagged for being absent.
+ */
+ import { entityFields, withHeadings } from '../lib/entityTypes.svelte.js';
+ import TemporalInput from './TemporalInput.svelte';
+
+ let { type, values = $bindable({}), exclude = [] } = $props();
+
+ const fields = $derived(entityFields(type));
+
+ /**
+ * A shape can only be traced on a map, and no map offers that gesture yet. So an
+ * empty footprint shows nothing at all: a label over a hint reads as a control
+ * that has stopped working, where absence reads as what it is. It appears the
+ * moment a shape exists — set through the API, or by the drawing tool when it
+ * lands — carrying the summary and the Clear that drops it.
+ */
+ const shown = $derived(withHeadings(fields.filter((field) => {
+ if (exclude.includes(field.key)) return false;
+ if (field.editable === false) return values?.[field.key] != null && values[field.key] !== '';
+ return field.kind !== 'geojson' || values?.[field.key];
+ })));
+
+ function set(key, raw) {
+ // `undefined` would be dropped from the JSON body and read as "leave it be";
+ // null is what actually clears a stored field.
+ values = { ...values, [key]: raw === '' || raw == null ? null : raw };
+ }
+
+ function setNumber(key, raw) {
+ const value = Number(raw);
+ set(key, raw === '' || !Number.isFinite(value) ? null : value);
+ }
+
+ /** A rung is a toggle, not a radio: clicking the chosen one clears the field back
+ * to unknown. Otherwise the only way out of a value picked by mistake would be to
+ * find the metre box and empty it, and "unknown" is a state the analyst is
+ * entitled to return to. */
+ function toggle(key, value) {
+ set(key, values?.[key] === value ? null : value);
+ }
+
+ /** A footprint is traced, never typed. This reports the shape it holds; the map
+ * is the only thing that can make one. */
+ function footprintSummary(value) {
+ if (!value?.coordinates) return '';
+ const count = JSON.stringify(value.coordinates).match(/-?\d+(\.\d+)?\s*,\s*-?\d+(\.\d+)?/g);
+ const points = count ? count.length : 0;
+ return `${value.type === 'MultiPolygon' ? 'Multi-polygon' : 'Polygon'}, ${points} points`;
+ }
+</script>
+
+{#if shown.length}
+ <div class="attrs">
+ {#each shown as field (field.key)}
+ {#if field.heads}<div class="attrs-h">{field.heads}</div>{/if}
+ <div class="attr">
+ {#if field.editable === false}
+ <span class="attr-k" title={field.hint}>{field.label}</span>
+ {:else}
+ <!-- the label says what the field is called, the tooltip what it is for -->
+ <label class="attr-k" for={`attr-${field.key}`} title={field.hint}>{field.label}</label>
+ {/if}
+
+ {#if field.editable === false}
+ <div class="legacy-value">
+ <span>{values[field.key]}</span>
+ <small>Older field</small>
+ </div>
+ {:else if field.kind === 'number'}
+ {#if field.rungs?.length}
+ <div class="rungs">
+ {#each field.rungs as rung (rung.value)}
+ <button
+ type="button"
+ class="chip"
+ class:on={values?.[field.key] === rung.value}
+ aria-pressed={values?.[field.key] === rung.value}
+ onclick={() => toggle(field.key, rung.value)}
+ >{rung.label}</button>
+ {/each}
+ </div>
+ {/if}
+ <input
+ id={`attr-${field.key}`}
+ class="input input-sm"
+ type="number"
+ min={field.minimum ?? undefined}
+ max={field.maximum ?? undefined}
+ step={field.whole ? 1 : 'any'}
+ value={values?.[field.key] ?? ''}
+ placeholder="Unknown"
+ oninput={(e) => setNumber(field.key, e.currentTarget.value)}
+ />
+ {:else if field.kind === 'choice'}
+ <!-- A closed scale, so the options are the registry's and never this
+ file's. The blank one clears the field: an ungraded source is the
+ normal case, and "we have not judged it" is a state to return to. -->
+ <select
+ id={`attr-${field.key}`}
+ class="select input-sm"
+ value={values?.[field.key] ?? ''}
+ onchange={(e) => set(field.key, e.currentTarget.value)}
+ >
+ <option value="">Unknown</option>
+ {#each field.options ?? [] as option (option.value)}
+ <option value={option.value}>
+ {option.value.length <= 2 ? `${option.value} · ${option.label}` : option.label}
+ </option>
+ {/each}
+ </select>
+ {:else if field.kind === 'temporal'}
+ <div class="temporal-field">
+ <TemporalInput
+ id={`attr-${field.key}`}
+ value={values?.[field.key] ?? ''}
+ onchange={(value) => set(field.key, value)}
+ />
+ </div>
+ {:else if field.kind === 'longtext'}
+ <!-- A quoted source and the reasoning behind a claim run to paragraphs.
+ Held in a one-line box they scroll sideways past eighty characters,
+ which is a field nobody fills in. -->
+ <textarea
+ id={`attr-${field.key}`}
+ class="textarea input-sm"
+ rows="3"
+ value={values?.[field.key] ?? ''}
+ placeholder="Unknown"
+ oninput={(e) => set(field.key, e.currentTarget.value)}
+ ></textarea>
+ {:else if field.kind === 'geojson'}
+ <div class="geo-row">
+ <span class="mono">{footprintSummary(values[field.key])}</span>
+ <button type="button" class="chip clear" onclick={() => set(field.key, null)}>
+ Clear
+ </button>
+ </div>
+ {:else}
+ <input
+ id={`attr-${field.key}`}
+ class="input input-sm"
+ type={field.kind === 'url' ? 'url' : 'text'}
+ value={values?.[field.key] ?? ''}
+ placeholder="Unknown"
+ oninput={(e) => set(field.key, e.currentTarget.value)}
+ />
+ {/if}
+ </div>
+ {/each}
+ </div>
+{/if}
+
+<style>
+ /* One block, so four optional fields read as a subject rather than as a form
+ someone left half-finished in the middle of the panel. */
+ .attrs {
+ margin: 10px 0 2px;
+ display: grid;
+ grid-template-columns: repeat(auto-fit, minmax(180px, 1fr));
+ gap: 10px 12px;
+ }
+ .attrs-h {
+ grid-column: 1 / -1;
+ font-size: var(--fs-xs);
+ font-weight: 600;
+ color: var(--text-2);
+ margin-bottom: 6px;
+ }
+ /* A second heading opens a block under one already filled, so it needs the air
+ the first one gets from the block above it. */
+ .attrs-h:not(:first-child) {
+ margin-top: 8px;
+ }
+ .attr-k {
+ display: block;
+ font-size: var(--fs-xs);
+ color: var(--text-3);
+ margin-bottom: 3px;
+ }
+ .input-sm {
+ width: 100%;
+ padding: 4px 7px;
+ font-size: var(--fs-xs);
+ }
+ /* A long field takes the whole row: two paragraph boxes side by side in a 180px
+ column would be narrower than the one-line input they replace. */
+ .attr:has(.textarea) {
+ grid-column: 1 / -1;
+ }
+ .attr:has(.temporal-field) {
+ grid-column: 1 / -1;
+ }
+ .textarea {
+ resize: vertical;
+ line-height: 1.5;
+ }
+ .rungs {
+ display: flex;
+ flex-wrap: wrap;
+ gap: 4px;
+ margin-bottom: 5px;
+ }
+ /* `.chip` is per-component in this codebase, never global — the rungs rendered
+ as bare text until this block existed. */
+ .chip {
+ padding: 3px 8px;
+ border: 1px solid var(--border);
+ border-radius: var(--r-sm);
+ background: var(--bg-2);
+ color: var(--text-2);
+ font-size: var(--fs-xs);
+ white-space: nowrap;
+ cursor: pointer;
+ transition: border-color 0.12s, color 0.12s, background 0.12s;
+ }
+ .chip:hover {
+ color: var(--text-1);
+ border-color: var(--border-strong);
+ }
+ .chip.on {
+ border-color: var(--accent);
+ background: var(--accent-soft);
+ color: var(--accent);
+ }
+ .chip.clear {
+ color: var(--danger);
+ }
+ .geo-row {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ }
+ .legacy-value {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ gap: 8px;
+ min-height: 30px;
+ padding: 5px 8px;
+ border: 1px solid var(--border);
+ border-radius: var(--r-sm);
+ background: var(--bg-2);
+ color: var(--text-2);
+ }
+ .legacy-value small {
+ color: var(--text-3);
+ font-size: 10px;
+ }
+</style>
diff --git a/frontend/src/components/AttrFields.test.js b/frontend/src/components/AttrFields.test.js
new file mode 100644
index 0000000..28faae8
--- /dev/null
+++ b/frontend/src/components/AttrFields.test.js
@@ -0,0 +1,147 @@
+import { describe, expect, it } from 'vitest';
+import { readFileSync } from 'node:fs';
+
+const source = readFileSync(new URL('./AttrFields.svelte', import.meta.url), 'utf8');
+
+describe('generated fields', () => {
+ it('renders whatever the registry declares rather than a form per type', () => {
+ expect(source).toContain(
+ "import { entityFields, withHeadings } from '../lib/entityTypes.svelte.js'"
+ );
+ expect(source).toContain('const fields = $derived(entityFields(type))');
+ expect(source).toContain('{#each shown as field (field.key)}');
+ });
+
+ it('reads each field with the editor its kind asks for', () => {
+ expect(source).toContain("{:else if field.kind === 'number'}");
+ expect(source).toContain("{:else if field.kind === 'choice'}");
+ expect(source).toContain("{:else if field.kind === 'temporal'}");
+ expect(source).toContain("import TemporalInput from './TemporalInput.svelte'");
+ expect(source).toContain('<TemporalInput');
+ expect(source).toContain("{:else if field.kind === 'geojson'}");
+ expect(source).not.toContain("field.kind === 'flag'");
+ expect(source).toContain("type={field.kind === 'url' ? 'url' : 'text'}");
+ });
+
+ it('carries the registry bounds onto the input, so the form refuses what the API does', () => {
+ expect(source).toContain('min={field.minimum ?? undefined}');
+ expect(source).toContain('max={field.maximum ?? undefined}');
+ });
+
+ it('can leave fields to a dedicated Details tab without changing the registry', () => {
+ expect(source).toContain('exclude = []');
+ expect(source).toContain('if (exclude.includes(field.key)) return false;');
+ });
+});
+
+describe('a field explains what it is for', () => {
+ it('carries the registry’s own clause on the label, never one written here', () => {
+ expect(source).toContain('title={field.hint}');
+ });
+});
+
+describe('empty is a value', () => {
+ it('clears to null rather than to zero or an empty string', () => {
+ // a blank radius means "we do not know how precise this is"; 0 would claim
+ // infinite precision, and undefined would be dropped from the body and read
+ // as "leave it be"
+ expect(source).toContain("values = { ...values, [key]: raw === '' || raw == null ? null : raw }");
+ expect(source).toContain("set(key, raw === '' || !Number.isFinite(value) ? null : value)");
+ });
+
+ it('says unknown in the placeholder instead of asking for a value', () => {
+ expect(source).toContain('placeholder="Unknown"');
+ // no field is ever marked required — checked against the markup, since the
+ // comment above it uses the word to promise exactly this
+ const markup = source.slice(source.indexOf('</script>'));
+ expect(markup).not.toMatch(/\brequired\b/);
+ });
+});
+
+describe('the radius ladder', () => {
+ it('offers the rungs the registry serves, never a list of its own', () => {
+ expect(source).toContain('{#each field.rungs as rung (rung.value)}');
+ expect(source).toContain('onclick={() => toggle(field.key, rung.value)}');
+ expect(source).toContain('class:on={values?.[field.key] === rung.value}');
+ });
+
+ it('toggles: clicking the chosen rung again clears the field back to unknown', () => {
+ // a rung picked by mistake must not force a trip to the metre box, and unknown
+ // is a state the analyst is entitled to return to
+ expect(source).toContain('set(key, values?.[key] === value ? null : value)');
+ expect(source).toContain('aria-pressed={values?.[field.key] === rung.value}');
+ });
+
+ it('keeps the metre input beside the rungs, since a rung is a shortcut not a cage', () => {
+ expect(source).toContain('type="number"');
+ });
+});
+
+describe('a closed scale', () => {
+ it('offers the options the registry serves, never a scale written here', () => {
+ // the Admiralty letters are data: spelling them in the markup is how a picker
+ // starts offering a grade the validator refuses
+ expect(source).toContain('{#each field.options ?? [] as option (option.value)}');
+ expect(source).toContain(
+ "option.value.length <= 2 ? `${option.value} · ${option.label}` : option.label"
+ );
+ expect(source).not.toMatch(/Usually reliable|Cannot be judged/);
+ });
+
+ it('leads with a blank option, because ungraded is the normal state', () => {
+ expect(source).toContain('<option value="">Unknown</option>');
+ });
+});
+
+describe('a footprint', () => {
+ it('is reported and droppable here, but only the map can trace one', () => {
+ expect(source).toContain('footprintSummary(values[field.key])');
+ expect(source).toContain('onclick={() => set(field.key, null)}');
+ });
+
+ it('is absent from the block entirely until a shape exists', () => {
+ // no map offers the tracing gesture yet, so a label over a hint would read as a
+ // control that has stopped working
+ expect(source).toContain("return field.kind !== 'geojson' || values?.[field.key]");
+ const markup = source.slice(source.indexOf('</script>'));
+ expect(markup).not.toContain('Drawn on the map.');
+ });
+});
+
+describe('one block, not loose inputs', () => {
+ it('heads the fields with whatever the registry calls them, and nothing when it calls them nothing', () => {
+ expect(source).toContain('withHeadings(');
+ expect(source).toContain('{#if field.heads}<div class="attrs-h">{field.heads}</div>{/if}');
+ });
+
+ it('resolves the headings after the hidden fields are dropped, not before', () => {
+ // an untraced footprint hides itself, and a heading resolved before that filter
+ // could outlive every field it was heading
+ const filtered = source.indexOf('withHeadings(fields.filter(');
+ expect(filtered).toBeGreaterThan(-1);
+ });
+
+ it('renders nothing at all when no field has anything to show', () => {
+ expect(source).toContain('{#if shown.length}');
+ });
+
+ it('shows old read-only fields only when a stored value exists', () => {
+ expect(source).toContain('if (field.editable === false)');
+ expect(source).toContain('<div class="legacy-value">');
+ expect(source).toContain('<small>Older field</small>');
+ });
+
+ it('lays fields out as a responsive grid instead of a long loose list', () => {
+ // `display: contents` put the label, the rungs and the input straight into the
+ // host's layout, which is how four fields came out cramped mid-panel
+ expect(source).not.toContain('display: contents');
+ expect(source).toContain('grid-template-columns: repeat(auto-fit, minmax(180px, 1fr));');
+ });
+
+ it('carries its own chip styling, since the class is per-component here', () => {
+ const markup = source.slice(source.indexOf('</script>'));
+ expect(markup).toContain('class="chip"');
+ expect(source).toMatch(/\.chip \{[^}]*border:/);
+ expect(source).toMatch(/\.chip\.on \{[^}]*--accent/);
+ });
+});
diff --git a/frontend/src/components/CaseSidebar.test.js b/frontend/src/components/CaseSidebar.test.js
index 861cffc..05e545c 100644
--- a/frontend/src/components/CaseSidebar.test.js
+++ b/frontend/src/components/CaseSidebar.test.js
@@ -197,6 +197,12 @@ describe('entity row', () => {
expect(row).toContain('title="Confirm"');
expect(row).toContain('title="Dismiss"');
});
+
+ it('uses the primary photo and keeps the type icon as the fallback', () => {
+ expect(row).toContain('{#if entity.thumb}');
+ expect(row).toContain('src={fileUrl(caseId, entity.thumb)}');
+ expect(row).toContain('<Icon name={entityIcon(entity)} size={14} />');
+ });
});
describe('details drawer', () => {
@@ -208,11 +214,19 @@ describe('details drawer', () => {
});
it('closes on Escape, on the back arrow and on delete', () => {
- expect(drawer).toContain("onkeydown={(e) => e.key === 'Escape' && onclose()}");
+ expect(drawer).toContain("onkeydown={(e) => e.key === 'Escape' && requestClose()}");
expect(drawer).toContain('title="Back to the case"');
expect(shell).toContain('<DetailsDrawer entity={infoEntity} onclose={closeInfo} ondeleted={closeInfo} />');
});
+ it('asks before a close would throw away an unsaved field', () => {
+ // the panel's fields wait for Save while its connections file themselves, so
+ // Escape and the back arrow used to drop a half-typed value without a word
+ expect(drawer).toContain('bind:dirty');
+ expect(drawer).toContain('if (dirty) discarding = true;');
+ expect(drawer).toContain('title="Discard changes?"');
+ });
+
it('hands focus back to the row it was opened from', () => {
expect(shell).toContain('returnFocusEl = document.activeElement');
expect(shell).toContain('returnFocusEl?.focus?.()');
diff --git a/frontend/src/components/CaseSwitcher.svelte b/frontend/src/components/CaseSwitcher.svelte
index a46e8c6..e205852 100644
--- a/frontend/src/components/CaseSwitcher.svelte
+++ b/frontend/src/components/CaseSwitcher.svelte
@@ -717,7 +717,7 @@
<span><Icon name="check" size={18} /></span>
<div>
<strong>No problems found</strong>
- <p>The database and media records match the case files.</p>
+ <p>The case files and derived indexes match the database.</p>
</div>
</div>
{:else if doctorReport}
diff --git a/frontend/src/components/ClaimConnections.svelte b/frontend/src/components/ClaimConnections.svelte
new file mode 100644
index 0000000..ccca94a
--- /dev/null
+++ b/frontend/src/components/ClaimConnections.svelte
@@ -0,0 +1,203 @@
+<script>
+ import { api } from '../lib/api.js';
+ import { saveRelation } from '../lib/relations.svelte.js';
+ import { toast } from '../lib/state.svelte.js';
+ import { entityIcon } from '../lib/entityIcon.js';
+ import Icon from './Icon.svelte';
+ import RelationPicker from './RelationPicker.svelte';
+
+ let {
+ caseId,
+ claim,
+ relations = [],
+ onwalk = null,
+ onchanged = null,
+ } = $props();
+
+ /**
+ * What a statement is made of, in the order it is built: what it is about, where
+ * it puts it, what it rests on, what rests on it, and what stands against it.
+ *
+ * **`cites` is read by direction, and `contradicts` is not.** A citation is not
+ * symmetric — this statement resting on that one is a different fact from that one
+ * resting on this — so the two readings are two groups, and only the outgoing one
+ * takes a source: what rests on this statement is stated from *there*, where the
+ * reasoning is being written. Two claims that cannot both hold say so whichever end
+ * they were filed from, which is why that group deliberately ignores `direction`
+ * the way an ordinary relation list does not.
+ */
+ const GROUPS = [
+ { type: 'about', label: 'Subjects', add: 'Add subject' },
+ { type: 'at', label: 'Location', add: 'Add location' },
+ { type: 'cites', way: 'out', label: 'Sources', add: 'Add source' },
+ {
+ type: 'cites',
+ way: 'in',
+ label: 'Supports',
+ hint: 'statements that rest on this one',
+ },
+ { type: 'contradicts', label: 'Contradictions', add: 'Add contradiction' },
+ ];
+
+ let adding = $state(null);
+ let busy = $state(false);
+ let busyId = $state(null);
+
+ /** A group's rows. `way` narrows to one reading; without it both are listed, which
+ * is what a symmetric verb wants. */
+ const rows = (group) =>
+ relations.filter(
+ (row) => row.link.type === group.type && (!group.way || row.direction === group.way)
+ );
+
+ async function add(choice) {
+ if (busy) return;
+ busy = true;
+ try {
+ await saveRelation(caseId, claim.id, choice);
+ adding = null;
+ await onchanged?.();
+ } catch (error) {
+ toast(error.message, 'danger');
+ throw error;
+ } finally {
+ busy = false;
+ }
+ }
+
+ async function remove(link) {
+ if (busyId) return;
+ busyId = link.id;
+ try {
+ await api.del(`/api/cases/${caseId}/links/${link.id}`);
+ await onchanged?.();
+ } catch (error) {
+ toast(error.message, 'danger');
+ } finally {
+ busyId = null;
+ }
+ }
+</script>
+
+<div class="claim-connections">
+ {#each GROUPS as group (`${group.type}:${group.way ?? 'both'}`)}
+ {@const items = rows(group)}
+ <!-- A reading nobody can add to is worth a heading only once it holds something:
+ an empty "Supports" on every statement would be a permanent blank. -->
+ {#if group.add || items.length}
+ <section class="claim-group">
+ <div class="claim-head">
+ <h4 title={group.hint ?? ''}>{group.label}</h4>
+ {#if group.add}
+ <button
+ class="btn btn-ghost btn-sm add"
+ class:on={adding === group.type}
+ onclick={() => (adding = adding === group.type ? null : group.type)}
+ >{group.add}</button>
+ {/if}
+ </div>
+ {#if items.length}
+ <div class="claim-items">
+ {#each items as row (row.link.id)}
+ <div class="claim-item">
+ <button class="claim-target" onclick={() => onwalk?.(row.entity)}>
+ <Icon name={entityIcon(row.entity)} size={12} />
+ <span>{row.entity.label}</span>
+ </button>
+ <button
+ class="btn btn-ghost btn-sm remove"
+ title="Remove"
+ disabled={busyId === row.link.id}
+ onclick={() => remove(row.link)}
+ ><Icon name="x" size={12} /></button>
+ </div>
+ {/each}
+ </div>
+ {/if}
+ {#if group.add && adding === group.type}
+ <RelationPicker
+ subjectType="claim"
+ subject={claim}
+ subjectId={claim.id}
+ action="claim"
+ relationType={group.type}
+ expanded
+ {busy}
+ oncommit={add}
+ oncancel={() => (adding = null)}
+ />
+ {/if}
+ </section>
+ {/if}
+ {/each}
+</div>
+
+<style>
+ .claim-connections {
+ display: grid;
+ gap: 10px;
+ }
+ .claim-group {
+ min-width: 0;
+ }
+ .claim-head,
+ .claim-item,
+ .claim-target {
+ display: flex;
+ align-items: center;
+ }
+ .claim-head {
+ justify-content: space-between;
+ gap: 8px;
+ min-height: 28px;
+ }
+ h4 {
+ margin: 0;
+ color: var(--text-2);
+ font-size: var(--fs-xs);
+ font-weight: 600;
+ }
+ .add {
+ color: var(--text-3);
+ }
+ .add.on {
+ color: var(--accent);
+ }
+ .claim-items {
+ display: grid;
+ gap: 2px;
+ }
+ .claim-item {
+ gap: 2px;
+ min-width: 0;
+ }
+ .claim-target {
+ flex: 1;
+ gap: 7px;
+ min-width: 0;
+ padding: 5px 6px;
+ border: 0;
+ border-radius: var(--r-sm);
+ background: transparent;
+ color: var(--text-2);
+ font: inherit;
+ font-size: var(--fs-sm);
+ text-align: left;
+ cursor: pointer;
+ }
+ .claim-target:hover {
+ background: var(--bg-2);
+ color: var(--text-1);
+ }
+ .claim-target span {
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ }
+ .remove {
+ color: var(--text-3);
+ }
+ .remove:hover {
+ color: var(--danger);
+ }
+</style>
diff --git a/frontend/src/components/ClaimConnections.test.js b/frontend/src/components/ClaimConnections.test.js
new file mode 100644
index 0000000..71034a5
--- /dev/null
+++ b/frontend/src/components/ClaimConnections.test.js
@@ -0,0 +1,64 @@
+import { describe, expect, it } from 'vitest';
+import { readFileSync } from 'node:fs';
+
+const editor = readFileSync(new URL('./ClaimConnections.svelte', import.meta.url), 'utf8');
+const references = readFileSync(new URL('./ClaimReferences.svelte', import.meta.url), 'utf8');
+
+describe('Claim connections', () => {
+ it('gives subjects, location, sources and contradictions separate controls', () => {
+ expect(editor).toContain("{ type: 'about', label: 'Subjects', add: 'Add subject' }");
+ expect(editor).toContain("{ type: 'at', label: 'Location', add: 'Add location' }");
+ expect(editor).toContain("{ type: 'cites', way: 'out', label: 'Sources', add: 'Add source' }");
+ expect(editor).toContain('relationType={group.type}');
+ expect(editor).toContain('action="claim"');
+ });
+
+ it('reads a citation by direction, because resting on is not symmetric', () => {
+ // this statement resting on that one is a different fact from that one resting on
+ // this, so the two readings are two groups
+ expect(editor).toContain("label: 'Supports'");
+ expect(editor).toContain("hint: 'statements that rest on this one'");
+ expect(editor).toContain('row.direction === group.way');
+ });
+
+ it('states what rests on a statement from where that reasoning is written', () => {
+ // the incoming group takes no source: it is added from the citing claim
+ expect(editor).toContain('{#if group.add}');
+ expect(editor).toContain('{#if group.add && adding === group.type}');
+ // and a reading nobody can add to earns a heading only once it holds something
+ expect(editor).toContain('{#if group.add || items.length}');
+ });
+
+ it('reads a contradiction under one heading, whichever end filed it', () => {
+ // two statements that cannot both hold say the same thing from either end, so
+ // splitting them into "contradicts" and "is contradicted by" would be two
+ // headings for one finding — the group declares no `way`, so both are listed
+ expect(editor).toContain(
+ "{ type: 'contradicts', label: 'Contradictions', add: 'Add contradiction' }"
+ );
+ expect(editor).toContain('(!group.way || row.direction === group.way)');
+ });
+
+ it('stores the connector through the shared relation contract', () => {
+ expect(editor).toContain('await saveRelation(caseId, claim.id, choice)');
+ expect(editor).toContain('api.del(`/api/cases/${caseId}/links/${link.id}`)');
+ expect(editor).not.toContain('api.patch');
+ });
+
+ it('never reads a rating off a Claim connector', () => {
+ // Confidence belongs to the Claim node, and `about`/`at`/`cites` are declared
+ // `ratable: false`, so no route can put one on these edges. Rendering one would
+ // be a control for a state the model cannot reach.
+ for (const source of [editor, references]) {
+ expect(source).not.toContain('link.confidence');
+ expect(source).not.toContain('confidenceLabel');
+ }
+ });
+
+ it('shows incoming Claims as references, not editable relations', () => {
+ expect(references).toContain('relationReading(row.link.type, row.direction)');
+ expect(references).toContain('onwalk?.(row.entity)');
+ expect(references).not.toContain('api.patch');
+ expect(references).not.toContain('api.del');
+ });
+});
diff --git a/frontend/src/components/ClaimReferences.svelte b/frontend/src/components/ClaimReferences.svelte
new file mode 100644
index 0000000..8900111
--- /dev/null
+++ b/frontend/src/components/ClaimReferences.svelte
@@ -0,0 +1,56 @@
+<script>
+ import { entityIcon } from '../lib/entityIcon.js';
+ import { relationReading } from '../lib/relations.svelte.js';
+ import Icon from './Icon.svelte';
+
+ let { relations = [], onwalk = null } = $props();
+</script>
+
+{#if relations.length}
+ <div class="claims">
+ {#each relations as row (row.link.id)}
+ <button class="claim" onclick={() => onwalk?.(row.entity)}>
+ <Icon name={entityIcon(row.entity)} size={12} />
+ <span class="name">{row.entity.label}</span>
+ <small>{relationReading(row.link.type, row.direction)}</small>
+ </button>
+ {/each}
+ </div>
+{/if}
+
+<style>
+ .claims {
+ display: grid;
+ gap: 2px;
+ }
+ .claim {
+ display: flex;
+ align-items: center;
+ gap: 7px;
+ min-width: 0;
+ padding: 5px 6px;
+ border: 0;
+ border-radius: var(--r-sm);
+ background: transparent;
+ color: var(--text-2);
+ font: inherit;
+ font-size: var(--fs-sm);
+ text-align: left;
+ cursor: pointer;
+ }
+ .claim:hover {
+ background: var(--bg-2);
+ color: var(--text-1);
+ }
+ .name {
+ flex: 1;
+ min-width: 0;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ }
+ small {
+ color: var(--text-3);
+ font-size: 10px;
+ }
+</style>
diff --git a/frontend/src/components/EntityCreate.svelte b/frontend/src/components/EntityCreate.svelte
new file mode 100644
index 0000000..cfb61e6
--- /dev/null
+++ b/frontend/src/components/EntityCreate.svelte
@@ -0,0 +1,289 @@
+<script>
+ /**
+ * Filing a hand-made entity, wherever the analyst is standing.
+ *
+ * One dialog for two surfaces, and that is the whole point: a `claim` is created
+ * with the same words, the same field names and the same duplicate warning whether
+ * it was started from a row in the Board or from a right-click on the drawing. Two
+ * copies of this form would be two vocabularies inside a week.
+ *
+ * Everything it renders comes from the registry (`engine/entities.py`): which types
+ * an analyst may create, what the primary value is called for each one — **IP
+ * address**, **Full name**, **Handle**, never a generic *Name* — and whatever else
+ * the type declares. Adding a type is an edit there, not a panel here.
+ */
+ import { api } from '../lib/api.js';
+ import { caseState, reloadCase, toast } from '../lib/state.svelte.js';
+ import {
+ creatableTypes,
+ entityFamily,
+ entityHint,
+ entityIdentityLabel,
+ entityIdentityPlaceholder,
+ hasImageGallery,
+ } from '../lib/entityTypes.svelte.js';
+ import Modal from './Modal.svelte';
+ import AttrFields from './AttrFields.svelte';
+ import EntityPhotoDraft from './EntityPhotoDraft.svelte';
+
+ let {
+ /** The type to open on: what the analyst is already looking at. */
+ startType = '',
+ /** Types this surface will not show once they exist, with the reason. A graph lens
+ * draws some types and not others, and creating something invisible is worse than
+ * being told beforehand. */
+ hidden = [],
+ hiddenNote = '',
+ /** The row this case already holds under the same identifier, offered instead. */
+ ontwin = () => {},
+ oncreated = () => {},
+ onclose = () => {},
+ } = $props();
+
+ // Captured once on purpose: `startType` is where the dialog *opens*, and the analyst
+ // picks from there. Tracked, the select would snap back under them whenever the
+ // surface behind re-rendered with its own idea of the type.
+ // svelte-ignore state_referenced_locally
+ let draft = $state({ type: startType || creatableTypes()[0]?.type || '', label: '', notes: '', attrs: {} });
+ let saving = $state(false);
+ let photos = $state([]);
+ let primaryPhotoId = $state(null);
+
+ const identityLabel = $derived(entityIdentityLabel(draft.type));
+ const identityPlaceholder = $derived(entityIdentityPlaceholder(draft.type));
+ const unseen = $derived(hidden.includes(draft.type));
+
+ $effect(() => {
+ if (!hasImageGallery(draft.type)) {
+ photos = [];
+ primaryPhotoId = null;
+ }
+ });
+
+ /**
+ * An entity of the same type already carrying this value.
+ *
+ * Only a warning, and only where it means something: in the `identifier` family the
+ * value *is* the identity, so two `email` rows holding one address are two records
+ * of one thing (ONTOLOGY §2). It does not block — merging is not shipped, and
+ * refusing the second entry would leave nowhere to put it — it offers the existing
+ * row instead, which is what the analyst almost always wanted.
+ *
+ * **What counts as the same value is the registry's** (`entities.identity_key`),
+ * asked for rather than worked out here. Comparing the lowercased label in the
+ * browser is what let `@handle` and `handle`, or one phone number spaced two ways,
+ * sit side by side as two records.
+ */
+ let twin = $state(null);
+ $effect(() => {
+ const label = draft.label.trim();
+ const kind = draft.type;
+ const caseId = caseState.current?.id;
+ // The family test is the same one the route applies, kept here to spare the
+ // request: nothing outside `identifier` has an identity a label can duplicate.
+ if (!label || !caseId || entityFamily(kind) !== 'identifier') {
+ twin = null;
+ return;
+ }
+ // debounced like every other search here: an address is typed one character at a
+ // time and none of the first fifteen is a question worth asking
+ let live = true;
+ const timer = setTimeout(() => {
+ api
+ .get(
+ `/api/cases/${caseId}/entities/twin?${new URLSearchParams({ type: kind, label })}`
+ )
+ .then((body) => {
+ if (live) twin = body.entity ?? null;
+ })
+ .catch(() => {
+ if (live) twin = null;
+ });
+ }, 250);
+ return () => {
+ live = false;
+ clearTimeout(timer);
+ };
+ });
+
+ async function addPhotos(entityId) {
+ const imageIds = new Map();
+ const knownIds = new Set();
+ let images = [];
+ let failed = 0;
+ for (const photo of photos) {
+ try {
+ let result;
+ if (photo.source === 'computer') {
+ const form = new FormData();
+ form.append('file', photo.file);
+ result = await api.post(
+ `/api/cases/${caseState.current.id}/entities/${entityId}/images/upload`,
+ form
+ );
+ const added = result.images.find((image) => !knownIds.has(image.id));
+ if (added) imageIds.set(photo.draftId, added.id);
+ } else {
+ result = await api.post(
+ `/api/cases/${caseState.current.id}/entities/${entityId}/images`,
+ { media_ids: [photo.mediaId] }
+ );
+ if (result.images.some((image) => image.id === photo.mediaId)) {
+ imageIds.set(photo.draftId, photo.mediaId);
+ }
+ }
+ images = result.images;
+ for (const image of images) knownIds.add(image.id);
+ } catch {
+ failed += 1;
+ }
+ }
+ const primaryImageId = imageIds.get(primaryPhotoId);
+ if (primaryImageId && !images.find((image) => image.id === primaryImageId)?.primary) {
+ try {
+ await api.put(
+ `/api/cases/${caseState.current.id}/entities/${entityId}/images/${primaryImageId}/primary`
+ );
+ } catch {
+ toast('Primary photo could not be set.', 'danger');
+ }
+ }
+ return failed;
+ }
+
+ async function create() {
+ if (saving) return;
+ const label = draft.label.trim();
+ if (!draft.type || !label) return;
+ saving = true;
+ try {
+ const entity = await api.post(`/api/cases/${caseState.current.id}/entities`, {
+ type: draft.type,
+ label,
+ attrs: {
+ ...draft.attrs,
+ ...(draft.notes.trim() ? { notes: draft.notes.trim() } : {}),
+ },
+ });
+ const failedPhotos = hasImageGallery(draft.type) ? await addPhotos(entity.id) : 0;
+ await reloadCase();
+ if (failedPhotos) {
+ toast(
+ failedPhotos === 1 ? 'One photo could not be added.' : `${failedPhotos} photos could not be added.`,
+ 'danger'
+ );
+ }
+ oncreated(entity);
+ } catch (e) {
+ toast(e.message, 'danger');
+ } finally {
+ saving = false;
+ }
+ }
+</script>
+
+<Modal title="New entity" {onclose} width="620px">
+ <label class="modal-label" for="create-type">Type</label>
+ <!-- the menu says what each type is for: `claim` and `capture` are terse words
+ nobody can look up, and choosing the wrong one is a filing mistake -->
+ <select id="create-type" class="select" bind:value={draft.type} title={entityHint(draft.type)}>
+ {#each creatableTypes() as entry (entry.type)}
+ <option value={entry.type}>{entry.label}</option>
+ {/each}
+ </select>
+ {#if entityHint(draft.type)}
+ <p class="field-help">{entityHint(draft.type)}</p>
+ {/if}
+ {#if unseen && hiddenNote}
+ <!-- Said before the act, not after it: creating something this surface will not
+ draw looks exactly like creating nothing at all. -->
+ <p class="field-help warn">{hiddenNote}</p>
+ {/if}
+
+ <section class="create-card">
+ <label class="modal-label" for="create-label">{identityLabel}</label>
+ <input
+ id="create-label"
+ class="input"
+ placeholder={identityPlaceholder}
+ bind:value={draft.label}
+ onkeydown={(e) => e.key === 'Enter' && create()}
+ />
+
+ {#if twin}
+ <p class="twin">
+ This case already holds
+ <button class="twin-open" onclick={() => ontwin(twin)}>{twin.label}</button>. On an
+ identifier the value is the identity, so this would be a second record of one thing.
+ </p>
+ {/if}
+
+ <!-- whatever else this type declares, generated from the registry -->
+ <AttrFields type={draft.type} bind:values={draft.attrs} />
+
+ <label class="modal-label" for="create-notes">Notes</label>
+ <textarea
+ id="create-notes"
+ class="textarea"
+ rows="3"
+ placeholder="Add context or observations"
+ bind:value={draft.notes}
+ ></textarea>
+
+ {#if hasImageGallery(draft.type)}
+ <EntityPhotoDraft bind:photos bind:primaryId={primaryPhotoId} disabled={saving} />
+ {/if}
+ </section>
+
+ <div class="modal-row">
+ <div style="flex:1"></div>
+ <button class="btn" onclick={onclose}>Cancel</button>
+ <button
+ class="btn btn-primary"
+ onclick={create}
+ disabled={saving || !draft.type || !draft.label.trim()}
+ >
+ {saving ? 'Creating…' : 'Create'}
+ </button>
+ </div>
+</Modal>
+
+<style>
+ .field-help {
+ margin: 5px 0 0;
+ color: var(--text-3);
+ font-size: var(--fs-xs);
+ }
+ .field-help.warn {
+ color: var(--warn);
+ }
+ .create-card {
+ margin-top: 14px;
+ padding: 12px;
+ border: 1px solid var(--border);
+ border-radius: var(--r);
+ background: var(--bg-2);
+ }
+ .create-card .modal-label:first-child {
+ margin-top: 0;
+ }
+ .create-card .textarea {
+ width: 100%;
+ resize: vertical;
+ }
+ .twin {
+ margin: 8px 0 0;
+ color: var(--warn);
+ font-size: var(--fs-xs);
+ line-height: 1.5;
+ }
+ .twin-open {
+ padding: 0;
+ border: 0;
+ background: none;
+ color: inherit;
+ font: inherit;
+ text-decoration: underline;
+ cursor: pointer;
+ }
+</style>
diff --git a/frontend/src/components/EntityCreate.test.js b/frontend/src/components/EntityCreate.test.js
new file mode 100644
index 0000000..5567ab1
--- /dev/null
+++ b/frontend/src/components/EntityCreate.test.js
@@ -0,0 +1,89 @@
+import { describe, expect, it } from 'vitest';
+import { readFileSync } from 'node:fs';
+
+const source = readFileSync(new URL('./EntityCreate.svelte', import.meta.url), 'utf8');
+
+describe('one dialog, wherever the analyst is standing', () => {
+ it('builds itself from the registry instead of a form per type', () => {
+ expect(source).toContain("import AttrFields from './AttrFields.svelte'");
+ expect(source).toContain('<AttrFields type={draft.type} bind:values={draft.attrs} />');
+ expect(source).toContain('creatableTypes()');
+ });
+
+ it('names the primary value for the chosen type, never "Name"', () => {
+ // an IP address, a full name, a handle — a generic box is the lie this vocabulary
+ // went to the trouble of avoiding
+ expect(source).toContain('entityIdentityLabel(draft.type)');
+ expect(source).toContain('entityIdentityPlaceholder(draft.type)');
+ expect(source).not.toContain('>Name</label>');
+ });
+
+ it('says what each type is for, since choosing wrong is a filing mistake', () => {
+ expect(source).toContain('title={entityHint(draft.type)}');
+ expect(source).toContain('{#if entityHint(draft.type)}');
+ });
+
+ it('takes notes with the creation rather than after it', () => {
+ expect(source).toContain('for="create-notes"');
+ expect(source).toContain("...(draft.notes.trim() ? { notes: draft.notes.trim() } : {})");
+ });
+
+ it('stages photos for supported types and adds them after the entity exists', () => {
+ expect(source).toContain("import EntityPhotoDraft from './EntityPhotoDraft.svelte'");
+ expect(source).toContain('{#if hasImageGallery(draft.type)}');
+ expect(source).toContain('<EntityPhotoDraft bind:photos');
+ expect(source).toContain('await addPhotos(entity.id)');
+ expect(source.indexOf('/entities`, {')).toBeLessThan(source.indexOf('await addPhotos(entity.id)'));
+ });
+
+ it('keeps computer imports private and Media choices as references', () => {
+ expect(source).toContain('/entities/${entityId}/images/upload`');
+ expect(source).toContain('{ media_ids: [photo.mediaId] }');
+ expect(source).not.toContain('/media/upload`');
+ });
+
+ it('applies the selected primary photo before opening Details', () => {
+ expect(source).toContain('imageIds.get(primaryPhotoId)');
+ expect(source).toContain('/images/${primaryImageId}/primary`');
+ expect(source.indexOf('await addPhotos(entity.id)')).toBeLessThan(source.indexOf('oncreated(entity)'));
+ });
+});
+
+describe('a second record of one thing', () => {
+ it('warns on an identifier the case already holds, and never blocks', () => {
+ // in that family the value *is* the identity; merging is not shipped, so refusing
+ // the entry would leave nowhere to put it
+ expect(source).toContain("entityFamily(kind) !== 'identifier'");
+ expect(source).toContain('This case already holds');
+ expect(source).toContain('disabled={saving || !draft.type || !draft.label.trim()}');
+ });
+
+ it('hands the existing row back to whoever opened the dialog', () => {
+ // the Board opens its Details, the graph selects its node: the same offer, two
+ // right answers, so the dialog states neither
+ expect(source).toContain('onclick={() => ontwin(twin)}');
+ });
+
+ it('asks the case once the value is typed, not once a letter is', () => {
+ expect(source).toContain('setTimeout(');
+ expect(source).toContain('}, 250);');
+ });
+
+ it('lets the registry decide what counts as the same value', () => {
+ // Lowercasing the raw label in the browser let `@handle` and `handle` sit side
+ // by side as two accounts, and one phone number spaced two ways as two numbers.
+ // `entities.identity_key` is the one comparison, so the route is asked for it.
+ expect(source).toContain('/entities/twin?');
+ expect(source).not.toContain('buildCatalogQuery');
+ expect(source).not.toContain('toLowerCase()');
+ });
+});
+
+describe('creating something the surface will not show', () => {
+ it('says so before the act rather than after it', () => {
+ // a graph lens draws some types and not others, and filing something invisible
+ // looks exactly like filing nothing at all
+ expect(source).toContain('const unseen = $derived(hidden.includes(draft.type))');
+ expect(source).toContain('{#if unseen && hiddenNote}');
+ });
+});
diff --git a/frontend/src/components/EntityDetails.render.test.js b/frontend/src/components/EntityDetails.render.test.js
new file mode 100644
index 0000000..952cc59
--- /dev/null
+++ b/frontend/src/components/EntityDetails.render.test.js
@@ -0,0 +1,127 @@
+// @vitest-environment happy-dom
+/**
+ * The panel mounted, for the one thing reading the source cannot answer: whether
+ * the declared fields end up carrying the values the entity actually holds.
+ *
+ * Seeding is keyed on the entity id, and the vocabulary is fetched — so a registry
+ * that landed after the panel opened used to leave a radius of 500 rendering as
+ * "Unknown". Nothing was lost on Save (the backend merges `attrs`), but the panel
+ * was telling the analyst the case held nothing there.
+ *
+ * The registry here is the real `entityTypes.svelte.js` with only its fetch stubbed,
+ * and `caseState` is a real rune object: the bug is in dependency tracking, so an
+ * inert stand-in would make the effect under test never re-run and the guard
+ * meaningless.
+ */
+import { describe, expect, it, vi, afterEach } from 'vitest';
+import { flushSync, mount, unmount } from 'svelte';
+
+const REGISTRY = [
+ {
+ type: 'place',
+ family: 'place',
+ label: 'Place',
+ manual: true,
+ icon: 'pin',
+ identity_label: 'Title',
+ identity_placeholder: 'What to call it',
+ group: '',
+ attrs: [
+ { key: 'radius_m', label: 'Uncertainty radius (m)', kind: 'number', rungs: [], minimum: 1 },
+ { key: 'method', label: 'How this point was found', kind: 'longtext', rungs: [] },
+ ],
+ },
+];
+
+// The vocabulary request, held open until the test lets it land.
+let landRegistry;
+const registryLanded = new Promise((resolve) => {
+ landRegistry = resolve;
+});
+
+vi.mock('../lib/api.js', async () => {
+ // The panel reads its entity off the bounded chain endpoint, never off the case.
+ const { entity } = await import('./details.fixture.svelte.js');
+ const chain = { entity, sources: [], lost: [], dependents: [], relations: [], empty: true };
+ return {
+ api: {
+ get: (url) => (url.includes('entity-types') ? registryLanded : Promise.resolve(chain)),
+ patch: vi.fn(),
+ post: vi.fn(),
+ del: vi.fn(),
+ },
+ };
+});
+vi.mock('../lib/state.svelte.js', async () => await import('./details.fixture.svelte.js'));
+vi.mock('../lib/relations.svelte.js', () => ({
+ loadRelationTypes: () => Promise.resolve(),
+ relatableTypes: () => [],
+ relationAction: () => 'relation',
+ saveRelation: vi.fn(),
+}));
+vi.mock('../lib/navigate.js', () => ({
+ openEntity: () => {},
+ opensInFileManager: () => false,
+ showInFolder: () => {},
+ gotoCapture: () => {},
+ gotoPoint: () => {},
+ ENTITY_TOOL: {},
+}));
+vi.mock('../lib/entityIcon.js', () => ({ entityIcon: () => 'pin' }));
+vi.mock('../lib/filing.js', () => ({ assignFolder: vi.fn() }));
+vi.mock('../lib/poll.js', () => ({ pollWhile: () => () => {} }));
+vi.mock('../lib/trash.js', () => ({ deletedToast: () => {}, RESTORABLE: [] }));
+
+const { default: EntityDetails } = await import('./EntityDetails.svelte');
+
+let live = null;
+
+async function open(props = {}) {
+ const target = document.createElement('div');
+ document.body.append(target);
+ live = mount(EntityDetails, {
+ target,
+ props: { entityId: 'e1', onclose: () => {}, ...props },
+ });
+ flushSync();
+ for (let i = 0; i < 5; i += 1) await Promise.resolve(); // the chain read lands
+ flushSync();
+ return target;
+}
+
+/** Let the held-open vocabulary request resolve, with the panel already on screen. */
+async function land() {
+ landRegistry(REGISTRY);
+ for (let i = 0; i < 5; i += 1) await Promise.resolve();
+ flushSync();
+}
+
+const valueOf = (target, key) => target.querySelector(`#attr-${key}`)?.value ?? null;
+
+afterEach(() => {
+ if (live) unmount(live);
+ live = null;
+});
+
+describe('EntityDetails field seeding', () => {
+ it('carries the stored values when the registry lands after the panel opened', async () => {
+ let dirty = false;
+ const target = await open({
+ get dirty() {
+ return dirty;
+ },
+ set dirty(value) {
+ dirty = value;
+ },
+ });
+ expect(target.querySelector('#attr-radius_m')).toBe(null); // nothing declared yet
+
+ await land();
+
+ expect(valueOf(target, 'radius_m')).toBe('500');
+ expect(valueOf(target, 'method')).toBe('roofline match');
+ // The values came off the entity, so nothing is unsaved. A panel that asked
+ // "discard changes?" on close here would be inventing an edit.
+ expect(dirty).toBe(false);
+ });
+});
diff --git a/frontend/src/components/EntityDetails.svelte b/frontend/src/components/EntityDetails.svelte
index edfa1fd..c9b38cb 100644
--- a/frontend/src/components/EntityDetails.svelte
+++ b/frontend/src/components/EntityDetails.svelte
@@ -11,21 +11,58 @@
* juggling. Clicking a chain row walks the details to that entity in place.
*/
import { api } from '../lib/api.js';
- import { caseState, reloadCase, toast } from '../lib/state.svelte.js';
+ import { fileUrl } from '../lib/fileUrl.js';
+ import { caseState, reloadCase, toast, uiState } from '../lib/state.svelte.js';
import { buildTree, flattenPaths, folderOf } from '../lib/folderTree.js';
import { assignFolder as fileEntity } from '../lib/filing.js';
- import { DEPENDS_ON } from '../lib/chain.js';
- import { loadRelationTypes, relatableTypes, saveRelation } from '../lib/relations.svelte.js';
- import { openEntity, gotoCapture, ENTITY_TOOL } from '../lib/navigate.js';
+ import {
+ entityFamily,
+ entityFields,
+ entityIdentityLabel,
+ entityIdentityPlaceholder,
+ entityLabel,
+ hasImageGallery,
+ loadEntityTypes,
+ } from '../lib/entityTypes.svelte.js';
+ import { entityIcon } from '../lib/entityIcon.js';
+ import { confidenceLine, countLines, noteLines } from '../lib/tally.js';
+ import {
+ loadRelationTypes,
+ relatableTypes,
+ relationAction,
+ saveRelation,
+ } from '../lib/relations.svelte.js';
+ import {
+ openEntity,
+ opensInFileManager,
+ showInFolder,
+ gotoCapture,
+ gotoPoint,
+ ENTITY_TOOL,
+ } from '../lib/navigate.js';
import { pollWhile } from '../lib/poll.js';
import { deletedToast, RESTORABLE } from '../lib/trash.js';
import Icon from './Icon.svelte';
import ConfirmDialog from './ConfirmDialog.svelte';
import FolderSelect from './FolderSelect.svelte';
+ import AttrFields from './AttrFields.svelte';
+ import ClaimConnections from './ClaimConnections.svelte';
+ import ClaimReferences from './ClaimReferences.svelte';
import RelationList from './RelationList.svelte';
import RelationPicker from './RelationPicker.svelte';
+ import EntityImages from './EntityImages.svelte';
+ import EntityTime from './EntityTime.svelte';
- let { entityId, onclose, ondeleted, previewActions } = $props();
+ let {
+ entityId,
+ onclose,
+ ondeleted,
+ previewActions,
+ // Whether the fields hold edits Save has not taken. Read by the hosts that can
+ // be closed out from under the panel — a modal answers Escape and its backdrop,
+ // and throwing a half-typed field away without a word is not a close.
+ dirty = $bindable(false),
+ } = $props();
// Chain rows walk the details to another entity in place; that override sticks
// until the host selects a different entity, when it clears back to the prop.
@@ -67,13 +104,11 @@
// Entity types backed by a file on disk — deleting them drops the file.
const FILE_BACKED = new Set(['media', 'capture', 'proof', 'post', 'inspect-session', 'note']);
- // Every artifact type gets the title/notes editor. Media/captures go through
- // their sidecar PATCH; the rest edit the entity itself.
- const EDITABLE = new Set(['capture', 'place', 'media', 'proof', 'post', 'inspect-session', 'note', 'bookmark']);
- const ENTITY_ICON = {
- media: 'media', capture: 'satellite', place: 'pin', proof: 'proof',
- post: 'post', 'inspect-session': 'inspect', note: 'note', bookmark: 'link',
- };
+ // Every type gets the title/notes editor — a list of which ones did was a list
+ // that drifted: none of the hand-made types were on it, so a claim created on the
+ // board opened with a title nobody could correct. A capture and a media commit
+ // through their own tool's route, which writes the sidecar; everything else
+ // patches the entity.
// ── resolved listing item (media/satellite) + editable fields ──────────────
let infoData = $state(null);
@@ -83,10 +118,66 @@
let infoFolder = $state('');
let infoSaving = $state(false);
let seededId = null; // the id whose fields are currently loaded
+ let seededFields = 0; // declared fields the registry knew when they were loaded
+ // The declared fields of this type (ONTOLOGY §2), edited through AttrFields and
+ // committed with Save like the title and the notes. Only declared keys are held
+ // here, so a save can never disturb the geometry or sidecar keys a tool wrote.
+ let infoAttrs = $state({});
+
+ // What was on screen when the fields were last seeded or saved. Everything above
+ // waits for Save while the connections file themselves, so the panel has to be
+ // able to say whether closing it would lose anything.
+ let baseline = $state(null);
+
+ function snapshot() {
+ baseline = {
+ title: infoTitle,
+ notes: infoNotes,
+ folder: infoFolder,
+ attrs: { ...infoAttrs },
+ };
+ }
+
+ function changed() {
+ if (!baseline) return false;
+ if (infoTitle !== baseline.title) return true;
+ if (infoNotes !== baseline.notes) return true;
+ if (infoFolder !== baseline.folder) return true;
+ const keys = new Set([...Object.keys(baseline.attrs), ...Object.keys(infoAttrs)]);
+ for (const key of keys) {
+ if ((baseline.attrs[key] ?? null) !== (infoAttrs[key] ?? null)) return true;
+ }
+ return false;
+ }
+
+ // Plain (untracked) mirror of the same answer: the seeding effect below has to
+ // ask "has anything been typed" without subscribing to every keystroke.
+ let dirtyNow = false;
+
+ $effect(() => {
+ dirty = changed();
+ dirtyNow = dirty;
+ });
+
+ // Every entity uses the same three readings. Keeping profile fields out of
+ // Connections also means Time can be opened without walking past unrelated rows.
+ let tab = $state('info');
+ $effect(() => {
+ currentId; // a different entity opens on its own terms
+ tab = 'info';
+ });
+
+
+ // The resolved item when there is one, and the entity's own pointer otherwise: a
+ // file action must not disappear because the browse index read came back empty.
const detailsFilePath = $derived(
- infoData?.path ?? (entity?.type === 'capture' ? entity.attrs?.path : null)
+ infoData?.path ??
+ (entity?.type === 'capture' || entity?.type === 'media' ? entity.attrs?.path : null)
);
+ // A document, a scan, a spreadsheet: no preview above, no tool to reopen it in,
+ // so the one action that helps is the folder it sits in.
+ const inFileManager = $derived(opensInFileManager(entity));
$effect(() => {
const e = entity;
@@ -97,12 +188,25 @@
return;
}
const firstSeed = seededId !== e.id; // …but only re-seed fields on a new selection
- if (firstSeed) {
+ const fields = entityFields(e.type);
+ // The vocabulary is fetched, so it can land *after* this panel opened — most
+ // visibly when the first request failed and the retry this component fires lands
+ // a moment later. Seeding is keyed on the entity, so without this the declared
+ // fields would render "Unknown" over an entity that holds a radius, a plate or a
+ // grade. Only when none were seeded yet, and only over an untouched panel: a
+ // late registry must never land on top of what the analyst has already typed.
+ const lateRegistry = !firstSeed && seededFields === 0 && fields.length > 0 && !dirtyNow;
+ if (firstSeed || lateRegistry) {
seededId = e.id;
- infoTitle = e.label ?? '';
- infoNotes = e.attrs?.notes ?? '';
- infoFolder = folderOf(e) ?? '';
- infoData = null;
+ seededFields = fields.length;
+ if (firstSeed) {
+ infoTitle = e.label ?? '';
+ infoNotes = e.attrs?.notes ?? '';
+ infoFolder = folderOf(e) ?? '';
+ infoData = null;
+ }
+ infoAttrs = Object.fromEntries(fields.map((f) => [f.key, e.attrs?.[f.key] ?? null]));
+ snapshot();
}
resolve(e, firstSeed);
});
@@ -136,6 +240,9 @@
if (infoData && seedFields) {
infoTitle = infoData.title ?? e.label ?? '';
infoNotes = infoData.notes ?? infoNotes;
+ // the sidecar is what the fields now hold, so it is what they are compared
+ // against — otherwise the panel would open already reading as edited
+ snapshot();
}
} catch {
// a failed quiet re-read keeps what is on screen: the panel is being read,
@@ -161,23 +268,229 @@
return pollWhile(() => enriching, () => resolve(entity, false, true), 1500);
});
- // A relation stated here rides along with Save, like the title and the notes:
- // the panel's model is "edit the fields, press Save", and a second commit
- // button beside it would be one gesture too many.
- let pendingRelation = $state(null);
+ // Connections have their own explicit composer. They are graph statements, not
+ // unsaved text fields, so waiting on the panel-wide Save made the Add action feel
+ // broken and let a mention masquerade as a relation.
+ let connectionComposer = $state(null); // 'relation' | 'mention' | null
+ let connectionSaving = $state(false);
loadRelationTypes();
- const canRelate = $derived(!!entity && relatableTypes(entity.type).length > 0);
+ loadEntityTypes();
+ const relationTargetTypes = $derived(
+ entity ? relatableTypes(entity, 'relation') : []
+ );
+ const mentionTargetTypes = $derived(
+ entity ? relatableTypes(entity, 'mention') : []
+ );
+ const canRelate = $derived(relationTargetTypes.length > 0);
+ const canMention = $derived(mentionTargetTypes.length > 0);
+ const relationTargetHint = $derived(
+ `Relate this to: ${relationTargetTypes.map(entityLabel).join(', ')}.`
+ );
+ const mentionTargetHint = $derived(
+ `Mentions connect this with: ${mentionTargetTypes.map(entityLabel).join(', ')}.`
+ );
+ const declaredFields = $derived(entity ? entityFields(entity.type) : []);
+ const identityLabel = $derived(entity ? entityIdentityLabel(entity.type) : 'Title');
+ const identityPlaceholder = $derived(
+ entity ? entityIdentityPlaceholder(entity.type) : 'What to call it'
+ );
+ const ordinaryRelations = $derived(
+ (chain?.relations ?? []).filter((row) => relationAction(row.link.type) === 'relation')
+ );
+ const mentionRelations = $derived(
+ (chain?.relations ?? []).filter((row) => relationAction(row.link.type) === 'mention')
+ );
+ const claimRelations = $derived(
+ (chain?.relations ?? []).filter((row) => relationAction(row.link.type) === 'claim')
+ );
+ const hasRelations = $derived(Boolean(chain?.relations?.length));
+ const lineageCount = $derived(
+ (chain?.sources?.length ?? 0) +
+ (chain?.lost?.length ?? 0) +
+ (chain?.dependents?.length ?? 0)
+ );
+ const lineageLabel = $derived(
+ entity?.type === 'inspect-session' ? 'Depends on & used by' : 'Made from & used by'
+ );
+
+ // Where the chain puts this entity (ONTOLOGY §3). Its own request, and only once
+ // the Connections tab is on screen: the walk reaches further than the chain's one hop,
+ // and the panel opens on Info, so clicking through a list of rows never pays for it.
+ let placement = $state(null); // { points, truncated }
+ let placeSeq = 0;
+ const placedPoints = $derived(placement?.points ?? []);
+
+ $effect(() => {
+ const id = currentId;
+ const cid = caseState.current?.id;
+ const wanted = tab === 'connections';
+ caseState.rev; // a save can add or drop a panel, and with it a point
+ const mySeq = ++placeSeq;
+ if (!id || !cid || !wanted) {
+ placement = null;
+ return;
+ }
+ api
+ .get(`/api/cases/${cid}/entities/${id}/placement`)
+ .then((p) => { if (mySeq === placeSeq) placement = p; })
+ .catch(() => { if (mySeq === placeSeq) placement = null; });
+ });
+
+ /**
+ * What the statements about this entity come to (`engine/tally.py`).
+ *
+ * The panel already lists the claims pointing here; it never added them up, so
+ * *how many of these were destroyed* was a question the analyst answered by reading
+ * four rows and doing the arithmetic. Read on the same terms as the placement
+ * beside it — its own request, only once Connections is on screen, and re-read
+ * after a save, since editing a statement changes what the case says.
+ *
+ * Over the whole case rather than any filter: this is a fact about the row, and a
+ * number that quietly obeyed a narrowing set on another screen would be a different
+ * number under the same words. 404 means nothing states anything about it, which is
+ * an ordinary answer here rather than an error.
+ */
+ let stated = $state(null);
+ let statedSeq = 0;
+
+ $effect(() => {
+ const id = currentId;
+ const cid = caseState.current?.id;
+ const wanted = tab === 'connections';
+ caseState.rev;
+ const mySeq = ++statedSeq;
+ if (!id || !cid || !wanted) {
+ stated = null;
+ return;
+ }
+ api
+ .get(`/api/cases/${cid}/entities/${id}/tally`)
+ .then((row) => { if (mySeq === statedSeq) stated = row; })
+ .catch(() => { if (mySeq === statedSeq) stated = null; });
+ });
+
+ /** The condition and confidence words, from the served registry rather than a list
+ * kept here, exactly as the Board's own tally reads them. */
+ const claimReads = $derived.by(() => {
+ const reads = {};
+ for (const field of entityFields('claim')) {
+ for (const option of field.options ?? []) reads[option.value] = option.label;
+ }
+ return (value) => reads[value] ?? value;
+ });
+
+ /** One point, written the way every other coordinate row in this panel writes one. */
+ function pointText(point) {
+ return `${Number(point.lat).toFixed(6)}, ${Number(point.lon).toFixed(6)}`;
+ }
$effect(() => {
currentId; // a different entity means a different subject
- pendingRelation = null;
+ connectionComposer = null;
});
+ /** Follow a connection or a lineage row, keeping unsaved fields.
+ *
+ * Walking replaces what the panel is showing, so it loses a half-typed field
+ * exactly the way closing does — and this one used to happen on a single click
+ * with nothing said. */
+ let pendingWalk = $state(null);
+
+ function walkTo(id) {
+ if (dirty) pendingWalk = id;
+ else walkedId = id;
+ }
+
+ /**
+ * The entity already holding the identifier this one is being renamed onto.
+ *
+ * The create form has warned about this since it shipped; renaming did not, and
+ * renaming is the half where it actually happens — an account filed as a bare
+ * handle gets its `@` typed in a week later, and the case quietly holds the same
+ * profile twice. Same route, same comparison (`entities.identity_key`), and it
+ * warns rather than refusing for the same reason it does there: merging is not
+ * shipped, so a refusal would leave the value nowhere to go.
+ */
+ let twin = $state(null);
+ $effect(() => {
+ const label = infoTitle.trim();
+ const kind = entity?.type;
+ const caseId = caseState.current?.id;
+ // Unchanged is not a duplicate, and `ignore` covers the rest: an entity is never
+ // its own twin, however the label is spelled on the way through.
+ if (!label || !kind || !caseId || entityFamily(kind) !== 'identifier') {
+ twin = null;
+ return;
+ }
+ let live = true;
+ const timer = setTimeout(() => {
+ api
+ .get(
+ `/api/cases/${caseId}/entities/twin?${new URLSearchParams({
+ type: kind,
+ label,
+ ignore: entity.id,
+ })}`
+ )
+ .then((body) => {
+ if (live) twin = body.entity ?? null;
+ })
+ .catch(() => {
+ if (live) twin = null;
+ });
+ }, 250);
+ return () => {
+ live = false;
+ clearTimeout(timer);
+ };
+ });
+
+ /** Accept a proposal from here as well as from the board: a suggestion is often
+ * read before it is settled, and the panel is where it is read. Its suggested
+ * relations are confirmed with it, which is the API's own invariant. */
+ let confirming = $state(false);
+
+ async function confirmEntity() {
+ if (!entity || confirming) return;
+ confirming = true;
+ try {
+ await api.patch(`/api/cases/${caseState.current.id}/entities/${entity.id}`, {
+ status: 'confirmed',
+ });
+ await reloadCase();
+ toast('Confirmed', 'ok', 1600);
+ } catch (e) {
+ toast(e.message, 'danger');
+ } finally {
+ confirming = false;
+ }
+ }
+
+ async function addConnection(choice) {
+ if (!entity || connectionSaving) return;
+ connectionSaving = true;
+ try {
+ await saveRelation(caseState.current.id, entity.id, choice);
+ await reloadCase();
+ toast(connectionComposer === 'mention' ? 'Mention added' : 'Relation added', 'ok', 1600);
+ connectionComposer = null;
+ } catch (e) {
+ toast(e.message, 'danger');
+ throw e; // keep the composer open so the selection is not lost
+ } finally {
+ connectionSaving = false;
+ }
+ }
+
async function saveInfo() {
if (!entity || infoSaving) return;
infoSaving = true;
const cid = caseState.current.id;
try {
+ // A capture and a media are saved through their own tool's route, which
+ // writes the sidecar and carries the title and the notes only. Neither type
+ // declares fields, so nothing is dropped here — and `tests/test_entities.py`
+ // fails the day one does, rather than letting a typed field vanish on Save.
if (entity.type === 'capture') {
await api.patch(`/api/cases/${cid}/satellite`, {
path: entity.attrs.path, title: infoTitle, notes: infoNotes,
@@ -186,19 +499,19 @@
await api.patch(`/api/cases/${cid}/media`, {
path: entity.attrs.path, title: infoTitle.trim(), notes: infoNotes,
});
- } else if (EDITABLE.has(entity.type)) {
+ } else {
await api.patch(`/api/cases/${cid}/entities/${entity.id}`, {
- label: infoTitle.trim() || entity.label, attrs: { notes: infoNotes.trim() },
+ label: infoTitle.trim() || entity.label,
+ // The backend merges attrs, so sending the declared fields beside the
+ // notes leaves every other key the tool wrote exactly where it was.
+ attrs: { notes: infoNotes.trim(), ...infoAttrs },
});
}
if ((infoFolder.trim() || '') !== (folderOf(entity) ?? '')) {
await fileEntity(cid, entity, infoFolder.trim());
}
- if (pendingRelation) {
- await saveRelation(cid, entity.id, pendingRelation);
- pendingRelation = null;
- }
await reloadCase();
+ snapshot(); // what is on screen is now what the case holds
toast('Saved', 'ok', 1600);
} catch (e) {
toast(e.message, 'danger');
@@ -276,18 +589,37 @@
<div class="info-loading">Loading…</div>
{/if}
+ <div class="ed-tabs" role="tablist" aria-label="Details sections">
+ <button
+ class="ed-tab" class:on={tab === 'info'} role="tab" aria-selected={tab === 'info'}
+ title="Identity, profile and file metadata"
+ onclick={() => (tab = 'info')}
+ >Info</button>
+ <button
+ class="ed-tab" class:on={tab === 'connections'} role="tab" aria-selected={tab === 'connections'}
+ title="Relations, statements and lineage"
+ onclick={() => (tab = 'connections')}
+ >Connections</button>
+ <button
+ class="ed-tab" class:on={tab === 'time'} role="tab" aria-selected={tab === 'time'}
+ title="Dates and time assessments"
+ onclick={() => (tab = 'time')}
+ >Time</button>
+ </div>
+
+ {#if tab === 'info'}
{#if infoData?.kind === 'image' && infoData.thumbnail}
<div class="info-preview">
- <img src={`/files/${caseState.current.id}/${infoData.path}`} alt={entity.label} />
+ <img src={fileUrl(caseState.current.id, infoData.path)} alt={entity.label} />
</div>
{:else if infoData?.kind === 'video'}
<div class="info-preview">
<!-- svelte-ignore a11y_media_has_caption -->
- <video src={`/files/${caseState.current.id}/${infoData.path}`} controls preload="metadata"></video>
+ <video src={fileUrl(caseState.current.id, infoData.path)} controls preload="metadata"></video>
</div>
{:else if entity.type === 'capture' && entity.attrs?.path}
<div class="info-preview">
- <img src={`/files/${caseState.current.id}/${entity.attrs.path}`} alt={entity.label} />
+ <img src={fileUrl(caseState.current.id, entity.attrs.path)} alt={entity.label} />
</div>
{/if}
@@ -297,11 +629,37 @@
</div>
{/if}
- {#if EDITABLE.has(entity.type)}
- <label class="modal-label" for="ed-title">Title</label>
- <input id="ed-title" class="input" bind:value={infoTitle} placeholder={entity.attrs?.coords ?? 'Title'} />
- {:else}
- <div class="details-title">{entity.label}</div>
+ <!-- A proposal says so where it is read, and carries the click that settles it.
+ Filtering the board to the suggestions only to have to guess which panel
+ accepts one is where this review stopped being a review. -->
+ {#if entity.provenance?.status === 'suggested'}
+ <div class="suggested-bar">
+ <Icon name="info" size={13} />
+ <span>A tool proposed this. Nobody has confirmed it.</span>
+ <button class="btn btn-sm" disabled={confirming} onclick={confirmEntity}>
+ {confirming ? 'Confirming…' : 'Confirm'}
+ </button>
+ </div>
+ {/if}
+
+ {#if hasImageGallery(entity.type)}
+ <EntityImages {entity} />
+ {/if}
+
+ <label class="modal-label" for="ed-title">{identityLabel}</label>
+ <input
+ id="ed-title"
+ class="input"
+ bind:value={infoTitle}
+ placeholder={entity.attrs?.coords ?? identityPlaceholder}
+ />
+
+ {#if twin}
+ <p class="twin">
+ This case already holds
+ <button class="twin-open" onclick={() => walkTo(twin.id)}>{twin.label}</button>. On an
+ identifier the value is the identity, so this would be a second record of one thing.
+ </p>
{/if}
<div class="info-rows">
@@ -367,12 +725,29 @@
<span class="info-k">URL</span>
<a class="mono src" href={entity.attrs.url} target="_blank" rel="noreferrer">{entity.attrs.url}</a>
</div>
+ <!-- When the page was seen, stamped by whatever filed it. Under Info because
+ it reports the save rather than the analyst's judgement, and absent on a
+ bookmark typed by hand — nothing was fetched. -->
+ {#if entity.attrs.fetched_at}
+ <div class="info-row">
+ <span class="info-k">Fetched</span>
+ <span class="mono">{entity.attrs.fetched_at.slice(0, 10)}</span>
+ </div>
+ {/if}
{/if}
{#if entity.attrs?.coords}
<div class="info-row"><span class="info-k">Coords</span><span class="mono">{entity.attrs.coords}</span></div>
{/if}
</div>
+ {#if declaredFields.length}
+ <AttrFields
+ type={entity.type}
+ bind:values={infoAttrs}
+ exclude={entity.type === 'claim' ? ['when', 'time_role', 'confidence', 'method', 'verbatim'] : []}
+ />
+ {/if}
+
{#if infoData?.kind === 'image' && (infoData.taken_at || infoData.gps || Object.keys(infoData.exif ?? {}).length)}
<details class="metadata-details">
<summary>EXIF metadata <span>{Object.keys(infoData.exif ?? {}).length}</span></summary>
@@ -407,74 +782,257 @@
</details>
{/if}
- <!-- derivation chain: click a row to walk to that entity's details -->
- {#if chain && (chain.sources.length || chain.lost.length || chain.dependents.length)}
- <div class="chain">
- {#if chain.sources.length || chain.lost.length}
- <div class="chain-h">Made from</div>
- {#each chain.sources as { entity: src, type } (src.id)}
- <button class="chain-row" onclick={() => (walkedId = src.id)}>
- <Icon name={ENTITY_ICON[src.type] ?? 'file'} size={12} />
- <span class="chain-label">{src.label}</span>
- {#if type === DEPENDS_ON}
- <span class="chain-tag" title="This view cannot outlive that item">needs</span>
+ <label class="modal-label" for="ed-notes">Notes</label>
+ <textarea id="ed-notes" class="textarea" rows="3" bind:value={infoNotes} placeholder="Add observations, links, context…"></textarea>
+
+ <span class="modal-label">Folder (My work)</span>
+ <FolderSelect bind:value={infoFolder} folders={allFolders} emptyLabel="None" />
+ {/if}
+
+ {#if tab === 'connections'}
+ <div class="case-layout">
+ {#if canRelate || canMention || hasRelations || lineageCount || placedPoints.length}
+ <section class="connections">
+ <div class="card-head connections-head"><h3>Connections</h3></div>
+
+ <!-- Read off the chain rather than stored: the label says what the rows
+ offer, and each row names what placed it, because the relation to the
+ point differs per row — a video was placed there by a proof, a proof
+ by the capture it composes. -->
+ {#if placedPoints.length}
+ <div class="connection-group">
+ <div class="connection-head"><h4>On the map</h4></div>
+ <div class="placed-items">
+ {#each placedPoints as point (`${point.lat},${point.lon}`)}
+ <div class="placed-item">
+ <span class="mono placed-point">{pointText(point)}</span>
+ {#if point.via}
+ <button
+ class="placed-via"
+ title={`Open ${point.via.label}`}
+ onclick={() => walkTo(point.via.id)}
+ >
+ <Icon name={entityIcon(point.via)} size={12} />
+ <span>via {point.via.label}</span>
+ </button>
+ {/if}
+ <button
+ class="btn btn-ghost btn-sm act"
+ title={`Show ${pointText(point)} on the map`}
+ aria-label={`Show ${pointText(point)} on the map`}
+ onclick={() => gotoPoint(Number(point.lat), Number(point.lon))}
+ >
+ <Icon name="crosshair" size={12} />
+ </button>
+ </div>
+ {/each}
+ {#if placement?.truncated}
+ <p class="placed-more">More points than this panel lists</p>
+ {/if}
+ </div>
+ </div>
+ {/if}
+
+ {#if canRelate || ordinaryRelations.length}
+ <div class="connection-group">
+ <div class="connection-head">
+ <h4>Relations</h4>
+ {#if canRelate}
+ <button
+ class="btn btn-ghost btn-sm"
+ class:on={connectionComposer === 'relation'}
+ title={relationTargetHint}
+ onclick={() => (connectionComposer = connectionComposer === 'relation' ? null : 'relation')}
+ >Add relation</button>
+ {/if}
+ </div>
+ <RelationList
+ caseId={caseState.current.id}
+ relations={ordinaryRelations}
+ subjectType={entity.type}
+ subject={entity}
+ actionFilter="relation"
+ onwalk={(target) => walkTo(target.id)}
+ onchanged={reloadCase}
+ />
+ {#if connectionComposer === 'relation'}
+ <RelationPicker
+ subjectType={entity.type}
+ subject={entity}
+ subjectId={entity.id}
+ action="relation"
+ expanded
+ busy={connectionSaving}
+ oncommit={addConnection}
+ oncancel={() => (connectionComposer = null)}
+ />
+ {/if}
+ </div>
+ {/if}
+
+ {#if canMention || mentionRelations.length}
+ <div class="connection-group">
+ <div class="connection-head">
+ <h4>Mentions</h4>
+ {#if canMention}
+ <button
+ class="btn btn-ghost btn-sm"
+ class:on={connectionComposer === 'mention'}
+ title={mentionTargetHint}
+ onclick={() => (connectionComposer = connectionComposer === 'mention' ? null : 'mention')}
+ >Add mention</button>
+ {/if}
+ </div>
+ <RelationList
+ caseId={caseState.current.id}
+ relations={mentionRelations}
+ subjectType={entity.type}
+ subject={entity}
+ actionFilter="mention"
+ onwalk={(target) => walkTo(target.id)}
+ onchanged={reloadCase}
+ />
+ {#if connectionComposer === 'mention'}
+ <RelationPicker
+ subjectType={entity.type}
+ subject={entity}
+ subjectId={entity.id}
+ action="mention"
+ expanded
+ busy={connectionSaving}
+ oncommit={addConnection}
+ oncancel={() => (connectionComposer = null)}
+ />
+ {/if}
+ </div>
+ {/if}
+
+ {#if entity.type === 'claim'}
+ <div class="connection-group claim-editor">
+ <ClaimConnections
+ caseId={caseState.current.id}
+ claim={entity}
+ relations={claimRelations}
+ onwalk={(target) => walkTo(target.id)}
+ onchanged={reloadCase}
+ />
+ </div>
+ {:else if claimRelations.length}
+ <div class="connection-group">
+ <div class="connection-head"><h4>Claims</h4></div>
+ <!-- What those statements come to, above the statements themselves.
+ The rows were always here; adding them up by reading four of them
+ was the arithmetic this line does. Only where a statement is
+ *about* this entity: a place reached by `at` and a source reached
+ by `cites` are listed below without being counted, because
+ neither says how many of anything. -->
+ {#if stated?.statements || stated?.refuted}
+ {@const lines = countLines(stated, claimReads)}
+ {@const notes = noteLines(stated)}
+ {@const sure = confidenceLine(stated, claimReads)}
+ <div class="stated">
+ {#if lines.length}
+ <p class="stated-sum">
+ {#each lines as line (line.value)}<span>{line.text}</span>{/each}
+ </p>
+ {/if}
+ <p class="stated-notes">
+ {stated.statements}
+ {stated.statements === 1 ? 'statement' : 'statements'}
+ {#if sure}<span>· {sure}</span>{/if}
+ {#each notes as note (note)}<span>· {note}</span>{/each}
+ </p>
+ </div>
+ {/if}
+ <ClaimReferences
+ relations={claimRelations}
+ onwalk={(target) => walkTo(target.id)}
+ />
+ </div>
+ {/if}
+
+ {#if lineageCount}
+ <details class="lineage-card">
+ <summary>
+ <span class="card-icon"><Icon name="layers" size={14} /></span>
+ <span class="lineage-title">{lineageLabel}</span>
+ <span class="lineage-count">{lineageCount}</span>
+ </summary>
+ <div class="lineage-columns">
+ {#if chain.sources.length || chain.lost.length}
+ <div class="lineage-group">
+ <h4>{entity.type === 'inspect-session' ? 'Depends on' : 'Made from'}</h4>
+ <div class="lineage-items">
+ {#each chain.sources as { entity: src, type } (src.id)}
+ <button class="lineage-item" onclick={() => walkTo(src.id)}>
+ <Icon name={entityIcon(src)} size={12} />
+ <span>{src.label}</span>
+ {#if type === 'depends-on'}
+ <small title="This view needs that item">needs</small>
+ {/if}
+ </button>
+ {/each}
+ {#each chain.lost as lost (lost.path)}
+ <div class="lineage-item gone" title={`Deleted on ${lost.at?.slice(0, 10) ?? 'an unknown date'}${lost.sha256 ? ` · sha256 ${lost.sha256}` : ''}`}>
+ <Icon name="alert" size={12} />
+ <span>{lost.label ?? lost.path}</span>
+ <small>deleted</small>
+ </div>
+ {#if lost.source_url}
+ <a class="lineage-source mono" href={lost.source_url} target="_blank" rel="noreferrer">{lost.source_url}</a>
+ {/if}
+ {/each}
+ </div>
+ </div>
+ {/if}
+ {#if chain.dependents.length}
+ <div class="lineage-group">
+ <h4>Used by</h4>
+ <div class="lineage-items">
+ {#each chain.dependents as { entity: dep, type } (dep.id)}
+ <button class="lineage-item" onclick={() => walkTo(dep.id)}>
+ <Icon name={entityIcon(dep)} size={12} />
+ <span>{dep.label}</span>
+ {#if type === 'depends-on'}
+ <small class="warn" title="Deleting this item also deletes that one">goes with it</small>
+ {/if}
+ </button>
+ {/each}
+ </div>
+ </div>
{/if}
- </button>
- {/each}
- {#each chain.lost as lost (lost.path)}
- <div class="chain-row gone" title={`Deleted on ${lost.at?.slice(0, 10) ?? 'an unknown date'}${lost.sha256 ? ` · sha256 ${lost.sha256}` : ''}`}>
- <Icon name="alert" size={12} />
- <span class="chain-label">{lost.label ?? lost.path}</span>
- <span class="chain-tag">deleted</span>
</div>
- {/each}
- {#each chain.lost as lost (lost.path + '-src')}
- {#if lost.source_url}
- <a class="chain-src mono" href={lost.source_url} target="_blank" rel="noreferrer">{lost.source_url}</a>
+ </details>
{/if}
- {/each}
+ </section>
{/if}
- {#if chain.dependents.length}
- <div class="chain-h">Used by</div>
- {#each chain.dependents as { entity: dep, type } (dep.id)}
- <button class="chain-row" onclick={() => (walkedId = dep.id)}>
- <Icon name={ENTITY_ICON[dep.type] ?? 'file'} size={12} />
- <span class="chain-label">{dep.label}</span>
- {#if type === DEPENDS_ON}
- <span class="chain-tag warn" title="Deleting this item deletes that one too">goes with it</span>
- {/if}
- </button>
- {/each}
- {/if}
- </div>
- {/if}
- <!-- relations: what this entity says about the world, not how it was made -->
- {#if canRelate}
- <div class="chain">
- <div class="chain-h">Relations</div>
- <RelationList
- caseId={caseState.current.id}
- relations={chain?.relations ?? []}
- subjectType={entity.type}
- onwalk={(target) => (walkedId = target.id)}
- onchanged={reloadCase}
- />
- <RelationPicker subjectType={entity.type} bind:value={pendingRelation} />
+ {#if !canRelate && !canMention && !hasRelations && !lineageCount && !placedPoints.length}
+ <div class="case-card empty-card">
+ <Icon name="link" size={16} />
+ <p>No connections yet.</p>
+ </div>
+ {/if}
</div>
{/if}
- {#if EDITABLE.has(entity.type)}
- <label class="modal-label" for="ed-notes">Notes</label>
- <textarea id="ed-notes" class="textarea" rows="3" bind:value={infoNotes} placeholder="Add observations, links, context…"></textarea>
+ {#if tab === 'time'}
+ <EntityTime caseId={caseState.current.id} {entity} {onclose} />
{/if}
- <span class="modal-label">Folder (My work)</span>
- <FolderSelect bind:value={infoFolder} folders={allFolders} emptyLabel="None" />
-
<div class="details-actions">
- {#if detailsFilePath}
- <a class="btn btn-ghost btn-sm" href={`/files/${caseState.current.id}/${detailsFilePath}`} target="_blank" rel="noreferrer">
+ {#if detailsFilePath && inFileManager}
+ <!-- Nothing here can display it, and the browser's answer is a download:
+ a second copy in Downloads, worked on outside the case. -->
+ <button
+ class="btn btn-ghost btn-sm"
+ title="Open the folder this file is in"
+ onclick={() => showInFolder(entity)}
+ >
+ <Icon name="folderOpen" size={13} /> Show in folder
+ </button>
+ {:else if detailsFilePath}
+ <a class="btn btn-ghost btn-sm" href={fileUrl(caseState.current.id, detailsFilePath)} target="_blank" rel="noreferrer">
<Icon name="external" size={13} /> Open file
</a>
{/if}
@@ -483,7 +1041,14 @@
<Icon name="external" size={13} /> Open link
</a>
{/if}
- {#if ENTITY_TOOL[entity.type] || entity.type === 'note'}
+ <!-- The archived copy is typed in Connections, so it needs somewhere to be
+ read: a field only ever written is a field nobody trusts. -->
+ {#if entity.type === 'bookmark' && entity.attrs?.archive_url}
+ <a class="btn btn-ghost btn-sm" href={entity.attrs.archive_url} target="_blank" rel="noreferrer">
+ <Icon name="external" size={13} /> Open archived copy
+ </a>
+ {/if}
+ {#if (ENTITY_TOOL[entity.type] && !inFileManager) || entity.type === 'note'}
<button class="btn btn-ghost btn-sm" onclick={() => { openEntity(entity); onclose?.(); }}>
<Icon name="arrowRight" size={13} /> {entity.type === 'note' ? 'Open note' : 'Open in tool'}
</button>
@@ -493,6 +1058,21 @@
<Icon name="crosshair" size={13} /> Go to coords
</button>
{/if}
+ <!-- Offered wherever an entity is read, which is the point: the panel opens off
+ a row, a map mark and a media tile alike, and every one of them is a place
+ somebody wants to ask *what is this connected to*. The drawing answers that
+ and no list can. -->
+ <button
+ class="btn btn-ghost btn-sm"
+ title="Draw it in the graph, with what it is connected to"
+ onclick={() => {
+ uiState.openGraphEntity = entity.id;
+ uiState.tool = 'graph';
+ onclose?.();
+ }}
+ >
+ <Icon name="graph" size={13} /> In the graph
+ </button>
</div>
<div class="details-actions">
<button
@@ -510,6 +1090,18 @@
</div>
{/if}
+{#if pendingWalk}
+ <ConfirmDialog
+ title="Discard changes?"
+ message="This item has edits that Save has not taken."
+ detail="Following the connection replaces what is on screen."
+ confirmLabel="Discard"
+ icon="alert"
+ onconfirm={() => { walkedId = pendingWalk; pendingWalk = null; }}
+ oncancel={() => (pendingWalk = null)}
+ />
+{/if}
+
{#if confirmState}
<ConfirmDialog
title={confirmState.title}
@@ -530,17 +1122,49 @@
.ed {
font-size: var(--fs-sm);
}
+ /* The same warning the create dialog carries, worded and styled the same: one
+ duplicate identifier reads one way whether it was typed into a new row or into
+ an existing one. */
+ .twin {
+ margin: 8px 0 0;
+ color: var(--warn);
+ font-size: var(--fs-xs);
+ line-height: 1.5;
+ }
+ .twin-open {
+ padding: 0;
+ border: 0;
+ background: none;
+ color: inherit;
+ font: inherit;
+ text-decoration: underline;
+ cursor: pointer;
+ }
+ .ed-tabs {
+ display: flex;
+ gap: 2px;
+ margin: 10px 0 8px;
+ border-bottom: 1px solid var(--border);
+ }
+ .ed-tab {
+ padding: 5px 10px;
+ background: none;
+ border: none;
+ border-bottom: 2px solid transparent;
+ color: var(--text-3);
+ font-size: var(--fs-xs);
+ cursor: pointer;
+ }
+ .ed-tab.on {
+ color: var(--text-1);
+ border-bottom-color: var(--accent);
+ }
.modal-label {
display: block;
font-size: var(--fs-xs);
color: var(--text-3);
margin: 8px 0 4px;
}
- .details-title {
- font-weight: 600;
- margin-bottom: 6px;
- overflow-wrap: anywhere;
- }
.details-actions {
display: flex;
align-items: center;
@@ -556,6 +1180,24 @@
color: var(--text-3);
padding: 6px 0;
}
+ /* the same hairline the relation rows and the board use for a machine's reading */
+ .suggested-bar {
+ display: flex;
+ align-items: center;
+ flex-wrap: wrap;
+ gap: 8px;
+ margin-bottom: 10px;
+ padding: 7px 9px;
+ border-left: 2px solid color-mix(in srgb, var(--accent) 55%, transparent);
+ border-radius: var(--r-sm);
+ background: var(--bg-2);
+ color: var(--text-2);
+ font-size: var(--fs-xs);
+ }
+ .suggested-bar span {
+ flex: 1;
+ min-width: 0;
+ }
.info-preview {
border-radius: var(--r);
overflow: hidden;
@@ -654,68 +1296,242 @@
resize: vertical;
}
- /* derivation chain rows (ONTOLOGY §3) */
- .chain {
- margin-top: 14px;
- display: flex;
- flex-direction: column;
- gap: 2px;
+ /* Case groups fields, connections and lineage without nesting every row in a card. */
+ .case-layout {
+ display: grid;
+ gap: 10px;
+ margin-top: 10px;
}
- .chain-h {
- font-size: var(--fs-xs);
- color: var(--text-3);
- text-transform: uppercase;
- letter-spacing: 0.04em;
- margin: 6px 0 3px;
+ .case-card {
+ min-width: 0;
+ padding: 12px;
+ border: 1px solid var(--border);
+ border-radius: var(--r);
+ background: var(--bg-2);
}
- .chain-row {
+ .card-head {
display: flex;
align-items: center;
- gap: 7px;
- width: 100%;
- padding: 5px 6px;
- border: 0;
+ gap: 9px;
+ margin-bottom: 8px;
+ }
+ .card-icon {
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+ width: 28px;
+ height: 28px;
+ flex: 0 0 auto;
border-radius: var(--r-sm);
- background: transparent;
+ background: var(--bg-3);
color: var(--text-2);
+ }
+ .card-head h3,
+ .lineage-group h4,
+ .empty-card p {
+ margin: 0;
+ }
+ .card-head h3 {
+ color: var(--text-1);
font-size: var(--fs-sm);
- text-align: left;
+ font-weight: 600;
+ }
+ .connections {
min-width: 0;
+ padding-top: 2px;
}
- button.chain-row {
- cursor: pointer;
+ .connections-head {
+ margin-bottom: 5px;
}
- button.chain-row:hover {
- background: var(--bg-2);
+ .connection-group {
+ padding: 7px 0;
+ border-top: 1px solid var(--border);
+ }
+ .connection-head {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ flex-wrap: wrap;
+ gap: 6px;
+ min-height: 28px;
+ }
+ .connection-head h4 {
+ margin: 0;
+ color: var(--text-2);
+ font-size: var(--fs-xs);
+ font-weight: 600;
+ }
+ .connection-head .on {
+ color: var(--accent);
+ }
+ /* The sum sits above the statements it is made of: the figure reads first because
+ it is the answer, and what it left out sits directly under it rather than in a
+ tooltip — a total that hides its uncounted and ruled-out statements is right and
+ misleading at once. */
+ .stated {
+ margin: 2px 0 8px;
+ }
+ .stated-sum {
+ display: flex;
+ flex-wrap: wrap;
+ gap: 4px 10px;
+ margin: 0;
color: var(--text-1);
+ font-variant-numeric: tabular-nums;
}
- .chain-row.gone {
+ .stated-notes {
+ margin: 2px 0 0;
color: var(--text-3);
+ font-size: var(--fs-xs);
}
- .chain-label {
- flex: 1;
+ .stated-notes span {
+ margin-left: 4px;
+ }
+ /* One row per point: the coordinate reads first because it is what the row is
+ for, the attribution second, the map action last — the same order the relation
+ rows put a name, its reading and its controls in. */
+ .placed-items {
+ display: flex;
+ flex-direction: column;
+ gap: 4px;
+ padding-top: 4px;
+ }
+ .placed-item {
+ display: flex;
+ align-items: center;
+ gap: 6px;
+ min-width: 0;
+ }
+ .placed-point {
+ font-size: var(--fs-xs);
+ }
+ .placed-via {
+ display: inline-flex;
+ align-items: center;
+ gap: 4px;
+ min-width: 0;
+ padding: 0;
+ border: 0;
+ background: none;
+ color: var(--text-3);
+ font: inherit;
+ font-size: 10px;
+ cursor: pointer;
+ }
+ .placed-via:hover {
+ color: var(--text-1);
+ }
+ .placed-via span {
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
- .chain-tag {
- flex-shrink: 0;
+ .placed-item .act {
+ margin-left: auto;
+ flex: none;
+ }
+ .placed-more {
+ margin: 2px 0 0;
+ color: var(--text-3);
font-size: 10px;
- padding: 1px 5px;
+ }
+ .lineage-card {
+ padding: 0;
+ border-top: 1px solid var(--border);
+ }
+ .lineage-card summary {
+ display: flex;
+ align-items: center;
+ gap: 9px;
+ padding: 9px 0;
+ color: var(--text-2);
+ cursor: pointer;
+ list-style: none;
+ }
+ .lineage-card summary::-webkit-details-marker {
+ display: none;
+ }
+ .lineage-title {
+ flex: 1;
+ font-weight: 600;
+ }
+ .lineage-count {
+ padding: 1px 6px;
border-radius: 999px;
- background: var(--bg-2);
+ background: var(--bg-3);
color: var(--text-3);
+ font-size: 10px;
+ }
+ .lineage-columns {
+ display: grid;
+ grid-template-columns: repeat(auto-fit, minmax(220px, 1fr));
+ gap: 12px;
+ padding: 0 0 8px;
+ }
+ .lineage-group h4 {
+ margin-bottom: 6px;
+ color: var(--text-3);
+ font-size: var(--fs-xs);
+ font-weight: 600;
+ }
+ .lineage-items {
+ display: flex;
+ flex-wrap: wrap;
+ gap: 6px;
+ }
+ .lineage-item {
+ display: inline-flex;
+ align-items: center;
+ gap: 6px;
+ min-width: 0;
+ max-width: 100%;
+ padding: 5px 7px;
+ border: 1px solid var(--border);
+ border-radius: var(--r-sm);
+ background: var(--bg-1);
+ color: var(--text-2);
+ font: inherit;
+ font-size: var(--fs-xs);
+ text-align: left;
+ }
+ button.lineage-item {
+ cursor: pointer;
+ }
+ button.lineage-item:hover {
+ border-color: var(--border-strong);
+ color: var(--text-1);
}
- .chain-tag.warn {
- background: color-mix(in srgb, var(--danger, #e5484d) 14%, transparent);
- color: color-mix(in srgb, var(--danger, #e5484d) 80%, var(--text-2));
+ .lineage-item span {
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
}
- .chain-src {
+ .lineage-item small {
+ color: var(--text-3);
font-size: 10px;
+ }
+ .lineage-item small.warn {
+ color: var(--danger);
+ }
+ .lineage-item.gone {
color: var(--text-3);
- padding: 0 6px 4px 25px;
+ }
+ .lineage-source {
+ display: block;
+ width: 100%;
overflow: hidden;
+ color: var(--text-3);
+ font-size: 10px;
text-overflow: ellipsis;
white-space: nowrap;
}
+ .empty-card {
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ gap: 8px;
+ min-height: 80px;
+ color: var(--text-3);
+ font-size: var(--fs-xs);
+ }
</style>
diff --git a/frontend/src/components/EntityDetails.test.js b/frontend/src/components/EntityDetails.test.js
index 00a495e..c0c40e9 100644
--- a/frontend/src/components/EntityDetails.test.js
+++ b/frontend/src/components/EntityDetails.test.js
@@ -3,6 +3,14 @@ import { readFileSync } from 'node:fs';
const source = readFileSync(new URL('./EntityDetails.svelte', import.meta.url), 'utf8');
+describe('entity photos', () => {
+ it('shows the gallery only for types enabled by the registry', () => {
+ expect(source).toContain("import EntityImages from './EntityImages.svelte'");
+ expect(source).toContain('{#if hasImageGallery(entity.type)}');
+ expect(source).toContain('<EntityImages {entity} />');
+ });
+});
+
describe('capture details', () => {
it('shows the recorded external capture page as a link', () => {
expect(source).toContain('{#if infoData?.source_url}');
@@ -30,36 +38,86 @@ describe('import enrichment details', () => {
});
it('renders relations through the shared list, walking the panel in place', () => {
- expect(source).toContain('relations={chain?.relations ?? []}');
- expect(source).toContain('onwalk={(target) => (walkedId = target.id)}');
+ expect(source).toContain('relations={ordinaryRelations}');
+ expect(source).toContain('relations={mentionRelations}');
+ expect(source).toContain('onwalk={(target) => walkTo(target.id)}');
expect(source).toContain('onchanged={reloadCase}');
});
+ it('asks before following a connection would throw away an unsaved field', () => {
+ // walking replaces what the panel shows, which loses a half-typed field the
+ // same way closing does — and it used to happen on one click, silently
+ expect(source).toContain('function walkTo(id) {');
+ expect(source).toContain('if (dirty) pendingWalk = id;');
+ expect(source).toContain('{#if pendingWalk}');
+ });
+
+ it('reports whether Save has taken what is on screen, for the host that closes it', () => {
+ expect(source).toContain('dirty = $bindable(false)');
+ expect(source).toContain('function snapshot() {');
+ expect(source).toContain('snapshot(); // what is on screen is now what the case holds');
+ });
+
+ it('says a proposal is one, and settles it where it is read', () => {
+ expect(source).toContain("entity.provenance?.status === 'suggested'");
+ expect(source).toContain("status: 'confirmed',");
+ expect(source).toContain('async function confirmEntity()');
+ });
+
it('separates relations from the derivation chain, which has its own rule', () => {
// a relation says something about the world; the chain says how a file was
// made and decides what a delete destroys
expect(source).toContain(
- '{#if chain && (chain.sources.length || chain.lost.length || chain.dependents.length)}'
+ '{#if canRelate || canMention || hasRelations || lineageCount || placedPoints.length}'
);
- expect(source).toContain('{#if canRelate}');
- expect(source).toContain('relatableTypes(entity.type).length > 0');
+ expect(source).toContain('{#if lineageCount}');
+ expect(source).toContain('<details class="lineage-card">');
});
- it('files a stated relation with Save rather than adding a second commit button', () => {
- expect(source).toContain('<RelationPicker subjectType={entity.type} bind:value={pendingRelation} />');
- expect(source).toContain('if (pendingRelation) {');
- expect(source).toContain('await saveRelation(cid, entity.id, pendingRelation);');
+ it('files a connection from its own Add action rather than the panel Save', () => {
+ expect(source).toContain('async function addConnection(choice)');
+ expect(source).toContain('await saveRelation(caseState.current.id, entity.id, choice);');
+ expect(source).toContain('oncommit={addConnection}');
+ const saveInfo = source.slice(source.indexOf('async function saveInfo()'), source.indexOf('// ── delete'));
+ expect(saveInfo).not.toContain('saveRelation(');
});
- it('drops a pending relation when the panel walks to another entity', () => {
+ it('closes the composer when the panel walks to another entity', () => {
expect(source).toContain('currentId; // a different entity means a different subject');
- expect(source).toContain('pendingRelation = null;');
+ expect(source).toContain('connectionComposer = null;');
+ });
+
+ it('gives relations and mentions separate controls', () => {
+ expect(source).toContain("relatableTypes(entity, 'relation') : []");
+ expect(source).toContain("relatableTypes(entity, 'mention') : []");
+ expect(source).toContain('>Add relation</button>');
+ expect(source).toContain('>Add mention</button>');
+ expect(source).toContain('action="relation"');
+ expect(source).toContain('action="mention"');
+ });
+
+ it('explains each Add button with the target types from the registry', () => {
+ expect(source).toContain('relationTargetTypes.map(entityLabel)');
+ expect(source).toContain('mentionTargetTypes.map(entityLabel)');
+ expect(source).toContain('title={relationTargetHint}');
+ expect(source).toContain('title={mentionTargetHint}');
+ });
+
+ it('warns when a rename walks an identifier onto one the case already holds', () => {
+ // The create dialog has warned since it shipped; renaming is the half where it
+ // actually happens — an account filed as a bare handle gets its `@` typed in a
+ // week later. Same route, same comparison, and it never refuses.
+ expect(source).toContain('/entities/twin?');
+ expect(source).toContain("entityFamily(kind) !== 'identifier'");
+ expect(source).toContain('ignore: entity.id');
+ expect(source).toContain('This case already holds');
+ expect(source).toContain('onclick={() => walkTo(twin.id)}');
});
});
describe('reading the file behind an entity', () => {
it('can place host actions directly below the media preview', () => {
- expect(source).toContain('let { entityId, onclose, ondeleted, previewActions } = $props();');
+ expect(source).toContain('previewActions,');
expect(source).toContain('{@render previewActions()}');
expect(source).toContain('.info-preview-actions {');
expect(source).toContain('justify-content: flex-end;');
@@ -98,3 +156,223 @@ describe('metadata arriving after the panel opened', () => {
expect(source).toContain('if (!quiet) infoData = null;');
});
});
+
+describe('the three tabs', () => {
+ it('gives every entity the same Info, Connections and Time sections', () => {
+ expect(source).toContain("let tab = $state('info')");
+ expect(source).toContain('aria-selected={tab === \'info\'}');
+ expect(source).toContain(">Info<");
+ expect(source).toContain(">Connections<");
+ expect(source).toContain(">Time<");
+ });
+
+ it('does not collapse hand-made entities into a different one-scroll layout', () => {
+ expect(source).not.toContain('unifiedDetails');
+ expect(source).not.toContain('isManualEntityType');
+ expect(source).toContain("{#if tab === 'info'}");
+ expect(source).toContain("{#if tab === 'connections'}");
+ expect(source).toContain("{#if tab === 'time'}");
+ });
+
+ it('files preview and identity under Info, with shared actions below every tab', () => {
+ const tabs = source.indexOf('<div class="ed-tabs"');
+ expect(source.indexOf('class="info-preview"')).toBeGreaterThan(tabs);
+ expect(source.indexOf('id="ed-title"')).toBeGreaterThan(tabs);
+ expect(source.indexOf('class="details-actions"')).toBeGreaterThan(
+ source.indexOf("{#if tab === 'time'}")
+ );
+ });
+
+ it('names the primary field from the entity type', () => {
+ expect(source).toContain('entityIdentityLabel(entity.type)');
+ expect(source).toContain('entityIdentityPlaceholder(entity.type)');
+ expect(source).toContain('for="ed-title">{identityLabel}</label>');
+ });
+
+ it('keeps profile fields in Info and graph structure in Connections', () => {
+ const infoTab = source.indexOf("{#if tab === 'info'}");
+ const connectionsTab = source.indexOf("{#if tab === 'connections'}");
+ expect(source.indexOf('<AttrFields', infoTab)).toBeLessThan(connectionsTab);
+ expect(source.indexOf('<details class="lineage-card">')).toBeGreaterThan(connectionsTab);
+ expect(source.indexOf('<RelationList')).toBeGreaterThan(connectionsTab);
+ });
+
+ it('keeps connections light and lineage collapsed', () => {
+ expect(source).toContain('<div class="case-layout">');
+ expect(source).toContain('<section class="connections">');
+ expect(source).not.toContain('profile-card');
+ expect(source).not.toContain('connections-card');
+ expect(source).not.toContain('layout="cards"');
+ expect(source).not.toContain('class="chain-h"');
+ expect(source).toContain('Made from & used by');
+ expect(source).not.toContain('>History<');
+ });
+
+ it('keeps Claim connectors in their own editor', () => {
+ expect(source).toContain("{#if entity.type === 'claim'}");
+ expect(source).toContain('<ClaimConnections');
+ expect(source).toContain('<ClaimReferences');
+ expect(source).toContain('relations={claimRelations}');
+ });
+
+ it('files the metadata, the notes and the folder under Info', () => {
+ const infoTab = source.indexOf("{#if tab === 'info'}");
+ const connectionsTab = source.indexOf("{#if tab === 'connections'}");
+ for (const marker of [
+ '<div class="info-rows">',
+ '<summary>EXIF metadata',
+ 'id="ed-notes"',
+ '<FolderSelect',
+ ]) {
+ const at = source.indexOf(marker);
+ expect(at, marker).toBeGreaterThan(infoTab);
+ expect(at, marker).toBeLessThan(connectionsTab);
+ }
+ });
+
+ it('mounts the entity-scoped temporal read only while Time is open', () => {
+ const timeTab = source.indexOf("{#if tab === 'time'}");
+ expect(source.indexOf('<EntityTime', timeTab)).toBeGreaterThan(timeTab);
+ expect(source).toContain('caseId={caseState.current.id}');
+ });
+
+ it('opens a freshly walked entity on Info rather than wherever the last one sat', () => {
+ expect(source).toContain("tab = 'info';");
+ });
+});
+
+describe('the declared fields', () => {
+ it('are generated from the registry, not written per type here', () => {
+ expect(source).toContain("import AttrFields from './AttrFields.svelte'");
+ expect(source).toContain('<AttrFields');
+ expect(source).toContain('type={entity.type}');
+ expect(source).toContain('bind:values={infoAttrs}');
+ expect(source).toContain("exclude={entity.type === 'claim'");
+ expect(source).toContain("['when', 'time_role', 'confidence', 'method', 'verbatim']");
+ expect(source).toContain('{#if declaredFields.length}');
+ });
+
+ it('are seeded from the entity and committed beside the notes, merged not replaced', () => {
+ expect(source).toContain('fields.map((f) => [f.key, e.attrs?.[f.key] ?? null])');
+ expect(source).toContain('attrs: { notes: infoNotes.trim(), ...infoAttrs }');
+ });
+
+ it('re-seed when the vocabulary lands after the panel opened', () => {
+ // The registry is fetched, so an entity can be on screen before its fields are
+ // known. `EntityDetails.render.test.js` drives the DOM for the real proof.
+ expect(source).toContain('seededFields === 0 && fields.length > 0 && !dirtyNow');
+ });
+
+ it('do not affect the Connections empty state because they live in Info', () => {
+ expect(source).toContain('!hasRelations && !lineageCount && !placedPoints.length');
+ expect(source).not.toContain('!declaredFields.length && !lineageCount');
+ });
+});
+
+describe('a bookmark, which is what a claim rests on', () => {
+ it('reports when the page was seen, under Info with the rest of the save', () => {
+ // stamped by whatever filed it, so it is what the item says about itself rather
+ // than the analyst's judgement — and absent on one typed by hand
+ expect(source).toContain('{#if entity.attrs.fetched_at}');
+ expect(source).toContain('<span class="info-k">Fetched</span>');
+ expect(source).not.toContain('Never fetched');
+ });
+
+ it('opens the archived copy, so the field is not one nobody can read back', () => {
+ expect(source).toContain("{#if entity.type === 'bookmark' && entity.attrs?.archive_url}");
+ expect(source).toContain('href={entity.attrs.archive_url}');
+ expect(source).toContain('Open archived copy');
+ });
+
+ it('leaves the grade and the archived copy to the generated form', () => {
+ // both are declared fields: spelling either one here is a second editor to keep
+ // in step with the registry
+ expect(source).not.toContain('reliability');
+ expect(source).not.toContain('Source reliability');
+ });
+});
+
+describe('where the chain puts this entity', () => {
+ it('reads it from its own route, once Connections is on screen', () => {
+ // the walk reaches further than the chain's one hop, and the panel opens on
+ // Info — a click through a list of rows must not pay for it
+ expect(source).toContain("const wanted = tab === 'connections';");
+ expect(source).toContain('/placement`)');
+ expect(source).toContain('if (mySeq === placeSeq) placement = p;');
+ });
+
+ it('lists one row per point, because a case can place one file twice', () => {
+ expect(source).toContain('{#each placedPoints as point (`${point.lat},${point.lon}`)}');
+ expect(source).toContain('<h4>On the map</h4>');
+ });
+
+ it('names what placed each point rather than claiming the entity holds it', () => {
+ // the relation to the point differs per row — a video was placed there by a
+ // proof, a proof by the capture it composes — so the row says it, not the label
+ expect(source).toContain('{#if point.via}');
+ expect(source).toContain('<span>via {point.via.label}</span>');
+ expect(source).toContain('onclick={() => walkTo(point.via.id)}');
+ });
+
+ it('offers the map for a point the way a relation row does', () => {
+ expect(source).toContain('onclick={() => gotoPoint(Number(point.lat), Number(point.lon))}');
+ expect(source).toContain('title={`Show ${pointText(point)} on the map`}');
+ });
+
+ it('says when it stopped short instead of trailing off in silence', () => {
+ expect(source).toContain('{#if placement?.truncated}');
+ expect(source).toContain('More points than this panel lists');
+ });
+});
+
+describe('what the statements about this entity come to', () => {
+ it('adds up the rows the panel was already listing', () => {
+ // the claims pointing here were always on screen; answering "how many of these
+ // were destroyed" meant reading four rows and doing the arithmetic
+ expect(source).toContain('/tally`)');
+ expect(source).toContain('if (mySeq === statedSeq) stated = row;');
+ expect(source).toContain('{#if stated?.statements || stated?.refuted}');
+ });
+
+ it('reads it on the same terms as the placement beside it', () => {
+ // its own request, only once Connections is on screen, re-read after a save
+ expect(source).toMatch(/const mySeq = \+\+statedSeq;/);
+ expect(source).toContain('caseState.rev;');
+ });
+
+ it('never prints the sum without what it left out', () => {
+ expect(source).toContain('countLines(stated, claimReads)');
+ expect(source).toContain('noteLines(stated)');
+ expect(source).toContain('confidenceLine(stated, claimReads)');
+ });
+
+ it('takes its words from the served registry, not a list kept here', () => {
+ expect(source).toContain("for (const field of entityFields('claim'))");
+ });
+
+ it('sits above the statements rather than replacing them', () => {
+ expect(source).toMatch(/<\/div>\s*{\/if}\s*<ClaimReferences/);
+ });
+});
+
+describe('a file the app has no viewer for', () => {
+ it('offers its folder instead of a download', () => {
+ // the browser's answer is a copy in Downloads, worked on outside the case
+ expect(source).toContain('opensInFileManager(entity)');
+ expect(source).toContain('Show in folder');
+ expect(source).toContain('onclick={() => showInFolder(entity)}');
+ });
+
+ it('drops the tool button for it, since no tool reopens a document', () => {
+ expect(source).toContain('{#if (ENTITY_TOOL[entity.type] && !inFileManager)');
+ });
+});
+
+describe('Claim details tabs', () => {
+ it('keeps assessment fields in Time instead of duplicating them in Info', () => {
+ expect(source).toContain(
+ "exclude={entity.type === 'claim' ? ['when', 'time_role', 'confidence', 'method', 'verbatim'] : []}"
+ );
+ expect(source).toContain('<EntityTime');
+ });
+});
diff --git a/frontend/src/components/EntityImages.svelte b/frontend/src/components/EntityImages.svelte
new file mode 100644
index 0000000..1815d6b
--- /dev/null
+++ b/frontend/src/components/EntityImages.svelte
@@ -0,0 +1,482 @@
+<script>
+ /** Presentation photos for one hand-made entity.
+ *
+ * Computer imports stay private to the entity. Images chosen from the Media
+ * Library remain references to their existing media.
+ */
+ import { api } from '../lib/api.js';
+ import { fileUrl } from '../lib/fileUrl.js';
+ import { caseState, reloadCase, toast } from '../lib/state.svelte.js';
+ import Icon from './Icon.svelte';
+ import Modal from './Modal.svelte';
+ import SearchInput from './SearchInput.svelte';
+
+ let { entity } = $props();
+
+ let images = $state([]);
+ let selectedId = $state(null);
+ let loading = $state(false);
+ let loadError = $state(false);
+ let busy = $state(false);
+ let fileInput = $state();
+ let pickerOpen = $state(false);
+ let pickerLoading = $state(false);
+ let media = $state([]);
+ let picked = $state([]);
+ let query = $state('');
+ let loadSeq = 0;
+
+ const selected = $derived(
+ images.find((image) => image.id === selectedId)
+ ?? images.find((image) => image.primary)
+ ?? images[0]
+ ?? null
+ );
+ const attached = $derived(
+ new Set(images.map((image) => image.media_id).filter(Boolean))
+ );
+ const available = $derived(
+ media.filter((item) => item.kind === 'image' && item.entity_id && !attached.has(item.entity_id))
+ );
+ const matching = $derived.by(() => {
+ const term = query.trim().toLowerCase();
+ if (!term) return available;
+ return available.filter((item) =>
+ `${item.title ?? ''} ${item.filename ?? ''}`.toLowerCase().includes(term)
+ );
+ });
+
+ function adopt(next) {
+ images = Array.isArray(next) ? next : [];
+ if (!images.some((image) => image.id === selectedId)) {
+ selectedId = images.find((image) => image.primary)?.id ?? images[0]?.id ?? null;
+ }
+ }
+
+ $effect(() => {
+ const caseId = caseState.current?.id;
+ const entityId = entity?.id;
+ caseState.rev;
+ const seq = ++loadSeq;
+ if (!caseId || !entityId) {
+ adopt([]);
+ return;
+ }
+ loading = true;
+ loadError = false;
+ api.get(`/api/cases/${caseId}/entities/${entityId}/images`)
+ .then((result) => {
+ if (seq === loadSeq) adopt(result.images);
+ })
+ .catch(() => {
+ if (seq === loadSeq) loadError = true;
+ })
+ .finally(() => {
+ if (seq === loadSeq) loading = false;
+ });
+ });
+
+ async function changed(next, message) {
+ adopt(next);
+ await reloadCase();
+ toast(message, 'ok');
+ }
+
+ function addedMessage(count) {
+ if (!count) return 'No new photos added.';
+ return count === 1 ? 'Photo added.' : `${count} photos added.`;
+ }
+
+ async function upload(files) {
+ if (!files.length || busy) return;
+ busy = true;
+ let added = 0;
+ let failed = 0;
+ let next = images;
+ try {
+ for (const file of files) {
+ if (file.type && !file.type.startsWith('image/')) {
+ failed += 1;
+ toast(`${file.name} is not an image.`, 'danger');
+ continue;
+ }
+ const form = new FormData();
+ form.append('file', file);
+ try {
+ const result = await api.post(
+ `/api/cases/${caseState.current.id}/entities/${entity.id}/images/upload`,
+ form
+ );
+ added += result.added;
+ next = result.images;
+ } catch (error) {
+ failed += 1;
+ toast(`${file.name}: ${error.message}`, 'danger');
+ }
+ }
+ if (added) {
+ await changed(next, addedMessage(added));
+ } else if (!failed) {
+ toast('No photos were selected.', 'info');
+ }
+ } catch (error) {
+ toast(error.message, 'danger');
+ } finally {
+ busy = false;
+ }
+ }
+
+ async function onfiles(event) {
+ const files = [...(event.currentTarget.files ?? [])];
+ event.currentTarget.value = '';
+ await upload(files);
+ }
+
+ async function openPicker() {
+ pickerOpen = true;
+ pickerLoading = true;
+ picked = [];
+ query = '';
+ try {
+ media = await api.get(`/api/cases/${caseState.current.id}/media`);
+ } catch (error) {
+ toast(error.message, 'danger');
+ pickerOpen = false;
+ } finally {
+ pickerLoading = false;
+ }
+ }
+
+ function toggle(mediaId) {
+ picked = picked.includes(mediaId)
+ ? picked.filter((id) => id !== mediaId)
+ : [...picked, mediaId];
+ }
+
+ async function addPicked() {
+ if (!picked.length || busy) return;
+ busy = true;
+ try {
+ const result = await api.post(
+ `/api/cases/${caseState.current.id}/entities/${entity.id}/images`,
+ { media_ids: picked }
+ );
+ pickerOpen = false;
+ await changed(result.images, addedMessage(result.added));
+ } catch (error) {
+ toast(error.message, 'danger');
+ } finally {
+ busy = false;
+ }
+ }
+
+ async function makePrimary() {
+ if (!selected || selected.primary || busy) return;
+ busy = true;
+ try {
+ const result = await api.put(
+ `/api/cases/${caseState.current.id}/entities/${entity.id}/images/${selected.id}/primary`
+ );
+ await changed(result.images, 'Primary photo updated.');
+ } catch (error) {
+ toast(error.message, 'danger');
+ } finally {
+ busy = false;
+ }
+ }
+
+ async function removeSelected() {
+ if (!selected || busy) return;
+ busy = true;
+ try {
+ const result = await api.del(
+ `/api/cases/${caseState.current.id}/entities/${entity.id}/images/${selected.id}`
+ );
+ await changed(result.images, 'Photo removed from this entity.');
+ } catch (error) {
+ toast(error.message, 'danger');
+ } finally {
+ busy = false;
+ }
+ }
+</script>
+
+<section class="gallery" aria-label="Photos">
+ <div class="gallery-head">
+ <span class="gallery-title">Photos</span>
+ <div class="gallery-actions">
+ <button class="btn btn-ghost btn-sm" onclick={() => fileInput?.click()} disabled={busy}>
+ <Icon name="upload" size={13} /> Add from computer
+ </button>
+ <button class="btn btn-ghost btn-sm" onclick={openPicker} disabled={busy}>
+ <Icon name="image" size={13} /> Choose from media
+ </button>
+ </div>
+ <input
+ class="file-input"
+ bind:this={fileInput}
+ type="file"
+ accept="image/*"
+ multiple
+ onchange={onfiles}
+ />
+ </div>
+
+ {#if loading}
+ <div class="empty">Loading photos…</div>
+ {:else if loadError}
+ <div class="empty">Photos could not be loaded.</div>
+ {:else if selected}
+ <div class="main-photo">
+ <img
+ src={fileUrl(caseState.current.id, selected.thumbnail ?? selected.path)}
+ alt={entity.label}
+ />
+ </div>
+ <div class="photo-controls">
+ {#if selected.primary}
+ <span class="primary"><Icon name="check" size={12} /> Primary</span>
+ {:else}
+ <button class="btn btn-ghost btn-sm" onclick={makePrimary} disabled={busy}>
+ Set as primary
+ </button>
+ {/if}
+ <button
+ class="btn btn-ghost btn-sm remove"
+ title="Remove from this entity"
+ onclick={removeSelected}
+ disabled={busy}
+ >Remove</button>
+ </div>
+ {#if images.length > 1}
+ <div class="thumbs" aria-label="Attached photos">
+ {#each images as image (image.id)}
+ <button
+ class="thumb"
+ class:selected={image.id === selected.id}
+ aria-label={`Show ${image.title ?? image.filename ?? 'photo'}`}
+ aria-pressed={image.id === selected.id}
+ onclick={() => (selectedId = image.id)}
+ >
+ <img
+ src={fileUrl(caseState.current.id, image.thumbnail ?? image.path)}
+ alt=""
+ loading="lazy"
+ />
+ {#if image.primary}<span class="primary-dot" title="Primary photo"></span>{/if}
+ </button>
+ {/each}
+ </div>
+ {/if}
+ {/if}
+</section>
+
+{#if pickerOpen}
+ <Modal title="Choose photos" width="620px" onclose={() => (pickerOpen = false)}>
+ <div class="picker-head">
+ <SearchInput bind:value={query} placeholder="Search photos…" count={matching.length} width="220px" />
+ </div>
+ {#if pickerLoading}
+ <div class="picker-empty">Loading photos…</div>
+ {:else if !matching.length}
+ <div class="picker-empty">{query ? 'No matching images.' : 'No images available.'}</div>
+ {:else}
+ <div class="picker-grid">
+ {#each matching as item (item.entity_id)}
+ <button
+ class="picker-item"
+ class:picked={picked.includes(item.entity_id)}
+ aria-pressed={picked.includes(item.entity_id)}
+ onclick={() => toggle(item.entity_id)}
+ >
+ <img src={fileUrl(caseState.current.id, item.thumbnail ?? item.path)} alt="" loading="lazy" />
+ <span>{item.title ?? item.filename}</span>
+ {#if picked.includes(item.entity_id)}
+ <span class="picked-mark"><Icon name="check" size={12} /></span>
+ {/if}
+ </button>
+ {/each}
+ </div>
+ {/if}
+ <div class="picker-actions">
+ <button class="btn btn-ghost" onclick={() => (pickerOpen = false)}>Cancel</button>
+ <button class="btn btn-primary" onclick={addPicked} disabled={!picked.length || busy}>
+ Add selected
+ </button>
+ </div>
+ </Modal>
+{/if}
+
+<style>
+ .gallery {
+ margin-bottom: 14px;
+ }
+ .gallery-head,
+ .photo-controls,
+ .picker-head,
+ .picker-actions {
+ display: flex;
+ align-items: center;
+ }
+ .gallery-head {
+ justify-content: space-between;
+ gap: 8px;
+ margin-bottom: 8px;
+ }
+ .gallery-title {
+ font-size: var(--fs-xs);
+ font-weight: 600;
+ color: var(--text-2);
+ }
+ .gallery-actions {
+ display: flex;
+ gap: 2px;
+ }
+ .gallery-actions .btn {
+ gap: 5px;
+ white-space: nowrap;
+ }
+ .file-input {
+ display: none;
+ }
+ .main-photo {
+ height: 220px;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ overflow: hidden;
+ border: 1px solid var(--border);
+ border-radius: var(--r);
+ background: var(--bg-2);
+ }
+ .main-photo img {
+ width: 100%;
+ height: 100%;
+ object-fit: contain;
+ }
+ .empty {
+ min-height: 74px;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ gap: 8px;
+ border: 1px dashed var(--border);
+ border-radius: var(--r);
+ color: var(--text-3);
+ font-size: var(--fs-xs);
+ }
+ .photo-controls {
+ min-height: 32px;
+ justify-content: flex-end;
+ gap: 4px;
+ }
+ .primary {
+ display: inline-flex;
+ align-items: center;
+ gap: 4px;
+ margin-right: auto;
+ color: var(--text-3);
+ font-size: var(--fs-xs);
+ }
+ .remove:hover {
+ color: var(--danger);
+ }
+ .thumbs {
+ display: flex;
+ gap: 6px;
+ overflow-x: auto;
+ padding: 2px 0;
+ }
+ .thumb {
+ position: relative;
+ flex: 0 0 52px;
+ height: 42px;
+ padding: 0;
+ overflow: hidden;
+ border: 1px solid var(--border);
+ border-radius: var(--r-sm);
+ background: var(--bg-2);
+ }
+ .thumb.selected {
+ border-color: var(--accent);
+ box-shadow: 0 0 0 1px var(--accent);
+ }
+ .thumb img {
+ width: 100%;
+ height: 100%;
+ object-fit: cover;
+ }
+ .primary-dot {
+ position: absolute;
+ right: 3px;
+ bottom: 3px;
+ width: 7px;
+ height: 7px;
+ border: 1px solid var(--bg-1);
+ border-radius: 50%;
+ background: var(--accent);
+ }
+ .picker-head {
+ justify-content: flex-end;
+ margin-bottom: 10px;
+ }
+ .picker-grid {
+ display: grid;
+ grid-template-columns: repeat(auto-fill, minmax(120px, 1fr));
+ gap: 8px;
+ max-height: 360px;
+ overflow: auto;
+ }
+ .picker-item {
+ position: relative;
+ min-width: 0;
+ padding: 5px;
+ border: 1px solid var(--border);
+ border-radius: var(--r-sm);
+ background: var(--bg-2);
+ color: var(--text-2);
+ text-align: left;
+ }
+ .picker-item.picked {
+ border-color: var(--accent);
+ }
+ .picker-item img {
+ width: 100%;
+ height: 82px;
+ display: block;
+ margin-bottom: 5px;
+ border-radius: 3px;
+ object-fit: cover;
+ }
+ .picker-item > span:not(.picked-mark) {
+ display: block;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ font-size: var(--fs-xs);
+ }
+ .picked-mark {
+ position: absolute;
+ top: 9px;
+ right: 9px;
+ display: grid;
+ place-items: center;
+ width: 20px;
+ height: 20px;
+ border-radius: 50%;
+ background: var(--accent);
+ color: white;
+ }
+ .picker-empty {
+ min-height: 150px;
+ display: grid;
+ place-items: center;
+ color: var(--text-3);
+ font-size: var(--fs-sm);
+ }
+ .picker-actions {
+ justify-content: flex-end;
+ gap: 8px;
+ margin-top: 14px;
+ }
+</style>
diff --git a/frontend/src/components/EntityImages.test.js b/frontend/src/components/EntityImages.test.js
new file mode 100644
index 0000000..fffe350
--- /dev/null
+++ b/frontend/src/components/EntityImages.test.js
@@ -0,0 +1,39 @@
+import { describe, expect, it } from 'vitest';
+import { readFileSync } from 'node:fs';
+
+const source = readFileSync(new URL('./EntityImages.svelte', import.meta.url), 'utf8');
+
+describe('entity photo gallery', () => {
+ it('supports multiple direct imports from the computer', () => {
+ expect(source).toContain('accept="image/*"');
+ expect(source).toContain('multiple');
+ expect(source).toContain('Add from computer');
+ expect(source).toContain('/entities/${entity.id}/images/upload`');
+ expect(source).not.toContain('/media/upload`');
+ });
+
+ it('also attaches multiple existing Media Library images', () => {
+ expect(source).toContain('Choose from media');
+ expect(source).toContain("item.kind === 'image' && item.entity_id");
+ expect(source).toContain(': [...picked, mediaId];');
+ expect(source).toContain('{ media_ids: picked }');
+ });
+
+ it('chooses one primary photo and propagates the change', () => {
+ expect(source).toContain('/primary`');
+ expect(source).toContain('Set as primary');
+ expect(source).toContain("await reloadCase();");
+ });
+
+ it('detaches without deleting the underlying media', () => {
+ expect(source).toContain('title="Remove from this entity"');
+ expect(source).toContain('/entities/${entity.id}/images/${selected.id}`');
+ expect(source).not.toContain('/media?path=');
+ });
+
+ it('shows no empty frame and keeps an added main image bounded', () => {
+ expect(source).not.toContain('No photos yet.');
+ expect(source).toContain('height: 220px;');
+ expect(source).toContain('object-fit: contain;');
+ });
+});
diff --git a/frontend/src/components/EntityPhotoDraft.svelte b/frontend/src/components/EntityPhotoDraft.svelte
new file mode 100644
index 0000000..3a1d5d2
--- /dev/null
+++ b/frontend/src/components/EntityPhotoDraft.svelte
@@ -0,0 +1,350 @@
+<script>
+ /** Photos staged before their entity exists. */
+ import { onDestroy } from 'svelte';
+ import { api } from '../lib/api.js';
+ import { fileUrl } from '../lib/fileUrl.js';
+ import { caseState, toast } from '../lib/state.svelte.js';
+ import Icon from './Icon.svelte';
+ import Modal from './Modal.svelte';
+ import SearchInput from './SearchInput.svelte';
+
+ let {
+ photos = $bindable([]),
+ primaryId = $bindable(null),
+ disabled = false,
+ } = $props();
+
+ let fileInput = $state();
+ let pickerOpen = $state(false);
+ let pickerLoading = $state(false);
+ let media = $state([]);
+ let picked = $state([]);
+ let query = $state('');
+ let sequence = 0;
+ const localUrls = new Set();
+
+ const attached = $derived(
+ new Set(photos.filter((photo) => photo.source === 'media').map((photo) => photo.mediaId))
+ );
+ const available = $derived(
+ media.filter((item) => item.kind === 'image' && item.entity_id && !attached.has(item.entity_id))
+ );
+ const matching = $derived.by(() => {
+ const term = query.trim().toLowerCase();
+ if (!term) return available;
+ return available.filter((item) =>
+ `${item.title ?? ''} ${item.filename ?? ''}`.toLowerCase().includes(term)
+ );
+ });
+
+ function addFiles(files) {
+ const added = [];
+ for (const file of files) {
+ if (file.type && !file.type.startsWith('image/')) {
+ toast(`${file.name} is not an image.`, 'danger');
+ continue;
+ }
+ const preview = URL.createObjectURL(file);
+ localUrls.add(preview);
+ added.push({
+ draftId: `computer-${++sequence}`,
+ source: 'computer',
+ file,
+ preview,
+ title: file.name.replace(/\.[^.]+$/, '') || 'Photo',
+ });
+ }
+ if (!added.length) return;
+ photos = [...photos, ...added];
+ primaryId ??= added[0].draftId;
+ }
+
+ function onfiles(event) {
+ addFiles([...(event.currentTarget.files ?? [])]);
+ event.currentTarget.value = '';
+ }
+
+ async function openPicker() {
+ pickerOpen = true;
+ pickerLoading = true;
+ picked = [];
+ query = '';
+ try {
+ media = await api.get(`/api/cases/${caseState.current.id}/media`);
+ } catch (error) {
+ toast(error.message, 'danger');
+ pickerOpen = false;
+ } finally {
+ pickerLoading = false;
+ }
+ }
+
+ function toggle(mediaId) {
+ picked = picked.includes(mediaId)
+ ? picked.filter((id) => id !== mediaId)
+ : [...picked, mediaId];
+ }
+
+ function addPicked() {
+ const selected = media
+ .filter((item) => picked.includes(item.entity_id) && !attached.has(item.entity_id))
+ .map((item) => ({
+ draftId: `media-${item.entity_id}`,
+ source: 'media',
+ mediaId: item.entity_id,
+ preview: fileUrl(caseState.current.id, item.thumbnail ?? item.path),
+ title: item.title ?? item.filename ?? 'Photo',
+ }));
+ if (selected.length) {
+ photos = [...photos, ...selected];
+ primaryId ??= selected[0].draftId;
+ }
+ pickerOpen = false;
+ }
+
+ function remove(photo) {
+ if (photo.source === 'computer') {
+ URL.revokeObjectURL(photo.preview);
+ localUrls.delete(photo.preview);
+ }
+ photos = photos.filter((item) => item.draftId !== photo.draftId);
+ if (primaryId === photo.draftId) primaryId = photos[0]?.draftId ?? null;
+ }
+
+ onDestroy(() => {
+ for (const url of localUrls) URL.revokeObjectURL(url);
+ });
+</script>
+
+<section class="photo-draft" aria-label="Photos">
+ <div class="photo-head">
+ <span class="modal-label">Photos</span>
+ <div class="photo-actions">
+ <button class="btn btn-ghost btn-sm" onclick={() => fileInput?.click()} {disabled}>
+ <Icon name="upload" size={13} /> Add from computer
+ </button>
+ <button class="btn btn-ghost btn-sm" onclick={openPicker} {disabled}>
+ <Icon name="image" size={13} /> Choose from media
+ </button>
+ </div>
+ <input
+ class="file-input"
+ bind:this={fileInput}
+ type="file"
+ accept="image/*"
+ multiple
+ onchange={onfiles}
+ />
+ </div>
+
+ {#if photos.length}
+ <div class="photos" aria-label="Photos to add">
+ {#each photos as photo (photo.draftId)}
+ <div class="photo">
+ <button
+ class="preview"
+ class:primary={photo.draftId === primaryId}
+ aria-label={`Use ${photo.title} as primary photo`}
+ aria-pressed={photo.draftId === primaryId}
+ onclick={() => (primaryId = photo.draftId)}
+ disabled={disabled}
+ >
+ <img src={photo.preview} alt="" />
+ {#if photo.draftId === primaryId}
+ <span class="primary-mark" title="Primary photo"><Icon name="check" size={11} /></span>
+ {/if}
+ </button>
+ <button
+ class="remove"
+ aria-label={`Remove ${photo.title}`}
+ title="Remove photo"
+ onclick={() => remove(photo)}
+ disabled={disabled}
+ ><Icon name="x" size={11} /></button>
+ </div>
+ {/each}
+ </div>
+ {/if}
+</section>
+
+{#if pickerOpen}
+ <Modal title="Choose photos" width="620px" onclose={() => (pickerOpen = false)}>
+ <div class="picker-head">
+ <SearchInput bind:value={query} placeholder="Search photos…" count={matching.length} width="220px" />
+ </div>
+ {#if pickerLoading}
+ <div class="picker-empty">Loading photos…</div>
+ {:else if !matching.length}
+ <div class="picker-empty">{query ? 'No matching images.' : 'No images available.'}</div>
+ {:else}
+ <div class="picker-grid">
+ {#each matching as item (item.entity_id)}
+ <button
+ class="picker-item"
+ class:picked={picked.includes(item.entity_id)}
+ aria-pressed={picked.includes(item.entity_id)}
+ onclick={() => toggle(item.entity_id)}
+ >
+ <img src={fileUrl(caseState.current.id, item.thumbnail ?? item.path)} alt="" loading="lazy" />
+ <span>{item.title ?? item.filename}</span>
+ {#if picked.includes(item.entity_id)}
+ <span class="picked-mark"><Icon name="check" size={12} /></span>
+ {/if}
+ </button>
+ {/each}
+ </div>
+ {/if}
+ <div class="picker-actions">
+ <button class="btn btn-ghost" onclick={() => (pickerOpen = false)}>Cancel</button>
+ <button class="btn btn-primary" onclick={addPicked} disabled={!picked.length}>Add selected</button>
+ </div>
+ </Modal>
+{/if}
+
+<style>
+ .photo-draft {
+ margin-top: 12px;
+ }
+ .photo-head,
+ .photo-actions,
+ .picker-head,
+ .picker-actions {
+ display: flex;
+ align-items: center;
+ }
+ .photo-head {
+ justify-content: space-between;
+ gap: 8px;
+ }
+ .photo-head .modal-label {
+ margin: 0;
+ }
+ .photo-actions {
+ gap: 2px;
+ }
+ .photo-actions .btn {
+ gap: 5px;
+ white-space: nowrap;
+ }
+ .file-input {
+ display: none;
+ }
+ .photos {
+ display: flex;
+ gap: 8px;
+ overflow-x: auto;
+ padding: 8px 2px 2px;
+ }
+ .photo {
+ position: relative;
+ flex: 0 0 74px;
+ }
+ .preview {
+ position: relative;
+ width: 74px;
+ height: 56px;
+ padding: 0;
+ overflow: hidden;
+ border: 1px solid var(--border);
+ border-radius: var(--r-sm);
+ background: var(--bg-1);
+ }
+ .preview.primary {
+ border-color: var(--accent);
+ box-shadow: 0 0 0 1px var(--accent);
+ }
+ .preview img {
+ width: 100%;
+ height: 100%;
+ object-fit: cover;
+ }
+ .primary-mark,
+ .picked-mark {
+ position: absolute;
+ display: grid;
+ place-items: center;
+ border-radius: 50%;
+ background: var(--accent);
+ color: white;
+ }
+ .primary-mark {
+ left: 4px;
+ bottom: 4px;
+ width: 18px;
+ height: 18px;
+ }
+ .remove {
+ position: absolute;
+ top: -5px;
+ right: -5px;
+ display: grid;
+ place-items: center;
+ width: 20px;
+ height: 20px;
+ padding: 0;
+ border: 1px solid var(--border);
+ border-radius: 50%;
+ background: var(--bg-1);
+ color: var(--text-2);
+ }
+ .remove:hover {
+ color: var(--danger);
+ }
+ .picker-head {
+ justify-content: flex-end;
+ margin-bottom: 10px;
+ }
+ .picker-grid {
+ display: grid;
+ grid-template-columns: repeat(auto-fill, minmax(120px, 1fr));
+ gap: 8px;
+ max-height: 360px;
+ overflow: auto;
+ }
+ .picker-item {
+ position: relative;
+ min-width: 0;
+ padding: 5px;
+ border: 1px solid var(--border);
+ border-radius: var(--r-sm);
+ background: var(--bg-2);
+ color: var(--text-2);
+ text-align: left;
+ }
+ .picker-item.picked {
+ border-color: var(--accent);
+ }
+ .picker-item img {
+ width: 100%;
+ height: 82px;
+ display: block;
+ margin-bottom: 5px;
+ border-radius: 3px;
+ object-fit: cover;
+ }
+ .picker-item > span:not(.picked-mark) {
+ display: block;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ font-size: var(--fs-xs);
+ }
+ .picked-mark {
+ top: 9px;
+ right: 9px;
+ width: 20px;
+ height: 20px;
+ }
+ .picker-empty {
+ min-height: 150px;
+ display: grid;
+ place-items: center;
+ color: var(--text-3);
+ font-size: var(--fs-sm);
+ }
+ .picker-actions {
+ justify-content: flex-end;
+ gap: 8px;
+ margin-top: 14px;
+ }
+</style>
diff --git a/frontend/src/components/EntityPhotoDraft.test.js b/frontend/src/components/EntityPhotoDraft.test.js
new file mode 100644
index 0000000..f20e1f0
--- /dev/null
+++ b/frontend/src/components/EntityPhotoDraft.test.js
@@ -0,0 +1,30 @@
+import { describe, expect, it } from 'vitest';
+import { readFileSync } from 'node:fs';
+
+const source = readFileSync(new URL('./EntityPhotoDraft.svelte', import.meta.url), 'utf8');
+
+describe('photos staged during entity creation', () => {
+ it('accepts several computer images without using the Media upload route', () => {
+ expect(source).toContain('accept="image/*"');
+ expect(source).toContain('multiple');
+ expect(source).toContain('URL.createObjectURL(file)');
+ expect(source).not.toContain('/media/upload');
+ });
+
+ it('also stages existing Media Library images', () => {
+ expect(source).toContain('Choose from media');
+ expect(source).toContain("item.kind === 'image' && item.entity_id");
+ expect(source).toContain("source: 'media'");
+ });
+
+ it('lets one staged image become primary and removes images before creation', () => {
+ expect(source).toContain('Use ${photo.title} as primary photo');
+ expect(source).toContain('primaryId = photo.draftId');
+ expect(source).toContain('Remove ${photo.title}');
+ });
+
+ it('shows no empty frame and releases local previews', () => {
+ expect(source).not.toContain('No photos yet');
+ expect(source).toContain('URL.revokeObjectURL');
+ });
+});
diff --git a/frontend/src/components/EntityTime.svelte b/frontend/src/components/EntityTime.svelte
new file mode 100644
index 0000000..b246564
--- /dev/null
+++ b/frontend/src/components/EntityTime.svelte
@@ -0,0 +1,250 @@
+<script>
+ /** Entity-scoped temporal history. Mounted only while the Time tab is open. */
+ import { api } from '../lib/api.js';
+ import { formatTemporalValue } from '../lib/timeline.js';
+ import { reloadCase, toast, uiState } from '../lib/state.svelte.js';
+ import Icon from './Icon.svelte';
+ import TemporalClaimEditor from './TemporalClaimEditor.svelte';
+
+ let { caseId, entity, onclose } = $props();
+
+ let items = $state([]);
+ let cursor = $state(null);
+ let loading = $state(true);
+ let editor = $state(null); // null, 'new', or a statement item
+ let seq = 0;
+
+ const dated = $derived(items.filter((item) => item.earliest));
+ const unplaced = $derived(items.filter((item) => !item.earliest && item.raw));
+ const undated = $derived(items.filter((item) => !item.earliest && !item.raw));
+ const ownStatement = $derived(
+ entity.type === 'claim'
+ ? items.find((item) => item.category === 'statement' && item.owner_id === entity.id) ?? null
+ : null
+ );
+ const statements = $derived(
+ dated.filter((item) => item.category === 'statement' && item.owner_id !== ownStatement?.owner_id)
+ );
+ const about = $derived(statements.filter((item) => item.subjects.includes(entity.id)));
+ const placed = $derived(statements.filter((item) => item.places.includes(entity.id) && !about.includes(item)));
+ const evidence = $derived(statements.filter((item) => item.sources.includes(entity.id) && !about.includes(item) && !placed.includes(item)));
+ const media = $derived(dated.filter((item) => item.category === 'media'));
+ const activity = $derived(dated.filter((item) => item.category === 'case_activity'));
+ const visibleUnplaced = $derived(unplaced.filter((item) => item.id !== ownStatement?.id));
+ const visibleUndated = $derived(undated.filter((item) => item.id !== ownStatement?.id));
+ const visibleCount = $derived(
+ about.length + placed.length + evidence.length + media.length + activity.length
+ + visibleUnplaced.length + visibleUndated.length + (ownStatement?.raw ? 1 : 0)
+ );
+ const assessmentLabel = $derived(
+ entity.type === 'claim'
+ ? ownStatement?.raw ? 'Edit statement date' : 'Set statement date'
+ : entity.type === 'media' ? 'Add capture assessment' : 'Add time assessment'
+ );
+
+ async function load({ more = false } = {}) {
+ if (!caseId) return;
+ const mine = ++seq;
+ loading = true;
+ try {
+ const params = new URLSearchParams({ entity: entity.id, include_undated: 'true', limit: '100' });
+ for (const category of ['statement', 'media', 'case_activity']) params.append('category', category);
+ if (more && cursor) params.set('cursor', cursor);
+ const page = await api.get(`/api/cases/${caseId}/timeline?${params}`);
+ if (mine !== seq) return;
+ items = more ? [...items, ...(page.items ?? [])] : page.items ?? [];
+ cursor = page.next_cursor ?? null;
+ } catch (error) {
+ if (mine === seq) toast(error.message, 'danger');
+ } finally {
+ if (mine === seq) loading = false;
+ }
+ }
+
+ $effect(() => {
+ entity.id;
+ items = [];
+ cursor = null;
+ void load();
+ });
+
+ function newAssessment() {
+ editor = entity.type === 'claim'
+ ? ownStatement ?? {
+ id: `temporal:claim:${entity.id}`,
+ owner_id: entity.id,
+ category: 'statement',
+ kind: 'claim',
+ label: entity.label,
+ raw: entity.attrs?.when ?? null,
+ }
+ : 'new';
+ }
+
+ async function saved() {
+ editor = null;
+ await reloadCase();
+ await load();
+ }
+
+ function openTimeline(item = null) {
+ uiState.timelineFocus = { entityId: entity.id, entityLabel: entity.label, itemId: item?.id ?? null };
+ uiState.tool = 'timeline';
+ onclose?.();
+ }
+
+ function kindLabel(item) {
+ return {
+ captured: 'Captured', published: 'Published', imagery: 'Imagery',
+ collected: 'Collected', added: 'Added to case', filed: 'Filed in case', claim: 'Assessment',
+ }[item.kind] ?? item.kind;
+ }
+
+ function timeLabel(item) {
+ return formatTemporalValue(item.raw ?? '').label;
+ }
+</script>
+
+{#snippet row(item, editable = false)}
+ <div class="time-row">
+ <button class="time-row-main" aria-label={`Open ${item.label} in Timeline`} onclick={() => openTimeline(item)}>
+ <span class={`time-mark ${item.category}`}></span>
+ <span class="time-copy">
+ <strong>{item.label}</strong>
+ <small>{kindLabel(item)}{#if item.time_role} · {item.time_role}{/if}{#if item.confidence} · {item.confidence}{/if}</small>
+ </span>
+ <span class="time-value" class:undated={!item.raw} title={item.raw || undefined}>{timeLabel(item)}</span>
+ </button>
+ {#if editable}
+ <button class="time-row-action" aria-label={`Edit ${item.label}`} title="Edit assessment" onclick={() => (editor = item)}><Icon name="edit" size={12} /></button>
+ {/if}
+ </div>
+{/snippet}
+
+<div class="entity-time">
+ <div class="time-actions">
+ <button class="btn btn-primary btn-sm" onclick={newAssessment}><Icon name="plus" size={12} />{assessmentLabel}</button>
+ <button class="btn btn-ghost btn-sm" onclick={() => openTimeline()}><Icon name="clock" size={12} />Open in Timeline</button>
+ </div>
+ {#if entity.type === 'claim'}
+ <p class="claim-time-rule">A statement has one date or range. Use another statement for a separate assessment.</p>
+ {/if}
+
+ {#if editor}
+ <section
+ class="time-editor"
+ aria-label={entity.type === 'claim' ? assessmentLabel : editor === 'new' ? assessmentLabel : 'Edit time assessment'}
+ >
+ <header>
+ <h3>{entity.type === 'claim' ? assessmentLabel : editor === 'new' ? assessmentLabel : 'Edit time assessment'}</h3>
+ <button class="btn btn-ghost btn-sm" aria-label="Close editor" onclick={() => (editor = null)}>
+ <Icon name="x" size={13} />
+ </button>
+ </header>
+ <!-- Keyed on what is being edited: the editor seeds itself once, so
+ reusing the instance would open a new assessment already holding the
+ statement, date and connectors of the one edited before it. -->
+ {#key editor}
+ <TemporalClaimEditor
+ {caseId}
+ item={editor === 'new' ? null : editor}
+ subject={editor === 'new' ? entity : null}
+ initialStatement={entity.type === 'media' ? 'This media was captured' : ''}
+ initialRole={entity.type === 'media' ? 'observed' : ''}
+ onsaved={saved}
+ oncancel={() => (editor = null)}
+ />
+ {/key}
+ </section>
+ {/if}
+
+ {#if loading && !items.length}
+ <div class="time-empty">Loading time history…</div>
+ {:else}
+ {#if ownStatement?.raw}
+ <section><h3>Statement date <span>1</span></h3>{@render row(ownStatement, true)}</section>
+ {:else if entity.type === 'claim'}
+ <div class="time-empty compact"><Icon name="clock" size={18} /><p>This statement has no date yet.</p></div>
+ {/if}
+ {#if about.length}
+ <section><h3>Statements about this <span>{about.length}</span></h3>{#each about as item (item.id)}{@render row(item, true)}{/each}</section>
+ {/if}
+ {#if placed.length}
+ <section><h3>Statements placed here <span>{placed.length}</span></h3>{#each placed as item (item.id)}{@render row(item, true)}{/each}</section>
+ {/if}
+ {#if evidence.length}
+ <section>
+ <h3>Evidence for <span>{evidence.length}</span></h3>
+ <p class="section-note">These dates belong to statements this item supports.</p>
+ {#each evidence as item (item.id)}{@render row(item, true)}{/each}
+ </section>
+ {/if}
+ {#if media.length}
+ <section><h3>Media dates <span>{media.length}</span></h3>{#each media as item (item.id)}{@render row(item)}{/each}</section>
+ {/if}
+ {#if activity.length}
+ <details class="activity"><summary>Case activity <span>{activity.length}</span></summary>{#each activity as item (item.id)}{@render row(item)}{/each}</details>
+ {/if}
+ {#if visibleUnplaced.length}
+ <section class="unplaced"><h3>Not on UTC axis <span>{visibleUnplaced.length}</span></h3><p class="section-note">Add a timezone or correct the value.</p>{#each visibleUnplaced as item (item.id)}{@render row(item, item.category === 'statement')}{/each}</section>
+ {/if}
+ {#if visibleUndated.length}
+ <section class="undated"><h3>Undated <span>{visibleUndated.length}</span></h3>{#each visibleUndated as item (item.id)}{@render row(item, item.category === 'statement')}{/each}</section>
+ {/if}
+ {#if !visibleCount && entity.type !== 'claim'}
+ <div class="time-empty"><Icon name="clock" size={18} /><p>No dates or time assessments yet.</p></div>
+ {/if}
+ {#if cursor}<button class="btn btn-ghost btn-sm more" disabled={loading} onclick={() => load({ more: true })}>{loading ? 'Loading…' : 'Show more'}</button>{/if}
+ {/if}
+</div>
+
+<style>
+ .entity-time { display: grid; gap: 14px; padding-top: 2px; }
+ .time-actions { display: flex; flex-wrap: wrap; gap: 6px; }
+ .claim-time-rule { margin: -7px 0 0; color: var(--text-3); font-size: var(--fs-xs); line-height: 1.4; }
+ section { display: grid; gap: 5px; }
+ h3 { display: flex; justify-content: space-between; gap: 8px; margin: 0 0 2px; font-size: var(--fs-sm); color: var(--text-2); }
+ h3 span { color: var(--text-3); font-size: var(--fs-xs); font-weight: 400; }
+ .section-note { margin: -1px 0 3px; color: var(--text-3); font-size: var(--fs-xs); }
+ .time-row {
+ width: 100%; display: grid; grid-template-columns: minmax(0, 1fr) auto;
+ align-items: stretch; border: 1px solid var(--border); border-radius: var(--r-sm);
+ background: var(--bg-2); color: var(--text-2); overflow: hidden;
+ }
+ .time-row:hover { border-color: var(--border-strong); background: var(--bg-3); }
+ .time-row-main {
+ min-width: 0; display: grid; grid-template-columns: auto minmax(0, 1fr) auto;
+ align-items: center; gap: 8px; padding: 8px 7px 8px 9px; border: 0;
+ background: none; color: inherit; text-align: left; cursor: pointer;
+ }
+ .time-row-action {
+ width: 34px; display: grid; place-items: center; border: 0; border-left: 1px solid var(--border);
+ background: none; color: var(--text-3); cursor: pointer;
+ }
+ .time-row-action:hover { background: color-mix(in srgb, var(--accent) 9%, transparent); color: var(--accent); }
+ .time-mark { width: 8px; height: 8px; border-radius: 50%; background: var(--timeline-media); box-shadow: 0 0 0 3px color-mix(in srgb, var(--timeline-media) 14%, transparent); }
+ .time-mark.statement { background: var(--timeline-statement); box-shadow: 0 0 0 3px color-mix(in srgb, var(--timeline-statement) 14%, transparent); }
+ .time-mark.media { border-radius: 2px; }
+ .time-mark.case_activity { background: var(--timeline-activity); box-shadow: 0 0 0 3px color-mix(in srgb, var(--timeline-activity) 14%, transparent); }
+ .time-copy { display: grid; min-width: 0; }
+ .time-copy strong { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; font-size: var(--fs-sm); }
+ .time-copy small { color: var(--text-3); text-transform: capitalize; }
+ .time-value { max-width: 210px; overflow: hidden; color: var(--text-2); font-size: var(--fs-xs); text-overflow: ellipsis; white-space: nowrap; }
+ .time-value.undated { color: var(--warn); }
+ .time-editor { padding: 10px; border: 1px solid var(--border-strong); border-radius: var(--r-md); background: var(--bg-1); }
+ .time-editor > header { display: flex; align-items: center; justify-content: space-between; margin-bottom: 7px; }
+ .time-editor > header h3 { margin: 0; color: var(--text-1); }
+ .activity { border-top: 1px solid var(--border); padding-top: 9px; }
+ .activity summary { cursor: pointer; color: var(--text-3); font-weight: 600; }
+ .activity summary span { margin-left: 4px; font-weight: 400; }
+ .activity[open] { display: grid; gap: 5px; }
+ .unplaced, .undated { padding-top: 9px; border-top: 1px solid var(--border); }
+ .time-empty { display: grid; justify-items: center; gap: 5px; padding: 20px 10px; color: var(--text-3); text-align: center; }
+ .time-empty p { margin: 0; }
+ .time-empty.compact { padding: 13px 10px; border: 1px dashed var(--border); border-radius: var(--r-sm); }
+ .more { justify-self: center; }
+ @media (max-width: 520px) {
+ .time-row-main { grid-template-columns: auto minmax(0, 1fr); }
+ .time-value { grid-column: 2; }
+ }
+</style>
diff --git a/frontend/src/components/EntityTime.test.js b/frontend/src/components/EntityTime.test.js
new file mode 100644
index 0000000..0daa017
--- /dev/null
+++ b/frontend/src/components/EntityTime.test.js
@@ -0,0 +1,54 @@
+import { describe, expect, it } from 'vitest';
+import { readFileSync } from 'node:fs';
+
+const source = readFileSync(new URL('./EntityTime.svelte', import.meta.url), 'utf8');
+
+describe('entity Time tab', () => {
+ it('uses the shared bounded projection and keeps all three authorities separate', () => {
+ expect(source).toContain("for (const category of ['statement', 'media', 'case_activity'])");
+ expect(source).toContain("item.category === 'statement'");
+ expect(source).toContain("item.category === 'media'");
+ expect(source).toContain("item.category === 'case_activity'");
+ expect(source).toContain('Case activity');
+ });
+
+ it('does not attribute a cited statement date to its evidence', () => {
+ expect(source).toContain("item.sources.includes(entity.id)");
+ expect(source).toContain('Evidence for <span>{evidence.length}</span>');
+ expect(source).toContain('These dates belong to statements this item supports.');
+ });
+
+ it('prefills a media capture assessment without changing file metadata', () => {
+ expect(source).toContain("entity.type === 'media' ? 'Add capture assessment'");
+ expect(source).toContain("initialStatement={entity.type === 'media' ? 'This media was captured' : ''}");
+ expect(source).toContain("initialRole={entity.type === 'media' ? 'observed' : ''}");
+ });
+
+ it('hands the visible entity scope to the global Timeline', () => {
+ expect(source).toContain('uiState.timelineFocus = { entityId: entity.id, entityLabel: entity.label');
+ expect(source).toContain("uiState.tool = 'timeline'");
+ });
+
+ it('opens an existing assessment in an explicit inline editor', () => {
+ expect(source).toContain('aria-label={`Edit ${item.label}`}');
+ expect(source).toContain('class="time-editor"');
+ expect(source).toContain("'Edit time assessment'");
+ expect(source).not.toContain('<Modal');
+ });
+
+ it('uses the Timeline visual language and separates unresolved dates', () => {
+ expect(source).toContain('formatTemporalValue(item.raw ?? \'\').label');
+ expect(source).toContain('var(--timeline-statement)');
+ expect(source).toContain('Not on UTC axis');
+ expect(source).toContain('Undated <span>{visibleUndated.length}</span>');
+ expect(source).not.toContain('title="Approximate">~');
+ });
+
+ it('edits the Claim date instead of creating an impossible nested assessment', () => {
+ expect(source).toContain("ownStatement?.raw ? 'Edit statement date' : 'Set statement date'");
+ expect(source).toContain("editor = entity.type === 'claim'");
+ expect(source).toContain('This statement has no date yet.');
+ expect(source).toContain('A statement has one date or range. Use another statement for a separate assessment.');
+ expect(source).toContain('visibleUndated = $derived(undated.filter');
+ });
+});
diff --git a/frontend/src/components/FilterBar.svelte b/frontend/src/components/FilterBar.svelte
new file mode 100644
index 0000000..5401e9d
--- /dev/null
+++ b/frontend/src/components/FilterBar.svelte
@@ -0,0 +1,818 @@
+<script>
+ /**
+ * The question the Board is asking, as a bar that never changes shape.
+ *
+ * What it replaces: seven selects in a row, four of which appeared and disappeared
+ * as the others were set. Every fault of that bar came from the same place —
+ * nothing said which terms were live, and a control that vanished took its own way
+ * back with it, so the most useful filter in the app (`kind`) was invisible until
+ * you happened to narrow by type first.
+ *
+ * Here the bar is three fixed parts: the search, one **+ Filter** menu, and the
+ * chips the question is made of. An axis that cannot be asked yet stays in the menu
+ * **with its reason written next to it** rather than disappearing, because a
+ * control you can see and cannot use teaches something, and one that is not there
+ * teaches nothing.
+ *
+ * The menu opens on four **Questions** — the ones every case is asked — and picking
+ * one drops its terms in as ordinary chips. That is the whole of the onboarding:
+ * the answer arrives, and the sentence that produced it is sitting there to edit.
+ *
+ * Every menu is built from what the case holds and counted, so a term says how much
+ * of an answer it is before it is chosen (`lib/entityFilter.js`).
+ */
+ import {
+ ADDED,
+ AXES,
+ QUESTIONS,
+ STATUSES,
+ chipsOf,
+ clearAxis,
+ emptyFilter,
+ hasTerm,
+ isFiltering,
+ toggleValue,
+ } from '../lib/entityFilter.js';
+ import Icon from './Icon.svelte';
+
+ let {
+ filter = $bindable(),
+ /** `{ total, by_type, by_status, by_folder, by_source, unlinked }`, or null. */
+ summary = null,
+ /** The fields the narrowed types hold, as `/catalog/attributes` answers. */
+ facets = [],
+ /** Whether those facets are for the whole case or still being fetched. */
+ facetState = 'ready', // 'ready' | 'loading' | 'unasked'
+ /** Types the case actually holds, in menu order: `[{ type, label, family }]`. */
+ types = [],
+ families = [],
+ /** Every folder the case declares, including the ones holding nothing yet. The
+ * summary can only report the folders that hold rows, so a parent whose contents
+ * all sit in its children is missing from it. */
+ caseFolders = [],
+ familyName = (family) => family,
+ typeName = (type) => type,
+ /** The registry's own clause for a family and for a type. The vocabulary explains
+ * itself where the word appears (UI.md), and these are the two menus that offer
+ * words an analyst never types. */
+ familyHint = () => '',
+ typeHint = () => '',
+ /** Snapshots keep the captured answer immutable. The bar stays visible so the
+ * analyst can read the question, but none of its terms can be changed. */
+ disabled = false,
+ /** Called the first time the Field axis is opened, so nothing is scanned on
+ * mount for a menu nobody asked for. */
+ onfields = () => {},
+ } = $props();
+
+ /** Which axis has its popover open, or '' for none. The menu itself is `'+'`. */
+ let open = $state('');
+
+ $effect(() => {
+ if (disabled) open = '';
+ });
+
+ const chips = $derived(chipsOf(filter, { type: typeName, family: familyName }));
+ const filtering = $derived(isFiltering(filter));
+
+ /**
+ * The folder tree, every level of it.
+ *
+ * Built from three sources on purpose, because each one alone leaves a hole. The
+ * summary counts only folders that hold rows **directly**, so a parent whose whole
+ * contents sit in its children — `Sources` over `Sources/Accounts` — never appeared
+ * at all, and "include subfolders" had nothing to be ticked on. The case's own list
+ * adds the folders that exist and hold nothing yet. And every path implies its
+ * ancestors, which covers a folder neither list happens to name.
+ *
+ * `direct` is what the folder holds itself, `under` what it holds with everything
+ * below it. The two are genuinely different numbers and the menu shows whichever
+ * the chip is currently reading.
+ */
+ const folders = $derived.by(() => {
+ const direct = new Map(Object.entries(summary?.by_folder ?? {}));
+ const paths = new Set([...direct.keys(), ...caseFolders]);
+ for (const path of [...paths]) {
+ const parts = path.split('/');
+ for (let cut = 1; cut < parts.length; cut += 1) paths.add(parts.slice(0, cut).join('/'));
+ }
+ const rows = [...paths].filter(Boolean).sort((a, b) => a.localeCompare(b));
+ return rows.map((path) => {
+ const parts = path.split('/');
+ return {
+ path,
+ name: parts.at(-1),
+ depth: parts.length - 1,
+ direct: direct.get(path) ?? 0,
+ under: rows
+ .filter((other) => other === path || other.startsWith(`${path}/`))
+ .reduce((sum, other) => sum + (direct.get(other) ?? 0), 0),
+ };
+ });
+ });
+ const unfiledCount = $derived(
+ Math.max(
+ (summary?.total ?? 0) -
+ Object.values(summary?.by_folder ?? {}).reduce((sum, count) => sum + count, 0),
+ 0
+ )
+ );
+ const filers = $derived(
+ Object.entries(summary?.by_source ?? {}).sort((a, b) => b[1] - a[1])
+ );
+ /** Only the types the case holds: offering "type: vessel" in a case with no vessel
+ * is offering an empty answer. */
+ const held = $derived(types.filter((entry) => summary?.by_type?.[entry.type]));
+ /**
+ * The types something is actually **joined to**, with how many rows join them.
+ *
+ * A different question from what the case holds, and the counts differ by a lot:
+ * four media pointing at one place is one place and four linked rows. The filter
+ * asks the second, so the menu prices the second — and a type nothing links to is
+ * left out, since asking it could only answer nothing.
+ */
+ const reachable = $derived(
+ types
+ .filter((entry) => summary?.linked_to?.[entry.type])
+ .map((entry) => ({ ...entry, count: summary.linked_to[entry.type] }))
+ );
+ /** How many rows each family covers, summed off the per-type counts rather than
+ * asked for again: a family is its types, and the summary already holds them. */
+ const familyCount = $derived((family) =>
+ types
+ .filter((entry) => entry.family === family)
+ .reduce((sum, entry) => sum + (summary?.by_type?.[entry.type] ?? 0), 0)
+ );
+ const fields = $derived(facets.filter((row) => row.values.length));
+ const values = $derived(fields.find((row) => row.key === filter.attrKey)?.values ?? []);
+
+ /** What each axis is worth right now, or the reason it cannot be asked yet. Said
+ * in the menu rather than by leaving the row out. */
+ function axisState(axis) {
+ if (axis === 'field') {
+ // Always openable, whatever the case holds: the fields are read on this click,
+ // which is the whole point — gated behind a type, `kind` was invisible, and
+ // gated behind a size the large cases lost the one filter that scales.
+ if (facetState === 'loading') return { off: false, note: 'reading…' };
+ if (facetState === 'unasked') return { off: false, note: '' };
+ return fields.length
+ ? { off: false, note: `${fields.length} fields` }
+ : { off: true, note: 'no stored fields here' };
+ }
+ if (axis === 'linked') {
+ return reachable.length
+ ? { off: false, note: `${reachable.length} types` }
+ : { off: true, note: 'nothing is linked yet' };
+ }
+ if (axis === 'connections') {
+ const loose = summary?.unlinked ?? 0;
+ return loose ? { off: false, note: String(loose) } : { off: true, note: 'all connected' };
+ }
+ if (axis === 'folder') {
+ return folders.length || unfiledCount
+ ? { off: false, note: folders.length ? `${folders.length} folders` : '' }
+ : { off: true, note: 'nothing filed yet' };
+ }
+ if (axis === 'by') {
+ return filers.length > 1
+ ? { off: false, note: `${filers.length} filers` }
+ : { off: true, note: 'all filed the same way' };
+ }
+ if (axis === 'type') return { off: !held.length, note: `${held.length} in this case` };
+ if (axis === 'family') return { off: !families.length, note: `${families.length}` };
+ return { off: false, note: '' };
+ }
+
+ /** How many the case holds under one Question, where the summary can answer
+ * honestly. A range needs a query, so it says nothing rather than a wrong number. */
+ function questionCount(id) {
+ if (id === 'review') return summary?.by_status?.suggested ?? 0;
+ if (id === 'loose') return summary?.unlinked ?? 0;
+ if (id === 'unfiled') return unfiledCount;
+ return null;
+ }
+
+ /**
+ * Open an axis, or act on it directly when there is nothing to pick.
+ *
+ * A toggle has no menu — its whole act is being chosen — so opening a popover for
+ * it would be a click that asks a question with one answer.
+ */
+ function chose(axis) {
+ if (axis === 'connections') {
+ filter = { ...filter, connections: filter.connections === 'none' ? '' : 'none' };
+ open = '';
+ return;
+ }
+ if (axis === 'field') onfields();
+ open = axis;
+ }
+
+ /**
+ * Pick a folder, and read a parent as the subtree it stands for.
+ *
+ * A folder holding nothing itself can only mean everything under it — `Sources` over
+ * its four children is a heading, not a bucket — so choosing one turns the subfolder
+ * reach on rather than answering with an empty table. The tick stays on screen and
+ * still switches, because the analyst may have meant the empty folder itself.
+ */
+ function pickFolder(row) {
+ const same = filter.folder === row.path;
+ filter = {
+ ...filter,
+ folder: same ? '' : row.path,
+ unfiled: false,
+ recursive: same ? false : filter.recursive || (!row.direct && row.under > 0),
+ };
+ }
+
+ function ask(id) {
+ const question = QUESTIONS.find((entry) => entry.id === id);
+ filter = { ...filter, ...question.terms };
+ open = '';
+ }
+
+ function clearAll() {
+ filter = emptyFilter();
+ open = '';
+ }
+
+ /**
+ * A press anywhere but inside what is open closes it.
+ *
+ * Scoped to the **open** control rather than to the bar, which is the difference
+ * between a menu that closes and one that seems stuck: pressing the search box, or
+ * another chip, is as much "somewhere else" as pressing the table. Bound on the
+ * window rather than on a backdrop element, so nothing invisible sits over the rest
+ * of the screen swallowing the first click.
+ */
+ function onWindowPointerDown(event) {
+ if (!open) return;
+ if (event.target.closest?.('.anchor.live')) return;
+ open = '';
+ }
+</script>
+
+<svelte:window
+ onpointerdown={onWindowPointerDown}
+ onkeydown={(event) => event.key === 'Escape' && (open = '')}
+/>
+
+<div class="filter-bar">
+ <div class="line">
+ <div class="search-box">
+ <Icon name="search" size={13} />
+ <input
+ class="search-input"
+ type="search"
+ placeholder="Search the case…"
+ aria-label="Search the case"
+ {disabled}
+ bind:value={filter.q}
+ />
+ </div>
+
+ <div class="anchor" class:live={open === '+'}>
+ <button
+ class="btn btn-sm add"
+ aria-expanded={open === '+'}
+ {disabled}
+ title="Narrow the case: a stored field such as kind = video, a type, a folder, a date"
+ onclick={() => (open = open === '+' ? '' : '+')}
+ >
+ <Icon name="plus" size={12} /> Filter
+ </button>
+ {#if open === '+'}
+ <div class="pop wide">
+ <p class="heading">Questions</p>
+ <ul>
+ {#each QUESTIONS as question (question.id)}
+ {@const count = questionCount(question.id)}
+ <li>
+ <button title={question.hint} onclick={() => ask(question.id)}>
+ <span class="what">
+ {question.label}
+ {#if count != null}<em>{count}</em>{/if}
+ </span>
+ <span class="why">{question.hint}</span>
+ </button>
+ </li>
+ {/each}
+ </ul>
+ <p class="heading">Narrow by</p>
+ <ul>
+ {#each AXES as axis (axis.key)}
+ {@const state = axisState(axis.key)}
+ <li>
+ <!-- Present and disabled, never absent: an axis that vanishes when it
+ cannot be asked takes its own explanation with it. Two lines,
+ because a name and a count do not say what a term does — and not
+ knowing what to click is the fault this menu exists to fix. -->
+ <button
+ disabled={state.off}
+ title={state.off ? `${axis.hint} — ${state.note}` : axis.hint}
+ onclick={() => chose(axis.key)}
+ >
+ <span class="what">
+ {axis.label}
+ {#if state.note}<em>{state.note}</em>{/if}
+ </span>
+ <span class="why">{axis.hint}</span>
+ </button>
+ </li>
+ {/each}
+ </ul>
+ </div>
+ {/if}
+ </div>
+
+ {#if filtering}
+ <button
+ class="btn btn-ghost btn-sm"
+ title="Drop every term and the search with them"
+ {disabled}
+ onclick={clearAll}
+ >
+ Clear all
+ </button>
+ {/if}
+ </div>
+
+ {#if chips.length}
+ <div class="line chips">
+ {#each chips as chip (chip.axis)}
+ {@const axis = AXES.find((entry) => entry.key === chip.axis)}
+ <div class="anchor" class:live={open === chip.axis}>
+ <span class="chip" class:open={open === chip.axis}>
+ <button
+ class="chip-open"
+ aria-expanded={open === chip.axis}
+ {disabled}
+ title="{axis?.hint ?? ''} — click to change it"
+ onclick={() => chose(chip.axis)}
+ >
+ {chip.text}
+ </button>
+ <button
+ class="chip-drop"
+ aria-label="Remove this filter"
+ {disabled}
+ title="Drop this term"
+ onclick={() => (filter = clearAxis(filter, chip.axis))}
+ >
+ <Icon name="x" size={11} />
+ </button>
+ </span>
+ {#if open === chip.axis}
+ {@render popover(chip.axis)}
+ {/if}
+ </div>
+ {/each}
+ </div>
+ {/if}
+
+ <!-- An axis picked from the menu that carries no chip yet: the popover has to open
+ somewhere, and the menu it was picked from has closed. -->
+ {#if open && open !== '+' && !hasTerm(filter, open)}
+ <div class="line">
+ <div class="anchor live">{@render popover(open)}</div>
+ </div>
+ {/if}
+</div>
+
+{#snippet popover(axis)}
+ {@const entry = AXES.find((row) => row.key === axis)}
+ <div class="pop">
+ <!-- Every popover says what it is and what it narrows. It can be opened from the
+ menu, where the chip that would explain it does not exist yet, and a bare list
+ of values is exactly the "what am I clicking" this bar was built to answer. -->
+ <p class="heading titled">
+ {entry?.label ?? axis}
+ <span>{entry?.hint ?? ''}</span>
+ </p>
+ {#if axis === 'family'}
+ <ul>
+ {#each families as family (family)}
+ <li>
+ <button
+ class:on={filter.families.includes(family)}
+ title={familyHint(family)}
+ onclick={() => (filter = { ...filter, families: toggleValue(filter.families, family) })}
+ >
+ <span>{familyName(family)}</span>
+ <em>{familyCount(family)}</em>
+ {#if filter.families.includes(family)}<Icon name="check" size={12} />{/if}
+ </button>
+ </li>
+ {/each}
+ </ul>
+ {:else if axis === 'type'}
+ <ul class="scroll">
+ {#each held as entry (entry.type)}
+ <li>
+ <button
+ class:on={filter.types.includes(entry.type)}
+ title={typeHint(entry.type)}
+ onclick={() => (filter = { ...filter, types: toggleValue(filter.types, entry.type) })}
+ >
+ <span>{entry.label}</span>
+ <em>{summary?.by_type?.[entry.type] ?? 0}</em>
+ </button>
+ </li>
+ {/each}
+ </ul>
+ {:else if axis === 'folder'}
+ <ul class="scroll">
+ <li>
+ <button
+ class:on={filter.unfiled}
+ onclick={() =>
+ (filter = { ...filter, unfiled: !filter.unfiled, folder: '', recursive: false })}
+ >
+ <span>Unfiled</span>
+ <em>{unfiledCount}</em>
+ </button>
+ </li>
+ {#each folders as row (row.path)}
+ <li>
+ <!-- Nested as it is nested: these paths run three deep on a worked case,
+ and a flat column of `Sources/Cut short` is a column nobody reads. -->
+ <button
+ class:on={filter.folder === row.path}
+ style="padding-left: {8 + row.depth * 12}px"
+ title="{row.path} — {row.direct} here, {row.under} with everything under it"
+ onclick={() => pickFolder(row)}
+ >
+ <span>{row.name}</span>
+ <em>{filter.recursive ? row.under : row.direct}</em>
+ </button>
+ </li>
+ {/each}
+ </ul>
+ {#if filter.folder}
+ <label class="check">
+ <input
+ type="checkbox"
+ checked={filter.recursive}
+ onchange={(event) => (filter = { ...filter, recursive: event.currentTarget.checked })}
+ />
+ Include subfolders
+ </label>
+ {/if}
+ {:else if axis === 'status'}
+ <ul>
+ {#each STATUSES as entry (entry.value)}
+ <li>
+ <button
+ class:on={filter.status === entry.value}
+ onclick={() =>
+ (filter = {
+ ...filter,
+ status: filter.status === entry.value ? '' : entry.value,
+ })}
+ >
+ <span>{entry.label}</span>
+ <em>{summary?.by_status?.[entry.value] ?? 0}</em>
+ </button>
+ </li>
+ {/each}
+ </ul>
+ {:else if axis === 'field'}
+ <!-- Two steps, one term: the field, then one of the values the case holds for
+ it. Nothing is asked of the table until the second is chosen, and each step
+ says which it is — a list of bare words with no heading is where "I do not
+ know what to click" comes from. -->
+ {#if facetState === 'loading'}
+ <p class="note">Reading what the case stores…</p>
+ {:else if !fields.length}
+ <p class="note">Nothing here stores a field a menu can offer.</p>
+ {:else}
+ <p class="heading">1 · which field</p>
+ <ul class="scroll">
+ {#each fields as row (row.key)}
+ <li>
+ <button
+ class:on={filter.attrKey === row.key}
+ title="{row.entities} carry {row.key}"
+ onclick={() => (filter = { ...filter, attrKey: row.key, attrValue: '' })}
+ >
+ <span>{row.key}</span>
+ <em>{row.entities}</em>
+ </button>
+ </li>
+ {/each}
+ </ul>
+ {#if filter.attrKey}
+ <p class="heading">2 · which value</p>
+ <ul class="scroll">
+ {#each values as row (row.value)}
+ <li>
+ <button
+ class:on={filter.attrValue === row.value}
+ onclick={() =>
+ (filter = {
+ ...filter,
+ attrValue: filter.attrValue === row.value ? '' : row.value,
+ })}
+ >
+ <span>{row.value}</span>
+ <em>{row.count}</em>
+ </button>
+ </li>
+ {/each}
+ </ul>
+ {/if}
+ {/if}
+ {:else if axis === 'linked'}
+ <ul class="scroll">
+ {#each reachable as entry (entry.type)}
+ <li>
+ <!-- The count is how many rows this term would answer with, not how many
+ of that type the case holds: four media pointing at one place is four
+ here. Pricing it the other way is a number that looks like an answer
+ and is not one. -->
+ <button
+ class:on={filter.linked === entry.type}
+ title="{entry.count} in this case touch a {entry.label.toLowerCase()}"
+ onclick={() =>
+ (filter = {
+ ...filter,
+ linked: filter.linked === entry.type ? '' : entry.type,
+ })}
+ >
+ <span>a {entry.label.toLowerCase()}</span>
+ <em>{entry.count}</em>
+ </button>
+ </li>
+ {/each}
+ </ul>
+ {:else if axis === 'added'}
+ <ul>
+ {#each ADDED as range (range.value)}
+ <li>
+ <button
+ class:on={filter.added === range.value}
+ onclick={() =>
+ (filter = {
+ ...filter,
+ added: filter.added === range.value ? '' : range.value,
+ since: '',
+ until: '',
+ })}
+ >
+ <span>{range.label}</span>
+ </button>
+ </li>
+ {/each}
+ </ul>
+ <!-- A range typed by hand is absolute and stays where it is put, where a preset
+ re-resolves against today on every request. Setting one drops the other. -->
+ <div class="dates">
+ <label>
+ From
+ <input
+ type="date"
+ value={filter.since}
+ onchange={(event) =>
+ (filter = { ...filter, since: event.currentTarget.value, added: '' })}
+ />
+ </label>
+ <label>
+ To
+ <input
+ type="date"
+ value={filter.until}
+ onchange={(event) =>
+ (filter = { ...filter, until: event.currentTarget.value, added: '' })}
+ />
+ </label>
+ </div>
+ {:else if axis === 'by'}
+ <ul class="scroll">
+ {#each filers as [who, count] (who)}
+ <li>
+ <button
+ class:on={filter.by.includes(who)}
+ onclick={() => (filter = { ...filter, by: toggleValue(filter.by, who) })}
+ >
+ <span>{who}</span>
+ <em>{count}</em>
+ </button>
+ </li>
+ {/each}
+ </ul>
+ {/if}
+ </div>
+{/snippet}
+
+<style>
+ .filter-bar {
+ display: flex;
+ flex-direction: column;
+ gap: 6px;
+ padding: 9px 16px;
+ border-bottom: 1px solid var(--border);
+ }
+ .line {
+ display: flex;
+ align-items: center;
+ gap: 6px;
+ flex-wrap: wrap;
+ }
+ .chips {
+ gap: 5px;
+ }
+ /* Every popover hangs off the control that opened it, so nothing has to measure
+ the viewport to place a menu. */
+ .anchor {
+ position: relative;
+ display: inline-flex;
+ }
+ .search-box {
+ display: flex;
+ align-items: center;
+ gap: 6px;
+ padding: 4px 8px;
+ border: 1px solid var(--border);
+ border-radius: var(--r-sm);
+ background: var(--bg-2);
+ color: var(--text-3);
+ }
+ .search-box:focus-within {
+ border-color: var(--accent);
+ }
+ .search-input {
+ width: 200px;
+ border: none;
+ background: none;
+ outline: none;
+ color: var(--text-1);
+ font-size: var(--fs-xs);
+ }
+ .add {
+ gap: 4px;
+ }
+ .chip {
+ display: inline-flex;
+ align-items: center;
+ border: 1px solid var(--border-strong);
+ border-radius: 999px;
+ background: var(--accent-soft);
+ color: var(--text-1);
+ font-size: var(--fs-xs);
+ }
+ .chip.open {
+ border-color: var(--accent);
+ }
+ .chip-open {
+ padding: 3px 4px 3px 10px;
+ border: 0;
+ background: none;
+ color: inherit;
+ font: inherit;
+ cursor: pointer;
+ }
+ .chip-drop {
+ display: inline-flex;
+ padding: 3px 8px 3px 4px;
+ border: 0;
+ background: none;
+ color: var(--text-3);
+ cursor: pointer;
+ }
+ .chip-drop:hover {
+ color: var(--danger);
+ }
+ .pop {
+ position: absolute;
+ z-index: 20;
+ top: calc(100% + 5px);
+ left: 0;
+ min-width: 200px;
+ padding: 6px;
+ border: 1px solid var(--border);
+ border-radius: var(--r-md);
+ background: var(--bg-2);
+ box-shadow: var(--shadow-2);
+ }
+ .pop.wide {
+ min-width: 250px;
+ }
+ .heading {
+ margin: 4px 0 2px;
+ padding: 0 8px;
+ color: var(--text-3);
+ font-size: 10px;
+ font-weight: 600;
+ letter-spacing: 0.04em;
+ text-transform: uppercase;
+ }
+ .pop ul {
+ list-style: none;
+ margin: 0;
+ padding: 0;
+ }
+ .pop ul.scroll {
+ max-height: 220px;
+ overflow-y: auto;
+ }
+ .pop li button {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ width: 100%;
+ padding: 4px 8px;
+ border: 0;
+ border-radius: var(--r-sm);
+ background: none;
+ color: var(--text-1);
+ font: inherit;
+ font-size: var(--fs-xs);
+ text-align: left;
+ cursor: pointer;
+ }
+ .pop li button > span {
+ flex: 1;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ }
+ .pop li button em {
+ color: var(--text-3);
+ font-style: normal;
+ font-size: 10px;
+ }
+ /* Two lines for the menu that has to teach: what the term is, then what it does. */
+ .pop li button:has(.why) {
+ flex-direction: column;
+ align-items: stretch;
+ gap: 1px;
+ padding: 5px 8px;
+ }
+ .what {
+ display: flex;
+ align-items: baseline;
+ justify-content: space-between;
+ gap: 8px;
+ }
+ .why {
+ color: var(--text-3);
+ font-size: 10px;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ }
+ .heading.titled {
+ display: flex;
+ flex-direction: column;
+ gap: 1px;
+ margin-bottom: 4px;
+ padding-bottom: 4px;
+ border-bottom: 1px solid var(--border);
+ }
+ .heading.titled span {
+ color: var(--text-3);
+ font-weight: 400;
+ letter-spacing: 0;
+ text-transform: none;
+ }
+ .note {
+ margin: 2px 0;
+ padding: 4px 8px;
+ color: var(--text-3);
+ font-size: var(--fs-xs);
+ }
+ .pop li button:hover:not(:disabled) {
+ background: var(--bg-3);
+ }
+ .pop li button.on {
+ color: var(--accent);
+ }
+ .pop li button:disabled {
+ color: var(--text-3);
+ cursor: default;
+ }
+ .check,
+ .dates label {
+ display: flex;
+ align-items: center;
+ gap: 6px;
+ padding: 5px 8px;
+ color: var(--text-2);
+ font-size: var(--fs-xs);
+ }
+ .dates {
+ display: flex;
+ flex-direction: column;
+ }
+ .dates input {
+ flex: 1;
+ padding: 2px 5px;
+ border: 1px solid var(--border);
+ border-radius: var(--r-sm);
+ background: var(--bg-1);
+ color: var(--text-1);
+ font: inherit;
+ font-size: var(--fs-xs);
+ }
+</style>
diff --git a/frontend/src/components/FilterBar.test.js b/frontend/src/components/FilterBar.test.js
new file mode 100644
index 0000000..ed409d2
--- /dev/null
+++ b/frontend/src/components/FilterBar.test.js
@@ -0,0 +1,174 @@
+import { describe, expect, it } from 'vitest';
+import { readFileSync } from 'node:fs';
+
+const source = readFileSync(new URL('./FilterBar.svelte', import.meta.url), 'utf8');
+const markup = source.slice(source.indexOf('</script>'));
+
+describe('a bar that never changes shape', () => {
+ it('keeps the search and the one menu on screen whatever is asked', () => {
+ // the fault of the row of selects it replaces: four of them appeared and
+ // disappeared as the others were set, so the bar moved under the pointer
+ const always = markup.slice(
+ markup.indexOf('<div class="line">'),
+ markup.indexOf("aria-expanded={open === '+'}")
+ );
+ expect(always).toContain('class="search-box"');
+ expect(always).toContain('<button');
+ // nothing between the top of the bar and its menu button is conditional, so
+ // neither control ever moves under the pointer
+ expect(always).not.toContain('{#if');
+ });
+
+ it('leaves an axis it cannot ask in the menu, with the reason beside it', () => {
+ // a control you can see and cannot use teaches something; one that is not there
+ // teaches nothing, which is how the field filter stayed invisible
+ expect(markup).toContain('disabled={state.off}');
+ expect(markup).toContain('title={state.off ? `${axis.hint} — ${state.note}` : axis.hint}');
+ expect(source).toContain("{ off: true, note: 'no stored fields here' }");
+ expect(source).toContain("{ off: true, note: 'nothing is linked yet' }");
+ });
+
+ it('says what every term does, in the menu and on hover', () => {
+ // "I do not know what to click" is the fault a name and a count leave behind
+ expect(markup).toContain('<span class="why">{axis.hint}</span>');
+ expect(markup).toContain('<span class="why">{question.hint}</span>');
+ expect(markup).toContain('title="{axis?.hint ?? \'\'} — click to change it"');
+ expect(markup).toContain('class="heading titled"');
+ });
+
+ it('opens the field menu before the fields are known, since the click reads them', () => {
+ // gated behind picking a type first, `kind = video` was a filter nobody could
+ // reach — and being greyed out is indistinguishable from not existing
+ expect(source).toContain("if (facetState === 'unasked') return { off: false, note: '' }");
+ expect(source).toContain("if (facetState === 'loading') return { off: false, note: 'reading…' }");
+ expect(markup).toContain('Reading what the case stores…');
+ // and it opens whatever the case holds: no size ever turns the row off
+ expect(source).not.toMatch(/narrow-first/);
+ expect(markup).not.toMatch(/Pick a type first/);
+ });
+
+ it('offers a way out of every term, and out of all of them at once', () => {
+ expect(markup).toContain('aria-label="Remove this filter"');
+ expect(markup).toContain('clearAxis(filter, chip.axis)');
+ expect(markup).toContain('Clear all');
+ });
+});
+
+describe('the menu opens on questions, not on axes', () => {
+ it('leads with the four every case is asked', () => {
+ expect(markup).toContain('<p class="heading">Questions</p>');
+ expect(markup).toContain('{#each QUESTIONS as question');
+ expect(markup).toContain('<p class="heading">Narrow by</p>');
+ });
+
+ it('counts a question only where the summary can answer it honestly', () => {
+ // a date range needs a query, so it says nothing rather than a wrong number
+ expect(source).toContain("if (id === 'review') return summary?.by_status?.suggested ?? 0");
+ expect(source).toContain("if (id === 'loose') return summary?.unlinked ?? 0");
+ expect(source).toContain('return null;');
+ expect(markup).toContain('{#if count != null}');
+ });
+});
+
+describe('every term is chosen from what the case holds', () => {
+ it('counts each option, so a term says how much of an answer it is', () => {
+ expect(markup).toContain('<em>{summary?.by_type?.[entry.type] ?? 0}</em>');
+ expect(markup).toContain('<em>{row.count}</em>');
+ expect(markup).toContain('<em>{count}</em>');
+ });
+
+ it('offers a type only where the case holds one', () => {
+ expect(source).toContain(
+ 'const held = $derived(types.filter((entry) => summary?.by_type?.[entry.type]))'
+ );
+ });
+
+ it('prices "linked to" by what it would answer with, not by what the case holds', () => {
+ // four media pointing at one place is four here and one under "type: place":
+ // a count answering the neighbouring question looks like an answer and is not one
+ expect(source).toContain('const reachable = $derived(');
+ expect(source).toContain('summary?.linked_to?.[entry.type]');
+ expect(markup).toContain('{#each reachable as entry (entry.type)}');
+ expect(markup).toContain('<em>{entry.count}</em>');
+ // and a type nothing links to is not offered at all
+ expect(source).toContain("{ off: true, note: 'nothing is linked yet' }");
+ });
+
+ it('counts a folder the way the chip beside it reads', () => {
+ // "and under" is a different number from the folder's own, and showing one for
+ // the other is a count nobody can trust
+ expect(markup).toContain('{filter.recursive ? row.under : row.direct}');
+ expect(source).toContain('.reduce((sum, other) => sum + (direct.get(other) ?? 0), 0),');
+ });
+
+ it('offers every level of the tree, not only the folders holding rows', () => {
+ // the summary counts a folder's own rows, so a parent whose whole contents sit in
+ // its children — `Sources` over `Sources/Accounts` — was missing from the menu,
+ // and "include subfolders" had nothing to be ticked on
+ expect(source).toContain('const paths = new Set([...direct.keys(), ...caseFolders]);');
+ expect(source).toContain('for (let cut = 1; cut < parts.length; cut += 1)');
+ expect(markup).toContain('style="padding-left: {8 + row.depth * 12}px"');
+ });
+
+ it('reads a folder that holds nothing itself as the subtree it stands for', () => {
+ // a heading rather than a bucket: answering it with an empty table is answering
+ // a question nobody asked
+ expect(source).toContain('function pickFolder(row)');
+ expect(source).toContain('recursive: same ? false : filter.recursive || (!row.direct && row.under > 0)');
+ });
+
+ it('works out unfiled from what the folders do not cover', () => {
+ expect(source).toContain('const unfiledCount = $derived(');
+ });
+
+ it('takes a field in two numbered steps and asks nothing between them', () => {
+ expect(markup).toContain('<p class="heading">1 · which field</p>');
+ expect(markup).toContain('{#if filter.attrKey}');
+ expect(markup).toContain('<p class="heading">2 · which value</p>');
+ });
+
+ it('lets a date range be typed when a preset is the wrong shape', () => {
+ expect(markup).toContain('type="date"');
+ // and the two spellings of the same axis never both apply
+ expect(markup).toContain("since: event.currentTarget.value, added: ''");
+ });
+});
+
+describe('the vocabulary explains itself', () => {
+ it('carries the registry’s clause on the two menus of words nobody types', () => {
+ expect(markup).toContain('title={familyHint(family)}');
+ expect(markup).toContain('title={typeHint(entry.type)}');
+ });
+
+ it('writes no reading of its own for a family or a type', () => {
+ expect(markup).not.toMatch(/title="[a-z ]*(claim|bookmark|capture|actor|material)/i);
+ });
+});
+
+describe('a toggle has no menu to open', () => {
+ it('acts on the click that chose it, since there is nothing to pick', () => {
+ expect(source).toContain("if (axis === 'connections')");
+ expect(source).toContain("connections: filter.connections === 'none' ? '' : 'none'");
+ });
+
+ it('reads the fields only when that axis is opened', () => {
+ expect(source).toContain("if (axis === 'field') onfields();");
+ });
+});
+
+describe('the popovers close', () => {
+ it('on a press anywhere but inside the one that is open, and on Escape', () => {
+ // scoped to the open control rather than to the bar: pressing the search box or
+ // another chip is as much "somewhere else" as pressing the table
+ expect(source).toContain("if (event.target.closest?.('.anchor.live')) return;");
+ expect(source).toContain("open = '';");
+ expect(source).toContain("event.key === 'Escape' && (open = '')");
+ expect(markup).toContain("class:live={open === '+'}");
+ expect(markup).toContain('class:live={open === chip.axis}');
+ });
+
+ it('hangs each one off the control that opened it, measuring nothing', () => {
+ expect(source).toMatch(/\.anchor \{[^}]*position: relative;/);
+ expect(source).toMatch(/\.pop \{[^}]*position: absolute;/);
+ });
+});
diff --git a/frontend/src/components/Icon.svelte b/frontend/src/components/Icon.svelte
index 4fb3f10..c05bc38 100644
--- a/frontend/src/components/Icon.svelte
+++ b/frontend/src/components/Icon.svelte
@@ -7,9 +7,14 @@
media: 'M4 5h16a1 1 0 0 1 1 1v12a1 1 0 0 1-1 1H4a1 1 0 0 1-1-1V6a1 1 0 0 1 1-1Zm0 11 4.5-4.5a1 1 0 0 1 1.4 0L14 15.5m-1.5-1.5 2.6-2.6a1 1 0 0 1 1.4 0L21 15M9 9.5h.01',
satellite: 'M9 4.2 3.6 6.4a1 1 0 0 0-.6.9v11.2a1 1 0 0 0 1.4.9L9 17.4l6 2.4 5.4-2.2a1 1 0 0 0 .6-.9V5.5a1 1 0 0 0-1.4-.9L15 6.6 9 4.2Zm0 0v13.2M15 6.6v13.2',
proof: 'M4 4h7v7H4V4Zm9 0h7v7h-7V4ZM4 13h7v7H4v-7Zm11.5 0v7m-3.5-3.5h7',
+ // the case as its graph: one entity and what it holds onto. The three spokes
+ // sit on the rose's thirds — north, then 210° and 330° — so the case reads in
+ // the same geometry as the mark
+ graph: 'M12 11.6a2.2 2.2 0 1 1 0 4.4 2.2 2.2 0 0 1 0-4.4ZM12 3.5a1.9 1.9 0 1 1 0 3.8 1.9 1.9 0 0 1 0-3.8ZM4.7 16.1a1.9 1.9 0 1 1 0 3.8 1.9 1.9 0 0 1 0-3.8ZM19.3 16.1a1.9 1.9 0 1 1 0 3.8 1.9 1.9 0 0 1 0-3.8ZM12 7.3v4.3M10.1 14.9 6.4 17.1M13.9 14.9l3.7 2.2',
post: 'M20 4 9 15m11-11-6.5 17-2.7-7.5L3 10.5 20 4Z',
// ui
plus: 'M12 5v14m-7-7h14',
+ minus: 'M5 12h14',
folder: 'M3 7a2 2 0 0 1 2-2h4l2 2h8a2 2 0 0 1 2 2v9a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V7Z',
folderOpen: 'M3 7a2 2 0 0 1 2-2h4l2 2h8a2 2 0 0 1 2 2v1M3 7v11a2 2 0 0 0 2 2h13a2 2 0 0 0 2-1.5l1.6-6A1.5 1.5 0 0 0 20.1 10H6.4a2 2 0 0 0-1.9 1.4L3 16',
folderMinus: 'M3 7a2 2 0 0 1 2-2h4l2 2h8a2 2 0 0 1 2 2v9a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V7Zm6 6h6',
@@ -29,6 +34,14 @@
check: 'm4.5 12.5 5 5 10-11',
note: 'M6 3h9l5 5v13a1 1 0 0 1-1 1H6a1 1 0 0 1-1-1V4a1 1 0 0 1 1-1Zm8 0v6h6M9 13h6m-6 4h4',
pin: 'M12 21s-7-6.1-7-11a7 7 0 0 1 14 0c0 4.9-7 11-7 11Zm0-8.5a2.5 2.5 0 1 0 0-5 2.5 2.5 0 0 0 0 5Z',
+ // A pushpin, and deliberately not the marker above it: `pin` means a point on
+ // the ground, so it would read as "this is a place" on a graph where place is
+ // a family. This one means "somebody put this here and it stays".
+ //
+ // One closed outline plus the needle, and no separate bar across the cap: drawn
+ // at 15 pixels, a bar meeting the two body verticals at the same point fills in
+ // under its own round joins and the top reads as a blob.
+ pushpin: 'M8.4 4h7.2v4.8l3.2 4.3H5.2l3.2-4.3V4ZM12 13.1V20',
crosshair: 'M12 3a9 9 0 1 0 0 18 9 9 0 0 0 0-18Zm0-1v4m0 12v4M2 12h4m12 0h4',
user: 'M12 4a4 4 0 1 1 0 8 4 4 0 0 1 0-8Zm-8 17c0-4 3.6-6.5 8-6.5s8 2.5 8 6.5',
layers: 'm12 3 9 5-9 5-9-5 9-5Zm-9 9.5 9 5 9-5M3 17l9 5 9-5',
@@ -39,6 +52,9 @@
file: 'M6 3h9l5 5v13a1 1 0 0 1-1 1H6a1 1 0 0 1-1-1V4a1 1 0 0 1 1-1Zm8 0v6h6',
hash: 'M9 4 7 20M17 4l-2 16M4 9h17M3 15h17',
globe: 'M12 3a9 9 0 1 0 0 18 9 9 0 0 0 0-18Zm-9 9h18M12 3c2.5 2.5 3.8 5.7 3.8 9S14.5 18.5 12 21c-2.5-2.5-3.8-5.7-3.8-9S9.5 5.5 12 3Z',
+ // a page the case points at, not a hostname: `domain` keeps the globe, and the
+ // two stopped being the same row at a glance
+ bookmark: 'M6.5 3.5h11a1 1 0 0 1 1 1V20.5L12 16.4l-6.5 4.1V4.5a1 1 0 0 1 1-1Z',
leaf: 'M6 21c0-6 2-13 14-15 0 0 1 13-9 14-2.5.3-4-.5-5 1Zm0 0c1.5-5 4-9 9-11',
settings: 'M12.22 2h-.44a2 2 0 0 0-2 2v.18a2 2 0 0 1-1 1.73l-.43.25a2 2 0 0 1-2 0l-.15-.08a2 2 0 0 0-2.73.73l-.22.38a2 2 0 0 0 .73 2.73l.15.1a2 2 0 0 1 1 1.72v.51a2 2 0 0 1-1 1.74l-.15.09a2 2 0 0 0-.73 2.73l.22.38a2 2 0 0 0 2.73.73l.15-.08a2 2 0 0 1 2 0l.43.25a2 2 0 0 1 1 1.73V20a2 2 0 0 0 2 2h.44a2 2 0 0 0 2-2v-.18a2 2 0 0 1 1-1.73l.43-.25a2 2 0 0 1 2 0l.15.08a2 2 0 0 0 2.73-.73l.22-.39a2 2 0 0 0-.73-2.73l-.15-.08a2 2 0 0 1-1-1.74v-.5a2 2 0 0 1 1-1.74l.15-.09a2 2 0 0 0 .73-2.73l-.22-.38a2 2 0 0 0-2.73-.73l-.15.08a2 2 0 0 1-2 0l-.43-.25a2 2 0 0 1-1-1.73V4a2 2 0 0 0-2-2ZM12 9a3 3 0 1 0 0 6 3 3 0 0 0 0-6Z',
compass: 'M12 3a9 9 0 1 0 0 18 9 9 0 0 0 0-18Zm3.5 5.5-2 5-5 2 2-5 5-2Z',
@@ -46,6 +62,23 @@
edit: 'M14 5.5 18.5 10M4 20l1-4.5L16.5 4a2.1 2.1 0 0 1 3 3L8 18.5 4 20Z',
external: 'M14 4h6v6m0-6L10 14M9 5H6a2 2 0 0 0-2 2v11a2 2 0 0 0 2 2h11a2 2 0 0 0 2-2v-3',
grip: 'M9 6h.01M9 12h.01M9 18h.01M15 6h.01M15 12h.01M15 18h.01',
+ // the three assets, each drawn as itself: one shared handle icon made a lorry,
+ // a freighter and an airframe read as the same row in a list of twenty
+ car: 'M5 17h14M4 17v-4.5l2-5A1.5 1.5 0 0 1 7.4 6h9.2a1.5 1.5 0 0 1 1.4 1.5l2 5V17M4 12.5h16M7.5 17v2M16.5 17v2M8 14.5h.01M16 14.5h.01',
+ ship: 'M3 17.5c1.8 0 1.8 2 3.5 2s1.7-2 3.5-2 1.8 2 3.5 2 1.7-2 3.5-2 1.8 2 3.5 2M4.5 15l1.5-5h12l1.5 5M12 10V5M9 5h6',
+ plane: 'M12 3a1.6 1.6 0 0 1 1.5 1.7V9l7 4v2l-7-2v4l2.5 2v1.5L12 19.5 8 20.5V19l2.5-2v-4l-7 2v-2l7-4V4.7A1.6 1.6 0 0 1 12 3Z',
+ // a model rather than an object: three cards of the same shape, because what an
+ // equipment type means is "there are several of these"
+ stack: 'M8 4h9a1 1 0 0 1 1 1v9M6 7h9a1 1 0 0 1 1 1v9M4 10h9a1 1 0 0 1 1 1v8a1 1 0 0 1-1 1H4a1 1 0 0 1-1-1v-8a1 1 0 0 1 1-1Z',
+ // a statement, not a page: the quotation marks say "somebody is asserting this"
+ quote: 'M9 5.5C6 7 4.5 9.5 4.5 12.5V18h6v-6h-3c0-2 .8-3.6 2.4-4.6L9 5.5Zm10 0c-3 1.5-4.5 4-4.5 7V18h6v-6h-3c0-2 .8-3.6 2.4-4.6L19 5.5Z',
+ // the identifiers, told apart: a globe for a domain said nothing about the
+ // account, the address and the range that were drawn with the same glyph
+ at: 'M15.5 12a3.5 3.5 0 1 0-1 2.5M15.5 8.5v5a2.5 2.5 0 0 0 5 0V12a8.5 8.5 0 1 0-3.5 6.9',
+ mail: 'M4 6h16a1 1 0 0 1 1 1v10a1 1 0 0 1-1 1H4a1 1 0 0 1-1-1V7a1 1 0 0 1 1-1Zm-.6.6 8.6 7 8.6-7',
+ phone: 'M7.5 3h-2A2 2 0 0 0 3.5 5 15.5 15.5 0 0 0 19 20.5a2 2 0 0 0 2-2v-2l-4.5-2-2 2.5a12 12 0 0 1-4.5-4.5L12.5 10 10.5 5.5 7.5 3Z',
+ network: 'M12 3.5a2.25 2.25 0 1 1 0 4.5 2.25 2.25 0 0 1 0-4.5ZM5 16a2.25 2.25 0 1 1 0 4.5A2.25 2.25 0 0 1 5 16Zm14 0a2.25 2.25 0 1 1 0 4.5 2.25 2.25 0 0 1 0-4.5ZM12 8v4m0 0-7 4m7-4 7 4',
+ building: 'M5 21V4.5A1 1 0 0 1 6 3.5h7a1 1 0 0 1 1 1V21M14 10h4a1 1 0 0 1 1 1v10M3 21h18M8 7.5h.01M11 7.5h.01M8 11h.01M11 11h.01M8 14.5h3',
alert: 'M12 3 2.5 19.5h19L12 3Zm0 7v4m0 3.5h.01',
info: 'M12 22a10 10 0 1 0 0-20 10 10 0 0 0 0 20Zm0-11v6m0-10h.01',
clock: 'M12 3a9 9 0 1 0 0 18 9 9 0 0 0 0-18Zm0 4v5l3.5 2',
diff --git a/frontend/src/components/PasteDialog.render.test.js b/frontend/src/components/PasteDialog.render.test.js
new file mode 100644
index 0000000..1551a32
--- /dev/null
+++ b/frontend/src/components/PasteDialog.render.test.js
@@ -0,0 +1,161 @@
+// @vitest-environment happy-dom
+/**
+ * The paste dialog, actually mounted.
+ *
+ * Its whole job is to show a different set of boxes depending on what was pasted
+ * and where, and to say no when a surface will not take something. Reading the
+ * source cannot tell whether the folder picker really stays away from the Media
+ * grid, or whether the button that files a nameless bookmark is really disabled.
+ */
+import { describe, expect, it, afterEach, vi } from 'vitest';
+import { flushSync, mount, unmount } from 'svelte';
+import { resolvePaste } from '../lib/clipboardPaste.js';
+
+const { default: PasteDialog } = await import('./PasteDialog.svelte');
+
+// happy-dom has no object-URL plumbing, and the preview is not what these assert.
+URL.createObjectURL = () => 'blob:preview';
+URL.revokeObjectURL = () => {};
+
+const imageFile = () => new File([new Uint8Array([1, 2, 3])], 'image.png', { type: 'image/png' });
+
+let live = null;
+
+function open(resolved, props = {}) {
+ const target = document.createElement('div');
+ document.body.append(target);
+ live = mount(PasteDialog, { target, props: { resolved, ...props } });
+ flushSync();
+ return document.body;
+}
+
+afterEach(() => {
+ if (live) unmount(live);
+ live = null;
+ document.body.innerHTML = '';
+});
+
+const labels = (root) => [...root.querySelectorAll('.modal-label')].map((el) => el.textContent.trim());
+const addButton = (root) =>
+ [...root.querySelectorAll('button')].find((b) => b.textContent.trim().startsWith('Add'));
+
+describe('a refusal', () => {
+ it('says why, and offers nothing to fill in', () => {
+ const root = open(resolvePaste('media', { kind: 'url', url: 'https://example.com/x' }));
+ expect(root.textContent).toContain('URL field');
+ expect(root.querySelectorAll('input')).toHaveLength(0);
+ expect(addButton(root)).toBeUndefined();
+ expect(root.textContent).toContain('Close');
+ });
+
+ it('is titled for what it is, whatever was pasted', () => {
+ // "Paste link" over a sentence explaining that links do not go here reads as
+ // an invitation
+ const root = open(resolvePaste('media', { kind: 'url', url: 'https://example.com/x' }));
+ expect(root.querySelector('[role="dialog"]')?.getAttribute('aria-label')).toBe(
+ 'Nothing to paste here'
+ );
+ });
+
+ it('closes on the one button it has', () => {
+ const onclose = vi.fn();
+ const root = open(resolvePaste('board', { kind: 'text', text: 'notes' }), { onclose });
+ [...root.querySelectorAll('button')].find((b) => b.textContent.trim() === 'Close').click();
+ expect(onclose).toHaveBeenCalled();
+ });
+});
+
+describe('a pasted image', () => {
+ const payload = () => ({ kind: 'image', file: imageFile(), sourceUrl: '' });
+
+ it('shows the pixels and asks for a name and an origin', () => {
+ const root = open(resolvePaste('media', payload()));
+ expect(root.querySelector('.preview img')?.getAttribute('src')).toBe('blob:preview');
+ expect(labels(root)).toEqual(['Title', 'Source URL']);
+ // the field exists because a pasted screenshot has no origin of its own
+ expect(root.textContent).toContain('no origin of its own');
+ });
+
+ it('offers a folder in Files and nowhere else', () => {
+ const filed = open(resolvePaste('files', payload()), { folders: ['Sources'] });
+ expect(labels(filed)).toContain('Folder (in My work)');
+ unmount(live);
+ live = null;
+ document.body.innerHTML = '';
+
+ const drawn = open(resolvePaste('graph', payload()));
+ expect(labels(drawn)).not.toContain('Folder (in My work)');
+ });
+
+ it('files with no title, since a stamped name is the honest default', () => {
+ const resolved = resolvePaste('media', payload());
+ const onconfirm = vi.fn();
+ const root = open(resolved, { onconfirm });
+ expect(addButton(root).disabled).toBe(false);
+ addButton(root).click();
+ expect(onconfirm).toHaveBeenCalledWith(resolved);
+ });
+
+ it('refuses to file a source that is not an address, and says so', () => {
+ const resolved = resolvePaste('media', payload());
+ const root = open(resolved);
+ const source = root.querySelector('#paste-source');
+ source.value = 'nonsense';
+ source.dispatchEvent(new Event('input', { bubbles: true }));
+ flushSync();
+ expect(root.textContent).toContain('http(s) address');
+ expect(addButton(root).disabled).toBe(true);
+ });
+
+ it('carries what was typed back to the surface that opened it', () => {
+ const onconfirm = vi.fn();
+ const root = open(resolvePaste('files', payload(), { folder: 'Sources' }), { onconfirm });
+ const title = root.querySelector('#paste-title');
+ title.value = 'Front gate';
+ title.dispatchEvent(new Event('input', { bubbles: true }));
+ flushSync();
+ addButton(root).click();
+ expect(onconfirm.mock.calls[0][0].values).toMatchObject({
+ title: 'Front gate',
+ folder: 'Sources',
+ });
+ });
+});
+
+describe('a pasted link', () => {
+ const payload = { kind: 'url', url: 'https://leak.example.com/thread/1' };
+
+ it('shows the address and asks what a bookmark needs', () => {
+ const root = open(resolvePaste('files', payload));
+ expect(root.querySelector('.target')?.textContent).toContain('leak.example.com/thread/1');
+ expect(labels(root)).toEqual(['Title', 'Folder (in My work)', 'Notes']);
+ // no source field: the link is the source
+ expect(root.querySelector('#paste-source')).toBeNull();
+ });
+
+ it('opens on the host as a title, so the button is live straight away', () => {
+ const root = open(resolvePaste('graph', payload));
+ expect(root.querySelector('#paste-title').value).toBe('leak.example.com');
+ expect(addButton(root).disabled).toBe(false);
+ });
+
+ it('holds the button once the title is emptied', () => {
+ const root = open(resolvePaste('graph', payload));
+ const title = root.querySelector('#paste-title');
+ title.value = '';
+ title.dispatchEvent(new Event('input', { bubbles: true }));
+ flushSync();
+ expect(root.textContent).toContain('needs a title');
+ expect(addButton(root).disabled).toBe(true);
+ });
+});
+
+describe('while it is filing', () => {
+ it('says so and cannot be pressed twice', () => {
+ const root = open(resolvePaste('board', { kind: 'url', url: 'https://x.example' }), {
+ busy: true,
+ });
+ expect(addButton(root).disabled).toBe(true);
+ expect(addButton(root).textContent.trim()).toBe('Adding…');
+ });
+});
diff --git a/frontend/src/components/PasteDialog.svelte b/frontend/src/components/PasteDialog.svelte
new file mode 100644
index 0000000..91f3390
--- /dev/null
+++ b/frontend/src/components/PasteDialog.svelte
@@ -0,0 +1,202 @@
+<script>
+ /**
+ * What a Ctrl+V shows, on whichever surface caught it.
+ *
+ * One dialog for four tools, for the reason the entity dialog is one dialog: a
+ * pasted screenshot is filed with the same words and the same field names in the
+ * Media grid, the Files desktop, the drawing and the table. Four copies of this
+ * form would be four vocabularies inside a week.
+ *
+ * It renders whatever `resolvePaste` decided (lib/clipboardPaste.js) — which
+ * fields to ask for, or the sentence saying why this surface will not take what
+ * was pasted. A refusal is a screen of its own rather than a toast, because it is
+ * the answer to a deliberate act and it has something to teach: where the thing
+ * does go.
+ */
+ import { pasteProblem } from '../lib/clipboardPaste.js';
+ import Icon from './Icon.svelte';
+ import Modal from './Modal.svelte';
+ import FolderSelect from './FolderSelect.svelte';
+
+ let {
+ /** What `resolvePaste` decided: which fields to ask for, or why not to. */
+ resolved,
+ folders = [],
+ busy = false,
+ onconfirm = () => {},
+ onclose = () => {},
+ } = $props();
+
+ // The draft is the dialog's own, and handed back on confirm. Writing through to
+ // the caller's object instead would make every surface responsible for wrapping
+ // its resolution in state before the fields could be typed into at all.
+ // svelte-ignore state_referenced_locally
+ let values = $state({ ...resolved.values });
+
+ const isImage = $derived(resolved.kind === 'image');
+ const asks = (field) => (resolved.fields ?? []).includes(field);
+ const problem = $derived(
+ resolved.mode === 'form' ? pasteProblem({ kind: resolved.kind, values }) : ''
+ );
+
+ // A refusal is titled for what it is whatever was pasted: "Paste link" over a
+ // sentence explaining that links do not go here reads as an invitation.
+ const TITLES = { image: 'Paste image', url: 'Paste link' };
+ const title = $derived(
+ resolved.mode === 'refuse' ? 'Nothing to paste here' : (TITLES[resolved.kind] ?? 'Paste')
+ );
+
+ // Revoked when the dialog goes: an object URL held after that keeps the pasted
+ // bytes alive for as long as the tab lives.
+ let previewUrl = $state('');
+ $effect(() => {
+ if (resolved.mode !== 'form' || !isImage) return;
+ const url = URL.createObjectURL(resolved.payload.file);
+ previewUrl = url;
+ return () => {
+ URL.revokeObjectURL(url);
+ previewUrl = '';
+ };
+ });
+
+ const sizeLabel = $derived(
+ isImage ? `${Math.max(1, Math.round(resolved.payload.file.size / 1024))} kB` : ''
+ );
+</script>
+
+<Modal {title} {onclose} width="520px">
+ {#if resolved.mode === 'refuse'}
+ <p class="refusal">{resolved.reason}</p>
+ <div class="modal-row">
+ <div style="flex:1"></div>
+ <button class="btn btn-primary" onclick={onclose}>Close</button>
+ </div>
+ {:else}
+ {#if isImage}
+ <figure class="preview">
+ {#if previewUrl}
+ <img src={previewUrl} alt="What the clipboard is holding" />
+ {/if}
+ <figcaption>{resolved.payload.file.type || 'image'} · {sizeLabel}</figcaption>
+ </figure>
+ {:else}
+ <p class="target"><Icon name="link" size={14} /> <span>{resolved.payload.url}</span></p>
+ {/if}
+
+ {#if asks('title')}
+ <label class="modal-label" for="paste-title">Title</label>
+ <input
+ id="paste-title"
+ class="input"
+ placeholder={isImage ? 'Name this image…' : 'Bookmark title…'}
+ bind:value={values.title}
+ />
+ {#if isImage}
+ <p class="field-help">Optional. Names the file in the case.</p>
+ {/if}
+ {/if}
+
+ {#if asks('folder')}
+ <span class="modal-label" style="margin-top:10px">Folder (in My work)</span>
+ <FolderSelect bind:value={values.folder} {folders} emptyLabel="My work (root)" />
+ {/if}
+
+ {#if asks('source')}
+ <label class="modal-label" for="paste-source" style="margin-top:10px">Source URL</label>
+ <input
+ id="paste-source"
+ class="input"
+ placeholder="https://…"
+ bind:value={values.source}
+ />
+ <p class="field-help">A pasted image carries no origin of its own.</p>
+ {/if}
+
+ {#if asks('notes')}
+ <label class="modal-label" for="paste-notes" style="margin-top:10px">Notes</label>
+ <textarea
+ id="paste-notes"
+ class="textarea"
+ rows="3"
+ placeholder="Why this page matters…"
+ bind:value={values.notes}
+ ></textarea>
+ {/if}
+
+ <div class="modal-row">
+ <div style="flex:1"></div>
+ {#if problem}<span class="problem">{problem}</span>{/if}
+ <button class="btn" onclick={onclose}>Cancel</button>
+ <button
+ class="btn btn-primary"
+ onclick={() => onconfirm({ ...resolved, values })}
+ disabled={busy || Boolean(problem)}
+ >
+ {busy ? 'Adding…' : 'Add to case'}
+ </button>
+ </div>
+ {/if}
+</Modal>
+
+<style>
+ .refusal {
+ margin: 6px 0 0;
+ color: var(--text-2);
+ font-size: var(--fs-sm);
+ line-height: 1.55;
+ }
+ .preview {
+ margin: 6px 0 12px;
+ padding: 8px;
+ border: 1px solid var(--border);
+ border-radius: var(--r);
+ background: var(--bg-2);
+ text-align: center;
+ }
+ .preview img {
+ display: block;
+ max-width: 100%;
+ max-height: 240px;
+ margin: 0 auto;
+ border-radius: var(--r-sm);
+ object-fit: contain;
+ }
+ .preview figcaption {
+ margin-top: 7px;
+ color: var(--text-3);
+ font-family: var(--font-mono);
+ font-size: var(--fs-xs);
+ }
+ .target {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ margin: 6px 0 12px;
+ padding: 8px 10px;
+ border: 1px solid var(--border);
+ border-radius: var(--r);
+ background: var(--bg-2);
+ color: var(--text-2);
+ font-size: var(--fs-sm);
+ }
+ .target span {
+ min-width: 0;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ }
+ .field-help {
+ margin: 5px 0 0;
+ color: var(--text-3);
+ font-size: var(--fs-xs);
+ }
+ .problem {
+ align-self: center;
+ color: var(--warn);
+ font-size: var(--fs-xs);
+ }
+ .textarea {
+ width: 100%;
+ resize: vertical;
+ }
+</style>
diff --git a/frontend/src/components/RelationList.render.test.js b/frontend/src/components/RelationList.render.test.js
new file mode 100644
index 0000000..40f1d05
--- /dev/null
+++ b/frontend/src/components/RelationList.render.test.js
@@ -0,0 +1,162 @@
+// @vitest-environment happy-dom
+/**
+ * The list actually mounted, for the one thing reading the source cannot answer:
+ * whether a pointer ends up under its own heading or inline among the findings.
+ *
+ * Its sibling suite checks the wiring. This one checks what an analyst sees — the
+ * complaint that started it was "relations and mentions are mixed together", which
+ * is a question about rendered order, not about which function was called.
+ */
+import { describe, expect, it, vi, afterEach } from 'vitest';
+import { flushSync, mount, unmount } from 'svelte';
+
+const GROUPS = { mentions: 'Mentions' };
+const VERBS = { 'located-at': 'was recorded at', mentions: 'mentions', depicts: 'shows' };
+
+vi.mock('../lib/relations.svelte.js', () => ({
+ confidenceHint: () => '',
+ confidenceLabel: () => '',
+ confidenceLevels: () => [],
+ isCurrentConnection: () => true,
+ isRatable: () => true,
+ loadRelationTypes: () => Promise.resolve(),
+ relationAction: (type) => (type === 'mentions' ? 'mention' : 'relation'),
+ relationGroup: (type) => GROUPS[type] ?? '',
+ relationHint: () => '',
+ relationOptions: () => [],
+ // Only the tie verb declares one, which is the whole point of the field belonging
+ // to the verb: every other row renders without it.
+ relationQualifier: (type) => (type === 'associated-with' ? 'How they are tied' : ''),
+ relationReading: (type) => VERBS[type] ?? type,
+ relationVerb: (type) => VERBS[type] ?? type,
+}));
+vi.mock('../lib/entityTypes.svelte.js', () => ({
+ loadEntityTypes: () => Promise.resolve(),
+ reliabilityOf: () => null,
+}));
+vi.mock('../lib/entityIcon.js', () => ({ entityIcon: () => 'note' }));
+vi.mock('../lib/navigate.js', () => ({ openEntity: () => {} }));
+vi.mock('../lib/state.svelte.js', () => ({ toast: () => {} }));
+vi.mock('../lib/api.js', () => ({ api: { patch: vi.fn(), del: vi.fn() } }));
+
+const { default: RelationList } = await import('./RelationList.svelte');
+
+/** One row, confirmed, so nothing sorts ahead of it for needing review. */
+const row = (id, type, label) => ({
+ link: { id, type, provenance: { status: 'confirmed' } },
+ entity: { id: `e${id}`, type: 'place', label, attrs: {} },
+ direction: 'out',
+});
+
+let live = null;
+
+function open(relations, extra = {}) {
+ const target = document.createElement('div');
+ document.body.append(target);
+ live = mount(RelationList, {
+ target,
+ props: { caseId: 'c1', relations, onchanged: () => {}, ...extra },
+ });
+ flushSync();
+ return target;
+}
+
+afterEach(() => {
+ if (live) unmount(live);
+ live = null;
+ document.body.innerHTML = '';
+});
+
+/** Every heading and every row name, in the order they are painted. */
+const reading = (root) =>
+ [...root.querySelectorAll('.group, .relation .name')].map((el) => el.textContent.trim());
+
+describe('a pointer is not shown as a finding', () => {
+ it('heads the mentions apart and leaves the rest of the list unheaded', () => {
+ const root = open([
+ row('1', 'located-at', 'North quay'),
+ row('2', 'mentions', 'The sawmill'),
+ row('3', 'depicts', 'Far ridge'),
+ ]);
+
+ expect(reading(root)).toEqual(['North quay', 'Far ridge', 'Mentions', 'The sawmill']);
+ });
+
+ it('draws no heading at all when every verb belongs with the others', () => {
+ const root = open([row('1', 'located-at', 'North quay'), row('2', 'depicts', 'Far ridge')]);
+
+ expect(root.querySelectorAll('.group')).toHaveLength(0);
+ expect(reading(root)).toEqual(['North quay', 'Far ridge']);
+ });
+
+ it('heads them even when the list holds nothing else', () => {
+ const root = open([row('1', 'mentions', 'The sawmill')]);
+
+ expect(reading(root)).toEqual(['Mentions', 'The sawmill']);
+ expect(root.querySelector('.mention .says').textContent).toContain('mentions');
+ expect(root.querySelector('.mention .rate')).toBeNull();
+ });
+
+ it('puts what needs a decision first inside its own section', () => {
+ // the split wins over review order across sections — a heading the analyst can
+ // read is not a hiding place — and review order still decides inside each one
+ const pending = row('2', 'mentions', 'The sawmill');
+ pending.link.provenance.status = 'suggested';
+ const root = open([
+ row('1', 'located-at', 'North quay'),
+ row('3', 'mentions', 'Old crane'),
+ pending,
+ ]);
+
+ expect(reading(root)).toEqual(['North quay', 'Mentions', 'The sawmill', 'Old crane']);
+ });
+
+ it('says the word once when the host already named the section', () => {
+ // Details draws its own "Mentions" heading above this list and asks for that
+ // action alone; the list heading it again read as two lists
+ const root = open([row('2', 'mentions', 'The sawmill')], { actionFilter: 'mention' });
+
+ expect(root.querySelectorAll('.group')).toHaveLength(0);
+ expect(reading(root)).toEqual(['The sawmill']);
+ });
+
+ it('counts a hidden row once, whichever section it would have landed in', () => {
+ const root = open(
+ [
+ row('1', 'located-at', 'North quay'),
+ row('2', 'mentions', 'The sawmill'),
+ row('3', 'depicts', 'Far ridge'),
+ ],
+ { max: 2 }
+ );
+
+ expect(root.querySelector('.more').textContent.trim()).toBe('+ 1 more');
+ // the cap counts rows, not sections: two rows survive it and one of them heads
+ expect(reading(root)).toEqual(['North quay', 'Mentions', 'The sawmill']);
+ });
+});
+
+describe('what kind of tie, where the verb cannot say it', () => {
+ it('draws the field on the verb that declares one, and on no other row', () => {
+ // Declared by the verb, never by the edge: a note every relation could hold
+ // would leave nothing saying what a relation *is*.
+ const root = open([row('l1', 'associated-with', 'Second'), row('l2', 'owns', 'A lorry')]);
+ const fields = [...root.querySelectorAll('.nature')];
+ expect(fields).toHaveLength(1);
+ expect(fields[0].placeholder).toBe('How they are tied');
+ });
+
+ it('shows the word already stated rather than an empty box', () => {
+ const stated = row('l1', 'associated-with', 'Second');
+ stated.link.nature = 'sister';
+ const root = open([stated]);
+ expect(root.querySelector('.nature').value).toBe('sister');
+ expect(root.querySelector('.nature').classList.contains('set')).toBe(true);
+ });
+
+ it('offers nothing to qualify on a proposal, which is reviewed before it is read', () => {
+ const proposed = row('l1', 'associated-with', 'Second');
+ proposed.link.provenance = { status: 'suggested' };
+ expect(open([proposed]).querySelector('.nature')).toBeNull();
+ });
+});
diff --git a/frontend/src/components/RelationList.svelte b/frontend/src/components/RelationList.svelte
index b959d4e..59d6148 100644
--- a/frontend/src/components/RelationList.svelte
+++ b/frontend/src/components/RelationList.svelte
@@ -2,7 +2,7 @@
/**
* The non-chain edges of one entity (ONTOLOGY §3), one row each.
*
- * A relation says something about the world — this photo was shot there, these
+ * A relation says something about the world — this photo was recorded there, these
* two files are the same picture — where the derivation chain says how a file
* was made. Import enrichment proposes them from a file's own metadata, so most
* rows start `suggested` and carry the two clicks that settle them: confirm
@@ -14,7 +14,22 @@
*/
import { api } from '../lib/api.js';
import { toast } from '../lib/state.svelte.js';
- import { loadRelationTypes, relationOptions, relationVerb } from '../lib/relations.svelte.js';
+ import {
+ confidenceHint,
+ confidenceLabel,
+ confidenceLevels,
+ isRatable,
+ isCurrentConnection,
+ loadRelationTypes,
+ relationAction,
+ relationGroup,
+ relationHint,
+ relationOptions,
+ relationQualifier,
+ relationReading,
+ } from '../lib/relations.svelte.js';
+ import { loadEntityTypes, reliabilityOf } from '../lib/entityTypes.svelte.js';
+ import { entityIcon } from '../lib/entityIcon.js';
import { openEntity } from '../lib/navigate.js';
import Icon from './Icon.svelte';
@@ -22,6 +37,8 @@
caseId,
relations = [],
subjectType = null, // the type these relations are about; enables restating
+ subject = null,
+ actionFilter = null,
onwalk = null, // given, a row walks the host to that entity in place
onchanged, // a relation was settled or restated: the host reloads what it reads
max = 6, // rows past this hide behind one "+ n more" click
@@ -32,12 +49,10 @@
* because a click that silently swaps the whole workspace reads as a bug. */
const walk = (entity) => (onwalk ? onwalk(entity) : openEntity(entity));
- const ENTITY_ICON = {
- media: 'media', capture: 'satellite', place: 'pin', proof: 'proof',
- post: 'post', 'inspect-session': 'inspect', note: 'note', bookmark: 'link',
- };
-
loadRelationTypes();
+ // Also the entity registry: a row reads its neighbour's reliability out of it, and
+ // this component has three homes, only one of which loads it for its own reasons.
+ loadEntityTypes();
let expanded = $state(false);
let busyId = $state(null);
@@ -60,15 +75,48 @@
}
// Suggestions first: they are the only rows that need a decision, and a case
- // with forty confirmed relations must not bury the three awaiting review.
+ // with forty confirmed relations must not bury the three awaiting review. Inside
+ // each section once the list is split — a heading the analyst reads on the way
+ // past is not a hiding place, and interleaving the two kinds to surface a
+ // proposal would undo the split it is being shown through.
+ const scoped = $derived(
+ actionFilter
+ ? relations.filter((relation) => relationAction(relation.link.type) === actionFilter)
+ : relations
+ );
const ordered = $derived(
- [...relations].sort(
+ [...scoped].sort(
(a, b) => Number(isSuggested(b)) - Number(isSuggested(a))
)
);
const shown = $derived(expanded ? ordered : ordered.slice(0, max));
const hidden = $derived(Math.max(0, ordered.length - shown.length));
+ /**
+ * The rows split under the headings their verbs declare, ungrouped ones first.
+ *
+ * A pointer is not a finding: "this note mentions that quay" says nothing about
+ * where the quay is, where "was recorded at" does. Run together in one list they read
+ * as the same kind of statement, and the weaker one quietly borrows the weight of
+ * the others. Which verbs head their own section is the registry's call
+ * (`links.RelationType.group`), never this component's.
+ */
+ const sections = $derived.by(() => {
+ const groups = new Map([['', []]]);
+ for (const relation of shown) {
+ // A host that already asked for one action has named it above the list — the
+ // Mentions section drawing a "Mentions" heading over its own rows said the
+ // word twice and looked like two lists. The heading is for a list that runs
+ // several actions together.
+ const group = actionFilter ? '' : relationGroup(relation.link.type);
+ if (!groups.has(group)) groups.set(group, []);
+ groups.get(group).push(relation);
+ }
+ return [...groups]
+ .filter(([, rows]) => rows.length)
+ .map(([group, rows]) => ({ group, rows }));
+ });
+
function isSuggested(relation) {
return relation.link?.provenance?.status === 'suggested';
}
@@ -87,12 +135,18 @@
* reword, and empty when the pair has only one reading. */
function verbOptions(relation) {
if (!subjectType) return [];
- const options = relationOptions(subjectType, relation.entity.type).filter(
+ const options = relationOptions(
+ subject ?? subjectType,
+ relation.entity,
+ relationAction(relation.link.type)
+ ).filter(
(option) => option.direction === relation.direction
);
return options.length > 1 ? options : [];
}
+ const legacy = (relation) => !isCurrentConnection(subject ?? subjectType, relation);
+
async function restate(link, type) {
if (busyId || type === link.type) return;
busyId = link.id;
@@ -107,6 +161,51 @@
}
}
+ /**
+ * Rate how sure the analyst is, or clear the rating.
+ *
+ * `''` in the select means *not assessed*, and it sends `null` rather than being
+ * left out: absent is a state to be able to return to, so a level picked by mistake
+ * is not a hole. A suggestion is not offered the control at all — reviewing a
+ * machine's claim and rating it are two different gestures, and the API refuses the
+ * second before the first.
+ */
+ async function rate(link, raw) {
+ if (busyId) return;
+ const value = raw === '' ? null : Number(raw);
+ busyId = link.id;
+ try {
+ await api.patch(`/api/cases/${caseId}/links/${link.id}`, { confidence: value });
+ await onchanged?.();
+ } catch (e) {
+ toast(e.message, 'danger');
+ } finally {
+ busyId = null;
+ }
+ }
+
+ /**
+ * Say what kind of tie this edge states, or clear it.
+ *
+ * On `change` rather than on every keystroke: the value is a word, and a request
+ * per letter would file "s", "si", "sis" before reaching "sister". Empty sends
+ * `null`, so a word typed by mistake is taken back rather than stored blank.
+ */
+ async function qualify(link, raw) {
+ if (busyId) return;
+ const value = raw.trim();
+ if (value === (link.nature ?? '')) return;
+ busyId = link.id;
+ try {
+ await api.patch(`/api/cases/${caseId}/links/${link.id}`, { nature: value || null });
+ await onchanged?.();
+ } catch (e) {
+ toast(e.message, 'danger');
+ } finally {
+ busyId = null;
+ }
+ }
+
async function confirm(link) {
if (busyId) return;
busyId = link.id;
@@ -125,12 +224,13 @@
* is a statement and taking it back is the only way to correct one — the
* wording differs so it reads as "not that" on a proposal and "no longer
* true" on something the analyst had already accepted. */
- async function remove(link, suggested) {
+ async function remove(link, suggested, action) {
if (busyId) return;
busyId = link.id;
try {
await api.del(`/api/cases/${caseId}/links/${link.id}`);
- toast(suggested ? 'Relation dismissed' : 'Relation removed', 'info', 1600);
+ const noun = action === 'mention' ? 'Mention' : 'Relation';
+ toast(suggested ? `${noun} dismissed` : `${noun} removed`, 'info', 1600);
await onchanged?.();
} catch (e) {
toast(e.message, 'danger');
@@ -140,70 +240,147 @@
}
</script>
-{#if ordered.length}
- <div class="relations">
- {#each shown as relation (relation.link.id)}
- {@const point = placePoint(relation.entity)}
- {@const suggested = isSuggested(relation)}
- {@const verbs = verbOptions(relation)}
- <div class="relation" class:suggested class:busy={busyId === relation.link.id}>
- <button
- class="subject"
- onclick={own(() => walk(relation.entity))}
- title={`Open ${relation.entity.label}${point ? ` · ${point}` : ''}`}
- >
- <Icon name={ENTITY_ICON[relation.entity.type] ?? 'file'} size={12} />
- <span class="label">{relation.entity.label}</span>
- {#if !verbs.length}
- <span class="verb">
- {relation.direction === 'in' ? '← ' : ''}{relationVerb(relation.link.type)}
- </span>
- {/if}
- </button>
- <div class="acts">
- {#if verbs.length}
- <!-- the reading is corrected in place: same edge, same id, right verb -->
- <select
- class="select verb-select"
- value={relation.link.type}
- title="What this relation states"
- disabled={busyId === relation.link.id}
- onchange={(event) => restate(relation.link, event.currentTarget.value)}
- >
- {#each verbs as option (option.type)}
- <option value={option.type}>{option.label}</option>
- {/each}
- </select>
- {/if}
- {#if point}
- <button
- class="btn btn-ghost btn-sm act"
- title={`Show ${point} on the map`}
- onclick={own(() => openEntity(relation.entity))}
- >
- <Icon name="crosshair" size={12} />
- </button>
- {/if}
- {#if suggested}
- <button
- class="btn btn-ghost btn-sm act ok"
- title="Confirm this relation"
- disabled={busyId === relation.link.id}
- onclick={own(() => confirm(relation.link))}
- >
- <Icon name="check" size={12} />
- </button>
- {/if}
+{#snippet row(relation)}
+ {@const point = placePoint(relation.entity)}
+ {@const suggested = isSuggested(relation)}
+ {@const verbs = verbOptions(relation)}
+ {@const rating = relation.link.confidence ?? null}
+ {@const source = reliabilityOf(relation.entity)}
+ {@const action = relationAction(relation.link.type)}
+ {@const older = legacy(relation)}
+ <div
+ class="relation"
+ class:mention={action === 'mention'}
+ class:suggested
+ class:refuted={rating === -1}
+ class:legacy={older}
+ class:busy={busyId === relation.link.id}
+ >
+ <div class="head">
+ <button
+ class="subject"
+ onclick={own(() => walk(relation.entity))}
+ title={`Open ${relation.entity.label}${point ? ` · ${point}` : ''}`}
+ >
+ <Icon name={entityIcon(relation.entity)} size={12} />
+ <span class="name">{relation.entity.label}</span>
+ </button>
+ <!-- What the source is worth, on the line that carries its name, because
+ that is whose property it is. The edge's own rating stays on the line
+ below: the two axes are never read as one number, and putting them on
+ one line is the first step to doing exactly that. -->
+ {#if source}
+ <span class="grade" title={`Source reliability: ${source.label}`}>
+ {source.grade}
+ </span>
+ {/if}
+ <div class="acts">
+ {#if point}
+ <button
+ class="btn btn-ghost btn-sm act"
+ title={`Show ${point} on the map`}
+ onclick={own(() => openEntity(relation.entity))}
+ >
+ <Icon name="crosshair" size={12} />
+ </button>
+ {/if}
+ {#if suggested && !older}
<button
- class="btn btn-ghost btn-sm act no"
- title={suggested ? 'Dismiss this relation' : 'Remove this relation'}
+ class="btn btn-ghost btn-sm act ok"
+ title="Confirm this relation"
disabled={busyId === relation.link.id}
- onclick={own(() => remove(relation.link, suggested))}
+ onclick={own(() => confirm(relation.link))}
>
- <Icon name="x" size={12} />
+ <Icon name="check" size={12} />
</button>
- </div>
+ {/if}
+ <button
+ class="btn btn-ghost btn-sm act no"
+ title={suggested ? `Dismiss this ${action}` : `Remove this ${action}`}
+ disabled={busyId === relation.link.id}
+ onclick={own(() => remove(relation.link, suggested, action))}
+ >
+ <Icon name="x" size={12} />
+ </button>
</div>
+ </div>
+ <!-- What the edge states and how sure of it, on their own line under the
+ name. A 300px panel cannot fit both beside a filename, and the name is
+ what the analyst reads first. -->
+ <div class="says">
+ {#if older}
+ <span class="chip verb">{relationReading(relation.link.type, relation.direction)}</span>
+ <span class="older">Older connection</span>
+ {:else if action === 'mention'}
+ <span class="chip verb">{relationReading(relation.link.type, relation.direction)}</span>
+ {:else if verbs.length}
+ <!-- the reading is corrected in place: same edge, same id, right verb -->
+ <select
+ class="select chip verb-select"
+ value={relation.link.type}
+ title={relationHint(relation.link.type) || 'What this relation states'}
+ disabled={busyId === relation.link.id}
+ onchange={(event) => restate(relation.link, event.currentTarget.value)}
+ >
+ {#each verbs as option (option.type)}
+ <option value={option.type}>{option.label}</option>
+ {/each}
+ </select>
+ {:else}
+ <span class="chip verb" title={relationHint(relation.link.type)}>
+ {relationReading(relation.link.type, relation.direction)}
+ </span>
+ {/if}
+ <!-- How sure of this one. Only on a reviewed relation the vocabulary allows
+ to carry a rating, so no control ever offers what the API refuses. -->
+ {#if !older && !suggested && isRatable(relation.link.type) && confidenceLevels().length}
+ <select
+ class="select chip rate"
+ class:set={rating !== null}
+ class:out={rating === -1}
+ value={rating ?? ''}
+ title={rating === null
+ ? 'How sure of this'
+ : confidenceHint(rating) || confidenceLabel(rating)}
+ disabled={busyId === relation.link.id}
+ onchange={(event) => rate(relation.link, event.currentTarget.value)}
+ >
+ <!-- clearing, not a fifth level: this is the absence of a rating -->
+ <option value="">Not assessed</option>
+ {#each confidenceLevels() as level (level.value)}
+ <option value={level.value}>{level.label}</option>
+ {/each}
+ </select>
+ {/if}
+ <!-- What kind of tie, where the verb alone cannot say it. Drawn because the
+ **verb** declares a qualifier, never because this edge happens to carry
+ one — the same rule the rating follows, and what keeps a free note off
+ every other edge in the vocabulary. -->
+ {#if !older && !suggested && relationQualifier(relation.link.type)}
+ <input
+ class="input chip nature"
+ class:set={Boolean(relation.link.nature)}
+ value={relation.link.nature ?? ''}
+ placeholder={relationQualifier(relation.link.type)}
+ title={relationQualifier(relation.link.type)}
+ maxlength="120"
+ disabled={busyId === relation.link.id}
+ onchange={(event) => qualify(relation.link, event.currentTarget.value)}
+ />
+ {/if}
+ </div>
+ </div>
+{/snippet}
+
+{#if ordered.length}
+ <div class="relations">
+ {#each sections as section (section.group)}
+ {#if section.group}
+ <p class="group">{section.group}</p>
+ {/if}
+ {#each section.rows as relation (relation.link.id)}
+ {@render row(relation)}
+ {/each}
{/each}
{#if hidden}
<button class="more" onclick={own(() => (expanded = true))}>+ {hidden} more</button>
@@ -215,22 +392,50 @@
.relations {
display: flex;
flex-direction: column;
- gap: 2px;
+ gap: 5px;
min-width: 0;
}
+ /* Quiet enough to read as a divider rather than as a row: it separates two kinds
+ of statement, it is not one itself. */
+ .group {
+ margin: 4px 0 0;
+ color: var(--text-3);
+ font-size: var(--fs-xs);
+ text-transform: uppercase;
+ letter-spacing: 0.06em;
+ }
+ /* Two lines, always the same two: the name, then what it states. Rows that
+ changed shape depending on what they carried made a list of six unreadable. */
.relation {
display: flex;
- align-items: center;
- gap: 2px;
+ flex-direction: column;
+ gap: 1px;
min-width: 0;
+ padding: 1px 0 2px;
+ border-left: 2px solid transparent;
border-radius: var(--r-sm);
}
+ .relation:hover {
+ background: color-mix(in srgb, var(--bg-2) 55%, transparent);
+ }
+ .relation.mention {
+ padding-block: 0;
+ }
.relation.busy {
opacity: 0.5;
}
/* a machine's reading, not a finding: one hairline is enough to say so */
- .relation.suggested .subject {
- border-left: 2px solid color-mix(in srgb, var(--accent) 55%, transparent);
+ .relation.suggested {
+ border-left-color: color-mix(in srgb, var(--accent) 55%, transparent);
+ }
+ .relation.legacy {
+ border-left-color: var(--border-strong);
+ }
+ .head {
+ display: flex;
+ align-items: center;
+ gap: 2px;
+ min-width: 0;
}
.subject {
display: flex;
@@ -254,20 +459,25 @@
background: var(--bg-2);
color: var(--text-1);
}
- .label {
+ /* not `.label`: that one is the app's form-label utility, and it was upper-casing
+ the filenames in every relation row */
+ .name {
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
- .verb {
- flex-shrink: 0;
- margin-left: auto;
- font-size: 10px;
+ /* The source's grade: one letter, stated not offered. Drawn flat rather than as a
+ `.chip` so it cannot be mistaken for the rating dropdown two lines of code away —
+ it is read here and edited in that source's own panel. */
+ .grade {
+ flex: 0 0 auto;
padding: 1px 5px;
- border-radius: 999px;
- background: var(--bg-2);
+ border: 1px solid var(--border);
+ border-radius: var(--r-sm);
color: var(--text-3);
- white-space: nowrap;
+ font-size: 10px;
+ line-height: 14px;
+ letter-spacing: 0.04em;
}
/* the row's own actions stay quiet until the row is under the pointer */
.acts {
@@ -283,14 +493,108 @@
.act {
padding-inline: 5px;
}
- .verb-select {
- flex: 0 0 auto;
+ /* hangs under the label, not under the icon: the line reads as the row's caption */
+ .says {
+ display: flex;
+ flex-wrap: wrap;
+ align-items: center;
+ gap: 6px;
+ min-width: 0;
+ padding-left: 25px;
+ }
+ /*
+ * The row's controls are the app's own select, one size down: same fill, border,
+ * radius and focus ring as every other dropdown. Drawn rather than left native
+ * because an OS-rendered select brings its own font and metrics, which is how the
+ * rating came out bigger than the verb beside it.
+ */
+ .chip {
+ display: inline-flex;
+ align-items: center;
+ flex: 0 1 auto;
width: auto;
- max-width: 128px;
- padding: 1px 4px;
+ max-width: 100%;
+ padding: 3px 9px;
+ border: 1px solid var(--border);
+ border-radius: var(--r-sm);
+ background-color: var(--bg-2);
+ color: var(--text-2);
+ font: inherit;
+ font-size: var(--fs-xs);
+ line-height: 16px;
+ white-space: nowrap;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ }
+ select.chip {
+ /* a select laid out as a flex box is a browser lottery; same box, drawn plainly */
+ display: inline-block;
+ appearance: none;
+ padding-right: 22px;
+ background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='none' stroke='%237d7d7d' stroke-width='2.5' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpath d='m6 9 6 6 6-6'/%3E%3C/svg%3E");
+ background-repeat: no-repeat;
+ background-position: right 5px center;
+ background-size: 10px 10px;
+ cursor: pointer;
+ }
+ select.chip:hover:not(:disabled) {
+ color: var(--text-1);
+ border-color: var(--text-3);
+ }
+ select.chip:focus {
+ outline: none;
+ border-color: var(--accent);
+ box-shadow: 0 0 0 2px var(--accent-soft);
+ }
+ /* The dropdown itself is the browser's, and it takes the control's own colours —
+ left to a transparent chip it opened white-on-white in dark mode. */
+ .chip option {
+ background-color: var(--bg-1);
+ color: var(--text-1);
+ }
+ /* a verb with no alternative states the same thing without pretending to open */
+ .verb {
+ border-color: transparent;
+ background-color: transparent;
+ color: var(--text-3);
+ padding-inline: 0;
+ }
+ .verb-select {
+ max-width: 170px;
+ }
+ .older {
+ color: var(--text-3);
font-size: 10px;
+ }
+ /* Quiet until it says something. An unrated edge is the common case and must not
+ read as a gap someone left, so the control only takes colour once it holds a
+ level — and a ruled-out one is the state worth spotting across a list of twelve. */
+ .rate {
+ color: var(--text-3);
+ }
+ .rate.set {
+ color: var(--text-1);
+ }
+ .rate.out {
+ color: var(--danger);
+ border-color: color-mix(in srgb, var(--danger) 45%, transparent);
+ background-color: color-mix(in srgb, var(--danger) 12%, transparent);
+ }
+ /* Sized to a word, because a word is what it holds: wide enough for "business
+ partner", narrow enough that nobody mistakes it for a notes box. */
+ .nature {
+ width: 11ch;
+ min-width: 0;
color: var(--text-3);
}
+ .nature.set {
+ color: var(--text-1);
+ }
+ /* A ruled-out candidate stays legible and stays in the list: the elimination is the
+ finding, so it is dimmed rather than struck through or hidden. */
+ .relation.refuted .subject .name {
+ opacity: 0.6;
+ }
.act.ok:hover {
color: var(--ok, #46a758);
}
diff --git a/frontend/src/components/RelationList.test.js b/frontend/src/components/RelationList.test.js
index 89f3b40..568b007 100644
--- a/frontend/src/components/RelationList.test.js
+++ b/frontend/src/components/RelationList.test.js
@@ -18,13 +18,13 @@ describe('RelationList', () => {
it('names an edge from the shared vocabulary, never by its type slug', () => {
expect(source).toContain("from '../lib/relations.svelte.js'");
- expect(source).toContain('relationVerb(relation.link.type)');
+ expect(source).toContain('relationReading(relation.link.type, relation.direction)');
});
it('offers confirm only on a suggestion', () => {
expect(source).toContain("relation.link?.provenance?.status === 'suggested'");
expect(source).toContain("api.patch(`/api/cases/${caseId}/links/${link.id}`, { status: 'confirmed' })");
- expect(source).toContain('{#if suggested}');
+ expect(source).toContain('{#if suggested && !older}');
expect(source).toContain('title="Confirm this relation"');
expect(source).toContain('await onchanged?.()');
});
@@ -33,10 +33,10 @@ describe('RelationList', () => {
// a relation is a statement; correcting one means removing the edge, and a
// confirmed relation the analyst stated by hand is the likeliest mistake
expect(source).toContain('api.del(`/api/cases/${caseId}/links/${link.id}`)');
- expect(source).toContain("title={suggested ? 'Dismiss this relation' : 'Remove this relation'}");
- expect(source).toContain("toast(suggested ? 'Relation dismissed' : 'Relation removed'");
+ expect(source).toContain("const noun = action === 'mention' ? 'Mention' : 'Relation';");
+ expect(source).toContain('title={suggested ? `Dismiss this ${action}` : `Remove this ${action}`}');
// the remove button sits outside the suggested-only branch
- const removeAt = source.indexOf('onclick={own(() => remove(relation.link, suggested))}');
+ const removeAt = source.indexOf('onclick={own(() => remove(relation.link, suggested, action))}');
const branchEnd = source.indexOf('{/if}', source.indexOf('{#if suggested}'));
expect(removeAt).toBeGreaterThan(branchEnd);
});
@@ -45,6 +45,7 @@ describe('RelationList', () => {
// a relation stays editable: same id, same provenance, right verb
expect(source).toContain("api.patch(`/api/cases/${caseId}/links/${link.id}`, { type })");
expect(source).toContain('function verbOptions(relation)');
+ expect(source).toContain('relationAction(relation.link.type)');
expect(source).toContain("option.direction === relation.direction");
expect(source).toContain('return options.length > 1 ? options : [];');
// no subject type means no restating: the alternatives cannot be worked out
@@ -75,7 +76,7 @@ describe('RelationList', () => {
for (const wired of [
'onclick={own(() => walk(relation.entity))}',
'onclick={own(() => confirm(relation.link))}',
- 'onclick={own(() => remove(relation.link, suggested))}',
+ 'onclick={own(() => remove(relation.link, suggested, action))}',
'onclick={own(() => (expanded = true))}',
]) {
expect(source).toContain(wired);
@@ -95,8 +96,14 @@ describe('RelationList', () => {
expect(source).toContain('+ {hidden} more');
});
+ it('keeps one light list in every host', () => {
+ expect(source).toContain('<div class="relations">');
+ expect(source).not.toContain('class:cards');
+ expect(source).not.toContain('.relations.cards');
+ });
+
it('offers the map for a neighbour that carries its own point', () => {
- // confirming "shot here" without seeing where is signing blind
+ // confirming "recorded here" without seeing where is signing blind
expect(source).toContain("entity?.type !== 'place'");
expect(source).toContain('${lat.toFixed(6)}, ${lon.toFixed(6)}');
expect(source).toContain('title={`Show ${point} on the map`}');
@@ -106,4 +113,171 @@ describe('RelationList', () => {
it('keeps the coordinates in the tooltip so a row stays one line', () => {
expect(source).toContain('title={`Open ${relation.entity.label}${point ? ` · ${point}` : \'\'}`}');
});
+
+ it('gives the name a line of its own and what it states the next one', () => {
+ // beside two controls in a 300px panel a filename came out as "IM…", and the
+ // name is what the analyst reads first
+ expect(source).toContain('<div class="head">');
+ expect(source).toContain('<div class="says">');
+ // the verb reads the same whether it can be restated or not
+ expect(source).toContain('<span class="chip verb" title=');
+ });
+
+ it('draws its own controls instead of letting the OS size a select', () => {
+ // a native select is rendered in the browser's UI font and ignores much of what
+ // it is told at this size, which is how the rating came out visibly larger than
+ // the verb beside it. One chip rule carries both.
+ expect(source).toContain('class="select chip verb-select"');
+ expect(source).toContain('class="select chip rate"');
+ expect(source).toContain('appearance: none;');
+ expect(source).toContain('font: inherit;');
+ // and it stays the app's dropdown rather than a second kind: same fill, border,
+ // radius and focus ring, one size down
+ expect(source).toContain('border-radius: var(--r-sm);');
+ expect(source).toContain('font-size: var(--fs-xs);');
+ expect(source).toContain('box-shadow: 0 0 0 2px var(--accent-soft);');
+ });
+
+ it('names the neighbour in its own class, clear of the form-label utility', () => {
+ // app.css's `.label` upper-cases and shrinks whatever wears it, so a filename in
+ // a relation row came out as a heading
+ expect(source).toContain('<span class="name">');
+ expect(source).not.toContain('class="label"');
+ });
+
+ it('colours the dropdown itself, which the browser draws from the control', () => {
+ // a chip left transparent opened white-on-white in dark mode
+ expect(source).toContain('.chip option {');
+ expect(source).toContain('background-color: var(--bg-1);');
+ });
+});
+
+describe('how sure of one relation', () => {
+ it('rates an edge through the link patch, and clears with null not a level', () => {
+ // absent is a state to return to, so '' sends null rather than being left out of
+ // the body — a level picked by mistake must not be a hole
+ expect(source).toContain("const value = raw === '' ? null : Number(raw);");
+ expect(source).toContain('{ confidence: value }');
+ });
+
+ it('offers the levels the registry serves rather than a list of its own', () => {
+ expect(source).toContain('{#each confidenceLevels() as level (level.value)}');
+ expect(source).toContain('<option value="">Not assessed</option>');
+ });
+
+ it('shows no control where the API would refuse one', () => {
+ // a derivation carries no rating, and a suggestion is reviewed before it is rated
+ expect(source).toContain(
+ '{#if !older && !suggested && isRatable(relation.link.type) && confidenceLevels().length}'
+ );
+ });
+
+ it('keeps a ruled-out candidate in the list, dimmed rather than struck out', () => {
+ // the elimination is the finding: eleven ruled out and one probable is what the
+ // panel has to be able to show at a glance
+ expect(source).toContain('class:refuted={rating === -1}');
+ expect(source).toContain('.relation.refuted .subject .name {');
+ expect(source).not.toContain('text-decoration: line-through');
+ });
+
+ it('stays quiet until it holds a level, since unrated is the common case', () => {
+ expect(source).toContain('class:set={rating !== null}');
+ expect(source).toContain('class:out={rating === -1}');
+ });
+});
+
+describe('the vocabulary explains itself', () => {
+ it('says what the verb means, from the registry rather than from here', () => {
+ // "is part of" against "owns" is the distinction an order of battle turns on,
+ // and neither word says it on its own
+ expect(source).toContain("title={relationHint(relation.link.type) || 'What this relation states'}");
+ expect(source).toContain('<span class="chip verb" title={relationHint(relation.link.type)}>');
+ });
+
+ it('places the rating on the scale rather than repeating its own label', () => {
+ expect(source).toContain('confidenceHint(rating) || confidenceLabel(rating)');
+ });
+});
+
+describe('how reliable the source is', () => {
+ it('reads the grade off the neighbour, in the registry’s words', () => {
+ // the letters are data, and the key is the contract — the same split as the
+ // confidence levels, which are served rather than spelled here
+ expect(source).toContain("import { loadEntityTypes, reliabilityOf } from '../lib/entityTypes.svelte.js'");
+ expect(source).toContain('{@const source = reliabilityOf(relation.entity)}');
+ expect(source).not.toMatch(/Usually reliable|Admiralty/);
+ });
+
+ it('never folds it into the edge’s rating', () => {
+ // the whole point of the Admiralty scheme: two axes, never one number. So the
+ // grade sits on the line carrying the entity's name, and the rating on the line
+ // below carrying the edge's verb — no expression ever holds both.
+ const head = source.slice(source.indexOf('<div class="head">'), source.indexOf('<div class="says">'));
+ expect(head).toContain('title={`Source reliability: ${source.label}`}');
+ expect(head).not.toMatch(/\{[^}]*\brating\b/);
+ const says = source.slice(source.indexOf('<div class="says">'), source.indexOf('{/each}'));
+ expect(says).not.toContain('source.grade');
+ });
+
+ it('shows nothing at all for an ungraded source', () => {
+ // absence is never flagged: most sources are never graded, and a "not assessed"
+ // badge on each of them is how an optional field becomes a chore
+ expect(source).toContain('{#if source}');
+ expect(source).not.toContain('Ungraded');
+ });
+
+ it('states the grade rather than offering it, since it belongs to that entity', () => {
+ // it is edited in the source's own panel; a dropdown here would suggest this row
+ // is what carries it
+ expect(source).toContain('<span class="grade"');
+ expect(source).not.toContain('class="select chip grade"');
+ });
+
+ it('loads the entity registry itself, since two of its three homes do not', () => {
+ expect(source).toContain('loadEntityTypes();');
+ });
+});
+
+describe('a pointer sits under its own heading', () => {
+ it('takes the split from the registry rather than naming a verb here', () => {
+ // which verbs head their own section is `links.RelationType.group`; a component
+ // that knew "mentions" by name would have to be edited for the next one
+ expect(source).toContain('relationGroup(relation.link.type)');
+ expect(source).toContain('<p class="group">{section.group}</p>');
+ // no verb is named in the code itself: the split is registry data
+ expect(source).not.toContain("=== 'mentions'");
+ expect(source).not.toContain("'Mentions'");
+ });
+
+ it('leaves the heading to a list that runs several actions together', () => {
+ // a host that asked for one action has already named it above the list, and
+ // the section drawing its own heading over its own rows said the word twice
+ expect(source).toContain("actionFilter ? '' : relationGroup(relation.link.type)");
+ });
+
+ it('keeps the ungrouped rows first and unheaded, so the common list is unchanged', () => {
+ // the map is seeded with the empty group, which is what fixes that order
+ expect(source).toContain("const groups = new Map([['', []]]);");
+ expect(source).toContain('{#if section.group}');
+ });
+
+ it('draws every row through one body, headed or not', () => {
+ // a second copy of the row markup under the heading is how the two kinds of
+ // statement start offering different gestures
+ expect(source).toContain('{#snippet row(relation)}');
+ expect((source.match(/\{@render row\(relation\)\}/g) ?? []).length).toBe(1);
+ });
+
+ it('shows the directed mention reading without a confidence control', () => {
+ expect(source).toContain("{@const action = relationAction(relation.link.type)}");
+ expect(source).toContain("class:mention={action === 'mention'}");
+ expect(source).toContain("{:else if action === 'mention'}");
+ expect(source).toContain('{relationReading(relation.link.type, relation.direction)}');
+ });
+
+ it('leaves an older out-of-matrix connection removable but not editable', () => {
+ expect(source).toContain('const legacy = (relation) => !isCurrentConnection');
+ expect(source).toContain('{#if older}');
+ expect(source).toContain('<span class="older">Older connection</span>');
+ });
});
diff --git a/frontend/src/components/RelationPicker.svelte b/frontend/src/components/RelationPicker.svelte
index 2914131..468d66d 100644
--- a/frontend/src/components/RelationPicker.svelte
+++ b/frontend/src/components/RelationPicker.svelte
@@ -3,7 +3,7 @@
* State one relation by hand: pick the other entity, then how it reads.
*
* A collected value rather than an action, because the subject often does not
- * exist yet — the Satellite save gate lets the analyst say "this photo was shot
+ * exist yet — the Satellite save gate lets the analyst say "this photo was recorded
* here" while filling in a place the case has never held. The host files the
* choice with `saveRelation` once it has both ends.
*
@@ -13,33 +13,103 @@
import { api } from '../lib/api.js';
import { buildCatalogQuery } from '../lib/catalog.js';
import { caseState } from '../lib/state.svelte.js';
- import { loadRelationTypes, relatableTypes, relationOptions } from '../lib/relations.svelte.js';
+ import {
+ loadRelationTypes,
+ relatableTypes,
+ relationHint,
+ relationOptions,
+ } from '../lib/relations.svelte.js';
+ import { entityLabel, loadEntityTypes } from '../lib/entityTypes.svelte.js';
+ import { entityIcon } from '../lib/entityIcon.js';
import Icon from './Icon.svelte';
import SearchInput from './SearchInput.svelte';
let {
subjectType, // entity type the relation is being stated about
+ subject = null, // full entity when media-kind rules or self-filtering matter
+ subjectId = null,
+ action = 'relation', // regular relation or the separate mention gesture
+ relationType = null, // fixed connector, used by the Claim editor
+ expanded = false, // Details opens this as a small, explicit composer
+ busy = false,
+ oncommit = null,
+ oncancel = null,
value = $bindable(null), // { entityId, label, entityType, type, direction } | null
} = $props();
- const PAGE = 8; // a short page: this is a picker, not a browser
- const ENTITY_ICON = {
- media: 'media', capture: 'satellite', place: 'pin', proof: 'proof',
- post: 'post', 'inspect-session': 'inspect', note: 'note', bookmark: 'link',
- };
-
+ const FETCH = 500; // one bounded catalog page, displayed inside the scroll area
loadRelationTypes();
+ loadEntityTypes(); // the icons come from the entity registry, not a map kept here
let query = $state('');
let results = $state([]);
let open = $state(false);
let searching = $state(false);
+ let committing = $state(false);
let seq = 0;
- const types = $derived(relatableTypes(subjectType));
+ $effect(() => {
+ if (expanded) open = true;
+ });
+
+ const subjectEnd = $derived(subject ?? subjectType);
+ const types = $derived(relatableTypes(subjectEnd, action));
+ const actionLabel = $derived(action === 'mention' ? 'Add mention' : 'Add relation');
+ const clearLabel = $derived(action === 'mention' ? 'Clear mention' : 'Clear relation');
+ const commitBusy = $derived(busy || committing);
+
+ /** What this subject may be related to, in words.
+ *
+ * An empty result used to read as "nothing can be related here", where the truth
+ * is usually "the case holds none of the types this one joins" — a proof relates
+ * to an account or a claim, and a case that has neither shows an empty list with
+ * no way to know that. The vocabulary is directed and typed on purpose, so the
+ * surface has to say what it is waiting for.
+ */
+ const accepted = $derived(
+ types
+ .map((type) => entityLabel(type))
+ .sort((a, b) => a.localeCompare(b))
+ .join(', ')
+ );
// The chosen entity decides which verbs are available: a place accepts "was
- // shot at" from a photo, and nothing at all from another place.
- const options = $derived(value ? relationOptions(subjectType, value.entityType) : []);
+ // recorded at" from a photo, and nothing at all from another place.
+ const options = $derived(
+ value
+ ? relationOptions(subjectEnd, { type: value.entityType, attrs: value.attrs }, action)
+ .filter((option) => !relationType || option.type === relationType)
+ : []
+ );
+ // The same split the relation list draws, on the control that states the edge:
+ // the registry says which verbs head their own section, nothing here does.
+ const verbGroups = $derived.by(() => {
+ const groups = new Map();
+ for (const option of options) {
+ const group = option.group ?? '';
+ if (!groups.has(group)) groups.set(group, []);
+ groups.get(group).push(option);
+ }
+ return [...groups].map(([group, list]) => ({ group, options: list }));
+ });
+
+ /** Keep the compact first page representative when several target types are
+ * legal. Without this, eight people could hide the only Network from an IP
+ * until the analyst already knew what to search for. A typed search keeps the
+ * server's relevance order instead. */
+ function visibleResults(items, term) {
+ if (term) return items;
+ const firstByType = [];
+ const rest = [];
+ const seen = new Set();
+ for (const entity of items) {
+ if (seen.has(entity.type)) rest.push(entity);
+ else {
+ seen.add(entity.type);
+ firstByType.push(entity);
+ }
+ }
+ return [...firstByType, ...rest];
+ }
$effect(() => {
const caseId = caseState.current?.id;
@@ -49,10 +119,16 @@
const mine = ++seq;
searching = true;
api
- .get(buildCatalogQuery(caseId, { types: wanted, query: term, limit: PAGE }))
+ .get(buildCatalogQuery(caseId, { types: wanted, query: term, limit: FETCH }))
.then((page) => {
if (mine !== seq) return; // a newer keystroke already answered
- results = page.items ?? [];
+ const compatible = (page.items ?? [])
+ .filter((entity) => entity.id !== subjectId)
+ .filter((entity) =>
+ relationOptions(subjectEnd, entity, action)
+ .some((option) => !relationType || option.type === relationType)
+ );
+ results = visibleResults(compatible, term);
})
.catch(() => {
if (mine === seq) results = [];
@@ -63,12 +139,14 @@
});
function choose(entity) {
- const [first] = relationOptions(subjectType, entity.type);
+ const [first] = relationOptions(subjectEnd, entity, action)
+ .filter((option) => !relationType || option.type === relationType);
if (!first) return; // the vocabulary has no reading for this pair
value = {
entityId: entity.id,
label: entity.label,
entityType: entity.type,
+ attrs: entity.attrs ?? {},
type: first.type,
direction: first.direction,
};
@@ -77,47 +155,111 @@
}
function setType(event) {
- const picked = options.find((o) => o.type === event.currentTarget.value);
+ const picked = options.find(
+ (option) => `${option.type}:${option.direction}` === event.currentTarget.value
+ );
if (picked) value = { ...value, type: picked.type, direction: picked.direction };
}
+
+ function cancel() {
+ value = null;
+ query = '';
+ open = false;
+ oncancel?.();
+ }
+
+ async function commit() {
+ if (!value || !oncommit || commitBusy) return;
+ committing = true;
+ try {
+ await oncommit(value);
+ } catch {
+ // The host reports the error. Keep the choice so it can be tried again.
+ } finally {
+ committing = false;
+ }
+ }
</script>
{#if types.length}
- <div class="picker">
+ <div class="picker" class:composer={expanded}>
{#if value}
<div class="chosen">
- <Icon name={ENTITY_ICON[value.entityType] ?? 'file'} size={13} />
+ <Icon name={entityIcon({ type: value.entityType })} size={13} />
<span class="chosen-label" title={value.label}>{value.label}</span>
- {#if options.length > 1}
- <select class="select verb-select" value={value.type} onchange={setType}>
- {#each options as option (option.type)}
- <option value={option.type}>{option.label}</option>
+ {#if action !== 'mention' && options.length > 1}
+ <select
+ class="select verb-select"
+ value={`${value.type}:${value.direction}`}
+ title={relationHint(value.type)}
+ onchange={setType}
+ >
+ <!-- Headed verbs sit under their heading here too, so the reading the
+ analyst picks is already sorted into what it will look like in the
+ list below. -->
+ {#each verbGroups as verbs (verbs.group)}
+ {#if verbs.group}
+ <optgroup label={verbs.group}>
+ {#each verbs.options as option (`${option.type}:${option.direction}`)}
+ <option value={`${option.type}:${option.direction}`}>{option.label}</option>
+ {/each}
+ </optgroup>
+ {:else}
+ {#each verbs.options as option (`${option.type}:${option.direction}`)}
+ <option value={`${option.type}:${option.direction}`}>{option.label}</option>
+ {/each}
+ {/if}
{/each}
</select>
- {:else}
+ {:else if action !== 'mention'}
<span class="verb">{options[0]?.label ?? value.type}</span>
{/if}
- <button class="btn btn-ghost btn-sm" title="Remove this relation" onclick={() => (value = null)}>
+ <button class="btn btn-ghost btn-sm" title={clearLabel} onclick={() => { value = null; open = true; }}>
<Icon name="x" size={12} />
</button>
</div>
+ {#if expanded}
+ <div class="composer-actions">
+ <button class="btn btn-ghost btn-sm" onclick={cancel}>Cancel</button>
+ <button class="btn btn-primary btn-sm" disabled={commitBusy} onclick={commit}>
+ {commitBusy ? 'Adding…' : actionLabel}
+ </button>
+ </div>
+ {/if}
{:else if open}
- <SearchInput bind:value={query} placeholder="Search the case…" width="100%" />
+ <div class="search-row">
+ <SearchInput bind:value={query} placeholder="Search the case…" width="100%" />
+ {#if expanded}
+ <button class="btn btn-ghost btn-sm" title="Close" onclick={cancel}>
+ <Icon name="x" size={12} />
+ </button>
+ {/if}
+ </div>
<div class="results">
{#each results as entity (entity.id)}
<button class="result" onclick={() => choose(entity)}>
- <Icon name={ENTITY_ICON[entity.type] ?? 'file'} size={12} />
+ <Icon name={entityIcon(entity)} size={12} />
<span class="result-label">{entity.label}</span>
<span class="result-type">{entity.type}</span>
</button>
{/each}
{#if !results.length}
- <p class="hint">{searching ? 'Searching…' : 'Nothing to relate here yet.'}</p>
+ <p class="hint">
+ {#if searching}
+ Searching…
+ {:else if query.trim()}
+ Nothing matches.
+ {:else if accepted}
+ This case holds no {accepted} to {action === 'mention' ? 'mention' : 'relate this to'}.
+ {:else}
+ Nothing in the vocabulary relates to this.
+ {/if}
+ </p>
{/if}
</div>
- {:else}
+ {:else if !expanded}
<button class="btn btn-sm add" onclick={() => (open = true)}>
- <Icon name="link" size={13} /> Relate to…
+ <Icon name="link" size={13} /> {actionLabel}
</button>
{/if}
</div>
@@ -130,6 +272,25 @@
gap: 6px;
min-width: 0;
}
+ .picker.composer {
+ gap: 8px;
+ padding-top: 9px;
+ border-top: 1px solid var(--border);
+ }
+ .search-row,
+ .composer-actions {
+ display: flex;
+ align-items: center;
+ gap: 6px;
+ min-width: 0;
+ }
+ .search-row :global(.search-input) {
+ flex: 1;
+ min-width: 0;
+ }
+ .composer-actions {
+ justify-content: flex-end;
+ }
.add {
align-self: flex-start;
}
diff --git a/frontend/src/components/RelationPicker.test.js b/frontend/src/components/RelationPicker.test.js
index e16dc58..5d0dd01 100644
--- a/frontend/src/components/RelationPicker.test.js
+++ b/frontend/src/components/RelationPicker.test.js
@@ -5,7 +5,7 @@ const source = readFileSync(new URL('./RelationPicker.svelte', import.meta.url),
describe('RelationPicker', () => {
it('collects a choice instead of filing it, because the subject may not exist yet', () => {
- // the Satellite save gate states "this photo was shot here" while filling in
+ // the Satellite save gate states "this photo was recorded here" while filling in
// a place the case has never held
expect(source).toContain('value = $bindable(null)');
expect(source).not.toContain('api.post');
@@ -14,9 +14,16 @@ describe('RelationPicker', () => {
});
it('searches only the entity types the vocabulary accepts for this subject', () => {
- expect(source).toContain('relatableTypes(subjectType)');
- expect(source).toContain('buildCatalogQuery(caseId, { types: wanted, query: term, limit: PAGE })');
- expect(source).toContain('const PAGE = 8');
+ expect(source).toContain('relatableTypes(subjectEnd, action)');
+ expect(source).toContain('buildCatalogQuery(caseId, { types: wanted, query: term, limit: FETCH })');
+ expect(source).toContain('const FETCH = 500');
+ expect(source).not.toContain('.slice(0, PAGE)');
+ });
+
+ it('keeps one target of each compatible type on the compact first page', () => {
+ expect(source).toContain('function visibleResults(items, term)');
+ expect(source).toContain('if (seen.has(entity.type)) rest.push(entity);');
+ expect(source).toContain('results = visibleResults(compatible, term);');
});
it('drops a stale page rather than letting it overwrite a newer keystroke', () => {
@@ -25,12 +32,78 @@ describe('RelationPicker', () => {
});
it('lets the analyst pick the reading when the pair has more than one', () => {
- expect(source).toContain('relationOptions(subjectType, value.entityType)');
- expect(source).toContain('{#if options.length > 1}');
+ expect(source).toContain('relationOptions(subjectEnd, { type: value.entityType, attrs: value.attrs }, action)');
+ expect(source).toContain("{#if action !== 'mention' && options.length > 1}");
expect(source).toContain('{option.label}');
+ expect(source).toContain('`${option.type}:${option.direction}` === event.currentTarget.value');
+ expect(source).toContain('value={`${value.type}:${value.direction}`}');
});
it('shows nothing at all when the subject can hold no relation', () => {
expect(source).toContain('{#if types.length}');
});
});
+
+describe('relations and mentions are separate gestures', () => {
+ it('filters the vocabulary before it searches or chooses a verb', () => {
+ expect(source).toContain("action = 'relation'");
+ expect(source).toContain('relationOptions(subjectEnd, entity, action)');
+ });
+
+ it('uses distinct add and clear labels for a mention', () => {
+ expect(source).toContain("action === 'mention' ? 'Add mention' : 'Add relation'");
+ expect(source).toContain("action === 'mention' ? 'Clear mention' : 'Clear relation'");
+ expect(source).not.toContain('Relate to…');
+ });
+
+ it('can commit immediately when Details opens it as a composer', () => {
+ expect(source).toContain('expanded = false');
+ expect(source).toContain('oncommit = null');
+ expect(source).toContain('await oncommit(value)');
+ expect(source).toContain("{commitBusy ? 'Adding…' : actionLabel}");
+ });
+
+ it('does not show a verb on a mention pointer', () => {
+ expect(source).toContain("{#if action !== 'mention' && options.length > 1}");
+ expect(source).toContain("{:else if action !== 'mention'}");
+ });
+});
+
+describe('an empty result says what it was waiting for', () => {
+ it('names the types this subject may be related to', () => {
+ // "Nothing to relate here yet" read as "nothing can be related here", where the
+ // truth is that the case holds none of the types this one joins
+ expect(source).toContain("{action === 'mention' ? 'mention' : 'relate this to'}");
+ expect(source).toContain('const accepted = $derived(');
+ expect(source).toContain('entityLabel(type)');
+ });
+
+ it('separates a case with none of them from a search that matched none', () => {
+ expect(source).toContain('{:else if query.trim()}');
+ expect(source).toContain('Nothing matches.');
+ });
+
+ it('keeps the last word for a subject the vocabulary joins to nothing at all', () => {
+ expect(source).toContain('Nothing in the vocabulary relates to this.');
+ });
+});
+
+describe('the verb menu is split the way the list is', () => {
+ it('offers a headed verb under its heading, from the registry', () => {
+ expect(source).toContain('<optgroup label={verbs.group}>');
+ expect(source).toContain("const group = option.group ?? '';");
+ expect(source).not.toContain('Mentions');
+ });
+
+ it('files the first reading, which relationOptions has already ordered', () => {
+ // the picker never re-sorts: the ordering rule lives in the shared registry so
+ // the list and this control cannot disagree about what a pair mainly says
+ expect(source).toContain('const [first] = relationOptions(subjectEnd, entity, action)');
+ expect(source).not.toContain('options.sort(');
+ });
+
+ it('can lock a Claim picker to one connector', () => {
+ expect(source).toContain('relationType = null');
+ expect(source).toContain('!relationType || option.type === relationType');
+ });
+});
diff --git a/frontend/src/components/SnapshotDetails.svelte b/frontend/src/components/SnapshotDetails.svelte
new file mode 100644
index 0000000..7e23aad
--- /dev/null
+++ b/frontend/src/components/SnapshotDetails.svelte
@@ -0,0 +1,105 @@
+<script>
+ /** Read-only detail for an entity copied into an analysis snapshot. */
+ import { entityIcon } from '../lib/entityIcon.js';
+ import { entityLabel } from '../lib/entityTypes.svelte.js';
+ import { loadRelationTypes, relationVerb } from '../lib/relations.svelte.js';
+ import Icon from './Icon.svelte';
+
+ loadRelationTypes();
+
+ let { entity, entities = [], links = [] } = $props();
+
+ const byId = $derived(new Map(entities.map((item) => [item.id, item])));
+ const relations = $derived(
+ links.filter((link) => link.from === entity.id || link.to === entity.id)
+ );
+ const fields = $derived(
+ Object.entries(entity.attrs ?? {}).filter(([, value]) => value != null && value !== '')
+ );
+ const label = (key) => key.replaceAll('_', ' ').replace(/^./, (letter) => letter.toUpperCase());
+ const value = (held) =>
+ typeof held === 'object' ? JSON.stringify(held, null, 2) : String(held);
+</script>
+
+<div class="snapshot-detail">
+ <p class="notice"><Icon name="clock" size={13} /> Captured data. Nothing here edits the case.</p>
+
+ <header>
+ <Icon name={entityIcon(entity)} size={22} />
+ <div>
+ <h3>{entity.label}</h3>
+ <p>{entityLabel(entity.type)}</p>
+ </div>
+ </header>
+
+ {#if entity.snapshot_images?.length}
+ <section>
+ <h4>Captured photos</h4>
+ <div class="photos">
+ {#each entity.snapshot_images as image (image.id)}
+ <figure>
+ <img src={image.data} alt={image.title} />
+ <figcaption>{image.title}</figcaption>
+ </figure>
+ {/each}
+ </div>
+ </section>
+ {/if}
+
+ {#if fields.length}
+ <section>
+ <h4>Fields</h4>
+ <dl>
+ {#each fields as [key, held] (key)}
+ <div><dt>{label(key)}</dt><dd><pre>{value(held)}</pre></dd></div>
+ {/each}
+ </dl>
+ </section>
+ {/if}
+
+ <section>
+ <h4>Provenance</h4>
+ <dl>
+ {#if entity.provenance?.by}<div><dt>Filed by</dt><dd>{entity.provenance.by}</dd></div>{/if}
+ {#if entity.provenance?.at}<div><dt>Filed at</dt><dd>{entity.provenance.at}</dd></div>{/if}
+ {#if entity.provenance?.status}<div><dt>Status</dt><dd>{entity.provenance.status}</dd></div>{/if}
+ {#if entity.provenance?.source}<div><dt>Source</dt><dd>{entity.provenance.source}</dd></div>{/if}
+ </dl>
+ </section>
+
+ {#if relations.length}
+ <section>
+ <h4>Captured relations</h4>
+ <ul>
+ {#each relations as relation (relation.id)}
+ {@const otherId = relation.from === entity.id ? relation.to : relation.from}
+ <li>
+ <span>{relation.from === entity.id ? relationVerb(relation.type) : 'linked from'}</span>
+ <strong>{byId.get(otherId)?.label ?? otherId}</strong>
+ </li>
+ {/each}
+ </ul>
+ </section>
+ {/if}
+</div>
+
+<style>
+ .snapshot-detail { display: grid; gap: 16px; }
+ .notice { display: flex; align-items: center; gap: 6px; margin: 0; padding: 8px 10px; border-radius: var(--r-sm); background: var(--accent-soft); color: var(--text-2); font-size: var(--fs-xs); }
+ header { display: flex; align-items: center; gap: 10px; }
+ h3, h4, p { margin: 0; }
+ header p { margin-top: 2px; color: var(--text-3); font-size: var(--fs-sm); }
+ h4 { margin-bottom: 8px; color: var(--text-2); font-size: var(--fs-xs); text-transform: uppercase; letter-spacing: .04em; }
+ .photos { display: grid; grid-template-columns: repeat(auto-fill, minmax(110px, 1fr)); gap: 8px; }
+ figure { margin: 0; }
+ img { width: 100%; aspect-ratio: 4 / 3; object-fit: cover; border-radius: var(--r-sm); background: var(--bg-0); }
+ figcaption { margin-top: 3px; overflow: hidden; color: var(--text-3); font-size: var(--fs-xs); text-overflow: ellipsis; white-space: nowrap; }
+ dl { display: grid; gap: 1px; margin: 0; }
+ dl > div { display: grid; grid-template-columns: 120px minmax(0, 1fr); gap: 10px; padding: 7px 0; border-bottom: 1px solid var(--border); }
+ dt { color: var(--text-3); font-size: var(--fs-xs); }
+ dd { min-width: 0; margin: 0; color: var(--text-1); font-size: var(--fs-sm); }
+ pre { margin: 0; overflow-wrap: anywhere; white-space: pre-wrap; font: inherit; }
+ ul { margin: 0; padding: 0; list-style: none; }
+ li { display: flex; gap: 8px; padding: 6px 0; border-bottom: 1px solid var(--border); font-size: var(--fs-sm); }
+ li span { color: var(--text-3); }
+</style>
diff --git a/frontend/src/components/SnapshotDetails.test.js b/frontend/src/components/SnapshotDetails.test.js
new file mode 100644
index 0000000..ba948e3
--- /dev/null
+++ b/frontend/src/components/SnapshotDetails.test.js
@@ -0,0 +1,19 @@
+import { describe, expect, it } from 'vitest';
+import { readFileSync } from 'node:fs';
+
+const source = readFileSync(new URL('./SnapshotDetails.svelte', import.meta.url), 'utf8');
+
+describe('snapshot details', () => {
+ it('states the read-only boundary and shows every captured layer', () => {
+ expect(source).toContain('Captured data. Nothing here edits the case.');
+ expect(source).toContain('Captured photos');
+ expect(source).toContain('Object.entries(entity.attrs ?? {})');
+ expect(source).toContain('Provenance');
+ expect(source).toContain('Captured relations');
+ });
+
+ it('renders embedded previews instead of reaching back into live case files', () => {
+ expect(source).toContain('<img src={image.data}');
+ expect(source).not.toContain('fileUrl');
+ });
+});
diff --git a/frontend/src/components/TemporalClaimEditor.svelte b/frontend/src/components/TemporalClaimEditor.svelte
new file mode 100644
index 0000000..3e90426
--- /dev/null
+++ b/frontend/src/components/TemporalClaimEditor.svelte
@@ -0,0 +1,198 @@
+<script>
+ /** One editor for creating or revising a Temporal Claim from Time or Timeline. */
+ import { api } from '../lib/api.js';
+ import { toast } from '../lib/state.svelte.js';
+ import TemporalInput from './TemporalInput.svelte';
+ import TemporalTargetPicker from './TemporalTargetPicker.svelte';
+
+ let {
+ caseId,
+ item = null,
+ subject = null,
+ initialWhen = '',
+ initialStatement = '',
+ initialRole = '',
+ onsaved,
+ oncancel,
+ } = $props();
+
+ let statement = $state('');
+ let when = $state('');
+ let timeRole = $state('');
+ let confidence = $state('');
+ let method = $state('');
+ let verbatim = $state('');
+ let about = $state([]);
+ let places = $state([]);
+ let cites = $state([]);
+ let loading = $state(false);
+ let saving = $state(false);
+ let whenValid = $state(true);
+ let seeded = false;
+
+ const lockedAbout = $derived(subject ? [subject] : []);
+
+ $effect(() => {
+ if (seeded) return;
+ seeded = true;
+ statement = item?.label ?? initialStatement;
+ when = item?.raw ?? initialWhen;
+ timeRole = item?.time_role ?? initialRole;
+ confidence = item?.confidence ?? '';
+ });
+
+ $effect(() => {
+ if (!item?.owner_id || !caseId) return;
+ let live = true;
+ loading = true;
+ api
+ .get(`/api/cases/${caseId}/entities/${item.owner_id}/chain`)
+ .then((chain) => {
+ if (!live) return;
+ statement = chain.entity.label ?? item.label;
+ when = chain.entity.attrs?.when ?? item.raw ?? '';
+ timeRole = chain.entity.attrs?.time_role ?? item.time_role ?? '';
+ confidence = chain.entity.attrs?.confidence ?? item.confidence ?? '';
+ method = chain.entity.attrs?.method ?? '';
+ verbatim = chain.entity.attrs?.verbatim ?? '';
+ const choices = (type) =>
+ (chain.relations ?? [])
+ .filter((row) => row.direction === 'out' && row.link.type === type)
+ .map((row) => ({ id: row.entity.id, label: row.entity.label, type: row.entity.type }));
+ about = choices('about').filter((choice) => choice.id !== subject?.id);
+ places = choices('at');
+ cites = choices('cites');
+ })
+ .catch((error) => toast(error.message, 'danger'))
+ .finally(() => { if (live) loading = false; });
+ return () => { live = false; };
+ });
+
+ async function save() {
+ const text = statement.trim();
+ if (!text || !whenValid || saving) return;
+ saving = true;
+ const body = {
+ statement: text,
+ when: when || null,
+ time_role: timeRole || null,
+ confidence: confidence || null,
+ method: method.trim() || null,
+ verbatim: verbatim.trim() || null,
+ about: [...new Set([...lockedAbout.map((entry) => entry.id), ...about.map((entry) => entry.id)])],
+ at: places.map((entry) => entry.id),
+ cites: cites.map((entry) => entry.id),
+ };
+ try {
+ const saved = item
+ ? await api.patch(`/api/cases/${caseId}/timeline/claims/${item.owner_id}`, body)
+ : await api.post(`/api/cases/${caseId}/timeline/claims`, body);
+ toast(item ? 'Time assessment updated' : 'Time assessment added', 'ok', 1800);
+ onsaved?.(saved);
+ } catch (error) {
+ toast(error.message, 'danger');
+ } finally {
+ saving = false;
+ }
+ }
+</script>
+
+<div class="claim-editor">
+ {#if loading}
+ <div class="loading">Loading assessment…</div>
+ {/if}
+
+ <label class="modal-label" for="temporal-statement">Statement</label>
+ <textarea
+ id="temporal-statement"
+ class="textarea"
+ rows="2"
+ bind:value={statement}
+ maxlength="300"
+ placeholder="What happened or was observed?"
+ ></textarea>
+
+ <label class="modal-label" for="temporal-when">When</label>
+ <TemporalInput
+ id="temporal-when"
+ value={when}
+ onchange={(value) => (when = value)}
+ onvaliditychange={(reading) => (whenValid = reading.valid)}
+ />
+
+ <div class="two-cols">
+ <label>
+ <span class="modal-label">Time role</span>
+ <select class="select" bind:value={timeRole}>
+ <option value="">Not specified</option>
+ <option value="occurred">Occurred</option>
+ <option value="observed">Observed</option>
+ <option value="valid">Valid during</option>
+ </select>
+ </label>
+ <label>
+ <span class="modal-label">Confidence</span>
+ <select class="select" bind:value={confidence}>
+ <option value="">Not assessed</option>
+ <option value="certain">Certain</option>
+ <option value="probable">Probable</option>
+ <option value="possible">Possible</option>
+ <option value="refuted">Refuted</option>
+ </select>
+ </label>
+ </div>
+
+ <section class="connections">
+ <TemporalTargetPicker
+ {caseId}
+ relationType="about"
+ label="About"
+ hint="Who or what this statement concerns"
+ bind:selected={about}
+ locked={lockedAbout}
+ />
+ <TemporalTargetPicker
+ {caseId}
+ relationType="at"
+ label="Place"
+ hint="Where this happened or was observed"
+ bind:selected={places}
+ />
+ <TemporalTargetPicker
+ {caseId}
+ relationType="cites"
+ label="Evidence"
+ hint="Files, notes or statements supporting this date"
+ bind:selected={cites}
+ />
+ </section>
+
+ <details class="reasoning">
+ <summary>Reasoning and source wording</summary>
+ <label class="modal-label" for="temporal-method">How this was worked out</label>
+ <textarea id="temporal-method" class="textarea" rows="3" bind:value={method}></textarea>
+ <label class="modal-label" for="temporal-verbatim">As the source put it</label>
+ <textarea id="temporal-verbatim" class="textarea" rows="3" bind:value={verbatim}></textarea>
+ </details>
+
+ <div class="actions">
+ <button class="btn btn-ghost" onclick={oncancel}>Cancel</button>
+ <button class="btn btn-primary" disabled={!statement.trim() || !whenValid || saving || loading} onclick={save}>
+ {saving ? 'Saving…' : item ? 'Update assessment' : 'Add assessment'}
+ </button>
+ </div>
+</div>
+
+<style>
+ .claim-editor { display: grid; gap: 8px; min-width: 0; }
+ .loading { padding: 7px 9px; border-radius: var(--r-sm); background: var(--bg-2); color: var(--text-3); }
+ .two-cols { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 10px; }
+ .two-cols label { display: grid; gap: 4px; }
+ .connections { display: grid; gap: 12px; margin-top: 5px; padding-top: 12px; border-top: 1px solid var(--border); }
+ .reasoning { margin-top: 4px; border: 1px solid var(--border); border-radius: var(--r-sm); }
+ .reasoning summary { padding: 8px 10px; cursor: pointer; color: var(--text-2); font-weight: 600; }
+ .reasoning[open] { padding: 0 10px 10px; }
+ .reasoning[open] summary { margin: 0 -10px 8px; }
+ .actions { display: flex; justify-content: flex-end; gap: 7px; margin-top: 7px; }
+ @media (max-width: 560px) { .two-cols { grid-template-columns: 1fr; } }
+</style>
diff --git a/frontend/src/components/TemporalClaimEditor.test.js b/frontend/src/components/TemporalClaimEditor.test.js
new file mode 100644
index 0000000..6d5cce3
--- /dev/null
+++ b/frontend/src/components/TemporalClaimEditor.test.js
@@ -0,0 +1,30 @@
+import { describe, expect, it } from 'vitest';
+import { readFileSync } from 'node:fs';
+
+const editor = readFileSync(new URL('./TemporalClaimEditor.svelte', import.meta.url), 'utf8');
+const picker = readFileSync(new URL('./TemporalTargetPicker.svelte', import.meta.url), 'utf8');
+
+describe('temporal Claim editor', () => {
+ it('uses the guided time helper and writes the atomic route', () => {
+ expect(editor).toContain("import TemporalInput from './TemporalInput.svelte'");
+ expect(editor).toContain('<TemporalInput\n id="temporal-when"');
+ expect(editor).toContain('onvaliditychange={(reading) => (whenValid = reading.valid)}');
+ expect(editor).toContain('!whenValid || saving || loading');
+ expect(editor).toContain("api.post(`/api/cases/${caseId}/timeline/claims`, body)");
+ expect(editor).toContain("api.patch(`/api/cases/${caseId}/timeline/claims/${item.owner_id}`, body)");
+ });
+
+ it('keeps Claim confidence separate and allows auditable reasoning', () => {
+ expect(editor).toContain('<span class="modal-label">Confidence</span>');
+ expect(editor).toContain('How this was worked out');
+ expect(editor).toContain('As the source put it');
+ });
+
+ it('gets about, place and evidence targets from the served relation registry', () => {
+ expect(editor).toContain('relationType="about"');
+ expect(editor).toContain('relationType="at"');
+ expect(editor).toContain('relationType="cites"');
+ expect(picker).toContain("relationOptions('claim', entry.type, 'claim')");
+ expect(picker).toContain('buildCatalogQuery(caseId, { types, query: term, limit: 200 })');
+ });
+});
diff --git a/frontend/src/components/TemporalInput.svelte b/frontend/src/components/TemporalInput.svelte
new file mode 100644
index 0000000..270cf26
--- /dev/null
+++ b/frontend/src/components/TemporalInput.svelte
@@ -0,0 +1,328 @@
+<script>
+ import {
+ TEMPORAL_FORMATS,
+ TEMPORAL_MARKERS,
+ TEMPORAL_SYNTAX,
+ readTemporalInput,
+ writeTemporalInput,
+ } from '../lib/temporalInput.js';
+ import { formatTemporalValue } from '../lib/timeline.js';
+
+ let { id, value = '', onchange, onvaliditychange } = $props();
+ let state = $state(readTemporalInput(''));
+ let sent = $state('');
+ const rawValue = $derived(writeTemporalInput(state));
+ const reading = $derived(formatTemporalValue(rawValue));
+
+ $effect(() => {
+ const incoming = value ?? '';
+ if (incoming !== sent) {
+ state = readTemporalInput(incoming);
+ sent = incoming;
+ onvaliditychange?.(formatTemporalValue(incoming));
+ }
+ });
+
+ function emit(patch) {
+ state = { ...state, ...patch };
+ sent = writeTemporalInput(state);
+ onchange?.(sent);
+ onvaliditychange?.(formatTemporalValue(sent));
+ }
+
+ function chooseMode(mode) {
+ if (mode === state.mode) return;
+ if (mode === 'advanced') {
+ emit({ mode, raw: writeTemporalInput(state) });
+ return;
+ }
+ state = readTemporalInput('');
+ emit({ mode });
+ }
+
+ function choosePrecision(precision) {
+ emit({ precision, date: '' });
+ }
+</script>
+
+<div class="temporal-editor">
+ <label class="field format-field">
+ <span>Format</span>
+ <select
+ class="select input-sm format"
+ aria-label="Date format"
+ value={state.mode}
+ onchange={(event) => chooseMode(event.currentTarget.value)}
+ >
+ {#each TEMPORAL_FORMATS as format (format.value)}
+ <option value={format.value}>{format.label}</option>
+ {/each}
+ </select>
+ </label>
+
+ {#if state.mode === 'date'}
+ <div class="parts date-parts">
+ <label class="field precision-field">
+ <span>Precision</span>
+ <select
+ class="select input-sm precision"
+ aria-label="Date precision"
+ value={state.precision}
+ onchange={(event) => choosePrecision(event.currentTarget.value)}
+ >
+ <option value="day">Day</option>
+ <option value="month">Month</option>
+ <option value="year">Year</option>
+ </select>
+ </label>
+ <label class="field date-field">
+ <span>Date</span>
+ <input
+ {id}
+ class="input input-sm mono date-value"
+ type={state.precision === 'day' ? 'date' : state.precision === 'month' ? 'month' : 'number'}
+ min={state.precision === 'year' ? 1 : undefined}
+ max={state.precision === 'year' ? 9998 : undefined}
+ placeholder={state.precision === 'year' ? 'YYYY' : 'Unknown'}
+ value={state.date}
+ oninput={(event) => emit({ date: event.currentTarget.value })}
+ />
+ </label>
+ <label class="field certainty-field">
+ <span>Certainty</span>
+ <select
+ class="select input-sm certainty"
+ aria-label="Date certainty"
+ value={state.certainty}
+ onchange={(event) => emit({ certainty: event.currentTarget.value })}
+ >
+ <option value="">Exact as stated</option>
+ <option value="~">Approximate</option>
+ <option value="?">Uncertain</option>
+ <option value="%">Approximate and uncertain</option>
+ </select>
+ </label>
+ </div>
+ {:else if state.mode === 'timestamp'}
+ <div class="parts timestamp-parts">
+ <label class="field datetime-field">
+ <span>Date and time</span>
+ <input
+ {id}
+ class="input input-sm mono datetime-value"
+ type="datetime-local"
+ step="any"
+ value={state.datetime}
+ oninput={(event) => emit({ datetime: event.currentTarget.value })}
+ />
+ </label>
+ <label class="field zone-field">
+ <span>Timezone</span>
+ <select
+ class="select input-sm zone"
+ aria-label="Timezone"
+ value={state.zone}
+ onchange={(event) => emit({ zone: event.currentTarget.value })}
+ >
+ <option value="local">Unknown</option>
+ <option value="utc">UTC</option>
+ <option value="offset">UTC offset</option>
+ </select>
+ </label>
+ {#if state.zone === 'offset'}
+ <label class="field offset-field">
+ <span>Offset</span>
+ <input
+ class="input input-sm mono offset"
+ aria-label="UTC offset"
+ type="text"
+ value={state.offset}
+ placeholder="+02:00"
+ autocomplete="off"
+ spellcheck="false"
+ oninput={(event) => emit({ offset: event.currentTarget.value })}
+ />
+ </label>
+ {/if}
+ </div>
+ {:else if state.mode === 'range'}
+ <div class="parts range-parts">
+ <label class="field">
+ <span>Start</span>
+ <input
+ {id}
+ class="input input-sm mono"
+ aria-label="Start date"
+ type="date"
+ value={state.start}
+ oninput={(event) => emit({ start: event.currentTarget.value })}
+ />
+ </label>
+ <label class="field">
+ <span>End</span>
+ <input
+ class="input input-sm mono"
+ aria-label="End date"
+ type="date"
+ value={state.end}
+ oninput={(event) => emit({ end: event.currentTarget.value })}
+ />
+ </label>
+ </div>
+ {:else if state.mode === 'time-range'}
+ <div class="parts time-range-parts">
+ <label class="field">
+ <span>Start</span>
+ <input
+ {id}
+ class="input input-sm mono"
+ aria-label="Start time"
+ type="datetime-local"
+ step="any"
+ value={state.startTime}
+ oninput={(event) => emit({ startTime: event.currentTarget.value })}
+ />
+ </label>
+ <label class="field">
+ <span>End</span>
+ <input
+ class="input input-sm mono"
+ aria-label="End time"
+ type="datetime-local"
+ step="any"
+ value={state.endTime}
+ oninput={(event) => emit({ endTime: event.currentTarget.value })}
+ />
+ </label>
+ <label class="field zone-field">
+ <span>Timezone</span>
+ <select class="select input-sm zone" aria-label="Range timezone" value={state.rangeZone} onchange={(event) => emit({ rangeZone: event.currentTarget.value })}>
+ <option value="utc">UTC</option>
+ <option value="offset">UTC offset</option>
+ </select>
+ </label>
+ {#if state.rangeZone === 'offset'}
+ <label class="field offset-field">
+ <span>Offset</span>
+ <input class="input input-sm mono offset" aria-label="Range UTC offset" type="text" value={state.rangeOffset} placeholder="+02:00" autocomplete="off" spellcheck="false" oninput={(event) => emit({ rangeOffset: event.currentTarget.value })} />
+ </label>
+ {/if}
+ </div>
+ {:else}
+ <div class="advanced-editor">
+ <label class="field">
+ <span>Stored value</span>
+ <input
+ {id}
+ class="input input-sm mono advanced"
+ type="text"
+ value={state.raw}
+ placeholder="2026-08~, 2026-08/2026-10"
+ autocomplete="off"
+ spellcheck="false"
+ aria-describedby={`${id}-advanced-guide`}
+ aria-invalid={!reading.valid}
+ oninput={(event) => emit({ raw: event.currentTarget.value })}
+ />
+ </label>
+
+ <details class="syntax-help">
+ <summary>Syntax guide</summary>
+ <section class="advanced-guide" id={`${id}-advanced-guide`} aria-label="Supported date syntax">
+ <header>
+ <h4>Supported syntax</h4>
+ <p>Dates use Azimut's EDTF profile. Times use ISO 8601.</p>
+ </header>
+
+ <div class="format-table" role="table" aria-label="Supported temporal formats">
+ <div class="format-row format-head" role="row">
+ <span role="columnheader">Meaning</span>
+ <span role="columnheader">Pattern</span>
+ <span role="columnheader">Example</span>
+ </div>
+ {#each TEMPORAL_SYNTAX as format (format.meaning)}
+ <div class="format-row" role="row">
+ <span role="cell">{format.meaning}</span>
+ <span role="cell"><code>{format.pattern}</code></span>
+ <span role="cell"><code>{format.example}</code></span>
+ </div>
+ {/each}
+ </div>
+
+ <div class="markers" aria-label="Date markers">
+ {#each TEMPORAL_MARKERS as marker (marker.value)}
+ <span><code>{marker.value}</code> {marker.meaning}</span>
+ {/each}
+ </div>
+
+ <ul class="syntax-rules">
+ <li>Markers follow a year, month or day.</li>
+ <li>Times include seconds.</li>
+ <li>Ranges contain two dates or two zoned times.</li>
+ <li>UTC offsets run from −14:00 to +14:00.</li>
+ </ul>
+ <p>A time without a timezone stays outside the UTC timeline.</p>
+ <p>Open ranges and other EDTF Level 2 forms are not supported.</p>
+ </section>
+ </details>
+ </div>
+ {/if}
+
+ {#if rawValue}
+ <div class="temporal-preview" class:error={!reading.valid} aria-live="polite">
+ <span>{reading.valid ? reading.label : reading.error}</span>
+ {#if reading.valid && reading.qualifiers.length}<small>{reading.qualifiers.join(' · ')}</small>{/if}
+ {#if reading.valid && reading.label !== rawValue}<code>{rawValue}</code>{/if}
+ </div>
+ {/if}
+</div>
+
+<style>
+ .temporal-editor { display: grid; gap: 7px; }
+ .field { min-width: 0; display: grid; gap: 3px; }
+ .field > span { color: var(--text-3); font-size: 10px; }
+ .parts { display: grid; align-items: end; gap: 6px; }
+ .date-parts { grid-template-columns: auto minmax(150px, 1fr) minmax(170px, .8fr); }
+ .timestamp-parts { grid-template-columns: minmax(190px, 1fr) auto auto; }
+ .range-parts { grid-template-columns: repeat(2, minmax(140px, 1fr)); }
+ .time-range-parts { grid-template-columns: repeat(2, minmax(180px, 1fr)) auto auto; }
+ .format-field { justify-self: start; }
+ .format, .precision, .zone { width: max-content; max-width: 100%; }
+ .date-value, .datetime-value, .certainty, .advanced { width: 100%; }
+ .offset { width: 90px; }
+ .advanced-editor { position: relative; display: grid; gap: 5px; }
+ .syntax-help { justify-self: start; }
+ .syntax-help > summary { color: var(--text-2); font-size: var(--fs-xs); cursor: pointer; }
+ .advanced-guide {
+ position: absolute; z-index: 40; top: calc(100% + 5px); left: 0;
+ width: min(610px, calc(100vw - 64px)); max-height: min(360px, 55vh); overflow: auto;
+ padding: 11px; border: 1px solid var(--border-strong); border-radius: var(--r-md);
+ background: var(--bg-1); box-shadow: var(--shadow-2); color: var(--text-3); font-size: var(--fs-xs);
+ }
+ .advanced-guide header { position: sticky; top: -11px; z-index: 1; margin: -11px -11px 0; padding: 11px; background: var(--bg-1); }
+ .advanced-guide h4, .advanced-guide p { margin: 0; }
+ .advanced-guide h4 { color: var(--text-2); font-size: var(--fs-xs); }
+ .advanced-guide header p { margin-top: 3px; }
+ .format-table { margin-top: 8px; border-top: 1px solid var(--border); }
+ .format-row {
+ display: grid; grid-template-columns: minmax(90px, .7fr) minmax(120px, 1fr) minmax(170px, 1.35fr);
+ gap: 8px; padding: 4px 0; border-bottom: 1px solid var(--border); align-items: baseline;
+ }
+ .format-head { color: var(--text-2); font-weight: 600; }
+ .markers { display: flex; flex-wrap: wrap; gap: 6px 14px; margin-top: 8px; }
+ .syntax-rules { margin: 7px 0; padding-left: 18px; line-height: 1.5; }
+ .advanced-guide > p + p { margin-top: 4px; }
+ .temporal-preview {
+ min-width: 0; display: flex; flex-wrap: wrap; align-items: baseline; gap: 5px 9px;
+ padding: 7px 9px; border-left: 2px solid var(--timeline-statement); background: var(--bg-2);
+ color: var(--text-2); font-size: var(--fs-xs);
+ }
+ .temporal-preview small { color: var(--text-3); }
+ .temporal-preview code { margin-left: auto; color: var(--text-3); overflow-wrap: anywhere; }
+ .temporal-preview.error { border-left-color: var(--danger); color: var(--danger); }
+ @media (max-width: 620px) {
+ .date-parts, .timestamp-parts, .range-parts, .time-range-parts { grid-template-columns: 1fr; }
+ .format-field { justify-self: stretch; }
+ .format, .precision, .zone, .offset { width: 100%; }
+ }
+</style>
diff --git a/frontend/src/components/TemporalInput.test.js b/frontend/src/components/TemporalInput.test.js
new file mode 100644
index 0000000..8375c98
--- /dev/null
+++ b/frontend/src/components/TemporalInput.test.js
@@ -0,0 +1,26 @@
+import { describe, expect, it } from 'vitest';
+import { readFileSync } from 'node:fs';
+
+const source = readFileSync(new URL('./TemporalInput.svelte', import.meta.url), 'utf8');
+
+describe('temporal input', () => {
+ it('labels the guided fields and shows a readable preview', () => {
+ expect(source).toContain('<span>Precision</span>');
+ expect(source).toContain('<span>Date</span>');
+ expect(source).toContain('<span>Certainty</span>');
+ expect(source).toContain('class="temporal-preview"');
+ expect(source).toContain('reading.label');
+ });
+
+ it('reports invalid input before save', () => {
+ expect(source).toContain('onvaliditychange?.(formatTemporalValue(sent))');
+ expect(source).toContain('aria-invalid={!reading.valid}');
+ expect(source).toContain('reading.error');
+ });
+
+ it('keeps the full syntax reference out of the form flow', () => {
+ expect(source).toContain('<summary>Syntax guide</summary>');
+ expect(source).toContain('position: absolute');
+ expect(source).toContain('max-height: min(360px, 55vh)');
+ });
+});
diff --git a/frontend/src/components/TemporalTargetPicker.render.test.js b/frontend/src/components/TemporalTargetPicker.render.test.js
new file mode 100644
index 0000000..71de6a6
--- /dev/null
+++ b/frontend/src/components/TemporalTargetPicker.render.test.js
@@ -0,0 +1,156 @@
+// @vitest-environment happy-dom
+import { afterEach, describe, expect, it, vi } from 'vitest';
+import { flushSync, mount, unmount } from 'svelte';
+
+const apiGet = vi.fn();
+const TYPES = [
+ { type: 'place' },
+ { type: 'media' },
+ { type: 'claim' },
+];
+
+vi.mock('../lib/api.js', () => ({ api: { get: apiGet } }));
+vi.mock('../lib/entityTypes.svelte.js', () => ({
+ entityTypes: () => TYPES,
+ loadEntityTypes: () => Promise.resolve(),
+}));
+vi.mock('../lib/relations.svelte.js', () => ({
+ loadRelationTypes: () => Promise.resolve(),
+ relationOptions: (_subject, other, action) =>
+ action === 'claim' && ['place', 'media'].includes(other)
+ ? [{ type: 'about', direction: 'out' }]
+ : [],
+}));
+vi.mock('../lib/entityIcon.js', () => ({ entityIcon: () => 'pin' }));
+
+const { default: TemporalTargetPicker } = await import('./TemporalTargetPicker.svelte');
+
+const ROWS = [
+ { id: 'selected', type: 'place', label: 'North quay' },
+ { id: 'locked', type: 'media', label: 'Interview frame' },
+ { id: 'free', type: 'place', label: 'Old warehouse' },
+];
+
+let live = null;
+
+function open(props = {}) {
+ const target = document.createElement('div');
+ document.body.append(target);
+ live = mount(TemporalTargetPicker, {
+ target,
+ props: {
+ caseId: 'case-1',
+ relationType: 'about',
+ label: 'About',
+ hint: 'What the statement concerns',
+ selected: [ROWS[0]],
+ locked: [ROWS[1]],
+ ...props,
+ },
+ });
+ flushSync();
+ return target;
+}
+
+async function settle() {
+ for (let i = 0; i < 5; i += 1) await Promise.resolve();
+ flushSync();
+}
+
+function click(root, text) {
+ const button = [...root.querySelectorAll('button')].find(
+ (candidate) => candidate.textContent.trim() === text
+ );
+ expect(button, `button ${text}`).toBeTruthy();
+ button.click();
+ flushSync();
+ return button;
+}
+
+function type(root, value) {
+ const input = root.querySelector('input[aria-label="Search the case…"]');
+ input.value = value;
+ input.dispatchEvent(new Event('input', { bubbles: true }));
+ flushSync();
+}
+
+afterEach(() => {
+ if (live) unmount(live);
+ live = null;
+ document.body.innerHTML = '';
+ apiGet.mockReset();
+});
+
+describe('TemporalTargetPicker', () => {
+ it('asks only for endpoint types allowed by the served relation registry', async () => {
+ apiGet.mockResolvedValue({ items: [] });
+ const root = open();
+
+ click(root, 'Add');
+ await settle();
+
+ expect(apiGet).toHaveBeenCalledWith(
+ '/api/cases/case-1/catalog/entities?limit=200&type=place%2Cmedia'
+ );
+ expect(root.textContent).toContain('No matching case items');
+ });
+
+ it('keeps locked and selected endpoints unavailable, while adding and removing another', async () => {
+ apiGet.mockResolvedValue({ items: ROWS });
+ const root = open();
+
+ click(root, 'Add');
+ await settle();
+
+ const results = [...root.querySelectorAll('.results > button')];
+ expect(results.map((button) => button.disabled)).toEqual([true, true, false]);
+
+ results[2].click();
+ flushSync();
+ expect(root.querySelector('button[title="Remove Old warehouse"]')).toBeTruthy();
+ expect(results[2].disabled).toBe(true);
+
+ root.querySelector('button[title="Remove Old warehouse"]').click();
+ flushSync();
+ expect(root.querySelector('button[title="Remove Old warehouse"]')).toBeNull();
+ expect(results[2].disabled).toBe(false);
+ });
+
+ it('keeps the newest search result when an older request finishes last', async () => {
+ let resolveFirst;
+ let resolveSecond;
+ apiGet
+ .mockImplementationOnce(() => new Promise((resolve) => { resolveFirst = resolve; }))
+ .mockImplementationOnce(() => new Promise((resolve) => { resolveSecond = resolve; }));
+ const root = open({ selected: [], locked: [] });
+
+ click(root, 'Add');
+ await settle();
+ type(root, 'warehouse');
+ await settle();
+
+ expect(apiGet).toHaveBeenNthCalledWith(
+ 2,
+ '/api/cases/case-1/catalog/entities?limit=200&type=place%2Cmedia&q=warehouse'
+ );
+
+ resolveSecond({ items: [ROWS[2]] });
+ await settle();
+ resolveFirst({ items: [ROWS[0]] });
+ await settle();
+
+ expect(root.querySelector('.results').textContent).toContain('Old warehouse');
+ expect(root.querySelector('.results').textContent).not.toContain('North quay');
+ });
+
+ it('recovers from a failed search with an empty result', async () => {
+ apiGet.mockRejectedValue(new Error('offline'));
+ const root = open({ selected: [], locked: [] });
+
+ click(root, 'Add');
+ expect(root.textContent).toContain('Searching…');
+ await settle();
+
+ expect(root.textContent).toContain('No matching case items');
+ });
+});
diff --git a/frontend/src/components/TemporalTargetPicker.svelte b/frontend/src/components/TemporalTargetPicker.svelte
new file mode 100644
index 0000000..5d615d3
--- /dev/null
+++ b/frontend/src/components/TemporalTargetPicker.svelte
@@ -0,0 +1,148 @@
+<script>
+ /** Pick several endpoints for one of a Temporal Claim's typed connectors. */
+ import { api } from '../lib/api.js';
+ import { buildCatalogQuery } from '../lib/catalog.js';
+ import { entityIcon } from '../lib/entityIcon.js';
+ import { entityTypes, loadEntityTypes } from '../lib/entityTypes.svelte.js';
+ import { loadRelationTypes, relationOptions } from '../lib/relations.svelte.js';
+ import Icon from './Icon.svelte';
+ import SearchInput from './SearchInput.svelte';
+
+ let {
+ caseId,
+ relationType,
+ label,
+ hint = '',
+ selected = $bindable([]),
+ locked = [],
+ } = $props();
+
+ loadEntityTypes();
+ loadRelationTypes();
+
+ let open = $state(false);
+ let query = $state('');
+ let rows = $state([]);
+ let loading = $state(false);
+ let seq = 0;
+
+ const lockedIds = $derived(new Set(locked.map((item) => item.id)));
+ const selectedIds = $derived(new Set(selected.map((item) => item.id)));
+ const acceptedTypes = $derived(
+ entityTypes()
+ .filter((entry) =>
+ relationOptions('claim', entry.type, 'claim').some(
+ (option) => option.type === relationType && option.direction === 'out'
+ )
+ )
+ .map((entry) => entry.type)
+ );
+
+ $effect(() => {
+ const term = query.trim();
+ const types = acceptedTypes;
+ if (!open || !caseId || !types.length) return;
+ const mine = ++seq;
+ loading = true;
+ api
+ .get(buildCatalogQuery(caseId, { types, query: term, limit: 200 }))
+ .then((page) => {
+ if (mine === seq) rows = page.items ?? [];
+ })
+ .catch(() => {
+ if (mine === seq) rows = [];
+ })
+ .finally(() => {
+ if (mine === seq) loading = false;
+ });
+ });
+
+ function add(entity) {
+ if (!selectedIds.has(entity.id) && !lockedIds.has(entity.id)) {
+ selected = [...selected, { id: entity.id, label: entity.label, type: entity.type }];
+ }
+ query = '';
+ }
+
+ function remove(id) {
+ selected = selected.filter((item) => item.id !== id);
+ }
+</script>
+
+<div class="target-picker">
+ <div class="target-head">
+ <div>
+ <span class="modal-label">{label}</span>
+ {#if hint}<p>{hint}</p>{/if}
+ </div>
+ <button class="btn btn-ghost btn-sm" class:on={open} onclick={() => (open = !open)}>
+ <Icon name={open ? 'x' : 'plus'} size={12} /> {open ? 'Close' : 'Add'}
+ </button>
+ </div>
+
+ {#if locked.length || selected.length}
+ <div class="chips">
+ {#each locked as item (item.id)}
+ <span class="chip locked"><Icon name={entityIcon(item)} size={11} />{item.label}</span>
+ {/each}
+ {#each selected as item (item.id)}
+ <span class="chip">
+ <Icon name={entityIcon(item)} size={11} />{item.label}
+ <button title={`Remove ${item.label}`} onclick={() => remove(item.id)}><Icon name="x" size={10} /></button>
+ </span>
+ {/each}
+ </div>
+ {/if}
+
+ {#if open}
+ <div class="picker-body">
+ <SearchInput bind:value={query} placeholder="Search the case…" width="100%" />
+ <div class="results">
+ {#each rows as entity (entity.id)}
+ <button
+ class:selected={selectedIds.has(entity.id) || lockedIds.has(entity.id)}
+ disabled={selectedIds.has(entity.id) || lockedIds.has(entity.id)}
+ onclick={() => add(entity)}
+ >
+ <Icon name={entityIcon(entity)} size={12} />
+ <span>{entity.label}</span>
+ <small>{entity.type}</small>
+ </button>
+ {:else}
+ <p class="empty">{loading ? 'Searching…' : 'No matching case items'}</p>
+ {/each}
+ </div>
+ </div>
+ {/if}
+</div>
+
+<style>
+ .target-picker { display: grid; gap: 6px; }
+ .target-head { display: flex; align-items: start; justify-content: space-between; gap: 12px; }
+ .target-head p { margin: 2px 0 0; color: var(--text-3); font-size: var(--fs-xs); }
+ .chips { display: flex; flex-wrap: wrap; gap: 5px; }
+ .chip {
+ display: inline-flex; align-items: center; gap: 5px; min-width: 0;
+ padding: 4px 7px; border: 1px solid var(--border); border-radius: 999px;
+ background: var(--bg-2); color: var(--text-2); font-size: var(--fs-xs);
+ }
+ .chip.locked { border-style: dashed; }
+ .chip button { display: grid; padding: 0; border: 0; background: none; color: var(--text-3); cursor: pointer; }
+ .picker-body { display: grid; gap: 5px; }
+ .results {
+ max-height: 180px; overflow: auto; border: 1px solid var(--border);
+ border-radius: var(--r-sm); background: var(--bg-2);
+ }
+ .results > button {
+ width: 100%; display: grid; grid-template-columns: auto minmax(0, 1fr) auto;
+ align-items: center; gap: 7px; padding: 7px 8px; border: 0;
+ border-bottom: 1px solid var(--border); background: transparent; color: var(--text-2);
+ text-align: left; cursor: pointer;
+ }
+ .results > button:last-child { border-bottom: 0; }
+ .results > button:hover:not(:disabled) { background: var(--bg-3); color: var(--text-1); }
+ .results > button.selected { opacity: .45; }
+ .results span { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
+ .results small { color: var(--text-3); }
+ .empty { margin: 0; padding: 12px; color: var(--text-3); text-align: center; font-size: var(--fs-xs); }
+</style>
diff --git a/frontend/src/components/TimelineTrackEditor.svelte b/frontend/src/components/TimelineTrackEditor.svelte
new file mode 100644
index 0000000..b4b5d5d
--- /dev/null
+++ b/frontend/src/components/TimelineTrackEditor.svelte
@@ -0,0 +1,231 @@
+<script>
+ import { api } from '../lib/api.js';
+ import { fetchAttrFacets } from '../lib/catalog.js';
+ import { chipsOf, clearAxis, emptyFilter, normalizeFilter, toGraphQuery } from '../lib/entityFilter.js';
+ import {
+ entityFamily,
+ entityHint,
+ entityLabel,
+ entityTypes,
+ familyReads,
+ loadEntityTypes,
+ } from '../lib/entityTypes.svelte.js';
+ import { TRACK_COLORS, timelineTrack, trackTint } from '../lib/timelineTracks.js';
+ import FilterBar from './FilterBar.svelte';
+
+ let { caseId, caseFolders = [], track = null, onsave = () => {}, oncancel = () => {} } = $props();
+
+ let name = $state('');
+ let color = $state('');
+ let categories = $state(new Set());
+ let relation = $state('any');
+ let roles = $state(new Set());
+ let filter = $state(emptyFilter());
+ let summary = $state(null);
+ let facets = $state([]);
+ let facetState = $state('unasked');
+ let fieldsWanted = $state(false);
+ let loadedFor = null;
+ let facetsFor = null;
+ let initialized = false;
+
+ $effect(() => {
+ if (initialized) return;
+ initialized = true;
+ name = track?.label ?? 'New track';
+ color = track?.color ?? '';
+ categories = new Set(track?.categories ?? ['statement']);
+ relation = track?.query?.relation ?? 'any';
+ roles = new Set(track?.query?.roles ?? []);
+ filter = normalizeFilter(track?.query?.filter ?? emptyFilter());
+ });
+
+ loadEntityTypes();
+ const families = $derived([
+ ...new Set(Object.keys(summary?.by_type ?? {}).map(entityFamily).filter(Boolean)),
+ ]);
+ const typeOptions = $derived(
+ entityTypes().filter((entry) => !filter.families.length || filter.families.includes(entry.family))
+ );
+ const wantedTypes = $derived(
+ filter.types.length ? filter.types
+ : filter.families.length ? typeOptions.map((entry) => entry.type) : []
+ );
+ const queryLabel = $derived(
+ chipsOf(filter, {
+ type: entityLabel,
+ family: (family) => family.charAt(0).toUpperCase() + family.slice(1),
+ }).map((chip) => chip.text).join(' · ')
+ );
+
+ $effect(() => {
+ if (!caseId || loadedFor === caseId) return;
+ loadedFor = caseId;
+ api.get(`/api/cases/${caseId}/catalog/summary`)
+ .then((value) => { if (loadedFor === caseId) summary = value; })
+ .catch(() => { if (loadedFor === caseId) summary = null; });
+ });
+
+ $effect(() => {
+ const key = `${caseId}|${wantedTypes.join(',')}|${fieldsWanted}`;
+ if (!caseId) return;
+ if (!wantedTypes.length && !fieldsWanted) {
+ facets = [];
+ facetState = 'unasked';
+ return;
+ }
+ if (facetsFor === key) return;
+ facetsFor = key;
+ facetState = 'loading';
+ fetchAttrFacets(caseId, wantedTypes)
+ .then((rows) => {
+ if (facetsFor !== key) return;
+ facets = rows;
+ facetState = 'ready';
+ if (filter.attrKey && !rows.some((row) => row.key === filter.attrKey && row.values.length)) {
+ filter = clearAxis(filter, 'field');
+ }
+ })
+ .catch(() => {
+ if (facetsFor === key) {
+ facets = [];
+ facetState = 'ready';
+ }
+ });
+ });
+
+ function toggleCategory(category) {
+ const next = new Set(categories);
+ if (next.has(category)) next.delete(category);
+ else next.add(category);
+ if (next.size) categories = next;
+ }
+
+ function toggleRole(role) {
+ const next = new Set(roles);
+ if (next.has(role)) next.delete(role);
+ else next.add(role);
+ roles = next;
+ }
+
+ function save() {
+ if (!name.trim() || !categories.size) return;
+ onsave(timelineTrack({
+ ...(track ?? {}),
+ label: name.trim(),
+ color,
+ categories: [...categories],
+ query: {
+ filter: normalizeFilter(filter),
+ terms: toGraphQuery(filter, { types: wantedTypes }),
+ label: queryLabel,
+ relation,
+ roles: [...roles],
+ },
+ }));
+ }
+</script>
+
+<section class="track-editor" aria-label={track ? 'Edit timeline track' : 'Add timeline track'}>
+ <div class="naming">
+ <label class="name">Name<input class="input" bind:value={name} maxlength="80" /></label>
+ <!-- Left unset the lane keeps the colours of the categories it holds, which is
+ what the legend explains. A colour here tells this reading apart instead. -->
+ <fieldset class="tint">
+ <legend>Colour</legend>
+ <div class="swatches">
+ <button
+ class="swatch none"
+ aria-pressed={!color}
+ title="By category"
+ onclick={() => (color = '')}
+ >Auto</button>
+ {#each TRACK_COLORS as option (option)}
+ <button
+ class="swatch"
+ aria-pressed={color === option}
+ aria-label={option}
+ title={option}
+ style:background={trackTint(option)}
+ onclick={() => (color = option)}
+ ></button>
+ {/each}
+ </div>
+ </fieldset>
+ </div>
+
+ <fieldset>
+ <legend>Timeline entries</legend>
+ <div class="checks">
+ {#each [['statement', 'Statements'], ['media', 'Media'], ['case_activity', 'Case activity']] as option}
+ <label><input type="checkbox" checked={categories.has(option[0])} onchange={() => toggleCategory(option[0])} />{option[1]}</label>
+ {/each}
+ </div>
+ </fieldset>
+
+ <label class="match">Match the Search+ question through
+ <select class="input" bind:value={relation}>
+ <option value="any">Any connection</option>
+ <option value="owner">Entry itself</option>
+ <option value="about">Subject</option>
+ <option value="place">Place</option>
+ <option value="source">Evidence</option>
+ </select>
+ </label>
+
+ <div class="search-query">
+ <span>Search+</span>
+ <FilterBar
+ bind:filter
+ {summary}
+ {facets}
+ {facetState}
+ {families}
+ {caseFolders}
+ types={typeOptions}
+ familyName={(family) => family.charAt(0).toUpperCase() + family.slice(1)}
+ typeName={entityLabel}
+ familyHint={familyReads}
+ typeHint={entityHint}
+ onfields={() => (fieldsWanted = true)}
+ />
+ </div>
+
+ <fieldset>
+ <legend>Time role</legend>
+ <div class="checks">
+ {#each [['occurred', 'Occurred'], ['observed', 'Observed'], ['valid', 'Valid'], ['unset', 'Not set']] as option}
+ <label><input type="checkbox" checked={roles.has(option[0])} onchange={() => toggleRole(option[0])} />{option[1]}</label>
+ {/each}
+ </div>
+ <small>Leave all clear to include every role.</small>
+ </fieldset>
+
+ <div class="actions">
+ <button class="btn" onclick={oncancel}>Cancel</button>
+ <button class="btn btn-primary" disabled={!name.trim() || !categories.size} onclick={save}>
+ {track ? 'Update track' : 'Add track'}
+ </button>
+ </div>
+</section>
+
+<style>
+ .track-editor { display: grid; gap: 15px; }
+ .name, .match { display: grid; gap: 5px; color: var(--text-2); font-size: var(--fs-sm); }
+ .naming { display: grid; grid-template-columns: minmax(0, 1fr) auto; align-items: end; gap: 12px; }
+ .tint { gap: 6px; padding: 7px 9px; }
+ .swatches { display: flex; align-items: center; gap: 5px; }
+ .swatch { width: 18px; height: 18px; border: 1px solid var(--border-strong); border-radius: 50%; cursor: pointer; }
+ .swatch.none { width: auto; padding: 0 7px; border-radius: 999px; background: var(--bg-2); color: var(--text-3); font-size: 9px; }
+ .swatch[aria-pressed='true'] { box-shadow: 0 0 0 2px var(--bg-1), 0 0 0 3px var(--text-1); }
+ .swatch.none[aria-pressed='true'] { color: var(--text-1); }
+ fieldset { display: grid; gap: 8px; margin: 0; padding: 10px 12px; border: 1px solid var(--border); border-radius: var(--r-sm); }
+ legend, .search-query > span { padding: 0 4px; color: var(--text-2); font-size: var(--fs-xs); font-weight: 650; }
+ .checks { display: flex; flex-wrap: wrap; gap: 8px 14px; }
+ .checks label { display: inline-flex; align-items: center; gap: 6px; color: var(--text-2); font-size: var(--fs-sm); }
+ fieldset small { color: var(--text-3); }
+ .search-query { overflow: visible; border: 1px solid var(--border); border-radius: var(--r-sm); }
+ .search-query > span { display: block; width: max-content; margin: -7px 0 0 8px; background: var(--bg-1); }
+ .search-query :global(.filter-bar) { padding: 10px 12px; border: 0; }
+ .actions { display: flex; justify-content: flex-end; gap: 8px; }
+</style>
diff --git a/frontend/src/components/TimelineTrackEditor.test.js b/frontend/src/components/TimelineTrackEditor.test.js
new file mode 100644
index 0000000..00f355e
--- /dev/null
+++ b/frontend/src/components/TimelineTrackEditor.test.js
@@ -0,0 +1,30 @@
+import { describe, expect, it } from 'vitest';
+import { readFileSync } from 'node:fs';
+
+const source = readFileSync(new URL('./TimelineTrackEditor.svelte', import.meta.url), 'utf8');
+
+describe('Timeline track editor', () => {
+ it('uses the shared Search+ builder and registry vocabulary', () => {
+ expect(source).toContain("import FilterBar from './FilterBar.svelte'");
+ expect(source).toContain('types={typeOptions}');
+ expect(source).toContain('typeName={entityLabel}');
+ expect(source).toContain('toGraphQuery(filter, { types: wantedTypes })');
+ });
+
+ it('keeps category, connector and time role as separate filters', () => {
+ expect(source).toContain('Timeline entries');
+ expect(source).toContain('Match the Search+ question through');
+ expect(source).toContain('<option value="source">Evidence</option>');
+ expect(source).toContain('<legend>Time role</legend>');
+ });
+
+ it('offers the track a colour of its own, and the category colours as the default', () => {
+ expect(source).toContain('<legend>Colour</legend>');
+ expect(source).toContain('{#each TRACK_COLORS as option (option)}');
+ expect(source).toContain('style:background={trackTint(option)}');
+ expect(source).toContain('onclick={() => (color = \'\')}');
+ expect(source).toContain('title="By category"');
+ expect(source).toContain('color = track?.color ?? \'\'');
+ expect(source).toContain(' color,');
+ });
+});
diff --git a/frontend/src/components/ViewSwitch.svelte b/frontend/src/components/ViewSwitch.svelte
new file mode 100644
index 0000000..4333bf8
--- /dev/null
+++ b/frontend/src/components/ViewSwitch.svelte
@@ -0,0 +1,83 @@
+<script>
+ /**
+ * The segmented control that says how a screen renders its answer.
+ *
+ * Files and the Media Library have drawn this by hand for a while — *Small · Large
+ * · List*, the same markup and the same rules copied twice. This is that control,
+ * defined once, so the third screen to want one adds no third copy. Those two are a
+ * drop-in migration whenever it is wanted: the classes, the sizes and the
+ * `aria-pressed` behaviour are theirs, unchanged.
+ *
+ * **An option may be offered and unavailable**, which is the reason this is a
+ * component rather than three buttons. The app's rule is that a control you can see
+ * and cannot use teaches something, where one that is not there teaches nothing —
+ * so a disabled option keeps its place and states its reason in the tooltip instead
+ * of disappearing. The state currently *on* is never disabled by a caller, or the
+ * screen would show itself as unavailable.
+ */
+ import Icon from './Icon.svelte';
+
+ /**
+ * @type {{
+ * options: Array<{id: string, label: string, icon: string, hint?: string, disabled?: boolean}>,
+ * value: string,
+ * label?: string,
+ * onpick: (id: string) => void,
+ * }}
+ */
+ let { options = [], value, label = 'View', onpick } = $props();
+</script>
+
+<div class="view-switch" role="group" aria-label={label}>
+ {#each options as option (option.id)}
+ <button
+ class="view-btn"
+ class:active={value === option.id}
+ title={option.hint ?? `${option.label} view`}
+ aria-pressed={value === option.id}
+ disabled={Boolean(option.disabled) && value !== option.id}
+ onclick={() => onpick?.(option.id)}
+ >
+ <Icon name={option.icon} size={14} /> {option.label}
+ </button>
+ {/each}
+</div>
+
+<style>
+ .view-switch {
+ display: flex;
+ gap: 2px;
+ padding: 2px;
+ border: 1px solid var(--border);
+ border-radius: var(--r-sm);
+ background: var(--bg-2);
+ flex-shrink: 0;
+ }
+ .view-btn {
+ display: flex;
+ align-items: center;
+ gap: 4px;
+ padding: 3px 8px;
+ border-radius: var(--r-sm);
+ color: var(--text-3);
+ font-size: var(--fs-xs);
+ white-space: nowrap;
+ }
+ .view-btn:hover {
+ color: var(--text-1);
+ }
+ .view-btn.active {
+ background: var(--bg-3);
+ color: var(--text-1);
+ }
+ /* Offered and unavailable: dimmed where a hidden control would have taught
+ nothing, and it keeps the pointer rather than inviting a click that does
+ nothing. The reason is in the tooltip, which is where the caller puts it. */
+ .view-btn:disabled {
+ opacity: 0.45;
+ cursor: default;
+ }
+ .view-btn:disabled:hover {
+ color: var(--text-3);
+ }
+</style>
diff --git a/frontend/src/components/ViewSwitch.test.js b/frontend/src/components/ViewSwitch.test.js
new file mode 100644
index 0000000..b4e48c3
--- /dev/null
+++ b/frontend/src/components/ViewSwitch.test.js
@@ -0,0 +1,42 @@
+import { describe, expect, it } from 'vitest';
+import { readFileSync } from 'node:fs';
+
+const source = readFileSync(new URL('./ViewSwitch.svelte', import.meta.url), 'utf8');
+const files = readFileSync(new URL('../tools/Files.svelte', import.meta.url), 'utf8');
+const media = readFileSync(new URL('../tools/MediaLibrary.svelte', import.meta.url), 'utf8');
+
+describe('the control that says how a screen renders its answer', () => {
+ it('keeps the markup Files and the Media Library already draw by hand', () => {
+ // so those two are a drop-in migration rather than a rewrite
+ expect(source).toContain('<div class="view-switch" role="group" aria-label={label}>');
+ expect(source).toContain('class:active={value === option.id}');
+ expect(source).toContain('aria-pressed={value === option.id}');
+ for (const drawn of [files, media]) {
+ expect(drawn).toContain('<div class="view-switch" role="group" aria-label="View">');
+ expect(drawn).toContain('aria-pressed={view === v.id}');
+ }
+ });
+
+ it('carries the same sizes, so a migrated switch does not move on screen', () => {
+ for (const rule of ['padding: 3px 8px;', 'border-radius: var(--r-sm);', 'gap: 2px;']) {
+ expect(source).toContain(rule);
+ }
+ expect(source).toContain('<Icon name={option.icon} size={14} />');
+ });
+
+ it('offers an option it cannot answer with, dimmed rather than absent', () => {
+ // a control you can see and cannot use teaches something; one that is not there
+ // teaches nothing
+ expect(source).toContain('disabled={Boolean(option.disabled) && value !== option.id}');
+ expect(source).toMatch(/\.view-btn:disabled \{[^}]*opacity: 0\.45;/);
+ });
+
+ it('never dims the state that is on', () => {
+ // the screen would be showing itself as unavailable
+ expect(source).toContain('&& value !== option.id}');
+ });
+
+ it('states the reason in the tooltip the caller gives it', () => {
+ expect(source).toContain('title={option.hint ?? `${option.label} view`}');
+ });
+});
diff --git a/frontend/src/components/ZonePicker.svelte b/frontend/src/components/ZonePicker.svelte
new file mode 100644
index 0000000..82597fa
--- /dev/null
+++ b/frontend/src/components/ZonePicker.svelte
@@ -0,0 +1,181 @@
+<script>
+ /**
+ * Which clock a chronology is read on.
+ *
+ * Four kinds of answer, in one searchable list because picking between them is one
+ * decision:
+ *
+ * - **UTC**, what the case stores and the only reading that means the same thing on
+ * every machine.
+ * - **This computer**, a legitimate reading of the analyst's own working day.
+ * - **A saved point**, which is the reading the work usually wants *and* the only one
+ * that can carry daylight with it: a band of day and night needs coordinates.
+ * - **Any zone in the world**, because an investigation is rarely in the analyst's
+ * own zone and often in no point the case has saved yet.
+ *
+ * Searchable rather than a four-hundred-row select, the way every other long picker
+ * in this app works. A zone is named rather than offered as an offset: a name carries
+ * the rules, so a stated hour survives the two days a year the offset moves.
+ */
+ import {
+ UTC,
+ machineZone,
+ offsetLabel,
+ worldZones,
+ zoneMatches,
+ zoneWords,
+ } from '../lib/timeline.js';
+ import Icon from './Icon.svelte';
+ import SearchInput from './SearchInput.svelte';
+
+ let {
+ /** `utc` | `machine` | `zone:<IANA>` | `place:<id>` */
+ choice = $bindable('utc'),
+ /** The case's saved points, as `{ id, label }`. */
+ places = [],
+ /** The instant the offsets are shown at: the window's own start, not today, or a
+ * winter window would be labelled with a summer offset. */
+ at = 0,
+ /** What the parent resolved the choice to, for the trigger's own label. */
+ resolved = UTC,
+ disabled = false,
+ } = $props();
+
+ /** How many zones the list shows before it asks for a narrower term. Long enough to
+ * browse a region, short enough not to be a wall. */
+ const ROWS = 40;
+
+ let open = $state(false);
+ let query = $state('');
+ let box = $state(null);
+
+ const local = machineZone();
+ const zones = worldZones();
+ const matching = $derived(zones.filter((zone) => zoneMatches(zone, query, at)));
+ const shown = $derived(matching.slice(0, ROWS));
+ const matchingPlaces = $derived(
+ places.filter((place) =>
+ place.label.toLowerCase().includes(query.trim().toLowerCase())
+ )
+ );
+
+ /** What the button says. The point's or zone's own words, never the raw choice. */
+ const label = $derived.by(() => {
+ if (choice === 'utc') return 'UTC';
+ if (choice === 'machine') return zoneWords(local).place;
+ if (choice.startsWith('place:')) {
+ return places.find((place) => place.id === choice.slice(6))?.label ?? 'Saved point';
+ }
+ return zoneWords(choice.slice(5)).place;
+ });
+
+ $effect(() => {
+ if (!open || typeof document === 'undefined') return;
+ const closeOutside = (event) => {
+ if (!box?.contains(event.target)) open = false;
+ };
+ document.addEventListener('pointerdown', closeOutside);
+ return () => document.removeEventListener('pointerdown', closeOutside);
+ });
+
+ function pick(value) {
+ choice = value;
+ open = false;
+ query = '';
+ }
+</script>
+
+<div class="zone-picker" bind:this={box}>
+ <button
+ class="trigger"
+ {disabled}
+ aria-expanded={open}
+ title="Which clock the axis is labelled with"
+ onclick={() => (open = !open)}
+ >
+ <Icon name="clock" size={12} />
+ <span>{label}</span>
+ <small>{offsetLabel(resolved, at)}</small>
+ </button>
+
+ {#if open}
+ <div class="menu">
+ <SearchInput bind:value={query} placeholder="Search a zone or a point…" width="100%" />
+ <div class="rows">
+ {#if zoneMatches('UTC', query, at)}
+ <button class:on={choice === 'utc'} onclick={() => pick('utc')}>
+ <span>UTC</span><small>what the case stores</small>
+ </button>
+ {/if}
+ {#if local !== UTC && zoneMatches(local, query, at)}
+ <button class:on={choice === 'machine'} onclick={() => pick('machine')}>
+ <span>{zoneWords(local).place}</span>
+ <small>this computer · {offsetLabel(local, at)}</small>
+ </button>
+ {/if}
+
+ {#if matchingPlaces.length}
+ <!-- Named apart because picking one does a second thing: a point has
+ coordinates, so its daylight can be drawn under the ruler. -->
+ <p class="heading">Saved points · with daylight</p>
+ {#each matchingPlaces as place (place.id)}
+ <button class:on={choice === `place:${place.id}`} onclick={() => pick(`place:${place.id}`)}>
+ <span>{place.label}</span><small>local time and daylight</small>
+ </button>
+ {/each}
+ {/if}
+
+ {#if zones.length}
+ <p class="heading">Anywhere in the world</p>
+ {#each shown as zone (zone)}
+ {@const words = zoneWords(zone)}
+ <button class:on={choice === `zone:${zone}`} onclick={() => pick(`zone:${zone}`)}>
+ <span>{words.place}</span>
+ <small>{words.region} · {offsetLabel(zone, at)}</small>
+ </button>
+ {/each}
+ {#if matching.length > shown.length}
+ <p class="more">{matching.length - shown.length} more. Keep typing.</p>
+ {:else if !matching.length && !matchingPlaces.length}
+ <p class="more">No zone or point matches that.</p>
+ {/if}
+ {:else}
+ <p class="more">This browser cannot list world zones. UTC and this computer still work.</p>
+ {/if}
+ </div>
+ </div>
+ {/if}
+</div>
+
+<style>
+ .zone-picker { position: relative; }
+ .trigger {
+ display: inline-flex; align-items: center; gap: 5px; height: 24px;
+ padding: 0 7px; border: 1px solid var(--border); border-radius: var(--r-sm);
+ background: var(--bg-2); color: var(--text-2); font-size: 10px; cursor: pointer;
+ }
+ .trigger:hover:not(:disabled) { border-color: var(--border-strong); color: var(--text-1); }
+ .trigger:disabled { opacity: .5; cursor: default; }
+ .trigger small { color: var(--text-3); font-variant-numeric: tabular-nums; }
+ .menu {
+ position: absolute; z-index: 45; top: calc(100% + 5px); left: 0;
+ width: 268px; display: grid; gap: 5px; padding: 7px;
+ border: 1px solid var(--border-strong); border-radius: var(--r-md);
+ background: var(--bg-1); box-shadow: var(--shadow-2);
+ }
+ .rows { max-height: 236px; overflow: auto; }
+ .rows > button {
+ width: 100%; display: grid; grid-template-columns: minmax(0, 1fr) auto;
+ align-items: baseline; gap: 8px; padding: 5px 6px; border: 0; border-radius: var(--r-sm);
+ background: none; color: var(--text-2); font-size: var(--fs-xs); text-align: left;
+ cursor: pointer;
+ }
+ .rows > button:hover { background: var(--bg-2); color: var(--text-1); }
+ .rows > button.on { background: var(--accent-soft); color: var(--text-1); }
+ .rows > button span { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
+ .rows > button small { color: var(--text-3); font-size: 9px; white-space: nowrap; }
+ .heading {
+ margin: 7px 0 3px; padding: 0 6px; color: var(--text-3); font-size: 9px;
+ }
+ .more { margin: 5px 0 2px; padding: 0 6px; color: var(--text-3); font-size: 9px; }
+</style>
diff --git a/frontend/src/components/ZonePicker.test.js b/frontend/src/components/ZonePicker.test.js
new file mode 100644
index 0000000..5b25bc2
--- /dev/null
+++ b/frontend/src/components/ZonePicker.test.js
@@ -0,0 +1,48 @@
+import { describe, expect, it } from 'vitest';
+import { readFileSync } from 'node:fs';
+
+const source = readFileSync(new URL('./ZonePicker.svelte', import.meta.url), 'utf8');
+
+describe('choosing the clock a chronology is read on', () => {
+ it('offers the four readings in one searchable list', () => {
+ // an investigation is rarely in the analyst's own zone and often in no saved point
+ // yet, so the reading has to be choosable outright — and picking between the four
+ // kinds is one decision, so it is one control
+ expect(source).toContain("onclick={() => pick('utc')}");
+ expect(source).toContain("onclick={() => pick('machine')}");
+ expect(source).toContain('onclick={() => pick(`place:${place.id}`)}');
+ expect(source).toContain('onclick={() => pick(`zone:${zone}`)}');
+ expect(source).toContain('<SearchInput bind:value={query}');
+ });
+
+ it('names the saved points apart, because picking one does a second thing', () => {
+ // a point has coordinates, so its daylight can be drawn; a zone name cannot
+ expect(source).toContain('Saved points · with daylight');
+ expect(source).toContain('local time and daylight');
+ });
+
+ it('shows the offset in force at the window, not today-s', () => {
+ // a winter window labelled with a summer offset is the bug this avoids
+ expect(source).toContain('offsetLabel(zone, at)');
+ expect(source).toContain('offsetLabel(resolved, at)');
+ expect(source).toContain('at = 0,');
+ });
+
+ it('bounds the list and says what it left out', () => {
+ expect(source).toContain('const ROWS = 40');
+ expect(source).toContain('matching.slice(0, ROWS)');
+ expect(source).toContain('more. Keep typing.');
+ expect(source).toContain('No zone or point matches that.');
+ });
+
+ it('says so where the engine cannot list the world-s zones', () => {
+ // `supportedValuesOf` landed in 2022; an older browser gets a plain sentence
+ // rather than a control that silently pretends the world is UTC
+ expect(source).toContain('This browser cannot list world zones.');
+ });
+
+ it('closes on a click outside, like every other menu here', () => {
+ expect(source).toContain("document.addEventListener('pointerdown', closeOutside)");
+ expect(source).toContain("document.removeEventListener('pointerdown', closeOutside)");
+ });
+});
diff --git a/frontend/src/components/details.fixture.svelte.js b/frontend/src/components/details.fixture.svelte.js
new file mode 100644
index 0000000..faf2c97
--- /dev/null
+++ b/frontend/src/components/details.fixture.svelte.js
@@ -0,0 +1,24 @@
+/**
+ * Reactive stand-ins for `EntityDetails.render.test.js`.
+ *
+ * The seeding bug this guards against lives in Svelte's dependency tracking, so a
+ * plain object standing in for `caseState` proves nothing: the effect under test
+ * would simply never re-run. Runes only work in `.svelte.js`, and a `vi.mock`
+ * factory runs inside the `.test.js`, so the reactive fixtures live here and the
+ * test hands this module back as the mock.
+ */
+export const entity = $state({
+ id: 'e1',
+ type: 'place',
+ label: 'Quay 4',
+ attrs: { lat: 1, lon: 2, radius_m: 500, method: 'roofline match' },
+ provenance: { by: 'user', at: '2026-01-01T00:00:00Z', status: 'confirmed' },
+});
+
+export const caseState = $state({
+ current: { id: 'c1', entities: [entity], folders: [] },
+ rev: 0,
+});
+
+export const reloadCase = () => Promise.resolve();
+export const toast = () => {};
diff --git a/frontend/src/components/sidebar/DetailsDrawer.svelte b/frontend/src/components/sidebar/DetailsDrawer.svelte
index 2bf65c6..cfa7e35 100644
--- a/frontend/src/components/sidebar/DetailsDrawer.svelte
+++ b/frontend/src/components/sidebar/DetailsDrawer.svelte
@@ -2,30 +2,53 @@
// Zone 3: the selection editor, over the sidebar rather than under the tree.
// The body is EntityDetails, unchanged — the Media Library modal shares it.
import Icon from '../Icon.svelte';
+ import ConfirmDialog from '../ConfirmDialog.svelte';
import EntityDetails from '../EntityDetails.svelte';
let { entity, onclose = () => {}, ondeleted = () => {} } = $props();
function focus(node) { node.focus(); }
+
+ // The panel's fields wait for Save, so the back arrow, the close button and
+ // Escape ask before dropping an edit. The panel's own `onclose` is its hand-off
+ // to another tool and closes without asking: it has already navigated.
+ let dirty = $state(false);
+ let discarding = $state(false);
+
+ function requestClose() {
+ if (dirty) discarding = true;
+ else onclose();
+ }
</script>
-<svelte:window onkeydown={(e) => e.key === 'Escape' && onclose()} />
+<svelte:window onkeydown={(e) => e.key === 'Escape' && requestClose()} />
<div class="drawer">
<div class="drawer-head">
- <button class="btn btn-ghost btn-sm" title="Back to the case" onclick={onclose} use:focus>
+ <button class="btn btn-ghost btn-sm" title="Back to the case" onclick={requestClose} use:focus>
<Icon name="chevronLeft" size={14} />
</button>
<span class="label">{entity.label}</span>
- <button class="btn btn-ghost btn-sm" title="Close details" onclick={onclose}>
+ <button class="btn btn-ghost btn-sm" title="Close details" onclick={requestClose}>
<Icon name="x" size={13} />
</button>
</div>
<div class="drawer-body">
- <EntityDetails entityId={entity.id} {onclose} {ondeleted} />
+ <EntityDetails entityId={entity.id} bind:dirty {onclose} {ondeleted} />
</div>
</div>
+{#if discarding}
+ <ConfirmDialog
+ title="Discard changes?"
+ message="This item has edits that Save has not taken."
+ confirmLabel="Discard"
+ icon="alert"
+ onconfirm={() => { discarding = false; dirty = false; onclose(); }}
+ oncancel={() => (discarding = false)}
+ />
+{/if}
+
<style>
.drawer {
position: absolute;
diff --git a/frontend/src/components/sidebar/EntityRow.svelte b/frontend/src/components/sidebar/EntityRow.svelte
index b5587c0..bdfa2d4 100644
--- a/frontend/src/components/sidebar/EntityRow.svelte
+++ b/frontend/src/components/sidebar/EntityRow.svelte
@@ -2,6 +2,7 @@
// One entity row. The folder tree and the result list render the same row, so
// it is a component rather than a snippet owned by either of them.
import { ENTITY_TOOL, gotoCapture } from '../../lib/navigate.js';
+ import { fileUrl } from '../../lib/fileUrl.js';
import { folderOf } from '../../lib/folderTree.js';
import { entityIcon } from '../../lib/entityIcon.js';
import Icon from '../Icon.svelte';
@@ -46,7 +47,11 @@
onkeydown={(ev) => ev.key === 'Enter' && onactivate(entity, ev)}
>
{#if !suggested}<Icon name="grip" size={13} />{/if}
- <Icon name={entityIcon(entity)} size={14} />
+ {#if entity.thumb}
+ <img class="entity-thumb" src={fileUrl(caseId, entity.thumb)} alt="" loading="lazy" />
+ {:else}
+ <Icon name={entityIcon(entity)} size={14} />
+ {/if}
<div class="e-body">
<span class="e-label">{entity.label}</span>
<span class="e-meta">{meta ?? entity.type}</span>
@@ -73,7 +78,7 @@
<a
class="btn btn-ghost btn-sm act"
title="Open in new tab"
- href={`/files/${caseId}/${entity.attrs.path}`}
+ href={fileUrl(caseId, entity.attrs.path)}
target="_blank"
rel="noreferrer"
onclick={(ev) => ev.stopPropagation()}
@@ -121,6 +126,15 @@
margin-bottom: 4px;
}
.e-body { flex: 1; min-width: 0; display: flex; flex-direction: column; }
+ .entity-thumb {
+ width: 28px;
+ height: 28px;
+ flex: 0 0 28px;
+ border: 1px solid var(--border);
+ border-radius: var(--r-sm);
+ object-fit: cover;
+ background: var(--bg-2);
+ }
.e-label {
font-size: var(--fs-sm);
color: var(--text-1);
diff --git a/frontend/src/lib/analysisPeriod.js b/frontend/src/lib/analysisPeriod.js
new file mode 100644
index 0000000..2638217
--- /dev/null
+++ b/frontend/src/lib/analysisPeriod.js
@@ -0,0 +1,51 @@
+/** A fact-time window shared by Board and Graph after an explicit handoff. */
+
+export const PERIOD_CATEGORIES = ['statement', 'media', 'case_activity'];
+
+export function emptyAnalysisPeriod() {
+ return { from: '', to: '', categories: ['statement', 'media'] };
+}
+
+export function normalizeAnalysisPeriod(value) {
+ const raw = value && typeof value === 'object' ? value : {};
+ const from = typeof raw.from === 'string' ? raw.from.slice(0, 40) : '';
+ const to = typeof raw.to === 'string' ? raw.to.slice(0, 40) : '';
+ const categories = Array.isArray(raw.categories)
+ ? [...new Set(raw.categories.filter((entry) => PERIOD_CATEGORIES.includes(entry)))]
+ : [];
+ const start = new Date(from).getTime();
+ const end = new Date(to).getTime();
+ if (!from || !to || !Number.isFinite(start) || !Number.isFinite(end) || start >= end) {
+ return emptyAnalysisPeriod();
+ }
+ return {
+ from,
+ to,
+ categories: categories.length ? categories : ['statement', 'media'],
+ };
+}
+
+export function hasAnalysisPeriod(value) {
+ const period = normalizeAnalysisPeriod(value);
+ return Boolean(period.from && period.to);
+}
+
+export function analysisPeriodQuery(value) {
+ const period = normalizeAnalysisPeriod(value);
+ if (!period.from || !period.to) return {};
+ return {
+ temporalFrom: period.from,
+ temporalTo: period.to,
+ temporalCategories: period.categories,
+ };
+}
+
+export function analysisPeriodSpec(value) {
+ const period = normalizeAnalysisPeriod(value);
+ return {
+ from: period.from || null,
+ to: period.to || null,
+ field: period.from ? 'fact-time' : null,
+ categories: period.categories,
+ };
+}
diff --git a/frontend/src/lib/analysisPeriod.test.js b/frontend/src/lib/analysisPeriod.test.js
new file mode 100644
index 0000000..4ffd0f2
--- /dev/null
+++ b/frontend/src/lib/analysisPeriod.test.js
@@ -0,0 +1,44 @@
+import { describe, expect, it } from 'vitest';
+import {
+ analysisPeriodQuery,
+ analysisPeriodSpec,
+ emptyAnalysisPeriod,
+ hasAnalysisPeriod,
+ normalizeAnalysisPeriod,
+} from './analysisPeriod.js';
+
+describe('the shared fact-time period', () => {
+ const period = {
+ from: '2026-08-12T09:00:00Z',
+ to: '2026-08-12T11:00:00Z',
+ categories: ['statement', 'case_activity', 'unknown'],
+ };
+
+ it('keeps only a complete ordered window and known categories', () => {
+ expect(normalizeAnalysisPeriod(period)).toEqual({
+ from: period.from,
+ to: period.to,
+ categories: ['statement', 'case_activity'],
+ });
+ expect(hasAnalysisPeriod(period)).toBe(true);
+ expect(normalizeAnalysisPeriod({ from: period.to, to: period.from }))
+ .toEqual(emptyAnalysisPeriod());
+ });
+
+ it('spells a separate server query instead of reusing filing dates', () => {
+ expect(analysisPeriodQuery(period)).toEqual({
+ temporalFrom: period.from,
+ temporalTo: period.to,
+ temporalCategories: ['statement', 'case_activity'],
+ });
+ });
+
+ it('round-trips through an analysis view spec', () => {
+ expect(analysisPeriodSpec(period)).toEqual({
+ from: period.from,
+ to: period.to,
+ field: 'fact-time',
+ categories: ['statement', 'case_activity'],
+ });
+ });
+});
diff --git a/frontend/src/lib/analysisSearch.svelte.js b/frontend/src/lib/analysisSearch.svelte.js
new file mode 100644
index 0000000..f4ecf42
--- /dev/null
+++ b/frontend/src/lib/analysisSearch.svelte.js
@@ -0,0 +1,129 @@
+/** The named readings each family of tools is holding.
+ *
+ * Board and Graph ask one question of the catalog — the same entities, drawn as rows
+ * or as a network — so they share a question and a saved view. The Timeline asks about
+ * time: its recipe is tracks, a window and a clock, and none of that means anything on
+ * a Board. Keeping one slot for both made a Timeline view unseat the Board's live view
+ * and, worse, replace the catalog question with the empty one a timeline spec carries.
+ * Two slots, one per family, and a view only ever lands in its own.
+ */
+import { emptyFilter, loadFilter, normalizeFilter, saveFilter } from './entityFilter.js';
+import {
+ emptyAnalysisPeriod,
+ normalizeAnalysisPeriod,
+} from './analysisPeriod.js';
+
+const idle = () => ({
+ activeView: null,
+ snapshotId: null,
+ modified: false,
+ changeVersion: 0,
+ saveState: 'idle',
+});
+
+export const analysisSearch = $state({
+ caseId: null,
+ /** The catalog question, shared by Board and Graph. */
+ filter: emptyFilter(),
+ /** The fact-time half of that question, separate from the filing-date filter. */
+ period: emptyAnalysisPeriod(),
+ catalog: idle(),
+ timeline: idle(),
+});
+
+/** Which family a surface belongs to. */
+export function viewFamily(surface) {
+ return surface === 'timeline' ? 'timeline' : 'catalog';
+}
+
+/** The slot a surface reads and writes. Mutated in place, never replaced, so a
+ * component may hold on to it. */
+export function viewSlot(surface) {
+ return analysisSearch[viewFamily(surface)];
+}
+
+export const catalogViews = analysisSearch.catalog;
+export const timelineViews = analysisSearch.timeline;
+
+const signature = (filter) => JSON.stringify(normalizeFilter(filter));
+
+function reset(slot) {
+ Object.assign(slot, idle());
+}
+
+function catalogQuestionModified(slot) {
+ if (!slot.activeView) return false;
+ const savedFilter = normalizeFilter(slot.activeView.spec?.query?.filter);
+ const savedPeriod = normalizeAnalysisPeriod(slot.activeView.spec?.timeline);
+ return (
+ signature(savedFilter) !== signature(analysisSearch.filter) ||
+ JSON.stringify(savedPeriod) !== JSON.stringify(analysisSearch.period)
+ );
+}
+
+/** Move the shared question across a case boundary, never across cases by accident. */
+export function openAnalysisCase(caseId) {
+ const id = caseId || null;
+ if (analysisSearch.caseId === id) return;
+ analysisSearch.caseId = id;
+ analysisSearch.filter = id ? loadFilter(id) : emptyFilter();
+ analysisSearch.period = emptyAnalysisPeriod();
+ reset(analysisSearch.catalog);
+ reset(analysisSearch.timeline);
+}
+
+/** Replace the shared fact-time window after a Timeline or Map handoff. */
+export function setAnalysisPeriod(caseId, value) {
+ openAnalysisCase(caseId);
+ const next = normalizeAnalysisPeriod(value);
+ const changed = JSON.stringify(analysisSearch.period) !== JSON.stringify(next);
+ if (changed) analysisSearch.period = next;
+ const slot = analysisSearch.catalog;
+ slot.modified = catalogQuestionModified(slot);
+ if (changed) slot.changeVersion += 1;
+}
+
+/** Replace the catalog question from either surface and remember it for this case. */
+export function setAnalysisFilter(caseId, filter) {
+ openAnalysisCase(caseId);
+ const next = normalizeFilter(filter);
+ const changed = signature(analysisSearch.filter) !== signature(next);
+ if (changed) analysisSearch.filter = next;
+ if (caseId) saveFilter(caseId, next);
+ const slot = analysisSearch.catalog;
+ slot.modified = catalogQuestionModified(slot);
+ if (changed) slot.changeVersion += 1;
+}
+
+/** Open a named recipe on the surfaces of its own family. */
+export function activateAnalysisView(caseId, view) {
+ openAnalysisCase(caseId);
+ const slot = viewSlot(view?.surface);
+ reset(slot);
+ slot.activeView = view;
+ slot.snapshotId = view?.mode === 'snapshot' ? view.id : null;
+ slot.saveState = view?.mode === 'live' ? 'saved' : 'idle';
+ if (viewFamily(view?.surface) !== 'catalog') return;
+ analysisSearch.filter = normalizeFilter(view?.spec?.query?.filter);
+ analysisSearch.period = normalizeAnalysisPeriod(view?.spec?.timeline);
+ if (caseId) saveFilter(caseId, analysisSearch.filter);
+}
+
+/** Accept an autosave response without replaying its presentation over newer edits. */
+export function adoptSavedAnalysisView(caseId, view) {
+ const slot = view ? viewSlot(view.surface) : null;
+ if (analysisSearch.caseId !== caseId || !slot || slot.activeView?.id !== view.id) return false;
+ slot.activeView = view;
+ return true;
+}
+
+/** Leave the named reading of one family. The catalog question can stay on screen
+ * or be dropped with it. */
+export function leaveAnalysisView(caseId, surface, { clear = false } = {}) {
+ openAnalysisCase(caseId);
+ reset(viewSlot(surface));
+ if (clear && viewFamily(surface) === 'catalog') {
+ setAnalysisFilter(caseId, emptyFilter());
+ setAnalysisPeriod(caseId, emptyAnalysisPeriod());
+ }
+}
diff --git a/frontend/src/lib/analysisSearch.test.js b/frontend/src/lib/analysisSearch.test.js
new file mode 100644
index 0000000..6e18b19
--- /dev/null
+++ b/frontend/src/lib/analysisSearch.test.js
@@ -0,0 +1,170 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+import {
+ activateAnalysisView,
+ adoptSavedAnalysisView,
+ analysisSearch,
+ catalogViews,
+ leaveAnalysisView,
+ openAnalysisCase,
+ setAnalysisFilter,
+ setAnalysisPeriod,
+ timelineViews,
+ viewFamily,
+} from './analysisSearch.svelte.js';
+import { emptyFilter } from './entityFilter.js';
+
+function storage() {
+ const values = new Map();
+ return {
+ getItem: (key) => values.get(key) ?? null,
+ setItem: (key, value) => values.set(key, String(value)),
+ removeItem: (key) => values.delete(key),
+ };
+}
+
+describe('the Board and Graph question', () => {
+ beforeEach(() => {
+ vi.stubGlobal('localStorage', storage());
+ openAnalysisCase(null);
+ });
+
+ it('is shared, remembered per case and cleared at the case boundary', () => {
+ setAnalysisFilter('case-a', { ...emptyFilter(), q: 'AB-123' });
+ expect(analysisSearch.filter.q).toBe('AB-123');
+
+ openAnalysisCase('case-b');
+ expect(analysisSearch.filter).toEqual(emptyFilter());
+ openAnalysisCase('case-a');
+ expect(analysisSearch.filter.q).toBe('AB-123');
+ });
+
+ it('opens a live recipe and marks it modified when either surface changes it', () => {
+ activateAnalysisView('case-a', {
+ id: 'v_live', mode: 'live', surface: 'board',
+ spec: { query: { filter: { ...emptyFilter(), q: 'port' } } },
+ });
+ expect(catalogViews.snapshotId).toBeNull();
+ expect(catalogViews.modified).toBe(false);
+ expect(catalogViews.saveState).toBe('saved');
+
+ setAnalysisFilter('case-a', { ...emptyFilter(), q: 'harbour' });
+ expect(catalogViews.modified).toBe(true);
+ expect(catalogViews.changeVersion).toBe(1);
+ });
+
+ it('shares and restores a fact-time period without turning it into a filing date', () => {
+ const period = {
+ from: '2026-08-12T09:00:00Z',
+ to: '2026-08-12T11:00:00Z',
+ categories: ['statement'],
+ };
+ activateAnalysisView('case-a', {
+ id: 'v_time_filter', mode: 'live', surface: 'board',
+ spec: { query: { filter: emptyFilter() }, timeline: period },
+ });
+ expect(analysisSearch.period).toEqual(period);
+ expect(analysisSearch.filter.since).toBe('');
+
+ setAnalysisPeriod('case-a', { ...period, to: '2026-08-12T12:00:00Z' });
+ expect(catalogViews.modified).toBe(true);
+ });
+
+ it('adopts an autosave response without replaying its older question', () => {
+ const view = {
+ id: 'v_live', mode: 'live', surface: 'graph',
+ spec: { query: { filter: { ...emptyFilter(), q: 'port' } } },
+ };
+ activateAnalysisView('case-a', view);
+ setAnalysisFilter('case-a', { ...emptyFilter(), q: 'harbour' });
+
+ expect(adoptSavedAnalysisView('case-a', {
+ ...view,
+ spec: { query: { filter: { ...emptyFilter(), q: 'port' } } },
+ updated_at: 'later',
+ })).toBe(true);
+ expect(analysisSearch.filter.q).toBe('harbour');
+ expect(catalogViews.activeView.updated_at).toBe('later');
+ });
+
+ it('identifies an immutable snapshot until the analyst leaves it', () => {
+ activateAnalysisView('case-a', {
+ id: 'v_snapshot', mode: 'snapshot', surface: 'board',
+ spec: { query: { filter: emptyFilter() } },
+ });
+ expect(catalogViews.snapshotId).toBe('v_snapshot');
+
+ leaveAnalysisView('case-a', 'board', { clear: true });
+ expect(catalogViews.activeView).toBeNull();
+ expect(catalogViews.snapshotId).toBeNull();
+ expect(analysisSearch.filter).toEqual(emptyFilter());
+ expect(analysisSearch.period.from).toBe('');
+ });
+});
+
+describe('the two families of saved views', () => {
+ beforeEach(() => {
+ vi.stubGlobal('localStorage', storage());
+ openAnalysisCase(null);
+ });
+
+ it('sorts Board and Graph together and the Timeline apart', () => {
+ expect([viewFamily('board'), viewFamily('graph')]).toEqual(['catalog', 'catalog']);
+ expect(viewFamily('timeline')).toBe('timeline');
+ });
+
+ it('holds one reading per family at once, and neither unseats the other', () => {
+ activateAnalysisView('case-a', {
+ id: 'v_board', mode: 'live', surface: 'board',
+ spec: { query: { filter: { ...emptyFilter(), q: 'port' } } },
+ });
+ activateAnalysisView('case-a', {
+ id: 'v_time', mode: 'live', surface: 'timeline', spec: { timeline: { tracks: [] } },
+ });
+
+ expect(catalogViews.activeView?.id).toBe('v_board');
+ expect(timelineViews.activeView?.id).toBe('v_time');
+ // a timeline recipe carries no catalog question, and must not impose its absence
+ expect(analysisSearch.filter.q).toBe('port');
+
+ leaveAnalysisView('case-a', 'timeline', { clear: true });
+ expect(timelineViews.activeView).toBeNull();
+ expect(catalogViews.activeView?.id).toBe('v_board');
+ expect(analysisSearch.filter.q).toBe('port');
+ });
+
+ it('marks only the catalog modified when the shared question changes', () => {
+ activateAnalysisView('case-a', {
+ id: 'v_time', mode: 'live', surface: 'timeline', spec: { timeline: { tracks: [] } },
+ });
+ activateAnalysisView('case-a', {
+ id: 'v_board', mode: 'live', surface: 'board',
+ spec: { query: { filter: { ...emptyFilter(), q: 'port' } } },
+ });
+
+ setAnalysisFilter('case-a', { ...emptyFilter(), q: 'harbour' });
+
+ expect(catalogViews.modified).toBe(true);
+ expect(timelineViews.modified).toBe(false);
+ expect(timelineViews.changeVersion).toBe(0);
+ });
+
+ it('answers an autosave into the family the saved view belongs to', () => {
+ const view = { id: 'v_time', mode: 'live', surface: 'timeline', spec: { timeline: {} } };
+ activateAnalysisView('case-a', view);
+
+ expect(adoptSavedAnalysisView('case-a', { ...view, updated_at: 'later' })).toBe(true);
+ expect(timelineViews.activeView.updated_at).toBe('later');
+ expect(catalogViews.activeView).toBeNull();
+ });
+
+ it('empties both families at the case boundary', () => {
+ activateAnalysisView('case-a', { id: 'v_board', mode: 'live', surface: 'board', spec: {} });
+ activateAnalysisView('case-a', { id: 'v_time', mode: 'live', surface: 'timeline', spec: {} });
+
+ openAnalysisCase('case-b');
+
+ expect(catalogViews.activeView).toBeNull();
+ expect(timelineViews.activeView).toBeNull();
+ expect(analysisSearch.period.from).toBe('');
+ });
+});
diff --git a/frontend/src/lib/analysisViews.js b/frontend/src/lib/analysisViews.js
new file mode 100644
index 0000000..6ab0d39
--- /dev/null
+++ b/frontend/src/lib/analysisViews.js
@@ -0,0 +1,8 @@
+export function copyName(name, existing = []) {
+ const used = new Set(existing.map((value) => String(value).trim().toLocaleLowerCase()));
+ const base = `${String(name).trim()} copy`;
+ if (!used.has(base.toLocaleLowerCase())) return base;
+ let index = 2;
+ while (used.has(`${base} ${index}`.toLocaleLowerCase())) index += 1;
+ return `${base} ${index}`;
+}
diff --git a/frontend/src/lib/analysisViews.test.js b/frontend/src/lib/analysisViews.test.js
new file mode 100644
index 0000000..c329c6a
--- /dev/null
+++ b/frontend/src/lib/analysisViews.test.js
@@ -0,0 +1,8 @@
+import { describe, expect, it } from 'vitest';
+import { copyName } from './analysisViews.js';
+
+describe('analysis view names', () => {
+ it('finds an unused duplicate name without a failing save first', () => {
+ expect(copyName('Ports', ['Ports', 'Ports copy', 'Ports copy 2'])).toBe('Ports copy 3');
+ });
+});
diff --git a/frontend/src/lib/bookmarks.js b/frontend/src/lib/bookmarks.js
index fc8901e..31e2092 100644
--- a/frontend/src/lib/bookmarks.js
+++ b/frontend/src/lib/bookmarks.js
@@ -5,7 +5,9 @@
* notes.js — the extension files the same shape over /api/ingest/bookmark when
* the open page isn't a map site.
*
- * Does not reload the case: the caller refetches once it returns.
+ * Does not reload the case: the caller refetches once it returns. Returns the
+ * entity, which is what lets the drawing put the new bookmark where it was pasted
+ * and the table open it — a caller that only needed it filed ignores the value.
*/
import { api } from './api.js';
@@ -14,7 +16,7 @@ export async function createBookmark(caseId, { title, url, folder = '', notes =
const target = (url ?? '').trim();
if (!label) throw new Error('Title required');
if (!/^https?:\/\//i.test(target)) throw new Error('Enter an http(s) URL');
- await api.post(`/api/cases/${caseId}/entities`, {
+ return api.post(`/api/cases/${caseId}/entities`, {
type: 'bookmark',
label,
attrs: { url: target, notes: (notes ?? '').trim(), folder: (folder ?? '').trim() },
diff --git a/frontend/src/lib/bookmarks.test.js b/frontend/src/lib/bookmarks.test.js
index cf675cf..034fe3e 100644
--- a/frontend/src/lib/bookmarks.test.js
+++ b/frontend/src/lib/bookmarks.test.js
@@ -43,3 +43,11 @@ describe('createBookmark', () => {
expect(api.post).not.toHaveBeenCalled();
});
});
+
+describe('what createBookmark hands back', () => {
+ it('returns the entity, so the drawing can place it and the table open it', async () => {
+ api.post.mockResolvedValueOnce({ id: 'ent-7', type: 'bookmark', label: 'Leak site' });
+ const entity = await createBookmark('case-1', { title: 'Leak site', url: 'https://x.example' });
+ expect(entity).toMatchObject({ id: 'ent-7' });
+ });
+});
diff --git a/frontend/src/lib/catalog.js b/frontend/src/lib/catalog.js
index e0762b1..ae5f90f 100644
--- a/frontend/src/lib/catalog.js
+++ b/frontend/src/lib/catalog.js
@@ -6,25 +6,104 @@ export function settleCatalogSummary(current, next, isCurrent) {
return isCurrent ? next : current;
}
-/** Build the catalog request path. Only the filters that are set appear.
- * `unfiled` (no folder) wins over an exact `folder` path when both are given. */
-export function buildCatalogQuery(
- caseId,
- { cursor, limit, types, status, query, folder, unfiled, recursive } = {}
+/**
+ * The narrowing itself, as request parameters. Only the terms that are set appear.
+ *
+ * `unfiled` (no folder) wins over an exact `folder` path when both are given.
+ * `attr` with `value` narrows on one stored field, `linked` on having a neighbour of
+ * that type and `unlinked` on having none at all; `since`, `until` and `by` ask how
+ * the row got here rather than what it says. A field with no value chosen is **not**
+ * sent: it is the analyst having picked what they are about to ask about, and asked
+ * as a term it would empty the table between two clicks of one act.
+ *
+ * Its own function because two readings ask the same question — the page lists the
+ * rows, the tally adds up the statements among them — and a term spelled twice is a
+ * term that eventually means two things.
+ */
+function narrowing(
+ {
+ types,
+ status,
+ query,
+ folder,
+ unfiled,
+ recursive,
+ attr,
+ value,
+ linked,
+ unlinked,
+ since,
+ until,
+ by,
+ temporalFrom,
+ temporalTo,
+ temporalCategories,
+ } = {},
+ params = new URLSearchParams()
) {
- const params = new URLSearchParams();
- if (limit != null) params.set('limit', String(limit));
- if (cursor) params.set('cursor', cursor);
if (types && types.length) params.set('type', types.join(','));
if (status) params.set('status', status);
if (query) params.set('q', query);
if (unfiled) params.set('unfiled', 'true');
else if (folder != null) params.set('folder', folder);
if (recursive) params.set('recursive', 'true');
+ if (attr && value) {
+ params.set('attr', attr);
+ params.set('value', value);
+ }
+ if (linked) params.set('linked', linked);
+ if (unlinked) params.set('unlinked', 'true');
+ if (since) params.set('since', since);
+ if (until) params.set('until', until);
+ if (by && by.length) params.set('by', by.join(','));
+ if (temporalFrom && temporalTo) {
+ params.set('temporal_from', temporalFrom);
+ params.set('temporal_to', temporalTo);
+ if (temporalCategories?.length) {
+ params.set('temporal_category', temporalCategories.join(','));
+ }
+ }
+ return params;
+}
+
+/** Build the catalog request path: the narrowing, plus what a *page* needs on top.
+ *
+ * `order` sorts the whole filtered set rather than the page — the difference between
+ * *the newest in this case* and *the newest of the rows already loaded*. */
+export function buildCatalogQuery(caseId, options = {}) {
+ const { cursor, limit, order, view } = options;
+ const params = new URLSearchParams();
+ if (limit != null) params.set('limit', String(limit));
+ if (cursor) params.set('cursor', cursor);
+ narrowing(options, params);
+ if (order) params.set('order', order);
+ if (view) params.set('view', view);
const qs = params.toString();
return `/api/cases/${caseId}/catalog/entities${qs ? `?${qs}` : ''}`;
}
+/** Build the tally request path: the same narrowing, added up instead of listed.
+ *
+ * Nothing about a page applies — a total has no cursor, no order of its own and no
+ * snapshot to read from, since a snapshot is a frozen copy of rows rather than a
+ * question the case can still be asked. */
+export function buildTallyQuery(caseId, options = {}) {
+ const qs = narrowing(options).toString();
+ return `/api/cases/${caseId}/catalog/tally${qs ? `?${qs}` : ''}`;
+}
+
+/** Which stored fields these types hold, and which values, as the menus a field
+ * filter is chosen from. Bounded server-side: a field with too many distinct values
+ * comes back with none of them and says it was cut. */
+export async function fetchAttrFacets(caseId, types, { get = api.get } = {}) {
+ if (!caseId) return [];
+ const params = new URLSearchParams();
+ if (types && types.length) params.set('type', types.join(','));
+ const qs = params.toString();
+ const body = await get(`/api/cases/${caseId}/catalog/attributes${qs ? `?${qs}` : ''}`);
+ return body?.attrs ?? [];
+}
+
/**
* Walk every page of the catalog and return the whole filtered list.
*
diff --git a/frontend/src/lib/catalog.test.js b/frontend/src/lib/catalog.test.js
index 99428f5..c5ee932 100644
--- a/frontend/src/lib/catalog.test.js
+++ b/frontend/src/lib/catalog.test.js
@@ -1,6 +1,7 @@
import { describe, expect, it } from 'vitest';
import {
- buildCatalogQuery, fetchAllEntities, lookupEntity, fetchDerivation, settleCatalogSummary,
+ buildCatalogQuery, fetchAllEntities, fetchAttrFacets, lookupEntity, fetchDerivation,
+ settleCatalogSummary,
} from './catalog.js';
describe('buildCatalogQuery', () => {
@@ -30,6 +31,79 @@ describe('buildCatalogQuery', () => {
'/api/cases/c1/catalog/entities?folder=Sources&recursive=true'
);
});
+
+ it('asks the sentence: one field holding one value, linked to a type', () => {
+ expect(
+ buildCatalogQuery('c1', {
+ types: ['media'],
+ attr: 'kind',
+ value: 'video',
+ linked: 'place',
+ })
+ ).toBe('/api/cases/c1/catalog/entities?type=media&attr=kind&value=video&linked=place');
+ });
+
+ it('leaves a field with no value out, since half an act is not a term', () => {
+ // The field is picked and its values have just been fetched. Sent as a term, the
+ // table would empty itself between two clicks of one act.
+ expect(buildCatalogQuery('c1', { attr: 'kind' })).toBe('/api/cases/c1/catalog/entities');
+ });
+
+ it('asks what the case connects to nothing, which no column reports', () => {
+ expect(buildCatalogQuery('c1', { unlinked: true })).toBe(
+ '/api/cases/c1/catalog/entities?unlinked=true'
+ );
+ });
+
+ it('asks how a row got here: when it was filed, and by what', () => {
+ expect(
+ buildCatalogQuery('c1', { since: '2026-08-03', until: '2026-08-10', by: ['user', 'satellite'] })
+ ).toBe('/api/cases/c1/catalog/entities?since=2026-08-03&until=2026-08-10&by=user%2Csatellite');
+ });
+
+ it('keeps fact time separate from filing time', () => {
+ expect(buildCatalogQuery('c1', {
+ temporalFrom: '2026-08-01T00:00:00Z',
+ temporalTo: '2026-09-01T00:00:00Z',
+ temporalCategories: ['statement', 'media'],
+ })).toBe(
+ '/api/cases/c1/catalog/entities?temporal_from=2026-08-01T00%3A00%3A00Z'
+ + '&temporal_to=2026-09-01T00%3A00%3A00Z&temporal_category=statement%2Cmedia'
+ );
+ });
+
+ it('orders the whole filtered set, and says nothing when it does not', () => {
+ expect(buildCatalogQuery('c1', { order: '-created' })).toBe(
+ '/api/cases/c1/catalog/entities?order=-created'
+ );
+ expect(buildCatalogQuery('c1', { order: '' })).toBe('/api/cases/c1/catalog/entities');
+ });
+
+ it('opens a frozen saved answer by its case-owned view id', () => {
+ expect(buildCatalogQuery('c1', { view: 'v_123' })).toBe(
+ '/api/cases/c1/catalog/entities?view=v_123'
+ );
+ });
+});
+
+describe('fetchAttrFacets — the menus a field filter is chosen from', () => {
+ it('narrows to the types being listed and unwraps the answer', async () => {
+ const asked = [];
+ const rows = await fetchAttrFacets('c1', ['media', 'capture'], {
+ get: async (path) => {
+ asked.push(path);
+ return { attrs: [{ key: 'kind', entities: 3, values: [], truncated: false }] };
+ },
+ });
+
+ expect(asked).toEqual(['/api/cases/c1/catalog/attributes?type=media%2Ccapture']);
+ expect(rows[0].key).toBe('kind');
+ });
+
+ it('answers with nothing rather than throwing when the read fails', async () => {
+ expect(await fetchAttrFacets('', [])).toEqual([]);
+ expect(await fetchAttrFacets('c1', [], { get: async () => null })).toEqual([]);
+ });
});
describe('settleCatalogSummary', () => {
diff --git a/frontend/src/lib/chain.js b/frontend/src/lib/chain.js
deleted file mode 100644
index 1922250..0000000
--- a/frontend/src/lib/chain.js
+++ /dev/null
@@ -1,146 +0,0 @@
-/**
- * Derivation chain: walking the case graph's links around one entity.
- *
- * The backend emits `derived-from` (an artifact and the sources it was made
- * from) and `depends-on` (a session and the subject it is worthless without)
- * at save time; this reads them back in both directions, so an entity can show
- * both what it came from and what was built on it.
- *
- * Entities carry `attrs.lost_sources` for sources deleted out from under them —
- * a source that is gone still shows in the chain, as a tombstone rather than a
- * link, so the trail never just ends.
- */
-
-export const DERIVED_FROM = 'derived-from';
-export const DEPENDS_ON = 'depends-on';
-
-const CHAIN_TYPES = [DERIVED_FROM, DEPENDS_ON];
-
-const byId = (entities) => new Map(entities.map((e) => [e.id, e]));
-
-/** Entities this one was made from or points at (outgoing links). */
-export function sourcesOf(entities, links, id) {
- const index = byId(entities);
- return links
- .filter((l) => l.from === id && CHAIN_TYPES.includes(l.type))
- .map((l) => ({ entity: index.get(l.to), type: l.type }))
- .filter((r) => r.entity);
-}
-
-/** Entities made from this one, or that could not exist without it (incoming). */
-export function dependentsOf(entities, links, id) {
- const index = byId(entities);
- return links
- .filter((l) => l.to === id && CHAIN_TYPES.includes(l.type))
- .map((l) => ({ entity: index.get(l.from), type: l.type }))
- .filter((r) => r.entity);
-}
-
-/** Sources that were deleted: kept as tombstones on the entity itself. */
-export function lostSourcesOf(entity) {
- return entity?.attrs?.lost_sources ?? [];
-}
-
-/**
- * Walk `derived-from`/`depends-on` upstream to the original — a proof's chain
- * back through its frame and its video to the download. Breadth-first, so the
- * closest source comes first; `depth` starts at 1 for a direct source.
- *
- * A cycle cannot happen through a save (an artifact is filed after its sources)
- * but the visited set makes the walk total regardless — a hand-edited case.json
- * must not hang the sidebar.
- */
-export function walkUp(entities, links, id, { maxDepth = 12 } = {}) {
- const out = [];
- const seen = new Set([id]);
- let frontier = [id];
- for (let depth = 1; depth <= maxDepth && frontier.length; depth++) {
- const next = [];
- for (const current of frontier) {
- for (const { entity, type } of sourcesOf(entities, links, current)) {
- if (seen.has(entity.id)) continue;
- seen.add(entity.id);
- out.push({ entity, type, depth });
- next.push(entity.id);
- }
- }
- frontier = next;
- }
- return out;
-}
-
-/** The mirror of `walkUp`: everything built on this entity, however indirectly. */
-export function walkDown(entities, links, id, { maxDepth = 12 } = {}) {
- const out = [];
- const seen = new Set([id]);
- let frontier = [id];
- for (let depth = 1; depth <= maxDepth && frontier.length; depth++) {
- const next = [];
- for (const current of frontier) {
- for (const { entity, type } of dependentsOf(entities, links, current)) {
- if (seen.has(entity.id)) continue;
- seen.add(entity.id);
- out.push({ entity, type, depth });
- next.push(entity.id);
- }
- }
- frontier = next;
- }
- return out;
-}
-
-/**
- * Everything the Details panel needs for one entity: its direct sources (live
- * and lost), what depends on it, and whether there is any chain at all — the
- * panel hides the section entirely rather than showing an empty shell.
- */
-export function chainOf(entities, links, id) {
- const entity = entities.find((e) => e.id === id) ?? null;
- const sources = sourcesOf(entities, links, id);
- const lost = lostSourcesOf(entity);
- const dependents = dependentsOf(entities, links, id);
- return {
- entity,
- sources,
- lost,
- dependents,
- empty: !sources.length && !lost.length && !dependents.length,
- };
-}
-
-/**
- * What deleting this entity would do, computed the same way the backend does
- * (engine/links.py) — `depends-on` cascades transitively, `derived-from` never
- * does. The dialog still asks the backend for the authoritative plan; this
- * mirror is what lets the sidebar warn without a round-trip.
- */
-export function deletePlan(entities, links, id) {
- const index = byId(entities);
- const doomed = [id];
- const frontier = [id];
- while (frontier.length) {
- const current = frontier.pop();
- for (const l of links) {
- if (l.to === current && l.type === DEPENDS_ON && !doomed.includes(l.from) && index.has(l.from)) {
- doomed.push(l.from);
- frontier.push(l.from);
- }
- }
- }
- const scarred = [];
- for (const l of links) {
- if (
- doomed.includes(l.to) &&
- l.type === DERIVED_FROM &&
- !doomed.includes(l.from) &&
- !scarred.includes(l.from) &&
- index.has(l.from)
- ) {
- scarred.push(l.from);
- }
- }
- return {
- cascade: doomed.slice(1).map((i) => index.get(i)),
- tombstone: scarred.map((i) => index.get(i)),
- };
-}
diff --git a/frontend/src/lib/chain.test.js b/frontend/src/lib/chain.test.js
deleted file mode 100644
index 0283754..0000000
--- a/frontend/src/lib/chain.test.js
+++ /dev/null
@@ -1,161 +0,0 @@
-import { describe, it, expect } from 'vitest';
-import {
- chainOf,
- deletePlan,
- dependentsOf,
- lostSourcesOf,
- sourcesOf,
- walkDown,
- walkUp,
-} from './chain.js';
-
-const ent = (id, type, attrs = {}) => ({ id, type, label: id, attrs });
-const link = (from, to, type = 'derived-from') => ({ id: `l_${from}${to}`, from, to, type });
-
-// The v1 workflow, filed: a download, a frame cut from it, a proof composed
-// from that frame, the post announcing the proof, and a session over the video.
-const entities = [
- ent('video', 'media', { path: 'media/v.mp4', sha256: 'abc', source_url: 'https://x/1' }),
- ent('frame', 'media', { path: 'media/f.png' }),
- ent('proof', 'proof', { spec: 'proofs/.meta/p.json', path: 'proofs/p.png' }),
- ent('post', 'post', { draft: 'exports/d.json' }),
- ent('session', 'inspect-session', { spec: 'inspect/s.json' }),
-];
-const links = [
- link('frame', 'video'),
- link('proof', 'frame'),
- link('post', 'proof'),
- link('session', 'video', 'depends-on'),
-];
-
-describe('sourcesOf / dependentsOf', () => {
- it('reads the two directions of an edge', () => {
- expect(sourcesOf(entities, links, 'frame').map((r) => r.entity.id)).toEqual(['video']);
- expect(dependentsOf(entities, links, 'video').map((r) => r.entity.id)).toEqual([
- 'frame',
- 'session',
- ]);
- });
-
- it('reports the link type so the UI can tell a derivation from a dependency', () => {
- expect(dependentsOf(entities, links, 'video').map((r) => r.type)).toEqual([
- 'derived-from',
- 'depends-on',
- ]);
- });
-
- it('ignores links to entities that are not in the case', () => {
- const dangling = [...links, link('proof', 'ghost')];
- expect(sourcesOf(entities, dangling, 'proof').map((r) => r.entity.id)).toEqual(['frame']);
- });
-
- it('ignores link types that are not part of the chain', () => {
- const withOther = [...links, link('proof', 'video', 'mentions')];
- expect(sourcesOf(entities, withOther, 'proof').map((r) => r.entity.id)).toEqual(['frame']);
- });
-});
-
-describe('walkUp', () => {
- it('climbs to the original, closest source first, with depth', () => {
- expect(walkUp(entities, links, 'post')).toEqual([
- { entity: entities[2], type: 'derived-from', depth: 1 },
- { entity: entities[1], type: 'derived-from', depth: 2 },
- { entity: entities[0], type: 'derived-from', depth: 3 },
- ]);
- });
-
- it('terminates on a cycle instead of hanging the sidebar', () => {
- const cyclic = [link('a', 'b'), link('b', 'a')];
- const pair = [ent('a', 'media'), ent('b', 'media')];
- expect(walkUp(pair, cyclic, 'a').map((r) => r.entity.id)).toEqual(['b']);
- });
-
- it('honours maxDepth', () => {
- expect(walkUp(entities, links, 'post', { maxDepth: 1 }).map((r) => r.entity.id)).toEqual([
- 'proof',
- ]);
- });
-});
-
-describe('walkDown', () => {
- it('finds everything built on a source, however indirectly', () => {
- expect(walkDown(entities, links, 'video').map((r) => r.entity.id)).toEqual([
- 'frame',
- 'session',
- 'proof',
- 'post',
- ]);
- });
-});
-
-describe('lostSourcesOf', () => {
- it('reads the tombstones, missing → empty', () => {
- const scarred = ent('x', 'proof', { lost_sources: [{ path: 'media/gone.mp4', sha256: 'd' }] });
- expect(lostSourcesOf(scarred)).toHaveLength(1);
- expect(lostSourcesOf(ent('y', 'proof'))).toEqual([]);
- expect(lostSourcesOf(null)).toEqual([]);
- });
-});
-
-describe('chainOf', () => {
- it('gathers both directions plus tombstones for one entity', () => {
- const chain = chainOf(entities, links, 'proof');
- expect(chain.sources.map((r) => r.entity.id)).toEqual(['frame']);
- expect(chain.dependents.map((r) => r.entity.id)).toEqual(['post']);
- expect(chain.empty).toBe(false);
- });
-
- it('flags an entity with no chain at all so the panel can hide the section', () => {
- const lonely = [...entities, ent('place', 'place')];
- expect(chainOf(lonely, links, 'place').empty).toBe(true);
- });
-
- it('is not empty when the only trace left is a tombstone', () => {
- const scarred = [ent('p', 'proof', { lost_sources: [{ path: 'media/gone.mp4' }] })];
- expect(chainOf(scarred, [], 'p').empty).toBe(false);
- });
-});
-
-describe('deletePlan', () => {
- it('takes the session down with its subject and leaves the outputs standing', () => {
- const plan = deletePlan(entities, links, 'video');
- expect(plan.cascade.map((e) => e.id)).toEqual(['session']);
- expect(plan.tombstone.map((e) => e.id)).toEqual(['frame']);
- });
-
- it('never cascades through derived-from: deleting a proof spares its post', () => {
- const plan = deletePlan(entities, links, 'proof');
- expect(plan.cascade).toEqual([]);
- expect(plan.tombstone.map((e) => e.id)).toEqual(['post']);
- });
-
- it('cascades depends-on transitively', () => {
- const chained = [...entities, ent('sub', 'inspect-session', { spec: 'inspect/2.json' })];
- const deep = [...links, link('sub', 'session', 'depends-on')];
- expect(deletePlan(chained, deep, 'video').cascade.map((e) => e.id)).toEqual(['session', 'sub']);
- });
-
- it('spares a session whose own subject survives the delete', () => {
- // a session opened over the frame, not the video: deleting the video scars
- // the frame but leaves it in place, so the session over it still stands.
- const more = [...entities, ent('session2', 'inspect-session', { spec: 'inspect/2.json' })];
- const deep = [...links, link('session2', 'frame', 'depends-on')];
- const plan = deletePlan(more, deep, 'video');
- expect(plan.cascade.map((e) => e.id)).toEqual(['session']);
- expect(plan.tombstone.map((e) => e.id)).toEqual(['frame']);
- });
-
- it('does not tombstone an entity that is itself being deleted', () => {
- // a producer that files both edges onto the same target: the depends-on
- // dooms the session, so its derived-from must not also list it as a
- // survivor to scar — a doomed entity is never tombstoned.
- const deep = [...links, link('session', 'video')];
- const plan = deletePlan(entities, deep, 'video');
- expect(plan.cascade.map((e) => e.id)).toEqual(['session']);
- expect(plan.tombstone.map((e) => e.id)).toEqual(['frame']);
- });
-
- it('reports nothing for an entity nothing hangs off', () => {
- expect(deletePlan(entities, links, 'post')).toEqual({ cascade: [], tombstone: [] });
- });
-});
diff --git a/frontend/src/lib/clipboardPaste.js b/frontend/src/lib/clipboardPaste.js
new file mode 100644
index 0000000..2620715
--- /dev/null
+++ b/frontend/src/lib/clipboardPaste.js
@@ -0,0 +1,196 @@
+/**
+ * What Ctrl+V means on each surface.
+ *
+ * The clipboard is the one place an analyst already holds material Azimut has
+ * never seen: a crop taken with the system screenshot tool exists nowhere on
+ * disk, and an address copied out of a browser is one keystroke from a bookmark.
+ * Dropping a file already works wherever it makes sense, so this covers the two
+ * things that have no file to drop.
+ *
+ * No surface takes everything, and a paste that quietly does nothing is worse
+ * than one that says why: `resolvePaste` answers with a form to fill or a refusal
+ * to read, never with silence. The refusals live in the table below rather than in
+ * four tools, because scattered copy becomes four vocabularies inside a week.
+ */
+import { api } from './api.js';
+
+const IMAGE_TYPE = /^image\//i;
+const HTTP_URL = /^https?:\/\/\S+$/i;
+
+/** The API's own cap on a swallowed image (api/limits.py), said here so the
+ * refusal names the limit instead of waiting for a 413. */
+export const MAX_PASTE_IMAGE_BYTES = 25 * 1024 * 1024;
+
+/**
+ * The http(s) address of the first `<img>` in a copied HTML fragment.
+ *
+ * An image copied out of a page carries the markup beside the pixels, and the
+ * markup is where the image's own address is. Worth reading because a pasted
+ * screenshot otherwise arrives with no origin at all.
+ */
+export function sourceFromHtml(html) {
+ const match = /<img\b[^>]*?\bsrc\s*=\s*(?:"([^"]*)"|'([^']*)')/i.exec(html ?? '');
+ const url = (match?.[1] ?? match?.[2] ?? '').trim();
+ return HTTP_URL.test(url) ? url : '';
+}
+
+function imageFrom(clipboardData) {
+ const items = [...(clipboardData.items ?? [])];
+ for (const item of items) {
+ if (item.kind === 'file' && IMAGE_TYPE.test(item.type ?? '')) {
+ const file = item.getAsFile?.();
+ if (file) return file;
+ }
+ }
+ return [...(clipboardData.files ?? [])].find((file) => IMAGE_TYPE.test(file.type ?? '')) ?? null;
+}
+
+/**
+ * What the clipboard is offering, or null when it holds nothing a case could take.
+ *
+ * An image wins over a link, because a screenshot copied from a browser carries
+ * both — the pixels and the page they were on — and the pixels are the thing being
+ * pasted. The address rides along as the image's source instead of competing with it.
+ */
+export function readPaste(clipboardData) {
+ if (!clipboardData) return null;
+ const text = (clipboardData.getData?.('text/plain') ?? '').trim();
+ const file = imageFrom(clipboardData);
+ if (file) {
+ const fromMarkup = sourceFromHtml(clipboardData.getData?.('text/html') ?? '');
+ return { kind: 'image', file, sourceUrl: fromMarkup || (HTTP_URL.test(text) ? text : '') };
+ }
+ if (HTTP_URL.test(text)) return { kind: 'url', url: text };
+ if (text) return { kind: 'text', text };
+ return null;
+}
+
+/**
+ * What each surface takes, and what it says when it will not take something.
+ *
+ * `fields` is what the dialog asks for, in the order it asks. A folder is offered
+ * only where filing is the surface's whole job: pasted into the drawing or the
+ * table, a thing lands unfiled, exactly as a dropped file does there today.
+ */
+export const PASTE_RULES = {
+ media: {
+ image: { fields: ['title', 'source'] },
+ url: { refuse: 'A link here is a download. Paste it in the URL field above the grid.' },
+ },
+ files: {
+ image: { fields: ['title', 'folder', 'source'] },
+ url: { fields: ['title', 'folder', 'notes'] },
+ },
+ graph: {
+ image: { fields: ['title', 'source'] },
+ url: { fields: ['title', 'notes'] },
+ },
+ board: {
+ image: { fields: ['title', 'source'] },
+ url: { fields: ['title', 'notes'] },
+ },
+};
+
+/** Said wherever a surface takes neither: the clipboard held something, and this
+ * screen is not where it goes. */
+const TEXT_REFUSAL = 'Only an image or a link can be pasted into a case. Text belongs in a note.';
+
+const OVERSIZE_REFUSAL =
+ `That image is over ${MAX_PASTE_IMAGE_BYTES / 1024 / 1024} MB. ` +
+ 'Save it to a file and drop it in instead.';
+
+/** The hostname a pasted link is named after until the analyst types something
+ * better. The same default the extension's own bookmark route applies. */
+export function hostOf(url) {
+ try {
+ return new URL(url).hostname;
+ } catch {
+ return '';
+ }
+}
+
+function pasteDefaults(payload, folder) {
+ return {
+ title: payload.kind === 'url' ? hostOf(payload.url) : '',
+ source: payload.kind === 'image' ? payload.sourceUrl ?? '' : '',
+ folder: folder ?? '',
+ notes: '',
+ };
+}
+
+/**
+ * Turn one clipboard reading into what the dialog should show on this surface.
+ *
+ * Returns null only when there is nothing to say at all — an empty clipboard, or a
+ * surface that does not take pastes — so a caller can treat a resolution as "open
+ * the dialog" without a second test.
+ */
+export function resolvePaste(tool, payload, { folder = '' } = {}) {
+ const rules = PASTE_RULES[tool];
+ if (!rules || !payload) return null;
+ const rule = rules[payload.kind];
+ if (!rule) return { mode: 'refuse', kind: payload.kind, reason: TEXT_REFUSAL };
+ if (rule.refuse) return { mode: 'refuse', kind: payload.kind, reason: rule.refuse };
+ if (payload.kind === 'image' && payload.file?.size > MAX_PASTE_IMAGE_BYTES) {
+ return { mode: 'refuse', kind: payload.kind, reason: OVERSIZE_REFUSAL };
+ }
+ return {
+ mode: 'form',
+ kind: payload.kind,
+ fields: [...rule.fields],
+ payload,
+ values: pasteDefaults(payload, folder),
+ };
+}
+
+/** What is wrong with the dialog as filled in, or '' when nothing is. */
+export function pasteProblem(resolved) {
+ const values = resolved?.values ?? {};
+ if (resolved?.kind === 'url' && !(values.title ?? '').trim()) return 'A bookmark needs a title.';
+ const source = (values.source ?? '').trim();
+ if (source && !HTTP_URL.test(source)) return 'The source must be an http(s) address.';
+ return '';
+}
+
+/**
+ * Listen for a paste on this surface, and hand over what it held.
+ *
+ * Returns the teardown, so a tool installs it inside an `$effect` gated on being
+ * the tool on screen: every tab the analyst has opened stays mounted behind the
+ * visible one (App.svelte), so a listener that did not check would have four
+ * surfaces answering one Ctrl+V. A paste into a field is left alone — there,
+ * Ctrl+V is the ordinary one.
+ */
+export function listenForPaste(handler) {
+ const onPaste = (event) => {
+ if (ignorePasteTarget(event.target)) return;
+ const payload = readPaste(event.clipboardData);
+ if (!payload) return;
+ event.preventDefault();
+ handler(payload);
+ };
+ window.addEventListener('paste', onPaste);
+ return () => window.removeEventListener('paste', onPaste);
+}
+
+/** Whether this paste belongs to whatever the analyst is typing into. */
+export function ignorePasteTarget(target) {
+ const editable = 'input, textarea, select, [contenteditable=""], [contenteditable="true"]';
+ return Boolean(target?.closest?.(editable));
+}
+
+/**
+ * File a pasted image as case media.
+ *
+ * Its own route rather than the upload one: a paste has no file behind it and no
+ * origin the bytes can be read for, so the name comes from the dialog and the
+ * source is whatever was typed beside it. Does not reload the case — the caller
+ * refetches once, as every other import here does.
+ */
+export async function pasteImage(caseId, { file, title = '', sourceUrl = '' }) {
+ const form = new FormData();
+ form.append('file', file);
+ if (title.trim()) form.append('title', title.trim());
+ if (sourceUrl.trim()) form.append('source_url', sourceUrl.trim());
+ return api.post(`/api/cases/${caseId}/media/paste`, form);
+}
diff --git a/frontend/src/lib/clipboardPaste.test.js b/frontend/src/lib/clipboardPaste.test.js
new file mode 100644
index 0000000..dafb9d0
--- /dev/null
+++ b/frontend/src/lib/clipboardPaste.test.js
@@ -0,0 +1,292 @@
+// @vitest-environment happy-dom
+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
+import { api } from './api.js';
+import {
+ hostOf,
+ ignorePasteTarget,
+ listenForPaste,
+ MAX_PASTE_IMAGE_BYTES,
+ pasteImage,
+ pasteProblem,
+ PASTE_RULES,
+ readPaste,
+ resolvePaste,
+ sourceFromHtml,
+} from './clipboardPaste.js';
+
+vi.mock('./api.js', () => ({ api: { post: vi.fn(async () => ({ entity: { id: 'e1' } })) } }));
+
+/** A clipboard as the browser hands one over: typed entries plus the flat file list. */
+function clipboard({ image = null, text = '', html = '', size = 1024 } = {}) {
+ const file = image ? { type: image, size, name: 'image.png' } : null;
+ const data = { 'text/plain': text, 'text/html': html };
+ return {
+ items: file ? [{ kind: 'file', type: image, getAsFile: () => file }] : [],
+ files: file ? [file] : [],
+ getData: (type) => data[type] ?? '',
+ file,
+ };
+}
+
+describe('reading one paste', () => {
+ it('takes the image when the clipboard carries pixels', () => {
+ const cd = clipboard({ image: 'image/png' });
+ expect(readPaste(cd)).toMatchObject({ kind: 'image', file: cd.file, sourceUrl: '' });
+ });
+
+ it('keeps the page an image was copied from as its source', () => {
+ // a screenshot copied out of a browser carries the markup beside the pixels,
+ // and that markup is the only place the image's own address exists
+ const cd = clipboard({
+ image: 'image/png',
+ html: '<meta charset="utf-8"><img alt="x" src="https://example.com/shot.png" width="800">',
+ });
+ expect(readPaste(cd).sourceUrl).toBe('https://example.com/shot.png');
+ });
+
+ it('falls back to the copied text as the source when the markup has none', () => {
+ const cd = clipboard({ image: 'image/png', text: 'https://example.com/page' });
+ expect(readPaste(cd).sourceUrl).toBe('https://example.com/page');
+ });
+
+ it('lets pixels win over the link that came with them', () => {
+ // the analyst pasted an image; the address is context, not the other candidate
+ const cd = clipboard({ image: 'image/png', text: 'https://example.com/page' });
+ expect(readPaste(cd).kind).toBe('image');
+ });
+
+ it('reads a lone http(s) address as a link', () => {
+ expect(readPaste(clipboard({ text: 'https://example.com/x?a=1' }))).toEqual({
+ kind: 'url',
+ url: 'https://example.com/x?a=1',
+ });
+ });
+
+ it('does not mistake a sentence containing an address for a link', () => {
+ expect(readPaste(clipboard({ text: 'see https://example.com for more' }))).toMatchObject({
+ kind: 'text',
+ });
+ });
+
+ it('reads anything else as text, and an empty clipboard as nothing', () => {
+ expect(readPaste(clipboard({ text: 'some notes' }))).toEqual({ kind: 'text', text: 'some notes' });
+ expect(readPaste(clipboard())).toBeNull();
+ expect(readPaste(null)).toBeNull();
+ });
+
+ it('takes the file list when an item entry hands back nothing', () => {
+ // Safari has been known to list the entry and refuse the file
+ const cd = clipboard({ image: 'image/png' });
+ cd.items = [{ kind: 'file', type: 'image/png', getAsFile: () => null }];
+ expect(readPaste(cd)).toMatchObject({ kind: 'image', file: cd.file });
+ });
+
+ it('ignores a non-image file entry', () => {
+ const cd = clipboard();
+ cd.items = [{ kind: 'file', type: 'application/pdf', getAsFile: () => ({ type: 'application/pdf' }) }];
+ expect(readPaste(cd)).toBeNull();
+ });
+});
+
+describe('the source read off copied markup', () => {
+ it('accepts either quoting', () => {
+ expect(sourceFromHtml("<img src='https://a.example/1.png'>")).toBe('https://a.example/1.png');
+ expect(sourceFromHtml('<img src="https://a.example/2.png">')).toBe('https://a.example/2.png');
+ });
+
+ it('refuses anything that is not an http(s) address', () => {
+ // a data: URI is the pixels again, not a provenance, and javascript: is worse
+ expect(sourceFromHtml('<img src="data:image/png;base64,AAA">')).toBe('');
+ expect(sourceFromHtml('<img src="javascript:alert(1)">')).toBe('');
+ expect(sourceFromHtml('')).toBe('');
+ expect(sourceFromHtml(null)).toBe('');
+ });
+});
+
+describe('what each surface takes', () => {
+ const image = { kind: 'image', file: { type: 'image/png', size: 2048 }, sourceUrl: '' };
+ const url = { kind: 'url', url: 'https://example.com/page' };
+ const text = { kind: 'text', text: 'hello' };
+
+ it('files an image on all four surfaces', () => {
+ for (const tool of ['media', 'files', 'graph', 'board']) {
+ expect(resolvePaste(tool, image)).toMatchObject({ mode: 'form', kind: 'image' });
+ }
+ });
+
+ it('refuses a link in Media, and says where it does work', () => {
+ // Media takes files; a link there means a download, which has its own field
+ const resolved = resolvePaste('media', url);
+ expect(resolved.mode).toBe('refuse');
+ expect(resolved.reason).toContain('URL field');
+ });
+
+ it('makes a bookmark of a link everywhere else', () => {
+ for (const tool of ['files', 'graph', 'board']) {
+ expect(resolvePaste(tool, url)).toMatchObject({ mode: 'form', kind: 'url' });
+ }
+ });
+
+ it('refuses text on every surface rather than doing nothing', () => {
+ for (const tool of ['media', 'files', 'graph', 'board']) {
+ const resolved = resolvePaste(tool, text);
+ expect(resolved.mode).toBe('refuse');
+ expect(resolved.reason).toContain('note');
+ }
+ });
+
+ it('refuses an image over the API cap, naming the limit', () => {
+ const huge = { ...image, file: { type: 'image/png', size: MAX_PASTE_IMAGE_BYTES + 1 } };
+ const resolved = resolvePaste('media', huge);
+ expect(resolved.mode).toBe('refuse');
+ expect(resolved.reason).toContain('25 MB');
+ });
+
+ it('offers a folder only where filing is what the surface is for', () => {
+ expect(PASTE_RULES.files.image.fields).toContain('folder');
+ expect(PASTE_RULES.files.url.fields).toContain('folder');
+ for (const tool of ['media', 'graph', 'board']) {
+ expect(PASTE_RULES[tool].image.fields).not.toContain('folder');
+ }
+ });
+
+ it('says nothing at all for an empty clipboard or a surface without a rule', () => {
+ expect(resolvePaste('media', null)).toBeNull();
+ expect(resolvePaste('satellite', image)).toBeNull();
+ });
+});
+
+describe('what the dialog opens on', () => {
+ it('names a pasted link after its host, so the title is never blank', () => {
+ const resolved = resolvePaste('files', { kind: 'url', url: 'https://leak.example.com/a/b' });
+ expect(resolved.values.title).toBe('leak.example.com');
+ });
+
+ it('opens on the folder the analyst is standing in', () => {
+ const resolved = resolvePaste('files', { kind: 'url', url: 'https://x.example' }, {
+ folder: 'Sources',
+ });
+ expect(resolved.values.folder).toBe('Sources');
+ });
+
+ it('prefills an image source with the page it was copied from', () => {
+ const resolved = resolvePaste('graph', {
+ kind: 'image',
+ file: { type: 'image/png', size: 10 },
+ sourceUrl: 'https://example.com/shot.png',
+ });
+ expect(resolved.values.source).toBe('https://example.com/shot.png');
+ expect(resolved.values.title).toBe('');
+ });
+
+ it('holds a bookmark until it has a title, and an image needs none', () => {
+ const bookmark = resolvePaste('files', { kind: 'url', url: 'https://x.example' });
+ expect(pasteProblem(bookmark)).toBe('');
+ bookmark.values.title = ' ';
+ expect(pasteProblem(bookmark)).toContain('title');
+
+ const image = resolvePaste('media', { kind: 'image', file: { type: 'image/png', size: 1 } });
+ expect(pasteProblem(image)).toBe('');
+ });
+
+ it('refuses a typed source that is not an http(s) address', () => {
+ const image = resolvePaste('media', { kind: 'image', file: { type: 'image/png', size: 1 } });
+ image.values.source = 'not a url';
+ expect(pasteProblem(image)).toContain('http(s)');
+ image.values.source = 'https://example.com/x';
+ expect(pasteProblem(image)).toBe('');
+ });
+
+ it('reads a host off an address, and nothing off a broken one', () => {
+ expect(hostOf('https://a.b.example/c')).toBe('a.b.example');
+ expect(hostOf('nonsense')).toBe('');
+ });
+});
+
+describe('the window listener', () => {
+ let off = null;
+ afterEach(() => {
+ off?.();
+ off = null;
+ });
+
+ function paste(cd, target = document.body) {
+ const event = new Event('paste', { bubbles: true, cancelable: true });
+ Object.defineProperty(event, 'clipboardData', { value: cd });
+ Object.defineProperty(event, 'target', { value: target });
+ window.dispatchEvent(event);
+ return event;
+ }
+
+ it('hands over what the clipboard held and keeps the browser out of it', () => {
+ const seen = [];
+ off = listenForPaste((payload) => seen.push(payload));
+ const event = paste(clipboard({ text: 'https://example.com/x' }));
+ expect(seen).toEqual([{ kind: 'url', url: 'https://example.com/x' }]);
+ expect(event.defaultPrevented).toBe(true);
+ });
+
+ it('leaves a paste into a field alone', () => {
+ // in a search box or a title input, Ctrl+V is the ordinary one
+ const input = document.createElement('input');
+ document.body.append(input);
+ const seen = [];
+ off = listenForPaste((payload) => seen.push(payload));
+ const event = paste(clipboard({ text: 'https://example.com/x' }), input);
+ expect(seen).toEqual([]);
+ expect(event.defaultPrevented).toBe(false);
+ input.remove();
+ });
+
+ it('stays quiet on an empty clipboard', () => {
+ const seen = [];
+ off = listenForPaste((payload) => seen.push(payload));
+ const event = paste(clipboard());
+ expect(seen).toEqual([]);
+ expect(event.defaultPrevented).toBe(false);
+ });
+
+ it('stops listening once torn down, which is what keeps hidden tabs quiet', () => {
+ // every visited tool stays mounted behind the visible one, so the teardown is
+ // the whole guard against four surfaces answering one Ctrl+V
+ const seen = [];
+ listenForPaste((payload) => seen.push(payload))();
+ paste(clipboard({ text: 'https://example.com/x' }));
+ expect(seen).toEqual([]);
+ });
+
+ it('reads an editable target through the node that was clicked', () => {
+ const box = document.createElement('div');
+ box.setAttribute('contenteditable', 'true');
+ const inner = document.createElement('span');
+ box.append(inner);
+ document.body.append(box);
+ expect(ignorePasteTarget(inner)).toBe(true);
+ expect(ignorePasteTarget(document.body)).toBe(false);
+ expect(ignorePasteTarget(undefined)).toBe(false);
+ box.remove();
+ });
+});
+
+describe('filing a pasted image', () => {
+ beforeEach(() => api.post.mockClear());
+
+ it('posts to the paste route with the title and the source typed beside it', async () => {
+ const file = new File([new Uint8Array([1, 2, 3])], 'image.png', { type: 'image/png' });
+ await pasteImage('case-1', { file, title: ' Front gate ', sourceUrl: ' https://e.example/x ' });
+ const [path, form] = api.post.mock.calls[0];
+ expect(path).toBe('/api/cases/case-1/media/paste');
+ expect(form.get('file')).toBe(file);
+ expect(form.get('title')).toBe('Front gate');
+ expect(form.get('source_url')).toBe('https://e.example/x');
+ });
+
+ it('sends neither field when the analyst filled in nothing', async () => {
+ await pasteImage('case-1', {
+ file: new File([new Uint8Array([1])], 'image.png', { type: 'image/png' }),
+ });
+ const form = api.post.mock.calls[0][1];
+ expect(form.has('title')).toBe(false);
+ expect(form.has('source_url')).toBe(false);
+ });
+});
diff --git a/frontend/src/lib/composer.js b/frontend/src/lib/composer.js
index 66cbe05..b44ac45 100644
--- a/frontend/src/lib/composer.js
+++ b/frontend/src/lib/composer.js
@@ -837,6 +837,11 @@ export function toSpec(proof) {
templateId: typeof proof.templateId === 'string' ? proof.templateId : null,
coords: autoCoords(proof.panels), // auto geo (first geo panel), for reference
coordsText: proof.coordsText?.trim() ? proof.coordsText.trim() : null, // null → auto
+ // Whether the point is where the camera stood rather than what it filmed.
+ // The proof cannot deduce it — a rooftop shot is recorded somewhere it never
+ // shows — so the analyst says, and the place filed on save takes the verb
+ // from it (engine/satellite.place_for_proof).
+ pov: proof.pov === true,
source: proof.source?.trim() ? proof.source.trim() : null, // null → auto (link only)
captionSize: proof.captionSize ?? CAPTION_SIZE,
legendSize: proof.legendSize ?? LEGEND_SIZE,
diff --git a/frontend/src/lib/dismiss.js b/frontend/src/lib/dismiss.js
new file mode 100644
index 0000000..abb99e2
--- /dev/null
+++ b/frontend/src/lib/dismiss.js
@@ -0,0 +1,16 @@
+/**
+ * Close a popover when the pointer goes down anywhere outside it.
+ *
+ * `pointerdown` rather than `click`: a menu that only closes on a completed click
+ * stays open while the press lands on a map or a canvas that swallows the click, and
+ * the same press then means two things. Returns the teardown, so the whole use is
+ * `$effect(() => open ? closeOnOutsidePointer(element, () => (open = false)) : undefined)`.
+ */
+export function closeOnOutsidePointer(element, close) {
+ if (typeof document === 'undefined') return undefined;
+ const outside = (event) => {
+ if (!element?.contains(event.target)) close();
+ };
+ document.addEventListener('pointerdown', outside);
+ return () => document.removeEventListener('pointerdown', outside);
+}
diff --git a/frontend/src/lib/dismiss.test.js b/frontend/src/lib/dismiss.test.js
new file mode 100644
index 0000000..7f49bb0
--- /dev/null
+++ b/frontend/src/lib/dismiss.test.js
@@ -0,0 +1,56 @@
+// @vitest-environment happy-dom
+import { afterEach, describe, expect, it, vi } from 'vitest';
+import { closeOnOutsidePointer } from './dismiss.js';
+
+afterEach(() => {
+ vi.unstubAllGlobals();
+ document.body.innerHTML = '';
+});
+
+describe('closeOnOutsidePointer', () => {
+ it('leaves the popover open when the press lands inside it', () => {
+ const popover = document.createElement('div');
+ const child = document.createElement('button');
+ popover.append(child);
+ document.body.append(popover);
+ const close = vi.fn();
+ const teardown = closeOnOutsidePointer(popover, close);
+
+ child.dispatchEvent(new Event('pointerdown', { bubbles: true }));
+
+ expect(close).not.toHaveBeenCalled();
+ teardown();
+ });
+
+ it('closes when the press lands outside it', () => {
+ const popover = document.createElement('div');
+ const outside = document.createElement('button');
+ document.body.append(popover, outside);
+ const close = vi.fn();
+ const teardown = closeOnOutsidePointer(popover, close);
+
+ outside.dispatchEvent(new Event('pointerdown', { bubbles: true }));
+
+ expect(close).toHaveBeenCalledOnce();
+ teardown();
+ });
+
+ it('stops listening after teardown', () => {
+ const popover = document.createElement('div');
+ const outside = document.createElement('button');
+ document.body.append(popover, outside);
+ const close = vi.fn();
+ const teardown = closeOnOutsidePointer(popover, close);
+
+ teardown();
+ outside.dispatchEvent(new Event('pointerdown', { bubbles: true }));
+
+ expect(close).not.toHaveBeenCalled();
+ });
+
+ it('does nothing when rendered without a document', () => {
+ vi.stubGlobal('document', undefined);
+
+ expect(closeOnOutsidePointer(null, vi.fn())).toBeUndefined();
+ });
+});
diff --git a/frontend/src/lib/entityFilter.js b/frontend/src/lib/entityFilter.js
new file mode 100644
index 0000000..ce36b12
--- /dev/null
+++ b/frontend/src/lib/entityFilter.js
@@ -0,0 +1,405 @@
+/**
+ * The question the Board is asking of the case, as a value.
+ *
+ * A filter used to be six `$state` variables and six selects, each appearing and
+ * disappearing as the others were set. That shape had two faults and they were the
+ * same fault twice: a term that was set looked exactly like a term that was not, and
+ * a control that vanished took its own way back with it. So the question is one
+ * object here, every term is a **chip** on screen, and the bar itself never changes
+ * shape — what changes is the sentence written across it.
+ *
+ * Nothing in this file touches the network, the registry or Svelte. It turns a
+ * question into request parameters and into the words that describe it, which is
+ * exactly what can be tested without a browser.
+ *
+ * **Every term is chosen, never typed** (SPEC anti-goals): the menus behind these
+ * keys are built from what the case holds. The one free-text term is `q`, and it is
+ * the search box rather than a term of the sentence.
+ */
+
+/**
+ * The axes, in the order the "+ Filter" menu offers them.
+ *
+ * `kind` is what the menu has to draw, not what the server does with it:
+ * - `picks` — several values at once, since *accounts and people* is one question
+ * - `pick` — one value
+ * - `folder` — one path, plus "unfiled" and "include subfolders", which are the two
+ * halves the catalog already spells apart
+ * - `field` — a stored field **and** one of its values: two steps, one term
+ * - `toggle` — no value to choose, so picking it from the menu is the whole act
+ */
+export const AXES = [
+ {
+ key: 'field',
+ label: 'Field',
+ kind: 'field',
+ hint: 'a value the case stored, such as kind = video',
+ },
+ { key: 'type', label: 'Type', kind: 'picks', hint: 'exactly what the case calls it' },
+ { key: 'family', label: 'Family', kind: 'picks', hint: 'the broad reading: who, what, where' },
+ { key: 'folder', label: 'Folder', kind: 'folder', hint: 'one of your own buckets' },
+ { key: 'status', label: 'Status', kind: 'pick', hint: 'confirmed, or proposed by a tool' },
+ { key: 'linked', label: 'Linked to', kind: 'pick', hint: 'it touches something of this type' },
+ {
+ key: 'connections',
+ label: 'Nothing linked',
+ kind: 'toggle',
+ hint: 'filed, and joined to nothing at all',
+ },
+ { key: 'added', label: 'Added', kind: 'added', hint: 'when it was filed into the case' },
+ { key: 'by', label: 'Filed by', kind: 'picks', hint: 'which tool filed it, or by hand' },
+];
+
+/** How recently a row was filed, as the menu offers it. Relative on purpose: a
+ * preset re-resolves against today on every request, where a date typed by hand is
+ * an absolute range and stays where it was put. */
+export const ADDED = [
+ { value: 'today', label: 'Today', days: 0 },
+ { value: '7d', label: 'Last 7 days', days: 7 },
+ { value: '30d', label: 'Last 30 days', days: 30 },
+];
+
+/** The two review states, worded as the rest of the app words them. */
+export const STATUSES = [
+ { value: 'confirmed', label: 'Confirmed' },
+ { value: 'suggested', label: 'Suggested' },
+];
+
+/**
+ * The questions the menu opens on, before any axis is picked.
+ *
+ * Not a saved search and deliberately not stored: these are the four questions
+ * every case is asked, so they are code rather than state the analyst has to build
+ * and the backup has to carry. Picking one drops its terms into the bar as ordinary
+ * chips, which is also how the filter language gets taught — the answer arrives and
+ * the sentence that produced it is sitting there to be edited.
+ */
+export const QUESTIONS = [
+ {
+ id: 'review',
+ label: 'To review',
+ hint: 'a tool proposed it and nobody has confirmed it',
+ terms: { status: 'suggested' },
+ },
+ {
+ id: 'loose',
+ label: 'Nothing linked yet',
+ hint: 'in the case, connected to nothing — the unexploited material',
+ terms: { connections: 'none' },
+ },
+ {
+ id: 'week',
+ label: 'Added this week',
+ hint: 'filed in the last seven days',
+ terms: { added: '7d' },
+ },
+ {
+ id: 'unfiled',
+ label: 'Unfiled',
+ hint: 'in none of your folders',
+ terms: { unfiled: true },
+ },
+];
+
+/** A question with no term set. Every field is present, so nothing downstream has to
+ * tell an absent key from an empty one. */
+export function emptyFilter() {
+ return {
+ q: '',
+ families: [],
+ types: [],
+ status: '',
+ folder: '',
+ unfiled: false,
+ recursive: false,
+ attrKey: '',
+ attrValue: '',
+ linked: '',
+ connections: '', // '' | 'none'
+ added: '', // one of ADDED, or '' when since/until say it in dates
+ since: '',
+ until: '',
+ by: [],
+ };
+}
+
+/** Bring a remembered or imported question back inside the current vocabulary.
+ * Unknown keys are dropped and every value gets the shape the request builders
+ * expect, so a view file made by another version cannot break either surface. */
+export function normalizeFilter(value) {
+ const raw = value && typeof value === 'object' ? value : {};
+ const strings = (items) =>
+ Array.isArray(items)
+ ? [...new Set(items.filter((item) => typeof item === 'string').map((item) => item.slice(0, 300)))]
+ : [];
+ const text = (item, limit = 1000) =>
+ typeof item === 'string' ? item.slice(0, limit) : '';
+ return {
+ q: text(raw.q),
+ families: strings(raw.families),
+ types: strings(raw.types),
+ status: ['confirmed', 'suggested'].includes(raw.status) ? raw.status : '',
+ folder: text(raw.folder, 300),
+ unfiled: raw.unfiled === true,
+ recursive: raw.recursive === true,
+ attrKey: text(raw.attrKey, 64),
+ attrValue: text(raw.attrValue),
+ linked: text(raw.linked, 40),
+ connections: raw.connections === 'none' ? 'none' : '',
+ added: ADDED.some((entry) => entry.value === raw.added) ? raw.added : '',
+ since: text(raw.since, 10),
+ until: text(raw.until, 10),
+ by: strings(raw.by),
+ };
+}
+
+/** Whether anything at all is being asked. What decides the count beside the search
+ * and whether "Clear all" is offered. */
+export function isFiltering(filter) {
+ return activeAxes(filter).length > 0 || Boolean(filter.q.trim());
+}
+
+/** Which axes carry a term right now, in AXES order. */
+export function activeAxes(filter) {
+ return AXES.filter((axis) => hasTerm(filter, axis.key)).map((axis) => axis.key);
+}
+
+/** Whether one axis is set. The field axis is only half an act until its value is
+ * chosen, and a folder axis is set by "unfiled" as much as by a path. */
+export function hasTerm(filter, axis) {
+ switch (axis) {
+ case 'family':
+ return filter.families.length > 0;
+ case 'type':
+ return filter.types.length > 0;
+ case 'folder':
+ return filter.unfiled || Boolean(filter.folder);
+ case 'status':
+ return Boolean(filter.status);
+ case 'field':
+ return Boolean(filter.attrKey);
+ case 'linked':
+ return Boolean(filter.linked);
+ case 'connections':
+ return filter.connections === 'none';
+ case 'added':
+ return Boolean(filter.added || filter.since || filter.until);
+ case 'by':
+ return filter.by.length > 0;
+ default:
+ return false;
+ }
+}
+
+/** Drop one axis, leaving the rest of the question alone. What a chip's `×` does. */
+export function clearAxis(filter, axis) {
+ switch (axis) {
+ case 'family':
+ return { ...filter, families: [] };
+ case 'type':
+ return { ...filter, types: [] };
+ case 'folder':
+ return { ...filter, folder: '', unfiled: false, recursive: false };
+ case 'status':
+ return { ...filter, status: '' };
+ // The value goes with the field: half a term is not a shorter question, it is
+ // the analyst having picked what they were about to ask about.
+ case 'field':
+ return { ...filter, attrKey: '', attrValue: '' };
+ case 'linked':
+ return { ...filter, linked: '' };
+ case 'connections':
+ return { ...filter, connections: '' };
+ case 'added':
+ return { ...filter, added: '', since: '', until: '' };
+ case 'by':
+ return { ...filter, by: [] };
+ default:
+ return filter;
+ }
+}
+
+/** Ask one of the standing questions, over whatever is already set. */
+export function askQuestion(filter, id) {
+ const question = QUESTIONS.find((entry) => entry.id === id);
+ return question ? { ...filter, ...question.terms } : filter;
+}
+
+/** Add or drop one value of a multi-value axis. */
+export function toggleValue(list, value) {
+ return list.includes(value) ? list.filter((entry) => entry !== value) : [...list, value];
+}
+
+/** The date a relative range starts on, as the `YYYY-MM-DD` the catalog compares
+ * against. ISO-8601 sorts lexicographically, so a bare date is a real bound. */
+export function sinceFor(added, now = Date.now()) {
+ const range = ADDED.find((entry) => entry.value === added);
+ if (!range) return '';
+ const at = new Date(now);
+ at.setDate(at.getDate() - range.days);
+ return at.toISOString().slice(0, 10);
+}
+
+/**
+ * The question as catalog request parameters.
+ *
+ * `types` is handed in rather than resolved here: the family layer is server
+ * vocabulary and the registry lives in a Svelte module, so the caller resolves
+ * families to types exactly as it always has and this stays pure.
+ *
+ * A field with no value chosen is **not sent**, which is the invariant the catalog
+ * route states in its own docstring: asked as a term it would empty the table between
+ * two clicks of one act.
+ */
+export function toQuery(filter, { types = [], now = Date.now() } = {}) {
+ const relative = filter.added ? sinceFor(filter.added, now) : '';
+ return {
+ types,
+ status: filter.status || undefined,
+ query: filter.q.trim() || undefined,
+ folder: filter.unfiled ? undefined : filter.folder || undefined,
+ unfiled: filter.unfiled || undefined,
+ recursive: (!filter.unfiled && filter.recursive) || undefined,
+ attr: filter.attrKey || undefined,
+ value: filter.attrKey && filter.attrValue ? filter.attrValue : undefined,
+ linked: filter.linked || undefined,
+ unlinked: filter.connections === 'none' || undefined,
+ since: relative || filter.since || undefined,
+ until: (!filter.added && filter.until) || undefined,
+ by: filter.by.length ? filter.by : undefined,
+ };
+}
+
+/**
+ * The same question, spelled the way the graph route asks for it.
+ *
+ * Two endpoints answer this filter and they name three of its terms differently — a
+ * type set, a text term, and every flag as a string. One function knows both
+ * spellings, so handing a question from the table to the drawing cannot quietly drop
+ * a term on the way: what the drawing holds is what the table counted.
+ */
+export function toGraphQuery(filter, { types = [], now = Date.now() } = {}) {
+ const asked = toQuery(filter, { types, now });
+ const params = {};
+ if (asked.types?.length) params.type = asked.types.join(',');
+ if (asked.status) params.status = asked.status;
+ if (asked.query) params.q = asked.query;
+ if (asked.folder) params.folder = asked.folder;
+ if (asked.unfiled) params.unfiled = 'true';
+ if (asked.recursive) params.recursive = 'true';
+ if (asked.attr && asked.value) {
+ params.attr = asked.attr;
+ params.value = asked.value;
+ }
+ if (asked.linked) params.linked = asked.linked;
+ if (asked.unlinked) params.unlinked = 'true';
+ if (asked.since) params.since = asked.since;
+ if (asked.until) params.until = asked.until;
+ if (asked.by?.length) params.by = asked.by.join(',');
+ return params;
+}
+
+/**
+ * The question in words, one chip per term.
+ *
+ * `names` translates the case's own slugs — a type, a family, a filer — into what
+ * the registry calls them. It defaults to the slug, so a free type the vocabulary has
+ * never heard of still reads as itself rather than as nothing.
+ */
+export function chipsOf(filter, names = {}) {
+ const typeName = names.type ?? ((value) => value);
+ const familyName = names.family ?? ((value) => value);
+ const chips = [];
+ if (filter.families.length) {
+ chips.push({ axis: 'family', text: `Family: ${filter.families.map(familyName).join(', ')}` });
+ }
+ if (filter.types.length) {
+ chips.push({ axis: 'type', text: `Type: ${filter.types.map(typeName).join(', ')}` });
+ }
+ if (filter.unfiled) {
+ chips.push({ axis: 'folder', text: 'Unfiled' });
+ } else if (filter.folder) {
+ const reach = filter.recursive ? ' and under' : '';
+ chips.push({ axis: 'folder', text: `Folder: ${filter.folder}${reach}` });
+ }
+ if (filter.status) {
+ const status = STATUSES.find((entry) => entry.value === filter.status);
+ chips.push({ axis: 'status', text: `Status: ${status?.label ?? filter.status}` });
+ }
+ if (filter.attrKey) {
+ // A field with no value yet is a term still being built, and it says so rather
+ // than reading as a filter that matches everything.
+ const value = filter.attrValue ? ` = ${filter.attrValue}` : ' — pick a value';
+ chips.push({ axis: 'field', text: `${filter.attrKey}${value}` });
+ }
+ if (filter.linked) {
+ chips.push({ axis: 'linked', text: `Linked to a ${typeName(filter.linked).toLowerCase()}` });
+ }
+ if (filter.connections === 'none') {
+ chips.push({ axis: 'connections', text: 'Nothing linked' });
+ }
+ if (filter.added) {
+ const range = ADDED.find((entry) => entry.value === filter.added);
+ chips.push({ axis: 'added', text: `Added: ${(range?.label ?? filter.added).toLowerCase()}` });
+ } else if (filter.since || filter.until) {
+ chips.push({ axis: 'added', text: `Added: ${filter.since || '…'} → ${filter.until || '…'}` });
+ }
+ if (filter.by.length) {
+ chips.push({ axis: 'by', text: `Filed by: ${filter.by.join(', ')}` });
+ }
+ return chips;
+}
+
+/**
+ * How the whole filtered set is sorted, and which of those the server can do.
+ *
+ * Two of the table's headings name a column the store can order the **case** by;
+ * the rest are sorted over the rows already loaded. That difference is the whole
+ * reason this table is worth anything on a large case — "newest first" over a
+ * hundred of eight hundred rows is not the newest of anything — so the two are told
+ * apart here rather than being one gesture that quietly means two things.
+ */
+export const SERVER_SORTS = { label: 'label', created: 'created' };
+
+/** The `order` parameter for a heading and a direction, or '' for the case's own
+ * cursor order. */
+export function orderFor(key, descending) {
+ const column = SERVER_SORTS[key];
+ if (!column) return '';
+ return descending ? `-${column}` : column;
+}
+
+const STORE_KEY = 'azimut:board-filter';
+
+/**
+ * Remember the question, per case, in the browser.
+ *
+ * Not in the case, and the distinction is the one the backup contract cares about: a
+ * filter is how somebody was looking at their material this afternoon, not something
+ * the case holds. Storing it would make it a new key to carry into a bundle and
+ * restore on another machine, for a value that is stale by then anyway.
+ */
+export function loadFilter(caseId) {
+ if (!caseId) return emptyFilter();
+ try {
+ const stored = JSON.parse(localStorage.getItem(`${STORE_KEY}:${caseId}`) ?? 'null');
+ // Merged over a fresh one, so a filter written by an older build cannot arrive
+ // missing a key every reader assumes is there.
+ return normalizeFilter(stored);
+ } catch {
+ return emptyFilter(); // unavailable or unparseable storage is not a failure
+ }
+}
+
+export function saveFilter(caseId, filter) {
+ if (!caseId) return;
+ try {
+ if (isFiltering(filter)) {
+ localStorage.setItem(`${STORE_KEY}:${caseId}`, JSON.stringify(filter));
+ } else {
+ localStorage.removeItem(`${STORE_KEY}:${caseId}`);
+ }
+ } catch {
+ /* ignore */
+ }
+}
diff --git a/frontend/src/lib/entityFilter.test.js b/frontend/src/lib/entityFilter.test.js
new file mode 100644
index 0000000..812deac
--- /dev/null
+++ b/frontend/src/lib/entityFilter.test.js
@@ -0,0 +1,218 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+import {
+ ADDED,
+ AXES,
+ QUESTIONS,
+ activeAxes,
+ askQuestion,
+ chipsOf,
+ clearAxis,
+ emptyFilter,
+ hasTerm,
+ isFiltering,
+ loadFilter,
+ orderFor,
+ saveFilter,
+ sinceFor,
+ toQuery,
+ toggleValue,
+} from './entityFilter.js';
+
+/** A localStorage stand-in — the test env has no DOM. */
+function fakeStorage(seed = {}) {
+ const store = { ...seed };
+ return {
+ getItem: (key) => (key in store ? store[key] : null),
+ setItem: (key, value) => {
+ store[key] = String(value);
+ },
+ removeItem: (key) => {
+ delete store[key];
+ },
+ all: () => store,
+ };
+}
+
+const at = (filter) => ({ ...emptyFilter(), ...filter });
+
+describe('the question is a value', () => {
+ it('starts with every key present, so nothing downstream guesses', () => {
+ const filter = emptyFilter();
+ for (const axis of AXES) expect(hasTerm(filter, axis.key)).toBe(false);
+ expect(isFiltering(filter)).toBe(false);
+ });
+
+ it('counts a typed term as asking something, since the table narrows on it', () => {
+ expect(isFiltering(at({ q: 'bridge' }))).toBe(true);
+ });
+
+ it('holds several values on the axes where that is one question', () => {
+ // "accounts and people" is one question about the case, not two filters
+ expect(toggleValue(['account'], 'person')).toEqual(['account', 'person']);
+ expect(toggleValue(['account', 'person'], 'account')).toEqual(['person']);
+ expect(activeAxes(at({ types: ['account', 'person'] }))).toEqual(['type']);
+ });
+
+ it('treats a field with no value as half an act, and drops it whole', () => {
+ // picked, values just fetched: it is a term being built, and asked as one it
+ // would empty the table between two clicks
+ const half = at({ attrKey: 'kind' });
+ expect(hasTerm(half, 'field')).toBe(true);
+ expect(toQuery(half).attr).toBe('kind');
+ expect(toQuery(half).value).toBeUndefined();
+ expect(clearAxis(half, 'field').attrKey).toBe('');
+ });
+
+ it('takes the whole folder term out at once, reach included', () => {
+ const filed = at({ folder: '/field-work', recursive: true });
+ const cleared = clearAxis(filed, 'folder');
+ expect(cleared.folder).toBe('');
+ expect(cleared.recursive).toBe(false);
+ expect(cleared.unfiled).toBe(false);
+ });
+});
+
+describe('the questions every case is asked', () => {
+ it('drops its terms in as ordinary chips, which is how the language is taught', () => {
+ for (const question of QUESTIONS) {
+ const asked = askQuestion(emptyFilter(), question.id);
+ expect(isFiltering(asked)).toBe(true);
+ expect(chipsOf(asked).length).toBe(1);
+ }
+ });
+
+ it('asks the case for what nothing connects to, which no column reports', () => {
+ const loose = askQuestion(emptyFilter(), 'loose');
+ expect(toQuery(loose).unlinked).toBe(true);
+ expect(chipsOf(loose)[0].text).toBe('Nothing linked');
+ });
+});
+
+describe('the question as a request', () => {
+ it('sends only the terms that are set', () => {
+ const params = toQuery(emptyFilter());
+ for (const value of Object.values(params)) {
+ expect(value === undefined || Array.isArray(value)).toBe(true);
+ }
+ });
+
+ it('lets unfiled win over a path, as the catalog does', () => {
+ const params = toQuery(at({ unfiled: true, folder: '/field-work', recursive: true }));
+ expect(params.unfiled).toBe(true);
+ expect(params.folder).toBeUndefined();
+ expect(params.recursive).toBeUndefined();
+ });
+
+ it('resolves a relative range against today on every request', () => {
+ // a preset is a standing question — "this week" means this week whenever it is
+ // asked — where a date typed by hand is an absolute bound and stays put
+ const now = Date.parse('2026-08-10T12:00:00Z');
+ expect(sinceFor('7d', now)).toBe('2026-08-03');
+ expect(toQuery(at({ added: '7d' }), { now }).since).toBe('2026-08-03');
+ expect(toQuery(at({ since: '2026-01-01', until: '2026-02-01' })).since).toBe('2026-01-01');
+ expect(toQuery(at({ since: '2026-01-01', until: '2026-02-01' })).until).toBe('2026-02-01');
+ });
+
+ it('offers every range the menu shows', () => {
+ const now = Date.parse('2026-08-10T12:00:00Z');
+ for (const range of ADDED) expect(sinceFor(range.value, now)).toMatch(/^\d{4}-\d{2}-\d{2}$/);
+ });
+
+ it('carries the types it was handed rather than resolving families itself', () => {
+ // the family layer is server vocabulary and the registry is a Svelte module, so
+ // this stays pure
+ expect(toQuery(at({ families: ['actor'] }), { types: ['person', 'account'] }).types).toEqual([
+ 'person',
+ 'account',
+ ]);
+ });
+});
+
+describe('the question in words', () => {
+ it('writes one chip per term, in the order the menu offers them', () => {
+ const filter = at({
+ families: ['actor'],
+ types: ['media'],
+ status: 'suggested',
+ attrKey: 'kind',
+ attrValue: 'video',
+ linked: 'place',
+ });
+ expect(chipsOf(filter, { type: (t) => t.toUpperCase() }).map((chip) => chip.axis)).toEqual([
+ 'family',
+ 'type',
+ 'status',
+ 'field',
+ 'linked',
+ ]);
+ });
+
+ it('says a field is still being built rather than reading as a live filter', () => {
+ expect(chipsOf(at({ attrKey: 'kind' }))[0].text).toContain('pick a value');
+ expect(chipsOf(at({ attrKey: 'kind', attrValue: 'video' }))[0].text).toBe('kind = video');
+ });
+
+ it('says how far a folder chip reaches', () => {
+ expect(chipsOf(at({ folder: '/a' }))[0].text).toBe('Folder: /a');
+ expect(chipsOf(at({ folder: '/a', recursive: true }))[0].text).toBe('Folder: /a and under');
+ expect(chipsOf(at({ unfiled: true }))[0].text).toBe('Unfiled');
+ });
+
+ it('falls back to the slug for a type the vocabulary has never heard of', () => {
+ expect(chipsOf(at({ types: ['vessel'] }))[0].text).toBe('Type: vessel');
+ });
+});
+
+describe('where a sort is answered', () => {
+ it('names the two columns the store can order the whole case by', () => {
+ expect(orderFor('created', true)).toBe('-created');
+ expect(orderFor('label', false)).toBe('label');
+ });
+
+ it('leaves every other heading to the rows already loaded', () => {
+ expect(orderFor('folder', false)).toBe('');
+ expect(orderFor('', false)).toBe('');
+ });
+});
+
+describe('remembering the question', () => {
+ beforeEach(() => {
+ vi.stubGlobal('localStorage', fakeStorage());
+ });
+
+ it('keeps it per case, so two cases do not inherit each other’s filters', () => {
+ saveFilter('c_one', at({ status: 'suggested' }));
+ expect(loadFilter('c_one').status).toBe('suggested');
+ expect(loadFilter('c_two').status).toBe('');
+ });
+
+ it('forgets it the moment nothing is being asked', () => {
+ saveFilter('c_one', at({ status: 'suggested' }));
+ saveFilter('c_one', emptyFilter());
+ expect(loadFilter('c_one')).toEqual(emptyFilter());
+ });
+
+ it('fills in a key an older build never wrote', () => {
+ vi.stubGlobal(
+ 'localStorage',
+ fakeStorage({ 'azimut:board-filter:c_one': JSON.stringify({ status: 'suggested' }) })
+ );
+ expect(loadFilter('c_one')).toEqual({ ...emptyFilter(), status: 'suggested' });
+ });
+
+ it('survives a hostile or absent localStorage (private mode)', () => {
+ vi.stubGlobal('localStorage', {
+ getItem() {
+ throw new Error('denied');
+ },
+ setItem() {
+ throw new Error('denied');
+ },
+ removeItem() {
+ throw new Error('denied');
+ },
+ });
+ expect(loadFilter('c_one')).toEqual(emptyFilter());
+ expect(() => saveFilter('c_one', at({ status: 'suggested' }))).not.toThrow();
+ });
+});
diff --git a/frontend/src/lib/entityIcon.js b/frontend/src/lib/entityIcon.js
index 2fc174b..e2aac3d 100644
--- a/frontend/src/lib/entityIcon.js
+++ b/frontend/src/lib/entityIcon.js
@@ -1,35 +1,114 @@
-/** Icon name for a case entity, shared by the sidebar rows and result list. */
-
-export const ENTITY_ICONS = {
- person: 'user',
- organization: 'layers',
- alias: 'user',
- account: 'globe',
- email: 'note',
- phone: 'hash',
- place: 'pin',
- capture: 'satellite',
- event: 'clock',
- media: 'image',
- proof: 'proof',
- post: 'post',
- domain: 'globe',
- ip: 'hash',
- vehicle: 'grip',
- note: 'note',
- 'inspect-session': 'inspect',
-};
+/**
+ * Icon name for a case entity, shared by every surface that lists one.
+ *
+ * The list itself is the backend registry's (`engine/entities.py`, served with
+ * `GET /api/cases/entity-types`), not a copy kept here: adding a type stays one
+ * entry there. A hand-kept map is how this drifted before — it still named `alias`
+ * and `event`, retired when the vocabulary was designed, and had never heard of a
+ * bookmark or a claim.
+ *
+ * `note` is the fallback, which covers a free-string type the vocabulary has never
+ * heard of and the moment before the registry lands. `App.svelte` asks for it at
+ * startup so that moment is over before a case is on screen.
+ */
+import { typeIcon } from './entityTypes.svelte.js';
const VIDEO_EXTS = new Set(['mp4', 'mov', 'webm', 'mkv', 'avi', 'm4v']);
+const AUDIO_EXTS = new Set(['mp3', 'wav', 'm4a', 'ogg', 'oga', 'opus', 'flac', 'aac']);
+const IMAGE_EXTS = new Set([
+ 'jpg', 'jpeg', 'png', 'gif', 'webp', 'bmp', 'tif', 'tiff', 'avif', 'heic', 'svg',
+]);
+
+const KINDS = new Set(['image', 'video', 'audio', 'file']);
+
+/** What one media entity actually holds: `image`, `video`, `audio` or `file`.
+ *
+ * The importer stamps `attrs.kind` from the MIME type, which is the answer when
+ * it is there. The extension is the fallback for entities filed before that attr
+ * existed, and **anything unrecognised is a `file`** rather than an image: a PDF,
+ * a scan bundle or a spreadsheet drawn as a photo is the list telling the analyst
+ * something untrue about what it holds.
+ *
+ * Two shapes reach this. A catalog row carries its `attrs`; a **graph node** carries
+ * the kind flat and no attrs at all, because a case draws a few hundred nodes and
+ * each one shipping its own attribute bag to be drawn would be the payload paying
+ * for what the picture never reads. */
+export function mediaKindOf(e) {
+ if (KINDS.has(e?.kind)) return e.kind;
+ const stated = e?.attrs?.kind;
+ if (KINDS.has(stated)) return stated;
+ const ext = e?.attrs?.path?.split('.').pop()?.toLowerCase();
+ if (!ext) return 'file';
+ if (VIDEO_EXTS.has(ext)) return 'video';
+ if (AUDIO_EXTS.has(ext)) return 'audio';
+ if (IMAGE_EXTS.has(ext)) return 'image';
+ return 'file';
+}
/** Media entities normally carry the same `kind` the Media Library uses to tell
* video from image; fall back to the file extension for entities filed before
* that attr existed. */
export function isVideoEntity(e) {
- if (e.attrs?.kind) return e.attrs.kind === 'video';
- const ext = e.attrs?.path?.split('.').pop()?.toLowerCase();
- return !!ext && VIDEO_EXTS.has(ext);
+ return mediaKindOf(e) === 'video';
}
+/** The icon a media kind is drawn with. The registry cannot make this call: a
+ * `media` is one type, and what the bytes are is a property of the file. */
+const MEDIA_ICONS = { image: 'image', video: 'video', audio: 'audio', file: 'file' };
+
+/** The same four in words, for a surface that names a row rather than drawing one.
+ *
+ * Here rather than in the entity registry for the same reason the icons are: the
+ * vocabulary has one `media` type, and "this is a video" is a fact about the bytes.
+ * Every surface that says it reads this one map, so no two of them can disagree. */
+const MEDIA_LABELS = { image: 'Image', video: 'Video', audio: 'Audio', file: 'File' };
+
+/** What to call one entity: the media kind when that is the real answer, and the
+ * registry's own label for everything else. `label` is the registry lookup, passed
+ * in rather than imported so this stays a pure function of what it is given. */
+export function entityKindLabel(e, label) {
+ return e?.type === 'media' ? MEDIA_LABELS[mediaKindOf(e)] : label;
+}
+
+/** The icon for one entity. */
export const entityIcon = (e) =>
- e.type === 'media' && isVideoEntity(e) ? 'video' : ENTITY_ICONS[e.type] ?? 'note';
+ e?.type === 'media' ? MEDIA_ICONS[mediaKindOf(e)] : (typeIcon(e?.type) ?? 'note');
+
+/** The tools that make material out of what the case already holds, in words.
+ * Their output is filed as ordinary media, so without this a frame and a
+ * photograph somebody handed over read as the same thing. */
+const MADE_BY = { inspect: 'Inspect' };
+
+/** The act, in the word an analyst would use for it. `enhance-video` is the one
+ * that needs saying twice over — it is a video, and it is not the original. */
+const MADE_AS = {
+ frame: 'Frame',
+ adjust: 'Adjusted image',
+ collage: 'Collage',
+ 'enhance-video': 'Enhanced video',
+};
+
+/** What one node was **made here** as, or null for material the case collected.
+ *
+ * Only graph nodes carry `origin`, and only for the tools in `MADE_HERE`
+ * (`engine/graph.py`) — the backend leaves it off an upload rather than sending
+ * "upload" for every surface to filter out, so a value here is already the answer.
+ * A route with no act (an older file, filed before the producer stamped one) still
+ * says it was made here; a caller falls back to the plain kind for the word. */
+export function madeHereLabel(e) {
+ if (!e?.origin) return null;
+ return MADE_AS[e.op] ?? null;
+}
+
+/** The same act mid-sentence, for an edge that stands for steps rather than for one
+ * node — *derived from 2 frames*. The backend sends the act itself on a folded edge
+ * precisely so the words stay here: a step it has no word for reads as whatever it
+ * was sent, which is the entity type and is still true. */
+export function madeAsWord(op) {
+ return MADE_AS[op]?.toLowerCase() ?? op;
+}
+
+/** Who made it, for the one line a panel gives it. Null for collected material. */
+export function madeHereBy(e) {
+ return e?.origin ? (MADE_BY[e.origin] ?? e.origin) : null;
+}
diff --git a/frontend/src/lib/entityIcon.test.js b/frontend/src/lib/entityIcon.test.js
index a83073a..46c3b64 100644
--- a/frontend/src/lib/entityIcon.test.js
+++ b/frontend/src/lib/entityIcon.test.js
@@ -1,27 +1,135 @@
-import { describe, expect, it } from 'vitest';
-import { entityIcon, isVideoEntity } from './entityIcon.js';
+import { describe, expect, it, vi, beforeEach } from 'vitest';
+
+const get = vi.fn();
+vi.mock('./api.js', () => ({ api: { get: (...a) => get(...a) } }));
+
+// The registry is the list now, so the fixture is the shape the API serves.
+const VOCABULARY = [
+ { type: 'place', label: 'Place', family: 'place', icon: 'pin', manual: false, group: '', attrs: [] },
+ { type: 'capture', label: 'Capture', family: 'collected', icon: 'satellite', manual: false, group: '', attrs: [] },
+ { type: 'media', label: 'Media', family: 'collected', icon: 'image', manual: false, group: '', attrs: [] },
+ { type: 'claim', label: 'Claim', family: 'claim', icon: 'note', manual: true, group: '', attrs: [] },
+ { type: 'vessel', label: 'Vessel', family: 'asset', icon: 'grip', manual: true, group: '', attrs: [] },
+];
+
+let mod;
+
+beforeEach(async () => {
+ vi.resetModules();
+ get.mockReset();
+ get.mockResolvedValue(VOCABULARY);
+ mod = await import('./entityIcon.js');
+ const types = await import('./entityTypes.svelte.js');
+ await types.loadEntityTypes();
+});
describe('entityIcon', () => {
- it('maps a type to its icon and falls back to the note glyph', () => {
- expect(entityIcon({ type: 'place', attrs: {} })).toBe('pin');
- expect(entityIcon({ type: 'capture', attrs: {} })).toBe('satellite');
- expect(entityIcon({ type: 'whatever-new', attrs: {} })).toBe('note');
+ it('takes the icon from the registry rather than a map kept here', async () => {
+ expect(mod.entityIcon({ type: 'place', attrs: {} })).toBe('pin');
+ expect(mod.entityIcon({ type: 'capture', attrs: {} })).toBe('satellite');
+ // the types the old hand-kept map had never heard of
+ expect(mod.entityIcon({ type: 'claim', attrs: {} })).toBe('note');
+ expect(mod.entityIcon({ type: 'vessel', attrs: {} })).toBe('grip');
+ });
+
+ it('falls back to the note glyph for a free type and for a missing entity', () => {
+ expect(mod.entityIcon({ type: 'whatever-new', attrs: {} })).toBe('note');
+ expect(mod.entityIcon(null)).toBe('note');
+ });
+
+ it('tells one kind of media from another, the call the registry cannot make', () => {
+ // `media` is a type; what the bytes are is a property of the file
+ expect(mod.entityIcon({ type: 'media', attrs: { kind: 'video' } })).toBe('video');
+ expect(mod.entityIcon({ type: 'media', attrs: { kind: 'image' } })).toBe('image');
+ expect(mod.entityIcon({ type: 'media', attrs: { kind: 'audio' } })).toBe('audio');
+ expect(mod.entityIcon({ type: 'media', attrs: { kind: 'file' } })).toBe('file');
+ });
+
+ it('never draws a document as a photograph', () => {
+ // a PDF, a scan bundle or a spreadsheet under an image glyph is the list
+ // telling the analyst something untrue about what the case holds
+ expect(mod.entityIcon({ type: 'media', attrs: { path: 'media/plan.pdf' } })).toBe('file');
+ expect(mod.entityIcon({ type: 'media', attrs: { path: 'media/notes.xlsx' } })).toBe('file');
+ expect(mod.entityIcon({ type: 'media', attrs: { path: 'media/scan.jpg' } })).toBe('image');
+ expect(mod.entityIcon({ type: 'media', attrs: { path: 'media/call.m4a' } })).toBe('audio');
+ // and a media entity with no path at all is still not an image
+ expect(mod.entityIcon({ type: 'media', attrs: {} })).toBe('file');
});
- it('tells video media from images', () => {
- expect(entityIcon({ type: 'media', attrs: { kind: 'video' } })).toBe('video');
- expect(entityIcon({ type: 'media', attrs: { kind: 'image' } })).toBe('image');
+ it('reads the note glyph until the registry lands, rather than an empty icon', async () => {
+ vi.resetModules();
+ const cold = await import('./entityIcon.js');
+
+ expect(cold.entityIcon({ type: 'place', attrs: {} })).toBe('note');
});
});
describe('isVideoEntity', () => {
it('falls back to the extension for media filed before `kind` existed', () => {
- expect(isVideoEntity({ attrs: { path: 'raw/clip_04.MP4' } })).toBe(true);
- expect(isVideoEntity({ attrs: { path: 'raw/frame.png' } })).toBe(false);
- expect(isVideoEntity({ attrs: {} })).toBe(false);
+ expect(mod.isVideoEntity({ attrs: { path: 'raw/clip_04.MP4' } })).toBe(true);
+ expect(mod.isVideoEntity({ attrs: { path: 'raw/frame.png' } })).toBe(false);
+ expect(mod.isVideoEntity({ attrs: {} })).toBe(false);
});
it('trusts `kind` over the extension', () => {
- expect(isVideoEntity({ attrs: { kind: 'image', path: 'weird.mp4' } })).toBe(false);
+ expect(mod.isVideoEntity({ attrs: { kind: 'image', path: 'weird.mp4' } })).toBe(false);
+ });
+});
+
+describe('madeHereLabel / madeHereBy', () => {
+ it('names the act for material the case made out of what it holds', () => {
+ expect(mod.madeHereLabel({ origin: 'inspect', op: 'frame' })).toBe('Frame');
+ expect(mod.madeHereLabel({ origin: 'inspect', op: 'collage' })).toBe('Collage');
+ expect(mod.madeHereLabel({ origin: 'inspect', op: 'adjust' })).toBe('Adjusted image');
+ expect(mod.madeHereLabel({ origin: 'inspect', op: 'enhance-video' })).toBe('Enhanced video');
+ });
+
+ it('says nothing about material the case collected', () => {
+ // The backend leaves `origin` off an upload rather than sending "upload" for
+ // every surface to filter out, so its absence is already the answer.
+ expect(mod.madeHereLabel({ kind: 'image' })).toBeNull();
+ expect(mod.madeHereBy({ kind: 'image' })).toBeNull();
+ expect(mod.madeHereLabel(null)).toBeNull();
+ });
+
+ it('leaves the word to the caller when the act was never stamped', () => {
+ // An older file: the route is on the row, the act is not. It was still made
+ // here, and the caller falls back to the plain kind for what to call it.
+ expect(mod.madeHereLabel({ origin: 'inspect' })).toBeNull();
+ expect(mod.madeHereBy({ origin: 'inspect' })).toBe('Inspect');
+ });
+
+ it('names a tool it has never heard of rather than dropping the line', () => {
+ expect(mod.madeHereBy({ origin: 'somenewtool' })).toBe('somenewtool');
+ });
+
+ it('says the same act mid-sentence, for the edge a folded step becomes', () => {
+ // "derived from 2 frames" is what the collapsed step is for, and the plural is
+ // the caller's, so the word arrives lowercase and bare.
+ expect(mod.madeAsWord('frame')).toBe('frame');
+ expect(mod.madeAsWord('adjust')).toBe('adjusted image');
+ expect(mod.madeAsWord('enhance-video')).toBe('enhanced video');
+ });
+
+ it('writes a step it has no word for as whatever it was sent', () => {
+ // The backend falls back to the entity type where no act was recorded, and that
+ // is still true of the node — "derived from 1 media" reads, where nothing does not.
+ expect(mod.madeAsWord('media')).toBe('media');
+ });
+});
+
+describe('mediaKindOf', () => {
+ it('answers what the importer stamped when it is there', () => {
+ expect(mod.mediaKindOf({ attrs: { kind: 'file', path: 'media/looks-like.png' } })).toBe('file');
+ });
+
+ it('reads the extension for anything filed before `kind` existed', () => {
+ expect(mod.mediaKindOf({ attrs: { path: 'media/Deed.PDF' } })).toBe('file');
+ expect(mod.mediaKindOf({ attrs: { path: 'media/quay.tiff' } })).toBe('image');
+ expect(mod.mediaKindOf({ attrs: { path: 'media/interview.opus' } })).toBe('audio');
+ });
+
+ it('refuses a kind the importer never writes', () => {
+ expect(mod.mediaKindOf({ attrs: { kind: 'satellite', path: 'media/x.png' } })).toBe('image');
});
});
diff --git a/frontend/src/lib/entitySearch.js b/frontend/src/lib/entitySearch.js
new file mode 100644
index 0000000..054d056
--- /dev/null
+++ b/frontend/src/lib/entitySearch.js
@@ -0,0 +1,69 @@
+/**
+ * Whether one entity answers a typed term, matching the server's own index.
+ *
+ * A bounded list searches in memory while the case fits one page and asks the
+ * server past it (`lib/pagedList.svelte.js`). Two predicates for one box means the
+ * same term answers differently either side of that threshold, which is what
+ * happened here: the board compared the label alone, so a plate, an IMO or a
+ * claim's wording was findable in a large case and invisible in a small one — the
+ * exact fields the vocabulary went to the trouble of declaring.
+ *
+ * So this mirrors `sqlite_backend._entity_search_text`: the label, the type, the
+ * folder, the notes, and the declared fields whose kind is worth matching text
+ * against. Numbers, geometries and stored grade letters stay out on both sides —
+ * "500" against every radius in a case buries the rows that actually say 500.
+ */
+import { entityFields } from './entityTypes.svelte.js';
+import { folderOf } from './folderTree.js';
+
+/** Declared kinds a value is worth finding an entity by. Mirrors
+ * `entities.SEARCHABLE_KINDS`. */
+const SEARCHABLE_KINDS = new Set(['text', 'longtext', 'url']);
+
+/** Everything a term is compared against, lowercased, in one string. */
+export function entitySearchText(entity) {
+ if (!entity) return '';
+ const declared = entityFields(entity.type)
+ .filter((field) => SEARCHABLE_KINDS.has(field.kind ?? 'text'))
+ .map((field) => entity.attrs?.[field.key]);
+ return [entity.label, entity.type, folderOf(entity), entity.attrs?.notes, ...declared]
+ .filter((value) => value !== null && value !== undefined && value !== '')
+ .join('\n')
+ .toLowerCase();
+}
+
+/** The fields that explain a hit, with the same declared-kind boundary as the index. */
+export function entitySearchMatches(entity, query) {
+ if (!entity) return [];
+ const terms = String(query ?? '').trim().toLowerCase().split(/\s+/).filter(Boolean);
+ if (!terms.length) return [];
+ const fields = [
+ { field: 'label', label: 'Name', value: entity.label },
+ { field: 'type', label: 'Type', value: entity.type },
+ { field: 'folder', label: 'Folder', value: folderOf(entity) },
+ { field: 'notes', label: 'Notes', value: entity.attrs?.notes },
+ ...entityFields(entity.type)
+ .filter((field) => SEARCHABLE_KINDS.has(field.kind ?? 'text'))
+ .map((field) => ({ field: field.key, label: field.label, value: entity.attrs?.[field.key] })),
+ ];
+ const covered = new Set();
+ const matches = [];
+ for (const field of fields) {
+ if (field.value === null || field.value === undefined || field.value === '') continue;
+ const value = String(field.value);
+ const folded = value.toLowerCase();
+ const hit = terms.filter((term) => folded.includes(term));
+ if (!hit.length) continue;
+ hit.forEach((term) => covered.add(term));
+ matches.push({ field: field.field, label: field.label, value });
+ }
+ return covered.size === new Set(terms).size ? matches : [];
+}
+
+/** True when the entity answers the term. An empty term matches everything, so a
+ * caller can hand the box straight through without a guard of its own. */
+export function matchesEntity(entity, query) {
+ const terms = String(query ?? '').trim().toLowerCase().split(/\s+/).filter(Boolean);
+ const text = entitySearchText(entity);
+ return !terms.length || terms.every((term) => text.includes(term));
+}
diff --git a/frontend/src/lib/entitySearch.test.js b/frontend/src/lib/entitySearch.test.js
new file mode 100644
index 0000000..b3106ff
--- /dev/null
+++ b/frontend/src/lib/entitySearch.test.js
@@ -0,0 +1,101 @@
+/**
+ * The in-memory predicate must answer the same term as the server's index.
+ *
+ * A small case filters here and a large one filters server-side. Before this the
+ * board compared the label alone, so a plate was findable in a case of two hundred
+ * rows and invisible in a case of ten — the same box, two answers, decided by a
+ * threshold nobody can see.
+ */
+import { describe, expect, it, vi } from 'vitest';
+
+const FIELDS = {
+ vehicle: [
+ { key: 'plate', label: 'Plate', kind: 'text' },
+ { key: 'make', label: 'Make', kind: 'text' },
+ ],
+ claim: [
+ { key: 'verbatim', label: 'As the source put it', kind: 'longtext' },
+ { key: 'confidence', label: 'Confidence', kind: 'choice' },
+ ],
+ place: [
+ { key: 'radius_m', label: 'Uncertainty radius (m)', kind: 'number' },
+ { key: 'footprint', label: 'Footprint', kind: 'geojson' },
+ ],
+ bookmark: [{ key: 'archive_url', label: 'Archived copy', kind: 'url' }],
+};
+
+vi.mock('./entityTypes.svelte.js', () => ({
+ entityFields: (type) => FIELDS[type] ?? [],
+}));
+
+const { entitySearchMatches, entitySearchText, matchesEntity } = await import('./entitySearch.js');
+
+describe('entity search', () => {
+ it('matches the label, the type, the folder and the notes', () => {
+ const entity = {
+ label: 'Truck 12',
+ type: 'vehicle',
+ attrs: { folder: 'Sources/Convoy', notes: 'seen twice at the depot' },
+ };
+
+ for (const term of ['truck', 'vehicle', 'convoy', 'depot']) {
+ expect(matchesEntity(entity, term)).toBe(true);
+ }
+ expect(matchesEntity(entity, 'harbour')).toBe(false);
+ });
+
+ it('matches the declared text fields the vocabulary names', () => {
+ const truck = { label: 'Truck 12', type: 'vehicle', attrs: { plate: 'AB-123-CD', make: 'Kamaz' } };
+ const claim = { label: 'Filmed at the quay', type: 'claim', attrs: { verbatim: 'on the north jetty' } };
+ const mark = { label: 'Port notice', type: 'bookmark', attrs: { archive_url: 'https://web.archive.org/x' } };
+
+ expect(matchesEntity(truck, 'AB-123')).toBe(true);
+ expect(matchesEntity(truck, 'kamaz')).toBe(true);
+ expect(matchesEntity(claim, 'north jetty')).toBe(true);
+ expect(matchesEntity(mark, 'web.archive.org')).toBe(true);
+ expect(entitySearchMatches(truck, 'AB-123')).toEqual([
+ { field: 'plate', label: 'Plate', value: 'AB-123-CD' },
+ ]);
+ });
+
+ it('lets separate words be satisfied by separate fields', () => {
+ const truck = {
+ label: 'Convoy lead',
+ type: 'vehicle',
+ attrs: { plate: 'AB-123-CD', make: 'Kamaz' },
+ };
+
+ expect(matchesEntity(truck, 'convoy AB-123')).toBe(true);
+ expect(entitySearchMatches(truck, 'convoy AB-123')).toEqual([
+ { field: 'label', label: 'Name', value: 'Convoy lead' },
+ { field: 'plate', label: 'Plate', value: 'AB-123-CD' },
+ ]);
+ });
+
+ it('leaves numbers, shapes and stored grades out, exactly as the index does', () => {
+ // "500" against every radius in a case buries the rows that actually say 500.
+ const place = {
+ label: 'Quay 4',
+ type: 'place',
+ attrs: { radius_m: 500, footprint: { type: 'Polygon', coordinates: [] } },
+ };
+ const claim = { label: 'A statement', type: 'claim', attrs: { confidence: 'probable' } };
+
+ expect(matchesEntity(place, '500')).toBe(false);
+ expect(matchesEntity(place, 'polygon')).toBe(false);
+ expect(matchesEntity(claim, 'probable')).toBe(false);
+ expect(matchesEntity(place, 'quay 4')).toBe(true);
+ });
+
+ it('matches everything on an empty term, and survives a missing entity', () => {
+ expect(matchesEntity({ label: 'x', type: 'vehicle' }, ' ')).toBe(true);
+ expect(matchesEntity(null, 'anything')).toBe(false);
+ expect(entitySearchText(undefined)).toBe('');
+ });
+
+ it('skips a declared field the entity never filled', () => {
+ const bare = { label: 'Truck 12', type: 'vehicle', attrs: { plate: '', make: null } };
+
+ expect(entitySearchText(bare)).toBe('truck 12\nvehicle');
+ });
+});
diff --git a/frontend/src/lib/entityTypes.svelte.js b/frontend/src/lib/entityTypes.svelte.js
new file mode 100644
index 0000000..23db6bd
--- /dev/null
+++ b/frontend/src/lib/entityTypes.svelte.js
@@ -0,0 +1,165 @@
+/**
+ * The entity vocabulary (ONTOLOGY §2), fetched once and shared.
+ *
+ * The backend owns it: which types a case may hold, the family each sits in, the
+ * icon that stands for it, and the fields an analyst may fill. Reading it here is
+ * what lets one form serve every type — adding `vessel` is an edit in
+ * `engine/entities.py`, not a new panel.
+ *
+ * Same lazy shape as the relation registry next door: loaded on the first surface
+ * that needs it, dropped rather than cached on failure so the next surface retries
+ * instead of inheriting an empty vocabulary for good. Until one succeeds a type
+ * reads as its own slug and declares no fields — degraded, never broken.
+ */
+import { api } from './api.js';
+
+const registry = $state({ types: [] });
+let pending = null;
+
+export function loadEntityTypes() {
+ pending ??= api
+ .get('/api/cases/entity-types')
+ .then((types) => {
+ registry.types = Array.isArray(types) ? types : [];
+ })
+ .catch(() => {
+ pending = null;
+ });
+ return pending;
+}
+
+const entryFor = (type) => registry.types.find((entry) => entry.type === type) ?? null;
+
+/** How a type reads in words, or the raw slug until the registry lands. */
+export function entityLabel(type) {
+ return entryFor(type)?.label ?? type;
+}
+
+/** Which family a type sits in, or null for a free type the registry has never
+ * heard of. Free types stay storable; they just have no verbs. */
+export function entityFamily(type) {
+ return entryFor(type)?.family ?? null;
+}
+
+/** One clause saying what a type is, or '' until the registry lands. The vocabulary
+ * is terse on purpose — `capture`, `claim`, `collected` — and a terse word nobody can
+ * look up is jargon, so every menu that offers a type can explain it. */
+export function entityHint(type) {
+ return entryFor(type)?.hint ?? '';
+}
+
+/** What the primary value is called in a form. It is stored as ``entity.label``;
+ * the type-specific reading avoids a second IP/handle/name field that could drift. */
+export function entityIdentityLabel(type) {
+ return entryFor(type)?.identity_label ?? 'Title';
+}
+
+/** Example or short prompt for the primary value. */
+export function entityIdentityPlaceholder(type) {
+ return entryFor(type)?.identity_placeholder ?? 'What to call it';
+}
+
+/** One clause saying what a family is. Families are the load-bearing idea and the
+ * one part an analyst never types, so a filter naming them has to say what they are.
+ * Read off any type in the family: the reading travels with the registry rows. */
+export function familyReads(family) {
+ return registry.types.find((entry) => entry.family === family)?.family_reads ?? '';
+}
+
+/** The icon that stands for a type, or null until the registry lands.
+ *
+ * The registry is where this lives, so adding a type is still one entry in
+ * `engine/entities.py`. Before this, four screens each kept their own map and
+ * every one of them had drifted: two still listed types retired at the design
+ * stage, none of them knew about a claim. `lib/entityIcon.js` is the one caller.
+ */
+export function typeIcon(type) {
+ return entryFor(type)?.icon ?? null;
+}
+
+/**
+ * The declared fields for a type, in registry order.
+ *
+ * "Declared" means *a field an analyst may fill*, never *everything this type
+ * holds*: a place's `lat`, `geo` and `notes` belong to the save that made the
+ * point and are not listed here, which is why rendering these cannot disturb them.
+ */
+export function entityFields(type) {
+ return entryFor(type)?.attrs ?? [];
+}
+
+/**
+ * Mark the field that opens each heading, over the fields actually being rendered.
+ *
+ * The registry heads a *field*, not a type, because one type can hold several
+ * subjects: a Claim says what it states, when it applies and why it is believed,
+ * where a place's four fields all answer how tightly the point is pinned. A heading
+ * is emitted where the group changes, so the registry's order is left exactly as it
+ * is — a form that regrouped its own fields would stop being the order the vocabulary
+ * declares.
+ *
+ * Takes the shown fields rather than the type, because a field can be hidden — an
+ * untraced footprint, an empty legacy value — and a heading resolved before that
+ * filter could survive every field it was heading.
+ */
+export function withHeadings(fields) {
+ let last = '';
+ return fields.map((field) => {
+ const group = field.group ?? '';
+ const heads = group && group !== last ? group : '';
+ last = group;
+ return { ...field, heads };
+ });
+}
+
+/** Every type the vocabulary knows, in menu order. Empty until the registry lands. */
+export function entityTypes() {
+ return registry.types;
+}
+
+/** The families, in the order the registry lists their types. What the board
+ * filters by first: a handful of readings is a menu, every type is a list. */
+export function entityFamilies() {
+ return [...new Set(registry.types.map((entry) => entry.family))];
+}
+
+/** The types an analyst creates by hand, for a create menu. A `media` is born
+ * from an import, so it is not one of them. */
+export function creatableTypes() {
+ return registry.types.filter((entry) => entry.manual);
+}
+
+/** Whether this type is entered as a graph record rather than born from a tool. */
+export function isManualEntityType(type) {
+ return Boolean(entryFor(type)?.manual);
+}
+
+/** Whether Details may attach presentation photos to this type. */
+export function hasImageGallery(type) {
+ return Boolean(entryFor(type)?.image_gallery);
+}
+
+/** Where a source's Admiralty grade is stored. The key is a contract, like `url` or
+ * `path`; the scale behind it is registry data, so nothing here spells the letters. */
+export const RELIABILITY = 'reliability';
+
+/**
+ * How reliable this entity says it is, as `{ grade, label }`, or null.
+ *
+ * Null covers all three ways there is nothing to show: the type is not a source, the
+ * source has not been graded, or a stored value the scale has never heard of. All
+ * three render as nothing — a source with no grade is the normal case, and flagging
+ * it would turn an optional field into a standing chore.
+ *
+ * It belongs to the entity and is read wherever that entity appears. It is never
+ * folded into the edge's own rating: reliability is what the source is worth,
+ * credibility is what this one statement is worth, and the Admiralty scheme exists
+ * precisely so the two are not multiplied together (ONTOLOGY §3).
+ */
+export function reliabilityOf(entity) {
+ const grade = entity?.attrs?.[RELIABILITY];
+ if (!grade) return null;
+ const field = entityFields(entity.type).find((f) => f.key === RELIABILITY);
+ const option = (field?.options ?? []).find((o) => o.value === grade);
+ return option ? { grade, label: option.label } : null;
+}
diff --git a/frontend/src/lib/entityTypes.test.js b/frontend/src/lib/entityTypes.test.js
new file mode 100644
index 0000000..e93d89f
--- /dev/null
+++ b/frontend/src/lib/entityTypes.test.js
@@ -0,0 +1,226 @@
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+// This instance is never given a registry, so it is also the "before the fetch
+// lands" case: a surface must render against an empty vocabulary at first paint.
+import { entityFields as coldFields, entityLabel as coldLabel } from './entityTypes.svelte.js';
+
+const get = vi.fn();
+vi.mock('./api.js', () => ({ api: { get: (...a) => get(...a) } }));
+
+const VOCABULARY = [
+ {
+ type: 'person', label: 'Person', family: 'actor', icon: 'user', manual: true,
+ image_gallery: true,
+ hint: 'a named individual', family_reads: 'a person or organization that can act or hold ownership',
+ identity_label: 'Full name', identity_placeholder: 'Name or known alias', attrs: [],
+ },
+ {
+ type: 'place',
+ label: 'Place',
+ family: 'place',
+ icon: 'pin',
+ manual: false,
+ hint: 'a saved point',
+ family_reads: 'a point on the map, never a thing standing on it',
+ attrs: [
+ {
+ key: 'radius_m',
+ label: 'Uncertainty radius (m)',
+ kind: 'number',
+ group: 'How precise',
+ rungs: [
+ { label: 'This block', value: 100 },
+ { label: 'This town', value: 2000 },
+ ],
+ minimum: 1,
+ maximum: 5000000,
+ },
+ { key: 'footprint', label: 'Footprint', kind: 'geojson', rungs: [], minimum: null, maximum: null },
+ { key: 'verbatim', label: 'As the source put it', kind: 'text', rungs: [], minimum: null, maximum: null },
+ ],
+ },
+ { type: 'media', label: 'Media', family: 'collected', icon: 'image', manual: false, attrs: [] },
+ {
+ type: 'bookmark',
+ label: 'Bookmark',
+ family: 'document',
+ icon: 'globe',
+ manual: false,
+ attrs: [
+ { key: 'archive_url', label: 'Archived copy', kind: 'url', rungs: [], options: [] },
+ {
+ key: 'reliability',
+ label: 'Source reliability',
+ kind: 'choice',
+ rungs: [],
+ options: [
+ { value: 'A', label: 'Completely reliable' },
+ { value: 'B', label: 'Usually reliable' },
+ ],
+ },
+ ],
+ },
+];
+
+let mod;
+
+beforeEach(async () => {
+ vi.resetModules();
+ get.mockReset();
+ get.mockResolvedValue(VOCABULARY);
+ mod = await import('./entityTypes.svelte.js');
+});
+
+describe('the entity vocabulary', () => {
+ it('is fetched once however many surfaces ask for it', async () => {
+ await Promise.all([mod.loadEntityTypes(), mod.loadEntityTypes(), mod.loadEntityTypes()]);
+
+ expect(get).toHaveBeenCalledTimes(1);
+ expect(get).toHaveBeenCalledWith('/api/cases/entity-types');
+ });
+
+ it('reads a type as words and names its family', async () => {
+ await mod.loadEntityTypes();
+
+ expect(mod.entityLabel('place')).toBe('Place');
+ expect(mod.entityFamily('person')).toBe('actor');
+ expect(mod.entityFamily('media')).toBe('collected');
+ });
+
+ it('names the primary value for the selected type', async () => {
+ await mod.loadEntityTypes();
+
+ expect(mod.entityIdentityLabel('person')).toBe('Full name');
+ expect(mod.entityIdentityPlaceholder('person')).toBe('Name or known alias');
+ expect(mod.entityIdentityLabel('cuneiform-tablet')).toBe('Title');
+ });
+
+ it('serves the declared fields in registry order, with their bounds', async () => {
+ await mod.loadEntityTypes();
+ const fields = mod.entityFields('place');
+
+ expect(fields.map((f) => f.key)).toEqual(['radius_m', 'footprint', 'verbatim']);
+ // the bounds ship with the field so the form refuses what the API refuses
+ expect(fields[0].minimum).toBe(1);
+ expect(fields[0].rungs.map((r) => r.value)).toEqual([100, 2000]);
+ });
+
+ it('opens a heading where the registry changes group, and nowhere else', () => {
+ // one type can hold several subjects, so the heading rides on the field that
+ // opens the block and the fields after it continue under whatever is open
+ const marked = mod.withHeadings([
+ { key: 'count', group: 'What it states' },
+ { key: 'condition' },
+ { key: 'when', group: 'When' },
+ { key: 'time_role' },
+ { key: 'confidence', group: 'Reasoning' },
+ { key: 'method' },
+ ]);
+
+ expect(marked.map((f) => f.heads)).toEqual([
+ 'What it states', '', 'When', '', 'Reasoning', '',
+ ]);
+ });
+
+ it('heads nothing for a type whose fields stand on their own labels', () => {
+ const marked = mod.withHeadings([{ key: 'imo' }, { key: 'mmsi' }]);
+
+ expect(marked.map((f) => f.heads)).toEqual(['', '']);
+ });
+
+ it('names the families in registry order, which is what the board filters by', async () => {
+ await mod.loadEntityTypes();
+
+ expect(mod.entityFamilies()).toEqual(['actor', 'place', 'collected', 'document']);
+ expect(mod.entityTypes().map((e) => e.type)).toEqual(['person', 'place', 'media', 'bookmark']);
+ });
+
+ it('explains a type and its family in one clause, so no menu is bare jargon', async () => {
+ await mod.loadEntityTypes();
+
+ expect(mod.entityHint('place')).toBe('a saved point');
+ expect(mod.familyReads('actor')).toBe('a person or organization that can act or hold ownership');
+ // and nothing invented locally for a word the registry has never heard of
+ expect(mod.entityHint('cuneiform-tablet')).toBe('');
+ expect(mod.familyReads('artefact')).toBe('');
+ });
+
+ it('serves the icon a type is drawn with, so no screen keeps its own map', async () => {
+ await mod.loadEntityTypes();
+
+ expect(mod.typeIcon('place')).toBe('pin');
+ expect(mod.typeIcon('cuneiform-tablet')).toBe(null);
+ });
+
+ it('offers only the hand-made types for creation', async () => {
+ await mod.loadEntityTypes();
+
+ // a media is born from an import and a place from a save, so neither belongs
+ // in a create menu
+ expect(mod.creatableTypes().map((e) => e.type)).toEqual(['person']);
+ expect(mod.isManualEntityType('person')).toBe(true);
+ expect(mod.isManualEntityType('media')).toBe(false);
+ });
+
+ it('says which types have presentation photos', async () => {
+ await mod.loadEntityTypes();
+
+ expect(mod.hasImageGallery('person')).toBe(true);
+ expect(mod.hasImageGallery('media')).toBe(false);
+ });
+
+ it('degrades to the raw slug and no fields before the registry lands', () => {
+ expect(coldLabel('vessel')).toBe('vessel');
+ expect(coldFields('place')).toEqual([]);
+ });
+
+ it('drops a failed read so the next surface retries', async () => {
+ vi.resetModules();
+ get.mockRejectedValueOnce(new Error('offline'));
+ const cold = await import('./entityTypes.svelte.js');
+
+ await cold.loadEntityTypes();
+ expect(cold.entityFields('place')).toEqual([]);
+
+ get.mockResolvedValue(VOCABULARY);
+ await cold.loadEntityTypes();
+ expect(cold.entityFields('place')).toHaveLength(3);
+ });
+
+ it('has no fields for a free type it has never heard of', async () => {
+ await mod.loadEntityTypes();
+
+ expect(mod.entityFields('cuneiform-tablet')).toEqual([]);
+ expect(mod.entityFamily('cuneiform-tablet')).toBe(null);
+ });
+});
+
+describe('how reliable a source says it is', () => {
+ const bookmark = (attrs) => ({ type: 'bookmark', attrs });
+
+ it('reads the grade in the registry’s own words', async () => {
+ await mod.loadEntityTypes();
+
+ expect(mod.reliabilityOf(bookmark({ reliability: 'B' }))).toEqual({
+ grade: 'B',
+ label: 'Usually reliable',
+ });
+ });
+
+ it('says nothing for an ungraded source, a type that carries no grade, or junk', async () => {
+ await mod.loadEntityTypes();
+
+ // all three render as nothing: an ungraded source is the normal case, and
+ // flagging it would turn an optional field into a standing chore
+ expect(mod.reliabilityOf(bookmark({}))).toBe(null);
+ expect(mod.reliabilityOf({ type: 'place', attrs: { reliability: 'B' } })).toBe(null);
+ expect(mod.reliabilityOf(bookmark({ reliability: 'F' }))).toBe(null);
+ expect(mod.reliabilityOf(null)).toBe(null);
+ });
+
+ it('never reports the edge’s own rating as the source’s grade', async () => {
+ await mod.loadEntityTypes();
+
+ // the two axes are separate objects, and this reader only ever looks at one
+ expect(mod.reliabilityOf({ type: 'bookmark', attrs: { confidence: 3 } })).toBe(null);
+ });
+});
diff --git a/frontend/src/lib/fileUrl.js b/frontend/src/lib/fileUrl.js
new file mode 100644
index 0000000..8c4206a
--- /dev/null
+++ b/frontend/src/lib/fileUrl.js
@@ -0,0 +1,37 @@
+/**
+ * URLs for the case-file route (`/files/<case>/<relative path>`).
+ *
+ * A media file's name is whatever it was called wherever it came from, and a
+ * TikTok download really lands as `#3deenero2025.mp4`. Interpolated raw, that
+ * `#` opens a fragment: the browser asks for `media/` and drops the rest, so
+ * the video plays nowhere while its hash-named thumbnail still shows. `?` and
+ * `%` break the same way. Every reader of a case file builds its URL here.
+ *
+ * Slashes stay slashes — the route takes a whole relative path — so encoding
+ * runs per segment.
+ */
+
+export function encodeRelPath(relPath) {
+ return String(relPath ?? '').split('/').map(encodeURIComponent).join('/');
+}
+
+export function fileUrl(caseId, relPath) {
+ return `/files/${encodeURIComponent(caseId ?? '')}/${encodeRelPath(relPath)}`;
+}
+
+/** The case-relative path a `/files/` URL points at, or null if it points
+ * elsewhere. The inverse of `fileUrl`, for the note markdown that stores these
+ * URLs as text: a path read back out has to match the one on the entity again.
+ * Notes written before the encoding still decode to themselves, and a lone `%`
+ * (which `decodeURIComponent` refuses) is returned as it was rather than
+ * throwing on someone's old note. */
+export function fileRelPath(url, caseId) {
+ const prefix = fileUrl(caseId, '');
+ if (!caseId || !String(url ?? '').startsWith(prefix)) return null;
+ const encoded = String(url).slice(prefix.length);
+ try {
+ return decodeURIComponent(encoded);
+ } catch {
+ return encoded;
+ }
+}
diff --git a/frontend/src/lib/fileUrl.test.js b/frontend/src/lib/fileUrl.test.js
new file mode 100644
index 0000000..70e0763
--- /dev/null
+++ b/frontend/src/lib/fileUrl.test.js
@@ -0,0 +1,76 @@
+import { readdirSync, readFileSync, statSync } from 'node:fs';
+import { fileURLToPath } from 'node:url';
+import { join } from 'node:path';
+
+import { describe, expect, it } from 'vitest';
+
+import { encodeRelPath, fileRelPath, fileUrl } from './fileUrl.js';
+
+describe('fileUrl', () => {
+ it('encodes the hash a downloaded video is really named with', () => {
+ // The bug this exists for: raw, the `#` opens a fragment, the request
+ // reaches the server as `media/` and the video plays nowhere while its
+ // hash-named thumbnail still shows.
+ const url = fileUrl('case-1', 'media/#3deenero2025.mp4');
+ expect(url).toBe('/files/case-1/media/%233deenero2025.mp4');
+ expect(new URL(url, 'http://localhost').hash).toBe('');
+ });
+
+ it('encodes every other character that would end or reroute the path', () => {
+ expect(encodeRelPath('media/what?.png')).toBe('media/what%3F.png');
+ expect(encodeRelPath('media/100%.jpg')).toBe('media/100%25.jpg');
+ expect(encodeRelPath('media/a+b.png')).toBe('media/a%2Bb.png');
+ expect(encodeRelPath('media/two words.png')).toBe('media/two%20words.png');
+ });
+
+ it('keeps the separators, so a nested path stays a path', () => {
+ expect(fileUrl('c', 'proofs/A trip.assets/shot.png')).toBe(
+ '/files/c/proofs/A%20trip.assets/shot.png',
+ );
+ });
+
+ it('leaves an ordinary name alone', () => {
+ expect(fileUrl('c', 'media/.thumbs/ae3606-g1.jpg')).toBe('/files/c/media/.thumbs/ae3606-g1.jpg');
+ });
+
+ it('reads a path back out of its own URL', () => {
+ const path = 'media/#3deenero2025.mp4';
+ expect(fileRelPath(fileUrl('c', path), 'c')).toBe(path);
+ });
+
+ it('reads back a path from a URL written before the encoding', () => {
+ expect(fileRelPath('/files/c/media/#3deenero2025.mp4', 'c')).toBe('media/#3deenero2025.mp4');
+ });
+
+ it('survives a stray percent rather than throwing on an old note', () => {
+ expect(fileRelPath('/files/c/media/100%.jpg', 'c')).toBe('media/100%.jpg');
+ });
+
+ it('ignores URLs that point somewhere else', () => {
+ expect(fileRelPath('https://example.com/a.png', 'c')).toBeNull();
+ expect(fileRelPath('/files/other/media/a.png', 'c')).toBeNull();
+ expect(fileRelPath('/files/c/media/a.png', null)).toBeNull();
+ });
+});
+
+describe('the case-file route has one builder', () => {
+ it('is reached through this module everywhere, never interpolated by hand', () => {
+ // The bug was one unencoded template literal among forty identical ones, in
+ // whichever tool happened to render that file. A tool added later would
+ // reintroduce it silently, so the gate is on the pattern, not on the tools.
+ const root = fileURLToPath(new URL('..', import.meta.url));
+ const offenders = [];
+ const walk = (dir) => {
+ for (const name of readdirSync(dir)) {
+ const path = join(dir, name);
+ if (statSync(path).isDirectory()) {
+ if (name !== 'node_modules') walk(path);
+ } else if (/\.(svelte|js)$/.test(name) && !name.endsWith('.test.js') && name !== 'fileUrl.js') {
+ if (/`\/files\//.test(readFileSync(path, 'utf8'))) offenders.push(path.slice(root.length));
+ }
+ }
+ };
+ walk(root);
+ expect(offenders).toEqual([]);
+ });
+});
diff --git a/frontend/src/lib/graph.js b/frontend/src/lib/graph.js
new file mode 100644
index 0000000..ff4d9f2
--- /dev/null
+++ b/frontend/src/lib/graph.js
@@ -0,0 +1,1060 @@
+/**
+ * Placing a case graph on a canvas, deterministically.
+ *
+ * The rule this file exists for: **the same case draws the same picture every
+ * time.** A graph screenshot goes into a report beside a satellite capture, and a
+ * capture is reproducible — a layout that settled somewhere new on every open
+ * would make the picture an illustration rather than a reading of the case. So
+ * nothing here simulates, jitters or animates towards a rest position. Every
+ * coordinate is a pure function of the payload, and equal payloads give equal
+ * pixels.
+ *
+ * That rules out the usual answer — an animated, randomly seeded simulation run
+ * until it goes quiet — but not the physics. Two placements are built, each
+ * carrying meaning:
+ *
+ * - **Clusters**, for the whole case. A ring per family (ONTOLOGY §2), ordered by
+ * degree, is the seed; a relaxation with a fixed pass count then pulls linked
+ * nodes together and pushes the rest apart, so the parts of the case that are
+ * about each other end up next to each other. Position means connectivity, and
+ * the same payload gives the same pixels.
+ * - **Columns per hop**, for a neighbourhood. Distance from the root is the
+ * question being asked, so it becomes the horizontal axis and nothing else
+ * competes with it.
+ *
+ * **A node the analyst dragged wins over both.** An arrangement somebody built by
+ * hand carries more than one a relaxation computed, so a pinned node is a fixed
+ * point: it pushes and pulls, nothing moves it, and the rest of the case settles
+ * around it. That does not weaken the rule above — a pin is part of the payload, so
+ * the same case with the same pins still draws the same picture. It is what lets a
+ * new node join an arrangement instead of restarting it.
+ *
+ * Neither placement reads a clock. When stated time lands (SPEC §6, v4), it
+ * becomes a third arrangement beside these two rather than a change to either:
+ * `arrange` dispatches on a mode, and a time mode is one more branch taking the
+ * same nodes and returning the same `{id, x, y}` shape.
+ */
+
+/** Golden-angle radians: the spacing that keeps a ring from forming spokes. */
+const GOLDEN = Math.PI * (3 - Math.sqrt(5));
+
+/** Ring geometry, in canvas units before the view transform. */
+const RING_GAP = 190;
+const NODE_GAP = 78;
+const COLUMN_GAP = 260;
+const ROW_GAP = 74;
+
+/**
+ * The families in drawing order, outermost ring last. Subjects sit innermost
+ * because a case is read from who and what, then out to the material that shows
+ * them and the statements made about them.
+ */
+export const FAMILY_ORDER = [
+ 'actor',
+ 'asset',
+ 'class',
+ 'identifier',
+ 'place',
+ 'collected',
+ 'document',
+ 'claim',
+];
+
+/** Where a family sits in the ring order; unknown families ring outside them all. */
+export function familyRank(family) {
+ const at = FAMILY_ORDER.indexOf(family);
+ return at === -1 ? FAMILY_ORDER.length : at;
+}
+
+/**
+ * Sort nodes into the order a ring is filled: most connected first, then by
+ * label, then by id. The last two are what make the layout stable — degree alone
+ * ties constantly, and a tie broken by array order would move a node whenever the
+ * server returned the same set differently.
+ */
+export function ringOrder(nodes) {
+ return [...nodes].sort(
+ (a, b) =>
+ b.degree - a.degree ||
+ String(a.label).localeCompare(String(b.label)) ||
+ String(a.id).localeCompare(String(b.id)),
+ );
+}
+
+/**
+ * Seed a whole-case view: one ring per family present, ordered by degree.
+ *
+ * This is the **starting** position, not the final one. On its own a ring is a bad
+ * graph layout — every node on a circle means every edge crosses the middle, which
+ * is the most crossings possible and tells the eye nothing. What it is good at is
+ * being a deterministic, well-spread, family-grouped starting point for the
+ * relaxation in `arrangeClusters`, which is what actually turns position into
+ * meaning.
+ *
+ * A ring's radius grows with how many nodes it holds, so a crowded family does
+ * not overlap the one outside it. Empty families take no ring at all rather than
+ * leaving a gap, which is what keeps a small case compact instead of drawing the
+ * skeleton of a large one.
+ */
+export function arrangeRings(nodes) {
+ const byFamily = new Map();
+ for (const node of nodes) {
+ const key = node.family || 'other';
+ if (!byFamily.has(key)) byFamily.set(key, []);
+ byFamily.get(key).push(node);
+ }
+ const families = [...byFamily.keys()].sort(
+ (a, b) => familyRank(a) - familyRank(b) || a.localeCompare(b),
+ );
+
+ const placed = [];
+ let radius = 0;
+ for (const family of families) {
+ const members = ringOrder(byFamily.get(family));
+ // The circumference has to hold every member at NODE_GAP apart, and a ring
+ // never pulls inside the one it encloses.
+ radius = Math.max(radius + RING_GAP, (members.length * NODE_GAP) / (2 * Math.PI));
+ if (members.length === 1) {
+ placed.push({ id: members[0].id, x: radius, y: 0, family, ring: radius });
+ continue;
+ }
+ members.forEach((node, index) => {
+ // Golden-angle offset per ring so neighbouring rings do not line their
+ // nodes up into spokes, which reads as structure that is not there.
+ const angle = (index / members.length) * 2 * Math.PI + familyRank(family) * GOLDEN;
+ placed.push({
+ id: node.id,
+ x: radius * Math.cos(angle),
+ y: radius * Math.sin(angle),
+ family,
+ ring: radius,
+ });
+ });
+ }
+ return placed;
+}
+
+/**
+ * Place a neighbourhood: one column per hop, the root alone on the left.
+ *
+ * Distance from the root is the whole question, so it owns the horizontal axis.
+ * Within a column, the same degree-then-label order as a ring, so a node does not
+ * move when the same neighbourhood is opened twice.
+ */
+export function arrangeHops(nodes) {
+ const byHop = new Map();
+ for (const node of nodes) {
+ const hop = Number.isFinite(node.hop) ? node.hop : 0;
+ if (!byHop.has(hop)) byHop.set(hop, []);
+ byHop.get(hop).push(node);
+ }
+ const placed = [];
+ for (const hop of [...byHop.keys()].sort((a, b) => a - b)) {
+ const column = ringOrder(byHop.get(hop));
+ const top = -((column.length - 1) * ROW_GAP) / 2;
+ column.forEach((node, index) => {
+ placed.push({ id: node.id, x: hop * COLUMN_GAP, y: top + index * ROW_GAP, hop });
+ });
+ }
+ return placed;
+}
+
+/** Where the parked column of unconnected nodes sits, relative to the cluster. */
+const PARK_GAP = 150;
+const PARK_ROWS = 8;
+
+/**
+ * Where a node was put by hand, or null when nobody has moved it.
+ *
+ * Two sources, one answer. The payload carries `pin` for a node the case has
+ * recorded; `pins` carries the drag that has just happened and may not have
+ * reached the server yet. The local one wins, because it is the more recent
+ * statement of the same thing.
+ *
+ * `null` rather than `{x: 0, y: 0}` for an unplaced node: the origin is a real
+ * spot on the canvas, and a node the layout owns has to be told apart from one
+ * that was dropped in the middle.
+ */
+function pinOf(node, pins) {
+ const local = pins.get(node.id);
+ if (local && Number.isFinite(local.x) && Number.isFinite(local.y)) return local;
+ const stated = node.pin;
+ if (!Array.isArray(stated) || !Number.isFinite(stated[0]) || !Number.isFinite(stated[1])) {
+ return null;
+ }
+ return { x: stated[0], y: stated[1] };
+}
+
+/**
+ * Seed a node the layout still owns beside the fixed points it is attached to.
+ *
+ * Without this a new node starts on its family ring, which can be most of the
+ * canvas away from the neighbours that will end up pulling it: the early passes
+ * then drag it across the picture and where it stops depends on how many passes
+ * there were. Starting it where it is going to end up makes the arrival quiet,
+ * which is the whole point of adding to an arrangement rather than recomputing it.
+ *
+ * This is where an arrival lands once the whole drawing is a fixed point: a node
+ * opened into a case of two thousand appears beside the neighbours that asked for
+ * it, and the two thousand do not stir.
+ *
+ * The fan-out is by index, not at random, so a node that arrives beside three
+ * pinned neighbours lands in the same place on every read.
+ */
+function seedBesideAnchors(ids, anchors, springs, at) {
+ const nearby = new Map();
+ for (const [a, b] of springs) {
+ for (const [self, other] of [
+ [a, b],
+ [b, a],
+ ]) {
+ const id = ids[self];
+ const anchor = anchors.get(ids[other]);
+ if (!anchor || anchors.has(id)) continue;
+ if (!nearby.has(id)) nearby.set(id, []);
+ nearby.get(id).push(anchor);
+ }
+ }
+ let placed = 0;
+ for (const [id, around] of nearby) {
+ const x = around.reduce((sum, spot) => sum + spot.x, 0) / around.length;
+ const y = around.reduce((sum, spot) => sum + spot.y, 0) / around.length;
+ // A ring of arrivals around the anchor rather than a pile on top of it.
+ const angle = placed * GOLDEN;
+ placed += 1;
+ at.set(id, { x: x + Math.cos(angle) * NODE_GAP, y: y + Math.sin(angle) * NODE_GAP });
+ }
+}
+
+/**
+ * How many relaxation passes a graph of this size gets.
+ *
+ * Fixed per size rather than "until it settles": a stopping rule that reads the
+ * current state is what makes a layout wander between runs. This is a pure
+ * function of the node count, so the same case gets the same number of passes
+ * forever, and a large graph does not pay O(n²) three hundred times.
+ */
+export function passesFor(count) {
+ return Math.max(60, Math.min(300, Math.round(2600 / Math.max(count, 1))));
+}
+
+/**
+ * Place a whole-case view so that **position means connectivity**.
+ *
+ * The ring seeding groups families and spreads them evenly; this then relaxes the
+ * result so nodes that are linked pull together and everything else pushes apart.
+ * What comes out is clusters — the parts of the case that are actually about each
+ * other end up near each other, and the eye reads structure instead of a circle of
+ * dots with lines through the middle.
+ *
+ * **It is still reproducible.** The objection to a force layout is that it settles
+ * somewhere new each time, and that objection is about *animated, randomly seeded,
+ * run-until-quiet* simulations. None of those apply: the seed is the deterministic
+ * ring, the pass count is fixed by size, the cooling schedule is fixed, and no
+ * clock or random number is read. Same payload, same pixels — which is what a graph
+ * that ends up in a report needs.
+ *
+ * **Unconnected nodes are parked, not mixed in.** A node nothing links to has no
+ * place in a picture about links: left in the cloud it drifts wherever repulsion
+ * pushes it and reads as meaningful position. It goes in a tidy column to the side,
+ * where being set apart is itself the reading.
+ *
+ * **A node the analyst placed is a fixed point.** An arrangement somebody built by
+ * hand outranks the one this computes, so a pinned node is never moved by a force —
+ * it still pushes its neighbours and still pulls what it is linked to, but nothing
+ * pushes back. Everything else settles around the pins, which is what lets a new
+ * node join an arrangement instead of restarting it.
+ *
+ * **So is a node the drawing already holds.** `settled` is where each node ended up
+ * last time this same question was drawn, and it is fixed for the same reason a pin
+ * is one step weaker: nobody put it there, but somebody has been *reading* the
+ * picture it is part of. Opening twenty nodes into a drawing of two thousand then
+ * costs twenty placements rather than two thousand, and — the part that matters more
+ * than the seconds — nothing already on screen moves when something arrives. The
+ * caller decides what "the same question" means and empties the map when it changes.
+ *
+ * The price, accepted: the picture depends on the order things were opened in. Pins
+ * already broke pure reproducibility, an arrangement built by hand is already part
+ * of the payload, and it becomes reproducible again the day a view is saved.
+ *
+ * The park is not part of that promise. It is placed *relative to* the drawing, so a
+ * column that follows the cluster's edge as the cluster grows is doing its job.
+ */
+export function arrangeClusters(nodes, links, pins = new Map(), settled = new Map()) {
+ const anchors = new Map();
+ for (const node of nodes) {
+ const spot = pinOf(node, pins);
+ if (spot) anchors.set(node.id, spot);
+ }
+ // A node that was placed by hand is not parked, whatever its degree: somebody
+ // chose where it goes, and the park is for what nothing has been decided about.
+ const linked = nodes.filter((node) => node.degree > 0 || anchors.has(node.id));
+ const loose = ringOrder(
+ nodes.filter((node) => node.degree <= 0 && !anchors.has(node.id)),
+ );
+ if (!linked.length) return parkOnly(loose);
+
+ // Both kinds of fixed point in one map: what the analyst placed, over what the
+ // drawing already held. A pin wins, because the two disagree only just after a
+ // drag, and the drag is the more recent statement of the same thing.
+ const held = new Map();
+ for (const node of linked) {
+ const spot = settled.get(node.id);
+ if (spot && Number.isFinite(spot.x) && Number.isFinite(spot.y)) {
+ held.set(node.id, { x: spot.x, y: spot.y });
+ }
+ }
+ for (const [id, spot] of anchors) held.set(id, spot);
+
+ const seats = arrangeRings(linked);
+ const at = new Map();
+ for (const seat of seats) at.set(seat.id, { x: seat.x, y: seat.y });
+ for (const [id, spot] of held) at.set(id, { x: spot.x, y: spot.y });
+
+ // **Indices come from the seating, not from the payload.** The relaxation sums a
+ // force per node in index order, and floating-point addition is not associative,
+ // so the same case handed back by the server in another order would settle a
+ // fraction of a pixel away and keep amplifying that over three hundred passes.
+ // The ring seating is already sorted by family and degree, so taking the order
+ // from it makes the whole arrangement a function of the case rather than of the
+ // response.
+ const ids = seats.map((seat) => seat.id);
+ const index = new Map(ids.map((id, i) => [id, i]));
+ const byId = new Map(linked.map((node) => [node.id, node]));
+ // A hub claims room and holds its ground: it pushes harder and is moved less by
+ // what it is attached to. Without this the node with thirty edges is dragged
+ // into the middle of its own satellites and the cluster reads as a blob.
+ const mass = ids.map((id) => 1 + Math.sqrt(Math.max(byId.get(id).degree, 0)) * 0.5);
+
+ // Edges between two placed nodes are the only ones that can pull. Sorted for the
+ // same reason the nodes are: the pulls are summed in this order.
+ const springs = [];
+ for (const link of links ?? []) {
+ const a = index.get(link.from);
+ const b = index.get(link.to);
+ if (a !== undefined && b !== undefined && a !== b) {
+ springs.push(a < b ? [a, b] : [b, a]);
+ }
+ }
+ springs.sort((one, other) => one[0] - other[0] || one[1] - other[1]);
+
+ if (held.size) seedBesideAnchors(ids, held, springs, at);
+ const xs = ids.map((id) => at.get(id).x);
+ const ys = ids.map((id) => at.get(id).y);
+ const fixed = ids.map((id) => held.has(id));
+ // Gravity pulls towards the middle of the arrangement, which is the middle of
+ // what is fixed once anything is. Towards the origin instead, an analyst who laid
+ // the case out away from the centre would watch every new node appear back where
+ // they had moved away from.
+ const centre = { x: 0, y: 0 };
+ if (held.size) {
+ for (const spot of held.values()) {
+ centre.x += spot.x / held.size;
+ centre.y += spot.y / held.size;
+ }
+ }
+
+ const n = ids.length;
+ const spread = 130; // the distance a linked pair settles at
+ const passes = passesFor(n);
+ // The one loop that costs the square of the drawing, walked so that it costs the
+ // square of what can still *move*. Every node comes up, movers first, and only a
+ // mover opens an inner loop — so a fixed pair is never visited, and a mover meets
+ // every node exactly once whichever side it is on.
+ //
+ // **Nothing about the result changes.** The force on a fixed node was already
+ // computed and thrown away by the integration below; not computing it cannot
+ // arrive anywhere else. With nothing fixed, `order` is the index order and this is
+ // the pair loop it replaces, term for term.
+ const movers = [];
+ const anchored = [];
+ for (let i = 0; i < n; i += 1) (fixed[i] ? anchored : movers).push(i);
+ const order = movers.concat(anchored);
+ for (let pass = 0; pass < passes; pass += 1) {
+ // A fixed cooling ramp: strong early moves, fine adjustments late. Linear,
+ // and read off the pass number rather than off the current state, because a
+ // stopping rule that looks at the layout is what makes a layout wander.
+ const heat = 1 - pass / passes;
+ const dx = new Array(n).fill(0);
+ const dy = new Array(n).fill(0);
+
+ // Repulsion falls off as 1/d and attraction grows as d², which is what makes
+ // a cluster a cluster: a pair with an edge between them settles at `spread`,
+ // and two nodes with no edge have nothing holding them at any distance, so
+ // they drift out of each other's way. A repulsion that fell off as 1/d²
+ // instead let unrelated nodes sit closer than linked ones.
+ for (let a = 0; a < movers.length; a += 1) {
+ const i = order[a];
+ for (let b = a + 1; b < order.length; b += 1) {
+ const j = order[b];
+ let ox = xs[i] - xs[j];
+ let oy = ys[i] - ys[j];
+ let dist = Math.hypot(ox, oy);
+ if (dist < 1e-3) {
+ // Two nodes exactly on top of each other have no direction to separate
+ // along. Offset by index rather than at random, so the tie breaks the
+ // same way every run.
+ ox = (i % 7) - 3 || 1;
+ oy = (j % 5) - 2 || 1;
+ dist = Math.hypot(ox, oy);
+ }
+ // A hub claims room: it pushes harder, and below it is moved less.
+ const push = ((spread * spread) / dist) * mass[i] * mass[j];
+ dx[i] += (ox / dist) * push;
+ dy[i] += (oy / dist) * push;
+ dx[j] -= (ox / dist) * push;
+ dy[j] -= (oy / dist) * push;
+ }
+ }
+
+ for (const [a, b] of springs) {
+ const ox = xs[b] - xs[a];
+ const oy = ys[b] - ys[a];
+ const dist = Math.hypot(ox, oy) || 1;
+ const pull = (dist * dist) / spread;
+ dx[a] += (ox / dist) * pull;
+ dy[a] += (oy / dist) * pull;
+ dx[b] -= (ox / dist) * pull;
+ dy[b] -= (oy / dist) * pull;
+ }
+
+ for (const i of movers) {
+ // What is fixed is where it was put, or where the drawing already had it. It
+ // pushed and pulled above, which is how the rest of the case arranges itself
+ // around it, but no force moves it.
+ // Gravity keeps a case of several components from drifting apart forever,
+ // and pulls the heaviest nodes hardest, so the busiest part of the case
+ // ends up in the middle of the picture rather than on an edge of it.
+ dx[i] -= (xs[i] - centre.x) * 0.9 * mass[i];
+ dy[i] -= (ys[i] - centre.y) * 0.9 * mass[i];
+ const force = Math.hypot(dx[i], dy[i]);
+ if (force < 1e-9) continue;
+ const step = Math.min(force / mass[i], spread * 0.5 * heat + 1);
+ xs[i] += (dx[i] / force) * step;
+ ys[i] += (dy[i] / force) * step;
+ }
+ }
+
+ // `pinned` travels with the seat so the canvas can mark a hand-placed node
+ // without asking a second question: a node that ignores the layout has to say so,
+ // or it reads as one the layout simply left there. Read off `anchors` and not off
+ // `fixed`: a node held where the drawing already had it is not one somebody placed,
+ // and marking it with a pin would offer "let it go" for a choice nobody made.
+ const placed = ids.map((id, i) =>
+ anchors.has(id) ? { id, x: xs[i], y: ys[i], pinned: true } : { id, x: xs[i], y: ys[i] },
+ );
+ return placed.concat(park(loose, placed));
+}
+
+/** The unconnected column, to the right of whatever the cluster occupies. */
+function park(loose, placed) {
+ if (!loose.length) return [];
+ const box = extent(placed);
+ const left = box.maxX + PARK_GAP;
+ const top = -((Math.min(loose.length, PARK_ROWS) - 1) * ROW_GAP) / 2;
+ return loose.map((node, i) => ({
+ id: node.id,
+ x: left + Math.floor(i / PARK_ROWS) * PARK_GAP,
+ y: top + (i % PARK_ROWS) * ROW_GAP,
+ parked: true,
+ }));
+}
+
+function parkOnly(loose) {
+ const top = -((Math.min(loose.length, PARK_ROWS) - 1) * ROW_GAP) / 2;
+ return loose.map((node, i) => ({
+ id: node.id,
+ x: Math.floor(i / PARK_ROWS) * PARK_GAP,
+ y: top + (i % PARK_ROWS) * ROW_GAP,
+ parked: true,
+ }));
+}
+
+/**
+ * Place nodes for a mode. The one entry point every caller uses, and the seam a
+ * stated-time arrangement lands on without touching either existing branch.
+ *
+ * `pins` and `settled` reach the cluster arrangement only. A neighbourhood gives its
+ * horizontal axis to distance from the root, so a coordinate stated against the
+ * cluster would fight the one thing that arrangement exists to show.
+ */
+export function arrange(nodes, mode = 'rings', links = [], pins = new Map(), settled = new Map()) {
+ return mode === 'hops' ? arrangeHops(nodes) : arrangeClusters(nodes, links, pins, settled);
+}
+
+/**
+ * The bounding box of a placement, or a unit box when nothing is placed. What the
+ * view transform is computed from, so an empty case does not divide by zero.
+ */
+export function extent(placed) {
+ if (!placed.length) return { minX: 0, minY: 0, maxX: 1, maxY: 1 };
+ let minX = Infinity;
+ let minY = Infinity;
+ let maxX = -Infinity;
+ let maxY = -Infinity;
+ for (const node of placed) {
+ if (node.x < minX) minX = node.x;
+ if (node.y < minY) minY = node.y;
+ if (node.x > maxX) maxX = node.x;
+ if (node.y > maxY) maxY = node.y;
+ }
+ return { minX, minY, maxX, maxY };
+}
+
+/**
+ * Scale and offset that fit a placement inside a viewport, capped at 1 so a
+ * two-node case is not blown up to fill a screen.
+ */
+export function fit(placed, width, height, pad = 56) {
+ const box = extent(placed);
+ const spanX = Math.max(box.maxX - box.minX, 1);
+ const spanY = Math.max(box.maxY - box.minY, 1);
+ const scale = Math.min(
+ 1,
+ Math.max((width - pad * 2) / spanX, 0.05),
+ Math.max((height - pad * 2) / spanY, 0.05),
+ );
+ return {
+ scale,
+ x: width / 2 - ((box.minX + box.maxX) / 2) * scale,
+ y: height / 2 - ((box.minY + box.maxY) / 2) * scale,
+ };
+}
+
+/**
+ * Index a placement by id, so drawing an edge is two lookups rather than a scan.
+ */
+export function positionsById(placed) {
+ return new Map(placed.map((node) => [node.id, node]));
+}
+
+/**
+ * The edges a placement can actually draw. The server returns a closed set, so a
+ * dangling edge means the payload and the placement disagree — dropping it keeps
+ * the canvas honest rather than drawing a line to the origin. An edge onto its own
+ * node goes too: it has no length to draw and would show as a smudge under the
+ * node, while still being counted in the degree the node reports.
+ */
+export function drawableLinks(links, positions) {
+ return links.filter(
+ (link) => link.from !== link.to && positions.has(link.from) && positions.has(link.to),
+ );
+}
+
+/**
+ * Who each node touches, as a set of distinct neighbours.
+ *
+ * Distinct, not one entry per edge, because the question every fold asks is *what
+ * else holds this node* — and two verbs between the same pair are one holder said
+ * twice. A node's edge onto itself is left out for the same reason it is never
+ * drawn: it holds nothing up.
+ */
+function adjacency(nodes, links) {
+ const near = new Map();
+ for (const node of nodes) near.set(node.id, new Set());
+ for (const link of links) {
+ if (link.from === link.to) continue;
+ const from = near.get(link.from);
+ const to = near.get(link.to);
+ if (!from || !to) continue;
+ from.add(link.to);
+ to.add(link.from);
+ }
+ return near;
+}
+
+/**
+ * What a fold takes off the screen, and what it leaves alone.
+ *
+ * Folding a node puts away **what only hung off it**: pull the node out of the
+ * drawing in your head, and whatever falls off with it is what the fold takes. The
+ * node itself stays, carrying the count of what it now holds.
+ *
+ * The rule has to answer one hard case, and the answer is the whole of why this is
+ * not simply "everything one hop away". Removing a node shatters the drawing into
+ * pieces, and every piece is, technically, hanging off it — including the rest of
+ * the case. So:
+ *
+ * - a **lone node** hanging off the fold always goes. This is the clutter the fold
+ * exists for: the forty captures around one account, the identifiers under one
+ * person, none of which the drawing holds for any other reason.
+ * - among the pieces that have some structure of their own, **the biggest stays**.
+ * That piece is the drawing, and a fold that could take the case away with it
+ * would be a trapdoor rather than a control.
+ * - a piece holding a node the analyst **placed by hand** never goes. An arrangement
+ * somebody built is a statement that those nodes matter, and no automatic rule
+ * outranks it.
+ *
+ * What follows from that, and it is the guarantee worth stating: **a fold never cuts
+ * a link between two nodes that both stay.** Everything it takes was joined to the
+ * drawing through the node being folded and through nothing else, so the picture
+ * left behind says exactly what it said before, with fewer dots.
+ *
+ * Deterministic like everything else here: the pieces are compared by size, then by
+ * their lowest id, so the same drawing folds the same way every time.
+ *
+ * Returns `{ hidden, by }` — the ids that leave, and how many left because of each
+ * folded node, which is the count the node then carries.
+ */
+export function foldAway(collapsed, nodes, links, anchors = new Set()) {
+ const hidden = new Set();
+ const by = new Map();
+ const present = new Set(nodes.map((node) => node.id));
+ const seeds = [...new Set(collapsed)].filter((id) => present.has(id));
+ if (!seeds.length) return { hidden, by };
+
+ const near = adjacency(nodes, links);
+ const folded = new Set(seeds);
+ // The drawing minus the folded nodes, walked into its pieces. A piece that touches
+ // no folded node at all is somewhere else in the case and is never this fold's
+ // business, which is what keeps folding one node from reaching across the drawing.
+ const seen = new Set(folded);
+ const pieces = [];
+ for (const node of nodes) {
+ if (seen.has(node.id)) continue;
+ const members = [];
+ const touches = new Set();
+ const queue = [node.id];
+ seen.add(node.id);
+ while (queue.length) {
+ const id = queue.pop();
+ members.push(id);
+ for (const other of near.get(id) ?? []) {
+ if (folded.has(other)) {
+ touches.add(other);
+ continue;
+ }
+ if (seen.has(other)) continue;
+ seen.add(other);
+ queue.push(other);
+ }
+ }
+ if (!touches.size) continue;
+ pieces.push({
+ members,
+ touches,
+ held: members.some((id) => anchors.has(id)),
+ low: members.reduce((least, id) => (id < least ? id : least), members[0]),
+ });
+ }
+
+ // The biggest piece with a shape of its own is the drawing, and it stays. Lone
+ // nodes are never in the running: a fold that spared one arbitrary leaf out of
+ // forty would look broken, and the leaf it spared would be picked by a tie-break
+ // nobody can see.
+ const standing = pieces
+ .filter((piece) => piece.members.length > 1)
+ .sort((a, b) => b.members.length - a.members.length || (a.low < b.low ? -1 : 1));
+ const body = standing[0] ?? null;
+
+ for (const piece of pieces) {
+ if (piece === body || piece.held) continue;
+ for (const id of piece.members) hidden.add(id);
+ // Charged to the first folded node the piece touches, in the order they were
+ // folded, so two folds sharing a piece do not each claim all of it and the counts
+ // on screen add up to what actually left.
+ const owner = seeds.find((id) => piece.touches.has(id)) ?? seeds[0];
+ by.set(owner, (by.get(owner) ?? 0) + piece.members.length);
+ }
+ return { hidden, by };
+}
+
+/**
+ * How many nodes folding this one would take, on the drawing as it currently
+ * stands. What the switch on the node counts before it is pressed.
+ */
+export function foldableCount(id, nodes, links, anchors = new Set()) {
+ return foldAway([id], nodes, links, anchors).hidden.size;
+}
+
+/**
+ * Every node within `hops` steps of one node, walked over the edges given.
+ *
+ * **Undirected on purpose.** An arrowhead is a reading of a connection, not a wall:
+ * asking what surrounds an account and being handed only what it posted — never who
+ * posted about it — answers a question nobody asked. Direction is what the edge
+ * *says*, and it is written on the edge; distance is what the focus *is*.
+ *
+ * Walked over the drawn edges rather than asked of the case, which is what keeps
+ * this a reading of the picture on screen. Two hops through a node the view had to
+ * cut would be a claim the drawing cannot back up, and the analyst would have no way
+ * to see where the extra ring came from.
+ *
+ * The start is always in the set, so an unconnected node focuses on itself rather
+ * than on nothing.
+ */
+export function ringsAround(links, start, hops = 1) {
+ const reached = new Set([start]);
+ if (!start || hops < 1) return reached;
+ const near = new Map();
+ for (const link of links) {
+ if (!near.has(link.from)) near.set(link.from, []);
+ if (!near.has(link.to)) near.set(link.to, []);
+ near.get(link.from).push(link.to);
+ near.get(link.to).push(link.from);
+ }
+ let frontier = [start];
+ for (let step = 0; step < hops && frontier.length; step += 1) {
+ const next = [];
+ for (const id of frontier) {
+ for (const other of near.get(id) ?? []) {
+ if (reached.has(other)) continue;
+ reached.add(other);
+ next.push(other);
+ }
+ }
+ frontier = next;
+ }
+ return reached;
+}
+
+/** The one rating drawn on the line (``engine/links.REFUTED``). See `refuted` below
+ * for why it is the only one of the four. */
+const RULED_OUT = -1;
+
+/**
+ * The ways an edge is drawn, and what each one means.
+ *
+ * One table, read by both the stroke and the legend, because an unexplained dash
+ * pattern is decoration: the analyst has no way to learn that fine dots mean a
+ * mention. The semantics ride on the line rather than on the colour, so the
+ * picture survives being printed in black and white — which is what happens to a
+ * graph that reaches a report.
+ */
+export const EDGE_KINDS = [
+ { kind: 'lineage', label: 'produced from', dash: [], width: 1.7 },
+ { kind: 'stated', label: 'stated relation', dash: [8, 5], width: 1.3 },
+ // A relation the analyst checked and eliminated, kept in the case on purpose
+ // (`engine/links.REFUTED`): "it is not this bridge" is half the work of a
+ // geolocation, and the eleven candidates ruled out are the record of it. Drawn
+ // apart because a verdict is not a nuance — *probable* against *possible* is read
+ // one edge at a time in the panel, where a dead statement has to be legible without
+ // reading anything, or a picture of the case counts eleven live hypotheses.
+ //
+ // **The other three levels deliberately get no stroke.** Four more patterns would
+ // put two different questions on one channel — what kind of edge this is, and how
+ // sure of it — and the eye cannot hold seven dashes apart anyway. Short dashes at a
+ // stated relation's weight rather than a thinner line: a hairline reads as *faint*,
+ // which is what a tentative edge would be, and this one is not tentative. It is
+ // settled, and settled the other way.
+ { kind: 'refuted', label: 'ruled out', dash: [2, 3], width: 1.6 },
+ // Drawn apart from every other thing an analyst states, because it is the only
+ // verb saying two rows of the case cannot both stand: a reader scanning a
+ // statement cluster has to see the argument without reading the labels. Dash-dot
+ // rather than a hue, for the reason the whole table is patterns — the families own
+ // the palette and a report prints grey — and a long dash broken by a beat is what
+ // opposition looks like on paper.
+ { kind: 'contradiction', label: 'contradicts', dash: [10, 4, 2, 4], width: 1.8 },
+ { kind: 'mention', label: 'mentions', dash: [1.5, 4], width: 1 },
+ // Thicker because it stands for several, and worded so the picture says which lines
+ // are a path rather than a row: an edge that folded three citations is not the same
+ // object as one the analyst stated, and it cannot be confirmed or removed. The
+ // wording is the edge panel's own — *drawn as one edge* — because **fold** is what
+ // an expansion does in this tool, and one word cannot name two acts.
+ { kind: 'folded', label: 'sources, drawn as one edge', dash: [8, 5], width: 2.4 },
+ { kind: 'proposed', label: 'proposed, not confirmed', dash: [3, 5], width: 1 },
+];
+
+const EDGE_BY_KIND = new Map(EDGE_KINDS.map((entry) => [entry.kind, entry]));
+
+/** Which of them an edge is. A proposal is drawn as one whatever its verb, and a
+ * fold as one whatever it folded — the two are the same rule, applied to the two
+ * things an edge can be besides its verb. */
+export function edgeKind(link, chainTypes = []) {
+ if (link.provenance?.status === 'suggested') return 'proposed';
+ if (link.folded) return 'folded';
+ if (chainTypes.includes(link.type)) return 'lineage';
+ if (link.type === 'contradicts') return 'contradiction';
+ if (link.type === 'mentions') return 'mention';
+ // Read here rather than above, and it costs nothing to place it last: the API
+ // refuses a rating on a derivation, on a mention and on a claim connector, so an
+ // ordinary stated relation is the only thing that can carry one. There is no other
+ // kind for the verdict to outrank.
+ if (link.confidence === RULED_OUT) return 'refuted';
+ return 'stated';
+}
+
+/**
+ * How an edge is stroked, including its head. **Every edge carries one**: the
+ * vocabulary is directed — a photo is recorded at a place, never the reverse — so
+ * a line without a head hides half of what the edge says.
+ */
+export function edgeStyle(link, chainTypes = []) {
+ const kind = edgeKind(link, chainTypes);
+ return { ...EDGE_BY_KIND.get(kind), kind };
+}
+
+/** How far apart parallel edges are pulled at their midpoint. */
+const BEND_GAP = 22;
+
+/**
+ * How much each edge bows out of the straight line.
+ *
+ * Two nodes can hold several edges — a unit that owns a vehicle and is mentioned
+ * by the report naming it — and drawn straight they land on top of each other, so
+ * the picture says "one link" where the case says two. Each edge of a pair is bent
+ * to its own side of the line, and the order is the payload's own so the bend does
+ * not change between reads.
+ */
+export function parallelBends(links) {
+ const groups = new Map();
+ for (const link of links) {
+ const pair = [link.from, link.to].sort().join('\u0000');
+ if (!groups.has(pair)) groups.set(pair, []);
+ groups.get(pair).push(link);
+ }
+ const bends = new Map();
+ for (const group of groups.values()) {
+ group.forEach((link, index) => {
+ bends.set(link.id, group.length === 1 ? 0 : (index - (group.length - 1) / 2) * BEND_GAP);
+ });
+ }
+ return bends;
+}
+
+/**
+ * The points an edge is drawn through, cut back to the rim of the nodes it joins.
+ *
+ * Cut back because a head buried under the target circle points at nothing, and
+ * an arrow that starts at the centre of a hub is a line across it. A bend adds a
+ * third point off the midpoint, which is what separates parallel edges.
+ */
+export function edgePoints(from, to, fromRadius, toRadius, bend = 0) {
+ const ox = to.x - from.x;
+ const oy = to.y - from.y;
+ const dist = Math.hypot(ox, oy) || 1;
+ const ux = ox / dist;
+ const uy = oy / dist;
+ // The head needs a little air off the rim, or it reads as touching the node.
+ const start = { x: from.x + ux * (fromRadius + 2), y: from.y + uy * (fromRadius + 2) };
+ const end = { x: to.x - ux * (toRadius + 6), y: to.y - uy * (toRadius + 6) };
+ if (!bend) return [start.x, start.y, end.x, end.y];
+ const mid = {
+ x: (start.x + end.x) / 2 - uy * bend,
+ y: (start.y + end.y) / 2 + ux * bend,
+ };
+ return [start.x, start.y, mid.x, mid.y, end.x, end.y];
+}
+
+/**
+ * Where an edge's verb is written: beside the line rather than on it.
+ *
+ * `lift` is in canvas units and pushes the words off the stroke, perpendicular to
+ * it. Written on the line, a verb is read through its own dashes; written at the
+ * exact midpoint of a hub's edge, it lands on the hub's own label.
+ */
+export function edgeMidpoint(points, lift = 0) {
+ const bowed = points.length >= 6;
+ const end = bowed ? { x: points[4], y: points[5] } : { x: points[2], y: points[3] };
+ const chord = { x: (points[0] + end.x) / 2, y: (points[1] + end.y) / 2 };
+ const at = bowed ? { x: points[2], y: points[3] } : chord;
+ if (!lift) return at;
+ if (bowed) {
+ // Lifted the way the bow already leans, which pulls two parallel edges' words
+ // apart instead of stacking them one over the other.
+ const ox = at.x - chord.x;
+ const oy = at.y - chord.y;
+ const away = Math.hypot(ox, oy) || 1;
+ return { x: at.x + (ox / away) * lift, y: at.y + (oy / away) * lift };
+ }
+ const ox = end.x - points[0];
+ const oy = end.y - points[1];
+ const dist = Math.hypot(ox, oy) || 1;
+ // Always lifted towards the top of the canvas, so the two halves of a path
+ // through one node do not write their verbs on the same spot.
+ const sign = oy > 0 ? -1 : 1;
+ return { x: at.x + (oy / dist) * lift * sign, y: at.y - (ox / dist) * lift * sign };
+}
+
+/**
+ * The mini card a node becomes when the view is close enough to read one.
+ *
+ * In **screen** pixels, not canvas units, which is what makes the card viable at
+ * all: drawn in canvas units a 158-wide card would overlap its neighbours at every
+ * zoom, since the placement only spaces nodes 130 apart. Sized off the screen, the
+ * gap between two nodes grows with the zoom faster than the card does, so past
+ * `CARD_SCALE` the cards have room and below it they would not.
+ *
+ * `art` is the picture column: full height, flush against the stripe, so a thumbnail
+ * has a side of the card rather than a stamp in a corner of it. `glyph` is what a
+ * node with no picture draws in that column instead, centred, at the size it has
+ * always been — the cards that were already right are left alone.
+ */
+export const CARD = { w: 176, h: 50, art: 50, glyph: 34, pad: 8, stripe: 4 };
+
+/** The zoom past which a node is worth drawing as a card rather than as a dot. */
+export const CARD_SCALE = 1.15;
+
+/** How much bigger than its base size a card is ever drawn. */
+export const CARD_GROWTH = 1.7;
+
+/**
+ * What one of the card's own units is worth in canvas units, at a given zoom.
+ *
+ * A card pinned to an exact screen size stops answering the zoom: past `CARD_SCALE`
+ * the case keeps spreading out while the card stays the same stamp, so zooming in
+ * buys distance and nothing else — and the thumbnail inside it can never become
+ * readable. It grows by the square root of the zoom instead. Across the card range
+ * the gaps widen 2.8× and the card 1.7×, so the drawing keeps getting easier to read
+ * without the cards ever closing back in on each other.
+ */
+export function cardFactor(scale) {
+ const zoom = Math.max(Number(scale) || 0, 0.01);
+ const grown = Math.min(Math.max(Math.sqrt(zoom / CARD_SCALE), 1), CARD_GROWTH);
+ return grown / zoom;
+}
+
+/**
+ * How far the rim of a card sits from its centre, along one direction.
+ *
+ * An arrow has to stop at the edge of what it points at, and in card mode that is
+ * a rectangle rather than a circle. Exact for a centred axis-aligned box: whichever
+ * side the ray leaves through is the nearer of the two crossings.
+ */
+export function boxRadius(halfWidth, halfHeight, dx, dy) {
+ const ux = Math.abs(dx);
+ const uy = Math.abs(dy);
+ if (ux < 1e-9) return halfHeight;
+ if (uy < 1e-9) return halfWidth;
+ const length = Math.hypot(ux, uy);
+ return Math.min((halfWidth * length) / ux, (halfHeight * length) / uy);
+}
+
+/**
+ * The part of a picture that fills the card's art column, without distorting it.
+ *
+ * A thumbnail is whatever shape its source was — a screenshot is wide, a phone photo
+ * is tall — and stretching either into the column would make a row of cards look
+ * wrong in a way that is hard to name and easy to see. Fitting it *inside* instead
+ * left a wide capture as a thin strip floating in a hole, which read as a broken
+ * card rather than as a picture. So the middle of the thumbnail fills the column and
+ * the edges are cropped: the card says which media this is, and the tooltip is where
+ * the whole of it is looked at.
+ *
+ * `aspect` is the column's own width over its height, in source pixels.
+ */
+export function cropToFill(naturalWidth, naturalHeight, aspect = 1) {
+ const width = Math.max(Number(naturalWidth) || 0, 1);
+ const height = Math.max(Number(naturalHeight) || 0, 1);
+ const shape = Math.max(Number(aspect) || 0, 0.01);
+ const wider = width / height > shape;
+ const kept = {
+ width: wider ? height * shape : width,
+ height: wider ? height : width / shape,
+ };
+ return { ...kept, x: (width - kept.width) / 2, y: (height - kept.height) / 2 };
+}
+
+/**
+ * The node under a point on the canvas, or null.
+ *
+ * Hit-testing in canvas units rather than asking the renderer, because the answer
+ * is needed while a link is being dragged — when the shape under the pointer is
+ * covered by the rubber band being drawn over it. Geometry has no such problem,
+ * and it is the same geometry the arrows already stop at: a circle below the card
+ * zoom, a box above it.
+ *
+ * The nearest match wins, so two overlapping nodes resolve to the one whose centre
+ * is closer rather than to whichever was drawn last.
+ */
+export function nodeAt(placed, byId, point, { carded = false, scale = 1 } = {}) {
+ let best = null;
+ let closest = Infinity;
+ const unit = cardFactor(scale);
+ const half = { x: (CARD.w / 2) * unit, y: (CARD.h / 2) * unit };
+ for (const seat of placed) {
+ const dx = point.x - seat.x;
+ const dy = point.y - seat.y;
+ const inside = carded
+ ? Math.abs(dx) <= half.x && Math.abs(dy) <= half.y
+ : Math.hypot(dx, dy) <= nodeRadius(byId.get(seat.id)?.degree) + 4;
+ if (!inside) continue;
+ const away = Math.hypot(dx, dy);
+ if (away < closest) {
+ closest = away;
+ best = seat.id;
+ }
+ }
+ return best;
+}
+
+/**
+ * A node's radius: a hub reads as a hub without a label being counted. Growth is
+ * by square root so a degree-80 node is legible beside a degree-2 one instead of
+ * swallowing the canvas.
+ */
+export function nodeRadius(degree) {
+ // A node whose degree never arrived still has to draw. `Math.max` propagates a
+ // NaN rather than clamping it, so the value is coerced before it is compared.
+ const edges = Math.max(Number(degree) || 0, 0);
+ return 11 + Math.min(Math.sqrt(edges) * 2.6, 13);
+}
+
+/**
+ * Shorten a label to fit under a node. Long labels are the fastest way to turn a
+ * readable graph into a wall of text, and the full value is one click away in
+ * Details.
+ */
+export function shortLabel(label, max = 22) {
+ const text = String(label ?? '').trim();
+ return text.length <= max ? text : `${text.slice(0, max - 1)}…`;
+}
+
+/**
+ * The drawing as one string, for the undo stack.
+ *
+ * The graph is unusual in what it costs to undo: the picture is **derived** from a
+ * handful of explicit lists, so there is no inverse to write per act and no inverse
+ * that can be wrong. Remember the lists, put them back, and every act that has ever
+ * edited the drawing is undone by the same six lines — including the ones added
+ * later, which is what keeps this from rotting.
+ *
+ * Serialized here rather than in the component because the history compares
+ * snapshots as strings: two states that differ only in the order a `Set` iterated
+ * would fork the timeline and record an act nobody performed. What has no meaningful
+ * order is sorted; what carries the analyst's own order is left in it.
+ */
+export function drawingSnapshot(state = {}) {
+ return JSON.stringify({
+ lens: state.lens ?? 'all',
+ order: state.order ?? 'degree',
+ root: state.root ?? null,
+ hops: state.hops ?? 1,
+ folder: state.folder ?? '',
+ families: [...(state.families ?? [])].sort(),
+ // Left in the order they were asked for: the case echoes these back in it, and
+ // it is the analyst's own list rather than a set the drawing happens to hold.
+ kept: [...(state.kept ?? [])],
+ expanded: [...(state.expanded ?? [])],
+ omitted: [...(state.omitted ?? [])],
+ collapsed: [...(state.collapsed ?? [])],
+ putAway: Object.fromEntries(
+ Object.entries(state.putAway ?? {})
+ .map(([id, gone]) => [id, [...gone].sort()])
+ .sort(([one], [two]) => (one < two ? -1 : one > two ? 1 : 0)),
+ ),
+ arrangement: [...(state.arrangement ?? [])]
+ .map((spot) => ({ id: spot.id, x: spot.x, y: spot.y }))
+ .sort((one, two) => (one.id < two.id ? -1 : one.id > two.id ? 1 : 0)),
+ });
+}
+
+/**
+ * What has to be filed to put an arrangement back: the pins to place, and the ones
+ * to let go of.
+ *
+ * Read over the nodes **currently drawn** on both sides, which is the guard that
+ * matters: a pinned node the budget cut or a filter left out is in neither list, so
+ * an undo can never drop an arrangement it could not see.
+ */
+export function arrangementDiff(now = [], want = []) {
+ const at = new Map(now.map((spot) => [spot.id, spot]));
+ const wanted = new Map(want.map((spot) => [spot.id, spot]));
+ return {
+ place: want.filter((spot) => {
+ const had = at.get(spot.id);
+ return !had || had.x !== spot.x || had.y !== spot.y;
+ }),
+ drop: now.filter((spot) => !wanted.has(spot.id)).map((spot) => spot.id),
+ };
+}
diff --git a/frontend/src/lib/graph.test.js b/frontend/src/lib/graph.test.js
new file mode 100644
index 0000000..996b784
--- /dev/null
+++ b/frontend/src/lib/graph.test.js
@@ -0,0 +1,1174 @@
+import { describe, it, expect } from 'vitest';
+import {
+ CARD,
+ arrangementDiff,
+ drawingSnapshot,
+ nodeAt,
+ CARD_SCALE,
+ CARD_GROWTH,
+ EDGE_KINDS,
+ arrange,
+ boxRadius,
+ cardFactor,
+ cropToFill,
+ arrangeClusters,
+ arrangeHops,
+ arrangeRings,
+ drawableLinks,
+ edgeKind,
+ edgeMidpoint,
+ edgePoints,
+ edgeStyle,
+ foldAway,
+ foldableCount,
+ extent,
+ familyRank,
+ fit,
+ nodeRadius,
+ parallelBends,
+ positionsById,
+ ringOrder,
+ ringsAround,
+ shortLabel,
+} from './graph.js';
+
+const node = (id, family, degree = 0, label = id) => ({ id, family, degree, label });
+
+describe('ring order', () => {
+ it('puts the most connected first', () => {
+ const order = ringOrder([node('a', 'actor', 1), node('b', 'actor', 9)]);
+ expect(order.map((n) => n.id)).toEqual(['b', 'a']);
+ });
+
+ it('breaks ties on label then id, so equal degrees never shuffle', () => {
+ // The layout is only reproducible if ties are broken by something stable.
+ // Degree alone ties constantly on a real case.
+ const shuffled = [
+ { id: 'z', family: 'actor', degree: 2, label: 'Bravo' },
+ { id: 'a', family: 'actor', degree: 2, label: 'Alpha' },
+ ];
+ expect(ringOrder(shuffled).map((n) => n.id)).toEqual(['a', 'z']);
+ expect(ringOrder([...shuffled].reverse()).map((n) => n.id)).toEqual(['a', 'z']);
+ });
+});
+
+describe('ring layout', () => {
+ it('draws the same picture for the same payload', () => {
+ const nodes = [node('a', 'actor', 3), node('b', 'place', 1), node('c', 'actor', 2)];
+ expect(arrangeRings(nodes)).toEqual(arrangeRings(nodes));
+ });
+
+ it('does not move a node when the server returns the set in another order', () => {
+ const nodes = [node('a', 'actor', 3), node('b', 'actor', 1), node('c', 'actor', 2)];
+ const first = positionsById(arrangeRings(nodes));
+ const second = positionsById(arrangeRings([...nodes].reverse()));
+ for (const id of ['a', 'b', 'c']) {
+ expect(second.get(id).x).toBeCloseTo(first.get(id).x, 10);
+ expect(second.get(id).y).toBeCloseTo(first.get(id).y, 10);
+ }
+ });
+
+ it('gives each family its own ring, innermost by family order', () => {
+ const placed = positionsById(
+ arrangeRings([node('a', 'actor'), node('b', 'claim'), node('c', 'place')]),
+ );
+ expect(placed.get('a').ring).toBeLessThan(placed.get('c').ring);
+ expect(placed.get('c').ring).toBeLessThan(placed.get('b').ring);
+ });
+
+ it('takes no ring for a family the case does not hold', () => {
+ // A small case must draw compactly, not as the skeleton of a large one.
+ const one = arrangeRings([node('a', 'claim')]);
+ expect(one).toHaveLength(1);
+ expect(one[0].ring).toBeLessThan(400);
+ });
+
+ it('widens a ring so a crowded family does not overlap the next', () => {
+ const crowded = Array.from({ length: 60 }, (_, i) => node(`a${i}`, 'actor'));
+ const placed = positionsById(arrangeRings([...crowded, node('p', 'place')]));
+ expect(placed.get('p').ring).toBeGreaterThan(placed.get('a0').ring);
+ });
+
+ it('files an unknown family outside the ones the ontology names', () => {
+ expect(familyRank('actor')).toBeLessThan(familyRank('made-up'));
+ });
+
+ it('rings a model beside the objects it classifies, not out with the documents', () => {
+ // `class` is read with who and what: a T-72B3 belongs next to the tanks that
+ // are one, not out past the material that shows them.
+ expect(familyRank('class')).toBeLessThan(familyRank('collected'));
+ expect(familyRank('asset')).toBeLessThan(familyRank('class'));
+ });
+});
+
+describe('hop layout', () => {
+ const hood = [
+ { id: 'root', family: 'actor', degree: 4, label: 'Root', hop: 0 },
+ { id: 'n1', family: 'organization', degree: 2, label: 'One', hop: 1 },
+ { id: 'n2', family: 'actor', degree: 1, label: 'Two', hop: 1 },
+ { id: 'far', family: 'place', degree: 1, label: 'Far', hop: 2 },
+ ];
+
+ it('gives distance from the root the horizontal axis', () => {
+ const placed = positionsById(arrangeHops(hood));
+ expect(placed.get('root').x).toBeLessThan(placed.get('n1').x);
+ expect(placed.get('n1').x).toBeLessThan(placed.get('far').x);
+ });
+
+ it('puts one hop in one column', () => {
+ const placed = positionsById(arrangeHops(hood));
+ expect(placed.get('n1').x).toBe(placed.get('n2').x);
+ expect(placed.get('n1').y).not.toBe(placed.get('n2').y);
+ });
+
+ it('centres a column on the axis', () => {
+ const placed = arrangeHops(hood).filter((n) => n.hop === 1);
+ const mid = placed.reduce((sum, n) => sum + n.y, 0) / placed.length;
+ expect(mid).toBeCloseTo(0, 10);
+ });
+
+ it('is reproducible like the rings are', () => {
+ expect(arrangeHops(hood)).toEqual(arrangeHops([...hood].reverse()));
+ });
+
+ it('treats a node with no hop as the root column', () => {
+ expect(arrangeHops([node('a', 'actor')])[0].x).toBe(0);
+ });
+});
+
+describe('cluster layout', () => {
+ /** A dumbbell: two triangles joined by one edge, plus a node nothing touches. */
+ const dumbbell = {
+ nodes: [
+ node('a1', 'actor', 3),
+ node('a2', 'actor', 2),
+ node('a3', 'actor', 2),
+ node('b1', 'place', 3),
+ node('b2', 'place', 2),
+ node('b3', 'place', 2),
+ node('lonely', 'document', 0),
+ ],
+ links: [
+ { id: 'l1', from: 'a1', to: 'a2' },
+ { id: 'l2', from: 'a2', to: 'a3' },
+ { id: 'l3', from: 'a3', to: 'a1' },
+ { id: 'l4', from: 'b1', to: 'b2' },
+ { id: 'l5', from: 'b2', to: 'b3' },
+ { id: 'l6', from: 'b3', to: 'b1' },
+ { id: 'bridge', from: 'a1', to: 'b1' },
+ ],
+ };
+
+ const spread = (placed) => {
+ const at = positionsById(placed);
+ return (from, to) => Math.hypot(at.get(from).x - at.get(to).x, at.get(from).y - at.get(to).y);
+ };
+
+ it('draws the same picture for the same payload, twice over', () => {
+ // The whole reason a simulation is allowed here: fixed seed, fixed pass count,
+ // no clock and no random number, so the screenshot in a report is reproducible.
+ expect(arrangeClusters(dumbbell.nodes, dumbbell.links)).toEqual(
+ arrangeClusters(dumbbell.nodes, dumbbell.links),
+ );
+ });
+
+ it('does not move a node when the server returns the set in another order', () => {
+ // Exactly, not nearly. The relaxation sums a force per node in index order and
+ // floating-point addition is not associative, so "close enough" here would mean
+ // the indices still came from the response — and a fraction of a pixel at pass
+ // one is a visible drift by pass three hundred.
+ expect(arrangeClusters([...dumbbell.nodes].reverse(), [...dumbbell.links].reverse())).toEqual(
+ arrangeClusters(dumbbell.nodes, dumbbell.links),
+ );
+ });
+
+ it('puts what is connected together and what is not apart', () => {
+ // This is the whole claim of the layout: position means connectivity. A ring
+ // seed alone put every node the same distance from every other one, which is
+ // a picture with no structure in it.
+ const gap = spread(arrangeClusters(dumbbell.nodes, dumbbell.links));
+ expect(gap('a1', 'a2')).toBeLessThan(gap('a2', 'b2'));
+ expect(gap('b1', 'b2')).toBeLessThan(gap('a3', 'b3'));
+ });
+
+ it('leaves the hubs nearer the middle than their own satellites', () => {
+ const at = positionsById(arrangeClusters(dumbbell.nodes, dumbbell.links));
+ const from = (id) => Math.hypot(at.get(id).x, at.get(id).y);
+ expect(from('a1')).toBeLessThan(from('a2'));
+ expect(from('b1')).toBeLessThan(from('b2'));
+ });
+
+ it('parks what nothing connects to instead of mixing it into the cloud', () => {
+ const at = positionsById(arrangeClusters(dumbbell.nodes, dumbbell.links));
+ expect(at.get('lonely').parked).toBe(true);
+ expect(at.get('lonely').x).toBeGreaterThan(at.get('a1').x);
+ expect(at.get('a1').parked).toBeUndefined();
+ });
+
+ it('parks a case that holds nothing but unconnected nodes', () => {
+ const placed = arrangeClusters([node('a', 'actor'), node('b', 'place')], []);
+ expect(placed.every((seat) => seat.parked)).toBe(true);
+ expect(placed).toHaveLength(2);
+ });
+
+ it('places every node it was given, links or not', () => {
+ const placed = arrangeClusters(dumbbell.nodes, dumbbell.links);
+ expect(placed.map((seat) => seat.id).sort()).toEqual(
+ dumbbell.nodes.map((n) => n.id).sort(),
+ );
+ expect(placed.every((seat) => Number.isFinite(seat.x) && Number.isFinite(seat.y))).toBe(true);
+ });
+
+ it('ignores an edge whose end it was not given', () => {
+ const placed = arrangeClusters([node('a', 'actor', 1)], [{ id: 'l', from: 'a', to: 'gone' }]);
+ expect(placed).toHaveLength(1);
+ expect(Number.isFinite(placed[0].x)).toBe(true);
+ });
+});
+
+describe('a node the analyst placed', () => {
+ /** The dumbbell again, with one hub dropped somewhere the layout would not put it. */
+ const pinnedAt = (id, x, y, nodes) =>
+ nodes.map((entry) => (entry.id === id ? { ...entry, pin: [x, y] } : entry));
+
+ const dumbbell = {
+ nodes: [
+ node('a1', 'actor', 3),
+ node('a2', 'actor', 2),
+ node('a3', 'actor', 2),
+ node('b1', 'place', 3),
+ node('b2', 'place', 2),
+ node('b3', 'place', 2),
+ node('lonely', 'document', 0),
+ ],
+ links: [
+ { id: 'l1', from: 'a1', to: 'a2' },
+ { id: 'l2', from: 'a2', to: 'a3' },
+ { id: 'l3', from: 'a3', to: 'a1' },
+ { id: 'l4', from: 'b1', to: 'b2' },
+ { id: 'l5', from: 'b2', to: 'b3' },
+ { id: 'l6', from: 'b3', to: 'b1' },
+ { id: 'bridge', from: 'a1', to: 'b1' },
+ ],
+ };
+
+ it('stays exactly where it was put, not approximately', () => {
+ // An anchor that drifted by a few pixels would make every drag feel broken.
+ const nodes = pinnedAt('a1', -900, 400, dumbbell.nodes);
+ const at = positionsById(arrangeClusters(nodes, dumbbell.links));
+ expect(at.get('a1').x).toBe(-900);
+ expect(at.get('a1').y).toBe(400);
+ expect(at.get('a1').pinned).toBe(true);
+ });
+
+ it('reads a drag that has not reached the server yet, and prefers it', () => {
+ // The local map is the more recent statement of the same thing.
+ const nodes = pinnedAt('a1', -900, 400, dumbbell.nodes);
+ const at = positionsById(
+ arrangeClusters(nodes, dumbbell.links, new Map([['a1', { x: 50, y: 60 }]])),
+ );
+ expect([at.get('a1').x, at.get('a1').y]).toEqual([50, 60]);
+ });
+
+ it('pulls its own neighbours over to it instead of leaving them behind', () => {
+ // The point of an anchor: it still pushes and pulls, so the cluster follows the
+ // node that was moved rather than staying where the relaxation had put it.
+ const loose = positionsById(arrangeClusters(dumbbell.nodes, dumbbell.links));
+ const nodes = pinnedAt('a1', -2000, 0, dumbbell.nodes);
+ const anchored = positionsById(arrangeClusters(nodes, dumbbell.links));
+ expect(anchored.get('a2').x).toBeLessThan(loose.get('a2').x);
+ expect(anchored.get('a3').x).toBeLessThan(loose.get('a3').x);
+ });
+
+ it('leaves a node nobody moved to the layout', () => {
+ const nodes = pinnedAt('a1', -900, 400, dumbbell.nodes);
+ expect(positionsById(arrangeClusters(nodes, dumbbell.links)).get('a2').pinned)
+ .toBeUndefined();
+ });
+
+ it('draws the same picture for the same payload and the same pins', () => {
+ const nodes = pinnedAt('b1', 300, -150, dumbbell.nodes);
+ expect(arrangeClusters(nodes, dumbbell.links)).toEqual(
+ arrangeClusters(nodes, dumbbell.links),
+ );
+ });
+
+ it('keeps a hand-placed node out of the parked column, whatever its degree', () => {
+ // Somebody chose where it goes. The park is for what nothing has been decided
+ // about, and a caption saying "nothing connects to these" over a node the
+ // analyst deliberately placed would be a lie about their own work.
+ const nodes = pinnedAt('lonely', 88, 99, dumbbell.nodes);
+ const at = positionsById(arrangeClusters(nodes, dumbbell.links));
+ expect([at.get('lonely').x, at.get('lonely').y]).toEqual([88, 99]);
+ expect(at.get('lonely').parked).toBeUndefined();
+ });
+
+ it('pulls new arrivals towards the arrangement, not back to the origin', () => {
+ // An analyst who laid the case out away from the centre must not watch every
+ // node that arrives afterwards appear where they moved away from.
+ const far = [
+ { ...node('hub', 'actor', 2), pin: [4000, 4000] },
+ { ...node('other', 'actor', 1), pin: [4200, 4000] },
+ node('fresh', 'actor', 1),
+ ];
+ const at = positionsById(
+ arrangeClusters(far, [
+ { id: 'l1', from: 'hub', to: 'fresh' },
+ { id: 'l2', from: 'hub', to: 'other' },
+ ]),
+ );
+ expect(at.get('fresh').x).toBeGreaterThan(2000);
+ expect(at.get('fresh').y).toBeGreaterThan(2000);
+ });
+
+ it('seats an arrival beside the pinned neighbour it is attached to', () => {
+ const nodes = [
+ { ...node('anchor', 'actor', 1), pin: [1000, 0] },
+ node('arrival', 'document', 1),
+ ];
+ const at = positionsById(
+ arrangeClusters(nodes, [{ id: 'l', from: 'anchor', to: 'arrival' }]),
+ );
+ const gap = Math.hypot(at.get('arrival').x - 1000, at.get('arrival').y);
+ expect(gap).toBeLessThan(400);
+ });
+
+ it('survives a pin that arrived as nonsense', () => {
+ // A coordinate is bounded at the API, but a doctored case.db or a half-written
+ // payload must draw rather than throw: an unusable pin is no pin.
+ const nodes = [
+ { ...node('a', 'actor', 1), pin: [Number.NaN, 3] },
+ { ...node('b', 'actor', 1), pin: 'somewhere' },
+ ];
+ const placed = arrangeClusters(nodes, [{ id: 'l', from: 'a', to: 'b' }]);
+ expect(placed.every((seat) => Number.isFinite(seat.x) && Number.isFinite(seat.y))).toBe(
+ true,
+ );
+ expect(placed.every((seat) => seat.pinned === undefined)).toBe(true);
+ });
+
+ it('never anchors a neighbourhood, where distance from the root owns the axis', () => {
+ const nodes = [{ ...node('a', 'actor', 1), hop: 1, pin: [500, 500] }];
+ expect(arrange(nodes, 'hops', [])).toEqual(arrangeHops(nodes));
+ });
+});
+
+describe('a node the drawing already held', () => {
+ const dumbbell = {
+ nodes: [
+ node('a1', 'actor', 3),
+ node('a2', 'actor', 2),
+ node('a3', 'actor', 2),
+ node('b1', 'place', 3),
+ node('b2', 'place', 2),
+ node('b3', 'place', 2),
+ node('lonely', 'document', 0),
+ ],
+ links: [
+ { id: 'l1', from: 'a1', to: 'a2' },
+ { id: 'l2', from: 'a2', to: 'a3' },
+ { id: 'l3', from: 'a3', to: 'a1' },
+ { id: 'l4', from: 'b1', to: 'b2' },
+ { id: 'l5', from: 'b2', to: 'b3' },
+ { id: 'l6', from: 'b3', to: 'b1' },
+ { id: 'bridge', from: 'a1', to: 'b1' },
+ ],
+ };
+
+ /** What the client keeps between two reads of the same question: the cluster only. */
+ const settle = (placed) =>
+ new Map(
+ placed.filter((seat) => !seat.parked).map((seat) => [seat.id, { x: seat.x, y: seat.y }]),
+ );
+
+ it('does not move at all when the same question is drawn again', () => {
+ // The promise the whole step rests on, and it has to be exact: a node that
+ // drifted two pixels every time something arrived would make a large case
+ // unreadable by the tenth expansion.
+ const first = arrangeClusters(dumbbell.nodes, dumbbell.links);
+ const again = arrangeClusters(dumbbell.nodes, dumbbell.links, new Map(), settle(first));
+ expect(again).toEqual(first);
+ });
+
+ it('places the arrival and nothing else', () => {
+ // Opening one node into a drawing costs one placement. Everything on screen is a
+ // fixed point, so the case the analyst was reading is the case they get back.
+ const before = arrangeClusters(dumbbell.nodes, dumbbell.links);
+ const grown = arrangeClusters(
+ [...dumbbell.nodes, node('fresh', 'document', 1)],
+ [...dumbbell.links, { id: 'l7', from: 'a1', to: 'fresh' }],
+ new Map(),
+ settle(before),
+ );
+ const was = positionsById(before);
+ const now = positionsById(grown);
+ for (const seat of before) {
+ if (seat.parked) continue;
+ expect([now.get(seat.id).x, now.get(seat.id).y]).toEqual([seat.x, seat.y]);
+ }
+ // And the arrival lands beside the neighbour that asked for it, rather than on
+ // its family ring half a canvas away.
+ const gap = Math.hypot(
+ now.get('fresh').x - was.get('a1').x,
+ now.get('fresh').y - was.get('a1').y,
+ );
+ expect(gap).toBeLessThan(400);
+ });
+
+ it('is not marked as one the analyst placed', () => {
+ // The pin mark offers "let it go", and there is nothing to let go of: nobody
+ // chose this spot, the drawing simply already had it.
+ const first = arrangeClusters(dumbbell.nodes, dumbbell.links);
+ const again = arrangeClusters(dumbbell.nodes, dumbbell.links, new Map(), settle(first));
+ expect(again.every((seat) => seat.pinned === undefined)).toBe(true);
+ });
+
+ it('gives way to a hand placed on the same node', () => {
+ // The two disagree only just after a drag, and the drag is the more recent
+ // statement of the same thing.
+ const first = arrangeClusters(dumbbell.nodes, dumbbell.links);
+ const at = positionsById(
+ arrangeClusters(
+ dumbbell.nodes,
+ dumbbell.links,
+ new Map([['a1', { x: 700, y: -400 }]]),
+ settle(first),
+ ),
+ );
+ expect([at.get('a1').x, at.get('a1').y]).toEqual([700, -400]);
+ expect(at.get('a1').pinned).toBe(true);
+ });
+
+ it('hands one node back to the layout when its spot is forgotten', () => {
+ // What "let it go" does: the node is the one thing the relaxation still owns, so
+ // it is placed against a case that stays where it is.
+ const first = arrangeClusters(dumbbell.nodes, dumbbell.links);
+ const kept = settle(first);
+ kept.delete('a2');
+ const at = positionsById(arrangeClusters(dumbbell.nodes, dumbbell.links, new Map(), kept));
+ const was = positionsById(first);
+ expect([at.get('a1').x, at.get('a1').y]).toEqual([was.get('a1').x, was.get('a1').y]);
+ expect(Number.isFinite(at.get('a2').x)).toBe(true);
+ });
+
+ it('parks an unconnected node wherever the park now is', () => {
+ // The park is placed against the cluster's edge rather than against the case, so
+ // it follows the drawing as the drawing grows. A spot remembered beside a cluster
+ // that has since moved would strand it in the middle of the picture.
+ const first = arrangeClusters(dumbbell.nodes, dumbbell.links);
+ const kept = settle(first);
+ kept.set('lonely', { x: -5000, y: -5000 });
+ const at = positionsById(arrangeClusters(dumbbell.nodes, dumbbell.links, new Map(), kept));
+ expect(at.get('lonely').parked).toBe(true);
+ expect(at.get('lonely').x).toBeGreaterThan(at.get('a1').x);
+ });
+
+ it('survives a remembered spot that arrived as nonsense', () => {
+ const at = positionsById(
+ arrangeClusters(
+ dumbbell.nodes,
+ dumbbell.links,
+ new Map(),
+ new Map([
+ ['a1', { x: Number.NaN, y: 3 }],
+ ['a2', { x: 10 }],
+ ]),
+ ),
+ );
+ expect(Number.isFinite(at.get('a1').x)).toBe(true);
+ expect(Number.isFinite(at.get('a2').y)).toBe(true);
+ });
+
+ it('draws the same picture for the same payload and the same memory', () => {
+ const first = arrangeClusters(dumbbell.nodes, dumbbell.links);
+ const kept = settle(first);
+ kept.delete('b2');
+ expect(arrangeClusters(dumbbell.nodes, dumbbell.links, new Map(), kept)).toEqual(
+ arrangeClusters(dumbbell.nodes, dumbbell.links, new Map(), kept),
+ );
+ });
+});
+
+describe('arrange', () => {
+ it('dispatches on the mode', () => {
+ const nodes = [{ id: 'a', family: 'actor', degree: 1, label: 'A', hop: 1 }];
+ const links = [{ id: 'l', from: 'a', to: 'a' }];
+ expect(arrange(nodes, 'hops', links)).toEqual(arrangeHops(nodes));
+ expect(arrange(nodes, 'rings', links)).toEqual(arrangeClusters(nodes, links));
+ });
+
+ it('carries what the drawing already held through to the cluster', () => {
+ const nodes = [node('a', 'actor', 1), node('b', 'place', 1)];
+ const links = [{ id: 'l', from: 'a', to: 'b' }];
+ const kept = new Map([['a', { x: 120, y: -60 }]]);
+ expect(arrange(nodes, 'rings', links, new Map(), kept)).toEqual(
+ arrangeClusters(nodes, links, new Map(), kept),
+ );
+ // A neighbourhood gives its horizontal axis to distance from the root, so a
+ // coordinate stated against the cluster would fight the one thing it shows.
+ expect(arrange(nodes, 'hops', links, new Map(), kept)).toEqual(arrangeHops(nodes));
+ });
+});
+
+describe('fitting the viewport', () => {
+ it('survives an empty case without dividing by zero', () => {
+ const view = fit([], 800, 600);
+ expect(Number.isFinite(view.scale)).toBe(true);
+ expect(Number.isFinite(view.x)).toBe(true);
+ });
+
+ it('never blows a two-node case up past its own size', () => {
+ expect(fit([{ x: 0, y: 0 }, { x: 10, y: 0 }], 900, 700).scale).toBeLessThanOrEqual(1);
+ });
+
+ it('shrinks a placement that overflows', () => {
+ const wide = [{ x: -4000, y: 0 }, { x: 4000, y: 0 }];
+ expect(fit(wide, 800, 600).scale).toBeLessThan(1);
+ });
+
+ it('centres what it fits', () => {
+ const view = fit([{ x: -100, y: -50 }, { x: 100, y: 50 }], 800, 600);
+ expect(view.x).toBeCloseTo(400, 6);
+ expect(view.y).toBeCloseTo(300, 6);
+ });
+
+ it('reports a unit box for nothing placed', () => {
+ expect(extent([])).toEqual({ minX: 0, minY: 0, maxX: 1, maxY: 1 });
+ });
+});
+
+describe('edges', () => {
+ const chain = ['derived-from', 'depends-on'];
+
+ it('drops an edge whose end was not placed', () => {
+ // The server returns a closed set; a dangling edge means the two disagree,
+ // and a line to the origin would be a drawing of nothing.
+ const positions = positionsById([{ id: 'a', x: 0, y: 0 }]);
+ const links = [{ from: 'a', to: 'gone', type: 'owns' }];
+ expect(drawableLinks(links, positions)).toEqual([]);
+ });
+
+ it('keeps an edge with both ends placed', () => {
+ const positions = positionsById([{ id: 'a', x: 0, y: 0 }, { id: 'b', x: 1, y: 1 }]);
+ const links = [{ from: 'a', to: 'b', type: 'owns' }];
+ expect(drawableLinks(links, positions)).toHaveLength(1);
+ });
+
+ it('drops an edge onto its own node, which has no line to draw', () => {
+ const positions = positionsById([{ id: 'a', x: 0, y: 0 }]);
+ expect(drawableLinks([{ from: 'a', to: 'a', type: 'owns' }], positions)).toEqual([]);
+ });
+
+ it('carries its meaning in the stroke, not the colour', () => {
+ // A graph that reaches a report gets printed, and a printed graph is grey.
+ const derivation = edgeStyle({ type: 'derived-from' }, chain);
+ const relation = edgeStyle({ type: 'owns' }, chain);
+ const mention = edgeStyle({ type: 'mentions' }, chain);
+ expect(derivation.dash).toEqual([]);
+ expect(relation.dash.length).toBeGreaterThan(0);
+ expect(mention.dash).not.toEqual(relation.dash);
+ });
+
+ it('draws a proposal differently from a stated edge', () => {
+ const suggested = edgeStyle(
+ { type: 'located-at', provenance: { status: 'suggested' } },
+ chain,
+ );
+ const stated = edgeStyle(
+ { type: 'located-at', provenance: { status: 'confirmed' } },
+ chain,
+ );
+ expect(suggested.dash).not.toEqual(stated.dash);
+ expect(edgeKind({ type: 'derived-from', provenance: { status: 'suggested' } }, chain)).toBe(
+ 'proposed',
+ );
+ });
+
+ it('draws an edge that stands for several as one of its own', () => {
+ // A folded edge is not a row: it cannot be confirmed or removed, and it says more
+ // than its verb. Drawn like a stated relation it would read as one.
+ const folded = edgeStyle(
+ { type: 'cites', folded: { sources: 3, via: ['bookmark'], accounts: 1 } },
+ chain,
+ );
+ expect(folded.kind).toBe('folded');
+ expect(folded.width).toBeGreaterThan(edgeStyle({ type: 'cites' }, chain).width);
+ // A proposal anywhere along the path still outranks it: the fold is only as
+ // confirmed as its weakest part, and that is what the dash says.
+ expect(
+ edgeKind({ type: 'cites', folded: {}, provenance: { status: 'suggested' } }, chain),
+ ).toBe('proposed');
+ });
+
+ it('draws what stands against a statement apart from what states it', () => {
+ // A statement cluster has to show its arguments before any label is read: an
+ // ordinary relation and a contradiction saying the same thing in the same dash
+ // is the picture hiding the one finding a reader is scanning for.
+ const against = edgeStyle({ type: 'contradicts' }, chain);
+ const stated = edgeStyle({ type: 'owns' }, chain);
+ expect(against.kind).toBe('contradiction');
+ expect(against.dash).not.toEqual(stated.dash);
+ expect(against.width).toBeGreaterThan(stated.width);
+ // Patterns, not hues: the families own the palette and a printed report is grey.
+ expect(EDGE_KINDS.map((entry) => entry.dash.join())).toHaveLength(
+ new Set(EDGE_KINDS.map((entry) => `${entry.dash.join()}|${entry.width}`)).size,
+ );
+ // A proposal still outranks it, the rule every other verb follows.
+ expect(
+ edgeKind({ type: 'contradicts', provenance: { status: 'suggested' } }, chain),
+ ).toBe('proposed');
+ });
+
+ it('draws a ruled-out relation apart from one nobody has assessed', () => {
+ // Eliminating a candidate is a finding the case keeps, not a deletion: twelve are
+ // checked and eleven ruled out. Drawn like any other stated relation, those eleven
+ // read as live hypotheses to anyone glancing at the picture.
+ const out = edgeStyle({ type: 'owns', confidence: -1 }, chain);
+ const stated = edgeStyle({ type: 'owns' }, chain);
+ expect(out.kind).toBe('refuted');
+ expect(out.dash).not.toEqual(stated.dash);
+ expect(out.label).toBe('ruled out');
+ });
+
+ it('gives a stroke to the verdict and not to the other three levels', () => {
+ // A verdict is not a nuance. *Probable* against *possible* is read one edge at a
+ // time in the panel; four more dash patterns would put "what kind of edge is this"
+ // and "how sure of it" on one channel, which is the mixture the three assessments
+ // are kept apart to prevent (ONTOLOGY §3).
+ for (const level of [3, 2, 1, null]) {
+ expect(edgeKind({ type: 'owns', confidence: level }, chain)).toBe('stated');
+ }
+ });
+
+ it('lets every other reading of an edge outrank the verdict', () => {
+ // A rating only ever reaches an ordinary stated relation — the API refuses one on
+ // a derivation, a mention and a claim connector — so nothing here is a contest.
+ // What is: an unreviewed edge is unreviewed first, and a fold is not a row at all.
+ expect(
+ edgeKind({ type: 'owns', confidence: -1, provenance: { status: 'suggested' } }, chain),
+ ).toBe('proposed');
+ expect(edgeKind({ type: 'cites', confidence: -1, folded: {} }, chain)).toBe('folded');
+ expect(edgeKind({ type: 'derived-from', confidence: -1 }, chain)).toBe('lineage');
+ });
+
+ it('gives the legend and the stroke one table to read, so a dash is explained', () => {
+ // An unexplained dash pattern is decoration: nothing tells the analyst that
+ // fine dots mean a mention.
+ for (const entry of EDGE_KINDS) expect(entry.label).toBeTruthy();
+ const kinds = EDGE_KINDS.map((entry) => entry.kind);
+ expect(kinds).toContain(edgeKind({ type: 'owns' }, chain));
+ expect(kinds).toContain(edgeKind({ type: 'mentions' }, chain));
+ expect(edgeStyle({ type: 'owns' }, chain).label).toBe('stated relation');
+ });
+
+ it('leaves the word “fold” to the act an expansion is undone by', () => {
+ // The legend read *sources, folded into one* while the toolbar, the panel and the
+ // menu all used folding for taking an expansion back out. One word cannot name two
+ // acts in the same picture, so the edge takes the panel's own wording.
+ const label = edgeStyle(
+ { type: 'cites', folded: { sources: 3, via: ['bookmark'], accounts: 1 } },
+ chain,
+ ).label;
+ expect(label).toBe('sources, drawn as one edge');
+ for (const entry of EDGE_KINDS) expect(entry.label).not.toMatch(/fold/i);
+ });
+
+ it('separates two edges between the same pair, in either direction', () => {
+ // Drawn straight they land on top of each other, and the picture says "one
+ // link" where the case says two.
+ const bends = parallelBends([
+ { id: 'x', from: 'a', to: 'b' },
+ { id: 'y', from: 'b', to: 'a' },
+ ]);
+ expect(bends.get('x')).toBe(-bends.get('y'));
+ expect(bends.get('x')).not.toBe(0);
+ });
+
+ it('leaves a lone edge straight', () => {
+ expect(parallelBends([{ id: 'x', from: 'a', to: 'b' }]).get('x')).toBe(0);
+ });
+
+ it('cuts an edge back to the rim of both nodes, leaving room for the head', () => {
+ // A head buried under the target circle points at nothing.
+ const points = edgePoints({ x: 0, y: 0 }, { x: 200, y: 0 }, 20, 20);
+ expect(points).toHaveLength(4);
+ expect(points[0]).toBeGreaterThan(20);
+ expect(points[2]).toBeLessThan(180);
+ });
+
+ it('writes a verb beside the line rather than through its own dashes', () => {
+ const points = edgePoints({ x: 0, y: 0 }, { x: 200, y: 0 }, 10, 10);
+ const on = edgeMidpoint(points);
+ const beside = edgeMidpoint(points, 12);
+ expect(beside.x).toBeCloseTo(on.x, 6);
+ expect(Math.abs(beside.y - on.y)).toBeCloseTo(12, 6);
+ });
+
+ it('lifts two parallel edges apart instead of stacking their verbs', () => {
+ // The bend already separates the lines; lifting both the same way would put
+ // the two verbs back on top of each other.
+ const bends = parallelBends([
+ { id: 'x', from: 'a', to: 'b' },
+ { id: 'y', from: 'b', to: 'a' },
+ ]);
+ const one = edgeMidpoint(
+ edgePoints({ x: 0, y: 0 }, { x: 200, y: 0 }, 10, 10, bends.get('x')),
+ 12,
+ );
+ const other = edgeMidpoint(
+ edgePoints({ x: 0, y: 0 }, { x: 200, y: 0 }, 10, 10, bends.get('y')),
+ 12,
+ );
+ const apart = Math.abs(one.y - other.y);
+ expect(apart).toBeGreaterThan(2 * Math.abs(bends.get('x')));
+ });
+
+ it('bows a bent edge off the straight line and writes the verb on the bow', () => {
+ const straight = edgePoints({ x: 0, y: 0 }, { x: 200, y: 0 }, 10, 10);
+ const bent = edgePoints({ x: 0, y: 0 }, { x: 200, y: 0 }, 10, 10, 30);
+ expect(bent).toHaveLength(6);
+ expect(Math.abs(edgeMidpoint(bent).y)).toBeCloseTo(30, 6);
+ // The midpoint of the line as drawn, which is the trimmed segment rather than
+ // the span between the two centres: that is where the verb has to sit.
+ expect(edgeMidpoint(straight).y).toBeCloseTo(0, 6);
+ expect(edgeMidpoint(straight).x).toBeCloseTo((straight[0] + straight[2]) / 2, 6);
+ expect(edgeMidpoint(straight).x).toBeGreaterThan(90);
+ });
+});
+
+describe('the card a node becomes close up', () => {
+ it('is measured in screen pixels, which is what lets it fit at all', () => {
+ // In canvas units a card this wide would overlap its neighbours at every zoom,
+ // since the placement only spaces nodes 130 apart.
+ expect(CARD.w).toBeGreaterThan(130);
+ expect(CARD_SCALE).toBeGreaterThan(1);
+ });
+
+ it('stops an arrow at the side of the box rather than under it', () => {
+ const wide = boxRadius(80, 25, 1, 0);
+ const tall = boxRadius(80, 25, 0, 1);
+ expect(wide).toBeCloseTo(80, 6);
+ expect(tall).toBeCloseTo(25, 6);
+ // A ray out of a corner leaves through whichever side it reaches first.
+ expect(boxRadius(80, 25, 1, 1)).toBeCloseTo(25 * Math.SQRT2, 6);
+ });
+
+ it('fills the art column from the middle of the picture', () => {
+ // A wide capture keeps its full height and gives up the sides; a tall photo
+ // keeps its full width. Either way the column is filled and nothing is stretched.
+ const wide = cropToFill(640, 360, 1);
+ expect(wide.height).toBeCloseTo(360, 6);
+ expect(wide.width).toBeCloseTo(360, 6);
+ expect(wide.x).toBeCloseTo(140, 6);
+ expect(wide.y).toBeCloseTo(0, 6);
+ const tall = cropToFill(360, 640, 1);
+ expect(tall.width).toBeCloseTo(360, 6);
+ expect(tall.y).toBeCloseTo(140, 6);
+ const square = cropToFill(100, 100, 1);
+ expect(square).toMatchObject({ x: 0, y: 0, width: 100, height: 100 });
+ });
+
+ it('crops to the column it is given rather than to a square', () => {
+ const half = cropToFill(400, 400, 2);
+ expect(half.width / half.height).toBeCloseTo(2, 6);
+ expect(half.width).toBeCloseTo(400, 6);
+ expect(half.y).toBeCloseTo(100, 6);
+ });
+
+ it('survives a picture whose size never arrived', () => {
+ const crop = cropToFill(undefined, 0, 1);
+ expect(Number.isFinite(crop.width)).toBe(true);
+ expect(crop.width).toBeGreaterThan(0);
+ });
+
+ it('grows with the zoom, but slower than the case spreads out', () => {
+ // The point of the growth: zooming in has to make the card bigger on screen, or
+ // close up the drawing is a handful of stamps floating between long arrows.
+ const onScreen = (zoom) => cardFactor(zoom) * zoom;
+ expect(onScreen(CARD_SCALE)).toBeCloseTo(1, 6);
+ expect(onScreen(2)).toBeGreaterThan(onScreen(CARD_SCALE));
+ expect(onScreen(3.2)).toBeGreaterThan(onScreen(2));
+ expect(onScreen(3.2)).toBeLessThanOrEqual(CARD_GROWTH);
+ // And the reason it can grow at all: between two zooms the gap between nodes
+ // widens faster than the card does, so cards that had room keep it.
+ const spread = 3.2 / CARD_SCALE;
+ expect(onScreen(3.2) / onScreen(CARD_SCALE)).toBeLessThan(spread);
+ });
+
+ it('never shrinks a card below its own size, or on a zoom that never arrived', () => {
+ expect(cardFactor(0.4) * 0.4).toBeCloseTo(1, 6);
+ expect(Number.isFinite(cardFactor(undefined))).toBe(true);
+ expect(Number.isFinite(cardFactor(0))).toBe(true);
+ });
+
+ it('gives the picture a column as tall as the card', () => {
+ // The crop assumes the column is the card's own height; the glyph sits inside
+ // that same column, which is what keeps every title on a row aligned.
+ expect(CARD.art).toBe(CARD.h);
+ expect(CARD.glyph).toBeLessThan(CARD.art);
+ expect(CARD.stripe + CARD.art + CARD.pad).toBeLessThan(CARD.w / 2);
+ });
+});
+
+describe('node drawing', () => {
+ it('grows a hub without letting it swallow the canvas', () => {
+ expect(nodeRadius(0)).toBeLessThan(nodeRadius(4));
+ expect(nodeRadius(4)).toBeLessThan(nodeRadius(40));
+ expect(nodeRadius(4000)).toBeLessThan(nodeRadius(4) * 3);
+ });
+
+ it('treats a missing degree as none rather than as NaN', () => {
+ expect(Number.isFinite(nodeRadius(undefined))).toBe(true);
+ });
+
+ it('shortens a long label and leaves a short one alone', () => {
+ expect(shortLabel('Short')).toBe('Short');
+ expect(shortLabel('x'.repeat(60))).toHaveLength(22);
+ expect(shortLabel('x'.repeat(60)).endsWith('…')).toBe(true);
+ });
+
+ it('survives a label that is not a string', () => {
+ expect(shortLabel(null)).toBe('');
+ expect(shortLabel(42)).toBe('42');
+ });
+});
+
+
+describe('what a pointer is over', () => {
+ const placed = [
+ { id: 'a', x: 0, y: 0 },
+ { id: 'b', x: 200, y: 0 },
+ ];
+ const byId = new Map([
+ ['a', { id: 'a', degree: 0 }],
+ ['b', { id: 'b', degree: 40 }],
+ ]);
+
+ it('answers with the node the point falls inside', () => {
+ expect(nodeAt(placed, byId, { x: 2, y: 2 })).toBe('a');
+ expect(nodeAt(placed, byId, { x: 200, y: 3 })).toBe('b');
+ });
+
+ it('answers with nothing over empty canvas', () => {
+ expect(nodeAt(placed, byId, { x: 100, y: 100 })).toBe(null);
+ });
+
+ it('picks the nearer of two nodes that overlap', () => {
+ // Two cards sitting on top of each other resolve to the one being pointed at,
+ // not to whichever happened to be drawn last.
+ const stacked = [
+ { id: 'a', x: 0, y: 0 },
+ { id: 'b', x: 30, y: 0 },
+ ];
+ expect(nodeAt(stacked, byId, { x: 26, y: 0 }, { carded: true })).toBe('b');
+ });
+
+ it('uses the card box once the view draws cards', () => {
+ // A point 60 units out is well past any circle and well inside a card.
+ expect(nodeAt(placed, byId, { x: 60, y: 0 })).toBe(null);
+ expect(nodeAt(placed, byId, { x: 60, y: 0 }, { carded: true })).toBe('a');
+ });
+
+ it('follows the card as it grows with the zoom', () => {
+ // The box tested here is the box on screen. A card drawn 1.7× its base size has
+ // to be clickable across all of it, or the drawing stops answering its own edges.
+ const far = { x: (CARD.w / 2) * cardFactor(3.2) - 1, y: 0 };
+ expect(nodeAt(placed, byId, far, { carded: true, scale: 3.2 })).toBe('a');
+ expect(nodeAt(placed, byId, { x: far.x + 3, y: 0 }, { carded: true, scale: 3.2 })).toBe(
+ null,
+ );
+ });
+});
+
+describe('rings around a node', () => {
+ // a — b — c — d, plus e hanging off a.
+ const chain = [
+ { from: 'a', to: 'b' },
+ { from: 'b', to: 'c' },
+ { from: 'c', to: 'd' },
+ { from: 'a', to: 'e' },
+ ];
+
+ it('holds the node itself at every reach', () => {
+ // An unconnected node focuses on itself, never on an empty set: the panel is
+ // open on it, and a highlight that excludes what it is about is a bug on screen.
+ expect([...ringsAround([], 'lonely', 1)]).toEqual(['lonely']);
+ expect(ringsAround(chain, 'a', 1).has('a')).toBe(true);
+ });
+
+ it('reaches one hop, which is what a click asks', () => {
+ expect([...ringsAround(chain, 'a', 1)].sort()).toEqual(['a', 'b', 'e']);
+ });
+
+ it('reaches two, which is the ring a click cannot show', () => {
+ expect([...ringsAround(chain, 'a', 2)].sort()).toEqual(['a', 'b', 'c', 'e']);
+ });
+
+ it('reaches three', () => {
+ expect([...ringsAround(chain, 'a', 3)].sort()).toEqual(['a', 'b', 'c', 'd', 'e']);
+ });
+
+ it('walks against the arrow as readily as along it', () => {
+ // Direction is what an edge says, not a wall. Asked what surrounds the far end
+ // of a one-way edge, a directed walk would answer "nothing".
+ expect(ringsAround([{ from: 'a', to: 'b' }], 'b', 1).has('a')).toBe(true);
+ });
+
+ it('stops at the reach asked for, on a graph that goes further', () => {
+ expect(ringsAround(chain, 'a', 1).has('c')).toBe(false);
+ expect(ringsAround(chain, 'a', 2).has('d')).toBe(false);
+ });
+
+ it('terminates on a cycle', () => {
+ const ring = [
+ { from: 'a', to: 'b' },
+ { from: 'b', to: 'c' },
+ { from: 'c', to: 'a' },
+ ];
+ expect([...ringsAround(ring, 'a', 3)].sort()).toEqual(['a', 'b', 'c']);
+ });
+
+ it('counts each node once however many edges reach it', () => {
+ const parallel = [
+ { from: 'a', to: 'b' },
+ { from: 'a', to: 'b' },
+ { from: 'b', to: 'a' },
+ ];
+ expect(ringsAround(parallel, 'a', 2).size).toBe(2);
+ });
+
+ it('reaches nothing below one hop', () => {
+ expect([...ringsAround(chain, 'a', 0)]).toEqual(['a']);
+ });
+});
+
+describe('folding a node', () => {
+ // A hub, the leaves that hang off it alone, and a case for them to hang off.
+ const hub = (leaves, extra = []) => {
+ const nodes = [node('h', 'actor', leaves + 2), node('body1', 'place'), node('body2', 'place')];
+ const links = [
+ { from: 'h', to: 'body1' },
+ { from: 'body1', to: 'body2' },
+ { from: 'body2', to: 'h' },
+ ];
+ for (let i = 0; i < leaves; i += 1) {
+ nodes.push(node(`leaf${i}`, 'collected', 1));
+ links.push({ from: 'h', to: `leaf${i}` });
+ }
+ return { nodes: [...nodes, ...(extra.nodes ?? [])], links: [...links, ...(extra.links ?? [])] };
+ };
+
+ it('takes the leaves that hung off it alone', () => {
+ const { nodes, links } = hub(4);
+ const { hidden } = foldAway(['h'], nodes, links);
+ expect([...hidden].sort()).toEqual(['leaf0', 'leaf1', 'leaf2', 'leaf3']);
+ });
+
+ it('leaves the node itself on screen, carrying what it took', () => {
+ const { nodes, links } = hub(4);
+ const { hidden, by } = foldAway(['h'], nodes, links);
+ expect(hidden.has('h')).toBe(false);
+ expect(by.get('h')).toBe(4);
+ });
+
+ it('keeps a leaf something else also holds', () => {
+ // The one that surprises, and the one that makes the rule trustworthy: a capture
+ // two accounts both posted is in the drawing for a second reason.
+ const { nodes, links } = hub(3);
+ links.push({ from: 'body1', to: 'leaf0' });
+ const { hidden } = foldAway(['h'], nodes, links);
+ expect(hidden.has('leaf0')).toBe(false);
+ expect([...hidden].sort()).toEqual(['leaf1', 'leaf2']);
+ });
+
+ it('follows a chain out to its end', () => {
+ // account -> post -> capture, where neither the post nor the capture is held by
+ // anything else. Stopping at the post would leave the capture floating.
+ const { nodes, links } = hub(0);
+ nodes.push(node('post', 'document', 2), node('shot', 'collected', 1));
+ links.push({ from: 'h', to: 'post' }, { from: 'post', to: 'shot' });
+ const { hidden } = foldAway(['h'], nodes, links);
+ expect([...hidden].sort()).toEqual(['post', 'shot']);
+ });
+
+ it('takes a small ring hanging off it, not only a tree', () => {
+ const { nodes, links } = hub(0);
+ nodes.push(node('p', 'document', 2), node('q', 'place', 2));
+ links.push({ from: 'h', to: 'p' }, { from: 'p', to: 'q' }, { from: 'q', to: 'h' });
+ const { hidden } = foldAway(['h'], nodes, links);
+ expect([...hidden].sort()).toEqual(['p', 'q']);
+ });
+
+ it('never takes the drawing away with it', () => {
+ // The trapdoor this rule exists to close: the rest of the case is, technically,
+ // hanging off any node you fold. The biggest piece with a shape of its own stays.
+ const { nodes, links } = hub(3);
+ const { hidden } = foldAway(['h'], nodes, links);
+ expect(hidden.has('body1')).toBe(false);
+ expect(hidden.has('body2')).toBe(false);
+ });
+
+ it('folds nothing when the node holds nothing up', () => {
+ const { nodes, links } = hub(0);
+ expect(foldAway(['h'], nodes, links).hidden.size).toBe(0);
+ expect(foldableCount('h', nodes, links)).toBe(0);
+ });
+
+ it('empties a star down to its hub, since every leaf is clutter', () => {
+ // No piece here has a shape of its own, so none of them is the drawing. Sparing
+ // one arbitrary leaf out of eleven would read as a bug.
+ const nodes = [node('h', 'actor', 3)];
+ const links = [];
+ for (const id of ['a', 'b', 'c']) {
+ nodes.push(node(id, 'collected', 1));
+ links.push({ from: 'h', to: id });
+ }
+ expect([...foldAway(['h'], nodes, links).hidden].sort()).toEqual(['a', 'b', 'c']);
+ });
+
+ it('spares a piece holding a node the analyst placed by hand', () => {
+ const { nodes, links } = hub(3);
+ const { hidden } = foldAway(['h'], nodes, links, new Set(['leaf1']));
+ expect(hidden.has('leaf1')).toBe(false);
+ expect([...hidden].sort()).toEqual(['leaf0', 'leaf2']);
+ });
+
+ it('never reaches a part of the case it does not touch', () => {
+ // A second cluster, joined to nothing. Folding here says nothing about it.
+ const { nodes, links } = hub(2);
+ nodes.push(node('far', 'actor', 0));
+ const { hidden } = foldAway(['h'], nodes, links);
+ expect(hidden.has('far')).toBe(false);
+ });
+
+ it('cuts no link between two nodes that both stay', () => {
+ // The guarantee, checked rather than asserted. What leaves is joined to the
+ // drawing through the folded node and nothing else, so every link that ends on
+ // something still on screen ends on the node that was folded.
+ const { nodes, links } = hub(3);
+ links.push({ from: 'body1', to: 'leaf0' });
+ const { hidden } = foldAway(['h'], nodes, links);
+ for (const link of links) {
+ for (const [gone, stays] of [
+ [link.from, link.to],
+ [link.to, link.from],
+ ]) {
+ if (hidden.has(gone) && !hidden.has(stays)) expect(stays).toBe('h');
+ }
+ }
+ });
+
+ it('adds two folds up without counting a shared piece twice', () => {
+ const { nodes, links } = hub(2);
+ nodes.push(node('h2', 'actor', 2), node('shared', 'collected', 2));
+ links.push({ from: 'h2', to: 'body1' }, { from: 'h', to: 'shared' }, { from: 'h2', to: 'shared' });
+ const { hidden, by } = foldAway(['h', 'h2'], nodes, links);
+ expect(hidden.has('shared')).toBe(true);
+ expect([...by.values()].reduce((sum, n) => sum + n, 0)).toBe(hidden.size);
+ });
+
+ it('folds the same drawing the same way whatever order it arrives in', () => {
+ const { nodes, links } = hub(4);
+ const first = foldAway(['h'], nodes, links).hidden;
+ const again = foldAway(['h'], [...nodes].reverse(), [...links].reverse()).hidden;
+ expect([...first].sort()).toEqual([...again].sort());
+ });
+
+ it('ignores a fold on a node the drawing no longer holds', () => {
+ const { nodes, links } = hub(2);
+ expect(foldAway(['gone'], nodes, links).hidden.size).toBe(0);
+ });
+
+ it('counts a pair joined twice as one holder', () => {
+ // Two verbs between the same pair are one holder said twice, so a leaf joined to
+ // its hub by two edges is still a leaf.
+ const nodes = [node('h', 'actor', 4), node('body1', 'place'), node('body2', 'place'), node('leaf', 'collected', 2)];
+ const links = [
+ { from: 'h', to: 'body1' },
+ { from: 'body1', to: 'body2' },
+ { from: 'body2', to: 'h' },
+ { from: 'h', to: 'leaf' },
+ { from: 'leaf', to: 'h' },
+ ];
+ expect([...foldAway(['h'], nodes, links).hidden]).toEqual(['leaf']);
+ });
+});
+
+describe('the drawing as a snapshot, for the way back', () => {
+ const at = (over = {}) => ({
+ lens: 'ground',
+ order: 'recent',
+ root: null,
+ hops: 1,
+ folder: 'field',
+ families: ['document', 'collected'],
+ kept: ['b', 'a'],
+ expanded: ['x'],
+ omitted: [],
+ collapsed: [],
+ putAway: { n2: ['z', 'y'], n1: ['q'] },
+ arrangement: [{ id: 'two', x: 3, y: 4 }, { id: 'one', x: 1, y: 2 }],
+ ...over,
+ });
+
+ it('reads the same for two states that differ only in iteration order', () => {
+ // The history compares snapshots as strings, so a set that came out the other way
+ // round would fork the timeline and record an act nobody performed.
+ expect(drawingSnapshot(at())).toBe(
+ drawingSnapshot(
+ at({
+ families: ['collected', 'document'],
+ putAway: { n1: ['q'], n2: ['y', 'z'] },
+ arrangement: [{ id: 'one', x: 1, y: 2 }, { id: 'two', x: 3, y: 4 }],
+ }),
+ ),
+ );
+ });
+
+ it('keeps the analyst\'s own lists in the order they were asked for', () => {
+ // The case echoes `keep` back in it, and these are named nodes rather than a set
+ // the drawing happens to hold.
+ expect(JSON.parse(drawingSnapshot(at())).kept).toEqual(['b', 'a']);
+ });
+
+ it('tells one reading from another', () => {
+ expect(drawingSnapshot(at())).not.toBe(drawingSnapshot(at({ lens: 'all' })));
+ expect(drawingSnapshot(at())).not.toBe(drawingSnapshot(at({ omitted: ['a'] })));
+ expect(drawingSnapshot(at())).not.toBe(
+ drawingSnapshot(at({ arrangement: [{ id: 'one', x: 9, y: 2 }, { id: 'two', x: 3, y: 4 }] })),
+ );
+ });
+
+ it('answers for a state with nothing in it', () => {
+ const bare = JSON.parse(drawingSnapshot());
+ expect(bare.lens).toBe('all');
+ expect(bare.kept).toEqual([]);
+ expect(bare.arrangement).toEqual([]);
+ });
+});
+
+describe('putting an arrangement back', () => {
+ it('places what moved and lets go of what was not pinned then', () => {
+ const now = [{ id: 'a', x: 1, y: 1 }, { id: 'b', x: 2, y: 2 }];
+ const want = [{ id: 'a', x: 5, y: 5 }];
+ expect(arrangementDiff(now, want)).toEqual({ place: [{ id: 'a', x: 5, y: 5 }], drop: ['b'] });
+ });
+
+ it('files nothing when the arrangement is already the one asked for', () => {
+ const same = [{ id: 'a', x: 1, y: 1 }];
+ expect(arrangementDiff(same, same)).toEqual({ place: [], drop: [] });
+ });
+
+ it('places a pin that is not there at all', () => {
+ expect(arrangementDiff([], [{ id: 'a', x: 1, y: 1 }])).toEqual({
+ place: [{ id: 'a', x: 1, y: 1 }],
+ drop: [],
+ });
+ });
+
+ it('never drops a pin it cannot see', () => {
+ // Both sides are read over the nodes currently drawn, so a pinned node the budget
+ // cut is in neither list and an undo cannot take an arrangement it never saw.
+ expect(arrangementDiff([], []).drop).toEqual([]);
+ });
+});
diff --git a/frontend/src/lib/markdown.js b/frontend/src/lib/markdown.js
index 87c0268..ff395a7 100644
--- a/frontend/src/lib/markdown.js
+++ b/frontend/src/lib/markdown.js
@@ -1,6 +1,8 @@
import DOMPurify from 'dompurify';
import { marked, Renderer } from 'marked';
+import { fileRelPath, fileUrl } from './fileUrl.js';
+
const ENTITY_REF = /\[\[entity:([A-Za-z0-9_-]+)\|([^\]]+)\]\]/g;
const MEDIA_REF = /\[\[media:([A-Za-z0-9_-]+)\|([^\]]+)\]\](?:\{([^}\n]+)\})?/g;
const IMAGE_ATTRS = /!\[([^\]]*)\]\((\S+?)(?:\s+["']([^"']*)["'])?\)\s*\{([^}\n]+)\}/g;
@@ -76,11 +78,6 @@ function broken(kind, label) {
return `<span class="broken-ref" title="Deleted from this case">${kind}: ${label}</span>`;
}
-function localMediaPath(href, caseId) {
- const prefix = `/files/${caseId}/`;
- return caseId && href.startsWith(prefix) ? href.slice(prefix.length) : null;
-}
-
function imageOptions(href) {
const url = new URL(href, 'https://notebook.invalid');
const attributes = url.searchParams.get(ATTR_PARAM) ?? '';
@@ -131,7 +128,7 @@ function renderer({ entities, caseId }) {
if (mediaMatch) {
const entity = byId.get(mediaMatch[1]);
if (!entity?.attrs?.path) return broken('Media unavailable', body);
- const url = `/files/${caseId}/${entity.attrs.path}`;
+ const url = fileUrl(caseId, entity.attrs.path);
return entity.attrs.kind === 'video'
? `<video controls src="${url}">${body}</video>`
: `<img src="${url}" alt="${entity.label}">`;
@@ -142,13 +139,16 @@ function renderer({ entities, caseId }) {
value.image = (token) => {
const options = imageOptions(token.href);
- const path = localMediaPath(options.href, caseId);
+ const path = fileRelPath(options.href, caseId);
if (path && !mediaByPath.has(path)) return broken('Media unavailable', token.text);
+ // Rebuilt rather than reused, so a case file whose name needs encoding
+ // resolves even in notes written before it was encoded.
+ if (path) options.href = fileUrl(caseId, path);
const mediaUrl = new URL(options.href, 'https://notebook.invalid');
if (mediaUrl.protocol === 'azimut:' && mediaUrl.hostname === 'media') {
const entity = byId.get(mediaUrl.pathname.slice(1));
if (!entity?.attrs?.path) return broken('Media unavailable', token.text);
- const url = `/files/${caseId}/${entity.attrs.path}`;
+ const url = fileUrl(caseId, entity.attrs.path);
const markup = imageMarkup({ href: url, alt: entity.label, title: token.title, ...options });
return entity.attrs.kind === 'video'
? `<video controls src="${url}" class="${markup.className}"${markup.attrs}>${token.text}</video>`
diff --git a/frontend/src/lib/mediaFilter.js b/frontend/src/lib/mediaFilter.js
index ff7ae8d..61f877b 100644
--- a/frontend/src/lib/mediaFilter.js
+++ b/frontend/src/lib/mediaFilter.js
@@ -36,6 +36,33 @@ export function isGenericImage(item) {
return item?.kind === 'image' && !isSatelliteMedia(item);
}
+/** How material the analyst brought in by hand arrives: dropped or picked off a
+ * disk, or pasted out of the clipboard. Two source types and one facet — the
+ * filter asks who brought the file in, not which gesture did it. Mirrors
+ * `_MEDIA_CATEGORY_SQL['upload']`, which the server answers the same question with. */
+const BROUGHT_IN = new Set(['upload', 'clipboard']);
+
+/** Whether the analyst put this file into the case themselves. */
+export function isBroughtIn(item) {
+ return BROUGHT_IN.has(item?.source?.type);
+}
+
+/** The tools that make a file out of material the case already holds. Mirrors
+ * `links.MADE_HERE`; the server filters on the same set, and this is the
+ * in-memory pass a case small enough for one page takes instead. */
+const MADE_HERE = new Set(['inspect']);
+
+/** Whether the case made this file rather than collected it: an extracted frame,
+ * an adjustment, a collage.
+ *
+ * Reads **how the file entered the case**, not everything true about it. Bytes
+ * imported first and later found identical to a frame keep `upload`, because that
+ * is how they arrived — which is the same reason the graph reads the origin off
+ * the index rather than off the derivation links, where both are true at once. */
+export function isMadeHere(item) {
+ return MADE_HERE.has(item?.source?.type);
+}
+
/** User-facing kind label for the Media Library card. */
export function mediaDisplayKind(item) {
return isSatelliteMedia(item) ? 'satellite' : item?.kind;
@@ -64,6 +91,7 @@ export function visibleMedia(
catMatch = null,
folderFilter = null,
gpsOnly = false,
+ collectedOnly = false,
query = '',
sort = 'newest',
direction,
@@ -76,6 +104,7 @@ export function visibleMedia(
(!catMatch || catMatch(i)) &&
(!folderFilter || i.folder === folderFilter) &&
(!gpsOnly || hasPosition(i)) &&
+ (!collectedOnly || !isMadeHere(i)) &&
matchesQuery(i, query)
),
sort,
diff --git a/frontend/src/lib/mediaFilter.test.js b/frontend/src/lib/mediaFilter.test.js
index cb68092..4309078 100644
--- a/frontend/src/lib/mediaFilter.test.js
+++ b/frontend/src/lib/mediaFilter.test.js
@@ -2,6 +2,8 @@ import { describe, it, expect } from 'vitest';
import {
hasMediaForFilters,
isGenericImage,
+ isBroughtIn,
+ isMadeHere,
isSatelliteMedia,
mediaDisplayKind,
matchesQuery,
@@ -220,3 +222,54 @@ describe('visibleMedia — position filter', () => {
expect(visibleMedia([located, bare], { gpsOnly: true, query: 'plain' })).toEqual([]);
});
});
+
+describe('what the case made, apart from what it collected', () => {
+ const frame = item({ filename: 'frame.png', source: { type: 'inspect', op: 'frame' } });
+ const collage = item({ filename: 'collage.png', source: { type: 'inspect', op: 'collage' } });
+ const upload = item({ filename: 'handed-over.jpg', source: { type: 'upload' } });
+ const capture = item({ filename: 'map.png', source: { type: 'satellite' } });
+
+ it('counts only the tools that compose case material', () => {
+ expect(isMadeHere(frame)).toBe(true);
+ expect(isMadeHere(collage)).toBe(true);
+ // Original imagery brought into the case, not made out of what it holds.
+ expect(isMadeHere(capture)).toBe(false);
+ expect(isMadeHere(upload)).toBe(false);
+ expect(isMadeHere(item())).toBe(false);
+ expect(isMadeHere(null)).toBe(false);
+ });
+
+ it('takes them out of the grid on request, and composes with the other filters', () => {
+ // The in-memory pass a case small enough for one page takes; a large case is
+ // filtered in SQL, and both read the same set.
+ expect(
+ visibleMedia([frame, upload, capture], { collectedOnly: true, sort: 'name' }).map(
+ (i) => i.filename
+ )
+ ).toEqual(['handed-over.jpg', 'map.png']);
+ expect(visibleMedia([frame, upload, capture], { collectedOnly: false }).length).toBe(3);
+ expect(visibleMedia([frame, upload], { collectedOnly: true, query: 'frame' })).toEqual([]);
+ });
+});
+
+describe('what the analyst brought in by hand', () => {
+ const dropped = item({ filename: 'dropped.png', source: { type: 'upload' } });
+ const pastedIn = item({ filename: 'Front gate.png', source: { type: 'clipboard' } });
+ const downloaded = item({ filename: 'clip.mp4', source: { type: 'download' } });
+
+ it('counts a paste and a drop as one facet', () => {
+ // Both were put there by the analyst, which is what the Imports filter asks.
+ // They stay two source types because only one of them can say where it came from.
+ expect(isBroughtIn(dropped)).toBe(true);
+ expect(isBroughtIn(pastedIn)).toBe(true);
+ expect(isBroughtIn(downloaded)).toBe(false);
+ expect(isBroughtIn(item({ source: { type: 'satellite' } }))).toBe(false);
+ expect(isBroughtIn(null)).toBe(false);
+ });
+
+ it('still reads a paste as collected rather than made here', () => {
+ // Azimut did not compose those pixels out of case material; a system screenshot
+ // tool did, outside the case.
+ expect(isMadeHere(pastedIn)).toBe(false);
+ });
+});
diff --git a/frontend/src/lib/mediaQuery.js b/frontend/src/lib/mediaQuery.js
index b54790d..4651ba7 100644
--- a/frontend/src/lib/mediaQuery.js
+++ b/frontend/src/lib/mediaQuery.js
@@ -3,7 +3,7 @@
* distinct from an unset folder. Mirrors `buildCatalogQuery` in catalog.js. */
export function buildMediaQuery(
caseId,
- { q, kind, category, folder, gps, sort, direction, limit, cursor } = {}
+ { q, kind, category, folder, gps, collectedOnly, sort, direction, limit, cursor } = {}
) {
const params = new URLSearchParams();
if (q) params.set('q', q);
@@ -11,6 +11,7 @@ export function buildMediaQuery(
if (category) params.set('category', category);
if (folder != null) params.set('folder', folder);
if (gps) params.set('gps', 'true');
+ if (collectedOnly) params.set('collected_only', 'true');
if (sort) params.set('sort', sort);
if (direction) params.set('direction', direction);
if (limit != null) params.set('limit', String(limit));
diff --git a/frontend/src/lib/mediaQuery.test.js b/frontend/src/lib/mediaQuery.test.js
index db4a686..fe6ac8b 100644
--- a/frontend/src/lib/mediaQuery.test.js
+++ b/frontend/src/lib/mediaQuery.test.js
@@ -37,3 +37,17 @@ describe('buildMediaQuery — position filter', () => {
expect(buildMediaQuery('c1', { gps: false })).toBe('/api/cases/c1/media/page');
});
});
+
+describe('buildMediaQuery — what the case collected', () => {
+ it('asks the server, because the counts and the paging are its', () => {
+ // Filtering this one in the browser would give a right-looking first page
+ // with a wrong total under it and a chooser offering rows it just hid.
+ expect(buildMediaQuery('c1', { collectedOnly: true })).toBe(
+ '/api/cases/c1/media/page?collected_only=true'
+ );
+ });
+
+ it('says nothing when it is off', () => {
+ expect(buildMediaQuery('c1', { collectedOnly: false })).toBe('/api/cases/c1/media/page');
+ });
+});
diff --git a/frontend/src/lib/naming.js b/frontend/src/lib/naming.js
index a5ba421..63014db 100644
--- a/frontend/src/lib/naming.js
+++ b/frontend/src/lib/naming.js
@@ -80,6 +80,23 @@ const SPEC_ATTR = {
draft: { dir: '.drafts/', attr: 'draft' },
};
+/** The entity attribute holding a kind's spec path: `spec`, or `draft` for posts. */
+export function specAttr(kind) {
+ return SPEC_ATTR[kind].attr;
+}
+
+/**
+ * Case-relative spec path of the item of `kind` saved under `slug` — the exact
+ * value its entity carries. Tools ask the catalog for this before deciding a
+ * saved item was deleted out from under them, so a hand-written literal goes
+ * stale the day the layout moves: sessions lived under `inspect/` and drafts
+ * under `exports/` before they were hidden, and a path that matches nothing
+ * reads as "deleted" on every save.
+ */
+export function specPath(kind, slug) {
+ return `${SPEC_ATTR[kind].dir}${slug}.json`;
+}
+
/** The filed entities of `kind`, read off a case's entity list. */
export function savedEntities(entities, kind) {
const { dir, attr } = SPEC_ATTR[kind];
diff --git a/frontend/src/lib/naming.test.js b/frontend/src/lib/naming.test.js
index 9b8111f..8378527 100644
--- a/frontend/src/lib/naming.test.js
+++ b/frontend/src/lib/naming.test.js
@@ -1,7 +1,7 @@
import { describe, it, expect } from 'vitest';
import {
MAX_SLUG, NAME_PREFIX, slugify, uniqueName, nextName, isDefaultName,
- savedEntities, savedSlugs, savedTitles, savedTitle,
+ savedEntities, savedSlugs, savedTitles, savedTitle, specAttr, specPath,
} from './naming.js';
describe('slugify — mirrors the backend api/naming.slugify', () => {
@@ -79,6 +79,25 @@ describe('saved-item case queries', () => {
{ label: 'No spec' },
];
+ it('builds the spec path a filed entity actually carries', () => {
+ // The tools look an item up by this exact string to tell whether it is still
+ // filed, so it has to name the hidden folders the case really uses — a stale
+ // `inspect/` matched nothing and warned "deleted" on every save.
+ expect(specPath('session', 'angle')).toBe('.inspect/angle.json');
+ expect(specPath('proof', 'rooftop')).toBe('proofs/.meta/rooftop.json');
+ expect(specPath('draft', 'thread')).toBe('.drafts/thread.json');
+ // and the same string the filed entities carry, so a lookup by it hits
+ for (const [kind, slug] of [['session', 'angle'], ['proof', 'rooftop'], ['draft', 'thread']]) {
+ expect(entities.some((e) => e.attrs?.[specAttr(kind)] === specPath(kind, slug))).toBe(true);
+ }
+ });
+
+ it('names the attribute each kind stores its spec under', () => {
+ expect(specAttr('session')).toBe('spec');
+ expect(specAttr('proof')).toBe('spec');
+ expect(specAttr('draft')).toBe('draft'); // posts are the odd one out
+ });
+
it('picks only the entities of the asked-for kind', () => {
expect(savedEntities(entities, 'proof').map((e) => e.label)).toEqual(['Rooftop', 'Bridge']);
expect(savedEntities(entities, 'session').map((e) => e.label)).toEqual(['Angle']);
diff --git a/frontend/src/lib/navigate.js b/frontend/src/lib/navigate.js
index 68fa484..3cfb8f8 100644
--- a/frontend/src/lib/navigate.js
+++ b/frontend/src/lib/navigate.js
@@ -4,7 +4,9 @@
* uiState; the target tool consumes it on mount. Shared so the case sidebar and
* the Details editor send an analyst to the same place.
*/
-import { uiState } from './state.svelte.js';
+import { caseState, toast, uiState } from './state.svelte.js';
+import { mediaKindOf } from './entityIcon.js';
+import { revealMediaFolder } from './reveal.js';
/**
* A number an entity actually recorded, or NaN when it recorded nothing.
@@ -26,8 +28,36 @@ export const ENTITY_TOOL = {
'inspect-session': 'inspect',
};
+/**
+ * Whether the app has to hand this one back to the desktop.
+ *
+ * Azimut displays images, video and audio, and nothing else: a PDF, a scan bundle,
+ * a spreadsheet or a plan has no viewer here and no tool to be reopened in. The
+ * browser's answer for those is a download, which quietly makes a second copy in
+ * Downloads and invites the analyst to work on the file the case no longer knows
+ * about. Showing the folder hands over the original instead.
+ */
+export function opensInFileManager(entity) {
+ return entity?.type === 'media' && mediaKindOf(entity) === 'file';
+}
+
+/** Show a file's own folder, and say so when the desktop refuses. */
+export function showInFolder(entity) {
+ const caseId = caseState.current?.id;
+ const path = entity?.attrs?.path;
+ if (!caseId || !path) return Promise.resolve();
+ return revealMediaFolder(caseId, path).catch((e) => toast(e.message, 'warn', 5000));
+}
+
/** Reopen an artifact in its tool, loading whatever spec/draft it carries. */
export function openEntity(entity) {
+ // A file the app cannot show is opened where it actually lives. This runs before
+ // the type branches below, so every surface that follows an entity — a relation
+ // row, a chain row, the sidebar — makes the same call.
+ if (opensInFileManager(entity)) {
+ void showInFolder(entity);
+ return;
+ }
if (entity.type === 'note') {
uiState.openNotebook = { noteId: entity.id };
uiState.tool = 'notebook';
@@ -98,7 +128,18 @@ export function openEntity(entity) {
return;
}
const tool = ENTITY_TOOL[entity.type];
- if (tool) uiState.tool = tool;
+ if (tool) {
+ uiState.tool = tool;
+ return;
+ }
+ // A person, an account, a claim: the graph-only types have no tool that reopens
+ // them, and until the board existed this call ended here doing nothing at all —
+ // a relation row on the map said "Open …" and swallowed the click. The board is
+ // where they are read, so that is where the jump lands.
+ if (entity.id) {
+ uiState.openBoardEntity = entity.id;
+ uiState.tool = 'board';
+ }
}
/** Open the case-wide note (null) or one filed note in the shared Notebook. */
diff --git a/frontend/src/lib/navigate.test.js b/frontend/src/lib/navigate.test.js
index 32ad143..fc99bb7 100644
--- a/frontend/src/lib/navigate.test.js
+++ b/frontend/src/lib/navigate.test.js
@@ -1,11 +1,18 @@
import { beforeEach, describe, expect, it, vi } from 'vitest';
-import { uiState } from './state.svelte.js';
-import { gotoCapture, gotoPoint, openEntity } from './navigate.js';
+
+const post = vi.fn().mockResolvedValue({ path: '/cases/c1/azimut/media' });
+vi.mock('./api.js', () => ({ api: { post: (...a) => post(...a), get: vi.fn() } }));
+
+const { caseState, uiState } = await import('./state.svelte.js');
+const { gotoCapture, gotoPoint, openEntity, opensInFileManager } = await import('./navigate.js');
beforeEach(() => {
uiState.tool = 'media';
uiState.gotoCoords = null;
uiState.focusCapture = null;
+ uiState.openBoardEntity = null;
+ post.mockClear();
+ caseState.current = { id: 'c1', name: 'Case', entities: [], links: [], folders: [] };
vi.stubGlobal('window', { open: vi.fn() });
});
@@ -50,6 +57,24 @@ describe('openEntity', () => {
});
});
+describe('a type with no tool of its own', () => {
+ it('opens on the board, which is where the graph types are read', () => {
+ // before this the call fell through doing nothing: a relation row on the map
+ // said "Open …" and swallowed the click
+ openEntity({ id: 'e-person', type: 'person', label: 'A. Analyst', attrs: {} });
+
+ expect(uiState.tool).toBe('board');
+ expect(uiState.openBoardEntity).toBe('e-person');
+ });
+
+ it('leaves the workspace alone for a row it cannot identify', () => {
+ openEntity({ type: 'person', attrs: {} });
+
+ expect(uiState.tool).toBe('media');
+ expect(uiState.openBoardEntity).toBeNull();
+ });
+});
+
describe('gotoCapture', () => {
it('leaves the zoom to the map when the capture records none', () => {
gotoCapture({ type: 'capture', attrs: { lat: 48.8584, lon: 2.2945, zoom: null } });
@@ -74,3 +99,32 @@ describe('gotoPoint', () => {
expect(uiState.gotoCoords).toBeNull();
});
});
+
+describe('a file the app cannot display', () => {
+ const plan = { id: 'm1', type: 'media', attrs: { path: 'media/site plan.pdf', kind: 'file' } };
+
+ it('is handed back to the desktop, in the folder it lives in', () => {
+ openEntity(plan);
+
+ expect(post).toHaveBeenCalledWith('/api/cases/c1/media/reveal', {
+ path: 'media/site plan.pdf',
+ });
+ // and the workspace does not move: nothing here could show it anyway
+ expect(uiState.tool).toBe('media');
+ expect(uiState.focusMedia).not.toBe('media/site plan.pdf');
+ });
+
+ it('leaves the images, video and audio the app does display alone', () => {
+ openEntity({ id: 'm2', type: 'media', attrs: { path: 'media/quay.jpg', kind: 'image' } });
+
+ expect(post).not.toHaveBeenCalled();
+ expect(uiState.focusMedia).toBe('media/quay.jpg');
+ });
+
+ it('says which entities need the file manager', () => {
+ expect(opensInFileManager(plan)).toBe(true);
+ expect(opensInFileManager({ type: 'media', attrs: { path: 'a.mp4' } })).toBe(false);
+ expect(opensInFileManager({ type: 'capture', attrs: { path: 'media/crop.png' } })).toBe(false);
+ expect(opensInFileManager(null)).toBe(false);
+ });
+});
diff --git a/frontend/src/lib/notebookContent.js b/frontend/src/lib/notebookContent.js
index b8971a9..ee2a611 100644
--- a/frontend/src/lib/notebookContent.js
+++ b/frontend/src/lib/notebookContent.js
@@ -4,10 +4,13 @@ export function insertNotebookText(text, value, start = text.length, end = start
return { text: `${before}${value}${after}`, cursor: before.length + value.length };
}
+import { fileUrl } from './fileUrl.js';
import { mediaReference } from './markdown.js';
export function notebookImageMarkdown(_caseId, item, entity) {
- return entity ? mediaReference(entity) : `![${item.filename}](/files/${_caseId}/${item.path})`;
+ return entity
+ ? mediaReference(entity)
+ : `![${item.filename}](${fileUrl(_caseId, item.path)})`;
}
export function notebookMediaMarkdown(_caseId, entity) {
diff --git a/frontend/src/lib/notes.js b/frontend/src/lib/notes.js
index 6858bcb..a669e15 100644
--- a/frontend/src/lib/notes.js
+++ b/frontend/src/lib/notes.js
@@ -7,13 +7,16 @@
*/
import { api } from './api.js';
-export async function createNote(caseId, { title, folder = '', content = '' }) {
+export async function createNote(caseId, { title, folder = '', content = '', sources = [] }) {
const label = (title ?? '').trim();
if (!label) throw new Error('Title required');
return api.post(`/api/cases/${caseId}/notes`, {
title: label,
folder: (folder ?? '').trim(),
content: content ?? '',
+ // case-relative paths the note was written from, filed as derivation edges.
+ // A note typed by hand sends none; a report sends the proof and media it embeds.
+ sources: sources.filter(Boolean),
});
}
diff --git a/frontend/src/lib/notes.test.js b/frontend/src/lib/notes.test.js
index 3ec0e52..96f9d6c 100644
--- a/frontend/src/lib/notes.test.js
+++ b/frontend/src/lib/notes.test.js
@@ -20,24 +20,36 @@ describe('createNote', () => {
it('posts a filed Markdown note with content and folder', async () => {
await createNote('case-1', { title: 'Lead', folder: 'Research', content: 'body' });
expect(api.post).toHaveBeenCalledWith('/api/cases/case-1/notes', {
- title: 'Lead', folder: 'Research', content: 'body',
+ title: 'Lead', folder: 'Research', content: 'body', sources: [],
});
});
it('trims the title and folder, and defaults content to empty', async () => {
await createNote('case-1', { title: ' Lead ', folder: ' Research ' });
expect(api.post).toHaveBeenCalledWith('/api/cases/case-1/notes', {
- title: 'Lead', folder: 'Research', content: '',
+ title: 'Lead', folder: 'Research', content: '', sources: [],
});
});
it('leaves the note unfiled when no folder is given', async () => {
await createNote('case-1', { title: 'Lead' });
expect(api.post).toHaveBeenCalledWith('/api/cases/case-1/notes', {
- title: 'Lead', folder: '', content: '',
+ title: 'Lead', folder: '', content: '', sources: [],
});
});
+ it('files what a report was written from, dropping the paths it has none of', async () => {
+ // a note typed by hand sends nothing; a report sends the proof and media it
+ // embeds, so deleting one of them scars the note instead of leaving a dead image
+ await createNote('case-1', {
+ title: 'Report',
+ content: 'body',
+ sources: ['proofs/a.png', null, 'media/b.jpg', ''],
+ });
+
+ expect(api.post.mock.calls[0][1].sources).toEqual(['proofs/a.png', 'media/b.jpg']);
+ });
+
it('rejects a blank title without hitting the API', async () => {
await expect(createNote('case-1', { title: ' ' })).rejects.toThrow('Title required');
expect(api.post).not.toHaveBeenCalled();
diff --git a/frontend/src/lib/post.js b/frontend/src/lib/post.js
index bc2df83..ab9aa86 100644
--- a/frontend/src/lib/post.js
+++ b/frontend/src/lib/post.js
@@ -158,7 +158,7 @@ export function postReportMarkdown({
entityReference(proofEntity),
'',
'::: center',
- `${mediaReference(proofEntity)}{width=70% align=center}`,
+ `${mediaReference(proofEntity)}{width=100% align=center}`,
':::',
].join('\n'));
} else if (cleanAttachments[0]?.startsWith('proofs/')) {
diff --git a/frontend/src/lib/post.test.js b/frontend/src/lib/post.test.js
index d321efb..ac57d09 100644
--- a/frontend/src/lib/post.test.js
+++ b/frontend/src/lib/post.test.js
@@ -405,7 +405,7 @@ describe('postReportMarkdown', () => {
expect(report).toContain('## Assessment\n\nMatch against reference imagery.');
expect(report).not.toContain('## Prepared thread');
expect(report).toContain('[[entity:e_proof|Rooftop proof]]');
- expect(report).toContain('[[media:e_proof|Rooftop proof]]{width=70% align=center}');
+ expect(report).toContain('[[media:e_proof|Rooftop proof]]{width=100% align=center}');
expect(report).toContain('[[entity:e_frame|Frame]]');
expect(report).toContain('[[media:e_frame|Frame]]{width=100% align=center}');
expect(report).not.toContain('- proofs/match.png');
diff --git a/frontend/src/lib/relations.svelte.js b/frontend/src/lib/relations.svelte.js
index d38caef..c8f75a7 100644
--- a/frontend/src/lib/relations.svelte.js
+++ b/frontend/src/lib/relations.svelte.js
@@ -11,7 +11,7 @@
*/
import { api } from './api.js';
-const registry = $state({ types: [] });
+const registry = $state({ types: [], levels: [] });
let pending = null;
/**
@@ -23,10 +23,13 @@ let pending = null;
* degraded label, never a broken panel.
*/
export function loadRelationTypes() {
- pending ??= api
- .get('/api/cases/relation-types')
- .then((types) => {
+ pending ??= Promise.all([
+ api.get('/api/cases/relation-types'),
+ api.get('/api/cases/confidence-levels'),
+ ])
+ .then(([types, levels]) => {
registry.types = Array.isArray(types) ? types : [];
+ registry.levels = Array.isArray(levels) ? levels : [];
})
.catch(() => {
pending = null;
@@ -34,38 +37,223 @@ export function loadRelationTypes() {
return pending;
}
+/**
+ * The two edges the app files by itself, and the words they read as.
+ *
+ * They are not in the registry because nobody may state them: an artifact is
+ * recorded as made from its source at save time (`engine/links.py`). The wording
+ * still has to live somewhere shared, since any surface drawing an edge has to
+ * name it, and `derived-from` is a type rather than a sentence.
+ */
+export const CHAIN_TYPES = ['derived-from', 'depends-on'];
+const CHAIN_VERBS = { 'derived-from': 'made from', 'depends-on': 'needs' };
+/**
+ * The same two edges read from the other end.
+ *
+ * A derivation is the one kind of edge an analyst walks in both directions as a
+ * matter of course — a proof is made from a collage made from a video, and the
+ * question is as often "what came out of this" as "what is this made from". Without
+ * these, reading one backwards fell through to the raw type and a panel said
+ * `derived-from` where every other edge said a sentence.
+ */
+const CHAIN_INVERSE = { 'derived-from': 'is the source of', 'depends-on': 'is needed by' };
+
/** How a link type reads in words, or the raw type until the registry lands. */
export function relationVerb(type) {
- return registry.types.find((entry) => entry.type === type)?.label ?? type;
+ return registry.types.find((entry) => entry.type === type)?.label ?? CHAIN_VERBS[type] ?? type;
+}
+
+/** How a relation reads from the entity being viewed. */
+export function relationReading(type, direction = 'out') {
+ const entry = registry.types.find((row) => row.type === type);
+ // The two chain types are deliberately absent from the registry — nobody may
+ // state them — so their wording is the fallback rather than the raw type.
+ if (!entry) {
+ const words = direction === 'in' ? CHAIN_INVERSE[type] : CHAIN_VERBS[type];
+ return words ?? type;
+ }
+ return direction === 'in' ? (entry.inverse_label ?? entry.label) : entry.label;
+}
+
+/**
+ * The levels an edge may be rated, coarsest word last.
+ *
+ * Served rather than written here for the reason the radius rungs are: one list, so
+ * the picker cannot offer a value the API would refuse. **Not assessed is not in it**
+ * — it is the absence of a rating, so a surface offers it as "clear", never as a
+ * fifth choice.
+ */
+export function confidenceLevels() {
+ return registry.levels;
+}
+
+/** How one rating reads in words, or '' when the edge has none. */
+export function confidenceLabel(value) {
+ if (value == null) return '';
+ return registry.levels.find((level) => level.value === value)?.label ?? String(value);
+}
+
+/** One clause saying what a verb means, where the words alone are ambiguous: "is part
+ * of" against "owns" is the distinction an order of battle turns on. */
+export function relationHint(type) {
+ return registry.types.find((entry) => entry.type === type)?.hint ?? '';
+}
+
+/** The heading a verb sits under, or '' when it sits with the rest. A pointer — a
+ * note naming a place it was not made from — reads as a finding when it shares a
+ * list with one, so the registry says where it belongs and every surface obeys. */
+export function relationGroup(type) {
+ return registry.types.find((entry) => entry.type === type)?.group ?? '';
+}
+
+/** Which user gesture files this verb. Mentions are pointers and use their own
+ * button; every older registry row safely remains a regular relation. */
+export function relationAction(type) {
+ return registry.types.find((entry) => entry.type === type)?.action ?? 'relation';
+}
+
+/** One clause placing a rating on the scale, for the control that offers it. */
+export function confidenceHint(value) {
+ if (value == null) return '';
+ return registry.levels.find((level) => level.value === value)?.hint ?? '';
+}
+
+/** Whether this link type may carry a rating at all: a derivation may not. */
+export function isRatable(type) {
+ return registry.types.find((entry) => entry.type === type)?.ratable ?? false;
+}
+
+/** How a free note on this verb is labelled, or '' when it takes none.
+ *
+ * It belongs to the verb and not to the edge, so a surface draws the field because
+ * the registry declares it — never because some edge happens to carry a value. Same
+ * shape as `isRatable`, and read the same way. */
+export function relationQualifier(type) {
+ return registry.types.find((entry) => entry.type === type)?.qualifier ?? '';
}
/**
* The relations an analyst may state between a subject and another entity.
*
- * The vocabulary is directed — a photo is shot at a place, never the reverse — so
+ * The vocabulary is directed — a photo is recorded at a place, never the reverse — so
* each option records which end the subject sits on: `out` when the subject is
* the `from`, `in` when it is the `to`. Callers never guess the order.
*/
-export function relationOptions(subjectType, otherType) {
+function endpoint(value) {
+ if (typeof value === 'string') return { type: value, kind: null };
+ return {
+ type: value?.type ?? null,
+ kind: value?.attrs?.kind ?? value?.kind ?? null,
+ };
+}
+
+function mediaKindAllowed(end, allowed) {
+ if (end.type !== 'media' || !allowed?.length || end.kind == null) return true;
+ return allowed.includes(end.kind);
+}
+
+/**
+ * Whether a verb reads the same word in both directions.
+ *
+ * `in-network` does not — a parent *contains* a child while the child *is in* the
+ * parent — so its two readings are two findings. `associated-with` does: two people
+ * are associated with each other, and there is no second sentence to tell apart. So
+ * it is offered once, and asking which way a stored one runs is a question with no
+ * answer.
+ *
+ * The inverse has to be **declared** and equal, never merely missing. The route
+ * always sends one, so the two cases never coincide against a real registry — but
+ * read as symmetric, a verb that simply never spelled its inverse would stop having
+ * its direction checked at all, which is the one thing this decides.
+ */
+function symmetric(entry) {
+ return Boolean(entry?.inverse_label) && entry.inverse_label === entry.label;
+}
+
+export function isSymmetric(type) {
+ return symmetric(registry.types.find((row) => row.type === type));
+}
+
+export function relationOptions(subject, other, action = 'all') {
+ const subjectEnd = endpoint(subject);
+ const otherEnd = endpoint(other);
const options = [];
for (const entry of registry.types) {
if (!entry.manual) continue;
- if (entry.from_types.includes(subjectType) && entry.to_types.includes(otherType)) {
- options.push({ type: entry.type, label: entry.label, direction: 'out' });
- } else if (entry.from_types.includes(otherType) && entry.to_types.includes(subjectType)) {
- options.push({ type: entry.type, label: entry.label, direction: 'in' });
+ if (action !== 'all' && (entry.action ?? 'relation') !== action) continue;
+ const group = entry.group ?? '';
+ const outward =
+ entry.from_types.includes(subjectEnd.type) &&
+ entry.to_types.includes(otherEnd.type) &&
+ mediaKindAllowed(subjectEnd, entry.from_media_kinds) &&
+ mediaKindAllowed(otherEnd, entry.to_media_kinds);
+ const inward =
+ entry.from_types.includes(otherEnd.type) &&
+ entry.to_types.includes(subjectEnd.type) &&
+ mediaKindAllowed(otherEnd, entry.from_media_kinds) &&
+ mediaKindAllowed(subjectEnd, entry.to_media_kinds);
+ if (outward) {
+ options.push({ type: entry.type, label: entry.label, group, direction: 'out' });
+ }
+ // Equal endpoint types can support both readings. A parent network contains a
+ // child network, while that child is in the parent; collapsing this to the
+ // first match made one direction impossible from half of the Details panels.
+ //
+ // Unless the two readings are the same word: `associated-with` is symmetric, so
+ // offering it twice puts one sentence in the menu twice and asks the analyst to
+ // choose between two identical lines.
+ if (inward && !(outward && symmetric(entry))) {
+ options.push({
+ type: entry.type,
+ label: entry.inverse_label ?? entry.label,
+ group,
+ direction: 'in',
+ });
}
}
- return options;
+ // Headed verbs last, registry order kept inside each. Callers take the first as
+ // the default reading, and a pointer is never the strongest thing a pair can say
+ // — where "was recorded at" is available, "mentions" must not win by declaration order.
+ return options.sort((a, b) => Number(Boolean(a.group)) - Number(Boolean(b.group)));
+}
+
+/**
+ * Whether a stored row still fits the current endpoint contract.
+ *
+ * The direction has to match, because the two readings of an asymmetric verb are two
+ * different findings and only one of them may still be legal. **A symmetric verb is
+ * the exception**: it is offered once, so the entity on the far end of one would
+ * find no inward reading to match and every such row read as an older connection —
+ * marked as out-of-matrix and stripped of its controls on exactly one of the two
+ * panels that show it.
+ */
+export function isCurrentConnection(subject, relation) {
+ return relationOptions(subject, relation.entity, relationAction(relation.link.type)).some(
+ (option) =>
+ option.type === relation.link.type &&
+ (option.direction === relation.direction || isSymmetric(option.type))
+ );
}
/** Entity types that can sit at the other end of a manual relation with this one. */
-export function relatableTypes(subjectType) {
+export function relatableTypes(subject, action = 'all') {
+ const subjectEnd = endpoint(subject);
const types = new Set();
for (const entry of registry.types) {
if (!entry.manual) continue;
- if (entry.from_types.includes(subjectType)) entry.to_types.forEach((t) => types.add(t));
- if (entry.to_types.includes(subjectType)) entry.from_types.forEach((t) => types.add(t));
+ if (action !== 'all' && (entry.action ?? 'relation') !== action) continue;
+ if (
+ entry.from_types.includes(subjectEnd.type) &&
+ mediaKindAllowed(subjectEnd, entry.from_media_kinds)
+ ) {
+ entry.to_types.forEach((type) => types.add(type));
+ }
+ if (
+ entry.to_types.includes(subjectEnd.type) &&
+ mediaKindAllowed(subjectEnd, entry.to_media_kinds)
+ ) {
+ entry.from_types.forEach((type) => types.add(type));
+ }
}
return [...types];
}
@@ -74,7 +262,7 @@ export function relatableTypes(subjectType) {
* File one collected choice against a subject that now exists.
*
* Split from the picker because a relation is often chosen before its subject is
- * saved: the Satellite save gate lets the analyst say "this photo was shot here"
+ * saved: the Satellite save gate lets the analyst say "this photo was recorded here"
* while filling in a place the case does not hold yet.
*/
export function saveRelation(caseId, subjectId, choice) {
diff --git a/frontend/src/lib/relations.test.js b/frontend/src/lib/relations.test.js
index ed3dd9c..eb2cccd 100644
--- a/frontend/src/lib/relations.test.js
+++ b/frontend/src/lib/relations.test.js
@@ -1,19 +1,34 @@
import { describe, it, expect, vi, beforeEach } from 'vitest';
+import { relationTypes as ontologyVocabulary } from '../../e2e/app.fixture.js';
// This instance is never given a registry, so it is also the "before the fetch
// lands" case: every surface renders against an empty vocabulary at first paint.
-import { relationOptions as coldOptions, relationVerb as coldVerb } from './relations.svelte.js';
+import {
+ confidenceLevels as coldLevels,
+ isRatable as coldRatable,
+ relationOptions as coldOptions,
+ relationVerb as coldVerb,
+} from './relations.svelte.js';
const get = vi.fn();
const post = vi.fn();
vi.mock('./api.js', () => ({ api: { get: (...a) => get(...a), post: (...a) => post(...a) } }));
+const LEVELS = [
+ { value: 3, label: 'Certain', hint: 'established and corroborated' },
+ { value: 2, label: 'Probable', hint: 'more likely than not' },
+ { value: 1, label: 'Possible' },
+ { value: -1, label: 'Ruled out' },
+];
+
const VOCABULARY = [
{
type: 'located-at',
- label: 'was shot at',
+ label: 'was recorded at',
from_types: ['capture', 'media'],
to_types: ['place'],
+ hint: 'the camera stood at this point',
manual: true,
+ ratable: true,
},
{
type: 'depicts',
@@ -21,6 +36,7 @@ const VOCABULARY = [
from_types: ['capture', 'media'],
to_types: ['place'],
manual: true,
+ ratable: true,
},
{
type: 'same-image-as',
@@ -28,16 +44,62 @@ const VOCABULARY = [
from_types: ['media'],
to_types: ['media'],
manual: false,
+ ratable: true,
+ },
+ {
+ type: 'in-network',
+ label: 'is in network',
+ inverse_label: 'contains',
+ from_types: ['ip', 'network'],
+ to_types: ['network'],
+ manual: true,
+ ratable: true,
+ },
+ // Symmetric, and the one verb carrying a free note: the tie is real, what kind of
+ // tie it is is a word only the analyst has.
+ {
+ type: 'associated-with',
+ label: 'is associated with',
+ inverse_label: 'is associated with',
+ from_types: ['organization', 'person'],
+ to_types: ['organization', 'person'],
+ manual: true,
+ ratable: true,
+ qualifier: 'How they are tied',
+ },
+ // The one verb the registry heads apart: a document naming something is a pointer,
+ // not a finding about where it is.
+ {
+ type: 'mentions',
+ label: 'mentions',
+ from_types: ['note', 'post'],
+ to_types: ['media', 'place'],
+ hint: 'refers to it, without having been made from it',
+ group: 'Mentions',
+ action: 'mention',
+ manual: true,
+ ratable: true,
},
];
+/** Answers each registry route, so a test can drop one without dropping both. */
+const serve = (routes = {}) => (url) => {
+ const table = {
+ '/api/cases/relation-types': VOCABULARY,
+ '/api/cases/confidence-levels': LEVELS,
+ ...routes,
+ };
+ const answer = table[url];
+ return answer instanceof Error ? Promise.reject(answer) : Promise.resolve(answer);
+};
+
let relations;
beforeEach(async () => {
vi.resetModules();
get.mockReset();
post.mockReset();
- get.mockResolvedValue(VOCABULARY);
+ get.mockImplementation(serve());
relations = await import('./relations.svelte.js');
});
@@ -48,8 +110,10 @@ describe('the relation vocabulary', () => {
relations.loadRelationTypes(),
relations.loadRelationTypes(),
]);
- expect(get).toHaveBeenCalledTimes(1);
+ // two routes, read together once: the vocabulary and the levels an edge may hold
+ expect(get).toHaveBeenCalledTimes(2);
expect(get).toHaveBeenCalledWith('/api/cases/relation-types');
+ expect(get).toHaveBeenCalledWith('/api/cases/confidence-levels');
});
it('leaves a surface usable before the fetch lands', () => {
@@ -59,7 +123,7 @@ describe('the relation vocabulary', () => {
it('names an edge in words once the registry is in', async () => {
await relations.loadRelationTypes();
- expect(relations.relationVerb('located-at')).toBe('was shot at');
+ expect(relations.relationVerb('located-at')).toBe('was recorded at');
expect(relations.relationVerb('same-image-as')).toBe('is the same picture as');
expect(relations.relationVerb('invented-by-hand')).toBe('invented-by-hand');
});
@@ -80,8 +144,8 @@ describe('relationOptions', () => {
it('records which end the subject sits on, because the vocabulary is directed', () => {
// from a place: the photo is the subject of the edge, the place its object
expect(relations.relationOptions('place', 'media')).toEqual([
- { type: 'located-at', label: 'was shot at', direction: 'in' },
- { type: 'depicts', label: 'shows', direction: 'in' },
+ { type: 'located-at', label: 'was recorded at', group: '', direction: 'in' },
+ { type: 'depicts', label: 'shows', group: '', direction: 'in' },
]);
// from the photo, the same two edges run outward
expect(relations.relationOptions('media', 'place').map((o) => o.direction)).toEqual([
@@ -96,7 +160,55 @@ describe('relationOptions', () => {
it('offers nothing for a pair the ontology has no reading for', () => {
expect(relations.relationOptions('place', 'place')).toEqual([]);
- expect(relations.relationOptions('post', 'place')).toEqual([]);
+ expect(relations.relationOptions('post', 'post')).toEqual([]);
+ });
+
+ it('carries the heading its verb declares, so a surface never sorts by type name', () => {
+ const [pointer] = relations.relationOptions('note', 'place');
+ expect(pointer).toEqual({
+ type: 'mentions',
+ label: 'mentions',
+ group: 'Mentions',
+ direction: 'out',
+ });
+ expect(relations.relationOptions('media', 'place').every((o) => o.group === '')).toBe(true);
+ });
+
+ it('keeps mentions out of the relation gesture', () => {
+ expect(relations.relationOptions('note', 'place', 'relation')).toEqual([]);
+ expect(relations.relationOptions('note', 'place', 'mention')).toEqual([
+ { type: 'mentions', label: 'mentions', group: 'Mentions', direction: 'out' },
+ ]);
+ expect(relations.relationAction('mentions')).toBe('mention');
+ expect(relations.relationAction('located-at')).toBe('relation');
+ });
+
+ it('puts a headed verb last however the registry declares it', async () => {
+ // the first option is the default reading a picker files, and a pointer is never
+ // the strongest thing a pair can say — declaration order must not decide that
+ vi.resetModules();
+ get.mockImplementation(
+ serve({
+ '/api/cases/relation-types': [
+ {
+ ...VOCABULARY.find((entry) => entry.type === 'mentions'),
+ from_types: ['note'],
+ to_types: ['place'],
+ },
+ {
+ ...VOCABULARY.find((entry) => entry.type === 'located-at'),
+ from_types: ['note'],
+ },
+ ],
+ })
+ );
+ const hostile = await import('./relations.svelte.js');
+ await hostile.loadRelationTypes();
+
+ expect(hostile.relationOptions('note', 'place').map((o) => o.type)).toEqual([
+ 'located-at',
+ 'mentions',
+ ]);
});
});
@@ -104,9 +216,124 @@ describe('relatableTypes', () => {
beforeEach(() => relations.loadRelationTypes());
it('lists what can sit at the other end, so a picker searches only those', () => {
- expect(relations.relatableTypes('place').sort()).toEqual(['capture', 'media']);
- expect(relations.relatableTypes('media')).toEqual(['place']);
- expect(relations.relatableTypes('post')).toEqual([]);
+ expect(relations.relatableTypes('place').sort()).toEqual(['capture', 'media', 'note', 'post']);
+ expect(relations.relatableTypes('media').sort()).toEqual(['note', 'place', 'post']);
+ // a headed verb widens the picker like any other: a pointer still needs a target
+ expect(relations.relatableTypes('post').sort()).toEqual(['media', 'place']);
+ });
+
+ it('gives relations and mentions separate target sets', () => {
+ expect(relations.relatableTypes('note', 'relation')).toEqual([]);
+ expect(relations.relatableTypes('note', 'mention').sort()).toEqual(['media', 'place']);
+ });
+
+ it('offers IP and nested-network links in both readable directions', () => {
+ expect(relations.relatableTypes('ip', 'relation')).toEqual(['network']);
+ expect(relations.relatableTypes('network', 'relation').sort()).toEqual(['ip', 'network']);
+ expect(relations.relationOptions('ip', 'network', 'relation')).toContainEqual({
+ type: 'in-network', label: 'is in network', group: '', direction: 'out',
+ });
+ expect(relations.relationOptions('network', 'ip', 'relation')).toContainEqual({
+ type: 'in-network', label: 'contains', group: '', direction: 'in',
+ });
+ expect(relations.relationOptions('network', 'network', 'relation')).toEqual([
+ { type: 'in-network', label: 'is in network', group: '', direction: 'out' },
+ { type: 'in-network', label: 'contains', group: '', direction: 'in' },
+ ]);
+ });
+
+ it('offers a symmetric verb once, not the same sentence twice', () => {
+ // A parent network *contains* a child while the child *is in* the parent: two
+ // readings, two lines. Two people are associated with each other in one word, so
+ // the second line would ask the analyst to choose between two identical options.
+ expect(relations.relationOptions('person', 'person', 'relation')).toEqual([
+ { type: 'associated-with', label: 'is associated with', group: '', direction: 'out' },
+ ]);
+ });
+
+ it('reads a symmetric row as current from the far end too', () => {
+ // The regression the dedup above caused: offered once, the entity on the far end
+ // found no inward reading to match, so every association read as an older
+ // connection — badged out-of-matrix and stripped of its controls on exactly one
+ // of the two panels showing it.
+ const tie = {
+ link: { id: 'l1', type: 'associated-with', provenance: { status: 'confirmed' } },
+ entity: { type: 'person' },
+ direction: 'in',
+ };
+ expect(relations.isCurrentConnection('person', tie)).toBe(true);
+ expect(relations.isCurrentConnection('person', { ...tie, direction: 'out' })).toBe(true);
+ // An asymmetric verb still has to match: its two readings are two findings, and
+ // only one of them may be legal for a given pair.
+ expect(relations.isSymmetric('in-network')).toBe(false);
+ expect(relations.isSymmetric('associated-with')).toBe(true);
+ expect(
+ relations.isCurrentConnection('ip', {
+ link: { id: 'l2', type: 'in-network', provenance: { status: 'confirmed' } },
+ entity: { type: 'network' },
+ direction: 'in',
+ })
+ ).toBe(false);
+ });
+
+ it('says which verb carries a free note, and which do not', () => {
+ // It belongs to the verb, never to the edge: a note every edge could hold would
+ // leave nothing saying what an edge *is*.
+ expect(relations.relationQualifier('associated-with')).toBe('How they are tied');
+ expect(relations.relationQualifier('in-network')).toBe('');
+ expect(relations.relationQualifier('mentions')).toBe('');
+ // an older registry with no such key answers the same as a verb declining one
+ expect(relations.relationQualifier('nothing-like-it')).toBe('');
+ });
+});
+
+describe('the complete browser ontology', () => {
+ let complete;
+
+ beforeEach(async () => {
+ vi.resetModules();
+ get.mockImplementation(
+ serve({ '/api/cases/relation-types': ontologyVocabulary })
+ );
+ complete = await import('./relations.svelte.js');
+ await complete.loadRelationTypes();
+ });
+
+ it('makes every manual endpoint reachable through its own frontend gesture', () => {
+ for (const entry of ontologyVocabulary.filter((row) => row.manual)) {
+ for (const fromType of entry.from_types) {
+ for (const toType of entry.to_types) {
+ expect(
+ complete.relatableTypes(fromType, entry.action),
+ `${entry.type}: ${fromType} must reach ${toType}`
+ ).toContain(toType);
+ expect(
+ complete.relationOptions(fromType, toType, entry.action),
+ `${entry.type}: ${fromType} must offer its outward reading for ${toType}`
+ ).toContainEqual({
+ type: entry.type,
+ label: entry.label,
+ group: entry.group,
+ direction: 'out',
+ });
+ }
+ }
+ }
+ });
+
+ it('keeps relation, mention and Claim connectors out of each other’s buttons', () => {
+ for (const entry of ontologyVocabulary.filter((row) => row.manual)) {
+ const otherActions = ['relation', 'mention', 'claim'].filter(
+ (action) => action !== entry.action
+ );
+ for (const action of otherActions) {
+ expect(
+ complete.relationOptions(entry.from_types[0], entry.to_types[0], action)
+ .some((option) => option.type === entry.type),
+ `${entry.type} leaked into ${action}`
+ ).toBe(false);
+ }
+ }
});
});
@@ -135,3 +362,119 @@ describe('saveRelation', () => {
});
});
});
+
+describe('how sure an edge says the analyst is', () => {
+ it('serves the levels the API declares, coarsest word last', async () => {
+ await relations.loadRelationTypes();
+
+ expect(relations.confidenceLevels().map((l) => l.value)).toEqual([3, 2, 1, -1]);
+ expect(relations.confidenceLabel(-1)).toBe('Ruled out');
+ expect(relations.confidenceLabel(2)).toBe('Probable');
+ });
+
+ it('reads an unrated edge as nothing at all, never as a level', async () => {
+ await relations.loadRelationTypes();
+
+ // absent is the lack of a rating, so it has no word and is not in the list
+ expect(relations.confidenceLabel(null)).toBe('');
+ expect(relations.confidenceLabel(undefined)).toBe('');
+ expect(relations.confidenceLevels().some((l) => l.value == null)).toBe(false);
+ });
+
+ it('says which link types may carry a rating at all', async () => {
+ await relations.loadRelationTypes();
+
+ expect(relations.isRatable('located-at')).toBe(true);
+ // a derivation is not in this registry, so it can never be offered one
+ expect(relations.isRatable('derived-from')).toBe(false);
+ });
+
+ it('offers no level before the registry lands, so no surface guesses one', () => {
+ expect(coldLevels()).toEqual([]);
+ expect(coldRatable('located-at')).toBe(false);
+ });
+
+ it('drops a failed read so the next surface retries both routes', async () => {
+ vi.resetModules();
+ get.mockImplementation(serve({ '/api/cases/confidence-levels': new Error('offline') }));
+ const cold = await import('./relations.svelte.js');
+
+ await cold.loadRelationTypes();
+ // one route failing leaves the whole registry empty rather than half-loaded
+ expect(cold.confidenceLevels()).toEqual([]);
+ expect(cold.relationVerb('located-at')).toBe('located-at');
+
+ get.mockImplementation(serve());
+ await cold.loadRelationTypes();
+ expect(cold.confidenceLevels()).toHaveLength(4);
+ expect(cold.relationVerb('located-at')).toBe('was recorded at');
+ });
+});
+
+describe('the vocabulary explains itself', () => {
+ it('says what a verb means, where the words alone are ambiguous', async () => {
+ await relations.loadRelationTypes();
+
+ expect(relations.relationHint('located-at')).toBe('the camera stood at this point');
+ // nothing invented locally for a verb the registry has never heard of
+ expect(relations.relationHint('bewitches')).toBe('');
+ });
+
+ it('says which verbs head their own section, and does not decide it here', async () => {
+ await relations.loadRelationTypes();
+
+ expect(relations.relationGroup('mentions')).toBe('Mentions');
+ expect(relations.relationGroup('located-at')).toBe('');
+ expect(relations.relationGroup('bewitches')).toBe('');
+ });
+
+ it('places a rating on the scale for the control that offers it', async () => {
+ await relations.loadRelationTypes();
+
+ expect(relations.confidenceHint(3)).toBe('established and corroborated');
+ expect(relations.confidenceHint(null)).toBe('');
+ });
+});
+
+describe('directed and media-aware endpoints', () => {
+ it('uses the inverse reading and refuses a non-media file kind', async () => {
+ vi.resetModules();
+ get.mockImplementation(
+ serve({
+ '/api/cases/relation-types': [
+ {
+ ...VOCABULARY[0],
+ label: 'was recorded at',
+ inverse_label: 'was recorded here',
+ from_media_kinds: ['image', 'video', 'audio'],
+ },
+ ],
+ })
+ );
+ const directed = await import('./relations.svelte.js');
+ await directed.loadRelationTypes();
+
+ const place = { type: 'place', attrs: {} };
+ const audio = { type: 'media', attrs: { kind: 'audio' } };
+ const file = { type: 'media', attrs: { kind: 'file' } };
+ expect(directed.relationOptions(place, audio)[0].label).toBe('was recorded here');
+ expect(directed.relationOptions(place, file)).toEqual([]);
+ expect(directed.relatableTypes(audio)).toEqual(['place']);
+ expect(directed.relatableTypes(file)).toEqual([]);
+ expect(directed.relationReading('located-at', 'in')).toBe('was recorded here');
+ });
+
+ it('recognizes whether a stored row still fits the current matrix', async () => {
+ await relations.loadRelationTypes();
+ const subject = { type: 'media', attrs: { kind: 'image' } };
+ const current = {
+ link: { type: 'located-at' },
+ entity: { type: 'place', attrs: {} },
+ direction: 'out',
+ };
+ const older = { ...current, direction: 'in' };
+
+ expect(relations.isCurrentConnection(subject, current)).toBe(true);
+ expect(relations.isCurrentConnection(subject, older)).toBe(false);
+ });
+});
diff --git a/frontend/src/lib/reveal.js b/frontend/src/lib/reveal.js
index f83ff8c..3490923 100644
--- a/frontend/src/lib/reveal.js
+++ b/frontend/src/lib/reveal.js
@@ -15,3 +15,14 @@ export function revealCaseFolder(caseId) {
export function revealWorkspaceFolder() {
return api.post('/api/settings/reveal-workspace');
}
+
+/**
+ * Show the folder holding one of a case's files.
+ *
+ * This one does send a path, because the file is what the analyst pointed at. It
+ * is a case-relative path like every other media route takes, resolved inside the
+ * case server-side; what opens is the folder, never the file.
+ */
+export function revealMediaFolder(caseId, path) {
+ return api.post(`/api/cases/${encodeURIComponent(caseId)}/media/reveal`, { path });
+}
diff --git a/frontend/src/lib/reveal.test.js b/frontend/src/lib/reveal.test.js
index 7ebae41..442d67b 100644
--- a/frontend/src/lib/reveal.test.js
+++ b/frontend/src/lib/reveal.test.js
@@ -1,6 +1,6 @@
import { beforeEach, expect, it, vi } from 'vitest';
import { api } from './api.js';
-import { revealCaseFolder, revealWorkspaceFolder } from './reveal.js';
+import { revealCaseFolder, revealMediaFolder, revealWorkspaceFolder } from './reveal.js';
vi.mock('./api.js', () => ({ api: { post: vi.fn() } }));
@@ -22,3 +22,10 @@ it('opens the workspace with no argument at all', async () => {
await revealWorkspaceFolder();
expect(api.post).toHaveBeenCalledWith('/api/settings/reveal-workspace');
});
+
+it('sends the file path so the folder it sits in can be shown', async () => {
+ await revealMediaFolder('case-1', 'media/site plan.pdf');
+ expect(api.post).toHaveBeenCalledWith('/api/cases/case-1/media/reveal', {
+ path: 'media/site plan.pdf',
+ });
+});
diff --git a/frontend/src/lib/staleness.js b/frontend/src/lib/staleness.js
new file mode 100644
index 0000000..338e25a
--- /dev/null
+++ b/frontend/src/lib/staleness.js
@@ -0,0 +1,66 @@
+/**
+ * What Settings has waiting: a newer Azimut, a newer downloader, a capture
+ * extension that is behind or was never installed.
+ *
+ * Pure on purpose: the checks that fill the store live in state.svelte.js and
+ * the dots live in App.svelte and Settings, so the placement rules are the part
+ * worth testing on their own.
+ */
+import { shouldShowUpdate } from './appUpdate.js';
+import { extensionOutdated } from './extBridge.js';
+
+/**
+ * @param {{
+ * app?: object|null,
+ * scrapers?: Array<{dist: string, outdated?: boolean}>|null,
+ * extensionInstalled?: string|null,
+ * extensionBundled?: string,
+ * }|null} state What the startup checks found (state.svelte.js updatesState).
+ * @param {string} dismissedVersion The release tag muted with "don't show again".
+ */
+export function updateBadges(state, dismissedVersion = '') {
+ // Muting a release silences its dot too. A marker the user cannot clear
+ // without upgrading is the nagging this whole feature exists to avoid.
+ const app = shouldShowUpdate(state?.app ?? null, dismissedVersion);
+ // A build that ships no extension has nothing to offer, so it says nothing.
+ const bundled = state?.extensionBundled ?? '';
+ const installed = state?.extensionInstalled ?? null;
+ const extensionMissing = Boolean(bundled) && !installed;
+ const extensionOld = extensionOutdated(installed, bundled);
+ const scrapers = (state?.scrapers ?? []).filter((s) => s?.outdated).map((s) => s.dist);
+ return {
+ app,
+ // Never installed and out of date are one dot on the tab but two different
+ // sentences on the button, so both answers travel.
+ extension: extensionMissing || extensionOld,
+ extensionMissing,
+ extensionOutdated: extensionOld,
+ scrapers,
+ // Settings keeps the app and the downloaders under System; the extension
+ // has a tab of its own.
+ tabs: { system: app || scrapers.length > 0, extension: extensionMissing || extensionOld },
+ any: app || extensionMissing || extensionOld || scrapers.length > 0,
+ };
+}
+
+/**
+ * Re-judge a local scraper read against what PyPI last reported.
+ *
+ * A read without `?check=true` knows the installed version and nothing about
+ * what's out there, so it would blank the verdict every time Settings reloads
+ * the list after an update. Carrying the known `latest` across and comparing it
+ * again — the backend's own rule, `version && latest !== version` — keeps the
+ * badge honest both ways: it clears the moment an update lands, and it comes
+ * back if a revert drops below what PyPI has.
+ *
+ * @param {Array<object>} fresh Entries from a local (unchecked) read.
+ * @param {Array<object>|null} previous The last checked entries, if any.
+ */
+export function carryLatest(fresh, previous) {
+ const known = new Map((previous ?? []).map((s) => [s.dist, s.latest]));
+ return (fresh ?? []).map((entry) => {
+ const latest = known.get(entry.dist);
+ if (!latest) return entry;
+ return { ...entry, latest, outdated: Boolean(entry.version && entry.version !== latest) };
+ });
+}
diff --git a/frontend/src/lib/staleness.test.js b/frontend/src/lib/staleness.test.js
new file mode 100644
index 0000000..e23e83c
--- /dev/null
+++ b/frontend/src/lib/staleness.test.js
@@ -0,0 +1,102 @@
+import { describe, it, expect } from 'vitest';
+import { updateBadges, carryLatest } from './staleness.js';
+
+const scraper = (dist, extra = {}) => ({ dist, version: '1.0', ...extra });
+
+describe('updateBadges', () => {
+ it('lights nothing when everything is current and installed', () => {
+ const badges = updateBadges({
+ app: { update_available: false },
+ scrapers: [scraper('yt-dlp', { latest: '1.0', outdated: false })],
+ extensionInstalled: '0.2.5',
+ extensionBundled: '0.2.5',
+ });
+ expect(badges.any).toBe(false);
+ expect(badges.tabs).toEqual({ system: false, extension: false });
+ });
+
+ it('lights nothing before the checks have run', () => {
+ expect(updateBadges(null).any).toBe(false);
+ expect(updateBadges({}).any).toBe(false);
+ });
+
+ it('files the app and the downloaders under System', () => {
+ const app = updateBadges({ app: { update_available: true, latest: 'v9.9.9' } });
+ expect(app.tabs.system).toBe(true);
+ expect(app.tabs.extension).toBe(false);
+
+ const stale = updateBadges({
+ scrapers: [scraper('yt-dlp', { outdated: true }), scraper('gallery-dl', { outdated: false })],
+ });
+ expect(stale.scrapers).toEqual(['yt-dlp']);
+ expect(stale.tabs.system).toBe(true);
+ });
+
+ it('files the extension under its own tab', () => {
+ const badges = updateBadges({ extensionInstalled: '0.2.1', extensionBundled: '0.2.5' });
+ expect(badges.extension).toBe(true);
+ expect(badges.tabs).toEqual({ system: false, extension: true });
+ expect(badges.any).toBe(true);
+ });
+
+ it('marks an extension that was never installed', () => {
+ const badges = updateBadges({ extensionInstalled: null, extensionBundled: '0.2.5' });
+ expect(badges.extension).toBe(true);
+ expect(badges.extensionMissing).toBe(true);
+ // The button says "Download extension", not "Download update".
+ expect(badges.extensionOutdated).toBe(false);
+ });
+
+ it('says nothing about an extension this build does not ship', () => {
+ const badges = updateBadges({ extensionInstalled: null, extensionBundled: '' });
+ expect(badges.extension).toBe(false);
+ expect(badges.any).toBe(false);
+ });
+
+ it('stays quiet when the bundled extension is older than the installed one', () => {
+ // The version tracks the release that last changed the extension, so a
+ // build can legitimately ship one older than what the browser already runs.
+ const badges = updateBadges({ extensionInstalled: '0.2.7', extensionBundled: '0.2.5' });
+ expect(badges.extension).toBe(false);
+ });
+
+ it('honours the release the user muted', () => {
+ const check = { update_available: true, latest: 'v9.9.9' };
+ expect(updateBadges({ app: check }, 'v9.9.9').app).toBe(false);
+ expect(updateBadges({ app: check }, 'v9.9.8').app).toBe(true);
+ });
+});
+
+describe('carryLatest', () => {
+ const checked = [
+ { dist: 'yt-dlp', version: '2026.1.1', latest: '2026.7.1', outdated: true },
+ { dist: 'gallery-dl', version: '1.29', latest: '1.30', outdated: true },
+ ];
+
+ it('clears the verdict for what was just updated and keeps the rest', () => {
+ const local = [
+ { dist: 'yt-dlp', version: '2026.7.1' }, // just updated
+ { dist: 'gallery-dl', version: '1.29' }, // untouched
+ ];
+ const carried = carryLatest(local, checked);
+ expect(carried[0].outdated).toBe(false);
+ expect(carried[1].outdated).toBe(true);
+ expect(carried[1].latest).toBe('1.30');
+ });
+
+ it('brings the verdict back when a revert drops below PyPI', () => {
+ const reverted = carryLatest([{ dist: 'yt-dlp', version: '2025.1.1' }], checked);
+ expect(reverted[0].outdated).toBe(true);
+ });
+
+ it('leaves entries alone when nothing was ever checked', () => {
+ const local = [{ dist: 'yt-dlp', version: '2026.1.1' }];
+ expect(carryLatest(local, null)).toEqual(local);
+ expect(carryLatest(local, [])).toEqual(local);
+ });
+
+ it('says nothing about a downloader that is not installed', () => {
+ const [entry] = carryLatest([{ dist: 'yt-dlp', version: null }], checked);
+ expect(entry.outdated).toBe(false);
+ });
+});
diff --git a/frontend/src/lib/state.svelte.js b/frontend/src/lib/state.svelte.js
index 9aa81d7..0dce05d 100644
--- a/frontend/src/lib/state.svelte.js
+++ b/frontend/src/lib/state.svelte.js
@@ -10,6 +10,7 @@ import { formatCoords as renderCoords } from './coords.js';
import { loadWidth, saveWidth, clampWidth } from './sidebar.js';
import { loadTheme, saveTheme, applyTheme } from './theme.js';
import { shouldShowUpdate } from './appUpdate.js';
+import { extensionVersion } from './extBridge.js';
import { loadRelationTypes } from './relations.svelte.js';
/**
@@ -39,6 +40,21 @@ export const updateState = $state({
notes: '', // the release body, Markdown
});
+/**
+ * What the startup checks found behind, feeding the dots on the Settings icon,
+ * on its tabs and on the buttons that do something about it (lib/staleness.js).
+ *
+ * Filled once, on load — nothing here polls. Settings writes back to it when a
+ * manual check or an update changes the answer, so clearing a badge doesn't
+ * wait for a reload.
+ */
+export const updatesState = $state({
+ app: null, // the /api/settings/update?check=true payload, or null
+ scrapers: null, // checked downloader entries, or null while never checked
+ extensionInstalled: null, // version stamped on <html> by the installed extension
+ extensionBundled: '', // version this build ships (GET /api/settings)
+});
+
/** Render a lat/lon the way the user asked for it. The tools' one entry point. */
export function fmtCoords(lat, lon) {
return renderCoords(lat, lon, prefs.coordFormat);
@@ -73,28 +89,37 @@ export function applyPrefs(s) {
if (s.update_check_on_start !== undefined) prefs.updateCheckOnStart = s.update_check_on_start;
if (s.update_dismissed_version !== undefined)
prefs.updateDismissedVersion = s.update_dismissed_version;
+ if (s.extension_version !== undefined) updatesState.extensionBundled = s.extension_version;
}
/**
- * On page load, ask GitHub whether a newer release is out and pop a notice if
- * so. The one network call Azimut makes on mount — gated on the user's
- * `updateCheckOnStart` preference (Settings turns it off), so with it disabled
- * opening the app still phones nowhere. Never throws: a failed or muted check
- * simply leaves the pop-up closed.
+ * On page load, work out what is behind: a newer Azimut release, a newer
+ * downloader, a newer capture extension. Runs once — nothing here polls, and
+ * nothing re-checks when Settings opens.
+ *
+ * The extension half is a local comparison (the installed one stamps its
+ * version on <html> at document_start), so it happens either way. The two
+ * network calls are gated together on `updateCheckOnStart`: with it off,
+ * opening the app still phones nowhere. Never throws — offline is the normal
+ * case here, and a check that fails just leaves the badge unlit.
*/
-export async function checkForUpdateOnStart() {
+export async function checkForUpdatesOnStart() {
+ updatesState.extensionInstalled = extensionVersion();
if (!prefs.updateCheckOnStart) return;
- try {
- const check = await api.get('/api/settings/update?check=true');
- if (shouldShowUpdate(check, prefs.updateDismissedVersion)) {
- updateState.latest = check.latest;
- updateState.url = check.url;
- updateState.notes = check.notes ?? '';
+ const [app, scrapers] = await Promise.allSettled([
+ api.get('/api/settings/update?check=true'),
+ api.get('/api/settings/scrapers?check=true'),
+ ]);
+ if (app.status === 'fulfilled') {
+ updatesState.app = app.value;
+ if (shouldShowUpdate(app.value, prefs.updateDismissedVersion)) {
+ updateState.latest = app.value.latest;
+ updateState.url = app.value.url;
+ updateState.notes = app.value.notes ?? '';
updateState.show = true;
}
- } catch {
- /* offline, rate-limited, whatever — the pop-up is a courtesy, not a gate */
}
+ if (scrapers.status === 'fulfilled') updatesState.scrapers = scrapers.value.scrapers ?? [];
}
/** Close the update pop-up. `mute` remembers the tag so it won't show again. */
@@ -164,6 +189,31 @@ export const uiState = $state({
inspectPath: null, // media path to open in the Inspect tool
focusMedia: null, // media path to highlight & scroll to in the Media Library
openInspect: null, // inspect-session name to reopen in the Inspect tool
+ // Entity id the Board should open Details on. The graph-only types — a person,
+ // an account, a claim — have no tool of their own to be reopened in, so the
+ // board is where following a relation to one of them lands.
+ openBoardEntity: null,
+ /**
+ * A question worked out in the Board, handed to the graph to be drawn.
+ *
+ * `{ terms, label }` — the catalog filter as request parameters, and the sentence
+ * it reads as. The **filter** travels rather than the ids it matched, which is what
+ * makes this work at any size: the graph asks the case the same question the table
+ * asked, so nothing is capped, no URL carries five hundred ids, and the drawing
+ * stays live as the case changes under it. Both surfaces resolve it through one
+ * predicate, so they cannot disagree about what it means.
+ */
+ drawInGraph: null,
+ /** One entity the graph should draw and select, wherever it came from. The mirror
+ * of `openBoardEntity`: a node has to be reachable from the row as much as a row
+ * from the node. */
+ openGraphEntity: null,
+ /** Entity/item handed to Timeline from Details. Timeline consumes and clears it. */
+ timelineFocus: null, // { entityId, entityLabel, itemId }
+ /** A fact-time range handed back to Timeline. Consumed once, never persisted. */
+ timelineRange: null, // { from, to }
+ /** A fact-time range handed to the Satellite map as a temporary event layer. */
+ mapTimelineRange: null, // { from, to }
gotoCoords: null, // { lat, lon } to fly to in the Satellite tool
// A point, a date and a time handed over by Coords & Sky: the Satellite tab
// opens its Sun & moon mode there. Session-only, and never part of a capture
@@ -255,19 +305,54 @@ function rememberCase(id) {
}
}
+let openingCase = 0;
+const caseChangeGuards = new Set();
+
+/** Finish case-owned work before another case becomes current. A guard returning
+ * false keeps the current case open, so a failed save cannot be mistaken for a
+ * successful switch. */
+export function registerCaseChangeGuard(guard) {
+ caseChangeGuards.add(guard);
+ return () => caseChangeGuards.delete(guard);
+}
+
+async function prepareCaseChange(fromId, toId) {
+ for (const guard of [...caseChangeGuards]) {
+ if ((await guard({ fromId, toId })) === false) return false;
+ }
+ return true;
+}
+
export async function openCase(id) {
+ const run = ++openingCase;
caseState.loading = true;
try {
+ const currentId = caseState.current?.id ?? null;
+ if (
+ currentId && currentId !== id &&
+ !(await prepareCaseChange(currentId, id))
+ ) return;
+ if (run !== openingCase) return;
// reference viewers point at the previous case's media — drop them
if (caseState.current?.id !== id) {
uiState.refViewers = [];
uiState.openNotebook = null;
uiState.focusCapture = null;
+ uiState.drawInGraph = null;
+ uiState.openBoardEntity = null;
+ uiState.openGraphEntity = null;
+ uiState.timelineFocus = null;
+ uiState.timelineRange = null;
+ uiState.mapTimelineRange = null;
}
- caseState.current = await api.get(`/api/cases/${id}`);
+ const opened = await api.get(`/api/cases/${id}`);
+ // Case reads can finish out of order. Only the latest choice may become current,
+ // or a slow first click can put its case back after a faster second one opened.
+ if (run !== openingCase) return;
+ caseState.current = opened;
rememberCase(id);
} finally {
- caseState.loading = false;
+ if (run === openingCase) caseState.loading = false;
}
}
@@ -300,11 +385,23 @@ export async function initSession() {
}
}
+let reloadingCase = 0;
+
export async function reloadCase() {
- if (caseState.current) {
- caseState.current = await api.get(`/api/cases/${caseState.current.id}`);
- caseState.rev++;
- }
+ const id = caseState.current?.id;
+ if (!id) return;
+ const selection = openingCase;
+ const run = ++reloadingCase;
+ const reloaded = await api.get(`/api/cases/${id}`);
+ // A write may finish while another case is being opened. Its refresh belongs to
+ // the case it started in and must never put that case back under the analyst.
+ if (
+ run !== reloadingCase ||
+ selection !== openingCase ||
+ caseState.current?.id !== id
+ ) return;
+ caseState.current = reloaded;
+ caseState.rev++;
}
export async function createCase(name) {
@@ -352,6 +449,8 @@ export async function promoteCase(name) {
* next, since the consuming effects only check that *some* case is open.
*/
export function closeCase() {
+ // Invalidate an open or refresh still in flight before dropping the current case.
+ openingCase++;
caseState.current = null;
rememberCase(null);
uiState.composeQueue = [];
@@ -361,6 +460,12 @@ export function closeCase() {
uiState.inspectPath = null;
uiState.focusMedia = null;
uiState.openInspect = null;
+ uiState.drawInGraph = null;
+ uiState.openBoardEntity = null;
+ uiState.openGraphEntity = null;
+ uiState.timelineFocus = null;
+ uiState.timelineRange = null;
+ uiState.mapTimelineRange = null;
uiState.gotoCoords = null;
uiState.skyAt = null;
uiState.refViewers = [];
diff --git a/frontend/src/lib/state.test.js b/frontend/src/lib/state.test.js
index ad0cccd..324bb6d 100644
--- a/frontend/src/lib/state.test.js
+++ b/frontend/src/lib/state.test.js
@@ -1,3 +1,9 @@
+/**
+ * @vitest-environment happy-dom
+ *
+ * The startup check reads the extension's marker off <html>, so this file needs
+ * a document like extBridge's own tests do.
+ */
import { describe, it, expect, beforeEach, vi, afterEach } from 'vitest';
import { caseState, uiState, closeCase, setSidebarWidth } from './state.svelte.js';
import { MIN_W, MAX_W } from './sidebar.js';
@@ -5,13 +11,25 @@ import { MIN_W, MAX_W } from './sidebar.js';
// The prefs tests below exercise import-time module state, so the transport is
// stubbed and the module re-imported fresh per test. The static import above
// still works: these tests never call the API.
-vi.mock('./api.js', () => ({ api: { get: vi.fn(), post: vi.fn(), del: vi.fn() } }));
+vi.mock('./api.js', () => ({
+ api: { get: vi.fn(), post: vi.fn(), put: vi.fn(), patch: vi.fn(), del: vi.fn() },
+}));
async function freshState() {
vi.resetModules();
return import('./state.svelte.js');
}
+function deferred() {
+ let resolve;
+ let reject;
+ const promise = new Promise((yes, no) => {
+ resolve = yes;
+ reject = no;
+ });
+ return { promise, resolve, reject };
+}
+
describe('closeCase', () => {
beforeEach(() => {
caseState.current = { id: 'case-a', name: 'Case A' };
@@ -22,6 +40,12 @@ describe('closeCase', () => {
uiState.inspectPath = 'media/a.jpg';
uiState.focusMedia = 'media/a.jpg';
uiState.openInspect = 'session-a';
+ uiState.drawInGraph = { label: 'A question' };
+ uiState.openBoardEntity = 'entity-a';
+ uiState.openGraphEntity = 'entity-a';
+ uiState.timelineFocus = { itemId: 'event-a' };
+ uiState.timelineRange = { from: '2026-01-01', to: '2026-02-01' };
+ uiState.mapTimelineRange = { from: '2026-01-01', to: '2026-02-01' };
uiState.gotoCoords = { lat: 1, lon: 2 };
});
@@ -39,6 +63,12 @@ describe('closeCase', () => {
expect(uiState.inspectPath).toBeNull();
expect(uiState.focusMedia).toBeNull();
expect(uiState.openInspect).toBeNull();
+ expect(uiState.drawInGraph).toBeNull();
+ expect(uiState.openBoardEntity).toBeNull();
+ expect(uiState.openGraphEntity).toBeNull();
+ expect(uiState.timelineFocus).toBeNull();
+ expect(uiState.timelineRange).toBeNull();
+ expect(uiState.mapTimelineRange).toBeNull();
expect(uiState.gotoCoords).toBeNull();
});
});
@@ -119,27 +149,58 @@ describe('applyPrefs', () => {
});
describe('startup update check', () => {
- it('checks by default and stays silent when the Settings switch is off', async () => {
+ it('checks the app and the downloaders by default, and neither when the Settings switch is off', async () => {
const { api } = await import('./api.js');
api.get.mockReset().mockResolvedValue({
- current: 'v0.1.0', latest: null, update_available: false,
+ current: 'v0.1.0', latest: null, update_available: false, scrapers: [],
});
- const { applyPrefs, checkForUpdateOnStart } = await freshState();
+ const { applyPrefs, checkForUpdatesOnStart } = await freshState();
- await checkForUpdateOnStart();
+ await checkForUpdatesOnStart();
expect(api.get).toHaveBeenCalledWith('/api/settings/update?check=true');
+ expect(api.get).toHaveBeenCalledWith('/api/settings/scrapers?check=true');
api.get.mockClear();
applyPrefs({ update_check_on_start: false });
- await checkForUpdateOnStart();
+ await checkForUpdatesOnStart();
expect(api.get).not.toHaveBeenCalled();
});
+ it('records what the downloaders check found', async () => {
+ const { api } = await import('./api.js');
+ const entries = [{ dist: 'yt-dlp', version: '2026.1.1', latest: '2026.7.1', outdated: true }];
+ api.get.mockReset().mockImplementation((path) =>
+ path.startsWith('/api/settings/scrapers')
+ ? Promise.resolve({ scrapers: entries })
+ : Promise.resolve({ update_available: false }),
+ );
+ const { checkForUpdatesOnStart, updatesState } = await freshState();
+
+ await checkForUpdatesOnStart();
+ expect(updatesState.scrapers).toEqual(entries);
+ });
+
+ it('compares the installed extension without asking the network', async () => {
+ const { api } = await import('./api.js');
+ api.get.mockReset().mockRejectedValue(new Error('must not be called'));
+ document.documentElement.dataset.azimutCaptureExtension = '0.2.1';
+ const { applyPrefs, checkForUpdatesOnStart, updatesState } = await freshState();
+ applyPrefs({ update_check_on_start: false, extension_version: '0.2.5' });
+
+ await checkForUpdatesOnStart();
+ expect(api.get).not.toHaveBeenCalled();
+ expect(updatesState.extensionInstalled).toBe('0.2.1');
+ expect(updatesState.extensionBundled).toBe('0.2.5');
+ delete document.documentElement.dataset.azimutCaptureExtension;
+ });
+
it('does not surface an offline failure', async () => {
const { api } = await import('./api.js');
api.get.mockReset().mockRejectedValue(new Error('offline'));
- const { checkForUpdateOnStart } = await freshState();
- await expect(checkForUpdateOnStart()).resolves.toBeUndefined();
+ const { checkForUpdatesOnStart, updatesState } = await freshState();
+ await expect(checkForUpdatesOnStart()).resolves.toBeUndefined();
+ expect(updatesState.app).toBeNull();
+ expect(updatesState.scrapers).toBeNull();
});
});
@@ -186,3 +247,82 @@ describe('templates store', () => {
expect(templatesState.post).toEqual([]);
});
});
+
+describe('case request ownership', () => {
+ let api;
+ let state;
+
+ beforeEach(async () => {
+ state = await freshState();
+ ({ api } = await import('./api.js'));
+ api.get.mockReset();
+ state.caseState.current = null;
+ state.caseState.loading = false;
+ state.caseState.rev = 0;
+ });
+
+ it('keeps the latest case when an older open finishes last', async () => {
+ const first = deferred();
+ const second = deferred();
+ api.get.mockImplementation((path) =>
+ path.endsWith('/case-a') ? first.promise : second.promise
+ );
+
+ const openingA = state.openCase('case-a');
+ const openingB = state.openCase('case-b');
+ second.resolve({ id: 'case-b', name: 'Case B' });
+ await openingB;
+ first.resolve({ id: 'case-a', name: 'Case A' });
+ await openingA;
+
+ expect(state.caseState.current).toEqual({ id: 'case-b', name: 'Case B' });
+ expect(state.caseState.loading).toBe(false);
+ });
+
+ it('waits for case-owned work and cancels the switch when it cannot be saved', async () => {
+ const guard = vi.fn().mockResolvedValue(false);
+ const unregister = state.registerCaseChangeGuard(guard);
+ state.caseState.current = { id: 'case-a', name: 'Case A' };
+
+ await state.openCase('case-b');
+
+ expect(guard).toHaveBeenCalledWith({ fromId: 'case-a', toId: 'case-b' });
+ expect(api.get).not.toHaveBeenCalled();
+ expect(state.caseState.current.id).toBe('case-a');
+ expect(state.caseState.loading).toBe(false);
+ unregister();
+ });
+
+ it('does not let a late refresh reopen the case it started in', async () => {
+ const refresh = deferred();
+ api.get.mockReturnValue(refresh.promise);
+ state.caseState.current = { id: 'case-a', name: 'Case A' };
+
+ const reloading = state.reloadCase();
+ state.caseState.current = { id: 'case-b', name: 'Case B' };
+ refresh.resolve({ id: 'case-a', name: 'Case A refreshed' });
+ await reloading;
+
+ expect(state.caseState.current).toEqual({ id: 'case-b', name: 'Case B' });
+ expect(state.caseState.rev).toBe(0);
+ });
+
+ it('keeps the latest refresh when two writes finish out of order', async () => {
+ const first = deferred();
+ const second = deferred();
+ api.get
+ .mockReturnValueOnce(first.promise)
+ .mockReturnValueOnce(second.promise);
+ state.caseState.current = { id: 'case-a', name: 'Before' };
+
+ const older = state.reloadCase();
+ const newer = state.reloadCase();
+ second.resolve({ id: 'case-a', name: 'Newest' });
+ await newer;
+ first.resolve({ id: 'case-a', name: 'Older' });
+ await older;
+
+ expect(state.caseState.current).toEqual({ id: 'case-a', name: 'Newest' });
+ expect(state.caseState.rev).toBe(1);
+ });
+});
diff --git a/frontend/src/lib/tally.js b/frontend/src/lib/tally.js
new file mode 100644
index 0000000..8f7d85a
--- /dev/null
+++ b/frontend/src/lib/tally.js
@@ -0,0 +1,89 @@
+/**
+ * Reading a tally row out loud (`engine/tally.py`).
+ *
+ * The server does the arithmetic and this does the sentence, which is where the
+ * honesty of the number actually lands: a total that prints "5" beside three
+ * statements, one of which carried no number and one of which was ruled out, is a
+ * true sum and a false impression. So nothing here ever prints a bare figure — the
+ * count lines say what was added, and the notes say what was left out and why.
+ *
+ * Pure, and it takes its words from the registry rather than spelling the vocabulary
+ * a second time: the condition labels come from the served `claim` field, so a
+ * condition added there reads correctly here with no edit.
+ */
+
+/** The unstated bucket, as the server groups it. */
+const UNSTATED = '';
+
+/**
+ * What the row's statements come to, one line per condition, in registry order.
+ *
+ * A bucket with no number contributes no line: two statements saying *destroyed*
+ * without a count add nothing to the sum, and a line reading "0 destroyed" would say
+ * the case checked and found none.
+ *
+ * @param {{conditions?: Array<{value: string, total: number}>}} row
+ * @param {(value: string) => string} label How the registry reads that condition.
+ */
+export function countLines(row, label = (value) => value) {
+ return (row?.conditions ?? [])
+ .filter((bucket) => bucket.total > 0)
+ .map((bucket) => ({
+ value: bucket.value,
+ text:
+ bucket.value === UNSTATED
+ ? `${bucket.total} unstated`
+ : `${bucket.total} ${String(label(bucket.value)).toLocaleLowerCase()}`,
+ }));
+}
+
+/**
+ * What the sum leaves out, in the row's own words.
+ *
+ * Two things can be left out and they are different: a statement that says *seen*
+ * without a number, and one the analyst ruled out. Neither is a gap in the data —
+ * "seen, not counted" is an answer, and eliminating a candidate is work the case
+ * keeps — so both are stated rather than quietly missing.
+ */
+export function noteLines(row) {
+ const notes = [];
+ const seen = (row?.statements ?? 0) - (row?.counted ?? 0);
+ if (seen > 0) notes.push(`${seen} without a number`);
+ if ((row?.refuted ?? 0) > 0) notes.push(`${row.refuted} ruled out`);
+ return notes;
+}
+
+/** How sure the row's statements are, worded for one line. Ruled-out ones are not
+ * here: they are in the notes, being the one level that leaves every sum. */
+export function confidenceLine(row, label = (value) => value) {
+ return (row?.confidence ?? [])
+ .map((level) =>
+ level.value
+ ? `${level.statements} ${String(label(level.value)).toLocaleLowerCase()}`
+ : `${level.statements} not assessed`
+ )
+ .join(' · ');
+}
+
+/**
+ * What the whole reading stands on, and what it could not put in a row.
+ *
+ * The cut comes first because it changes what every number below it means: a total
+ * over two thousand of three thousand statements looks whole and is not.
+ */
+export function readingNotes(body) {
+ const notes = [];
+ if (body?.truncated) {
+ notes.push(`Added up ${body.read} of ${body.matched} statements`);
+ }
+ const loose = body?.unattributed ?? 0;
+ if (loose > 0) {
+ notes.push(`${loose} ${loose === 1 ? 'statement says' : 'statements say'} nothing about what it concerns`);
+ }
+ return notes;
+}
+
+/** Whether the reading has anything to draw at all. */
+export function isEmpty(body) {
+ return !(body?.rows?.length || body?.unattributed);
+}
diff --git a/frontend/src/lib/tally.test.js b/frontend/src/lib/tally.test.js
new file mode 100644
index 0000000..5921aec
--- /dev/null
+++ b/frontend/src/lib/tally.test.js
@@ -0,0 +1,167 @@
+import { describe, it, expect } from 'vitest';
+import {
+ confidenceLine,
+ countLines,
+ isEmpty,
+ noteLines,
+ readingNotes,
+} from './tally.js';
+import { buildTallyQuery, buildCatalogQuery } from './catalog.js';
+
+const reads = { destroyed: 'Destroyed', damaged: 'Damaged', probable: 'Probable' };
+const label = (value) => reads[value] ?? value;
+
+const row = (extra = {}) => ({
+ id: 'e_1',
+ label: 'T-72B3',
+ type: 'equipment-type',
+ statements: 0,
+ counted: 0,
+ total: 0,
+ refuted: 0,
+ conditions: [],
+ confidence: [],
+ ...extra,
+});
+
+describe('countLines', () => {
+ it('reads one line per condition, in the order the server sent', () => {
+ const lines = countLines(
+ row({
+ conditions: [
+ { value: 'destroyed', total: 5, statements: 2, counted: 2 },
+ { value: 'damaged', total: 1, statements: 1, counted: 1 },
+ ],
+ }),
+ label
+ );
+ expect(lines.map((line) => line.text)).toEqual(['5 destroyed', '1 damaged']);
+ });
+
+ it('words the unstated bucket rather than printing a bare number', () => {
+ const lines = countLines(row({ conditions: [{ value: '', total: 3, counted: 1 }] }), label);
+ expect(lines[0].text).toBe('3 unstated');
+ });
+
+ it('draws no line for a condition nothing counted', () => {
+ // Two statements saying "destroyed" with no number add nothing, and "0 destroyed"
+ // would say the case checked and found none.
+ const lines = countLines(
+ row({ conditions: [{ value: 'destroyed', total: 0, statements: 2, counted: 0 }] }),
+ label
+ );
+ expect(lines).toEqual([]);
+ });
+
+ it('falls back to the stored word when the registry has no reading for it', () => {
+ const lines = countLines(row({ conditions: [{ value: 'scuttled', total: 1 }] }), label);
+ expect(lines[0].text).toBe('1 scuttled');
+ });
+
+ it('answers an absent row with nothing', () => {
+ expect(countLines(null)).toEqual([]);
+ expect(countLines({})).toEqual([]);
+ });
+});
+
+describe('noteLines', () => {
+ it('says how many statements carried no number', () => {
+ expect(noteLines(row({ statements: 3, counted: 1 }))).toEqual(['2 without a number']);
+ });
+
+ it('says how many were ruled out, apart from the sum', () => {
+ expect(noteLines(row({ statements: 2, counted: 2, refuted: 4 }))).toEqual(['4 ruled out']);
+ });
+
+ it('says both when both happened', () => {
+ expect(noteLines(row({ statements: 3, counted: 2, refuted: 1 }))).toEqual([
+ '1 without a number',
+ '1 ruled out',
+ ]);
+ });
+
+ it('stays quiet when every statement was counted and none eliminated', () => {
+ expect(noteLines(row({ statements: 2, counted: 2 }))).toEqual([]);
+ });
+});
+
+describe('confidenceLine', () => {
+ it('reads the levels the server ordered', () => {
+ const line = confidenceLine(
+ row({ confidence: [{ value: 'probable', statements: 2 }, { value: '', statements: 1 }] }),
+ label
+ );
+ expect(line).toBe('2 probable · 1 not assessed');
+ });
+
+ it('is empty when nothing stands', () => {
+ expect(confidenceLine(row())).toBe('');
+ });
+});
+
+describe('readingNotes', () => {
+ it('states the cut before anything else, because it changes every number under it', () => {
+ const notes = readingNotes({ read: 2000, matched: 3400, truncated: true, unattributed: 0 });
+ expect(notes).toEqual(['Added up 2000 of 3400 statements']);
+ });
+
+ it('reports the statements that name no subject', () => {
+ expect(readingNotes({ truncated: false, unattributed: 1 })).toEqual([
+ '1 statement says nothing about what it concerns',
+ ]);
+ expect(readingNotes({ truncated: false, unattributed: 3 })).toEqual([
+ '3 statements say nothing about what it concerns',
+ ]);
+ });
+
+ it('says nothing about a whole reading that lost nothing', () => {
+ expect(readingNotes({ read: 4, matched: 4, truncated: false, unattributed: 0 })).toEqual([]);
+ expect(readingNotes(null)).toEqual([]);
+ });
+});
+
+describe('isEmpty', () => {
+ it('is empty only when there is neither a row nor a loose statement', () => {
+ expect(isEmpty({ rows: [], unattributed: 0 })).toBe(true);
+ expect(isEmpty({ rows: [row()], unattributed: 0 })).toBe(false);
+ expect(isEmpty({ rows: [], unattributed: 2 })).toBe(false);
+ expect(isEmpty(null)).toBe(true);
+ });
+});
+
+describe('buildTallyQuery', () => {
+ it('asks the same narrowing as the page beside it', () => {
+ const options = {
+ types: ['claim'],
+ status: 'confirmed',
+ query: 'quay',
+ folder: 'Ground',
+ recursive: true,
+ attr: 'confidence',
+ value: 'probable',
+ linked: 'place',
+ since: '2026-01-01',
+ by: ['user'],
+ };
+ const tally = new URL(buildTallyQuery('c1', options), 'http://x');
+ const page = new URL(buildCatalogQuery('c1', options), 'http://x');
+
+ expect(tally.pathname).toBe('/api/cases/c1/catalog/tally');
+ expect(tally.searchParams.toString()).toBe(page.searchParams.toString());
+ });
+
+ it('carries nothing that belongs to a page', () => {
+ const url = buildTallyQuery('c1', {
+ types: ['claim'],
+ cursor: '12',
+ limit: 100,
+ order: 'label',
+ view: 'v_1',
+ });
+ expect(url).toBe('/api/cases/c1/catalog/tally?type=claim');
+ });
+
+ it('asks for the whole case when nothing is narrowed', () => {
+ expect(buildTallyQuery('c1')).toBe('/api/cases/c1/catalog/tally');
+ });
+});
diff --git a/frontend/src/lib/temporalInput.js b/frontend/src/lib/temporalInput.js
new file mode 100644
index 0000000..12371b5
--- /dev/null
+++ b/frontend/src/lib/temporalInput.js
@@ -0,0 +1,101 @@
+const DATE = /^(\d{4})(?:-(\d{2})(?:-(\d{2}))?)?([~?%])?$/;
+const TIMESTAMP = /^(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,6})?)(Z|[+-]\d{2}:\d{2})?$/;
+
+export const TEMPORAL_FORMATS = [
+ { value: 'date', label: 'Date' },
+ { value: 'timestamp', label: 'Date and time' },
+ { value: 'range', label: 'Date range' },
+ { value: 'time-range', label: 'Time range' },
+ { value: 'advanced', label: 'Advanced syntax' },
+];
+
+export const TEMPORAL_SYNTAX = [
+ { meaning: 'Year', pattern: 'YYYY', example: '2026' },
+ { meaning: 'Month', pattern: 'YYYY-MM', example: '2026-08' },
+ { meaning: 'Day', pattern: 'YYYY-MM-DD', example: '2026-08-11' },
+ {
+ meaning: 'Local time',
+ pattern: 'YYYY-MM-DDThh:mm:ss',
+ example: '2026-08-11T18:40:00',
+ },
+ { meaning: 'UTC time', pattern: '…ssZ', example: '2026-08-11T16:40:00Z' },
+ { meaning: 'UTC offset', pattern: '…ss±hh:mm', example: '2026-08-11T18:40:00+02:00' },
+ { meaning: 'Subseconds', pattern: '…ss.ffffffZ', example: '2026-08-11T16:40:00.123Z' },
+ { meaning: 'Date range', pattern: 'start/end', example: '2026-08~/2026-10?' },
+ { meaning: 'Time range', pattern: 'time/time', example: '2026-08-11T10:15:00Z/2026-08-11T11:40:00Z' },
+];
+
+export const TEMPORAL_MARKERS = [
+ { value: '~', meaning: 'Approximate' },
+ { value: '?', meaning: 'Uncertain' },
+ { value: '%', meaning: 'Approximate and uncertain' },
+];
+
+export function readTemporalInput(value) {
+ const raw = typeof value === 'string' ? value : '';
+ const date = DATE.exec(raw);
+ if (date) {
+ const precision = date[3] ? 'day' : date[2] ? 'month' : 'year';
+ return {
+ mode: 'date', precision, certainty: date[4] ?? '', date: raw.slice(0, raw.length - (date[4] ? 1 : 0)),
+ datetime: '', zone: 'local', offset: '+00:00', start: '', end: '',
+ startTime: '', endTime: '', rangeZone: 'utc', rangeOffset: '+00:00', raw,
+ };
+ }
+ const timestamp = TIMESTAMP.exec(raw);
+ if (timestamp) {
+ const suffix = timestamp[2] ?? '';
+ return {
+ mode: 'timestamp', precision: 'day', certainty: '', date: '',
+ datetime: timestamp[1], zone: suffix === 'Z' ? 'utc' : suffix ? 'offset' : 'local',
+ offset: suffix && suffix !== 'Z' ? suffix : '+00:00', start: '', end: '',
+ startTime: '', endTime: '', rangeZone: 'utc', rangeOffset: '+00:00', raw,
+ };
+ }
+ const interval = raw.split('/');
+ if (interval.length === 2 && interval.every((part) => /^\d{4}-\d{2}-\d{2}$/.test(part))) {
+ return {
+ mode: 'range', precision: 'day', certainty: '', date: '', datetime: '',
+ zone: 'local', offset: '+00:00', start: interval[0], end: interval[1],
+ startTime: '', endTime: '', rangeZone: 'utc', rangeOffset: '+00:00', raw,
+ };
+ }
+ if (interval.length === 2) {
+ const start = TIMESTAMP.exec(interval[0]);
+ const end = TIMESTAMP.exec(interval[1]);
+ const startZone = start?.[2] ?? '';
+ const endZone = end?.[2] ?? '';
+ if (start && end && startZone && startZone === endZone) {
+ return {
+ mode: 'time-range', precision: 'day', certainty: '', date: '', datetime: '',
+ zone: 'local', offset: '+00:00', start: '', end: '',
+ startTime: start[1], endTime: end[1],
+ rangeZone: startZone === 'Z' ? 'utc' : 'offset',
+ rangeOffset: startZone === 'Z' ? '+00:00' : startZone, raw,
+ };
+ }
+ }
+ return {
+ mode: raw ? 'advanced' : 'date', precision: 'day', certainty: '', date: '',
+ datetime: '', zone: 'local', offset: '+00:00', start: '', end: '',
+ startTime: '', endTime: '', rangeZone: 'utc', rangeOffset: '+00:00', raw,
+ };
+}
+
+function timestampWithSeconds(value) {
+ return /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}$/.test(value) ? `${value}:00` : value;
+}
+
+export function writeTemporalInput(state) {
+ if (state.mode === 'date') return state.date ? `${state.date}${state.certainty}` : '';
+ if (state.mode === 'range') return state.start && state.end ? `${state.start}/${state.end}` : '';
+ if (state.mode === 'time-range') {
+ if (!state.startTime || !state.endTime) return '';
+ const zone = state.rangeZone === 'utc' ? 'Z' : state.rangeOffset;
+ return `${timestampWithSeconds(state.startTime)}${zone}/${timestampWithSeconds(state.endTime)}${zone}`;
+ }
+ if (state.mode === 'advanced') return state.raw ?? '';
+ if (!state.datetime) return '';
+ const zone = state.zone === 'utc' ? 'Z' : state.zone === 'offset' ? state.offset : '';
+ return `${timestampWithSeconds(state.datetime)}${zone}`;
+}
diff --git a/frontend/src/lib/temporalInput.test.js b/frontend/src/lib/temporalInput.test.js
new file mode 100644
index 0000000..c3732e5
--- /dev/null
+++ b/frontend/src/lib/temporalInput.test.js
@@ -0,0 +1,50 @@
+import { describe, expect, it } from 'vitest';
+import {
+ TEMPORAL_MARKERS,
+ TEMPORAL_SYNTAX,
+ readTemporalInput,
+ writeTemporalInput,
+} from './temporalInput.js';
+
+describe('the temporal input adapter', () => {
+ it.each([
+ '2026',
+ '2026-08',
+ '2026-08-11?',
+ '2026-08-11T18:40:00',
+ '2026-08-11T16:40:00Z',
+ '2026-08-11T18:40:00+02:00',
+ '2026-08-11/2026-08-14',
+ '2026-08~/2026-10?',
+ '2026-08-11T10:15:00Z/2026-08-11T11:40:00Z',
+ '2026-08-11T10:15:00+02:00/2026-08-11T11:40:00+02:00',
+ ])('round-trips %s without rewriting it', (raw) => {
+ expect(writeTemporalInput(readTemporalInput(raw))).toBe(raw);
+ });
+
+ it('adds the seconds required by the backend profile', () => {
+ expect(writeTemporalInput({
+ mode: 'timestamp', datetime: '2026-08-11T18:40', zone: 'utc', offset: '+00:00',
+ })).toBe('2026-08-11T18:40:00Z');
+ });
+
+ it('keeps an unrecognised existing value in the advanced editor', () => {
+ const state = readTemporalInput('circa late summer');
+
+ expect(state.mode).toBe('advanced');
+ expect(writeTemporalInput(state)).toBe('circa late summer');
+ });
+
+ it('documents every supported family with a pattern and an example', () => {
+ expect(TEMPORAL_SYNTAX.map(({ meaning }) => meaning)).toEqual([
+ 'Year', 'Month', 'Day', 'Local time', 'UTC time', 'UTC offset',
+ 'Subseconds', 'Date range', 'Time range',
+ ]);
+ expect(TEMPORAL_SYNTAX.every(({ pattern, example }) => pattern && example)).toBe(true);
+ expect(TEMPORAL_MARKERS).toEqual([
+ { value: '~', meaning: 'Approximate' },
+ { value: '?', meaning: 'Uncertain' },
+ { value: '%', meaning: 'Approximate and uncertain' },
+ ]);
+ });
+});
diff --git a/frontend/src/lib/temporalMap.js b/frontend/src/lib/temporalMap.js
new file mode 100644
index 0000000..501925c
--- /dev/null
+++ b/frontend/src/lib/temporalMap.js
@@ -0,0 +1,23 @@
+/** Pure helpers for the session-only Timeline layer on the map. */
+
+export function temporalMapQuery(caseId, from, to, categories = []) {
+ const params = new URLSearchParams({ from, to });
+ // The layer answers the categories the Timeline was reading, so a window of
+ // photographs does not arrive at the map as an empty one.
+ for (const category of categories) params.append('category', category);
+ return `/api/cases/${caseId}/timeline/map?${params}`;
+}
+
+export function groupTemporalMapItems(items) {
+ const groups = new Map();
+ for (const item of items ?? []) {
+ for (const place of item.place_entities ?? []) {
+ if (!Number.isFinite(place.lat) || !Number.isFinite(place.lon)) continue;
+ const key = place.id || `${place.lat}:${place.lon}`;
+ const group = groups.get(key) ?? { ...place, items: [] };
+ group.items.push(item);
+ groups.set(key, group);
+ }
+ }
+ return [...groups.values()];
+}
diff --git a/frontend/src/lib/temporalMap.test.js b/frontend/src/lib/temporalMap.test.js
new file mode 100644
index 0000000..d8da8ee
--- /dev/null
+++ b/frontend/src/lib/temporalMap.test.js
@@ -0,0 +1,19 @@
+import { describe, expect, it } from 'vitest';
+import { groupTemporalMapItems, temporalMapQuery } from './temporalMap.js';
+
+describe('the temporary Timeline map layer', () => {
+ it('asks for one fact-time window', () => {
+ expect(temporalMapQuery('case-a', '2026-08-01T00:00:00Z', '2026-09-01T00:00:00Z'))
+ .toBe('/api/cases/case-a/timeline/map?from=2026-08-01T00%3A00%3A00Z&to=2026-09-01T00%3A00%3A00Z');
+ });
+
+ it('stacks claims at the same place and ignores places without coordinates', () => {
+ const place = { id: 'place-a', label: 'Harbour', lat: 50, lon: 2 };
+ const groups = groupTemporalMapItems([
+ { id: 'claim-a', place_entities: [place] },
+ { id: 'claim-b', place_entities: [place, { id: 'unknown', label: 'Unknown' }] },
+ ]);
+ expect(groups).toHaveLength(1);
+ expect(groups[0].items.map((item) => item.id)).toEqual(['claim-a', 'claim-b']);
+ });
+});
diff --git a/frontend/src/lib/timeline.js b/frontend/src/lib/timeline.js
new file mode 100644
index 0000000..220f0e3
--- /dev/null
+++ b/frontend/src/lib/timeline.js
@@ -0,0 +1,1411 @@
+export const SECOND = 1_000;
+export const MINUTE = 60 * SECOND;
+export const HOUR = 60 * MINUTE;
+export const DAY = 24 * HOUR;
+
+const MIN_WINDOW = 2 * SECOND;
+const MONTHS = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
+
+export const TIMELINE_CATEGORIES = [
+ { id: 'statement', label: 'Statements', short: 'Statements' },
+ { id: 'media', label: 'Media dates', short: 'Media' },
+ { id: 'case_activity', label: 'Case activity', short: 'Activity' },
+];
+
+function clamp(value, low = 0, high = 1) {
+ return Math.min(high, Math.max(low, value));
+}
+
+// ── the zone the axis is read in ─────────────────────────────────────────────
+//
+// **Storage is UTC and stays UTC.** Every instant on disk, in a query and in a
+// stated value is unchanged by anything below: this is presentation, the way the
+// display preferences are (SPEC §9), and the switch moves where the ticks fall and
+// what they are called, never what the case holds.
+//
+// It exists because an investigator argues in the *event's* local time. A photo
+// posted at 19:40 is checked against the light at the place it was taken, not
+// against a clock in the analyst's own country — and reading a UTC axis while
+// thinking in local time is where an hour goes missing in a chronology.
+//
+// The rule for ticks: **above a day the step is a calendar one**, so a day tick is
+// local midnight whatever the offset was doing that week; **below it a fixed
+// interval**, so an hour tick keeps its exact spacing and a zone that jumps an hour
+// shows the jump — 01:00 then 03:00 — instead of hiding it.
+
+/** The zone every reading defaults to, and the one the case is stored in. */
+export const UTC = 'UTC';
+
+/** This machine's own zone, for the analyst who wants their own working day. It is
+ * a legitimate reading and a poor default, which is why UTC is the default. */
+export function machineZone() {
+ try {
+ return Intl.DateTimeFormat().resolvedOptions().timeZone || UTC;
+ } catch {
+ return UTC;
+ }
+}
+
+/** Whether this browser can read that zone at all. A zone name carried in from
+ * another machine must never throw the axis away. */
+export function knownZone(zone) {
+ if (!zone || zone === UTC) return true;
+ try {
+ partsFor(zone).format(0);
+ return true;
+ } catch {
+ return false;
+ }
+}
+
+const FORMATTERS = new Map();
+
+function partsFor(zone) {
+ let held = FORMATTERS.get(zone);
+ if (!held) {
+ held = new Intl.DateTimeFormat('en-US', {
+ timeZone: zone,
+ hourCycle: 'h23',
+ year: 'numeric',
+ month: '2-digit',
+ day: '2-digit',
+ hour: '2-digit',
+ minute: '2-digit',
+ second: '2-digit',
+ });
+ FORMATTERS.set(zone, held);
+ }
+ return held;
+}
+
+/** The wall-clock reading of an instant in a zone, as plain numbers. */
+export function zonedFields(millis, zone = UTC) {
+ const date = new Date(millis);
+ if (!zone || zone === UTC) {
+ return {
+ year: date.getUTCFullYear(),
+ month: date.getUTCMonth() + 1,
+ day: date.getUTCDate(),
+ hour: date.getUTCHours(),
+ minute: date.getUTCMinutes(),
+ second: date.getUTCSeconds(),
+ };
+ }
+ const held = {};
+ for (const part of partsFor(zone).formatToParts(date)) {
+ if (part.type !== 'literal') held[part.type] = Number(part.value);
+ }
+ return {
+ year: held.year,
+ month: held.month,
+ day: held.day,
+ // Midnight comes back as 24 in some engines even under h23; both spellings mean
+ // the start of the day, and only one of them survives arithmetic.
+ hour: held.hour === 24 ? 0 : held.hour,
+ minute: held.minute,
+ second: held.second,
+ };
+}
+
+/** A wall clock as an instant, built through `Date` rather than `Date.UTC` so a
+ * two-digit year stays itself instead of landing in the twentieth century. */
+function fieldsToUtc({ year, month, day, hour = 0, minute = 0, second = 0 }) {
+ const date = new Date(0);
+ date.setUTCFullYear(year, month - 1, day);
+ date.setUTCHours(hour, minute, second, 0);
+ return date.getTime();
+}
+
+/** How far ahead of UTC the zone runs at that instant, in milliseconds. */
+export function zoneOffset(millis, zone = UTC) {
+ if (!zone || zone === UTC) return 0;
+ return fieldsToUtc(zonedFields(millis, zone)) - Math.floor(millis / SECOND) * SECOND;
+}
+
+/**
+ * The instant a wall clock names in a zone.
+ *
+ * Corrected twice, which is what a zone lookup costs when only the inverse is on
+ * offer: the first pass lands within an hour of the answer, and the second settles
+ * it — including on the two days a year when the offset moves under the guess. A wall
+ * clock a spring change skipped over lands an hour later, in the offset now in force,
+ * which is what every calendar does with a time that never happened.
+ */
+export function instantOf(fields, zone = UTC) {
+ const wanted = fieldsToUtc(fields);
+ if (!zone || zone === UTC) return wanted;
+ let millis = wanted - zoneOffset(wanted, zone);
+ millis = wanted - zoneOffset(millis, zone);
+ return millis;
+}
+
+const pad = (value, size = 2) => String(value).padStart(size, '0');
+
+/** The zone as the analyst sees it named: the short abbreviation the zone itself
+ * uses, or its numeric offset where it has no word for the season. */
+export function zoneAbbreviation(zone, at = 0) {
+ if (!zone || zone === UTC) return 'UTC';
+ try {
+ const parts = new Intl.DateTimeFormat('en-US', {
+ timeZone: zone,
+ timeZoneName: 'short',
+ }).formatToParts(new Date(at));
+ return parts.find((part) => part.type === 'timeZoneName')?.value ?? zone;
+ } catch {
+ return zone;
+ }
+}
+
+/**
+ * Every zone this browser can name, sorted.
+ *
+ * An investigation is rarely in the analyst's own zone and often in no zone the case
+ * has a saved point for yet, so the reading has to be choosable outright. The list is
+ * the platform's own copy of the IANA database — no dependency, nothing fetched — and
+ * naming a zone rather than an offset is what makes a stated hour survive the two days
+ * a year the offset moves.
+ *
+ * Empty where the engine will not list them (`supportedValuesOf` landed in 2022), and
+ * the picker says so rather than pretending the world is UTC.
+ */
+export function worldZones() {
+ try {
+ const held = Intl.supportedValuesOf?.('timeZone') ?? [];
+ return [...held].sort((one, other) => one.localeCompare(other));
+ } catch {
+ return [];
+ }
+}
+
+/** A zone's offset at an instant, as `UTC+02:00`. What tells two zones of the same
+ * name apart, and what an analyst reads a stated `+03:00` against. */
+export function offsetLabel(zone, at = 0) {
+ const minutes = Math.round(zoneOffset(at, zone) / MINUTE);
+ if (!minutes) return 'UTC';
+ const sign = minutes < 0 ? '-' : '+';
+ const size = Math.abs(minutes);
+ return `UTC${sign}${pad(Math.floor(size / 60))}:${pad(size % 60)}`;
+}
+
+/** The zone as a line in a menu: the place part first, since that is what is typed. */
+export function zoneWords(zone) {
+ const parts = String(zone ?? '').split('/');
+ return {
+ place: parts.at(-1).replace(/_/g, ' '),
+ region: parts.length > 1 ? parts.slice(0, -1).join(' / ').replace(/_/g, ' ') : '',
+ };
+}
+
+/**
+ * Cities the database renamed, and the name an analyst is going to type.
+ *
+ * Which of the two a platform lists is not ours to decide: this machine's own copy
+ * offers `Europe/Kiev` and `Asia/Calcutta` where a current browser offers `Europe/Kyiv`
+ * and `Asia/Kolkata`. Both spellings load either way, so the only thing that breaks is
+ * the *search* — and someone working Ukraine typing "kyiv" into a list that says Kiev
+ * concludes the zone is missing. Matched both directions, so neither spelling hides a
+ * zone the other name would have found.
+ */
+const ZONE_ALIASES = [
+ ['kiev', 'kyiv'],
+ ['calcutta', 'kolkata'],
+ ['saigon', 'ho chi minh'],
+ ['rangoon', 'yangon'],
+ ['katmandu', 'kathmandu'],
+ ['asmera', 'asmara'],
+ ['dacca', 'dhaka'],
+ ['ujung pandang', 'makassar'],
+ ['bombay', 'mumbai'],
+ ['madras', 'chennai'],
+];
+
+/**
+ * Whether a zone answers what was typed.
+ *
+ * Matched on the whole name, on the city alone, on the offset and across the renames
+ * above, so `kyiv`, `europe` and `+03` all reach the zone whichever way this platform
+ * spells it. Underscores are not something anyone types.
+ */
+export function zoneMatches(zone, query, at = 0) {
+ const term = String(query ?? '').trim().toLowerCase();
+ if (!term) return true;
+ const name = String(zone ?? '').toLowerCase().replace(/_/g, ' ');
+ if (name.includes(term) || offsetLabel(zone, at).toLowerCase().includes(term)) return true;
+ return ZONE_ALIASES.some(
+ ([one, other]) =>
+ (name.includes(one) && other.includes(term)) ||
+ (name.includes(other) && one.includes(term)),
+ );
+}
+
+/** One instant written out in the zone, for a readout rather than for a tick. */
+export function zonedStamp(value, zone = UTC) {
+ const millis = value instanceof Date ? value.getTime() : new Date(value).getTime();
+ if (!Number.isFinite(millis)) return '';
+ const at = zonedFields(millis, zone);
+ return (
+ `${pad(at.year, 4)}-${pad(at.month)}-${pad(at.day)} ` +
+ `${pad(at.hour)}:${pad(at.minute)}:${pad(at.second)}`
+ );
+}
+
+export function isoDay(value) {
+ const date = value instanceof Date ? value : new Date(value);
+ return Number.isFinite(date.getTime()) ? date.toISOString().slice(0, 10) : '';
+}
+
+export function isoInstant(value) {
+ const date = value instanceof Date ? value : new Date(value);
+ if (!Number.isFinite(date.getTime())) return '';
+ return date.toISOString().replace('.000Z', 'Z');
+}
+
+function boundaryMillis(value, upper = false) {
+ if (!value) return Number.NaN;
+ if (/^\d{4}-\d{2}-\d{2}$/.test(value)) {
+ const start = new Date(`${value}T00:00:00Z`).getTime();
+ return upper ? start + DAY : start;
+ }
+ return new Date(value).getTime();
+}
+
+export function windowMillis(from, to) {
+ const start = boundaryMillis(from);
+ const end = boundaryMillis(to, true);
+ return Number.isFinite(start) && Number.isFinite(end) && start < end
+ ? { start, end, span: end - start }
+ : null;
+}
+
+export function initialWindow(extent) {
+ if (!extent?.from || !extent?.to) return { from: '', to: '' };
+ const first = new Date(extent.from).getTime();
+ const last = new Date(extent.to).getTime();
+ if (!Number.isFinite(first) || !Number.isFinite(last)) return { from: '', to: '' };
+ const span = Math.max(last - first, SECOND);
+ const padding = Math.max(span <= DAY ? SECOND : DAY, span * 0.035);
+ return { from: isoInstant(first - padding), to: isoInstant(last + padding) };
+}
+
+function rangeFromMillis(start, end) {
+ return { from: isoInstant(start), to: isoInstant(end) };
+}
+
+export function shiftWindow(from, to, fraction) {
+ const window = windowMillis(from, to);
+ if (!window) return { from, to };
+ const shift = window.span * fraction;
+ return rangeFromMillis(window.start + shift, window.end + shift);
+}
+
+export function zoomWindow(from, to, factor, anchor = 0.5) {
+ const window = windowMillis(from, to);
+ if (!window) return { from, to };
+ const nextSpan = Math.max(MIN_WINDOW, window.span * factor);
+ const pivot = window.start + window.span * clamp(anchor);
+ const start = pivot - nextSpan * clamp(anchor);
+ return rangeFromMillis(start, start + nextSpan);
+}
+
+/**
+ * The window in words, for the control that opens it.
+ *
+ * One reading replaces two date boxes on the toolbar: the boxes are how a window is
+ * *typed*, which is the rare act, and the frequent one is checking what is on screen.
+ * Read in the axis's own zone, so it agrees with the ticks under it.
+ */
+export function windowWords(from, to, zone = UTC) {
+ const window = windowMillis(from, to);
+ if (!window) return 'All dates';
+ const start = zonedFields(window.start, zone);
+ const end = zonedFields(window.end, zone);
+ const day = (at) => `${at.day} ${MONTHS[at.month - 1]}`;
+ const clock = (at) => `${pad(at.hour)}:${pad(at.minute)}`;
+ if (start.year === end.year && start.month === end.month && start.day === end.day) {
+ return `${day(start)} ${start.year}, ${clock(start)} – ${clock(end)}`;
+ }
+ // Under two days the hours are the point; above it they are noise, and the year is
+ // stated once unless the window crosses one.
+ if (window.span < 2 * DAY) {
+ return `${day(start)} ${clock(start)} – ${day(end)} ${clock(end)}`;
+ }
+ const left = start.year === end.year ? day(start) : `${day(start)} ${start.year}`;
+ return `${left} – ${day(end)} ${end.year}`;
+}
+
+/**
+ * The spans the window can be set to, widest last.
+ *
+ * They replace a pair of zoom buttons: pressing − four times to see a year is
+ * counting, and "Year" is the thing being asked for. A month and a year are the
+ * round numbers a viewport wants, not calendar arithmetic — the ticks handle the
+ * calendar.
+ */
+export const WINDOW_SPANS = [
+ { label: 'Hour', ms: HOUR },
+ { label: 'Day', ms: DAY },
+ { label: 'Week', ms: 7 * DAY },
+ { label: 'Month', ms: 30 * DAY },
+ { label: 'Year', ms: 365 * DAY },
+];
+
+/** Resize the window around its middle, which is what the analyst is looking at. */
+export function resizeWindow(from, to, span) {
+ const window = windowMillis(from, to);
+ if (!window) return { from, to };
+ return zoomWindow(from, to, span / window.span, 0.5);
+}
+
+export function windowInputValue(value, zone = UTC) {
+ const millis = boundaryMillis(value);
+ if (!Number.isFinite(millis)) return '';
+ if (!zone || zone === UTC) return new Date(millis).toISOString().slice(0, 19);
+ const at = zonedFields(millis, zone);
+ return (
+ `${pad(at.year, 4)}-${pad(at.month)}-${pad(at.day)}` +
+ `T${pad(at.hour)}:${pad(at.minute)}:${pad(at.second)}`
+ );
+}
+
+/** The other direction: the boundary control holds a wall clock, and which instant
+ * that names depends on the zone the axis is being read in. */
+export function inputWindowValue(value, zone = UTC) {
+ if (!value) return '';
+ const withSeconds = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}$/.test(value) ? `${value}:00` : value;
+ if (!zone || zone === UTC) return `${withSeconds}Z`;
+ const match = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})$/.exec(withSeconds);
+ if (!match) return '';
+ const [, year, month, day, hour, minute, second] = match.map(Number);
+ return isoInstant(
+ instantOf({ year, month, day, hour, minute, second }, zone)
+ );
+}
+
+export function timeAtRatio(from, to, ratio) {
+ const window = windowMillis(from, to);
+ if (!window) return '';
+ const milliseconds = window.start + window.span * clamp(ratio);
+ return isoInstant(Math.round(milliseconds / SECOND) * SECOND);
+}
+
+export function dateAtRatio(from, to, ratio) {
+ const instant = timeAtRatio(from, to, ratio);
+ return instant ? instant.slice(0, 10) : '';
+}
+
+export function draftWhen(from, to, startRatio, endRatio) {
+ const window = windowMillis(from, to);
+ if (!window) return '';
+ const low = Math.min(startRatio, endRatio);
+ const high = Math.max(startRatio, endRatio);
+ if (window.span <= 3 * DAY) {
+ const start = timeAtRatio(from, to, low);
+ const end = timeAtRatio(from, to, high);
+ return high - low < .004 ? start : `${start}/${end}`;
+ }
+ const a = dateAtRatio(from, to, low);
+ const b = dateAtRatio(from, to, high);
+ if (!a || !b) return '';
+ return a === b ? a : `${a}/${b}`;
+}
+
+const DATE_TOKEN = /^(\d{4})(?:-(\d{2})(?:-(\d{2}))?)?([~?%])?$/;
+const TIMESTAMP_TOKEN = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.(\d{1,6}))?(Z|([+-])(\d{2}):(\d{2}))?$/;
+
+function makeUtc(year, month, day) {
+ const value = new Date(0);
+ value.setUTCHours(0, 0, 0, 0);
+ value.setUTCFullYear(year, month - 1, day);
+ return value;
+}
+
+function validDateParts(year, month = 1, day = 1) {
+ if (year < 1 || year > 9998 || month < 1 || month > 12 || day < 1) return false;
+ const value = makeUtc(year, month, day);
+ return value.getUTCFullYear() === year && value.getUTCMonth() === month - 1 && value.getUTCDate() === day;
+}
+
+function dateBounds(match) {
+ const year = Number(match[1]);
+ const month = match[2] ? Number(match[2]) : 1;
+ const day = match[3] ? Number(match[3]) : 1;
+ if (!validDateParts(year, month, day)) return null;
+ const first = makeUtc(year, month, day);
+ const last = new Date(first);
+ if (match[3]) last.setUTCDate(last.getUTCDate() + 1);
+ else if (match[2]) last.setUTCMonth(last.getUTCMonth() + 1);
+ else last.setUTCFullYear(last.getUTCFullYear() + 1);
+ return { first: first.getTime(), last: last.getTime() };
+}
+
+function validateDate(raw) {
+ const match = DATE_TOKEN.exec(raw);
+ return match ? dateBounds(match) : null;
+}
+
+function validateTimestamp(raw) {
+ const match = TIMESTAMP_TOKEN.exec(raw);
+ if (!match) return false;
+ const [, year, month, day, hour, minute, second, , zone, , offsetHour, offsetMinute] = match;
+ if (!validDateParts(Number(year), Number(month), Number(day))) return false;
+ if (Number(hour) > 23 || Number(minute) > 59 || Number(second) > 59) return false;
+ if (zone && zone !== 'Z') {
+ const h = Number(offsetHour);
+ const m = Number(offsetMinute);
+ if (h > 14 || m > 59 || (h === 14 && m > 0)) return false;
+ }
+ return true;
+}
+
+function sortableTimestamp(raw) {
+ return validateTimestamp(raw) && /(Z|[+-]\d{2}:\d{2})$/.test(raw);
+}
+
+export function validateTemporalValue(raw) {
+ if (raw === '') return { valid: true, empty: true, error: '' };
+ if (typeof raw !== 'string' || raw !== raw.trim()) {
+ return { valid: false, empty: false, error: 'Remove spaces around the value.' };
+ }
+ if (!raw.includes('/')) {
+ const valid = Boolean(validateDate(raw)) || validateTimestamp(raw);
+ return {
+ valid,
+ empty: false,
+ error: valid ? '' : 'Use a supported date or timestamp.',
+ };
+ }
+ if (raw.split('/').length !== 2) {
+ return { valid: false, empty: false, error: 'A range needs two dates.' };
+ }
+ const [start, end] = raw.split('/');
+ const first = validateDate(start);
+ const last = validateDate(end);
+ if (first && last) {
+ if (first.first >= last.last) {
+ return { valid: false, empty: false, error: 'The end must come after the start.' };
+ }
+ return { valid: true, empty: false, error: '' };
+ }
+ if (!sortableTimestamp(start) || !sortableTimestamp(end)) {
+ return { valid: false, empty: false, error: 'Use two dates or two times with timezones.' };
+ }
+ if (new Date(start).getTime() >= new Date(end).getTime()) {
+ return { valid: false, empty: false, error: 'The end must come after the start.' };
+ }
+ return { valid: true, empty: false, error: '' };
+}
+
+function dateLabel(raw) {
+ const match = DATE_TOKEN.exec(raw);
+ if (!match) return raw;
+ const year = Number(match[1]);
+ if (!match[2]) return String(year);
+ const month = MONTHS[Number(match[2]) - 1];
+ if (!match[3]) return `${month} ${year}`;
+ return `${Number(match[3])} ${month} ${year}`;
+}
+
+function timestampLabel(raw) {
+ const match = TIMESTAMP_TOKEN.exec(raw);
+ if (!match) return raw;
+ const date = `${Number(match[3])} ${MONTHS[Number(match[2]) - 1]} ${match[1]}`;
+ const fraction = match[7] ? `.${match[7]}` : '';
+ const zone = match[8] === 'Z' ? ' UTC' : match[8] ? ` UTC${match[8]}` : ' local time';
+ return `${date}, ${match[4]}:${match[5]}:${match[6]}${fraction}${zone}`;
+}
+
+function qualifierLabels(raw) {
+ const labels = [];
+ if (raw.includes('~') || raw.includes('%')) labels.push('Approximate');
+ if (raw.includes('?') || raw.includes('%')) labels.push('Uncertain');
+ return labels;
+}
+
+export function formatTemporalValue(raw) {
+ const check = validateTemporalValue(raw ?? '');
+ if (!raw) return { ...check, label: 'Undated', qualifiers: [] };
+ if (!check.valid) return { ...check, label: raw, qualifiers: [] };
+ const parts = raw.split('/');
+ const label = parts.length === 2
+ ? `${DATE_TOKEN.test(parts[0]) ? dateLabel(parts[0]) : timestampLabel(parts[0])} to ${DATE_TOKEN.test(parts[1]) ? dateLabel(parts[1]) : timestampLabel(parts[1])}`
+ : DATE_TOKEN.test(raw) ? dateLabel(raw) : timestampLabel(raw);
+ return { ...check, label, qualifiers: qualifierLabels(raw) };
+}
+
+function moveDateToken(raw, deltaMs) {
+ const match = DATE_TOKEN.exec(raw);
+ if (!match) return null;
+ const marker = match[4] ?? '';
+ if (match[3]) {
+ const date = makeUtc(Number(match[1]), Number(match[2]), Number(match[3]));
+ date.setUTCDate(date.getUTCDate() + Math.round(deltaMs / DAY));
+ return `${isoDay(date)}${marker}`;
+ }
+ if (match[2]) {
+ const date = makeUtc(Number(match[1]), Number(match[2]), 1);
+ date.setUTCMonth(date.getUTCMonth() + Math.round(deltaMs / (DAY * 30.4375)));
+ return `${date.toISOString().slice(0, 7)}${marker}`;
+ }
+ const year = Number(match[1]) + Math.round(deltaMs / (DAY * 365.2425));
+ return year >= 1 && year <= 9998 ? `${String(year).padStart(4, '0')}${marker}` : null;
+}
+
+export function canDragTemporal(item) {
+ if (item?.category !== 'statement' || !item.raw) return false;
+ const parts = item.raw.split('/');
+ const dates = parts.every((part) => DATE_TOKEN.test(part));
+ const timestamps = parts.every((part) => sortableTimestamp(part));
+ return parts.length <= 2 && (dates || timestamps);
+}
+
+const bareDate = (part) => part.replace(/[~?%]$/, '');
+
+function ordered(parts) {
+ return parts.length < 2 || validateTemporalValue(parts.join('/')).valid;
+}
+
+function timestampOffset(raw) {
+ if (raw.endsWith('Z')) return { suffix: 'Z', minutes: 0 };
+ const match = raw.match(/([+-])(\d{2}):(\d{2})$/);
+ if (!match) return null;
+ const minutes = Number(match[2]) * 60 + Number(match[3]);
+ return { suffix: match[0], minutes: match[1] === '-' ? -minutes : minutes };
+}
+
+function shiftedTimestamp(raw, deltaMs) {
+ const match = TIMESTAMP_TOKEN.exec(raw);
+ const zone = timestampOffset(raw);
+ if (!match || !zone) return null;
+ const fraction = match[7] ?? '';
+ const resolution = fraction ? Math.max(1, 10 ** (3 - Math.min(3, fraction.length))) : SECOND;
+ const shifted = new Date(raw).getTime() + Math.round(deltaMs / resolution) * resolution;
+ if (!Number.isFinite(shifted)) return null;
+ const wall = new Date(shifted + zone.minutes * MINUTE);
+ const base = wall.toISOString().slice(0, 19);
+ let heldFraction = '';
+ if (fraction) {
+ const millis = String(wall.getUTCMilliseconds()).padStart(3, '0');
+ heldFraction = `.${fraction.length <= 3 ? millis.slice(0, fraction.length) : millis + fraction.slice(3)}`;
+ }
+ return `${base}${heldFraction}${zone.suffix}`;
+}
+
+function timestampAtZone(value, template) {
+ const millis = new Date(value).getTime();
+ const original = new Date(template).getTime();
+ return Number.isFinite(millis) && Number.isFinite(original)
+ ? shiftedTimestamp(template, millis - original)
+ : null;
+}
+
+export function moveTemporalRaw(item, deltaMs) {
+ if (!canDragTemporal(item)) return null;
+ const timestamp = item.raw.includes('T');
+ const parts = item.raw.split('/').map((part) => timestamp ? shiftedTimestamp(part, deltaMs) : moveDateToken(part, deltaMs));
+ if (parts.some((part) => part === null) || !ordered(parts)) return null;
+ return parts.join('/');
+}
+
+export function resizeTemporalRaw(item, edge, value) {
+ if (!canDragTemporal(item) || item.shape !== 'interval') return null;
+ const [start, end] = item.raw.split('/');
+ if (item.raw.includes('T')) {
+ const template = edge === 'start' ? start : end;
+ const restated = timestampAtZone(value, template);
+ if (!restated) return null;
+ const parts = edge === 'start' ? [restated, end] : [start, restated];
+ return ordered(parts) ? parts.join('/') : null;
+ }
+ if (!/^\d{4}-\d{2}-\d{2}$/.test(value)) return null;
+ const marker = (edge === 'start' ? start : end).match(/[~?%]$/)?.[0] ?? '';
+ const parts = edge === 'start' ? [`${value}${marker}`, end] : [start, `${value}${marker}`];
+ return ordered(parts) ? parts.join('/') : null;
+}
+
+export function nudgeTemporalRaw(item, mode, direction) {
+ if (!canDragTemporal(item) || ![-1, 1].includes(direction)) return null;
+ if (item.raw.includes('T')) {
+ if (mode === 'move') return moveTemporalRaw(item, SECOND * direction);
+ if (item.shape !== 'interval') return null;
+ const parts = item.raw.split('/');
+ const index = mode === 'start' ? 0 : 1;
+ parts[index] = shiftedTimestamp(parts[index], SECOND * direction);
+ return parts[index] && ordered(parts) ? parts.join('/') : null;
+ }
+ if (mode === 'move') {
+ const unit = item.raw.match(/^\d{4}(?!-)/) ? 365.2425 * DAY
+ : item.raw.match(/^\d{4}-\d{2}(?:[~?%]|\/|$)/) ? 30.4375 * DAY : DAY;
+ return moveTemporalRaw(item, unit * direction);
+ }
+ if (item.shape !== 'interval') return null;
+ const parts = item.raw.split('/');
+ const index = mode === 'start' ? 0 : 1;
+ const moved = moveDateToken(parts[index], DAY * direction);
+ if (!moved) return null;
+ parts[index] = moved;
+ return ordered(parts) ? parts.join('/') : null;
+}
+
+function itemBounds(item, window) {
+ const first = new Date(item.earliest).getTime();
+ const last = new Date(item.latest).getTime();
+ if (!Number.isFinite(first) || !Number.isFinite(last)) return null;
+ const left = clamp((first - window.start) / window.span);
+ const right = clamp((last - window.start) / window.span);
+ const midpoint = clamp(((first + last) / 2 - window.start) / window.span);
+ return { left, right: Math.max(left, right), midpoint };
+}
+
+function pointWidth(item) {
+ const date = formatTemporalValue(item.raw).label;
+ return clamp(Math.max(String(item.label ?? '').length * 5.45, date.length * 5.1) + 40, 82, 230);
+}
+
+/** Pack the rendered geometry, not just the instant anchoring each item. */
+export function layoutTimelineItems(items, from, to, axisWidth = 1000, maxItemRows = 6) {
+ const window = windowMillis(from, to);
+ if (!window) return { items: [], clusters: [], rows: 1 };
+ const width = Math.max(320, axisWidth);
+ const gap = 7 / width;
+ const lanes = [];
+ const placed = [];
+ const hidden = new Map();
+ const sorted = [...items].sort((a, b) =>
+ Number(Boolean(b.pinned)) - Number(Boolean(a.pinned))
+ || String(a.earliest).localeCompare(String(b.earliest))
+ || String(a.id).localeCompare(String(b.id))
+ );
+ for (const item of sorted) {
+ const bounds = itemBounds(item, window);
+ if (!bounds) continue;
+ const interval = item.shape === 'interval';
+ const left = interval ? bounds.left : bounds.midpoint;
+ const displayWidth = interval
+ ? Math.max(28, (bounds.right - bounds.left) * width)
+ : pointWidth(item);
+ const endAligned = !interval && bounds.midpoint > 0.82;
+ const visualLeft = interval ? left : endAligned
+ ? left - (displayWidth - 8) / width
+ : left - 8 / width;
+ const visualRight = interval ? left + displayWidth / width : endAligned
+ ? left + 8 / width
+ : left + (displayWidth - 8) / width;
+ let lane = lanes.findIndex((end) => end + gap < visualLeft);
+ if (lane === -1 && (lanes.length < maxItemRows || item.pinned)) {
+ lane = lanes.length;
+ lanes.push(visualRight);
+ } else if (lane !== -1) {
+ lanes[lane] = visualRight;
+ } else {
+ const bucket = Math.floor(clamp(bounds.midpoint, 0, 0.9999) * width / 88);
+ const group = hidden.get(bucket) ?? { count: 0, items: [], midpoint: bounds.midpoint };
+ group.count += 1;
+ group.items.push(item);
+ group.midpoint = (group.midpoint * (group.count - 1) + bounds.midpoint) / group.count;
+ hidden.set(bucket, group);
+ continue;
+ }
+ placed.push({
+ ...item,
+ lane,
+ left: left * 100,
+ width: (displayWidth / width) * 100,
+ displayWidth,
+ endAligned,
+ haloLeft: bounds.left * 100,
+ haloWidth: Math.max(0, (bounds.right - bounds.left) * 100),
+ });
+ }
+ const clusters = [...hidden.entries()].map(([bucket, group]) => ({
+ id: `cluster:${bucket}`,
+ lane: Math.max(maxItemRows, lanes.length),
+ left: group.midpoint * 100,
+ count: group.count,
+ items: group.items,
+ earliest: group.items[0]?.earliest ?? '',
+ }));
+ return {
+ items: placed,
+ clusters,
+ rows: Math.max(1, lanes.length + (clusters.length ? 1 : 0)),
+ };
+}
+
+const TICK_STEPS = [
+ ['second', 1, SECOND], ['second', 5, 5 * SECOND], ['second', 10, 10 * SECOND],
+ ['second', 30, 30 * SECOND], ['minute', 1, MINUTE], ['minute', 5, 5 * MINUTE],
+ ['minute', 15, 15 * MINUTE], ['minute', 30, 30 * MINUTE], ['hour', 1, HOUR],
+ ['hour', 3, 3 * HOUR], ['hour', 6, 6 * HOUR], ['hour', 12, 12 * HOUR],
+ ['day', 1, DAY], ['day', 2, 2 * DAY], ['day', 7, 7 * DAY], ['day', 14, 14 * DAY],
+ ['month', 1, 30.4375 * DAY], ['month', 3, 91.3125 * DAY], ['month', 6, 182.625 * DAY],
+ ['year', 1, 365.25 * DAY], ['year', 2, 730.5 * DAY], ['year', 5, 1826.25 * DAY],
+ ['year', 10, 3652.5 * DAY], ['year', 25, 9131.25 * DAY], ['year', 50, 18262.5 * DAY],
+ ['year', 100, 36525 * DAY],
+].map(([unit, step, ms]) => ({ unit, step, ms }));
+
+function tickChoice(span, width = 1000) {
+ const target = clamp(Math.round(width / 100), 8, 12);
+ return TICK_STEPS.reduce((best, choice) => {
+ const distance = Math.abs(span / choice.ms - target);
+ return distance < best.distance ? { choice, distance } : best;
+ }, { choice: TICK_STEPS.at(-1), distance: Infinity }).choice;
+}
+
+/** A whole number of local days added to a date, normalised through UTC so a month
+ * end and a leap day are the calendar's problem rather than this file's. */
+function addDays(fields, count) {
+ const date = new Date(fieldsToUtc({ ...fields, hour: 0, minute: 0, second: 0 }));
+ date.setUTCDate(date.getUTCDate() + count);
+ return {
+ year: date.getUTCFullYear(),
+ month: date.getUTCMonth() + 1,
+ day: date.getUTCDate(),
+ hour: 0,
+ minute: 0,
+ second: 0,
+ };
+}
+
+/**
+ * Where the first tick falls, as an instant.
+ *
+ * Aligned to an anchor that does not depend on the window, or the ticks would slide
+ * under a pan: a year to a multiple of the step, a month to an absolute month
+ * number, a day to a local day number, and anything shorter to a multiple of its own
+ * length off the zone's midnight.
+ */
+function alignTick(window, choice, zone) {
+ const at = zonedFields(window.start, zone);
+ if (choice.unit === 'year') {
+ const year = Math.ceil(at.year / choice.step) * choice.step;
+ return instantOf({ year, month: 1, day: 1 }, zone);
+ }
+ if (choice.unit === 'month') {
+ const absolute = at.year * 12 + (at.month - 1);
+ const aligned = Math.ceil(absolute / choice.step) * choice.step;
+ return instantOf(
+ { year: Math.floor(aligned / 12), month: (aligned % 12) + 1, day: 1 },
+ zone,
+ );
+ }
+ const shift = zoneOffset(window.start, zone);
+ if (choice.unit === 'day') {
+ const days = Math.ceil((window.start + shift) / DAY / choice.step) * choice.step;
+ const midnight = new Date(days * DAY);
+ return instantOf(
+ {
+ year: midnight.getUTCFullYear(),
+ month: midnight.getUTCMonth() + 1,
+ day: midnight.getUTCDate(),
+ },
+ zone,
+ );
+ }
+ return Math.ceil((window.start + shift) / choice.ms) * choice.ms - shift;
+}
+
+function advanceTick(millis, choice, zone) {
+ if (choice.unit === 'year' || choice.unit === 'month') {
+ const at = zonedFields(millis, zone);
+ const absolute =
+ at.year * 12 + (at.month - 1) + (choice.unit === 'year' ? choice.step * 12 : choice.step);
+ return instantOf(
+ { year: Math.floor(absolute / 12), month: (absolute % 12) + 1, day: 1 },
+ zone,
+ );
+ }
+ if (choice.unit === 'day') {
+ return instantOf(addDays(zonedFields(millis, zone), choice.step), zone);
+ }
+ return millis + choice.ms;
+}
+
+function tickLabel(millis, unit, zone) {
+ const at = zonedFields(millis, zone);
+ if (unit === 'year') return String(at.year);
+ if (unit === 'month') return `${MONTHS[at.month - 1]} ${at.year}`;
+ if (unit === 'day') return `${at.day} ${MONTHS[at.month - 1]}`;
+ // An hour tick is on the hour in UTC and on the half hour in a zone whose offset
+ // is not a whole one, so the minutes are printed rather than assumed to be zero.
+ if (unit === 'hour') return `${pad(at.hour)}:${pad(at.minute)}`;
+ if (unit === 'minute') return `${pad(at.hour)}:${pad(at.minute)}`;
+ return `${pad(at.minute)}:${pad(at.second)}`;
+}
+
+function generateTicks(window, choice, labelled, zone) {
+ let cursor = alignTick(window, choice, zone);
+ const ticks = [];
+ for (let guard = 0; cursor <= window.end && guard < 500; guard++) {
+ if (cursor >= window.start) {
+ ticks.push({
+ at: new Date(cursor).toISOString(),
+ left: ((cursor - window.start) / window.span) * 100,
+ label: labelled ? tickLabel(cursor, choice.unit, zone) : '',
+ });
+ }
+ const next = advanceTick(cursor, choice, zone);
+ // A calendar step that fails to move — an hour a zone skipped, a guard against
+ // any future unit — would spin the loop out on its own guard instead of drawing.
+ if (next <= cursor) break;
+ cursor = next;
+ }
+ return ticks;
+}
+
+export function axisTicks(from, to, width = 1000, zone = UTC) {
+ const window = windowMillis(from, to);
+ return window ? generateTicks(window, tickChoice(window.span, width), true, zone) : [];
+}
+
+export function axisMinorTicks(from, to, width = 1000, zone = UTC) {
+ const window = windowMillis(from, to);
+ if (!window) return [];
+ const major = tickChoice(window.span, width);
+ const index = TICK_STEPS.indexOf(major);
+ const minor = TICK_STEPS[Math.max(0, index - 1)];
+ if (window.span / minor.ms > 64 || minor === major) return [];
+ const majorTimes = new Set(generateTicks(window, major, false, zone).map((tick) => tick.at));
+ return generateTicks(window, minor, false, zone).filter((tick) => !majorTimes.has(tick.at));
+}
+
+export function axisScale(from, to, width = 1000) {
+ const window = windowMillis(from, to);
+ if (!window) return '';
+ const unit = tickChoice(window.span, width).unit;
+ return `${unit[0].toUpperCase()}${unit.slice(1)}s`;
+}
+
+export function axisBands(from, to, width = 1000, zone = UTC) {
+ const window = windowMillis(from, to);
+ if (!window) return [];
+ const unit = tickChoice(window.span, width).unit;
+ const bandUnit = ['second', 'minute', 'hour'].includes(unit) ? 'day' : unit === 'day' ? 'month' : 'year';
+ const at = zonedFields(window.start, zone);
+ // The band a window opens inside starts before it, so it is floored rather than
+ // aligned: half a day at the left edge is still that day.
+ let head =
+ bandUnit === 'day'
+ ? { year: at.year, month: at.month, day: at.day }
+ : bandUnit === 'month'
+ ? { year: at.year, month: at.month, day: 1 }
+ : { year: at.year, month: 1, day: 1 };
+ const bands = [];
+ for (let guard = 0; guard < 200; guard++) {
+ const cursor = instantOf(head, zone);
+ if (cursor >= window.end) break;
+ const after =
+ bandUnit === 'day'
+ ? addDays(head, 1)
+ : bandUnit === 'month'
+ ? { year: head.month === 12 ? head.year + 1 : head.year, month: head.month === 12 ? 1 : head.month + 1, day: 1 }
+ : { year: head.year + 1, month: 1, day: 1 };
+ const next = instantOf(after, zone);
+ const start = Math.max(cursor, window.start);
+ const end = Math.min(next, window.end);
+ const label = bandUnit === 'day'
+ ? `${head.day} ${MONTHS[head.month - 1]} ${head.year}`
+ : bandUnit === 'month' ? `${MONTHS[head.month - 1]} ${head.year}`
+ : String(head.year);
+ if (end > start) {
+ bands.push({
+ label,
+ left: ((start - window.start) / window.span) * 100,
+ width: ((end - start) / window.span) * 100,
+ });
+ }
+ if (next <= cursor) break;
+ head = after;
+ }
+ return bands;
+}
+
+export function nowPosition(from, to, now = Date.now()) {
+ const window = windowMillis(from, to);
+ return window && now >= window.start && now <= window.end
+ ? ((now - window.start) / window.span) * 100
+ : null;
+}
+
+/** The instants a bucket key opens and closes: `2026`, `2026-08`, `2026-08-02`, `2026-08-02T14`. */
+function bucketBounds(start) {
+ const tail = { 4: '-01-01T00:00:00Z', 7: '-01T00:00:00Z', 10: 'T00:00:00Z', 13: ':00:00Z' };
+ const suffix = tail[String(start ?? '').length];
+ if (suffix === undefined) return null;
+ const first = new Date(`${start}${suffix}`);
+ if (!Number.isFinite(first.getTime())) return null;
+ const last = new Date(first);
+ if (start.length === 4) last.setUTCFullYear(last.getUTCFullYear() + 1);
+ else if (start.length === 7) last.setUTCMonth(last.getUTCMonth() + 1);
+ else if (start.length === 10) last.setUTCDate(last.getUTCDate() + 1);
+ else last.setUTCHours(last.getUTCHours() + 1);
+ return { first: first.getTime(), last: last.getTime() };
+}
+
+/**
+ * Where clicking a bar takes the axis: onto what that bar holds.
+ *
+ * The entries themselves rather than the period they were counted under, so the
+ * window the click opens is the one the bar draws — landing on the period would put
+ * six entries from the first week of August under a window a month wide, and the
+ * brush would come to rest somewhere other than on the bar that was clicked. A margin
+ * on each side keeps the outermost entry off the very edge of the axis.
+ */
+export function bucketWindow(bucket) {
+ const held = typeof bucket === 'string' ? null : bucketSpan(bucket);
+ const start = typeof bucket === 'string' ? bucket : bucket?.start ?? '';
+ if (held && held.last > held.first) {
+ const margin = (held.last - held.first) * 0.06;
+ return rangeFromMillis(held.first - margin, held.last + margin);
+ }
+ if (held) return rangeFromMillis(held.first - 12 * HOUR, held.first + 12 * HOUR);
+ const bounds = bucketBounds(start);
+ if (!bounds) return null;
+ if (start.length === 10) return rangeFromMillis(bounds.first - 3 * DAY, bounds.first + 4 * DAY);
+ return rangeFromMillis(bounds.first, bounds.last);
+}
+
+/**
+ * How tall a bucket's column stands, against the fullest one.
+ *
+ * On the square root of the share rather than the share itself: a scraped batch puts
+ * two hundred entries in one week and the rest of the case holds ones and twos, and
+ * read straight those all sit on the floor together, indistinguishable. The exact
+ * count is a hover away, which is what the minimap says it is for.
+ */
+export function bucketScale(buckets) {
+ const max = Math.max(1, ...buckets.map((bucket) => bucket.count));
+ return buckets.map((bucket) => ({
+ ...bucket,
+ height: Math.max(12, Math.sqrt(Math.max(0, bucket.count) / max) * 100),
+ }));
+}
+
+/**
+ * Where a bucket's entries actually sit, which is what its bar is drawn across.
+ *
+ * The period a bucket is named after is the coarse thing: six rows in the first week
+ * of August are not "August". The server reports the inner span with the counts, so a
+ * bar marks the days something happened on. The period is the fallback for a reading
+ * that predates that — a captured snapshot, mostly.
+ */
+export function bucketSpan(bucket) {
+ const first = new Date(bucket?.first ?? '').getTime();
+ const last = new Date(bucket?.last ?? '').getTime();
+ if (Number.isFinite(first)) {
+ return { first, last: Number.isFinite(last) && last > first ? last : first };
+ }
+ const bounds = bucketBounds(bucket?.start);
+ return bounds ? { first: bounds.first, last: bounds.last } : null;
+}
+
+/**
+ * The instants the overview draws between: the whole of what the case holds.
+ *
+ * The bars, the date scale and the visible-range brush are all placed on this one
+ * mapping from instant to position, which is the only way the three can agree. Held
+ * as the union of the extent and every bar, so nothing the overview draws can fall
+ * off the end of the scale it is drawn on.
+ */
+export function densityScale(buckets, extent) {
+ const from = new Date(extent?.from ?? '').getTime();
+ const to = new Date(extent?.to ?? '').getTime();
+ const bins = (buckets ?? []).map((bucket) => bucketBounds(bucket?.start)).filter(Boolean);
+ const starts = [...bins.map((bin) => bin.first), ...(Number.isFinite(from) ? [from] : [])];
+ const ends = [...bins.map((bin) => bin.last), ...(Number.isFinite(to) ? [to] : [])];
+ if (!starts.length || !ends.length) return null;
+ const start = Math.min(...starts);
+ const end = Math.max(...ends);
+ return end > start ? { first: start, last: end, span: end - start } : null;
+}
+
+/**
+ * One column per bin, across the bin it counts.
+ *
+ * A histogram's columns are as wide as its bins, which is what makes the heights
+ * comparable — and it is honest here only because the bins are cut fine enough to be
+ * columns (`densityUnit`). Cut coarse, the same rule drew a month-wide block for six
+ * entries in one week, and a mark at the month's opening claimed a date nothing
+ * happened on: a January bucket holding the 14th and the 27th marked the 1st, ahead
+ * of a window that opened on the 6th, so the bar for two entries on screen sat
+ * outside the brush that was showing them.
+ */
+export function layoutDensityBuckets(buckets, extent) {
+ const scale = densityScale(buckets, extent);
+ if (!scale) return [];
+ const { first, span } = scale;
+ return bucketScale(buckets).flatMap((bucket) => {
+ const bounds = bucketBounds(bucket.start);
+ if (!bounds) return [];
+ const left = clamp((bounds.first - first) / span) * 100;
+ const right = clamp((bounds.last - first) / span) * 100;
+ // A bin thinner than a hairline still has to be visible; the floor is a
+ // `min-width` in the stylesheet, so the geometry here stays honest.
+ return [{ ...bucket, left, width: right - left }];
+ });
+}
+
+function stepPeriod(millis, unit) {
+ const at = new Date(millis);
+ if (unit === 'year') at.setUTCFullYear(at.getUTCFullYear() + 1);
+ else if (unit === 'month') at.setUTCMonth(at.getUTCMonth() + 1);
+ else if (unit === 'hour') at.setUTCHours(at.getUTCHours() + 1);
+ else at.setUTCDate(at.getUTCDate() + 1);
+ return at.getTime();
+}
+
+function floorPeriod(millis, unit) {
+ const at = new Date(millis);
+ if (unit === 'hour') at.setUTCMinutes(0, 0, 0);
+ else at.setUTCHours(0, 0, 0, 0);
+ if (unit === 'month' || unit === 'year') at.setUTCDate(1);
+ if (unit === 'year') at.setUTCMonth(0);
+ return at.getTime();
+}
+
+/**
+ * How finely to cut the overview, so it reads as a histogram rather than as a stroke.
+ *
+ * The finest cut whose bins still have a column's width on screen. Cut by the period
+ * a case happens to span — months, because the case runs over months — every bar was
+ * a month wide, and two hundred entries in one week drew the same mark as one entry
+ * that could be anywhere in May. Counted by day instead, that week is five columns
+ * and May is one, which is the shape the case actually has.
+ */
+export function densityUnit(extent, width = 800) {
+ const first = new Date(extent?.from ?? '').getTime();
+ const last = new Date(extent?.to ?? '').getTime();
+ if (!Number.isFinite(first) || !Number.isFinite(last) || last <= first) return 'day';
+ const span = last - first;
+ // Around two pixels a bin — the floor the stylesheet gives a column — held between
+ // a readable minimum and the server's ceiling on how many buckets a reading carries.
+ const room = Math.min(500, Math.max(60, Math.round(width / 2)));
+ for (const [unit, length] of [['hour', HOUR], ['day', DAY], ['month', 28 * DAY]]) {
+ if (span / length <= room) return unit;
+ }
+ return 'year';
+}
+
+/** Room for the longest label a scale prints, so two never land on each other. */
+const TICK_ROOM = 56;
+
+/**
+ * The scale under the minimap: one slot per period, named in the middle of its own.
+ *
+ * A bucket counts a period rather than an instant, so its name belongs under the
+ * middle of the block that draws it. Named at the instant the period opens — which is
+ * how the continuous ruler on the axis is labelled, and the wrong rule here — every
+ * name sat to the right of the bar it named, and the reader had to pair each block
+ * with the label after it.
+ *
+ * Only as many names as fit, so two years of months read as a scale rather than a
+ * crowd; the unnamed slots still carry their share of the width. Read in UTC because
+ * that is how the buckets themselves are cut, and naming them in another zone would
+ * rename them.
+ */
+export function densityTicks(buckets, extent, width = 800) {
+ const scale = densityScale(buckets, extent);
+ if (!scale) return [];
+ // Its own unit, not the bins': the bins are cut as fine as they can be drawn, and a
+ // scale reading "3 Jan, 4 Jan, 5 Jan…" across eight months would name the columns
+ // rather than the case. Months for a case that runs over months, hours for a day.
+ const unit = scale.span <= 2 * DAY ? 'hour'
+ : scale.span <= 62 * DAY ? 'day'
+ : scale.span <= 6 * 365 * DAY ? 'month' : 'year';
+ const slots = [];
+ // Floored to the period the scale opens inside, so the slots are whole calendar
+ // months rather than months counted from whatever day the case starts on. The two
+ // outermost are clipped to the scale, which is what a period the case only holds
+ // part of looks like.
+ let cursor = floorPeriod(scale.first, unit);
+ for (let guard = 0; cursor < scale.last && guard < 400; guard++) {
+ const next = stepPeriod(cursor, unit);
+ if (next <= cursor) break;
+ slots.push({
+ at: cursor,
+ first: Math.max(cursor, scale.first),
+ last: Math.min(next, scale.last),
+ });
+ cursor = next;
+ }
+ if (!slots.length) return [];
+ const every = Math.max(1, Math.ceil(TICK_ROOM / Math.max(1, width / slots.length)));
+ const last = slots.length - 1 - ((slots.length - 1) % every);
+ let named = '';
+ return slots.map((slot, index) => {
+ const at = zonedFields(slot.at, UTC);
+ const year = String(at.year);
+ const names = index % every === 0;
+ // The wider unit is stated when it changes, not on every slot: eight months in one
+ // year do not need the year eight times, and the hours of one day need its date
+ // once.
+ const context = unit === 'hour' ? `${at.day} ${MONTHS[at.month - 1]}` : year;
+ const label = !names ? ''
+ : unit === 'year' ? year
+ : unit === 'hour'
+ ? (context === named ? `${pad(at.hour)}:00` : `${pad(at.hour)}:00 · ${context}`)
+ : unit === 'day' ? `${at.day} ${MONTHS[at.month - 1]}`
+ : year === named ? MONTHS[at.month - 1] : `${MONTHS[at.month - 1]} ${year}`;
+ if (names) named = context;
+ return {
+ key: String(slot.at),
+ left: ((slot.first - scale.first) / scale.span) * 100,
+ width: ((slot.last - slot.first) / scale.span) * 100,
+ label,
+ // The outermost names are pinned to their own edge instead of centred, so a
+ // label wider than its slot leans inward rather than off the minimap.
+ anchor: !names ? '' : index === 0 ? 'start' : index === last ? 'end' : 'middle',
+ };
+ });
+}
+
+/**
+ * Spans of absolute time as bands across the visible window.
+ *
+ * Used for the daylight ribbon (`/api/geo/daylight`), and it is deliberately not
+ * zone-aware: when the sun was up is a fact about instants, so it is placed on the
+ * axis the same way whichever clock the axis is labelled with. Clipped rather than
+ * dropped, so the run that opens before the window still fills the left edge.
+ */
+export function ribbonBands(spans, from, to) {
+ const window = windowMillis(from, to);
+ if (!window || !Array.isArray(spans)) return [];
+ const bands = [];
+ for (const span of spans) {
+ const first = new Date(span?.from ?? '').getTime();
+ const last = new Date(span?.to ?? '').getTime();
+ if (!Number.isFinite(first) || !Number.isFinite(last)) continue;
+ const left = clamp((first - window.start) / window.span);
+ const right = clamp((last - window.start) / window.span);
+ if (right <= left) continue;
+ bands.push({ key: span.from, left: left * 100, width: (right - left) * 100 });
+ }
+ return bands;
+}
+
+// ── how far apart two entries are ────────────────────────────────────────────
+//
+// The one figure a chronology is read for and the one it never printed: an axis
+// shows that two things are near each other, and the finding is *four hours and
+// twelve minutes*, measured by hand off two tooltips.
+//
+// It is arithmetic over the **bounds the case derived**, never over the words a
+// source used, and that is what keeps it honest. A stated day is a window a day
+// wide (``engine/temporal``: bounds are half-open, ``earliest`` inclusive and
+// ``latest`` exclusive), so two dated statements are not a number apart — they are a
+// *range* apart, and printing the difference of the two midnights as a fact is how a
+// chronology ends up claiming precision nobody has. Two exact timestamps do give one
+// number, and then it is given.
+
+/** The window an entry occupies, or null when it has no place on the axis. */
+export function itemWindow(item) {
+ const first = new Date(item?.earliest ?? '').getTime();
+ const last = new Date(item?.latest ?? '').getTime();
+ if (!Number.isFinite(first) || !Number.isFinite(last)) return null;
+ return { first, last: Math.max(first, last) };
+}
+
+/** Whether a window is tight enough to be read as one instant. A second-precision
+ * timestamp carries a one-second window, which is a point for every purpose here. */
+const isInstant = (window) => window.last - window.first <= SECOND;
+
+/**
+ * How much of an entry's width is *not knowing*, as opposed to lasting.
+ *
+ * The distinction the gap arithmetic turns on. A point dated to the day is a day-wide
+ * window of ignorance, and everything measured from it inherits that. An interval's
+ * two bounds are what the analyst stated its extent to be — vagueness about either
+ * end is carried by the value's own `~`/`?` qualifier, which the panel shows
+ * separately — so its edges are taken as given. Without this, two exact periods four
+ * hours apart came back as "between 2 h and 12 h", which is the invented uncertainty
+ * this whole file exists to avoid.
+ */
+function slackOf(item, window) {
+ if (item?.shape === 'interval') return 0;
+ const width = window.last - window.first;
+ return width <= SECOND ? 0 : width;
+}
+
+/**
+ * What an entry's own width means: a period lasts, a point is merely imprecise.
+ *
+ * The distinction the panel exists to keep: *this closure ran for three days* and
+ * *this photo is dated to some point in one day* are the same three-day-ish number on
+ * screen and opposite readings of the case.
+ */
+export function itemExtent(item) {
+ const window = itemWindow(item);
+ if (!window) return null;
+ const ms = window.last - window.first;
+ if (item.shape === 'interval') return { ms, kind: 'duration', precision: item.precision ?? '' };
+ if (isInstant(window)) return null;
+ return { ms, kind: 'precision', precision: item.precision ?? '' };
+}
+
+/**
+ * Where two entries stand relative to each other.
+ *
+ * ``gap.min``/``gap.max`` bracket what the bounds allow, ``gap.stated`` is the
+ * difference between the two values as written, and ``gap.exact`` says whether the
+ * three are the same number. Overlapping windows report the overlap and refuse to
+ * order the pair: either could be first, and saying which would be invention.
+ */
+export function compareTimelineItems(a, b) {
+ const one = itemWindow(a);
+ const other = itemWindow(b);
+ if (!one || !other || a?.id === b?.id) return null;
+ const forwards = one.first <= other.first;
+ const [early, late] = forwards ? [one, other] : [other, one];
+ const [earlyItem, lateItem] = forwards ? [a, b] : [b, a];
+ const apart = early.last <= late.first;
+ // Measured from where the first one **ends** to where the second one **starts**,
+ // which is the same thing as instant-to-instant once both are points, and the only
+ // right reading once either is a period.
+ const slack = { early: slackOf(earlyItem, early), late: slackOf(lateItem, late) };
+ const ends = early.first + (earlyItem.shape === 'interval' ? early.last - early.first : 0);
+ return {
+ order: apart ? 'sequence' : 'overlap',
+ earlier: earlyItem,
+ later: lateItem,
+ gap: apart
+ ? {
+ min: Math.max(0, late.first - early.last),
+ max: late.first + slack.late - ends,
+ // As the two values were written, ignoring what each one leaves open. Only
+ // ever shown beside a range, and there it is the number the analyst expects
+ // to see: the difference between the two dates on the page.
+ stated: late.first - ends,
+ exact: !slack.early && !slack.late,
+ }
+ : null,
+ overlap: apart ? null : Math.min(early.last, late.last) - late.first,
+ extents: [
+ { item: earlyItem, extent: itemExtent(earlyItem) },
+ { item: lateItem, extent: itemExtent(lateItem) },
+ ].filter((row) => row.extent),
+ };
+}
+
+const SPAN_UNITS = [
+ { ms: 365.2425 * DAY, word: 'year' },
+ { ms: DAY, word: 'day' },
+ { ms: HOUR, word: 'hour' },
+ { ms: MINUTE, word: 'minute' },
+ { ms: SECOND, word: 'second' },
+];
+
+/**
+ * A length of time as its parts: at most two, largest first.
+ *
+ * Two rather than all of them because the second one is where the reading stops being
+ * useful: *2 days 6 hours* is a fact and *2 days 6 hours 14 minutes 3 seconds* is a
+ * serial number.
+ */
+function spanParts(ms) {
+ const total = Math.max(0, Math.round(Number(ms) || 0));
+ const parts = [];
+ let rest = total;
+ for (const unit of SPAN_UNITS) {
+ if (parts.length === 2) break;
+ const count = Math.floor(rest / unit.ms);
+ if (!count && !parts.length) continue;
+ if (!count) break;
+ parts.push({ count, word: unit.word });
+ rest -= count * unit.ms;
+ }
+ return parts;
+}
+
+/** Words, not symbols. A panel that reads *2 d 6 h* is a panel written for whoever
+ * already knew what it said. */
+const spanWords = (parts) =>
+ parts.map(({ count, word }) => `${count} ${word}${count === 1 ? '' : 's'}`).join(' ');
+
+/** A length of time in plain words, or an honest shrug under one second. */
+export function formatSpan(ms) {
+ const parts = spanParts(ms);
+ return parts.length ? spanWords(parts) : 'under a second';
+}
+
+/**
+ * A gap the dates only pin down to a range, as one phrase.
+ *
+ * *Between 2 and 4 days* rather than *2 days to 4 days*: the unit is factored out when
+ * both ends land on the same one, which is the common case and the only version that
+ * reads like a sentence. A minimum of nothing is not a range at all — *up to 4 days*
+ * is what two consecutive dates actually license, where "between 0 and 4" invites the
+ * reader to average it.
+ */
+export function formatSpanRange(min, max) {
+ const low = spanParts(min);
+ const high = spanParts(max);
+ if (!low.length) return `up to ${formatSpan(max)}`;
+ if (low.length === 1 && high.length === 1 && low[0].word === high[0].word) {
+ return `between ${low[0].count} and ${spanWords(high)}`;
+ }
+ return `between ${spanWords(low)} and ${spanWords(high)}`;
+}
+
+/** How coarse a value is, in the words the panel uses for it. */
+const PRECISION_READS = {
+ year: 'to the year',
+ month: 'to the month',
+ day: 'to the day',
+ second: 'to the second',
+ subsecond: 'to the fraction',
+ mixed: 'unevenly',
+};
+
+/**
+ * The pair as the inspector reads it out: one headline, one supporting clause and
+ * the notes that stop the headline being read as more than it is.
+ *
+ * The wording lives here rather than in the component for the reason every other
+ * count in this app states its own caveat: a figure printed bare is true and
+ * misleading in the same breath.
+ */
+export function describePair(a, b) {
+ const read = compareTimelineItems(a, b);
+ if (!read) {
+ return {
+ ok: false,
+ headline: 'Nothing to measure',
+ detail: 'One of these two has no place on the UTC axis.',
+ notes: [],
+ extents: [],
+ };
+ }
+ const notes = read.extents.map(({ item, extent }) =>
+ extent.kind === 'duration'
+ ? `${item.label} runs for ${formatSpan(extent.ms)}.`
+ : `${item.label} is dated ${PRECISION_READS[extent.precision] ?? 'coarsely'}.`
+ );
+ if (read.order === 'overlap') {
+ return {
+ ok: true,
+ headline: read.overlap > 0 ? `Overlapping by ${formatSpan(read.overlap)}` : 'Overlapping',
+ detail: 'Either could come first, so these dates do not order them.',
+ notes,
+ extents: read.extents,
+ };
+ }
+ const { min, max, stated, exact } = read.gap;
+ const first = `${read.earlier.label} first`;
+ if (exact) {
+ return {
+ ok: true,
+ headline: stated === 0 ? 'At the same instant' : `${formatSpan(stated)} apart`,
+ detail: stated === 0 ? 'Both are the same timestamp.' : first,
+ notes,
+ extents: read.extents,
+ };
+ }
+ const range = formatSpanRange(min <= SECOND ? 0 : min, max);
+ return {
+ ok: true,
+ // Capitalised here rather than in the phrase, which is also read mid-sentence.
+ headline: `${range[0].toUpperCase()}${range.slice(1)} apart`,
+ detail: first,
+ notes: [`As written, ${formatSpan(stated)} apart.`, ...notes],
+ extents: read.extents,
+ };
+}
diff --git a/frontend/src/lib/timeline.test.js b/frontend/src/lib/timeline.test.js
new file mode 100644
index 0000000..8c5924a
--- /dev/null
+++ b/frontend/src/lib/timeline.test.js
@@ -0,0 +1,537 @@
+import { describe, expect, it } from 'vitest';
+import {
+ DAY,
+ HOUR,
+ WINDOW_SPANS,
+ axisBands,
+ axisMinorTicks,
+ axisScale,
+ axisTicks,
+ bucketScale,
+ bucketSpan,
+ bucketWindow,
+ densityScale,
+ densityTicks,
+ densityUnit,
+ compareTimelineItems,
+ dateAtRatio,
+ describePair,
+ draftWhen,
+ formatSpan,
+ formatSpanRange,
+ formatTemporalValue,
+ initialWindow,
+ UTC,
+ inputWindowValue,
+ instantOf,
+ itemExtent,
+ offsetLabel,
+ layoutDensityBuckets,
+ layoutTimelineItems,
+ moveTemporalRaw,
+ nudgeTemporalRaw,
+ resizeTemporalRaw,
+ resizeWindow,
+ shiftWindow,
+ timeAtRatio,
+ validateTemporalValue,
+ windowInputValue,
+ windowWords,
+ worldZones,
+ zoneMatches,
+ zoneOffset,
+ zoneWords,
+ zonedFields,
+ zoomWindow,
+} from './timeline.js';
+
+describe('timeline window', () => {
+ it('keeps exact UTC boundaries while moving and zooming', () => {
+ expect(initialWindow({
+ from: '2026-08-10T00:00:00Z',
+ to: '2026-08-13T00:00:00Z',
+ })).toEqual({ from: '2026-08-09T00:00:00Z', to: '2026-08-14T00:00:00Z' });
+ expect(shiftWindow('2026-08-01', '2026-08-10', 1)).toEqual({
+ from: '2026-08-11T00:00:00Z', to: '2026-08-21T00:00:00Z',
+ });
+ expect(zoomWindow('2026-08-01T00:00:00Z', '2026-08-11T00:00:00Z', .5)).toEqual({
+ from: '2026-08-03T12:00:00Z', to: '2026-08-08T12:00:00Z',
+ });
+ });
+
+ it('round-trips second-level range controls as UTC', () => {
+ expect(windowInputValue('2026-08-11T18:40:12Z')).toBe('2026-08-11T18:40:12');
+ expect(inputWindowValue('2026-08-11T18:40')).toBe('2026-08-11T18:40:00Z');
+ expect(inputWindowValue('2026-08-11T18:40:12')).toBe('2026-08-11T18:40:12Z');
+ });
+
+ it('preserves date precision and qualifiers during direct edits', () => {
+ expect(moveTemporalRaw({ category: 'statement', raw: '2026-08~' }, 31 * DAY)).toBe('2026-09~');
+ expect(moveTemporalRaw({ category: 'statement', raw: '2026-08-11/2026-08-13', shape: 'interval' }, 2 * DAY)).toBe('2026-08-13/2026-08-15');
+ expect(resizeTemporalRaw({ category: 'statement', raw: '2026-08-11~/2026-08-13?', shape: 'interval' }, 'end', '2026-08-16')).toBe('2026-08-11~/2026-08-16?');
+ expect(nudgeTemporalRaw({ category: 'statement', raw: '2026-08-11', shape: 'instant' }, 'move', 1)).toBe('2026-08-12');
+ expect(moveTemporalRaw({
+ category: 'statement', shape: 'interval',
+ raw: '2026-08-11T10:15:00Z/2026-08-11T11:40:00Z',
+ }, 60_000)).toBe('2026-08-11T10:16:00Z/2026-08-11T11:41:00Z');
+ expect(resizeTemporalRaw({
+ category: 'statement', shape: 'interval',
+ raw: '2026-08-11T10:15:00+02:00/2026-08-11T11:40:00+02:00',
+ }, 'end', '2026-08-11T10:00:00Z')).toBe(
+ '2026-08-11T10:15:00+02:00/2026-08-11T12:00:00+02:00'
+ );
+ });
+
+ it('refuses direct changes the case would reject', () => {
+ expect(moveTemporalRaw(
+ { category: 'statement', raw: '2026-09/2026-09-05', shape: 'interval' }, 16 * DAY
+ )).toBeNull();
+ expect(resizeTemporalRaw(
+ { category: 'statement', raw: '2026-08-11/2026-08-13', shape: 'interval' },
+ 'start', '2026-08-20'
+ )).toBeNull();
+ expect(moveTemporalRaw({ category: 'statement', raw: '9998' }, 3 * 365 * DAY)).toBeNull();
+ });
+
+ it('creates exact timestamps when the visible window is close enough', () => {
+ expect(dateAtRatio('2026-08-01', '2026-08-10', 0)).toBe('2026-08-01');
+ expect(timeAtRatio('2026-06-23T00:00:00Z', '2026-06-24T00:00:00Z', .39999997))
+ .toBe('2026-06-23T09:36:00Z');
+ expect(draftWhen('2026-08-11T18:00:00Z', '2026-08-11T19:00:00Z', .5, .5))
+ .toBe('2026-08-11T18:30:00Z');
+ expect(draftWhen('2026-08-11T18:00:00Z', '2026-08-11T19:00:00Z', .25, .75))
+ .toBe('2026-08-11T18:15:00Z/2026-08-11T18:45:00Z');
+ expect(draftWhen('2026-08-01', '2026-08-10', .1, .8)).toBe('2026-08-02/2026-08-09');
+ });
+});
+
+describe('temporal reading', () => {
+ it('renders the stored syntax in plain language without losing it', () => {
+ expect(formatTemporalValue('2026-08~')).toMatchObject({
+ valid: true, label: 'Aug 2026', qualifiers: ['Approximate'],
+ });
+ expect(formatTemporalValue('2026-08-11T18:40:00+02:00').label)
+ .toBe('11 Aug 2026, 18:40:00 UTC+02:00');
+ expect(formatTemporalValue('2026-08-11/2026-08-14').label)
+ .toBe('11 Aug 2026 to 14 Aug 2026');
+ });
+
+ it('validates the same supported families before save', () => {
+ for (const raw of ['2026', '2026-08~', '2026-08-11?', '2026-08-11T18:40:00Z', '2026-08/2026-10', '2026-08-11T10:00:00Z/2026-08-11T11:00:00Z']) {
+ expect(validateTemporalValue(raw).valid, raw).toBe(true);
+ }
+ for (const raw of ['2026-8', '2026-02-29', '2026-08-11T18:40', '2026-08-11T18:40:00+15:00', '2026-10/2026-08', '2026-08-11T10:00:00/2026-08-11T11:00:00']) {
+ expect(validateTemporalValue(raw).valid, raw).toBe(false);
+ }
+ });
+});
+
+describe('timeline layout', () => {
+ const point = (id, earliest, latest, shape = 'instant', label = id) => ({
+ id, earliest, latest, shape, label, raw: earliest.slice(0, 10),
+ });
+
+ it('packs the rendered label width instead of a fixed axis fraction', () => {
+ const layout = layoutTimelineItems([
+ point('a', '2026-08-02T00:00:00Z', '2026-08-03T00:00:00Z', 'instant', 'A long checkpoint observation'),
+ point('b', '2026-08-02T12:00:00Z', '2026-08-03T00:00:00Z', 'instant', 'Another long checkpoint observation'),
+ point('c', '2026-08-05T00:00:00Z', '2026-08-08T00:00:00Z', 'interval', 'Road closure'),
+ ], '2026-08-01', '2026-08-10', 1000);
+ expect(layout.items.map((item) => item.lane)).toEqual([0, 1, 0]);
+ expect(layout.items[0].displayWidth).toBeGreaterThan(150);
+ expect(layout.items[0].haloWidth).toBeCloseTo(10, 3);
+ expect(layout.items[2].displayWidth).toBeGreaterThan(250);
+ });
+
+ it('collapses overflow into a clear count', () => {
+ const entries = Array.from({ length: 10 }, (_, index) =>
+ point(`same-${index}`, '2026-08-02T00:00:00Z', '2026-08-03T00:00:00Z')
+ );
+ const layout = layoutTimelineItems(entries, '2026-08-01', '2026-08-10', 800, 3);
+ expect(layout.items).toHaveLength(3);
+ expect(layout.clusters).toHaveLength(1);
+ expect(layout.clusters[0].count).toBe(7);
+ expect(layout.rows).toBe(4);
+ });
+
+ it('keeps pinned entries visible when a dense track is packed', () => {
+ const entries = Array.from({ length: 9 }, (_, index) => ({
+ ...point(`same-${index}`, '2026-08-02T00:00:00Z', '2026-08-03T00:00:00Z'),
+ pinned: index === 8,
+ }));
+ const layout = layoutTimelineItems(entries, '2026-08-01', '2026-08-10', 800, 3);
+ expect(layout.items.some((item) => item.id === 'same-8')).toBe(true);
+ expect(layout.clusters.flatMap((cluster) => cluster.items).some((item) => item.id === 'same-8'))
+ .toBe(false);
+ });
+
+ it('targets a useful number of major ticks and adds context', () => {
+ const short = axisTicks('2026-08-01T00:00:00Z', '2026-08-04T00:00:00Z', 1000);
+ const medium = axisTicks('2026-06-10T00:00:00Z', '2026-08-03T00:00:00Z', 1000);
+ const year = axisTicks('2026-01-01T00:00:00Z', '2027-01-01T00:00:00Z', 1000);
+ for (const ticks of [short, medium, year]) {
+ expect(ticks.length).toBeGreaterThanOrEqual(7);
+ expect(ticks.length).toBeLessThanOrEqual(13);
+ }
+ expect(axisMinorTicks('2026-08-01T00:00:00Z', '2026-08-04T00:00:00Z', 1000).length)
+ .toBeGreaterThan(0);
+ expect(axisBands('2026-06-10T00:00:00Z', '2026-08-03T00:00:00Z', 1000).map((band) => band.label))
+ .toContain('Jul 2026');
+ expect(axisScale('2026-06-10T00:00:00Z', '2026-08-03T00:00:00Z', 1000)).toBe('Days');
+ });
+
+ it('keeps category breakdowns and scales the heights by count', () => {
+ // The square root of the share: a quarter of the entries stands half as tall, so a
+ // case whose one big batch dwarfs everything else still shows the rest.
+ expect(bucketScale([{ start: '2025', count: 1 }, { start: '2026', count: 4 }]))
+ .toEqual([{ start: '2025', count: 1, height: 50 }, { start: '2026', count: 4, height: 100 }]);
+ expect(bucketScale([{ start: '2025', count: 1 }, { start: '2026', count: 200 }])[0].height)
+ .toBe(12);
+ const buckets = layoutDensityBuckets([
+ { start: '2026-06-12', count: 2, categories: { statement: 1, media: 1 } },
+ ], { from: '2026-06-12T00:00:00Z', to: '2026-06-13T00:00:00Z' });
+ expect(buckets[0].categories).toEqual({ statement: 1, media: 1 });
+ });
+
+ it('opens a bucket onto what it holds, not onto the period it is named after', () => {
+ // Six entries in the first week of August open a window on that week. Landing on
+ // the month instead left the brush resting somewhere other than the bar clicked.
+ expect(bucketWindow({
+ start: '2026-08', first: '2026-08-02T00:00:00Z', last: '2026-08-10T00:00:00Z',
+ })).toEqual({ from: '2026-08-01T12:28:48Z', to: '2026-08-10T11:31:12Z' });
+
+ // One entry has no span of its own, so the window is half a day either side.
+ expect(bucketWindow({
+ start: '2026-08', first: '2026-08-02T00:00:00Z', last: '2026-08-02T00:00:00Z',
+ })).toEqual({ from: '2026-08-01T12:00:00Z', to: '2026-08-02T12:00:00Z' });
+
+ // A reading that predates the inner span — a saved snapshot — still opens the period.
+ expect(bucketWindow('2026-06-12')).toEqual({ from: '2026-06-09T00:00:00Z', to: '2026-06-16T00:00:00Z' });
+ expect(bucketWindow('2026-02')).toEqual({ from: '2026-02-01T00:00:00Z', to: '2026-03-01T00:00:00Z' });
+ expect(bucketWindow('2026')).toEqual({ from: '2026-01-01T00:00:00Z', to: '2027-01-01T00:00:00Z' });
+ });
+
+ it('cuts the overview as fine as it can be drawn', () => {
+ // Cut by the period the case happens to span, a scraped batch of two hundred in one
+ // week and a single entry that could be anywhere in May drew the same one-month
+ // mark. The bins are chosen for the width they will have on screen instead.
+ const eightMonths = { from: '2026-01-03T00:00:00Z', to: '2026-08-09T00:00:00Z' };
+ expect(densityUnit(eightMonths, 800)).toBe('day');
+ // Zoomed onto a single day, the same rule cuts by the hour.
+ expect(densityUnit({ from: '2026-08-02T00:00:00Z', to: '2026-08-02T20:00:00Z' }, 800)).toBe('hour');
+ // A case spanning decades cannot be drawn by the day, and says so.
+ expect(densityUnit({ from: '1998-01-01T00:00:00Z', to: '2026-08-09T00:00:00Z' }, 800)).toBe('month');
+ expect(densityUnit({ from: '1500-01-01T00:00:00Z', to: '2026-08-09T00:00:00Z' }, 800)).toBe('year');
+ // A narrow minimap holds fewer bins, so it is cut more coarsely.
+ expect(densityUnit(eightMonths, 120)).toBe('month');
+ expect(densityUnit(null, 800)).toBe('day');
+ });
+
+ it('draws one column per bin, across the bin, inside the brush that holds it', () => {
+ // The overview's one promise: what the visible-range brush covers is what the axis
+ // is showing. A bar drawn at the opening of the period it was counted under broke
+ // it — a January bucket holding the 14th and the 27th marked the 1st, so the bar
+ // for two entries on screen sat outside the brush that was showing them.
+ const buckets = [
+ { start: '2026-01-14', count: 1 },
+ { start: '2026-01-27', count: 1 },
+ { start: '2026-08-02', count: 6 },
+ ];
+ const extent = { from: '2026-01-14T00:00:00Z', to: '2026-08-03T00:00:00Z' };
+ const scale = densityScale(buckets, extent);
+ const at = (raw) => ((new Date(raw).getTime() - scale.first) / scale.span) * 100;
+
+ // A column is as wide as its own bin — the day it counts — which is what makes the
+ // heights beside it comparable.
+ const drawn = layoutDensityBuckets(buckets, extent);
+ expect(drawn.map((bar) => bar.left)).toEqual([
+ at('2026-01-14T00:00:00Z'), at('2026-01-27T00:00:00Z'), at('2026-08-02T00:00:00Z'),
+ ]);
+ expect(drawn.map((bar) => bar.left + bar.width)).toEqual([
+ at('2026-01-15T00:00:00Z'), at('2026-01-28T00:00:00Z'), at('2026-08-03T00:00:00Z'),
+ ]);
+
+ // Every column sits inside a window that holds the whole case, and only August's
+ // sits inside a window opened on August.
+ const holdsAll = { left: 0, right: 100 };
+ const holdsAugust = { left: at('2026-08-01T00:00:00Z'), right: 100 };
+ const inside = (bar, window) =>
+ bar.left >= window.left - 1e-9 && bar.left + bar.width <= window.right + 1e-9;
+ expect(drawn.map((bar) => inside(bar, holdsAll))).toEqual([true, true, true]);
+ expect(drawn.map((bar) => inside(bar, holdsAugust))).toEqual([false, false, true]);
+
+ // An hour bin is read back the same way.
+ const hourly = layoutDensityBuckets(
+ [{ start: '2026-08-02T14', count: 2 }],
+ { from: '2026-08-02T00:00:00Z', to: '2026-08-03T00:00:00Z' },
+ );
+ expect(hourly[0].left).toBeCloseTo((14 / 24) * 100, 6);
+ expect(hourly[0].width).toBeCloseTo((1 / 24) * 100, 6);
+ });
+
+ it('names each period under its own bar, and only as often as the labels fit', () => {
+ const buckets = [
+ { start: '2026-01', count: 2, first: '2026-01-14T00:00:00Z', last: '2026-01-28T00:00:00Z' },
+ { start: '2026-08', count: 6, first: '2026-08-02T00:00:00Z', last: '2026-08-10T00:00:00Z' },
+ ];
+ const extent = { from: '2026-01-14T00:00:00Z', to: '2026-08-10T00:00:00Z' };
+ const slots = densityTicks(buckets, extent, 800);
+
+ // One slot per month the case runs through, holes included: the eight months of a
+ // case with two buckets, not two labels sitting wherever the entries happen to be.
+ expect(slots.map((slot) => slot.label))
+ .toEqual(['Jan 2026', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug']);
+ expect(slots[0].left).toBe(0);
+ expect(slots.at(-1).left + slots.at(-1).width).toBeCloseTo(100, 6);
+
+ // The outermost months are clipped to what the case holds of them, and each label
+ // covers the slot it names, so it is centred over its own bar.
+ const scale = densityScale(buckets, extent);
+ const at = (raw) => ((new Date(raw).getTime() - scale.first) / scale.span) * 100;
+ expect(slots[1].left).toBeCloseTo(at('2026-02-01T00:00:00Z'), 6);
+ expect(slots.at(-1).left).toBeCloseTo(at('2026-08-01T00:00:00Z'), 6);
+ expect(slots[0].anchor).toBe('start');
+ expect(slots[1].anchor).toBe('middle');
+ expect(slots.at(-1).anchor).toBe('end');
+
+ // Narrow, the same scale names fewer of them rather than piling them up.
+ const narrow = densityTicks(buckets, extent, 200).filter((slot) => slot.label);
+ expect(narrow.length).toBeLessThan(4);
+ expect(narrow[0].label).toBe('Jan 2026');
+ });
+
+ it('reads a bucket with no inner span back as the period it names', () => {
+ // What a saved snapshot taken before the server reported the span answers with.
+ expect(bucketSpan({ start: '2026-02' })).toEqual({
+ first: Date.UTC(2026, 1, 1), last: Date.UTC(2026, 2, 1),
+ });
+ expect(bucketSpan({ start: 'nonsense' })).toBe(null);
+ });
+});
+
+describe('reading the axis in a zone', () => {
+ it('leaves UTC exactly as it was', () => {
+ // the default path answers without asking Intl anything, so the stored case and
+ // every existing reading of it are untouched by the switch
+ expect(zoneOffset(Date.UTC(2026, 7, 11), 'UTC')).toBe(0);
+ expect(zonedFields(Date.UTC(2026, 7, 11, 18, 40, 12))).toEqual({
+ year: 2026, month: 8, day: 11, hour: 18, minute: 40, second: 12,
+ });
+ expect(windowInputValue('2026-08-11T18:40:12Z')).toBe('2026-08-11T18:40:12');
+ expect(inputWindowValue('2026-08-11T18:40')).toBe('2026-08-11T18:40:00Z');
+ });
+
+ it('reads an instant as the wall clock of the chosen zone, and back', () => {
+ expect(zoneOffset(Date.parse('2026-08-11T18:40:12Z'), 'Europe/Kyiv')).toBe(3 * HOUR);
+ expect(windowInputValue('2026-08-11T18:40:12Z', 'Europe/Kyiv')).toBe('2026-08-11T21:40:12');
+ // the boundary control holds a wall clock, so the same string means a different
+ // instant in each zone
+ expect(inputWindowValue('2026-08-11T21:40:12', 'Europe/Kyiv')).toBe('2026-08-11T18:40:12Z');
+ expect(instantOf({ year: 2026, month: 8, day: 11, hour: 21, minute: 40, second: 12 }, 'Europe/Kyiv'))
+ .toBe(Date.parse('2026-08-11T18:40:12Z'));
+ });
+
+ it('survives the two days a year the offset moves', () => {
+ // 26 Oct 2026, 03:00 local goes back to 02:00 in Kyiv: an hour lived twice
+ expect(zoneOffset(Date.parse('2026-10-25T00:00:00Z'), 'Europe/Kyiv')).toBe(3 * HOUR);
+ expect(zoneOffset(Date.parse('2026-10-26T00:00:00Z'), 'Europe/Kyiv')).toBe(2 * HOUR);
+ // 29 March, 03:00 local jumps to 04:00: the half hour asked for here never
+ // happened, and it lands an hour later in the offset now in force (04:30 local)
+ // rather than resolving to nothing
+ const skipped = instantOf(
+ { year: 2026, month: 3, day: 29, hour: 3, minute: 30, second: 0 }, 'Europe/Kyiv'
+ );
+ expect(new Date(skipped).toISOString()).toBe('2026-03-29T01:30:00.000Z');
+ expect(zonedFields(skipped, 'Europe/Kyiv')).toMatchObject({ hour: 4, minute: 30 });
+ });
+
+ it('offers every zone the platform knows, with the offset in force', () => {
+ // an investigation is rarely in the analyst's own zone, and often in no point the
+ // case has saved yet, so the reading has to be choosable outright
+ const zones = worldZones();
+ expect(zones.length).toBeGreaterThan(100);
+ // which of the two spellings this platform lists is not ours to decide
+ expect(zones.some((zone) => /^Europe\/(Kyiv|Kiev)$/.test(zone))).toBe(true);
+ expect(zones).toEqual([...zones].sort((one, other) => one.localeCompare(other)));
+ const august = Date.parse('2026-08-11T00:00:00Z');
+ expect(offsetLabel('Europe/Kyiv', august)).toBe('UTC+03:00');
+ expect(offsetLabel('Asia/Kolkata', august)).toBe('UTC+05:30');
+ expect(offsetLabel('America/Chicago', august)).toBe('UTC-05:00');
+ expect(offsetLabel(UTC, august)).toBe('UTC');
+ // and the offset follows the season rather than being the zone's standard one
+ expect(offsetLabel('Europe/Kyiv', Date.parse('2026-01-11T00:00:00Z'))).toBe('UTC+02:00');
+ });
+
+ it('finds a zone by city, by region or by offset', () => {
+ const august = Date.parse('2026-08-11T00:00:00Z');
+ expect(zoneMatches('Europe/Kyiv', 'kyiv', august)).toBe(true);
+ // and the rename must not hide the zone: this machine lists Europe/Kiev, a current
+ // browser lists Europe/Kyiv, and someone working Ukraine types one of the two
+ expect(zoneMatches('Europe/Kiev', 'kyiv', august)).toBe(true);
+ expect(zoneMatches('Europe/Kyiv', 'kiev', august)).toBe(true);
+ expect(zoneMatches('Asia/Calcutta', 'kolkata', august)).toBe(true);
+ expect(zoneMatches('Asia/Ho_Chi_Minh', 'saigon', august)).toBe(true);
+ expect(zoneMatches('Europe/Kyiv', 'europe', august)).toBe(true);
+ expect(zoneMatches('Europe/Kyiv', '+03', august)).toBe(true);
+ expect(zoneMatches('Europe/Kyiv', 'paris', august)).toBe(false);
+ // nobody types an underscore
+ expect(zoneMatches('America/New_York', 'new york', august)).toBe(true);
+ expect(zoneWords('America/New_York')).toEqual({ place: 'New York', region: 'America' });
+ expect(zoneWords('UTC')).toEqual({ place: 'UTC', region: '' });
+ });
+
+ it('puts a day tick on the zone-s own midnight, not on the UTC one', () => {
+ const ticks = axisTicks('2026-08-01T00:00:00Z', '2026-08-11T00:00:00Z', 1000, 'Europe/Kyiv');
+ expect(ticks.length).toBeGreaterThanOrEqual(7);
+ // Kyiv is UTC+3 in August, so local midnight is 21:00 the day before
+ expect(ticks[0].at.endsWith('T21:00:00.000Z')).toBe(true);
+ expect(ticks[0].label).toBe(`${Number(ticks[0].at.slice(8, 10)) + 1} Aug`);
+ expect(axisBands('2026-08-01T00:00:00Z', '2026-08-11T00:00:00Z', 1000, 'Europe/Kyiv')[0].label)
+ .toMatch(/Aug 2026/);
+ });
+
+ it('keeps the ticks in the same places while the window is panned', () => {
+ // a tick phase read off the window start slides under a pan, which reads as the
+ // axis rewriting itself
+ const first = axisTicks('2026-08-01T00:00:00Z', '2026-08-11T00:00:00Z', 1000, 'Europe/Kyiv');
+ const panned = axisTicks('2026-08-02T07:00:00Z', '2026-08-12T07:00:00Z', 1000, 'Europe/Kyiv');
+ const shared = first.map((tick) => tick.at).filter((at) => panned.some((tick) => tick.at === at));
+ expect(shared.length).toBeGreaterThan(5);
+ });
+});
+
+describe('how far apart two entries are', () => {
+ const entry = (id, earliest, latest, extra = {}) => ({
+ id, label: id, earliest, latest, shape: 'instant', ...extra,
+ });
+
+ it('gives one number for two exact timestamps', () => {
+ const read = describePair(
+ entry('a', '2026-08-11T14:28:00Z', '2026-08-11T14:28:01Z'),
+ entry('b', '2026-08-11T18:40:00Z', '2026-08-11T18:40:01Z'),
+ );
+ expect(read.headline).toBe('4 hours 12 minutes apart');
+ expect(read.detail).toBe('a first');
+ expect(read.notes).toEqual([]);
+ });
+
+ it('brackets the gap when either side is only dated to the day', () => {
+ // 12 May and 15 May are not three days apart: they are between two and four,
+ // and printing the difference of two midnights as a fact invents precision
+ const read = describePair(
+ entry('a', '2026-05-12T00:00:00Z', '2026-05-13T00:00:00Z', { precision: 'day' }),
+ entry('b', '2026-05-15T00:00:00Z', '2026-05-16T00:00:00Z', { precision: 'day' }),
+ );
+ expect(read.headline).toBe('Between 2 and 4 days apart');
+ expect(read.notes[0]).toBe('As written, 3 days apart.');
+ expect(read.notes).toContain('a is dated to the day.');
+ const pair = compareTimelineItems(
+ entry('a', '2026-05-12T00:00:00Z', '2026-05-13T00:00:00Z'),
+ entry('b', '2026-05-15T00:00:00Z', '2026-05-16T00:00:00Z'),
+ );
+ expect(pair.gap).toMatchObject({ min: 2 * DAY, max: 4 * DAY, stated: 3 * DAY, exact: false });
+ });
+
+ it('measures two exact periods end to start, with no invented uncertainty', () => {
+ // an interval's bounds are its stated extent, not a window of ignorance: these
+ // two are two hours apart, and answering "between 2 h and 12 h" would be the
+ // manufactured vagueness the bracketing exists to avoid
+ const read = describePair(
+ entry('a', '2026-05-12T08:00:00Z', '2026-05-12T14:00:00Z', { shape: 'interval' }),
+ entry('b', '2026-05-12T16:00:00Z', '2026-05-12T20:00:00Z', { shape: 'interval' }),
+ );
+ expect(read.headline).toBe('2 hours apart');
+ expect(read.detail).toBe('a first');
+ expect(read.notes).toEqual(['a runs for 6 hours.', 'b runs for 4 hours.']);
+ });
+
+ it('carries a coarse point-s slack into the gap beside an exact period', () => {
+ const read = describePair(
+ entry('a', '2026-05-12T00:00:00Z', '2026-05-13T00:00:00Z', { precision: 'day' }),
+ entry('b', '2026-05-15T08:00:00Z', '2026-05-15T14:00:00Z', { shape: 'interval' }),
+ );
+ // the day could be any moment of 12 May, so the gap runs from 2 d 8 h to 3 d 8 h
+ expect(read.headline).toBe('Between 2 days 8 hours and 3 days 8 hours apart');
+ });
+
+ it('reads two consecutive days as a gap that may be nothing at all', () => {
+ const read = describePair(
+ entry('a', '2026-05-12T00:00:00Z', '2026-05-13T00:00:00Z', { precision: 'day' }),
+ entry('b', '2026-05-13T00:00:00Z', '2026-05-14T00:00:00Z', { precision: 'day' }),
+ );
+ expect(read.headline).toBe('Up to 2 days apart');
+ });
+
+ it('refuses to order a pair whose windows overlap, and says how much', () => {
+ const read = describePair(
+ entry('a', '2026-05-12T08:00:00Z', '2026-05-12T14:00:00Z', { shape: 'interval' }),
+ entry('b', '2026-05-12T12:00:00Z', '2026-05-12T20:00:00Z', { shape: 'interval' }),
+ );
+ expect(read.headline).toBe('Overlapping by 2 hours');
+ expect(read.detail).toContain('Either could come first');
+ expect(read.notes).toContain('a runs for 6 hours.');
+ });
+
+ it('tells a period that lasts from a point that is merely vague', () => {
+ expect(itemExtent(
+ entry('a', '2026-05-12T00:00:00Z', '2026-05-15T00:00:00Z', { shape: 'interval' })
+ )).toMatchObject({ kind: 'duration', ms: 3 * DAY });
+ expect(itemExtent(
+ entry('a', '2026-05-12T00:00:00Z', '2026-05-13T00:00:00Z', { precision: 'day' })
+ )).toMatchObject({ kind: 'precision', ms: DAY });
+ // an exact timestamp carries a one-second window, which is a point
+ expect(itemExtent(entry('a', '2026-05-12T10:00:00Z', '2026-05-12T10:00:01Z'))).toBeNull();
+ });
+
+ it('measures nothing against an entry the axis cannot place', () => {
+ const read = describePair(
+ entry('a', '2026-05-12T00:00:00Z', '2026-05-13T00:00:00Z'),
+ { id: 'b', label: 'b', earliest: null, latest: null, raw: '2026-05-14T10:00:00' },
+ );
+ expect(read.ok).toBe(false);
+ expect(read.detail).toContain('no place on the UTC axis');
+ });
+
+ it('phrases a range like a sentence, and a floor of nothing as a ceiling', () => {
+ // "between 0 and 4 days" invites the reader to average it; two consecutive dates
+ // license "up to 4 days" and nothing more
+ expect(formatSpanRange(2 * DAY, 4 * DAY)).toBe('between 2 and 4 days');
+ expect(formatSpanRange(DAY, 4 * DAY)).toBe('between 1 and 4 days');
+ expect(formatSpanRange(0, 2 * DAY)).toBe('up to 2 days');
+ expect(formatSpanRange(2 * DAY + 8 * HOUR, 3 * DAY + 8 * HOUR))
+ .toBe('between 2 days 8 hours and 3 days 8 hours');
+ });
+
+ it('names a length to two units', () => {
+ expect(formatSpan(0)).toBe('under a second');
+ expect(formatSpan(90 * 1000)).toBe('1 minute 30 seconds');
+ expect(formatSpan(2 * DAY + 6 * HOUR)).toBe('2 days 6 hours');
+ expect(formatSpan(400 * DAY)).toBe('1 year 34 days');
+ });
+});
+
+describe('the window, as one reading', () => {
+ it('states the hours only when the window is short enough to be about them', () => {
+ expect(windowWords('2026-08-23T20:49:00Z', '2026-10-01T10:12:00Z')).toBe('23 Aug – 1 Oct 2026');
+ expect(windowWords('2026-12-30T00:00:00Z', '2027-01-02T00:00:00Z')).toBe('30 Dec 2026 – 2 Jan 2027');
+ expect(windowWords('2026-08-23T20:49:00Z', '2026-08-24T06:00:00Z'))
+ .toBe('23 Aug 20:49 – 24 Aug 06:00');
+ expect(windowWords('2026-08-23T20:49:00Z', '2026-08-23T23:10:00Z'))
+ .toBe('23 Aug 2026, 20:49 – 23:10');
+ expect(windowWords('', '')).toBe('All dates');
+ });
+
+ it('reads the boundaries on the clock the axis is drawn in', () => {
+ expect(windowWords('2026-08-23T20:49:00Z', '2026-08-23T23:10:00Z', 'Asia/Tokyo'))
+ .toBe('24 Aug 2026, 05:49 – 08:10');
+ });
+
+ it('resizes to a named span around the middle of the window', () => {
+ const window = resizeWindow('2026-08-23T00:00:00Z', '2026-08-24T00:00:00Z', 2 * 60 * 60 * 1000);
+ expect(window).toEqual({ from: '2026-08-23T11:00:00Z', to: '2026-08-23T13:00:00Z' });
+ expect(WINDOW_SPANS.map((span) => span.label))
+ .toEqual(['Hour', 'Day', 'Week', 'Month', 'Year']);
+ // nothing to resize without a window, and nothing invented either
+ expect(resizeWindow('', '', 1000)).toEqual({ from: '', to: '' });
+ });
+});
diff --git a/frontend/src/lib/timelineTracks.js b/frontend/src/lib/timelineTracks.js
new file mode 100644
index 0000000..610170b
--- /dev/null
+++ b/frontend/src/lib/timelineTracks.js
@@ -0,0 +1,201 @@
+import { emptyFilter, normalizeFilter } from './entityFilter.js';
+
+const CATEGORIES = new Set(['statement', 'media', 'case_activity']);
+/**
+ * The colours a track may be given, by name.
+ *
+ * A track is a question the analyst wrote, and on a busy axis its colour is how the
+ * answer is read at a glance. Left unset the lane keeps the **category** colours —
+ * statement, media, activity — which is what the legend explains; a chosen colour
+ * says the analyst wants this reading told apart from the others instead, and it wins
+ * for that track only. Names rather than hex so the palette stays the app's own
+ * (`--anno-*`) and a saved view cannot carry an unreadable colour.
+ */
+export const TRACK_COLORS = ['red', 'blue', 'amber', 'green', 'magenta', 'orange'];
+
+/** The colour as CSS, or nothing at all — an unset track must inherit the category
+ * colours rather than a grey stand-in. Ordered with the palette above. */
+export function trackTint(color) {
+ const index = TRACK_COLORS.indexOf(color);
+ return index < 0 ? undefined : `var(--anno-${index + 1})`;
+}
+const RELATIONS = new Set(['any', 'owner', 'about', 'place', 'source']);
+const ROLES = new Set(['occurred', 'observed', 'valid', 'unset']);
+
+const unique = (values, allowed = null, limit = 500) => [
+ ...new Set(
+ (Array.isArray(values) ? values : [])
+ .filter((value) => typeof value === 'string' && value && (!allowed || allowed.has(value)))
+ .slice(0, limit)
+ ),
+];
+
+export function timelineTrack(value, index = 0) {
+ const raw = value && typeof value === 'object' ? value : {};
+ const query = raw.query && typeof raw.query === 'object' ? raw.query : {};
+ const categories = unique(raw.categories, CATEGORIES, 3);
+ return {
+ id: typeof raw.id === 'string' && raw.id ? raw.id.slice(0, 64) : `track-${index + 1}`,
+ label: typeof raw.label === 'string' && raw.label.trim()
+ ? raw.label.trim().slice(0, 80)
+ : `Track ${index + 1}`,
+ categories: categories.length ? categories : ['statement'],
+ query: {
+ filter: normalizeFilter(query.filter ?? emptyFilter()),
+ terms: query.terms && typeof query.terms === 'object' ? query.terms : {},
+ label: typeof query.label === 'string' ? query.label.slice(0, 300) : '',
+ relation: RELATIONS.has(query.relation) ? query.relation : 'any',
+ roles: unique(query.roles, ROLES, 4),
+ },
+ color: TRACK_COLORS.includes(raw.color) ? raw.color : '',
+ collapsed: raw.collapsed === true,
+ hidden: unique(raw.hidden),
+ pinned: unique(raw.pinned),
+ };
+}
+
+export function defaultTimelineTracks() {
+ return [
+ timelineTrack({ id: 'events', label: 'Events', categories: ['statement'] }),
+ timelineTrack({ id: 'media', label: 'Media', categories: ['media'] }, 1),
+ ];
+}
+
+export function normalizeTimelineTracks(value) {
+ const raw = Array.isArray(value) ? value.slice(0, 20) : [];
+ const tracks = raw.length ? raw.map(timelineTrack) : defaultTimelineTracks();
+ const seen = new Set();
+ return tracks.map((track, index) => {
+ let id = track.id;
+ while (seen.has(id)) id = `${track.id}-${index + 1}`;
+ seen.add(id);
+ return { ...track, id };
+ });
+}
+
+export function trackPresets(types = []) {
+ const ofType = (type, relation = 'about') => timelineTrack({
+ id: `preset-${type}`,
+ label: types.find((entry) => entry.type === type)?.label ?? type,
+ categories: ['statement'],
+ query: { relation, terms: { type }, filter: { ...emptyFilter(), types: [type] } },
+ });
+ return [
+ timelineTrack({ id: 'preset-events', label: 'Events', categories: ['statement'] }),
+ ofType('person'),
+ ofType('place', 'place'),
+ timelineTrack({ id: 'preset-media', label: 'Media', categories: ['media'] }),
+ timelineTrack({
+ id: 'preset-sources', label: 'Sources', categories: ['statement'],
+ query: { relation: 'source' },
+ }),
+ timelineTrack({ id: 'preset-activity', label: 'Case activity', categories: ['case_activity'] }),
+ ];
+}
+
+export function copyTimelineTrack(track, tracks) {
+ const used = new Set(tracks.map((entry) => entry.label.toLocaleLowerCase()));
+ const stem = `${track.label} copy`;
+ let label = stem;
+ let index = 2;
+ while (used.has(label.toLocaleLowerCase())) label = `${stem} ${index++}`;
+ return {
+ ...timelineTrack(track),
+ id: `track-${globalThis.crypto?.randomUUID?.() ?? Date.now()}-${Math.random().toString(16).slice(2)}`,
+ label,
+ collapsed: false,
+ };
+}
+
+export function moveTimelineTrack(tracks, from, to) {
+ if (from === to || from < 0 || to < 0 || from >= tracks.length || to >= tracks.length) return tracks;
+ const next = [...tracks];
+ const [moved] = next.splice(from, 1);
+ next.splice(to, 0, moved);
+ return next;
+}
+
+export function timelineTrackQuery(track) {
+ return JSON.stringify({
+ ...track.query,
+ hidden: track.hidden,
+ });
+}
+
+function groupKeys(item, groupBy, typeName) {
+ if (groupBy === 'subject') {
+ return item.subject_entities?.length
+ ? item.subject_entities : [{ id: 'none', label: 'No subject' }];
+ }
+ if (groupBy === 'place') {
+ return item.place_entities?.length
+ ? item.place_entities : [{ id: 'none', label: 'No place' }];
+ }
+ if (groupBy === 'source') {
+ return item.source_entities?.length
+ ? item.source_entities : [{ id: 'none', label: 'No evidence' }];
+ }
+ if (groupBy === 'type') {
+ const types = [...new Set((item.subject_entities ?? []).map((entry) => entry.type).filter(Boolean))];
+ if (!types.length && item.owner_type) types.push(item.owner_type);
+ if (!types.length) return [{ id: 'none', label: 'Unknown type' }];
+ return types.map((type) => ({ id: type, label: typeName(type), type }));
+ }
+ if (groupBy === 'role') {
+ const role = item.time_role || 'Not set';
+ return [{ id: role, label: role }];
+ }
+ return [];
+}
+
+export function groupedTimelineTracks(tracks, itemSets, groupBy = 'none', typeName = (type) => type) {
+ if (groupBy === 'none') return tracks.map((track) => ({ ...track, items: itemSets[track.id] ?? [] }));
+ const result = [];
+ for (const track of tracks) {
+ const groups = new Map();
+ for (const item of itemSets[track.id] ?? []) {
+ for (const key of groupKeys(item, groupBy, typeName)) {
+ const id = String(key.id || key.label || 'other');
+ const group = groups.get(id) ?? { id, label: key.label || id, items: [] };
+ group.items.push(item);
+ groups.set(id, group);
+ }
+ }
+ if (!groups.size) result.push({ ...track, items: [], groupLabel: 'No matches' });
+ else for (const group of groups.values()) {
+ result.push({
+ ...track,
+ id: `${track.id}:group:${group.id}`,
+ parentId: track.id,
+ label: group.label,
+ groupLabel: track.label,
+ items: group.items,
+ });
+ }
+ }
+ return result;
+}
+
+export function timelineViewState(value) {
+ const raw = value && typeof value === 'object' ? value : {};
+ const tracks = normalizeTimelineTracks(raw.tracks);
+ return {
+ from: typeof raw.from === 'string' ? raw.from : '',
+ to: typeof raw.to === 'string' ? raw.to : '',
+ timezone: typeof raw.timezone === 'string' && raw.timezone
+ ? raw.timezone.slice(0, 80) : 'UTC',
+ // `zone:<IANA name>` is the fourth reading, for an investigation at the other end
+ // of the world that the case has no saved point in yet. Validated by shape only:
+ // whether this machine can load the name is asked when the axis is drawn, so a
+ // view made where the zone exists does not lose it on a stricter box.
+ zoneChoice: typeof raw.zone_choice === 'string'
+ && /^(utc|machine|place:[^\s]{1,64}|zone:[A-Za-z0-9+\-_/]{1,64})$/.test(raw.zone_choice)
+ ? raw.zone_choice : 'utc',
+ viewMode: raw.view_mode === 'list' ? 'list' : 'plot',
+ groupBy: ['subject', 'type', 'place', 'source', 'role'].includes(raw.group_by)
+ ? raw.group_by : 'none',
+ tracks,
+ categories: unique(tracks.flatMap((track) => track.categories), CATEGORIES, 3),
+ entity: raw.entity?.id ? { id: raw.entity.id, label: raw.entity.label || raw.entity.id } : null,
+ };
+}
diff --git a/frontend/src/lib/timelineTracks.test.js b/frontend/src/lib/timelineTracks.test.js
new file mode 100644
index 0000000..9a374ea
--- /dev/null
+++ b/frontend/src/lib/timelineTracks.test.js
@@ -0,0 +1,109 @@
+import { describe, expect, it } from 'vitest';
+import {
+ TRACK_COLORS,
+ copyTimelineTrack,
+ defaultTimelineTracks,
+ groupedTimelineTracks,
+ moveTimelineTrack,
+ normalizeTimelineTracks,
+ timelineTrack,
+ timelineViewState,
+ trackPresets,
+ trackTint,
+} from './timelineTracks.js';
+
+describe('Timeline tracks', () => {
+ it('starts with editable event and media tracks', () => {
+ expect(defaultTimelineTracks().map((track) => [track.label, track.categories])).toEqual([
+ ['Events', ['statement']], ['Media', ['media']],
+ ]);
+ });
+
+ it('builds presets from registry labels rather than a second type vocabulary', () => {
+ const presets = trackPresets([{ type: 'person', label: 'Human' }, { type: 'place', label: 'Location' }]);
+ expect(presets.map((preset) => preset.label)).toEqual([
+ 'Events', 'Human', 'Location', 'Media', 'Sources', 'Case activity',
+ ]);
+ expect(presets[1].query.terms).toEqual({ type: 'person' });
+ });
+
+ it('normalizes imported state and keeps track ids unique', () => {
+ const tracks = normalizeTimelineTracks([
+ { id: 'same', label: 'One', categories: ['statement', 'bad'] },
+ { id: 'same', label: 'Two', categories: [] },
+ ]);
+ expect(tracks.map((track) => track.id)).toEqual(['same', 'same-2']);
+ expect(tracks[0].categories).toEqual(['statement']);
+ expect(tracks[1].categories).toEqual(['statement']);
+ });
+
+ it('reorders and duplicates presentation without sharing arrays', () => {
+ const tracks = defaultTimelineTracks();
+ expect(moveTimelineTrack(tracks, 0, 1).map((track) => track.label)).toEqual(['Media', 'Events']);
+ const copy = copyTimelineTrack({ ...tracks[0], hidden: ['a'] }, tracks);
+ expect(copy.label).toBe('Events copy');
+ expect(copy.id).not.toBe(tracks[0].id);
+ });
+
+ it('groups one event into each matching subject without copying the event', () => {
+ const tracks = defaultTimelineTracks().slice(0, 1);
+ const item = { id: 'event', subject_entities: [{ id: 'a', label: 'A' }, { id: 'b', label: 'B' }] };
+ const grouped = groupedTimelineTracks(tracks, { events: [item] }, 'subject');
+ expect(grouped.map((track) => track.label)).toEqual(['A', 'B']);
+ expect(grouped.every((track) => track.items[0] === item)).toBe(true);
+ });
+
+ it('keeps entries without a grouping value visible', () => {
+ const tracks = defaultTimelineTracks();
+ const event = { id: 'event', owner_type: 'claim' };
+ const media = { id: 'media', owner_type: 'capture' };
+ expect(groupedTimelineTracks(tracks, { events: [event], media: [media] }, 'subject')
+ .map((track) => track.label)).toEqual(['No subject', 'No subject']);
+ expect(groupedTimelineTracks(tracks, { events: [event], media: [media] }, 'type')
+ .map((track) => track.label)).toEqual(['claim', 'capture']);
+ expect(groupedTimelineTracks(tracks, { events: [event], media: [media] }, 'type',
+ (type) => type.toUpperCase()).map((track) => track.label)).toEqual(['CLAIM', 'CAPTURE']);
+ });
+
+ it('leaves a track on its category colours until one is chosen', () => {
+ expect(defaultTimelineTracks().map((track) => track.color)).toEqual(['', '']);
+ expect(timelineTrack({ label: 'Vessels', color: 'blue' }).color).toBe('blue');
+ expect(timelineTrack({ label: 'Vessels', color: 'chartreuse' }).color).toBe('');
+ expect(trackTint('blue')).toBe('var(--anno-2)');
+ expect(trackTint('')).toBeUndefined();
+ expect(trackTint('chartreuse')).toBeUndefined();
+ // a duplicate is the same reading again, colour included
+ expect(copyTimelineTrack(timelineTrack({ label: 'Vessels', color: 'amber' }), []).color)
+ .toBe('amber');
+ expect(TRACK_COLORS).toHaveLength(6);
+ });
+
+ it('restores old specs with explicit defaults', () => {
+ expect(timelineViewState({ from: '2026-01-01', group_by: 'unknown' })).toMatchObject({
+ from: '2026-01-01', to: '', groupBy: 'none', viewMode: 'plot',
+ timezone: 'UTC', zoneChoice: 'utc',
+ });
+ expect(timelineViewState({
+ timezone: 'Europe/Paris', zone_choice: 'place:harbour',
+ })).toMatchObject({ timezone: 'Europe/Paris', zoneChoice: 'place:harbour' });
+ // a zone named outright is the fourth reading, and a view made in it must not come
+ // back on UTC — validated by shape, since whether this machine can load the name is
+ // asked when the axis is drawn
+ expect(timelineViewState({
+ timezone: 'Europe/Kyiv', zone_choice: 'zone:Europe/Kyiv',
+ })).toMatchObject({ zoneChoice: 'zone:Europe/Kyiv' });
+ expect(timelineViewState({ zone_choice: 'zone:../../etc/passwd' }).zoneChoice).toBe('utc');
+ expect(timelineViewState({ zone_choice: 'zone:' }).zoneChoice).toBe('utc');
+ });
+
+ it('derives visible categories from tracks', () => {
+ const restored = timelineViewState({
+ visible_categories: ['case_activity'],
+ tracks: [
+ { id: 'claims', label: 'Claims', categories: ['statement'] },
+ { id: 'files', label: 'Files', categories: ['media'] },
+ ],
+ });
+ expect(restored.categories).toEqual(['statement', 'media']);
+ });
+});
diff --git a/frontend/src/lib/workspaces.js b/frontend/src/lib/workspaces.js
index b762919..002d41f 100644
--- a/frontend/src/lib/workspaces.js
+++ b/frontend/src/lib/workspaces.js
@@ -5,10 +5,22 @@
* workspace is always derived from the active tool, so cross-tool handoffs
* (`uiState.tool = 'proof'`) keep working untouched.
*
- * Future tools land as new entries in a workspace's `tools` array, never as
- * new rail entries. The Case workspace arrives with the v3 investigation
- * layer (today the case sidebar covers it).
+ * Future tools land as new entries in a workspace's `tools` array rather than as
+ * new rail entries.
+ *
+ * `case` is a workspace like any other — tabs, deep links, its own remembered
+ * sidebar — but it is not on the rail. The rail reads as a sequence of stages,
+ * and the case is not a stage: it is what every stage files into. It hangs off
+ * the case switcher in the topbar instead, beside the name of the case it opens.
*/
+export const CASE_WORKSPACE = {
+ id: 'case',
+ label: 'Case',
+ icon: 'graph',
+ tools: ['board', 'graph', 'timeline'],
+};
+
+/** The rail, in investigation order. */
export const WORKSPACES = [
{ id: 'collect', label: 'Sources', icon: 'download', tools: ['media', 'files', 'reverse'] },
{ id: 'examine', label: 'Examine', icon: 'inspect', tools: ['inspect'] },
@@ -16,7 +28,13 @@ export const WORKSPACES = [
{ id: 'compose', label: 'Compose', icon: 'proof', tools: ['proof', 'post', 'notebook'] },
];
+/** Every workspace, on the rail or not — what tool lookup and deep links resolve against. */
+export const ALL_WORKSPACES = [CASE_WORKSPACE, ...WORKSPACES];
+
export const TOOL_LABELS = {
+ board: 'Board',
+ graph: 'Graph',
+ timeline: 'Timeline',
media: 'Media',
files: 'Files',
reverse: 'Reverse Search',
@@ -30,13 +48,17 @@ export const TOOL_LABELS = {
};
export function workspaceOf(tool) {
- return WORKSPACES.find((w) => w.tools.includes(tool)) ?? null;
+ return ALL_WORKSPACES.find((w) => w.tools.includes(tool)) ?? null;
}
-/** Return the session's sidebar state for a workspace, falling back to defaults. */
+/** Return the session's sidebar state for a workspace, falling back to defaults.
+ *
+ * Closed on `map`, which needs the width, and on `case`, where the board already
+ * lists the same entities — two lists of one case side by side is a question about
+ * which one is the real one. */
export function sidebarOpenForWorkspace(workspaceId, remembered = {}) {
if (remembered[workspaceId] !== undefined) return remembered[workspaceId];
- return workspaceId !== 'map';
+ return workspaceId !== 'map' && workspaceId !== 'case';
}
/**
@@ -49,7 +71,7 @@ export function sidebarOpenForWorkspace(workspaceId, remembered = {}) {
export function toolFromHash(hash, allTools) {
const [head, sub] = hash.replace(/^#/, '').split('/');
if (allTools.includes(head)) return head;
- const ws = WORKSPACES.find((w) => w.id === head);
+ const ws = ALL_WORKSPACES.find((w) => w.id === head);
if (!ws) return null;
return sub && ws.tools.includes(sub) ? sub : ws.tools[0];
}
diff --git a/frontend/src/lib/workspaces.test.js b/frontend/src/lib/workspaces.test.js
index 1250268..38c85fe 100644
--- a/frontend/src/lib/workspaces.test.js
+++ b/frontend/src/lib/workspaces.test.js
@@ -1,19 +1,40 @@
import { describe, it, expect } from 'vitest';
-import { WORKSPACES, TOOL_LABELS, sidebarOpenForWorkspace, workspaceOf, toolFromHash } from './workspaces.js';
+import {
+ ALL_WORKSPACES,
+ CASE_WORKSPACE,
+ WORKSPACES,
+ TOOL_LABELS,
+ sidebarOpenForWorkspace,
+ workspaceOf,
+ toolFromHash,
+} from './workspaces.js';
const ALL_TOOLS = [
- 'media', 'files', 'reverse', 'inspect', 'satellite', 'coordinates', 'proof', 'post', 'settings',
+ 'board', 'graph', 'timeline', 'media', 'files', 'reverse', 'inspect', 'satellite', 'coordinates', 'proof', 'post', 'notebook',
+ 'settings',
];
describe('workspaceOf', () => {
- it('maps every rail tool to exactly one workspace', () => {
- for (const tool of ['media', 'files', 'reverse', 'inspect', 'satellite', 'coordinates', 'proof', 'post']) {
- const owners = WORKSPACES.filter((w) => w.tools.includes(tool));
+ it('maps every tool to exactly one workspace', () => {
+ for (const tool of ['board', 'graph', 'timeline', 'media', 'files', 'reverse', 'inspect', 'satellite', 'coordinates', 'proof', 'post', 'notebook']) {
+ const owners = ALL_WORKSPACES.filter((w) => w.tools.includes(tool));
expect(owners).toHaveLength(1);
expect(workspaceOf(tool)).toBe(owners[0]);
}
});
+ it('keeps the case off the rail: it is not a stage, it is what the stages file into', () => {
+ expect(WORKSPACES.map((w) => w.id)).not.toContain('case');
+ expect(WORKSPACES[0].id).toBe('collect');
+ expect(workspaceOf('board')).toBe(CASE_WORKSPACE);
+ expect(workspaceOf('timeline')).toBe(CASE_WORKSPACE);
+ });
+
+ it('resolves the case workspace even though the rail never lists it', () => {
+ expect(ALL_WORKSPACES[0]).toBe(CASE_WORKSPACE);
+ expect(ALL_WORKSPACES).toHaveLength(WORKSPACES.length + 1);
+ });
+
it('groups media, files and reverse search under collect', () => {
expect(workspaceOf('media').id).toBe('collect');
expect(workspaceOf('files').id).toBe('collect');
@@ -41,12 +62,15 @@ describe('product-facing labels', () => {
expect(WORKSPACES.find((w) => w.id === 'collect').label).toBe('Sources');
expect(TOOL_LABELS.proof).toBe('Geo Proof');
expect(TOOL_LABELS.post).toBe('Geo Report');
+ expect(TOOL_LABELS.timeline).toBe('Timeline');
});
});
describe('sidebarOpenForWorkspace', () => {
- it('defaults Map closed and other workspaces open', () => {
+ it('defaults Map and Case closed, and other workspaces open', () => {
expect(sidebarOpenForWorkspace('map')).toBe(false);
+ // the board lists the same case: two lists side by side ask which is the real one
+ expect(sidebarOpenForWorkspace('case')).toBe(false);
expect(sidebarOpenForWorkspace('collect')).toBe(true);
expect(sidebarOpenForWorkspace('examine')).toBe(true);
});
@@ -67,6 +91,9 @@ describe('toolFromHash', () => {
it('accepts a bare workspace id (first tool)', () => {
expect(toolFromHash('#collect', ALL_TOOLS)).toBe('media');
expect(toolFromHash('#compose', ALL_TOOLS)).toBe('proof');
+ // off the rail, still a workspace: #case has to keep resolving
+ expect(toolFromHash('#case', ALL_TOOLS)).toBe('board');
+ expect(toolFromHash('#case/timeline', ALL_TOOLS)).toBe('timeline');
});
it('accepts workspace/tab form', () => {
diff --git a/frontend/src/tools/Board.svelte b/frontend/src/tools/Board.svelte
new file mode 100644
index 0000000..c1bdf82
--- /dev/null
+++ b/frontend/src/tools/Board.svelte
@@ -0,0 +1,1513 @@
+<script>
+ /**
+ * The case as its graph: every entity the case holds, filtered, sorted and opened.
+ *
+ * Until this existed the vocabulary was reachable only through the API. A case
+ * could hold a `person`, a `claim` or an `account` — the registry declared them,
+ * the relation verbs accepted them — but no screen created one, so a bookmark had
+ * nothing to be related *to* and a statement had nowhere to be read. That is what
+ * this tool is: create the hand-made types, list what the case holds, and open any
+ * row in the same Details panel every other surface uses.
+ *
+ * Bounded like every other list here (docs/STORAGE_AND_PERFORMANCE.md): one page
+ * off the catalog endpoint, filters applied server-side, "Show more" for the rest.
+ * A case that fits one page filters in memory, so typing costs no request.
+ *
+ * One view, a table. Two views of the same rows only asked which one was the real
+ * one. The graph is what comes next, and that is a different question, not a
+ * different rendering of this list.
+ */
+ import { untrack } from 'svelte';
+ import { api } from '../lib/api.js';
+ import {
+ analysisSearch,
+ catalogViews,
+ openAnalysisCase,
+ setAnalysisFilter,
+ setAnalysisPeriod,
+ } from '../lib/analysisSearch.svelte.js';
+ import {
+ analysisPeriodQuery,
+ analysisPeriodSpec,
+ emptyAnalysisPeriod,
+ hasAnalysisPeriod,
+ normalizeAnalysisPeriod,
+ } from '../lib/analysisPeriod.js';
+ import { caseState, reloadCase, toast, uiState } from '../lib/state.svelte.js';
+ import { buildCatalogQuery, buildTallyQuery, fetchAttrFacets } from '../lib/catalog.js';
+ import {
+ confidenceLine,
+ countLines,
+ isEmpty as nothingTotalled,
+ noteLines,
+ readingNotes,
+ } from '../lib/tally.js';
+ import { createPagedList } from '../lib/pagedList.svelte.js';
+ import { entitySearchMatches, matchesEntity } from '../lib/entitySearch.js';
+ import { entityIcon } from '../lib/entityIcon.js';
+ import { fileUrl } from '../lib/fileUrl.js';
+ import { folderOf } from '../lib/folderTree.js';
+ import { deletedToast } from '../lib/trash.js';
+ import {
+ chipsOf,
+ clearAxis,
+ emptyFilter,
+ isFiltering,
+ normalizeFilter,
+ orderFor,
+ toGraphQuery,
+ toQuery,
+ } from '../lib/entityFilter.js';
+ import {
+ creatableTypes,
+ entityFamily,
+ entityFields,
+ entityHint,
+ entityIdentityLabel,
+ entityLabel,
+ entityTypes,
+ familyReads,
+ loadEntityTypes,
+ } from '../lib/entityTypes.svelte.js';
+ import { createBookmark } from '../lib/bookmarks.js';
+ import { windowWords } from '../lib/timeline.js';
+ import { listenForPaste, pasteImage, resolvePaste } from '../lib/clipboardPaste.js';
+ import Icon from '../components/Icon.svelte';
+ import Modal from '../components/Modal.svelte';
+ import ConfirmDialog from '../components/ConfirmDialog.svelte';
+ import AnalysisViews from '../components/AnalysisViews.svelte';
+ import AnalysisPeriodBar from '../components/AnalysisPeriodBar.svelte';
+ import FilterBar from '../components/FilterBar.svelte';
+ import EntityCreate from '../components/EntityCreate.svelte';
+ import EntityDetails from '../components/EntityDetails.svelte';
+ import PasteDialog from '../components/PasteDialog.svelte';
+ import SnapshotDetails from '../components/SnapshotDetails.svelte';
+ import ViewSwitch from '../components/ViewSwitch.svelte';
+
+ const PAGE = 100;
+
+ loadEntityTypes();
+
+ /**
+ * The question being asked of the case, as one value (`lib/entityFilter.js`).
+ *
+ * It used to be six variables behind six selects, four of which appeared and
+ * disappeared as the others were set — so a term that was live looked exactly like
+ * one that was not, and the most useful filter in the app was invisible until you
+ * happened to narrow by type first. One object, one chip per term, one bar that
+ * never changes shape.
+ */
+ let filter = $state(emptyFilter());
+ let facets = $state([]); // the fields these types hold, and their values
+ /** Whether the field menu has anything to offer, or why it has not: nothing is
+ * scanned for a menu nobody has opened. */
+ let facetState = $state('unasked'); // 'unasked' | 'loading' | 'ready'
+ let sortKey = $state(''); // '' = the catalog's own stable order
+ let sortDesc = $state(false);
+ let summary = $state(null); // { total, by_type, by_status, by_folder, by_source, unlinked }
+ let openId = $state(null); // the row whose Details are open
+ let snapshotOpen = $state(null); // a captured row, read without touching the live case
+ let draft = $state(null); // the entity being created, or null
+ let busyId = $state(null); // the row whose review action is in flight
+ let discarding = $state(false); // Details closing with unsaved fields on screen
+ let dirty = $state(false); // Details has edits the panel's Save has not taken
+
+ /** The families the case actually holds, read off the summary: a filter offering a
+ * family nothing is filed under is offering an empty answer. */
+ const families = $derived(
+ [
+ ...new Set(
+ Object.keys(summary?.by_type ?? {})
+ .map((type) => entityFamily(type))
+ .filter(Boolean)
+ ),
+ ].sort()
+ );
+ /** The type menu follows the family chips: picking "actor" leaves two types to
+ * choose between rather than seventeen. */
+ const typeOptions = $derived(
+ entityTypes().filter(
+ (entry) => !filter.families.length || filter.families.includes(entry.family)
+ )
+ );
+
+ /** What the request asks for: the types picked, or every type of the families
+ * picked, or nothing at all — the family layer is server vocabulary, so it
+ * resolves to types here rather than needing a route of its own. */
+ const wantedTypes = $derived(
+ filter.types.length
+ ? filter.types
+ : filter.families.length
+ ? typeOptions.map((entry) => entry.type)
+ : []
+ );
+
+ /** The one type on screen, or '' for a mixed list. What decides the declared
+ * columns and what the first one is called: a column of addresses headed "Name" is
+ * the lie this vocabulary went to the trouble of avoiding, and a mixed list has no
+ * such reading to give. */
+ const onlyType = $derived(filter.types.length === 1 ? filter.types[0] : '');
+ const activePeriod = $derived(hasAnalysisPeriod(analysisSearch.period));
+
+ /** A type left outside the families now chosen would filter to nothing, so it goes
+ * with them — the same rule the family select used to apply on its way out. */
+ $effect(() => {
+ if (!filter.families.length || !filter.types.length) return;
+ const inside = filter.types.filter((type) =>
+ typeOptions.some((entry) => entry.type === type)
+ );
+ if (inside.length !== filter.types.length) filter = { ...filter, types: inside };
+ });
+
+ const pl = createPagedList({
+ fetchPage: ({ query: q, cursor }) =>
+ api.get(
+ buildCatalogQuery(caseState.current.id, {
+ cursor,
+ limit: PAGE,
+ ...toQuery({ ...filter, q }, { types: wantedTypes }),
+ ...(catalogViews.snapshotId ? {} : analysisPeriodQuery(analysisSearch.period)),
+ order,
+ view: catalogViews.snapshotId || undefined,
+ })
+ ),
+ });
+
+ // Hand the term to the list, which records it on a small case and debounces a
+ // server search on a large one. Without this the box would go quiet at exactly
+ // the size that needs it: past one page, the rows are the server's answer and
+ // filtering them here would search the page rather than the case.
+ $effect(() => {
+ pl.setQuery(filter.q);
+ });
+
+ // A small case never reaches the server for a keystroke, so the term is applied
+ // here; a large one is already searching server-side and the rows are the answer.
+ // Same predicate either way (`lib/entitySearch.js`), or the box would answer one
+ // way under a hundred rows and another way over.
+ const matching = $derived(
+ pl.serverMode || !filter.q.trim()
+ ? pl.items
+ : pl.items.filter((e) => matchesEntity(e, filter.q))
+ );
+ const filtering = $derived(isFiltering(filter) || activePeriod);
+ const snapshotReading = $derived(Boolean(catalogViews.snapshotId));
+ /** How many the question matches, across the case. The page's own count, except on
+ * a small case searching in memory — there the server was never told the term, so
+ * its count would answer a wider question than the one on screen. */
+ const matchCount = $derived(
+ pl.serverMode || !filter.q.trim() ? pl.total : matching.length
+ );
+ /** What the answer is a part of. The **whole case**, always: a proportion is the
+ * information a count carries, and a denominator that shrinks with the numerator
+ * carries none. */
+ const caseTotal = $derived(summary?.total ?? pl.total);
+
+ /**
+ * The same question, added up instead of listed.
+ *
+ * Not a second view of these rows — the one thing this tool refuses (see the top of
+ * this file) — but the one answer the rows cannot give. A case that follows a
+ * conflict writes *two of these destroyed here* twenty times over, and twenty rows
+ * later what the analyst wants is the total, which a table gives only by being added
+ * up by hand.
+ *
+ * So it is a **gesture on the question**, exactly like "Draw these": the chips stay
+ * where they are, the sentence is unchanged, and what moves is what is done with the
+ * answer. Every rule about what may enter a sum is the server's
+ * (`engine/tally.py`), and every word about what was left out of one is
+ * `lib/tally.js` — a total printed bare is true and misleading in the same breath.
+ */
+ let totalling = $state(false);
+ let tally = $state(null);
+ let tallying = $state(false);
+
+ /**
+ * The two renderings, as the switch offers them.
+ *
+ * **Totals is offered from the first day and dimmed until it can draw a real line**,
+ * rather than appearing the day a case gains one — the rule the filter menu already
+ * follows: a control you can see and cannot use teaches something, one that is not
+ * there teaches nothing.
+ *
+ * What makes a line real is both halves at once: a statement carrying a **number**,
+ * and pointing at **something** (`summary.countable`). Either alone opens the total
+ * on nothing — *seen, not counted* is an answer rather than a row, and a statement
+ * about nothing has no subject to sit under — and a reading that opens on an empty
+ * answer reads as a finding about the case instead of as a control that was not
+ * ready. Priced by the same summary every filter term is priced from, so it costs no
+ * request of its own.
+ *
+ * The state currently on is never dimmed (`ViewSwitch` enforces it too), or the
+ * screen would show itself as unavailable while being what is on screen.
+ */
+ const countable = $derived(summary?.countable ?? 0);
+ const viewOptions = $derived.by(() => {
+ const nothingToDraw = countable === 0;
+ const empty = !rows.length;
+ return [
+ { id: 'rows', label: 'Rows', icon: 'note', hint: 'One row per thing the case holds' },
+ {
+ id: 'totals',
+ label: 'Totals',
+ icon: 'hash',
+ disabled: nothingToDraw || empty || snapshotReading,
+ hint: snapshotReading
+ ? 'A frozen snapshot holds rows rather than a question to add up'
+ : nothingToDraw
+ ? 'No statement counts anything about a subject yet'
+ : empty
+ ? 'Nothing in the table to add up'
+ : 'What the statements about these come to, per subject',
+ },
+ ];
+ });
+
+ /**
+ * Read on the same terms as the page, and only while it is on screen: a total
+ * nobody is looking at is a request nobody is waiting for.
+ *
+ * Debounced on **every** term rather than on the text one alone. The search box is
+ * the only term that changes per keystroke, but a sum has no in-memory half to fall
+ * back on the way the row list does — the arithmetic is the server's at any case
+ * size — so one delay for the whole question is one rule instead of a term-by-term
+ * bookkeeping, and a quarter second after a chip click is not felt.
+ */
+ const TALLY_DELAY = 250; // the paged list's own, for the same box
+ $effect(() => {
+ if (!totalling || snapshotReading || !caseState.current?.id) return;
+ // A statement stated, counted or related changes what the case comes to, and the
+ // total is the one reading where that is the whole point. Read like the row list
+ // beside it and like the panel's own total, or a relation added while this is on
+ // screen would need the page reloaded to appear in it.
+ caseState.rev;
+ const url = buildTallyQuery(caseState.current.id, {
+ ...toQuery(filter, { types: wantedTypes }),
+ ...analysisPeriodQuery(analysisSearch.period),
+ });
+ let current = true;
+ const timer = setTimeout(() => {
+ tallying = true;
+ api
+ .get(url)
+ .then((body) => {
+ if (current) tally = body;
+ })
+ .catch(() => {
+ if (current) tally = null;
+ })
+ .finally(() => {
+ if (current) tallying = false;
+ });
+ }, TALLY_DELAY);
+ return () => {
+ current = false;
+ clearTimeout(timer);
+ };
+ });
+
+ /** A snapshot is a frozen copy of rows rather than a question the case can still be
+ * asked, so the addition has nothing to run over and steps back to the list. */
+ $effect(() => {
+ if (snapshotReading && totalling) totalling = false;
+ });
+
+ /** The condition and confidence words, from the served registry rather than spelled
+ * again here: a level added there reads correctly in the tally with no edit. */
+ const claimReads = $derived.by(() => {
+ const reads = {};
+ for (const field of entityFields('claim')) {
+ for (const option of field.options ?? []) reads[option.value] = option.label;
+ }
+ return (value) => reads[value] ?? value;
+ });
+
+ /** The columns a table shows beyond the ones every entity has. Only when a single
+ * type is picked: a mixed list has no shared attributes, and a column that is
+ * blank for four rows out of five is noise. Read-only here — editing cells and
+ * CSV are the Case Sheet's, not this list's. */
+ const columns = $derived(onlyType ? entityFields(onlyType) : []);
+
+ /** What the first column is called. Once a single type is picked it holds that
+ * type's own identity — an IP address, a handle — and the create form already
+ * says so; "Name" over a column of addresses is the same lie this vocabulary
+ * went to the trouble of avoiding. Mixed rows have no such reading. */
+ const identityColumn = $derived(onlyType ? entityIdentityLabel(onlyType) : 'Name');
+
+ /**
+ * Which ordering the store is being asked for, or '' when the sort is this page's
+ * own (`lib/entityFilter.js`).
+ *
+ * Two of the headings name a column the case can be ordered by, and clicking one
+ * asks the **case** for its newest or its alphabet rather than sorting the hundred
+ * rows that happen to be loaded. The other headings have no such column, so they
+ * keep the client sort and say so. One gesture either way: which of the two it is
+ * is a property of the column, not a second control the analyst has to find.
+ */
+ const order = $derived(orderFor(sortKey, sortDesc));
+
+ /** Sorted here only when the store did not sort it. What the note beside "Show
+ * more" is about: an alphabet over the first hundred of eight hundred rows looks
+ * exactly like an alphabet over the case. */
+ const rows = $derived.by(() => {
+ if (!sortKey || order) return matching;
+ const direction = sortDesc ? -1 : 1;
+ return [...matching].sort((a, b) => {
+ const left = sortValue(a, sortKey);
+ const right = sortValue(b, sortKey);
+ if (typeof left === 'number' && typeof right === 'number') return (left - right) * direction;
+ return String(left).localeCompare(String(right)) * direction;
+ });
+ });
+
+ function sortValue(entity, key) {
+ if (key === 'label') return (entity.label ?? '').toLowerCase();
+ if (key === 'type') return entityLabel(entity.type).toLowerCase();
+ if (key === 'folder') return folderName(entity).toLowerCase();
+ if (key === 'created') return entity.provenance?.at ?? '';
+ const field = columns.find((column) => column.key === key);
+ if (!field) return '';
+ // a number sorts as one: "100" before "25" is the classic table bug
+ if (field.kind === 'number') {
+ const value = Number(entity.attrs?.[field.key]);
+ return Number.isFinite(value) ? value : -Infinity;
+ }
+ return cell(entity, field).toLowerCase();
+ }
+
+ /** Click a heading to sort by it, click it again to reverse. A third click is not
+ * a third state: the catalog's order is what the empty sort already is. */
+ function sortBy(key) {
+ if (sortKey === key) sortDesc = !sortDesc;
+ else {
+ sortKey = key;
+ sortDesc = false;
+ }
+ }
+
+ let loadedFor = null;
+ $effect(() => {
+ const id = caseState.current?.id;
+ caseState.rev; // a save, a delete or a relation stated in the panel
+ if (!id) {
+ pl.clear();
+ summary = null;
+ loadedFor = null;
+ return;
+ }
+ if (loadedFor !== id) {
+ loadedFor = id;
+ pl.clear();
+ // The question travels with the case, not with the tab: reopening Azimut on a
+ // case lands on what was being asked of it.
+ openAnalysisCase(id);
+ filter = normalizeFilter(analysisSearch.filter);
+ fieldsWanted = false;
+ facetState = 'unasked';
+ }
+ void pl.reload();
+ api
+ .get(`/api/cases/${id}/catalog/summary`)
+ .then((s) => {
+ if (caseState.current?.id === id) summary = s;
+ })
+ .catch(() => {});
+ });
+
+ // Graph edits the same Search+ value while this mounted tool is hidden. Mirror
+ // that value back into the local bindable object without waiting for a case reload.
+ $effect(() => {
+ const id = caseState.current?.id;
+ const shared = JSON.stringify(analysisSearch.filter);
+ if (
+ !id || analysisSearch.caseId !== id ||
+ shared === untrack(() => JSON.stringify(filter))
+ ) return;
+ untrack(() => (filter = normalizeFilter(analysisSearch.filter)));
+ });
+
+ // A filter is a different request, so the baseline is re-established rather than
+ // filtered out of what is already loaded — page two of "every type" is not page
+ // two of "places".
+ // Seeded with the filter's own initial value, so opening the board is one request
+ // rather than this effect and the case effect above both asking for page one.
+ let lastAsked = null;
+ $effect(() => {
+ const asked = JSON.stringify([
+ toQuery(filter, { types: wantedTypes }),
+ analysisPeriodQuery(analysisSearch.period),
+ order,
+ catalogViews.snapshotId,
+ ]);
+ if (asked === lastAsked) {
+ setAnalysisFilter(caseState.current?.id, filter);
+ return;
+ }
+ const first = lastAsked === null;
+ lastAsked = asked;
+ setAnalysisFilter(caseState.current?.id, filter);
+ // The text term is the paged list's own, debounced there; asking again here would
+ // be a second request per keystroke.
+ if (!first && caseState.current?.id) void pl.reload();
+ });
+
+ /**
+ * The fields on offer follow the types being listed, in one bounded read.
+ *
+ * **Read on demand**, which is the change that stopped the field filter being
+ * invisible: the scan costs the stored attributes of everything the narrowing
+ * covers, so it used to be gated behind picking a type first — and an analyst who
+ * had not picked one never learnt the filter existed. Now the gate is the click
+ * that opens the menu, which is the explicit act the cost was always worth paying
+ * behind.
+ *
+ * **The size of the case decides nothing.** It used to: past five thousand entities
+ * the menu went dark and asked for a type first, which is exactly backwards — a case
+ * that large is the one where a field is the only practical way to narrow. The scan
+ * is linear and small (measured: 50 000 entities in 0.3 s, 100 000 in 0.7 s), and
+ * what keeps the menu readable is the server's own bound on **values** — a field
+ * holding more of them than the limit comes back with none and says it was cut. That
+ * was always the right bound; the entity count never was.
+ *
+ * A field that survives a narrowing keeps its value, since changing the type filter
+ * must not silently drop the term beside it; one that does not is cleared and said,
+ * because a question about a field nothing on screen carries has no answer.
+ */
+ let fieldsWanted = $state(false);
+ let facetsFor = null;
+ $effect(() => {
+ const id = caseState.current?.id;
+ caseState.rev; // a save can add the first entity carrying a field
+ const key = `${id ?? ''}|${wantedTypes.join(',')}|${caseState.rev}`;
+ if (!id) {
+ facets = [];
+ facetsFor = null;
+ facetState = 'unasked';
+ return;
+ }
+ if (!wantedTypes.length && !fieldsWanted) {
+ facets = [];
+ facetsFor = null;
+ facetState = 'unasked';
+ return;
+ }
+ if (facetsFor === key) return;
+ facetsFor = key;
+ facetState = 'loading';
+ fetchAttrFacets(id, wantedTypes)
+ .then((rows) => {
+ if (caseState.current?.id !== id) return;
+ facets = rows;
+ facetState = 'ready';
+ if (filter.attrKey && !rows.some((row) => row.key === filter.attrKey && row.values.length)) {
+ const dropped = filter.attrKey;
+ filter = clearAxis(filter, 'field');
+ toast(`Nothing on screen carries ${dropped}, so that term went`, 'warn');
+ }
+ })
+ .catch(() => {
+ facets = [];
+ facetState = 'ready';
+ });
+ });
+
+ // A value that is no longer among the field's own is not a term the table can
+ // answer, and left on screen it would read as a filter that stopped working.
+ $effect(() => {
+ if (!filter.attrValue) return;
+ const held = facets.find((row) => row.key === filter.attrKey)?.values ?? [];
+ if (held.length && !held.some((row) => row.value === filter.attrValue)) {
+ filter = { ...filter, attrValue: '' };
+ }
+ });
+
+ // A column that is no longer on screen cannot go on ordering the table.
+ $effect(() => {
+ const keys = ['label', 'type', 'folder', 'created', ...columns.map((c) => c.key)];
+ if (sortKey && !keys.includes(sortKey)) sortKey = '';
+ });
+
+ /** Start from what the analyst is already looking at: the chosen type, or the
+ * first type of the chosen family. Opening on "Person" while the family chip
+ * says Identifier is the menu ignoring the question just asked. */
+ function startCreate() {
+ if (snapshotReading) return;
+ const wanted = creatableTypes().filter(
+ (entry) => !filter.families.length || filter.families.includes(entry.family)
+ );
+ draft = {
+ type: onlyType || wanted[0]?.type || creatableTypes()[0]?.type || '',
+ label: '',
+ notes: '',
+ attrs: {},
+ };
+ }
+
+ /** Accept a machine's proposal. The far end of its suggested relations comes with
+ * it, which is the invariant the API keeps: an edge is confirmed together with
+ * the entity it hangs off, or neither is. */
+ async function confirmEntity(entity) {
+ if (snapshotReading) return;
+ if (busyId) return;
+ busyId = entity.id;
+ try {
+ await api.patch(`/api/cases/${caseState.current.id}/entities/${entity.id}`, {
+ status: 'confirmed',
+ });
+ await reloadCase();
+ toast('Confirmed', 'ok', 1600);
+ } catch (e) {
+ toast(e.message, 'danger');
+ } finally {
+ busyId = null;
+ }
+ }
+
+ /** Drop a proposal. The standard delete, so it lands in the case trash with the
+ * same Undo as every other one — dismissing a machine's reading is not a reason
+ * to make it unrecoverable. */
+ async function dismissEntity(entity) {
+ if (snapshotReading) return;
+ if (busyId) return;
+ busyId = entity.id;
+ const caseId = caseState.current.id;
+ try {
+ const result = await api.del(`/api/cases/${caseId}/entities/${entity.id}`);
+ await reloadCase();
+ deletedToast(caseId, result, entity.label);
+ } catch (e) {
+ toast(e.message, 'danger');
+ } finally {
+ busyId = null;
+ }
+ }
+
+ /**
+ * Take a file into the case: a PDF, a scan, a plan, an exported mail.
+ *
+ * The same import the Media Library runs, offered where the case is read rather
+ * than only under "Media" — a word that says nothing about a scanned plan. The
+ * file lands as a `media` of whatever kind its bytes are (ONTOLOGY §2), hashed,
+ * deduped on that hash, and relatable like everything else here.
+ */
+ let fileInput = $state();
+ let importing = $state(false);
+ let dragOver = $state(false);
+
+ async function importFiles(fileList) {
+ const files = [...(fileList ?? [])];
+ if (snapshotReading) return;
+ if (!files.length || !caseState.current || importing) return;
+ const caseId = caseState.current.id;
+ importing = true;
+ let added = 0;
+ let duplicates = 0;
+ let last = null;
+ try {
+ for (const file of files) {
+ const form = new FormData();
+ form.append('file', file);
+ try {
+ const result = await api.post(`/api/cases/${caseId}/media/upload`, form);
+ if (result.duplicate) duplicates++;
+ else added++;
+ last = result.entity?.id ?? last;
+ } catch (e) {
+ toast(`${file.name}: ${e.message}`, 'danger');
+ }
+ }
+ await reloadCase();
+ if (added) toast(`${added} file${added > 1 ? 's' : ''} added to the case`, 'ok');
+ // The same bytes twice is not an error and not a second item: the case keeps
+ // the one it has, and saying so is what stops the analyst importing again.
+ if (duplicates) {
+ toast(
+ `${duplicates} duplicate${duplicates > 1 ? 's' : ''} skipped (same SHA-256)`,
+ 'warn'
+ );
+ }
+ // One file opens where the analyst can say what it is; a batch does not, since
+ // a panel over the list would be about whichever one happened to land last.
+ if (files.length === 1 && last) openId = last;
+ } finally {
+ importing = false;
+ }
+ }
+
+ // ── paste ────────────────────────────────────────────────────────────────────
+ /**
+ * Ctrl+V files what the clipboard holds and opens the row it made.
+ *
+ * The table is where the case is read as a list, and a screenshot or a link
+ * arriving while reading it has somewhere to be: filed, then open, so the next
+ * gesture is relating it to whatever prompted the paste.
+ */
+ let pasted = $state(null);
+ let pasteBusy = $state(false);
+ $effect(() => {
+ if (uiState.tool !== 'board') return;
+ return listenForPaste((payload) => {
+ if (snapshotReading) {
+ toast('This snapshot is read-only. Leave it to paste.', 'warn');
+ return;
+ }
+ pasted ??= resolvePaste('board', payload);
+ });
+ });
+
+ async function confirmPaste(resolved) {
+ const caseId = caseState.current?.id;
+ if (pasteBusy || !caseId) return;
+ pasteBusy = true;
+ const { kind, values, payload } = resolved;
+ try {
+ if (kind === 'image') {
+ const result = await pasteImage(caseId, {
+ file: payload.file,
+ title: values.title,
+ sourceUrl: values.source,
+ });
+ pasted = null;
+ await reloadCase();
+ // The same bytes twice is not an error and not a second row: the case keeps
+ // the one it has, and saying so is what stops the analyst pasting again.
+ if (result.duplicate) toast('Already in the case (same SHA-256)', 'warn');
+ openId = result.entity.id;
+ } else {
+ const entity = await createBookmark(caseId, { ...values, url: payload.url });
+ pasted = null;
+ await reloadCase();
+ openId = entity.id;
+ }
+ } catch (e) {
+ toast(e.message, 'danger');
+ } finally {
+ pasteBusy = false;
+ }
+ }
+
+ function closeDetails() {
+ if (dirty) discarding = true;
+ else openId = null;
+ }
+
+ // Following a relation to a person, an account or a claim lands here: those types
+ // have no tool of their own, so `navigate.openEntity` hands the id over instead.
+ $effect(() => {
+ const id = uiState.openBoardEntity;
+ if (!id) return;
+ uiState.openBoardEntity = null;
+ if (snapshotReading) {
+ snapshotOpen = catalogViews.activeView?.spec?.snapshot?.entities?.find(
+ (entity) => entity.id === id
+ ) ?? null;
+ } else {
+ openId = id;
+ }
+ });
+
+ /** The slug with a capital, not a second vocabulary: the families are code, and
+ * inventing readings for them here is how two lists start. */
+ const familyTitle = (family) => family.charAt(0).toUpperCase() + family.slice(1);
+
+ /** The question as one sentence, which is what the graph writes over the drawing
+ * so nobody has to remember what they asked two tabs ago. */
+ const said = $derived(
+ [
+ filter.q.trim() ? `“${filter.q.trim()}”` : '',
+ ...chipsOf(filter, { type: entityLabel, family: familyTitle }).map((chip) => chip.text),
+ activePeriod ? `Fact time · ${windowWords(
+ analysisSearch.period.from, analysisSearch.period.to, 'UTC'
+ )}` : '',
+ ]
+ .filter(Boolean)
+ .join(' · ')
+ );
+ const drawTitle = $derived(`Draw this question in the graph: ${said}`);
+
+ /**
+ * Hand the question to the graph.
+ *
+ * The **filter** goes over, never the ids it matched. A list of ids would be capped,
+ * would bloat the URL, and would go stale the moment anything was saved; the filter
+ * is a question the case can be asked again, and both surfaces resolve it through
+ * one predicate — so what the drawing holds is what the table counted.
+ */
+ function drawAnswer() {
+ uiState.drawInGraph = {
+ terms: toGraphQuery(filter, { types: wantedTypes }),
+ label: said,
+ filter: normalizeFilter(filter),
+ };
+ uiState.tool = 'graph';
+ }
+
+ function openPeriodInTimeline() {
+ uiState.timelineRange = {
+ from: analysisSearch.period.from,
+ to: analysisSearch.period.to,
+ };
+ uiState.tool = 'timeline';
+ }
+
+ function openPeriodOnMap() {
+ uiState.mapTimelineRange = {
+ from: analysisSearch.period.from,
+ to: analysisSearch.period.to,
+ categories: analysisSearch.period.categories ?? [],
+ };
+ uiState.tool = 'satellite';
+ }
+
+ function clearPeriod() {
+ setAnalysisPeriod(caseState.current?.id, emptyAnalysisPeriod());
+ }
+
+ /** The portable recipe. Snapshot rows are resolved server-side from the same
+ * question, so a case larger than the page is never silently cut to what loaded. */
+ function captureAnalysisView() {
+ return {
+ version: 1,
+ query: {
+ filter: normalizeFilter(filter),
+ terms: toGraphQuery(filter, { types: wantedTypes }),
+ label: said,
+ },
+ board: { order, sortKey, sortDesc },
+ timeline: analysisPeriodSpec(analysisSearch.period),
+ };
+ }
+
+ async function openAnalysisView(view) {
+ openId = null;
+ snapshotOpen = null;
+ filter = normalizeFilter(view.spec?.query?.filter);
+ const board = view.spec?.board ?? {};
+ sortKey = typeof board.sortKey === 'string' ? board.sortKey : '';
+ sortDesc = board.sortDesc === true;
+ // Board and Graph read one saved question, so a Graph view opened here is a
+ // request for the other drawing of it. The Timeline keeps its own views.
+ if (view.surface === 'graph') uiState.tool = 'graph';
+ }
+
+ let appliedViewId = null;
+ $effect(() => {
+ const view = catalogViews.activeView;
+ if (!view) {
+ appliedViewId = null;
+ return;
+ }
+ if (view.surface !== 'board' || view.id === appliedViewId) return;
+ appliedViewId = view.id;
+ untrack(() => void openAnalysisView(view));
+ });
+
+ let observedLiveView = null;
+ let observedLiveState = '';
+ $effect(() => {
+ const view = catalogViews.activeView;
+ if (!view || view.mode !== 'live' || view.surface !== 'board') {
+ observedLiveView = null;
+ observedLiveState = '';
+ return;
+ }
+ const savedFilter = normalizeFilter(view.spec?.query?.filter);
+ const savedBoard = view.spec?.board ?? {};
+ const current = JSON.stringify({
+ filter: normalizeFilter(filter),
+ period: normalizeAnalysisPeriod(analysisSearch.period),
+ sortKey,
+ sortDesc,
+ });
+ const saved = JSON.stringify({
+ filter: savedFilter,
+ period: normalizeAnalysisPeriod(view.spec?.timeline),
+ sortKey: typeof savedBoard.sortKey === 'string' ? savedBoard.sortKey : '',
+ sortDesc: savedBoard.sortDesc === true,
+ });
+ if (observedLiveView !== view.id) {
+ observedLiveView = view.id;
+ observedLiveState = current;
+ } else if (current !== observedLiveState) {
+ observedLiveState = current;
+ catalogViews.changeVersion += 1;
+ }
+ catalogViews.modified = current !== saved;
+ });
+
+ function leaveAnalysisReading() {
+ appliedViewId = null;
+ openId = null;
+ snapshotOpen = null;
+ filter = normalizeFilter(analysisSearch.filter);
+ }
+
+ const matchReasons = (entity) =>
+ entity.matches?.length ? entity.matches : entitySearchMatches(entity, filter.q);
+ const folderName = (entity) => folderOf(entity) || '';
+ const created = (entity) => (entity.provenance?.at ?? '').slice(0, 10);
+ const isSuggested = (entity) => entity.provenance?.status === 'suggested';
+ /** Declared fields hold text, a number or a closed grade. A shape is not
+ * a cell, so it says what it is rather than spilling coordinates across a row. */
+ const cell = (entity, field) => {
+ const value = entity.attrs?.[field.key];
+ if (value == null || value === '') return '';
+ if (field.kind === 'geojson') return 'traced area';
+ return String(value);
+ };
+</script>
+
+<div class="tool">
+ <div class="tool-header">
+ <h2>Board</h2>
+ <span class="sub">Everything this case holds</span>
+ <div class="spacer"></div>
+ <AnalysisViews
+ surface="board"
+ capture={captureAnalysisView}
+ onopen={openAnalysisView}
+ onleave={leaveAnalysisReading}
+ />
+ <button
+ class="btn"
+ title="Take a file into the case: a document, a scan, a plan, an image"
+ disabled={!caseState.current || importing || snapshotReading}
+ onclick={() => fileInput?.click()}
+ >
+ <Icon name="upload" size={14} /> {importing ? 'Adding…' : 'Add file'}
+ </button>
+ <input
+ type="file"
+ multiple
+ hidden
+ bind:this={fileInput}
+ onchange={(e) => {
+ importFiles(e.currentTarget.files);
+ e.currentTarget.value = '';
+ }}
+ />
+ <button class="btn btn-primary" onclick={startCreate} disabled={!caseState.current || snapshotReading}>
+ <Icon name="plus" size={14} /> New entity
+ </button>
+ </div>
+
+ <!-- The question, as a bar that never changes shape: a search, one menu, and a chip
+ per term. Every menu behind it is built from what the case holds and counted,
+ so a term says how much of an answer it is before it is chosen. -->
+ <FilterBar
+ bind:filter
+ {summary}
+ {facets}
+ {facetState}
+ {families}
+ caseFolders={caseState.current?.folders ?? []}
+ types={typeOptions}
+ familyName={familyTitle}
+ typeName={entityLabel}
+ familyHint={familyReads}
+ typeHint={entityHint}
+ onfields={() => (fieldsWanted = true)}
+ disabled={snapshotReading}
+ />
+
+ {#if activePeriod}
+ <AnalysisPeriodBar
+ period={analysisSearch.period}
+ ontimeline={openPeriodInTimeline}
+ onmap={openPeriodOnMap}
+ onclear={clearPeriod}
+ />
+ {/if}
+
+ <!-- The answer, and what it is an answer out of. The denominator is the whole case
+ even under a filter: a proportion is the information a count carries. -->
+ <p class="answer">
+ <span class="said">
+ {#if !caseState.current}
+ &nbsp;
+ {:else if filtering}
+ <strong>{matchCount}</strong> of {caseTotal}
+ <!-- The table is good at narrowing and says nothing about how things join up;
+ the drawing is the opposite. This is the one gesture between them, and it
+ hands over the **question** rather than the rows it matched — so it works at
+ any size, and the drawing stays live as the case changes under it. -->
+ <button class="as-link" onclick={drawAnswer} title={drawTitle}>
+ Draw these {matchCount}
+ </button>
+ {:else}
+ {caseTotal} in this case
+ {/if}
+ </span>
+ <!-- How this screen renders the answer, in the control Files and the Media Library
+ already use for the same job. What a single subject comes to is read where
+ that subject is, in its own Details; this one reads several at once, ranked. -->
+ <ViewSwitch
+ options={viewOptions}
+ value={totalling ? 'totals' : 'rows'}
+ onpick={(id) => (totalling = id === 'totals')}
+ />
+ </p>
+
+ <!-- Dropping a file onto the list files it, the way the Media Library takes one.
+ `dragleave` is guarded on the container itself: the event fires for every
+ child the pointer crosses, so an unguarded handler flickers the overlay off
+ halfway across the table. -->
+ <div
+ class="body"
+ role="presentation"
+ ondragover={(e) => {
+ if (!caseState.current || snapshotReading) return;
+ e.preventDefault();
+ dragOver = true;
+ }}
+ ondragleave={(e) => {
+ if (e.target === e.currentTarget) dragOver = false;
+ }}
+ ondrop={(e) => {
+ e.preventDefault();
+ dragOver = false;
+ importFiles(e.dataTransfer?.files);
+ }}
+ >
+ {#if dragOver}
+ <div class="drop-overlay">
+ <div class="drop-box">
+ <Icon name="upload" size={28} />
+ <span>Drop to file it in this case</span>
+ </div>
+ </div>
+ {/if}
+ {#if !caseState.current}
+ <p class="empty">Open a case to see what it holds.</p>
+ {:else if totalling}
+ <!-- The addition. One row per subject the statements point at, and every number
+ beside what it left out: a sum that hid its uncounted and its ruled-out
+ statements would be arithmetically right and read as more than it is. -->
+ {#if nothingTotalled(tally)}
+ {#if !tallying}
+ <p class="empty">No statement in this narrowing.</p>
+ {/if}
+ {:else}
+ {#each readingNotes(tally) as note (note)}
+ <p class="reading-note">{note}</p>
+ {/each}
+ <table class="table tally">
+ <thead>
+ <tr>
+ <th>Subject</th>
+ <th title="added over the statements that carried a number">
+ What the statements come to
+ </th>
+ <th title="how many statements point at this subject">Statements</th>
+ </tr>
+ </thead>
+ <tbody>
+ {#each tally.rows as row (row.id)}
+ {@const lines = countLines(row, claimReads)}
+ {@const notes = noteLines(row)}
+ {@const sure = confidenceLine(row, claimReads)}
+ <tr
+ tabindex="0"
+ onclick={() => (openId = row.id)}
+ onkeydown={(e) => {
+ if (e.target !== e.currentTarget) return;
+ if (e.key === 'Enter' || e.key === ' ') {
+ e.preventDefault();
+ openId = row.id;
+ }
+ }}
+ >
+ <td>
+ <Icon name={entityIcon(row)} size={12} />
+ <span class="name">{row.label}</span>
+ <span class="dim">{entityLabel(row.type)}</span>
+ </td>
+ <td>
+ {#if lines.length}
+ {#each lines as line (line.value)}
+ <span class="sum">{line.text}</span>
+ {/each}
+ {:else}
+ <span class="dim">—</span>
+ {/if}
+ </td>
+ <td class="dim">
+ {row.statements}
+ {#each notes as note (note)}<span class="note">{note}</span>{/each}
+ {#if sure}<span class="sure">{sure}</span>{/if}
+ </td>
+ </tr>
+ {/each}
+ </tbody>
+ </table>
+ {/if}
+ {:else if !rows.length && !pl.loading}
+ <p class="empty">{filtering ? 'Nothing matches.' : 'Nothing filed in this case yet.'}</p>
+ {:else}
+ <table class="table">
+ <thead>
+ <tr>
+ {#each [
+ { key: 'label', label: identityColumn },
+ { key: 'type', label: 'Type' },
+ { key: 'folder', label: 'Folder', hint: 'the My-work folder it is filed in' },
+ { key: 'created', label: 'Created', hint: 'when it was filed into the case' },
+ ...columns,
+ ] as column (column.key)}
+ <th aria-sort={sortKey === column.key ? (sortDesc ? 'descending' : 'ascending') : 'none'}>
+ <button class="sorter" title={column.hint ?? ''} onclick={() => sortBy(column.key)}>
+ {column.label}
+ {#if sortKey === column.key}
+ <Icon name={sortDesc ? 'chevronDown' : 'chevronUp'} size={11} />
+ {/if}
+ </button>
+ </th>
+ {/each}
+ <!-- The action column has nothing to head and nothing to sort by: the
+ button under it says what it does, and a heading over an icon would
+ be a second name for one act. -->
+ <th class="go"></th>
+ </tr>
+ </thead>
+ <tbody>
+ {#each rows as entity (entity.id)}
+ <!-- A row is a control: focusable and answering Enter, because a table
+ nobody can walk with the keyboard is a table half the analysts
+ cannot use. -->
+ <tr
+ class:suggested={isSuggested(entity)}
+ class:busy={busyId === entity.id}
+ tabindex="0"
+ onclick={() => {
+ if (snapshotReading) snapshotOpen = entity;
+ else openId = entity.id;
+ }}
+ onkeydown={(e) => {
+ // only the row's own key press: Enter on the confirm button inside
+ // it is that button's, and would otherwise open Details as well
+ if (e.target !== e.currentTarget) return;
+ if (e.key === 'Enter' || e.key === ' ') {
+ e.preventDefault();
+ if (snapshotReading) snapshotOpen = entity;
+ else openId = entity.id;
+ }
+ }}
+ >
+ <td>
+ {#if entity.thumb}
+ <img
+ class="entity-thumb"
+ src={entity.thumb.startsWith('data:')
+ ? entity.thumb
+ : fileUrl(caseState.current.id, entity.thumb)}
+ alt=""
+ loading="lazy"
+ />
+ {:else}
+ <Icon name={entityIcon(entity)} size={12} />
+ {/if}
+ <span class="name">{entity.label}</span>
+ {#if filter.q.trim() && matchReasons(entity)[0]}
+ {@const match = matchReasons(entity)[0]}
+ <span class="match-reason" title={match.value}>
+ {match.label}: {match.value}
+ </span>
+ {/if}
+ {#if isSuggested(entity)}
+ <span class="tag" title="a tool proposed this, and nobody has confirmed it">
+ suggested
+ </span>
+ <!-- Settled where it is read. Filtering to the proposals and then
+ having to open each one to accept it made the filter a list
+ nobody could act on. -->
+ {#if !snapshotReading}<span class="review">
+ <button
+ class="btn btn-ghost btn-sm act ok"
+ title="Confirm this item"
+ disabled={busyId === entity.id}
+ onclick={(e) => { e.stopPropagation(); confirmEntity(entity); }}
+ >
+ <Icon name="check" size={12} />
+ </button>
+ <button
+ class="btn btn-ghost btn-sm act no"
+ title="Dismiss this item, recoverable from the trash"
+ disabled={busyId === entity.id}
+ onclick={(e) => { e.stopPropagation(); dismissEntity(entity); }}
+ >
+ <Icon name="x" size={12} />
+ </button>
+ </span>{/if}
+ {/if}
+ </td>
+ <td title={entityHint(entity.type)}>{entityLabel(entity.type)}</td>
+ <td class="dim">{folderName(entity)}</td>
+ <td class="dim mono">{created(entity)}</td>
+ {#each columns as column (column.key)}<td class="dim">{cell(entity, column)}</td>{/each}
+ <!-- The row's one way out of the table. A list is good at narrowing and
+ says nothing about how things join up, so the question a row most
+ often raises is the one only the drawing answers. Quiet until the
+ row is under the pointer, like the review clicks beside it. -->
+ <td class="go">
+ {#if !snapshotReading}
+ <button
+ class="btn btn-ghost btn-sm act"
+ aria-label="Show {entity.label} in the graph"
+ title="Show it in the graph, with what it is connected to"
+ onclick={(e) => {
+ e.stopPropagation();
+ uiState.openGraphEntity = entity.id;
+ uiState.tool = 'graph';
+ }}
+ >
+ <Icon name="graph" size={13} />
+ </button>
+ {/if}
+ </td>
+ </tr>
+ {/each}
+ </tbody>
+ </table>
+ {/if}
+
+ <!-- Paging belongs to the list. The addition is bounded server-side and says so on
+ its own line, so a "Show more" under it would offer to lengthen a total. -->
+ {#if pl.hasMore && !totalling}
+ <div class="more">
+ <!-- A sort the store could not answer runs over what is loaded, so it says
+ so while there is more: an alphabet over the first hundred of eight
+ hundred rows looks exactly like an alphabet over the case. The two
+ headings the case can order by say nothing, because there is nothing to
+ warn about. -->
+ <span class="dim">
+ Showing {rows.length} of {matchCount}{sortKey && !order
+ ? ', sorted over the rows loaded'
+ : ''}
+ </span>
+ <button class="btn btn-ghost btn-sm" onclick={() => pl.loadMore()} disabled={pl.loading}>
+ {pl.loading ? 'Loading…' : 'Show more'}
+ </button>
+ </div>
+ {/if}
+ </div>
+</div>
+
+{#if draft}
+ <!-- The one create dialog, shared with the graph: a `claim` is filed with the same
+ words and the same duplicate warning wherever the analyst is standing. -->
+ <EntityCreate
+ startType={draft.type}
+ ontwin={(entity) => {
+ draft = null;
+ openId = entity.id;
+ }}
+ oncreated={(entity) => {
+ draft = null;
+ // Create it, then open it: a claim exists in order to be pointed at things, so
+ // landing on its own Details with the relation picker is the next gesture.
+ openId = entity.id;
+ }}
+ onclose={() => (draft = null)}
+ />
+{/if}
+
+<!-- Ctrl+V: a screenshot or a link, filed and opened -->
+{#if pasted && !snapshotReading}
+ <PasteDialog
+ resolved={pasted}
+ busy={pasteBusy}
+ onconfirm={confirmPaste}
+ onclose={() => (pasted = null)}
+ />
+{/if}
+
+{#if openId && !snapshotReading}
+ <!-- Escape and the backdrop both close a modal, and the panel's fields wait for
+ Save: closing over unsaved edits threw them away without a word. The ask is
+ only raised when there is something to lose. -->
+ <Modal title="Details" onclose={closeDetails} width="640px">
+ <!-- The panel's own `onclose` is its hand-off to another tool — it has already
+ navigated by the time it fires, so it closes rather than asking. -->
+ <EntityDetails
+ entityId={openId}
+ bind:dirty
+ onclose={() => (openId = null)}
+ ondeleted={() => (openId = null)}
+ />
+ </Modal>
+{/if}
+
+{#if snapshotOpen && snapshotReading}
+ <Modal title="Snapshot details" onclose={() => (snapshotOpen = null)} width="640px">
+ <SnapshotDetails
+ entity={snapshotOpen}
+ entities={catalogViews.activeView?.spec?.snapshot?.entities ?? []}
+ links={catalogViews.activeView?.spec?.snapshot?.links ?? []}
+ />
+ </Modal>
+{/if}
+
+{#if discarding}
+ <ConfirmDialog
+ title="Discard changes?"
+ message="This item has edits that Save has not taken."
+ confirmLabel="Discard"
+ icon="alert"
+ onconfirm={() => { discarding = false; dirty = false; openId = null; }}
+ oncancel={() => (discarding = false)}
+ />
+{/if}
+
+<style>
+ .spacer {
+ flex: 1;
+ }
+ /* The count reads first because it is the answer; the control that decides how that
+ answer is drawn sits at the other end, directly above what it governs. */
+ .answer {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ margin: 0;
+ padding: 8px 16px 2px;
+ color: var(--text-3);
+ font-size: var(--fs-xs);
+ }
+ /* The whole sentence is one flex item, or the gap would fall between "23" and
+ "of 1204" as well as around the control. */
+ .answer .said {
+ margin-right: auto;
+ }
+ .answer strong {
+ color: var(--text-1);
+ font-weight: 600;
+ }
+ .answer .as-link {
+ margin-left: 8px;
+ padding: 0;
+ border: 0;
+ background: none;
+ color: var(--accent);
+ font: inherit;
+ cursor: pointer;
+ }
+ .answer .as-link:hover {
+ text-decoration: underline;
+ }
+ /* The one scrolling region. `.tool` is a full-height flex column, so the body
+ needs min-height:0 or the table pushes the column taller than the viewport and
+ nothing scrolls at all. */
+ .body {
+ position: relative;
+ flex: 1;
+ min-height: 0;
+ overflow: auto;
+ padding: 0 16px 16px;
+ }
+ .drop-overlay {
+ position: absolute;
+ inset: 0;
+ z-index: 2;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ background: color-mix(in srgb, var(--bg-1) 82%, transparent);
+ backdrop-filter: blur(2px);
+ pointer-events: none;
+ }
+ .drop-box {
+ display: flex;
+ flex-direction: column;
+ align-items: center;
+ gap: 8px;
+ padding: 22px 30px;
+ border: 1px dashed var(--accent);
+ border-radius: var(--r);
+ color: var(--text-2);
+ font-size: var(--fs-sm);
+ }
+ .empty {
+ color: var(--text-3);
+ font-size: var(--fs-sm);
+ padding: 24px 2px;
+ }
+ .table {
+ width: 100%;
+ border-collapse: collapse;
+ font-size: var(--fs-sm);
+ }
+ /* the headings stay put while the rows scroll under them */
+ .table th {
+ position: sticky;
+ top: 0;
+ z-index: 1;
+ text-align: left;
+ padding: 0;
+ background: var(--bg-1);
+ border-bottom: 1px solid var(--border);
+ white-space: nowrap;
+ }
+ .sorter {
+ display: flex;
+ align-items: center;
+ gap: 4px;
+ width: 100%;
+ padding: 8px 10px 8px 0;
+ border: 0;
+ background: none;
+ color: var(--text-3);
+ font: inherit;
+ font-size: var(--fs-xs);
+ font-weight: 600;
+ cursor: pointer;
+ }
+ .sorter:hover {
+ color: var(--text-1);
+ }
+ .table td {
+ padding: 6px 10px 6px 0;
+ border-bottom: 1px solid var(--border);
+ color: var(--text-2);
+ max-width: 320px;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ }
+ .table tbody tr {
+ cursor: pointer;
+ border-left: 2px solid transparent;
+ }
+ /* a machine's proposal, marked the way the relation rows mark one */
+ .table tbody tr.suggested {
+ border-left-color: color-mix(in srgb, var(--accent) 55%, transparent);
+ }
+ .table tbody tr:hover td,
+ .table tbody tr:focus-visible td {
+ background: var(--bg-2);
+ color: var(--text-1);
+ }
+ .table tbody tr:focus-visible {
+ outline: 2px solid var(--accent);
+ outline-offset: -2px;
+ }
+ .table tbody tr.busy {
+ opacity: 0.5;
+ }
+ /* the two review clicks, quiet until the row is under the pointer or focused */
+ .review {
+ display: inline-flex;
+ gap: 1px;
+ margin-left: 4px;
+ opacity: 0.55;
+ vertical-align: -3px;
+ }
+ tr:hover .review,
+ tr:focus-within .review {
+ opacity: 1;
+ }
+ .act {
+ padding-inline: 5px;
+ }
+ /* The row's way into the drawing: right-aligned, and quiet until the row is under
+ the pointer or focused — the same restraint as the review clicks, so a table of
+ eight hundred rows is not eight hundred buttons. */
+ .table .go {
+ width: 1%;
+ padding-right: 0;
+ text-align: right;
+ white-space: nowrap;
+ }
+ .table td.go .act {
+ opacity: 0;
+ color: var(--text-3);
+ }
+ tr:hover td.go .act,
+ tr:focus-within td.go .act,
+ tr:focus-visible td.go .act {
+ opacity: 1;
+ }
+ .table td.go .act:hover {
+ color: var(--accent);
+ }
+ .act.ok:hover {
+ color: var(--ok, #46a758);
+ }
+ .act.no:hover {
+ color: var(--danger);
+ }
+ .name {
+ overflow: hidden;
+ text-overflow: ellipsis;
+ }
+ .match-reason {
+ display: block;
+ max-width: 290px;
+ margin: 2px 0 0 18px;
+ overflow: hidden;
+ color: var(--accent);
+ font-size: var(--fs-xs);
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ }
+ .entity-thumb {
+ width: 26px;
+ height: 26px;
+ display: inline-block;
+ margin-right: 6px;
+ border: 1px solid var(--border);
+ border-radius: var(--r-sm);
+ object-fit: cover;
+ vertical-align: middle;
+ background: var(--bg-2);
+ }
+ .dim {
+ color: var(--text-3);
+ font-size: var(--fs-xs);
+ }
+ .tag {
+ font-size: 10px;
+ padding: 1px 5px;
+ margin-left: 6px;
+ border-radius: 999px;
+ background: var(--bg-2);
+ color: var(--text-3);
+ }
+ .table td :global(svg) {
+ display: inline-block;
+ vertical-align: -2px;
+ margin-right: 6px;
+ }
+ .more {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ padding-top: 10px;
+ }
+ /* The addition. A sum reads as one figure per condition rather than as a sentence,
+ and everything it left out sits under the count it was left out of. */
+ .reading-note {
+ margin: 0 0 8px;
+ color: var(--text-3);
+ font-size: var(--fs-xs);
+ }
+ .tally .sum {
+ display: block;
+ font-variant-numeric: tabular-nums;
+ }
+ .tally .note,
+ .tally .sure {
+ display: block;
+ margin-top: 2px;
+ font-size: var(--fs-xs);
+ }
+ .tally .note {
+ color: var(--text-3);
+ }
+ .tally .sure {
+ color: var(--text-3);
+ font-style: italic;
+ }
+ .tally td .dim {
+ margin-left: 6px;
+ }
+</style>
diff --git a/frontend/src/tools/Board.test.js b/frontend/src/tools/Board.test.js
new file mode 100644
index 0000000..1707cd4
--- /dev/null
+++ b/frontend/src/tools/Board.test.js
@@ -0,0 +1,497 @@
+import { describe, expect, it } from 'vitest';
+import { readFileSync } from 'node:fs';
+
+const source = readFileSync(new URL('./Board.svelte', import.meta.url), 'utf8');
+
+describe('the board is what makes the vocabulary reachable', () => {
+ it('creates the hand-made types, which nothing else could', () => {
+ // before this, a case could hold a person, an account or a claim only through
+ // the API: the registry declared them and the verbs accepted them, but no
+ // screen made one — so a bookmark had nothing to be related to
+ expect(source).toContain('creatableTypes()');
+ expect(source).toContain('New entity');
+ // the dialog itself is shared with the graph, so a claim is filed with the same
+ // words wherever the analyst is standing (`EntityCreate.test.js`)
+ expect(source).toContain("import EntityCreate from '../components/EntityCreate.svelte'");
+ });
+
+ it('opens the shared dialog on the type already being looked at', () => {
+ expect(source).toContain('startType={draft.type}');
+ expect(source).toContain('oncreated={(entity) => {');
+ });
+
+ it('keeps Details compact while typed fields use the available row', () => {
+ expect(source).toContain('width="640px"');
+ });
+
+ it('opens what it just created, since a claim exists to be pointed at things', () => {
+ expect(source).toContain('openId = entity.id;');
+ });
+
+ it('opens any row in the one Details panel every other surface uses', () => {
+ expect(source).toContain("import EntityDetails from '../components/EntityDetails.svelte'");
+ expect(source).toContain('ondeleted={() => (openId = null)}');
+ });
+
+ it('takes its icons from the registry rather than a fifth hand-kept map', () => {
+ expect(source).toContain("import { entityIcon } from '../lib/entityIcon.js'");
+ expect(source).not.toContain('ENTITY_ICON');
+ });
+
+ it('uses the primary photo when an entity has one', () => {
+ expect(source).toContain('{#if entity.thumb}');
+ expect(source).toContain("entity.thumb.startsWith('data:')");
+ expect(source).toContain('fileUrl(caseState.current.id, entity.thumb)');
+ expect(source).toContain('{:else}\n <Icon name={entityIcon(entity)}');
+ });
+});
+
+describe('the vocabulary explains itself', () => {
+ it('hands the registry’s own readings to the menus that offer them', () => {
+ // families are the load-bearing idea and the one part an analyst never types, so
+ // the filter menu carries the clause the registry declares rather than one of its
+ // own (`FilterBar.test.js` holds the other half)
+ expect(source).toContain('familyHint={familyReads}');
+ expect(source).toContain('typeHint={entityHint}');
+ });
+
+ it('says what a type is where it offers one', () => {
+ expect(source).toContain('title={entityHint(entity.type)}');
+ });
+
+ it('says what a proposal is, since the tag is the only thing marking one', () => {
+ expect(source).toContain('title="a tool proposed this, and nobody has confirmed it"');
+ });
+
+ it('takes every reading from the registry rather than writing one here', () => {
+ const markup = source.slice(source.indexOf('</script>'));
+ // the only titles in the markup are either registry readings or the fallback
+ // that names the control itself
+ expect(markup).not.toMatch(/title="[a-z ]*(claim|bookmark|capture|actor|material)/i);
+ });
+});
+
+describe('bounded loading', () => {
+ it('reads one page of the catalog, never the whole graph', () => {
+ expect(source).toContain('createPagedList');
+ expect(source).toContain('buildCatalogQuery');
+ expect(source).toContain('limit: PAGE');
+ expect(source).toContain('/catalog/summary');
+ });
+
+ it('offers Show more with an honest total', () => {
+ expect(source).toContain('pl.hasMore');
+ expect(source).toContain('pl.loadMore()');
+ expect(source).toContain('Showing {rows.length} of {matchCount}');
+ });
+
+ it('counts the answer against the whole case, since a proportion is the point', () => {
+ // a denominator that shrinks with the numerator carries no information at all
+ expect(source).toContain('const caseTotal = $derived(summary?.total ?? pl.total)');
+ expect(source).toContain('<strong>{matchCount}</strong> of {caseTotal}');
+ });
+
+ it('counts a memory-filtered page itself, since the server never heard the term', () => {
+ expect(source).toContain(
+ "pl.serverMode || !filter.q.trim() ? pl.total : matching.length"
+ );
+ });
+
+ it('hands the term to the list, which is what searches past one page', () => {
+ // client-side filtering is switched off in server mode, so without this the box
+ // goes quiet at exactly the case size that needs it
+ expect(source).toContain('pl.setQuery(filter.q);');
+ });
+
+ it('drops the previous case before loading the next', () => {
+ expect(source).toContain('pl.clear()');
+ expect(source).toContain("if (caseState.current?.id === id) summary = s;");
+ });
+
+ it('re-establishes the baseline when the question changes', () => {
+ // page two of "every type" is not page two of "places", and the request itself is
+ // the key: a term that changes nothing about what is asked reloads nothing. The
+ // fact-time window is part of the question, so moving it reloads too.
+ expect(source).toMatch(
+ /const asked = JSON\.stringify\(\[\s*toQuery\(filter, \{ types: wantedTypes \}\),\s*analysisPeriodQuery\(analysisSearch\.period\),\s*order,\s*catalogViews\.snapshotId,\s*\]\)/
+ );
+ expect(source).toContain('void pl.reload()');
+ });
+
+ it('filters a small case in memory, so typing costs no request', () => {
+ expect(source).toContain("pl.serverMode || !filter.q.trim()");
+ });
+});
+
+describe('the question is one value, and one bar that never changes shape', () => {
+ it('holds every term in one filter rather than a state per select', () => {
+ // seven selects, four of which appeared and disappeared as the others were set:
+ // a live term looked exactly like a dead one, and a control that vanished took
+ // its own way back with it
+ expect(source).toContain("import FilterBar from '../components/FilterBar.svelte'");
+ expect(source).toContain('let filter = $state(emptyFilter());');
+ expect(source).toContain('<FilterBar');
+ expect(source).toContain('bind:filter');
+ // and none of the old selects survive in the toolbar
+ const markup = source.slice(source.indexOf('</script>'));
+ expect(markup).not.toContain('Every family');
+ expect(markup).not.toContain('Every type');
+ expect(markup).not.toContain('Any field');
+ });
+
+ it('resolves families to types here, as the catalog endpoint speaks types', () => {
+ expect(source).toContain('const wantedTypes = $derived(');
+ expect(source).toContain('filter.families.length');
+ expect(source).toContain('...toQuery({ ...filter, q }, { types: wantedTypes })');
+ });
+
+ it('narrows the type menu to the chosen families, and drops a type they leave out', () => {
+ expect(source).toContain(
+ '(entry) => !filter.families.length || filter.families.includes(entry.family)'
+ );
+ expect(source).toContain('if (inside.length !== filter.types.length)');
+ });
+
+ it('offers a family only where the case holds one', () => {
+ // offering a family nothing is filed under is offering an empty answer
+ expect(source).toContain('Object.keys(summary?.by_type ?? {})');
+ });
+
+ it('reads the fields on the click that opens their menu, not on mount', () => {
+ // the scan is what reaches `kind`, which the importer writes and the vocabulary
+ // declares nowhere — gating it behind picking a type first is what made the most
+ // useful filter in the app invisible
+ expect(source).toContain('fetchAttrFacets(id, wantedTypes)');
+ expect(source).toContain('onfields={() => (fieldsWanted = true)}');
+ expect(source).toContain('if (!wantedTypes.length && !fieldsWanted) {');
+ });
+
+ it('offers the field menu at any case size', () => {
+ // it used to go dark past five thousand entities, which is exactly the case where
+ // a field is the only practical way to narrow. The scan is linear and small; the
+ // bound that keeps the menu readable is the server's own one on values.
+ expect(source).not.toMatch(/FACET_SCAN_MAX/);
+ expect(source).not.toMatch(/narrow-first/);
+ expect(source).not.toMatch(/summary\?\.total \?\? 0\) >/);
+ });
+
+ it('drops a term the narrowing has left with nothing to answer, and says so', () => {
+ // a filter still on screen that the current rows cannot carry reads as one that
+ // stopped working
+ expect(source).toContain("filter = clearAxis(filter, 'field');");
+ expect(source).toContain('so that term went');
+ });
+
+ it('remembers the question per case, in the browser rather than in the case', () => {
+ // an unnamed question is remembered locally; naming it turns it into case state
+ expect(source).toContain('openAnalysisCase(id);');
+ expect(source).toContain('setAnalysisFilter(caseState.current?.id, filter)');
+ });
+});
+
+describe('one table, and it scrolls', () => {
+ it('is the tool shell, so the rows scroll instead of the page growing', () => {
+ // `.tool` is a full-height flex column; a body without min-height:0 pushes the
+ // column past the viewport and nothing scrolls at all
+ expect(source).toContain('<div class="tool">');
+ expect(source).toContain('.body {');
+ expect(source).toMatch(/\.body \{[^}]*min-height: 0;/);
+ expect(source).toMatch(/\.body \{[^}]*overflow: auto;/);
+ });
+
+ it('keeps the headings in place while the rows move under them', () => {
+ expect(source).toMatch(/\.table th \{[^}]*position: sticky;/);
+ });
+
+ it('offers one view rather than two readings of the same rows', () => {
+ const markup = source.slice(source.indexOf('</script>'));
+ expect(markup).not.toContain('class="views"');
+ expect(source).not.toContain("view = 'list'");
+ });
+
+ it('adds a type’s own columns only when a single type is picked', () => {
+ // a column blank for four rows out of five is noise, and two types picked at once
+ // have no shared attributes to head
+ expect(source).toContain("const onlyType = $derived(filter.types.length === 1 ? filter.types[0] : '')");
+ expect(source).toContain('const columns = $derived(onlyType ? entityFields(onlyType) : [])');
+ });
+
+ it('reads cells rather than editing them, and imports nothing', () => {
+ const markup = source.slice(source.indexOf('</script>'));
+ expect(markup).not.toContain('contenteditable');
+ expect(markup).not.toMatch(/\bCSV\b/);
+ // no cell holds an input: the Sheet is the editable view, this is the list
+ expect(markup.slice(markup.indexOf('<table'), markup.indexOf('</table>'))).not.toContain('<input');
+ });
+});
+
+describe('sorting', () => {
+ it('sorts on any heading, and reverses on a second click', () => {
+ expect(source).toContain('function sortBy(key)');
+ expect(source).toContain('if (sortKey === key) sortDesc = !sortDesc;');
+ expect(source).toContain('aria-sort={sortKey === column.key');
+ });
+
+ it('sorts a number as a number', () => {
+ // "100" before "25" is the classic table bug
+ expect(source).toContain("if (field.kind === 'number')");
+ expect(source).toContain('(left - right) * direction');
+ });
+
+ it('compares text the way the reader’s language does', () => {
+ expect(source).toContain('localeCompare');
+ });
+
+ it('drops the ordering when its column leaves the table', () => {
+ expect(source).toContain('if (sortKey && !keys.includes(sortKey)) sortKey = ');
+ });
+
+ it('asks the case for the two orderings the store can answer', () => {
+ // "newest first" over a hundred of eight hundred rows is not the newest of
+ // anything, and that is the one sort a worked case needs most
+ expect(source).toContain('const order = $derived(orderFor(sortKey, sortDesc))');
+ expect(source).toContain('order,');
+ expect(source).toContain('if (!sortKey || order) return matching;');
+ });
+
+ it('says the ordering is over the rows loaded only when it really is', () => {
+ // an alphabet over the first hundred of eight hundred rows looks exactly like
+ // an alphabet over the case — but the headings the store ordered have nothing
+ // to warn about
+ expect(source).toContain("sortKey && !order\n ? ', sorted over the rows loaded'");
+ });
+});
+
+describe('a proposal can be settled here', () => {
+ it('offers the two clicks on the row, not only inside the panel', () => {
+ // filtering to Suggested and then having to open each row to accept it made
+ // the filter a list nobody could act on
+ expect(source).toContain('async function confirmEntity(entity)');
+ expect(source).toContain('async function dismissEntity(entity)');
+ expect(source).toContain("status: 'confirmed',");
+ expect(source).toContain('title="Confirm this item"');
+ });
+
+ it('dismisses through the standard delete, so it stays recoverable', () => {
+ expect(source).toContain("import { deletedToast } from '../lib/trash.js'");
+ expect(source).toContain('deletedToast(caseId, result, entity.label)');
+ });
+
+ it('keeps a review click off the row it sits on', () => {
+ expect(source).toContain('e.stopPropagation(); confirmEntity(entity);');
+ expect(source).toContain('e.stopPropagation(); dismissEntity(entity);');
+ });
+});
+
+describe('the table answers a keyboard', () => {
+ it('makes each row focusable and Enter open it', () => {
+ expect(source).toContain('tabindex="0"');
+ expect(source).toContain("if (e.key === 'Enter' || e.key === ' ')");
+ expect(source).toContain('.table tbody tr:focus-visible {');
+ });
+});
+
+describe('creating one', () => {
+ it('starts from the family already being looked at', () => {
+ expect(source).toContain(
+ '(entry) => !filter.families.length || filter.families.includes(entry.family)'
+ );
+ expect(source).toContain('type: onlyType || wanted[0]?.type');
+ });
+
+ it('names the first column after the chosen type, as the create form does', () => {
+ expect(source).toContain(
+ "const identityColumn = $derived(onlyType ? entityIdentityLabel(onlyType) : 'Name')"
+ );
+ });
+
+ it('offers the row this case already holds under the same identifier', () => {
+ // the warning itself lives in the shared dialog; what the Board owns is where the
+ // offer lands — the existing row, opened
+ expect(source).toContain('ontwin={(entity) => {');
+ expect(source).toContain('openId = entity.id;');
+ });
+
+ it('asks before a close would throw away an unsaved field', () => {
+ expect(source).toContain('function closeDetails()');
+ expect(source).toContain('if (dirty) discarding = true;');
+ expect(source).toContain('title="Discard changes?"');
+ });
+});
+
+describe('a frozen analysis snapshot', () => {
+ it('keeps its question and captured rows read-only while retaining details', () => {
+ expect(source).toContain('const snapshotReading = $derived(Boolean(catalogViews.snapshotId))');
+ expect(source).toContain('disabled={!caseState.current || importing || snapshotReading}');
+ expect(source).toContain('disabled={snapshotReading}');
+ expect(source).toContain('{#if openId && !snapshotReading}');
+ expect(source).toContain('{#if !snapshotReading}<span class="review">');
+ expect(source).toContain('<Modal title="Snapshot details"');
+ expect(source).toContain('<SnapshotDetails');
+ expect(source).toContain('snapshotOpen = null;');
+ });
+});
+
+describe('taking a file into the case', () => {
+ it('imports through the one media chokepoint rather than a second path', () => {
+ // hash, dedupe, sidecar, thumbnail, enrichment and provenance all hang off it
+ expect(source).toContain('/media/upload');
+ expect(source).toContain("form.append('file', file)");
+ expect(source).toContain('Add file');
+ });
+
+ it('takes a drop on the list as well as a click', () => {
+ expect(source).toContain('ondrop=');
+ expect(source).toContain('importFiles(e.dataTransfer?.files)');
+ expect(source).toContain('Drop to file it in this case');
+ });
+
+ it('says what happened, duplicates included', () => {
+ // the same bytes twice is not an error and not a second item
+ expect(source).toContain('result.duplicate');
+ expect(source).toContain('duplicate${duplicates > 1');
+ });
+
+ it('opens one file where the analyst can say what it is, and a batch nowhere', () => {
+ expect(source).toContain('if (files.length === 1 && last) openId = last;');
+ });
+});
+
+describe('where a graph-only type is read', () => {
+ it('opens the entity another surface handed over', () => {
+ // a person, an account, a claim have no tool of their own to be reopened in
+ expect(source).toContain('uiState.openBoardEntity');
+ expect(source).toContain('openId = id;');
+ });
+});
+
+describe('handing the question to the drawing', () => {
+ it('sends the question, never the rows it matched', () => {
+ // ids would be capped, would bloat the URL and would go stale on the next save;
+ // a filter is something the case can be asked again, and both surfaces resolve it
+ // through one predicate — so what the drawing holds is what the table counted
+ expect(source).toContain('uiState.drawInGraph = {');
+ expect(source).toContain('terms: toGraphQuery(filter, { types: wantedTypes })');
+ expect(source).toContain("uiState.tool = 'graph';");
+ expect(source).not.toContain('keep:');
+ });
+
+ it('offers it only where there is an answer to draw, and says which', () => {
+ expect(source).toContain('Draw these {matchCount}');
+ expect(source).toContain('label: said,');
+ expect(source).toContain('const drawTitle = $derived(');
+ });
+});
+
+describe('a row reaches the drawing', () => {
+ it('offers the graph from the row itself, not only from Details', () => {
+ // a list is good at narrowing and says nothing about how things join up, so the
+ // question a row most often raises is the one only the drawing answers
+ expect(source).toContain('uiState.openGraphEntity = entity.id;');
+ expect(source).toContain('aria-label="Show {entity.label} in the graph"');
+ });
+
+ it('keeps that click off the row it sits on', () => {
+ expect(source).toMatch(/e\.stopPropagation\(\);\s*uiState\.openGraphEntity/);
+ });
+
+ it('stays quiet until the row is under the pointer, like the review clicks', () => {
+ // eight hundred rows must not read as eight hundred buttons
+ expect(source).toMatch(/\.table td\.go \.act \{[^}]*opacity: 0;/);
+ expect(source).toContain('tr:hover td.go .act,');
+ });
+});
+
+describe('adding the statements up', () => {
+ it('renders the same question, through the switch the other lists already use', () => {
+ // the chips stay where they are and the sentence is unchanged; what moves is how
+ // the answer is drawn
+ expect(source).toContain("import ViewSwitch from '../components/ViewSwitch.svelte'");
+ expect(source).toContain("{ id: 'rows', label: 'Rows', icon: 'note'");
+ expect(source).toContain("id: 'totals',");
+ expect(source).toContain("onpick={(id) => (totalling = id === 'totals')}");
+ // The totals answer the question on screen, period included: a sum over a wider
+ // window than the table is showing would be a different question.
+ expect(source).toMatch(
+ /buildTallyQuery\(caseState\.current\.id, \{\s*\.\.\.toQuery\(filter, \{ types: wantedTypes \}\),\s*\.\.\.analysisPeriodQuery\(analysisSearch\.period\),\s*\}\)/
+ );
+ });
+
+ it('offers Totals from the first day, dimmed until it can draw a real line', () => {
+ // a control you can see and cannot use teaches something; one that is not there
+ // teaches nothing — the rule the filter menu already follows
+ expect(source).toContain('disabled: nothingToDraw || empty || snapshotReading,');
+ expect(source).toContain("'No statement counts anything about a subject yet'");
+ expect(source).toContain("'Nothing in the table to add up'");
+ });
+
+ it('calls a line real only when a statement counts something about a subject', () => {
+ // either half alone opens the total on nothing: "seen, not counted" is an answer
+ // rather than a row, and a statement about nothing has no subject to sit under
+ expect(source).toContain('const countable = $derived(summary?.countable ?? 0);');
+ expect(source).toContain('const nothingToDraw = countable === 0;');
+ expect(source).toContain('const empty = !rows.length;');
+ // priced off the summary every filter term is priced from, so it costs no request
+ expect(source).not.toContain('summary?.by_type?.claim');
+ });
+
+ it('re-reads after a write, since a relation is what changes a total', () => {
+ // stating one while the total is on screen used to need the page reloaded before
+ // it appeared; the row list and the panel's own total both read this already
+ expect(source).toMatch(/caseState\.rev;\s*const url = buildTallyQuery/);
+ });
+
+ it('asks only while it is on screen, and not once per keystroke', () => {
+ // a sum has no in-memory half to fall back on the way the row list does, so the
+ // whole question is debounced rather than the text term alone
+ expect(source).toContain('if (!totalling || snapshotReading || !caseState.current?.id) return;');
+ expect(source).toContain('const TALLY_DELAY = 250;');
+ expect(source).toMatch(/setTimeout\(\(\) => \{\s*tallying = true;/);
+ expect(source).toContain('clearTimeout(timer);');
+ });
+
+ it('steps back to the list inside a frozen snapshot', () => {
+ // a snapshot is a copy of rows rather than a question the case can still be asked
+ expect(source).toContain('if (snapshotReading && totalling) totalling = false;');
+ expect(source).toContain('A frozen snapshot holds rows rather than a question to add up');
+ });
+
+ it('never prints a sum without what was left out of it', () => {
+ expect(source).toContain('countLines(row, claimReads)');
+ expect(source).toContain('noteLines(row)');
+ expect(source).toContain('readingNotes(tally)');
+ });
+
+ it('takes its words from the served registry, not from a list kept here', () => {
+ expect(source).toContain("for (const field of entityFields('claim'))");
+ expect(source).not.toContain("'destroyed'");
+ });
+
+ it('offers no Show more under a bounded total', () => {
+ expect(source).toContain('{#if pl.hasMore && !totalling}');
+ });
+
+ it('opens the subject a row stands for', () => {
+ expect(source).toContain('onclick={() => (openId = row.id)}');
+ });
+});
+
+describe('Ctrl+V on the table', () => {
+ it('files what the clipboard holds and opens the row it made', () => {
+ expect(source).toContain("import { listenForPaste, pasteImage, resolvePaste } from '../lib/clipboardPaste.js'");
+ expect(source).toContain("import PasteDialog from '../components/PasteDialog.svelte'");
+ expect(source).toContain("resolvePaste('board', payload)");
+ // opened, not just filed: the next gesture is relating it to what prompted it
+ expect(source).toContain('openId = result.entity.id;');
+ expect(source).toContain('openId = entity.id;');
+ });
+
+ it('only answers while it is the tool on screen', () => {
+ expect(source).toMatch(/uiState\.tool !== 'board'\) return;\s*return listenForPaste/);
+ });
+
+ it('refuses to write into a frozen reading, and says why', () => {
+ expect(source).toContain("toast('This snapshot is read-only. Leave it to paste.', 'warn')");
+ expect(source).toContain('{#if pasted && !snapshotReading}');
+ });
+});
diff --git a/frontend/src/tools/Files.svelte b/frontend/src/tools/Files.svelte
index ee77708..10cc9bf 100644
--- a/frontend/src/tools/Files.svelte
+++ b/frontend/src/tools/Files.svelte
@@ -9,14 +9,17 @@
* lib/filing.js); the selection math is pure and unit-tested (lib/gridSelect.js).
*/
import { api } from '../lib/api.js';
+ import { fileUrl } from '../lib/fileUrl.js';
import { caseState, reloadCase, toast, uiState } from '../lib/state.svelte.js';
import { buildTree, subtreeCount, folderOf, flattenPaths, isInFolderSubtree } from '../lib/folderTree.js';
- import { assignFolderBatch } from '../lib/filing.js';
+ import { assignFolder, assignFolderBatch } from '../lib/filing.js';
import { createNote } from '../lib/notes.js';
import { openNotebook } from '../lib/navigate.js';
import { createBookmark } from '../lib/bookmarks.js';
+ import { listenForPaste, pasteImage, resolvePaste } from '../lib/clipboardPaste.js';
import { marqueeRect, marqueeHits, toggleSelection } from '../lib/gridSelect.js';
import { buildCatalogQuery, fetchAllEntities } from '../lib/catalog.js';
+ import { matchesEntity } from '../lib/entitySearch.js';
import { sortFileEntities } from '../lib/fileSort.js';
import {
deletedToast,
@@ -34,6 +37,7 @@
import ConfirmDialog from '../components/ConfirmDialog.svelte';
import EntityDetails from '../components/EntityDetails.svelte';
import FolderSelect from '../components/FolderSelect.svelte';
+ import PasteDialog from '../components/PasteDialog.svelte';
const TYPE_ICON = {
media: 'image', capture: 'satellite', note: 'note', proof: 'proof',
@@ -151,15 +155,10 @@
const total = $derived(
searching && pl.serverMode ? pl.total : (summary?.total ?? confirmed.length)
);
- function matches(e) {
- const q = query.trim().toLowerCase();
- return (
- (e.label ?? '').toLowerCase().includes(q) ||
- e.type.toLowerCase().includes(q) ||
- (folderOf(e) ?? '').toLowerCase().includes(q) ||
- (e.attrs?.notes ?? '').toLowerCase().includes(q)
- );
- }
+ // The server's own index, restated once in `lib/entitySearch.js` rather than
+ // spelled out per tool: a bookmark's archived copy is a declared field, so it is
+ // searchable here exactly as it is past one page.
+ const matches = (e) => matchesEntity(e, query);
// Sort the current view. The list headers use the same state as the grid
// selector, so changing view does not silently change the order.
@@ -696,6 +695,70 @@
}
}
+ // ── paste ────────────────────────────────────────────────────────────────────
+ /**
+ * Ctrl+V files what the clipboard holds into the folder being looked at.
+ *
+ * The only surface here that had no way to take a file at all: its drag and drop
+ * moves items between folders, so an image had to go through the Media grid and
+ * be filed afterwards. A pasted screenshot and a pasted link now land already
+ * filed, which is what this desktop is for.
+ */
+ let pasted = $state(null);
+ let pasteBusy = $state(false);
+ $effect(() => {
+ if (uiState.tool !== 'files') return;
+ return listenForPaste((payload) => {
+ pasted ??= resolvePaste('files', payload, { folder: showUnfiled ? '' : cwd });
+ });
+ });
+
+ /** Show the folder the paste landed in, so it is never filed out of sight. */
+ function revealFiled(folder) {
+ if (folder) openFolder(folder);
+ else openUnfiled();
+ }
+
+ async function confirmPaste(resolved) {
+ if (pasteBusy || !caseState.current) return;
+ pasteBusy = true;
+ const { kind, values, payload } = resolved;
+ try {
+ const caseId = caseState.current.id;
+ if (kind === 'image') {
+ const result = await pasteImage(caseId, {
+ file: payload.file,
+ title: values.title,
+ sourceUrl: values.source,
+ });
+ // A duplicate is left where it already sits: the case keeps the copy it has,
+ // and refiling it under the folder of this paste would move an item the
+ // analyst filed on purpose the first time.
+ if (!result.duplicate && values.folder) {
+ await assignFolder(caseId, result.entity, values.folder);
+ }
+ pasted = null;
+ await reloadCase();
+ if (result.duplicate) {
+ toast('Already in the case (same SHA-256)', 'warn');
+ } else {
+ toast('Image filed', 'ok', 1600);
+ revealFiled(values.folder);
+ }
+ } else {
+ await createBookmark(caseId, { ...values, url: payload.url });
+ pasted = null;
+ await reloadCase();
+ toast('Bookmark saved', 'ok', 1600);
+ revealFiled(values.folder);
+ }
+ } catch (e) {
+ toast(e.message, 'danger');
+ } finally {
+ pasteBusy = false;
+ }
+ }
+
// ── tree rail ────────────────────────────────────────────────────────────────
let expanded = $state({});
const isExpanded = (p) => expanded[p] === true;
@@ -705,6 +768,15 @@
// ── details ────────────────────────────────────────────────────────────────
let infoEntityId = $state(null);
+ // The panel's fields wait for Save while its connections file themselves, so
+ // Escape and the backdrop ask before throwing an edit away.
+ let infoDirty = $state(false);
+ let infoDiscarding = $state(false);
+
+ function closeInfo() {
+ if (infoDirty) infoDiscarding = true;
+ else infoEntityId = null;
+ }
// View mode: small/large icon grids, plus a details list with columns.
let view = $state('small');
@@ -1048,7 +1120,7 @@
>
<span class="lcol-name">
{#if tileThumb(e)}
- <img class="lrow-thumb" src={`/files/${caseState.current.id}/${tileThumb(e)}`} alt="" loading="lazy" />
+ <img class="lrow-thumb" src={fileUrl(caseState.current.id, tileThumb(e))} alt="" loading="lazy" />
{:else}
<Icon name={tileIcon(e)} size={15} />
{/if}
@@ -1138,7 +1210,7 @@
>
<div class="thumb">
{#if tileThumb(e)}
- <img src={`/files/${caseState.current.id}/${tileThumb(e)}`} alt={e.label} loading="lazy" />
+ <img src={fileUrl(caseState.current.id, tileThumb(e))} alt={e.label} loading="lazy" />
{:else}
<Icon name={tileIcon(e)} size={dense ? 24 : 34} />
{/if}
@@ -1343,17 +1415,40 @@
</Modal>
{/if}
+<!-- Ctrl+V: a screenshot or a link, filed into the folder being looked at -->
+{#if pasted}
+ <PasteDialog
+ resolved={pasted}
+ folders={allFolders}
+ busy={pasteBusy}
+ onconfirm={confirmPaste}
+ onclose={() => (pasted = null)}
+ />
+{/if}
+
<!-- details editor: the shared body, same as the sidebar and Media modal -->
{#if infoEntityId}
- <Modal title="Details" onclose={() => (infoEntityId = null)} width="520px">
+ <Modal title="Details" onclose={closeInfo} width="520px">
<EntityDetails
entityId={infoEntityId}
+ bind:dirty={infoDirty}
onclose={() => (infoEntityId = null)}
ondeleted={() => (infoEntityId = null)}
/>
</Modal>
{/if}
+{#if infoDiscarding}
+ <ConfirmDialog
+ title="Discard changes?"
+ message="This item has edits that Save has not taken."
+ confirmLabel="Discard"
+ icon="alert"
+ onconfirm={() => { infoDiscarding = false; infoDirty = false; infoEntityId = null; }}
+ oncancel={() => (infoDiscarding = false)}
+ />
+{/if}
+
<style>
.spacer {
flex: 1;
diff --git a/frontend/src/tools/Files.test.js b/frontend/src/tools/Files.test.js
index bb0e053..a3e62a5 100644
--- a/frontend/src/tools/Files.test.js
+++ b/frontend/src/tools/Files.test.js
@@ -46,8 +46,11 @@ describe('Files desktop affordances', () => {
expect(source).toContain('sortEntities(');
});
- it('search also matches notes, not just label/type/folder', () => {
- expect(source).toContain('e.attrs?.notes');
+ it('searches through the one predicate the server index is mirrored in', () => {
+ // Notes, folder and the declared fields all ride on that shared helper, so this
+ // tool cannot drift from the board or from `search_text`.
+ expect(source).toContain("import { matchesEntity } from '../lib/entitySearch.js'");
+ expect(source).toContain('matchesEntity(e, query)');
});
it('keeps the sort control compact instead of stretching to full width', () => {
@@ -99,7 +102,7 @@ describe('Files desktop affordances', () => {
it('previews rendered proof PNGs in both tiles and list rows', () => {
expect(source).toContain("e.type === 'proof' && typeof path === 'string' && /\\.png$/i.test(path)");
expect(source).toContain('class="lrow-thumb"');
- expect(source).toContain('src={`/files/${caseState.current.id}/${tileThumb(e)}`}');
+ expect(source).toContain('src={fileUrl(caseState.current.id, tileThumb(e))}');
expect(source).toContain('{#if tileThumb(e)}');
});
});
@@ -144,3 +147,41 @@ describe('Files delete shortcut', () => {
expect(source).toContain('target.isContentEditable');
});
});
+
+describe('Ctrl+V on the desktop', () => {
+ it('gives Files the only way it has ever had to take a file', () => {
+ // its drag and drop moves items between folders, so an image had to go through
+ // the Media grid and be filed afterwards
+ expect(source).toContain("import { listenForPaste, pasteImage, resolvePaste } from '../lib/clipboardPaste.js'");
+ expect(source).toContain("import PasteDialog from '../components/PasteDialog.svelte'");
+ expect(source).toContain("resolvePaste('files', payload,");
+ });
+
+ it('only answers while it is the tool on screen', () => {
+ expect(source).toMatch(/uiState\.tool !== 'files'\) return;\s*return listenForPaste/);
+ });
+
+ it('opens on the folder being looked at, like the New bookmark button does', () => {
+ expect(source).toContain("{ folder: showUnfiled ? '' : cwd }");
+ });
+
+ it('files the image where the dialog said, and takes a link as a bookmark', () => {
+ expect(source).toContain('await assignFolder(caseId, result.entity, values.folder)');
+ expect(source).toContain('await createBookmark(caseId, { ...values, url: payload.url })');
+ });
+
+ it('shows the folder it landed in, so nothing is filed out of sight', () => {
+ expect(source).toContain('function revealFiled(folder)');
+ expect(source).toContain('if (folder) openFolder(folder);');
+ expect(source).toContain('else openUnfiled();');
+ });
+
+ it('leaves a duplicate where it already sits', () => {
+ // refiling it under this paste's folder would move an item filed on purpose
+ expect(source).toContain('if (!result.duplicate && values.folder)');
+ });
+
+ it('offers the folder picker the same tree every other dialog here gets', () => {
+ expect(source).toMatch(/<PasteDialog[^>]*folders=\{allFolders\}/s);
+ });
+});
diff --git a/frontend/src/tools/Graph.svelte b/frontend/src/tools/Graph.svelte
new file mode 100644
index 0000000..ad746ba
--- /dev/null
+++ b/frontend/src/tools/Graph.svelte
@@ -0,0 +1,6583 @@
+<script>
+ /**
+ * The case drawn as nodes and edges (SPEC §6, v2 "Case graph").
+ *
+ * The Board lists the same entities and lists them better — it sorts, filters
+ * and shows columns. So this is not a second rendering of that list. It answers
+ * what a table cannot: what sits at the centre of the case, what is connected to
+ * what, and what nobody has connected to anything yet.
+ *
+ * It opens on the **whole case**, bounded, because a case is a subject before it
+ * is a set of statements: a conflict followed over months has no single root to
+ * expand out from. Expansion is the drill-down, not the entry point. On a case
+ * too large to draw, the server keeps the most connected nodes, so what stays on
+ * screen is the shape of the case rather than an arbitrary slice — and the view
+ * says how much it left out instead of presenting the slice as the whole.
+ *
+ * Four things carry the interaction, and each answers a way a graph usually
+ * fails:
+ *
+ * - **Hover reads, selection commits.** Passing over a node lights it and its
+ * edges and names them; only a click narrows the picture. A graph that
+ * restyles everything under a moving mouse is a graph that flickers.
+ * - **Focus and context.** Selecting a node fades everything more than one hop
+ * away instead of hiding it. A graph where selection hides is a graph that
+ * loses your place; one where it does nothing is a wall.
+ * - **Every edge says which way it goes and in what words.** The vocabulary is
+ * directed, so each edge carries a head, and the verbs are written along the
+ * edges of whatever is under the eye.
+ * - **The cost of a click is on the node.** A node shows its degree before it is
+ * expanded, so nothing ever explodes without warning.
+ * - **A node can be put somewhere, and stays there.** Dragging one pins it: the
+ * case remembers the spot, the layout treats it as a fixed point and arranges
+ * everything else around it, and what arrives later joins the arrangement
+ * instead of restarting it. Moves are saved as they are made, and there are three
+ * ways back at three sizes: `Ctrl+Z` for the last one, one node at a time from
+ * the panel, the whole arrangement from the toolbar. **Each lens keeps its own
+ * arrangement**,
+ * because a lens is a reading: it draws its own nodes and its own edges, so it
+ * clusters differently, and one shared arrangement would anchor every reading
+ * into the shape of whichever one it was built in. Offered on the whole case
+ * only: a neighbourhood gives its horizontal axis to distance from the root, and
+ * a node moved off its column would contradict what that view is drawn to show.
+ *
+ * Drawn on canvas through Konva, already in the bundle for Geo Proof and Inspect,
+ * so the graph costs no new dependency. **Canvas resolves no CSS variable**, so
+ * every colour is read off the document at draw time and re-read when the theme
+ * changes. The placement is pure and lives in `lib/graph.js`: the same case draws
+ * the same picture every time, because a graph screenshot goes into a report
+ * beside a satellite capture and a capture is reproducible.
+ */
+ import Konva from 'konva';
+ import { fileUrl } from '../lib/fileUrl.js';
+ import { tick, untrack } from 'svelte';
+ import { api } from '../lib/api.js';
+ import {
+ analysisSearch,
+ catalogViews,
+ openAnalysisCase,
+ setAnalysisFilter,
+ setAnalysisPeriod,
+ } from '../lib/analysisSearch.svelte.js';
+ import {
+ analysisPeriodQuery,
+ analysisPeriodSpec,
+ emptyAnalysisPeriod,
+ hasAnalysisPeriod,
+ normalizeAnalysisPeriod,
+ } from '../lib/analysisPeriod.js';
+ import { buildCatalogQuery, fetchAttrFacets } from '../lib/catalog.js';
+ import {
+ chipsOf,
+ clearAxis,
+ emptyFilter,
+ isFiltering,
+ normalizeFilter,
+ toGraphQuery,
+ } from '../lib/entityFilter.js';
+ import { caseState, toast, uiState } from '../lib/state.svelte.js';
+ import {
+ entityIcon,
+ entityKindLabel,
+ madeAsWord,
+ madeHereBy,
+ madeHereLabel,
+ } from '../lib/entityIcon.js';
+ import {
+ entityFamily,
+ entityLabel,
+ entityTypes,
+ familyReads,
+ loadEntityTypes,
+ } from '../lib/entityTypes.svelte.js';
+ import {
+ CHAIN_TYPES,
+ confidenceHint,
+ confidenceLabel,
+ confidenceLevels,
+ isRatable,
+ loadRelationTypes,
+ relationOptions,
+ relationQualifier,
+ relationReading,
+ relationVerb,
+ } from '../lib/relations.svelte.js';
+ import {
+ CARD,
+ CARD_SCALE,
+ EDGE_KINDS,
+ FAMILY_ORDER,
+ familyRank,
+ arrange,
+ arrangementDiff,
+ boxRadius,
+ cardFactor,
+ cropToFill,
+ drawingSnapshot,
+ drawableLinks,
+ edgeKind,
+ edgeMidpoint,
+ edgePoints,
+ edgeStyle,
+ fit,
+ foldAway,
+ foldableCount,
+ nodeAt,
+ nodeRadius,
+ parallelBends,
+ positionsById,
+ ringsAround,
+ shortLabel,
+ } from '../lib/graph.js';
+ import { createHistory } from '../lib/history.js';
+ import { createBookmark } from '../lib/bookmarks.js';
+ import { windowWords } from '../lib/timeline.js';
+ import { listenForPaste, pasteImage, resolvePaste } from '../lib/clipboardPaste.js';
+ import Icon, { paths } from '../components/Icon.svelte';
+ import AnalysisViews from '../components/AnalysisViews.svelte';
+ import AnalysisPeriodBar from '../components/AnalysisPeriodBar.svelte';
+ import FilterBar from '../components/FilterBar.svelte';
+ import Modal from '../components/Modal.svelte';
+ import EntityCreate from '../components/EntityCreate.svelte';
+ import EntityDetails from '../components/EntityDetails.svelte';
+ import PasteDialog from '../components/PasteDialog.svelte';
+ import SnapshotDetails from '../components/SnapshotDetails.svelte';
+
+ loadEntityTypes();
+ loadRelationTypes();
+
+ /** How wide a dot has to be drawn, in screen pixels, before its glyph is worth
+ * putting inside it. Below this the icon is a smudge and the cost is a few
+ * hundred shapes at the one zoom that cannot afford them. */
+ const GLYPH_MIN = 17;
+
+ /** How far the park's frame stands off the column it encloses, in canvas units.
+ * Enough for a node's own radius and the label under the bottom row. */
+ const PARK_PAD = { x: 46, top: 34, bottom: 30 };
+
+ /** Below this scale a label is noise, so only the node in hand keeps one. */
+ const LABEL_SCALE = 0.62;
+ const ZOOM_MIN = 0.12;
+ const ZOOM_MAX = 3.2;
+ /** Pointer travel that turns a click into a pan, so a hand tremor still selects. */
+ const DRAG_SLOP = 4;
+ /** How long a drag waits before it is filed, so a flurry of them is one request. */
+ const SAVE_AFTER = 400;
+ /** How far one arrow key moves a node, in canvas units. The keyboard path to the
+ * same act: a canvas cannot otherwise be arranged without a mouse. */
+ const NUDGE = 12;
+ const NUDGE_FAR = 60;
+ /** How long the search waits before asking the case, so typing a name is one
+ * request rather than one per letter. */
+ const FIND_AFTER = 220;
+ /** Letters before the case is worth asking. One matches most of it. */
+ const FIND_MIN = 2;
+ /** How many connections of one kind the panel lists before the rest are asked for.
+ * A node with forty of the same verb is a hub, and reading it is not the same act
+ * as reading its forty rows. */
+ const GROUP_ROWS = 8;
+ /**
+ * How many nodes the placement starts to cost at, and how many it freezes at.
+ *
+ * Measured rather than guessed: the relaxation compares every node against every
+ * other, sixty times over, on the main thread — 500 nodes place in a quarter of a
+ * second, a thousand in one, two thousand in four with the tab frozen throughout.
+ * The drawing refuses nothing at either line. It says what the next change will
+ * cost, which is the honest half of having no ceiling.
+ */
+ const HEAVY = 1000;
+ const FREEZING = 2000;
+ /** A type no registry can declare, standing for "an allow-list with nothing in it".
+ * Two narrowings that share no type is a real answer, and it is an empty one.
+ * Written as an escape: a raw NUL byte in the source makes the file binary to
+ * git and to every search tool, so the whole module goes quiet under `grep`. */
+ const NOTHING = '\0none';
+
+ let lenses = $state([]);
+ let orders = $state([]);
+ let lens = $state('all');
+ let order = $state('degree');
+ let payload = $state(null);
+ let root = $state(null); // the node an expansion is centred on, null for the case
+ let hops = $state(1);
+ /**
+ * The nodes that have been opened, whose neighbours joined the view.
+ *
+ * The whole case is still on screen behind them: opening a node adds to the
+ * picture rather than replacing it with a different question, which is what
+ * makes this a place to work rather than a thing to navigate.
+ */
+ let expanded = $state([]);
+ /**
+ * The nodes whose surroundings are folded away.
+ *
+ * The other half of one switch, and the only one of these lists the case never
+ * hears about. Folding is a reading of the drawing already on screen: it asks no
+ * question, so it costs no read, and unfolding is instant because nothing left.
+ *
+ * It is what lets the picture the case **opened on** be tidied, which no other
+ * list can do. Opening a node adds to the drawing and hiding one takes it away;
+ * neither speaks for the two hundred nodes that were there before the analyst
+ * touched anything, and those are the ones in the way.
+ *
+ * Because it draws rather than asks, a fold does not give the budget its room
+ * back — the case still sent those nodes. Hiding is the act that does, and the
+ * two are worded apart for exactly that reason: folding tidies, hiding edits.
+ */
+ let collapsed = $state([]);
+ /**
+ * The nodes drawn because they were named, and **nothing around them**.
+ *
+ * The other half of what one list used to conflate. Opening a node is right for a
+ * node you are reading; it is wrong for a route, which arrived with one whole
+ * neighbourhood per step and buried the sentence it was drawn to say. So the two
+ * acts are two lists: this one draws exactly what it names.
+ */
+ let kept = $state([]);
+ /**
+ * The nodes taken out of the drawing by hand.
+ *
+ * What makes the drawing a set the analyst owns rather than a query's answer they
+ * have to live with. Nothing hands one of these back — the case applies it last, so
+ * a removal survives an expansion that reaches the same node — and the ways back are
+ * the neighbour it was hanging on, `Ctrl+Z`, and **Reset view** for the lot.
+ *
+ * The reason it is not optional: everything already drawn is a fixed point, so a
+ * drawing can grow indefinitely without re-placing itself. Without a way to take one
+ * node out, the only way back was folding every expansion, which takes the reading
+ * that raised the question down with it.
+ */
+ let omitted = $state([]);
+ /**
+ * What hiding took off each node still drawn, so the node it hung on can hand it
+ * back.
+ *
+ * Hiding is the analyst's own act on their own picture, and undoing one node of it
+ * used to cost either the whole drawing (**Reset view**) or the name of a node they
+ * had just decided not to look at. Recorded at the moment of the hiding, because
+ * that is the only moment the edge to it is still drawn: the case applies `omit`
+ * last, so the read that follows sends neither the node nor the link.
+ *
+ * Keyed by the node that stays, one entry per **link** taken with it — the case
+ * prices a degree per link, so two entries are what makes the count add up on the
+ * pair joined twice.
+ */
+ let putAway = $state({});
+ /**
+ * The one folder being drawn, or the whole case. The analyst's own bucket, read the
+ * way the Board reads it.
+ *
+ * The Board's other two filters are deliberately **not** here. Review state would
+ * draw the proposals alone, and a proposal's other end is nearly always a confirmed
+ * entity — so the closed link set drops every edge and the picture becomes a column
+ * of dots, while the dash on a node and on an edge already says "proposed" in
+ * place. An exact type is the same failure for the same reason: the verbs run
+ * between families, so one type on its own has almost nothing to join. The two
+ * verbs that do stay inside a family — organizational containment, a network
+ * holding an address — are reached by leaving one family switched on.
+ */
+ let pickFolder = $state('');
+ let folders = $state([]);
+ let summary = $state(null);
+ let searchFilter = $state(emptyFilter());
+ let facets = $state([]);
+ let facetState = $state('unasked');
+ let fieldsWanted = $state(false);
+ /**
+ * A question the Board worked out, being drawn here.
+ *
+ * `{ terms, label }`: the catalog filter as request parameters, and the sentence it
+ * reads as. The **question** travels rather than the rows it matched, which is what
+ * makes the hand-over work at any size — the case is asked the same thing the table
+ * asked, so nothing is capped and the drawing stays live. It is announced over the
+ * canvas and let go in one press, because a narrowing nothing explains is a drawing
+ * that looks broken.
+ */
+ let fromBoard = $state(null);
+ /**
+ * The families switched off, and why this control still matters.
+ *
+ * A lens narrows nodes by **role** — what the analyst wrote leaves the drawing —
+ * which is a decision about the reading, taken once. This narrows by **family**,
+ * which is a decision about the budget: on a real case one family dwarfs the rest,
+ * so switching `collected` off can turn two thousand nodes into three hundred and
+ * spend the budget on the actors, places and statements instead.
+ *
+ * A handful of checkboxes, and no knowledge of the case needed to use them — the
+ * opposite trade from picking entities, which asks the analyst to answer the
+ * question they came to ask.
+ */
+ let hiddenFamilies = $state([]);
+ /** Every type the case actually holds, from the catalog summary. */
+ let caseTypes = $state([]);
+ const familyTitle = (family) => family.charAt(0).toUpperCase() + family.slice(1);
+ const searchFamilies = $derived(
+ [...new Set(caseTypes.map((type) => entityFamily(type)).filter(Boolean))].sort()
+ );
+ const searchTypeOptions = $derived(
+ entityTypes().filter(
+ (entry) =>
+ !searchFilter.families.length || searchFilter.families.includes(entry.family)
+ )
+ );
+ const searchWantedTypes = $derived(
+ searchFilter.types.length
+ ? searchFilter.types
+ : searchFilter.families.length
+ ? searchTypeOptions.map((entry) => entry.type)
+ : []
+ );
+ const searchTerms = $derived(
+ toGraphQuery(searchFilter, { types: searchWantedTypes })
+ );
+ const activePeriod = $derived(hasAnalysisPeriod(analysisSearch.period));
+ const temporalTerms = $derived.by(() => {
+ const period = analysisPeriodQuery(analysisSearch.period);
+ if (!period.temporalFrom) return {};
+ return {
+ temporal_from: period.temporalFrom,
+ temporal_to: period.temporalTo,
+ temporal_category: period.temporalCategories.join(','),
+ };
+ });
+ const searchSaid = $derived(
+ [
+ searchFilter.q.trim() ? `“${searchFilter.q.trim()}”` : '',
+ ...chipsOf(searchFilter, { type: entityLabel, family: familyTitle })
+ .map((chip) => chip.text),
+ activePeriod ? `Fact time · ${windowWords(
+ analysisSearch.period.from, analysisSearch.period.to, 'UTC'
+ )}` : '',
+ ].filter(Boolean).join(' · ')
+ );
+ let loading = $state(false);
+ /**
+ * Why the case could not be read, and **only** that.
+ *
+ * It draws as a message where the drawing would be, which is the truth when there
+ * is no drawing. A write that failed over a case still on screen belongs in `say`
+ * instead: put here, a pin that did not save covered the graph with a sentence
+ * that read as the graph having failed, and nothing cleared it until the next read.
+ */
+ let failed = $state('');
+ let selected = $state(null);
+ /**
+ * How far the focus reaches from the selected node, in hops.
+ *
+ * One hop answers "what touches this", which is the question a click asks. Two
+ * answers "what does this sit between", and it is the one that finds the account
+ * two people both cite without either of them naming the other — a shape that is
+ * invisible at one hop and drowned at the whole case. Three is the ceiling because
+ * past it a well-connected case is reached entirely, and a highlight that covers
+ * everything highlights nothing.
+ *
+ * Kept across a change of node: how far you are looking is a stance, not a
+ * property of what you happen to be looking at. It goes back to one only when the
+ * focus itself is let go.
+ */
+ let focusHops = $state(1);
+ /**
+ * Whether the focus **removes** the rest of the case rather than dimming it.
+ *
+ * Dimming keeps your place — the shape of the case is still there behind the
+ * reading — and that is why it is the default. But a subset you mean to work on
+ * has to be readable on its own: at 0.16 opacity a thousand faded nodes are still
+ * a texture the eye has to fight, and a card at that strength still occludes what
+ * is under it.
+ *
+ * It never touches `nodes`, and this is the point: `placed` is derived from
+ * `arrange`, so filtering the list would re-run the relaxation and put every
+ * surviving node somewhere new. Switched off, the case comes back exactly where it
+ * was, which is what makes this something to try rather than something to commit
+ * to.
+ */
+ let onlyThis = $state(false);
+ /** Where the view stood before the subset was framed, so switching back is a
+ * return rather than a second thing to undo. */
+ let beforeOnly = null;
+ /**
+ * Whether a path is being walked, and the steps of it so far.
+ *
+ * **The primitive the tool was missing.** A case answers "what connects to what"
+ * one hop at a time, but the question an investigation actually asks is "how does
+ * this reach that" — and until now the only way to ask it was to click through the
+ * case and hold the answer in your head.
+ *
+ * Each step is the node arrived at and the edge arrived by, because the edge is
+ * the half that carries the meaning: two nodes joined by `posted` and by
+ * `mentions` are two different findings, and a path recorded as nodes alone cannot
+ * tell them apart when both edges exist.
+ *
+ * It is an **armed gesture**, not a mode a click can wander into, and that is the
+ * whole of why it can be trusted. A click that extended a path whenever it landed
+ * on a neighbour would leave a click on a *non*-neighbour with three bad answers:
+ * do nothing (a canvas that ignores a click), read the node and leave a path
+ * half-built beside it (two questions on one screen), or break the path (six hops
+ * lost to a slip). Armed, there is no such click: what the path can reach is lit
+ * before the press, exactly as `drawing` lights only the ends a relation may land
+ * on, so an impossible step cannot be taken rather than being taken and refused.
+ *
+ * Nothing is stored. A path is derived from edges that can be deleted, so a saved
+ * one goes quietly false the day a link in its middle is removed — the sentence it
+ * reads out is what gets kept, in a note, written by a person.
+ */
+ let tracing = $state(false);
+ let path = $state([]); // [{ id, via }], via being the link arrived by
+ /**
+ * The node a route is being asked *from*, while the gesture waits for its other
+ * end. Armed exactly like a connection: the act is named first, and the click that
+ * follows means the one thing the arming said it would.
+ *
+ * **Nothing is dimmed while it waits**, and that is the one place this parts
+ * company with `drawing`. A relation has a vocabulary that says which pairs are
+ * legal, so an illegal end can be refused before the press. A route has no such
+ * rule: the case is searched, not the drawing, and the view holds five hundred of
+ * a thousand nodes — so a node with no route on screen may be two hops away in the
+ * case. Greying it out would be the picture asserting something only the server
+ * can know. "No route within four hops" is the honest form of that answer, and it
+ * arrives after the question rather than instead of it.
+ */
+ let asking = $state(null); // { from }
+ /**
+ * Every equally short route the case answered with, and which one is being read.
+ *
+ * All of them are lit, and this is the point rather than a flourish: two accounts
+ * reaching the same place through two different sources is what independence looks
+ * like on a real case, and an answer that drew one of them would hide the finding.
+ * The drawing says *how these are connected*; the sentence takes one at a time and
+ * says *by what exactly*, because a sentence cannot be read three times over.
+ */
+ let routes = $state([]);
+ let routeAt = $state(0);
+ let hovered = $state(null);
+ let hoveredLink = $state(null);
+ let openId = $state(null);
+ let snapshotOpen = $state(null);
+ let dirty = $state(false);
+ /** The edge under the panel. An edge is a statement, and often the finding. */
+ let chosenLink = $state(null);
+ /** A relation being drawn: where it started, where the pointer is, what it can
+ * legally land on, and the menu once it has landed. */
+ let drawing = $state(null);
+ let offer = $state(null); // { x, y, from, to, options }
+ /** The node menu, where a node says what can be done with it. */
+ let menu = $state(null); // { id, x, y }
+ /** The canvas menu: what can be done to the drawing where nothing is. Until this
+ * existed the empty space answered a right-click with nothing, and the only way to
+ * put a new entity into a case being read here was to leave for the Board. */
+ let blank = $state(null); // { x, y, at: {x, y} in canvas units }
+ /** An entity being filed from the drawing, and where on the canvas it goes.
+ * `{ at }` — the spot the right-click landed on, which is where the node appears
+ * and stays. */
+ let creating = $state(null);
+ /** What the last write said, cleared on its own: a banner that never leaves stops
+ * being read, and the next failure would go unnoticed under it. */
+ let saving = $state('');
+ let sayTimer = 0;
+ function say(message) {
+ saving = message;
+ clearTimeout(sayTimer);
+ if (message) sayTimer = setTimeout(() => (saving = ''), 6000);
+ }
+ let tip = $state(null); // { x, y, label, type, degree } in screen pixels
+ let zoom = $state(1);
+ let panning = $state(false);
+ /** Whether a card shows the picture the case holds or the entity's own glyph.
+ * Session-only: it is how the analyst is looking at the case right now, not a
+ * setting the workspace has to carry to another machine. */
+ let showPreviews = $state(true);
+
+ let host = $state();
+ let width = $state(0);
+ let height = $state(0);
+
+ /** The whole tool, which is what full screen takes over: a canvas alone would
+ * leave the toolbar behind, and the toolbar is how the drawing is steered. */
+ let toolElement = $state(null);
+ let fullscreen = $state(false);
+
+ /**
+ * Where nodes have been dragged to, and why this map is deliberately not `$state`.
+ *
+ * Dropping a node must not re-arrange the case. If the layout re-ran on every
+ * drop, every *other* node would slide to a new resting place under the hand —
+ * which is the opposite of direct manipulation, and the thing that makes most
+ * graph editors unusable. So the drag moves the one shape it is holding, records
+ * the spot here, and leaves `placed` alone. The map is read the next time the
+ * layout genuinely does run — a resize, a lens change, a reload — and then the
+ * dropped node is an anchor and the rest settle around it.
+ *
+ * `pinnedIds` is the same fact in the form the markup can read, and `pinCount`
+ * counts the whole case rather than this view, because the control that undoes an
+ * arrangement has to appear even when the pinned nodes were cut from the view.
+ */
+ const pins = new Map();
+ let pinnedIds = $state([]);
+ let pinCount = $state(0);
+ // A named graph owns its arrangement. The case-wide pins remain the default
+ // everywhere else and are never rewritten by a view-local drag.
+ let arrangementOwner = $state(null);
+ let arrangementRevision = $state(0);
+ let arrangementSaveRevision = $state(0);
+ let cameraRevision = $state(0);
+ let pending = new Map(); // dropped, not filed yet
+ let savingCase = null; // the case those drops came from
+ let savingFor = null; // the lens those drops belong to
+ let saveTimer = 0;
+
+ /**
+ * Where the drawing put each node last time, and not `$state` for the same reason
+ * `pins` is not: writing it back must not re-derive the thing it was read from.
+ *
+ * This is what makes growing a drawing cost the arrivals rather than the case.
+ * Opening twenty nodes into two thousand re-ran the relaxation over all two
+ * thousand — four seconds of frozen tab on every click, and every node on screen
+ * sliding somewhere new while the analyst was reading it. Held here, the two
+ * thousand are fixed points and only the twenty are placed.
+ *
+ * **It is emptied whenever the question changes**, which is the same seam
+ * `resetView` already turns on: a lens, a filter or a folder is a different reading
+ * and gets a fresh arrangement. Growing, folding back and unpinning are the same
+ * question, and keep it.
+ */
+ const settled = new Map();
+
+ /**
+ * What the case sent, and what is left of it once the folds are applied.
+ *
+ * The seam the whole fold lives on, and it is deliberately this early: everything
+ * downstream — the placement, the edges, the legend, the search, the focus — reads
+ * `nodes` and `links`, so a folded node is absent from all of them at once without
+ * one of them having to know that folding exists.
+ *
+ * A node the analyst placed by hand anchors its piece: an arrangement somebody
+ * built outranks a rule that tidies.
+ */
+ const sentNodes = $derived(payload?.nodes ?? []);
+ const sentLinks = $derived(payload?.links ?? []);
+ const folds = $derived(foldAway(collapsed, sentNodes, sentLinks, new Set(pinnedIds)));
+ const nodes = $derived(
+ folds.hidden.size ? sentNodes.filter((node) => !folds.hidden.has(node.id)) : sentNodes,
+ );
+ const links = $derived(
+ folds.hidden.size
+ ? sentLinks.filter((link) => !folds.hidden.has(link.from) && !folds.hidden.has(link.to))
+ : sentLinks,
+ );
+ const mode = $derived(root ? 'hops' : 'rings');
+ const ownsViewArrangement = () => Boolean(
+ arrangementOwner &&
+ catalogViews.activeView?.surface === 'graph' &&
+ catalogViews.activeView?.id === arrangementOwner
+ );
+ const placed = $derived.by(() => {
+ void arrangementRevision;
+ // A view with no local pin means "let the layout decide", not "borrow the
+ // case-wide pin that happened to be stored under this lens".
+ const placementNodes = ownsViewArrangement()
+ ? nodes.map((node) => node.pin ? { ...node, pin: null } : node)
+ : nodes;
+ return arrange(placementNodes, mode, links, pins, settled);
+ });
+ const positions = $derived(positionsById(placed));
+ const edges = $derived(drawableLinks(links, positions));
+ const bends = $derived(parallelBends(edges));
+ const byId = $derived(new Map(nodes.map((node) => [node.id, node])));
+ const chosen = $derived(selected ? (byId.get(selected) ?? null) : null);
+ const edgeById = $derived(new Map(edges.map((link) => [link.id, link])));
+ const chosenEdge = $derived(chosenLink ? (edgeById.get(chosenLink) ?? null) : null);
+ const snapshotReading = $derived(Boolean(catalogViews.snapshotId || payload?.snapshot));
+
+ /**
+ * The readings a landed connection offers, under the registry's own headings.
+ *
+ * A pointer must not borrow the weight of a finding (ONTOLOGY §3), and in one
+ * unheaded list it does: "mentions" sitting under "owns" makes a document naming a
+ * place look like a statement about it. The heading is the registry's `group`, the
+ * same one the Details picker puts over its verbs, so nothing is worded here — and
+ * the ungrouped readings come first because that is the order the registry sorts.
+ */
+ const offerGroups = $derived.by(() => {
+ const groups = new Map();
+ for (const option of offer?.options ?? []) {
+ const group = option.group ?? '';
+ if (!groups.has(group)) groups.set(group, []);
+ groups.get(group).push(option);
+ }
+ return [...groups].map(([group, options]) => ({ group, options }));
+ });
+
+ /** Whether the drawing has been edited at all, and so whether there is anything to
+ * put back. Four lists, one way back: which of them is in the way is not a question
+ * the analyst should have to answer before undoing their own picture. */
+ const edited = $derived(
+ Boolean(expanded.length || kept.length || omitted.length || collapsed.length),
+ );
+ /** How many nodes the folds are currently holding off the screen. */
+ const foldedCount = $derived(folds.hidden.size);
+ /**
+ * What the switch on the node in hand would do, and to how many.
+ *
+ * Computed for one node rather than for all of them, and that is a decision about
+ * the picture before it is one about the cost: a count pinned to every dot is a
+ * few hundred numbers nobody reads. The badge belongs to the node under the eye.
+ */
+ const switchFor = $derived.by(() => {
+ const id = hovered ?? selected;
+ if (!id || !byId.has(id)) return null;
+ if (collapsed.includes(id)) return { id, act: 'unfold', count: folds.by.get(id) ?? 0 };
+ const away = root ? 0 : offScreen(id);
+ if (away > 0) return { id, act: 'expand', count: away };
+ const takes = foldableCount(id, nodes, links, new Set(pinnedIds));
+ return takes ? { id, act: 'fold', count: takes } : null;
+ });
+ /**
+ * What a drawing this size costs to place, once it costs anything worth saying.
+ *
+ * The drawing has no ceiling — one that refuses is the app overruling the analyst
+ * about their own picture — so what is left is telling them what the next change
+ * will cost. Null below the first line, where it costs nothing worth a word.
+ */
+ const weight = $derived(
+ nodes.length >= FREEZING ? 'freezing' : nodes.length >= HEAVY ? 'heavy' : null,
+ );
+
+ /**
+ * How many of a node's connections are **not** on screen.
+ *
+ * The number that makes expanding a node worth offering. A node states its whole
+ * degree, but a view that already holds every one of its neighbours has nothing
+ * left to bring in — which is most of the time on a case that fits. Offering it
+ * there was offering an act that could only appear to do nothing.
+ */
+ const offScreen = $derived.by(() => {
+ const held = new Map();
+ // Counted over the connections the **drawing holds**, not the ones the case sent:
+ // a fold takes nodes off the screen, and their connections are missing from the
+ // picture in exactly the sense this number means. An edge from a node onto itself
+ // is dropped by the canvas — a loop has no length and would smudge under the dot —
+ // but the view has it and no expansion can bring it in again, so counting it as
+ // missing left a node saying "1 more not drawn" for ever, under a control that
+ // could never do anything about it. Both ends every time, undeduplicated, because
+ // that is how the case counts a degree: the server's tally is one row per end, so
+ // a loop is two there and has to be two here or the subtraction never reaches zero.
+ for (const link of links) {
+ for (const end of [link.from, link.to]) held.set(end, (held.get(end) ?? 0) + 1);
+ }
+ // Plus what hiding took off it. The case prices a degree against the picture it
+ // sent, so a hidden neighbour is not in that number — and the node would say every
+ // connection was drawn while the analyst was looking at the gap they had just made.
+ return (id) =>
+ Math.max((byId.get(id)?.degree ?? 0) - (held.get(id) ?? 0), 0) + (putAway[id]?.length ?? 0);
+ });
+
+ /**
+ * Ids within `focusHops` of the selected node: the focus, and the weakest of the
+ * questions that narrow the picture (see `narrowing`).
+ *
+ * Selection only, and never the root of an expansion. Fading the whole case
+ * under a moving mouse made the picture strobe, and left Escape looking broken:
+ * the highlight stayed as long as the pointer had not moved off the node. Fading
+ * around the root of a neighbourhood was worse than cosmetic — asking for three
+ * hops and getting hops two and three greyed out contradicts the question.
+ *
+ * Walked over the edges already drawn, so no read is owed to a change of reach:
+ * the case on screen is a closed set of connections, and the second and third
+ * rings are already in it. The one that does cost a read is the neighbourhood's
+ * own Hops, which asks the case a different question.
+ */
+ const focused = $derived.by(() => {
+ if (!selected || selected === root) return null;
+ return ringsAround(edges, selected, focusHops);
+ });
+
+ const neighbours = $derived.by(() => {
+ if (!selected) return [];
+ return edges
+ .filter((link) => link.from === selected || link.to === selected)
+ .map((link) => {
+ const far = link.from === selected ? link.to : link.from;
+ return { link, entity: byId.get(far), outgoing: link.from === selected };
+ })
+ .filter((row) => row.entity);
+ });
+
+ /**
+ * The same connections, grouped by what they say about the node.
+ *
+ * A flat list in edge order is a list of edges rather than a reading of a node:
+ * forty rows with "posted" written on twelve of them say less than one heading
+ * that says twelve. The key is the verb **and** its direction, because the registry
+ * words those apart — a document that mentions something and one that is mentioned
+ * by it are not the same fact — and because the heading is where the verb now
+ * lives, so two directions under one heading would each read as the wrong one.
+ *
+ * Biggest group first. What a node mostly is, is the first thing to say about it.
+ */
+ const neighbourGroups = $derived.by(() => {
+ const groups = new Map();
+ for (const row of neighbours) {
+ const way = row.outgoing ? 'out' : 'in';
+ const key = `${row.link.type} ${way}`;
+ if (!groups.has(key)) {
+ groups.set(key, { key, reading: relationReading(row.link.type, way), rows: [] });
+ }
+ groups.get(key).rows.push(row);
+ }
+ return [...groups.values()].sort(
+ (a, b) => b.rows.length - a.rows.length || a.reading.localeCompare(b.reading),
+ );
+ });
+
+ /**
+ * The groups showing all their rows rather than the first few.
+ *
+ * Cleared with the selection: it is how one node is being read right now, not a
+ * setting about how nodes are read. Keeping it would open the next node's list
+ * half-unfolded on whichever verbs the last one happened to share.
+ */
+ let allOf = $state([]);
+ $effect(() => {
+ void selected;
+ allOf = [];
+ });
+
+ /**
+ * The types this reading leaves out of the drawing, as the case states them.
+ *
+ * A lens narrows nodes as well as verbs: what the analyst *wrote* — a post, a note,
+ * an Inspect session — is the filing rather than the case, so the four readings of
+ * the case leave it out and **My work** is where it lives. Read from the lens
+ * registry rather than listed here, for the same reason the lenses are: the roles
+ * live on the server, and a copy would go stale the day a type is added.
+ *
+ * Two controls need it *before* the case is asked, and both would otherwise appear
+ * broken: a legend row that switches nothing, and "bring this in" on an entity this
+ * reading is going to refuse.
+ */
+ const lensHides = $derived(lenses.find((entry) => entry.id === lens)?.hides ?? []);
+
+ /**
+ * The families this **case** holds, in drawing order.
+ *
+ * Read off the catalog summary rather than off the drawing, which is the change
+ * that lets the legend be a control: a family read from what is drawn disappears
+ * the moment it is switched off, taking with it the only thing that could switch
+ * it back on. It still never advertises a family the case does not hold — nor one
+ * whose every member this reading leaves out, since that row would be a switch with
+ * nothing behind it.
+ */
+ const caseFamilies = $derived.by(() => {
+ const seen = new Set();
+ for (const type of caseTypes) {
+ if (lensHides.includes(type)) continue;
+ const family = entityFamily(type);
+ if (family) seen.add(family);
+ }
+ // Until the summary lands, whatever is drawn: the legend is never blank while
+ // there are nodes on screen.
+ if (!seen.size) for (const node of nodes) if (node.family) seen.add(node.family);
+ return [...seen].sort((a, b) => familyRank(a) - familyRank(b) || a.localeCompare(b));
+ });
+
+ /** The legend: each family the case holds, how many of it is drawn, and whether it
+ * is switched on. The count is of the drawing, because that is what a legend
+ * explains; the row is of the case, because that is what it switches. */
+ const legend = $derived.by(() => {
+ const counts = new Map();
+ for (const node of nodes) counts.set(node.family, (counts.get(node.family) ?? 0) + 1);
+ return caseFamilies.map((family) => ({
+ family,
+ count: counts.get(family) ?? 0,
+ on: !hiddenFamilies.includes(family),
+ }));
+ });
+
+ /**
+ * The types a narrowed set of families resolves to, as one comma-separated list.
+ *
+ * Resolved here rather than by a route of its own, the way the Board resolves its
+ * own family filter: the family layer is server vocabulary, and the catalog read
+ * already speaks types.
+ *
+ * Built from the types the **case** holds, not from the registry's, for one reason
+ * that would otherwise be a silent loss: a free-typed entity has no declared
+ * family (`family_of` answers None), so an allowlist drawn from the registry would
+ * drop it the moment any family was switched off. Here it is always kept, because
+ * no tick claims to speak for it.
+ */
+ const familyTypes = $derived.by(() => {
+ if (!hiddenFamilies.length) return '';
+ const held = caseTypes.length ? caseTypes : entityTypes().map((entry) => entry.type);
+ return held
+ .filter((type) => {
+ const family = entityFamily(type);
+ return !family || !hiddenFamilies.includes(family);
+ })
+ .join(',');
+ });
+
+ /**
+ * Switch a family off, or back on.
+ *
+ * The last one on stays on: every family off is a blank canvas, which is not a
+ * reading of anything, and the empty `type` filter would be read server-side as
+ * "no narrowing" and draw the whole case back — a control that does the opposite
+ * of what it says at one particular setting.
+ */
+ function toggleFamily(family) {
+ const off = hiddenFamilies.includes(family);
+ if (!off && hiddenFamilies.length >= caseFamilies.length - 1) return;
+ hiddenFamilies = off
+ ? hiddenFamilies.filter((entry) => entry !== family)
+ : [...hiddenFamilies, family];
+ }
+
+ /**
+ * The few nodes that keep their name at any zoom.
+ *
+ * What sits at the centre of the case is the question this tool exists to answer,
+ * and a wide view of unnamed dots answers it only as a shape. Six is the number
+ * that stays readable: labels are held at a fixed size on screen, so naming forty
+ * of them at a wide zoom would be a wall of overlapping text, which is the reason
+ * labels declutter in the first place.
+ */
+ const hubs = $derived.by(() => {
+ const ranked = nodes
+ .filter((node) => node.degree >= 2)
+ .sort((a, b) => b.degree - a.degree || String(a.id).localeCompare(String(b.id)));
+ return new Set(ranked.slice(0, 6).map((node) => node.id));
+ });
+
+ /** The strokes on screen, worded. An unexplained dash pattern is decoration. */
+ const strokes = $derived.by(() => {
+ const present = new Set(edges.map((link) => edgeKind(link, CHAIN_TYPES)));
+ return EDGE_KINDS.filter((entry) => present.has(entry.kind));
+ });
+
+ const lensHint = $derived(lenses.find((entry) => entry.id === lens)?.hint ?? '');
+
+ /**
+ * Finding a node by name. On a case drawn at a few hundred nodes, hunting one by
+ * eye is hopeless, and a canvas is unreachable from the keyboard — so this is
+ * both the way in without a mouse and the only practical way to reach a
+ * particular entity. Matches are ranked the way the rings are, most connected
+ * first, so the obvious answer is the first one.
+ */
+ let find = $state('');
+
+ /**
+ * Whether the list under the field is showing, which is not the same question as
+ * whether anything was typed.
+ *
+ * The two used to be one, and that was fine while a search only fed a list. Now the
+ * typing lights the drawing, so the answer is on the canvas — and the list is a
+ * panel sitting on top of the answer, in the way of every click that would follow
+ * it. Pressing on the case puts it away without giving the search up: the matches
+ * stay lit, the count stays, and the node under the pointer can be read. The field
+ * brings the list back, because asking for it again is what returning to the field
+ * means.
+ */
+ let listing = $state(true);
+
+ /**
+ * Every drawn node the typed name matches, uncapped.
+ *
+ * Uncapped because this is what the **drawing** lights, and the count beside it
+ * states. A picture that lit eight of twenty-three matches would answer a
+ * different question from the one written over it. The list under the field is the
+ * capped one, and deliberately so: a dropdown is a handful to pick from, where the
+ * canvas is the reading.
+ */
+ const found = $derived.by(() => {
+ const term = find.trim().toLowerCase();
+ const hit = new Set();
+ if (!term) return hit;
+ for (const node of nodes) {
+ if (String(node.label).toLowerCase().includes(term)) hit.add(node.id);
+ }
+ return hit;
+ });
+
+ /**
+ * Finding a node by name. On a case drawn at a few hundred nodes, hunting one by
+ * eye is hopeless, and a canvas is unreachable from the keyboard — so this is
+ * both the way in without a mouse and the only practical way to reach a
+ * particular entity. Matches are ranked the way the rings are, most connected
+ * first, so the obvious answer is the first one.
+ */
+ const matches = $derived.by(() => {
+ const term = find.trim().toLowerCase();
+ if (!term) return [];
+ // Over what the case **sent**, not over what is drawn, so a folded node is found
+ // where it is rather than reported missing and fetched again. It says it is
+ // folded, and picking it gives its fold back.
+ return sentNodes
+ .filter((node) => String(node.label).toLowerCase().includes(term))
+ .sort((a, b) => b.degree - a.degree)
+ .slice(0, 8);
+ });
+
+ // -- the path --------------------------------------------------------------
+
+ // What the drawing lights. A walked path is the one route there is; an answered
+ // question is every route that ties for shortest, all of them at once.
+ const pathIds = $derived(
+ routes.length
+ ? new Set(routes.flatMap((route) => route.nodes))
+ : new Set(path.map((step) => step.id)),
+ );
+ const pathLinks = $derived(
+ routes.length
+ ? new Set(routes.flatMap((route) => route.links))
+ : new Set(path.map((step) => step.via).filter(Boolean)),
+ );
+ /** Where the sentence currently ends, and so where a further step would leave from. */
+ const pathEnd = $derived(path.at(-1)?.id ?? null);
+
+ /**
+ * Where the path may go next: the neighbours of its far end it has not been
+ * through, each with the edge that would carry it there.
+ *
+ * Lit before the click rather than judged after it. A node already on the path is
+ * deliberately not here — walking back onto it truncates instead, since a route
+ * that visits a node twice is not a path — and the first edge found wins when two
+ * nodes are joined more than once, which the sentence then names.
+ */
+ const nextSteps = $derived.by(() => {
+ const steps = new Map();
+ if (!tracing || !pathEnd) return steps;
+ for (const link of edges) {
+ const far = link.from === pathEnd ? link.to : link.to === pathEnd ? link.from : null;
+ if (!far || pathIds.has(far) || steps.has(far)) continue;
+ steps.set(far, link);
+ }
+ return steps;
+ });
+
+ /**
+ * Whether the drawing is narrowed to the statements that rest on one account.
+ *
+ * The toolbar's number named a set and gave no way to reach it: "2 on one account"
+ * left the analyst opening statements one at a time to find out which two. Pressing
+ * it asks the question the number was only half answering.
+ */
+ let singling = $state(false);
+
+ /**
+ * Those statements and one hop around them, or null while nothing is narrowed.
+ *
+ * One hop is where the finding is. The sources a statement rests on are folded into
+ * its edges, so the statement and what its edges reach **is** the shape being
+ * reported — a claim, one account, and nothing else lit. Unfolded, the sources are
+ * the hop and the account stands one step behind them in the context, which is the
+ * honest reading of that gesture: asking to see the sources themselves is a
+ * different question from asking who published them.
+ *
+ * Null rather than an empty set when nothing qualifies, so a lens drawing no such
+ * statement fades nothing instead of fading everything.
+ */
+ const singled = $derived.by(() => {
+ if (!singling) return null;
+ const resting = new Set(nodes.filter((node) => node.rests?.one).map((node) => node.id));
+ if (!resting.size) return null;
+ // One pass over the edges, collecting into a second set: growing the set being
+ // read from would let a neighbour pull in its own neighbours, and the one hop
+ // this promises would quietly become two.
+ const near = new Set(resting);
+ for (const link of edges) {
+ if (resting.has(link.from)) near.add(link.to);
+ if (resting.has(link.to)) near.add(link.from);
+ }
+ return near;
+ });
+
+ /**
+ * Ask for those statements, or give the case back.
+ *
+ * The typed name outranks this question, so it goes when this one is asked: left
+ * standing it would answer the press with an unchanged picture, and a control that
+ * does nothing the first time is one nobody presses twice.
+ */
+ function showResting() {
+ singling = !singling;
+ if (singling) find = '';
+ }
+
+ /**
+ * What the picture is narrowed around: the one set that keeps full strength while
+ * everything else falls to context.
+ *
+ * Several questions dim the case — a path, a search, the statements on one account,
+ * the focused node — and **only one may do it at a time**. Two fades composited over
+ * each other are not a third reading, they are an unreadable one: typing a name
+ * while a node was selected left two sets of context over each other, with nothing
+ * on screen saying which question the drawing was answering.
+ *
+ * So they are ranked rather than combined, the most recently asked first — a name
+ * is typed after the node was clicked, and a path is walked after both. The
+ * selection is the weakest, which is why a click narrows nothing while a search is
+ * on: it still rings the node and opens the panel, which is what a click is for.
+ *
+ * A path keeps its next steps at full strength alongside itself. They are the
+ * question the gesture is asking — *where can this go* — and a walk whose choices
+ * were dimmed into the context would be a walk taken blind.
+ */
+ const narrowing = $derived.by(() => {
+ // A question waiting for its other end narrows **nothing**, and this is not a
+ // detail of taste. Every node is a legal answer, so the focus fade left over
+ // from selecting the node the question starts from says "only these can be
+ // pressed" — the exact opposite of what the strip above it says, and it makes a
+ // gesture that works everywhere look like one that works on five nodes.
+ if (asking) return null;
+ if (tracing) return new Set([...pathIds, ...nextSteps.keys()]);
+ if (found.size) return found;
+ if (singled) return singled;
+ return focused;
+ });
+
+ /**
+ * The path read as a sentence: the nodes it goes through and the verb of each edge
+ * between them, in the direction that edge actually points.
+ *
+ * The deliverable, and the reason a path beats a highlight. A drawing says *these
+ * are joined*; a sentence says **what the joining is**, and that is the thing that
+ * goes into a report — an account that posted a video and a video that mentions an
+ * account are not the same claim, and a sentence that flattened both to "connects
+ * to" would say nothing.
+ *
+ * **Every step reads forwards, in the order it was walked.** An edge traversed
+ * against its arrow takes the registry's inverse wording, exactly as the node
+ * panel does — the same edge, said from the other end. Writing the plain verb with
+ * a reversed arrow instead was the first attempt, and it made a true sentence
+ * unreadable: *A ← made from B ← made from C* is a route the eye has to walk
+ * backwards to understand, and the analyst has to hold the reversal for every step
+ * to see that it says C was made from B was made from A.
+ */
+ const sentence = $derived.by(() =>
+ path.map((step, index) => {
+ const link = index ? edgeById.get(step.via) : null;
+ const forward = link ? link.from === path[index - 1].id : true;
+ return {
+ id: step.id,
+ label: byId.get(step.id)?.label ?? '',
+ node: byId.get(step.id) ?? null,
+ verb: link ? relationReading(link.type, forward ? 'out' : 'in') : '',
+ };
+ }),
+ );
+
+ /** Arm the walk on the node in hand, which becomes its first step. */
+ function traceFrom(id) {
+ if (!id) return;
+ asking = null;
+ routes = [];
+ tracing = true;
+ path = [{ id, via: null }];
+ selected = id;
+ letGoOnly();
+ }
+
+ /** Arm the question, and wait for the node that answers it. */
+ function askWayFrom(id) {
+ if (!id) return;
+ traceStop();
+ asking = { from: id };
+ selected = id;
+ letGoOnly();
+ }
+
+ /** Give the walk up whole. A path is one thing, so half of it is not worth keeping. */
+ function traceStop() {
+ tracing = false;
+ path = [];
+ routes = [];
+ routeAt = 0;
+ }
+
+ /** A route the case answered with, waiting for the read that draws its nodes. */
+ let routing = null;
+ let routeRun = 0;
+
+ /**
+ * Ask the case how one node reaches another.
+ *
+ * The other end is named by clicking it or by typing its name, and the second is
+ * not a convenience: the view holds five hundred nodes of a thousand, and "are
+ * these two connected" is asked precisely about things far enough apart to be off
+ * screen. A node that cannot be clicked would otherwise be a node that cannot be
+ * asked about.
+ *
+ * What comes back fills the same object a hand-walked path does, so it is drawn,
+ * worded and stepped back through identically — and can be walked onward from,
+ * which is what makes an answer a place to keep working rather than a result.
+ */
+ async function wayTo(to) {
+ const cid = caseState.current?.id;
+ const start = asking?.from;
+ const run = ++routeRun;
+ find = '';
+ asking = null;
+ if (!cid || !start || to === start) return;
+ let body;
+ try {
+ body = await api.get(
+ `/api/cases/${cid}/graph/paths?${new URLSearchParams({ from: start, to, lens })}`,
+ );
+ } catch {
+ if (run !== routeRun || caseState.current?.id !== cid) return;
+ say('The case could not be asked for a route.');
+ return;
+ }
+ if (run !== routeRun || caseState.current?.id !== cid) return;
+ if (!body.found) {
+ // An answer, not a failure: that two entities are *not* connected within the
+ // budget is a finding about the case, and the only one nothing else reports.
+ say(`No route to that one in this lens, within ${body.searched} hops.`);
+ return;
+ }
+ // A sentence whose nodes are not on screen points at nothing, so a route through
+ // what the budget cut is drawn first — **as itself**. Opened instead, each step of
+ // the route brought its whole neighbourhood, and a four-node answer arrived inside
+ // a crowd of forty. A named node outranks the cut that hid it either way.
+ const drawn = body.routes.every((route) => route.nodes.every((id) => byId.has(id)));
+ if (!drawn) {
+ routing = body.routes;
+ holdOn(body.routes.flatMap((route) => route.nodes));
+ return;
+ }
+ layRoutes(body.routes);
+ }
+
+ function layRoutes(answered) {
+ routes = answered;
+ routeAt = 0;
+ tracing = true;
+ readRoute(0);
+ }
+
+ /** Read one of the tied routes as the sentence, leaving all of them lit. */
+ function readRoute(index) {
+ const route = routes[index];
+ if (!route) return;
+ routeAt = index;
+ path = route.nodes.map((id, at) => ({ id, via: at ? route.links[at - 1] : null }));
+ selected = route.nodes.at(-1);
+ }
+
+ /** Lay the answered routes once the read that draws them has landed. */
+ function settleRoute() {
+ const answered = routing;
+ if (!answered) return;
+ routing = null;
+ // A route outranks a fold for the same reason a typed name does: the sentence is
+ // the answer, and half of it put away is not one.
+ showAgain(answered.flatMap((route) => route.nodes));
+ const held = new Set(payload?.nodes.map((node) => node.id) ?? []);
+ const drawn = answered.filter((route) => route.nodes.every((id) => held.has(id)));
+ if (!drawn.length) {
+ say('That route did not fit in the view. Narrow the case and ask again.');
+ return;
+ }
+ layRoutes(drawn);
+ }
+
+ function stepTo(id) {
+ // Stepping by hand leaves the case's answer behind: the tied routes were the
+ // reply to one question, and taking a step is asking a different one.
+ routes = [];
+ const back = path.findIndex((step) => step.id === id);
+ if (back >= 0) {
+ path = path.slice(0, back + 1);
+ } else {
+ const link = nextSteps.get(id);
+ if (!link) return;
+ path = [...path, { id, via: link.id }];
+ }
+ selected = id;
+ if (!inSight(id)) bringUnderEye(id);
+ }
+
+ /**
+ * What "Only this" is currently taking off the screen, or null while it is not.
+ *
+ * It answers to the same ladder the fade does, and for the same reason: a name
+ * typed while the rest of the case is hidden outranks the hiding, so the case
+ * comes back with the matches lit, and the same goes for the statements on one
+ * account — a question asked of the whole drawing cannot be answered by a drawing
+ * cut down to one node. The alternative was worse than a rule broken —
+ * hiding everything outside the matches strands them, since an edge is only drawn
+ * when both of its ends survive, and the answer to a search would have been a
+ * scatter of unconnected dots.
+ *
+ * Read by the drawing **and** by the connection band, so a relation cannot be
+ * landed on a node that is not on screen to receive it.
+ */
+ const hiding = $derived(onlyThis && !tracing && !found.size && !singling ? focused : null);
+
+ /**
+ * The entities the case holds under this name that the drawing does **not**.
+ *
+ * The reason this exists: a view is bounded, so on a case larger than the budget
+ * most of it is not on screen — and a search that only read the drawing answered
+ * "no such entity" for entities the case plainly holds. Nothing distinguished
+ * "not in the case" from "not in this picture", which is the worse of the two
+ * silences.
+ *
+ * Asked of the catalog, the read the Board uses, so the two surfaces cannot
+ * disagree about what a name matches. **The narrowing is deliberately ignored**:
+ * an analyst typing a name is asking about the case, not about the filters they
+ * set earlier — the same argument `expand` already makes server-side, and the same
+ * one that lets a brought-in node survive them.
+ */
+ let elsewhere = $state([]);
+ /** The node asked for, waiting for the read that brings it into the picture. */
+ let bringing = null;
+ let lookupRun = 0;
+
+ $effect(() => {
+ const term = find.trim();
+ const cid = caseState.current?.id;
+ // Not in a neighbourhood: that read is one node and its hops, and it takes no
+ // `expand`, so there is nowhere to bring an entity into. The filters are folded
+ // away there for the same reason.
+ // One letter matches most of a case, so the local list carries it and the case
+ // is not asked. Below two, there is nothing worth a request.
+ if (!cid || root || term.length < FIND_MIN) {
+ elsewhere = [];
+ return;
+ }
+ const timer = setTimeout(() => lookUp(cid, term), FIND_AFTER);
+ return () => clearTimeout(timer);
+ });
+
+ async function lookUp(caseId, term) {
+ const run = ++lookupRun;
+ try {
+ const page = await api.get(
+ buildCatalogQuery(caseId, { query: term, limit: 12 }),
+ );
+ // A later keystroke owns the field now, and its own request is in flight.
+ if (
+ run !== lookupRun ||
+ caseState.current?.id !== caseId ||
+ term !== find.trim()
+ ) return;
+ // What the case sent counts as held, folded or not: a node the drawing has put
+ // away is not one to go and fetch, it is one to unfold, and the list above
+ // already offers it.
+ const drawn = new Set(sentNodes.map((node) => node.id));
+ elsewhere = (page.items ?? []).filter((entity) => !drawn.has(entity.id)).slice(0, 6);
+ } catch {
+ if (run !== lookupRun || caseState.current?.id !== caseId) return;
+ // A failed lookup leaves the local matches alone: the drawing is still
+ // searchable, and a banner over a search box nobody has finished typing in
+ // would be noise.
+ elsewhere = [];
+ }
+ }
+
+ /**
+ * Bring an entity the drawing does not hold into it.
+ *
+ * The same act as opening a node, and deliberately the same mechanism: `expand`
+ * keeps the named node whatever the ranking and the filters would have done with
+ * it, and brings what touches it. An entity alone in a picture about connections
+ * says nothing, so its neighbours come too.
+ *
+ * **A lens is the one thing it cannot be brought past.** A filter is a narrowing set
+ * earlier and a name outranks it; a reading that does not draw notes would stop
+ * being that reading with a note in it. Said here rather than after the read, or the
+ * case would answer with an unchanged picture and the sentence would blame the
+ * budget for a refusal the reading made.
+ */
+ function bringIn(entity) {
+ if (snapshotReading) {
+ say('This snapshot is read-only. Leave it to change the drawing.');
+ return;
+ }
+ const { id, type } = entity;
+ if (lensHides.includes(type)) {
+ find = '';
+ elsewhere = [];
+ say('Not drawn in this lens. My work draws it.');
+ return;
+ }
+ find = '';
+ elsewhere = [];
+ bringing = id;
+ // A name typed outranks a removal made earlier, or the case would answer the
+ // search with the same unchanged picture the removal left.
+ backIn([id]);
+ if (!expanded.includes(id)) expanded = [...expanded, id];
+ }
+
+ /** Put a node in the middle of the view, keeping the current zoom. */
+ function bringUnderEye(id) {
+ const spot = positions.get(id);
+ if (!spot || !group) return;
+ const scale = group.scaleX();
+ group.position({ x: width / 2 - spot.x * scale, y: height / 2 - spot.y * scale });
+ cameraRevision += 1;
+ restyle();
+ }
+
+ /**
+ * Select a node and bring it under the eye, keeping the current zoom.
+ *
+ * While a walk is armed the search moves the **eye** and not the selection: the
+ * walk owns where the path is, and a name typed into the field cannot teleport it
+ * to a node nothing connects to. The node arrives under the pointer, and it is
+ * stepped onto by clicking it if it is lit.
+ */
+ function jumpTo(id) {
+ // A name typed outranks a fold, as it outranks a removal: the node comes back
+ // before anything is done with it, or the eye would be sent to a spot the
+ // drawing is not drawing.
+ showAgain([id]);
+ // An armed gesture takes the name as its other end. This is the half a click
+ // cannot cover: the node being asked about is often not drawn, and Find is the
+ // keyboard's way into a canvas.
+ if (drawing) {
+ find = '';
+ bringUnderEye(id);
+ landOn(id);
+ return;
+ }
+ if (asking) {
+ wayTo(id);
+ return;
+ }
+ // During a hand-walk the search moves the eye and not the path: the walk owns
+ // where the path is, and a name cannot teleport it to a node nothing joins.
+ if (tracing) {
+ find = '';
+ bringUnderEye(id);
+ return;
+ }
+ selected = id;
+ find = '';
+ bringUnderEye(id);
+ }
+
+ /**
+ * Whether a node is already in front of the analyst.
+ *
+ * Not `onScreen`, which pads by two cards so that a drag reveals cards already
+ * built. The question here is whether following a connection has to move anything,
+ * and a node sitting half off the edge is one that cannot be read where it is.
+ */
+ function inSight(id) {
+ const spot = positions.get(id);
+ if (!spot || !group) return false;
+ const scale = group.scaleX() || 1;
+ const left = -group.x() / scale;
+ const top = -group.y() / scale;
+ const pad = 60 / scale;
+ return (
+ spot.x > left + pad &&
+ spot.x < left + width / scale - pad &&
+ spot.y > top + pad &&
+ spot.y < top + height / scale - pad
+ );
+ }
+
+ /**
+ * Read the node at the other end of a connection.
+ *
+ * **The view moves only when it has to.** Following a thread through a case is a
+ * sequence of these, and recentring on every one of them makes the drawing lurch
+ * under the reading — the neighbour was usually right there, since the layout puts
+ * linked nodes next to each other. When it is off screen the view goes to it at the
+ * current zoom, which is what the search already does.
+ *
+ * A running search is left alone, unlike picking a name out of the list: following
+ * a connection is not answering the question that was typed, and dropping the
+ * highlight would put the case back just as the analyst walks into it.
+ *
+ * While a walk is armed the same row steps the path instead, which is what makes
+ * the walk reachable without a mouse: a row is always a neighbour of the node the
+ * path currently ends on, so it is always a legal step or a step back. While a
+ * question is armed it names the other end, for the same reason — an armed gesture
+ * owns every way of pointing at a node, or the keyboard would be left out of the
+ * one act the canvas cannot offer it.
+ */
+ function followTo(id) {
+ selected = id;
+ if (!inSight(id)) bringUnderEye(id);
+ }
+
+ // -- the locked focus ------------------------------------------------------
+
+ /** Frame what the focus reaches, so a subset drawn alone is drawn at a size worth
+ * reading. Uses the placement as it stands, dragged nodes included. */
+ function frameOnly() {
+ if (!focused || !group || !width || !height) return;
+ const view = fit(
+ placed.filter((node) => focused.has(node.id)),
+ width,
+ height,
+ );
+ group.position({ x: view.x, y: view.y });
+ group.scale({ x: view.scale, y: view.scale });
+ zoom = view.scale;
+ cameraRevision += 1;
+ restyle();
+ }
+
+ /** Put the case back, and the view with it. */
+ function letGoOnly() {
+ if (!onlyThis) return;
+ onlyThis = false;
+ if (beforeOnly && group) {
+ group.position({ x: beforeOnly.x, y: beforeOnly.y });
+ group.scale({ x: beforeOnly.scale, y: beforeOnly.scale });
+ zoom = beforeOnly.scale;
+ cameraRevision += 1;
+ }
+ beforeOnly = null;
+ restyle();
+ }
+
+ function toggleOnly() {
+ if (onlyThis) {
+ letGoOnly();
+ return;
+ }
+ if (!focused || !group) return;
+ beforeOnly = { x: group.x(), y: group.y(), scale: group.scaleX() };
+ onlyThis = true;
+ frameOnly();
+ }
+
+ /**
+ * How far the focus reaches, changed.
+ *
+ * Reframing happens only while the rest is hidden, and only here. Asking for a
+ * different reach is asking for a subset of a different size, and nothing else on
+ * screen says by how much. Walking from node to node deliberately does **not**
+ * reframe: that is a reading in progress, and a view that jumps on every step is
+ * the lurch `followTo` exists to avoid.
+ */
+ function setFocusHops(count) {
+ if (!focused || focusHops === count) return;
+ focusHops = count;
+ if (onlyThis) frameOnly();
+ }
+
+ // Letting the node go lets its reach go with it: a hop count with nothing to count
+ // from is a setting nobody can see, and it would silently apply itself to whatever
+ // was clicked next.
+ $effect(() => {
+ if (selected) return;
+ untrack(() => {
+ focusHops = 1;
+ letGoOnly();
+ });
+ });
+
+ // -- reading ---------------------------------------------------------------
+
+ async function loadRegistry() {
+ try {
+ const body = await api.get('/api/cases/graph-lenses');
+ lenses = body.lenses ?? [];
+ orders = body.orders ?? [];
+ } catch {
+ // A missing registry degrades the controls, never the drawing: the default
+ // lens still reads the whole case.
+ lenses = [];
+ }
+ }
+
+ /** Which read answers the question currently being asked, and with what. */
+ function request() {
+ if (root) return ['/graph/neighborhood', { root, lens, hops: String(hops) }];
+ // A question handed over by the Board, already spelled the way this route asks
+ // for it (`lib/entityFilter.js`). Applied as **terms** rather than as the ids it
+ // matched: the drawing then answers the same question the table did, at any size,
+ // and goes on answering it as the case changes underneath.
+ const params = {
+ lens,
+ order,
+ ...searchTerms,
+ ...(catalogViews.snapshotId ? {} : temporalTerms),
+ };
+ if (catalogViews.snapshotId) params.view = catalogViews.snapshotId;
+ // The types the switched-on families resolve to, as the catalog's own
+ // comma-separated list. Empty when every family is on, which is no narrowing.
+ // Intersected with a handed-over type set rather than replacing it: both are
+ // narrowings, and a legend switch that widened the question it was applied to
+ // would be a control doing the opposite of what it says.
+ if (familyTypes) {
+ const legend = familyTypes.split(',');
+ const asked = params.type ? params.type.split(',') : null;
+ const both = asked ? legend.filter((type) => asked.includes(type)) : legend;
+ // An empty allow-list is not "no narrowing". The two questions genuinely have
+ // nothing in common, and an empty `type` reads server-side as asking for
+ // everything — so the drawing would answer a contradiction with the whole case.
+ params.type = both.length ? both.join(',') : NOTHING;
+ }
+ // Exactly this folder, as the Board reads it. Including descendants made a
+ // folder holding one entity draw three, which is a filter nobody can trust.
+ if (pickFolder && !params.folder) params.folder = pickFolder;
+ // Sent as one parameter each rather than repeated, matching the catalog's own
+ // comma-separated type list. Three lists, because the drawing is a set: draw
+ // these, draw these and one hop, leave these out.
+ if (kept.length) params.keep = kept.join(',');
+ if (expanded.length) params.expand = expanded.join(',');
+ if (omitted.length) params.omit = omitted.join(',');
+ return ['/graph', params];
+ }
+
+ let loadRun = 0;
+
+ async function load() {
+ const run = ++loadRun;
+ const cid = caseState.current?.id;
+ if (!cid) {
+ payload = null;
+ loading = false;
+ return;
+ }
+ // A drag that has not been filed yet must reach the case before the case is
+ // read back, or the answer overwrites it with the position it replaced.
+ await flushPins();
+ if (run !== loadRun || caseState.current?.id !== cid) return;
+ loading = true;
+ failed = '';
+ // What is being asked, minus what was opened: two reads that differ only by an
+ // expansion are the same question, and the view stays where the analyst left it.
+ const asked = [
+ cid, lens, order, root ?? '', hops, pickFolder, hiddenFamilies.join(','),
+ // A question the Board handed over is the question: arriving with one, and
+ // letting it go, both refit the view rather than growing what was on screen.
+ JSON.stringify(searchTerms), JSON.stringify(temporalTerms), catalogViews.snapshotId ?? '',
+ ].join('|');
+ try {
+ const [path, params] = request();
+ const next = await api.get(`/api/cases/${cid}${path}?${new URLSearchParams(params)}`);
+ // Reads are allowed to overlap: a filter, a mutation or a case switch can ask
+ // a newer question before this one answers. Only the latest read may own the
+ // canvas, even when an older response arrives last.
+ if (run !== loadRun || caseState.current?.id !== cid) return;
+ payload = next;
+ // Only what the case confirmed it drew and opened, so a node deleted elsewhere
+ // stops being offered as something to fold back or hand over. A removal needs no
+ // such answer: taking a node out of a picture always succeeds.
+ if (Array.isArray(payload.kept)) kept = payload.kept;
+ if (Array.isArray(payload.expanded)) expanded = payload.expanded;
+ if (selected && !payload.nodes.some((node) => node.id === selected)) selected = null;
+ if (chosenLink && !payload.links.some((link) => link.id === chosenLink)) chosenLink = null;
+ if (ownsViewArrangement()) {
+ // The payload still carries case-wide pins because the graph route serves
+ // every reading. A named view keeps its own map instead of adopting them.
+ pinnedIds = [...pins.keys()];
+ pinCount = pinnedIds.length;
+ } else {
+ // Outside a named graph, the case is the source of truth for arrangement.
+ pins.clear();
+ pinnedIds = payload.nodes.filter((node) => node.pin).map((node) => node.id);
+ pinCount = payload.pinned ?? 0;
+ }
+ // A handful gathered in one reading means nothing in the next one, and half of
+ // it may not even be drawn there.
+ held = [];
+ // A new *question* refits the view **and re-places it**; growing the picture
+ // does neither. Opening a node and watching the whole case slide to a new
+ // position is the fastest way to lose your place, and losing your place is
+ // exactly what growing in place was built to stop. Cleared here rather than in
+ // an effect, because the placement is derived from the payload just assigned
+ // and reads this map the first time anything asks for it.
+ const fresh = asked !== askedFor;
+ if (fresh) settled.clear();
+ resetView = fresh;
+ askedFor = asked;
+ settleArrival();
+ settleRoute();
+ // The stack starts at the picture the case opened on, not at the empty state
+ // before the first read: anchored there, one undo too many would ask the case
+ // to drop every pin it had never sent.
+ if (anchored !== cid) {
+ anchored = cid;
+ history.reset(snapshotNow());
+ mark();
+ }
+ } catch (err) {
+ if (run !== loadRun || caseState.current?.id !== cid) return;
+ failed = err.message || 'The graph could not be read.';
+ payload = null;
+ } finally {
+ if (run === loadRun && caseState.current?.id === cid) loading = false;
+ }
+ }
+
+ /**
+ * Pick out the node that was asked for, once the read that brings it has landed.
+ *
+ * Selected and centred, because being told "it is here now" without being shown
+ * where is the same as not having found it — on a case of a few hundred nodes an
+ * arrival that lands off screen is indistinguishable from nothing happening.
+ *
+ * Centred on the next frame, not now: the placement is derived from the payload
+ * that has only just been set, and the scene is rebuilt by an effect that has not
+ * run yet. Selecting is safe here; moving the view is not.
+ */
+ function settleArrival() {
+ const id = bringing;
+ if (!id) return;
+ bringing = null;
+ if (!payload?.nodes.some((node) => node.id === id)) {
+ // The budget ended the walk before it reached. Said rather than left silent:
+ // the analyst asked for one named thing and the picture did not change.
+ say('That one did not fit in the view. Narrow the case and try again.');
+ return;
+ }
+ selected = id;
+ requestAnimationFrame(() => jumpTo(id));
+ }
+
+ /**
+ * Expand a node: its neighbours join the picture, and the picture stays.
+ *
+ * The gesture the whole tool turns on. Replacing the view with a neighbourhood
+ * answered the question and lost the case it was asked about, so following a
+ * thread meant navigating back and forth to keep your place. Here nothing is
+ * taken away, and the arrivals say they arrived.
+ */
+ function expandNode(id) {
+ // A folded node is expanded by giving back what it is holding, which costs no
+ // read and is what the switch on it offers first.
+ if (collapsed.includes(id)) {
+ unfoldNode(id);
+ return;
+ }
+ // Then what hiding took off it, before anything is asked of the case: those are
+ // connections this node really has and the picture really lacks, so they are what
+ // the count on it is offering. A node hidden by hand is undone from the node it
+ // was hanging on, rather than costing the whole drawing or a name typed into Find.
+ if (bringBackAt(id)) return;
+ // Asked once and answered whole: an expansion brings every neighbour the picture
+ // lacks, so a second press on the same node has nothing left to ask for.
+ if (expanded.includes(id)) return;
+ expanded = [...expanded, id];
+ }
+
+ /**
+ * Fold a node: what only hung off it leaves the picture, and it stays.
+ *
+ * The act the drawing was missing, and the only one that reaches the nodes the case
+ * **opened on**. Expanding adds and hiding removes; neither speaks for the two
+ * hundred nodes that were on screen before the analyst touched anything, and those
+ * are the ones in the way.
+ *
+ * Nothing is asked of the case and nothing is given up: the nodes are still in the
+ * payload, so unfolding is instant. What it does not do is make room — the case
+ * still sent them. Hiding is the act that frees the budget.
+ */
+ function foldNode(id) {
+ if (collapsed.includes(id)) return;
+ // Never offered where it would do nothing: a node holding nothing up has nothing
+ // to fold, and a switch that answers a press with an unchanged picture is the
+ // failure every count in this tool exists to prevent.
+ if (!foldableCount(id, nodes, links, new Set(pinnedIds))) return;
+ collapsed = [...collapsed, id];
+ menu = null;
+ }
+
+ /** The nodes hidden off this one, each named once however many edges it took. */
+ function putAwayAt(id) {
+ return [...new Set(putAway[id] ?? [])];
+ }
+
+ /**
+ * Give back what hiding took off one node. True when there was something to give.
+ *
+ * Whole rather than one node at a time, like the fold: what left together was one
+ * act, and half of an act undone is not one.
+ */
+ function bringBackAt(id) {
+ const back = putAwayAt(id);
+ if (!back.length) return false;
+ omitted = omitted.filter((entry) => !back.includes(entry));
+ forgetHidden(back);
+ return true;
+ }
+
+ /** Stop holding a way back to nodes that are drawn again, whatever brought them. */
+ function forgetHidden(ids) {
+ const back = new Set(ids);
+ const left = {};
+ for (const [near, gone] of Object.entries(putAway)) {
+ const rest = gone.filter((id) => !back.has(id));
+ if (rest.length) left[near] = rest;
+ }
+ putAway = left;
+ }
+
+ /** Give one node's surroundings back. */
+ function unfoldNode(id) {
+ collapsed = collapsed.filter((entry) => entry !== id);
+ }
+
+ /**
+ * The one switch, in the one place it can be pressed: on the node.
+ *
+ * Grow first, and that ordering is the whole of what makes it learnable. A node
+ * holding folded nodes gives them back; a node with neighbours the drawing does not
+ * have goes and gets them; a node with everything already around it puts that away.
+ * The badge states which of the three the press will do before it is pressed, so
+ * there is never a click whose outcome has to be remembered.
+ */
+ function toggleAround(id) {
+ if (collapsed.includes(id)) unfoldNode(id);
+ else if (!root && offScreen(id) > 0) expandNode(id);
+ else foldNode(id);
+ }
+
+ /**
+ * Draw these nodes and nothing around them.
+ *
+ * The act a route and a named entity want: an answer of four nodes stays four
+ * nodes. Opening them instead brought one neighbourhood per node, and on a
+ * well-connected case the sentence was drawn inside a crowd.
+ */
+ function holdOn(ids) {
+ const named = ids.filter(Boolean);
+ if (!named.length) return;
+ kept = [...new Set([...kept, ...named])];
+ backIn(named);
+ }
+
+ // -- filing from the drawing ------------------------------------------------
+ //
+ // The hole this closes: the graph could state a relation between two nodes it was
+ // already drawing, and could not put a third thing into the case. An analyst
+ // reading a picture and realising it is missing an account had to leave for the
+ // Board, create it, come back, search for it and bring it in — five screens for a
+ // sentence they were in the middle of.
+
+ /**
+ * Draw what was just filed, where the gesture aimed, and offer the way back.
+ *
+ * Three acts on the drawing and one on the case, and the split is the point: `keep`
+ * and the pin are presentation, so `Ctrl+Z` reaches them like every other edit here.
+ * **The creation itself is not on that stack.** A single stack mixing *I hid a node*
+ * with *I filed an entity* would write to the case on the fourth press to get a view
+ * back, which is exactly the boundary this tool's undo is built on — so the way back
+ * out of the writing is the toast, with the standard recoverable delete behind it.
+ */
+ function drewIn(entity, at, caseId = caseState.current?.id) {
+ if (!caseId || caseState.current?.id !== caseId) return;
+ if (at && canArrange) {
+ // Pinned before the read rather than after it: the placement runs on the
+ // payload that read brings back, and a node pinned afterwards would be put
+ // somewhere by the layout first and moved a frame later.
+ pins.set(entity.id, { x: at.x, y: at.y });
+ dropNode(entity.id);
+ }
+ // The same arrival the search already uses: the reading effect sees `kept` change
+ // and reads the case once, then `settleArrival` selects the node and brings it
+ // under the eye. Reading here as well would be two requests for one act.
+ bringing = entity.id;
+ holdOn([entity.id]);
+ toast(`${entity.label} filed`, 'ok', 6000, {
+ label: 'Undo',
+ onClick: () => dropEntity(entity, caseId),
+ });
+ }
+
+ /** Take back a creation. The standard delete, so it lands in the case trash with the
+ * same recovery as every other one: a mis-typed entity is not a reason to make it
+ * unrecoverable. */
+ async function dropEntity(entity, caseId = caseState.current?.id) {
+ const cid = caseId;
+ if (!cid) return;
+ try {
+ await api.del(`/api/cases/${cid}/entities/${entity.id}`);
+ if (caseState.current?.id !== cid) return;
+ kept = kept.filter((id) => id !== entity.id);
+ if (selected === entity.id) selected = null;
+ await load();
+ } catch (err) {
+ say(err.message || 'That one could not be taken back.');
+ }
+ }
+
+ /**
+ * Take files dropped on the canvas into the case, at the spot they were dropped.
+ *
+ * The Media Library's own import, offered where the case is being **read**: the
+ * fastest thing an analyst does with a screenshot is drop it beside the thing it is
+ * about, and the drawing was the one surface that could not take one.
+ */
+ let dropOver = $state(false);
+ let importing = $state(false);
+
+ async function importDropped(fileList, at) {
+ const files = [...(fileList ?? [])];
+ const cid = caseState.current?.id;
+ if (snapshotReading) {
+ say('This snapshot is read-only. Leave it to add files.');
+ return;
+ }
+ if (!files.length || !cid || importing) return;
+ importing = true;
+ let last = null;
+ let duplicates = 0;
+ try {
+ for (const file of files) {
+ const form = new FormData();
+ form.append('file', file);
+ try {
+ const result = await api.post(`/api/cases/${cid}/media/upload`, form);
+ if (result.duplicate) duplicates += 1;
+ last = result.entity ?? last;
+ } catch (err) {
+ say(`${file.name}: ${err.message}`);
+ }
+ }
+ // The same bytes twice is not an error and not a second item: the case keeps the
+ // one it has, and saying so is what stops the analyst importing again.
+ if (duplicates) {
+ say(`${duplicates} duplicate${duplicates > 1 ? 's' : ''} skipped (same SHA-256)`);
+ }
+ // One file lands where it was dropped; a batch has no such spot, so it joins the
+ // drawing and the layout places it.
+ if (last) drewIn(last, files.length === 1 ? at : null, cid);
+ } finally {
+ importing = false;
+ }
+ }
+
+ // ── paste ────────────────────────────────────────────────────────────────────
+ /**
+ * Ctrl+V draws what the clipboard holds, in the middle of what is being looked at.
+ *
+ * The drawing is where a case is thought about, so a screenshot or a link arriving
+ * mid-thought should land here rather than send the analyst to another tab and
+ * back. The centre of the viewport is the honest spot: a paste has no pointer
+ * position the way a drop does.
+ */
+ let pasted = $state(null);
+ let pasteBusy = $state(false);
+ $effect(() => {
+ if (uiState.tool !== 'graph') return;
+ return listenForPaste((payload) => {
+ if (snapshotReading) {
+ say('This snapshot is read-only. Leave it to paste.');
+ return;
+ }
+ pasted ??= resolvePaste('graph', payload);
+ });
+ });
+
+ async function confirmPaste(resolved) {
+ const cid = caseState.current?.id;
+ if (pasteBusy || !cid) return;
+ pasteBusy = true;
+ const { kind, values, payload } = resolved;
+ const at = width && height ? toCanvas({ x: width / 2, y: height / 2 }) : null;
+ try {
+ if (kind === 'image') {
+ const result = await pasteImage(cid, {
+ file: payload.file,
+ title: values.title,
+ sourceUrl: values.source,
+ });
+ pasted = null;
+ // The same bytes twice is not an error and not a second node: the case keeps
+ // the one it has, and saying so is what stops the analyst pasting again.
+ if (result.duplicate) say('Already in the case (same SHA-256)');
+ drewIn(result.entity, at, cid);
+ } else {
+ const entity = await createBookmark(cid, { ...values, url: payload.url });
+ pasted = null;
+ drewIn(entity, at, cid);
+ }
+ } catch (err) {
+ say(err.message);
+ } finally {
+ pasteBusy = false;
+ }
+ }
+
+ /**
+ * Undo a removal, because a node named again outranks the edit that took it out.
+ *
+ * Left standing, an earlier removal would silently refuse the thing just asked for:
+ * a route through it would come back short, and a source handed over from an edge
+ * would answer with the edge it was pressed on.
+ */
+ function backIn(ids) {
+ const named = new Set(ids);
+ if (omitted.some((id) => named.has(id))) {
+ omitted = omitted.filter((id) => !named.has(id));
+ // Drawn again, so no node is still holding a way back to it: a neighbour
+ // offering to bring in what is already on screen is the empty act again.
+ forgetHidden(ids);
+ }
+ showAgain(ids);
+ }
+
+ /**
+ * Unfold whatever is keeping these nodes off the screen.
+ *
+ * A node asked for by name outranks a fold, exactly as it outranks a removal. Left
+ * standing, a fold would answer a search, a route or a followed connection with the
+ * picture it was already showing — and the analyst would be looking for a node the
+ * drawing had quietly decided not to draw.
+ *
+ * The fold that hides a node is undone whole rather than for that one node: a fold
+ * is a reading of one node's surroundings, and half a fold is not one.
+ */
+ function showAgain(ids) {
+ const wanted = new Set(ids.filter(Boolean));
+ if (!wanted.size || !collapsed.length) return;
+ const anchors = new Set(pinnedIds);
+ const still = collapsed.filter((id) => {
+ const { hidden } = foldAway([id], sentNodes, sentLinks, anchors);
+ for (const gone of hidden) if (wanted.has(gone)) return false;
+ return true;
+ });
+ if (still.length !== collapsed.length) collapsed = still;
+ }
+
+ /**
+ * Take nodes out of the drawing, whatever put them there.
+ *
+ * **Any node, not only one you opened**, which is the whole point: a drawing that
+ * grows without re-placing itself grows indefinitely, and the only way back used to
+ * be folding every expansion — trading the reading away to tidy the picture.
+ *
+ * Nothing is deleted. The case still holds the entity and every one of its
+ * connections; this says only that this picture is not about it.
+ */
+ function takeOut(ids) {
+ const going = new Set(ids.filter(Boolean));
+ if (!going.size) return;
+ // Which nodes are left holding an edge to what is leaving, counted before the read
+ // that drops both. This is what lets the neighbour offer it back.
+ const record = { ...putAway };
+ for (const link of links) {
+ for (const [near, far] of [[link.from, link.to], [link.to, link.from]]) {
+ if (going.has(far) && !going.has(near)) record[near] = [...(record[near] ?? []), far];
+ }
+ }
+ putAway = record;
+ // Added here and taken from nowhere else, and that is deliberate: the case applies
+ // this list last, so it wins over the name that drew the node and over the hop that
+ // reached it. Pruning those lists instead would make **Bring back** a half-undo —
+ // a node that was only in the picture because it was named would not return.
+ omitted = [...new Set([...omitted, ...going])];
+ held = held.filter((id) => !going.has(id));
+ // The panel and the walk are let go of here rather than after the read: a node on
+ // its way out of the picture must not be left being read, and half a path is not
+ // worth keeping — the same bargain Escape already makes with a walk.
+ if (going.has(selected)) selected = null;
+ if (path.some((step) => going.has(step.id))) traceStop();
+ menu = null;
+ }
+
+ /**
+ * Put the drawing back the way the case opened it.
+ *
+ * One way back rather than one per list. Growing, naming, hiding and folding are
+ * four ways of editing one picture, and four separate undos meant reading four
+ * counts in the toolbar to work out which of them was in the way. The arrangement
+ * is deliberately left alone: **Reset pins** undoes work done by hand, and this
+ * undoes a reading.
+ *
+ * Still worth its button beside the step-by-step undo: this is *back to the
+ * beginning* in one press, where undo is *not that last one*. On a picture edited
+ * thirty times they are not the same act.
+ */
+ function resetDrawing() {
+ expanded = [];
+ kept = [];
+ omitted = [];
+ collapsed = [];
+ putAway = {};
+ }
+
+ /** Give every fold back at once. Costs no read, since nothing ever left. */
+ function unfoldAll() {
+ collapsed = [];
+ }
+
+ // -- the way back, one act at a time ---------------------------------------
+ //
+ // The drawing is **derived** from the lists above, which is what makes an undo
+ // cheap here: there is no inverse to write per act, and therefore no inverse that
+ // can be wrong. Remember the lists, put them back. An act added later is undone by
+ // the same code without being told about it, because the history follows the
+ // *state* rather than the acts — recorded by an effect over everything the picture
+ // is made of, and deduplicated by the snapshot string, so a read that hands back
+ // the same lists records nothing.
+ //
+ // **It stops at the drawing and the arrangement.** Both are presentation: a fold,
+ // a hiding, a lens, a dragged node. Writing to the case is deliberately outside —
+ // a single stack mixing "I hid a node" with "I deleted a statement" means four
+ // presses to get a view back quietly rewrite the case, and an edge cannot be
+ // un-deleted anyway: re-filing one mints a new id, a new date and a new author, so
+ // the undo would forge the provenance it claims to restore. A relation filed by a
+ // mis-drop is offered back where it is announced instead.
+
+ const history = createHistory();
+ let canUndo = $state(false);
+ let canRedo = $state(false);
+ /** The case whose first read anchored the stack, so nothing before it is undone. */
+ let anchored = null;
+ /**
+ * True while a snapshot is being put back, and it is not belt and braces.
+ *
+ * Restoring an arrangement waits on the case, and an effect that ran between the
+ * pins landing and the lists being assigned would record a picture that was never
+ * asked for — one entry off the state being restored, which forks the timeline and
+ * takes the redo with it. Only an undone *drag* reaches that seam; every other act
+ * files nothing and returns at once.
+ */
+ let restoring = $state(false);
+ /**
+ * Bumped by a restore, and read by the question the view asks.
+ *
+ * An undo that only puts an arrangement back changes nothing the reading is keyed
+ * on, so without this the pins would be filed and the picture would sit there
+ * showing the drag that was just undone. One counter, one read, through the single
+ * path everything else already takes.
+ */
+ let rereads = $state(0);
+
+ function replaceViewArrangement(wanted, owner = arrangementOwner) {
+ pins.clear();
+ settled.clear();
+ for (const spot of wanted ?? []) {
+ if (
+ typeof spot?.id !== 'string' ||
+ !Number.isFinite(spot.x) ||
+ !Number.isFinite(spot.y)
+ ) continue;
+ pins.set(spot.id, { x: spot.x, y: spot.y });
+ }
+ arrangementOwner = owner;
+ pinnedIds = [...pins.keys()];
+ pinCount = pinnedIds.length;
+ arrangementRevision += 1;
+ arrangementSaveRevision += 1;
+ }
+
+ function releaseViewArrangement() {
+ if (!arrangementOwner) return;
+ arrangementOwner = null;
+ pins.clear();
+ settled.clear();
+ pinnedIds = [];
+ pinCount = 0;
+ arrangementRevision += 1;
+ }
+
+ /** Where every pin in the active arrangement stands. A named view retains local
+ * off-screen pins; the case-wide undo remains limited to nodes currently drawn. */
+ function arrangementNow() {
+ const at = new Map();
+ if (!ownsViewArrangement()) {
+ for (const node of payload?.nodes ?? []) {
+ if (node.pin) at.set(node.id, { x: node.pin[0], y: node.pin[1] });
+ }
+ }
+ for (const [id, spot] of pins) at.set(id, { x: spot.x, y: spot.y });
+ const held = new Set(pinnedIds);
+ return [...at.entries()]
+ .filter(([id]) => held.has(id))
+ .map(([id, spot]) => ({ id, x: spot.x, y: spot.y }));
+ }
+
+ function snapshotNow() {
+ return drawingSnapshot({
+ lens,
+ order,
+ root,
+ hops,
+ folder: pickFolder,
+ families: hiddenFamilies,
+ kept,
+ expanded,
+ omitted,
+ collapsed,
+ putAway,
+ arrangement: arrangementNow(),
+ });
+ }
+
+ function mark() {
+ canUndo = history.canUndo;
+ canRedo = history.canRedo;
+ }
+
+ /**
+ * Record where the picture stands now, unless it stands where it already did.
+ *
+ * **The snapshot is taken before the guard, and that is load bearing**: the effect
+ * that calls this tracks whatever it reads, so a run that returned early would
+ * subscribe to nothing but the case id — and the recorder would go deaf the moment
+ * it was anchored, which is the moment it starts mattering.
+ */
+ function record() {
+ const now = snapshotNow();
+ if (restoring || !anchored || anchored !== caseState.current?.id) return;
+ history.push(now);
+ mark();
+ }
+
+ /**
+ * Put one snapshot back.
+ *
+ * The arrangement first and the lists second, in that order and on purpose: the
+ * lists are what the reading is keyed on, so assigning them before the pins were
+ * filed would read the case back with the arrangement still undone. The counter
+ * goes last, so the whole restore is one question and one read.
+ *
+ * **The arrangement is only touched inside the reading it was taken in.** Pins are
+ * per lens and survive a switch, so an undo that crosses one finds that lens's
+ * arrangement already where it was left; diffing against the lens on screen would
+ * take one reading's pins off with the other reading's list.
+ */
+ async function restore(text) {
+ let was;
+ try {
+ was = JSON.parse(text);
+ } catch {
+ return;
+ }
+ restoring = true;
+ try {
+ if (ownsViewArrangement() || was.lens === lens) {
+ await putArrangement(lens, was.arrangement ?? []);
+ }
+ lens = was.lens;
+ order = was.order;
+ root = was.root;
+ hops = was.hops;
+ pickFolder = was.folder;
+ hiddenFamilies = was.families;
+ kept = was.kept;
+ expanded = was.expanded;
+ omitted = was.omitted;
+ collapsed = was.collapsed;
+ putAway = was.putAway;
+ // A menu opened on a node the restore may take away would act on nothing.
+ menu = null;
+ rereads += 1;
+ } finally {
+ // Let the effects settle before the recorder is listening again, or the run
+ // that answers this restore is the one that undoes the undo.
+ await tick();
+ restoring = false;
+ }
+ }
+
+ /** File the pins one snapshot asks for, and let go of the ones it does not. */
+ async function putArrangement(reading, wanted) {
+ if (ownsViewArrangement()) {
+ replaceViewArrangement(wanted);
+ return;
+ }
+ const { place, drop } = arrangementDiff(arrangementNow(), wanted);
+ if (!place.length && !drop.length) return;
+ const cid = caseState.current?.id;
+ if (!cid) return;
+ // A drag still in hand reaches the case first, or it lands on top of the undo.
+ await flushPins();
+ if (caseState.current?.id !== cid) return;
+ try {
+ if (place.length) {
+ await api.put(`/api/cases/${cid}/graph/pins`, { lens: reading, pins: place });
+ }
+ for (const id of drop) {
+ await api.del(`/api/cases/${cid}/graph/pins/${id}?lens=${reading}`);
+ }
+ for (const id of drop) {
+ // The layout owns the node again, and where it came to rest is forgotten with
+ // the pin — kept, it would stay the one fixed point nothing can place.
+ pins.delete(id);
+ settled.delete(id);
+ }
+ } catch (err) {
+ say(err.message || 'The arrangement could not be put back.');
+ }
+ }
+
+ function undo() {
+ const back = history.undo();
+ mark();
+ if (back !== null) restore(back);
+ }
+
+ function redo() {
+ const forward = history.redo();
+ mark();
+ if (forward !== null) restore(forward);
+ }
+
+ /**
+ * Centre a neighbourhood on one node: the other reading, now asked for.
+ *
+ * **Not the same act as `expandNode`**, and the two are worded apart because they
+ * were once both called expanding. This one *replaces* the case with one node and
+ * its distance rings; that one *adds* a node's missing neighbours to the case
+ * already drawn. Two near-synonyms for opposite acts, one in the panel and one in
+ * the menu, is a trap the words have to close.
+ */
+ function focusOn(id) {
+ if (snapshotReading) {
+ selected = id;
+ bringUnderEye(id);
+ return;
+ }
+ root = id;
+ selected = id;
+ hops = 1;
+ }
+
+ function wholeCase() {
+ root = null;
+ hops = 1;
+ }
+
+
+
+ /**
+ * What the case holds, in one read: its folders, and every type present in it.
+ *
+ * The types are what the family switches resolve against. Read from the case
+ * rather than from the registry so a free-typed entity — one no family speaks for
+ * — is never dropped by a switch that does not claim to cover it.
+ */
+ let holdingsRun = 0;
+
+ async function loadHoldings(caseId = caseState.current?.id) {
+ const run = ++holdingsRun;
+ const cid = caseId;
+ if (!cid) return;
+ try {
+ const body = await api.get(`/api/cases/${cid}/catalog/summary`);
+ if (run !== holdingsRun || caseState.current?.id !== cid) return;
+ summary = body;
+ folders = Object.keys(body.by_folder ?? {}).sort();
+ caseTypes = Object.keys(body.by_type ?? {});
+ } catch {
+ if (run !== holdingsRun || caseState.current?.id !== cid) return;
+ summary = null;
+ folders = [];
+ caseTypes = [];
+ }
+ }
+
+ // -- arranging by hand -----------------------------------------------------
+ //
+ // Dragging is only offered on the whole case. A neighbourhood gives its
+ // horizontal axis to distance from the root, so a node moved off its column
+ // would contradict the one thing that arrangement is drawn to show.
+
+ const canArrange = $derived(!root && !snapshotReading);
+
+ /**
+ * The nodes ctrl-clicked into one handful, so a drag moves all of them together.
+ *
+ * A separate act from selection, and deliberately: selection is what the panel
+ * reads and what the fade is computed from, and turning it into a set would make
+ * "one hop from the selected node" a question with no single answer. This says
+ * only "these move together", which is the whole of what it is for.
+ */
+ let held = $state([]);
+ /** Where each held node stood when the current drag began, for one shared delta. */
+ let grip = null;
+
+ function toggleHeld(id) {
+ held = held.includes(id) ? held.filter((entry) => entry !== id) : [...held, id];
+ }
+
+ /**
+ * Expand the whole handful in one read, rather than one node per read.
+ *
+ * Growth over a list is the other half of owning the drawing: five nodes expanded
+ * one at a time is five reads and five arrivals landing in five different places,
+ * where the analyst asked one question about five nodes.
+ */
+ function expandGathered() {
+ expanded = [...new Set([...expanded, ...held])];
+ // The handful was gathered for the act. Kept, it would sit over the arrivals as a
+ // group nobody is still building.
+ held = [];
+ }
+
+ /**
+ * Move one node and remember it, without re-arranging anything else.
+ *
+ * The shapes are moved in place and the seat is rewritten, so the edges follow
+ * on the next redraw. `placed` is deliberately untouched: re-deriving it would
+ * re-run the relaxation and slide every other node out from under the hand.
+ */
+ function moveNode(id, x, y) {
+ const spot = positions.get(id);
+ if (!spot) return;
+ spot.x = x;
+ spot.y = y;
+ spot.pinned = true;
+ pins.set(id, { x, y });
+ shapes.get(id)?.circle.position({ x, y });
+ // Not while the case is being panned: the pan owns the frame budget, and the
+ // band is redrawn with everything else the moment the pointer comes up.
+ if (dragged) return;
+ frame ||= requestAnimationFrame(() => {
+ frame = 0;
+ restyle();
+ });
+ }
+
+ /** File a move, once the hand has stopped. */
+ function dropNode(id) {
+ const spot = pins.get(id);
+ if (!spot) return;
+ const cid = caseState.current?.id;
+ if (!cid) return;
+ if (!pinnedIds.includes(id)) {
+ pinnedIds = [...pinnedIds, id];
+ pinCount += 1;
+ }
+ if (ownsViewArrangement()) {
+ arrangementSaveRevision += 1;
+ record();
+ return;
+ }
+ savingCase ??= cid;
+ savingFor ??= lens;
+ pending.set(id, spot);
+ clearTimeout(saveTimer);
+ saveTimer = setTimeout(flushPins, SAVE_AFTER);
+ // Recorded here rather than by the effect above: a node already pinned moves
+ // without any reactive state changing, so the drag would go unseen. Once the hand
+ // has stopped, so a drag is one entry rather than one per frame.
+ record();
+ }
+
+ /**
+ * Send the moves nobody has filed yet.
+ *
+ * Saved as they are made rather than behind a Save button: asking for a
+ * keystroke after every drag would put friction on the one gesture this is for.
+ * A failure says so and keeps the positions in hand, so the next drag retries
+ * them rather than losing the arrangement.
+ */
+ async function flushPins() {
+ clearTimeout(saveTimer);
+ saveTimer = 0;
+ // The case and lens are captured when the drag happens. Reading the current case
+ // here sent a last move from A to B when the debounce expired during a switch.
+ const cid = savingCase;
+ if (!cid || !pending.size) return;
+ const batch = [...pending.entries()].map(([id, at]) => ({ id, x: at.x, y: at.y }));
+ // The reading the drag happened in, captured with the batch: a lens change
+ // reloads, and a pin filed under the lens that arrived after the drag would
+ // arrange a picture nobody was looking at.
+ const reading = savingFor ?? lens;
+ pending = new Map();
+ savingCase = null;
+ savingFor = null;
+ try {
+ const body = await api.put(`/api/cases/${cid}/graph/pins`, {
+ lens: reading,
+ pins: batch,
+ });
+ if (caseState.current?.id === cid && reading === lens) {
+ pinCount = body.pinned ?? pinCount;
+ }
+ } catch (err) {
+ // Keep a failed batch for the next save only while no newer case/lens owns the
+ // pending slot. Mixing two readings would be worse than asking for another drag.
+ if (!pending.size) {
+ for (const entry of batch) pending.set(entry.id, { x: entry.x, y: entry.y });
+ savingCase = cid;
+ savingFor = reading;
+ }
+ say(err.message || 'The arrangement could not be saved.');
+ }
+ }
+
+ /**
+ * Hand one node back to the layout.
+ *
+ * One node, and only that one: forgetting where it settled makes it the single
+ * thing the relaxation still owns, so it is placed against a case that stays where
+ * it is. Dropping the whole arrangement to answer a question asked about one node
+ * would take the reading down with it.
+ */
+ async function unpinNode(id) {
+ const cid = caseState.current?.id;
+ if (!cid) return;
+ pins.delete(id);
+ settled.delete(id);
+ pending.delete(id);
+ pinnedIds = pinnedIds.filter((entry) => entry !== id);
+ if (ownsViewArrangement()) {
+ pinCount = pinnedIds.length;
+ arrangementRevision += 1;
+ arrangementSaveRevision += 1;
+ return;
+ }
+ try {
+ const body = await api.del(`/api/cases/${cid}/graph/pins/${id}?lens=${lens}`);
+ if (caseState.current?.id !== cid) return;
+ pinCount = body.pinned ?? Math.max(pinCount - 1, 0);
+ } catch (err) {
+ say(err.message || 'The pin could not be removed.');
+ }
+ // The layout has to run again for the node to be placed by it, and for its
+ // neighbours to close the gap it leaves.
+ loadedFor = null;
+ load();
+ }
+
+ /**
+ * Redraw the cards after the preview toggle, since a card is built once and kept.
+ *
+ * Destroyed rather than restyled: what a card holds — an `Image` or a `Path` — is
+ * decided when it is built, and a picture and a glyph are not the same shape.
+ */
+ function forgetCards() {
+ for (const entry of shapes.values()) {
+ entry.card?.destroy();
+ entry.card = null;
+ }
+ restyle();
+ }
+
+ /** Drop this reading's arrangement. The way back out of an autosave. */
+ async function resetLayout() {
+ const cid = caseState.current?.id;
+ if (!cid) return;
+ clearTimeout(saveTimer);
+ saveTimer = 0;
+ pending = new Map();
+ savingCase = null;
+ savingFor = null;
+ pins.clear();
+ // And where everything came to rest, or "let the layout place these again" would
+ // answer with the picture it was asked to drop: a case whose every node is a
+ // fixed point has nothing left to place.
+ settled.clear();
+ pinnedIds = [];
+ if (ownsViewArrangement()) {
+ pinCount = 0;
+ arrangementRevision += 1;
+ arrangementSaveRevision += 1;
+ return;
+ }
+ try {
+ await api.del(`/api/cases/${cid}/graph/pins?lens=${lens}`);
+ if (caseState.current?.id !== cid) return;
+ pinCount = 0;
+ } catch (err) {
+ say(err.message || 'The arrangement could not be cleared.');
+ }
+ loadedFor = null;
+ load();
+ }
+
+ /**
+ * Move the selected node from the keyboard.
+ *
+ * The same act as a drag, reachable without a mouse — a canvas has no keyboard
+ * path into it at all, so without this the arrangement is mouse-only.
+ */
+ function nudge(dx, dy, far) {
+ if (!canArrange) return false;
+ // The handful if there is one, so the keyboard reaches the group move too.
+ const moving = held.length ? held : selected ? [selected] : [];
+ const step = far ? NUDGE_FAR : NUDGE;
+ let moved = false;
+ for (const id of moving) {
+ const spot = positions.get(id);
+ if (!spot) continue;
+ moveNode(id, spot.x + dx * step, spot.y + dy * step);
+ dropNode(id);
+ moved = true;
+ }
+ return moved;
+ }
+
+ /** Put every case-owned reading aside before the next case is asked anything. */
+ let openedFor = null;
+ function startCase(cid) {
+ openedFor = cid;
+
+ // In-flight answers belong to the case that asked for them. Invalidating them
+ // here makes the boundary immediate, before the next request has even started.
+ loadRun += 1;
+ lookupRun += 1;
+ routeRun += 1;
+ holdingsRun += 1;
+
+ payload = null;
+ summary = null;
+ failed = '';
+ loading = true;
+ folders = [];
+ caseTypes = [];
+ openAnalysisCase(cid);
+ searchFilter = normalizeFilter(analysisSearch.filter);
+
+ root = null;
+ hops = 1;
+ pickFolder = '';
+ fromBoard = null;
+ hiddenFamilies = [];
+ expanded = [];
+ kept = [];
+ omitted = [];
+ collapsed = [];
+ putAway = {};
+
+ selected = null;
+ focusHops = 1;
+ onlyThis = false;
+ beforeOnly = null;
+ find = '';
+ listing = true;
+ elsewhere = [];
+ bringing = null;
+ singling = false;
+ traceStop();
+ asking = null;
+ routing = null;
+ routes = [];
+ routeAt = 0;
+
+ held = [];
+ hovered = null;
+ hoveredLink = null;
+ chosenLink = null;
+ openId = null;
+ dirty = false;
+ drawing = null;
+ offer = null;
+ menu = null;
+ blank = null;
+ creating = null;
+ dropOver = false;
+
+ // A pending drag is deliberately not cleared: `flushPins` still owns its case
+ // id and files it there. Only the drawing-side copy is put away now.
+ pins.clear();
+ arrangementOwner = null;
+ arrangementRevision += 1;
+ arrangementSaveRevision += 1;
+ pinnedIds = [];
+ pinCount = 0;
+ settled.clear();
+ askedFor = null;
+ anchored = null;
+ canUndo = false;
+ canRedo = false;
+ }
+
+ let loadedFor = null;
+ /** The question the current drawing answers, so a growth is not read as a new one. */
+ let askedFor = null;
+ $effect(() => {
+ const cid = caseState.current?.id ?? '';
+ const rev = caseState.rev;
+ if (cid !== (openedFor ?? '')) startCase(cid || null);
+ const key = [
+ cid,
+ // Every case mutation bumps this shared revision. The graph is a live reading
+ // of the case, so an entity or edge filed on any other surface must reread it.
+ String(rev),
+ lens,
+ order,
+ root ?? '',
+ hops,
+ kept.join(','),
+ expanded.join(','),
+ omitted.join(','),
+ pickFolder,
+ hiddenFamilies.join(','),
+ JSON.stringify(searchTerms),
+ JSON.stringify(temporalTerms),
+ catalogViews.snapshotId ?? '',
+ // An undo that only puts an arrangement back changes nothing else the reading
+ // is keyed on, and the picture has to move all the same.
+ String(rereads),
+ ].join('|');
+ if (key === loadedFor) return;
+ loadedFor = key;
+ load();
+ });
+
+ /** Folders and present types change with the same writes as the graph payload. */
+ let holdingsFor = null;
+ $effect(() => {
+ const cid = caseState.current?.id;
+ const key = cid ? `${cid}|${caseState.rev}` : '';
+ if (key === holdingsFor) return;
+ holdingsFor = key;
+ if (!cid) {
+ summary = null;
+ folders = [];
+ caseTypes = [];
+ return;
+ }
+ loadHoldings(cid);
+ });
+
+ // Board and Graph stay mounted while only one is visible. Search+ therefore lives
+ // above either component and both mirrors follow it, including a case switch.
+ $effect(() => {
+ const cid = caseState.current?.id;
+ const shared = JSON.stringify(analysisSearch.filter);
+ if (
+ !cid || analysisSearch.caseId !== cid ||
+ shared === untrack(() => JSON.stringify(searchFilter))
+ ) return;
+ untrack(() => (searchFilter = normalizeFilter(analysisSearch.filter)));
+ });
+
+ $effect(() => {
+ const cid = caseState.current?.id;
+ const local = JSON.stringify(searchFilter);
+ const shared = untrack(() => JSON.stringify(analysisSearch.filter));
+ if (!cid || untrack(() => analysisSearch.caseId) !== cid) return;
+ if (local !== shared) {
+ setAnalysisFilter(cid, untrack(() => searchFilter));
+ }
+ });
+
+ let facetsFor = null;
+ $effect(() => {
+ const cid = caseState.current?.id;
+ caseState.rev;
+ const key = `${cid ?? ''}|${searchWantedTypes.join(',')}|${caseState.rev}`;
+ if (!cid) {
+ facets = [];
+ facetsFor = null;
+ facetState = 'unasked';
+ return;
+ }
+ if (!searchWantedTypes.length && !fieldsWanted) {
+ facets = [];
+ facetsFor = null;
+ facetState = 'unasked';
+ return;
+ }
+ if (facetsFor === key) return;
+ facetsFor = key;
+ facetState = 'loading';
+ fetchAttrFacets(cid, searchWantedTypes)
+ .then((rows) => {
+ if (caseState.current?.id !== cid) return;
+ facets = rows;
+ facetState = 'ready';
+ if (
+ searchFilter.attrKey &&
+ !rows.some((row) => row.key === searchFilter.attrKey && row.values.length)
+ ) {
+ const dropped = searchFilter.attrKey;
+ searchFilter = clearAxis(searchFilter, 'field');
+ toast(`Nothing on screen carries ${dropped}, so that term went`, 'warn');
+ }
+ })
+ .catch(() => {
+ facets = [];
+ facetState = 'ready';
+ });
+ });
+
+ $effect(() => {
+ if (!searchFilter.attrValue) return;
+ const heldValues = facets.find((row) => row.key === searchFilter.attrKey)?.values ?? [];
+ if (
+ heldValues.length &&
+ !heldValues.some((row) => row.value === searchFilter.attrValue)
+ ) {
+ searchFilter = { ...searchFilter, attrValue: '' };
+ }
+ });
+
+ /**
+ * Take the question the Board handed over, and frame what it answers.
+ *
+ * Cleared out of `uiState` as it is taken, like every other hand-off here: left
+ * standing it would re-apply itself on the next visit to this tab, and the analyst
+ * would find a narrowing they let go of two questions ago.
+ */
+ $effect(() => {
+ const asked = uiState.drawInGraph;
+ if (!asked) return;
+ uiState.drawInGraph = null;
+ untrack(() => {
+ // A question about the case is a question about the whole of it: arriving into
+ // a neighbourhood would answer it with one node's surroundings.
+ root = null;
+ selected = null;
+ fromBoard = asked;
+ searchFilter = normalizeFilter(asked.filter ?? searchFilter);
+ setAnalysisFilter(caseState.current?.id, searchFilter);
+ });
+ });
+
+ /** One entity, drawn and selected wherever the ask came from. The mirror of the
+ * board's own `openBoardEntity`: a row has to reach its node as much as a node has
+ * to reach its row. */
+ $effect(() => {
+ const id = uiState.openGraphEntity;
+ if (!id) return;
+ uiState.openGraphEntity = null;
+ untrack(() => {
+ if (snapshotReading && byId.has(id)) {
+ selected = id;
+ bringUnderEye(id);
+ } else {
+ bringIn({ id, type: byId.get(id)?.type ?? '' });
+ }
+ });
+ });
+
+ $effect(() => {
+ loadRegistry();
+ });
+
+ /**
+ * Record the picture whenever it changes, rather than at every act that changes it.
+ *
+ * Hooking the acts one by one is the version that rots: the next control added to
+ * the toolbar is undoable only if somebody remembered, and nothing fails when they
+ * did not. This reads the state instead, so an act is undoable by existing.
+ *
+ * Safe against its own restores because the snapshot is a string: `undo` moves the
+ * index onto the entry being restored, so the push that follows is equal to it and
+ * is dropped, and the redo tail survives. A drag is the one thing this cannot see —
+ * the coordinates live outside the reactive state — so `dropNode` records its own.
+ */
+ $effect(() => {
+ record();
+ });
+
+ // -- drawing ---------------------------------------------------------------
+ //
+ // Konva is imperative. The scene is rebuilt when the *structure* changes and
+ // only restyled when the selection does, so panning to a corner and clicking a
+ // node does not throw the view back to where it started.
+
+ let stage = null;
+ let layer = null;
+ let group = null;
+ let cards = null; // mini cards, built on the first zoom that shows them
+ let trays = null; // regions drawn behind everything: the park
+ let glyphs = null; // what each dot is, drawn inside it once it is big enough
+ let rings = null; // the handful's rings, over whichever shape a node is drawn as
+ let names = null; // labels and verbs, drawn over the edges they sit on
+ let pills = null; // the switch on the node: what a press would grow or fold
+ let shapes = new Map(); // id -> { circle, label, card, glyph, ring, mark, pill }
+ let lines = []; // { arrow, link, points, verb }
+ let parkBox = null; // the region the unconnected column is set apart into
+ let band = null; // the relation being drawn, from its node to the pointer
+ let resetView = true;
+ let colours = {};
+ /** Canvas takes a real font stack; `inherit` is not one, and silently fell back
+ * to the browser's default face for every label on the graph. */
+ let fontStack = 'sans-serif';
+ /** Loaded previews, by url: an `Image`, or 'failed' once it will never load. */
+ const previews = new Map();
+
+ /** Canvas has no CSS variables, so the palette is read off the document. */
+ function readColours() {
+ const style = getComputedStyle(document.documentElement);
+ const pick = (name, fallback) => style.getPropertyValue(name).trim() || fallback;
+ fontStack = pick('--font-sans', 'sans-serif');
+ colours = {
+ accent: pick('--accent', '#e8a33d'),
+ edge: pick('--text-3', '#6c6c6c'),
+ label: pick('--text-2', '#9f9f9f'),
+ strong: pick('--text-1', '#e6e6e6'),
+ surface: pick('--bg-0', '#1c1c1c'),
+ panel: pick('--bg-1', '#232323'),
+ border: pick('--border', '#333333'),
+ warn: pick('--warn', '#d9a53f'),
+ family: Object.fromEntries(
+ FAMILY_ORDER.map((family) => [family, pick(`--graph-${family}`, '#8f9aa8')]),
+ ),
+ };
+ }
+
+ const familyColour = (family) => colours.family?.[family] ?? colours.label ?? '#8f9aa8';
+
+ function applyView() {
+ if (!stage || !group) return;
+ const view = fit(placed, width, height);
+ group.position({ x: view.x, y: view.y });
+ group.scale({ x: view.scale, y: view.scale });
+ zoom = view.scale;
+ cameraRevision += 1;
+ }
+
+ function rebuild() {
+ if (!host || !width || !height) return;
+ readColours();
+ // A resize, a theme change or a reload of the same case must not throw away
+ // where the analyst had panned to. Only a new question resets the view.
+ const keep = group && !resetView
+ ? { x: group.x(), y: group.y(), scale: group.scaleX() }
+ : null;
+
+ if (!stage) {
+ stage = new Konva.Stage({ container: host, width, height });
+ // Clicking the background clears the selection, which is what a click on
+ // nothing means everywhere else in the app. Bound to the stage once, because
+ // `destroyChildren` leaves stage-level listeners in place and a rebuild would
+ // otherwise stack another copy of this one every time the case reloaded.
+ stage.on('click tap', (event) => {
+ // The right button opens the canvas menu and does nothing else. Konva reports
+ // a `click` on any button, so without this the same press that opened the menu
+ // closed it again on release — and the menu could only be read while the
+ // button was held down. `ctrlKey` is the same press on macOS.
+ if (event?.evt?.button === 2 || event?.evt?.ctrlKey) return;
+ if (dragged) return;
+ // Whatever is mid-gesture goes first, as everywhere else: a click on nothing
+ // calls off a connection rather than silently leaving it armed.
+ if (menu) menu = null;
+ else if (blank) blank = null;
+ else if (drawing) {
+ drawing = null;
+ restyle();
+ } else selected = null;
+ });
+ stage.on('contextmenu', (event) => {
+ // The browser's own menu over a canvas offers nothing but "save image".
+ event.evt?.preventDefault();
+ // A node's own handler stops this one, so reaching here means the press
+ // landed on nothing — which is the one place the drawing can be added to
+ // rather than only read.
+ if (!canArrange || snapshotReading) return;
+ const at = stage?.getPointerPosition();
+ if (!at) return;
+ blank = { x: at.x, y: at.y, at: toCanvas(at) };
+ menu = null;
+ });
+ }
+ stage.width(width);
+ stage.height(height);
+ stage.destroyChildren();
+ shapes = new Map();
+ lines = [];
+
+ layer = new Konva.Layer();
+ group = new Konva.Group();
+ trays = new Konva.Group({ listening: false });
+ // The edges listen now: an edge is a statement, and on a well-worked case it
+ // is more often the finding than either node it joins.
+ const wires = new Konva.Group();
+ const dots = new Konva.Group();
+ cards = new Konva.Group();
+ glyphs = new Konva.Group({ listening: false });
+ rings = new Konva.Group({ listening: false });
+ names = new Konva.Group({ listening: false });
+ // Listens, unlike every other annotation here: this one is a control.
+ pills = new Konva.Group();
+
+ for (const link of edges) {
+ // An arrow rather than a line: the vocabulary is directed, and a line
+ // without a head hides half of what the edge says. The points are set in
+ // `restyle`, since where an edge stops depends on whether the thing it
+ // points at is currently a dot or a card.
+ //
+ // `perfectDrawEnabled: false` is what makes the graph pannable, and it is not
+ // a micro-optimisation. A Konva shape that has a fill *and* a stroke *and* an
+ // opacity is composited through a buffer canvas the size of the whole stage —
+ // so every faded arrow allocated and cleared a full-screen canvas on every
+ // frame of a drag. Forty-five of them cost 246ms of a 247ms redraw. Without
+ // the buffer the same redraw is one millisecond, and all it gives up is the
+ // exact blend where a translucent head overlaps its own line.
+ const arrow = new Konva.Arrow({
+ tension: 0.4,
+ // A stroke one pixel wide is unhittable with a mouse. The hit region is
+ // widened rather than the line, so the picture is unchanged.
+ hitStrokeWidth: 14,
+ perfectDrawEnabled: false,
+ });
+ arrow.on('click tap', (event) => {
+ event.cancelBubble = true;
+ if (dragged) return;
+ chosenLink = chosenLink === link.id ? null : link.id;
+ selected = null;
+ });
+ arrow.on('mouseenter', () => {
+ if (panning || drawing) return;
+ hoveredLink = link.id;
+ });
+ arrow.on('mouseleave', () => {
+ if (panning) return;
+ hoveredLink = null;
+ });
+ lines.push({ arrow, link, points: [], verb: null });
+ wires.add(arrow);
+ }
+
+ for (const node of placed) {
+ const data = byId.get(node.id);
+ if (!data) continue;
+ const circle = new Konva.Circle({
+ x: node.x,
+ y: node.y,
+ radius: nodeRadius(data.degree),
+ // A node is small at a wide zoom; the hit region stays clickable.
+ hitStrokeWidth: 10,
+ perfectDrawEnabled: false,
+ });
+ answerTo(circle, data);
+ const label = new Konva.Text({
+ x: node.x - 70,
+ y: node.y + nodeRadius(data.degree) + 5,
+ width: 140,
+ align: 'center',
+ text: shortLabel(data.label),
+ fontSize: 11,
+ fontFamily: fontStack,
+ listening: false,
+ // Text over an edge is unreadable without a halo, and the graph is drawn
+ // edges-first on purpose.
+ fillAfterStrokeEnabled: true,
+ lineJoin: 'round',
+ perfectDrawEnabled: false,
+ });
+ shapes.set(data.id, { circle, label, card: null });
+ dots.add(circle);
+ names.add(label);
+ }
+
+ parkedTray();
+
+ band = new Konva.Arrow({ listening: false, visible: false, perfectDrawEnabled: false });
+ names.add(band);
+
+
+ group.add(trays);
+ group.add(wires);
+ group.add(dots);
+ group.add(glyphs);
+ group.add(cards);
+ group.add(rings);
+ group.add(names);
+ group.add(pills);
+ layer.add(group);
+ stage.add(layer);
+
+ if (keep) {
+ group.position({ x: keep.x, y: keep.y });
+ group.scale({ x: keep.scale, y: keep.scale });
+ zoom = keep.scale;
+ } else {
+ applyView();
+ resetView = false;
+ }
+ restyle();
+ }
+
+ /**
+ * Make a shape answer for a node: pick it, move it, expand it, name it.
+ *
+ * Shared, because a node is a dot at a wide zoom and a card at a close one, and
+ * both have to behave identically — a card that could not be clicked would be a
+ * picture of a graph rather than a graph, and one that could not be dragged while
+ * the dot could would be a trapdoor at a particular zoom.
+ *
+ * `moves` is the shape the drag actually moves, which for a card is the group
+ * rather than the rectangle carrying the pointer: the picture, the title and the
+ * stripe have to travel with it.
+ */
+ function answerTo(shape, data, { named = false, moves = shape } = {}) {
+ if (canArrange) grabbable(shape, moves, data);
+ shape.on('contextmenu', (event) => {
+ event.cancelBubble = true;
+ event.evt?.preventDefault();
+ if (!canArrange) return;
+ // On macOS this same press is also a ctrl-click, which gathers. The menu is
+ // not offered on top of that: one press, one act.
+ if (event.evt?.ctrlKey && event.evt?.button === 0) return;
+ openMenu(data.id, stage?.getPointerPosition());
+ });
+ shape.on('click tap', (event) => {
+ event.cancelBubble = true;
+ // The right button opens the menu and does nothing else. Konva reports it here
+ // too, and without this the press that opened the menu also toggled the
+ // selection under it.
+ if (event.evt?.button === 2) return;
+ if (dragged || arranged) return;
+ // A connection was armed from the menu, so this click names its other end.
+ if (drawing && landOn(data.id)) return;
+ // A question was armed, so this click names the node it is about. Every node
+ // is a legal answer here, unlike a connection: the case is searched, not the
+ // drawing, so nothing on screen can be ruled out before asking.
+ if (asking) {
+ wayTo(data.id);
+ return;
+ }
+ // A walk was armed, so this click is a step along it. Every node it could
+ // reach is lit, and no other node listens — an armed gesture owns the click.
+ if (tracing) {
+ stepTo(data.id);
+ return;
+ }
+ // Ctrl or Cmd gathers instead of choosing, so several nodes can be moved as
+ // one. `preventDefault` because ctrl-click is the right-button gesture on
+ // macOS and would otherwise open the browser's own menu over the canvas.
+ if (canArrange && (event.evt?.ctrlKey || event.evt?.metaKey)) {
+ event.evt?.preventDefault();
+ toggleHeld(data.id);
+ return;
+ }
+ selected = selected === data.id ? null : data.id;
+ });
+ // The same act as the switch on the node, reachable without aiming at a badge:
+ // at a wide zoom the pill is a few pixels across, and a case is read wide.
+ //
+ // Konva counts a double-click by the clock alone, so two presses of the *right*
+ // button on one node arrive here as well — and the second time a menu was opened
+ // on a node, the drawing folded under it. The right button opens the menu and
+ // does nothing else, exactly as the single click already says.
+ shape.on('dblclick dbltap', (event) => {
+ event.cancelBubble = true;
+ if (event.evt?.button === 2) return;
+ toggleAround(data.id);
+ });
+ shape.on('mouseenter', () => {
+ if (panning) return;
+ hovered = data.id;
+ // A card already carries its name, its type and its picture, so a tooltip
+ // over one would repeat the thing being pointed at. A dot carries nothing.
+ if (named) return;
+ const box = shape.getClientRect({ relativeTo: stage });
+ tip = {
+ x: box.x + box.width / 2,
+ y: box.y,
+ label: data.label,
+ type: data.type,
+ // What the bytes are, for the one type where that is the real answer.
+ kind: data.kind ?? '',
+ // And whether the case made them, which the card says and a dot cannot.
+ origin: data.origin ?? '',
+ op: data.op ?? '',
+ degree: data.degree,
+ folder: data.folder ?? '',
+ thumb: data.thumb ?? '',
+ };
+ });
+ shape.on('mouseleave', () => {
+ // Not while dragging: the shapes slide out from under a still pointer, and
+ // each of those would restyle the whole scene in the middle of a pan.
+ if (panning) return;
+ hovered = null;
+ tip = null;
+ });
+ }
+
+ /**
+ * Let a node be picked up and put somewhere.
+ *
+ * Konva does the dragging, which is why the pointer press has to be kept from
+ * reaching the container: that listener pans the canvas, and a node drag that
+ * also panned would move the node and the case in opposite directions. Konva
+ * dispatches shape events from a div inside the host, so stopping the native
+ * event there is what keeps it from bubbling out to the pan.
+ *
+ * `dragDistance` is the same slop a click already tolerates, so a hand tremor on
+ * a node still selects it rather than moving it a pixel and pinning it there.
+ */
+ function grabbable(shape, moves, data) {
+ moves.draggable(true);
+ moves.dragDistance(DRAG_SLOP);
+ shape.on('pointerdown', (event) => {
+ event.evt?.stopPropagation();
+ // The container's own press handler is what normally clears this, and the line
+ // above is what stops it from running. Without clearing it here, the flag left
+ // true by the last pan survives, and the next click on a node is swallowed by
+ // the guard that exists to ignore the click ending a pan.
+ dragged = false;
+ });
+ moves.on('dragstart', () => {
+ arranged = false;
+ tip = null;
+ // Picking up one of a handful picks up the handful. Their starting positions
+ // are copied, so every one of them moves by the drag's own delta rather than
+ // being read back mid-move from a seat this is in the middle of rewriting.
+ grip = null;
+ if (held.includes(data.id)) {
+ grip = {
+ from: { x: moves.x(), y: moves.y() },
+ at: new Map(
+ held
+ .filter((id) => positions.has(id))
+ .map((id) => [id, { x: positions.get(id).x, y: positions.get(id).y }]),
+ ),
+ };
+ }
+ });
+ moves.on('dragmove', () => {
+ arranged = true;
+ if (!grip) {
+ moveNode(data.id, moves.x(), moves.y());
+ return;
+ }
+ const dx = moves.x() - grip.from.x;
+ const dy = moves.y() - grip.from.y;
+ for (const [id, start] of grip.at) moveNode(id, start.x + dx, start.y + dy);
+ });
+ moves.on('dragend', () => {
+ if (arranged) for (const id of grip ? grip.at.keys() : [data.id]) dropNode(id);
+ grip = null;
+ // Cleared on the next frame, so the click that ends this drag still sees it
+ // and does not toggle the selection.
+ requestAnimationFrame(() => {
+ arranged = false;
+ });
+ });
+ }
+
+ // -- stating a relation ----------------------------------------------------
+ //
+ // The graph drew links it could not make. To connect two entities sitting side
+ // by side on screen an analyst had to leave, open Details and find the second one
+ // again by name — in the one surface where it was already under the eye.
+ //
+ // **Right-click a node** and the menu says what can be done with it, "Connect
+ // to…" among them. Then the next node clicked is the other end.
+ //
+ // Two drag gestures were tried first and both were wrong. A press on an invisible
+ // rim band covered most of a small node, so moving one started a link by
+ // accident. A visible handle fixed that and was still a drag: fiddly on a
+ // trackpad, and invisible until you already knew it was there. A menu is where
+ // people look for what a thing can do, it needs no aim, and it names the act in
+ // words instead of hoping a ring is understood.
+ //
+ // Between arming and landing, the pointer drags a dashed arrow and only the
+ // endpoints the vocabulary accepts stay lit — so an illegal pair cannot be drawn
+ // rather than being drawn and then refused.
+
+ /**
+ * The node menu: where it sits, and what it is about.
+ *
+ * It selects nothing. Asking what can be done with a node is not the same act as
+ * choosing it, and making it one made the whole case dim behind the menu — every
+ * node more than a hop away faded, which read as the graph flickering under a
+ * right-click.
+ */
+ function openMenu(id, at) {
+ menu = { id, x: at?.x ?? 0, y: at?.y ?? 0 };
+ offer = null;
+ tip = null;
+ }
+
+ /**
+ * Run a menu item against the node the menu is about, then close it.
+ *
+ * The id is read *before* the menu is cleared. Closing it first destroys what the
+ * markup read the node from, and an item that did that reached for the id of
+ * something that no longer existed — which is how every item here silently did
+ * nothing at all.
+ */
+ function chose(act) {
+ const id = menu?.id;
+ menu = null;
+ if (id) act(id);
+ }
+
+
+
+ /**
+ * Arm a connection out of a node, and work out what it may land on.
+ *
+ * The vocabulary is asked once, here, rather than on every pointer move: the
+ * answer cannot change while the pointer travels, and asking it per move would
+ * run the registry over every node a hundred times a second.
+ */
+ function startDrawing(id) {
+ const from = byId.get(id);
+ if (!from) return;
+ const targets = new Set();
+ for (const node of nodes) {
+ if (node.id !== id && relationOptions(from, node).length) targets.add(node.id);
+ }
+ menu = null;
+ const at = positions.get(id);
+ drawing = { from: id, targets, at: { x: at?.x ?? 0, y: at?.y ?? 0 }, to: null, over: null };
+ tip = null;
+ restyle();
+ }
+
+ /** Land the armed connection on a node, or say why it cannot land there. */
+ function landOn(id) {
+ if (!drawing) return false;
+ const { from } = drawing;
+ if (id === from) {
+ // Clicking the node it started from is how the gesture is called off from the
+ // canvas, without reaching for a key.
+ drawing = null;
+ restyle();
+ return true;
+ }
+ if (!drawing.targets.has(id)) {
+ say(`The vocabulary has no connection between those two.`);
+ return true;
+ }
+ const options = relationOptions(byId.get(from), byId.get(id));
+ const at = positions.get(id);
+ const scale = group?.scaleX() || 1;
+ drawing = null;
+ restyle();
+ offer = {
+ from,
+ to: id,
+ options,
+ x: (at?.x ?? 0) * scale + (group?.x() ?? 0),
+ y: (at?.y ?? 0) * scale + (group?.y() ?? 0),
+ };
+ return true;
+ }
+
+ /**
+ * Follow the pointer, and light the node it could land on.
+ *
+ * Redrawn once per frame like the pan is, not once per pointer event: a pointer
+ * reports faster than the screen refreshes, and a full restyle of a few hundred
+ * shapes per report is what makes a canvas feel like treacle.
+ */
+ function drawTo(event) {
+ if (!drawing || !stage || !group) return;
+ if (!host?.contains(event.target) && event.target !== host) return;
+ stage.setPointersPositions(event);
+ const spot = stage.getPointerPosition();
+ if (!spot) return;
+ const scale = group.scaleX() || 1;
+ // The *pending* transform when a pan is in flight, not the committed one. A pan
+ // stores where the group is going and only applies it on the next frame, so
+ // reading the group here put the arrow one transform behind the case sliding
+ // under it — and it caught up in a jump when the pointer came up.
+ const origin = drag?.to ?? { x: group.x(), y: group.y() };
+ const point = { x: (spot.x - origin.x) / scale, y: (spot.y - origin.y) / scale };
+ const over = nodeAt(placed, byId, point, { carded: scale >= CARD_SCALE, scale });
+ // What is hidden cannot receive a connection: the placement still knows where it
+ // stands, so without this the band snapped to a node the analyst cannot see and
+ // the menu named an entity that was nowhere on screen.
+ const landable = over && (!hiding || hiding.has(over));
+ drawing = {
+ ...drawing,
+ to: point,
+ over: landable && over !== drawing.from && drawing.targets.has(over) ? over : null,
+ };
+ // One frame does both when a pan is running, since both want the same redraw and
+ // there is one slot for it. Two callers racing for that slot was the other half
+ // of the arrow's stutter.
+ if (drag) return;
+ frame ||= requestAnimationFrame(() => {
+ frame = 0;
+ restyle();
+ });
+ }
+
+ /** File the chosen reading, then read the case back so the edge is the case's. */
+ async function stateRelation(option) {
+ if (snapshotReading) return;
+ const cid = caseState.current?.id;
+ const chosenOffer = offer;
+ offer = null;
+ if (!cid || !chosenOffer) return;
+ say('');
+ try {
+ const [from, to] =
+ option.direction === 'out'
+ ? [chosenOffer.from, chosenOffer.to]
+ : [chosenOffer.to, chosenOffer.from];
+ const filed = await api.post(`/api/cases/${cid}/links`, {
+ from_id: from,
+ to_id: to,
+ type: option.type,
+ });
+ if (caseState.current?.id !== cid) return;
+ loadedFor = null;
+ await load();
+ // The edge appearing is the confirmation, so nothing is said when it does.
+ // A lens holds one set of verbs, though, and one that does not hold this verb
+ // draws nothing new — a write with no visible result reads as a write that
+ // failed, which is the one case worth a sentence.
+ if (filed?.id && !payload?.links?.some((edge) => edge.id === filed.id)) {
+ say('Filed, and not drawn in this lens.');
+ }
+ } catch (err) {
+ say(err.message || 'That connection was refused.');
+ }
+ }
+
+ /** Rule on a proposal from the panel: the review queue, in the picture. */
+ async function ruleOn(linkId, status) {
+ if (snapshotReading) return;
+ const cid = caseState.current?.id;
+ if (!cid) return;
+ say('');
+ try {
+ await api.patch(`/api/cases/${cid}/links/${linkId}`, { status });
+ if (caseState.current?.id !== cid) return;
+ loadedFor = null;
+ await load();
+ } catch (err) {
+ say(err.message || 'That edge could not be updated.');
+ }
+ }
+
+ /**
+ * How sure of this edge, said where the edge is read.
+ *
+ * The assessment lived one panel away: reading a line here and grading it meant
+ * leaving the drawing for the node's Details and finding the row again among the
+ * grouped connections. On a worked case the finding is more often on the edge than
+ * on either node it joins, so the judgement belongs on the same click as the reading.
+ *
+ * `''` is *not assessed*, and it sends `null` rather than being left out: absence is
+ * a state to be able to return to, so a level picked by mistake is not a hole. The
+ * control is not offered on a proposal at all — reviewing a machine's claim and
+ * grading it are two gestures, and the API refuses the second before the first.
+ *
+ * The whole view is re-read afterwards, like every other write here, because the
+ * rating can change the stroke: a relation ruled out is drawn apart.
+ */
+ async function rateEdge(linkId, raw) {
+ if (snapshotReading) return;
+ const cid = caseState.current?.id;
+ if (!cid) return;
+ say('');
+ try {
+ await api.patch(`/api/cases/${cid}/links/${linkId}`, {
+ confidence: raw === '' ? null : Number(raw),
+ });
+ if (caseState.current?.id !== cid) return;
+ loadedFor = null;
+ await load();
+ } catch (err) {
+ say(err.message || 'That edge could not be rated.');
+ }
+ }
+
+ /**
+ * Say what kind of tie this edge states, or clear it.
+ *
+ * The drawing already writes it on the line — *is associated with (sister)* — and
+ * could not change it, which is the odd half of the seam this closes: the word was
+ * readable in the picture and editable only outside it.
+ *
+ * On `change` rather than on every keystroke, so "sister" is one request rather than
+ * six. A value equal to what the edge already holds files nothing: `change` fires on
+ * blur, and a click through the panel would otherwise re-read the case for nothing.
+ */
+ async function qualifyEdge(link, raw) {
+ if (snapshotReading) return;
+ const cid = caseState.current?.id;
+ const value = raw.trim();
+ if (!cid || value === (link.nature ?? '')) return;
+ say('');
+ try {
+ await api.patch(`/api/cases/${cid}/links/${link.id}`, { nature: value || null });
+ if (caseState.current?.id !== cid) return;
+ loadedFor = null;
+ await load();
+ } catch (err) {
+ say(err.message || 'That edge could not be qualified.');
+ }
+ }
+
+ /**
+ * How a collapsed edge reads: how many sources it stands for, and how many accounts
+ * published them.
+ *
+ * "3 sources · 1 account" is the whole finding — three citations are not three
+ * sources when one account published all three — and it is what makes the
+ * independence a measurement rather than a computation somebody has to do by eye.
+ * The account clause is left off when nothing published these, since a proof and a
+ * capture have no publisher and "0 accounts" would read as a gap rather than as
+ * "not that kind of source".
+ *
+ * A collapsed derivation says the act instead of the type — *derived from 2 frames*,
+ * not *2 medias* — because "there was a step here" is the whole of what the edge is
+ * for, and the step is what the analyst named it by in Inspect.
+ *
+ */
+ function standsFor(link) {
+ const { sources, accounts, via } = link.folded;
+ const what = via.length === 1 ? madeAsWord(via[0]) : 'source';
+ const many = sources === 1 ? what : `${sources} ${what}s`;
+ return accounts ? `${many} · ${accounts} account${accounts === 1 ? '' : 's'}` : many;
+ }
+
+ /**
+ * How the count on a node reads: what came out of it and was used by nothing.
+ *
+ * The same words as the collapsed step, for the same reason — *3 frames* is the act
+ * the analyst named it by, where *3 medias* spends the sentence saying nothing. The
+ * number is always written, because this one appears mid-sentence and "frame made
+ * from it" is not one.
+ */
+ function rolledReads(rolled) {
+ const { count, via } = rolled;
+ const what = via.length === 1 ? madeAsWord(via[0]) : 'derivative';
+ return `${count} ${count === 1 ? what : `${what}s`}`;
+ }
+
+ /**
+ * What one line says, and it says it whether or not the pointer is on it when the
+ * line stands for more than itself.
+ *
+ * A collapsed wrapper spells out what it replaced — *cites 3 sources · 1 account* is
+ * the finding. A merged arrow is the case's own statement plus the ones saying the
+ * same thing off the same material, so it carries a bare `+3`: writing the material
+ * into the verb would put words in the statement's mouth, and the panel is where the
+ * three are named and handed back.
+ */
+ function lineReads(link) {
+ const verb = relationVerb(link.type);
+ if (link.folded) return `${verb} ${standsFor(link)}`;
+ if (link.merged) return `${verb} (+${link.merged.sources})`;
+ // What kind of tie, where the verb alone cannot say it. Two people being
+ // "associated with" each other is the thin half of the statement; *sister* is
+ // the half worth reading, and it is on the line rather than a panel away.
+ if (link.nature) return `${verb} (${link.nature})`;
+ return verb;
+ }
+
+ /**
+ * Bring back the nodes a collapsed edge stands for.
+ *
+ * Named rather than opened, and that is the difference the split bought: a source is
+ * wanted as itself, where opening it dragged whatever else it touches in with it. A
+ * node the analyst named is never folded, so naming these draws them with their own
+ * edges again — which is what makes the collapse a reading rather than a loss.
+ */
+ function unfold(link) {
+ const back = link.folded?.open ?? link.merged?.open ?? [];
+ if (!back.length) return;
+ // The selection is left where it is: the edge keeps its id while it still stands
+ // for something, so the panel shows the count come down as the nodes arrive, and
+ // the read that follows clears it once there is nothing left to stand for.
+ holdOn(back);
+ }
+
+ /** Drop an edge. The case keeps the two entities; only the statement goes. */
+ async function dropLink(linkId) {
+ if (snapshotReading) return;
+ const cid = caseState.current?.id;
+ if (!cid) return;
+ say('');
+ try {
+ await api.del(`/api/cases/${cid}/links/${linkId}`);
+ if (caseState.current?.id !== cid) return;
+ chosenLink = null;
+ loadedFor = null;
+ await load();
+ } catch (err) {
+ say(err.message || 'That edge could not be removed.');
+ }
+ }
+
+ /**
+ * A node as a mini card: what it is a picture of, what it is called, and one
+ * line of what it is.
+ *
+ * Built on the first zoom that actually shows one, and only for the nodes on
+ * screen. A case draws a few hundred nodes; building every card up front would
+ * mean five shapes and one image request per node for cards nobody looked at.
+ */
+ function buildCard(data) {
+ const art = CARD.stripe;
+ const textLeft = art + CARD.art + CARD.pad;
+ const textWidth = CARD.w - textLeft - CARD.pad;
+ const card = new Konva.Group();
+ card.add(
+ new Konva.Rect({
+ name: 'bg',
+ width: CARD.w,
+ height: CARD.h,
+ cornerRadius: 7,
+ perfectDrawEnabled: false,
+ shadowBlur: 6,
+ shadowOpacity: 0.35,
+ shadowOffsetY: 1,
+ }),
+ );
+ card.add(
+ new Konva.Rect({
+ name: 'stripe',
+ width: CARD.stripe,
+ height: CARD.h,
+ cornerRadius: [7, 0, 0, 7],
+ listening: false,
+ }),
+ );
+ if (showPreviews && data.thumb) {
+ // A ground under the picture and a rule down its right side. A thumbnail is
+ // whatever colours its source was, and dropped straight onto the card it read
+ // as a scrap lying on top of one; given a seat and an edge it reads as a side
+ // of the card. The ground also holds the column while the picture loads, or
+ // for good if it never does.
+ card.add(
+ new Konva.Rect({
+ name: 'ground',
+ x: art,
+ width: CARD.art,
+ height: CARD.h,
+ // Rounded on the left only, and tighter than the card's own corner, which
+ // keeps the column inside the curve it sits in.
+ cornerRadius: [4, 0, 0, 4],
+ listening: false,
+ }),
+ );
+ card.add(
+ new Konva.Image({
+ name: 'art',
+ x: art,
+ width: CARD.art,
+ height: CARD.h,
+ cornerRadius: [4, 0, 0, 4],
+ listening: false,
+ }),
+ );
+ card.add(
+ new Konva.Rect({
+ name: 'rule',
+ x: art + CARD.art,
+ width: 1,
+ height: CARD.h,
+ listening: false,
+ }),
+ );
+ showPreview(card, data.thumb);
+ } else {
+ // No picture to show: the entity's own glyph, from the one icon set, so a
+ // card without a preview still says what kind of thing it is. Centred in the
+ // column the picture would have filled, which is where it already sat.
+ const glyph = CARD.glyph / 24;
+ card.add(
+ new Konva.Path({
+ name: 'glyph',
+ data: paths[entityIcon(data)] ?? paths.alert,
+ x: art + (CARD.art - CARD.glyph) / 2,
+ y: (CARD.h - CARD.glyph) / 2,
+ scaleX: glyph,
+ scaleY: glyph,
+ strokeWidth: 1.8 / glyph,
+ lineCap: 'round',
+ lineJoin: 'round',
+ listening: false,
+ }),
+ );
+ }
+ // Clipped with an ellipsis rather than wrapped: a card is one fixed shape, and
+ // a title that took two lines would push the type line off the bottom of it.
+ card.add(
+ new Konva.Text({
+ name: 'title',
+ x: textLeft,
+ y: CARD.pad + 1,
+ width: textWidth,
+ text: data.label,
+ fontSize: 12,
+ fontStyle: '600',
+ fontFamily: fontStack,
+ wrap: 'none',
+ ellipsis: true,
+ listening: false,
+ }),
+ );
+ card.add(
+ new Konva.Text({
+ name: 'meta',
+ x: textLeft,
+ y: CARD.pad + 19,
+ width: textWidth,
+ text: cardMeta(data),
+ fontSize: 10,
+ fontFamily: fontStack,
+ wrap: 'none',
+ ellipsis: true,
+ listening: false,
+ }),
+ );
+ card.offset({ x: CARD.w / 2, y: CARD.h / 2 });
+ answerTo(card.findOne('.bg'), data, { named: true, moves: card });
+ cards.add(card);
+ return card;
+ }
+
+ /** The one line under a card's title: what it is, and how connected it is. */
+ function cardMeta(data) {
+ // A media node says what it holds — a video, an image — because `media` covers
+ // all of them and "Media" answers a question nobody asked. Material the case
+ // *made* says the act instead: a video with twelve saved frames drew as thirteen
+ // images, and "Image" on the twelve was the true word for the least useful thing
+ // about them. The glyph still says it is a picture.
+ const parts = [madeHereLabel(data) ?? entityKindLabel(data, entityLabel(data.type))];
+ if (data.status === 'suggested') parts.push('proposed');
+ parts.push(`${data.degree} link${data.degree === 1 ? '' : 's'}`);
+ return parts.join(' · ');
+ }
+
+ /**
+ * Put a preview in a card, once. Thumbnails are served immutable and shared with
+ * the Media Library, so the second view of the same picture costs nothing; a
+ * thumbnail that will not load leaves the card as it is rather than a broken box.
+ */
+ function showPreview(card, thumb) {
+ const cid = caseState.current?.id;
+ if (!cid) return;
+ const url = thumb.startsWith('data:') ? thumb : fileUrl(cid, thumb);
+ const draw = (image) => {
+ const art = card.findOne('.art');
+ if (!art || !image?.naturalWidth) return;
+ art.image(image);
+ art.crop(cropToFill(image.naturalWidth, image.naturalHeight, CARD.art / CARD.h));
+ stage?.batchDraw();
+ };
+ const held = previews.get(url);
+ if (held === 'failed') return;
+ if (held) {
+ draw(held);
+ return;
+ }
+ const image = new Image();
+ image.onload = () => {
+ previews.set(url, image);
+ draw(image);
+ };
+ image.onerror = () => previews.set(url, 'failed');
+ image.src = url;
+ }
+
+ /**
+ * Draw the park as a region, with its name inside it.
+ *
+ * The park is a place, not a caption: these nodes are set apart on purpose, and
+ * that only reads if the area they are set apart *into* is drawn. Floating a line
+ * of text over the canvas above them left the words belonging to nothing and the
+ * column looking like a layout accident.
+ *
+ * One word, and not the sentence the toolbar already says: the chip up there counts
+ * them, this says which ones, and stating the same finding twice in two wordings is
+ * how a picture starts arguing with itself.
+ */
+ function parkedTray() {
+ const parked = placed.filter((node) => node.parked);
+ parkBox = null;
+ if (!parked.length) return;
+ // The column's own extent, in canvas units, widened to clear the dots and the
+ // labels under them and to leave the title a line of its own at the top.
+ const xs = parked.map((node) => node.x);
+ const ys = parked.map((node) => node.y);
+ parkBox = {
+ x: Math.min(...xs) - PARK_PAD.x,
+ y: Math.min(...ys) - PARK_PAD.top,
+ w: Math.max(...xs) - Math.min(...xs) + PARK_PAD.x * 2,
+ h: Math.max(...ys) - Math.min(...ys) + PARK_PAD.top + PARK_PAD.bottom,
+ };
+ trays.add(
+ new Konva.Rect({
+ name: 'parked-tray',
+ cornerRadius: 10,
+ listening: false,
+ perfectDrawEnabled: false,
+ }),
+ );
+ names.add(
+ new Konva.Text({
+ name: 'parked-caption',
+ text: 'Unconnected',
+ fontSize: 11,
+ fontFamily: fontStack,
+ listening: false,
+ fillAfterStrokeEnabled: true,
+ lineJoin: 'round',
+ perfectDrawEnabled: false,
+ }),
+ );
+ }
+
+ /**
+ * Selection, hover and zoom, applied without rebuilding the scene.
+ *
+ * Also where a node decides what it is drawn as. Past `CARD_SCALE` there is room
+ * on screen for a card, so the picture stops being a diagram of the case and
+ * starts being a reading of it; below that, a card would cover its neighbours and
+ * a dot is what the eye wants anyway.
+ */
+ function restyle() {
+ if (!stage || !group) return;
+ const scale = group.scaleX() || 1;
+ // Hover only lights what it is over; narrowing the picture is a question being
+ // asked of it, and one question does it at a time.
+ const lit = hovered ?? selected;
+ const near = narrowing;
+ const asCards = scale >= CARD_SCALE;
+ // What one of the card's units is worth out here. Everything hung off a card —
+ // its rim, the ring around it, the pin, the switch — is measured with it, so the
+ // card and its furniture grow as one shape.
+ const unit = cardFactor(scale);
+ const rim = { x: (CARD.w / 2) * unit, y: (CARD.h / 2) * unit };
+ const seen = onScreen(scale);
+ // Built once per redraw rather than asked per node: a few hundred nodes each
+ // scanning these lists would be the one quadratic thing in the loop.
+ const marked = new Set(pinnedIds);
+ const inHand = new Set(held);
+
+ for (const entry of lines) {
+ const { arrow, link } = entry;
+ // An edge survives the hiding only when both of its ends do. A line running off
+ // to a node that is not there points at nothing, and would read as the case
+ // continuing off screen when it does not.
+ if (hiding && !(hiding.has(link.from) && hiding.has(link.to))) {
+ arrow.visible(false);
+ styleVerb(entry, false, scale);
+ continue;
+ }
+ arrow.visible(true);
+ const style = edgeStyle(link, CHAIN_TYPES);
+ // An edge under the pointer or under the panel lights the same way a node
+ // does: the two are the same kind of thing to be reading.
+ //
+ // And when one edge is singled out that way, the node's others step back.
+ // Otherwise the answer to "which line is this row" was every line the node
+ // has, since selecting it already lit all of them and wrote all their verbs —
+ // which is exactly the question the panel's rows exist to answer.
+ const picked = link.id === chosenLink || link.id === hoveredLink;
+ const singled = Boolean(chosenLink || hoveredLink);
+ // A path outranks all of that: it is the most recently asked question, and its
+ // edges *are* the answer. Nothing else on a walked case may light.
+ const onPath = pathLinks.has(link.id);
+ const touching = tracing
+ ? onPath
+ : singled
+ ? picked
+ : Boolean(lit && (link.from === lit || link.to === lit));
+ const faded = near && !(near.has(link.from) && near.has(link.to));
+ const stands = Boolean(link.folded || link.merged);
+ const from = positions.get(link.from);
+ const to = positions.get(link.to);
+ // A response swap updates derived positions before the scene rebuild effect
+ // replaces its old Konva arrows. Hide that one-frame mismatch; leaving a
+ // snapshot for another surface used to send an old edge into `edgePoints`
+ // with no endpoint and raise after the navigation had already succeeded.
+ if (!from || !to) {
+ arrow.visible(false);
+ styleVerb(entry, false, scale);
+ continue;
+ }
+ // Where an edge stops depends on what it points at: the rim of a circle, or
+ // the side of a card. A head buried under either one points at nothing.
+ const side = asCards ? boxRadius(rim.x, rim.y, to.x - from.x, to.y - from.y) : 0;
+ entry.points = edgePoints(
+ from,
+ to,
+ asCards ? side : nodeRadius(byId.get(link.from)?.degree),
+ asCards ? side : nodeRadius(byId.get(link.to)?.degree),
+ bends.get(link.id) ?? 0,
+ );
+ arrow.points(entry.points);
+ arrow.stroke(touching ? colours.accent : colours.edge);
+ arrow.fill(touching ? colours.accent : colours.edge);
+ // A path edge is drawn as a ribbon: three times the weight, and solid whatever
+ // its verb would dash. **The distinction is in the stroke, not in the hue** —
+ // a graph that reaches a report gets printed, and a printed graph is grey, so
+ // a route told apart by colour alone is a route the page cannot show. Every
+ // free colour is taken anyway: the families own the palette and the accent is
+ // the selection.
+ // A line that replaced nodes carries their weight too, so it is not read as one
+ // statement among the others.
+ arrow.strokeWidth(
+ (onPath
+ ? style.width + 3
+ : (touching ? style.width + 0.6 : style.width) + (stands ? 0.9 : 0)) / scale,
+ );
+ arrow.dash(onPath ? [] : style.dash.map((n) => n / scale));
+ arrow.pointerLength((style.kind === 'mention' ? 6 : 8) / scale);
+ arrow.pointerWidth((style.kind === 'mention' ? 5 : 7) / scale);
+ // A faded edge is context, not decoration: what keeps your place is the shape
+ // of the rest of the case, and the shape is in the lines as much as in the
+ // dots. At 0.07 a one-pixel stroke was gone in both themes, so the nodes were
+ // carrying it alone and the far clusters read as loose points.
+ arrow.opacity(touching ? 0.95 : faded ? 0.12 : 0.45);
+ // Every verb on the path is written at once: the path is a sentence, and the
+ // sentence is on the drawing as well as under it.
+ //
+ // A line standing for more than itself is written **once the drawing is close
+ // enough to read**, which is the same threshold the nodes become cards at. Its
+ // count is the whole reason those nodes are not on screen, so leaving it to the
+ // hover lost them; writing it at every zoom put three hundred sentences over the
+ // shape of the case, which is the one thing this tool exists to show. Wide, the
+ // extra weight below carries it instead.
+ styleVerb(entry, Boolean(touching) || (stands && asCards), scale);
+ }
+
+ for (const [id, entry] of shapes) {
+ const data = byId.get(id);
+ if (!data) continue;
+ const { circle, label } = entry;
+ const isSelected = id === selected;
+ const isNear = !near || near.has(id);
+ // A node whose name was typed is outlined rather than only left at full
+ // strength: on a picture where most of the case is already dim, "not faded" is
+ // not a mark, and the eye has to be able to count the matches.
+ const matched = found.has(id);
+ const carded = asCards && seen(circle);
+ // Whether the node is on screen at all, which "Only this" is the only thing
+ // that decides. Threaded through the annotations rather than left to opacity:
+ // a glyph or a pin mark drawn over nothing is the tell that a node was removed
+ // by painting rather than by being left out.
+ const drawn = !hiding || hiding.has(id);
+ // On the path, or offered as its next step. The two are told apart because
+ // they are different claims: one is a route taken, the other is a route
+ // available, and a walk that drew them alike would be a walk you cannot read.
+ const stepped = tracing && pathIds.has(id);
+ const offered = tracing && nextSteps.has(id);
+ circle.visible(drawn && !carded);
+ circle.fill(familyColour(data.family));
+ circle.stroke(
+ stepped || offered || isSelected || id === hovered || matched
+ ? colours.accent
+ : colours.surface,
+ );
+ // The path's own nodes are ringed heaviest, an offered step half that: the
+ // weight says how settled the claim is, which the stroke can carry in grey.
+ circle.strokeWidth(
+ (stepped ? 3.6 : offered ? 2 : isSelected ? 3 : id === hovered || matched ? 2.2 : 1.5) /
+ scale,
+ );
+ // A proposal is drawn as one everywhere it appears (ONTOLOGY §4).
+ circle.dash(data.status === 'suggested' ? [3 / scale, 3 / scale] : []);
+ circle.opacity(isNear ? 1 : 0.16);
+
+ // Whatever is in hand keeps its name, and so does its neighbourhood: a
+ // selection is read as a sentence, and an unnamed neighbour cannot be read.
+ // The lit node itself gives its label up, because the words of its own edges
+ // are written where that label sits, and the panel and the tooltip both name
+ // it anyway.
+ const named =
+ isSelected || id === hovered || Boolean(near) || hubs.has(id) || scale >= LABEL_SCALE;
+ label.visible(drawn && !carded && named && isNear && id !== lit);
+ label.fill(isSelected ? colours.accent : colours.label);
+ label.stroke(colours.surface);
+ label.strokeWidth(3 / scale);
+ label.fontSize(11 / scale);
+ label.x(circle.x() - 70 / scale);
+ label.width(140 / scale);
+ label.y(circle.y() + circle.radius() + 5 / scale);
+
+ if (carded || entry.card) {
+ styleCard(entry, data, { scale, unit, carded, isSelected, isNear, matched, drawn });
+ }
+ styleGlyph(entry, data, { scale, carded, isNear, drawn });
+ stylePill(entry, data, { scale, unit, carded, isNear, drawn });
+ styleMark(entry, { scale, unit, carded, marked: drawn && isNear && marked.has(id) });
+ styleHeld(entry, { scale, unit, carded, inHand: drawn && isNear && inHand.has(id) });
+ // While a relation is being drawn, what it cannot land on steps back. The
+ // vocabulary decides that, so an illegal pair is never drawn and then refused.
+ if (drawing) {
+ const target = drawing.from === id || drawing.targets.has(id);
+ circle.opacity(target ? 1 : 0.12);
+ entry.card?.opacity(target ? 1 : 0.12);
+ }
+ }
+
+ styleBand(scale);
+
+ // The park: a drawn region with its name inside it, so the nodes set apart read
+ // as set apart rather than as a column that drifted there. The frame is in canvas
+ // units because it encloses canvas things; only its stroke and its title are held
+ // at a fixed size on screen.
+ const tray = trays?.findOne('.parked-tray');
+ const caption = names?.findOne('.parked-caption');
+ // The park holds what nothing connects to, so it has no place in a picture of
+ // what one node reaches: an empty frame captioned "Unconnected" beside a subset
+ // reads as a claim about the subset.
+ tray?.visible(!hiding);
+ caption?.visible(!hiding);
+ if (tray && parkBox) {
+ tray.position({ x: parkBox.x, y: parkBox.y });
+ tray.width(parkBox.w);
+ tray.height(parkBox.h);
+ tray.fill(colours.panel);
+ tray.stroke(colours.border);
+ tray.strokeWidth(1 / scale);
+ tray.opacity(near ? 0.25 : 0.55);
+ }
+ if (caption && parkBox) {
+ caption.fill(colours.label);
+ caption.stroke(colours.surface);
+ caption.strokeWidth(3 / scale);
+ caption.fontSize(11 / scale);
+ // Inside the frame, at its top left: a region's name belongs in the region.
+ caption.x(parkBox.x + 12 / scale);
+ caption.y(parkBox.y + 9 / scale);
+ caption.opacity(near ? 0.25 : 0.85);
+ }
+ stage.batchDraw();
+ }
+
+ /**
+ * A test for whether a node is in view, in canvas units.
+ *
+ * Cards are only built and only ask for their picture once they are actually on
+ * screen: zooming in on one corner of a 500-node case must not fire 500 image
+ * requests for cards nobody can see.
+ */
+ function onScreen(scale) {
+ const left = -group.x() / scale;
+ const top = -group.y() / scale;
+ // Two cards of slack, so a normal drag reveals cards that already exist rather
+ // than the dots underneath them: the scene is only redressed when the drag ends.
+ const margin = CARD.w * 2 * cardFactor(scale);
+ const right = left + width / scale;
+ const bottom = top + height / scale;
+ return (shape) => {
+ const x = shape.x();
+ const y = shape.y();
+ return x > left - margin && x < right + margin && y > top - margin && y < bottom + margin;
+ };
+ }
+
+ /**
+ * Put the entity's own glyph inside the dot.
+ *
+ * A family colour says which of seven groups a node belongs to; the glyph says
+ * what it *is*, which is the question the eye asks first. The card already answers
+ * it close up, and this answers it at the zoom where a case is actually read.
+ *
+ * **Only where it can be read.** A dot is eleven to twenty-four canvas units, so
+ * below `GLYPH_MIN` screen pixels the glyph is a smudge — and a wide zoom is
+ * exactly where a case draws the most nodes. Gating on the drawn size is what
+ * keeps this from adding a few hundred shapes to the one view that cannot afford
+ * them, and it costs nothing where they would not have been legible anyway.
+ */
+ function styleGlyph(entry, data, { scale, carded, isNear, drawn = true }) {
+ const across = entry.circle.radius() * scale * 2;
+ const show = drawn && !carded && across >= GLYPH_MIN;
+ if (!show && !entry.glyph) return;
+ if (!entry.glyph) {
+ entry.glyph = new Konva.Path({
+ data: paths[entityIcon(data)] ?? paths.alert,
+ listening: false,
+ perfectDrawEnabled: false,
+ lineCap: 'round',
+ lineJoin: 'round',
+ });
+ glyphs.add(entry.glyph);
+ }
+ const glyph = entry.glyph;
+ glyph.visible(show);
+ if (!show) return;
+ // Sized off the dot, not off the screen: it has to sit inside the circle at
+ // every zoom, and the circle is measured in canvas units.
+ const box = entry.circle.radius() * 1.3;
+ const unit = box / 24;
+ glyph.scale({ x: unit, y: unit });
+ glyph.strokeWidth(1.9 / unit / scale);
+ // Struck in the background colour, so it reads as cut out of the family hue
+ // rather than as a second thing drawn on top of it.
+ glyph.stroke(colours.surface);
+ glyph.position({ x: entry.circle.x() - box / 2, y: entry.circle.y() - box / 2 });
+ glyph.opacity(isNear ? 0.9 : 0.16);
+ }
+
+ /**
+ * Ring a node that is in the handful, so a group drag is not a surprise.
+ *
+ * Outside the node rather than on it, because the node's own stroke already says
+ * whether it is selected and whether it is a proposal. A ring around it is the one
+ * free place left to say "this one moves with the others".
+ */
+ function styleHeld(entry, { scale, unit, carded, inHand }) {
+ if (!inHand && !entry.ring) return;
+ if (!entry.ring) {
+ entry.ring = new Konva.Circle({
+ listening: false,
+ perfectDrawEnabled: false,
+ fillEnabled: false,
+ });
+ rings.add(entry.ring);
+ }
+ const ring = entry.ring;
+ ring.visible(inHand);
+ if (!inHand) return;
+ ring.position({ x: entry.circle.x(), y: entry.circle.y() });
+ // Clear of a card too, which is wider than it is tall: the ring has to sit
+ // outside whichever shape the node is currently drawn as.
+ const around = carded
+ ? Math.hypot(CARD.w / 2, CARD.h / 2) * unit + 4 / scale
+ : entry.circle.radius() + 6 / scale;
+ ring.radius(around);
+ ring.stroke(colours.accent);
+ // Solid, never dashed: a dashed outline means "proposed" everywhere else in this
+ // picture (ONTOLOGY §4), and a handful of nodes is not a claim about the case.
+ ring.strokeWidth(1.6 / scale);
+ ring.opacity(0.8);
+ }
+
+ /** One card, sized off the screen and centred on the node it stands for. */
+ function styleCard(
+ entry,
+ data,
+ { scale, unit, carded, isSelected, isNear, matched, drawn = true },
+ ) {
+ if (!carded || !drawn) {
+ entry.card?.visible(false);
+ return;
+ }
+ entry.card ??= buildCard(data);
+ const card = entry.card;
+ card.visible(true);
+ card.opacity(isNear ? 1 : 0.16);
+ // Sized off the screen rather than off the canvas, which is the whole reason a
+ // card can exist here: the gap between two nodes grows with the zoom faster than
+ // the card does, so the cards never close back in on each other (`cardFactor`).
+ card.scale({ x: unit, y: unit });
+ card.position({ x: entry.circle.x(), y: entry.circle.y() });
+ // A card carries the search the same way a dot does, or a name typed at a zoom
+ // close enough to read the cards would light nothing at all.
+ const lit = isSelected || matched || data.id === hovered;
+ const bg = card.findOne('.bg');
+ bg.fill(colours.panel);
+ bg.stroke(lit ? colours.accent : colours.border);
+ bg.strokeWidth(lit ? 2 : 1);
+ bg.shadowColor(colours.surface);
+ bg.dash(data.status === 'suggested' ? [3, 3] : []);
+ card.findOne('.stripe').fill(familyColour(data.family));
+ card.findOne('.glyph')?.stroke(familyColour(data.family));
+ card.findOne('.ground')?.fill(colours.surface);
+ card.findOne('.rule')?.fill(lit ? colours.accent : colours.border);
+ card.findOne('.title').fill(lit ? colours.accent : colours.strong);
+ card.findOne('.meta').fill(colours.label);
+ }
+
+ /**
+ * The switch on the node: one press, and it says what the press does.
+ *
+ * A canvas teaches no gesture on its own, so the count is the teaching. `+5` is
+ * five connections the drawing does not have; `−35` is thirty-five nodes that hang
+ * off this one and nothing else; a filled `+35` is thirty-five it is currently
+ * holding. The sign is the promise — plus grows the picture, minus shrinks it — and
+ * it is the same promise in all three states.
+ *
+ * Drawn only on the node under the eye, and permanently on a node that is holding
+ * something. A pill on every dot would be a few hundred numbers competing with the
+ * shape of the case, which is the one thing this tool exists to show.
+ */
+ function stylePill(entry, data, { scale, unit, carded, isNear, drawn }) {
+ const on = switchFor?.id === data.id ? switchFor : null;
+ const holding = collapsed.includes(data.id);
+ const act = holding ? 'unfold' : on?.act;
+ const count = holding ? (folds.by.get(data.id) ?? 0) : (on?.count ?? 0);
+ // Never over an armed gesture: while a connection, a route or a walk is waiting
+ // for its other end, every press on the case belongs to that gesture.
+ const show =
+ drawn && isNear && Boolean(act) && count > 0 && !drawing && !tracing && !asking;
+ if (!show && !entry.pill) return;
+ if (!entry.pill) {
+ const box = new Konva.Rect({ cornerRadius: 7, perfectDrawEnabled: false });
+ const text = new Konva.Text({
+ fontSize: 10,
+ fontFamily: fontStack,
+ align: 'center',
+ listening: false,
+ perfectDrawEnabled: false,
+ });
+ const pill = new Konva.Group();
+ pill.add(box, text);
+ pill.on('click tap', (event) => {
+ event.cancelBubble = true;
+ if (dragged || arranged) return;
+ toggleAround(data.id);
+ });
+ entry.pill = { pill, box, text };
+ pills.add(pill);
+ }
+ const { pill, box, text } = entry.pill;
+ pill.visible(show);
+ if (!show) return;
+ text.text(`${act === 'fold' ? '−' : '+'}${count}`);
+ const width = Math.max(text.getTextWidth() + 10, 20);
+ const height = 15;
+ box.width(width);
+ box.height(height);
+ text.width(width);
+ text.y(3);
+ // Filled while it is holding something, outlined while it is offering: a state
+ // and an offer must not read alike, or the drawing stops saying which nodes have
+ // something put away under them.
+ box.fill(holding ? colours.accent : colours.panel);
+ box.stroke(holding ? colours.accent : colours.border);
+ box.strokeWidth(1);
+ text.fill(holding ? colours.surface : colours.label);
+ // Held at a fixed size on screen like every other annotation, and hung off the
+ // node's top right — clear of the label, which sits under it.
+ pill.scale({ x: 1 / scale, y: 1 / scale });
+ const reach = carded
+ ? { x: (CARD.w / 2) * unit, y: (CARD.h / 2) * unit }
+ : { x: 0, y: 0 };
+ const radius = carded ? 0 : entry.circle.radius() * 0.7;
+ pill.position({
+ x: entry.circle.x() + radius + reach.x - (carded ? width / scale : 0),
+ y: entry.circle.y() - radius - reach.y - height / scale,
+ });
+ }
+
+ /**
+ * Mark a node the analyst placed by hand.
+ *
+ * Without it a pinned node is a mystery: it ignores the lens, it does not move
+ * when the case is re-arranged around it, and nothing on screen says why. The mark
+ * is the entity vocabulary's own pin glyph, held at a fixed size on screen like
+ * every other annotation here, and built on the first node that needs one.
+ */
+ function styleMark(entry, { scale, unit, carded, marked }) {
+ if (!marked && !entry.mark) return;
+ if (!entry.mark) {
+ entry.mark = new Konva.Path({
+ data: paths.pushpin,
+ listening: false,
+ lineCap: 'round',
+ lineJoin: 'round',
+ perfectDrawEnabled: false,
+ });
+ names.add(entry.mark);
+ }
+ const mark = entry.mark;
+ mark.visible(marked);
+ if (!marked) return;
+ // The icon set draws in a 24-unit box; this holds the glyph and its stroke at a
+ // fixed size on screen whatever the zoom, like every other annotation here.
+ const size = 15 / scale;
+ const glyph = size / 24;
+ mark.scale({ x: glyph, y: glyph });
+ mark.strokeWidth(1.7 / (glyph * scale));
+ mark.stroke(colours.accent);
+ const circle = entry.circle;
+ const half = carded
+ ? { x: (CARD.w / 2) * unit, y: (CARD.h / 2) * unit }
+ : { x: circle.radius(), y: circle.radius() };
+ mark.position({
+ x: circle.x() + half.x - (carded ? size * 1.1 : size * 0.35),
+ y: circle.y() - half.y - (carded ? -size * 0.15 : size * 0.55),
+ });
+ }
+
+
+ /**
+ * The relation being drawn, from its node to the pointer.
+ *
+ * Drawn as an arrow because what it will become is one, and dashed because it is
+ * not a statement yet. It lands on the node under the pointer rather than on the
+ * pointer itself once there is a legal target, so the gesture snaps and the drop
+ * is not a pixel hunt.
+ */
+ function styleBand(scale) {
+ if (!band) return;
+ band.visible(Boolean(drawing?.to));
+ if (!drawing?.to) return;
+ const from = positions.get(drawing.from);
+ const to = drawing.over ? positions.get(drawing.over) : drawing.to;
+ if (!from || !to) return;
+ band.points([from.x, from.y, to.x, to.y]);
+ band.stroke(drawing.over ? colours.accent : colours.label);
+ band.fill(drawing.over ? colours.accent : colours.label);
+ band.strokeWidth(1.8 / scale);
+ band.dash([7 / scale, 5 / scale]);
+ band.pointerLength(9 / scale);
+ band.pointerWidth(8 / scale);
+ band.opacity(drawing.over ? 0.95 : 0.6);
+ }
+
+ /**
+ * Write the verb along an edge under the eye.
+ *
+ * The **forward** wording, not the panel's inverse reading: here the words sit
+ * beside a head that already points somewhere, so "has member" pointing at the
+ * unit would contradict the arrow. The panel has no arrow and reads from the
+ * selected node outwards, which is why the two differ.
+ *
+ * Created on the first edge that needs one rather than up front: a case draws a
+ * few hundred edges and only the handful under the pointer are ever worded.
+ *
+ * A collapsed edge says what it stands for beside its verb, because that is the
+ * whole point of collapsing it: *cites 3 sources · 1 account* is the finding, where
+ * "cites" alone would be a thinner line saying less than the three it replaced.
+ */
+ function styleVerb(entry, show, scale) {
+ if (!show && !entry.verb) return;
+ if (!entry.verb) {
+ entry.verb = new Konva.Text({
+ text: lineReads(entry.link),
+ fontSize: 10,
+ fontFamily: fontStack,
+ listening: false,
+ fillAfterStrokeEnabled: true,
+ lineJoin: 'round',
+ perfectDrawEnabled: false,
+ });
+ names.add(entry.verb);
+ }
+ const text = entry.verb;
+ text.visible(show);
+ if (!show) return;
+ text.fontSize(10 / scale);
+ text.stroke(colours.surface);
+ text.strokeWidth(3.5 / scale);
+ text.fill(colours.accent);
+ const mid = edgeMidpoint(entry.points, 13 / scale);
+ text.offsetX(text.width() / 2);
+ text.offsetY(text.height() / 2);
+ text.position(mid);
+ }
+
+ /** A screen point in the canvas units the placement and the pins are stated in.
+ * The same inverse `zoomBy` already takes to keep the pointer over the same spot
+ * while zooming, said once so a dropped file and a new entity land where the
+ * gesture aimed. */
+ function toCanvas(point) {
+ if (!group) return { x: point.x, y: point.y };
+ const scale = group.scaleX() || 1;
+ return { x: (point.x - group.x()) / scale, y: (point.y - group.y()) / scale };
+ }
+
+ function zoomBy(factor, anchor) {
+ if (!group || !stage) return;
+ const old = group.scaleX();
+ const next = Math.min(ZOOM_MAX, Math.max(ZOOM_MIN, old * factor));
+ if (next === old) return;
+ const point = anchor ?? { x: width / 2, y: height / 2 };
+ const local = { x: (point.x - group.x()) / old, y: (point.y - group.y()) / old };
+ group.scale({ x: next, y: next });
+ group.position({ x: point.x - local.x * next, y: point.y - local.y * next });
+ zoom = next;
+ cameraRevision += 1;
+ restyle();
+ }
+
+ function onWheel(event) {
+ event.preventDefault();
+ const pointer = stage?.getPointerPosition();
+ zoomBy(event.deltaY < 0 ? 1.12 : 1 / 1.12, pointer);
+ }
+
+ // -- panning ---------------------------------------------------------------
+ //
+ // Done by hand rather than with Konva's `draggable`, which is the bug this
+ // replaces: a draggable Group only drags where the pointer hits one of its own
+ // shapes, so the canvas could only be moved by grabbing a node — and the empty
+ // space, which is most of a graph, did nothing at all.
+
+ let drag = null;
+ let dragged = false; // a click that ended a pan must not also select
+ let arranged = false; // nor a click that ended a node's own drag
+ let frame = 0; // the redraw already asked for, so a pan draws once per frame
+
+ function onPointerDown(event) {
+ // Whatever the press turns out to be, it was aimed at the case, and the list is
+ // sitting over the case.
+ listing = false;
+ if (event.button !== 0 || !group) return;
+ drag = { id: event.pointerId, x: event.clientX, y: event.clientY, at: group.position() };
+ dragged = false;
+ panning = true;
+ tip = null;
+ }
+
+ function onPointerMove(event) {
+ // An armed connection follows the pointer, and does not stop the case being
+ // panned under it: the two nodes worth joining are often nowhere near each
+ // other, and a mode that pinned the view would make those the hard ones.
+ if (drawing) drawTo(event);
+ if (!drag || event.pointerId !== drag.id || !group) return;
+ // A button released outside the window never reaches us, so a move with no
+ // button held ends the pan instead of dragging the case around behind a
+ // pointer nobody is pressing.
+ if (event.buttons === 0) {
+ onPointerUp(event);
+ return;
+ }
+ const dx = event.clientX - drag.x;
+ const dy = event.clientY - drag.y;
+ if (!dragged && Math.hypot(dx, dy) < DRAG_SLOP) return;
+ if (!dragged) {
+ dragged = true;
+ // Nothing can be picked mid-pan, so the hit canvas — a second full drawing of
+ // every shape — is not worth redrawing on the way. This is most of what made
+ // dragging feel heavy.
+ layer?.listening(false);
+ }
+ drag.to = { x: drag.at.x + dx, y: drag.at.y + dy };
+ // A pointer reports faster than the screen refreshes, so several moves per
+ // frame would each pay for a full redraw and only the last would be seen.
+ frame ||= requestAnimationFrame(() => {
+ frame = 0;
+ if (!drag?.to || !group) return;
+ group.position(drag.to);
+ // Only the arrow, never the scene: a pan deliberately does not restyle, and
+ // paying for a few hundred shapes on every frame of one to keep a single line
+ // in step would undo the whole reason it draws this way. What the arrow could
+ // land on is caught up when the pointer comes up.
+ if (drawing) styleBand(group.scaleX() || 1);
+ layer?.batchDraw();
+ });
+ }
+
+ function onPointerUp(event) {
+ if (!drag || event.pointerId !== drag.id) return;
+ if (drag.to && group) group.position(drag.to);
+ drag = null;
+ panning = false;
+ if (frame) {
+ cancelAnimationFrame(frame);
+ frame = 0;
+ }
+ layer?.listening(true);
+ // What the pan brought into view has to be dressed: a card is only built once
+ // it is on screen, so panning to a new corner is what asks for its cards. Drawn
+ // straight away rather than on the next batch, so releasing the mouse does not
+ // leave the last stretch of the drag one frame behind the pointer.
+ if (dragged) {
+ cameraRevision += 1;
+ restyle();
+ layer?.draw();
+ }
+ }
+
+ function fitView() {
+ applyView();
+ restyle();
+ }
+
+ /** Native full screen, so the drawing gets the browser chrome's rows too. The
+ * canvas is measured with `bind:clientWidth`, so the stage follows on its own.
+ * Esc leaves it without asking us, which is why the flag is read back from the
+ * document rather than toggled here. */
+ async function toggleFullscreen() {
+ if (!toolElement || typeof document === 'undefined') return;
+ try {
+ if (document.fullscreenElement) await document.exitFullscreen();
+ else await toolElement.requestFullscreen();
+ } catch {
+ toast('Full screen is not available', 'danger');
+ }
+ }
+
+ $effect(() => {
+ if (typeof document === 'undefined') return;
+ const changed = () => (fullscreen = document.fullscreenElement === toolElement);
+ document.addEventListener('fullscreenchange', changed);
+ return () => document.removeEventListener('fullscreenchange', changed);
+ });
+
+ /** Which way one arrow key moves a node. */
+ const ARROWS = {
+ ArrowLeft: [-1, 0],
+ ArrowRight: [1, 0],
+ ArrowUp: [0, -1],
+ ArrowDown: [0, 1],
+ };
+
+ function onKey(event) {
+ // Escape still reaches the search field, because leaving it is what Escape is
+ // for there. Everything else belongs to the canvas, and a field that is being
+ // typed into owns its own keys: without this, naming a node "0" fits the view
+ // and an arrow key moves the case instead of the cursor.
+ const typing = /^(INPUT|TEXTAREA|SELECT)$/.test(event.target?.tagName ?? '');
+ if (event.key === 'Escape') {
+ // The search list is what Escape closes first, then the handful, then the
+ // selection: the shallower thing goes first, as everywhere else. A menu or a
+ // half-drawn relation is shallower than any of them — it is mid-gesture.
+ //
+ // One press takes the list and the term together, and it is the browser that
+ // decides: Escape in a `type="search"` field clears it natively, so a first
+ // press that only put the list away would be fighting the platform to stage a
+ // distinction the pointer already makes.
+ if (menu) menu = null;
+ else if (blank) blank = null;
+ else if (offer) offer = null;
+ else if (drawing) {
+ drawing = null;
+ restyle();
+ }
+ // A question waiting for its other end is the shallowest thing here: nothing
+ // has been drawn from it yet, so giving it up costs nothing.
+ else if (asking) asking = null;
+ // A path is mid-gesture like a half-drawn relation, and goes the same way:
+ // whole, in one press. Keeping the steps taken would leave a route on screen
+ // that nothing is still building, which is a picture nobody asked for.
+ else if (tracing) traceStop();
+ else if (find) find = '';
+ // A narrowing is shallower than a gathered handful: it costs one click to ask
+ // again, where the handful was built node by node.
+ else if (singling) singling = false;
+ else if (held.length) held = [];
+ else if (chosenLink) chosenLink = null;
+ // The case comes back before the node is let go, which is the same ladder run
+ // one rung deeper: showing the rest again is a smaller step than giving up what
+ // you were reading, and it leaves the panel open on the node you kept.
+ else if (onlyThis) letGoOnly();
+ else if (selected) selected = null;
+ hovered = null;
+ tip = null;
+ return;
+ }
+ if (typing) return;
+ if (event.ctrlKey || event.metaKey) {
+ // The same three chords ProofComposer binds, so one undo is learned once. Never
+ // over an armed gesture: a relation, a route or a walk waiting for its other end
+ // owns the press, exactly as the switch on the node already gives it up.
+ const chord = event.key.toLowerCase();
+ if (drawing || tracing || asking) return;
+ if (chord === 'z') {
+ event.preventDefault();
+ if (event.shiftKey) redo();
+ else undo();
+ } else if (chord === 'y') {
+ event.preventDefault();
+ redo();
+ }
+ // Everything else with a modifier belongs to the browser: Ctrl+0 and Ctrl+- are
+ // its zoom, and the bare keys below are the canvas's own.
+ return;
+ }
+ const arrow = ARROWS[event.key];
+ if (arrow && nudge(arrow[0], arrow[1], event.shiftKey)) {
+ // Only once a node actually moved: with nothing selected the arrows still
+ // scroll the page, which is what they should do.
+ event.preventDefault();
+ } else if (event.key === '0') fitView();
+ // Beside the key that fits the case, because they are the same kind of act: how
+ // much of it you are looking at. Silent with nothing selected rather than arming
+ // a reach that nothing on screen is reading.
+ else if (event.key === '1' || event.key === '2' || event.key === '3') {
+ setFocusHops(Number(event.key));
+ } else if (event.key === '+' || event.key === '=') zoomBy(1.2);
+ else if (event.key === '-') zoomBy(1 / 1.2);
+ }
+
+ // Structure changed: rebuild. Selection or hover changed: restyle only. Both
+ // read state, so both are untracked — a rebuild triggered by a hover was the
+ // bug that teleported the view back to its starting position on every mouseover.
+ // Where this drawing came to rest, kept for the next read of the same question.
+ // The parked column is deliberately left out: it is placed against the cluster's
+ // edge rather than against the case, so remembering a spot beside a cluster that
+ // has since grown would strand it — and a node that leaves the park has no reason
+ // to be nailed to where it sat while nothing linked to it.
+ $effect(() => {
+ for (const seat of placed) {
+ if (!seat.parked) settled.set(seat.id, { x: seat.x, y: seat.y });
+ }
+ });
+
+ $effect(() => {
+ void placed;
+ void edges;
+ void bends;
+ void width;
+ void height;
+ untrack(rebuild);
+ });
+
+ $effect(() => {
+ void selected;
+ void hovered;
+ // Typing a name narrows the picture, which is a restyle and never a rebuild:
+ // nothing moves while a search runs, or the shape being read would come apart
+ // under the letters being typed.
+ void find;
+ // An edge under the pointer or under the panel lights like a node does.
+ void chosenLink;
+ void hoveredLink;
+ // How far the focus reaches, and whether it removes the rest rather than dimming
+ // it. Both change what is drawn and neither moves anything, which is the whole
+ // reason the locked focus never has to touch the layout.
+ void focusHops;
+ void onlyThis;
+ // A step taken lights one more edge and offers a different set of next ones,
+ // and an answered question lights every route that tied for shortest.
+ void tracing;
+ void path;
+ void routes;
+ // The handle hides while a menu is up, so it is not left hanging over one.
+ void offer;
+ // Which nodes are marked or in hand is a restyle, not a rebuild: both change what
+ // is drawn on a node without moving anything.
+ void pinnedIds;
+ void held;
+ // And so is the switch on the node under the eye. A fold itself is a rebuild, since
+ // nodes leave the drawing; what the switch *offers* is drawn on one node.
+ void switchFor;
+ // Narrowing to the statements on one account dims the rest, like a search does,
+ // and moves nothing for the same reason.
+ void singling;
+ untrack(restyle);
+ });
+
+ $effect(() => {
+ const observer = new MutationObserver(() => {
+ readColours();
+ untrack(restyle);
+ });
+ observer.observe(document.documentElement, {
+ attributes: true,
+ attributeFilter: ['data-theme', 'class'],
+ });
+ return () => observer.disconnect();
+ });
+
+ /** A saved graph is a question plus presentation state. Its arrangement belongs
+ * to the view, so reopening it restores the reading without rewriting case pins. */
+ function openPeriodInTimeline() {
+ uiState.timelineRange = {
+ from: analysisSearch.period.from,
+ to: analysisSearch.period.to,
+ };
+ uiState.tool = 'timeline';
+ }
+
+ function openPeriodOnMap() {
+ uiState.mapTimelineRange = {
+ from: analysisSearch.period.from,
+ to: analysisSearch.period.to,
+ categories: analysisSearch.period.categories ?? [],
+ };
+ uiState.tool = 'satellite';
+ }
+
+ function clearPeriod() {
+ fromBoard = null;
+ setAnalysisPeriod(caseState.current?.id, emptyAnalysisPeriod());
+ }
+
+ function captureAnalysisView(mode) {
+ const graph = JSON.parse(snapshotNow());
+ graph.camera = group
+ ? { x: group.x(), y: group.y(), zoom: group.scaleX() }
+ : null;
+ return {
+ version: 1,
+ query: {
+ filter: normalizeFilter(searchFilter),
+ terms: searchTerms,
+ label: searchSaid,
+ },
+ graph,
+ timeline: analysisPeriodSpec(analysisSearch.period),
+ ...(mode === 'snapshot' ? { capture_ids: nodes.map((node) => node.id) } : {}),
+ };
+ }
+
+ let appliedViewId = null;
+
+ async function applyGraphView(view) {
+ if (!view || view.surface !== 'graph') return;
+ restoring = true;
+ // Finish a case-wide drag before replacing the drawing-side map with the view's
+ // own arrangement. The two stores never borrow coordinates from each other.
+ await flushPins();
+ if (catalogViews.activeView?.id !== view.id) {
+ restoring = false;
+ return;
+ }
+ appliedViewId = view.id;
+ const saved = view.spec?.graph ?? {};
+ try {
+ replaceViewArrangement(saved.arrangement ?? [], view.id);
+ root = view.mode === 'live' && typeof saved.root === 'string' ? saved.root : null;
+ selected = null;
+ openId = null;
+ snapshotOpen = null;
+ lens = typeof saved.lens === 'string' ? saved.lens : lens;
+ order = typeof saved.order === 'string' ? saved.order : order;
+ hops = [1, 2, 3].includes(saved.hops) ? saved.hops : 1;
+ pickFolder = typeof saved.folder === 'string' ? saved.folder : '';
+ hiddenFamilies = Array.isArray(saved.families) ? saved.families : [];
+ kept = Array.isArray(saved.kept) ? saved.kept : [];
+ expanded = Array.isArray(saved.expanded) ? saved.expanded : [];
+ omitted = Array.isArray(saved.omitted) ? saved.omitted : [];
+ collapsed = Array.isArray(saved.collapsed) ? saved.collapsed : [];
+ putAway = saved.putAway && typeof saved.putAway === 'object' ? saved.putAway : {};
+ anchored = null;
+ rereads += 1;
+ await tick();
+ if (saved.camera && group) {
+ const scale = Math.min(ZOOM_MAX, Math.max(ZOOM_MIN, Number(saved.camera.zoom) || 1));
+ group.position({ x: Number(saved.camera.x) || 0, y: Number(saved.camera.y) || 0 });
+ group.scale({ x: scale, y: scale });
+ zoom = scale;
+ cameraRevision += 1;
+ restyle();
+ }
+ } finally {
+ restoring = false;
+ }
+ }
+
+ async function openAnalysisView(view) {
+ if (view.surface !== 'graph') {
+ // The only other surface in this family is the Board: same question, rows.
+ uiState.tool = 'board';
+ return;
+ }
+ await applyGraphView(view);
+ }
+
+ async function leaveAnalysisReading() {
+ appliedViewId = null;
+ releaseViewArrangement();
+ searchFilter = normalizeFilter(analysisSearch.filter);
+ root = null;
+ selected = null;
+ openId = null;
+ snapshotOpen = null;
+ resetDrawing();
+ rereads += 1;
+ }
+
+ // A view can be opened from the other surface while this component is hidden.
+ $effect(() => {
+ const view = catalogViews.activeView;
+ if (!view || view.surface !== 'graph') {
+ appliedViewId = null;
+ if (arrangementOwner) {
+ untrack(() => {
+ releaseViewArrangement();
+ rereads += 1;
+ });
+ }
+ return;
+ }
+ if (view.id === appliedViewId) return;
+ untrack(() => void applyGraphView(view));
+ });
+
+ let observedLiveView = null;
+ let observedLiveState = '';
+ $effect(() => {
+ const view = catalogViews.activeView;
+ void arrangementRevision;
+ void arrangementSaveRevision;
+ void cameraRevision;
+ void zoom;
+ if (!view || view.mode !== 'live' || view.surface !== 'graph') {
+ observedLiveView = null;
+ observedLiveState = '';
+ return;
+ }
+ if (restoring) return;
+ const current = {
+ filter: normalizeFilter(searchFilter),
+ period: normalizeAnalysisPeriod(analysisSearch.period),
+ graph: captureAnalysisView('live').graph,
+ };
+ const saved = {
+ filter: normalizeFilter(view.spec?.query?.filter),
+ period: normalizeAnalysisPeriod(view.spec?.timeline),
+ graph: view.spec?.graph ?? {},
+ };
+ const currentState = JSON.stringify(current);
+ if (observedLiveView !== view.id) {
+ observedLiveView = view.id;
+ observedLiveState = currentState;
+ } else if (currentState !== observedLiveState) {
+ observedLiveState = currentState;
+ catalogViews.changeVersion += 1;
+ }
+ catalogViews.modified = currentState !== JSON.stringify(saved);
+ });
+
+ $effect(() => () => {
+ if (frame) cancelAnimationFrame(frame);
+ frame = 0;
+ // A drag inside the debounce window would otherwise be lost to the tab closing.
+ flushPins();
+ stage?.destroy();
+ stage = null;
+ layer = null;
+ group = null;
+ });
+</script>
+
+<svelte:window
+ onkeydown={onKey}
+ onpointermove={onPointerMove}
+ onpointerup={onPointerUp}
+ onpointercancel={onPointerUp}
+/>
+
+<div class="graph-tool" bind:this={toolElement}>
+ <div class="toolbar">
+ {#if root}
+ <button class="btn btn-ghost btn-sm" onclick={wholeCase}>
+ <Icon name="chevronLeft" size={15} /> Whole case
+ </button>
+ <label class="control">
+ Hops
+ <select class="select pick" bind:value={hops}>
+ <option value={1}>1</option>
+ <option value={2}>2</option>
+ <option value={3}>3</option>
+ </select>
+ </label>
+ {:else if payload?.truncated}
+ <!-- Only on a case too large to draw whole, because that is the only time it
+ does anything: it picks which nodes survive the cut. On a case that fits,
+ the control changed nothing on screen and read as a sort order. -->
+ <!-- Named for what it decides rather than for what it does to the survivors:
+ *Keep* read as a verb the analyst was pressing, and the drawing has a list
+ of nodes kept by name that this control has nothing to do with. -->
+ <label class="control" title="Which nodes this view keeps, now that the case is too large to draw whole">
+ Ranking
+ <select class="select pick" bind:value={order}>
+ {#each orders as entry (entry.value)}
+ <option value={entry.value} title={entry.hint}>{entry.label}</option>
+ {/each}
+ </select>
+ </label>
+ {/if}
+
+ <label class="control">
+ Lens
+ <select class="select pick" bind:value={lens} title={lensHint}>
+ {#each lenses as entry (entry.id)}
+ <option value={entry.id} title={entry.hint}>{entry.label}</option>
+ {/each}
+ </select>
+ </label>
+
+ <!-- Off, a card shows what the entity is rather than what it looks like — and
+ asks for no pictures at all, which is the other half of what this is for. -->
+ <label class="control check" title="Show the pictures the case holds, or the entity glyphs">
+ <input type="checkbox" bind:checked={showPreviews} onchange={forgetCards} />
+ Preview
+ </label>
+
+ <div class="find">
+ <Icon name="search" size={13} />
+ <input
+ class="input"
+ type="search"
+ placeholder="Find a node"
+ aria-label="Find a node"
+ bind:value={find}
+ oninput={() => (listing = true)}
+ onpointerdown={() => (listing = true)}
+ onfocus={() => (listing = true)}
+ onkeydown={(event) => {
+ if (event.key !== 'Enter') return;
+ if (matches.length) jumpTo(matches[0].id);
+ else if (elsewhere.length) bringIn(elsewhere[0]);
+ }}
+ />
+ {#if listing && (matches.length || elsewhere.length)}
+ <ul class="found">
+ {#each matches as row (row.id)}
+ <li>
+ <!-- A folded match says so rather than being left out: the drawing has
+ it, put away, and picking it gives its fold back. Reported missing
+ instead, it would be fetched from the case a second time. -->
+ <button
+ onclick={() => jumpTo(row.id)}
+ title={folds.hidden.has(row.id) ? 'Folded away. Picking it unfolds it.' : null}
+ >
+ <Icon name={entityIcon(row)} size={13} />
+ <span>{shortLabel(row.label, 30)}</span>
+ <em>{folds.hidden.has(row.id) ? 'folded' : row.degree}</em>
+ </button>
+ </li>
+ {/each}
+ <!-- What the case holds under this name and the drawing does not. Told
+ apart rather than mixed in, because clicking one costs a read and
+ changes the picture, where clicking a drawn one only moves the eye. -->
+ {#each elsewhere as row (row.id)}
+ {@const filed = lensHides.includes(row.type)}
+ <li>
+ <button
+ class="afar"
+ onclick={() => bringIn(row)}
+ title={filed
+ ? 'This reading does not draw it. My work does.'
+ : 'Not drawn. Bring it in with what touches it.'}
+ >
+ <Icon name={entityIcon(row)} size={13} />
+ <span>{shortLabel(row.label, 30)}</span>
+ <em>{filed ? 'in My work' : 'bring in'}</em>
+ </button>
+ </li>
+ {/each}
+ </ul>
+ {/if}
+ </div>
+
+ <AnalysisViews
+ surface="graph"
+ capture={captureAnalysisView}
+ onopen={openAnalysisView}
+ onleave={leaveAnalysisReading}
+ />
+
+ <span class="spacer"></span>
+
+ {#if payload}
+ <!-- What is **drawn**, which the folds change and the case does not hear about.
+ Counting what the case sent would leave the number arguing with the picture
+ the moment anything was folded. -->
+ <span class="count">
+ {#if root}
+ {nodes.length} around this{#if payload.truncated}<em>, partial</em>{/if}
+ {:else}
+ {nodes.length} of {payload.total}
+ {#if payload.truncated}
+ <em title="Narrow with a lens, or open one node">
+ , most connected
+ </em>
+ {/if}
+ {/if}
+ </span>
+ {#if !root && payload.isolated > 0}
+ <!-- Counted across the case like the total beside it, never over what was
+ drawn: a node with no edge is the first thing a cut discards, so on the
+ cases where this number matters it would always have read zero. -->
+ <span
+ class="count isolated"
+ title="Nothing in this lens connects to them, counted across the case"
+ >
+ {payload.isolated} unconnected
+ </span>
+ {/if}
+ <!-- The independence number, and it reads off the collapsed edges rather than
+ being computed: three citations are not three sources when one account
+ published all three. Counted over the drawing, like the match count, because
+ those are the edges that were resolved. It concludes nothing — a source's
+ independence is a measurement, and what it means here is the analyst's.
+
+ Pressable, because a number that names a set the analyst cannot reach sends
+ them opening statements one at a time to find out which ones it meant. -->
+ {#if !root && payload.single_account > 0}
+ <button
+ class="count resting"
+ class:on={singling}
+ aria-pressed={singling}
+ onclick={showResting}
+ title={singling
+ ? 'Click again to bring the rest of the case back.'
+ : 'These cite several sources, but one account published every one of them. Click to light just those statements.'}
+ >
+ {payload.single_account} on one account
+ </button>
+ {/if}
+ <!-- What a drawing this size costs, said where the counts are. Nothing is
+ refused: the picture is the analyst's, and this is the price of the next
+ change rather than a wall in front of it. -->
+ {#if weight}
+ <span
+ class="count weight"
+ class:full={weight === 'freezing'}
+ title={weight === 'freezing'
+ ? 'Every change now freezes the tab for a few seconds. Hide what the picture is not about.'
+ : 'Placing this many nodes costs about a second on every change.'}
+ >
+ {weight === 'freezing' ? 'very heavy' : 'heavy'} drawing
+ </span>
+ {/if}
+ {/if}
+
+ <!-- What the typing lit, counted over the **drawing**. "No match drawn" is a
+ different answer from "no such entity", and the list under the field is
+ where the case's own answer to the same name lives. -->
+ {#if find.trim()}
+ <span class="count isolated" title="Counted over the drawing, not the case">
+ {#if found.size}
+ {found.size} match{found.size === 1 ? '' : 'es'}
+ {:else}
+ no match drawn
+ {/if}
+ </span>
+ {/if}
+
+ <!-- What the folds are holding, and the way to have it all back. A chip rather
+ than a button in the row below, because it belongs with the counts: it says
+ how much of the case is currently put away.
+
+ Its own control rather than part of the reset, since giving the folds back
+ costs no read and undoes nothing that was asked of the case. -->
+ {#if foldedCount}
+ <button
+ class="count folded"
+ onclick={unfoldAll}
+ title="Give back everything the folds are holding"
+ >
+ {foldedCount} folded
+ </button>
+ {/if}
+
+ <!-- The way back, one act at a time. Said in the toolbar as well as bound to the
+ chord, because a canvas teaches no gesture: a shortcut nothing announces is a
+ shortcut nobody uses. Absent rather than greyed while there is nothing to
+ undo, like every other control here. -->
+ {#if canUndo}
+ <button
+ class="btn btn-ghost btn-sm placed"
+ onclick={undo}
+ title="Undo the last change to the drawing (Ctrl+Z)"
+ >
+ <Icon name="undo" size={14} stroke={1.7} />
+ Undo
+ </button>
+ {/if}
+ {#if canRedo}
+ <button
+ class="btn btn-ghost btn-sm placed"
+ onclick={redo}
+ title="Do it again (Ctrl+Shift+Z)"
+ >
+ <Icon name="redo" size={14} stroke={1.7} />
+ Redo
+ </button>
+ {/if}
+
+ <!-- One way back for the whole picture, whichever of the four lists is in the
+ way, and a different act from the undo beside it: this is back to the
+ beginning in one press. The arrangement is deliberately not part of it:
+ **Reset pins** undoes work done by hand, and this undoes a reading. -->
+ {#if edited}
+ <button
+ class="btn btn-ghost btn-sm placed"
+ onclick={resetDrawing}
+ title="Draw the case the way it opened"
+ >
+ Reset view
+ </button>
+ {/if}
+
+ <!-- Armed, waiting for its other end. Said in the toolbar rather than only on
+ the canvas: a mode with no words is a mode nobody can get out of. -->
+ {#if drawing}
+ <span class="count connecting">
+ Connecting from {shortLabel(byId.get(drawing.from)?.label ?? '', 18)} — click the
+ other end
+ <button
+ class="as-link"
+ onclick={() => {
+ drawing = null;
+ restyle();
+ }}
+ >
+ cancel
+ </button>
+ </span>
+ {/if}
+
+ <!-- Only while a handful is gathered, and it is how the handful is let go: a
+ group that can be built with no visible way to unbuild it is a trap. -->
+ {#if held.length}
+ <button
+ class="btn btn-ghost btn-sm placed"
+ onclick={() => (held = [])}
+ title="Let go of the handful (Escape)"
+ >
+ {held.length} held
+ </button>
+ <!-- Growth and removal over a list, which is what a gathered handful is for
+ besides moving: one question about five nodes is one read, where five clicks
+ are five reads landing in five places. -->
+ <button
+ class="btn btn-ghost btn-sm placed"
+ onclick={expandGathered}
+ title="Bring in what touches all of them, in one read"
+ >
+ Expand {held.length}
+ </button>
+ <button
+ class="btn btn-ghost btn-sm placed"
+ onclick={() => takeOut(held)}
+ title="Out of the drawing, not out of the case"
+ >
+ Hide {held.length}
+ </button>
+ {/if}
+
+ <!-- Only once something has been moved, because that is the only time it does
+ anything. The verb is in the label rather than the tooltip: a count on its
+ own reads as a status, and this one is the way back out of an arrangement.
+ Outside a named reading it counts the whole case, so that way back remains
+ available when pinned nodes are filtered out. Inside one it counts that
+ view's local arrangement. -->
+ {#if pinCount > 0}
+ <button
+ class="btn btn-ghost btn-sm placed"
+ onclick={resetLayout}
+ title={ownsViewArrangement()
+ ? 'Let the layout place this saved view again.'
+ : 'Let the layout place these again. Each lens keeps its own arrangement.'}
+ >
+ <Icon name="pushpin" size={14} stroke={1.7} />
+ Reset {pinCount} pin{pinCount === 1 ? '' : 's'}
+ </button>
+ {/if}
+
+ <span class="zoom">
+ <button class="icon-btn" onclick={() => zoomBy(1 / 1.2)} title="Zoom out (-)">
+ <Icon name="minus" size={15} />
+ </button>
+ <span class="level" title="Scroll to zoom, drag to pan">{Math.round(zoom * 100)}%</span>
+ <button class="icon-btn" onclick={() => zoomBy(1.2)} title="Zoom in (+)">
+ <Icon name="plus" size={15} />
+ </button>
+ <button class="icon-btn apart" onclick={fitView} title="Fit everything on screen (0)">
+ <Icon name="reset" size={14} />
+ </button>
+ </span>
+
+ <!-- Last in the row, and always there: a big case is read by giving it the whole
+ screen, and a control that moves as chips appear is a control you hunt for. -->
+ <button
+ class="btn btn-ghost btn-sm placed"
+ aria-pressed={fullscreen}
+ onclick={toggleFullscreen}
+ title={fullscreen ? 'Back to the window (Esc)' : 'Draw the case on the whole screen'}
+ >
+ <Icon name={fullscreen ? 'minimize' : 'maximize'} size={14} stroke={1.7} />
+ {fullscreen ? 'Exit full screen' : 'Full screen'}
+ </button>
+ </div>
+
+ {#if !root}
+ <FilterBar
+ bind:filter={searchFilter}
+ {summary}
+ {facets}
+ {facetState}
+ families={searchFamilies}
+ caseFolders={caseState.current?.folders ?? []}
+ types={searchTypeOptions}
+ familyName={familyTitle}
+ typeName={entityLabel}
+ familyHint={familyReads}
+ disabled={snapshotReading}
+ onfields={() => (fieldsWanted = true)}
+ />
+ {#if activePeriod}
+ <AnalysisPeriodBar
+ period={analysisSearch.period}
+ ontimeline={openPeriodInTimeline}
+ onmap={openPeriodOnMap}
+ onclear={clearPeriod}
+ />
+ {/if}
+ {/if}
+
+ {#if fromBoard}
+ <!-- What the drawing is narrowed to, and where it came from. A picture that
+ silently answers somebody else's question is a picture that looks broken: the
+ sentence the Board asked is written out, and one press gives the case back.
+ In the flow rather than over the canvas, because it describes the whole
+ drawing where the strips below describe one node in it. -->
+ <div class="from-board">
+ <Icon name="sliders" size={13} />
+ <span>{fromBoard.label || 'A question from the Board'}</span>
+ <button
+ class="as-link"
+ onclick={() => {
+ fromBoard = null;
+ searchFilter = emptyFilter();
+ }}
+ >Show the whole case</button>
+ </div>
+ {/if}
+
+ <div class="canvas-row">
+ <!-- Konva owns the pointer here; the wheel is intercepted so the page does not
+ scroll while zooming, and the drag is handled above so that the empty
+ space pans. Keyboard reaches the same actions through the toolbar buttons,
+ which is what keeps the canvas from being the only way in. -->
+ <!-- svelte-ignore a11y_no_static_element_interactions -->
+ <div
+ class="canvas"
+ class:panning
+ class:on-node={Boolean(hovered)}
+ class:arrangeable={canArrange}
+ bind:this={host}
+ bind:clientWidth={width}
+ bind:clientHeight={height}
+ onwheel={onWheel}
+ onpointerdown={onPointerDown}
+ ondragover={(event) => {
+ if (!caseState.current) return;
+ event.preventDefault();
+ dropOver = true;
+ }}
+ ondragleave={(event) => {
+ // Guarded on the container itself: the event fires for every child the
+ // pointer crosses, and an unguarded handler flickers the overlay off.
+ if (event.target === event.currentTarget) dropOver = false;
+ }}
+ ondrop={(event) => {
+ event.preventDefault();
+ dropOver = false;
+ const at = stage?.getPointerPosition();
+ importDropped(event.dataTransfer?.files, at ? toCanvas(at) : null);
+ }}
+ ></div>
+
+ {#if tip}
+ <!-- The full label, which a card truncates, and the preview at any zoom: the
+ picture is often the fastest answer to "which one is this". -->
+ <div class="tip" style="left:{tip.x}px; top:{tip.y}px">
+ {#if showPreviews && tip.thumb && caseState.current}
+ <img src={tip.thumb.startsWith('data:')
+ ? tip.thumb
+ : fileUrl(caseState.current.id, tip.thumb)} alt="" />
+ {/if}
+ <strong>{tip.label}</strong>
+ <span>
+ {madeHereLabel(tip) ?? entityKindLabel(tip, entityLabel(tip.type))}
+ · {tip.degree} connection{tip.degree === 1 ? '' : 's'}
+ </span>
+ {#if tip.folder}<span class="in-folder">{tip.folder}</span>{/if}
+ {#if switchFor && switchFor.id === hovered}
+ <!-- What the pill on the node means, in words, the first time it is seen.
+ A number in a circle is a number until something says what it counts. -->
+ <span class="how">
+ {#if switchFor.act === 'expand'}
+ {switchFor.count} connection{switchFor.count === 1 ? '' : 's'} not drawn. Double-click
+ to bring them in.
+ {:else if switchFor.act === 'fold'}
+ {switchFor.count} hang{switchFor.count === 1 ? 's' : ''} off this one alone.
+ Double-click to fold them away.
+ {:else}
+ Holding {switchFor.count} folded. Double-click to give them back.
+ {/if}
+ </span>
+ {/if}
+ {#if canArrange}
+ <!-- Where a node's gestures are learned. A canvas teaches nothing on its
+ own, and none of this is guessable. -->
+ <span class="how">Right-click for what you can do with it</span>
+ {/if}
+ </div>
+ {/if}
+
+ {#if loading}
+ <p class="overlay">Reading the case…</p>
+ {:else if failed}
+ <p class="overlay">{failed}</p>
+ {:else if payload && !nodes.length}
+ <p class="overlay">Nothing here yet. The Board files the first entity.</p>
+ {/if}
+
+ <!-- The focus, and the only place it can be read or changed. Over the drawing
+ rather than in the toolbar: everything here is about the one node in hand,
+ and it appears and leaves with it, where a toolbar control would sit there
+ greyed out most of the time. Never on the root of a neighbourhood, which is
+ what `focused` already decides. -->
+ {#if asking}
+ <!-- Armed and waiting, worded like the connection gesture because it is the
+ same shape of act: named first, then the click that follows means the one
+ thing the naming said it would. -->
+ <div class="focus walk">
+ <span class="on">
+ <Icon name="arrowRight" size={13} />
+ Path from {shortLabel(byId.get(asking.from)?.label ?? '', 22)} — click the other
+ end, or find it by name
+ </span>
+ <button class="icon-btn" onclick={() => (asking = null)} title="Give it up (Esc)">
+ <Icon name="x" size={13} />
+ </button>
+ </div>
+ {:else if tracing}
+ <!-- The walk, read as the sentence it is building. It takes the focus strip's
+ place rather than sitting beside it: while a path is being walked the hops
+ and the hiding answer a question nobody is asking. -->
+ <div class="focus walk">
+ <span class="on">
+ <Icon name="arrowRight" size={13} />
+ {path.length === 1
+ ? 'Click a lit node'
+ : `${path.length - 1} hop${path.length === 2 ? '' : 's'}`}
+ </span>
+ <!-- Every tied route is lit on the drawing; the sentence takes one at a time,
+ because a sentence cannot be read three times over. The count is the
+ number that says "this is a hub". -->
+ {#if routes.length > 1}
+ <span class="reach ties">
+ <button
+ class="step"
+ aria-label="The route before this one"
+ onclick={() => readRoute((routeAt + routes.length - 1) % routes.length)}
+ title="The route before this one"
+ >
+ ‹
+ </button>
+ <span class="of">{routeAt + 1} / {routes.length}</span>
+ <button
+ class="step"
+ aria-label="The next equally short route"
+ onclick={() => readRoute((routeAt + 1) % routes.length)}
+ title="The next equally short route"
+ >
+ ›
+ </button>
+ </span>
+ {/if}
+ <p class="said-path">
+ {#each sentence as step, index (step.id)}
+ {#if index > 0}<span class="verb">{step.verb}</span>{/if}
+ <button class="node" onclick={() => stepTo(step.id)} title="Go back to this step">
+ {#if step.node}<Icon name={entityIcon(step.node)} size={12} />{/if}
+ {shortLabel(step.label, 24)}
+ </button>
+ {/each}
+ </p>
+ <button class="icon-btn" onclick={traceStop} title="Give the walk up (Esc)">
+ <Icon name="x" size={13} />
+ </button>
+ </div>
+ {:else if focused && chosen}
+ <div class="focus">
+ <span class="on" title="What the picture is narrowed around">
+ <Icon name={entityIcon(chosen)} size={13} />
+ {shortLabel(chosen.label, 20)}
+ </span>
+ <span class="reach">
+ {#each [1, 2, 3] as step (step)}
+ <button
+ class="step"
+ class:set={focusHops === step}
+ aria-pressed={focusHops === step}
+ onclick={() => setFocusHops(step)}
+ title="Reach {step} hop{step === 1 ? '' : 's'} from this node ({step})"
+ >
+ {step}
+ </button>
+ {/each}
+ </span>
+ <button
+ class="step wide"
+ class:set={onlyThis}
+ aria-pressed={onlyThis}
+ onclick={toggleOnly}
+ title="Take the rest of the case off the screen and frame what is left"
+ >
+ Only this
+ </button>
+ <button
+ class="step wide"
+ onclick={() => askWayFrom(chosen.id)}
+ title="Find how this reaches another entity: click the other end, or name it"
+ >
+ Path to…
+ </button>
+ <button class="icon-btn" onclick={() => (selected = null)} title="Let the focus go (Esc)">
+ <Icon name="x" size={13} />
+ </button>
+ </div>
+ {/if}
+
+ {#if legend.length}
+ <div class="legend">
+ <!-- The legend is the control. A lens decides the reading and takes a whole
+ role out of it; switching a family off is the budget decision, which on a
+ case larger than the budget is the difference between spending it on media
+ and spending it on the case. It sits here rather than in the toolbar
+ because this is already where the eye goes to learn what a colour means. -->
+ <div class="row families">
+ {#each legend as row (row.family)}
+ <button
+ class="swatch-row"
+ class:off={!row.on}
+ aria-pressed={row.on}
+ onclick={() => toggleFamily(row.family)}
+ title={familyReads(row.family) || 'Draw this family, or leave it out'}
+ >
+ <i class="swatch" style="background: var(--graph-{row.family}, var(--text-3))"></i>
+ {row.family}
+ <em>{row.on ? row.count : 'off'}</em>
+ </button>
+ {/each}
+ </div>
+ {#if strokes.length}
+ <div class="row strokes">
+ {#each strokes as entry (entry.kind)}
+ <span class="swatch-row">
+ <svg width="26" height="9" aria-hidden="true">
+ <line
+ x1="0"
+ y1="4.5"
+ x2="18"
+ y2="4.5"
+ stroke="var(--text-3)"
+ stroke-width={entry.width}
+ stroke-dasharray={entry.dash.join(' ')}
+ />
+ <polygon points="18,1 25,4.5 18,8" fill="var(--text-3)" />
+ </svg>
+ {entry.label}
+ </span>
+ {/each}
+ </div>
+ {/if}
+ </div>
+ {/if}
+
+ {#if chosen}
+ {@const away = offScreen(chosen.id)}
+ <aside class="panel">
+ <header>
+ <Icon name={entityIcon(chosen)} size={16} />
+ <strong>{chosen.label}</strong>
+ <button class="icon-btn" onclick={() => (selected = null)} title="Close (Esc)">
+ <Icon name="x" size={14} />
+ </button>
+ </header>
+ <p class="meta">
+ {madeHereLabel(chosen) ?? entityKindLabel(chosen, entityLabel(chosen.type))}
+ · {entityFamily(chosen.type)}
+ {#if chosen.status === 'suggested'}<em class="proposed">proposed</em>{/if}
+ </p>
+ {#if chosen.matches?.[0]}
+ <p class="meta match-reason">
+ Matched {chosen.matches[0].label}: {shortLabel(chosen.matches[0].value, 72)}
+ </p>
+ {/if}
+ {#if madeHereBy(chosen)}
+ <!-- Where the file came from, said once. A frame and a photograph somebody
+ handed over are the same node otherwise, and the difference decides
+ whether it is evidence or something the case built. -->
+ <p class="meta made-here">
+ <Icon name="layers" size={13} stroke={1.7} />
+ Made in {madeHereBy(chosen)} out of material the case already holds.
+ </p>
+ {/if}
+ <div class="actions">
+ {#if snapshotReading}
+ <button
+ class="btn btn-ghost"
+ onclick={() => (snapshotOpen = catalogViews.activeView?.spec?.snapshot?.entities
+ ?.find((entity) => entity.id === chosen.id) ?? null)}
+ >Captured details</button>
+ {:else}
+ <button class="btn btn-ghost" onclick={() => (openId = chosen.id)}>Details</button>
+ {/if}
+ <!-- The same switch as the one on the node, in words and reachable from the
+ keyboard: the canvas answers a pointer, and the pill it draws is a few
+ pixels across at the zoom a case is read at. Absent when there is
+ nothing to do, like the pill. -->
+ {#if switchFor?.id === chosen.id}
+ <button
+ class="btn btn-ghost"
+ onclick={() => toggleAround(chosen.id)}
+ title={switchFor.act === 'expand'
+ ? 'Bring in the connections this one has that the drawing does not'
+ : switchFor.act === 'fold'
+ ? 'Put away what hangs off this one and nothing else'
+ : 'Put back what this one is holding'}
+ >
+ {switchFor.act === 'expand'
+ ? `Expand (${switchFor.count})`
+ : switchFor.act === 'fold'
+ ? `Collapse (${switchFor.count})`
+ : `Unfold (${switchFor.count})`}
+ </button>
+ {/if}
+ <!-- "Around this" replaces the case with this node and its hops, where
+ expanding adds its missing neighbours to the case already drawn. Both
+ used to be called expanding, which made the panel and the menu look
+ like two ways to the same place. -->
+ <button
+ class="btn btn-ghost"
+ onclick={() => focusOn(chosen.id)}
+ title="Draw this one and what reaches it, in place of the case"
+ >
+ Around this ({chosen.degree})
+ </button>
+ <!-- The way back to the table, which is the half the hand-over was missing:
+ a row could reach its node and a node could not reach its row. -->
+ {#if !snapshotReading}<button
+ class="btn btn-ghost"
+ onclick={() => {
+ uiState.openBoardEntity = chosen.id;
+ uiState.tool = 'board';
+ }}
+ title="Read this one in the Board, with its own row"
+ >
+ In the Board
+ </button>{/if}
+ <!-- Offered here as well as in the menu, because the menu is a right-click
+ and the drawing has to be editable from the keyboard too. Not on a
+ neighbourhood: that read is one node and its hops, and taking the root
+ out of it would leave the view answering nothing.
+ *Hide* rather than "Remove", which on the edge panel beside it means
+ deleting the statement from the case. -->
+ {#if !root}
+ <button
+ class="btn btn-ghost"
+ onclick={() => takeOut([chosen.id])}
+ title="Out of the drawing, not out of the case"
+ >
+ Hide
+ </button>
+ {/if}
+ </div>
+ {#if chosen.rests}
+ <!-- What this statement rests on. The number the case could not state before:
+ three citations are not three sources when one account published all
+ three, and counting them by eye is what nobody does on the two hundredth
+ claim. It says what it measured and concludes nothing. -->
+ <p class="meta" class:resting={chosen.rests.one}>
+ Rests on {chosen.rests.sources} source{chosen.rests.sources === 1 ? '' : 's'}
+ {#if chosen.rests.accounts}
+ · {chosen.rests.accounts} account{chosen.rests.accounts === 1 ? '' : 's'}
+ {/if}
+ {#if chosen.rests.one}<em>all one account</em>{/if}
+ </p>
+ {/if}
+ {#if canArrange && pinnedIds.includes(chosen.id)}
+ <!-- Where the mark on the node is explained, and the one place a single
+ node can be handed back without dropping the whole arrangement. -->
+ <p class="meta placed-here">
+ <Icon name="pushpin" size={13} stroke={1.7} />
+ You placed this one.
+ <button class="as-link" onclick={() => unpinNode(chosen.id)}>Let it go</button>
+ </p>
+ {/if}
+ <!-- Said, not offered: the act is the switch in the row above, and a second
+ control for it here is what left the analyst deciding whether two labels
+ meant two things. -->
+ {#if chosen.rolled}
+ <!-- What came out of this one and was used by nothing. Twelve frames saved
+ off a video are twelve pictures of that video, so the video says it
+ instead. The act is the switch in the row above. -->
+ <p class="meta placed-here">
+ <Icon name="layers" size={13} stroke={1.7} />
+ {rolledReads(chosen.rolled)} made from it, used by nothing.
+ </p>
+ {/if}
+ {#if collapsed.includes(chosen.id)}
+ <p class="meta placed-here">
+ <Icon name="layers" size={13} stroke={1.7} />
+ Holding {folds.by.get(chosen.id) ?? 0} folded under it.
+ </p>
+ {:else if expanded.includes(chosen.id)}
+ <p class="meta placed-here">
+ <Icon name="plus" size={13} stroke={1.7} />
+ You expanded this one.
+ </p>
+ {/if}
+ <!-- Grouped by what the connection says, and counted: reading a node is
+ reading what it mostly is, which a flat list of edges never states. The
+ registry already carries the inverse wording, so an incoming edge heads
+ its group as a sentence rather than as an arrow. -->
+ {#each neighbourGroups as group (group.key)}
+ {@const all = allOf.includes(group.key)}
+ <p class="group">
+ <span class="verb">{group.reading}</span>
+ <em>{group.rows.length}</em>
+ </p>
+ <ul class="neighbours">
+ {#each all ? group.rows : group.rows.slice(0, GROUP_ROWS) as row (row.link.id)}
+ <li>
+ <!-- Hovering a row lights its edge on the canvas, verb written on it:
+ the same answer as hovering the edge itself, since the row and
+ the line are the same connection. -->
+ <button
+ class="link-row"
+ onclick={() =>
+ asking
+ ? wayTo(row.entity.id)
+ : tracing
+ ? stepTo(row.entity.id)
+ : followTo(row.entity.id)}
+ onmouseenter={() => (hoveredLink = row.link.id)}
+ onmouseleave={() => (hoveredLink = null)}
+ onfocus={() => (hoveredLink = row.link.id)}
+ onblur={() => (hoveredLink = null)}
+ >
+ <Icon name={entityIcon(row.entity)} size={13} />
+ <span>{shortLabel(row.entity.label, 28)}</span>
+ </button>
+ </li>
+ {/each}
+ {#if !all && group.rows.length > GROUP_ROWS}
+ <li>
+ <button class="link-row rest" onclick={() => (allOf = [...allOf, group.key])}>
+ Show all {group.rows.length}
+ </button>
+ </li>
+ {/if}
+ </ul>
+ {/each}
+ <!-- The hole this closes: the list above is drawn from the edges on screen,
+ so a node with forty connections and three of them drawn read as a node
+ with three. The count is the node's own, and the act that answers it is
+ the switch in the row above. -->
+ {#if away > 0}
+ <!-- In a neighbourhood the way further out is Hops, not an expansion: that
+ read takes no `expand`, so the switch is not offered there. The count is
+ still true, so it is still said. -->
+ <p class="meta more">
+ {#if root}
+ {away} more, further than {hops} hop{hops === 1 ? '' : 's'}
+ {:else}
+ {away} more not drawn
+ {/if}
+ </p>
+ {:else if !neighbours.length}
+ <p class="meta">Nothing connects to this in the chosen lens.</p>
+ {/if}
+ </aside>
+ {:else if chosenEdge}
+ <!-- An edge is a statement, and on a worked case it is more often the finding
+ than either node it joins. It is read here, and ruled on here. -->
+ <aside class="panel">
+ <header>
+ <Icon name="link" size={16} />
+ <strong>{relationVerb(chosenEdge.type)}</strong>
+ <button class="icon-btn" onclick={() => (chosenLink = null)} title="Close (Esc)">
+ <Icon name="x" size={14} />
+ </button>
+ </header>
+ <p class="meta">
+ {byId.get(chosenEdge.from)?.label ?? chosenEdge.from}
+ → {byId.get(chosenEdge.to)?.label ?? chosenEdge.to}
+ {#if chosenEdge.provenance?.status === 'suggested'}<em class="proposed">proposed</em>{/if}
+ </p>
+ {#if chosenEdge.folded}
+ <!-- What the edge stands for, said in the words the finding is in: three
+ citations that are one source is the reading, not the count of rows. A
+ proposal anywhere along the path makes the whole path proposed, which the
+ dash above already says. -->
+ <p class="meta">
+ {standsFor(chosenEdge)}, drawn as one edge
+ </p>
+ {#if chosenEdge.folded.open?.length}
+ <div class="actions">
+ <button class="btn btn-ghost" onclick={() => unfold(chosenEdge)}>
+ Show the {chosenEdge.folded.open.length === 1
+ ? 'source'
+ : `${chosenEdge.folded.open.length} sources`}
+ </button>
+ </div>
+ {:else}
+ <!-- Nothing to hand back: this reading does not draw that type at all, so
+ the panel says where it lives instead of offering an act it would
+ refuse. -->
+ <p class="meta">My work draws {chosenEdge.folded.via.join(', ')}.</p>
+ {/if}
+ {:else}
+ {#if chosenEdge.merged}
+ <!-- The case's own row, and it also carries what said the same thing off
+ the same material. Named here rather than folded away with the
+ statement, because withdrawing this one has to stay possible. -->
+ <p class="meta">
+ Stands for {chosenEdge.merged.sources} more, all the same material.
+ </p>
+ <div class="actions">
+ <button class="btn btn-ghost" onclick={() => unfold(chosenEdge)}>
+ Show the {chosenEdge.merged.open.length}
+ </button>
+ </div>
+ {/if}
+ {#if chosenEdge.provenance?.by}
+ <p class="meta">Filed by {chosenEdge.provenance.by}</p>
+ {/if}
+ <!-- How sure of this, and what kind of tie it is: the two values an edge
+ carries besides its verb, offered where the edge is read rather than a
+ panel away. Each is drawn because the **registry** declares it — a
+ ratable verb, a verb that takes a qualifier — never because this edge
+ happens to hold a value. Same rule as Details, and it is what keeps a
+ free note off the rest of the vocabulary. -->
+ {#if !snapshotReading && chosenEdge.provenance?.status !== 'suggested'}
+ {@const rating = chosenEdge.confidence ?? null}
+ {@const qualifier = relationQualifier(chosenEdge.type)}
+ {@const gradable = isRatable(chosenEdge.type) && confidenceLevels().length}
+ {#if gradable || qualifier}
+ <div class="says">
+ {#if gradable}
+ <select
+ class="select pick rate"
+ class:set={rating !== null}
+ class:out={rating === -1}
+ value={rating ?? ''}
+ title={rating === null
+ ? 'How sure of this'
+ : confidenceHint(rating) || confidenceLabel(rating)}
+ onchange={(event) => rateEdge(chosenEdge.id, event.currentTarget.value)}
+ >
+ <!-- clearing, not a fifth level: this is the absence of a rating -->
+ <option value="">Not assessed</option>
+ {#each confidenceLevels() as level (level.value)}
+ <option value={level.value}>{level.label}</option>
+ {/each}
+ </select>
+ {/if}
+ {#if qualifier}
+ <input
+ class="input pick nature"
+ class:set={Boolean(chosenEdge.nature)}
+ value={chosenEdge.nature ?? ''}
+ placeholder={qualifier}
+ title={qualifier}
+ maxlength="120"
+ onchange={(event) => qualifyEdge(chosenEdge, event.currentTarget.value)}
+ />
+ {/if}
+ </div>
+ {/if}
+ {/if}
+ {#if !snapshotReading}<div class="actions">
+ {#if chosenEdge.provenance?.status === 'suggested'}
+ <button class="btn btn-ghost" onclick={() => ruleOn(chosenEdge.id, 'confirmed')}>
+ Confirm
+ </button>
+ {/if}
+ <button class="btn btn-ghost" onclick={() => dropLink(chosenEdge.id)}>Remove</button>
+ </div>{/if}
+ {/if}
+ <ul class="neighbours">
+ {#each [chosenEdge.from, chosenEdge.to] as end (end)}
+ {@const entity = byId.get(end)}
+ {#if entity}
+ <li>
+ <button class="link-row" onclick={() => ((chosenLink = null), (selected = end))}>
+ <span class="verb">{entityKindLabel(entity, entityLabel(entity.type))}</span>
+ <span>{shortLabel(entity.label, 28)}</span>
+ </button>
+ </li>
+ {/if}
+ {/each}
+ </ul>
+ </aside>
+ {/if}
+
+ {#if menu}
+ <!-- Guarded rather than `byId.get(menu.id)`: `{@const}` re-runs the moment the
+ menu closes, so an item that cleared it before acting read `menu.id` off
+ null and threw — which is how every item in this menu did nothing. -->
+ {@const at = menu && byId.get(menu.id)}
+ {#if at}
+ {@const away = offScreen(at.id)}
+ {@const takes = root ? 0 : foldableCount(at.id, nodes, links, new Set(pinnedIds))}
+ <!-- Where a node says what can be done with it, and the one place all three
+ acts on the drawing are named at once: a canvas teaches no gesture on its
+ own, and the switch on the node only ever offers one of them at a time. -->
+ <div class="menu" style="left:{menu.x}px; top:{menu.y}px">
+ <p class="meta">{shortLabel(at.label, 24)}</p>
+ <ul>
+ <li>
+ <!-- The count is what is *missing*, not the degree: a node whose
+ neighbours are all drawn has nothing to bring in, and saying so beats
+ an act that appears to do nothing. -->
+ <button
+ onclick={() => chose(expandNode)}
+ disabled={!away || Boolean(root)}
+ >
+ {#if away && root}
+ <!-- A neighbourhood is read one hop further, not expanded: that
+ read takes no `expand`, so this act is not this view's. -->
+ {away} more, further than {hops} hop{hops === 1 ? '' : 's'}
+ {:else if away}
+ Expand {away} more connection{away === 1 ? '' : 's'}
+ {:else}
+ All its connections are drawn
+ {/if}
+ </button>
+ </li>
+ <!-- The fold, and the way back out of it. Offered here in words as well as
+ on the node, because the pill states one act at a time and this is
+ where a node says everything it can do. -->
+ {#if collapsed.includes(at.id)}
+ <li>
+ <button onclick={() => chose(unfoldNode)}>
+ Unfold {folds.by.get(at.id) ?? 0}
+ </button>
+ </li>
+ {:else if takes}
+ <li>
+ <button
+ onclick={() => chose(foldNode)}
+ title="Put away what hangs off this one and nothing else"
+ >
+ Collapse {takes}
+ </button>
+ </li>
+ {/if}
+ <li><button onclick={() => chose(startDrawing)}>Connect to…</button></li>
+ <!-- Both ways to fill a path, in the one place a node's acts are named.
+ Asking is the common question, so it comes first; choosing the route
+ by hand is the rarer one and lives only here, which keeps the strip
+ over the drawing to a single line. -->
+ <li><button onclick={() => chose(askWayFrom)}>Path to…</button></li>
+ <li><button onclick={() => chose(traceFrom)}>Walk by hand</button></li>
+ <li><button onclick={() => chose((id) => (openId = id))}>Details</button></li>
+ {#if pinnedIds.includes(at.id)}
+ <li><button onclick={() => chose(unpinNode)}>Let it go</button></li>
+ {/if}
+ <!-- The drawing is a set, and this is how a node leaves it. Never on a
+ neighbourhood, whose root is the question being asked. The wording
+ keeps well clear of the edge panel's *Remove*, which deletes a
+ statement from the case: nothing here touches what the case holds. -->
+ {#if !root}
+ <li>
+ <button
+ onclick={() => chose((id) => takeOut([id]))}
+ title="Out of the drawing, not out of the case"
+ >
+ Hide it
+ </button>
+ </li>
+ <!-- The same acts over the gathered handful, offered where the handful is
+ under the pointer: growth and removal by the group are what make a
+ drawing you own workable at more than one node at a time. -->
+ {#if held.length > 1 && held.includes(at.id)}
+ <li>
+ <button onclick={() => ((menu = null), expandGathered())}>
+ Expand these {held.length}
+ </button>
+ </li>
+ <li>
+ <button onclick={() => takeOut(held)}>
+ Hide these {held.length}
+ </button>
+ </li>
+ {/if}
+ {/if}
+ </ul>
+ </div>
+ {/if}
+ {/if}
+
+ {#if blank}
+ <!-- What can be done where nothing is. The empty space used to answer a
+ right-click with nothing at all, which made the drawing a thing to read
+ rather than a place to work. -->
+ <div class="menu" style="left:{blank.x}px; top:{blank.y}px">
+ <ul>
+ {#if !snapshotReading}<li>
+ <button
+ onclick={() => {
+ creating = { at: blank.at, caseId: caseState.current?.id };
+ blank = null;
+ }}
+ >
+ New entity here
+ </button>
+ </li>{/if}
+ <li>
+ <button onclick={() => ((blank = null), fitView())}>Fit everything on screen</button>
+ </li>
+ </ul>
+ <p class="meta">Or drop a file anywhere on the drawing.</p>
+ </div>
+ {/if}
+
+ {#if dropOver}
+ <div class="drop-over">
+ <div class="drop-box">
+ <Icon name="upload" size={26} />
+ <span>{importing ? 'Adding…' : 'Drop to file it here'}</span>
+ </div>
+ </div>
+ {/if}
+
+ {#if offer}
+ <!-- Where a drawn relation is named. Only the readings the vocabulary accepts
+ between these two are here, so nothing offered can be refused, and a
+ reading the registry heads sits under its heading rather than among the
+ statements. -->
+ <div class="offer" style="left:{offer.x}px; top:{offer.y}px">
+ <p class="meta">
+ {shortLabel(byId.get(offer.from)?.label ?? '', 20)} →
+ {shortLabel(byId.get(offer.to)?.label ?? '', 20)}
+ </p>
+ {#each offerGroups as set (set.group)}
+ {#if set.group}<p class="heading">{set.group}</p>{/if}
+ <ul>
+ {#each set.options as option (option.type + option.direction)}
+ <li>
+ <button onclick={() => stateRelation(option)}>{option.label}</button>
+ </li>
+ {/each}
+ </ul>
+ {/each}
+ <button class="as-link" onclick={() => (offer = null)}>Cancel</button>
+ </div>
+ {/if}
+
+ {#if saving}
+ <p class="said">{saving}</p>
+ {/if}
+ </div>
+</div>
+
+{#if creating && !snapshotReading}
+ <!-- The one create dialog, shared with the Board: a claim is filed with the same
+ words and the same duplicate warning wherever the analyst is standing. What is
+ said here and not there is the lens — filing something this reading does not
+ draw looks exactly like filing nothing. -->
+ <EntityCreate
+ hidden={lensHides}
+ hiddenNote="This reading does not draw that type. My work does."
+ ontwin={(entity) => {
+ creating = null;
+ bringIn(entity);
+ }}
+ oncreated={(entity) => {
+ const { at, caseId } = creating;
+ creating = null;
+ drewIn(entity, at, caseId);
+ }}
+ onclose={() => (creating = null)}
+ />
+{/if}
+
+<!-- Ctrl+V: a screenshot or a link, drawn where the eye already is -->
+{#if pasted && !snapshotReading}
+ <PasteDialog
+ resolved={pasted}
+ busy={pasteBusy}
+ onconfirm={confirmPaste}
+ onclose={() => (pasted = null)}
+ />
+{/if}
+
+{#if openId && !snapshotReading}
+ <Modal title="Details" onclose={() => (openId = null)} width="640px">
+ <EntityDetails
+ entityId={openId}
+ bind:dirty
+ onclose={() => (openId = null)}
+ ondeleted={() => {
+ openId = null;
+ selected = null;
+ loadedFor = null;
+ load();
+ }}
+ />
+ </Modal>
+{/if}
+
+{#if snapshotOpen && snapshotReading}
+ <Modal title="Snapshot details" onclose={() => (snapshotOpen = null)} width="640px">
+ <SnapshotDetails
+ entity={snapshotOpen}
+ entities={catalogViews.activeView?.spec?.snapshot?.entities ?? []}
+ links={catalogViews.activeView?.spec?.snapshot?.links ?? []}
+ />
+ </Modal>
+{/if}
+
+<style>
+ .graph-tool {
+ display: flex;
+ flex-direction: column;
+ height: 100%;
+ min-height: 0;
+ }
+ /* The fullscreen backdrop is black by default, and the toolbar draws no background
+ of its own, so the page's is stated here. */
+ .graph-tool:fullscreen {
+ width: 100vw;
+ height: 100vh;
+ background: var(--bg-0);
+ color: var(--text-1);
+ }
+ .toolbar {
+ display: flex;
+ align-items: center;
+ gap: 10px;
+ padding: 8px 12px;
+ border-bottom: 1px solid var(--border);
+ flex-wrap: wrap;
+ }
+ .control {
+ display: flex;
+ align-items: center;
+ gap: 6px;
+ color: var(--text-3);
+ font-size: var(--fs-xs);
+ }
+ /* The controls sit in one row, so they read at one size: the search field
+ inheriting a browser default beside two small selects was the mismatch. */
+ .pick {
+ width: auto;
+ padding: 3px 6px;
+ font-size: var(--fs-xs);
+ }
+ .spacer {
+ flex: 1;
+ }
+ .find {
+ position: relative;
+ display: flex;
+ align-items: center;
+ color: var(--text-3);
+ }
+ /* The field's own magnifier, and only it: as a descendant rule this also took every
+ icon in the result list and stacked them all inside the input. */
+ .find > :global(svg) {
+ position: absolute;
+ left: 7px;
+ pointer-events: none;
+ }
+ .find input {
+ width: 170px;
+ padding: 3px 8px 3px 24px;
+ font-size: var(--fs-xs);
+ }
+ .find input::-webkit-search-cancel-button {
+ display: none;
+ }
+ .found {
+ position: absolute;
+ z-index: 3;
+ top: calc(100% + 4px);
+ left: 0;
+ width: 240px;
+ list-style: none;
+ margin: 0;
+ padding: 3px;
+ border: 1px solid var(--border);
+ border-radius: var(--r-md);
+ background: var(--bg-2);
+ box-shadow: var(--shadow-2);
+ }
+ .found button {
+ display: flex;
+ align-items: center;
+ gap: 6px;
+ width: 100%;
+ padding: 5px 6px;
+ border: 0;
+ border-radius: var(--r-sm);
+ background: none;
+ color: inherit;
+ text-align: left;
+ cursor: pointer;
+ }
+ .found button:hover {
+ background: var(--bg-3);
+ }
+ .found span {
+ flex: 1;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ }
+ .found em {
+ font-style: normal;
+ color: var(--text-3);
+ font-size: var(--fs-xs);
+ }
+ /* A row that is not on the canvas yet. Its own hue on the word alone: the row has
+ to read as a different act without becoming a second kind of list. */
+ .found .afar em {
+ color: var(--accent);
+ }
+ .count {
+ color: var(--text-3);
+ font-size: var(--fs-xs);
+ }
+ .count em {
+ font-style: normal;
+ color: var(--warn);
+ }
+ .isolated {
+ padding-left: 10px;
+ }
+ /* A measurement, so it is marked rather than coloured as a fault: whether three
+ citations on one account is a problem is the analyst's to say. */
+ .resting {
+ padding-left: 10px;
+ color: var(--text-2);
+ }
+ .resting em {
+ padding-left: 4px;
+ color: var(--accent);
+ }
+ /* A count that is also a question, and it keeps the register of the numbers beside
+ it rather than taking the look of a button: pressing it narrows the drawing, it
+ does not change the case. Nothing is reset here on purpose — the global rule
+ already strips a button back, and `font: inherit` written again would take the
+ size from the toolbar and print this one larger than the counts it sits among. */
+ button.resting:hover {
+ color: var(--text-1);
+ }
+ button.resting.on {
+ color: var(--accent);
+ }
+ /* What the folds are holding. A count in the register of the numbers beside it,
+ pressable like the independence one: a number naming a set the analyst cannot
+ reach is a number they have to work around. */
+ .folded {
+ padding-left: 10px;
+ color: var(--accent);
+ }
+ button.folded:hover {
+ color: var(--text-1);
+ }
+ .weight {
+ padding-left: 10px;
+ }
+ .weight.full {
+ color: var(--warn);
+ }
+ .check {
+ gap: 4px;
+ cursor: pointer;
+ }
+ .check input {
+ margin: 0;
+ accent-color: var(--accent);
+ cursor: pointer;
+ }
+ .placed {
+ color: var(--text-2);
+ }
+ .placed-here,
+ .made-here {
+ display: flex;
+ align-items: center;
+ gap: 5px;
+ }
+ /* A second action in a line of prose, so it reads as part of the sentence rather
+ than competing with Details and Expand above it. */
+ .as-link {
+ padding: 0;
+ border: 0;
+ background: none;
+ color: var(--accent);
+ font-size: inherit;
+ cursor: pointer;
+ }
+ .as-link:hover {
+ text-decoration: underline;
+ }
+ .zoom {
+ display: flex;
+ align-items: center;
+ gap: 3px;
+ margin-left: 8px;
+ }
+ /* Fitting the case back is a different act from stepping the zoom, so it sits
+ apart from the pair rather than crowded against the plus. */
+ .zoom .apart {
+ margin-left: 9px;
+ }
+ /* `icon-btn` was never a class this app defines: these four buttons fell back to
+ the bare button reset, which is why they had no room and no hover. */
+ .icon-btn {
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+ width: 26px;
+ height: 24px;
+ border-radius: var(--r-sm);
+ color: var(--text-2);
+ transition: background 0.12s var(--ease);
+ }
+ .icon-btn:hover {
+ background: var(--bg-2);
+ color: var(--text-1);
+ }
+ .level {
+ min-width: 42px;
+ text-align: center;
+ color: var(--text-3);
+ font-size: var(--fs-xs);
+ font-variant-numeric: tabular-nums;
+ }
+ .canvas-row {
+ position: relative;
+ flex: 1;
+ min-height: 0;
+ background: var(--bg-0);
+ }
+ .canvas {
+ position: absolute;
+ inset: 0;
+ cursor: grab;
+ touch-action: none;
+ }
+ /* On the whole case a node can be picked up, so the pointer says so; in a
+ neighbourhood it can only be chosen. */
+ .canvas.on-node {
+ cursor: pointer;
+ }
+ .canvas.on-node.arrangeable {
+ cursor: grab;
+ }
+ .canvas.panning {
+ cursor: grabbing;
+ }
+ .overlay {
+ position: absolute;
+ inset: 0;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ margin: 0;
+ color: var(--text-3);
+ pointer-events: none;
+ }
+ .tip {
+ position: absolute;
+ z-index: 2;
+ transform: translate(-50%, calc(-100% - 8px));
+ display: flex;
+ flex-direction: column;
+ gap: 1px;
+ max-width: 240px;
+ padding: 5px 8px;
+ border: 1px solid var(--border);
+ border-radius: var(--r-md);
+ background: var(--bg-2);
+ box-shadow: var(--shadow-1);
+ font-size: var(--fs-xs);
+ pointer-events: none;
+ }
+ .tip span {
+ color: var(--text-3);
+ }
+ .tip img {
+ width: 100%;
+ max-height: 120px;
+ object-fit: contain;
+ margin-bottom: 3px;
+ border-radius: var(--r-sm);
+ background: var(--bg-0);
+ }
+ .how {
+ color: var(--accent) !important;
+ }
+ .in-folder {
+ font-variant: small-caps;
+ }
+ /* Top left, the one corner the panel and the legend both leave alone. */
+ .drop-over {
+ position: absolute;
+ inset: 0;
+ z-index: 4;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ background: color-mix(in srgb, var(--bg-1) 78%, transparent);
+ pointer-events: none;
+ }
+ .drop-box {
+ display: flex;
+ flex-direction: column;
+ align-items: center;
+ gap: 8px;
+ padding: 20px 28px;
+ border: 1px dashed var(--accent);
+ border-radius: var(--r);
+ color: var(--text-2);
+ font-size: var(--fs-sm);
+ }
+ /* Under the toolbar rather than over the drawing's own strips: it says what the
+ whole picture is, where the focus strip says what one node is. */
+ .from-board {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ padding: 6px 12px;
+ border-bottom: 1px solid var(--border);
+ background: var(--accent-soft);
+ color: var(--text-2);
+ font-size: var(--fs-xs);
+ }
+ .from-board span {
+ flex: 1;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ color: var(--text-1);
+ }
+ .focus {
+ position: absolute;
+ top: 12px;
+ left: 12px;
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ max-width: calc(100% - 300px);
+ padding: 5px 6px 5px 10px;
+ border: 1px solid var(--border);
+ border-radius: var(--r-md);
+ background: var(--bg-1);
+ box-shadow: var(--shadow-2);
+ color: var(--text-2);
+ font-size: var(--fs-xs);
+ }
+ .focus .on {
+ display: flex;
+ align-items: center;
+ gap: 5px;
+ overflow: hidden;
+ white-space: nowrap;
+ color: var(--text-1);
+ }
+ .focus .reach {
+ display: flex;
+ gap: 2px;
+ }
+ .step {
+ padding: 2px 7px;
+ border: 1px solid var(--border);
+ border-radius: var(--r-sm);
+ background: none;
+ color: var(--text-3);
+ font-size: var(--fs-xs);
+ cursor: pointer;
+ }
+ .step:hover {
+ color: var(--text-1);
+ }
+ /* The set reach and the hiding read the same, because they are one answer: this
+ is how much of the case is currently being looked at. */
+ .step.set {
+ border-color: var(--accent);
+ background: var(--accent);
+ color: var(--bg-1);
+ }
+ .step.wide {
+ white-space: nowrap;
+ }
+ /* The walk gets the width the sentence needs, and wraps rather than truncating:
+ the sentence is the deliverable, and a truncated one states nothing. */
+ .walk {
+ max-width: calc(100% - 300px);
+ align-items: flex-start;
+ }
+ .walk .on {
+ padding-top: 3px;
+ color: var(--text-3);
+ white-space: nowrap;
+ }
+ .said-path {
+ display: flex;
+ flex-wrap: wrap;
+ align-items: center;
+ gap: 2px 5px;
+ margin: 0;
+ }
+ .said-path .node {
+ display: inline-flex;
+ align-items: center;
+ gap: 4px;
+ padding: 2px 5px;
+ border: 1px solid var(--border);
+ border-radius: var(--r-sm);
+ background: none;
+ color: var(--text-1);
+ font-size: inherit;
+ cursor: pointer;
+ }
+ .said-path .node:hover {
+ border-color: var(--accent);
+ }
+ /* One arrow, always forwards: an edge walked against its own direction is said in
+ the registry's inverse wording instead, so the sentence never has to be read
+ backwards. */
+ .said-path .verb::after {
+ content: ' →';
+ }
+ .said-path .verb {
+ color: var(--accent);
+ white-space: nowrap;
+ }
+ .ties {
+ align-items: center;
+ white-space: nowrap;
+ }
+ .ties .of {
+ padding: 0 2px;
+ color: var(--text-3);
+ }
+ .legend {
+ position: absolute;
+ left: 12px;
+ bottom: 12px;
+ display: flex;
+ flex-direction: column;
+ gap: 5px;
+ max-width: calc(100% - 24px);
+ padding: 7px 10px;
+ border: 1px solid var(--border);
+ border-radius: var(--r-md);
+ background: var(--bg-1);
+ color: var(--text-3);
+ font-size: var(--fs-xs);
+ }
+ .legend .row {
+ display: flex;
+ flex-wrap: wrap;
+ gap: 4px 12px;
+ }
+ /* The stroke key explains, it does not act, so it lets clicks through to the
+ canvas underneath the way the whole legend used to. */
+ .strokes {
+ padding-top: 5px;
+ border-top: 1px solid var(--border);
+ pointer-events: none;
+ }
+ .swatch-row {
+ display: flex;
+ align-items: center;
+ gap: 5px;
+ }
+ .families button {
+ padding: 1px 4px;
+ border: 0;
+ border-radius: var(--r-sm);
+ background: none;
+ color: inherit;
+ font-size: inherit;
+ cursor: pointer;
+ }
+ .families button:hover {
+ background: var(--bg-3);
+ }
+ /* A family left out reads as left out: the row dims and its own colour goes with
+ it, so the drawing and the legend cannot disagree about what is on screen. */
+ .families .off {
+ opacity: 0.45;
+ }
+ .families .off .swatch {
+ background: var(--text-3) !important;
+ }
+ .swatch {
+ width: 9px;
+ height: 9px;
+ border-radius: 50%;
+ }
+ .legend em {
+ font-style: normal;
+ color: var(--text-2);
+ }
+ .panel {
+ position: absolute;
+ top: 12px;
+ right: 12px;
+ width: 264px;
+ max-height: calc(100% - 24px);
+ overflow: auto;
+ padding: 12px;
+ border: 1px solid var(--border);
+ border-radius: var(--r-lg);
+ background: var(--bg-1);
+ box-shadow: var(--shadow-2);
+ }
+ .panel header {
+ display: flex;
+ align-items: center;
+ gap: 6px;
+ margin-bottom: 4px;
+ }
+ .panel header strong {
+ flex: 1;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ }
+ .meta {
+ margin: 0 0 8px;
+ color: var(--text-3);
+ font-size: var(--fs-xs);
+ }
+ .proposed {
+ margin-left: 6px;
+ font-style: normal;
+ color: var(--warn);
+ }
+ /* The two judgements an edge carries, on their own line above the acts: they are
+ what the analyst *says* about the edge, where the buttons below are what happens
+ to it. Wrapping, because a 264px panel does not hold a rating and a word side by
+ side in every language. */
+ .says {
+ display: flex;
+ flex-wrap: wrap;
+ align-items: center;
+ gap: 6px;
+ margin-bottom: 8px;
+ }
+ .rate {
+ color: var(--text-3);
+ }
+ .rate.set {
+ color: var(--text-1);
+ }
+ /* Ruled out is the one rating the drawing marks, so the control marks it too: the
+ line and the panel have to agree about which statements are dead. */
+ .rate.out {
+ color: var(--danger);
+ border-color: color-mix(in srgb, var(--danger) 45%, transparent);
+ background-color: color-mix(in srgb, var(--danger) 12%, transparent);
+ }
+ /* Sized to a word, because a word is what it holds: wide enough for "business
+ partner", narrow enough that nobody mistakes it for a notes box. */
+ .nature {
+ width: 11ch;
+ min-width: 0;
+ color: var(--text-3);
+ }
+ .nature.set {
+ color: var(--text-1);
+ }
+ /* Wrapping, because the row grew a fourth act and a fixed-width panel then squeezed
+ the last one until *Collapse (35)* read as *Collapse*. A button clipped to its
+ first word names a different act than the one it performs. */
+ .actions {
+ display: flex;
+ flex-wrap: wrap;
+ gap: 6px;
+ margin-bottom: 8px;
+ }
+ .neighbours {
+ list-style: none;
+ margin: 0;
+ padding: 0;
+ border-top: 1px solid var(--border);
+ }
+ .neighbours li {
+ border-bottom: 1px solid var(--border);
+ }
+ .link-row {
+ display: flex;
+ align-items: center;
+ gap: 6px;
+ width: 100%;
+ padding: 6px 2px;
+ border: 0;
+ background: none;
+ color: inherit;
+ text-align: left;
+ cursor: pointer;
+ }
+ .link-row:hover {
+ background: var(--bg-3);
+ }
+ .link-row span {
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ }
+ /* The rest of a group is asked for from inside the group, in the accent every
+ other "there is more" in this tool uses. */
+ .rest {
+ color: var(--accent);
+ font-size: var(--fs-xs);
+ }
+ /* The heading a group of connections reads under: what they say, then how many. */
+ .group {
+ display: flex;
+ align-items: baseline;
+ justify-content: space-between;
+ gap: 8px;
+ margin: 10px 0 0;
+ }
+ .group em {
+ font-style: normal;
+ color: var(--text-3);
+ font-size: var(--fs-xs);
+ }
+ .verb {
+ color: var(--text-3);
+ font-size: var(--fs-xs);
+ }
+ /* Said under the list it corrects, so the count and the list are read together. */
+ .more {
+ display: flex;
+ align-items: baseline;
+ gap: 6px;
+ margin-top: 10px;
+ }
+ .connecting {
+ display: flex;
+ align-items: center;
+ gap: 5px;
+ color: var(--accent);
+ }
+ /* Both float over the canvas and read the same way: a title, then what can be
+ chosen. The menu opens from the pointer, the offer from the node it landed on. */
+ .menu,
+ .offer {
+ position: absolute;
+ z-index: 5;
+ transform: translate(-50%, 8px);
+ min-width: 180px;
+ padding: 8px;
+ border: 1px solid var(--border);
+ border-radius: var(--r-md);
+ background: var(--bg-2);
+ box-shadow: var(--shadow-2);
+ }
+ .menu {
+ min-width: 170px;
+ padding: 6px;
+ border: 1px solid var(--border);
+ border-radius: var(--r-md);
+ background: var(--bg-2);
+ box-shadow: var(--shadow-2);
+ }
+ .menu ul,
+ .offer ul {
+ list-style: none;
+ margin: 0 0 4px;
+ padding: 0;
+ }
+ .menu .meta {
+ margin: 2px 6px 5px;
+ }
+ /* The registry's heading over the readings it heads, so a pointer is not read as
+ a statement. Set apart from the list above it rather than boxed. */
+ .offer .heading {
+ margin: 7px 6px 3px;
+ color: var(--text-3);
+ font-size: var(--fs-xs);
+ }
+ .menu button,
+ .offer button {
+ display: block;
+ width: 100%;
+ padding: 5px 6px;
+ border: 0;
+ border-radius: var(--r-sm);
+ background: none;
+ color: inherit;
+ text-align: left;
+ cursor: pointer;
+ }
+ .menu li button:hover:not(:disabled),
+ .offer li button:hover {
+ background: var(--bg-3);
+ }
+ .menu li button:disabled {
+ color: var(--text-3);
+ cursor: default;
+ }
+ .said {
+ position: absolute;
+ left: 50%;
+ bottom: 14px;
+ transform: translateX(-50%);
+ margin: 0;
+ padding: 5px 10px;
+ border: 1px solid var(--border);
+ border-radius: var(--r-md);
+ background: var(--bg-2);
+ color: var(--text-2);
+ font-size: var(--fs-xs);
+ }
+</style>
diff --git a/frontend/src/tools/Graph.test.js b/frontend/src/tools/Graph.test.js
new file mode 100644
index 0000000..23d0781
--- /dev/null
+++ b/frontend/src/tools/Graph.test.js
@@ -0,0 +1,2074 @@
+import { describe, expect, it } from 'vitest';
+import { readFileSync } from 'node:fs';
+
+const source = readFileSync(new URL('./Graph.svelte', import.meta.url), 'utf8');
+const layout = readFileSync(new URL('../lib/graph.js', import.meta.url), 'utf8');
+const css = readFileSync(new URL('../app.css', import.meta.url), 'utf8');
+
+describe('the graph answers what the table cannot', () => {
+ it('opens on the whole case, not on a root to expand from', () => {
+ // A case is a subject before it is a set of statements: a conflict followed
+ // over months has no single node to start at. Expansion is the drill-down.
+ expect(source).toContain('let root = $state(null)');
+ expect(source).toContain("if (root) return ['/graph/neighborhood'");
+ expect(source).toContain('Whole case');
+ });
+
+ it('reads the lenses and orderings from the server, keeping no copy', () => {
+ expect(source).toContain("api.get('/api/cases/graph-lenses')");
+ expect(source).not.toMatch(/const LENSES\s*=/);
+ });
+
+ it('says how much of the case it left out instead of presenting a slice', () => {
+ // Counted over the drawing and stated against the case's own total, so a first
+ // draw says what it is a part of rather than passing a slice off as the whole.
+ expect(source).toContain('{nodes.length} of {payload.total}');
+ expect(source).toContain('payload.truncated');
+ });
+
+ it('shows what nobody has connected, which no table column reports', () => {
+ expect(source).toContain('payload.isolated');
+ expect(source).toContain('unconnected');
+ });
+});
+
+describe('the interaction', () => {
+ it('fades the far context instead of hiding it, so selection keeps your place', () => {
+ expect(source).toContain('const focused = $derived.by');
+ expect(source).toContain('circle.opacity(isNear ? 1 : 0.16)');
+ // Edges fade with the nodes rather than out: the shape of the rest of the case
+ // is what keeps your place, and it is in the lines as much as in the dots.
+ expect(source).toContain('faded ? 0.12 : 0.45');
+ });
+
+ it('fades on a selection only, never under a moving mouse', () => {
+ // Hover restyling the whole case made the picture strobe, and left Escape
+ // looking broken: the highlight stayed while the pointer sat on the node.
+ expect(source).toMatch(/const lit = hovered \?\? selected/);
+ expect(source).toMatch(/if \(!selected \|\| selected === root\) return null/);
+ });
+
+ it('does not grey out the hops an expansion was asked for', () => {
+ // Asking for three hops and getting two of them greyed contradicts the
+ // question, so the root of a neighbourhood never narrows its own view.
+ expect(source).toContain('selected === root');
+ });
+
+ it('puts the cost of a click on the node before it is paid', () => {
+ expect(source).toContain('Around this ({chosen.degree})');
+ expect(source).toContain('connection{tip.degree === 1');
+ });
+
+ it('words the act that replaces the case apart from the act that grows it', () => {
+ // Both were called expanding, in two surfaces that look alike, for opposite
+ // acts: "Around this" swaps the case for one node's hops, expanding adds a
+ // node's missing neighbours to the case already drawn.
+ expect(source).toContain('Around this ({chosen.degree})');
+ expect(source).toContain('Expand {away} more connection');
+ expect(source).toContain('function focusOn(id)');
+ expect(source).toContain('function expandNode(id)');
+ });
+
+ it('groups a node’s connections by what they say, biggest group first', () => {
+ // Forty rows with "posted" written on twelve of them say less than one heading
+ // that says twelve. What a node mostly is, is the first thing to say about it.
+ expect(source).toContain('const neighbourGroups = $derived.by');
+ expect(source).toMatch(/b\.rows\.length - a\.rows\.length \|\| a\.reading\.localeCompare/);
+ expect(source).toContain('<span class="verb">{group.reading}</span>');
+ expect(source).toContain('<em>{group.rows.length}</em>');
+ });
+
+ it('lists the first few of a group and asks before listing forty', () => {
+ expect(source).toContain('const GROUP_ROWS = 8');
+ expect(source).toContain('group.rows.slice(0, GROUP_ROWS)');
+ expect(source).toContain('Show all {group.rows.length}');
+ expect(source).toContain('!all && group.rows.length > GROUP_ROWS');
+ });
+
+ it('forgets which groups were unfolded when another node is read', () => {
+ // How one node is being read now, not a setting about how nodes are read: the
+ // next one would otherwise open half-unfolded on whichever verbs it shares.
+ expect(source).toMatch(/let allOf = \$state\(\[\]\);\s*\$effect\(\(\) => \{\s*void selected;\s*allOf = \[\];/);
+ });
+
+ it('lights the edge a row stands for, since they are the same connection', () => {
+ expect(source).toContain('onmouseenter={() => (hoveredLink = row.link.id)}');
+ expect(source).toContain('onmouseleave={() => (hoveredLink = null)}');
+ // Reachable by keyboard too: the panel is the way into a canvas without a mouse.
+ expect(source).toContain('onfocus={() => (hoveredLink = row.link.id)}');
+ });
+
+ it('narrows to the one edge singled out, or the row answers with all of them', () => {
+ // Selecting a node already lights every edge it has and writes every verb, so
+ // pointing at one row lit nothing new. One edge under the pointer or the panel
+ // now stands alone, which is the question the rows exist to answer.
+ expect(source).toContain('const singled = Boolean(chosenLink || hoveredLink)');
+ expect(source).toMatch(
+ /: singled\s*\? picked\s*: Boolean\(lit && \(link\.from === lit \|\| link\.to === lit\)\)/,
+ );
+ });
+
+ it('follows a connection without lurching the view at every step', () => {
+ // The layout puts linked nodes next to each other, so the neighbour is usually
+ // already on screen — and recentring on each one makes the drawing move under
+ // the reading. A running search survives it: following is not answering it.
+ expect(source).toContain('function followTo(id)');
+ expect(source).toMatch(/selected = id;\s*if \(!inSight\(id\)\) bringUnderEye\(id\);/);
+ expect(source).toContain('function inSight(id)');
+ // The same row means whatever gesture is armed: it names the far end of a
+ // question, steps a walk, or reads the neighbour. An armed gesture owns every way
+ // of pointing at a node, or the keyboard is left out of it.
+ expect(source).toContain('asking\n ? wayTo(row.entity.id)');
+ expect(source).toContain(': followTo(row.entity.id)}');
+ });
+
+ it('states the connections the drawing does not hold, which the list cannot', () => {
+ // The list is built from the edges on screen, so a node with forty connections
+ // and three of them drawn read as a node with three.
+ expect(source).toContain('{away} more not drawn');
+ // The act itself is the switch in the row above, said once.
+ expect(source).toContain('onclick={() => toggleAround(chosen.id)}');
+ // And the empty state never claims nothing connects while something does.
+ expect(source).toContain('{:else if !neighbours.length}');
+ });
+
+ it('counts what is missing over the links the drawing holds', () => {
+ // A loop is dropped by the canvas and kept by the view, so counting off the
+ // drawable set left a node reporting one missing connection for ever, under a
+ // control no expansion could ever satisfy. The tally matches the server's, which
+ // counts one row per end — so a loop is two on both sides. Counted over the drawn
+ // links rather than the sent ones, so a fold shows up in the number.
+ expect(source).toMatch(/const offScreen = \$derived\.by[\s\S]{0,900}?for \(const link of links\)/);
+ expect(source).toContain('for (const end of [link.from, link.to]) held.set(end');
+ });
+
+ it('does not offer an expansion in a view whose read takes none', () => {
+ // A neighbourhood is read one hop further; it sends no `expand`, so "Open" there
+ // was a live control that could only appear to do nothing. The count still gets
+ // said, with the reason it cannot be pressed.
+ expect(source).toContain('{away} more, further than {hops} hop{hops === 1 ? \'\' : \'s\'}');
+ expect(source).toContain('disabled={!away || Boolean(root)}');
+ });
+
+ it('pans from the empty space, not only from a node', () => {
+ // The bug this guards: a draggable Konva group only drags where the pointer
+ // hits one of its own shapes, so the empty space — most of a graph — did
+ // nothing at all and the canvas could only be moved by grabbing a node.
+ expect(source).not.toContain('draggable: true');
+ expect(source).toContain('onpointerdown={onPointerDown}');
+ expect(source).toContain('function onPointerMove');
+ expect(source).toContain('DRAG_SLOP');
+ // Neither a pan nor a node's own drag may also select.
+ expect(source).toContain('if (dragged || arranged) return;');
+ });
+
+ it('zooms at the pointer, fits back and says where it is', () => {
+ expect(source).toContain('function onWheel');
+ expect(source).toContain('stage?.getPointerPosition()');
+ expect(source).toContain('function fitView');
+ expect(source).toContain('{Math.round(zoom * 100)}%');
+ });
+
+ it('clamps the zoom so a case cannot be lost off-screen', () => {
+ expect(source).toContain('ZOOM_MIN');
+ expect(source).toContain('ZOOM_MAX');
+ expect(source).toContain('Math.min(ZOOM_MAX, Math.max(ZOOM_MIN');
+ });
+
+ it('gives the whole screen to the drawing, toolbar included', () => {
+ // The tool element, not the canvas: full screen without the toolbar is a picture
+ // that can no longer be steered. The canvas is measured with `bind:clientWidth`,
+ // so the stage follows the new size on its own.
+ expect(source).toContain('<div class="graph-tool" bind:this={toolElement}>');
+ expect(source).toContain('await toolElement.requestFullscreen()');
+ expect(source).toContain('await document.exitFullscreen()');
+ expect(source).toContain("fullscreen ? 'Exit full screen' : 'Full screen'");
+ // Esc leaves it without telling us, so the flag is read back off the document.
+ expect(source).toContain('fullscreen = document.fullscreenElement === toolElement');
+ expect(source).toContain(".addEventListener('fullscreenchange', changed)");
+ expect(source).toContain('.graph-tool:fullscreen');
+ });
+
+ it('reaches the same actions from the keyboard as from the canvas', () => {
+ expect(source).toContain('onkeydown={onKey}');
+ expect(source).toContain("event.key === 'Escape'");
+ expect(source).toContain("event.key === '0'");
+ });
+
+ it('clears the hover with the selection, so Escape leaves nothing lit', () => {
+ // Shallowest thing first: the search, the handful, the edge, the hiding, then
+ // the selection.
+ expect(source).toMatch(
+ /else if \(find\) find = '';[\s\S]{0,600}?else if \(selected\) selected = null;\s*hovered = null;\s*tip = null;/,
+ );
+ });
+
+ it('leaves the keys of a field being typed into alone', () => {
+ // Without this, naming a node "0" fits the view and an arrow key moves the
+ // case instead of the text cursor. Escape still reaches the field, because
+ // leaving it is what Escape is for there.
+ expect(source).toContain('INPUT|TEXTAREA|SELECT');
+ expect(source).toContain('if (typing) return;');
+ });
+
+ it('names the few busiest nodes at any zoom, since that is the question', () => {
+ // A wide view of unnamed dots answers "what sits at the centre of this case"
+ // only as a shape. Six, because labels are held at a fixed size on screen.
+ expect(source).toContain('const hubs = $derived.by');
+ expect(source).toContain('hubs.has(id)');
+ expect(source).toContain('ranked.slice(0, 6)');
+ });
+
+ it('does not repeat a card in a tooltip over it', () => {
+ expect(source).toContain('if (named) return;');
+ expect(source).toContain("answerTo(card.findOne('.bg'), data, { named: true, moves: card })");
+ });
+
+ it('offers the ordering only when the case is too large to draw whole', () => {
+ // It picks which nodes survive the cut, and nothing else: on a case that fits
+ // it changed nothing on screen and read as a sort order.
+ expect(source).toContain('{:else if payload?.truncated}');
+ });
+
+ it('finds a node by name, since a canvas has no keyboard path into it', () => {
+ // Also the only practical way to a particular entity once a case is drawn at
+ // a few hundred nodes: hunting one by eye does not work.
+ expect(source).toContain("aria-label=\"Find a node\"");
+ expect(source).toContain('function jumpTo');
+ expect(source).toContain('a.degree'); // matches ranked most-connected first
+ });
+
+ it('searches the case, not the picture of it', () => {
+ // A view is bounded, so on a case larger than the budget most of it is not on
+ // screen — and a search reading only the drawing answered "no such entity" for
+ // entities the case plainly holds. Nothing told "not in the case" from "not in
+ // this picture", which is the worse of the two silences.
+ expect(source).toContain('let elsewhere = $state([])');
+ expect(source).toContain('buildCatalogQuery(caseId, { query: term, limit: 12 })');
+ // The narrowing is ignored on purpose, as `expand` already ignores it.
+ expect(source).not.toMatch(/buildCatalogQuery\([^)]*pickFolder/);
+ });
+
+ it('lights what a typed name matches instead of removing what it does not', () => {
+ // Removing the rest takes the shape with it, and the shape is what the analyst
+ // is holding their place with. Dimming answers the same question and keeps it.
+ expect(source).toContain('const found = $derived.by');
+ expect(source).toContain('const matched = found.has(id)');
+ expect(source).toMatch(/isSelected \|\| id === hovered \|\| matched\s*\? colours\.accent/);
+ });
+
+ it('lights every match, not only the eight the list can hold', () => {
+ // The count over the drawing states one number and the drawing has to show it:
+ // lighting eight of twenty-three answers a different question from the one
+ // written above it. The cap belongs to the dropdown, which is a handful to pick
+ // from rather than a reading of the case.
+ expect(source).toMatch(/const found = \$derived\.by[\s\S]{0,420}?hit\.add\(node\.id\)/);
+ expect(source).not.toMatch(/const found = \$derived\.by[\s\S]{0,420}?slice\(0, 8\)/);
+ expect(source).toMatch(/const matches = \$derived\.by[\s\S]{0,600}?slice\(0, 8\)/);
+ });
+
+ it('lights an edge only when both of its ends match', () => {
+ // An edge with one end in the answer joins the answer to something else, which
+ // is a statement about the case the search did not make.
+ expect(source).toContain('near && !(near.has(link.from) && near.has(link.to))');
+ });
+
+ it('narrows the picture from one question at a time, the latest asked', () => {
+ // Typing a name while a node was selected composited two fades over each other:
+ // not a third reading, an unreadable one. A search outranks the selection, which
+ // still rings its node and opens its panel — what a click is actually for.
+ expect(source).toMatch(
+ /if \(found\.size\) return found;\s*if \(singled\) return singled;\s*return focused;\s*\}\);/,
+ );
+ expect(source).toContain('const near = narrowing;');
+ });
+
+ it('counts the matches over the drawing, which is not the case', () => {
+ // "No match drawn" and "no such entity" are different answers, and the second
+ // one is the list's to give: it asks the catalog rather than the picture.
+ expect(source).toContain('no match drawn');
+ expect(source).toContain("{found.size} match{found.size === 1 ? '' : 'es'}");
+ expect(source).toContain('{#if find.trim()}');
+ });
+
+ it('narrows without moving anything, so the shape survives the typing', () => {
+ // The layout is derived from the nodes, so a search that filtered them would
+ // re-run the relaxation and slide the whole case under the letters being typed.
+ expect(source).toMatch(/void find;/);
+ expect(source).not.toMatch(/nodes\.filter\([^)]*\)\s*,\s*mode/);
+ });
+
+ it('puts the list away when the case is pressed, keeping what is lit', () => {
+ // The list is a panel over the answer now that the typing lights the drawing:
+ // every click that follows a search lands under it. Pressing the case puts it
+ // away without giving the search up, and the field asks for it back.
+ expect(source).toContain('let listing = $state(true)');
+ expect(source).toContain('{#if listing && (matches.length || elsewhere.length)}');
+ expect(source).toMatch(/function onPointerDown\(event\) \{[\s\S]{0,200}?listing = false;/);
+ expect(source).toContain('onfocus={() => (listing = true)}');
+ expect(source).toContain('oninput={() => (listing = true)}');
+ });
+
+ it('brings a found entity into the picture through the one mechanism for it', () => {
+ // `expand` keeps the named node whatever the ranking and the filters would have
+ // done with it, and brings what touches it: an entity alone in a picture about
+ // connections says nothing.
+ expect(source).toContain('function bringIn(entity)');
+ expect(source).toMatch(/bringing = id;[\s\S]{0,240}if \(!expanded\.includes\(id\)\) expanded = \[/);
+ // And a name typed outranks a removal made earlier, or the case answers the search
+ // with the same unchanged picture that removal left.
+ expect(source).toMatch(/function bringIn[\s\S]{0,700}backIn\(\[id\]\)/);
+ expect(source).toContain('function settleArrival()');
+ expect(source).toContain('requestAnimationFrame(() => jumpTo(id))');
+ });
+
+ it('refuses a name this reading does not draw before asking the case', () => {
+ // A lens is the one narrowing a name cannot outrank. Asked anyway, the case would
+ // answer with an unchanged picture and the sentence would blame the budget for a
+ // refusal the reading made.
+ expect(source).toContain("if (lensHides.includes(type))");
+ expect(source).toContain("say('Not drawn in this lens. My work draws it.')");
+ // And the row says it before it is pressed, rather than offering an act that
+ // cannot land.
+ expect(source).toContain("{filed ? 'in My work' : 'bring in'}");
+ });
+
+ it('says so when the budget kept the entity out rather than staying silent', () => {
+ expect(source).toContain("say('That one did not fit in the view.");
+ });
+
+ it('asks the case once a name is typed, not once a letter is', () => {
+ expect(source).toContain('FIND_AFTER');
+ expect(source).toContain('FIND_MIN');
+ expect(source).toContain('return () => clearTimeout(timer)');
+ // A later keystroke owns the field, so a slow answer never overwrites a newer one.
+ expect(source).toContain('run !== lookupRun');
+ expect(source).toContain('caseState.current?.id !== caseId');
+ expect(source).toContain('term !== find.trim()');
+ });
+
+ it('offers nothing to bring in from a neighbourhood, which takes no expansion', () => {
+ expect(source).toContain('if (!cid || root || term.length < FIND_MIN)');
+ });
+
+ it('keeps the zoom when it jumps, so finding does not lose the view', () => {
+ expect(source).toContain('const scale = group.scaleX()');
+ expect(source).toContain('width / 2 - spot.x * scale');
+ });
+
+ it('declutters labels by zoom, keeping the one in hand and its neighbours named', () => {
+ // A selection is read as a sentence, and an unnamed neighbour cannot be read.
+ expect(source).toContain('LABEL_SCALE');
+ expect(source).toMatch(
+ /const named =\s*isSelected \|\| id === hovered \|\| Boolean\(near\) \|\| hubs\.has\(id\) \|\| scale >= LABEL_SCALE/,
+ );
+ });
+
+ it('restyles a selection without rebuilding, so panning survives a click', () => {
+ // A rebuild would reset the transform and throw the view back to the start
+ // every time a node was picked.
+ expect(source).toContain('function restyle()');
+ expect(source).toContain('function rebuild()');
+ expect(source).toMatch(/void selected;\s*void hovered;[\s\S]{0,1600}?untrack\(restyle\);/);
+ });
+
+ it('keeps the drawing effects from tracking what they draw', () => {
+ // The teleport this guards: `rebuild` ends in `restyle`, which reads the
+ // selection — so the rebuild effect tracked hover, and every mouseover threw
+ // the view back to its starting transform.
+ expect(source).toContain("import { tick, untrack } from 'svelte'");
+ expect(source).toMatch(/void height;\s*untrack\(rebuild\);/);
+ });
+
+ it('keeps where the analyst had panned to across a rebuild', () => {
+ expect(source).toContain('const keep = group && !resetView');
+ expect(source).toContain('group.position({ x: keep.x, y: keep.y })');
+ });
+});
+
+describe('the focus is locked, sized, and walked back out of', () => {
+ it('sizes the focus rather than fixing it at one hop', () => {
+ // One hop answers "what touches this". Two answers "what does this sit
+ // between", which is the shape a click could never show.
+ expect(source).toContain('let focusHops = $state(1)');
+ expect(source).toContain('return ringsAround(edges, selected, focusHops)');
+ });
+
+ it('walks the edges already drawn, so a wider reach owes no read', () => {
+ // The second and third rings are in the payload already. Asking the case for
+ // them would make a highlight cost a round trip, and would let the fade claim
+ // a connection the drawing cannot show.
+ expect(source).toContain('ringsAround(edges');
+ expect(source).not.toMatch(/focusHops[^\n]*\/graph/);
+ expect(layout).toContain('export function ringsAround');
+ });
+
+ it('offers the reach on the keys beside the one that fits the case', () => {
+ expect(source).toMatch(/event\.key === '1' \|\| event\.key === '2' \|\| event\.key === '3'/);
+ expect(source).toContain('setFocusHops(Number(event.key))');
+ // Under the guard that gives a field being typed into its own keys, or naming a
+ // node "2" would resize the focus instead of moving the cursor.
+ expect(source.indexOf('if (typing) return;')).toBeLessThan(
+ source.indexOf('setFocusHops(Number(event.key))'),
+ );
+ });
+
+ it('does nothing with the reach keys when nothing is focused', () => {
+ expect(source).toMatch(/function setFocusHops\(count\) \{\s*if \(!focused \|\| focusHops === count\) return;/);
+ });
+
+ it('keeps the reach across a change of node, and drops it with the focus', () => {
+ // How far you are looking is a stance, not a property of what you clicked.
+ expect(source).not.toMatch(/selected = id;\s*focusHops = 1/);
+ expect(source).toMatch(/if \(selected\) return;[\s\S]{0,200}focusHops = 1;/);
+ });
+
+ it('hides rather than dims once the subset is what is being worked on', () => {
+ expect(source).toContain('let onlyThis = $state(false)');
+ expect(source).toContain(
+ 'const hiding = $derived(onlyThis && !tracing && !found.size && !singling ? focused : null)',
+ );
+ expect(source).toContain('const drawn = !hiding || hiding.has(id)');
+ expect(source).toContain('circle.visible(drawn && !carded)');
+ });
+
+ it('lets a search outrank the hiding, as it outranks the fade', () => {
+ // Hiding everything outside the matches strands them: an edge needs both ends,
+ // so the answer to a search would have been a scatter of unconnected dots.
+ expect(source).toContain('onlyThis && !tracing && !found.size');
+ });
+
+ it('drops an edge whose far end is off the screen', () => {
+ expect(source).toContain('if (hiding && !(hiding.has(link.from) && hiding.has(link.to)))');
+ });
+
+ it('takes the annotations off a hidden node instead of painting over them', () => {
+ // A glyph or a pin mark left drawn is the tell that a node was removed by
+ // opacity rather than by being left out.
+ expect(source).toContain('styleGlyph(entry, data, { scale, carded, isNear, drawn })');
+ expect(source).toContain('marked: drawn && isNear && marked.has(id)');
+ expect(source).toContain('inHand: drawn && isNear && inHand.has(id)');
+ expect(source).toMatch(/if \(!carded \|\| !drawn\) \{/);
+ expect(source).toContain('label.visible(drawn && !carded');
+ });
+
+ it('refuses a connection landed on a node that is not on screen', () => {
+ expect(source).toContain('const landable = over && (!hiding || hiding.has(over))');
+ });
+
+ it('never touches the nodes, so switching back puts the case where it was', () => {
+ // `placed` is derived from `arrange`: filtering the list would re-run the
+ // relaxation and give every surviving node a new resting place.
+ expect(source).not.toMatch(/arrange\(\s*nodes\.filter/);
+ expect(source).toContain('void onlyThis;');
+ expect(source).toContain('beforeOnly = { x: group.x(), y: group.y(), scale: group.scaleX() }');
+ expect(source).toMatch(/function letGoOnly\(\)[\s\S]{0,300}zoom = beforeOnly\.scale;/);
+ });
+
+ it('frames the subset when it is asked for and when its size changes', () => {
+ expect(source).toMatch(/function frameOnly\(\)[\s\S]{0,200}placed\.filter\(\(node\) => focused\.has\(node\.id\)\)/);
+ expect(source).toMatch(/focusHops = count;\s*if \(onlyThis\) frameOnly\(\);/);
+ });
+
+ it('does not reframe on every step of a walk', () => {
+ // A view that jumps on each click is the lurch `followTo` exists to avoid.
+ expect(source).toMatch(/function followTo\(id\) \{\s*selected = id;\s*if \(!inSight\(id\)\) bringUnderEye\(id\);\s*\}/);
+ });
+
+ it('gives the case back before it gives the node up', () => {
+ expect(source).toMatch(/else if \(chosenLink\) chosenLink = null;[\s\S]{0,300}else if \(onlyThis\) letGoOnly\(\);\s*else if \(selected\) selected = null;/);
+ });
+
+ it('takes the unconnected park off a picture of what one node reaches', () => {
+ expect(source).toContain('tray?.visible(!hiding)');
+ expect(source).toContain('caption?.visible(!hiding)');
+ });
+
+ it('keeps no history of what was clicked, which was never a path', () => {
+ // A breadcrumb strip was built here and removed: it recorded every selection,
+ // and a selection arrives from a search, a canvas click or a bring-in as readily
+ // as from a connection followed. Chevrons between its labels claimed an
+ // adjacency nothing guaranteed, which in a tool whose whole grammar is "an edge
+ // is a statement" is a picture asserting what the case does not say. Walking a
+ // path is now a gesture that can only step along an edge.
+ expect(source).not.toContain('trail');
+ expect(source).not.toContain('crumb');
+ });
+
+ it('says what the focus is on, and never on the root of a neighbourhood', () => {
+ expect(source).toContain('{:else if focused && chosen}');
+ expect(source).toContain('Only this');
+ expect(source).toContain('aria-pressed={focusHops === step}');
+ });
+});
+
+describe('a path is walked, not remembered', () => {
+ it('records the edge arrived by, not only the node arrived at', () => {
+ // Two nodes joined by `posted` and by `mentions` are two different findings, and
+ // a path kept as nodes alone cannot tell them apart when both edges exist.
+ expect(source).toContain('let path = $state([])');
+ expect(source).toContain('path = [...path, { id, via: link.id }]');
+ expect(source).toContain('new Set(path.map((step) => step.via).filter(Boolean))');
+ });
+
+ it('is an armed gesture, so no click can wander into it', () => {
+ // Unarmed, a click on a non-neighbour has only bad answers: ignore it, read the
+ // node and leave a half-path beside it, or break six hops on a slip.
+ expect(source).toContain('let tracing = $state(false)');
+ expect(source).toContain('Walk by hand');
+ expect(source).toMatch(/if \(tracing\) \{\s*stepTo\(data\.id\);\s*return;\s*\}/);
+ });
+
+ it('asks the case for a route by naming two nodes', () => {
+ // The common question, and the one the tool existed without. Armed like a
+ // connection: the act is named, then the click that follows means that act.
+ expect(source).toContain('let asking = $state(null)');
+ expect(source).toContain('function askWayFrom(id)');
+ expect(source).toContain('Path to…');
+ expect(source).toMatch(/if \(asking\) \{\s*wayTo\(data\.id\);\s*return;\s*\}/);
+ });
+
+ it('takes the far end from a name too, since it is often not drawn', () => {
+ // The view holds five hundred nodes of a thousand, and "are these two connected"
+ // is asked about things far enough apart to be off screen. A node that cannot be
+ // clicked would otherwise be a node that cannot be asked about.
+ expect(source).toMatch(/function jumpTo\(id\) \{[\s\S]{0,600}if \(asking\) \{\s*wayTo\(id\);/);
+ });
+
+ it('takes a connection target from Find, which is the keyboard way into the canvas', () => {
+ expect(source).toMatch(
+ /function jumpTo\(id\) \{[\s\S]{0,500}if \(drawing\) \{[\s\S]{0,120}landOn\(id\);/,
+ );
+ });
+
+ it('dims nothing while the question waits, unlike a connection', () => {
+ // A relation has a vocabulary that rules a pair out before the press. A route has
+ // none: the case is searched, not the drawing, so a node with no route on screen
+ // may be two hops away in the case. Greying it would be the picture asserting
+ // what only the server can know.
+ //
+ // The narrowing has to be *dropped*, not merely left unset: the question is armed
+ // on a selected node, so without this the focus fade stays on and the drawing
+ // says "only these five can be pressed" over a strip that says click anything.
+ // The first version of this test asserted the absence of a dim keyed on `asking`,
+ // which was true of code that had the defect.
+ expect(source).toMatch(/const narrowing = \$derived\.by[\s\S]{0,600}if \(asking\) return null;/);
+ expect(source).toContain('within ${body.searched} hops');
+ });
+
+ it('lights every route that tied for shortest, and reads one of them', () => {
+ // Two accounts reaching the same place through two different sources is what
+ // independence looks like, and an answer that drew one would hide the finding.
+ expect(source).toContain('let routes = $state([])');
+ expect(source).toContain('new Set(routes.flatMap((route) => route.links))');
+ expect(source).toContain('new Set(routes.flatMap((route) => route.nodes))');
+ expect(source).toContain('{routeAt + 1} / {routes.length}');
+ expect(source).toContain('function readRoute(index)');
+ });
+
+ it('leaves the answer behind when a step is taken by hand', () => {
+ // The tied routes were the reply to one question; stepping asks a different one.
+ expect(source).toMatch(/function stepTo\(id\) \{[\s\S]{0,200}routes = \[\];/);
+ });
+
+ it('gives an armed question up before a route already drawn', () => {
+ expect(source).toMatch(
+ /else if \(asking\) asking = null;[\s\S]{0,300}else if \(tracing\) traceStop\(\);/,
+ );
+ });
+
+ it('offers both ways to fill a path where a node’s acts are named', () => {
+ expect(source).toContain('chose(askWayFrom)');
+ expect(source).toContain('chose(traceFrom)');
+ });
+
+ it('lights what the walk can reach before the click, as the connection does', () => {
+ expect(source).toMatch(/const nextSteps = \$derived\.by/);
+ expect(source).toContain('if (!far || pathIds.has(far) || steps.has(far)) continue');
+ // The offered steps keep full strength: a walk whose choices were dimmed into
+ // the context is a walk taken blind.
+ expect(source).toContain('if (tracing) return new Set([...pathIds, ...nextSteps.keys()])');
+ });
+
+ it('outranks the search and the focus, being the latest question asked', () => {
+ expect(source).toMatch(
+ /if \(tracing\) return new Set[\s\S]{0,120}if \(found\.size\) return found;\s*if \(singled\) return singled;\s*return focused;/,
+ );
+ // And the hiding stands down, since its subset is not what is being asked about.
+ expect(source).toContain('onlyThis && !tracing && !found.size');
+ });
+
+ it('walks back onto a step already taken instead of looping through it', () => {
+ // A route that visits a node twice is not a path, so the same click truncates.
+ expect(source).toContain('const back = path.findIndex((step) => step.id === id)');
+ expect(source).toContain('path = path.slice(0, back + 1)');
+ });
+
+ it('gives the walk up whole, as a half-drawn relation is given up', () => {
+ expect(source).toMatch(/else if \(tracing\) traceStop\(\);\s*else if \(find\) find = '';/);
+ expect(source).toMatch(/function traceStop\(\) \{\s*tracing = false;\s*path = \[\];/);
+ });
+
+ it('tells a path edge apart by its stroke, not by its colour', () => {
+ // A graph that reaches a report gets printed, and a printed graph is grey. Every
+ // free hue is spoken for anyway: the families own the palette, accent is the
+ // selection, and blue is the actor family.
+ expect(source).toContain('? style.width + 3');
+ expect(source).toContain('arrow.dash(onPath ? []');
+ expect(css).not.toMatch(/--graph-path/);
+ });
+
+ it('tells a step taken apart from a step offered', () => {
+ expect(source).toContain('const stepped = tracing && pathIds.has(id)');
+ expect(source).toContain('const offered = tracing && nextSteps.has(id)');
+ expect(source).toMatch(/stepped \? 3\.6 : offered \? 2 :/);
+ });
+
+ it('reads the path as a sentence, in the direction the case states it', () => {
+ // A drawing says these are joined; a sentence says what the joining is, and an
+ // account that posted a video is not a video that mentions an account.
+ expect(source).toContain('const sentence = $derived.by');
+ // Every step reads forwards, in the order it was walked: an edge crossed against
+ // its arrow takes the registry's inverse wording, exactly as the node panel does.
+ // Writing the plain verb with a reversed arrow made a true sentence unreadable —
+ // "A <- made from B <- made from C" has to be walked backwards to be understood.
+ expect(source).toContain("relationReading(link.type, forward ? 'out' : 'in')");
+ expect(source).toContain('const forward = link ? link.from === path[index - 1].id : true');
+ });
+
+ it('stores nothing, because a stored path goes false in silence', () => {
+ // Its edges can be deleted. What gets kept is the sentence, in a note, written
+ // by a person — and if a path is ever saved it will be the question rather than
+ // the answer, recomputed on open.
+ expect(source).not.toMatch(/api\.(post|put|patch)\([^)]*path/i);
+ expect(source).not.toMatch(/localStorage[\s\S]{0,40}path/);
+ });
+
+ it('walks the drawn edges, so it can claim no connection the picture cannot show', () => {
+ expect(source).toMatch(/const nextSteps = \$derived\.by[\s\S]{0,300}for \(const link of edges\)/);
+ });
+});
+
+describe('a node close up', () => {
+ it('draws as a card past the zoom that has room for one', () => {
+ // A card in canvas units would overlap its neighbours at every zoom, since the
+ // placement spaces nodes 130 apart; sized off the screen it fits.
+ expect(source).toContain('const asCards = scale >= CARD_SCALE');
+ expect(source).toContain('card.scale({ x: unit, y: unit })');
+ expect(source).toContain('circle.visible(drawn && !carded)');
+ });
+
+ it('measures the card and everything hung off it with the same unit', () => {
+ // The rim an arrow stops at, the ring, the pin and the switch all sit on the
+ // card's edge. Measured any other way they drift off it as the card grows.
+ expect(source).toContain('const unit = cardFactor(scale)');
+ expect(source).toContain('const rim = { x: (CARD.w / 2) * unit, y: (CARD.h / 2) * unit }');
+ expect(source).toContain('Math.hypot(CARD.w / 2, CARD.h / 2) * unit');
+ expect(source).toContain('const margin = CARD.w * 2 * cardFactor(scale)');
+ });
+
+ it('shows the preview the case already holds, never the file itself', () => {
+ // A few hundred nodes reaching for their own full-size image would download
+ // the case to draw it. The thumbnail is the one the Media Library uses.
+ expect(source).toContain('fileUrl(cid, thumb)');
+ expect(source).toContain('previews.set(url, image)');
+ expect(source).toContain("previews.set(url, 'failed')");
+ });
+
+ it('fills the picture column instead of letterboxing a thumbnail into it', () => {
+ // A wide capture fitted inside a square left a strip floating in a hole, which
+ // read as a broken card. The column is filled from the middle of the picture,
+ // over a ground that holds the shape while it loads or if it never does.
+ expect(source).toContain(
+ 'art.crop(cropToFill(image.naturalWidth, image.naturalHeight, CARD.art / CARD.h))',
+ );
+ expect(source).toContain("name: 'ground'");
+ expect(source).toContain("card.findOne('.ground')?.fill(colours.surface)");
+ });
+
+ it('falls back to the entity glyph from the one icon set', () => {
+ expect(source).toContain("import Icon, { paths } from '../components/Icon.svelte'");
+ expect(source).toContain('paths[entityIcon(data)]');
+ });
+
+ it('only builds and only fetches for what is on screen', () => {
+ expect(source).toContain('function onScreen(');
+ expect(source).toContain('entry.card ??= buildCard(data)');
+ });
+
+ it('stops an edge at the side of a card rather than under it', () => {
+ expect(source).toContain('boxRadius(rim.x, rim.y');
+ });
+
+ it('gives a card and a dot the same behaviour, since they are the same node', () => {
+ expect(source).toContain('function answerTo(shape, data,');
+ expect(source).toContain('answerTo(circle, data)');
+ expect(source).toContain("answerTo(card.findOne('.bg'), data,");
+ });
+
+ it('asks the canvas for a real font stack, which `inherit` is not', () => {
+ // `12px inherit` is an invalid font shorthand: every label silently rendered
+ // in the browser's default face instead of the app's.
+ expect(source).not.toContain("fontFamily: 'inherit'");
+ expect(source).toContain("pick('--font-sans'");
+ });
+});
+
+describe('drawing on canvas', () => {
+ it('resolves the palette off the document, because canvas has no CSS variables', () => {
+ // The bug this guards: `stroke: 'var(--accent)'` silently draws nothing.
+ expect(source).toContain('function readColours()');
+ expect(source).toContain('getComputedStyle(document.documentElement)');
+ expect(source).not.toMatch(/stroke\(['"]var\(--/);
+ expect(source).not.toMatch(/fill\(['"]var\(--/);
+ });
+
+ it('re-reads the palette when the theme changes under an open tab', () => {
+ expect(source).toContain('MutationObserver');
+ expect(source).toContain("attributeFilter: ['data-theme', 'class']");
+ });
+
+ it('takes its family hues from the shared palette in both themes', () => {
+ for (const family of [
+ 'actor', 'asset', 'class', 'identifier', 'collected', 'document', 'place', 'claim',
+ ]) {
+ expect(css.match(new RegExp(`--graph-${family}:`, 'g'))).toHaveLength(2);
+ }
+ });
+
+ it('costs no new dependency, drawing with the Konva already in the bundle', () => {
+ expect(source).toContain("import Konva from 'konva'");
+ expect(source).not.toMatch(/from ['"](d3|cytoscape|vis-network|sigma)/);
+ });
+
+ it('leaves the meaning of an edge on its stroke, for a graph that gets printed', () => {
+ expect(layout).toContain('export function edgeStyle');
+ expect(source).toContain('style.dash.map((n) => n / scale)');
+ });
+
+ it('draws every edge with a head, since the vocabulary is directed', () => {
+ expect(source).toContain('new Konva.Arrow(');
+ expect(source).toContain('arrow.pointerLength(');
+ });
+
+ it('explains its strokes instead of leaving four dash patterns unexplained', () => {
+ expect(layout).toContain('export const EDGE_KINDS');
+ expect(source).toContain('const strokes = $derived.by');
+ expect(source).toContain('stroke-dasharray={entry.dash.join(\' \')}');
+ });
+
+ it('writes the verb along the edges under the eye, with the arrow, not against it', () => {
+ expect(source).toContain('function styleVerb');
+ expect(source).toContain('function lineReads(link)');
+ expect(source).toContain('const verb = relationVerb(link.type)');
+ });
+
+ it('writes what kind of tie on the line, not a panel away', () => {
+ // "is associated with" is the thin half of the statement; *sister* is the half
+ // worth reading, and a picture that hides it makes the analyst click every edge.
+ expect(source).toContain('if (link.nature) return `${verb} (${link.nature})`');
+ });
+
+ it('draws a proposal as one, as every other surface does', () => {
+ expect(source).toContain("data.status === 'suggested'");
+ });
+
+ it('destroys the stage when the tab closes', () => {
+ expect(source).toContain('stage?.destroy()');
+ });
+
+ it('keeps Konva off the buffer canvas, which is what makes the graph pannable', () => {
+ // Measured, not guessed: a shape with a fill *and* a stroke *and* an opacity is
+ // composited through a buffer canvas the size of the stage, so 45 faded arrows
+ // allocated and cleared a full-screen canvas per frame of a drag — 246ms of a
+ // 247ms redraw. Without it the same redraw is 3ms. Anything here that gains a
+ // fill beside its stroke has to opt out too.
+ const shapes = source.match(/new Konva\.(Arrow|Circle|Rect|Text)\(\{/g) ?? [];
+ const optedOut = source.match(/perfectDrawEnabled: false/g) ?? [];
+ expect(shapes.length).toBeGreaterThan(3);
+ expect(optedOut.length).toBeGreaterThanOrEqual(5);
+ });
+
+ it('draws once per frame while panning, not once per pointer report', () => {
+ expect(source).toContain('requestAnimationFrame');
+ expect(source).toContain('cancelAnimationFrame');
+ // Nothing can be picked mid-pan, so the hit canvas is not redrawn on the way.
+ expect(source).toContain('layer?.listening(false)');
+ expect(source).toContain('layer?.listening(true)');
+ });
+});
+
+describe('arranging the case by hand', () => {
+ it('lets a node be picked up and put somewhere', () => {
+ expect(source).toContain('function grabbable');
+ expect(source).toContain('moves.draggable(true)');
+ expect(source).toContain('function moveNode');
+ });
+
+ it('gives a dot and a card the same grip, since they are the same node', () => {
+ // A card that could not be dragged while the dot could would be a trapdoor at
+ // one particular zoom. The card moves as a group: the picture, the title and
+ // the stripe travel with it, not just the rectangle under the pointer.
+ expect(source).toContain('function answerTo(shape, data, { named = false, moves = shape }');
+ expect(source).toContain('{ named: true, moves: card }');
+ });
+
+ it('keeps a node drag from also panning the case', () => {
+ // Konva dispatches shape events from a div inside the host, so stopping the
+ // native event there is what keeps the container's pan listener out of it.
+ expect(source).toContain("shape.on('pointerdown'");
+ expect(source).toContain('event.evt?.stopPropagation()');
+ });
+
+ it('tolerates the same tremor a click does, so a shake never pins a node', () => {
+ expect(source).toContain('moves.dragDistance(DRAG_SLOP)');
+ });
+
+ it('does not re-arrange the case when one node is dropped', () => {
+ // The rule the whole feature rests on: if the layout re-ran on every drop,
+ // every other node would slide out from under the hand. The drop moves the one
+ // shape it holds and leaves `placed` alone, which is why the pin map is not
+ // reactive state.
+ expect(source).toContain('const pins = new Map();');
+ expect(source).not.toMatch(/const pins = \$state/);
+ expect(source).toContain('return arrange(placementNodes, mode, links, pins, settled)');
+ expect(source).toMatch(
+ /if \(ownsViewArrangement\(\)\) \{\s*arrangementSaveRevision \+= 1;\s*record\(\);\s*return;/,
+ );
+ });
+
+ it('files a move as it is made rather than behind a Save button', () => {
+ expect(source).toContain('setTimeout(flushPins, SAVE_AFTER)');
+ expect(source).toContain("api.put(`/api/cases/${cid}/graph/pins`");
+ });
+
+ it('keeps a failed save in hand instead of losing the arrangement', () => {
+ expect(source).toContain('for (const entry of batch) pending.set(');
+ });
+
+ it('says a failed arrangement without covering the drawing it failed over', () => {
+ // `failed` draws a message where the drawing would be, which is only true when
+ // there is no drawing. A pin that did not save put a permanent sentence over a
+ // live graph, and nothing cleared it until the next read.
+ expect(source).toContain("say(err.message || 'The arrangement could not be saved.')");
+ expect(source).toContain("say(err.message || 'The pin could not be removed.')");
+ expect(source).toContain("say(err.message || 'The arrangement could not be cleared.')");
+ expect(source).not.toMatch(/failed = err\.message \|\| 'The (arrangement|pin)/);
+ });
+
+ it('files what is pending before reading the case back', () => {
+ // Otherwise the answer overwrites the drag with the position it replaced.
+ expect(source).toMatch(
+ /await flushPins\(\);\s*if \(run !== loadRun \|\| caseState\.current\?\.id !== cid\) return;\s*loading = true/,
+ );
+ });
+
+ it('files a move in the case where the drag happened', () => {
+ expect(source).toContain('savingCase ??= cid;');
+ expect(source).toMatch(/const cid = savingCase;[\s\S]{0,900}?\/graph\/pins/);
+ expect(source).toContain('caseState.current?.id === cid && reading === lens');
+ });
+
+ it('offers a way out of an autosave, one node and all of them', () => {
+ expect(source).toContain('function unpinNode');
+ expect(source).toContain('function resetLayout');
+ expect(source).toContain("api.del(`/api/cases/${cid}/graph/pins/${id}?lens=${lens}`)");
+ expect(source).toContain("api.del(`/api/cases/${cid}/graph/pins?lens=${lens}`)");
+ expect(source).toContain('Let it go');
+ });
+
+ it('counts the pins in the case, not the ones on screen', () => {
+ // The way back has to be offered even when the pinned nodes were cut from the
+ // view, or the cut hides it.
+ expect(source).toContain('pinCount = payload.pinned ?? 0');
+ expect(source).toContain('{#if pinCount > 0}');
+ });
+
+ it('marks a node it placed, so ignoring the layout is not a mystery', () => {
+ expect(source).toContain('function styleMark');
+ expect(source).toContain('data: paths.pushpin');
+ });
+
+ it('reaches the same act from the keyboard, which a canvas otherwise cannot', () => {
+ expect(source).toContain('function nudge');
+ expect(source).toContain('ArrowLeft');
+ expect(source).toContain('event.shiftKey');
+ });
+
+ it('only arranges the whole case, never a neighbourhood', () => {
+ // Distance from the root owns the horizontal axis there, so a node moved off
+ // its column would contradict what that view is drawn to show.
+ expect(source).toContain('const canArrange = $derived(!root && !snapshotReading)');
+ expect(source).toContain('if (canArrange) grabbable(shape, moves, data)');
+ });
+
+ it('saves a drag caught by the debounce when the tab goes', () => {
+ expect(source).toMatch(/flushPins\(\);\s*stage\?\.destroy\(\)/);
+ });
+
+ it('files an arrangement against the reading it was built in', () => {
+ // A lens is a reading: it draws its own nodes and edges and clusters them its
+ // own way, so one shared arrangement would anchor every reading into the shape
+ // of whichever one it was built in.
+ expect(source).toContain('lens: reading,');
+ expect(source).toContain('const reading = savingFor ?? lens');
+ expect(source).toContain('Each lens keeps its own arrangement');
+ });
+
+ it('gathers a handful with ctrl and moves all of it at once', () => {
+ expect(source).toContain('event.evt?.ctrlKey || event.evt?.metaKey');
+ expect(source).toContain('function toggleHeld');
+ expect(source).toContain('if (held.includes(data.id))');
+ // One delta for the whole handful, read off copies of where they started rather
+ // than off seats the move is in the middle of rewriting.
+ expect(source).toContain('for (const [id, start] of grip.at) moveNode(id, start.x + dx, start.y + dy)');
+ expect(source).toContain('for (const id of grip ? grip.at.keys() : [data.id]) dropNode(id)');
+ });
+
+ it('keeps the handful apart from the selection', () => {
+ // Selection is what the panel reads and what the fade is computed from; a set
+ // would make "one hop from the selected node" a question with no single answer.
+ expect(source).toContain('let held = $state([])');
+ expect(source).toContain('let selected = $state(null)');
+ });
+
+ it('says a handful is gathered, and how to let it go', () => {
+ expect(source).toContain('{held.length} held');
+ expect(source).toContain('Let go of the handful (Escape)');
+ });
+
+ it('rings a held node without borrowing the meaning of a dash', () => {
+ // A dashed outline means "proposed" everywhere else in the picture.
+ expect(source).toContain('function styleHeld');
+ expect(source).not.toMatch(/ring\.dash\(/);
+ });
+
+ it('lets the arrows move the handful too', () => {
+ expect(source).toContain('const moving = held.length ? held : selected ? [selected] : []');
+ });
+
+ it('drops the handful when the reading changes', () => {
+ // Half of it may not even be drawn in the next lens.
+ expect(source).toMatch(/pinCount = payload\.pinned \?\? 0;[\s\S]{0,180}?held = \[\];/);
+ });
+});
+
+describe('growing a drawing costs the arrivals, not the case', () => {
+ it('remembers where the drawing came to rest, outside the reactive graph', () => {
+ // Writing it back must not re-derive the thing it was read from, which is the
+ // same reason the pin map is a plain Map.
+ expect(source).toContain('const settled = new Map();');
+ expect(source).not.toMatch(/const settled = \$state/);
+ expect(source).toMatch(/\$effect\(\(\) => \{\s*for \(const seat of placed\) \{/);
+ expect(source).toContain('if (!seat.parked) settled.set(seat.id, { x: seat.x, y: seat.y });');
+ });
+
+ it('leaves the parked column out of what is remembered', () => {
+ // The park is placed against the cluster's edge rather than against the case, so
+ // a spot remembered beside a cluster that has grown since would strand it.
+ expect(source).toContain('if (!seat.parked)');
+ });
+
+ it('hands one node back to the layout without dropping the arrangement', () => {
+ // "Let it go" is asked about one node. Forgetting the whole drawing to answer it
+ // would take the reading down with it.
+ expect(source).toMatch(/pins\.delete\(id\);\s*settled\.delete\(id\);/);
+ });
+
+ it('forgets every spot when the arrangement is reset, or the reset does nothing', () => {
+ // A case whose every node is a fixed point has nothing left to place, so "let the
+ // layout place these again" would answer with the picture it was asked to drop.
+ expect(source).toMatch(/pins\.clear\(\);[\s\S]{0,300}?settled\.clear\(\);/);
+ });
+});
+
+describe('what a node is, not only which family it belongs to', () => {
+ it('says what a media node holds, since one type covers all of them', () => {
+ // "Media" answers a question nobody asked: the analyst wants to know it is a
+ // video. The map lives beside the icons, so no two surfaces can disagree.
+ expect(source).toContain('entityKindLabel(data, entityLabel(data.type))');
+ expect(source).toContain('entityKindLabel(tip, entityLabel(tip.type))');
+ expect(source).toContain('kind: data.kind ?? ');
+ });
+
+ it('tells material the case made from material it collected', () => {
+ // A frame pulled out of a video and a photograph somebody handed over were the
+ // same node: same type, same family, same glyph. A video with twelve saved
+ // frames drew as thirteen pictures with nothing saying which twelve came out of
+ // the first. The card says the act, and the panel says where it came from.
+ expect(source).toContain('madeHereLabel(data) ?? entityKindLabel(data, entityLabel(data.type))');
+ expect(source).toContain('madeHereLabel(tip) ?? entityKindLabel(tip, entityLabel(tip.type))');
+ expect(source).toContain('origin: data.origin ?? ');
+ expect(source).toContain('{#if madeHereBy(chosen)}');
+ expect(source).toContain('Made in {madeHereBy(chosen)} out of material the case already holds.');
+ });
+
+ it('says nothing about a file the case collected, rather than labelling every one', () => {
+ // The backend leaves `origin` off an upload, so the mark is the whole signal.
+ // A card reading "Upload" on everything imported is a mark on nothing.
+ expect(source).not.toContain("'upload'");
+ expect(source).not.toContain('Imported');
+ });
+
+ it('draws each dot with its own glyph, once the dot is big enough to hold one', () => {
+ // The cost this bounds: a wide zoom is where a case draws the most nodes and
+ // where an icon is a smudge, so the glyph is gated on the drawn size.
+ expect(source).toContain('function styleGlyph');
+ expect(source).toContain('GLYPH_MIN');
+ expect(source).toContain('across >= GLYPH_MIN');
+ });
+
+ it('offers previews as a choice, and asks for no pictures when they are off', () => {
+ expect(source).toContain('let showPreviews = $state(true)');
+ expect(source).toContain('if (showPreviews && data.thumb)');
+ expect(source).toContain('{#if showPreviews && tip.thumb && caseState.current}');
+ // A card is built once and kept, so the toggle has to throw the built ones away.
+ expect(source).toContain('function forgetCards');
+ });
+
+ it('draws the park as a region rather than floating a caption over it', () => {
+ // Set apart only reads if the area they are set apart into is drawn, and the
+ // toolbar already counts them — so this names them once, in one word.
+ expect(source).toContain("name: 'parked-tray'");
+ expect(source).toContain("text: 'Unconnected'");
+ expect(source).not.toContain('nothing connects to these');
+ });
+});
+
+describe('it does not rebuild what already exists', () => {
+ it('opens rows in the one Details panel every other surface uses', () => {
+ expect(source).toContain("import EntityDetails from '../components/EntityDetails.svelte'");
+ });
+
+ it('names verbs and types from the registries rather than a local map', () => {
+ expect(source).toContain('relationReading,');
+ expect(source).toContain("} from '../lib/relations.svelte.js'");
+ expect(source).toContain("from '../lib/entityIcon.js'");
+ expect(source).not.toContain('const VERB_LABELS');
+ });
+
+ it('reads an incoming edge with the registry inverse, not with an arrow glyph', () => {
+ // The wording heads the group now, which is also why the direction is part of
+ // the key: one heading over both directions would read as the wrong one for half
+ // the rows under it.
+ expect(source).toContain("const way = row.outgoing ? 'out' : 'in'");
+ expect(source).toContain('relationReading(row.link.type, way)');
+ expect(source).toContain('const key = `${row.link.type} ${way}`');
+ });
+
+ it('keeps the placement pure and out of the component', () => {
+ expect(source).toContain("from '../lib/graph.js'");
+ expect(source).not.toContain('Math.random');
+ });
+});
+
+describe('the view grows instead of being replaced', () => {
+ it('expands a node by adding it to the expansion, not by re-rooting the view', () => {
+ // The gesture the whole tool turns on: what was on screen stays on screen.
+ expect(source).toContain('function expandNode(id)');
+ expect(source).toContain('expanded = [...expanded, id]');
+ expect(source).toContain("shape.on('dblclick dbltap'");
+ expect(source).toMatch(/dblclick dbltap[\s\S]{0,200}toggleAround\(data\.id\)/);
+ });
+
+ it('sends the opened nodes to the same read the case opens on', () => {
+ expect(source).toContain("params.expand = expanded.join(',')");
+ expect(source).toContain("return ['/graph', params]");
+ });
+
+ it('offers to open only what is not already on screen', () => {
+ // A view that already holds every one of a node's neighbours has nothing left
+ // to bring in, which is most of the time on a case that fits. Offering the act
+ // there was offering one that could only appear to do nothing.
+ expect(source).toContain('const offScreen = $derived.by');
+ expect(source).toContain('All its connections are drawn');
+ expect(source).toContain('disabled={!away || Boolean(root)}');
+ });
+
+ it('offers one way back for the whole picture, not one per list', () => {
+ // Four lists edit one drawing, and four counts in the toolbar meant reading all
+ // of them to work out which was in the way.
+ expect(source).toContain('function resetDrawing()');
+ expect(source).toMatch(
+ /function resetDrawing\(\) \{\s*expanded = \[\];\s*kept = \[\];\s*omitted = \[\];\s*collapsed = \[\];/,
+ );
+ expect(source).toContain('Reset view');
+ // The arrangement is not part of it: that one undoes work done by hand.
+ expect(source).toMatch(/function resetDrawing[\s\S]{0,200}\}/);
+ expect(source).not.toMatch(/function resetDrawing\(\)[\s\S]{0,200}pins\.clear/);
+ });
+
+ it('says the three acts on the drawing in three words and no others', () => {
+ // One act, one word, everywhere it is offered. The tool used to say Open, Fold
+ // back, Fold it back, Take it out and Bring back for what is really three things.
+ expect(source).toContain('Expand {away} more connection');
+ expect(source).toContain('Collapse {takes}');
+ expect(source).toContain('Hide it');
+ expect(source).not.toMatch(/>\s*Fold back/);
+ expect(source).not.toMatch(/Fold it back/);
+ expect(source).not.toMatch(/Take it out of the drawing/);
+ expect(source).not.toMatch(/Bring back \{/);
+ });
+
+ it('takes the case at its word about what is open', () => {
+ // A node deleted in another tab must stop being offered as foldable.
+ expect(source).toContain('if (Array.isArray(payload.expanded)) expanded = payload.expanded');
+ });
+});
+
+describe('a comfort number, not a ceiling', () => {
+ it('states no ceiling, because the drawing has none', () => {
+ // A limit that refuses is the app overruling the analyst about their own picture.
+ // What was left of it here was a gauge, a greyed control and a refusal in words.
+ expect(source).not.toContain('viewFull');
+ expect(source).not.toContain('payload?.room');
+ expect(source).not.toContain('The view is full');
+ });
+
+ it('says what a heavy drawing costs instead of refusing to draw one', () => {
+ // Measured, not guessed: the relaxation is O(n²) on the main thread, so a
+ // thousand nodes cost about a second and two thousand freeze the tab.
+ expect(source).toContain('const HEAVY = 1000');
+ expect(source).toContain('const FREEZING = 2000');
+ expect(source).toMatch(
+ /const weight = \$derived\([\s\S]{0,160}nodes\.length >= FREEZING \? 'freezing'/,
+ );
+ expect(source).toContain('Every change now freezes the tab for a few seconds');
+ });
+
+ it('answers an expansion whole, so a second press has nothing to ask for', () => {
+ // The budget used to serve part of an answer and report the node open, which
+ // greyed the one control offering to open it.
+ expect(source).toMatch(
+ /function expandNode\(id\)[\s\S]{0,900}if \(expanded\.includes\(id\)\) return;/,
+ );
+ expect(source).toMatch(/if \(away > 0\) return \{ id, act: 'expand', count: away \};/);
+ });
+
+ it('hands a hidden node back from the node it was hanging on', () => {
+ // Undoing one node of a hiding used to cost the whole drawing, since Reset view is
+ // the only way back and it puts every other edit back with it.
+ expect(source).toContain('let putAway = $state({})');
+ expect(source).toMatch(/function takeOut\(ids\)[\s\S]{0,700}putAway = record;/);
+ expect(source).toMatch(/function expandNode\(id\)[\s\S]{0,700}if \(bringBackAt\(id\)\) return;/);
+ expect(source).toMatch(/function bringBackAt\(id\)[\s\S]{0,300}omitted = omitted\.filter/);
+ // Counted as missing, or the node would say every connection was drawn while the
+ // analyst was looking at the gap they had just made.
+ expect(source).toContain('(putAway[id]?.length ?? 0)');
+ // And forgotten the moment it is drawn again, whatever brought it back.
+ expect(source).toMatch(/function backIn\(ids\)[\s\S]{0,400}forgetHidden\(ids\)/);
+ expect(source).toMatch(/function resetDrawing\(\)[\s\S]{0,160}putAway = \{\};/);
+ });
+
+});
+
+describe('the drawing is a set you own', () => {
+ it('tells drawing a node from drawing a node and one hop', () => {
+ // One list conflated the two acts, so a named node always arrived with its whole
+ // neighbourhood. Right for a node being read, wrong for everything else.
+ expect(source).toContain('function holdOn(ids)');
+ expect(source).toContain('kept = [...new Set([...kept, ...named])]');
+ expect(source).toContain("params.keep = kept.join(',')");
+ expect(source).toContain("params.expand = expanded.join(',')");
+ });
+
+ it('draws a route as itself instead of one neighbourhood per step', () => {
+ // A four-node answer used to arrive inside a crowd of forty, which is the sentence
+ // being drawn and then buried.
+ expect(source).toMatch(/routing = body\.routes;\s*holdOn\(body\.routes\.flatMap/);
+ });
+
+ it('takes any node out, not only one that was opened', () => {
+ expect(source).toContain('function takeOut(ids)');
+ expect(source).toContain("params.omit = omitted.join(',')");
+ // Both surfaces a node states its acts in, and the panel is the keyboard path:
+ // the menu is a right-click, which no key sends.
+ expect(source).toContain('onclick={() => takeOut([chosen.id])}');
+ expect(source).toContain('onclick={() => chose((id) => takeOut([id]))}');
+ expect(source).toContain('Hide it');
+ });
+
+ it('words it clear of the edge panel’s Remove, which deletes a statement', () => {
+ // Two acts, one word, in two panels a click apart: "Remove" on an edge takes the
+ // case's own row away, where this takes a node out of a picture.
+ expect(source).toContain('>\n Hide\n </button>');
+ expect(source).toMatch(/takeOut\(\[chosen\.id\]\)[\s\S]{0,200}not out of the case/);
+ expect(source).not.toMatch(/onclick=\{\(\) => takeOut\(\[chosen\.id\]\)\}>\s*Remove/);
+ });
+
+ it('lets the panel’s acts wrap rather than clipping the last one’s label', () => {
+ // The row grew a fourth act, and a fixed-width panel squeezed it until
+ // *Collapse (35)* read as *Collapse* — a button clipped to its first word naming a
+ // different act than the one it performs.
+ expect(source).toMatch(/\.actions \{[^}]*flex-wrap: wrap;/);
+ });
+
+ it('adds to the removals and prunes nothing, so bringing back is a whole undo', () => {
+ // The case applies the removals last, so they already win over the name that drew
+ // the node and the hop that reached it. Pruning those lists would make the way back
+ // a half-undo: a node in the picture only because it was named would not return.
+ expect(source).toMatch(/function takeOut\(ids\)[\s\S]{0,900}omitted = \[\.\.\.new Set\(\[\.\.\.omitted, \.\.\.going\]\)\]/);
+ expect(source).not.toMatch(/function takeOut\(ids\)[\s\S]{0,900}kept = kept\.filter/);
+ });
+
+ it('offers a way back out of a removal, as a control rather than an undo', () => {
+ // The same way back as for every other edit: the nodes cannot be named the way an
+ // expansion's are — they are not on screen to have a label — so naming the lists
+ // apart bought nothing and cost the analyst a choice.
+ expect(source).toContain('function resetDrawing()');
+ expect(source).toContain('Draw the case the way it opened');
+ });
+
+ it('lets a name asked for again outrank a removal made earlier', () => {
+ expect(source).toContain('function backIn(ids)');
+ expect(source).toContain('omitted = omitted.filter((id) => !named.has(id))');
+ });
+
+ it('lets go of what a removed node was carrying, before the read lands', () => {
+ // A node on its way out of the picture must not be left being read, and half a
+ // path is not worth keeping — the bargain Escape already makes with a walk.
+ expect(source).toContain('if (going.has(selected)) selected = null');
+ expect(source).toContain('if (path.some((step) => going.has(step.id))) traceStop()');
+ });
+
+ it('grows and empties by the group, not one node per read', () => {
+ // Five nodes opened one at a time is five reads and five arrivals landing in five
+ // places, where the analyst asked one question about five nodes.
+ expect(source).toContain('function expandGathered()');
+ expect(source).toContain('Expand {held.length}');
+ expect(source).toContain('Hide {held.length}');
+ expect(source).toContain('onclick={() => takeOut(held)}');
+ });
+
+ it('takes the case at its word about what it drew by name', () => {
+ // A node deleted in another tab, or of a type this reading does not draw, must
+ // stop being carried in the list the client sends back.
+ expect(source).toContain('if (Array.isArray(payload.kept)) kept = payload.kept');
+ });
+
+ it('never offers to edit the drawing in a view that is one node’s hops', () => {
+ // A neighbourhood's root is the question being asked, and its read takes none of
+ // these lists.
+ expect(source).toMatch(/\{#if !root\}[\s\S]{0,600}takeOut\(\[chosen\.id\]\)/);
+ expect(source).toMatch(/\{#if !root\}[\s\S]{0,600}Hide it/);
+ });
+
+ it('rereads without refitting or replacing the drawing after an edit', () => {
+ // Growing, folding and removing are the same question. Only a lens, an order, a
+ // folder, a family or a question handed over by the Board is a new one — and the
+ // key that decides that carries none of the three lists.
+ expect(source).toMatch(/cid,[\s\S]{0,260}?String\(rev\),\s*lens,\s*order,\s*root \?\? '',\s*hops/);
+ expect(source).toContain('JSON.stringify(searchTerms), JSON.stringify(temporalTerms), catalogViews.snapshotId');
+ expect(source).toMatch(/kept\.join\(','\),\s*expanded\.join\(','\),\s*omitted\.join\(','\),/);
+ });
+
+ it('rereads when another surface changes the case', () => {
+ expect(source).toContain('const rev = caseState.rev;');
+ expect(source).toContain('String(rev),');
+ expect(source).toContain('`${cid}|${caseState.rev}`');
+ });
+
+ it('lets only the latest case read own the canvas', () => {
+ expect(source).toContain('let loadRun = 0;');
+ expect(source).toContain('const run = ++loadRun;');
+ expect(source).toContain('run !== loadRun || caseState.current?.id !== cid');
+ expect(source).toContain('const next = await api.get');
+ });
+
+ it('starts a new case with no edits carried over from the last one', () => {
+ // Ids from another case name nothing here, and a removal carried over would take a
+ // node out of a picture nobody has looked at yet.
+ expect(source).toMatch(/function startCase\(cid\)[\s\S]{0,500}?root = null;/);
+ expect(source).toMatch(/function startCase\(cid\)[\s\S]{0,900}?pickFolder = '';/);
+ expect(source).toMatch(/function startCase\(cid\)[\s\S]{0,1200}?fromBoard = null;/);
+ expect(source).toMatch(/function startCase\(cid\)[\s\S]{0,1600}?find = '';/);
+ expect(source).toMatch(/function startCase\(cid\)[\s\S]{0,2200}?creating = null;/);
+ });
+});
+
+describe('the drawing folds, including the part the case opened on', () => {
+ it('folds without asking the case anything', () => {
+ // The whole reason this act exists beside the other three: it reads the drawing
+ // already on screen, so it reaches the nodes that were there before the analyst
+ // touched anything — which no server-side list can do.
+ expect(source).toContain('let collapsed = $state([])');
+ expect(source).toContain('function foldNode(id)');
+ expect(source).toContain('collapsed = [...collapsed, id]');
+ // Never sent, unlike the three lists that edit the set.
+ expect(source).not.toMatch(/params\.\w+ = collapsed/);
+ // And never a reason to re-read the case.
+ expect(source).not.toMatch(/loadedFor = null;[\s\S]{0,60}collapsed/);
+ });
+
+ it('takes the folded nodes out at the seam everything else reads', () => {
+ // One filter, before the placement, so the legend, the search, the focus and the
+ // edges are all folded at once without any of them knowing folding exists.
+ expect(source).toContain('const folds = $derived(foldAway(collapsed, sentNodes, sentLinks');
+ expect(source).toMatch(/const nodes = \$derived\([\s\S]{0,140}folds\.hidden\.has\(node\.id\)/);
+ expect(source).toMatch(/const links = \$derived\([\s\S]{0,220}folds\.hidden\.has\(link\.from\)/);
+ });
+
+ it('never folds a node the analyst placed by hand', () => {
+ // An arrangement somebody built outranks a rule that tidies.
+ expect(source).toContain('foldAway(collapsed, sentNodes, sentLinks, new Set(pinnedIds))');
+ });
+
+ it('refuses a fold that would do nothing rather than answering with the same picture', () => {
+ expect(source).toMatch(
+ /function foldNode\(id\)[\s\S]{0,500}if \(!foldableCount\(id, nodes, links[\s\S]{0,60}return;/,
+ );
+ });
+
+ it('states what the switch will do before it is pressed', () => {
+ // A canvas teaches no gesture, so the count is the teaching: plus grows the
+ // picture, minus shrinks it, in all three states of the same switch.
+ expect(source).toContain('const switchFor = $derived.by');
+ expect(source).toContain("act: 'unfold'");
+ expect(source).toContain("act: 'expand'");
+ expect(source).toContain("act === 'fold' ? '−' : '+'");
+ });
+
+ it('grows before it tidies, so one switch never has to be remembered', () => {
+ // A node holding folded nodes gives them back; one with neighbours off screen
+ // fetches them; one with everything already around it puts that away.
+ expect(source).toMatch(
+ /function toggleAround\(id\) \{\s*if \(collapsed\.includes\(id\)\) unfoldNode\(id\);\s*else if \(!root && offScreen\(id\) > 0\) expandNode\(id\);\s*else foldNode\(id\);/,
+ );
+ });
+
+ it('draws the switch on the node in hand, not on all three hundred', () => {
+ // A count pinned to every dot is a few hundred numbers competing with the shape
+ // of the case, which is the one thing the tool exists to show.
+ expect(source).toContain('function stylePill(');
+ expect(source).toMatch(/const on = switchFor\?\.id === data\.id \? switchFor : null/);
+ // A node that is holding something says so whether or not it is under the eye.
+ expect(source).toContain('const holding = collapsed.includes(data.id)');
+ });
+
+ it('keeps the switch off an armed gesture, which owns the press', () => {
+ expect(source).toMatch(/count > 0 && !drawing && !tracing && !asking/);
+ });
+
+ it('lets a name, a route or a connection outrank a fold', () => {
+ // Left standing, a fold answers the thing just asked for with the picture it was
+ // already showing.
+ expect(source).toContain('function showAgain(ids)');
+ expect(source).toMatch(/function backIn\(ids\)[\s\S]{0,520}showAgain\(ids\)/);
+ expect(source).toMatch(/function jumpTo\(id\) \{[\s\S]{0,260}showAgain\(\[id\]\)/);
+ expect(source).toMatch(/function settleRoute\(\)[\s\S]{0,320}showAgain\(/);
+ });
+
+ it('finds a folded node where it is instead of fetching it again', () => {
+ expect(source).toMatch(/const matches = \$derived\.by[\s\S]{0,600}sentNodes/);
+ expect(source).toContain("{folds.hidden.has(row.id) ? 'folded' : row.degree}");
+ // And the catalog list does not offer to bring in what the drawing already has.
+ expect(source).toContain('const drawn = new Set(sentNodes.map((node) => node.id))');
+ });
+
+ it('counts what is drawn rather than what the case sent', () => {
+ // A number that argues with the picture is worse than no number.
+ expect(source).toContain('{nodes.length} of {payload.total}');
+ expect(source).toContain('{foldedCount} folded');
+ });
+
+ it('gives every fold back at once, and for free', () => {
+ expect(source).toMatch(/function unfoldAll\(\) \{\s*collapsed = \[\];\s*\}/);
+ expect(source).toContain('Give back everything the folds are holding');
+ });
+});
+
+describe('an edge is a thing to read and to rule on', () => {
+ it('lets the pointer reach an edge at all', () => {
+ // A one-pixel stroke is unhittable, so the hit region is widened rather than
+ // the line: the picture is unchanged.
+ expect(source).toContain('hitStrokeWidth: 14');
+ expect(source).toContain('const wires = new Konva.Group();');
+ });
+
+ it('reads the chosen edge in the panel the nodes use', () => {
+ expect(source).toContain('const chosenEdge = $derived(');
+ expect(source).toContain('{relationVerb(chosenEdge.type)}');
+ });
+
+ it('rules on a proposal from the picture', () => {
+ expect(source).toContain("ruleOn(chosenEdge.id, 'confirmed')");
+ expect(source).toContain("api.patch(`/api/cases/${cid}/links/${linkId}`, { status })");
+ });
+
+ it('lights an edge under the pointer the way a node lights', () => {
+ expect(source).toContain('const picked = link.id === chosenLink || link.id === hoveredLink');
+ });
+
+ it('judges the edge where it is read, instead of a panel away', () => {
+ // Reading a line here and grading it used to mean leaving the drawing for the
+ // node's Details and finding the row again among its grouped connections. On a
+ // worked case the finding is more often on the edge than on either node.
+ expect(source).toContain('async function rateEdge(linkId, raw)');
+ expect(source).toContain('confidence: raw === \'\' ? null : Number(raw)');
+ expect(source).toContain('onchange={(event) => rateEdge(chosenEdge.id, event.currentTarget.value)}');
+ });
+
+ it('offers the two controls because the registry declares them, not because the edge holds one', () => {
+ // A qualifier belongs to the verb and a rating to a ratable one, so a derivation
+ // and a mention offer neither — the same rule Details follows, and what keeps a
+ // free note off the rest of the vocabulary.
+ expect(source).toContain('{@const qualifier = relationQualifier(chosenEdge.type)}');
+ expect(source).toContain(
+ '{@const gradable = isRatable(chosenEdge.type) && confidenceLevels().length}',
+ );
+ });
+
+ it('reads the levels from the registry and offers clearing as the absence of one', () => {
+ // One list, so the picker cannot offer a value the API would refuse; and "not
+ // assessed" is a state to return to rather than a fifth level.
+ expect(source).toContain('{#each confidenceLevels() as level (level.value)}');
+ expect(source).toContain('<option value="">Not assessed</option>');
+ });
+
+ it('never grades a proposal, which the API refuses before it is reviewed', () => {
+ // Reviewing a machine's claim and grading it are two gestures: the confirm has to
+ // land first, so the control is not there to be pressed.
+ expect(source).toContain(
+ "{#if !snapshotReading && chosenEdge.provenance?.status !== 'suggested'}",
+ );
+ });
+
+ it('lets the line carrying a qualifier be the line that changes it', () => {
+ // The drawing already wrote *is associated with (sister)* and could not correct
+ // it: readable in the picture, editable only outside it.
+ expect(source).toContain('if (link.nature) return `${verb} (${link.nature})`');
+ expect(source).toContain('async function qualifyEdge(link, raw)');
+ expect(source).toContain('{ nature: value || null }');
+ // On change, and not on a value the edge already holds: `change` fires on blur, so
+ // clicking through the panel would otherwise re-read the case for nothing.
+ expect(source).toContain("if (!cid || value === (link.nature ?? '')) return");
+ });
+
+ it('re-reads the case after a judgement, because the rating can change the stroke', () => {
+ expect(source).toMatch(
+ /confidence: raw === ''[\s\S]{0,200}loadedFor = null;\s*await load\(\);/,
+ );
+ });
+});
+
+describe('two entities can be connected from the graph', () => {
+ it('offers the act in a menu, where people look for what a thing can do', () => {
+ // Two drag gestures were tried first. A rim band covered most of a small node,
+ // so moving one started a link by accident; a visible handle was still a drag,
+ // fiddly on a trackpad and invisible until you knew it was there.
+ expect(source).toContain("shape.on('contextmenu'");
+ expect(source).toContain('function openMenu(id, at)');
+ expect(source).toContain('Connect to…');
+ expect(source).not.toContain('function onRim');
+ expect(source).not.toContain('function placeHandle');
+ });
+
+ it('names the other end with a click, not with a held button', () => {
+ expect(source).toContain('function landOn(id)');
+ expect(source).toContain('if (drawing && landOn(data.id)) return');
+ });
+
+ it('asks the vocabulary once, when the connection is armed', () => {
+ // The answer cannot change while the pointer travels, and asking per move would
+ // run the registry over every node a hundred times a second.
+ expect(source).toMatch(/function startDrawing[\s\S]{0,300}relationOptions\(from, node\)\.length/);
+ expect(source).toContain('drawing.targets.has(over)');
+ });
+
+ it('refuses a pair the vocabulary has no reading for, in words', () => {
+ expect(source).toContain('The vocabulary has no connection between those two.');
+ });
+
+ it('moves only the arrow while the case is panned under it', () => {
+ // A pan deliberately does not restyle. Paying for a few hundred shapes on every
+ // frame of one to keep a single line in step would undo the reason it draws
+ // that way.
+ expect(source).toMatch(/group\.position\(drag\.to\);[\s\S]{0,320}if \(drawing\) styleBand\(/);
+ expect(source).toContain('const origin = drag?.to ?? { x: group.x(), y: group.y() }');
+ });
+
+ it('lets the case be panned while a connection is armed', () => {
+ // The two nodes worth joining are often nowhere near each other, and a mode that
+ // pinned the view would make exactly those the hard ones.
+ expect(source).toMatch(/if \(drawing\) drawTo\(event\);\s*if \(!drag/);
+ });
+
+ it('says it is mid-gesture, and offers the way out', () => {
+ // A mode with no words is a mode nobody can get out of.
+ expect(source).toContain('Connecting from');
+ expect(source).toMatch(
+ /if \(menu\) menu = null;\s*else if \(blank\) blank = null;\s*else if \(offer\) offer = null;\s*else if \(drawing\)/
+ );
+ });
+
+ it('files the relation through the route every other surface uses', () => {
+ expect(source).toMatch(
+ /api\.post\(`\/api\/cases\/\$\{cid\}\/links`, \{\s*from_id: from,\s*to_id: to,\s*type: option\.type,\s*\}\)/,
+ );
+ });
+
+ it('heads a pointer apart from a statement, as the registry does', () => {
+ // "mentions" in the same unheaded list as "owns" makes a document naming a
+ // place look like a statement about it (ONTOLOGY §3). The heading is the
+ // registry's own, so no wording is invented on the canvas.
+ expect(source).toContain('const offerGroups = $derived.by(');
+ expect(source).toContain('{#if set.group}<p class="heading">{set.group}</p>{/if}');
+ });
+
+ it('speaks up only when a filed edge is not drawn by the current lens', () => {
+ // The edge appearing is the confirmation. A lens that does not hold the verb
+ // draws nothing new, and a write with no visible result reads as one that failed.
+ expect(source).toContain("say('Filed, and not drawn in this lens.')");
+ expect(source).toContain("!payload?.links?.some((edge) => edge.id === filed.id)");
+ });
+
+ it('calls nothing it does not define', () => {
+ // A helper that was never written threw a ReferenceError into the catch that
+ // exists to report a refused connection, so a relation filed successfully
+ // reported an error naming the missing function.
+ expect(source).not.toContain('loadLeads');
+ expect(source).not.toContain('saveRelation');
+ });
+
+ it('does not offer the menu where a node cannot be arranged', () => {
+ // A neighbourhood lays out by distance from its root; a link drawn there would
+ // fight the axis that view exists to show.
+ expect(source).toMatch(/contextmenu[\s\S]{0,200}if \(!canArrange\) return/);
+ });
+
+ it('leaves the ctrl-click that gathers alone on macOS', () => {
+ // One press, one act: that same press is a right-click there.
+ expect(source).toContain('if (event.evt?.ctrlKey && event.evt?.button === 0) return');
+ });
+
+ it('redraws the armed arrow once per frame, not once per pointer report', () => {
+ expect(source).toMatch(/frame \|\|= requestAnimationFrame\(\(\) => \{\s*frame = 0;\s*restyle\(\);/);
+ });
+});
+
+describe('the view does not move under the analyst', () => {
+ it('refits on a new question and never on a growth', () => {
+ // Opening a node and watching the whole case slide to a new position is the
+ // fastest way to lose your place — the thing growing in place was built to stop.
+ expect(source).toMatch(/const fresh = asked !== askedFor;[\s\S]{0,120}resetView = fresh;/);
+ });
+
+ it('re-places on a new question and never on a growth, off the same seam', () => {
+ // The same fact told twice would let the view and the arrangement disagree about
+ // what a new question is, which is a picture that refits without re-placing.
+ expect(source).toContain('if (fresh) settled.clear();');
+ });
+
+ it('clears what it said instead of leaving a banner nobody reads', () => {
+ expect(source).toContain('function say(message)');
+ expect(source).toContain("sayTimer = setTimeout(() => (saving = ''), 6000)");
+ });
+});
+
+describe('the way back, one act at a time', () => {
+ it('follows the state rather than the acts, so a new control is undoable by existing', () => {
+ // Hooking each act is the version that rots: the next control is undoable only if
+ // somebody remembered, and nothing fails when they did not.
+ expect(source).toContain('const history = createHistory()');
+ expect(source).toMatch(/\$effect\(\(\) => \{\s*record\(\);\s*\}\)/);
+ expect(source).toContain('function record()');
+ // The snapshot is read before the guard or the effect subscribes to nothing but
+ // the case id, and the recorder goes deaf the moment it is anchored.
+ expect(source).toMatch(
+ /function record\(\) \{\s*const now = snapshotNow\(\);\s*if \(restoring \|\| !anchored/,
+ );
+ expect(source).toContain('history.push(now)');
+ });
+
+ it('records a drag itself, since its coordinates are not reactive state', () => {
+ expect(source).toMatch(/function dropNode\(id\)[\s\S]{0,700}?record\(\);/);
+ });
+
+ it('anchors on the picture the case opened on, never before its first read', () => {
+ // Anchored earlier, one undo too many would ask the case to drop every pin it had
+ // not yet sent.
+ expect(source).toContain('if (anchored !== cid)');
+ expect(source).toContain('history.reset(snapshotNow())');
+ });
+
+ it('asks the case again even when only the arrangement moved', () => {
+ // A restored arrangement changes nothing the reading is keyed on, and the picture
+ // has to move all the same.
+ expect(source).toContain('String(rereads)');
+ expect(source).toContain('rereads += 1');
+ });
+
+ it('does not let the run that answers a restore undo the undo', () => {
+ // Putting an arrangement back waits on the case, and an effect between the pins
+ // landing and the lists being assigned would record a picture nobody asked for —
+ // one entry off the state being restored, which forks the timeline and takes the
+ // redo with it.
+ expect(source).toContain('let restoring = $state(false)');
+ expect(source).toContain('if (restoring || !anchored');
+ expect(source).toMatch(/} finally \{\s*\/\/[\s\S]{0,180}?await tick\(\);\s*restoring = false;/);
+ });
+
+ it('touches an arrangement only inside the reading it was taken in', () => {
+ // Pins are per lens and survive a switch, so diffing against the lens on screen
+ // would take one reading's pins off with the other reading's list.
+ expect(source).toContain('if (ownsViewArrangement() || was.lens === lens)');
+ expect(source).toContain('arrangementDiff(arrangementNow(), wanted)');
+ });
+
+ it('binds the three chords the rest of the app binds, and gives up a gesture', () => {
+ expect(source).toMatch(/if \(drawing \|\| tracing \|\| asking\) return;/);
+ expect(source).toMatch(/chord === 'z'[\s\S]{0,160}?event\.shiftKey\) redo\(\);\s*else undo\(\)/);
+ expect(source).toContain("chord === 'y'");
+ // A field being typed into owns its own undo, and the guard above it is shared.
+ expect(source).toMatch(/if \(typing\) return;\s*if \(event\.ctrlKey \|\| event\.metaKey\)/);
+ });
+
+ it('says so in the toolbar, because a canvas teaches no gesture', () => {
+ expect(source).toContain('{#if canUndo}');
+ expect(source).toContain('{#if canRedo}');
+ expect(source).toContain('onclick={undo}');
+ expect(source).toContain('Undo the last change to the drawing (Ctrl+Z)');
+ });
+
+ it('never reaches a write to the case', () => {
+ // A stack mixing "I hid a node" with "I deleted a statement" rewrites the case on
+ // the fourth press to get a view back, and a re-filed edge mints a new id, date
+ // and author — an undo that forges the provenance it claims to restore.
+ const restore = source.slice(source.indexOf('async function restore(text)'));
+ const body = restore.slice(0, restore.indexOf('\n }'));
+ expect(body).not.toMatch(/api\.(post|del)\(/);
+ expect(body).not.toContain('/links');
+ });
+});
+
+describe('one finding on the ground is one arrow', () => {
+ it('keeps the acts on it, because it is the row the case holds', () => {
+ // Not a synthetic edge: the video really does state that point, so confirming or
+ // withdrawing it stays possible and the merge is said beside those acts.
+ expect(source).toContain('{#if chosenEdge.merged}');
+ expect(source).toMatch(
+ /\{#if chosenEdge\.merged\}[\s\S]{0,900}?\{#if chosenEdge\.provenance\?\.by\}/,
+ );
+ });
+
+ it('hands back what it absorbed through the one mechanism for it', () => {
+ expect(source).toContain('const back = link.folded?.open ?? link.merged?.open ?? []');
+ expect(source).toContain('Show the {chosenEdge.merged.open.length}');
+ expect(source).toContain('Stands for {chosenEdge.merged.sources} more, all the same material.');
+ });
+
+ it('says so without being pointed at, and carries the weight it took on', () => {
+ // The count is the whole reason those nodes are not on screen, so leaving it to
+ // the hover lost them. Written at every zoom it was three hundred sentences over
+ // the shape of the case, so it waits for the zoom the nodes become cards at and
+ // the extra weight carries it until then.
+ expect(source).toContain('const stands = Boolean(link.folded || link.merged)');
+ expect(source).toContain('styleVerb(entry, Boolean(touching) || (stands && asCards), scale)');
+ expect(source).toContain('+ (stands ? 0.9 : 0)');
+ // A bare count on a merged arrow: writing the material into the verb would put
+ // words in the statement's mouth.
+ expect(source).toContain('return `${verb} (+${link.merged.sources})`');
+ });
+});
+
+describe('what came out of a node and was used by nothing', () => {
+ it('says it on the node, in the act the analyst named it by', () => {
+ // "3 medias made from it" spends the sentence saying nothing; "3 frames" is the
+ // whole fact. Same words as the collapsed step, resolved on the same surface.
+ expect(source).toContain('function rolledReads(rolled)');
+ expect(source).toContain("const what = via.length === 1 ? madeAsWord(via[0]) : 'derivative'");
+ expect(source).toContain('{rolledReads(chosen.rolled)} made from it, used by nothing.');
+ });
+
+ it('is one count and one offer, not two of each', () => {
+ // The node prices its unused derivatives among the connections the drawing does
+ // not hold, and expanding brings them like any other. Split off, the pill read
+ // "+4" while the menu offered "1 more connection" for the same five nodes, and the
+ // difference between the two numbers was about the mechanism rather than the case.
+ expect(source).not.toContain("act: 'derived'");
+ expect(source).not.toContain('Show {rolledReads(at.rolled)}');
+ expect(source).toMatch(
+ /function toggleAround\(id\) \{\s*if \(collapsed[\s\S]{0,120}?else if \(!root && offScreen\(id\) > 0\) expandNode\(id\);/,
+ );
+ });
+});
+
+describe('the wrapper is an edge, and the count is what it says', () => {
+ it('writes what a folded edge stands for beside its verb', () => {
+ // "cites" alone would be a thicker line saying less than the three it replaced.
+ expect(source).toContain('function standsFor(link)');
+ expect(source).toContain('return `${verb} ${standsFor(link)}`');
+ // The account clause is left off where nothing published these: a proof has no
+ // publisher, and "0 accounts" reads as a gap rather than as another kind of source.
+ expect(source).toContain(
+ "return accounts ? `${many} · ${accounts} account${accounts === 1 ? '' : 's'}` : many",
+ );
+ });
+
+ it('writes a collapsed step as the act rather than as the type', () => {
+ // "derived from 2 medias" spends the edge saying nothing: the step is what the
+ // analyst named it by in Inspect, and the words live on the one surface for them.
+ expect(source).toContain("const what = via.length === 1 ? madeAsWord(via[0]) : 'source'");
+ expect(source).toContain('madeAsWord,');
+ });
+
+ it('hands back what it stands for through the one mechanism for it', () => {
+ // A node the analyst named is never folded, so naming these draws them again —
+ // named rather than opened, since a source is wanted as itself and opening it
+ // would drag whatever else it touches in behind it.
+ expect(source).toContain('function unfold(link)');
+ expect(source).toMatch(/function unfold\(link\)[\s\S]{0,600}holdOn\(back\)/);
+ });
+
+ it('does not offer to confirm, remove or judge an edge that is not a row', () => {
+ // Nothing may be written to a folded edge: the case has no such link, so the
+ // controls would 404 on an act the panel had just offered. A rating and a
+ // qualifier are writes like the other two, so they sit on the same side of the
+ // branch — sliced rather than length-matched, since the row's half keeps growing.
+ const start = source.indexOf('{#if chosenEdge.folded}');
+ const split = source.indexOf('{#if chosenEdge.merged}', start);
+ const end = source.indexOf('<ul class="neighbours">', split);
+ expect(start).toBeGreaterThan(-1);
+ expect(split).toBeGreaterThan(start);
+ expect(source.slice(start, split)).not.toMatch(/dropLink|ruleOn|rateEdge|qualifyEdge/);
+ const row = source.slice(split, end);
+ expect(row).toContain('dropLink(chosenEdge.id)');
+ expect(row).toContain('rateEdge(chosenEdge.id');
+ expect(row).toContain('qualifyEdge(chosenEdge,');
+ });
+
+ it('says where a folded type lives when it cannot be handed back', () => {
+ // The safeguard's fold: this reading does not draw a note at all, so the panel
+ // names the lens that does instead of offering an act it would refuse.
+ expect(source).toContain('{#if chosenEdge.folded.open?.length}');
+ expect(source).toContain('My work draws {chosenEdge.folded.via.join');
+ });
+
+ it('reads the independence off the edges, in the toolbar and on the statement', () => {
+ // Three citations are not three sources when one account published all three.
+ expect(source).toContain('payload.single_account > 0');
+ expect(source).toContain('{payload.single_account} on one account');
+ expect(source).toContain('Rests on {chosen.rests.sources} source');
+ // It measures and concludes nothing, so it is marked rather than coloured as a
+ // fault: whether it is a problem is the analyst's to say.
+ expect(source).toContain('{#if chosen.rests.one}<em>all one account</em>{/if}');
+ });
+
+ it('reaches the set the number names instead of only counting it', () => {
+ // A count that names a set and gives no way to it sends the analyst opening
+ // statements one at a time to find out which ones it meant.
+ expect(source).toContain('onclick={showResting}');
+ expect(source).toContain('aria-pressed={singling}');
+ expect(source).toMatch(/function showResting\(\) \{\s*singling = !singling;/);
+ });
+
+ it('lights those statements and one hop, which is where the finding is', () => {
+ // The sources are folded into the edges, so the statement and what its edges
+ // reach is the shape being reported.
+ expect(source).toMatch(
+ /const singled = \$derived\.by[\s\S]{0,600}?node\.rests\?\.one/,
+ );
+ expect(source).toContain('if (resting.has(link.from)) near.add(link.to);');
+ // Collected into a second set: growing the one being read would turn the one hop
+ // this promises into two.
+ expect(source).toContain('const near = new Set(resting);');
+ });
+
+ it('fades nothing when the drawing holds no such statement', () => {
+ // An empty narrowing fades the whole case, which answers the press with a
+ // picture saying the opposite of what was asked.
+ expect(source).toContain('if (!resting.size) return null;');
+ });
+
+ it('gives up the typed name rather than answering with an unchanged picture', () => {
+ // A search outranks this question, so leaving one on would make the press do
+ // nothing at all.
+ expect(source).toMatch(/singling = !singling;\s*if \(singling\) find = '';/);
+ });
+
+ it('says in words what the number means, and how to undo the press', () => {
+ expect(source).toContain(
+ 'These cite several sources, but one account published every one of them.',
+ );
+ expect(source).toContain('Click again to bring the rest of the case back.');
+ });
+
+ it('ranks the question under a search and over the selection', () => {
+ expect(source).toMatch(/if \(found\.size\) return found;\s*if \(singled\) return singled;/);
+ });
+
+ it('lets it go with Escape, before the handful it costs nothing to rebuild', () => {
+ expect(source).toMatch(/else if \(singling\) singling = false;\s*else if \(held\.length\)/);
+ });
+});
+
+describe('what is drawn is chosen by role, then by family', () => {
+ it('reads the types a lens leaves out rather than keeping a copy of the roles', () => {
+ // A lens narrows nodes by role: what the analyst wrote is the filing rather than
+ // the case. The roles live on the server, so a copy here would go stale the day a
+ // type is added.
+ expect(source).toContain(
+ "const lensHides = $derived(lenses.find((entry) => entry.id === lens)?.hides ?? [])",
+ );
+ // A legend row whose every member this reading leaves out is a switch with
+ // nothing behind it.
+ expect(source).toContain('if (lensHides.includes(type)) continue');
+ });
+
+ it('switches a family off from the legend, where the colours are already read', () => {
+ // The lens decides the reading; the family decides the budget. On a case larger
+ // than the budget one family dwarfs the rest, and this is what spends it elsewhere.
+ expect(source).toContain('function toggleFamily(family)');
+ expect(source).toContain('let hiddenFamilies = $state([])');
+ expect(source).toContain('aria-pressed={row.on}');
+ });
+
+ it('resolves families to types on the way out, as the Board does', () => {
+ // The family layer is server vocabulary, so it resolves here rather than
+ // needing a route of its own, and the catalog read already speaks types.
+ expect(source).toContain('const familyTypes = $derived.by');
+ expect(source).toContain('const legend = familyTypes.split(\',\');');
+ // ...and it narrows a handed-over type set rather than replacing it: a legend
+ // switch that widened the question it was applied to would do the opposite of
+ // what it says, and an allow-list with nothing in it is a real, empty answer
+ expect(source).toContain('legend.filter((type) => asked.includes(type))');
+ expect(source).toContain('params.type = both.length ? both.join(\',\') : NOTHING;');
+ });
+
+ it('resolves against the types the case holds, not the registry\'s', () => {
+ // A free-typed entity has no declared family, so an allowlist built from the
+ // registry would drop it the moment any family was switched off.
+ expect(source).toContain('caseTypes.length ? caseTypes :');
+ expect(source).toContain('return !family || !hiddenFamilies.includes(family)');
+ });
+
+ it('keeps the last family on, since a blank canvas reads as the whole case', () => {
+ // An empty type list is "no narrowing" server-side, so switching everything
+ // off would draw the case back — a control doing the opposite of what it says.
+ expect(source).toContain('if (!off && hiddenFamilies.length >= caseFamilies.length - 1) return');
+ });
+
+ it('lists the families the case holds, so one switched off can be switched back', () => {
+ // Read off the drawing, a family disappears the moment it is left out, taking
+ // the only control that could bring it back with it.
+ expect(source).toContain('const caseFamilies = $derived.by');
+ expect(source).toContain('caseTypes = Object.keys(body.by_type ?? {})');
+ });
+
+ it('reloads when a family or the folder changes', () => {
+ expect(source).toMatch(/pickFolder,\s*hiddenFamilies\.join\(','\),/);
+ });
+
+ it('uses Search+ for the same typed, review, folder and field question as the Board', () => {
+ expect(source).toMatch(
+ /const params = \{\s*lens,\s*order,\s*\.\.\.searchTerms,\s*\.\.\.\(catalogViews\.snapshotId \? \{\} : temporalTerms\),\s*\};/
+ );
+ expect(source).toContain('bind:filter={searchFilter}');
+ expect(source).toContain('if (pickFolder && !params.folder) params.folder = pickFolder;');
+ });
+});
+
+describe('a question handed over by the Board', () => {
+ it('is applied as the terms it was asked in, so any size of answer survives', () => {
+ // a list of ids would be capped and would go stale; a question is something the
+ // case can be asked again, and this one is spelled for this route already. The
+ // fact-time window rides with it, except on a snapshot, which already answered.
+ expect(source).toMatch(
+ /const params = \{\s*lens,\s*order,\s*\.\.\.searchTerms,\s*\.\.\.\(catalogViews\.snapshotId \? \{\} : temporalTerms\),\s*\};/
+ );
+ });
+
+ it('is announced over the drawing, with one press back to the case', () => {
+ // a picture that silently answers somebody else's question looks broken
+ expect(source).toContain('{#if fromBoard}');
+ expect(source).toContain("fromBoard.label || 'A question from the Board'");
+ expect(source).toContain('Show the whole case');
+ });
+
+ it('is taken out of the hand-off as it is read, so it cannot re-apply itself', () => {
+ expect(source).toContain('uiState.drawInGraph = null;');
+ expect(source).toContain('uiState.openGraphEntity = null;');
+ });
+
+ it('arrives on the whole case, never inside a neighbourhood', () => {
+ // a question about the case answered with one node's surroundings is a different
+ // question
+ expect(source).toMatch(/uiState\.drawInGraph = null;[\s\S]{0,260}root = null;/);
+ });
+
+ it('refits the view, because it is a new question rather than a growth', () => {
+ expect(source).toContain('JSON.stringify(searchTerms),');
+ });
+});
+
+describe('the way back to the table', () => {
+ it('reads a node in the Board, which is the half the hand-over was missing', () => {
+ expect(source).toContain('uiState.openBoardEntity = chosen.id;');
+ expect(source).toContain('In the Board');
+ });
+});
+
+describe('filing from the drawing', () => {
+ it('puts a new entity where the gesture aimed, on the empty space', () => {
+ // the empty space used to answer a right-click with nothing, which made the
+ // drawing a thing to read rather than a place to work
+ expect(source).toContain('blank = { x: at.x, y: at.y, at: toCanvas(at) };');
+ expect(source).toContain('New entity here');
+ expect(source).toContain('creating = { at: blank.at, caseId: caseState.current?.id };');
+ });
+
+ it('files it once, through the arrival the search already uses', () => {
+ // the reading effect sees `kept` change and reads the case once; reading here as
+ // well would be two requests for one act
+ expect(source).toContain('bringing = entity.id;');
+ expect(source).toContain('holdOn([entity.id]);');
+ });
+
+ it('leaves stating the relation to the gesture that already does it', () => {
+ // creating something and saying what it is are two acts, and the drawing already
+ // has one for the second: file the entity, then connect it by hand
+ expect(source).not.toContain('Connect to a new entity');
+ expect(source).toContain('Connect to…');
+ });
+
+ it('takes a file dropped on the canvas, at the spot it was dropped', () => {
+ expect(source).toContain('ondrop=');
+ expect(source).toContain('importDropped(event.dataTransfer?.files');
+ expect(source).toContain('/media/upload');
+ expect(source).toContain('Drop to file it here');
+ });
+
+ it('keeps the creation off the drawing’s undo stack, and offers its own way back', () => {
+ // a single stack mixing "I hid a node" with "I filed an entity" would write to the
+ // case on the fourth press to get a view back
+ expect(source).toContain("label: 'Undo',");
+ expect(source).toContain('onClick: () => dropEntity(entity, caseId),');
+ expect(source).toContain('async function dropEntity(entity, caseId = caseState.current?.id)');
+ expect(source).toContain('api.del(`/api/cases/${cid}/entities/${entity.id}`)');
+ });
+
+ it('draws what it filed and pins it, which are edits to the view', () => {
+ expect(source).toContain('holdOn([entity.id]);');
+ expect(source).toContain('pins.set(entity.id, { x: at.x, y: at.y });');
+ expect(source).toContain('dropNode(entity.id);');
+ });
+
+ it('says beforehand when this reading would not draw what is being filed', () => {
+ expect(source).toContain('hidden={lensHides}');
+ expect(source).toContain('This reading does not draw that type. My work does.');
+ });
+
+ it('shares the one create dialog rather than growing a second form', () => {
+ expect(source).toContain("import EntityCreate from '../components/EntityCreate.svelte'");
+ });
+});
+
+describe('a named live graph', () => {
+ it('captures and restores its own arrangement and camera', () => {
+ expect(source).not.toContain('delete graph.arrangement');
+ expect(source).toContain('replaceViewArrangement(saved.arrangement ?? [], view.id)');
+ expect(source).toContain("graph.camera = group");
+ expect(source).toContain('cameraRevision += 1');
+ });
+
+ it('keeps view pins out of the case-wide pin routes', () => {
+ expect(source).toMatch(
+ /function dropNode\(id\)[\s\S]{0,500}?if \(ownsViewArrangement\(\)\)[\s\S]{0,160}?return;[\s\S]{0,220}?pending\.set\(id, spot\)/,
+ );
+ expect(source).toMatch(
+ /async function unpinNode\(id\)[\s\S]{0,500}?if \(ownsViewArrangement\(\)\)[\s\S]{0,180}?return;[\s\S]{0,180}?api\.del/,
+ );
+ expect(source).toContain('node.pin ? { ...node, pin: null } : node');
+ });
+
+ it('tracks repeated drawing and camera edits for debounced autosave', () => {
+ expect(source).toContain('let arrangementSaveRevision = $state(0)');
+ expect(source).toContain('void arrangementSaveRevision');
+ expect(source).toContain('catalogViews.changeVersion += 1');
+ });
+});
+
+describe('a frozen analysis snapshot', () => {
+ it('stays on its captured surface and opens retained details without writing', () => {
+ expect(source).toContain('const snapshotReading = $derived(Boolean(catalogViews.snapshotId || payload?.snapshot))');
+ expect(source).toContain('const canArrange = $derived(!root && !snapshotReading)');
+ expect(source).toContain('disabled={snapshotReading}');
+ expect(source).toContain('if (snapshotReading) return;');
+ expect(source).toContain('{#if openId && !snapshotReading}');
+ expect(source).toContain('>Captured details</button>');
+ expect(source).toContain('<Modal title="Snapshot details"');
+ expect(source).toContain('<SnapshotDetails');
+ expect(source).toContain('{#if !snapshotReading}<button');
+ expect(source).toContain('if (!from || !to)');
+ });
+});
+
+describe('the canvas menu stays open', () => {
+ it('ignores the release of the press that opened it', () => {
+ // Konva reports a `click` on any button, so without this the right-click that
+ // opened the menu closed it again on release, and it could only be read while
+ // the button was held down
+ expect(source).toContain("if (event?.evt?.button === 2 || event?.evt?.ctrlKey) return;");
+ });
+});
+
+describe('what a control says it does', () => {
+ const tooltips = () =>
+ [...source.matchAll(/title="([^"{}]+)"/g)].map((match) => match[1]);
+
+ it('says one thing per tooltip', () => {
+ // A tooltip that runs to two sentences is a paragraph on a hover: the second
+ // one is read by nobody and the first is what the control does.
+ const wordy = tooltips().filter((text) => /\.\s+\S/.test(text));
+
+ expect(wordy).toEqual([]);
+ });
+
+ it('states the guarantee on the act that needs it, and nowhere else', () => {
+ // Undo, Reset view, Unfold and Collapse all used to end by promising the case
+ // was untouched. Said five times it stops being read; said once, on the act
+ // whose name sounds like a delete, it lands.
+ const reassuring = tooltips().filter((text) =>
+ /nothing (is|was) (deleted|hidden)|case is not touched/i.test(text)
+ );
+
+ expect(reassuring).toEqual([]);
+ expect(source).toContain('Out of the drawing, not out of the case');
+ });
+
+ it('spells one act one way, wherever it is offered', () => {
+ // Hide is offered on the panel, in the node menu and over a gathered handful.
+ // Three wordings for one act read as three behaviours.
+ const hiding = tooltips().filter((text) => text.includes('not out of the case'));
+
+ expect(new Set(hiding).size).toBe(1);
+ expect(hiding.length).toBeGreaterThan(1);
+ });
+});
+
+describe('Ctrl+V on the drawing', () => {
+ it('draws a pasted screenshot or link where the eye already is', () => {
+ expect(source).toContain("import { listenForPaste, pasteImage, resolvePaste } from '../lib/clipboardPaste.js'");
+ expect(source).toContain("import PasteDialog from '../components/PasteDialog.svelte'");
+ expect(source).toContain("resolvePaste('graph', payload)");
+ // a paste has no pointer position the way a drop does, so the viewport centre
+ // is the honest spot
+ expect(source).toContain('toCanvas({ x: width / 2, y: height / 2 })');
+ });
+
+ it('files it through the same arrival a created node uses', () => {
+ // drewIn pins, reads once and offers Undo — a second path would be a second
+ // set of rules about what happens after something is filed
+ expect(source).toContain('drewIn(result.entity, at, cid)');
+ expect(source).toContain('drewIn(entity, at, cid)');
+ });
+
+ it('only answers while it is the tool on screen', () => {
+ expect(source).toMatch(/uiState\.tool !== 'graph'\) return;\s*return listenForPaste/);
+ });
+
+ it('refuses to write into a frozen reading, and says why', () => {
+ expect(source).toContain("say('This snapshot is read-only. Leave it to paste.')");
+ expect(source).toContain('{#if pasted && !snapshotReading}');
+ });
+});
diff --git a/frontend/src/tools/Inspector.svelte b/frontend/src/tools/Inspector.svelte
index 31e18c9..ed942cd 100644
--- a/frontend/src/tools/Inspector.svelte
+++ b/frontend/src/tools/Inspector.svelte
@@ -1,5 +1,6 @@
<script>
import { api } from '../lib/api.js';
+ import { fileUrl } from '../lib/fileUrl.js';
import { fetchAllEntities, lookupEntity } from '../lib/catalog.js';
import { matchesTerms } from '../lib/folderBrowse.js';
import { caseState, uiState, reloadCase, toast } from '../lib/state.svelte.js';
@@ -8,7 +9,9 @@
collageBounds, quadFromCropRect, cropImgStyle, cropAspect, styleText, hasVideoEdits,
normalizeRightAngleRotation, rotationOps, sourceStem, frameSaveNames, autoSaveNames, saveNameOf,
} from '../lib/inspect.js';
- import { isDefaultName, nextName, savedSlugs, savedTitles, savedTitle, slugify } from '../lib/naming.js';
+ import {
+ isDefaultName, nextName, savedSlugs, savedTitles, savedTitle, slugify, specAttr, specPath,
+ } from '../lib/naming.js';
import { createHistory } from '../lib/history.js';
import { deletedToast } from '../lib/trash.js';
import { IDENTITY, matrixCss, rotateAbout, isIdentity, matrixAngleDeg, pointerAngleDeg } from '../lib/frameRotate.js';
@@ -261,7 +264,7 @@
const cid = caseState.current?.id;
const stem = stemFor(session.source?.path, session.source);
if (session.source?.kind === 'video' && hasVideoEdits(videoFilters, session.videoAdjust, videoRotation)) {
- const t = session.source.thumbnail ? `/files/${cid}/${session.source.thumbnail}` : null;
+ const t = session.source.thumbnail ? fileUrl(cid, session.source.thumbnail) : null;
out.push({
key: 'video', kind: 'video', defaultName: `${stem} (enhanced)`, thumb: t,
filter: videoPreview.filter, transform: videoPreviewTransform,
@@ -392,7 +395,7 @@
let live = true;
(async () => {
if (sessionName) {
- const bound = await lookupEntity(id, 'spec', `inspect/${sessionName}.json`);
+ const bound = await lookupEntity(id, specAttr('session'), specPath('session', sessionName));
if (live && !bound && openedSession?.name === sessionName) {
openedSession = null;
toast('The saved session was deleted. Saving now creates a new one', 'warn');
@@ -584,7 +587,7 @@
session.videoAdjust = adjustDefaults(videoFilters);
activeTab = 'selection';
} else {
- const frame = makeFrame(item.path, null, `/files/${caseState.current.id}/${item.path}`);
+ const frame = makeFrame(item.path, null, fileUrl(caseState.current.id, item.path));
session.frames.push(frame);
session.activeFrameId = frame.id;
activeTab = 'frame';
@@ -1308,7 +1311,7 @@
{#if activeTab === 'selection'}
<VideoPlayer
bind:video={videoEl}
- src={`/files/${caseState.current?.id}/${session.source.path}`}
+ src={fileUrl(caseState.current?.id, session.source.path)}
filter={videoPreview.filter}
transform={videoPreviewTransform}
quarterTurn={videoQuarterTurn}
@@ -1531,7 +1534,7 @@
<button class="source-open" onclick={() => selectNewSource(m)}>
<div class="source-thumb">
{#if m.thumbnail}
- <img src={`/files/${caseState.current.id}/${m.thumbnail}`} alt="" loading="lazy" />
+ <img src={fileUrl(caseState.current.id, m.thumbnail)} alt="" loading="lazy" />
{:else}
<Icon name={m.kind === 'video' ? 'video' : 'image'} size={22} />
{/if}
diff --git a/frontend/src/tools/Inspector.test.js b/frontend/src/tools/Inspector.test.js
index 1eafa08..9421f37 100644
--- a/frontend/src/tools/Inspector.test.js
+++ b/frontend/src/tools/Inspector.test.js
@@ -36,6 +36,14 @@ describe('Inspect sessions', () => {
expect(source).toContain("const signature = () => JSON.stringify([sessionName.trim(), sessionSpec()]);");
});
+ it('checks the current hidden spec path before claiming a saved session was deleted', () => {
+ // Sessions moved from `inspect/` to `.inspect/` when the case folder hid its
+ // machinery. The old literal matched no entity, so every save dropped the
+ // binding and warned the session had been deleted. Ask the helper instead.
+ expect(source).toContain("lookupEntity(id, specAttr('session'), specPath('session', sessionName))");
+ expect(source).not.toContain('`inspect/${sessionName}.json`');
+ });
+
it('asks before an unbound workspace takes a name another session holds', () => {
expect(source).toContain('if (!openedSession && takenSlugs().has(slug))');
expect(source).toContain('title="Overwrite this session?"');
diff --git a/frontend/src/tools/MediaLibrary.svelte b/frontend/src/tools/MediaLibrary.svelte
index 0fd44e6..b50b8e3 100644
--- a/frontend/src/tools/MediaLibrary.svelte
+++ b/frontend/src/tools/MediaLibrary.svelte
@@ -1,5 +1,6 @@
<script>
import { api } from '../lib/api.js';
+ import { fileUrl } from '../lib/fileUrl.js';
import { lookupEntity } from '../lib/catalog.js';
import { buildMediaQuery } from '../lib/mediaQuery.js';
import { createPagedList } from '../lib/pagedList.svelte.js';
@@ -7,16 +8,21 @@
import { caseState, uiState, ensureCase, reloadCase, toast } from '../lib/state.svelte.js';
import {
hasMediaForFilters,
+ isBroughtIn,
isGenericImage,
+ isMadeHere,
isSatelliteMedia,
mediaDisplayKind,
mediaPoint,
visibleMedia,
SORTS,
} from '../lib/mediaFilter.js';
+ import { listenForPaste, pasteImage, resolvePaste } from '../lib/clipboardPaste.js';
import { gotoPoint } from '../lib/navigate.js';
+ import { revealMediaFolder } from '../lib/reveal.js';
import { deletedToast, RESTORABLE } from '../lib/trash.js';
import Icon from '../components/Icon.svelte';
+ import PasteDialog from '../components/PasteDialog.svelte';
import SearchInput from '../components/SearchInput.svelte';
import Modal from '../components/Modal.svelte';
import ConfirmDialog from '../components/ConfirmDialog.svelte';
@@ -39,6 +45,7 @@
category: catFilter,
folder: folderFilter,
gps: gpsOnly,
+ collectedOnly,
sort,
direction: sortDirection,
limit: PAGE,
@@ -80,7 +87,7 @@
{ key: 'video', label: 'Videos', icon: 'video', match: (i) => i.kind === 'video' },
{ key: 'collage', label: 'Collages', icon: 'layers', match: (i) => i.source?.op === 'collage' },
{ key: 'satellite', label: 'Satellite', icon: 'satellite', match: isSatelliteMedia },
- { key: 'upload', label: 'Imports', icon: 'upload', match: (i) => i.source?.type === 'upload' },
+ { key: 'upload', label: 'Imports', icon: 'upload', match: isBroughtIn },
{ key: 'download', label: 'Downloads', icon: 'download', match: (i) => i.source?.type === 'download' },
{ key: 'other', label: 'Other files', icon: 'file', match: (i) => i.kind !== 'image' && i.kind !== 'video' },
];
@@ -107,6 +114,18 @@
pl.facets?.gps_count ?? items.filter((i) => mediaPoint(i)).length
);
+ // --- what the case made, out of the way (independent of type and folder) ---
+ // A geolocation case ends up with 150 extracted frames beside 50 collected
+ // files, and the question "what did we actually collect" has no answer in a
+ // chooser: the chips are single-select and say "show me only X". This is the
+ // other axis, so it is a switch. On by default — the library opens on what the
+ // case collected, and the switch is how the working files come back; it says
+ // how many they are rather than leaving them unannounced.
+ let collectedOnly = $state(true);
+ const madeHereCount = $derived(
+ pl.facets?.made_here_count ?? items.filter(isMadeHere).length
+ );
+
// --- free-text search + sort ---
let query = $state('');
let sort = $state('name');
@@ -120,12 +139,14 @@
{ id: 'added', label: 'Added' },
];
const browseFiltersActive = $derived(
- query.length > 0 || catFilter !== null || folderFilter !== null || gpsOnly
+ query.length > 0 || catFilter !== null || folderFilter !== null || gpsOnly || !collectedOnly
);
const filtersActive = $derived(
browseFiltersActive || sort !== 'name' || sortDirection !== 'asc'
);
- const showBrowseBar = $derived(items.length > 0 || browseFiltersActive);
+ // Also shown for a case whose files are all working ones: the grid is empty
+ // because the switch is on, and the switch is in this bar.
+ const showBrowseBar = $derived(items.length > 0 || browseFiltersActive || madeHereCount > 0);
const folders = $derived(
[
@@ -145,6 +166,7 @@
catMatch,
folderFilter,
gpsOnly,
+ collectedOnly,
query,
sort,
direction: sortDirection,
@@ -204,6 +226,14 @@
reloadIfServerBacked();
}
+ function toggleCollectedOnly() {
+ collectedOnly = !collectedOnly;
+ // Always refetch, unlike the other filters: this one is on at load, so the
+ // page in memory is the collected subset and no in-memory pass can put the
+ // working files back. Every other control only ever narrows what was loaded.
+ if (caseState.current) pl.reload();
+ }
+
/** The stated position, spelled out. Lives in the tooltip rather than in the
* row: a filename is what the analyst reads a list by. */
function pointLabel(item) {
@@ -224,6 +254,7 @@
catFilter = null;
folderFilter = null;
gpsOnly = false;
+ collectedOnly = true;
sort = 'name';
sortDirection = 'asc';
headerSort = null;
@@ -241,6 +272,16 @@
// --- details modal (shared EntityDetails, keyed by the file's entity id) ---
let infoEntityId = $state(null);
+ // The panel's fields wait for Save while its connections file themselves, so
+ // Escape and the backdrop ask before throwing an edit away.
+ let infoDirty = $state(false);
+ let infoDiscarding = $state(false);
+
+ function closeInfo() {
+ if (infoDirty) infoDiscarding = true;
+ else infoEntityId = null;
+ }
+
let infoItem = $state(null); // the media row behind the details modal, for Export
// Where a media copy lands, app-wide and remembered. Empty = the case folder.
let exportDir = $state('');
@@ -410,6 +451,17 @@
}
}
+ /** Hand a file the app cannot display back to the desktop, in its own folder.
+ * A download would put a second copy in Downloads and invite editing the one
+ * the case does not know about. */
+ async function revealFolder(item) {
+ try {
+ await revealMediaFolder(caseState.current.id, item.path);
+ } catch (e) {
+ toast(e.message, 'warn', 5000);
+ }
+ }
+
async function importFiles(fileList) {
const files = [...fileList];
if (!files.length) return;
@@ -596,6 +648,46 @@
importFiles(e.dataTransfer.files);
}
+ // ── paste ────────────────────────────────────────────────────────────────
+ // A screenshot taken with the system tool is only in the clipboard: there is no
+ // file to drop, so without this it has to be saved to disk first. A link is
+ // refused here and says so — this grid takes files, and a URL is the download
+ // field's business.
+ let pasted = $state(null);
+ let pasteBusy = $state(false);
+ $effect(() => {
+ if (uiState.tool !== 'media') return;
+ return listenForPaste((payload) => {
+ pasted ??= resolvePaste('media', payload);
+ });
+ });
+
+ async function confirmPaste(resolved) {
+ if (pasteBusy) return;
+ pasteBusy = true;
+ try {
+ const c = await ensureCase();
+ const result = await pasteImage(c.id, {
+ file: resolved.payload.file,
+ title: resolved.values.title,
+ sourceUrl: resolved.values.source,
+ });
+ pasted = null;
+ await Promise.all([refresh(), reloadCase()]);
+ // The same bytes twice is not an error and not a second item: the case keeps
+ // the one it has, and saying so is what stops the analyst pasting again.
+ if (result.duplicate) toast('Already in the case (same SHA-256)', 'warn');
+ else {
+ toast('Image added to the case', 'ok');
+ uiState.focusMedia = result.item.path;
+ }
+ } catch (e) {
+ toast(`Could not add the image: ${e.message}`, 'danger');
+ } finally {
+ pasteBusy = false;
+ }
+ }
+
// Open the shared details editor (same body as the case sidebar) for this
// file's case entity — full provenance, derivation chain, title/notes/folder.
async function openInfo(item) {
@@ -762,6 +854,27 @@
</button>
{/if}
+ <!-- Offered only where the case made something, so a case of imports never
+ carries a dead control. Resting, it says how many files it is holding
+ back rather than letting them stay out of the grid quietly. -->
+ {#if madeHereCount || !collectedOnly}
+ <button
+ class="btn btn-sm gps-filter"
+ class:on={!collectedOnly}
+ type="button"
+ aria-pressed={!collectedOnly}
+ title={collectedOnly
+ ? `Show the ${madeHereCount} file${madeHereCount > 1 ? 's' : ''} the case made from material it already holds`
+ : 'Show only what the case collected'}
+ onclick={toggleCollectedOnly}
+ >
+ <Icon name="layers" size={13} />
+ {collectedOnly
+ ? `Show ${madeHereCount} working file${madeHereCount > 1 ? 's' : ''}`
+ : 'Hide working files'}
+ </button>
+ {/if}
+
<!-- user-defined folders (independent facet) -->
{#if folders.length}
<span class="bar-sep"></span>
@@ -808,7 +921,17 @@
</div>
{/each}
- {#if !items.length && !jobs.length && !browseFiltersActive}
+ {#if !items.length && !jobs.length && !browseFiltersActive && madeHereCount}
+ <!-- A case of nothing but frames and collages opens on an empty grid. It
+ holds files, so say which ones rather than offering to import. -->
+ <div class="empty" style="height: 100%">
+ <div class="empty-icon"><Icon name="layers" size={38} /></div>
+ <h3>Nothing collected yet</h3>
+ <p>
+ {madeHereCount} working file{madeHereCount > 1 ? 's' : ''}, held back by the switch above.
+ </p>
+ </div>
+ {:else if !items.length && !jobs.length && !browseFiltersActive}
<div class="empty" style="height: 100%">
<div class="empty-icon"><Icon name="media" size={42} /></div>
<h3>No media yet</h3>
@@ -857,7 +980,7 @@
>
{#if item.thumbnail && item.thumb_state === 'ready' && !brokenThumbs.has(mediaKey(item))}
<img
- src={`/files/${caseState.current.id}/${item.thumbnail}`}
+ src={fileUrl(caseState.current.id, item.thumbnail)}
data-media-key={mediaKey(item)}
alt=""
loading="lazy"
@@ -898,15 +1021,25 @@
<button class="btn btn-ghost btn-sm" title="Info / Edit notes" onclick={() => openInfo(item)}>
<Icon name="note" size={14} />
</button>
- <a
- class="btn btn-ghost btn-sm"
- href={`/files/${caseState.current.id}/${item.path}`}
- target="_blank"
- rel="noreferrer"
- title="Open file"
- >
- <Icon name="external" size={14} />
- </a>
+ {#if item.kind === 'file'}
+ <button
+ class="btn btn-ghost btn-sm"
+ title="Open the folder this file is in"
+ onclick={() => revealFolder(item)}
+ >
+ <Icon name="folderOpen" size={14} />
+ </button>
+ {:else}
+ <a
+ class="btn btn-ghost btn-sm"
+ href={fileUrl(caseState.current.id, item.path)}
+ target="_blank"
+ rel="noreferrer"
+ title="Open file"
+ >
+ <Icon name="external" size={14} />
+ </a>
+ {/if}
{#if item.kind === 'image' || item.kind === 'video'}
<button class="btn btn-ghost btn-sm" title="Open in Inspect" onclick={() => inspect(item)}>
<Icon name="inspect" size={14} />
@@ -946,7 +1079,7 @@
>
{#if item.thumbnail && item.thumb_state === 'ready' && !brokenThumbs.has(mediaKey(item))}
<img
- src={`/files/${caseState.current.id}/${item.thumbnail}`}
+ src={fileUrl(caseState.current.id, item.thumbnail)}
data-media-key={mediaKey(item)}
alt={item.filename}
loading="lazy"
@@ -1011,15 +1144,25 @@
>
<Icon name="note" size={14} />
</button>
- <a
- class="btn btn-ghost btn-sm"
- href={`/files/${caseState.current.id}/${item.path}`}
- target="_blank"
- rel="noreferrer"
- title="Open file"
- >
- <Icon name="external" size={14} />
- </a>
+ {#if item.kind === 'file'}
+ <button
+ class="btn btn-ghost btn-sm"
+ title="Open the folder this file is in"
+ onclick={() => revealFolder(item)}
+ >
+ <Icon name="folderOpen" size={14} />
+ </button>
+ {:else}
+ <a
+ class="btn btn-ghost btn-sm"
+ href={fileUrl(caseState.current.id, item.path)}
+ target="_blank"
+ rel="noreferrer"
+ title="Open file"
+ >
+ <Icon name="external" size={14} />
+ </a>
+ {/if}
{#if item.kind === 'image' || item.kind === 'video'}
<button
class="btn btn-ghost btn-sm"
@@ -1163,9 +1306,10 @@
<!-- details modal: the same editor body as the case sidebar (provenance,
derivation chain, title/notes/folder) so both stay in step -->
{#if infoEntityId}
- <Modal title="Details" onclose={() => (infoEntityId = null)} width="520px">
+ <Modal title="Details" onclose={closeInfo} width="520px">
<EntityDetails
entityId={infoEntityId}
+ bind:dirty={infoDirty}
onclose={() => (infoEntityId = null)}
ondeleted={() => (infoEntityId = null)}
>
@@ -1187,6 +1331,17 @@
</Modal>
{/if}
+{#if infoDiscarding}
+ <ConfirmDialog
+ title="Discard changes?"
+ message="This item has edits that Save has not taken."
+ confirmLabel="Discard"
+ icon="alert"
+ onconfirm={() => { infoDiscarding = false; infoDirty = false; infoEntityId = null; }}
+ oncancel={() => (infoDiscarding = false)}
+ />
+{/if}
+
{#if exportPicker}
<ExportFolderPicker
kind="media"
@@ -1229,7 +1384,7 @@
</button>
{/if}
<img
- src={`/files/${caseState.current.id}/${lightboxItem.path}`}
+ src={fileUrl(caseState.current.id, lightboxItem.path)}
alt={lightboxItem.filename}
/>
<span class="lb-caption">
@@ -1256,6 +1411,16 @@
/>
{/if}
+<!-- Ctrl+V: the screenshot that only exists in the clipboard -->
+{#if pasted}
+ <PasteDialog
+ resolved={pasted}
+ busy={pasteBusy}
+ onconfirm={confirmPaste}
+ onclose={() => (pasted = null)}
+ />
+{/if}
+
<style>
.tool {
position: relative;
diff --git a/frontend/src/tools/MediaLibrary.test.js b/frontend/src/tools/MediaLibrary.test.js
index d6a2eb7..47fe953 100644
--- a/frontend/src/tools/MediaLibrary.test.js
+++ b/frontend/src/tools/MediaLibrary.test.js
@@ -122,6 +122,57 @@ describe('Media Library positions', () => {
});
});
+describe('Media Library — what the case collected', () => {
+ it('is a switch beside the chips, not another chip', () => {
+ // The chips are single-select and each says "show me only X". This is the
+ // other axis — get X out of my way — the way the position filter already is.
+ expect(source).toContain('function toggleCollectedOnly()');
+ expect(source).toContain('aria-pressed={!collectedOnly}');
+ });
+
+ it('opens on what the case collected, working files held back', () => {
+ expect(source).toContain('let collectedOnly = $state(true)');
+ });
+
+ it('filters server-side, so the counts and the paging cannot disagree with it', () => {
+ expect(source).toContain('collectedOnly,');
+ // ...and through the same shared predicate client-side
+ expect(source).toContain('isMadeHere');
+ });
+
+ it('refetches on every toggle, since the loaded page is already the subset', () => {
+ // The other filters only narrow what was loaded; this one is on at load, so
+ // turning it off has to go and get the working files.
+ expect(source).toContain(
+ 'function toggleCollectedOnly() {\n collectedOnly = !collectedOnly;'
+ );
+ expect(source).toContain('if (caseState.current) pl.reload();');
+ });
+
+ it('says how many it is holding back rather than hiding them quietly', () => {
+ expect(source).toContain('pl.facets?.made_here_count ?? items.filter(isMadeHere).length');
+ expect(source).toContain('`Show ${madeHereCount} working file${madeHereCount > 1 ? \'s\' : \'\'}`');
+ expect(source).toContain(": 'Hide working files'");
+ });
+
+ it('does not appear in a case that made nothing', () => {
+ expect(source).toContain('{#if madeHereCount || !collectedOnly}');
+ });
+
+ it('tells a case of nothing but working files that it holds some', () => {
+ // Without this the default hides every file the case has and the grid says
+ // "No media yet", which is false.
+ expect(source).toContain(
+ '{#if !items.length && !jobs.length && !browseFiltersActive && madeHereCount}'
+ );
+ expect(source).toContain('<h3>Nothing collected yet</h3>');
+ });
+
+ it('counts as a browse filter only once the working files are showing', () => {
+ expect(source).toContain('|| gpsOnly || !collectedOnly');
+ });
+});
+
describe('Media Library names', () => {
it('shows the canonical stem once and keeps the extension out of the title', () => {
expect(source).toContain('<span class="list-name">{item.title ?? item.filename}</span>');
@@ -172,9 +223,11 @@ describe('Media Library search empty state', () => {
it('keeps the search bar available when a search has no matches', () => {
expect(source).toContain('const browseFiltersActive = $derived(');
expect(source).toContain('query.length > 0 || catFilter !== null || folderFilter !== null');
- expect(source).toContain('const showBrowseBar = $derived(items.length > 0 || browseFiltersActive)');
+ expect(source).toContain(
+ 'const showBrowseBar = $derived(items.length > 0 || browseFiltersActive || madeHereCount > 0)'
+ );
expect(source).toContain('{#if showBrowseBar}');
- expect(source).toContain('{#if !items.length && !jobs.length && !browseFiltersActive}');
+ expect(source).toContain('{:else if !items.length && !jobs.length && !browseFiltersActive}');
});
it('describes media fields without mentioning notes', () => {
@@ -257,7 +310,7 @@ describe('Media Library browse controls', () => {
it('offers a right-side reset button for all browse filters', () => {
expect(source).toContain('function resetFilters()');
- expect(source).toContain("query = '';\n catFilter = null;\n folderFilter = null;\n gpsOnly = false;\n sort = 'name';\n sortDirection = 'asc';");
+ expect(source).toContain("query = '';\n catFilter = null;\n folderFilter = null;\n gpsOnly = false;\n collectedOnly = true;\n sort = 'name';\n sortDirection = 'asc';");
expect(source).toContain('class="btn btn-ghost btn-sm reset-filters"');
expect(source).toContain('Reset filters');
expect(source).toContain('<Icon name="reset" size={13} /> Reset filters');
@@ -347,3 +400,40 @@ describe('row and card actions fit', () => {
expect(source).not.toMatch(/\n \.actions \{[^}]*flex-wrap: wrap/);
});
});
+
+describe('a file the library cannot display', () => {
+ it('opens the folder it sits in rather than downloading a copy', () => {
+ expect(source).toContain("import { revealMediaFolder } from '../lib/reveal.js'");
+ expect(source).toContain('async function revealFolder(item)');
+ expect(source).toContain('title="Open the folder this file is in"');
+ // and the images, video and audio it does display keep the direct link
+ expect(source).toContain('title="Open file"');
+ });
+});
+
+describe('Ctrl+V on the grid', () => {
+ it('files a screenshot that exists nowhere but the clipboard', () => {
+ // dropping already covers a file; this covers what has no file to drop
+ expect(source).toContain("import { listenForPaste, pasteImage, resolvePaste } from '../lib/clipboardPaste.js'");
+ expect(source).toContain("import PasteDialog from '../components/PasteDialog.svelte'");
+ expect(source).toContain("resolvePaste('media', payload)");
+ });
+
+ it('only answers while it is the tool on screen', () => {
+ // every visited tool stays mounted behind the visible one (App.svelte), so an
+ // ungated listener would have four surfaces answering one Ctrl+V
+ expect(source).toMatch(/uiState\.tool !== 'media'\) return;\s*return listenForPaste/);
+ });
+
+ it('leaves a paste it is already asking about alone', () => {
+ expect(source).toContain('pasted ??= resolvePaste');
+ });
+
+ it('rings the new card so the paste is never filed out of sight', () => {
+ expect(source).toContain('uiState.focusMedia = result.item.path');
+ });
+
+ it('says a duplicate is one already, and files nothing twice', () => {
+ expect(source).toContain("toast('Already in the case (same SHA-256)', 'warn')");
+ });
+});
diff --git a/frontend/src/tools/PostComposer.svelte b/frontend/src/tools/PostComposer.svelte
index 3587db9..e2403a7 100644
--- a/frontend/src/tools/PostComposer.svelte
+++ b/frontend/src/tools/PostComposer.svelte
@@ -1,5 +1,6 @@
<script>
import { api } from '../lib/api.js';
+ import { fileUrl } from '../lib/fileUrl.js';
import { fetchAllEntities, lookupEntity, fetchDerivation } from '../lib/catalog.js';
import { caseState, uiState, toast, reloadCase, prefs } from '../lib/state.svelte.js';
import { templatesState } from '../lib/state.svelte.js';
@@ -7,7 +8,9 @@
import { openNotebook } from '../lib/navigate.js';
import { deletedToast, RESTORABLE } from '../lib/trash.js';
import { proofCoordsText, proofSource } from '../lib/composer.js';
- import { isDefaultName, nextName, savedSlugs, savedTitles, savedTitle, slugify } from '../lib/naming.js';
+ import {
+ isDefaultName, nextName, savedSlugs, savedTitles, savedTitle, slugify, specAttr, specPath,
+ } from '../lib/naming.js';
import { filingName, planProofHandoff } from './post/handoff.js';
import {
buildTweet1 as buildTweet1Lines, DEFAULT_TWEET_BODY,
@@ -101,7 +104,7 @@
let live = true;
(async () => {
if (draft) {
- const bound = await lookupEntity(id, 'draft', `exports/${draft}.json`);
+ const bound = await lookupEntity(id, specAttr('draft'), specPath('draft', draft));
if (live && !bound && draftName === draft) {
draftName = null;
toast('The saved draft was deleted. Saving now creates a new one', 'warn');
@@ -601,7 +604,7 @@
}
function mediaHref(path) {
- return path && caseState.current ? `/files/${caseState.current.id}/${path}` : null;
+ return path && caseState.current ? fileUrl(caseState.current.id, path) : null;
}
function mediaKind(path) {
@@ -610,7 +613,7 @@
const proofHref = $derived(
proofPng && caseState.current
- ? `/files/${caseState.current.id}/${proofPng}${proofVer ? `?v=${proofVer}` : ''}`
+ ? `${fileUrl(caseState.current.id, proofPng)}${proofVer ? `?v=${proofVer}` : ''}`
: null
);
@@ -934,6 +937,14 @@
title: reportModal.title,
folder: reportModal.folder,
content: reportContent(reportModal.title.trim(), evidence),
+ // What the report was written from: the proof and media it embeds, and the
+ // draft it was composed in when that draft is saved. The note reads as a
+ // page of case files, so the graph has to say which ones — otherwise
+ // deleting a proof leaves a dead image nothing accounted for.
+ sources: [
+ ...reportAttachmentPaths(),
+ ...(draftName ? [specPath('draft', draftName)] : []),
+ ],
});
await reloadCase();
reportModal = null;
@@ -1491,7 +1502,7 @@
>
<div class="picker-thumb">
{#if item.thumbnail}
- <img src={`/files/${caseState.current.id}/${item.thumbnail}`} alt={item.path} />
+ <img src={fileUrl(caseState.current.id, item.thumbnail)} alt={item.path} />
{:else}
<Icon name={item.kind === 'video' ? 'video' : item.kind === 'audio' ? 'audio' : 'file'} size={24} />
{/if}
@@ -1519,7 +1530,7 @@
<button class="picker-item" onclick={() => pickProof(item)} title={item.title} disabled={!item.png}>
<div class="picker-thumb">
{#if item.png}
- <img src={`/files/${caseState.current.id}/${item.png}`} alt={item.title} />
+ <img src={fileUrl(caseState.current.id, item.png)} alt={item.title} />
{:else}
<Icon name="proof" size={24} />
{/if}
diff --git a/frontend/src/tools/PostComposer.test.js b/frontend/src/tools/PostComposer.test.js
index 407dfc5..a7d449f 100644
--- a/frontend/src/tools/PostComposer.test.js
+++ b/frontend/src/tools/PostComposer.test.js
@@ -36,6 +36,18 @@ describe('Geo Report actions', () => {
expect(body).toContain('Publish on');
expect(body).not.toContain('Copy report');
});
+
+ it('files the report note against what it was written from', () => {
+ // the note embeds the proof and its media, so the graph has to say which case
+ // files it depends on — otherwise deleting a proof leaves a dead image link
+ // nothing accounted for, and the note sits in the case with no chain at all
+ expect(source).toContain('...reportAttachmentPaths(),');
+ expect(source).toContain("...(draftName ? [specPath('draft', draftName)] : []),");
+ });
+
+ it('checks the current hidden draft path before claiming a saved draft was deleted', () => {
+ expect(source).toContain("lookupEntity(id, specAttr('draft'), specPath('draft', draft))");
+ });
});
describe('Proof handoff', () => {
diff --git a/frontend/src/tools/ProofComposer.svelte b/frontend/src/tools/ProofComposer.svelte
index 55c6d46..384ef7f 100644
--- a/frontend/src/tools/ProofComposer.svelte
+++ b/frontend/src/tools/ProofComposer.svelte
@@ -1,5 +1,6 @@
<script>
import { onMount } from 'svelte';
+ import { fileUrl } from '../lib/fileUrl.js';
import Konva from 'konva';
import { api } from '../lib/api.js';
import { lookupEntity, fetchAllEntities } from '../lib/catalog.js';
@@ -44,7 +45,9 @@
import {
assetName, base64Of, PASTE_TYPES, MAX_PASTES, MAX_PASTE_BYTES,
} from '../lib/pasteAsset.js';
- import { nextName, savedSlugs, savedTitles, savedTitle, slugify } from '../lib/naming.js';
+ import {
+ nextName, savedSlugs, savedTitles, savedTitle, slugify, specAttr, specPath,
+ } from '../lib/naming.js';
import { createHistory } from '../lib/history.js';
import { pollWhile } from '../lib/poll.js';
@@ -69,6 +72,7 @@
title: '', panels: [], pastes: [], shapes: [], notes: {}, legendOrder: [],
templateId: null, // selected saved house style; its values remain copied below
coordsText: '', source: '', // '' → auto-derived from panels; non-empty → manual override
+ pov: false, // the point is where the camera stood, not what it filmed
captionSize: CAPTION_SIZE, legendSize: LEGEND_SIZE, footerSize: FOOTER_SIZE, footer: '',
footerEnabled: true, // false → no footer line at all
footerColor: null, // null → auto from the background
@@ -110,7 +114,7 @@
const name = savedName;
if (!id || !name) return;
let live = true;
- lookupEntity(id, 'spec', `proofs/.meta/${name}.json`).then((bound) => {
+ lookupEntity(id, specAttr('proof'), specPath('proof', name)).then((bound) => {
if (live && !bound && savedName === name) {
savedName = null;
dirty = true;
@@ -248,6 +252,7 @@
if (pathDraft) finishPath(false);
proof.title = spec.title ?? freshTitle();
proof.coordsText = spec.coordsText ?? '';
+ proof.pov = spec.pov === true;
proof.source = spec.source ?? '';
proof.captionSize = style.captionSize;
proof.legendSize = style.legendSize;
@@ -276,7 +281,7 @@
proof.shapes = spec.shapes ?? [];
// a panel image missing from the cache (shouldn't happen) reloads async
for (const p of proof.panels.filter((x) => !x.img)) {
- loadImage(`/files/${caseState.current?.id}/${p.src}`)
+ loadImage(fileUrl(caseState.current?.id, p.src))
.then((img) => {
imgCache.set(p.src, img);
p.img = img;
@@ -751,7 +756,7 @@
async function addPanel(item) {
try {
proofStarted = true;
- const img = await loadImage(`/files/${caseState.current.id}/${item.src}`);
+ const img = await loadImage(fileUrl(caseState.current.id, item.src));
imgCache.set(item.src, img);
// A template can stack the first pair. Later panels keep joining the
// current bottom row, preserving the composer's existing workflow.
@@ -1000,19 +1005,26 @@
!!el && (['INPUT', 'TEXTAREA', 'SELECT'].includes(el.tagName) || el.isContentEditable);
/**
- * One place decides what Ctrl+V means: an image in the system clipboard is
- * what the analyst just copied, so it wins; otherwise the copied annotation is
- * pasted, which is what this shortcut did before images could be pasted.
+ * One place decides what Ctrl+V means, and the rule is which copy came last.
+ *
+ * Two clipboards answer one chord: the system's, which may hold a screenshot from
+ * an hour ago, and this composer's, which holds the annotation just copied. Only
+ * one of them is visible to this page, so freshness cannot be compared directly —
+ * what can be is whether the analyst left. A copy made here without leaving the
+ * window is necessarily the more recent of the two, so it wins; going somewhere
+ * else and coming back is the only way an outside copy could have happened, and
+ * that hands the chord back to the system clipboard. Without this, Ctrl+C on a
+ * rectangle followed by Ctrl+V pasted whatever image was in the clipboard.
*/
function onPaste(e) {
if (uiState.tool !== 'proof' || isTextTarget(e.target)) return;
const item = [...(e.clipboardData?.items ?? [])].find((i) => i.type.startsWith('image/'));
- if (item) {
- e.preventDefault();
- addPastedImage(item.getAsFile());
- } else if (clipboard) {
+ if (clipboard && (shapeCopyFresh || !item)) {
e.preventDefault();
pasteShape();
+ } else if (item) {
+ e.preventDefault();
+ addPastedImage(item.getAsFile());
}
}
@@ -2007,13 +2019,26 @@
// ---- clipboard (copy / paste / duplicate of a single element) ---------------
let clipboard = null; // detached deep copy of a shape spec (no id)
+ /** Whether that copy is the last one the analyst made without leaving the window.
+ * What lets Ctrl+V tell a shape just copied here from an older screenshot sitting
+ * in the system clipboard (see `onPaste`). */
+ let shapeCopyFresh = false;
function copyShape(id = selectedId) {
const s = proof.shapes.find((x) => x.id === id);
if (!s) return;
clipboard = copyShapeSpec(s);
+ shapeCopyFresh = true;
}
+ // The composer only ever hears about its own copies, so losing focus is the one
+ // signal that the system clipboard may have moved on since.
+ $effect(() => {
+ const release = () => (shapeCopyFresh = false);
+ window.addEventListener('blur', release);
+ return () => window.removeEventListener('blur', release);
+ });
+
// Paste the clipboard as a fresh element, nudged down-right so it doesn't hide
// the original. Points-based kinds shift every vertex.
function pasteShape() {
@@ -2311,6 +2336,58 @@
const freshTitle = () => nextName('proof', savedProofTitles());
let overwritePrompt = $state(null); // { slug, andPost } when a save hits a named proof
+ // { name, lat, lon } — the point a save carried, where the setting says to ask
+ // first. Only ever set for a point the case does not already hold.
+ let placeOffer = $state(null);
+ let placeSaving = $state(false);
+ // [{ id, label }] — points this save moved the proof off that nothing else in
+ // the case holds. Asked about after the question above, never beside it.
+ let orphanOffer = $state(null);
+ let orphanDeleting = $state(false);
+
+ /** Say yes to the point: it is filed exactly as the automatic path files it. */
+ async function acceptPlaceOffer() {
+ if (!placeOffer || placeSaving) return;
+ placeSaving = true;
+ const offer = placeOffer;
+ try {
+ const place = await api.post(
+ `/api/cases/${caseState.current.id}/proofs/${encodeURIComponent(offer.name)}/place`,
+ { lat: offer.lat, lon: offer.lon }
+ );
+ placeOffer = null;
+ await reloadCase();
+ toast(`Saved the point as a place: ${place.label}`, 'ok', 2600);
+ } catch (e) {
+ toast(`Could not save the point: ${e.message}`, 'danger', 6000);
+ } finally {
+ placeSaving = false;
+ }
+ }
+
+ /** Say yes to dropping the point the proof moved off. Deleted like any entity,
+ * so it lands in the trash and comes back from there. */
+ async function deleteOrphanPlaces() {
+ if (!orphanOffer || orphanDeleting) return;
+ orphanDeleting = true;
+ const going = orphanOffer;
+ try {
+ for (const place of going) {
+ await api.del(`/api/cases/${caseState.current.id}/entities/${place.id}`);
+ }
+ orphanOffer = null;
+ await reloadCase();
+ toast(
+ going.length === 1 ? `Deleted the old place: ${going[0].label}` : `Deleted ${going.length} old places`,
+ 'ok',
+ 2600
+ );
+ } catch (e) {
+ toast(`Could not delete the old place: ${e.message}`, 'danger', 6000);
+ } finally {
+ orphanDeleting = false;
+ }
+ }
async function save({ andPost = false } = {}) {
if (!proof.panels.length || saving) return;
@@ -2353,6 +2430,14 @@
dirty = false;
await reloadCase();
toast(`Proof saved: ${result.png}`, 'ok');
+ // The point this proof carries. Filed already, or a question — the server
+ // answers with nothing at all when the case already holds that point, so
+ // re-saving never asks twice.
+ if (result.place?.filed) toast(`Saved the point as a place: ${result.place.label}`, 'ok', 2600);
+ else if (result.place) placeOffer = { name: result.name, ...result.place };
+ // Corrected coordinates take the old point back. The place stays on the map
+ // until the analyst says otherwise, so it is a question, not a cleanup.
+ orphanOffer = result.orphans?.length ? result.orphans : null;
if (andPost) {
uiState.postProof = {
title: result.title,
@@ -2450,6 +2535,7 @@
savedName = entry.name;
proof.title = spec.title;
proof.coordsText = spec.coordsText ?? '';
+ proof.pov = spec.pov === true;
proof.source = spec.source ?? '';
proof.captionSize = style.captionSize;
proof.legendSize = style.legendSize;
@@ -2469,7 +2555,7 @@
color = proof.palette[0];
for (const p of spec.panels) {
try {
- const img = await loadImage(`/files/${caseState.current.id}/${p.src}`);
+ const img = await loadImage(fileUrl(caseState.current.id, p.src));
imgCache.set(p.src, img);
proof.panels.push({ ...p, id: p.id ?? newId('p'), row: p.row ?? 0, img });
} catch {
@@ -2481,7 +2567,7 @@
for (const p of spec.pastes ?? []) {
try {
const img = await loadImage(
- `/files/${caseState.current.id}/proofs/${entry.name}.assets/${p.asset}`
+ fileUrl(caseState.current.id, `proofs/${entry.name}.assets/${p.asset}`)
);
pasteAssets.set(p.asset, { img, data: null, pending: false });
proof.pastes.push({ ...p, id: p.id ?? newId('x'), img });
@@ -2723,6 +2809,17 @@
value={displayedCoords}
oninput={(e) => { proof.coordsText = e.target.value; dirty = true; }}
/>
+ <!-- What the point means. Nothing in the composition can answer it: a
+ rooftop shot is recorded somewhere it never shows, and a distant
+ skyline is shown from kilometres away. -->
+ <label class="meta-check" title="The point is where the camera stood, not what it filmed">
+ <input
+ type="checkbox"
+ checked={proof.pov}
+ onchange={(e) => { proof.pov = e.currentTarget.checked; dirty = true; }}
+ />
+ <span>POV</span>
+ </label>
</div>
<div class="meta-field">
<div class="meta-head">
@@ -3013,6 +3110,41 @@
/>
{/if}
+<!-- The point this proof concludes on, offered once. The map is where it will be
+ read, so the question names the coordinates rather than the file. -->
+{#if placeOffer}
+ <ConfirmDialog
+ title="Save this point as a place?"
+ message={`${formatCoords({ lat: placeOffer.lat, lon: placeOffer.lon }, prefs.coordFormat)} is not saved in this case yet.`}
+ detail={placeOffer.pov
+ ? 'It joins the map, and the footage this proof composes will say it was recorded there.'
+ : 'It joins the map, and this proof and the files it composes will say they show it.'}
+ confirmLabel="Save the point"
+ tone="default"
+ icon="pin"
+ busy={placeSaving}
+ onconfirm={acceptPlaceOffer}
+ oncancel={() => (placeOffer = null)}
+ />
+<!-- The point the proof moved off, once the question above is answered: one save
+ can raise both, and two dialogs at once is a save nobody can read. -->
+{:else if orphanOffer}
+ <ConfirmDialog
+ title={orphanOffer.length === 1 ? 'Delete the old place?' : 'Delete the old places?'}
+ message={orphanOffer.length === 1
+ ? `This proof no longer points at “${orphanOffer[0].label}”.`
+ : `This proof no longer points at ${orphanOffer.length} saved places.`}
+ detail="Nothing else in the case points there."
+ restorable={RESTORABLE}
+ confirmLabel="Delete"
+ tone="default"
+ icon="trash"
+ busy={orphanDeleting}
+ onconfirm={deleteOrphanPlaces}
+ oncancel={() => (orphanOffer = null)}
+ />
+{/if}
+
{#if deleteEntry}
<ConfirmDialog
title="Delete this proof?"
@@ -3069,7 +3201,7 @@
{#each visiblePanelItems as item (item.src)}
<button class="pick card" onclick={() => addPanelFromPicker(item)}>
{#if item.thumb}
- <img src={`/files/${caseState.current.id}/${item.thumb}`} alt="" loading="lazy" decoding="async" />
+ <img src={fileUrl(caseState.current.id, item.thumb)} alt="" loading="lazy" decoding="async" />
{:else if item.thumbPending}
<span class="pick-placeholder"><Icon name="clock" size={20} /></span>
{:else}
@@ -3133,7 +3265,7 @@
{#if entry.thumb || entry.png}
<!-- the thumbnail of the export, or the export itself when
it could not be rendered; decoded off the main thread -->
- <img src={`/files/${caseState.current.id}/${entry.thumb ?? entry.png}`} alt="" loading="lazy" decoding="async" />
+ <img src={fileUrl(caseState.current.id, entry.thumb ?? entry.png)} alt="" loading="lazy" decoding="async" />
{/if}
<div class="open-meta">
<span class="open-title">{entry.title}</span>
@@ -3264,6 +3396,16 @@
border-radius: var(--r-sm);
}
.meta-reset:hover { color: var(--text-1); background: var(--bg-2); }
+ .meta-check {
+ display: inline-flex;
+ align-items: center;
+ gap: 5px;
+ margin-top: 5px;
+ font-size: var(--fs-xs);
+ color: var(--text-3);
+ cursor: pointer;
+ }
+ .meta-check:hover { color: var(--text-1); }
.tpl-settings-link {
margin-left: auto;
display: inline-flex;
diff --git a/frontend/src/tools/ProofComposer.test.js b/frontend/src/tools/ProofComposer.test.js
index 7892ab8..0bba380 100644
--- a/frontend/src/tools/ProofComposer.test.js
+++ b/frontend/src/tools/ProofComposer.test.js
@@ -82,8 +82,10 @@ describe('Proof Composer naming', () => {
});
it('checks the current hidden spec path before claiming a saved proof was deleted', () => {
- expect(source).toContain("lookupEntity(id, 'spec', `proofs/.meta/${name}.json`)");
- expect(source).not.toContain("lookupEntity(id, 'spec', `proofs/${name}.json`)");
+ // Via the shared helper, never a literal: the path moved once already, and a
+ // stale one matches nothing, so every save warns the proof was deleted.
+ expect(source).toContain("lookupEntity(id, specAttr('proof'), specPath('proof', name))");
+ expect(source).not.toContain('`proofs/${name}.json`');
});
});
@@ -339,7 +341,7 @@ describe('Proof Composer saved-proof list', () => {
// backfills it, and one that could not be rendered never gets one
const row = source.slice(source.indexOf('<div class="open-list">'), source.indexOf('open-del'));
expect(row).toContain('{#if entry.thumb || entry.png}');
- expect(row).toContain('${entry.thumb ?? entry.png}');
+ expect(row).toContain('fileUrl(caseState.current.id, entry.thumb ?? entry.png)');
});
});
@@ -386,13 +388,25 @@ describe('Proof Composer pasted images', () => {
it('lets one paste handler decide between an image and a copied annotation', () => {
expect(source).toContain('onpaste={onPaste}');
expect(source).toContain("i.type.startsWith('image/')");
- expect(source).toContain('} else if (clipboard) {');
// the old Ctrl+V keydown branch would have swallowed the paste event
expect(source).not.toContain("k === 'v' && clipboard");
// and a paste into the title or a caption stays text
expect(source).toContain('isTextTarget(e.target)');
});
+ it('decides that chord on which copy came last', () => {
+ // Ctrl+C on a rectangle then Ctrl+V pasted whatever screenshot the system
+ // clipboard was holding, because the system one was read first.
+ expect(source).toContain('if (clipboard && (shapeCopyFresh || !item))');
+ expect(source).toContain('shapeCopyFresh = true;');
+ });
+
+ it('hands the chord back to the system clipboard once the analyst leaves', () => {
+ // going somewhere else is the only way an outside copy could have happened
+ expect(source).toContain("window.addEventListener('blur', release)");
+ expect(source).toContain('const release = () => (shapeCopyFresh = false)');
+ });
+
it('offers the file picker and the drop as well as Ctrl+V', () => {
expect(source).toContain('{pickImageFile}');
expect(source).toContain("containerEl.addEventListener('drop', onCanvasDrop)");
@@ -470,3 +484,54 @@ describe('Proof Composer frames', () => {
expect(fn).toContain('natural[0] - w');
});
});
+
+describe('POV', () => {
+ it('asks what the point means, since the composition cannot say', () => {
+ // recorded-at and shows are independent: a rooftop shot is recorded
+ // somewhere it never shows
+ expect(source).toContain('pov: false');
+ expect(source).toContain('proof.pov = spec.pov === true');
+ expect(source).toContain('The point is where the camera stood, not what it filmed');
+ expect(source).toContain('<span>POV</span>');
+ });
+});
+
+describe("the point a proof concludes on", () => {
+ it('files it silently, or asks — never both, and never for a point already saved', () => {
+ // the server answers with nothing when the case holds that point already
+ expect(source).toContain('if (result.place?.filed)');
+ expect(source).toContain('else if (result.place) placeOffer =');
+ });
+
+ it('asks with the coordinates, since the map is where the point will be read', () => {
+ expect(source).toContain('Save this point as a place?');
+ expect(source).toContain('is not saved in this case yet.');
+ expect(source).toContain('this proof and the files it composes will say they show it');
+ expect(source).toContain('was recorded there');
+ });
+
+ it('answers through the proof, so the edge is filed with the point', () => {
+ expect(source).toContain('/proofs/${encodeURIComponent(offer.name)}/place');
+ expect(source).toContain('await reloadCase()');
+ });
+
+ it('asks before dropping the point a correction moved it off', () => {
+ // the place stays on the map until the analyst says otherwise: a save
+ // withdraws the claim, it does not clean up after them
+ expect(source).toContain('orphanOffer = result.orphans?.length ? result.orphans : null');
+ expect(source).toContain('Delete the old place?');
+ expect(source).toContain('This proof no longer points at');
+ expect(source).toContain('Nothing else in the case points there.');
+ });
+
+ it('queues that question behind the other one, since a save can raise both', () => {
+ const dialogs = source.slice(source.indexOf('{#if placeOffer}'));
+ expect(dialogs.indexOf('{:else if orphanOffer}')).toBeGreaterThan(-1);
+ expect(dialogs.indexOf('{:else if orphanOffer}')).toBeLessThan(dialogs.indexOf('{#if deleteEntry}'));
+ });
+
+ it('drops it through the entity route, so it lands in the trash like any delete', () => {
+ expect(source).toContain('await api.del(`/api/cases/${caseState.current.id}/entities/${place.id}`)');
+ expect(source).toContain('restorable={RESTORABLE}');
+ });
+});
diff --git a/frontend/src/tools/RefViewer.svelte b/frontend/src/tools/RefViewer.svelte
index b3bbdad..1d2bd8a 100644
--- a/frontend/src/tools/RefViewer.svelte
+++ b/frontend/src/tools/RefViewer.svelte
@@ -5,6 +5,7 @@
// lib/refViewers.js; this file is the pointer/DOM glue. Session-only: nothing
// here is captured or saved.
import Icon from '../components/Icon.svelte';
+ import { fileUrl } from '../lib/fileUrl.js';
import {
clamp,
clampWindow,
@@ -178,10 +179,10 @@
{#if caseId}
{#if isVideo}
<!-- svelte-ignore a11y_media_has_caption -->
- <video src={`/files/${caseId}/${viewer.path}`} controls preload="metadata"></video>
+ <video src={fileUrl(caseId, viewer.path)} controls preload="metadata"></video>
{:else}
<img
- src={`/files/${caseId}/${viewer.path}`}
+ src={fileUrl(caseId, viewer.path)}
alt={viewer.title}
draggable="false"
style:transform={`translate(${viewer.ox}px, ${viewer.oy}px) scale(${viewer.scale})`}
diff --git a/frontend/src/tools/ReverseSearch.svelte b/frontend/src/tools/ReverseSearch.svelte
index 045bd12..4598fb9 100644
--- a/frontend/src/tools/ReverseSearch.svelte
+++ b/frontend/src/tools/ReverseSearch.svelte
@@ -9,6 +9,7 @@
// image via a same-origin canvas — nothing leaves the machine until an
// engine tab is opened by the analyst.
import { api } from '../lib/api.js';
+ import { fileUrl } from '../lib/fileUrl.js';
import { matchesTerms } from '../lib/folderBrowse.js';
import { caseState, uiState, toast } from '../lib/state.svelte.js';
import { UPLOAD_PAGES } from '../lib/reverseSearch.js';
@@ -67,7 +68,7 @@
);
const resetAdjust = () => (adjust = { ...NEUTRAL });
- const srcOf = (item) => `/files/${caseState.current.id}/${item.path}`;
+ const srcOf = (item) => fileUrl(caseState.current.id, item.path);
const nameOf = (item) => (item.label || item.path).replace(/^media\//, '');
const frameLabel = $derived(selected?.kind === 'video' ? 'frame' : 'image');
@@ -399,7 +400,7 @@
<button class="picker-open" onclick={() => pickMedia(item)} title={item.path}>
<div class="picker-thumb">
{#if item.thumbnail}
- <img src={`/files/${caseState.current.id}/${item.thumbnail}`} alt="" loading="lazy" />
+ <img src={fileUrl(caseState.current.id, item.thumbnail)} alt="" loading="lazy" />
{:else}
<Icon name={item.kind === 'video' ? 'video' : 'image'} size={22} />
{/if}
diff --git a/frontend/src/tools/Satellite.svelte b/frontend/src/tools/Satellite.svelte
index a5a387a..1430c3f 100644
--- a/frontend/src/tools/Satellite.svelte
+++ b/frontend/src/tools/Satellite.svelte
@@ -1,8 +1,12 @@
<script>
import { onMount, tick } from 'svelte';
+ import { fileUrl } from '../lib/fileUrl.js';
import L from 'leaflet';
import 'leaflet/dist/leaflet.css';
import { api } from '../lib/api.js';
+ import { setAnalysisPeriod } from '../lib/analysisSearch.svelte.js';
+ import { temporalMapQuery } from '../lib/temporalMap.js';
+ import { windowWords } from '../lib/timeline.js';
import { filterSaved, isMode, pendingLocate } from '../lib/geoTree.js';
import {
caseState, uiState, ensureCase, reloadCase, toast, prefs, fmtCoords, prefsReady,
@@ -69,6 +73,7 @@
import SavedTree from './satellite/SavedTree.svelte';
import SavedSearch from './satellite/SavedSearch.svelte';
import SavedOverlay from './satellite/SavedOverlay.svelte';
+ import TemporalMapOverlay from './satellite/TemporalMapOverlay.svelte';
let mapEl;
let toolEl; // Browser fullscreen target.
@@ -97,6 +102,10 @@
let savedQuery = $state('');
let savedSearchOpen = $state(false);
let savedOverlay = $state(false); // map layer: off by default, session only
+ let temporalMap = $state(null); // Timeline handoff, session-only
+ let temporalMapLoading = $state(false);
+ let temporalMapError = $state('');
+ let temporalMapSeq = 0;
// Persist geography or My-work folder grouping across reloads.
const GROUP_KEY = 'azimut:satelliteSavedGroup';
let savedGroup = $state(loadSavedGroup());
@@ -1209,6 +1218,10 @@
locateStopped = true;
locateGeneration += 1;
locating = null;
+ temporalMapSeq += 1;
+ temporalMap = null;
+ temporalMapLoading = false;
+ temporalMapError = '';
}
if (!id) {
return;
@@ -1277,6 +1290,88 @@
}
});
+ $effect(() => {
+ const handed = uiState.mapTimelineRange;
+ const caseId = caseState.current?.id;
+ if (!mapReady || !handed || !caseId) return;
+ uiState.mapTimelineRange = null;
+ const run = ++temporalMapSeq;
+ temporalMap = {
+ from: handed.from,
+ to: handed.to,
+ items: [],
+ matched: 0,
+ mapped: 0,
+ marks: 0,
+ truncated: false,
+ };
+ temporalMapLoading = true;
+ temporalMapError = '';
+ // The case's own saved pins go off, rather than being assumed off. They are the
+ // whole index and take no notice of the window, so left on they answer a period
+ // with every place the case has ever held — the layer then reads as showing
+ // everything. The pin button is right there for anyone who wants that comparison.
+ savedOverlay = false;
+ api.get(temporalMapQuery(caseId, handed.from, handed.to, handed.categories ?? []))
+ .then((result) => {
+ if (run !== temporalMapSeq || caseState.current?.id !== caseId) return;
+ temporalMap = { ...temporalMap, ...result, from: handed.from, to: handed.to };
+ // Framed on what the window holds, and on nothing else. Fitting the case's own
+ // pins as well was a way to see none of them: a window with nothing placed in
+ // it pulled the view out to whatever continents the case has saved work on,
+ // which reads as the layer showing everything rather than showing nothing.
+ // With nothing to frame, the map stays where the analyst left it.
+ const points = result.items.flatMap((item) =>
+ item.place_entities.map((place) => [place.lat, place.lon])
+ );
+ if (!points.length) return;
+ tick().then(() => {
+ if (run !== temporalMapSeq || !map) return;
+ map.fitBounds(L.latLngBounds(points), { padding: [54, 54], maxZoom: 14 });
+ });
+ })
+ .catch((error) => {
+ if (run === temporalMapSeq) {
+ temporalMapError = error.message || 'The Timeline layer could not be loaded.';
+ }
+ })
+ .finally(() => {
+ if (run === temporalMapSeq) temporalMapLoading = false;
+ });
+ });
+
+ function openTemporalTimeline(item = null) {
+ if (!temporalMap) return;
+ uiState.timelineRange = {
+ from: temporalMap.from,
+ to: temporalMap.to,
+ itemId: item?.id ?? null,
+ };
+ uiState.tool = 'timeline';
+ }
+
+ function openTemporalCatalog(tool) {
+ if (!temporalMap || !caseState.current?.id) return;
+ setAnalysisPeriod(caseState.current.id, {
+ from: temporalMap.from,
+ to: temporalMap.to,
+ categories: ['statement'],
+ });
+ if (tool === 'graph') {
+ uiState.drawInGraph = {
+ label: `Fact time · ${windowWords(temporalMap.from, temporalMap.to, 'UTC')}`,
+ };
+ }
+ uiState.tool = tool;
+ }
+
+ function closeTemporalMap() {
+ temporalMapSeq += 1;
+ temporalMap = null;
+ temporalMapLoading = false;
+ temporalMapError = '';
+ }
+
// --- sun and moon mode ---
//
// One anchored point, one date, and an hour you drag: the day's path drawn as
@@ -2672,6 +2767,29 @@
else openNotes(row);
}
+ /** Accept a point a tool proposed, from the panel the analyst is reading it in.
+ *
+ * The same PATCH the sidebar sends, so the far end of the point's suggested
+ * relations is accepted with it — the API keeps that invariant, and a point
+ * confirmed here while the edge tying it to its capture stayed proposed would
+ * be the two surfaces disagreeing about one click. */
+ let acceptingId = $state(null);
+ async function acceptSaved(row) {
+ if (acceptingId) return;
+ acceptingId = row.id;
+ try {
+ await api.patch(`/api/cases/${caseState.current.id}/entities/${row.id}`, {
+ status: 'confirmed',
+ });
+ await reloadCase(); // re-reads the saved index and the case sidebar
+ toast('Point accepted', 'ok', 1600);
+ } catch (e) {
+ toast(`Could not accept this point: ${e.message}`, 'danger');
+ } finally {
+ acceptingId = null;
+ }
+ }
+
// --- details modal (title + notes) ---
let notesItem = $state(null);
let notesText = $state('');
@@ -2863,6 +2981,7 @@
locating = { done: 0, total };
let located = 0;
let failed = 0;
+ let throttled = false;
try {
let remaining = total;
while (remaining > 0 && !locateStopped && generation === locateGeneration) {
@@ -2872,22 +2991,26 @@
if (generation !== locateGeneration) return;
located += batch.located;
failed += batch.failed;
- // A batch that resolved nothing means the network is down, not that the
- // next one will do better: stop instead of hammering Nominatim forever.
+ throttled = Boolean(batch.throttled);
+ // A batch that resolved nothing means the network is down, or that
+ // Nominatim put us in its penalty box — not that the next one will do
+ // better: stop instead of hammering it forever.
const stalled = batch.remaining >= remaining;
remaining = batch.remaining;
locating = { done: total - remaining, total };
- if (stalled) break;
+ if (stalled || throttled) break;
}
if (generation !== locateGeneration) return;
const rows = await api.get(`/api/cases/${id}/satellite/index`);
if (generation !== locateGeneration) return;
saved = rows;
toast(
- failed
- ? `Located ${located} of ${total}. ${failed} lookup(s) failed; run Locate again to retry`
- : `Located ${located} of ${total}`,
- failed ? 'warn' : 'ok'
+ throttled
+ ? `Located ${located} of ${total}. OpenStreetMap is rate-limiting this address; wait a minute and run Locate again`
+ : failed
+ ? `Located ${located} of ${total}. ${failed} lookup(s) failed; run Locate again to retry`
+ : `Located ${located} of ${total}`,
+ failed || throttled ? 'warn' : 'ok'
);
} catch (e) {
if (generation === locateGeneration) {
@@ -3044,6 +3167,38 @@
/>
{/if}
+ {#if temporalMap}
+ <TemporalMapOverlay
+ map={mapReady ? map : null}
+ items={temporalMap.items}
+ caseId={caseState.current?.id}
+ onopen={openTemporalTimeline}
+ />
+ <div class="temporal-layer-card" aria-label="Timeline map layer">
+ <div>
+ <strong>Timeline</strong>
+ <span>{windowWords(temporalMap.from, temporalMap.to, 'UTC')}</span>
+ </div>
+ {#if temporalMapLoading}
+ <p>Loading placed statements…</p>
+ {:else if temporalMapError}
+ <p class="error">{temporalMapError}</p>
+ {:else if !temporalMap.matched}
+ <p>Nothing is dated in this window.</p>
+ {:else if !temporalMap.mapped}
+ <p>None of the {temporalMap.matched} dated here carries a place.</p>
+ {:else}
+ <p>{temporalMap.mapped} placed of {temporalMap.matched} dated{temporalMap.truncated ? ', partial' : ''}</p>
+ {/if}
+ <nav aria-label="Open Timeline range">
+ <button onclick={() => openTemporalTimeline()}>Timeline</button>
+ <button onclick={() => openTemporalCatalog('board')}>Board</button>
+ <button onclick={() => openTemporalCatalog('graph')}>Graph</button>
+ <button class="quiet" onclick={closeTemporalMap}>Close</button>
+ </nav>
+ </div>
+ {/if}
+
<!-- top-left control cluster: fullscreen, OSM labels overlay, measure tools -->
<div class="map-tools">
<MapToolCluster
@@ -3491,6 +3646,7 @@
onedit={editSaved}
ondelete={(row) => (deleteTarget = row)}
onproof={sendToComposer}
+ onaccept={acceptSaved}
onbrowse={() => (savedSearchOpen = true)}
onlocate={runLocate}
oncancelLocate={() => (locateStopped = true)}
@@ -3562,7 +3718,7 @@
<a
class="link-out"
class:disabled={fullscreen}
- href={fullscreen ? undefined : `/files/${caseState.current?.id}/${notesItem.path}`}
+ href={fullscreen ? undefined : fileUrl(caseState.current?.id, notesItem.path)}
target="_blank"
rel="noreferrer"
aria-disabled={fullscreen}
@@ -3605,6 +3761,7 @@
onedit={editSaved}
ondelete={(row) => (deleteTarget = row)}
onproof={sendToComposer}
+ onaccept={acceptSaved}
/>
{/if}
@@ -3729,6 +3886,7 @@
caseId={caseState.current.id}
relations={placeModal.relations}
subjectType="place"
+ actionFilter="relation"
onwalk={(entity) => { placeModal = null; openEntity(entity); }}
onchanged={async () => {
await loadPlaceRelations(placeModal?.id);
@@ -3812,7 +3970,7 @@
<button class="ref-pick" onclick={() => addRef(m)} title={m.title ?? m.filename}>
<div class="ref-thumb">
{#if m.thumbnail}
- <img src={`/files/${caseState.current.id}/${m.thumbnail}`} alt={m.filename} loading="lazy" />
+ <img src={fileUrl(caseState.current.id, m.thumbnail)} alt={m.filename} loading="lazy" />
{:else}
<Icon name={m.kind === 'video' ? 'video' : 'image'} size={26} />
{/if}
@@ -3858,6 +4016,44 @@
inset: 0;
background: var(--bg-2);
}
+ .temporal-layer-card {
+ position: absolute;
+ z-index: 720;
+ top: 12px;
+ right: 12px;
+ width: min(330px, calc(100% - 90px));
+ padding: 10px 12px;
+ border: 1px solid var(--border-strong);
+ border-radius: var(--r-md);
+ background: color-mix(in srgb, var(--bg-1) 94%, transparent);
+ box-shadow: var(--shadow-2);
+ color: var(--text-2);
+ font-size: var(--fs-xs);
+ }
+ .temporal-layer-card > div {
+ display: flex;
+ gap: 7px;
+ min-width: 0;
+ }
+ .temporal-layer-card strong { color: var(--text-1); }
+ .temporal-layer-card span {
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ }
+ .temporal-layer-card p { margin: 6px 0 8px; color: var(--text-3); }
+ .temporal-layer-card .error { color: var(--danger); }
+ .temporal-layer-card nav { display: flex; gap: 9px; }
+ .temporal-layer-card button {
+ padding: 0;
+ border: 0;
+ background: none;
+ color: var(--accent);
+ font: inherit;
+ cursor: pointer;
+ }
+ .temporal-layer-card button:hover { text-decoration: underline; }
+ .temporal-layer-card .quiet { margin-left: auto; color: var(--text-3); }
/* Mid screen-grab: a widget capture crops the map element's *rectangle*, so
everything we paint over the map (HUD, control clusters, capture bar,
reference windows, the frame outline itself) would land in the capture.
diff --git a/frontend/src/tools/Satellite.test.js b/frontend/src/tools/Satellite.test.js
index 3c851e9..4c49c3a 100644
--- a/frontend/src/tools/Satellite.test.js
+++ b/frontend/src/tools/Satellite.test.js
@@ -111,7 +111,14 @@ describe('Satellite saved work', () => {
// offline, every batch comes back with the same backlog — looping on that
// would hammer Nominatim forever
expect(source).toContain('const stalled = batch.remaining >= remaining');
- expect(source).toContain('if (stalled) break;');
+ expect(source).toContain('if (stalled || throttled) break;');
+ });
+
+ it('stops and says so when OpenStreetMap is rate-limiting the address', () => {
+ // a 429 is not a lookup failure: running the pass again is exactly the
+ // wrong advice, so the pass ends and the toast says to wait
+ expect(source).toContain('throttled = Boolean(batch.throttled)');
+ expect(source).toContain('OpenStreetMap is rate-limiting this address');
});
it('does not let a Locate pass continue in another case', () => {
@@ -351,3 +358,22 @@ describe('sun and moon mode', () => {
expect(source).not.toContain('handed.sun');
});
});
+
+describe('accepting a proposed point from the Saved panel', () => {
+ // import enrichment still proposes places from a file's GPS, and the panel
+ // reading them is where they are settled
+ it('sends the same PATCH the sidebar does, so one click means one thing', () => {
+ expect(source).toContain("status: 'confirmed',");
+ expect(source).toContain('onaccept={acceptSaved}');
+ });
+
+ it('re-reads the case, or the row would keep claiming it is proposed', () => {
+ const fn = source.slice(source.indexOf('async function acceptSaved'));
+ expect(fn.slice(0, fn.indexOf('\n }'))).toContain('await reloadCase()');
+ });
+
+ it('offers it in the search modal too, which lists the same index', () => {
+ const modal = source.slice(source.indexOf('<SavedSearch'));
+ expect(modal.slice(0, modal.indexOf('/>'))).toContain('onaccept={acceptSaved}');
+ });
+});
diff --git a/frontend/src/tools/Settings.svelte b/frontend/src/tools/Settings.svelte
index 22231f9..d9123b7 100644
--- a/frontend/src/tools/Settings.svelte
+++ b/frontend/src/tools/Settings.svelte
@@ -1,7 +1,8 @@
<script>
import { onMount } from 'svelte';
import { api } from '../lib/api.js';
- import { toast, prefs, applyPrefs, uiState } from '../lib/state.svelte.js';
+ import { toast, prefs, applyPrefs, uiState, updatesState } from '../lib/state.svelte.js';
+ import { updateBadges, carryLatest } from '../lib/staleness.js';
import {
templatesState, loadTemplates, saveTemplate, deleteTemplate,
} from '../lib/state.svelte.js';
@@ -21,7 +22,7 @@
FREE_TIER,
} from '../lib/usage.js';
import { probeKey, googleMapsLoadedKey } from '../lib/gmaps.js';
- import { extensionVersion, extensionOutdated } from '../lib/extBridge.js';
+ import { extensionVersion } from '../lib/extBridge.js';
import { CASE_FOLDER_LABEL, saveDestination } from '../lib/exportDest.js';
import Icon from '../components/Icon.svelte';
import ExportFolderPicker from '../components/ExportFolderPicker.svelte';
@@ -176,8 +177,10 @@
// Read once per mount because an extension installed mid-session needs a reload.
const extDetected = extensionVersion();
- // Flag when the bundled extension is newer than the browser's loaded copy.
- let extOutdated = $derived(extensionOutdated(extDetected, about.extension_version));
+ // Every dot in this tool comes from the same place as the one on the Settings
+ // icon, so a tab can never disagree with the rail that led the user to it.
+ let badges = $derived(updateBadges(updatesState, prefs.updateDismissedVersion));
+ let extOutdated = $derived(badges.extensionOutdated);
async function copyToken() {
try {
@@ -208,6 +211,8 @@
let mention = $state('');
let postTarget = $state('x');
let updateOnStart = $state(true); // pop a notice on load when a release is out
+ // whether saving a proof files its point as a place, or asks first
+ let proofPlaceAuto = $state(true);
// The app-wide logo lives beside settings.json and reaches cases only in proof PNGs.
// `sigBust` refreshes the preview after replacement.
let signature = $state(false);
@@ -270,10 +275,17 @@
async function loadScrapers(check = false) {
const path = check ? '/api/settings/scrapers?check=true' : '/api/settings/scrapers';
- scrapers = (await api.get(path)).scrapers;
+ const fresh = (await api.get(path)).scrapers;
+ // A local read knows the installed version and nothing about PyPI, so it
+ // would blank the verdict the startup check found. Carry `latest` across
+ // and judge it again, and updating one downloader stops clearing the other
+ // one's badge.
+ scrapers = check ? fresh : carryLatest(fresh, updatesState.scrapers);
+ updatesState.scrapers = scrapers;
}
- // Scraper checks run only when requested and never on Settings mount.
+ // Scraper checks run only when requested and never on Settings mount: the
+ // startup check already asked, and its answer is in the store.
async function checkScrapers() {
if (checking) return;
checking = true;
@@ -290,17 +302,20 @@
}
}
- // Manual app update check. The separate startup check remains enabled by default.
- let appUpdate = $state(null); // { current, latest, update_available, url, error }
+ // The startup check's answer, until the user asks for a fresher one. Both land
+ // in the same place so the row and the dot beside it can't tell different
+ // stories — { current, latest, update_available, url, error } or null.
+ let appUpdate = $derived(updatesState.app);
let checkingApp = $state(false);
async function checkAppUpdate() {
if (checkingApp) return;
checkingApp = true;
try {
- appUpdate = await api.get('/api/settings/update?check=true');
- if (appUpdate.error) toast(`Could not reach GitHub: ${appUpdate.error}`, 'danger');
- else if (!appUpdate.update_available) toast('Azimut is up to date', 'ok');
+ const fresh = await api.get('/api/settings/update?check=true');
+ updatesState.app = fresh;
+ if (fresh.error) toast(`Could not reach GitHub: ${fresh.error}`, 'danger');
+ else if (!fresh.update_available) toast('Azimut is up to date', 'ok');
} catch (e) {
toast(`Could not check for updates: ${e.message}`, 'danger');
} finally {
@@ -408,6 +423,7 @@
mention = s.post_mention ?? '';
postTarget = s.post_target ?? 'x';
updateOnStart = s.update_check_on_start ?? true;
+ proofPlaceAuto = s.proof_place_auto ?? true;
applyPrefs(s); // the rest of the app reads these live
await loadScrapers().catch(() => {}); // local disk read; never blocks Settings
// shells out to `ffmpeg -version`; non-blocking, System only reads it
@@ -662,7 +678,7 @@
<nav class="rail" aria-label="Settings sections">
{#each TABS as t (t.id)}
<button
- class="rail-tab"
+ class="rail-tab dotted"
class:active={tab === t.id}
class:rail-break={t.id === 'storage'}
onclick={() => (tab = t.id)}
@@ -670,6 +686,9 @@
>
<Icon name={t.icon} size={15} />
{t.label}
+ {#if badges.tabs[t.id]}
+ <span class="update-dot" aria-label="something to install or update"></span>
+ {/if}
</button>
{/each}
</nav>
@@ -741,6 +760,28 @@
</label>
</div>
</section>
+
+ <section class="group">
+ <h3>Proofs</h3>
+ <p class="intro">
+ Saving a proof turns the coordinates it carries into a place on the map, and
+ says the proof shows it.
+ </p>
+ <div class="row">
+ <div class="row-label">
+ <span>Save the point without asking</span>
+ <span class="row-hint">
+ Off, the composer asks each time. A point already saved is never asked about.
+ </span>
+ </div>
+ <input
+ type="checkbox"
+ bind:checked={proofPlaceAuto}
+ onchange={() => savePrefs({ proof_place_auto: proofPlaceAuto })}
+ aria-label="Save a proof's point without asking"
+ />
+ </div>
+ </section>
{/if}
{#if tab === 'publishing'}
@@ -1107,9 +1148,15 @@
{/if}
</span>
</div>
- <a class="btn btn-sm btn-primary" href="/api/ingest/extension.zip" download>
+ <a class="btn btn-sm btn-primary dotted" href="/api/ingest/extension.zip" download>
<Icon name="download" size={13} />
{extOutdated ? 'Download update (.zip)' : 'Download extension (.zip)'}
+ {#if badges.extension}
+ <span
+ class="update-dot"
+ aria-label={extOutdated ? 'an update is waiting' : 'not installed yet'}
+ ></span>
+ {/if}
</a>
</div>
{#if extOutdated}
@@ -1250,8 +1297,11 @@
</span>
</div>
{#if appUpdate?.update_available}
- <a class="btn btn-sm btn-primary" href={appUpdate.url} target="_blank" rel="noreferrer">
+ <a class="btn btn-sm btn-primary dotted" href={appUpdate.url} target="_blank" rel="noreferrer">
<Icon name="download" size={13} /> Get {appUpdate.latest} <Icon name="external" size={11} />
+ {#if badges.app}
+ <span class="update-dot" aria-label="an update is waiting"></span>
+ {/if}
</a>
{:else}
<button class="btn btn-sm" onclick={checkAppUpdate} disabled={checkingApp}>
@@ -1263,7 +1313,7 @@
<div class="row-label">
<span>Tell me on startup</span>
<span class="row-hint">
- Checks GitHub when the app opens and reports available releases.
+ Asks GitHub and PyPI once when the app opens, and marks what is behind.
</span>
</div>
<input
@@ -1368,12 +1418,15 @@
<button class="btn btn-sm" onclick={() => resetScraper(s.dist)}>Revert</button>
{/if}
<button
- class="btn btn-sm"
+ class="btn btn-sm dotted"
class:btn-primary={s.outdated}
disabled={updating[s.dist]}
onclick={() => updateScraper(s.dist)}
>
{updating[s.dist] ? 'Updating…' : 'Update'}
+ {#if s.outdated && !updating[s.dist]}
+ <span class="update-dot" aria-label="an update is waiting"></span>
+ {/if}
</button>
</div>
</div>
@@ -1552,6 +1605,13 @@
cursor: pointer;
transition: background 0.12s var(--ease), color 0.12s var(--ease);
}
+ /* A rail tab is a full-width row, not a control with a corner, so its dot
+ sits at the end of the line instead of hanging off it. */
+ .rail-tab .update-dot {
+ top: 50%;
+ right: 9px;
+ transform: translateY(-50%);
+ }
.rail-tab:hover {
background: var(--bg-2);
color: var(--text-1);
diff --git a/frontend/src/tools/Settings.test.js b/frontend/src/tools/Settings.test.js
index 4937c54..18f5384 100644
--- a/frontend/src/tools/Settings.test.js
+++ b/frontend/src/tools/Settings.test.js
@@ -81,6 +81,13 @@ describe('Settings sections', () => {
expect(source).toContain("const aliases = { preferences: 'general', about: 'system' }");
});
+ it('offers the proof point as save-or-ask, never as a status', () => {
+ expect(source).toContain('proof_place_auto: proofPlaceAuto');
+ expect(source).toContain('proofPlaceAuto = s.proof_place_auto ?? true');
+ expect(source).toContain('Save the point without asking');
+ expect(source).toContain('Off, the composer asks each time.');
+ });
+
it('manages all three export folders from Storage', () => {
expect(source).toContain("{ id: 'notes', label: 'Note PDFs' }");
expect(source).toContain("{ id: 'media', label: 'Media copies' }");
diff --git a/frontend/src/tools/Timeline.svelte b/frontend/src/tools/Timeline.svelte
new file mode 100644
index 0000000..bdb9d31
--- /dev/null
+++ b/frontend/src/tools/Timeline.svelte
@@ -0,0 +1,2336 @@
+<script>
+ /** A windowed UTC axis over the case's derived temporal projection. */
+ import { untrack } from 'svelte';
+ import { api } from '../lib/api.js';
+ import {
+ openAnalysisCase,
+ setAnalysisPeriod,
+ timelineViews,
+ } from '../lib/analysisSearch.svelte.js';
+ import { buildCatalogQuery } from '../lib/catalog.js';
+ import { closeOnOutsidePointer } from '../lib/dismiss.js';
+ import { caseState, reloadCase, toast, uiState } from '../lib/state.svelte.js';
+ import { entityLabel, entityTypes, loadEntityTypes } from '../lib/entityTypes.svelte.js';
+ import {
+ TIMELINE_CATEGORIES,
+ UTC,
+ WINDOW_SPANS,
+ axisBands,
+ axisMinorTicks,
+ axisScale,
+ axisTicks,
+ bucketWindow,
+ canDragTemporal,
+ dateAtRatio,
+ describePair,
+ draftWhen,
+ formatTemporalValue,
+ initialWindow,
+ inputWindowValue,
+ isoInstant,
+ knownZone,
+ densityScale,
+ densityTicks,
+ densityUnit,
+ layoutDensityBuckets,
+ layoutTimelineItems,
+ machineZone,
+ moveTemporalRaw,
+ nowPosition,
+ nudgeTemporalRaw,
+ resizeTemporalRaw,
+ resizeWindow,
+ ribbonBands,
+ shiftWindow,
+ timeAtRatio,
+ windowInputValue,
+ windowMillis,
+ windowWords,
+ zoneAbbreviation,
+ zonedFields,
+ zonedStamp,
+ zoomWindow,
+ } from '../lib/timeline.js';
+ import {
+ copyTimelineTrack,
+ defaultTimelineTracks,
+ groupedTimelineTracks,
+ moveTimelineTrack,
+ normalizeTimelineTracks,
+ timelineTrack,
+ timelineTrackQuery,
+ timelineViewState,
+ trackPresets,
+ trackTint,
+ } from '../lib/timelineTracks.js';
+ import AnalysisViews from '../components/AnalysisViews.svelte';
+ import ConfirmDialog from '../components/ConfirmDialog.svelte';
+ import EntityDetails from '../components/EntityDetails.svelte';
+ import Icon from '../components/Icon.svelte';
+ import Modal from '../components/Modal.svelte';
+ import TemporalClaimEditor from '../components/TemporalClaimEditor.svelte';
+ import TimelineTrackEditor from '../components/TimelineTrackEditor.svelte';
+ import ZonePicker from '../components/ZonePicker.svelte';
+
+ const PAGE = 200;
+ loadEntityTypes();
+ let trackSpecs = $state(defaultTimelineTracks());
+ let trackPages = $state({});
+ let groupBy = $state('none');
+ let trackEditor = $state(null);
+ let trackMenu = $state(false);
+ let trackMenuElement = $state(null);
+ let draggedTrack = null;
+ let selectedTrackId = $state(null);
+ let from = $state('');
+ let to = $state('');
+ let items = $state([]);
+ let total = $state(0);
+ let undatedTotal = $state(0);
+ let unplacedTotal = $state(0);
+ let cursor = $state(null);
+ let loading = $state(false);
+ let extent = $state(null);
+ let overview = $state([]);
+ let overviewTruncated = $state(false);
+ let selected = $state(null);
+ /**
+ * The second entry, held against the first (Ctrl-click).
+ *
+ * What a chronology is read for and never printed: an axis shows that two things
+ * are near each other, and the finding is the figure between them. Kept beside
+ * `selected` rather than replacing it, so the panel still says what the entry *is*
+ * while it measures.
+ */
+ let against = $state(null);
+ /**
+ * Which clock the axis is *read* on: `utc`, `machine`, or `place:<id>` for the
+ * local time at a point the case has saved.
+ *
+ * The case is stored in UTC and stays there (`lib/timeline.js`): this moves the
+ * ticks and their words, nothing else. UTC is the default because it is the one
+ * reading that means the same thing on every machine — and it is the wrong reading
+ * for the work, because an investigator argues in the local time of the *event*,
+ * and checking a 19:40 timestamp against a clock in the analyst's own country is
+ * how an hour goes missing.
+ *
+ * A saved point is that reading, and it is the only one that can carry the daylight
+ * ribbon with it: a band of day and night needs coordinates, so it arrives with the
+ * zone rather than being a second control.
+ */
+ let zoneChoice = $state('utc');
+ /** The case's saved points, for that menu. Bounded like every other list here. */
+ let places = $state([]);
+ /** `{ zone, day, civil, truncated }` for the chosen point over the visible window. */
+ let daylight = $state(null);
+ let daylightLoading = $state(false);
+ let daylightSeq = 0;
+ let editor = $state(null);
+ let detailsId = $state(null);
+ let entityFilter = $state(null);
+ let viewMode = $state('plot');
+ let expandedTracks = $state({});
+ let toolElement = $state(null);
+ let fullscreen = $state(false);
+ let legendElement = $state(null);
+ let legendOpen = $state(false);
+ let rangeElement = $state(null);
+ let rangeMenu = $state(false);
+ let plotElement = $state(null);
+ let plotWidth = $state(1000);
+ let overviewWidth = $state(800);
+ let tooltip = $state(null);
+ /** `{ item, track, x, y }` while an entry is being asked what can be done with it. */
+ let itemMenu = $state(null);
+ let itemMenuElement = $state(null);
+ let inspectorChain = $state(null);
+ let inspectorLoading = $state(false);
+ let seq = 0;
+ let overviewSeq = 0;
+ let inspectorSeq = 0;
+ let loadedCase = null;
+ let pendingSelection = null;
+ let navigationBusy = $state(false);
+ let navigationTimer = null;
+ let panning = $state(null);
+ let overviewGesture = $state(null);
+
+ const activeCategories = $derived(
+ [...new Set(trackSpecs.flatMap((track) => track.categories))]
+ );
+ // Only a Timeline view can land in this slot, so its surface no longer needs asking.
+ const snapshotReading = $derived(timelineViews.activeView?.mode === 'snapshot');
+ const axisWindow = $derived(windowMillis(from, to));
+ const ticks = $derived(axisTicks(from, to, plotWidth, zone));
+ const minorTicks = $derived(axisMinorTicks(from, to, plotWidth, zone));
+ const bands = $derived(axisBands(from, to, plotWidth, zone));
+ const nowLeft = $derived(nowPosition(from, to));
+ const baseTrackItems = $derived(Object.fromEntries(
+ trackSpecs.map((track) => [
+ track.id,
+ (trackPages[track.id]?.items ?? [])
+ .filter((item) => !track.hidden.includes(item.id))
+ .map((item) => ({ ...item, pinned: track.pinned.includes(item.id) })),
+ ])
+ ));
+ const visibleItems = $derived.by(() => {
+ const unique = new Map();
+ for (const rows of Object.values(baseTrackItems)) {
+ for (const item of rows) unique.set(item.id, item);
+ }
+ return [...unique.values()];
+ });
+ const dated = $derived(visibleItems.filter((item) => item.earliest));
+ /**
+ * Everything the loaded page holds, including entries hidden only from a track.
+ *
+ * What the two holding lists below are read from, and the reason they are read from
+ * this rather than from `visibleItems`: hiding tidies a **lane**, and an entry with
+ * no place on the axis was never in one. Applied to those entries, hiding had exactly
+ * one visible effect — it emptied the queue whose whole job is to say *these still
+ * need a date* — and the way back was a control on a track that also gave back
+ * everything else that track was holding.
+ *
+ * An entry is in these lists because one of the current tracks asks for it, not
+ * because of where it is drawn.
+ */
+ const pageItems = $derived.by(() => {
+ const unique = new Map();
+ for (const page of Object.values(trackPages)) {
+ for (const item of page?.items ?? []) unique.set(item.id, item);
+ }
+ return [...unique.values()];
+ });
+ const unplaced = $derived(pageItems.filter((item) => !item.earliest && item.raw));
+ const undated = $derived(pageItems.filter((item) => !item.earliest && !item.raw));
+ const tracks = $derived(
+ groupedTimelineTracks(trackSpecs, baseTrackItems, groupBy, entityLabel).map((track) => {
+ const baseId = track.parentId ?? track.id;
+ const expanded = Boolean(expandedTracks[baseId]);
+ return {
+ ...track,
+ expanded,
+ total: groupBy === 'none' ? (trackPages[baseId]?.total ?? track.items.length) : track.items.length,
+ layout: layoutTimelineItems(
+ track.items.filter((item) => item.earliest), from, to, plotWidth,
+ expanded ? PAGE : 6
+ ),
+ };
+ })
+ );
+ const density = $derived(layoutDensityBuckets(overview, extent));
+ const overviewUnit = $derived(
+ { 13: 'Hour', 10: 'Day', 7: 'Month' }[overview[0]?.start?.length] ?? 'Year'
+ );
+ /**
+ * The date scale under the minimap: one slot per period, named under its own bar.
+ *
+ * Measured rather than assumed — a fixed 800 chose how many names to print for a
+ * minimap that is as wide as the window, so it crowded on a narrow one and left the
+ * wide one half empty.
+ */
+ const overviewTicks = $derived(densityTicks(overview, extent, overviewWidth));
+ const selectedReading = $derived(formatTemporalValue(selected?.raw ?? ''));
+ const selectedTrack = $derived(trackSpecs.find((track) => track.id === selectedTrackId) ?? null);
+ const inspectorConnections = $derived.by(() => {
+ const grouped = { about: [], at: [], cites: [] };
+ if (snapshotReading && selected) {
+ grouped.about = selected.subject_entities ?? [];
+ grouped.at = selected.place_entities ?? [];
+ grouped.cites = selected.source_entities ?? [];
+ return grouped;
+ }
+ for (const row of inspectorChain?.relations ?? []) {
+ if (row.direction === 'out' && grouped[row.link.type]) grouped[row.link.type].push(row.entity);
+ }
+ return grouped;
+ });
+ const listGroups = $derived.by(() => {
+ const groups = new Map();
+ for (const item of [...dated].sort((a, b) => String(a.earliest).localeCompare(String(b.earliest)))) {
+ const date = new Date(item.earliest);
+ // Grouped by the month the reading falls in, so the list and the axis agree
+ // about which month an entry near a midnight belongs to.
+ const at = zonedFields(date.getTime(), zone);
+ const key = `${at.year}-${String(at.month).padStart(2, '0')}`;
+ const label = date.toLocaleDateString('en-GB', { month: 'long', year: 'numeric', timeZone: zone });
+ const group = groups.get(key) ?? { key, label, items: [] };
+ group.items.push(item);
+ groups.set(key, group);
+ }
+ return [...groups.values()];
+ });
+ const overviewWindow = $derived.by(() => {
+ const scale = densityScale(overview, extent);
+ if (!axisWindow || !scale) return { left: 0, width: 100 };
+ const span = Math.max(1, scale.span);
+ const left = Math.max(0, Math.min(1, (axisWindow.start - scale.first) / span));
+ const right = Math.max(left, Math.min(1, (axisWindow.end - scale.first) / span));
+ return { left: left * 100, width: Math.max(.35, (right - left) * 100) };
+ });
+ /**
+ * The zone in force. A point's own zone arrives with its daylight, so until that
+ * lands the axis stays on UTC rather than flickering through a guess.
+ */
+ const sunPlace = $derived(
+ zoneChoice.startsWith('place:')
+ ? places.find((place) => place.id === zoneChoice.slice(6)) ?? null
+ : null
+ );
+ const frozenZone = $derived(
+ snapshotReading ? timelineViews.activeView?.spec?.timeline?.timezone ?? null : null
+ );
+ const zone = $derived.by(() => {
+ if (frozenZone && knownZone(frozenZone)) return frozenZone;
+ if (zoneChoice === 'machine') return knownZone(localZone) ? localZone : UTC;
+ // A zone named outright: the investigation is at the other end of the world and
+ // the case has no saved point there yet. It carries no coordinates, so it labels
+ // the axis and draws no daylight.
+ if (zoneChoice.startsWith('zone:')) {
+ const named = zoneChoice.slice(5);
+ return knownZone(named) ? named : UTC;
+ }
+ if (!sunPlace) return UTC;
+ const named = daylight?.zone?.name;
+ return named && knownZone(named) ? named : UTC;
+ });
+ /** What one tick is worth, and which clock is being read. */
+ const zoneWord = $derived(
+ zone === UTC ? 'UTC' : zoneAbbreviation(zone, axisWindow?.start ?? 0)
+ );
+ /**
+ * Day and civil twilight across the visible window, drawn only on a local reading.
+ *
+ * The point of pairing them: a photo stamped 19:40 is argued against the light at
+ * the place it claims, and doing that against a UTC axis in another country is
+ * where an hour goes missing. Two runs rather than one because dusk is not a line.
+ */
+ const daylightBands = $derived(
+ sunPlace && !daylight?.truncated ? ribbonBands(daylight?.day ?? [], from, to) : []
+ );
+ const twilightBands = $derived(
+ sunPlace && !daylight?.truncated ? ribbonBands(daylight?.civil ?? [], from, to) : []
+ );
+ const scaleLabel = $derived.by(() => {
+ const unit = axisScale(from, to, plotWidth);
+ return unit ? `${unit} · ${zoneWord}` : zoneWord;
+ });
+ /** The machine's own zone is offered rather than assumed: it is a legitimate
+ * reading of a working day and a poor default. */
+ const localZone = machineZone();
+ /** The pair reading, when a second entry is held against the first. */
+ const pairReading = $derived(
+ selected && against && selected.id !== against.id ? describePair(selected, against) : null
+ );
+
+ $effect(() => {
+ if (!plotElement || typeof ResizeObserver === 'undefined') return;
+ const observer = new ResizeObserver(([entry]) => {
+ plotWidth = Math.max(320, Math.round(entry.contentRect.width));
+ });
+ observer.observe(plotElement);
+ return () => observer.disconnect();
+ });
+
+ $effect(() => trackMenu ? closeOnOutsidePointer(trackMenuElement, () => (trackMenu = false)) : undefined);
+ $effect(() => rangeMenu ? closeOnOutsidePointer(rangeElement, () => (rangeMenu = false)) : undefined);
+
+ $effect(() => {
+ if (typeof document === 'undefined') return;
+ const changed = () => (fullscreen = document.fullscreenElement === toolElement);
+ document.addEventListener('fullscreenchange', changed);
+ return () => document.removeEventListener('fullscreenchange', changed);
+ });
+
+ $effect(() => legendOpen ? closeOnOutsidePointer(legendElement, () => (legendOpen = false)) : undefined);
+ $effect(() => itemMenu ? closeOnOutsidePointer(itemMenuElement, () => (itemMenu = null)) : undefined);
+
+ function overviewQuery(track, { densityBucket = 'year' } = {}) {
+ const params = new URLSearchParams({
+ include_undated: 'false',
+ limit: '1',
+ bucket: densityBucket,
+ });
+ for (const category of track.categories) {
+ params.append('category', category);
+ }
+ if (entityFilter?.id) params.set('entity', entityFilter.id);
+ params.set('track', timelineTrackQuery(track));
+ return params;
+ }
+
+ function mergeOverviewPages(pages) {
+ const buckets = new Map();
+ for (const page of pages) {
+ for (const row of page.buckets ?? []) {
+ const held = buckets.get(row.start)
+ ?? { start: row.start, count: 0, categories: {}, first: null, last: null };
+ held.count += row.count ?? 0;
+ for (const [category, count] of Object.entries(row.categories ?? {})) {
+ held.categories[category] = (held.categories[category] ?? 0) + count;
+ }
+ // One track's bucket and another's cover different days of the same month, and
+ // the bar drawn for it has to reach across both.
+ if (row.first && (!held.first || row.first < held.first)) held.first = row.first;
+ if (row.last && (!held.last || row.last > held.last)) held.last = row.last;
+ buckets.set(row.start, held);
+ }
+ }
+ const extents = pages.map((page) => page.extent).filter((value) => value?.from);
+ return {
+ buckets: [...buckets.values()].sort((left, right) => left.start.localeCompare(right.start)),
+ buckets_truncated: pages.some((page) => page.buckets_truncated),
+ extent: extents.length ? {
+ from: extents.map((value) => value.from).sort()[0],
+ to: extents.map((value) => value.to).sort().at(-1),
+ } : null,
+ };
+ }
+
+ /**
+ * One page of a lane. `spread` is what makes the page a reading of the window
+ * rather than of its first days: a case whose media pile into January filled the
+ * page before February, and the lanes then contradicted the overview above them
+ * by drawing an empty spring. The server samples the same rows instead, and
+ * "Load more" fills the sample in.
+ */
+ function trackQuery(track, { more = false } = {}) {
+ const params = new URLSearchParams({
+ include_undated: 'true', limit: String(PAGE), spread: 'true',
+ });
+ for (const category of track.categories) {
+ params.append('category', category);
+ }
+ if (entityFilter?.id) params.set('entity', entityFilter.id);
+ if (from) params.set('from', from);
+ if (to) params.set('to', to);
+ if (more && trackPages[track.id]?.cursor) params.set('cursor', trackPages[track.id].cursor);
+ params.set('track', timelineTrackQuery(track));
+ return params;
+ }
+
+ async function loadMain({ more = false } = {}) {
+ const caseId = caseState.current?.id;
+ if (!caseId || !activeCategories.length || snapshotReading) return;
+ const targets = trackSpecs.filter((track) => !more || trackPages[track.id]?.cursor);
+ if (!targets.length) return;
+ const mine = ++seq;
+ loading = true;
+ try {
+ const responses = await Promise.all(targets.map(async (track) => ({
+ track,
+ page: await api.get(`/api/cases/${caseId}/timeline?${trackQuery(track, { more })}`),
+ })));
+ if (mine !== seq) return;
+ const nextPages = more ? { ...trackPages } : {};
+ for (const { track, page } of responses) {
+ nextPages[track.id] = {
+ items: more
+ ? [...(nextPages[track.id]?.items ?? []), ...(page.items ?? [])]
+ : page.items ?? [],
+ total: page.total ?? 0,
+ undated: page.undated ?? 0,
+ unplaced: page.unplaced ?? 0,
+ cursor: page.next_cursor ?? null,
+ extent: page.extent ?? null,
+ };
+ }
+ trackPages = nextPages;
+ const unique = new Map();
+ for (const page of Object.values(nextPages)) {
+ for (const item of page.items ?? []) unique.set(item.id, item);
+ }
+ items = [...unique.values()];
+ total = Object.values(nextPages).reduce((sum, page) => sum + (page.total ?? 0), 0);
+ undatedTotal = Object.values(nextPages).reduce((sum, page) => sum + (page.undated ?? 0), 0);
+ unplacedTotal = Object.values(nextPages).reduce((sum, page) => sum + (page.unplaced ?? 0), 0);
+ cursor = Object.values(nextPages).some((page) => page.cursor) ? 'more' : null;
+ const extents = Object.values(nextPages).map((page) => page.extent).filter((value) => value?.from);
+ extent = extents.length ? {
+ from: extents.map((value) => value.from).sort()[0],
+ to: extents.map((value) => value.to).sort().at(-1),
+ } : extent;
+ if (!from && !to && extent?.from) ({ from, to } = initialWindow(extent));
+ if (pendingSelection) {
+ selected = items.find((item) => item.id === pendingSelection.id)
+ ?? pendingSelection.fallback
+ ?? null;
+ pendingSelection = null;
+ } else if (selected) {
+ selected = items.find((item) => item.id === selected.id) ?? null;
+ }
+ } catch (error) {
+ if (mine === seq) toast(error.message, 'danger');
+ } finally {
+ if (mine === seq) loading = false;
+ }
+ }
+
+ async function loadOverview() {
+ const caseId = caseState.current?.id;
+ if (!caseId || !activeCategories.length || snapshotReading) return;
+ const targets = trackSpecs;
+ if (!targets.length) return;
+ const mine = ++overviewSeq;
+ try {
+ let pages = await Promise.all(targets.map((track) =>
+ api.get(`/api/cases/${caseId}/timeline?${overviewQuery(track)}`)
+ ));
+ if (mine !== overviewSeq) return;
+ let page = mergeOverviewPages(pages);
+ // The first reading is by year, which is only ever asked to report the extent:
+ // how finely the case can be cut is a question about the span, and the span is
+ // what that reading answers.
+ const finer = densityUnit(page.extent, overviewWidth);
+ if (finer !== 'year') {
+ pages = await Promise.all(targets.map((track) =>
+ api.get(`/api/cases/${caseId}/timeline?${overviewQuery(track, { densityBucket: finer })}`)
+ ));
+ if (mine !== overviewSeq) return;
+ page = mergeOverviewPages(pages);
+ }
+ overview = page.buckets ?? [];
+ overviewTruncated = Boolean(page.buckets_truncated);
+ extent = page.extent ?? null;
+ } catch {
+ if (mine === overviewSeq) overview = [];
+ }
+ }
+
+ function snapshotBuckets(rows) {
+ const datedRows = rows.filter((item) => item.earliest);
+ if (!datedRows.length) return [];
+ // Cut by the same rule the server is asked for, so a frozen reading and the live
+ // one it was taken from draw the same histogram.
+ const width = { hour: 13, day: 10, month: 7, year: 4 }[densityUnit({
+ from: datedRows.map((item) => item.earliest).sort()[0],
+ to: datedRows.map((item) => item.latest ?? item.earliest).sort().at(-1),
+ }, overviewWidth)];
+ const grouped = new Map();
+ for (const item of datedRows) {
+ const start = item.earliest.slice(0, width);
+ const bucket = grouped.get(start)
+ ?? { start, count: 0, categories: {}, first: item.earliest, last: item.latest ?? item.earliest };
+ bucket.count += 1;
+ bucket.categories[item.category] = (bucket.categories[item.category] ?? 0) + 1;
+ // The same inner span the server reports beside its counts, so a frozen reading
+ // draws its bars across the days its entries are on, exactly as a live one does.
+ if (item.earliest < bucket.first) bucket.first = item.earliest;
+ const reach = item.latest ?? item.earliest;
+ if (reach > bucket.last) bucket.last = reach;
+ grouped.set(start, bucket);
+ }
+ return [...grouped.values()].sort((a, b) => a.start.localeCompare(b.start));
+ }
+
+ function captureAnalysisView() {
+ return {
+ version: 1,
+ query: { filter: {}, terms: {}, label: '' },
+ timeline: {
+ from: from || null,
+ to: to || null,
+ timezone: zone,
+ zone_choice: zoneChoice,
+ view_mode: viewMode,
+ group_by: groupBy,
+ visible_categories: activeCategories,
+ tracks: trackSpecs,
+ entity: entityFilter,
+ },
+ };
+ }
+
+ function openRangeIn(tool) {
+ if (!caseState.current?.id || !axisWindow) return;
+ const period = { from, to, categories: activeCategories };
+ if (tool === 'board' || tool === 'graph') {
+ setAnalysisPeriod(caseState.current.id, period);
+ }
+ if (tool === 'graph') {
+ uiState.drawInGraph = {
+ label: `Fact time · ${windowWords(from, to, 'UTC')}`,
+ };
+ } else if (tool === 'satellite') {
+ uiState.mapTimelineRange = { from, to, categories: activeCategories };
+ }
+ uiState.tool = tool;
+ rangeMenu = false;
+ }
+
+ async function applyTimelineView(view) {
+ if (!view) return;
+ const state = timelineViewState(view.spec?.timeline);
+ from = state.from;
+ to = state.to;
+ viewMode = state.viewMode;
+ groupBy = state.groupBy;
+ zoneChoice = state.zoneChoice;
+ trackSpecs = state.tracks;
+ entityFilter = state.entity;
+ selected = null;
+ selectedTrackId = null;
+ expandedTracks = {};
+ if (view.mode !== 'snapshot') {
+ trackPages = {};
+ items = [];
+ return;
+ }
+ const captured = view.spec?.snapshot?.timeline_items ?? [];
+ const byId = new Map(captured.map((item) => [item.id, item]));
+ const assignments = view.spec?.snapshot?.timeline_tracks ?? {};
+ trackPages = Object.fromEntries(state.tracks.map((track) => {
+ const ids = assignments[track.id] ?? [];
+ const rows = ids.map((id) => byId.get(id)).filter(Boolean);
+ return [track.id, {
+ items: rows,
+ total: rows.length,
+ undated: rows.filter((item) => !item.raw).length,
+ unplaced: rows.filter((item) => item.raw && !item.earliest).length,
+ cursor: null,
+ extent: null,
+ }];
+ }));
+ items = captured;
+ total = Object.values(trackPages).reduce((sum, page) => sum + page.total, 0);
+ undatedTotal = Object.values(trackPages).reduce((sum, page) => sum + page.undated, 0);
+ unplacedTotal = Object.values(trackPages).reduce((sum, page) => sum + page.unplaced, 0);
+ cursor = null;
+ const datedRows = captured.filter((item) => item.earliest);
+ extent = datedRows.length ? {
+ from: datedRows.map((item) => item.earliest).sort()[0],
+ to: datedRows.map((item) => item.latest).sort().at(-1),
+ } : null;
+ overview = snapshotBuckets(Object.values(trackPages).flatMap((page) => page.items));
+ overviewTruncated = false;
+ }
+
+ async function openAnalysisView(view) {
+ appliedViewId = view.id;
+ await applyTimelineView(view);
+ }
+
+ async function leaveAnalysisReading() {
+ selected = null;
+ selectedTrackId = null;
+ trackPages = {};
+ items = [];
+ trackSpecs = defaultTimelineTracks();
+ groupBy = 'none';
+ zoneChoice = 'utc';
+ from = '';
+ to = '';
+ entityFilter = null;
+ }
+
+ let appliedViewId = null;
+ $effect(() => {
+ const view = timelineViews.activeView;
+ if (!view) {
+ appliedViewId = null;
+ return;
+ }
+ if (view.id === appliedViewId) return;
+ appliedViewId = view.id;
+ untrack(() => void applyTimelineView(view));
+ });
+
+ let observedLiveView = null;
+ let observedLiveState = '';
+ $effect(() => {
+ const view = timelineViews.activeView;
+ const current = JSON.stringify(captureAnalysisView().timeline);
+ if (!view || view.mode !== 'live') {
+ observedLiveView = null;
+ observedLiveState = '';
+ return;
+ }
+ const saved = JSON.stringify(timelineViewState(view.spec?.timeline));
+ const comparable = JSON.stringify({
+ from, to, timezone: zone, zoneChoice, viewMode, groupBy,
+ tracks: normalizeTimelineTracks(trackSpecs),
+ categories: activeCategories,
+ entity: entityFilter,
+ });
+ if (observedLiveView !== view.id) {
+ observedLiveView = view.id;
+ observedLiveState = current;
+ } else if (current !== observedLiveState) {
+ observedLiveState = current;
+ timelineViews.changeVersion += 1;
+ }
+ timelineViews.modified = comparable !== saved;
+ });
+
+ $effect(() => {
+ const caseId = caseState.current?.id;
+ caseState.rev;
+ const chosen = activeCategories.join(',');
+ const scoped = entityFilter?.id ?? '';
+ const first = from;
+ const last = to;
+ const navigating = navigationBusy;
+ const recipe = JSON.stringify(trackSpecs.map((track) => ({
+ id: track.id, categories: track.categories, query: track.query, hidden: track.hidden,
+ })));
+ if (caseId !== loadedCase) {
+ loadedCase = caseId;
+ openAnalysisCase(caseId);
+ from = '';
+ to = '';
+ items = [];
+ trackSpecs = defaultTimelineTracks();
+ trackPages = {};
+ groupBy = 'none';
+ zoneChoice = 'utc';
+ selected = null;
+ pendingSelection = null;
+ cursor = null;
+ expandedTracks = {};
+ }
+ if (!caseId || !chosen || navigating || snapshotReading) return;
+ untrack(() => void loadMain());
+ void scoped; void first; void last; void recipe;
+ });
+
+ $effect(() => {
+ const caseId = caseState.current?.id;
+ caseState.rev;
+ const chosen = activeCategories.join(',');
+ const scoped = entityFilter?.id ?? '';
+ if (!caseId || !chosen || snapshotReading) return;
+ untrack(() => void loadOverview());
+ void scoped;
+ });
+
+ /**
+ * The case's saved points, for the local-time menu. One bounded page, and only
+ * once per case: this is a menu of reference points, not a list of the case.
+ */
+ $effect(() => {
+ const caseId = caseState.current?.id;
+ if (!caseId || snapshotReading) {
+ places = [];
+ return;
+ }
+ let live = true;
+ api
+ .get(buildCatalogQuery(caseId, { types: ['place'], limit: 50 }))
+ .then((page) => {
+ if (!live || caseState.current?.id !== caseId) return;
+ places = (page.items ?? [])
+ .filter((entity) => Number.isFinite(Number(entity.attrs?.lat)))
+ .map((entity) => ({
+ id: entity.id,
+ label: entity.label,
+ lat: Number(entity.attrs.lat),
+ lon: Number(entity.attrs.lon),
+ }));
+ })
+ .catch(() => {
+ if (live) places = [];
+ });
+ return () => {
+ live = false;
+ };
+ });
+
+ /** A point no longer in the case cannot go on labelling the axis. */
+ $effect(() => {
+ if (zoneChoice.startsWith('place:') && places.length && !sunPlace) zoneChoice = 'utc';
+ });
+
+ /**
+ * When it was light at the chosen point, over the window on screen.
+ *
+ * Read on the window because that is what it draws, and the reply carries the
+ * point's own civil zone — so picking a point answers both questions in one call.
+ * A window wider than the server's bound comes back cut and says so, rather than
+ * costing a second to draw a moiré of day and night stripes.
+ */
+ $effect(() => {
+ const place = sunPlace;
+ if (!place || !from || !to) {
+ daylight = null;
+ daylightLoading = false;
+ return;
+ }
+ const mine = ++daylightSeq;
+ daylightLoading = true;
+ const params = new URLSearchParams({
+ lat: String(place.lat), lon: String(place.lon), from, to,
+ });
+ const timer = setTimeout(() => {
+ api
+ .get(`/api/geo/daylight?${params}`)
+ .then((body) => {
+ if (mine === daylightSeq) daylight = body;
+ })
+ .catch(() => {
+ if (mine === daylightSeq) daylight = null;
+ })
+ .finally(() => {
+ if (mine === daylightSeq) daylightLoading = false;
+ });
+ }, 180);
+ return () => clearTimeout(timer);
+ });
+
+ /**
+ * Take the entry another surface asked to open.
+ *
+ * The load that a changed window or scope starts is what usually resolves it. When
+ * nothing about the reading changed — the Map handing back the very window it was
+ * given — no load follows, and a selection waiting for one would never arrive. What
+ * is already drawn answers in that case.
+ */
+ function handOverSelection(itemId) {
+ const held = itemId ? items.find((item) => item.id === itemId) : null;
+ selected = held ?? selected;
+ pendingSelection = itemId && !held ? { id: itemId } : null;
+ }
+
+ $effect(() => {
+ const range = uiState.timelineRange;
+ if (!range) return;
+ uiState.timelineRange = null;
+ if (!windowMillis(range.from, range.to)) return;
+ from = range.from;
+ to = range.to;
+ handOverSelection(range.itemId);
+ });
+
+ $effect(() => {
+ const focus = uiState.timelineFocus;
+ if (!focus) return;
+ entityFilter = { id: focus.entityId, label: focus.entityLabel || 'Selected entity' };
+ selected = null;
+ handOverSelection(focus.itemId);
+ from = '';
+ to = '';
+ uiState.timelineFocus = null;
+ });
+
+ $effect(() => {
+ const caseId = caseState.current?.id;
+ const ownerId = selected?.owner_id;
+ caseState.rev;
+ if (!caseId || !ownerId || snapshotReading) {
+ inspectorChain = null;
+ inspectorLoading = false;
+ return;
+ }
+ const mine = ++inspectorSeq;
+ inspectorLoading = true;
+ api.get(`/api/cases/${caseId}/entities/${ownerId}/chain`)
+ .then((chain) => { if (mine === inspectorSeq) inspectorChain = chain; })
+ .catch(() => { if (mine === inspectorSeq) inspectorChain = null; })
+ .finally(() => { if (mine === inspectorSeq) inspectorLoading = false; });
+ });
+
+ function setBoundary(which, value) {
+ // The control holds a wall clock, and which instant that names depends on the
+ // zone the axis is being read in.
+ const next = inputWindowValue(value, zone);
+ if (!next) return;
+ if (which === 'from') from = next;
+ else to = next;
+ }
+
+ function pan(fraction) {
+ // A menu opened on an entry names a spot the axis is about to move out from under.
+ itemMenu = null;
+ ({ from, to } = shiftWindow(from, to, fraction));
+ }
+
+ function zoom(factor, anchor = .5) {
+ itemMenu = null;
+ ({ from, to } = zoomWindow(from, to, factor, anchor));
+ }
+
+ function finishWheelNavigation() {
+ clearTimeout(navigationTimer);
+ navigationTimer = setTimeout(() => (navigationBusy = false), 140);
+ }
+
+ function navigateWheel(event) {
+ if (!axisWindow) return;
+ const horizontal = Math.abs(event.deltaX) > Math.abs(event.deltaY) * .35;
+ event.preventDefault();
+ navigationBusy = true;
+ itemMenu = null;
+ const rect = event.currentTarget.getBoundingClientRect();
+ if (!event.shiftKey && !horizontal) {
+ const anchor = Math.min(1, Math.max(0, (event.clientX - rect.left) / rect.width));
+ const delta = Math.max(-120, Math.min(120, event.deltaY));
+ ({ from, to } = zoomWindow(from, to, Math.exp(delta * .0025), anchor));
+ } else {
+ const delta = horizontal ? event.deltaX : event.deltaY;
+ ({ from, to } = shiftWindow(from, to, delta / Math.max(1, rect.width)));
+ }
+ finishWheelNavigation();
+ }
+
+ function navigateKey(event) {
+ const key = event.key;
+ if (!['ArrowLeft', 'ArrowRight', 'PageUp', 'PageDown', '+', '=', '-', '_', 'Home'].includes(key)) return;
+ event.preventDefault();
+ if (key === 'ArrowLeft') pan(-.1);
+ else if (key === 'ArrowRight') pan(.1);
+ else if (key === 'PageUp') pan(-.7);
+ else if (key === 'PageDown') pan(.7);
+ else if (key === '+' || key === '=') zoom(.5);
+ else if (key === '-' || key === '_') zoom(2);
+ else showAll();
+ }
+
+ function panStart(event) {
+ if (event.button !== 0 || !axisWindow) return;
+ event.preventDefault();
+ navigationBusy = true;
+ const rect = event.currentTarget.getBoundingClientRect();
+ panning = { pointer: event.pointerId, startX: event.clientX, from, to, width: rect.width };
+ event.currentTarget.setPointerCapture(event.pointerId);
+ }
+
+ function showAll() {
+ ({ from, to } = initialWindow(extent));
+ }
+
+ /** What a track is a reading of, for its hover: the name, then the question that
+ * filled it, so a lane of eleven events can be told from the twelve beside it. */
+ function trackTitle(track) {
+ const words = track.categories
+ .map((category) => TIMELINE_CATEGORIES.find((entry) => entry.id === category)?.short ?? category)
+ .join(' · ');
+ const asked = track.query?.label?.trim();
+ return [track.label, [words, asked || 'the whole case'].join(' · ')].join('\n');
+ }
+
+ /** A span asked for by name. Absolute where a zoom step is relative: "Week" is the
+ * thing wanted, and pressing minus four times is counting. */
+ function setSpan(span) {
+ ({ from, to } = resizeWindow(from, to, span));
+ }
+
+ function expandTrack(id, expanded = true) {
+ expandedTracks = { ...expandedTracks, [id]: expanded };
+ }
+
+ function addPreset(preset) {
+ const duplicate = copyTimelineTrack(preset, trackSpecs);
+ const used = trackSpecs.some((track) => track.label.toLocaleLowerCase() === preset.label.toLocaleLowerCase());
+ trackSpecs = [...trackSpecs, { ...duplicate, label: used ? duplicate.label : preset.label }];
+ trackMenu = false;
+ }
+
+ function saveTrack(track) {
+ if (trackEditor?.mode === 'edit') {
+ trackSpecs = trackSpecs.map((entry) => entry.id === trackEditor.track.id ? { ...track, id: entry.id } : entry);
+ } else {
+ const created = copyTimelineTrack(track, trackSpecs);
+ trackSpecs = [...trackSpecs, { ...created, label: track.label }];
+ }
+ trackEditor = null;
+ }
+
+ function duplicateTrack(id) {
+ const index = trackSpecs.findIndex((track) => track.id === id);
+ if (index < 0) return;
+ const next = copyTimelineTrack(trackSpecs[index], trackSpecs);
+ trackSpecs = [...trackSpecs.slice(0, index + 1), next, ...trackSpecs.slice(index + 1)];
+ }
+
+ function removeTrack(id) {
+ if (trackSpecs.length === 1) return;
+ trackSpecs = trackSpecs.filter((track) => track.id !== id);
+ if (selectedTrackId === id) {
+ selectedTrackId = null;
+ selected = null;
+ }
+ }
+
+ function setTrackCollapsed(id, collapsed) {
+ trackSpecs = trackSpecs.map((track) => track.id === id ? { ...track, collapsed } : track);
+ }
+
+ function dropTrack(targetId) {
+ const fromIndex = trackSpecs.findIndex((track) => track.id === draggedTrack);
+ const toIndex = trackSpecs.findIndex((track) => track.id === targetId);
+ trackSpecs = moveTimelineTrack(trackSpecs, fromIndex, toIndex);
+ draggedTrack = null;
+ }
+
+ /**
+ * The track an entry is being read in: the lane it was clicked in, or failing that
+ * the first lane that holds it.
+ *
+ * Both lane acts need it, and they are reached from three places — the inspector,
+ * the entry menu, and the list view, where nothing says which lane a row came from.
+ */
+ function trackHolding(item, trackId = null) {
+ const id = trackId ?? trackSpecs.find((track) =>
+ (baseTrackItems[track.id] ?? []).some((entry) => entry.id === item.id)
+ )?.id ?? null;
+ return trackSpecs.find((track) => track.id === id) ?? null;
+ }
+
+ function togglePinned(item = selected, track = selectedTrack) {
+ if (!track || !item) return;
+ const pinned = track.pinned.includes(item.id)
+ ? track.pinned.filter((id) => id !== item.id)
+ : [...track.pinned, item.id];
+ trackSpecs = trackSpecs.map((entry) => entry.id === track.id ? { ...entry, pinned } : entry);
+ }
+
+ function hideFromTrack(item = selected, track = selectedTrack) {
+ if (!track || !item) return;
+ const hidden = [...new Set([...track.hidden, item.id])];
+ trackSpecs = trackSpecs.map((entry) => entry.id === track.id
+ ? { ...entry, hidden, pinned: entry.pinned.filter((id) => id !== item.id) }
+ : entry
+ );
+ // What is no longer drawn cannot go on being the entry the panel is about, nor
+ // the second half of a measurement.
+ if (selected?.id === item.id) {
+ selected = null;
+ selectedTrackId = null;
+ }
+ if (against?.id === item.id) against = null;
+ }
+
+ function restoreHidden(id) {
+ trackSpecs = trackSpecs.map((track) => track.id === id ? { ...track, hidden: [] } : track);
+ }
+
+ /**
+ * A click selects; **Ctrl-click holds a second entry against the first**, and the
+ * panel measures between them.
+ *
+ * The modifier rather than a mode, because measuring is something an analyst does
+ * *while* reading one entry — a "compare" button would be a state to enter, leave
+ * and forget you were in. Ctrl-clicking the held entry again lets it go.
+ */
+ function selectItem(item, trackId = null, event = null) {
+ if ((event?.ctrlKey || event?.metaKey) && selected && selected.id !== item.id) {
+ against = against?.id === item.id ? null : item;
+ return;
+ }
+ selected = item;
+ against = null;
+ selectedTrackId = trackHolding(item, trackId)?.id ?? null;
+ }
+
+ /**
+ * What can be done with an entry, said where the pointer is.
+ *
+ * The inspector already names these four acts, and every one of them cost a
+ * selection first: reading a lane meant clicking an entry, losing the entry the
+ * panel was on and any pair being measured with it. The menu asks nothing of the
+ * selection — right-clicking an entry is a question about it, not a choice of it.
+ */
+ function openItemMenu(event, item, trackId = null) {
+ // On macOS this same press is the Ctrl-click that holds a second entry against
+ // the first. One press, one act.
+ if (event.ctrlKey && event.button === 0) return;
+ event.preventDefault();
+ event.stopPropagation();
+ tooltip = null;
+ itemMenu = {
+ item,
+ track: trackHolding(item, trackId),
+ x: Math.min(window.innerWidth - 206, event.clientX),
+ y: Math.min(window.innerHeight - 186, event.clientY),
+ };
+ }
+
+ /**
+ * Run a menu item against the entry the menu is about, then close it.
+ *
+ * The entry is read *before* the menu is cleared: closing it first destroys what
+ * the markup read the entry from, and the act then runs on nothing.
+ */
+ function fromItemMenu(act) {
+ const held = itemMenu;
+ itemMenu = null;
+ if (held) act(held.item, held.track);
+ }
+
+ async function toggleFullscreen() {
+ if (!toolElement || typeof document === 'undefined') return;
+ try {
+ if (document.fullscreenElement) await document.exitFullscreen();
+ else await toolElement.requestFullscreen();
+ } catch {
+ toast('Full screen is not available', 'danger');
+ }
+ }
+
+ function openBucket(bucket) {
+ const range = bucketWindow(bucket);
+ if (range) ({ from, to } = range);
+ }
+
+ function openEditor(item = null, when = '', options = {}) {
+ if (snapshotReading) return;
+ editor = { item, when, ...options };
+ }
+
+ function addMediaCorrection() {
+ if (!inspectorChain?.entity) return;
+ openEditor(null, selected?.raw ?? '', {
+ subject: inspectorChain.entity,
+ statement: 'This media was captured',
+ role: 'observed',
+ });
+ }
+
+ async function editorSaved(saved) {
+ editor = null;
+ pendingSelection = saved.temporal ? { id: saved.temporal.id, fallback: saved.temporal } : null;
+ await reloadCase();
+ }
+
+ let drawing = $state(null);
+ function drawStart(event, trackId) {
+ const track = trackSpecs.find((entry) => entry.id === trackId);
+ if (
+ snapshotReading || !track?.categories.includes('statement') ||
+ event.button !== 0 || event.target.closest('button')
+ ) return;
+ const rect = event.currentTarget.getBoundingClientRect();
+ const ratio = (event.clientX - rect.left) / rect.width;
+ drawing = { pointer: event.pointerId, trackId, start: ratio, end: ratio, rect };
+ event.currentTarget.setPointerCapture(event.pointerId);
+ }
+
+ function createFromKeyboard() {
+ openEditor(null, draftWhen(from, to, .5, .5));
+ }
+
+ /** The instants the minimap spans — the bars', so a drag lands where it looks. */
+ function overviewExtent() {
+ return densityScale(overview, extent);
+ }
+
+ function applyOverviewWindow(left, right) {
+ const full = overviewExtent();
+ if (!full) return;
+ const low = Math.max(0, Math.min(.999, left));
+ const high = Math.min(1, Math.max(low + Math.max(.002, 2_000 / full.span), right));
+ from = isoInstant(full.first + full.span * low);
+ to = isoInstant(full.first + full.span * high);
+ }
+
+ function beginOverview(event, mode) {
+ if (event.button !== 0) return;
+ event.preventDefault();
+ event.stopPropagation();
+ const rect = event.currentTarget.closest('.density-bars').getBoundingClientRect();
+ overviewGesture = {
+ pointer: event.pointerId, mode, startX: event.clientX, rect,
+ left: overviewWindow.left / 100, right: (overviewWindow.left + overviewWindow.width) / 100,
+ moved: false,
+ };
+ navigationBusy = true;
+ event.currentTarget.setPointerCapture(event.pointerId);
+ }
+
+ function overviewRecenter(event) {
+ if (event.target.closest('.overview-window') || !axisWindow) return;
+ const rect = event.currentTarget.getBoundingClientRect();
+ const center = Math.max(0, Math.min(1, (event.clientX - rect.left) / rect.width));
+ const width = overviewWindow.width / 100;
+ applyOverviewWindow(center - width / 2, center + width / 2);
+ }
+
+ function overviewKey(event, mode) {
+ if (!['ArrowLeft', 'ArrowRight'].includes(event.key)) return;
+ event.preventDefault();
+ const delta = event.key === 'ArrowLeft' ? -.02 : .02;
+ const left = overviewWindow.left / 100;
+ const right = (overviewWindow.left + overviewWindow.width) / 100;
+ if (mode === 'move') applyOverviewWindow(left + delta, right + delta);
+ else if (mode === 'start') applyOverviewWindow(left + delta, right);
+ else applyOverviewWindow(left, right + delta);
+ }
+
+ function pointerMove(event) {
+ if (overviewGesture?.pointer === event.pointerId) {
+ const gesture = overviewGesture;
+ const delta = (event.clientX - gesture.startX) / Math.max(1, gesture.rect.width);
+ gesture.moved ||= Math.abs(event.clientX - gesture.startX) > 2;
+ if (gesture.mode === 'move') {
+ const width = gesture.right - gesture.left;
+ const left = Math.max(0, Math.min(1 - width, gesture.left + delta));
+ applyOverviewWindow(left, left + width);
+ } else if (gesture.mode === 'start') applyOverviewWindow(gesture.left + delta, gesture.right);
+ else applyOverviewWindow(gesture.left, gesture.right + delta);
+ return;
+ }
+ if (panning?.pointer === event.pointerId) {
+ const fraction = -(event.clientX - panning.startX) / Math.max(1, panning.width);
+ ({ from, to } = shiftWindow(panning.from, panning.to, fraction));
+ return;
+ }
+ if (drawing?.pointer === event.pointerId) {
+ drawing.end = Math.min(1, Math.max(0, (event.clientX - drawing.rect.left) / drawing.rect.width));
+ return;
+ }
+ if (moving?.pointer === event.pointerId) moving.currentX = event.clientX;
+ }
+
+ function pointerUp(event) {
+ if (overviewGesture?.pointer === event.pointerId) {
+ overviewGesture = null;
+ navigationBusy = false;
+ return;
+ }
+ if (panning?.pointer === event.pointerId) {
+ panning = null;
+ navigationBusy = false;
+ return;
+ }
+ if (drawing?.pointer === event.pointerId) {
+ const draft = drawing;
+ drawing = null;
+ openEditor(null, draftWhen(from, to, draft.start, draft.end));
+ return;
+ }
+ if (!moving || moving.pointer !== event.pointerId) return;
+ const edit = moving;
+ moving = null;
+ const ratio = Math.min(1, Math.max(0, (event.clientX - edit.rect.left) / edit.rect.width));
+ let raw = null;
+ if (edit.mode === 'move') {
+ const delta = ((event.clientX - edit.startX) / edit.rect.width) * axisWindow.span;
+ raw = moveTemporalRaw(edit.item, delta);
+ } else {
+ const value = edit.item.raw.includes('T')
+ ? timeAtRatio(from, to, ratio)
+ : dateAtRatio(from, to, ratio);
+ raw = resizeTemporalRaw(edit.item, edit.mode, value);
+ }
+ if (raw && raw !== edit.item.raw) pendingEdit = { item: edit.item, raw };
+ }
+
+ let moving = $state(null);
+ let pendingEdit = $state(null);
+ let directSaving = $state(false);
+ function beginMove(event, item, mode = 'move') {
+ // The right button asks what can be done with the entry. Without this, opening
+ // that menu on the selected entry also armed a drag of its date.
+ if (snapshotReading || event.button !== 0) return;
+ event.stopPropagation();
+ const rect = event.currentTarget.closest('.track-canvas').getBoundingClientRect();
+ moving = { pointer: event.pointerId, item, mode, startX: event.clientX, currentX: event.clientX, rect };
+ event.currentTarget.setPointerCapture(event.pointerId);
+ }
+
+ function keyboardEdit(event, item, mode) {
+ if (snapshotReading) return;
+ if (!['ArrowLeft', 'ArrowRight'].includes(event.key)) return;
+ event.preventDefault();
+ event.stopPropagation();
+ const raw = nudgeTemporalRaw(item, mode, event.key === 'ArrowLeft' ? -1 : 1);
+ if (raw && raw !== item.raw) pendingEdit = { item, raw };
+ }
+
+ async function confirmDirectEdit() {
+ if (!pendingEdit || directSaving) return;
+ directSaving = true;
+ try {
+ await api.patch(
+ `/api/cases/${caseState.current.id}/timeline/claims/${pendingEdit.item.owner_id}`,
+ { when: pendingEdit.raw }
+ );
+ pendingEdit = null;
+ await reloadCase();
+ toast('Time assessment updated', 'ok', 1600);
+ } catch (error) {
+ toast(error.message, 'danger');
+ } finally {
+ directSaving = false;
+ }
+ }
+
+ function categoryName(item) {
+ return TIMELINE_CATEGORIES.find((entry) => entry.id === item.category)?.label ?? item.category;
+ }
+
+ function unplacedReason(item) {
+ if (item.parse_error) return item.parse_error;
+ if (item.zone === 'local') return 'Timezone needed';
+ return 'Needs review';
+ }
+
+ function showItemTooltip(event, item) {
+ const reading = formatTemporalValue(item.raw ?? '');
+ tooltip = {
+ x: Math.min(window.innerWidth - 286, event.clientX + 12),
+ y: Math.min(window.innerHeight - 132, event.clientY + 12),
+ title: item.label,
+ date: reading.label,
+ detail: [categoryName(item), item.time_role, item.confidence].filter(Boolean).join(' · '),
+ };
+ }
+
+ function showFocusedTooltip(event, item) {
+ const rect = event.currentTarget.getBoundingClientRect();
+ showItemTooltip({ clientX: rect.right, clientY: rect.top }, item);
+ }
+
+ function showBucketTooltip(event, bucket) {
+ const parts = TIMELINE_CATEGORIES
+ .map((category) => bucket.categories?.[category.id] ? `${category.short} ${bucket.categories[category.id]}` : '')
+ .filter(Boolean)
+ .join(' · ');
+ tooltip = {
+ x: Math.min(window.innerWidth - 286, event.clientX + 12),
+ y: Math.min(window.innerHeight - 110, event.clientY + 12),
+ title: bucket.start,
+ date: `${bucket.count} ${bucket.count === 1 ? 'entry' : 'entries'}`,
+ detail: parts,
+ };
+ }
+
+</script>
+
+<svelte:window
+ onpointermove={pointerMove}
+ onpointerup={pointerUp}
+ onkeydown={(event) => { if (event.key === 'Escape' && itemMenu) itemMenu = null; }}
+/>
+
+<div class="timeline-tool" class:fullscreen bind:this={toolElement}>
+ <header class="timeline-head">
+ <!-- Titled the way every other tool is (`app.css .tool-header`): the name, then
+ one clause saying what is on screen. It used to carry a second title over the
+ first in accent capitals, which said the same word twice. -->
+ <div class="title-block">
+ <h2>Timeline</h2>
+ <span class="sub">{total} {total === 1 ? 'entry' : 'entries'} across tracks</span>
+ </div>
+
+ <!-- The window, read rather than spelled out in controls. Two date boxes, four
+ icons and an All button were seven things on the toolbar for one fact; the
+ boundaries are typed rarely and checked constantly, so the reading is what
+ stays out and the rest opens under it. Panning keeps its arrows because
+ stepping through a chronology is the frequent move. -->
+ <div class="range" bind:this={rangeElement}>
+ <button class="range-step" title="Earlier" aria-label="Earlier" onclick={() => pan(-.7)} disabled={!axisWindow}>
+ <Icon name="chevronLeft" size={15} />
+ </button>
+ <button class="range-face" aria-expanded={rangeMenu} onclick={() => (rangeMenu = !rangeMenu)}>
+ {windowWords(from, to, zone)}
+ </button>
+ <button class="range-step" title="Later" aria-label="Later" onclick={() => pan(.7)} disabled={!axisWindow}>
+ <Icon name="chevronRight" size={15} />
+ </button>
+ {#if rangeMenu}
+ <div class="range-menu">
+ <label>
+ From
+ <input class="input input-sm mono" type="datetime-local" step="1" value={windowInputValue(from, zone)} onchange={(event) => setBoundary('from', event.currentTarget.value)} />
+ </label>
+ <label>
+ To
+ <input class="input input-sm mono" type="datetime-local" step="1" value={windowInputValue(to, zone)} onchange={(event) => setBoundary('to', event.currentTarget.value)} />
+ </label>
+ <div class="range-spans" role="group" aria-label="Window span">
+ {#each WINDOW_SPANS as span (span.label)}
+ <button onclick={() => setSpan(span.ms)} disabled={!axisWindow}>{span.label}</button>
+ {/each}
+ <button onclick={() => { showAll(); rangeMenu = false; }} disabled={!extent?.from}>All</button>
+ </div>
+ </div>
+ {/if}
+ </div>
+
+ <div class="head-actions">
+ <AnalysisViews
+ surface="timeline"
+ capture={captureAnalysisView}
+ onopen={openAnalysisView}
+ onleave={leaveAnalysisReading}
+ />
+ <button class="btn btn-ghost fullscreen-btn" aria-pressed={fullscreen} onclick={toggleFullscreen}>{fullscreen ? 'Exit full screen' : 'Full screen'}</button>
+ <button class="btn btn-primary add-event" disabled={snapshotReading} onclick={() => openEditor()}><Icon name="plus" size={13} />Add assessment</button>
+ </div>
+ </header>
+
+ <div class="filter-row">
+ {#if entityFilter}
+ <button class="scope-chip" disabled={snapshotReading} title="Clear entity filter" onclick={() => { entityFilter = null; from = ''; to = ''; }}>
+ <Icon name="crosshair" size={11} /><span>{entityFilter.label}</span><Icon name="x" size={10} />
+ </button>
+ {/if}
+ <div class="view-switch" aria-label="Timeline display">
+ <button class:active={viewMode === 'plot'} aria-pressed={viewMode === 'plot'} onclick={() => (viewMode = 'plot')}>Plot</button>
+ <button class:active={viewMode === 'list'} aria-pressed={viewMode === 'list'} onclick={() => (viewMode = 'list')}>List</button>
+ </div>
+ <!-- Which clock the axis is read on. Presentation only: the case stores UTC, the
+ queries ask in UTC, and this moves the ticks and their words. A saved point
+ also brings its daylight with it, since a band of day and night needs
+ coordinates and there is no sense in asking for them twice. -->
+ <ZonePicker
+ bind:choice={zoneChoice}
+ {places}
+ at={axisWindow?.start ?? 0}
+ resolved={zone}
+ disabled={snapshotReading}
+ />
+ <details class="legend" bind:this={legendElement} bind:open={legendOpen}>
+ <summary>Legend</summary>
+ <div class="legend-card">
+ <strong>Date quality</strong>
+ <span><i class="sample approximate"></i>Approximate date</span>
+ <span><i class="sample uncertain"></i>Uncertain date</span>
+ <strong>Assessment</strong>
+ <span><i class="sample suggested"></i>Suggested status</span>
+ <span><i class="sample refuted"></i>Refuted confidence</span>
+ <p>Confidence and date quality are independent.</p>
+ </div>
+ </details>
+ <span class="utc-readout">{scaleLabel} · Wheel zoom · Shift-wheel pan</span>
+ </div>
+
+ <div class="track-toolbar">
+ <div class="track-add" bind:this={trackMenuElement}>
+ <button class="btn btn-sm" aria-expanded={trackMenu} disabled={snapshotReading || trackSpecs.length >= 20} onclick={() => (trackMenu = !trackMenu)}>
+ <Icon name="plus" size={12} /> Track
+ </button>
+ {#if trackMenu}
+ <div class="track-menu">
+ <strong>Add a track</strong>
+ {#each trackPresets(entityTypes()) as preset (preset.id)}
+ <button onclick={() => addPreset(preset)}><span>{preset.label}</span><small>{preset.categories.map((category) => category === 'case_activity' ? 'activity' : category).join(' · ')}</small></button>
+ {/each}
+ <button class="custom" onclick={() => { trackEditor = { mode: 'new' }; trackMenu = false; }}>
+ <span>Custom</span><small>Build with Search+</small>
+ </button>
+ </div>
+ {/if}
+ </div>
+ <label>Group by
+ <select class="input input-sm" bind:value={groupBy} disabled={snapshotReading}>
+ <option value="none">None</option>
+ <option value="subject">Subject</option>
+ <option value="type">Type</option>
+ <option value="place">Place</option>
+ <option value="source">Evidence</option>
+ <option value="role">Time role</option>
+ </select>
+ </label>
+ <span>{trackSpecs.length} {trackSpecs.length === 1 ? 'track' : 'tracks'}</span>
+ {#if snapshotReading}<em>Frozen view</em>{/if}
+
+ <!-- Asking the same period of the other three surfaces is the point of having a
+ period, so the handoff stays in the open rather than under the window's
+ boundaries: the window is set rarely and handed over often. It ends the track
+ row instead of trailing the window, which left six controls fighting for the
+ middle of the header for one fact. -->
+ <div class="range-handoffs" role="group" aria-label="Open range">
+ <span>Open in</span>
+ <button onclick={() => openRangeIn('board')} disabled={!axisWindow}>Board</button>
+ <button onclick={() => openRangeIn('graph')} disabled={!axisWindow}>Graph</button>
+ <button onclick={() => openRangeIn('satellite')} disabled={!axisWindow}>Map</button>
+ </div>
+ </div>
+
+ <div class="timeline-grid">
+ <main class="chronology">
+ {#if !caseState.current}
+ <div class="blank-state"><Icon name="clock" size={24} /><h2>Open a case to build its timeline.</h2></div>
+ {:else if !extent?.from && !loading}
+ <div class="blank-state">
+ <Icon name="clock" size={24} />
+ <h2>No dated entries yet</h2>
+ <p>Add a time assessment here or from an entity's Time tab.</p>
+ <button class="btn btn-primary" disabled={snapshotReading} onclick={() => openEditor()}>Add first assessment</button>
+ </div>
+ {:else}
+ <section class="overview-card" aria-label="Timeline overview">
+ <div class="overview-title">
+ <span>Overview</span>
+ <!-- The extent in words rather than the first and last bucket keys, which
+ read as `2026-08-02T03` the moment the case is cut by the hour. -->
+ <small>{extent?.from ? windowWords(extent.from, extent.to, 'UTC') : 'No dated entries'}</small>
+ {#if overview.length}<small>{overviewUnit} buckets · exact counts on hover</small>{/if}
+ <div class="overview-counts">
+ {#if unplacedTotal}<span>{unplacedTotal} local</span>{/if}
+ {#if undatedTotal}<span>{undatedTotal} undated</span>{/if}
+ </div>
+ {#if overviewTruncated}<small class="capped">Partial overview</small>{/if}
+ </div>
+ <!-- svelte-ignore a11y_no_noninteractive_tabindex -->
+ <!-- svelte-ignore a11y_no_noninteractive_element_interactions -->
+ <div class="density-bars" role="application" tabindex="0" aria-label="Timeline minimap" bind:clientWidth={overviewWidth} onclick={overviewRecenter} onkeydown={navigateKey}>
+ {#each overviewTicks as slot (slot.key)}
+ {#if slot.label && slot.left > 0}
+ <span class="overview-rule" style:left={`${slot.left}%`}></span>
+ {/if}
+ {/each}
+ {#each density as bucket (bucket.start)}
+ <button
+ class="density-bucket"
+ aria-label={`${bucket.start}, ${bucket.count} entries`}
+ style:left={`${bucket.left}%`}
+ style:width={`${bucket.width}%`}
+ onclick={(event) => { event.stopPropagation(); openBucket(bucket); }}
+ onpointerenter={(event) => showBucketTooltip(event, bucket)}
+ onpointermove={(event) => showBucketTooltip(event, bucket)}
+ onpointerleave={() => (tooltip = null)}
+ >
+ <span class="density-stack" style:height={`${bucket.height}%`}>
+ {#each TIMELINE_CATEGORIES as category (category.id)}
+ {#if bucket.categories?.[category.id]}
+ <i class={category.id} style:flex-grow={bucket.categories[category.id]}></i>
+ {/if}
+ {/each}
+ </span>
+ </button>
+ {/each}
+ <span class="density-baseline"></span>
+ {#each overviewTicks as slot (slot.key)}
+ {#if slot.label}
+ <span
+ class="overview-tick {slot.anchor}"
+ style:left={`${slot.left}%`}
+ style:width={`${slot.width}%`}
+ >{slot.label}</span>
+ {/if}
+ {/each}
+ <!-- What the axis is not showing, dimmed: the brush says where the window
+ is, and these say what it left out. -->
+ <span class="overview-shade" style:left="0" style:width={`${overviewWindow.left}%`}></span>
+ <span class="overview-shade" style:left={`${overviewWindow.left + overviewWindow.width}%`} style:right="0"></span>
+ <div class="overview-window" style:left={`${overviewWindow.left}%`} style:width={`${overviewWindow.width}%`}>
+ <button class="overview-drag" aria-label="Move visible range" title="Move visible range" onpointerdown={(event) => beginOverview(event, 'move')} onkeydown={(event) => overviewKey(event, 'move')}></button>
+ <button class="overview-handle start" aria-label="Change range start" title="Change range start" onpointerdown={(event) => beginOverview(event, 'start')} onkeydown={(event) => overviewKey(event, 'start')}></button>
+ <button class="overview-handle end" aria-label="Change range end" title="Change range end" onpointerdown={(event) => beginOverview(event, 'end')} onkeydown={(event) => overviewKey(event, 'end')}></button>
+ </div>
+ </div>
+ </section>
+
+ {#if viewMode === 'plot'}
+ <section class="axis-card" aria-label="Timeline axis">
+ <div class="axis-row">
+ <div class="axis-label">
+ <span>{zoneWord}</span>
+ <small>{windowInputValue(from, zone).replace('T', ' ')} to {windowInputValue(to, zone).replace('T', ' ')}</small>
+ </div>
+ <!-- svelte-ignore a11y_no_noninteractive_tabindex -->
+ <!-- svelte-ignore a11y_no_noninteractive_element_interactions -->
+ <div
+ class="axis-ruler"
+ class:panning={Boolean(panning)}
+ bind:this={plotElement}
+ role="application"
+ tabindex="0"
+ aria-label="Timeline ruler"
+ onpointerdown={panStart}
+ onwheel={navigateWheel}
+ onkeydown={navigateKey}
+ >
+ <div class="axis-bands">
+ {#each bands as band (band.label + band.left)}
+ <span style:left={`${band.left}%`} style:width={`${band.width}%`}>{band.label}</span>
+ {/each}
+ </div>
+ {#each minorTicks as tick (tick.at)}<span class="axis-minor" style:left={`${tick.left}%`}></span>{/each}
+ {#each ticks as tick (tick.at)}
+ <div class="axis-tick" class:end={tick.left > 94} style:left={`${tick.left}%`}><span>{tick.label}</span></div>
+ {/each}
+ {#if nowLeft !== null}<span class="now-line" style:left={`${nowLeft}%`}><small>Now</small></span>{/if}
+ <!-- Day and night at the chosen point, on the same scale as the
+ entries above it: a stamp of 19:40 is argued against the light,
+ and the ribbon is where that argument becomes visible. Night is
+ the strip itself, twilight and day are laid over it. -->
+ {#if sunPlace}
+ <div class="daylight" aria-hidden="true">
+ {#each twilightBands as band (band.key)}
+ <span class="twilight" style:left={`${band.left}%`} style:width={`${band.width}%`}></span>
+ {/each}
+ {#each daylightBands as band (band.key)}
+ <span class="day" style:left={`${band.left}%`} style:width={`${band.width}%`}></span>
+ {/each}
+ </div>
+ {/if}
+ </div>
+ </div>
+ {#if sunPlace}
+ <!-- What the ribbon is of, said next to it: a band of day and night
+ nobody can attribute to a point is decoration. -->
+ <p class="daylight-note">
+ Daylight at {sunPlace.label}{#if daylight?.zone?.name}, {zoneWord}{/if}.
+ {#if daylightLoading}
+ Reading…
+ {:else if daylight?.truncated}
+ Zoom in past a month to draw it.
+ {:else if !daylightBands.length && !twilightBands.length}
+ Dark for the whole window.
+ {/if}
+ </p>
+ {/if}
+
+ {#each tracks as track (track.id)}
+ {@const baseId = track.parentId ?? track.id}
+ {@const canCreate = track.categories.includes('statement') && !snapshotReading}
+ <div
+ class="track-row"
+ class:folded={track.collapsed}
+ role="listitem"
+ style:--track-tint={trackTint(track.color)}
+ style:min-height={track.collapsed ? '42px' : `${Math.max(78, track.layout.rows * 46 + 28)}px`}
+ ondragover={(event) => { if (groupBy === 'none' && !snapshotReading) event.preventDefault(); }}
+ ondrop={() => dropTrack(baseId)}
+ >
+ <div class="track-label" class:movable={groupBy === 'none' && !snapshotReading}>
+ {#if groupBy === 'none' && !snapshotReading}
+ <button
+ class="drag-track"
+ aria-label={`Move ${track.label} track`}
+ title="Drag or press Alt-arrow to reorder"
+ draggable="true"
+ ondragstart={() => (draggedTrack = baseId)}
+ onkeydown={(event) => {
+ if (!event.altKey || !['ArrowUp', 'ArrowDown'].includes(event.key)) return;
+ event.preventDefault();
+ const index = trackSpecs.findIndex((entry) => entry.id === baseId);
+ const next = event.key === 'ArrowUp' ? index - 1 : index + 1;
+ trackSpecs = moveTimelineTrack(trackSpecs, index, next);
+ }}
+ ><Icon name="grip" size={11} /></button>
+ {/if}
+ <button class="fold-track" aria-label={`${track.collapsed ? 'Expand' : 'Fold'} ${track.label}`} disabled={snapshotReading} onclick={() => setTrackCollapsed(baseId, !track.collapsed)}>
+ <Icon name={track.collapsed ? 'chevronRight' : 'chevronDown'} size={11} />
+ </button>
+ <span class={`category-dot ${track.categories[0]}`}></span>
+ <!-- The hover says what the lane below is a reading of: the whole
+ name, then the question that filled it. -->
+ <span class="track-name" title={trackTitle(track)}><strong>{track.label}</strong>{#if track.groupLabel}<em>{track.groupLabel}</em>{/if}</span>
+ <small title={track.total !== track.items.length ? 'A sample across the window. Load more fills it in.' : undefined}>{track.layout.items.length + track.layout.clusters.reduce((sum, cluster) => sum + cluster.count, 0)}{#if track.total !== track.items.length} / {track.total}{/if}</small>
+ {#if groupBy === 'none' && !snapshotReading}
+ <div class="track-actions">
+ <button aria-label={`Edit ${track.label}`} title="Edit track" onclick={() => (trackEditor = { mode: 'edit', track })}><Icon name="edit" size={11} /></button>
+ <button aria-label={`Duplicate ${track.label}`} title="Duplicate track" onclick={() => duplicateTrack(baseId)}><Icon name="copy" size={11} /></button>
+ <button aria-label={`Delete ${track.label}`} title="Delete track" disabled={trackSpecs.length === 1} onclick={() => removeTrack(baseId)}><Icon name="trash" size={11} /></button>
+ </div>
+ {/if}
+ {#if trackSpecs.find((entry) => entry.id === baseId)?.hidden.length}
+ <button class="restore-hidden" disabled={snapshotReading} onclick={() => restoreHidden(baseId)}>Show hidden</button>
+ {/if}
+ {#if track.expanded}<button class="collapse-track" onclick={() => expandTrack(baseId, false)}>Collapse</button>{/if}
+ </div>
+ <!-- svelte-ignore a11y_no_noninteractive_tabindex -->
+ <!-- svelte-ignore a11y_no_noninteractive_element_interactions -->
+ <div
+ class="track-canvas"
+ class:createable={canCreate}
+ role="application"
+ tabindex="0"
+ aria-label={`${track.label} track`}
+ onpointerdown={(event) => drawStart(event, baseId)}
+ onwheel={navigateWheel}
+ onkeydown={(event) => {
+ if ((event.key === 'Enter' || event.key === ' ') && canCreate) {
+ event.preventDefault(); createFromKeyboard();
+ } else navigateKey(event);
+ }}
+ >
+ {#if !track.collapsed}
+ {#each minorTicks as tick (tick.at)}<span class="gridline minor" style:left={`${tick.left}%`}></span>{/each}
+ {#each ticks as tick (tick.at)}<span class="gridline" style:left={`${tick.left}%`}></span>{/each}
+ {#if nowLeft !== null}<span class="track-now" style:left={`${nowLeft}%`}></span>{/if}
+ {#if drawing?.trackId === baseId}
+ <div class="draw-range" style:left={`${Math.min(drawing.start, drawing.end) * 100}%`} style:width={`${Math.max(.35, Math.abs(drawing.end - drawing.start) * 100)}%`}></div>
+ {/if}
+ {#each track.layout.items as item (item.id)}
+ {#if item.shape !== 'interval' && item.zone === 'date-only' && item.haloWidth > 0}
+ <span
+ class={`precision-span ${item.category}`}
+ class:chosen={selected?.id === item.id}
+ style:left={`${item.haloLeft}%`}
+ style:width={`${item.haloWidth}%`}
+ style:top={`${item.lane * 46 + 31}px`}
+ aria-hidden="true"
+ ></span>
+ {/if}
+ <div
+ class={`timeline-event ${item.category}`}
+ class:chosen={selected?.id === item.id}
+ class:against={against?.id === item.id}
+ class:period={item.shape === 'interval'}
+ class:approximate={item.approximate}
+ class:uncertain={item.uncertain}
+ class:suggested={item.status === 'suggested'}
+ class:refuted={item.confidence === 'refuted'}
+ class:pinned={item.pinned}
+ class:axis-editable={canDragTemporal(item) && !snapshotReading}
+ class:end-aligned={item.endAligned}
+ style:left={`${item.left}%`}
+ style:width={`${item.width}%`}
+ style:top={`${item.lane * 46 + 18}px`}
+ >
+ {#if item.shape === 'interval' && canDragTemporal(item) && !snapshotReading}
+ <button class="resize start" aria-label="Resize start" title="Resize start" onpointerdown={(event) => beginMove(event, item, 'start')} onkeydown={(event) => keyboardEdit(event, item, 'start')}></button>
+ {/if}
+ <button
+ class="event-select"
+ aria-label={`${item.label}, ${formatTemporalValue(item.raw).label}`}
+ onpointerdown={(event) => {
+ // Ctrl is the measure gesture, so it must not also start a drag
+ if (event.ctrlKey || event.metaKey) return;
+ if (selected?.id === item.id && canDragTemporal(item) && !snapshotReading) beginMove(event, item);
+ }}
+ onclick={(event) => { event.stopPropagation(); selectItem(item, baseId, event); }}
+ oncontextmenu={(event) => openItemMenu(event, item, baseId)}
+ onpointerenter={(event) => showItemTooltip(event, item)}
+ onpointermove={(event) => showItemTooltip(event, item)}
+ onpointerleave={() => (tooltip = null)}
+ onfocus={(event) => showFocusedTooltip(event, item)}
+ onblur={() => (tooltip = null)}
+ >
+ {#if item.shape !== 'interval'}<span class="event-point"></span>{/if}
+ <span class="event-text">
+ <strong class="event-label">{item.label}</strong>
+ <small class="event-date">{formatTemporalValue(item.raw).label}</small>
+ </span>
+ </button>
+ {#if canDragTemporal(item) && !snapshotReading}
+ <button class="move-grip" aria-label="Move selected date" title="Move date" onpointerdown={(event) => beginMove(event, item)} onkeydown={(event) => keyboardEdit(event, item, 'move')}><Icon name="grip" size={10} /></button>
+ {/if}
+ {#if item.shape === 'interval' && canDragTemporal(item) && !snapshotReading}
+ <button class="resize end" aria-label="Resize end" title="Resize end" onpointerdown={(event) => beginMove(event, item, 'end')} onkeydown={(event) => keyboardEdit(event, item, 'end')}></button>
+ {/if}
+ </div>
+ {/each}
+ {#each track.layout.clusters as cluster (cluster.id)}
+ <button
+ class="timeline-cluster"
+ style:left={`${cluster.left}%`}
+ style:top={`${cluster.lane * 46 + 22}px`}
+ aria-label={`${cluster.count} more events near ${formatTemporalValue(cluster.earliest).label}`}
+ onclick={() => expandTrack(baseId)}
+ >+{cluster.count}</button>
+ {/each}
+ {#if canCreate}<span class="track-hint">Click or drag to add an assessment</span>{/if}
+ {#if !track.layout.items.length && !track.layout.clusters.length && !canCreate}<span class="track-empty">No entries in this window</span>{/if}
+ {:else}<span class="folded-note">Track folded</span>{/if}
+ </div>
+ </div>
+ {/each}
+ </section>
+ {:else}
+ <section class="timeline-list" aria-label="Timeline list">
+ {#each listGroups as group (group.key)}
+ <h2>{group.label}<span>{group.items.length}</span></h2>
+ {#each group.items as item (item.id)}
+ <button
+ class:chosen={selected?.id === item.id}
+ class:against={against?.id === item.id}
+ onclick={(event) => selectItem(item, null, event)}
+ oncontextmenu={(event) => openItemMenu(event, item)}
+ >
+ <span class={`category-dot ${item.category}`}></span>
+ <span class="list-copy"><strong>{item.label}</strong><small>{categoryName(item)}{#if item.time_role} · {item.time_role}{/if}{#if item.confidence} · {item.confidence}{/if}</small></span>
+ <span class="list-date"><strong>{formatTemporalValue(item.raw).label}</strong><code>{item.raw}</code></span>
+ <Icon name="arrowRight" size={12} />
+ </button>
+ {/each}
+ {/each}
+ </section>
+ {/if}
+
+ {#if unplaced.length || unplacedTotal}
+ <details class="holding-card" open>
+ <summary><span><Icon name="alert" size={14} />Not on UTC axis</span><strong>{unplacedTotal}</strong></summary>
+ <p class="holding-note">Add a timezone or correct the value to place these entries.</p>
+ <div class="holding-list">
+ {#each unplaced as item (item.id)}
+ <button onclick={() => selectItem(item)} oncontextmenu={(event) => openItemMenu(event, item)}>
+ <span class={`category-dot ${item.category}`}></span>
+ <span><strong>{item.label}</strong><small><span class="mono">{item.raw}</span> · {unplacedReason(item)}</small></span>
+ {#if item.category === 'statement'}<Icon name="edit" size={12} />{/if}
+ </button>
+ {/each}
+ {#if unplacedTotal > unplaced.length}<p>Load more to see the remaining entries.</p>{/if}
+ </div>
+ </details>
+ {/if}
+
+ {#if undated.length || undatedTotal}
+ <details class="holding-card undated-card" open>
+ <summary><span><Icon name="clock" size={14} />Undated</span><strong>{undatedTotal}</strong></summary>
+ <div class="holding-list">
+ {#each undated as item (item.id)}
+ <button onclick={() => selectItem(item)} oncontextmenu={(event) => openItemMenu(event, item)}>
+ <span class={`category-dot ${item.category}`}></span>
+ <span><strong>{item.label}</strong><small>{item.parse_error || categoryName(item)}</small></span>
+ {#if item.category === 'statement'}<Icon name="edit" size={12} />{/if}
+ </button>
+ {/each}
+ {#if undatedTotal > undated.length}<p>Load more to see the remaining undated entries.</p>{/if}
+ </div>
+ </details>
+ {/if}
+
+ {#if cursor}
+ <button class="btn btn-ghost load-more" disabled={loading} onclick={() => loadMain({ more: true })}>
+ {loading ? 'Loading…' : `Load more · ${items.length} of ${total}`}
+ </button>
+ {/if}
+ {/if}
+ {#if loading}<div class="loading-line"></div>{/if}
+ </main>
+
+ <aside class="inspector" class:empty={!selected}>
+ {#if selected}
+ <header><span class={`category-dot ${selected.category}`}></span><span>{categoryName(selected)}</span><button title="Close inspector" onclick={() => (selected = null)}><Icon name="x" size={13} /></button></header>
+ <div class="inspector-body">
+ <div class="item-kind">{selected.kind}{#if selected.time_role} · {selected.time_role}{/if}</div>
+ <h2>{selected.label}</h2>
+ {#if inspectorLoading}<div class="inspector-loading">Loading details…</div>{/if}
+ <div class="date-reading">
+ <Icon name="clock" size={15} />
+ <div>
+ <strong>{selectedReading.label}</strong>{#if selected.raw}<code>{selected.raw}</code>{/if}<small>{selected.precision || 'No global position'}{#if selected.zone} · {selected.zone}{/if}</small>
+ <!-- The same instant on the clock the axis is being read on. Only for a
+ value that names one: a date has no time of day, and printing 00:00
+ in another zone would invent an hour the source never gave. -->
+ {#if zone !== UTC && selected.earliest && ['second', 'subsecond'].includes(selected.precision)}
+ <small class="in-zone">{zonedStamp(selected.earliest, zone)} {zoneWord}</small>
+ {/if}
+ </div>
+ </div>
+
+ <!-- What the case knows about the time between two entries. The wording is
+ `lib/timeline.js`: a gap printed as one number when the dates only allow
+ a range is the invented precision this whole panel exists to avoid. -->
+ {#if pairReading}
+ <section class="pair" aria-label="Time between the two held entries">
+ <header>
+ <span>against {against.label}</span>
+ <button title="Let the second entry go" onclick={() => (against = null)}>
+ <Icon name="x" size={11} />
+ </button>
+ </header>
+ <strong>{pairReading.headline}</strong>
+ <small>{pairReading.detail}</small>
+ {#each pairReading.notes as note (note)}<small class="caveat">{note}</small>{/each}
+ </section>
+ {:else}
+ <p class="measure-hint">Ctrl-click a second entry to measure between them.</p>
+ {/if}
+ <div class="badges">
+ {#if selected.approximate}<span>Date: approximate</span>{/if}
+ {#if selected.uncertain}<span>Date: uncertain</span>{/if}
+ {#if selected.confidence}<span>Confidence: {selected.confidence}</span>{/if}
+ {#if selected.status === 'suggested'}<span>Status: suggested</span>{/if}
+ </div>
+ {#if selected.parse_error}<p class="warning">{selected.parse_error}</p>{/if}
+ {#if selected.raw && !selected.earliest && selected.zone === 'local'}<p class="warning">Add a timezone to place this time on the UTC axis.</p>{/if}
+ {#if canDragTemporal(selected) && !snapshotReading}<p class="axis-edit-help">{selected.shape === 'interval' ? 'Drag to move. Use either edge to resize.' : 'Drag the event to move it.'}</p>{/if}
+ <dl class="temporal-facts">
+ <div><dt>Precision</dt><dd>{selected.precision || 'Not set'}</dd></div>
+ <div><dt>Timezone</dt><dd>{selected.zone || 'Not set'}</dd></div>
+ <div><dt>Authority</dt><dd>{selected.authority || selected.category}</dd></div>
+ {#if selected.time_role}<div><dt>Time role</dt><dd>{selected.time_role}</dd></div>{/if}
+ {#if selected.status}<div><dt>Status</dt><dd>{selected.status}</dd></div>{/if}
+ {#if selected.confidence}<div><dt>Confidence</dt><dd>{selected.confidence}</dd></div>{/if}
+ </dl>
+
+ {#if inspectorChain?.entity?.attrs?.method}
+ <section class="inspector-note"><h3>Method</h3><p>{inspectorChain.entity.attrs.method}</p></section>
+ {/if}
+ {#if inspectorChain?.entity?.attrs?.verbatim}
+ <section class="inspector-note"><h3>Source wording</h3><blockquote>{inspectorChain.entity.attrs.verbatim}</blockquote></section>
+ {/if}
+
+ {#if inspectorConnections.about.length || inspectorConnections.at.length || inspectorConnections.cites.length}
+ <section class="inspector-connections">
+ {#if inspectorConnections.about.length}
+ <h3>About</h3>
+ {#each inspectorConnections.about as entry (entry.id)}<button disabled={snapshotReading} onclick={() => (detailsId = entry.id)}><span>{entry.label}</span><small>{entry.type}</small><Icon name="arrowRight" size={11} /></button>{/each}
+ {/if}
+ {#if inspectorConnections.at.length}
+ <h3>Place</h3>
+ {#each inspectorConnections.at as entry (entry.id)}<button disabled={snapshotReading} onclick={() => (detailsId = entry.id)}><span>{entry.label}</span><small>{entry.type}</small><Icon name="arrowRight" size={11} /></button>{/each}
+ {/if}
+ {#if inspectorConnections.cites.length}
+ <h3>Evidence</h3>
+ {#each inspectorConnections.cites as entry (entry.id)}<button disabled={snapshotReading} onclick={() => (detailsId = entry.id)}><span>{entry.label}</span><small>{entry.type}</small><Icon name="arrowRight" size={11} /></button>{/each}
+ {/if}
+ </section>
+ {/if}
+ <!-- Both acts are about a lane: pinning keeps an entry out of that lane's
+ density overflow, hiding takes it out of that lane. An entry with no
+ place on the axis is in neither, so it is offered neither — a control
+ that can only take a row out of the Undated queue is a trapdoor. -->
+ {#if selectedTrack && selected.earliest && !snapshotReading}
+ <section class="track-item-actions">
+ <h3>{selectedTrack.label}</h3>
+ <button onclick={() => togglePinned()}><Icon name="pushpin" size={12} />{selectedTrack.pinned.includes(selected.id) ? 'Unpin from track' : 'Pin in track'}</button>
+ <button onclick={() => hideFromTrack()}><Icon name="eyeOff" size={12} />Hide from track</button>
+ </section>
+ {/if}
+ </div>
+ <footer>
+ <button class="btn btn-ghost" disabled={snapshotReading} onclick={() => (detailsId = selected.owner_id)}>Details</button>
+ {#if selected.category === 'statement'}<button class="btn btn-primary" disabled={snapshotReading} onclick={() => openEditor(selected)}>Edit assessment</button>{/if}
+ {#if selected.category === 'media'}<button class="btn btn-primary" disabled={snapshotReading || !inspectorChain?.entity} onclick={addMediaCorrection}>Add correction</button>{/if}
+ </footer>
+ {:else}
+ <!-- The tool's own clock rather than a target: nothing is being aimed at here,
+ and the panel is empty until an entry is chosen. -->
+ <div class="inspector-empty"><Icon name="clock" size={16} /><span>Select an entry</span></div>
+ {/if}
+ </aside>
+ </div>
+
+ <!-- Inside the tool, not beside it: this screen goes to full screen, and nothing
+ outside the element being shown is drawn there. -->
+ {#if itemMenu}
+ {@const item = itemMenu.item}
+ {@const track = itemMenu.track}
+ <div class="item-menu" bind:this={itemMenuElement} style:left={`${itemMenu.x}px`} style:top={`${itemMenu.y}px`}>
+ <p class="meta">{item.label}</p>
+ <ul>
+ <!-- Both lane acts, on the same rule the inspector follows: an entry with no
+ place on the axis is in no lane, so neither is offered for it. -->
+ {#if track && item.earliest && !snapshotReading}
+ <li>
+ <button onclick={() => fromItemMenu(togglePinned)}>
+ <Icon name="pushpin" size={12} />{track.pinned.includes(item.id) ? 'Unpin from' : 'Pin in'} {track.label}
+ </button>
+ </li>
+ <li>
+ <button onclick={() => fromItemMenu(hideFromTrack)}>
+ <Icon name="eyeOff" size={12} />Hide from {track.label}
+ </button>
+ </li>
+ {/if}
+ <li>
+ <button disabled={snapshotReading} onclick={() => fromItemMenu((entry) => (detailsId = entry.owner_id))}>
+ <Icon name="inspect" size={12} />Details
+ </button>
+ </li>
+ {#if item.category === 'statement'}
+ <li>
+ <button disabled={snapshotReading} onclick={() => fromItemMenu((entry) => openEditor(entry))}>
+ <Icon name="edit" size={12} />Edit assessment
+ </button>
+ </li>
+ {/if}
+ </ul>
+ </div>
+ {/if}
+</div>
+
+{#if tooltip}
+ <div class="timeline-tooltip" style:left={`${tooltip.x}px`} style:top={`${tooltip.y}px`} role="tooltip">
+ <strong>{tooltip.title}</strong><span>{tooltip.date}</span>{#if tooltip.detail}<small>{tooltip.detail}</small>{/if}
+ </div>
+{/if}
+
+{#if editor}
+ <Modal title={editor.item ? 'Edit time assessment' : 'Add assessment'} onclose={() => (editor = null)} width="660px">
+ <TemporalClaimEditor
+ caseId={caseState.current.id}
+ item={editor.item}
+ subject={editor.subject}
+ initialWhen={editor.when}
+ initialStatement={editor.statement ?? ''}
+ initialRole={editor.role ?? ''}
+ onsaved={editorSaved}
+ oncancel={() => (editor = null)}
+ />
+ </Modal>
+{/if}
+
+{#if trackEditor}
+ <Modal title={trackEditor.mode === 'edit' ? 'Edit track' : 'Add track'} onclose={() => (trackEditor = null)} width="720px">
+ <TimelineTrackEditor
+ caseId={caseState.current.id}
+ caseFolders={caseState.current?.folders ?? []}
+ track={trackEditor.mode === 'edit' ? trackEditor.track : null}
+ onsave={saveTrack}
+ oncancel={() => (trackEditor = null)}
+ />
+ </Modal>
+{/if}
+
+{#if detailsId}
+ <Modal title="Details" onclose={() => (detailsId = null)} width="640px">
+ <EntityDetails entityId={detailsId} onclose={() => (detailsId = null)} ondeleted={() => (detailsId = null)} />
+ </Modal>
+{/if}
+
+{#if pendingEdit}
+ <ConfirmDialog
+ title={pendingEdit.item.shape === 'interval' ? 'Change this period?' : 'Move this date?'}
+ message={pendingEdit.item.label}
+ detail={`${pendingEdit.item.raw} → ${pendingEdit.raw}`}
+ confirmLabel="Update date"
+ icon="clock"
+ busy={directSaving}
+ onconfirm={confirmDirectEdit}
+ oncancel={() => (pendingEdit = null)}
+ />
+{/if}
+
+<style>
+ /* Plain surface, like every other tool. The glow that used to sit behind the head
+ was decoration this screen had no more claim to than the Board does. */
+ .timeline-tool {
+ height: 100%; min-height: 0; display: flex; flex-direction: column;
+ --track-statement: var(--timeline-statement); --track-media: var(--timeline-media); --track-activity: var(--timeline-activity);
+ background: var(--bg-0);
+ color: var(--text-1);
+ }
+ .timeline-head { display: grid; grid-template-columns: minmax(160px, 1fr) auto minmax(160px, 1fr); align-items: center; gap: 18px; padding: 12px 24px 10px; }
+ /* The house header: name, then one clause. `app.css .tool-header` spells the same
+ two rules, and this screen keeps its own only because the head is a three-column
+ grid with the range controls in the middle. */
+ .title-block { min-width: 0; display: flex; align-items: baseline; gap: 10px; }
+ .title-block h2 { font-size: var(--fs-lg); font-weight: 600; letter-spacing: -0.01em; }
+ .title-block .sub { overflow: hidden; color: var(--text-3); font-size: var(--fs-sm); text-overflow: ellipsis; white-space: nowrap; }
+ /* The middle column carries the window and nothing else. One segmented group: step
+ back, the window itself, step on. */
+ .range { position: relative; display: flex; align-items: center; justify-self: center; }
+ .range-step, .range-face {
+ height: 30px; border: 1px solid var(--border); background: var(--bg-2);
+ color: var(--text-2); cursor: pointer;
+ }
+ .range-step { width: 28px; display: grid; place-items: center; padding: 0; }
+ .range-step:first-child { border-radius: var(--r-sm) 0 0 var(--r-sm); }
+ .range-step:last-of-type { border-radius: 0 var(--r-sm) var(--r-sm) 0; }
+ .range-face { min-width: 190px; margin: 0 -1px; padding: 0 12px; color: var(--text-1); font-size: var(--fs-sm); }
+ .range-step:hover, .range-face:hover, .range-face[aria-expanded='true'] { border-color: var(--border-strong); color: var(--text-1); }
+ .range-step:disabled { opacity: .4; cursor: default; }
+ .range-menu {
+ position: absolute; z-index: 80; top: calc(100% + 6px); left: 50%; width: 244px;
+ display: grid; gap: 9px; padding: 11px; border: 1px solid var(--border-strong);
+ border-radius: var(--r-md); background: var(--bg-1); box-shadow: var(--shadow-2);
+ transform: translateX(-50%);
+ }
+ .range-menu label { display: grid; gap: 4px; color: var(--text-3); font-size: var(--fs-xs); }
+ .range-spans { display: flex; flex-wrap: wrap; gap: 4px; padding-top: 9px; border-top: 1px solid var(--border); }
+ .range-spans button {
+ flex: 1 1 30%; padding: 5px 0; border: 1px solid var(--border); border-radius: var(--r-sm);
+ background: var(--bg-2); color: var(--text-2); font-size: var(--fs-xs); cursor: pointer;
+ }
+ /* Ends the track row: the label in the row's own small grey, the three surfaces
+ welded into one segmented control so they read as one choice. */
+ .range-handoffs { margin-left: auto; flex: 0 0 auto; display: flex; align-items: center; }
+ .range-handoffs > span { margin-right: 8px; color: var(--text-3); font-size: 10px; }
+ .range-handoffs button {
+ height: 24px;
+ padding: 0 10px;
+ border: 1px solid var(--border);
+ background: var(--bg-2);
+ color: var(--text-2);
+ font-size: var(--fs-xs);
+ cursor: pointer;
+ }
+ .range-handoffs button + button { margin-left: -1px; }
+ .range-handoffs button:first-of-type { border-radius: var(--r-sm) 0 0 var(--r-sm); }
+ .range-handoffs button:last-of-type { border-radius: 0 var(--r-sm) var(--r-sm) 0; }
+ .range-handoffs button:hover { position: relative; border-color: var(--border-strong); color: var(--text-1); }
+ .range-handoffs button:disabled { opacity: .4; cursor: default; }
+ .range-spans button:hover { border-color: var(--border-strong); color: var(--text-1); }
+ .range-spans button:disabled { opacity: .4; cursor: default; }
+ .head-actions { justify-self: end; display: flex; gap: 5px; }
+ .add-event { justify-self: end; }
+ .timeline-tool:fullscreen { width: 100vw; height: 100vh; }
+ .filter-row { min-height: 42px; display: flex; align-items: center; gap: 8px; padding: 0 24px 10px; border-bottom: 1px solid color-mix(in srgb, var(--border) 75%, transparent); }
+ .category-dot { width: 7px; height: 7px; flex: 0 0 auto; border-radius: 50%; background: var(--text-3); }
+ /* `--track-tint` is the colour the analyst gave this track, set on its row. Unset
+ everywhere else, so the category keeps its own colour and the legend stays true. */
+ .category-dot.statement { background: var(--track-tint, var(--track-statement)); box-shadow: 0 0 0 3px color-mix(in srgb, var(--track-tint, var(--track-statement)) 15%, transparent); }
+ .category-dot.media { border-radius: 2px; background: var(--track-tint, var(--track-media)); box-shadow: 0 0 0 3px color-mix(in srgb, var(--track-tint, var(--track-media)) 15%, transparent); }
+ .category-dot.case_activity { background: var(--track-tint, var(--track-activity)); box-shadow: 0 0 0 3px color-mix(in srgb, var(--track-tint, var(--track-activity)) 15%, transparent); }
+ .scope-chip { display: inline-flex; align-items: center; gap: 5px; max-width: 220px; padding: 5px 8px; border: 1px solid color-mix(in srgb, var(--accent) 35%, var(--border)); border-radius: 999px; background: color-mix(in srgb, var(--accent) 8%, var(--bg-2)); color: var(--text-2); font-size: var(--fs-xs); cursor: pointer; }
+ .scope-chip span { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
+ .view-switch { display: flex; padding: 2px; border: 1px solid var(--border); border-radius: var(--r-sm); background: var(--bg-1); }
+ .view-switch button { padding: 3px 7px; border: 0; border-radius: 2px; background: none; color: var(--text-3); font-size: 10px; cursor: pointer; }
+ .view-switch button.active { background: var(--bg-3); color: var(--text-1); }
+ .legend { position: relative; }
+ .legend > summary { padding: 4px 6px; color: var(--text-3); font-size: 10px; cursor: pointer; list-style: none; }
+ .legend > summary::-webkit-details-marker { display: none; }
+ .legend-card { position: absolute; z-index: 45; top: calc(100% + 5px); left: 0; width: 210px; display: grid; gap: 7px; padding: 10px; border: 1px solid var(--border-strong); border-radius: var(--r-md); background: var(--bg-1); box-shadow: var(--shadow-2); }
+ .legend-card > strong { margin-top: 2px; color: var(--text-3); font-size: 9px; letter-spacing: .06em; text-transform: uppercase; }
+ .legend-card > span { display: flex; align-items: center; gap: 8px; color: var(--text-2); font-size: var(--fs-xs); }
+ .legend-card p { margin: 2px 0 0; color: var(--text-2); font-size: var(--fs-xs); line-height: 1.35; }
+ .legend-card small { margin-top: 2px; color: var(--text-3); line-height: 1.35; }
+ .sample { position: relative; width: 28px; height: 11px; display: inline-block; border: 1px solid var(--track-statement); border-radius: 3px; background: color-mix(in srgb, var(--track-statement) 12%, var(--bg-1)); }
+ .sample.approximate { border-style: dashed; }
+ .sample.uncertain { background-image: repeating-linear-gradient(135deg, transparent, transparent 3px, color-mix(in srgb, var(--text-2) 18%, transparent) 3px, color-mix(in srgb, var(--text-2) 18%, transparent) 5px); }
+ .sample.suggested::after { content: ''; position: absolute; top: 2px; right: 2px; width: 4px; height: 4px; border-radius: 50%; background: var(--track-statement); box-shadow: 0 0 0 1px var(--bg-1); }
+ .sample.refuted { position: relative; opacity: .8; }
+ .sample.refuted::after { content: ''; position: absolute; left: 2px; right: 2px; top: 4px; border-top: 1px solid var(--text-2); transform: rotate(-8deg); }
+ .utc-readout { margin-left: auto; color: var(--text-3); font: 10px var(--mono); letter-spacing: .03em; }
+ /* Wraps rather than scrolls: the Add-a-track menu hangs out of this row, and an
+ overflow container would clip it. */
+ .track-toolbar { min-height: 38px; display: flex; flex-wrap: wrap; align-items: center; gap: 6px 12px; padding: 6px 24px; border-bottom: 1px solid var(--border); background: color-mix(in srgb, var(--bg-1) 82%, transparent); }
+ .track-toolbar > label { display: inline-flex; align-items: center; gap: 6px; color: var(--text-3); font-size: 10px; }
+ .track-toolbar > label select { width: 118px; }
+ .track-toolbar > span { color: var(--text-3); font-size: 10px; }
+ .track-toolbar > em { color: var(--accent); font-size: 10px; font-style: normal; }
+ .track-add { position: relative; }
+ .track-menu { position: absolute; z-index: 70; top: calc(100% + 5px); left: 0; width: 250px; display: grid; padding: 7px; border: 1px solid var(--border-strong); border-radius: var(--r-md); background: var(--bg-1); box-shadow: var(--shadow-2); }
+ .track-menu > strong { padding: 5px 7px 7px; color: var(--text-3); font-size: 9px; letter-spacing: .07em; text-transform: uppercase; }
+ .track-menu > button { display: flex; justify-content: space-between; gap: 8px; padding: 7px; border: 0; border-radius: var(--r-sm); background: none; color: var(--text-2); text-align: left; cursor: pointer; }
+ .track-menu > button:hover { background: var(--bg-2); color: var(--text-1); }
+ .track-menu > button small { color: var(--text-3); font-size: 9px; }
+ .track-menu .custom { margin-top: 5px; border-top: 1px solid var(--border); border-radius: 0 0 var(--r-sm) var(--r-sm); }
+ .timeline-grid { min-height: 0; flex: 1; display: grid; grid-template-columns: minmax(0, 1fr) 330px; }
+ .chronology { position: relative; min-width: 0; overflow: auto; padding: 18px 24px 28px; }
+ /* A panel is a border and a fill. The 35px drop shadow under each one read as a
+ floating card, which is a look rather than a reading of the case. */
+ .axis-card, .overview-card, .holding-card, .timeline-list { border: 1px solid var(--border); border-radius: var(--r); background: var(--bg-1); overflow: hidden; }
+ /* One width for the gutter, and wide enough for a name the analyst chose: at 132px
+ "Events" arrived as "E." and a track nobody can read is a colour with a count. */
+ .axis-card, .overview-card { --gutter: 178px; }
+ .axis-row, .track-row { display: grid; grid-template-columns: var(--gutter) minmax(500px, 1fr); }
+ .axis-row { min-height: 66px; border-bottom: 1px solid var(--border); }
+ .axis-label, .track-label { padding: 12px 14px; border-right: 1px solid var(--border); }
+ .axis-label { display: grid; align-content: center; }
+ .axis-label span { color: var(--text-2); font: 600 var(--fs-xs) var(--mono); }
+ .axis-label small { color: var(--text-3); font-size: 9px; overflow-wrap: anywhere; }
+ .axis-ruler, .track-canvas { position: relative; min-width: 500px; }
+ .axis-ruler { cursor: grab; touch-action: none; background: linear-gradient(to bottom, transparent, color-mix(in srgb, var(--bg-2) 70%, transparent)); }
+ .axis-ruler.panning { cursor: grabbing; }
+ .axis-bands { position: absolute; inset: 0 0 auto; height: 24px; overflow: hidden; border-bottom: 1px solid var(--border); }
+ .axis-bands span { position: absolute; height: 24px; overflow: hidden; padding: 5px 7px; border-right: 1px solid var(--border); color: var(--text-2); font: 9px var(--mono); white-space: nowrap; }
+ .axis-minor { position: absolute; bottom: 0; height: 11px; border-left: 1px solid color-mix(in srgb, var(--border) 70%, transparent); }
+ /* The daylight ribbon: a strip at the foot of the ruler, on the ruler's own scale.
+ The strip is the night, and the two runs of spans are laid over it — dusk is not
+ a line, so twilight has to be a band of its own rather than an edge. */
+ .daylight { position: absolute; inset: auto 0 0; height: 5px; background: color-mix(in srgb, var(--text-1) 22%, transparent); }
+ .daylight span { position: absolute; inset: 0; }
+ .daylight .twilight { background: color-mix(in srgb, var(--text-1) 45%, transparent); }
+ .daylight .day { background: color-mix(in srgb, var(--warn) 70%, transparent); }
+ .daylight-note { margin: 0; padding: 5px 14px; border-top: 1px solid var(--border); color: var(--text-3); font-size: 9px; }
+ .axis-tick { position: absolute; top: 24px; bottom: 0; border-left: 1px solid var(--border-strong); }
+ .axis-tick span { position: absolute; top: 14px; left: 5px; color: var(--text-3); font: 10px var(--mono); white-space: nowrap; }
+ .axis-tick.end span { left: -5px; transform: translateX(-100%); }
+ .now-line, .track-now { position: absolute; z-index: 1; inset-block: 24px 0; border-left: 1px solid var(--danger); pointer-events: none; }
+ .now-line small { position: absolute; top: 2px; left: 4px; color: var(--danger); font: 8px var(--mono); text-transform: uppercase; }
+ .track-row { border-bottom: 1px solid color-mix(in srgb, var(--border) 78%, transparent); transition: min-height .16s ease; }
+ .track-row.folded { min-height: 42px; }
+ .track-row:last-child { border-bottom: 0; }
+ .track-label { display: grid; grid-template-columns: auto auto minmax(0, 1fr) auto; align-content: start; align-items: center; gap: 7px; padding: 14px 10px; }
+ .track-label.movable { grid-template-columns: auto auto auto minmax(0, 1fr) auto; }
+ .drag-track, .fold-track { display: grid; place-items: center; padding: 2px; border: 0; background: none; color: var(--text-3); cursor: pointer; }
+ .drag-track { cursor: grab; }
+ .drag-track:active { cursor: grabbing; }
+ .track-name { min-width: 0; display: grid; }
+ /* Two lines before the ellipsis: "Case activity" and "Vessel movements" are the
+ names people actually write, and one line of 60px cannot hold either. */
+ .track-name strong { display: -webkit-box; overflow: hidden; -webkit-box-orient: vertical; -webkit-line-clamp: 2; line-clamp: 2; }
+ .track-name em { overflow: hidden; color: var(--text-3); font-size: 8px; font-style: normal; text-overflow: ellipsis; white-space: nowrap; }
+ .track-label strong { font-size: var(--fs-xs); }
+ .track-label small { padding: 1px 5px; border-radius: 999px; background: var(--bg-3); color: var(--text-3); font-size: 9px; }
+ .track-actions { grid-column: 3 / -1; display: flex; gap: 2px; }
+ .track-label.movable .track-actions { grid-column: 4 / -1; }
+ .track-actions button { display: grid; place-items: center; padding: 3px; border: 0; background: none; color: var(--text-3); cursor: pointer; }
+ .track-actions button:hover { color: var(--text-1); }
+ .track-actions button:disabled { opacity: .35; cursor: default; }
+ .collapse-track, .restore-hidden { grid-column: 3 / -1; justify-self: start; margin-top: 1px; padding: 3px 7px; border: 1px solid var(--border); border-radius: 999px; background: var(--bg-2); color: var(--text-2); font-size: 9px; cursor: pointer; }
+ .track-label.movable .collapse-track, .track-label.movable .restore-hidden { grid-column: 4 / -1; }
+ .restore-hidden + .collapse-track { margin-left: 72px; }
+ .collapse-track:hover { border-color: var(--border-strong); color: var(--accent); }
+ .track-canvas { overflow: hidden; background: linear-gradient(90deg, transparent 49.9%, color-mix(in srgb, var(--accent) 3%, transparent) 50%, transparent 50.1%); cursor: default; }
+ .track-canvas.createable { cursor: crosshair; }
+ .gridline { position: absolute; inset-block: 0; border-left: 1px solid color-mix(in srgb, var(--border) 65%, transparent); pointer-events: none; }
+ .gridline.minor { border-left-color: color-mix(in srgb, var(--border) 35%, transparent); }
+ .track-now { inset-block: 0; opacity: .7; }
+ .track-hint, .track-empty { position: absolute; right: 12px; top: 6px; color: color-mix(in srgb, var(--text-3) 65%, transparent); font-size: 9px; pointer-events: none; }
+ .track-empty { left: 14px; right: auto; top: 26px; font-size: var(--fs-xs); }
+ .folded-note { position: absolute; top: 13px; left: 14px; color: var(--text-3); font-size: 9px; }
+ .draw-range { position: absolute; inset-block: 12px; z-index: 6; border: 1px solid color-mix(in srgb, var(--accent) 70%, transparent); border-radius: 4px; background: color-mix(in srgb, var(--accent) 14%, transparent); pointer-events: none; }
+ .timeline-event { --event-color: var(--track-tint, var(--track-statement)); position: absolute; z-index: 2; height: 36px; display: flex; align-items: stretch; border: 1px solid color-mix(in srgb, var(--event-color) 65%, var(--border)); border-radius: 7px; background: color-mix(in srgb, var(--event-color) 11%, var(--bg-1)); color: var(--text-1); transform: translateX(-8px); box-shadow: 0 3px 10px color-mix(in srgb, var(--bg-0) 55%, transparent); }
+ .timeline-event.media { --event-color: var(--track-tint, var(--track-media)); }
+ .timeline-event.case_activity { --event-color: var(--track-tint, var(--track-activity)); }
+ .timeline-event.period { min-width: 28px; transform: none; }
+ .timeline-event.end-aligned { transform: translateX(calc(-100% + 8px)); }
+ .timeline-event.chosen { z-index: 8; border-color: var(--accent); box-shadow: 0 0 0 3px color-mix(in srgb, var(--accent) 18%, transparent), 0 5px 16px color-mix(in srgb, var(--bg-0) 70%, transparent); }
+ /* The entry held against the selected one. Marked apart rather than as a second
+ selection: only one of the two is the one being read. */
+ .timeline-event.against { z-index: 8; border-color: var(--text-2); border-style: dashed; }
+ .timeline-event.pinned { box-shadow: inset 0 2px 0 var(--accent), 0 3px 10px color-mix(in srgb, var(--bg-0) 55%, transparent); }
+ .timeline-event.approximate { border-style: dashed; }
+ .timeline-event.uncertain { background-image: repeating-linear-gradient(135deg, transparent, transparent 4px, color-mix(in srgb, var(--text-2) 12%, transparent) 4px, color-mix(in srgb, var(--text-2) 12%, transparent) 7px); }
+ .timeline-event.suggested::after { content: ''; position: absolute; z-index: 5; top: 3px; right: 3px; width: 5px; height: 5px; border-radius: 50%; background: var(--event-color); box-shadow: 0 0 0 2px var(--bg-1); pointer-events: none; }
+ .timeline-event.refuted { opacity: .8; }
+ .timeline-event.refuted .event-label { text-decoration: line-through; text-decoration-thickness: 1px; }
+ .event-select { min-width: 0; flex: 1; display: flex; align-items: center; gap: 6px; padding: 3px 7px; overflow: hidden; border: 0; background: none; color: inherit; text-align: left; cursor: pointer; }
+ .event-point { width: 8px; height: 8px; flex: 0 0 auto; border: 2px solid var(--bg-1); border-radius: 50%; background: var(--event-color); box-shadow: 0 0 0 1px var(--event-color); }
+ .event-text { min-width: 0; display: grid; line-height: 1.12; }
+ .event-label, .event-date { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
+ .event-label { font-size: 10px; font-weight: 650; }
+ .event-date { margin-top: 2px; color: var(--text-3); font: 8px var(--mono); }
+ .precision-span { --event-color: var(--track-tint, var(--track-statement)); position: absolute; z-index: 1; height: 10px; min-width: 1px; border-inline: 1px solid color-mix(in srgb, var(--event-color) 55%, transparent); background: linear-gradient(to bottom, transparent 4px, color-mix(in srgb, var(--event-color) 42%, transparent) 4px, color-mix(in srgb, var(--event-color) 42%, transparent) 6px, transparent 6px); pointer-events: none; }
+ .precision-span.media { --event-color: var(--track-tint, var(--track-media)); }
+ .precision-span.case_activity { --event-color: var(--track-tint, var(--track-activity)); }
+ .precision-span.chosen { border-inline-color: var(--event-color); background: linear-gradient(to bottom, transparent 4px, color-mix(in srgb, var(--event-color) 72%, transparent) 4px, color-mix(in srgb, var(--event-color) 72%, transparent) 6px, transparent 6px); }
+ .move-grip { display: none; width: 18px; place-items: center; padding: 0; border: 0; border-left: 1px solid var(--border); background: color-mix(in srgb, var(--bg-1) 90%, transparent); color: var(--text-3); cursor: ew-resize; }
+ .timeline-event.chosen .move-grip { display: grid; }
+ .resize { display: none; position: absolute; z-index: 3; top: 4px; bottom: 4px; width: 7px; padding: 0; border: 0; border-radius: 3px; background: var(--accent); cursor: ew-resize; }
+ .timeline-event.chosen .resize { display: block; }
+ .resize.start { left: -4px; } .resize.end { right: -4px; }
+ .timeline-cluster { position: absolute; z-index: 7; min-width: 32px; height: 24px; padding: 0 7px; border: 1px solid var(--border-strong); border-radius: 999px; background: var(--bg-3); color: var(--text-2); font: 700 10px var(--mono); transform: translateX(-50%); cursor: pointer; }
+ .timeline-list { display: grid; padding-bottom: 5px; }
+ .timeline-list h2 { display: flex; justify-content: space-between; margin: 0; padding: 9px 12px; border-top: 1px solid var(--border); background: var(--bg-2); color: var(--text-2); font-size: var(--fs-xs); }
+ .timeline-list h2:first-child { border-top: 0; }
+ .timeline-list h2 span { color: var(--text-3); font-weight: 400; }
+ .timeline-list > button { display: grid; grid-template-columns: auto minmax(180px, 1fr) minmax(190px, auto) auto; align-items: center; gap: 10px; margin: 5px 7px 0; padding: 8px; border: 1px solid transparent; border-radius: var(--r-sm); background: none; color: var(--text-2); text-align: left; cursor: pointer; }
+ .timeline-list > button:hover { background: var(--bg-2); }
+ .timeline-list > button.chosen { border-color: var(--accent); background: var(--accent-soft); }
+ .timeline-list > button.against { border-color: var(--text-3); border-style: dashed; }
+ .list-copy, .list-date { min-width: 0; display: grid; }
+ .list-copy strong, .list-copy small, .list-date strong, .list-date code { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
+ .list-copy strong { color: var(--text-1); font-size: var(--fs-sm); }
+ .list-copy small { color: var(--text-3); font-size: 10px; text-transform: capitalize; }
+ .list-date { justify-items: end; }
+ .list-date strong { font-size: var(--fs-xs); font-weight: 500; }
+ .list-date code { color: var(--text-3); font-size: 9px; }
+ .overview-card { display: grid; grid-template-columns: var(--gutter) minmax(500px, 1fr); min-height: 92px; margin-bottom: 12px; }
+ .overview-title { display: grid; align-content: center; gap: 2px; padding: 10px 12px; border-right: 1px solid var(--border); }
+ .overview-title > span { font-size: var(--fs-xs); font-weight: 700; }
+ .overview-title small { color: var(--text-3); font-size: 9px; }
+ .overview-title .capped { color: var(--warn); }
+ .overview-counts { display: flex; flex-wrap: wrap; gap: 3px; margin-top: 3px; }
+ .overview-counts span { padding: 1px 4px; border-radius: 2px; background: var(--bg-3); color: var(--text-3); font-size: 8px; }
+ .density-bars { position: relative; min-width: 500px; height: 68px; margin: 12px 10px; overflow: hidden; border-radius: 3px; background: color-mix(in srgb, var(--bg-2) 40%, transparent); cursor: crosshair; }
+ /* One column per bin, as wide as the bin, stacked by category — a histogram, which
+ is only readable because the bins are cut as fine as they can be drawn. The floor
+ keeps a lone day visible and clickable at a scale where a day is under a pixel.
+
+ Above the brush, and only the column answers the pointer. Underneath it, a column
+ the window covered could not be clicked at all: the surface you drag the brush by
+ took the press, so clicking a bar in view did nothing and nudging it moved the
+ window instead. The empty height over a short column stays part of that surface. */
+ .density-bucket { position: absolute; z-index: 6; bottom: 17px; height: 46px; min-width: 2px; display: flex; align-items: end; border: 0; background: none; pointer-events: none; }
+ .density-stack { width: 100%; display: flex; flex-direction: column-reverse; overflow: hidden; border-radius: 1px 1px 0 0; opacity: .85; cursor: pointer; pointer-events: auto; }
+ .density-stack i { display: block; min-height: 1px; }
+ .density-stack i.statement { background: var(--track-statement); }
+ .density-stack i.media { background: var(--track-media); }
+ .density-stack i.case_activity { background: var(--track-activity); }
+ .density-bucket:hover .density-stack { opacity: 1; box-shadow: 0 0 0 1px var(--accent); }
+ .density-baseline { position: absolute; z-index: 3; right: 0; bottom: 16px; left: 0; border-top: 1px solid var(--border-strong); pointer-events: none; }
+ .overview-rule { position: absolute; z-index: 1; top: 0; bottom: 16px; border-left: 1px solid var(--border); pointer-events: none; }
+ /* Centred on the period it names, so the name sits under its own bar. The two
+ outermost lean inward instead, or a name wider than its slot would be clipped by
+ the edge of the minimap. */
+ .overview-tick { position: absolute; z-index: 7; bottom: 2px; color: var(--text-3); font: 8px var(--mono); text-align: center; white-space: nowrap; pointer-events: none; }
+ .overview-tick.start { text-align: left; }
+ .overview-tick.end { text-align: right; }
+ .overview-shade { position: absolute; z-index: 4; top: 0; bottom: 16px; background: color-mix(in srgb, var(--bg-1) 62%, transparent); pointer-events: none; }
+ .overview-window { position: absolute; z-index: 5; inset: 3px auto 16px; min-width: 8px; border: 1px solid color-mix(in srgb, var(--accent) 74%, transparent); border-radius: 3px; background: color-mix(in srgb, var(--accent) 5%, transparent); }
+ .overview-drag { position: absolute; inset: 0 5px; padding: 0; border: 0; background: none; cursor: grab; }
+ .overview-handle { position: absolute; z-index: 2; top: 5px; bottom: 5px; width: 5px; padding: 0; border: 0; border-radius: 2px; background: var(--accent); cursor: ew-resize; }
+ .overview-handle.start { left: -3px; } .overview-handle.end { right: -3px; }
+ .holding-card { margin-top: 12px; }
+ .holding-card summary { display: flex; justify-content: space-between; align-items: center; padding: 11px 14px; cursor: pointer; }
+ .holding-card summary span { display: inline-flex; align-items: center; gap: 7px; font-size: var(--fs-sm); font-weight: 700; }
+ .holding-card summary strong { min-width: 24px; padding: 2px 6px; border-radius: 999px; background: var(--bg-3); color: var(--text-3); font-size: var(--fs-xs); text-align: center; }
+ .holding-note { margin: -5px 14px 9px; color: var(--text-3); font-size: var(--fs-xs); }
+ .holding-list { display: grid; grid-template-columns: repeat(auto-fill, minmax(250px, 1fr)); gap: 6px; padding: 0 12px 12px; }
+ .holding-list button { display: grid; grid-template-columns: auto minmax(0,1fr) auto; align-items: center; gap: 8px; padding: 8px; border: 1px solid var(--border); border-radius: var(--r-sm); background: var(--bg-2); color: var(--text-2); text-align: left; cursor: pointer; }
+ .holding-list button > span:nth-child(2) { display: grid; min-width: 0; }
+ .holding-list strong, .holding-list small { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
+ .holding-list strong { font-size: var(--fs-xs); }
+ .holding-list small { color: var(--text-3); font-size: 9px; }
+ .holding-list p { margin: 0; padding: 8px; color: var(--text-3); font-size: var(--fs-xs); }
+ .load-more { display: flex; margin: 14px auto 0; }
+ .loading-line { position: sticky; bottom: 0; height: 2px; margin-top: -2px; background: linear-gradient(90deg, transparent, var(--accent), transparent); animation: pulse 1.2s ease-in-out infinite; }
+ @keyframes pulse { 50% { opacity: .35; } }
+ .blank-state { height: 100%; min-height: 340px; display: grid; place-content: center; justify-items: center; gap: 8px; color: var(--text-3); text-align: center; }
+ .blank-state h2 { margin: 0; color: var(--text-1); font-size: var(--fs-md); font-weight: 600; }
+ .blank-state p { max-width: 360px; margin: 0 0 6px; }
+ .inspector { min-height: 0; display: flex; flex-direction: column; border-left: 1px solid var(--border); background: color-mix(in srgb, var(--bg-1) 97%, transparent); }
+ .inspector > header { display: flex; align-items: center; gap: 7px; min-height: 45px; padding: 0 13px; border-bottom: 1px solid var(--border); color: var(--text-3); font-size: 10px; font-weight: 700; text-transform: uppercase; letter-spacing: .08em; }
+ .inspector > header button { display: grid; margin-left: auto; padding: 4px; border: 0; background: none; color: var(--text-3); cursor: pointer; }
+ .inspector-body { min-height: 0; overflow: auto; padding: 16px; }
+ .inspector-loading { margin: -7px 0 9px; color: var(--text-3); font-size: 9px; }
+ .item-kind { color: var(--accent); font-size: 9px; font-weight: 800; letter-spacing: .08em; text-transform: uppercase; }
+ .inspector h2 { margin: 4px 0 16px; font-size: 17px; line-height: 1.3; }
+ .date-reading { display: flex; gap: 9px; padding: 10px; border: 1px solid var(--border); border-radius: var(--r-sm); background: var(--bg-2); }
+ .date-reading :global(> svg) { color: var(--accent); }
+ .date-reading div { min-width: 0; display: grid; }
+ .date-reading strong, .date-reading code { overflow-wrap: anywhere; }
+ .date-reading strong { font-size: var(--fs-xs); }
+ .date-reading code { margin-top: 3px; color: var(--text-3); font-size: 9px; }
+ .date-reading small { margin-top: 3px; color: var(--text-3); font-size: 9px; }
+ .date-reading .in-zone { color: var(--text-2); }
+ /* The measurement between two entries. The figure reads first, what it rests on
+ under it, and every caveat the reading carries below that — a gap printed bare is
+ true and misleading in the same breath. */
+ .pair { display: grid; gap: 3px; margin-top: 10px; padding: 10px; border: 1px solid var(--border-strong); border-radius: var(--r-sm); background: var(--bg-2); }
+ .pair header { display: flex; align-items: center; gap: 6px; color: var(--text-3); font-size: 9px; }
+ .pair header span { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
+ .pair header button { display: grid; margin-left: auto; padding: 2px; border: 0; background: none; color: var(--text-3); cursor: pointer; }
+ .pair header button:hover { color: var(--text-1); }
+ .pair > strong { font-size: var(--fs-sm); font-variant-numeric: tabular-nums; }
+ .pair > small { color: var(--text-2); font-size: var(--fs-xs); }
+ .pair .caveat { color: var(--text-3); font-size: 9px; line-height: 1.4; }
+ .measure-hint { margin: 8px 0 0; color: var(--text-3); font-size: 9px; }
+ .badges { display: flex; flex-wrap: wrap; gap: 4px; margin-top: 10px; }
+ .badges span { padding: 3px 6px; border: 1px solid var(--border); border-radius: 999px; color: var(--text-3); font-size: 9px; text-transform: capitalize; }
+ .warning { padding: 8px; border-radius: var(--r-sm); background: var(--danger-soft); color: var(--danger); font-size: var(--fs-xs); }
+ .axis-edit-help { margin: 10px 0 0; color: var(--text-3); font-size: var(--fs-xs); }
+ dl { display: grid; gap: 8px; margin: 16px 0 0; }
+ dl div { display: flex; justify-content: space-between; gap: 8px; }
+ dt { color: var(--text-3); font-size: var(--fs-xs); } dd { margin: 0; font-size: var(--fs-xs); }
+ .temporal-facts { padding-bottom: 13px; border-bottom: 1px solid var(--border); }
+ .temporal-facts dd { color: var(--text-2); text-transform: capitalize; }
+ .inspector-note, .inspector-connections { display: grid; gap: 5px; margin-top: 14px; }
+ .inspector-note h3, .inspector-connections h3 { margin: 0; color: var(--text-3); font-size: 9px; text-transform: uppercase; letter-spacing: .07em; }
+ .inspector-note p, .inspector-note blockquote { margin: 0; color: var(--text-2); font-size: var(--fs-xs); line-height: 1.45; overflow-wrap: anywhere; }
+ .inspector-note blockquote { padding-left: 9px; border-left: 2px solid var(--border-strong); }
+ .inspector-connections h3:not(:first-child) { margin-top: 7px; }
+ .inspector-connections button { display: grid; grid-template-columns: minmax(0, 1fr) auto auto; align-items: center; gap: 6px; padding: 7px 8px; border: 1px solid var(--border); border-radius: var(--r-sm); background: var(--bg-2); color: var(--text-2); text-align: left; cursor: pointer; }
+ .inspector-connections button:hover { border-color: var(--border-strong); }
+ .inspector-connections button span { overflow: hidden; color: var(--text-1); font-size: var(--fs-xs); text-overflow: ellipsis; white-space: nowrap; }
+ .inspector-connections button small { color: var(--text-3); font-size: 9px; text-transform: capitalize; }
+ .track-item-actions { display: grid; grid-template-columns: 1fr 1fr; gap: 5px; margin-top: 14px; padding-top: 12px; border-top: 1px solid var(--border); }
+ .track-item-actions h3 { grid-column: 1 / -1; margin: 0 0 2px; color: var(--text-3); font-size: 9px; text-transform: uppercase; letter-spacing: .07em; }
+ .track-item-actions button { display: inline-flex; align-items: center; gap: 5px; padding: 6px 7px; border: 1px solid var(--border); border-radius: var(--r-sm); background: var(--bg-2); color: var(--text-2); font-size: 10px; cursor: pointer; }
+ .inspector footer { display: flex; justify-content: flex-end; gap: 5px; padding: 12px; border-top: 1px solid var(--border); }
+ .inspector-empty { flex: 1; display: grid; place-content: center; justify-items: center; gap: 7px; color: var(--text-3); font-size: var(--fs-xs); }
+ .timeline-tooltip { position: fixed; z-index: 100; width: 270px; display: grid; gap: 3px; padding: 9px 10px; border: 1px solid var(--border-strong); border-radius: var(--r-md); background: var(--bg-1); box-shadow: var(--shadow-2); color: var(--text-2); pointer-events: none; }
+ .timeline-tooltip strong { color: var(--text-1); font-size: var(--fs-xs); }
+ .timeline-tooltip span { font: 10px var(--mono); }
+ .timeline-tooltip small { color: var(--text-3); font-size: 9px; text-transform: capitalize; }
+ /* Over the pointer, above the tooltip it replaces: a hover reading and a menu about
+ the same entry cannot both be answered, so the menu is the one on top. */
+ .item-menu { position: fixed; z-index: 110; width: 196px; padding: 6px; border: 1px solid var(--border-strong); border-radius: var(--r-md); background: var(--bg-1); box-shadow: var(--shadow-2); }
+ .item-menu .meta { margin: 2px 6px 5px; overflow: hidden; color: var(--text-3); font-size: 10px; text-overflow: ellipsis; white-space: nowrap; }
+ .item-menu ul { list-style: none; margin: 0; padding: 0; }
+ .item-menu button { display: flex; width: 100%; align-items: center; gap: 7px; padding: 6px; border: 0; border-radius: var(--r-sm); background: none; color: var(--text-2); font-size: var(--fs-xs); text-align: left; cursor: pointer; }
+ .item-menu button:hover:not(:disabled) { background: var(--bg-3); color: var(--text-1); }
+ .item-menu button:disabled { color: var(--text-3); cursor: default; }
+ :global(.timeline-tool button:focus-visible), .axis-ruler:focus-visible, .track-canvas:focus-visible, .density-bars:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }
+ @media (max-width: 1160px) {
+ .timeline-head { grid-template-columns: 1fr auto; }
+ .range { grid-column: 1 / -1; grid-row: 2; }
+ .head-actions { grid-column: 2; grid-row: 1; }
+ .timeline-grid { grid-template-columns: minmax(0, 1fr) 250px; }
+ .utc-readout { display: none; }
+ }
+ @media (max-width: 760px) {
+ .timeline-head { padding-inline: 14px; }
+ .range { width: 100%; justify-self: stretch; }
+ .filter-row { padding-inline: 14px; overflow-x: auto; }
+ .track-toolbar { padding-inline: 14px; }
+ .chronology { padding: 12px 14px 22px; }
+ .timeline-grid { position: relative; grid-template-columns: minmax(0, 1fr); }
+ .inspector { position: absolute; z-index: 30; right: 0; bottom: 0; top: 0; width: min(310px, 88vw); box-shadow: -12px 0 32px color-mix(in srgb, var(--bg-0) 70%, transparent); }
+ .inspector.empty { display: none; }
+ .timeline-list > button { grid-template-columns: auto minmax(0, 1fr) auto; }
+ .list-date { grid-column: 2; justify-items: start; }
+ }
+</style>
diff --git a/frontend/src/tools/Timeline.test.js b/frontend/src/tools/Timeline.test.js
new file mode 100644
index 0000000..1a84b1e
--- /dev/null
+++ b/frontend/src/tools/Timeline.test.js
@@ -0,0 +1,306 @@
+import { describe, expect, it } from 'vitest';
+import { readFileSync } from 'node:fs';
+
+const source = readFileSync(new URL('./Timeline.svelte', import.meta.url), 'utf8');
+
+describe('Timeline workspace', () => {
+ it('loads a bounded visible window plus a separate overview', () => {
+ expect(source).toContain('const PAGE = 200');
+ expect(source).toContain("densityBucket = 'year'");
+ // The first reading is by year and answers the extent; how finely the case can
+ // then be cut is a question about the width it will be drawn at.
+ expect(source).toContain('densityUnit(page.extent, overviewWidth)');
+ expect(source).toContain("if (from) params.set('from', from)");
+ expect(source).toContain("if (to) params.set('to', to)");
+ expect(source).toContain('Load more · ${items.length} of ${total}');
+ });
+
+ it('samples a lane across the window instead of taking its first days', () => {
+ expect(source).toContain("spread: 'true'");
+ // The overview counts the whole case server-side and must stay a plain read,
+ // or the two readings of the same window disagree.
+ expect(source).not.toMatch(/bucket: densityBucket,\n\s*spread/);
+ expect(source).toContain('A sample across the window. Load more fills it in.');
+ });
+
+ it('measures the axis and packs the rendered event width', () => {
+ expect(source).toContain('new ResizeObserver');
+ expect(source).toContain('layoutTimelineItems(');
+ expect(source).toContain('from, to, plotWidth');
+ expect(source).toContain('{#each track.layout.clusters as cluster');
+ expect(source).toContain('onclick={() => expandTrack(baseId)}');
+ expect(source).toContain('>Collapse</button>');
+ expect(source.indexOf('aria-label="Timeline overview"')).toBeLessThan(
+ source.indexOf('aria-label="Timeline axis"')
+ );
+ });
+
+ it('keeps the current workspace in native full screen', () => {
+ expect(source).toContain('await toolElement.requestFullscreen()');
+ expect(source).toContain('await document.exitFullscreen()');
+ expect(source).toContain("fullscreen ? 'Exit full screen' : 'Full screen'");
+ });
+
+ it('only creates assessments from the statement track', () => {
+ expect(source).toContain("!track?.categories.includes('statement')");
+ expect(source).toContain("event.target.closest('button')");
+ expect(source).toContain('class:createable={canCreate}');
+ expect(source).toContain('Click or drag to add an assessment');
+ expect(source).toContain('Add assessment');
+ });
+
+ it('shows uncertainty through patterns and a visible legend', () => {
+ expect(source).toContain('class:approximate={item.approximate}');
+ expect(source).toContain('class:uncertain={item.uncertain}');
+ expect(source).toContain("class:suggested={item.status === 'suggested'}");
+ expect(source).toContain('text-decoration: line-through');
+ expect(source).toContain('<summary>Legend</summary>');
+ expect(source).toContain('Confidence and date quality are independent.');
+ expect(source).toContain('Date: approximate');
+ expect(source).toContain('closeOnOutsidePointer(legendElement, () => (legendOpen = false))');
+ expect(source).toContain('bind:open={legendOpen}');
+ });
+
+ it('supports adaptive ticks, exact range controls and direct navigation', () => {
+ expect(source).toContain('type="datetime-local"');
+ expect(source).toContain('axisMinorTicks');
+ expect(source).toContain('axisBands');
+ expect(source).toContain('nowPosition');
+ expect(source).toContain('onpointerdown={panStart}');
+ expect(source).toContain('onwheel={navigateWheel}');
+ expect(source).toContain('Wheel zoom · Shift-wheel pan');
+ expect(source).toContain('if (!event.shiftKey && !horizontal)');
+ });
+
+ it('reads the window rather than spelling it out in seven controls', () => {
+ // one face, two steps, and the boundaries under it
+ expect(source).toContain('{windowWords(from, to, zone)}');
+ expect(source).toContain('aria-expanded={rangeMenu}');
+ expect(source).toContain('closeOnOutsidePointer(rangeElement, () => (rangeMenu = false))');
+ expect(source).toContain('{#each WINDOW_SPANS as span (span.label)}');
+ expect(source).toContain('onclick={() => setSpan(span.ms)}');
+ expect(source).toContain('resizeWindow(from, to, span)');
+ // the zoom pair and the loose All button are gone from the toolbar
+ expect(source).not.toContain('class="zoom-controls"');
+ expect(source).not.toContain('title="Zoom in"');
+ expect(source).not.toContain('class="all-btn"');
+ });
+
+ it('makes a track readable in its gutter: the name, its hover, its colour', () => {
+ expect(source).toContain('--gutter: 178px');
+ expect(source).toContain('<strong>{track.label}</strong>');
+ expect(source).toContain('title={trackTitle(track)}');
+ expect(source).toContain('-webkit-line-clamp: 2');
+ expect(source).not.toContain('track.short');
+ // a colour the analyst chose wins for that track, and only there
+ expect(source).toContain('style:--track-tint={trackTint(track.color)}');
+ expect(source).toContain('--event-color: var(--track-tint, var(--track-media))');
+ expect(source).toContain('background: var(--track-tint, var(--track-statement))');
+ });
+
+ it('makes the overview a category minimap with a movable window', () => {
+ expect(source).toContain('bucket.categories?.[category.id]');
+ expect(source).toContain('class="overview-drag"');
+ expect(source).toContain('class="overview-handle start"');
+ expect(source).toContain('overviewRecenter');
+ expect(source).toContain('unplacedTotal} local');
+ expect(source).toContain('exact counts on hover');
+ expect(source).toContain('class="overview-tick {slot.anchor}"');
+ // The ink answers the pointer and the box around it does not, so a bar the brush
+ // covers can still be clicked instead of the press landing on the brush.
+ expect(source).toContain('.density-bucket { position: absolute; z-index: 6;');
+ expect(source).toContain('pointer-events: none;');
+ expect(source).toContain('.density-stack { width: 100%;');
+ expect(source).toContain('pointer-events: auto;');
+ // What the window leaves out is dimmed rather than merely un-brushed.
+ expect(source).toContain('class="overview-shade"');
+ });
+
+ it('offers readable events, a list view and a stable inspector column', () => {
+ expect(source).toContain("viewMode === 'list'");
+ expect(source).toContain('formatTemporalValue(item.raw).label');
+ expect(source).toContain('class="timeline-tooltip"');
+ expect(source).toContain("item.zone === 'date-only'");
+ expect(source).toContain('class={`precision-span ${item.category}`}');
+ expect(source).toContain('grid-template-columns: minmax(0, 1fr) 330px');
+ // the tool's own clock, not a target: nothing is being aimed at in an empty panel
+ expect(source).toContain('<Icon name="clock" size={16} /><span>Select an entry</span>');
+ expect(source).toContain('inspectorConnections.cites');
+ expect(source).toContain('Add correction');
+ expect(source).toContain("openEditor(null, selected?.raw ?? '', {");
+ });
+
+ it('keeps date edits confirmable by pointer and keyboard', () => {
+ expect(source).toContain('moveTemporalRaw(edit.item, delta)');
+ expect(source).toContain('resizeTemporalRaw(edit.item, edit.mode');
+ expect(source).toContain('nudgeTemporalRaw(item, mode');
+ expect(source).toContain('aria-label="Resize start"');
+ expect(source).toContain("['ArrowLeft', 'ArrowRight'");
+ expect(source).toContain("title={pendingEdit.item.shape === 'interval' ? 'Change this period?' : 'Move this date?'}");
+ });
+
+ it('separates local times from missing dates', () => {
+ expect(source).toContain('!item.earliest && item.raw');
+ expect(source).toContain('Not on UTC axis');
+ expect(source).toContain('Timezone needed');
+ expect(source).toContain('<Icon name="clock" size={14} />Undated');
+ });
+
+ it('builds case-owned tracks and saved Timeline readings', () => {
+ expect(source).toContain('surface="timeline"');
+ expect(source).toContain('capture={captureAnalysisView}');
+ expect(source).toContain('groupedTimelineTracks(trackSpecs, baseTrackItems, groupBy, entityLabel)');
+ expect(source).toContain('trackPresets(entityTypes())');
+ expect(source).toContain('class="drag-track"');
+ expect(source).toContain('draggable="true"');
+ expect(source).toContain('Show hidden');
+ expect(source).toContain('Pin in track');
+ expect(source).toContain('Frozen view');
+ });
+});
+
+describe('which clock the axis is read on', () => {
+ it('keeps UTC as the default and stores nothing else', () => {
+ // presentation only: the case is stored in UTC, the queries ask in UTC, and the
+ // switch moves where the ticks fall and what they are called
+ expect(source).toContain("let zoneChoice = $state('utc')");
+ expect(source).toContain('axisTicks(from, to, plotWidth, zone)');
+ expect(source).toContain('axisBands(from, to, plotWidth, zone)');
+ expect(source).toContain('windowInputValue(from, zone)');
+ expect(source).toContain('inputWindowValue(value, zone)');
+ });
+
+ it('hands the choice to one searchable picker', () => {
+ // UTC, this computer, any zone in the world and the case's own saved points are
+ // one decision, so they are one list rather than a switch plus a menu
+ expect(source).toContain('<ZonePicker');
+ expect(source).toContain('bind:choice={zoneChoice}');
+ expect(source).toContain('resolved={zone}');
+ expect(source).toContain('at={axisWindow?.start ?? 0}');
+ expect(source).toContain("buildCatalogQuery(caseId, { types: ['place'], limit: 50 })");
+ });
+
+ it('reads a zone named outright, which carries no daylight', () => {
+ // the investigation is at the other end of the world and the case has no saved
+ // point there yet; a band of day and night needs coordinates, a label does not
+ expect(source).toContain("if (zoneChoice.startsWith('zone:')) {");
+ expect(source).toContain('return knownZone(named) ? named : UTC;');
+ });
+
+ it('waits for a point-s own zone rather than guessing one', () => {
+ // the zone arrives with the daylight, so until it lands the axis stays on UTC
+ expect(source).toContain('const named = daylight?.zone?.name;');
+ expect(source).toContain('return named && knownZone(named) ? named : UTC;');
+ expect(source).toContain("if (zoneChoice.startsWith('place:') && places.length && !sunPlace) zoneChoice = 'utc'");
+ });
+
+ it('keeps a snapshot on the clock captured with it', () => {
+ expect(source).toContain("snapshotReading ? timelineViews.activeView?.spec?.timeline?.timezone ?? null : null");
+ expect(source).toContain('if (frozenZone && knownZone(frozenZone)) return frozenZone;');
+ expect(source).toContain('if (!caseId || snapshotReading) {\n places = [];');
+ expect(source).toContain('disabled={snapshotReading}');
+ });
+
+ it('draws day and twilight at that point, and says what it is of', () => {
+ expect(source).toContain('/api/geo/daylight?');
+ expect(source).toContain("ribbonBands(daylight?.day ?? [], from, to)");
+ expect(source).toContain("ribbonBands(daylight?.civil ?? [], from, to)");
+ expect(source).toContain('Daylight at {sunPlace.label}');
+ // and a window too wide to draw says so instead of drawing a moiré
+ expect(source).toContain('Zoom in past a month to draw it.');
+ expect(source).toContain('Dark for the whole window.');
+ });
+});
+
+describe('the queues for what has no place on the axis', () => {
+ it('reads them from the page, never through a track-s hidden list', () => {
+ // hiding tidies a lane, and an entry with no position was never in one: applied to
+ // these, hiding only emptied the queue that exists to say they need a date
+ expect(source).toContain('const pageItems = $derived.by(() => {');
+ expect(source).toContain('for (const item of page?.items ?? []) unique.set(item.id, item);');
+ expect(source).toContain("const unplaced = $derived(pageItems.filter((item) => !item.earliest && item.raw));");
+ expect(source).toContain("const undated = $derived(pageItems.filter((item) => !item.earliest && !item.raw));");
+ // the lanes themselves still answer to hiding
+ expect(source).toContain('const dated = $derived(visibleItems.filter((item) => item.earliest));');
+ });
+
+ it('lets tracks own categories without a second global switch', () => {
+ expect(source).toContain('trackSpecs.flatMap((track) => track.categories)');
+ expect(source).not.toContain('category-filters');
+ expect(source).not.toContain('Timeline categories');
+ });
+
+ it('offers neither pinning nor hiding for an entry with no lane', () => {
+ expect(source).toContain('{#if selectedTrack && selected.earliest && !snapshotReading}');
+ expect(source).toContain('{#if track && item.earliest && !snapshotReading}');
+ });
+});
+
+describe('what an entry can be asked on a right-click', () => {
+ it('names the four acts where the pointer is, on the axis and in the list', () => {
+ expect(source).toContain('oncontextmenu={(event) => openItemMenu(event, item, baseId)}');
+ expect(source).toContain('oncontextmenu={(event) => openItemMenu(event, item)}');
+ expect(source).toContain('class="item-menu"');
+ expect(source).toContain("{track.pinned.includes(item.id) ? 'Unpin from' : 'Pin in'} {track.label}");
+ expect(source).toContain('Hide from {track.label}');
+ expect(source).toContain('fromItemMenu((entry) => (detailsId = entry.owner_id))');
+ expect(source).toContain('fromItemMenu((entry) => openEditor(entry))');
+ });
+
+ it('leaves the selection alone, so a pair being measured survives it', () => {
+ // the inspector reaches the same acts and costs a selection to get there
+ expect(source).toContain('itemMenu = {\n item,\n track: trackHolding(item, trackId),');
+ expect(source).not.toContain('openItemMenu(event, item); selectItem(');
+ });
+
+ it('is one press, one act on macOS, where ctrl-click already measures', () => {
+ expect(source).toContain('if (event.ctrlKey && event.button === 0) return;');
+ });
+
+ it('reads the entry before closing, and closes on the axis moving under it', () => {
+ expect(source).toContain('const held = itemMenu;\n itemMenu = null;');
+ expect(source).toContain('closeOnOutsidePointer(itemMenuElement, () => (itemMenu = null))');
+ expect(source).toContain("if (event.key === 'Escape' && itemMenu) itemMenu = null;");
+ // panning, zooming and the wheel all move the spot the menu was opened on
+ expect(source).toContain('itemMenu = null;\n ({ from, to } = shiftWindow(from, to, fraction));');
+ expect(source).toContain('itemMenu = null;\n ({ from, to } = zoomWindow(from, to, factor, anchor));');
+ });
+
+ it('acts on the lane the entry was clicked in, from either surface', () => {
+ expect(source).toContain('function trackHolding(item, trackId = null)');
+ expect(source).toContain('function togglePinned(item = selected, track = selectedTrack)');
+ expect(source).toContain('function hideFromTrack(item = selected, track = selectedTrack)');
+ // hiding an entry cannot leave the panel or the measurement pointing at it
+ expect(source).toContain('if (against?.id === item.id) against = null;');
+ });
+
+ it('draws over the tooltip it replaces, inside the full-screen element', () => {
+ expect(source).toContain('.item-menu { position: fixed; z-index: 110;');
+ expect(source.indexOf('{#if itemMenu}')).toBeLessThan(source.indexOf('{#if tooltip}'));
+ });
+});
+
+describe('measuring between two entries', () => {
+ it('holds a second entry on Ctrl-click, without starting a drag', () => {
+ expect(source).toContain('if ((event?.ctrlKey || event?.metaKey) && selected && selected.id !== item.id)');
+ expect(source).toContain('against = against?.id === item.id ? null : item;');
+ expect(source).toContain('if (event.ctrlKey || event.metaKey) return;');
+ expect(source).toContain('selectItem(item, baseId, event)');
+ });
+
+ it('reads the figure out in the inspector, with what it rests on', () => {
+ expect(source).toContain('describePair(selected, against)');
+ expect(source).toContain('{pairReading.headline}');
+ expect(source).toContain('{pairReading.detail}');
+ expect(source).toContain('{#each pairReading.notes as note (note)}');
+ });
+
+ it('teaches the gesture, since nothing else announces it', () => {
+ expect(source).toContain('Ctrl-click a second entry to measure between them.');
+ expect(source).toContain('class:against={against?.id === item.id}');
+ });
+
+ it('drops the pair when a different entry is selected outright', () => {
+ expect(source).toContain('selected = item;\n against = null;');
+ });
+});
diff --git a/frontend/src/tools/proof/NewProofDialog.svelte b/frontend/src/tools/proof/NewProofDialog.svelte
index 2f2c3ae..237fec0 100644
--- a/frontend/src/tools/proof/NewProofDialog.svelte
+++ b/frontend/src/tools/proof/NewProofDialog.svelte
@@ -1,5 +1,6 @@
<script>
import Icon from '../../components/Icon.svelte';
+ import { fileUrl } from '../../lib/fileUrl.js';
import Modal from '../../components/Modal.svelte';
import FolderBrowser from '../../components/FolderBrowser.svelte';
import PanelCategories from './PanelCategories.svelte';
@@ -112,7 +113,7 @@
>
<span class="pick-image">
{#if item.thumb}
- <img src={`/files/${caseId}/${item.thumb}`} alt="" loading="lazy" decoding="async" />
+ <img src={fileUrl(caseId, item.thumb)} alt="" loading="lazy" decoding="async" />
{:else}
<!-- no cached thumbnail yet: a placeholder, never the
full-size original in a 150px cell -->
diff --git a/frontend/src/tools/proof/ProofLayersPanel.svelte b/frontend/src/tools/proof/ProofLayersPanel.svelte
index 4804754..ebadb04 100644
--- a/frontend/src/tools/proof/ProofLayersPanel.svelte
+++ b/frontend/src/tools/proof/ProofLayersPanel.svelte
@@ -1,5 +1,6 @@
<script>
import Icon from '../../components/Icon.svelte';
+ import { fileUrl } from '../../lib/fileUrl.js';
let {
proof,
@@ -108,7 +109,7 @@
title="Select this panel on the canvas"
onclick={() => (selectedPanelId = selectedPanelId === panel.id ? null : panel.id)}
>
- <img src={`/files/${caseId}/${panel.src}`} alt="" />
+ <img src={fileUrl(caseId, panel.src)} alt="" />
{#if proof.layout === 'free'}
<span class="row-badge" title="Z1 is the foreground">Z{index + 1}</span>
{:else}
diff --git a/frontend/src/tools/satellite/SavedOverlay.svelte b/frontend/src/tools/satellite/SavedOverlay.svelte
index 90dd553..09c580c 100644
--- a/frontend/src/tools/satellite/SavedOverlay.svelte
+++ b/frontend/src/tools/satellite/SavedOverlay.svelte
@@ -159,12 +159,39 @@
rebuild(rows, precision);
});
+ /**
+ * How tightly a mark is pinned, as a shape under its pin (ONTOLOGY §2).
+ *
+ * A pin dropped on a guess is the lie this fixes: "somewhere on the north quay"
+ * draws as the circle it is. A footprint wins over a radius when both are set,
+ * because a traced shape says more than the circle around it.
+ *
+ * A mark with neither returns nothing and draws exactly as it always has —
+ * absence is a state, never something to flag.
+ */
+ function shapesFor(mark) {
+ const row = mark.items.find((r) => r.footprint || r.radius_m > 0);
+ if (!row) return [];
+ const style = {
+ color: '#f5a623',
+ weight: 1.5,
+ opacity: 0.9,
+ fillColor: '#f5a623',
+ fillOpacity: 0.12,
+ // never steals the click from the pin it sits under
+ interactive: false,
+ };
+ return row.footprint
+ ? [L.geoJSON(row.footprint, { style: () => style })]
+ : [L.circle([mark.lat, mark.lon], { ...style, radius: row.radius_m })];
+ }
+
function rebuild(rows, precision) {
const marks = groupSavedMarkers(rows, precision);
const next = new Map();
group?.remove();
group = L.layerGroup(
- marks.map((mark) => {
+ marks.flatMap((mark) => {
const marker = L.marker([mark.lat, mark.lon], {
icon: icon(mark),
title: mark.items.length > 1 ? `${mark.items.length} saved here` : mark.items[0].title,
@@ -185,7 +212,8 @@
maxWidth: 330,
autoPanPadding: [24, 24],
});
- return marker;
+ // the shape first, so the pin stays on top of its own uncertainty
+ return [...shapesFor(mark), marker];
})
).addTo(map);
elements = next;
diff --git a/frontend/src/tools/satellite/SavedOverlay.test.js b/frontend/src/tools/satellite/SavedOverlay.test.js
new file mode 100644
index 0000000..33ca6c9
--- /dev/null
+++ b/frontend/src/tools/satellite/SavedOverlay.test.js
@@ -0,0 +1,28 @@
+import { describe, expect, it } from 'vitest';
+import { readFileSync } from 'node:fs';
+
+const source = readFileSync(new URL('./SavedOverlay.svelte', import.meta.url), 'utf8');
+
+describe('how precisely a point is pinned', () => {
+ it('draws a radius as a circle in metres, not a fixed pixel dot', () => {
+ // L.circleMarker is sized in pixels and would lie at every other zoom
+ expect(source).toContain("L.circle([mark.lat, mark.lon], { ...style, radius: row.radius_m })");
+ });
+
+ it('prefers a traced footprint over the circle around it', () => {
+ expect(source).toContain('row.footprint\n ? [L.geoJSON(row.footprint');
+ });
+
+ it('leaves a point with no precision drawing exactly as before', () => {
+ // absence is a state, never something to flag
+ expect(source).toContain('if (!row) return [];');
+ expect(source).toContain('mark.items.find((r) => r.footprint || r.radius_m > 0)');
+ });
+
+ it('keeps the shape under the pin and out of the click path', () => {
+ expect(source).toContain('interactive: false');
+ expect(source).toContain('return [...shapesFor(mark), marker];');
+ // one group still holds everything, so a rebuild clears shapes with their pins
+ expect(source).toContain('marks.flatMap((mark) => {');
+ });
+});
diff --git a/frontend/src/tools/satellite/SavedPopup.svelte b/frontend/src/tools/satellite/SavedPopup.svelte
index 8954ec9..717cd6f 100644
--- a/frontend/src/tools/satellite/SavedPopup.svelte
+++ b/frontend/src/tools/satellite/SavedPopup.svelte
@@ -9,10 +9,12 @@
* the ground rather than of your clicks.
*/
import Icon from '../../components/Icon.svelte';
+ import { fileUrl } from '../../lib/fileUrl.js';
import RelationList from '../../components/RelationList.svelte';
import { api } from '../../lib/api.js';
import { toast } from '../../lib/state.svelte.js';
import { postTarget } from '../../lib/post.js';
+ import { loadRelationTypes, relationAction } from '../../lib/relations.svelte.js';
import { stackOrder } from '../../lib/savedMarkers.js';
let {
@@ -52,10 +54,21 @@
const worked = (row) =>
row.proofs > 0 ? `${row.proofs} proof${row.proofs > 1 ? 's' : ''} here` : null;
+ /** How tightly this point is pinned, read-only: the shape is already drawn on the
+ * map behind this card, and editing it belongs to the details drawer. Two forms
+ * for one field is how they drift apart. */
+ function spread(row) {
+ if (row.footprint) return 'traced area';
+ const m = Number(row.radius_m);
+ if (!(m > 0)) return null;
+ return m >= 1000 ? `±${(m / 1000).toFixed(m >= 10000 ? 0 : 1)} km` : `±${Math.round(m)} m`;
+ }
+
const ordered = $derived(stackOrder(items));
const here = $derived(ordered[0]);
const day = (stamp) => (stamp ? String(stamp).slice(0, 10) : null);
+ loadRelationTypes();
// Relations: the saved index carries the count, never the edges — it is loaded
@@ -86,7 +99,11 @@
if (!caseId || !row.id) return;
try {
const chain = await api.get(`/api/cases/${caseId}/entities/${row.id}/chain`);
- relationsByRow = { ...relationsByRow, [rowKey(row)]: chain?.relations ?? [] };
+ await loadRelationTypes();
+ const ordinary = (chain?.relations ?? []).filter(
+ (relation) => relationAction(relation.link.type) === 'relation'
+ );
+ relationsByRow = { ...relationsByRow, [rowKey(row)]: ordinary };
} catch (e) {
// A read that failed is not an answer: caching it as an empty list would
// have the card claim this point holds no relations. Fold the row back so
@@ -133,7 +150,7 @@
onclick={() => onopen(row)}
>
{#if row.thumbnail && caseId}
- <img src={`/files/${caseId}/${row.thumbnail}`} alt="" loading="lazy" decoding="async" />
+ <img src={fileUrl(caseId, row.thumbnail)} alt="" loading="lazy" decoding="async" />
{:else}
<Icon name={GLYPH[row.kind] ?? 'pin'} size={20} />
{/if}
@@ -146,6 +163,9 @@
<span class="kind"><Icon name={GLYPH[row.kind] ?? 'pin'} size={10} /> {KIND[row.kind]}</span>
{#if row.provider ?? row.site}<span>{row.provider ?? row.site}</span>{/if}
{#if row.zoom != null}<span>z{Math.round(row.zoom)}</span>{/if}
+ {#if spread(row)}
+ <span title="How tightly this point is pinned">{spread(row)}</span>
+ {/if}
{#if row.status === 'suggested'}
<span class="proposed" title="Proposed from a file's own metadata">suggested</span>
{/if}
@@ -175,6 +195,7 @@
{caseId}
relations={relationsByRow[rowKey(row)] ?? []}
subjectType={row.kind === 'place' ? 'place' : 'capture'}
+ actionFilter="relation"
max={3}
onwalk={(entity) => onentity?.(entity)}
onchanged={() => relationSettled(row)}
@@ -237,7 +258,7 @@
<a
class="link"
class:off={fullscreen}
- href={fullscreen ? undefined : `/files/${caseId}/${row.path}`}
+ href={fullscreen ? undefined : fileUrl(caseId, row.path)}
target="_blank"
rel="noreferrer"
aria-disabled={fullscreen}
diff --git a/frontend/src/tools/satellite/SavedPopup.test.js b/frontend/src/tools/satellite/SavedPopup.test.js
index a9166fa..55a8641 100644
--- a/frontend/src/tools/satellite/SavedPopup.test.js
+++ b/frontend/src/tools/satellite/SavedPopup.test.js
@@ -206,7 +206,8 @@ describe('SavedPopup relations', () => {
it('loads the edges from the bounded chain endpoint, not from the index', () => {
const source = readFileSync(new URL('./SavedPopup.svelte', import.meta.url), 'utf8');
expect(source).toContain('api.get(`/api/cases/${caseId}/entities/${row.id}/chain`)');
- expect(source).toContain('relationsByRow = { ...relationsByRow, [rowKey(row)]: chain?.relations ?? [] }');
+ expect(source).toContain("relationAction(relation.link.type) === 'relation'");
+ expect(source).toContain('relationsByRow = { ...relationsByRow, [rowKey(row)]: ordinary }');
// a single mark opens them straight away: clicking a place to see which
// photos claim it is the whole point of the gesture
expect(source).toContain('const only = ordered.length === 1 ? ordered[0] : null;');
@@ -246,3 +247,23 @@ describe('SavedPopup relations', () => {
expect(overlay).toContain('openEntity(entity);');
});
});
+
+describe('how precisely a point is pinned', () => {
+ const popup = readFileSync(new URL('./SavedPopup.svelte', import.meta.url), 'utf8');
+
+ it('reads the spread out in the meta line, in the unit that suits it', () => {
+ expect(popup).toContain("`±${(m / 1000).toFixed(m >= 10000 ? 0 : 1)} km`");
+ expect(popup).toContain("`±${Math.round(m)} m`");
+ expect(popup).toContain("if (row.footprint) return 'traced area';");
+ });
+
+ it('says nothing when nothing was stated', () => {
+ expect(popup).toContain('if (!(m > 0)) return null;');
+ expect(popup).toContain('{#if spread(row)}');
+ });
+
+ it('is read-only here, because the drawer owns the field', () => {
+ const card = popup.slice(popup.indexOf('{#if spread(row)}'));
+ expect(card.slice(0, 200)).not.toMatch(/<input|<button/);
+ });
+});
diff --git a/frontend/src/tools/satellite/SavedRow.svelte b/frontend/src/tools/satellite/SavedRow.svelte
index 1894136..e527cab 100644
--- a/frontend/src/tools/satellite/SavedRow.svelte
+++ b/frontend/src/tools/satellite/SavedRow.svelte
@@ -8,6 +8,7 @@
* a long list scans as titles and coordinates rather than as rows of buttons.
*/
import Icon from '../../components/Icon.svelte';
+ import { fileUrl } from '../../lib/fileUrl.js';
let {
row,
@@ -24,6 +25,9 @@
onedit,
ondelete,
onproof,
+ // Absent where a surface has no way to reload after the change; the accept
+ // action then stays off the row rather than being offered and doing nothing.
+ onaccept = null,
onhover = () => {},
} = $props();
@@ -45,6 +49,7 @@
.join(' · ')
);
const blocked = $derived(fullscreen ? 'Exit fullscreen first. This leaves the map' : null);
+ const proposed = $derived(row.status === 'suggested');
</script>
<div
@@ -73,7 +78,7 @@
>
<span class="thumb">
{#if row.thumbnail && caseId}
- <img src={`/files/${caseId}/${row.thumbnail}`} alt="" loading="lazy" decoding="async" />
+ <img src={fileUrl(caseId, row.thumbnail)} alt="" loading="lazy" decoding="async" />
{:else}
<Icon name={GLYPH[row.kind] ?? 'pin'} size={dense ? 16 : 14} />
{/if}
@@ -89,9 +94,10 @@
say so rather than printing 0°, 0° -->
{#if flyable}<span class="mono">{coords(row)}</span>{:else}<span>No coordinates</span>{/if}
{#if meta}<span class="bits">{meta}</span>{/if}
- <!-- a point enrichment proposed from a file's metadata, not analyst work -->
- {#if row.status === 'suggested'}
- <span class="proposed" title="Proposed from a file's own metadata">suggested</span>
+ <!-- a point a tool proposed: a file's own metadata, or a capture filed
+ while the analyst was not accepting them on the spot -->
+ {#if proposed}
+ <span class="proposed" title="Proposed by a tool, waiting for you">suggested</span>
{/if}
</span>
{#if row.notes}<span class="note">{row.notes}</span>{/if}
@@ -99,6 +105,15 @@
</button>
<div class="actions">
+ <!-- Accepting is offered where the point is read, not only in the sidebar:
+ the analyst is looking at the map that decides whether the point is
+ right, and sending them to another panel to say so is the trip this
+ saves. -->
+ {#if proposed && onaccept}
+ <button class="act accept" title="Accept this point" onclick={() => onaccept(row)}>
+ <Icon name="check" size={13} />
+ </button>
+ {/if}
{#if isProof}
<!-- a proof is edited and deleted in the composer that owns it; here it
is a point on the map, and the one thing to do with it is open it -->
@@ -311,6 +326,9 @@
.act.danger:hover {
color: var(--danger);
}
+ .act.accept {
+ color: var(--accent);
+ }
.act.disabled,
.act:disabled {
opacity: 0.35;
diff --git a/frontend/src/tools/satellite/SavedSearch.svelte b/frontend/src/tools/satellite/SavedSearch.svelte
index d46ab7d..a9203d0 100644
--- a/frontend/src/tools/satellite/SavedSearch.svelte
+++ b/frontend/src/tools/satellite/SavedSearch.svelte
@@ -29,6 +29,7 @@
onedit,
ondelete,
onproof,
+ onaccept = null,
} = $props();
// A case can hold thousands of saved items; a modal that renders all of them
@@ -80,6 +81,7 @@
{onedit}
{ondelete}
{onproof}
+ {onaccept}
/>
{/snippet}
diff --git a/frontend/src/tools/satellite/SavedTree.svelte b/frontend/src/tools/satellite/SavedTree.svelte
index cd62bda..4fc6db8 100644
--- a/frontend/src/tools/satellite/SavedTree.svelte
+++ b/frontend/src/tools/satellite/SavedTree.svelte
@@ -40,6 +40,7 @@
onedit,
ondelete,
onproof,
+ onaccept = null,
onbrowse,
onlocate,
oncancelLocate,
@@ -173,6 +174,7 @@
{onedit}
{ondelete}
{onproof}
+ {onaccept}
/>
{/each}
</div>
diff --git a/frontend/src/tools/satellite/SavedTree.test.js b/frontend/src/tools/satellite/SavedTree.test.js
index 8190d5a..cc67a32 100644
--- a/frontend/src/tools/satellite/SavedTree.test.js
+++ b/frontend/src/tools/satellite/SavedTree.test.js
@@ -270,3 +270,36 @@ describe('SavedTree folder view', () => {
expect(source).not.toContain('assignFolder');
});
});
+
+describe('accepting a proposed point', () => {
+ const proposed = [
+ {
+ id: 'p9',
+ kind: 'place',
+ title: 'roof match',
+ lat: 48.8584,
+ lon: 2.2945,
+ status: 'suggested',
+ geo: { state: 'ok', country: 'France', country_code: 'fr' },
+ continent: 'Europe',
+ fetched_at: '2026-07-20T09:12:04Z',
+ },
+ ];
+
+ it('offers it on the row, where the map that decides is already open', () => {
+ const body = at({ rows: proposed, query: 'roof', onaccept: noop });
+ expect(body).toContain('Accept this point');
+ expect(body).toContain('suggested');
+ });
+
+ it('stays off a point nobody proposed', () => {
+ const settled = [{ ...proposed[0], status: 'confirmed' }];
+ expect(at({ rows: settled, query: 'roof', onaccept: noop })).not.toContain(
+ 'Accept this point'
+ );
+ });
+
+ it('stays off where a surface cannot reload after the change', () => {
+ expect(at({ rows: proposed, query: 'roof' })).not.toContain('Accept this point');
+ });
+});
diff --git a/frontend/src/tools/satellite/TemporalMapOverlay.svelte b/frontend/src/tools/satellite/TemporalMapOverlay.svelte
new file mode 100644
index 0000000..939d53b
--- /dev/null
+++ b/frontend/src/tools/satellite/TemporalMapOverlay.svelte
@@ -0,0 +1,174 @@
+<script>
+ /**
+ * Session-only marks for whatever the Timeline window puts on the ground.
+ *
+ * Drawn as the saved index's own pins are — the same teardrop, count badge and
+ * card — because they are the same gesture on the same map, and a second visual
+ * language would only ask the analyst to learn the map twice. The tint is the one
+ * difference, and it earns its place: both layers can be on at once, and this one
+ * is transient.
+ */
+ import { mount, unmount } from 'svelte';
+ import L from 'leaflet';
+ import { paths } from '../../components/Icon.svelte';
+ import { groupTemporalMapItems } from '../../lib/temporalMap.js';
+ import TemporalPopup from './TemporalPopup.svelte';
+
+ let { map = null, items = [], caseId = '', onopen = () => {} } = $props();
+ let group = null;
+ let mounted = null;
+
+ function glyph(name, size) {
+ return (
+ `<svg viewBox="0 0 24 24" width="${size}" height="${size}" fill="none" stroke="currentColor"` +
+ ` stroke-width="2" stroke-linecap="round" stroke-linejoin="round">` +
+ `<path d="${paths[name] ?? paths.alert}"/></svg>`
+ );
+ }
+
+ function icon(mark) {
+ const count = mark.items.length > 1 ? `<i class="temporal-mark-count">${mark.items.length}</i>` : '';
+ return L.divIcon({
+ className: 'temporal-mark-wrap',
+ html: `<span class="temporal-mark">${glyph('clock', 13)}${count}</span>`,
+ iconSize: [24, 24],
+ iconAnchor: [12, 12],
+ });
+ }
+
+ function popup(mark) {
+ const host = document.createElement('div');
+ if (mounted) unmount(mounted);
+ mounted = mount(TemporalPopup, {
+ target: host,
+ props: {
+ place: mark,
+ items: mark.items,
+ caseId,
+ onopen: (item) => {
+ map.closePopup();
+ onopen(item);
+ },
+ // Following a row leaves the map, so the card closes first — the same gesture
+ // as the saved layer's, rather than a popup that vanishes without saying it
+ // would.
+ onleave: () => map.closePopup(),
+ },
+ });
+ return host;
+ }
+
+ function shape(mark) {
+ const style = {
+ color: '#35b6a0',
+ weight: 1.5,
+ opacity: 0.9,
+ fillColor: '#35b6a0',
+ fillOpacity: 0.12,
+ interactive: false,
+ };
+ if (mark.footprint) return L.geoJSON(mark.footprint, { style: () => style });
+ if (Number(mark.radius_m) > 0) {
+ return L.circle([mark.lat, mark.lon], { ...style, radius: Number(mark.radius_m) });
+ }
+ return null;
+ }
+
+ $effect(() => {
+ const marks = groupTemporalMapItems(items);
+ if (!map) return;
+ group?.remove();
+ group = L.layerGroup(marks.flatMap((mark) => {
+ const marker = L.marker([mark.lat, mark.lon], {
+ icon: icon(mark),
+ keyboard: true,
+ title: mark.items.length === 1
+ ? mark.items[0].label
+ : `${mark.items.length} statements at ${mark.label}`,
+ });
+ marker.bindPopup(() => popup(mark), {
+ className: 'temporal-popup',
+ minWidth: 272,
+ maxWidth: 320,
+ autoPanPadding: [24, 24],
+ });
+ // The shape first, so the pin stays on top of its own uncertainty.
+ const area = shape(mark);
+ return area ? [area, marker] : [marker];
+ })).addTo(map);
+ });
+
+ $effect(() => () => {
+ group?.remove();
+ group = null;
+ if (mounted) {
+ unmount(mounted);
+ mounted = null;
+ }
+ });
+</script>
+
+<style>
+ /* Leaflet builds these elements itself, outside this component's markup, so the
+ marker styles have to be global. The saved layer's geometry throughout — the
+ teardrop, the badge on its corner, the lift on hover — in this layer's tint. */
+ :global(.temporal-mark-wrap) { border: 0; background: none; }
+ :global(.temporal-mark) {
+ position: relative;
+ display: grid;
+ width: 24px;
+ height: 24px;
+ place-items: center;
+ border-radius: 50% 50% 50% 2px;
+ transform: rotate(-45deg);
+ background: rgba(20, 20, 20, .82);
+ box-shadow: 0 0 0 1.5px #35b6a0, 0 2px 5px rgba(0, 0, 0, .45);
+ color: #35b6a0;
+ transition: transform .12s var(--ease);
+ }
+ :global(.temporal-mark > svg) { transform: rotate(45deg); }
+ :global(.temporal-mark-count) {
+ position: absolute;
+ top: -5px;
+ right: -5px;
+ min-width: 15px;
+ padding: 0 3px;
+ border-radius: 8px;
+ transform: rotate(45deg);
+ background: #141414;
+ color: #fff;
+ font-size: 9px;
+ font-style: normal;
+ font-weight: 700;
+ line-height: 15px;
+ text-align: center;
+ }
+ :global(.temporal-mark-wrap:hover .temporal-mark) {
+ z-index: 500;
+ transform: rotate(-45deg) scale(1.25);
+ }
+ /* Leaflet's default popup is a white speech bubble; over imagery it has to be one
+ of the app's own surfaces instead. */
+ :global(.temporal-popup .leaflet-popup-content-wrapper) {
+ padding: 2px;
+ border: 1px solid var(--border-strong);
+ border-radius: var(--r-lg);
+ background: var(--bg-1);
+ box-shadow: var(--shadow-2);
+ color: var(--text-1);
+ }
+ :global(.temporal-popup .leaflet-popup-content) { margin: 10px 12px; line-height: 1.4; }
+ :global(.temporal-popup .leaflet-popup-tip) {
+ border: 1px solid var(--border-strong);
+ background: var(--bg-1);
+ box-shadow: none;
+ }
+ :global(.temporal-popup .leaflet-popup-close-button) {
+ padding: 6px 7px 0 0 !important;
+ color: var(--text-3) !important;
+ }
+ :global(.temporal-popup .leaflet-popup-close-button:hover) {
+ background: none !important;
+ color: var(--text-1) !important;
+ }
+</style>
diff --git a/frontend/src/tools/satellite/TemporalPopup.svelte b/frontend/src/tools/satellite/TemporalPopup.svelte
new file mode 100644
index 0000000..7241291
--- /dev/null
+++ b/frontend/src/tools/satellite/TemporalPopup.svelte
@@ -0,0 +1,215 @@
+<script>
+ /**
+ * What one point holds inside the Timeline window, when you click it.
+ *
+ * The same card as the saved index's, read for a different question: not "what do
+ * I already have here?" but "what does this window put here?". So a row leads with
+ * what it is — a photograph shows itself — and then says when.
+ *
+ * Two ways out of every row, because a mark on the map is not the end of the
+ * gesture: the entry on the axis it came from, and the thing itself in the tool
+ * that owns it.
+ */
+ import Icon from '../../components/Icon.svelte';
+ import { entityIcon, mediaKindOf } from '../../lib/entityIcon.js';
+ import { fileUrl } from '../../lib/fileUrl.js';
+ import { ENTITY_TOOL, openEntity, opensInFileManager } from '../../lib/navigate.js';
+ import { TIMELINE_CATEGORIES, formatTemporalValue, zonedStamp } from '../../lib/timeline.js';
+
+ let { place = null, items = [], caseId = '', onopen, onleave } = $props();
+
+ const CATEGORY = Object.fromEntries(
+ TIMELINE_CATEGORIES.map((category) => [category.id, category.short])
+ );
+ const TOOL = {
+ media: 'Media', proof: 'Proof', place: 'Map', post: 'Post',
+ 'inspect-session': 'Inspect', note: 'Notebook', bookmark: 'the source',
+ capture: 'Map',
+ };
+
+ const ordered = $derived(
+ [...items].sort((left, right) => String(left.earliest).localeCompare(String(right.earliest)))
+ );
+
+ const owner = (item) => item.owner ?? { id: item.owner_id, type: item.owner_type, attrs: {} };
+ const preview = (item) => {
+ const held = owner(item);
+ return held.thumb && caseId && mediaKindOf(held) !== 'file' ? fileUrl(caseId, held.thumb) : '';
+ };
+
+ /**
+ * The file itself, for a tab of its own.
+ *
+ * Only what the browser can actually show: handed a PDF or a spreadsheet a new tab
+ * downloads it, which quietly makes a second copy the case knows nothing about.
+ * Those open in the folder instead, which is what following the row already does.
+ */
+ function rawFile(item) {
+ const held = owner(item);
+ const path = held.attrs?.path;
+ return held.type === 'media' && path && caseId && mediaKindOf(held) !== 'file'
+ ? fileUrl(caseId, path)
+ : '';
+ }
+
+ /**
+ * When, short enough to sit beside the title.
+ *
+ * The full reading names the timezone and every recorded decimal, which is right in
+ * the inspector and four wrapped lines wide in a card this size.
+ */
+ function when(item) {
+ if (!item.raw) return '';
+ if (!item.raw.includes('T')) return formatTemporalValue(item.raw).label;
+ const stamp = zonedStamp(item.earliest);
+ return stamp ? `${stamp.slice(8, 10)} ${stamp.slice(5, 7)} · ${stamp.slice(11, 16)}` : '';
+ }
+
+ /** Where this row's own thing is read, when the app has somewhere to read it. */
+ function opensIn(item) {
+ const held = owner(item);
+ if (opensInFileManager(held)) return 'the folder';
+ if (held.type === 'bookmark' && !held.attrs?.url) return '';
+ return TOOL[held.type] ?? (held.id ? 'Board' : '');
+ }
+
+ function follow(item) {
+ const held = owner(item);
+ if (!held?.id) return;
+ onleave?.();
+ openEntity(held);
+ }
+</script>
+
+<div class="pop">
+ <header>
+ <span class="where">{place?.label || 'Place'}</span>
+ {#if ordered.length > 1}<span class="tally">{ordered.length} here</span>{/if}
+ </header>
+
+ <div class="stack" class:scrolls={ordered.length > 2}>
+ {#each ordered as item (item.id)}
+ {@const held = owner(item)}
+ {@const shot = preview(item)}
+ {@const tool = opensIn(item)}
+ {@const raw = rawFile(item)}
+ <div class="entry">
+ <button
+ type="button"
+ class="preview"
+ title={tool ? `Open in ${tool}` : 'Open on the Timeline'}
+ onclick={() => (tool ? follow(item) : onopen(item))}
+ >
+ {#if shot}
+ <img src={shot} alt="" loading="lazy" decoding="async" />
+ {#if mediaKindOf(held) === 'video'}<span class="play"><Icon name="play" size={13} /></span>{/if}
+ {:else}
+ <Icon name={entityIcon(held) ?? 'clock'} size={18} />
+ {/if}
+ </button>
+ <div class="body">
+ <button type="button" class="title" onclick={() => onopen(item)}>
+ {item.label || 'Untitled'}
+ </button>
+ <p class="meta">
+ {#if when(item)}<span class="mono">{when(item)}</span>{/if}
+ <span class="kind">{CATEGORY[item.category] ?? item.category}</span>
+ {#if item.uncertain}<span title="Recorded as uncertain">uncertain</span>{/if}
+ {#if item.approximate}<span title="Recorded as approximate">approximate</span>{/if}
+ </p>
+ <p class="acts">
+ <button type="button" class="link" onclick={() => onopen(item)}>On the Timeline</button>
+ {#if tool}
+ <button type="button" class="link" onclick={() => follow(item)}>Open in {tool}</button>
+ {/if}
+ {#if raw}
+ <a
+ class="link out"
+ href={raw}
+ target="_blank"
+ rel="noopener noreferrer"
+ title="Open the file in a new tab"
+ ><Icon name="external" size={10} /></a>
+ {/if}
+ </p>
+ </div>
+ </div>
+ {/each}
+ </div>
+</div>
+
+<style>
+ .pop { width: 292px; font-family: var(--font-sans); }
+ header {
+ display: flex;
+ align-items: baseline;
+ justify-content: space-between;
+ gap: 8px;
+ padding-bottom: 6px;
+ border-bottom: 1px solid var(--border);
+ }
+ .where { color: var(--text-1); font-size: var(--fs-sm); font-weight: 600; }
+ .tally { color: var(--accent); font-size: var(--fs-xs); white-space: nowrap; }
+ .stack { display: flex; flex-direction: column; }
+ /* two entries fit; past that the card scrolls rather than growing off-map */
+ .stack.scrolls { max-height: 244px; overflow-y: auto; }
+ .entry { display: flex; gap: 9px; padding: 8px 0; }
+ .entry + .entry { border-top: 1px solid var(--border); }
+ .preview {
+ position: relative;
+ flex: 0 0 auto;
+ display: grid;
+ width: 66px;
+ height: 48px;
+ place-items: center;
+ overflow: hidden;
+ border: 0;
+ border-radius: var(--r-sm);
+ background: var(--bg-3);
+ color: var(--text-3);
+ cursor: pointer;
+ }
+ .preview img { position: absolute; inset: 0; width: 100%; height: 100%; object-fit: cover; }
+ .preview:hover { box-shadow: 0 0 0 1px var(--accent); }
+ .play {
+ position: absolute;
+ display: grid;
+ width: 22px;
+ height: 22px;
+ place-items: center;
+ border-radius: 50%;
+ background: rgba(0, 0, 0, .58);
+ color: #fff;
+ }
+ .body { min-width: 0; display: flex; flex-direction: column; gap: 3px; }
+ .title {
+ overflow: hidden;
+ padding: 0;
+ border: 0;
+ background: none;
+ color: var(--text-1);
+ font: inherit;
+ font-size: var(--fs-xs);
+ text-align: left;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ cursor: pointer;
+ }
+ .title:hover { color: var(--accent); }
+ .meta { display: flex; flex-wrap: wrap; gap: 6px; color: var(--text-3); font-size: 9px; }
+ .meta .mono { font-family: var(--mono); }
+ .kind { text-transform: capitalize; }
+ .acts { display: flex; flex-wrap: wrap; gap: 8px; }
+ .link {
+ padding: 0;
+ border: 0;
+ background: none;
+ color: var(--accent);
+ font: inherit;
+ font-size: 9px;
+ cursor: pointer;
+ }
+ .link:hover { text-decoration: underline; }
+ .out { display: inline-grid; place-items: center; text-decoration: none; }
+ .out:hover { color: var(--text-1); }
+</style>
diff --git a/frontend/vite.config.js b/frontend/vite.config.js
index 6a272f2..7676999 100644
--- a/frontend/vite.config.js
+++ b/frontend/vite.config.js
@@ -4,6 +4,17 @@ import { svelte } from '@sveltejs/vite-plugin-svelte';
// Builds straight into the Python package so `pip install .` ships the UI.
export default defineConfig({
plugins: [svelte()],
+ // Vitest's dependency optimiser writes beside the file whose imports it is
+ // resolving, so a suite run left two `node_modules` trees inside `src/`. They
+ // are ignored by git and never shipped, but they shadow module resolution in
+ // an editor and answer every grep over the source with a dozen false hits.
+ cacheDir: 'node_modules/.vite',
+ // Under vitest, resolve Svelte's browser build so a `*.render.test.js` can mount a
+ // component and drive it. Without this, `mount()` gets the server build and every
+ // interaction test fails on import — which is why the suite could only ever read
+ // source strings, and why "these inputs accept nothing" went unnoticed. Gated on
+ // VITEST so the production build keeps resolving exactly as it did.
+ resolve: process.env.VITEST ? { conditions: ['browser'] } : {},
test: {
include: ['src/**/*.test.js'],
},
diff --git a/scripts/relaunch.py b/scripts/relaunch.py
index 4d1f74a..d641cef 100755
--- a/scripts/relaunch.py
+++ b/scripts/relaunch.py
@@ -4,6 +4,10 @@
The tool supervises the process it starts and exposes a token-protected local
control socket. A later invocation can therefore stop that exact process
without scanning process names or killing unrelated Vite/Azimut instances.
+
+When that handshake finds nothing (a server started by hand, or one whose
+launcher was killed hard), the port itself is reclaimed: whoever still listens
+on it is stopped so the relaunch never hits "address already in use".
"""
from __future__ import annotations
@@ -125,6 +129,121 @@ def _stop_previous(path: Path, timeout: float = 10) -> bool:
return True
+def _probe_reuses_address(platform: str = os.name) -> bool:
+ """Whether the probe binds the way the server will.
+
+ On POSIX the server sets SO_REUSEADDR, so the probe must too: connections
+ left in TIME-WAIT block a plain bind long after the server is gone, and the
+ port would look busy forever. On Windows the same option lets a bind steal a
+ live listener, which would report a busy port as free.
+ """
+ return platform != "nt"
+
+
+def _port_is_free(port: int) -> bool:
+ with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as probe:
+ if _probe_reuses_address():
+ probe.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
+ try:
+ probe.bind(("127.0.0.1", port))
+ except OSError:
+ return False
+ return True
+
+
+def _command_output(command: list[str]) -> str:
+ if not shutil.which(command[0]):
+ return ""
+ try:
+ result = subprocess.run(
+ command, capture_output=True, text=True, timeout=10, check=False
+ )
+ except (OSError, subprocess.SubprocessError):
+ return ""
+ return result.stdout
+
+
+def _listener_pids(port: int, platform: str = os.name) -> set[int]:
+ """Processes listening on the port, best effort and never fatal."""
+ pids: set[int] = set()
+ if platform == "nt":
+ for line in _command_output(["netstat", "-a", "-n", "-o", "-p", "TCP"]).splitlines():
+ fields = line.split()
+ if len(fields) < 5 or fields[3].upper() != "LISTENING":
+ continue
+ if fields[1].rsplit(":", 1)[-1] != str(port):
+ continue
+ if fields[4].isdigit():
+ pids.add(int(fields[4]))
+ return pids
+
+ output = _command_output(
+ ["lsof", "-t", "-n", "-P", f"-iTCP:{port}", "-sTCP:LISTEN"]
+ )
+ for token in output.split():
+ if token.isdigit():
+ pids.add(int(token))
+ if pids:
+ return pids
+
+ # lsof is missing on plenty of Linux installs; ss ships with iproute2.
+ for line in _command_output(["ss", "-H", "-l", "-t", "-n", "-p", "-a"]).splitlines():
+ fields = line.split()
+ if len(fields) < 4 or fields[3].rsplit(":", 1)[-1] != str(port):
+ continue
+ for chunk in line.split("pid=")[1:]:
+ digits = chunk.split(",")[0].split(")")[0]
+ if digits.isdigit():
+ pids.add(int(digits))
+ return pids
+
+
+def _kill_pid(pid: int, *, force: bool) -> None:
+ if os.name == "nt":
+ command = ["taskkill", "/PID", str(pid), "/T"]
+ if force:
+ command.append("/F")
+ subprocess.run(
+ command, check=False, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL
+ )
+ return
+ try:
+ os.kill(pid, signal.SIGKILL if force else signal.SIGTERM)
+ except OSError:
+ pass
+
+
+def _free_port(port: int, timeout: float = 10) -> list[int]:
+ """Stop whatever still listens on the port. Returns the PIDs stopped."""
+ if _port_is_free(port):
+ return []
+
+ stopped: list[int] = []
+ deadline = time.monotonic() + timeout
+ forced = False
+ while True:
+ for pid in sorted(_listener_pids(port)):
+ if pid == os.getpid():
+ continue
+ _kill_pid(pid, force=forced)
+ if pid not in stopped:
+ stopped.append(pid)
+ for _ in range(20):
+ if _port_is_free(port):
+ return stopped
+ time.sleep(0.05)
+ if time.monotonic() >= deadline:
+ break
+ forced = True
+
+ if stopped:
+ raise RuntimeError(f"port {port} is still held by {stopped} after a kill")
+ raise RuntimeError(
+ f"port {port} is in use and its owner could not be identified; "
+ "stop it by hand or relaunch with --port"
+ )
+
+
def _venv_python(root: Path, platform: str = os.name) -> Path:
relative = Path("Scripts/python.exe") if platform == "nt" else Path("bin/python")
python = root / ".venv" / relative
@@ -199,6 +318,10 @@ def _run_process(
def run(*, port: int, no_browser: bool) -> int:
if _stop_previous(STATE_PATH):
print("Stopped the previous managed Azimut instance.")
+ stopped = _free_port(port)
+ if stopped:
+ joined = ", ".join(str(pid) for pid in stopped)
+ print(f"Freed port {port} (stopped {joined}).")
control = _ControlServer(STATE_PATH)
control.start()
diff --git a/src/azimut/__init__.py b/src/azimut/__init__.py
index c0e321e..bf86454 100644
--- a/src/azimut/__init__.py
+++ b/src/azimut/__init__.py
@@ -4,11 +4,15 @@ import warnings
from PIL import Image as _Image
-# The single source of truth for the app version. pyproject.toml reads it back
-# through hatchling's dynamic version (``[tool.hatch.version]``) and the
-# extension manifest is kept in lock-step by a test, so a release is bumped in
-# exactly one place. Getting this wrong nags every user with a false update
-# (the binary's self-check compares this against the latest GitHub tag).
+# The single source of truth for the app version: pyproject.toml reads it back
+# through hatchling's dynamic version (``[tool.hatch.version]``), so a release
+# is bumped in exactly one place. Getting this wrong nags every user with a
+# false update (the binary's self-check compares this against the latest GitHub
+# tag).
+#
+# The capture extension is versioned separately, on purpose — it carries the
+# release that last changed it (tests/test_updates.py). Don't move the two
+# together.
__version__ = "0.2.7"
# Cap the pixels Pillow will decode from a file, process-wide. A tiny,
diff --git a/src/azimut/api/analysis_views.py b/src/azimut/api/analysis_views.py
new file mode 100644
index 0000000..ab4b6cd
--- /dev/null
+++ b/src/azimut/api/analysis_views.py
@@ -0,0 +1,155 @@
+"""Named, case-owned Board, Graph and Timeline readings."""
+
+from __future__ import annotations
+
+import uuid
+from datetime import datetime, timezone
+from typing import Any, Literal
+
+from fastapi import APIRouter, HTTPException
+from pydantic import BaseModel, Field
+
+from ..engine import analysis_views as view_engine
+from ..engine import trash as trash_engine
+from ..workspace import CaseError
+from .cases import get_case
+
+router = APIRouter(
+ prefix="/api/cases/{case_id}/analysis-views", tags=["analysis views"]
+)
+
+
+def _now() -> str:
+ return datetime.now(timezone.utc).isoformat(timespec="seconds").replace("+00:00", "Z")
+
+
+class AnalysisViewIn(BaseModel):
+ name: str = Field(min_length=1, max_length=80)
+ mode: Literal["live", "snapshot"] = "live"
+ surface: Literal["board", "graph", "timeline"] = "board"
+ spec: dict[str, Any] = Field(default_factory=dict)
+
+
+class AnalysisViewDuplicateIn(BaseModel):
+ name: str = Field(min_length=1, max_length=80)
+
+
+def _unique(case, name: str, surface: str, *, ignore: str | None = None) -> None:
+ """A name is claimed inside its own family, not across the app: the Timeline's
+ views and the catalog's are separate lists, and refusing a name the user cannot
+ see anywhere is worse than allowing the repeat."""
+ wanted = name.strip().casefold()
+ wanted_family = view_engine.family(surface)
+ if any(
+ view["id"] != ignore
+ and view_engine.family(view.get("surface")) == wanted_family
+ and str(view["name"]).strip().casefold() == wanted
+ for view in case.list_analysis_views()
+ ):
+ raise HTTPException(status_code=409, detail=f"an analysis view named '{name}' already exists")
+
+
+def _save(
+ case,
+ view_id: str,
+ body: AnalysisViewIn,
+ *,
+ created_at: str,
+ snapshot_copy: bool = False,
+) -> dict[str, Any]:
+ name = body.name.strip()
+ _unique(case, name, body.surface, ignore=view_id)
+ try:
+ spec = view_engine.prepare(
+ case,
+ body.spec,
+ mode=body.mode,
+ surface=body.surface,
+ snapshot_copy=snapshot_copy,
+ )
+ except CaseError as exc:
+ raise HTTPException(status_code=400, detail=str(exc)) from exc
+ now = _now()
+ return case.save_analysis_view({
+ "id": view_id,
+ "name": name,
+ "mode": body.mode,
+ "surface": body.surface,
+ "spec": spec,
+ "created_at": created_at,
+ "updated_at": now,
+ })
+
+
+def list_analysis_views(case_id: str) -> dict[str, Any]:
+ case = get_case(case_id)
+ return {"views": [view_engine.summary(view) for view in case.list_analysis_views()]}
+
+
+def create_analysis_view(case_id: str, body: AnalysisViewIn) -> dict[str, Any]:
+ case = get_case(case_id)
+ now = _now()
+ return _save(case, f"v_{uuid.uuid4().hex[:16]}", body, created_at=now)
+
+
[email protected]("/{view_id}")
+def get_analysis_view(case_id: str, view_id: str) -> dict[str, Any]:
+ view = get_case(case_id).get_analysis_view(view_id)
+ if view is None:
+ raise HTTPException(status_code=404, detail=f"analysis view '{view_id}' not found")
+ return view
+
+
[email protected]("/{view_id}/duplicate")
+def duplicate_analysis_view(
+ case_id: str, view_id: str, body: AnalysisViewDuplicateIn
+) -> dict[str, Any]:
+ case = get_case(case_id)
+ current = case.get_analysis_view(view_id)
+ if current is None:
+ raise HTTPException(status_code=404, detail=f"analysis view '{view_id}' not found")
+ now = _now()
+ duplicate = AnalysisViewIn(
+ name=body.name,
+ mode=current["mode"],
+ surface=current["surface"],
+ spec=current["spec"],
+ )
+ return _save(
+ case,
+ f"v_{uuid.uuid4().hex[:16]}",
+ duplicate,
+ created_at=now,
+ snapshot_copy=True,
+ )
+
+
[email protected]("/{view_id}")
+def update_analysis_view(
+ case_id: str, view_id: str, body: AnalysisViewIn
+) -> dict[str, Any]:
+ case = get_case(case_id)
+ current = case.get_analysis_view(view_id)
+ if current is None:
+ raise HTTPException(status_code=404, detail=f"analysis view '{view_id}' not found")
+ if current["mode"] == "snapshot":
+ raise HTTPException(status_code=409, detail="a snapshot is immutable; duplicate it instead")
+ return _save(case, view_id, body, created_at=current["created_at"])
+
+
[email protected]("/{view_id}")
+def delete_analysis_view(case_id: str, view_id: str) -> dict[str, Any]:
+ case = get_case(case_id)
+ view = case.get_analysis_view(view_id)
+ if view is None:
+ raise HTTPException(status_code=404, detail=f"analysis view '{view_id}' not found")
+ group = trash_engine.send_analysis_view(case, view)
+ try:
+ case.remove_analysis_view(view_id)
+ trash_engine.commit(case, group["id"])
+ except Exception:
+ trash_engine.rollback(case, group["id"])
+ raise
+ return {"status": "deleted", "deleted": [view_id], "trash": group["id"]}
diff --git a/src/azimut/api/cases.py b/src/azimut/api/cases.py
index fca7ff0..eb5975e 100644
--- a/src/azimut/api/cases.py
+++ b/src/azimut/api/cases.py
@@ -5,23 +5,36 @@ The note bodies and their PDF export live next door in `api/notes.py`.
from __future__ import annotations
+import json
+import math
import sqlite3
+from io import BytesIO
from pathlib import Path
-from typing import Any, cast
+from typing import Any, Literal, cast
-from fastapi import APIRouter, File, Form, HTTPException, UploadFile
+from fastapi import APIRouter, File, Form, HTTPException, Query, UploadFile
from fastapi.responses import FileResponse
-from pydantic import BaseModel, Field
+from pydantic import BaseModel, Field, StrictInt
from .. import config, workspace
+from ..engine import artifacts as artifact_engine
+from ..engine import analysis_views as analysis_view_engine
from ..engine import bundles as bundle_engine
from ..engine import doctor as doctor_engine
+from ..engine import entities as entity_engine
+from ..engine import entity_images as entity_image_engine
+from ..engine import graph as graph_engine
from ..engine import links as link_engine
from ..engine import media as media_engine
from ..engine import reveal as reveal_engine
+from ..engine import satellite as satellite_engine
+from ..engine import tally as tally_engine
from ..engine import trash as trash_engine
+from ..engine import timeline as timeline_engine
+from ..engine.temporal import TemporalError, window_bound
from ..repository import EntityStatus
from ..workspace import Case, CaseError
+from .limits import MAX_IMAGE_BYTES
router = APIRouter(prefix="/api/cases", tags=["cases"])
@@ -175,6 +188,10 @@ class EntityDeleteIn(BaseModel):
ids: list[str] = Field(min_length=1, max_length=200)
+class EntityImagesIn(BaseModel):
+ media_ids: list[str] = Field(min_length=1, max_length=100)
+
+
class LinkIn(BaseModel):
# `from`/`to` are the link's own field names, but `from` is a Python keyword;
# the request spells them out rather than aliasing around it.
@@ -186,6 +203,48 @@ class LinkIn(BaseModel):
class LinkPatch(BaseModel):
status: EntityStatus | None = None
type: str | None = Field(default=None, min_length=1, max_length=40)
+ #: One closed ordinal, or `null` to return the edge to "not assessed". Sending it
+ #: at all is what counts, so the route reads `model_fields_set` rather than the
+ #: value: `null` clears a rating, where omitting the key leaves it alone.
+ #:
+ #: Strict, so JSON `true` is refused rather than coerced to `1`: a lax int would
+ #: turn a nonsense body into the "possible" level without anyone noticing, and
+ #: `2.5` into `2`.
+ confidence: StrictInt | None = None
+ #: What kind of tie the edge states, in the analyst's own words, or `null` to
+ #: clear it. Read through `model_fields_set` like the rating above, for the same
+ #: reason: `null` unsays it, omitting the key leaves it alone. Only a verb
+ #: declaring a `qualifier` accepts one (`engine/links.set_qualifier`).
+ nature: str | None = None
+
+
+class TemporalClaimIn(BaseModel):
+ statement: str = Field(min_length=1, max_length=300)
+ when: str | None = None
+ time_role: Literal["occurred", "observed", "valid"] | None = None
+ confidence: Literal["certain", "probable", "possible", "refuted"] | None = None
+ method: str | None = None
+ verbatim: str | None = None
+ count: StrictInt | None = None
+ condition: Literal["intact", "damaged", "destroyed", "abandoned"] | None = None
+ about: list[str] = Field(default_factory=list, max_length=200)
+ at: list[str] = Field(default_factory=list, max_length=50)
+ cites: list[str] = Field(default_factory=list, max_length=200)
+
+
+class TemporalClaimPatch(BaseModel):
+ statement: str | None = Field(default=None, min_length=1, max_length=300)
+ when: str | None = None
+ time_role: Literal["occurred", "observed", "valid"] | None = None
+ confidence: Literal["certain", "probable", "possible", "refuted"] | None = None
+ method: str | None = None
+ verbatim: str | None = None
+ count: StrictInt | None = None
+ condition: Literal["intact", "damaged", "destroyed", "abandoned"] | None = None
+ about: list[str] | None = Field(default=None, max_length=200)
+ at: list[str] | None = Field(default=None, max_length=50)
+ cites: list[str] | None = Field(default=None, max_length=200)
+ status: EntityStatus | None = None
class FolderIn(BaseModel):
@@ -207,6 +266,35 @@ class BundleUpload(BundlePassword):
upload_id: str = Field(min_length=32, max_length=32)
+class MediaPath(BaseModel):
+ """One case-relative file path, bounded the way every other media route bounds
+ one. Where it may point is `Case.resolve_inside`'s answer, not this model's."""
+
+ path: str = Field(min_length=1, max_length=300)
+
+
+class GraphPin(BaseModel):
+ """One node and where it was dropped, in the graph's own canvas units.
+
+ Bounded because a coordinate arrives from a pointer and nothing downstream
+ clamps it: the layout would happily place a node at 1e300 and the view would
+ then scale the whole case down to a dot trying to frame it.
+ """
+
+ id: str = Field(min_length=1, max_length=64)
+ x: float = Field(ge=-1_000_000, le=1_000_000)
+ y: float = Field(ge=-1_000_000, le=1_000_000)
+
+
+class GraphPins(BaseModel):
+ #: Which reading was being arranged. An arrangement belongs to one, because a
+ #: lens draws its own nodes and clusters them its own way.
+ lens: str = Field(min_length=1, max_length=40)
+ #: One drag, or the batch a debounce collected. Capped at the view's own node
+ #: ceiling: nothing can be arranged that was never drawn.
+ pins: list[GraphPin] = Field(min_length=1, max_length=graph_engine.MAX_OPENING)
+
+
class DoctorRepair(BaseModel):
action: str = Field(min_length=1, max_length=20)
entity_id: str | None = Field(default=None, max_length=64)
@@ -324,14 +412,143 @@ def relation_types() -> list[dict[str, Any]]:
{
"type": entry.type,
"label": entry.label,
+ "inverse_label": entry.inverse_label or entry.label,
+ # one clause saying what the verb means, for the surface that shows it
+ "hint": entry.hint,
+ # the heading this verb sits under, empty when it sits with the rest
+ "group": entry.group,
+ # A mention is filed with its own gesture. It is not another wording
+ # a relation can turn into after the analyst chose a target.
+ "action": entry.action,
"from_types": sorted(entry.from_types),
"to_types": sorted(entry.to_types),
"manual": entry.manual,
+ # A mention is a pointer, not a claim to grade. The surface omits the
+ # control instead of offering one the model would refuse.
+ "ratable": entry.ratable,
+ # How a free note on this edge is labelled, empty when the verb takes
+ # none — the same shape as `ratable`, and read the same way: a surface
+ # draws the field because the verb declares it, never because an edge
+ # happens to carry one.
+ "qualifier": entry.qualifier,
+ "from_media_kinds": sorted(entry.from_media_kinds),
+ "to_media_kinds": sorted(entry.to_media_kinds),
}
for entry in link_engine.RELATION_TYPES
]
[email protected]("/graph-lenses")
+def graph_lenses() -> dict[str, Any]:
+ """The readings the graph offers, and the orderings it ranks by.
+
+ A lens is a set of verbs *and* a set of node roles, and both live in the
+ registries, so each one is resolved from them rather than listed again here — a
+ verb or a type added there joins its lens with no edit. ``orders`` is the same
+ contract as the radius rungs: served, so the picker and the validator cannot drift.
+
+ ``hides`` is the types the reading leaves out of the drawing. Served because the
+ surface has to be able to say so *before* asking: a legend row that switches
+ nothing and a "bring this in" that the reading will refuse are both controls that
+ can only appear to be broken.
+
+ Declared above ``/{case_id}`` so the literal path wins.
+ """
+ return {
+ "lenses": [
+ {"id": entry.id, "label": entry.label, "hint": entry.hint,
+ "types": list(entry.types), "hides": list(entry.hides)}
+ for entry in graph_engine.lenses()
+ ],
+ "orders": [
+ {"value": value, "label": label, "hint": hint}
+ for value, label, hint in graph_engine.ORDERS
+ ],
+ "max_hops": graph_engine.MAX_HOPS,
+ }
+
+
[email protected]("/confidence-levels")
+def confidence_levels() -> list[dict[str, Any]]:
+ """How sure an edge may say the analyst is (ONTOLOGY §3), coarsest word last.
+
+ Served rather than hardcoded on each surface for the reason the radius rungs are:
+ one list, so the picker and the validator cannot drift. **Not assessed is absent
+ from this list on purpose** — it is the lack of a rating, not a sixth level, and a
+ surface offers it as "clear" rather than as a choice.
+
+ Declared above ``/{case_id}`` so the literal path wins.
+ """
+ return [
+ {"value": value, "label": label, "hint": hint}
+ for value, label, hint in link_engine.CONFIDENCE_LEVELS
+ ]
+
+
[email protected]("/entity-types")
+def entity_types() -> list[dict[str, Any]]:
+ """The entity vocabulary (ONTOLOGY §2): each type's reading, family, icon and
+ the fields an analyst may fill on it.
+
+ One registry so a create form is generated rather than written per type, and so
+ no screen keeps its own copy. ``manual`` marks the types an analyst creates by
+ hand — a ``media`` is born from an import, so it never belongs in a create menu.
+ Declared above ``/{case_id}`` so the literal path wins.
+ """
+ return [
+ {
+ "type": entry.type,
+ "label": entry.label,
+ "family": entry.family,
+ # what the type is, and what its family is, each in one clause. The
+ # vocabulary is terse by design, and a terse word nobody can look up is
+ # jargon — so the readings travel with it rather than being written per
+ # screen.
+ "hint": entry.hint,
+ "family_reads": entity_engine.FAMILY_READS.get(entry.family, ""),
+ "icon": entry.icon,
+ "manual": entry.manual,
+ "image_gallery": entry.image_gallery,
+ # ``entity.label`` is the primary value, but "Name" is not an honest
+ # reading for an IP address, a phone number or a claim. The generated
+ # form names that field from the type instead of duplicating it in attrs.
+ "identity_label": entry.identity_label,
+ "identity_placeholder": entry.identity_placeholder,
+ "attrs": [
+ {
+ "key": attr.key,
+ "label": attr.label,
+ "hint": attr.hint,
+ "kind": attr.kind,
+ "editable": attr.editable,
+ # Heads this field and the ones after it that share it; empty
+ # means the field stands on its own label. On the field rather
+ # than on the type because a Claim separates what it states,
+ # when it applies and why it is believed.
+ "group": attr.group,
+ # Served so the form refuses exactly what the API refuses; a
+ # rung list is the shortcut UI, the bounds are the contract.
+ "rungs": [{"label": name, "value": v} for name, v in attr.rungs],
+ "minimum": attr.minimum,
+ "maximum": attr.maximum,
+ # A count steps by one. Served so the spinner and the validator
+ # cannot disagree about what a valid quantity is.
+ "whole": attr.whole,
+ # The whole of a closed field, in scale order. A source's
+ # reliability rides here rather than on a route of its own: it
+ # belongs to the entity, so it travels with the entity registry.
+ "options": [
+ {"value": stored, "label": reading}
+ for stored, reading in attr.options
+ ],
+ }
+ for attr in entry.attrs
+ ],
+ }
+ for entry in entity_engine.ENTITY_TYPES
+ ]
+
+
@router.get("/{case_id}/doctor")
def doctor_report(case_id: str) -> dict[str, Any]:
"""Inspect a case even when its database is missing."""
@@ -351,7 +568,13 @@ def doctor_repair(case_id: str, body: DoctorRepair) -> dict[str, Any]:
case = located
else:
case = Case.open(case_id)
- if body.action == "import" and body.path:
+ if body.action == "rebuild-timeline":
+ doctor_engine.require_stale_temporal_projection(case)
+ result = {
+ "status": "rebuilt",
+ "items": case.rebuild_temporal_projection(),
+ }
+ elif body.action == "import" and body.path:
doctor_engine.require_unknown_media(case, body.path)
result = media_engine.register_existing(case, body.path)
elif body.action == "drop" and body.entity_id:
@@ -418,6 +641,33 @@ def reveal_case_folder(case_id: str) -> dict[str, str]:
return {"path": str(case.path)}
[email protected]("/{case_id}/media/reveal")
+def reveal_media_folder(case_id: str, body: MediaPath) -> dict[str, str]:
+ """Show the folder holding one of this case's files.
+
+ For what the app cannot display: a PDF, a scan bundle, a spreadsheet. Handing
+ those to the browser downloads a second copy into Downloads, which is how an
+ analyst ends up working on a file the case no longer knows about. The folder is
+ the honest answer — the original is opened in whatever program owns it.
+
+ The path is the browser's, so it goes through ``resolve_inside`` like every
+ other media route; ``reveal`` then re-checks that the folder is inside the
+ workspace, and it is a folder that is opened, never the file itself.
+ """
+ case = get_case(case_id)
+ try:
+ target = case.resolve_inside(body.path)
+ except CaseError as exc:
+ raise HTTPException(status_code=400, detail=str(exc)) from exc
+ if not target.is_file():
+ raise HTTPException(status_code=404, detail="file not found")
+ try:
+ reveal_engine.reveal(target.parent)
+ except reveal_engine.RevealError as exc:
+ raise HTTPException(status_code=409, detail=str(exc)) from exc
+ return {"path": str(target.parent)}
+
+
@router.post("/{case_id}/bundle/export")
def export_bundle(case_id: str, body: BundlePassword) -> dict[str, Any]:
case = get_case(case_id)
@@ -471,6 +721,42 @@ def download_bundle(case_id: str, job_id: str) -> FileResponse:
)
+def _explain_catalog_matches(page: dict[str, Any], query: str | None) -> dict[str, Any]:
+ if not query:
+ return page
+ for entity in page.get("items", []):
+ if matches := entity_engine.search_matches(entity, query):
+ entity["matches"] = matches
+ return page
+
+
+def _temporal_filter_args(
+ from_: str | None,
+ to: str | None,
+ category: str | None,
+) -> tuple[str | None, str | None, list[str] | None]:
+ """Validate the fact-time window kept separate from filing dates."""
+ if from_ is None and to is None:
+ return None, None, None
+ if from_ is None or to is None:
+ raise HTTPException(status_code=400, detail="a temporal filter needs both boundaries")
+ since = _timeline_bound(from_, upper=False)
+ until = _timeline_bound(to, upper=True)
+ if since is not None and until is not None and since >= until:
+ raise HTTPException(status_code=400, detail="the temporal filter ends before it starts")
+ categories = (
+ list(dict.fromkeys(part.strip() for part in category.split(",") if part.strip()))
+ if category is not None
+ else list(timeline_engine.DEFAULT_CATEGORIES)
+ )
+ invalid = sorted(set(categories) - set(timeline_engine.ALL_CATEGORIES))
+ if invalid:
+ raise HTTPException(status_code=400, detail=f"unknown timeline category '{invalid[0]}'")
+ if not categories:
+ raise HTTPException(status_code=400, detail="a temporal filter needs a category")
+ return since, until, categories
+
+
@router.get("/{case_id}/catalog/entities")
def catalog_entities(
case_id: str,
@@ -482,37 +768,382 @@ def catalog_entities(
folder: str | None = None,
unfiled: bool = False,
recursive: bool = False,
+ attr: str | None = None,
+ value: str | None = None,
+ linked: str | None = None,
+ unlinked: bool = False,
+ since: str | None = None,
+ until: str | None = None,
+ by: str | None = None,
+ temporal_from: str | None = None,
+ temporal_to: str | None = None,
+ temporal_category: str | None = None,
+ order: str = "",
+ view: str | None = None,
) -> dict[str, Any]:
"""A bounded page of the entity catalog (Step 5, "Bounded loading").
- Stable cursor order, server-side filters (a comma-separated ``type`` set,
- ``status``, a label substring ``q``, and folder — ``unfiled=true`` or an
- ``folder`` path, optionally including descendants) and a ``next_cursor``
- that is null on the last page. ``limit`` is clamped so no request can ask
- for the whole graph at once.
+ Stable cursor order, server-side filters and a ``next_cursor`` that is null on the
+ last page. ``limit`` is clamped so no request can ask for the whole graph at once.
+
+ The filters: a comma-separated ``type`` set, ``status``, a label substring ``q``,
+ folder (``unfiled=true`` or a ``folder`` path, optionally including descendants),
+ one stored field holding one value (``attr`` with ``value``), having a neighbour of
+ a type (``linked``) or none at all (``unlinked``), and how the row got here —
+ ``since``/``until`` over the date it was filed, and a comma-separated ``by`` set of
+ whatever filed it. Together they are what make the page an answer rather than a
+ shorter list: *media, kind video, linked to a place* is "which videos have
+ coordinates", and ``total`` is how many.
+
+ ``order`` sorts the whole filtered set rather than the page — ``created`` and
+ ``label``, each with a ``-`` prefix for the other direction. Empty is the insertion
+ order that has always been the default.
+
+ ``attr`` without ``value`` is not a term — it is the analyst having chosen which
+ field they are about to ask about, and answering it as "holds nothing" would empty
+ the table between two clicks of one act.
"""
case = get_case(case_id)
limit = max(1, min(limit, 500))
+ if view:
+ saved = case.get_analysis_view(view)
+ if saved is None:
+ raise HTTPException(status_code=404, detail=f"analysis view '{view}' not found")
+ if saved["mode"] == "snapshot":
+ try:
+ return _explain_catalog_matches(
+ analysis_view_engine.snapshot_page(
+ saved, limit=limit, cursor=cursor, order=order
+ ),
+ q,
+ )
+ except CaseError as exc:
+ raise HTTPException(status_code=400, detail=str(exc)) from exc
types = [t.strip() for t in type.split(",") if t.strip()] if type else None
+ filed_by = [name.strip() for name in by.split(",") if name.strip()] if by else None
+ temporal_since, temporal_until, temporal_categories = _temporal_filter_args(
+ temporal_from, temporal_to, temporal_category
+ )
valid_status = (
cast(EntityStatus, status) if status in ("confirmed", "suggested") else None
)
try:
- return case.page_entities(
+ page = case.page_entities(
limit=limit, cursor=cursor, types=types, status=valid_status,
query=q, folder=folder, unfiled=unfiled, recursive=recursive,
+ attr=attr, attr_value=value, linked=linked, unlinked=unlinked,
+ since=since, until=until, filed_by=filed_by, order=order,
+ temporal_since=temporal_since, temporal_until=temporal_until,
+ temporal_categories=temporal_categories,
)
+ thumbs = case.entity_image_thumbs([entity["id"] for entity in page["items"]])
+ for entity in page["items"]:
+ if thumb := thumbs.get(entity["id"]):
+ entity["thumb"] = thumb
+ return _explain_catalog_matches(page, q)
except CaseError as exc:
raise HTTPException(status_code=400, detail=str(exc)) from exc
@router.get("/{case_id}/catalog/summary")
def catalog_summary(case_id: str) -> dict[str, Any]:
- """Total plus per-type and per-status counts, so the catalog can show badges
- without loading the graph."""
+ """Counts per type, status, folder and filer, plus how many the case connects to
+ nothing, so the catalog shows badges and populates its filter menus without
+ loading the graph."""
return get_case(case_id).catalog_summary()
[email protected]("/{case_id}/catalog/attributes")
+def catalog_attributes(case_id: str, type: str | None = None) -> dict[str, Any]:
+ """Which stored fields these entities hold, and which values, as a menu.
+
+ What lets a field be filtered on without a query language: the field select and
+ the value select are both populated from the case, so every term of a search is
+ chosen rather than typed (SPEC anti-goals). It reaches fields the vocabulary does
+ not declare, which is the point — `kind` is written by the importer, so a
+ registry-driven menu would never have offered the one field an analyst most wants.
+
+ Narrowed by the same comma-separated ``type`` set as the page it filters: the
+ fields a media holds are not the fields a claim holds, and one menu of both is a
+ menu of neither.
+ """
+ types = [t.strip() for t in type.split(",") if t.strip()] if type else None
+ return {"attrs": get_case(case_id).attr_facets(types=types)}
+
+
[email protected]("/{case_id}/catalog/tally")
+def catalog_tally(
+ case_id: str,
+ type: str | None = None,
+ status: str | None = None,
+ q: str | None = None,
+ folder: str | None = None,
+ unfiled: bool = False,
+ recursive: bool = False,
+ attr: str | None = None,
+ value: str | None = None,
+ linked: str | None = None,
+ unlinked: bool = False,
+ since: str | None = None,
+ until: str | None = None,
+ by: str | None = None,
+ temporal_from: str | None = None,
+ temporal_to: str | None = None,
+ temporal_category: str | None = None,
+) -> dict[str, Any]:
+ """What the statements in this narrowing add up to, per subject.
+
+ The same terms as the catalog page it sits beside, spelled the same way, because
+ it is the same question: the table lists the statements, this one adds them up
+ (``engine/tally.py``). Every rule about what may enter a sum is there — a ruled-out
+ statement never does, an absent count is not one, and nothing is totalled across
+ subjects.
+ """
+ types = [t.strip() for t in type.split(",") if t.strip()] if type else None
+ filed_by = [name.strip() for name in by.split(",") if name.strip()] if by else None
+ temporal_since, temporal_until, temporal_categories = _temporal_filter_args(
+ temporal_from, temporal_to, temporal_category
+ )
+ try:
+ return tally_engine.tally(
+ get_case(case_id), types=types, status=status, query=q,
+ folder=folder, unfiled=unfiled, recursive=recursive,
+ attr=attr, attr_value=value, linked=linked, unlinked=unlinked,
+ since=since, until=until, filed_by=filed_by,
+ temporal_since=temporal_since, temporal_until=temporal_until,
+ temporal_categories=temporal_categories,
+ )
+ except CaseError as exc:
+ raise HTTPException(status_code=400, detail=str(exc)) from exc
+
+
+def _ids(value: str | None) -> list[str] | None:
+ """One of the graph's comma-separated id lists, or nothing at all.
+
+ ``None`` rather than an empty list when nothing was sent, because the engine
+ tells "no list" from "an empty one" and answers the first by not asking.
+ """
+ if not value:
+ return None
+ named = [entity_id.strip() for entity_id in value.split(",") if entity_id.strip()]
+ return named or None
+
+
[email protected]("/{case_id}/graph")
+def graph_view(
+ case_id: str,
+ lens: str = "all",
+ limit: int | None = None,
+ order: str = "degree",
+ type: str | None = None,
+ status: str | None = None,
+ q: str | None = None,
+ folder: str | None = None,
+ unfiled: bool = False,
+ recursive: bool = False,
+ attr: str | None = None,
+ value: str | None = None,
+ linked: str | None = None,
+ unlinked: bool = False,
+ since: str | None = None,
+ until: str | None = None,
+ by: str | None = None,
+ temporal_from: str | None = None,
+ temporal_to: str | None = None,
+ temporal_category: str | None = None,
+ keep: str | None = None,
+ expand: str | None = None,
+ omit: str | None = None,
+ view: str | None = None,
+) -> dict[str, Any]:
+ """The whole case as one bounded graph — the view the graph opens on.
+
+ A case is a subject before it is a set of statements, so this is the entry
+ point and expansion is the drill-down, not the other way round. ``order``
+ decides which nodes a case too large to draw keeps: the hubs, or the latest
+ work. **The catalog's whole filter vocabulary narrows it** — down to the stored
+ field, the one-hop test and the date it was filed — so the board and the graph
+ cannot disagree about what "confirmed people in this folder, added this week"
+ means, and a question asked in the table can be handed to the drawing as itself
+ rather than as a list of ids that goes stale on the next save.
+
+ Three comma-separated lists then edit that set, and the drawing is whatever they
+ say it is. ``keep`` draws these nodes and nothing around them; ``expand`` draws
+ these and one hop, which is what lets the analyst follow a thread without losing
+ the case they were reading it in; ``omit`` leaves these out, whichever of the
+ three put them there. Ids the case does not hold are skipped rather than refused —
+ a drawing races a delete made in another tab.
+ """
+ case = get_case(case_id)
+ if view:
+ saved = case.get_analysis_view(view)
+ if saved is None:
+ raise HTTPException(status_code=404, detail=f"analysis view '{view}' not found")
+ if saved["mode"] == "snapshot":
+ try:
+ return graph_engine.snapshot_view(
+ saved["spec"]["snapshot"], lens_id=lens, query=q
+ )
+ except CaseError as exc:
+ raise HTTPException(status_code=400, detail=str(exc)) from exc
+ types = [t.strip() for t in type.split(",") if t.strip()] if type else None
+ filed_by = [name.strip() for name in by.split(",") if name.strip()] if by else None
+ temporal_since, temporal_until, temporal_categories = _temporal_filter_args(
+ temporal_from, temporal_to, temporal_category
+ )
+ try:
+ payload = graph_engine.view(
+ case, lens_id=lens, limit=limit, types=types, status=status,
+ query=q, folder=folder, unfiled=unfiled, recursive=recursive, order=order,
+ attr=attr, attr_value=value, linked=linked, unlinked=unlinked,
+ since=since, until=until, filed_by=filed_by,
+ temporal_since=temporal_since, temporal_until=temporal_until,
+ temporal_categories=temporal_categories,
+ keep=_ids(keep), expand=_ids(expand), omit=_ids(omit),
+ )
+ except CaseError as exc:
+ raise HTTPException(status_code=400, detail=str(exc)) from exc
+ _adopt_spec_previews(case, payload)
+ return payload
+
+
[email protected]("/{case_id}/graph/neighborhood")
+def graph_neighborhood(
+ case_id: str,
+ root: str,
+ lens: str = "all",
+ hops: int = 1,
+ limit: int | None = None,
+) -> dict[str, Any]:
+ """One node and what surrounds it, for a question that does have a root.
+
+ Every node carries its degree in this lens, so the analyst sees what a further
+ expansion costs before paying it, and ``truncated`` says when the node budget
+ ended the walk rather than the graph doing so.
+ """
+ case = get_case(case_id)
+ try:
+ payload = graph_engine.neighborhood(
+ case, root, lens_id=lens, hops=hops, limit=limit
+ )
+ except CaseError as exc:
+ detail = str(exc)
+ status_code = 404 if "not found" in detail else 400
+ raise HTTPException(status_code=status_code, detail=detail) from exc
+ _adopt_spec_previews(case, payload)
+ return payload
+
+
[email protected]("/{case_id}/graph/paths")
+def graph_paths(
+ case_id: str,
+ from_id: str = Query(alias="from"),
+ to_id: str = Query(alias="to"),
+ lens: str = "all",
+ hops: int = graph_engine.MAX_PATH_HOPS,
+) -> dict[str, Any]:
+ """Every shortest route between two entities, or the fact that there is none.
+
+ A read, and the one question the graph existed without: the case answers "what
+ touches this" a hop at a time, where an investigation asks "how does this reach
+ that". ``found: false`` is an answer rather than an error — learning that two
+ entities are *not* connected within the budget is a finding about the case.
+
+ ``from`` and ``to`` are query names rather than argument names because ``from``
+ is a Python keyword, and the URL is the vocabulary the client reads.
+ """
+ case = get_case(case_id)
+ try:
+ return graph_engine.paths(case, from_id, to_id, lens_id=lens, max_hops=hops)
+ except CaseError as exc:
+ detail = str(exc)
+ status_code = 404 if "not found" in detail else 400
+ raise HTTPException(status_code=status_code, detail=detail) from exc
+
+
+def _lens_id(lens: str) -> str:
+ """The lens an arrangement belongs to, refused if the registry does not know it.
+
+ Checked at the edge like every other lens: an unrecognised one would file pins
+ under a reading nothing can ever draw, where they would sit in the case forever
+ with no surface able to show or clear them.
+ """
+ try:
+ return graph_engine.lens(lens).id
+ except CaseError as exc:
+ raise HTTPException(status_code=400, detail=str(exc)) from exc
+
+
[email protected]("/{case_id}/graph/pins")
+def pin_graph_nodes(case_id: str, body: GraphPins) -> dict[str, Any]:
+ """Record where nodes were dragged to, so the arrangement survives a reload.
+
+ Filed against the lens they were arranged in: a lens draws its own nodes and
+ clusters them its own way, so one shared arrangement would anchor every reading
+ into the shape of whichever one it was built in.
+
+ The whole batch in one transaction: a drag that moved several nodes is one
+ act, and half of it landing would leave an arrangement nobody chose. Writing a
+ pin asserts nothing about the case — it is where a hand put a dot — which is
+ why it never touches the entity or its provenance.
+ """
+ case = get_case(case_id)
+ lens = _lens_id(body.lens)
+ case.pin_entities(lens, {pin.id: (pin.x, pin.y) for pin in body.pins})
+ return {"lens": lens, "pinned": len(case.graph_pins(lens))}
+
+
[email protected]("/{case_id}/graph/pins/{entity_id}")
+def unpin_graph_node(case_id: str, entity_id: str, lens: str = "all") -> dict[str, Any]:
+ """Hand one node back to the computed layout, in this lens."""
+ case = get_case(case_id)
+ reading = _lens_id(lens)
+ case.unpin_entities(reading, [entity_id])
+ return {"lens": reading, "pinned": len(case.graph_pins(reading))}
+
+
[email protected]("/{case_id}/graph/pins")
+def unpin_graph(case_id: str, lens: str = "all") -> dict[str, Any]:
+ """Drop this lens's arrangement: the reading goes back to the placement it
+ computes, and the other readings keep theirs.
+
+ The way out of an arrangement that stopped helping. It is offered because the
+ pins are saved as they are made — an autosave with no way back is a trap.
+ """
+ case = get_case(case_id)
+ reading = _lens_id(lens)
+ case.clear_graph_pins(reading)
+ return {"lens": reading, "pinned": 0}
+
+
+def _adopt_spec_previews(case: Case, payload: dict[str, Any]) -> None:
+ """Give a node the preview its own spec file has been keeping to itself.
+
+ A proof records its thumbnail in ``proofs/.meta/<name>.json``, and the graph
+ answers from the database alone — that boundary is what keeps a graph read one
+ query instead of a walk of the case, so it is not the place to open files. This
+ copies the path across, **once per proof, ever**: the first view that draws one
+ reads its spec, records it on the entity, and every later view finds it on the row
+ like any other preview. A proof saved from now on carries it from the start.
+ """
+ for node in payload.get("nodes", []):
+ if node.get("thumb") or node.get("type") != "proof":
+ continue
+ entity = case.get_entity(node["id"])
+ thumb = artifact_engine.spec_thumb(case, entity) if entity else None
+ if not thumb:
+ continue
+ node["thumb"] = thumb
+ try:
+ case.update_entity(node["id"], {"attrs": {"thumb": thumb}})
+ except (CaseError, sqlite3.Error):
+ # The copy is an optimisation, not the answer: a background import or
+ # a mass delete holding the write lock past `busy_timeout` must not
+ # turn a read of the graph into an error. The node already carries
+ # what it needs, and the next draw tries the copy again.
+ pass
+
+
@router.get("/{case_id}/entities/lookup")
def lookup_entity(case_id: str, attr: str, value: str) -> dict[str, Any]:
"""One entity by an ``attrs`` value (``path``, ``spec``, ``draft``), or null.
@@ -525,9 +1156,39 @@ def lookup_entity(case_id: str, attr: str, value: str) -> dict[str, Any]:
return {"entity": entity}
[email protected]("/{case_id}/entities/twin")
+def entity_twin(
+ case_id: str, type: str, label: str, ignore: str = ""
+) -> dict[str, Any]:
+ """The entity already holding this identifier's value, or null.
+
+ Only the ``identifier`` family answers anything: there the value *is* the
+ identity, so two records of it are two records of one thing (ONTOLOGY §2).
+ Everywhere else two entities may share a label and the question is meaningless.
+
+ **It warns, it never refuses.** Merging is not shipped (`same-as`, SPEC §10), and
+ a create that failed would leave the analyst holding a value with nowhere to put
+ it — so this reports and the surface offers the row it found. ``ignore`` is the
+ entity being renamed, which is not its own twin.
+
+ The comparison lives in ``engine/entities.identity_key`` and is served rather
+ than reimplemented: the create form used to lowercase the raw label in the
+ browser, which let `@handle` and `handle` sit side by side as two accounts.
+ """
+ key = entity_engine.identity_key(type, label)
+ if not key:
+ return {"entity": None}
+ case = get_case(case_id)
+ for entity_id, existing in case.labels_of_type(type):
+ if entity_id != ignore and entity_engine.identity_key(type, existing) == key:
+ return {"entity": case.get_entity(entity_id)}
+ return {"entity": None}
+
+
@router.post("/{case_id}/entities")
def add_entity(case_id: str, body: EntityIn) -> dict[str, Any]:
case = get_case(case_id)
+ _check_attrs(body.type, body.attrs)
if body.type == "note":
attrs = body.attrs
return case.create_note(
@@ -538,10 +1199,377 @@ def add_entity(case_id: str, body: EntityIn) -> dict[str, Any]:
return case.add_entity(body.type, body.label, body.attrs, by="user", status=body.status)
+def _check_attrs(
+ type_: str,
+ attrs: dict[str, Any],
+ *,
+ current: dict[str, Any] | None = None,
+) -> None:
+ """Refuse a malformed declared field with a 400, never a 404.
+
+ Split out because the two write paths reach it from different places and the
+ update path's own ``except CaseError`` answers 404 — a bad radius is a bad
+ request, not a missing entity.
+ """
+ try:
+ entity_engine.check_attrs(type_, attrs, current=current)
+ except CaseError as exc:
+ raise HTTPException(status_code=400, detail=str(exc)) from exc
+
+
+def _timeline_bound(raw: str | None, *, upper: bool) -> str | None:
+ if raw is None:
+ return None
+ try:
+ return window_bound(raw, upper=upper)
+ except TemporalError as exc:
+ raise HTTPException(status_code=400, detail=str(exc)) from exc
+
+
[email protected]("/{case_id}/timeline")
+def timeline(
+ case_id: str,
+ from_: str | None = Query(default=None, alias="from"),
+ to: str | None = None,
+ category: list[str] | None = Query(default=None),
+ entity: str | None = None,
+ include_undated: bool = True,
+ limit: int = Query(default=100, ge=1, le=200),
+ cursor: str | None = None,
+ bucket: Literal["year", "month", "day", "hour"] | None = None,
+ track: str | None = None,
+ spread: bool = False,
+) -> dict[str, Any]:
+ """One bounded temporal page, independent of the projection's SQL shape.
+
+ ``spread`` is for a caller drawing the page on an axis: it samples the window
+ rather than serving its front, so a lopsided case fills the axis it spans.
+ """
+ since = _timeline_bound(from_, upper=False)
+ until = _timeline_bound(to, upper=True)
+ if since is not None and until is not None and since >= until:
+ raise HTTPException(status_code=400, detail="the timeline window ends before it starts")
+ if track and len(track.encode("utf-8")) > 64 * 1024:
+ raise HTTPException(status_code=400, detail="timeline track query is too large")
+ try:
+ track_query = json.loads(track) if track else None
+ if track_query is not None and not isinstance(track_query, dict):
+ raise CaseError("a timeline track query must be an object")
+ page = get_case(case_id).timeline_page(
+ since=since,
+ until=until,
+ categories=category,
+ entity_id=entity,
+ include_undated=include_undated,
+ limit=limit,
+ cursor=cursor,
+ bucket=bucket,
+ track=track_query,
+ spread=spread,
+ )
+ except (CaseError, json.JSONDecodeError) as exc:
+ raise HTTPException(status_code=400, detail=str(exc)) from exc
+ return {**page, "window": {"from": since, "to": until}}
+
+
+# Every way the case puts something on the map. A Claim says where it happened with
+# `at`, and that was the only one this layer knew — so a window full of photographs
+# recorded somewhere, captures showing somewhere, or a structure standing somewhere
+# answered with an empty map and the words "nothing carries a place". `mentions` is
+# not here: a note referring to a place is not a thing that was there.
+_MAP_PLACE_LINKS = (
+ link_engine.AT,
+ link_engine.LOCATED_AT,
+ link_engine.DEPICTS,
+ link_engine.SITED_AT,
+)
+
+
[email protected]("/{case_id}/timeline/map")
+def timeline_map(
+ case_id: str,
+ from_: str = Query(alias="from"),
+ to: str = Query(),
+ category: list[str] | None = Query(default=None),
+) -> dict[str, Any]:
+ """Whatever the window holds that the case has put somewhere, for the Map layer."""
+ since = _timeline_bound(from_, upper=False)
+ until = _timeline_bound(to, upper=True)
+ if since is None or until is None or since >= until:
+ raise HTTPException(status_code=400, detail="the timeline window ends before it starts")
+ categories = (
+ list(dict.fromkeys(part.strip() for part in ",".join(category).split(",") if part.strip()))
+ if category
+ else list(timeline_engine.DEFAULT_CATEGORIES)
+ )
+ invalid = sorted(set(categories) - set(timeline_engine.ALL_CATEGORIES))
+ if invalid:
+ raise HTTPException(status_code=400, detail=f"unknown timeline category '{invalid[0]}'")
+ if not categories:
+ raise HTTPException(status_code=400, detail="a temporal filter needs a category")
+
+ case = get_case(case_id)
+ rows: list[dict[str, Any]] = []
+ cursor: str | None = None
+ read = 0
+ total = 0
+ ceiling = 5000
+ while read < ceiling:
+ page = case.timeline_page(
+ since=since,
+ until=until,
+ categories=categories,
+ include_undated=False,
+ limit=min(200, ceiling - read),
+ cursor=cursor,
+ )
+ if read == 0:
+ total = int(page["total"])
+ batch = list(page["items"])
+ rows.extend(batch)
+ read += len(batch)
+ cursor = page["next_cursor"]
+ if cursor is None or not batch:
+ break
+
+ # Resolved from the edges themselves rather than from the row's own `at` list,
+ # which only a Claim ever fills.
+ owners = {str(item["owner_id"]) for item in rows}
+ held: dict[str, list[str]] = {}
+ for edge in case.links_touching(
+ sorted(owners), types=list(_MAP_PLACE_LINKS), end_types=["place"]
+ ):
+ if edge["from"] in owners and edge["to"] != edge["from"]:
+ held.setdefault(edge["from"], []).append(edge["to"])
+
+ place_ids = list(dict.fromkeys(
+ place_id for places in held.values() for place_id in places
+ ))
+ places = {entity["id"]: entity for entity in case.entities_by_ids(place_ids)}
+
+ # What a mark on the map has to know to hand its row back to the tool that owns
+ # it, and to show a photograph as a photograph rather than as a line of text.
+ placed_owners = sorted(held)
+ owned = {entity["id"]: entity for entity in case.entities_by_ids(placed_owners)}
+ thumbs = dict(case.media_thumbs(placed_owners))
+ thumbs.update(case.entity_image_thumbs(placed_owners))
+ for owner_id, entity in owned.items():
+ # A capture or a proof records its own preview rather than owning an indexed
+ # media row, and the graph reads them the same way.
+ recorded = (entity.get("attrs") or {}).get("thumb")
+ if recorded and owner_id not in thumbs:
+ thumbs[owner_id] = recorded
+
+ mapped: list[dict[str, Any]] = []
+ mark_count = 0
+ for item in rows:
+ owner_id = str(item["owner_id"])
+ owner = owned.get(owner_id)
+ positioned = []
+ for place_id in dict.fromkeys(held.get(owner_id, [])):
+ place = places.get(place_id)
+ attrs = place.get("attrs") if place else None
+ if place is None or not isinstance(attrs, dict):
+ continue
+ try:
+ lat = float(attrs["lat"])
+ lon = float(attrs["lon"])
+ except (KeyError, TypeError, ValueError):
+ continue
+ if not math.isfinite(lat) or not math.isfinite(lon):
+ continue
+ positioned.append({
+ "id": place_id,
+ "label": place.get("label", "Place"),
+ "lat": lat,
+ "lon": lon,
+ "radius_m": attrs.get("radius_m"),
+ "footprint": attrs.get("footprint"),
+ })
+ if positioned:
+ mapped.append({
+ **item,
+ "place_entities": positioned,
+ "owner": {
+ "id": owner_id,
+ "type": owner.get("type", "") if owner else item.get("owner_type", ""),
+ "label": owner.get("label", "") if owner else item.get("label", ""),
+ "attrs": owner.get("attrs") or {} if owner else {},
+ "thumb": thumbs.get(owner_id),
+ },
+ })
+ mark_count += len(positioned)
+
+ return {
+ "items": mapped,
+ "matched": total,
+ "mapped": len(mapped),
+ "marks": mark_count,
+ "truncated": read < total,
+ "window": {"from": since, "to": until},
+ }
+
+
+_TEMPORAL_CLAIM_ATTRS = (
+ "when", "time_role", "confidence", "method", "verbatim", "count", "condition"
+)
+_TEMPORAL_CONNECTORS = ("about", "at", "cites")
+
+
+def _temporal_item(case: Case, claim_id: str) -> dict[str, Any]:
+ """The row this Claim owns, wherever the entity scope puts it.
+
+ That scope also answers with rows owned by whatever cites the Claim, and they
+ are ordered by date rather than by ownership — so a Claim many others rest on
+ can sit past the first page, and reading only that page would fail a write
+ that has already been committed.
+ """
+ cursor: str | None = None
+ while True:
+ page = case.timeline_page(
+ categories=[timeline_engine.STATEMENT],
+ entity_id=claim_id,
+ include_undated=True,
+ limit=200,
+ cursor=cursor,
+ )
+ for item in page["items"]:
+ if item["owner_id"] == claim_id:
+ return item
+ cursor = page["next_cursor"]
+ if cursor is None:
+ raise HTTPException(
+ status_code=500,
+ detail=f"claim '{claim_id}' was saved without a temporal row",
+ )
+
+
+def _check_claim_connectors(
+ case: Case,
+ source: dict[str, Any],
+ connectors: dict[str, list[str]],
+) -> None:
+ for type_, targets in connectors.items():
+ for target in dict.fromkeys(targets):
+ target_entity = case.get_entity(target)
+ if type_ == "about" and target_entity is not None and target_entity["type"] == "claim":
+ raise HTTPException(
+ status_code=400,
+ detail=(
+ "A Claim has one date or range. Edit its date, or create a"
+ " separate Claim."
+ ),
+ )
+ try:
+ link_engine.check_relation_target(case, source, target, type_)
+ except CaseError as exc:
+ raise HTTPException(status_code=400, detail=str(exc)) from exc
+
+
[email protected]("/{case_id}/timeline/claims")
+def create_temporal_claim(case_id: str, body: TemporalClaimIn) -> dict[str, Any]:
+ """Create the statement, date and all of its connectors in one transaction."""
+ case = get_case(case_id)
+ statement = body.statement.strip()
+ if not statement:
+ raise HTTPException(status_code=400, detail="a Claim statement cannot be empty")
+ attrs = {
+ key: getattr(body, key)
+ for key in _TEMPORAL_CLAIM_ATTRS
+ if getattr(body, key) is not None
+ }
+ _check_attrs("claim", attrs)
+ connectors = {key: getattr(body, key) for key in _TEMPORAL_CONNECTORS}
+ _check_claim_connectors(case, {"type": "claim"}, connectors)
+ try:
+ saved = case.save_temporal_claim(
+ entity_id=None,
+ label=statement,
+ attrs=attrs,
+ connectors=connectors,
+ by="user",
+ )
+ except CaseError as exc:
+ raise HTTPException(status_code=400, detail=str(exc)) from exc
+ return {**saved, "temporal": _temporal_item(case, saved["entity"]["id"])}
+
+
[email protected]("/{case_id}/timeline/claims/{claim_id}")
+def update_temporal_claim(
+ case_id: str, claim_id: str, body: TemporalClaimPatch
+) -> dict[str, Any]:
+ """Replace a Claim's temporal fields and selected connector sets atomically."""
+ if not body.model_fields_set:
+ raise HTTPException(status_code=400, detail="nothing to update")
+ case = get_case(case_id)
+ current = case.get_entity(claim_id)
+ if current is None:
+ raise HTTPException(status_code=404, detail=f"entity '{claim_id}' not found")
+ if current["type"] != "claim":
+ raise HTTPException(status_code=400, detail=f"entity '{claim_id}' is not a Claim")
+ if "statement" in body.model_fields_set and body.statement is None:
+ raise HTTPException(status_code=400, detail="a Claim statement cannot be empty")
+ statement = (body.statement or current["label"]).strip()
+ if not statement:
+ raise HTTPException(status_code=400, detail="a Claim statement cannot be empty")
+
+ attrs = dict(current.get("attrs") or {})
+ for key in _TEMPORAL_CLAIM_ATTRS:
+ if key in body.model_fields_set:
+ attrs[key] = getattr(body, key)
+ _check_attrs("claim", attrs, current=current.get("attrs") or {})
+ connector_keys = set(_TEMPORAL_CONNECTORS) & body.model_fields_set
+ connectors = (
+ {key: list(getattr(body, key) or []) for key in connector_keys}
+ if connector_keys
+ else None
+ )
+ if connectors is not None:
+ _check_claim_connectors(case, current, connectors)
+ try:
+ saved = case.save_temporal_claim(
+ entity_id=claim_id,
+ label=statement,
+ attrs=attrs,
+ connectors=connectors,
+ by="user",
+ status=body.status or current["provenance"]["status"],
+ )
+ except CaseError as exc:
+ raise HTTPException(status_code=400, detail=str(exc)) from exc
+ return {**saved, "temporal": _temporal_item(case, claim_id)}
+
+
[email protected]("/{case_id}/timeline/claims/{claim_id}")
+def remove_temporal_claim(case_id: str, claim_id: str) -> dict[str, Any]:
+ """Delete one Claim through the normal recoverable Trash workflow."""
+ case = get_case(case_id)
+ entity = case.get_entity(claim_id)
+ if entity is None:
+ raise HTTPException(status_code=404, detail=f"entity '{claim_id}' not found")
+ if entity["type"] != "claim":
+ raise HTTPException(status_code=400, detail=f"entity '{claim_id}' is not a Claim")
+ try:
+ return delete_entity_deep(case, claim_id)
+ except CaseError as exc:
+ raise HTTPException(status_code=400, detail=str(exc)) from exc
+
+
@router.patch("/{case_id}/entities/{entity_id}")
def update_entity(case_id: str, entity_id: str, body: EntityPatch) -> dict[str, Any]:
case = get_case(case_id)
patch = {k: v for k, v in body.model_dump().items() if v is not None}
+ if body.attrs is not None:
+ # Against the type it will have once patched, and the entity has to exist
+ # before its fields can be judged.
+ current = case.get_entity(entity_id)
+ if current is None:
+ raise HTTPException(status_code=404, detail=f"entity '{entity_id}' not found")
+ _check_attrs(
+ body.type or str(current["type"]),
+ body.attrs,
+ current=current.get("attrs") or {},
+ )
try:
entity = case.update_entity(entity_id, patch)
if body.status == "confirmed":
@@ -564,12 +1592,21 @@ def create_link(case_id: str, body: LinkIn) -> dict[str, Any]:
@router.patch("/{case_id}/links/{link_id}")
def update_link(case_id: str, link_id: str, body: LinkPatch) -> dict[str, Any]:
- """Confirm a suggestion, or correct which relation an edge states.
+ """Confirm a suggestion, correct which relation an edge states, rate it, or say
+ what kind of tie it is.
Restating the type goes through the vocabulary, so a 400 means the ontology
has no such reading for those two entities; a missing link is a 404.
+
+ Rating runs last on purpose: confirming a suggestion and rating it can arrive in
+ one request, and a rating is refused on an unreviewed edge — so the confirm has
+ to have landed before the rating is judged. The qualifier runs last for the
+ mirror reason: a reword that drops it must not be undone by a value sent against
+ the verb the edge no longer states.
"""
- if body.status is None and body.type is None:
+ rating = "confidence" in body.model_fields_set
+ qualifying = "nature" in body.model_fields_set
+ if body.status is None and body.type is None and not rating and not qualifying:
raise HTTPException(status_code=400, detail="nothing to update")
case = get_case(case_id)
try:
@@ -582,6 +1619,10 @@ def update_link(case_id: str, link_id: str, body: LinkPatch) -> dict[str, Any]:
link = link_engine.confirm_relation(case, link_id)
elif body.status is not None:
link = case.update_link(link_id, {"status": body.status})
+ if rating:
+ link = link_engine.set_confidence(case, link_id, body.confidence)
+ if qualifying:
+ link = link_engine.set_qualifier(case, link_id, body.nature)
return link
except CaseError as exc:
raise HTTPException(status_code=400, detail=str(exc)) from exc
@@ -631,6 +1672,112 @@ def entity_chain(case_id: str, entity_id: str) -> dict[str, Any]:
return chain
+def _entity_image_error(exc: CaseError) -> HTTPException:
+ status = 404 if "not found" in str(exc) else 400
+ return HTTPException(status_code=status, detail=str(exc))
+
+
[email protected]("/{case_id}/entities/{entity_id}/images")
+def entity_images(case_id: str, entity_id: str) -> dict[str, Any]:
+ """Presentation photos attached to one hand-made entity."""
+ try:
+ images = entity_image_engine.list_images(get_case(case_id), entity_id)
+ except CaseError as exc:
+ raise _entity_image_error(exc) from exc
+ return {"images": images}
+
+
[email protected]("/{case_id}/entities/{entity_id}/images")
+def attach_entity_images(
+ case_id: str, entity_id: str, body: EntityImagesIn
+) -> dict[str, Any]:
+ """Attach existing case images without creating semantic graph links."""
+ try:
+ return entity_image_engine.attach(get_case(case_id), entity_id, body.media_ids)
+ except CaseError as exc:
+ raise _entity_image_error(exc) from exc
+
+
[email protected]("/{case_id}/entities/{entity_id}/images/upload")
+async def upload_entity_image(
+ case_id: str,
+ entity_id: str,
+ file: UploadFile = File(...),
+) -> dict[str, Any]:
+ """Store one private presentation photo outside the Media Library.
+
+ Bounded at the edge like the two other surfaces that swallow an image, and
+ against the same limit: a portrait is a portrait wherever it came from. The
+ pixel clamp further in answers a decompression bomb, not a file that is simply
+ enormous, and refusing early is what keeps a mistaken drag from filling the
+ disk with a temporary nobody asked for.
+ """
+ raw = await file.read(MAX_IMAGE_BYTES + 1)
+ if len(raw) > MAX_IMAGE_BYTES:
+ raise HTTPException(
+ status_code=413,
+ detail=f"photo must be under {MAX_IMAGE_BYTES // 1024 // 1024} MB",
+ )
+ try:
+ return entity_image_engine.import_photo(
+ get_case(case_id), entity_id, BytesIO(raw), file.filename
+ )
+ except CaseError as exc:
+ raise _entity_image_error(exc) from exc
+
+
[email protected]("/{case_id}/entities/{entity_id}/images/{image_id}/primary")
+def set_primary_entity_image(
+ case_id: str, entity_id: str, image_id: str
+) -> dict[str, Any]:
+ try:
+ images = entity_image_engine.set_primary(get_case(case_id), entity_id, image_id)
+ except CaseError as exc:
+ raise _entity_image_error(exc) from exc
+ return {"images": images}
+
+
[email protected]("/{case_id}/entities/{entity_id}/images/{image_id}")
+def detach_entity_image(case_id: str, entity_id: str, image_id: str) -> dict[str, Any]:
+ """Detach a Media reference or delete a private presentation photo."""
+ try:
+ images = entity_image_engine.detach(get_case(case_id), entity_id, image_id)
+ except CaseError as exc:
+ raise _entity_image_error(exc) from exc
+ return {"images": images}
+
+
[email protected]("/{case_id}/entities/{entity_id}/placement")
+def entity_placement(case_id: str, entity_id: str) -> dict[str, Any]:
+ """Where the derivation chain puts this entity, nearest placement first.
+
+ Its own route rather than a field on the chain payload: the chain is read on
+ every Details open and every map popup, and this walks further than one hop.
+ """
+ case = get_case(case_id)
+ placement = satellite_engine.placements(case, entity_id)
+ if placement is None:
+ raise HTTPException(status_code=404, detail=f"entity '{entity_id}' not found")
+ return placement
+
+
[email protected]("/{case_id}/entities/{entity_id}/tally")
+def entity_tally(case_id: str, entity_id: str) -> dict[str, Any]:
+ """What the statements about this entity come to, or 404 when nothing states one.
+
+ Its own route for the same reason placement is: the panel already lists the claims
+ pointing here, and adding them up walks their attributes, which the chain read has
+ no reason to carry on every Details open.
+
+ Over the whole case, never a filter: the panel is not narrowed, so a total obeying
+ a narrowing set on another screen would be a different number under one wording.
+ """
+ row = tally_engine.for_subject(get_case(case_id), entity_id)
+ if row is None:
+ raise HTTPException(status_code=404, detail="no statement is about this entity")
+ return row
+
+
@router.get("/{case_id}/entities/{entity_id}/derivation")
def entity_derivation(case_id: str, entity_id: str) -> dict[str, Any]:
"""The transitive ``derived-from`` closure rooted at this entity as
diff --git a/src/azimut/api/drafts.py b/src/azimut/api/drafts.py
index be3c9fa..5076811 100644
--- a/src/azimut/api/drafts.py
+++ b/src/azimut/api/drafts.py
@@ -1,7 +1,7 @@
"""REST API for post drafts: save, list, load, delete.
A draft is the re-editable state of the Post Composer (thread of tweets built
-from a geolocation). Drafts live in ``<case>/exports/`` as JSON and are indexed
+from a geolocation). Drafts live in ``<case>/.drafts/`` as JSON and are indexed
as ``post`` entities so they show up in the case sidebar (spec §4 — the case is
the product). Azimut never posts on your behalf; a draft is prepared here and the
human publishes it (spec §6 non-goals).
diff --git a/src/azimut/api/ingest.py b/src/azimut/api/ingest.py
index d4eae7f..13ce560 100644
--- a/src/azimut/api/ingest.py
+++ b/src/azimut/api/ingest.py
@@ -344,6 +344,13 @@ def ingest_bookmark(
Nothing is fetched: we store the URL the user is already on, its title and
the source site — a pointer, not a copy. An empty ``case_id`` opens a fresh
scratch session, the same as a screenshot ingest.
+
+ ``fetched_at`` is stamped here, as it is on a capture, and by the server rather
+ than from the request: the extension is standing on the page at this instant, so
+ the moment is known rather than typed, and a browser clock is not a source. A
+ bookmark added by hand in the app carries none — nothing was fetched — and that
+ absence is never flagged. It is what an archived copy is later dated against
+ (ONTOLOGY §2).
"""
split = urlsplit(url)
if split.scheme not in ("http", "https") or not split.hostname:
@@ -354,7 +361,12 @@ def ingest_bookmark(
entity = case.add_entity(
"bookmark",
label,
- {"url": url, "site": split.hostname, "folder": ""},
+ {
+ "url": url,
+ "site": split.hostname,
+ "folder": "",
+ "fetched_at": datetime.now(timezone.utc).isoformat(timespec="seconds"),
+ },
by="ingest",
)
events.publish(
@@ -385,11 +397,42 @@ def _extension_dir() -> Path | None:
return None
+def shipped_extension_files(src: Path) -> list[tuple[str, Path]]:
+ """Every file ``extension.zip`` carries, as ``(posix relative name, path)``
+ sorted by name. Paths are posix so the listing is identical on the three
+ release platforms.
+
+ The version gate in ``tests/test_updates.py`` digests exactly this list, so
+ "what the manifest version claims" and "what the user downloads" cannot
+ drift: a change to a shipped file fails the gate until the version moves.
+
+ Ordered by that posix name rather than by ``Path``, which is the whole point:
+ comparing paths is case-insensitive on Windows and case-sensitive everywhere
+ else, so ``README.md`` sorts first on Linux and mid-list on Windows. The gate
+ digests names in order, so sorting by the object would hand the three release
+ platforms three verdicts about one unchanged extension.
+ """
+ shipped: list[tuple[str, Path]] = []
+ for path in src.rglob("*"):
+ rel = path.relative_to(src)
+ if not path.is_file() or path.name in _ZIP_EXCLUDE_FILES:
+ continue
+ if any(part in _ZIP_EXCLUDE_DIRS or part.endswith(".test.js") for part in rel.parts):
+ continue
+ shipped.append((rel.as_posix(), path))
+ return sorted(shipped, key=lambda entry: entry[0])
+
+
def bundled_extension_version() -> str | None:
"""The ``version`` of the extension this Azimut build ships. Settings
compares it to the version stamped by the *installed* extension
(lib/extBridge.js) so it can flag "an update is bundled — re-download and
- reload". None if no extension is bundled (unusual builds)."""
+ reload". None if no extension is bundled (unusual builds).
+
+ This tracks the extension, not the app: it is the Azimut version whose
+ release last changed a shipped file, so it stays put across releases that
+ leave the extension alone. Bumping it in lock-step with ``__version__``
+ would tell every user to reinstall an identical zip."""
src = _extension_dir()
if src is None:
return None
@@ -414,13 +457,8 @@ def extension_zip() -> Response:
raise HTTPException(status_code=404, detail="extension not bundled with this build")
buf = io.BytesIO()
with zipfile.ZipFile(buf, "w", zipfile.ZIP_DEFLATED) as zf:
- for path in sorted(src.rglob("*")):
- rel = path.relative_to(src)
- if not path.is_file() or path.name in _ZIP_EXCLUDE_FILES:
- continue
- if any(part in _ZIP_EXCLUDE_DIRS or part.endswith(".test.js") for part in rel.parts):
- continue
- zf.write(path, str(rel))
+ for name, path in shipped_extension_files(src):
+ zf.write(path, name)
return Response(
content=buf.getvalue(),
media_type="application/zip",
diff --git a/src/azimut/api/media.py b/src/azimut/api/media.py
index fe7065d..fe666ca 100644
--- a/src/azimut/api/media.py
+++ b/src/azimut/api/media.py
@@ -1,11 +1,15 @@
-"""REST API for the Media Library: upload, URL download (async job), list, delete,
-and copying one file back out to a folder of the analyst's own."""
+"""REST API for the Media Library: upload, clipboard paste, URL download (async
+job), list, delete, and copying one file back out to a folder of the analyst's own."""
from __future__ import annotations
+import io
+import warnings
from typing import Any
+from urllib.parse import urlsplit
-from fastapi import APIRouter, HTTPException, UploadFile
+from fastapi import APIRouter, Form, HTTPException, UploadFile
+from PIL import Image
from pydantic import BaseModel, Field, HttpUrl
from .. import config, jobs
@@ -16,6 +20,7 @@ from ..engine import reveal as reveal_engine
from ..engine import thumbnails as thumbnail_engine
from ..workspace import Case, CaseError
from .cases import delete_by_path, get_case
+from .limits import MAX_IMAGE_BYTES
router = APIRouter(prefix="/api", tags=["media"])
@@ -110,6 +115,7 @@ def page_media(
category: str | None = None,
folder: str | None = None,
gps: bool = False,
+ collected_only: bool = False,
sort: str = "newest",
direction: str | None = None,
limit: int = 200,
@@ -120,6 +126,9 @@ def page_media(
``next_cursor``, so the client filters in memory with no further calls; a
large case pages via ``cursor`` and searches server-side via ``q``.
``gps=true`` keeps only the files whose metadata states a position.
+ ``collected_only=true`` drops what the case made out of its own material — an
+ extracted frame, a collage — and scopes the counts with it; the number it hides
+ comes back as ``facets.made_here_count``.
``facets`` counts the whole filtered set so category/folder/GPS controls stay
accurate. The unbounded ``GET .../media`` stays for consumers that need the
full index (pickers, satellite crops, derivation)."""
@@ -132,6 +141,7 @@ def page_media(
category=category,
folder=folder,
gps=gps,
+ collected_only=collected_only,
sort=sort,
direction=direction,
limit=limit,
@@ -243,6 +253,59 @@ async def upload(case_id: str, file: UploadFile) -> dict[str, Any]:
return result
[email protected]("/cases/{case_id}/media/paste")
+async def paste(
+ case_id: str,
+ file: UploadFile,
+ title: str = Form(default="", max_length=200),
+ source_url: str = Form(default="", max_length=4000),
+) -> dict[str, Any]:
+ """File an image pasted out of the clipboard (lib/clipboardPaste.js).
+
+ Separate from ``upload`` because the provenance differs and provenance is the
+ point: a dropped file states its own name and came off a disk, while a pasted
+ screenshot has neither, so the dialog behind this route is where a title and an
+ origin get stated at all. Both are optional — an unnamed paste is stamped, and a
+ crop of the analyst's own screen honestly has no source.
+
+ Bounded at the edge like every other surface that swallows an image, and against
+ the same limit. The pixel clamp answers a decompression bomb; refusing early is
+ what keeps a mistaken Ctrl+V from writing an enormous temporary nobody asked for.
+ Images only: the clipboard is not a file picker, and a case takes a pasted
+ screenshot, not an arbitrary payload.
+ """
+ raw = await file.read(MAX_IMAGE_BYTES + 1)
+ if len(raw) > MAX_IMAGE_BYTES:
+ raise HTTPException(
+ status_code=413,
+ detail=f"pasted image must be under {MAX_IMAGE_BYTES // 1024 // 1024} MB",
+ )
+ try:
+ # Kept explicit even when a test runner or embedding process installs its
+ # own warning policy after Azimut starts.
+ with warnings.catch_warnings():
+ warnings.simplefilter("error", Image.DecompressionBombWarning)
+ Image.open(io.BytesIO(raw)).verify()
+ except (Image.DecompressionBombWarning, Image.DecompressionBombError) as exc:
+ raise HTTPException(status_code=413, detail="image exceeds the 100 MP limit") from exc
+ except Exception as exc:
+ raise HTTPException(status_code=422, detail=f"not a readable image: {exc}") from exc
+
+ source_url = source_url.strip()
+ if source_url:
+ split = urlsplit(source_url)
+ if split.scheme not in ("http", "https") or not split.hostname:
+ raise HTTPException(status_code=422, detail="the source must be an http(s) URL")
+
+ return media_engine.import_paste(
+ get_case(case_id),
+ file.filename or "pasted-image.png",
+ io.BytesIO(raw),
+ source_url=source_url,
+ title=title,
+ )
+
+
@router.post("/cases/{case_id}/media/download")
def download(case_id: str, body: DownloadIn) -> dict[str, str]:
case = get_case(case_id)
diff --git a/src/azimut/api/notes.py b/src/azimut/api/notes.py
index 8e80012..2465612 100644
--- a/src/azimut/api/notes.py
+++ b/src/azimut/api/notes.py
@@ -27,6 +27,7 @@ from pydantic import BaseModel, Field
from .. import layout
from ..engine import exportdir
+from ..engine import links as link_engine
from ..engine import notes_pdf as pdf_engine
from ..engine import pdffonts
from ..engine import reveal as reveal_engine
@@ -59,6 +60,12 @@ class NoteIn(BaseModel):
title: str = Field(min_length=1, max_length=300)
folder: str = Field(default="", max_length=120)
content: str = ""
+ #: Case-relative paths of the artifacts this note was written from, recorded as
+ #: ``derived-from`` edges. A note typed from scratch sends none; a report note
+ #: composed out of a proof and its media sends every one it embeds, so the chain
+ #: is traversable from either end and deleting a source scars the note instead of
+ #: leaving a dead image link nothing accounts for.
+ sources: list[str] = Field(default_factory=list, max_length=200)
class NoteSelection(BaseModel):
@@ -90,7 +97,19 @@ def write_notes(case_id: str, body: Notes) -> dict[str, str]:
@router.post("/{case_id}/notes")
def create_note(case_id: str, body: NoteIn) -> dict[str, Any]:
- return get_case(case_id).create_note(body.title.strip(), body.folder.strip(), body.content)
+ """File a Markdown note, and record what it was written from.
+
+ ``sources`` goes through the same chain the other composing tools use on save
+ (`api/proofs.py`, `api/drafts.py`): a note assembled out of a proof and its media
+ is an artifact made from case files, so it says so. Without this a report note was
+ the one filed artifact with no chain — its images pointed at case files that
+ nothing in the graph knew it depended on.
+ """
+ case = get_case(case_id)
+ note = case.create_note(body.title.strip(), body.folder.strip(), body.content)
+ if body.sources:
+ link_engine.sync(case, note["id"], link_engine.DERIVED_FROM, body.sources, by="note")
+ return note
@router.get("/{case_id}/notes/{note_id}")
@@ -103,10 +122,22 @@ def read_note(case_id: str, note_id: str) -> dict[str, str]:
@router.put("/{case_id}/notes/{note_id}")
def write_note(case_id: str, note_id: str, body: Notes) -> dict[str, str]:
+ """Save a note's Markdown, and restate what it is made from.
+
+ The body is the note's own statement of which case files it shows, so it is read
+ on every save the way a proof's spec is: an image inserted through the Notebook's
+ Media button gets its ``derived-from`` edge, and one deleted from the text loses
+ it. Only the types the text can name are reconciled — the draft a report was
+ composed in is the composer's to declare, and no wording could restate it.
+ """
+ case = get_case(case_id)
try:
- get_case(case_id).write_note(note_id, body.text)
+ case.write_note(note_id, body.text)
except CaseError as exc:
raise HTTPException(status_code=404, detail=str(exc)) from exc
+ link_engine.sync_embedded(
+ case, note_id, pdf_engine.embedded_entity_ids(body.text), by="note"
+ )
return {"status": "saved"}
diff --git a/src/azimut/api/proofs.py b/src/azimut/api/proofs.py
index e16c524..5adab9c 100644
--- a/src/azimut/api/proofs.py
+++ b/src/azimut/api/proofs.py
@@ -25,6 +25,7 @@ from typing import Any
from fastapi import APIRouter, HTTPException
from pydantic import BaseModel, Field
+from .. import config
from ..engine import artifacts as artifact_engine
from ..engine import exportdir
from ..engine import links as link_engine
@@ -36,6 +37,7 @@ from ..workspace import Case, CaseError, ensure_dir
from .cases import delete_by_path, get_case
from .drafts import list_drafts
from .naming import read_created_at, slugify
+from .satellite import locate_on_save
from .. import layout
router = APIRouter(prefix="/api", tags=["proofs"])
@@ -59,6 +61,13 @@ class AssetIn(BaseModel):
data: str # base64 body
+class ProofPlaceIn(BaseModel):
+ """The point the composer asked about, answered yes."""
+
+ lat: float = Field(ge=-90, le=90)
+ lon: float = Field(ge=-180, le=180)
+
+
class ProofIn(BaseModel):
# The filename always follows the title, so renaming a saved proof moves its
# spec and its export. ``rename_from`` is the stem the composer is currently
@@ -355,6 +364,12 @@ def save_proof(case_id: str, body: ProofIn) -> dict[str, Any]:
# a spec-only proof exported later gains its PNG here — without the
# path the sidebar preview and delete_by_path can't see the file
attrs["path"] = png_rel
+ # The thumbnail travels on the entity as well as in the spec, so a surface
+ # drawing a proof beside other entities — the graph draws a few hundred at
+ # once — reads it off the row it already has instead of opening one JSON
+ # file per proof.
+ if thumb_rel and existing["attrs"].get("thumb") != thumb_rel:
+ attrs["thumb"] = thumb_rel
if attrs:
patch["attrs"] = attrs
case.update_entity(existing["id"], patch)
@@ -363,7 +378,11 @@ def save_proof(case_id: str, body: ProofIn) -> dict[str, Any]:
entity_id = case.add_entity(
"proof",
name,
- attrs={"spec": rel, **({"path": png_rel} if png_rel else {})},
+ attrs={
+ "spec": rel,
+ **({"path": png_rel} if png_rel else {}),
+ **({"thumb": thumb_rel} if thumb_rel else {}),
+ },
by="proof-composer",
)["id"]
if old_rel:
@@ -380,15 +399,114 @@ def save_proof(case_id: str, body: ProofIn) -> dict[str, Any]:
by="proof-composer",
)
+ place, released = _place_for(case, entity_id, spec)
return {
"name": name,
"title": name,
"png": png_rel,
"thumb": thumb_rel,
"spec_path": rel,
+ "place": place,
+ # points this save moved off that nothing holds any more; the composer asks
+ "orphans": [{"id": e["id"], "label": e["label"]} for e in released],
}
+def _place_for(
+ case: Case, proof_id: str, spec: dict[str, Any]
+) -> tuple[dict[str, Any] | None, list[dict[str, Any]]]:
+ """File the point this proof carries, or hand the composer the question.
+
+ A proof is where a geolocation is concluded, so its point is what becomes a
+ node — once, here, rather than on every capture taken while looking for it.
+ ``proof_place_auto`` decides which of the two happens; neither is a
+ suggestion, because both spell out the analyst's own answer.
+
+ Every path restates what the proof says (``satellite.restate_proof_point``),
+ which is what makes a *re*-save mean something: corrected coordinates move the
+ edges instead of adding a second set, and a POV answer changed on the way back
+ through changes the verb. The first half of the answer is the question to ask,
+ ``None`` when there is none — **a point the case already holds is neither
+ filed twice nor asked about**, so a proof re-saved untouched stays silent while
+ still restating what it says. The second half is the points it let go of.
+ """
+ point = satellite_engine.own_point(spec)
+ pov = bool(spec.get("pov"))
+ if point is None:
+ # the coordinate field was cleared: the proof withdraws the point it stated
+ return None, satellite_engine.restate_proof_point(case, proof_id, None, pov=pov)
+ standing = satellite_engine.place_at(case, point["lat"], point["lon"], keyed_only=False)
+ if standing is not None:
+ # nothing to file, so nothing to ask — but the proof still says it is there
+ return None, satellite_engine.restate_proof_point(
+ case, proof_id, standing["id"], pov=pov
+ )
+ if not config.load_settings().get("proof_place_auto", True):
+ # the point moved somewhere the case cannot hold yet: the old claim is
+ # withdrawn either way, and the new one waits on the analyst's yes
+ released = satellite_engine.restate_proof_point(case, proof_id, None, pov=pov)
+ return {
+ "filed": False,
+ "lat": point["lat"],
+ "lon": point["lon"],
+ # so the question can say what the point will mean
+ "pov": pov,
+ }, released
+ place, released = file_proof_place(case, proof_id, point["lat"], point["lon"], pov=pov)
+ return {"filed": True, "id": place["id"], "label": place["label"]}, released
+
+
+def file_proof_place(
+ case: Case, proof_id: str, lat: float, lon: float, *, pov: bool = False
+) -> tuple[dict[str, Any], list[dict[str, Any]]]:
+ """Write the place, then resolve its country, as every other place save does.
+
+ Shared by the automatic path above and the composer's own answer to the
+ question, so both leave exactly the same trace.
+ """
+ place, released = satellite_engine.place_for_proof(case, proof_id, lat, lon, pov=pov)
+ locate_on_save(case, place["id"], lat, lon)
+ return place, released
+
+
[email protected]("/cases/{case_id}/proofs/{name}/place")
+def save_proof_place(case_id: str, name: str, body: ProofPlaceIn) -> dict[str, Any]:
+ """File the point of a proof the composer just asked the analyst about.
+
+ The other half of ``proof_place_auto`` being off: the save reported a point
+ with nowhere to live, the composer asked, and this is the yes. It re-checks
+ that nothing stands there, so two open tabs answering the same question file
+ one place rather than two.
+ """
+ case = get_case(case_id)
+ proof = case.find_entity(attr="spec", value=layout.proof_spec_rel(slugify(name, "proof")))
+ if proof is None:
+ raise HTTPException(status_code=404, detail="no such proof")
+ # POV is read off the spec on disk rather than taken from the body: it is a
+ # property of the proof that was just saved, not of the answer to the question.
+ pov = bool(_read_spec(case, proof).get("pov"))
+ existing = satellite_engine.place_at(case, body.lat, body.lon, keyed_only=False)
+ if existing is not None:
+ # somebody filed that point between the question and the yes: the proof
+ # joins the place standing there rather than minting a second one
+ satellite_engine.restate_proof_point(case, proof["id"], existing["id"], pov=pov)
+ return existing
+ place, _released = file_proof_place(case, proof["id"], body.lat, body.lon, pov=pov)
+ return place
+
+
+def _read_spec(case: Case, proof: dict[str, Any]) -> dict[str, Any]:
+ """The saved spec of a proof, or an empty one if it cannot be read."""
+ rel = (proof.get("attrs") or {}).get("spec")
+ if not isinstance(rel, str) or not rel:
+ return {}
+ try:
+ loaded = json.loads(case.resolve_inside(rel).read_text(encoding="utf-8"))
+ except (OSError, ValueError, CaseError):
+ return {}
+ return loaded if isinstance(loaded, dict) else {}
+
+
@router.delete("/cases/{case_id}/proofs/{name}")
def delete_proof(case_id: str, name: str) -> dict[str, Any]:
case = get_case(case_id)
diff --git a/src/azimut/api/satellite.py b/src/azimut/api/satellite.py
index fcb4d53..08e94a6 100644
--- a/src/azimut/api/satellite.py
+++ b/src/azimut/api/satellite.py
@@ -7,7 +7,6 @@ import math
import os
import re
import tempfile
-import time
# Aliased: this module already imports the ``time`` module for tile timing, and
# the sky routes need the datetime classes of the same names.
from datetime import date as calendar_date, datetime, time as wall_clock, timezone
@@ -615,6 +614,79 @@ def sky_for_point(
}
+#: How wide a window the daylight ribbon answers for.
+#:
+#: Both a cost bound and a legibility one, and they land in the same place. The search
+#: is linear in the window and this route walks it twice, once per threshold: measured
+#: at 65 ms for a week and 170 ms for a month, per run. And a ribbon drawn over more
+#: than a month is stripes a few pixels wide, which is moiré rather than a reading —
+#: while the axis it sits under is panned, so the request repeats. Past this the answer
+#: is empty and says it was cut, the way every other bounded read here does.
+MAX_DAYLIGHT_DAYS = 31
+
+
+def _instant(value: str, field: str) -> datetime:
+ try:
+ parsed = datetime.fromisoformat(value.replace("Z", "+00:00"))
+ except ValueError as exc:
+ raise HTTPException(
+ status_code=422, detail=f"{field} must be an ISO 8601 instant"
+ ) from exc
+ return parsed if parsed.tzinfo else parsed.replace(tzinfo=timezone.utc)
+
+
[email protected]("/geo/daylight")
+def daylight_for_window(
+ lat: float = Query(ge=-90, le=90),
+ lon: float = Query(ge=-180, le=180),
+ start: str = Query(alias="from"),
+ end: str = Query(alias="to"),
+) -> dict[str, Any]:
+ """When it was light at a point, over a window, plus that point's civil zone.
+
+ Pure computation like ``/geo/sky``: nothing here reaches the network, and the
+ zone comes from the bundled boundaries (``engine.localtime``) rather than from a
+ lookup service.
+
+ Two runs of spans, because dusk is not a line: ``day`` is the sun above the
+ horizon and ``civil`` is it above −6°, so a caller can draw the hour in between
+ as what it is. Instants are UTC — the axis they land on is UTC underneath
+ whatever clock it is labelled with.
+ """
+ first = _instant(start, "from")
+ last = _instant(end, "to")
+ if last <= first:
+ raise HTTPException(status_code=422, detail="to must come after from")
+ zone_name = localtime.zone_for(lat, lon)
+ stamped = localtime.both(first, zone_name) or {}
+ zone = {
+ "name": zone_name,
+ "abbreviation": stamped.get("abbreviation"),
+ "offset": stamped.get("offset"),
+ "offset_minutes": stamped.get("offset_minutes"),
+ }
+ if (last - first).total_seconds() > MAX_DAYLIGHT_DAYS * 86_400:
+ return {"lat": lat, "lon": lon, "zone": zone, "day": [], "civil": [], "truncated": True}
+
+ def spans(threshold: float) -> list[dict[str, str]]:
+ return [
+ {
+ "from": span["from"].isoformat().replace("+00:00", "Z"),
+ "to": span["to"].isoformat().replace("+00:00", "Z"),
+ }
+ for span in sky.daylight_spans(lat, lon, first, last, threshold)
+ ]
+
+ return {
+ "lat": lat,
+ "lon": lon,
+ "zone": zone,
+ "day": spans(sky.SUN_HORIZON_DEG),
+ "civil": spans(sky.TWILIGHTS["civil"]),
+ "truncated": False,
+ }
+
+
@router.post("/cases/{case_id}/satellite/capture")
def capture(case_id: str, body: CaptureIn) -> dict[str, Any]:
case = get_case(case_id)
@@ -808,11 +880,6 @@ def saved_index(case_id: str) -> list[dict[str, Any]]:
return satellite_engine.saved_index(get_case(case_id))
-# Nominatim asks for at most one request a second. A backfill is the only place
-# we make more than one lookup in a row, so it is the only place that waits.
-NOMINATIM_INTERVAL = 1.1
-
-
@router.post("/cases/{case_id}/satellite/locate")
def locate_saved(
case_id: str, limit: int = Query(default=10, ge=1, le=25)
@@ -822,11 +889,16 @@ def locate_saved(
Progress is the stored geography itself, so the pass resumes after a restart
and re-running it is a no-op: ``remaining`` is what the client loops on. The
cap keeps one request comfortably inside a timeout at Nominatim's one-per-
- second pace.
+ second pace, which ``engine.geo`` holds in front of every lookup — including
+ the second one ``locate_point`` makes for the English region name, which no
+ caller can see and which used to double the real pace.
+
+ ``throttled`` says Nominatim answered 429. A batch that resolved nothing
+ because the address is in the penalty box is not the same event as a batch of
+ genuine lookup failures, and the client must be able to say which.
"""
case = get_case(case_id)
located = failed = 0
- looked_up = False
for entity in satellite_engine.unlocated_entities(case, limit):
attrs = entity.get("attrs") or {}
lat, lon = attrs.get("lat"), attrs.get("lon")
@@ -835,9 +907,6 @@ def locate_saved(
satellite_engine.set_geo(case, entity["id"], {"state": "nocoords"})
located += 1
continue
- if looked_up:
- time.sleep(NOMINATIM_INTERVAL)
- looked_up = True
result = geo.locate_point(float(lat), float(lon))
satellite_engine.set_geo(case, entity["id"], result)
if result["state"] == "failed":
@@ -848,6 +917,7 @@ def locate_saved(
"located": located,
"failed": failed,
"remaining": len(satellite_engine.unlocated_entities(case)),
+ "throttled": geo.throttled(),
}
diff --git a/src/azimut/api/settings.py b/src/azimut/api/settings.py
index 4ad1753..cbecb14 100644
--- a/src/azimut/api/settings.py
+++ b/src/azimut/api/settings.py
@@ -96,6 +96,8 @@ class PrefsIn(BaseModel):
coord_format: str | None = None # one of config.COORD_FORMATS
units: str | None = None # one of config.UNIT_SYSTEMS
home_view: HomeView | None = None # where the Satellite tab opens
+ # whether saving a proof files its point as a place, or asks first
+ proof_place_auto: bool | None = None
post_mention: str | None = None # handle a new post draft is addressed to
post_target: str | None = None # social composer a new post draft starts with
signature_handle: str | None = None # account handle stamped on opted-in proofs
@@ -122,6 +124,7 @@ def _prefs(settings: dict[str, Any]) -> dict[str, Any]:
"coord_format": settings.get("coord_format", "dd"),
"units": settings.get("units", "metric"),
"home_view": settings.get("home_view", DEFAULT_HOME_VIEW),
+ "proof_place_auto": bool(settings.get("proof_place_auto", True)),
"post_mention": settings.get("post_mention", DEFAULT_POST_MENTION),
"post_target": settings.get("post_target", DEFAULT_POST_TARGET),
"signature_handle": settings.get("signature_handle", DEFAULT_SIGNATURE_HANDLE),
@@ -247,6 +250,8 @@ def _apply_prefs(settings: dict[str, Any], body: PrefsIn) -> None:
settings["units"] = body.units
if body.home_view is not None:
settings["home_view"] = body.home_view.model_dump()
+ if body.proof_place_auto is not None:
+ settings["proof_place_auto"] = bool(body.proof_place_auto)
if body.post_mention is not None:
settings["post_mention"] = body.post_mention.strip()[:64]
if body.post_target is not None:
@@ -560,6 +565,7 @@ class ImportedSettings(BaseModel):
home_view: ImportedHomeView = Field(
default_factory=lambda: ImportedHomeView.model_validate(DEFAULT_HOME_VIEW)
)
+ proof_place_auto: bool = True
post_mention: str = Field(default=DEFAULT_POST_MENTION, max_length=64)
post_target: Literal["x", "bluesky", "mastodon"] = DEFAULT_POST_TARGET
signature_handle: str = Field(default=DEFAULT_SIGNATURE_HANDLE, max_length=64)
diff --git a/src/azimut/config.py b/src/azimut/config.py
index d80e609..1d002aa 100644
--- a/src/azimut/config.py
+++ b/src/azimut/config.py
@@ -99,6 +99,14 @@ DEFAULT_SETTINGS: dict[str, Any] = {
# Where the Satellite tab opens before anything points it somewhere else
# (a case artifact, a "go to coords" handoff). {"lat", "lon", "zoom"}.
"home_view": {"lat": 48.8584, "lon": 2.2945, "zoom": 16},
+ # Saving a proof files the point it carries as a `place`, joined by `depicts`
+ # (engine/satellite.place_for_proof). A geolocation is concluded in the
+ # composer, not while framing the map, so the point becomes a node once —
+ # where somebody committed to it — rather than on every capture taken while
+ # looking. On, the save files it; off, the composer asks first. Either way it
+ # is the analyst's own answer, so nothing here is ever `suggested`, and a
+ # point the case already holds is neither filed twice nor asked about.
+ "proof_place_auto": True,
# The handle a new post draft is addressed to. Empty means no mention.
"post_mention": "@GeoConfirmed",
# The social composer a new post draft starts with. A saved draft keeps its
diff --git a/src/azimut/engine/analysis_views.py b/src/azimut/engine/analysis_views.py
new file mode 100644
index 0000000..0d5991f
--- /dev/null
+++ b/src/azimut/engine/analysis_views.py
@@ -0,0 +1,619 @@
+"""Saved Board, Graph and Timeline readings.
+
+A live view is a recipe: the Search+ question is asked again whenever it opens. A
+snapshot is evidence of a reading at one moment, so it stores copies of the matching
+entities and the links among them. Both live in the case database and therefore move
+with a bundle without becoming semantic graph entities.
+
+Views come in two families: Board and Graph share one question of the catalog, the
+Timeline reads time. See `family()`.
+"""
+
+from __future__ import annotations
+
+import base64
+import binascii
+import json
+import re
+from datetime import datetime, timezone
+from typing import Any, cast
+
+from ..repository import EntityStatus
+from ..workspace import Case, CaseError
+from .temporal import TemporalError, window_bound
+
+VERSION = 1
+MAX_SPEC_BYTES = 8 * 1024 * 1024
+MAX_SNAPSHOT_ENTITIES = 2000
+MAX_SNAPSHOT_LINKS = 10000
+MAX_SNAPSHOT_TIMELINE_ITEMS = 5000
+MAX_SNAPSHOT_PREVIEW_BYTES = 4 * 1024 * 1024
+MAX_ONE_PREVIEW_BYTES = 512 * 1024
+
+
+def _now() -> str:
+ return datetime.now(timezone.utc).isoformat(timespec="seconds").replace("+00:00", "Z")
+
+
+def family(surface: Any) -> str:
+ """Which family of tools a saved view belongs to.
+
+ Board and Graph ask one question of the catalog and share their views. The Timeline
+ asks about time — tracks, a window, a clock — and shares with neither, so the two
+ are separate namespaces: a name taken in one is free in the other.
+ """
+ return "timeline" if surface == "timeline" else "catalog"
+
+
+def summary(view: dict[str, Any]) -> dict[str, Any]:
+ """The bounded row a view menu needs, without its snapshot payload."""
+ return {key: value for key, value in view.items() if key != "spec"}
+
+
+def _short(value: Any, limit: int) -> str:
+ text = str(value or "").strip()
+ return text[:limit]
+
+
+def _query_terms(spec: dict[str, Any]) -> dict[str, str]:
+ query = spec.get("query")
+ raw = query.get("terms") if isinstance(query, dict) else None
+ if not isinstance(raw, dict):
+ return {}
+ allowed = {
+ "type", "status", "q", "folder", "unfiled", "recursive", "attr",
+ "value", "linked", "unlinked", "since", "until", "by",
+ }
+ return {
+ key: _short(value, 1000)
+ for key, value in raw.items()
+ if key in allowed and value not in (None, "")
+ }
+
+
+def _bound(raw: Any, *, upper: bool) -> str | None:
+ """One end of the window a capture freezes, read the way the live view reads it.
+
+ A snapshot answers the question its view was showing, so both ends go through the
+ same reader as the route: a period saved as `2024-03` has to freeze March, not
+ stop at its first instant.
+ """
+ if not raw:
+ return None
+ try:
+ return window_bound(str(raw), upper=upper)
+ except TemporalError as exc:
+ raise CaseError(str(exc)) from exc
+
+
+def _string_list(value: Any, *, limit: int = 100, item_limit: int = 160) -> list[str]:
+ if not isinstance(value, list):
+ return []
+ return list(dict.fromkeys(
+ _short(item, item_limit) for item in value[:limit] if _short(item, item_limit)
+ ))
+
+
+#: The colours a track may be given, by name — the frontend's own palette
+#: (`lib/timelineTracks.js`). An unset colour means the lane keeps the colours of the
+#: categories it holds.
+TRACK_COLORS = ("red", "blue", "amber", "green", "magenta", "orange")
+
+
+def _clean_track(value: Any, index: int) -> dict[str, Any]:
+ if not isinstance(value, dict):
+ raise CaseError("timeline track is invalid")
+ track_id = _short(value.get("id"), 64) or f"track-{index + 1}"
+ label = _short(value.get("label"), 80) or f"Track {index + 1}"
+ categories = [
+ category for category in _string_list(value.get("categories"), limit=3, item_limit=40)
+ if category in {"statement", "media", "case_activity"}
+ ]
+ if not categories:
+ raise CaseError(f"timeline track '{label}' needs a category")
+ query: dict[str, Any] = (
+ value["query"] if isinstance(value.get("query"), dict) else {}
+ )
+ filter_ = query.get("filter") if isinstance(query.get("filter"), dict) else {}
+ roles = [
+ role for role in _string_list(query.get("roles"), limit=4, item_limit=24)
+ if role in {"occurred", "observed", "valid", "unset"}
+ ]
+ relation = query.get("relation")
+ if relation not in {"any", "owner", "about", "place", "source"}:
+ relation = "any"
+ color = _short(value.get("color"), 16)
+ return {
+ "id": track_id,
+ "label": label,
+ "color": color if color in TRACK_COLORS else "",
+ "categories": categories,
+ "query": {
+ "filter": filter_,
+ "terms": _query_terms({"query": {"terms": query.get("terms")}}),
+ "label": _short(query.get("label"), 300),
+ "relation": relation,
+ "roles": roles,
+ },
+ "collapsed": bool(value.get("collapsed")),
+ "hidden": _string_list(value.get("hidden"), limit=500),
+ "pinned": _string_list(value.get("pinned"), limit=500),
+ }
+
+
+_ZONE_NAME = re.compile(r"[A-Za-z0-9+\-_/]{1,64}")
+
+
+def _valid_zone_choice(choice: str) -> bool:
+ """Which clock the axis was read on: UTC, this machine, a saved point, or a zone
+ named outright. The last one has to travel — a view made on `zone:Asia/Tokyo` must
+ not come back on UTC — so the name is kept whether or not the machine reopening it
+ can load the name; the axis asks that when it draws."""
+ if choice in {"utc", "machine"}:
+ return True
+ if choice.startswith("place:"):
+ rest = choice.removeprefix("place:")
+ return bool(rest) and not any(character.isspace() for character in rest)
+ if choice.startswith("zone:"):
+ return bool(_ZONE_NAME.fullmatch(choice.removeprefix("zone:")))
+ return False
+
+
+def _clean_timeline(value: Any, *, surface: str) -> dict[str, Any]:
+ raw = value if isinstance(value, dict) else {}
+ if surface != "timeline":
+ categories = [
+ category
+ for category in _string_list(raw.get("categories"), limit=3, item_limit=40)
+ if category in {"statement", "media", "case_activity"}
+ ]
+ return {
+ "from": _short(raw.get("from"), 40) or None,
+ "to": _short(raw.get("to"), 40) or None,
+ "field": _short(raw.get("field"), 64) or None,
+ "categories": categories or ["statement", "media"],
+ }
+ tracks_raw: list[Any] = (
+ raw["tracks"] if isinstance(raw.get("tracks"), list) else []
+ )
+ if len(tracks_raw) > 20:
+ raise CaseError("a timeline view holds at most 20 tracks")
+ tracks = [_clean_track(track, index) for index, track in enumerate(tracks_raw)]
+ ids = [track["id"] for track in tracks]
+ if len(ids) != len(set(ids)):
+ raise CaseError("timeline track ids must be unique")
+ if surface == "timeline" and not tracks:
+ tracks = [
+ _clean_track({"id": "events", "label": "Events", "categories": ["statement"]}, 0),
+ _clean_track({"id": "media", "label": "Media", "categories": ["media"]}, 1),
+ ]
+ entity = raw.get("entity") if isinstance(raw.get("entity"), dict) else None
+ zone_choice = _short(raw.get("zone_choice"), 72)
+ if not _valid_zone_choice(zone_choice):
+ zone_choice = "utc"
+ return {
+ "from": _short(raw.get("from"), 40) or None,
+ "to": _short(raw.get("to"), 40) or None,
+ "field": _short(raw.get("field"), 64) or None,
+ "timezone": _short(raw.get("timezone"), 80) or "UTC",
+ "zone_choice": zone_choice,
+ "view_mode": raw.get("view_mode") if raw.get("view_mode") in {"plot", "list"} else "plot",
+ "group_by": (
+ raw.get("group_by")
+ if raw.get("group_by") in {"none", "subject", "type", "place", "source", "role"}
+ else "none"
+ ),
+ "tracks": tracks,
+ # Kept in the serialized view for compatibility. Tracks own category
+ # selection, so there is no second visibility switch to reconcile.
+ "visible_categories": list(
+ dict.fromkeys(category for track in tracks for category in track["categories"])
+ ),
+ "entity": (
+ {"id": _short(entity.get("id"), 64), "label": _short(entity.get("label"), 300)}
+ if entity and _short(entity.get("id"), 64) else None
+ ),
+ }
+
+
+def _preview_data(case: Case, rel: Any, budget: list[int]) -> str | None:
+ if not isinstance(rel, str) or not rel:
+ return None
+ try:
+ path = case.resolve_inside(rel)
+ size = path.stat().st_size
+ except (CaseError, OSError):
+ return None
+ if size > MAX_ONE_PREVIEW_BYTES:
+ raise CaseError("one captured preview is too large; use a smaller thumbnail")
+ if budget[0] + size > MAX_SNAPSHOT_PREVIEW_BYTES:
+ raise CaseError("snapshot previews are too large; narrow the view")
+ try:
+ raw = path.read_bytes()
+ except OSError:
+ return None
+ budget[0] += len(raw)
+ suffix = path.suffix.casefold()
+ mime = {
+ ".png": "image/png",
+ ".webp": "image/webp",
+ ".gif": "image/gif",
+ }.get(suffix, "image/jpeg")
+ return f"data:{mime};base64,{base64.b64encode(raw).decode('ascii')}"
+
+
+def _capture_previews(case: Case, captured: list[dict[str, Any]]) -> None:
+ """Embed bounded gallery thumbnails so a frozen row keeps its visual identity."""
+ budget = [0]
+ media = case.media_thumbs([entity["id"] for entity in captured])
+ for entity in captured:
+ previews: list[dict[str, Any]] = []
+ for image in case.entity_images(entity["id"]):
+ data = _preview_data(case, image.get("thumbnail") or image.get("path"), budget)
+ if data:
+ previews.append({
+ "id": _short(image.get("id"), 64),
+ "title": _short(image.get("title"), 300) or "Photo",
+ "primary": bool(image.get("primary")),
+ "data": data,
+ })
+ own = _preview_data(case, media.get(entity["id"]), budget)
+ if own and not previews:
+ previews.append({"id": "preview", "title": "Preview", "primary": True, "data": own})
+ if previews:
+ entity["snapshot_images"] = previews
+ primary = next((image for image in previews if image["primary"]), previews[0])
+ entity["thumb"] = primary["data"]
+
+
+def _capture(case: Case, spec: dict[str, Any]) -> dict[str, Any]:
+ ids = spec.pop("capture_ids", None)
+ if ids is not None:
+ if not isinstance(ids, list) or any(not isinstance(one, str) for one in ids):
+ raise CaseError("snapshot capture ids are invalid")
+ wanted = list(dict.fromkeys(ids))
+ if len(wanted) > MAX_SNAPSHOT_ENTITIES:
+ raise CaseError(
+ f"a snapshot view holds at most {MAX_SNAPSHOT_ENTITIES} entities; narrow the view"
+ )
+ entities = case.entities_by_ids(wanted)
+ else:
+ terms = _query_terms(spec)
+ saved_period = spec.get("timeline")
+ temporal: dict[str, Any] = saved_period if isinstance(saved_period, dict) else {}
+ types = [part for part in terms.get("type", "").split(",") if part]
+ filed_by = [part for part in terms.get("by", "").split(",") if part]
+ page = case.page_entities(
+ limit=MAX_SNAPSHOT_ENTITIES + 1,
+ types=types or None,
+ status=(
+ cast(EntityStatus, terms["status"])
+ if terms.get("status") in {"confirmed", "suggested"}
+ else None
+ ),
+ query=terms.get("q"),
+ folder=terms.get("folder"),
+ unfiled=terms.get("unfiled") == "true",
+ recursive=terms.get("recursive") == "true",
+ attr=terms.get("attr"),
+ attr_value=terms.get("value"),
+ linked=terms.get("linked"),
+ unlinked=terms.get("unlinked") == "true",
+ since=terms.get("since"),
+ until=terms.get("until"),
+ filed_by=filed_by or None,
+ temporal_since=_bound(temporal.get("from"), upper=False),
+ temporal_until=_bound(temporal.get("to"), upper=True),
+ temporal_categories=temporal.get("categories"),
+ )
+ entities = list(page["items"])
+ if page["total"] > MAX_SNAPSHOT_ENTITIES:
+ raise CaseError(
+ f"a snapshot view holds at most {MAX_SNAPSHOT_ENTITIES} entities; narrow the question"
+ )
+ _capture_previews(case, entities)
+ entity_ids = [entity["id"] for entity in entities]
+ links = case.links_among(entity_ids) if entity_ids else []
+ if len(links) > MAX_SNAPSHOT_LINKS:
+ raise CaseError(
+ f"a snapshot view holds at most {MAX_SNAPSHOT_LINKS} relations; narrow the question"
+ )
+ return {"captured_at": _now(), "entities": entities, "links": links}
+
+
+def _clean_preview(value: Any, budget: list[int]) -> str:
+ text = str(value or "")
+ allowed = (
+ "data:image/jpeg;base64,",
+ "data:image/png;base64,",
+ "data:image/webp;base64,",
+ "data:image/gif;base64,",
+ )
+ prefix = next((entry for entry in allowed if text.startswith(entry)), None)
+ if prefix is None:
+ raise CaseError("snapshot preview is invalid")
+ try:
+ raw = base64.b64decode(text[len(prefix):], validate=True)
+ except (ValueError, binascii.Error) as exc:
+ raise CaseError("snapshot preview is invalid") from exc
+ if len(raw) > MAX_ONE_PREVIEW_BYTES:
+ raise CaseError("snapshot preview is too large")
+ budget[0] += len(raw)
+ if budget[0] > MAX_SNAPSHOT_PREVIEW_BYTES:
+ raise CaseError("snapshot previews are too large")
+ return text
+
+
+def _clean_snapshot(value: Any) -> dict[str, Any]:
+ """Validate a snapshot copied inside its case."""
+ if not isinstance(value, dict):
+ raise CaseError("snapshot data is missing")
+ entities = value.get("entities", [])
+ links = value.get("links", [])
+ timeline_items = value.get("timeline_items", [])
+ if (
+ not isinstance(entities, list)
+ or not isinstance(links, list)
+ or not isinstance(timeline_items, list)
+ ):
+ raise CaseError("snapshot data is invalid")
+ if (
+ len(entities) > MAX_SNAPSHOT_ENTITIES
+ or len(links) > MAX_SNAPSHOT_LINKS
+ or len(timeline_items) > MAX_SNAPSHOT_TIMELINE_ITEMS
+ ):
+ raise CaseError("snapshot data is too large")
+ clean_entities: list[dict[str, Any]] = []
+ ids: set[str] = set()
+ preview_budget = [0]
+ for entity in entities:
+ if not isinstance(entity, dict):
+ raise CaseError("snapshot entity is invalid")
+ entity_id = _short(entity.get("id"), 64)
+ type_ = _short(entity.get("type"), 40)
+ label = _short(entity.get("label"), 300)
+ if not entity_id or not type_ or not label or entity_id in ids:
+ raise CaseError("snapshot entity is invalid")
+ ids.add(entity_id)
+ raw_images = entity.get("snapshot_images") or []
+ if not isinstance(raw_images, list):
+ raise CaseError("snapshot previews are invalid")
+ images = []
+ for image in raw_images:
+ if not isinstance(image, dict):
+ raise CaseError("snapshot preview is invalid")
+ images.append({
+ "id": _short(image.get("id"), 64),
+ "title": _short(image.get("title"), 300) or "Photo",
+ "primary": bool(image.get("primary")),
+ "data": _clean_preview(image.get("data"), preview_budget),
+ })
+ clean_entity: dict[str, Any] = {
+ "id": entity_id,
+ "type": type_,
+ "label": label,
+ "attrs": entity.get("attrs") if isinstance(entity.get("attrs"), dict) else {},
+ "provenance": entity.get("provenance")
+ if isinstance(entity.get("provenance"), dict) else {},
+ }
+ if images:
+ clean_entity["snapshot_images"] = images
+ clean_entity["thumb"] = next(
+ (image["data"] for image in images if image["primary"]), images[0]["data"]
+ )
+ clean_entities.append(clean_entity)
+ clean_links: list[dict[str, Any]] = []
+ link_ids: set[str] = set()
+ for link in links:
+ if not isinstance(link, dict):
+ raise CaseError("snapshot relation is invalid")
+ link_id = _short(link.get("id"), 64)
+ from_id = _short(link.get("from"), 64)
+ to_id = _short(link.get("to"), 64)
+ type_ = _short(link.get("type"), 40)
+ if (
+ not link_id or link_id in link_ids or from_id not in ids or to_id not in ids
+ or not type_
+ ):
+ raise CaseError("snapshot relation is invalid")
+ link_ids.add(link_id)
+ clean_links.append({
+ "id": link_id,
+ "from": from_id,
+ "to": to_id,
+ "type": type_,
+ "provenance": link.get("provenance")
+ if isinstance(link.get("provenance"), dict) else {},
+ **({"confidence": link["confidence"]} if "confidence" in link else {}),
+ **({"nature": link["nature"]} if "nature" in link else {}),
+ })
+ clean_timeline: list[dict[str, Any]] = []
+ temporal_ids: set[str] = set()
+
+ def references(item: dict[str, Any], key: str) -> list[dict[str, str]]:
+ raw = item.get(key)
+ if not isinstance(raw, list):
+ return []
+ clean = []
+ for entry in raw[:100]:
+ if not isinstance(entry, dict):
+ continue
+ entity_id = _short(entry.get("id"), 64)
+ if entity_id:
+ clean.append({
+ "id": entity_id,
+ "label": _short(entry.get("label"), 300) or entity_id,
+ "type": _short(entry.get("type"), 40),
+ })
+ return clean
+
+ for item in timeline_items:
+ if not isinstance(item, dict):
+ raise CaseError("snapshot timeline entry is invalid")
+ temporal_id = _short(item.get("id"), 160)
+ owner_id = _short(item.get("owner_id"), 64)
+ category = _short(item.get("category"), 40)
+ label = _short(item.get("label"), 300)
+ if (
+ not temporal_id or temporal_id in temporal_ids or not owner_id
+ or category not in {"statement", "media", "case_activity"} or not label
+ ):
+ raise CaseError("snapshot timeline entry is invalid")
+ temporal_ids.add(temporal_id)
+ clean_timeline.append({
+ "id": temporal_id,
+ "owner_id": owner_id,
+ "authority": _short(item.get("authority"), 40),
+ "category": category,
+ "kind": _short(item.get("kind"), 40),
+ "label": label,
+ "raw": _short(item.get("raw"), 100) or None,
+ "earliest": _short(item.get("earliest"), 40) or None,
+ "latest": _short(item.get("latest"), 40) or None,
+ "precision": _short(item.get("precision"), 24) or None,
+ "shape": _short(item.get("shape"), 24) or None,
+ "time_role": _short(item.get("time_role"), 24) or None,
+ "uncertain": bool(item.get("uncertain")),
+ "approximate": bool(item.get("approximate")),
+ "zone": _short(item.get("zone"), 24) or None,
+ "sortable": bool(item.get("sortable")),
+ "status": _short(item.get("status"), 24) or None,
+ "confidence": _short(item.get("confidence"), 24) or None,
+ "parse_error": _short(item.get("parse_error"), 500) or None,
+ "owner_type": _short(item.get("owner_type"), 40),
+ "subjects": _string_list(item.get("subjects"), item_limit=64),
+ "places": _string_list(item.get("places"), item_limit=64),
+ "sources": _string_list(item.get("sources"), item_limit=64),
+ "subject_entities": references(item, "subject_entities"),
+ "place_entities": references(item, "place_entities"),
+ "source_entities": references(item, "source_entities"),
+ })
+ result: dict[str, Any] = {
+ "captured_at": _short(value.get("captured_at"), 40) or _now(),
+ "entities": clean_entities,
+ "links": clean_links,
+ }
+ if "timeline_items" in value or "timeline_tracks" in value:
+ result["timeline_items"] = clean_timeline
+ raw_tracks = value.get("timeline_tracks")
+ if not isinstance(raw_tracks, dict):
+ raise CaseError("snapshot timeline tracks are invalid")
+ result["timeline_tracks"] = {
+ _short(track_id, 64): [
+ item_id for item_id in _string_list(item_ids, limit=MAX_SNAPSHOT_TIMELINE_ITEMS)
+ if item_id in temporal_ids
+ ]
+ for track_id, item_ids in list(raw_tracks.items())[:20]
+ if _short(track_id, 64)
+ }
+ return result
+
+
+def _capture_timeline(case: Case, spec: dict[str, Any]) -> dict[str, Any]:
+ """Freeze the exact temporal rows the Timeline presentation currently reads."""
+ timeline = spec["timeline"]
+ since = _bound(timeline.get("from"), upper=False)
+ until = _bound(timeline.get("to"), upper=True)
+ captured: dict[str, dict[str, Any]] = {}
+ track_items: dict[str, list[str]] = {}
+ for track in timeline["tracks"]:
+ categories = track["categories"]
+ cursor: str | None = None
+ track_items[track["id"]] = []
+ if not categories:
+ continue
+ while True:
+ page = case.timeline_page(
+ since=since,
+ until=until,
+ categories=categories,
+ entity_id=(timeline.get("entity") or {}).get("id"),
+ include_undated=True,
+ limit=200,
+ cursor=cursor,
+ track={**track["query"], "hidden": track["hidden"]},
+ )
+ for item in page["items"]:
+ captured[item["id"]] = item
+ track_items[track["id"]].append(item["id"])
+ if len(captured) > MAX_SNAPSHOT_TIMELINE_ITEMS:
+ raise CaseError(
+ f"a timeline snapshot holds at most {MAX_SNAPSHOT_TIMELINE_ITEMS} entries;"
+ " narrow the view"
+ )
+ cursor = page["next_cursor"]
+ if cursor is None:
+ break
+ return {
+ "captured_at": _now(),
+ "entities": [],
+ "links": [],
+ "timeline_items": list(captured.values()),
+ "timeline_tracks": track_items,
+ }
+
+
+def prepare(
+ case: Case,
+ raw: dict[str, Any],
+ *,
+ mode: str,
+ surface: str,
+ snapshot_copy: bool = False,
+) -> dict[str, Any]:
+ """Validate a recipe and materialise its snapshot when requested."""
+ if not isinstance(raw, dict):
+ raise CaseError("analysis view spec must be an object")
+ # JSON round-trip strips Pydantic or reactive wrappers and proves the value is
+ # serialisable before it reaches SQLite.
+ try:
+ spec = json.loads(json.dumps(raw, ensure_ascii=False))
+ except (TypeError, ValueError) as exc:
+ raise CaseError("analysis view spec is not valid JSON") from exc
+ spec["version"] = VERSION
+ spec["surface"] = surface
+ query = spec.get("query") if isinstance(spec.get("query"), dict) else {}
+ query["terms"] = _query_terms(spec)
+ spec["query"] = query
+ spec["timeline"] = _clean_timeline(spec.get("timeline"), surface=surface)
+ if mode == "snapshot":
+ if "snapshot" in spec:
+ if not snapshot_copy:
+ raise CaseError("snapshot data can only be duplicated inside its case")
+ spec["snapshot"] = _clean_snapshot(spec["snapshot"])
+ elif surface == "timeline":
+ spec["snapshot"] = _capture_timeline(case, spec)
+ else:
+ spec["snapshot"] = _capture(case, spec)
+ else:
+ spec.pop("snapshot", None)
+ spec.pop("capture_ids", None)
+ spec.pop("capture_timeline_ids", None)
+ size = len(json.dumps(spec, ensure_ascii=False).encode("utf-8"))
+ if size > MAX_SPEC_BYTES:
+ raise CaseError("analysis view is too large")
+ return spec
+
+
+def snapshot_page(view: dict[str, Any], *, limit: int, cursor: str | None, order: str) -> dict[str, Any]:
+ """A bounded Board page over immutable captured rows."""
+ snapshot = view.get("spec", {}).get("snapshot") or {}
+ rows = list(snapshot.get("entities") or [])
+ if order in {"label", "-label"}:
+ rows.sort(key=lambda row: str(row.get("label") or "").casefold(), reverse=order.startswith("-"))
+ elif order in {"created", "-created"}:
+ rows.sort(
+ key=lambda row: str(row.get("provenance", {}).get("at") or ""),
+ reverse=order.startswith("-"),
+ )
+ elif order:
+ raise CaseError(f"'{order}' is not an ordering")
+ try:
+ start = int(cursor or "0")
+ except ValueError as exc:
+ raise CaseError(f"invalid snapshot cursor '{cursor}'") from exc
+ if start < 0:
+ raise CaseError(f"invalid snapshot cursor '{cursor}'")
+ page = rows[start : start + limit]
+ next_cursor = str(start + limit) if start + limit < len(rows) else None
+ return {"items": page, "next_cursor": next_cursor, "total": len(rows)}
diff --git a/src/azimut/engine/artifacts.py b/src/azimut/engine/artifacts.py
index 320cded..3384a5e 100644
--- a/src/azimut/engine/artifacts.py
+++ b/src/azimut/engine/artifacts.py
@@ -6,9 +6,10 @@ chain in ``api/cases.py``, and that chain already had a hole: deleting a proof
dropped its spec and its export but left ``proofs/<name>.assets/`` behind, so
pasted images outlived the composition they belonged to.
-A type that owns nothing on disk says so in `NO_FILES`, with the reason beside
-it. A type in neither table is an oversight, and `tests/test_artifacts.py` fails
-on it: a new tool declares what it writes, or it does not ship.
+A type with no intrinsic artifact says so in `NO_FILES`, with the reason beside
+it. Optional private entity photos are a cross-cutting ownership rule. A type in
+neither table is an oversight, and `tests/test_artifacts.py` fails on it: a new
+tool declares what it writes, or it does not ship.
Companions are the files named after the main artifact — a media's sidecar, a
proof's export and its assets folder. A companion that does not `travels` is a
@@ -19,6 +20,7 @@ would blank a surviving row.
from __future__ import annotations
+import json
import shutil
from collections.abc import Callable
from dataclasses import dataclass, field
@@ -112,22 +114,27 @@ KINDS: dict[str, Kind] = {
"note": Kind(path_attr="path"),
}
-#: Types that own nothing on disk, and why. A free-typed entity the analyst
-#: invents needs no entry — it is a label in the graph until a tool gives it a
-#: file, and that tool declares it in `KINDS`.
+#: Types with no intrinsic main artifact, and why. Supported entities can still
+#: own optional private presentation photos through `_direct_entity_photos`.
+#: A free-typed entity the analyst invents needs no entry — it is a label in the
+#: graph until a tool gives it a file, and that tool declares it in `KINDS`.
NO_FILES: dict[str, str] = {
"place": "coordinates and a label",
- "event": "a date and a label",
"person": "an identity in the graph",
"organization": "an identity in the graph",
- "alias": "an identity in the graph",
"account": "an identity in the graph",
"email": "an identifier in the graph",
"phone": "an identifier in the graph",
"domain": "an identifier in the graph",
"ip": "an identifier in the graph",
+ "network": "an identifier in the graph",
"vehicle": "an identity in the graph",
+ "vessel": "an identity in the graph",
+ "aircraft": "an identity in the graph",
+ "structure": "an identity in the graph",
+ "equipment-type": "a model in the graph, which owns no object of its own",
"bookmark": "a URL in the graph",
+ "claim": "a statement in the graph, and the edges that carry it",
}
@@ -175,12 +182,64 @@ def _paths(case: "Case", entity: dict[str, Any], *, travelling: bool) -> list[st
return out
+def _direct_entity_photos(case: "Case", entity: dict[str, Any]) -> list[str]:
+ """Private presentation files owned by this entity, if it has any.
+
+ Gallery rows that point into the Media Library own no bytes here. The Media
+ entity remains the sole owner of those files.
+ """
+ out: list[str] = []
+ for image in case.entity_images(str(entity.get("id") or "")):
+ if not image.get("direct"):
+ continue
+ for rel in (image.get("path"), image.get("thumbnail")):
+ if not isinstance(rel, str) or not rel:
+ continue
+ path = _resolve(case, rel)
+ if path is not None and path.exists():
+ out.append(rel)
+ return list(dict.fromkeys(out))
+
+
def owned(case: "Case", entity: dict[str, Any]) -> list[str]:
"""The case-relative files and folders this entity owns, that exist now.
These are what a delete removes and what the trash moves aside.
"""
- return _paths(case, entity, travelling=True)
+ return list(
+ dict.fromkeys(
+ [
+ *_paths(case, entity, travelling=True),
+ *_direct_entity_photos(case, entity),
+ ]
+ )
+ )
+
+
+def spec_thumb(case: "Case", entity: dict[str, Any]) -> str | None:
+ """The cached thumbnail an entity's own spec file records, if it keeps one there.
+
+ A proof is the one kind that does: its preview is written into
+ ``proofs/.meta/<name>.json`` when the export is rendered. That is the wrong place
+ for something a surface might need for a few hundred entities at once — the graph
+ answers from the database alone — so the caller copies what this returns onto the
+ entity, once, and reads it off the row from then on.
+
+ Unreadable, missing or thumbnail-less spec: None. A preview is disposable pixels,
+ and never a reason for a drawing to fail.
+ """
+ spec_rel = entity.get("attrs", {}).get("spec")
+ if not isinstance(spec_rel, str) or not spec_rel:
+ return None
+ path = _resolve(case, spec_rel)
+ if path is None or not path.is_file():
+ return None
+ try:
+ spec = json.loads(path.read_text(encoding="utf-8"))
+ except (OSError, ValueError):
+ return None
+ thumb = spec.get("thumb") if isinstance(spec, dict) else None
+ return thumb if isinstance(thumb, str) and thumb else None
def caches(case: "Case", entity: dict[str, Any]) -> list[str]:
diff --git a/src/azimut/engine/doctor.py b/src/azimut/engine/doctor.py
index 3059ccf..59816d7 100644
--- a/src/azimut/engine/doctor.py
+++ b/src/azimut/engine/doctor.py
@@ -3,6 +3,7 @@
from __future__ import annotations
import json
+import shutil
import sqlite3
import uuid
from pathlib import Path
@@ -17,6 +18,7 @@ DATABASE_MISSING = "database-missing"
DATABASE_UNREADABLE = "database-unreadable"
MEDIA_MISSING = "media-missing"
MEDIA_UNKNOWN = "media-unknown"
+TEMPORAL_INDEX_STALE = "temporal-index-stale"
def _media_files(case: Case) -> Iterator[Path]:
@@ -61,10 +63,17 @@ def _database_issue(*, unreadable: str | None = None) -> dict[str, Any]:
"detail": (
"Azimut can rebuild media, notes and proofs from their files and sidecars."
),
+ # What a rebuild costs, stated before it is chosen. Every line is case
+ # state that lives only in `case.db`: the rebuild reads files, and these
+ # were never written to one. A new table that cannot be read back from
+ # disk belongs here, or the app is asking for a yes it has not earned.
"losses": [
"Relations between entities",
"Catalog filing folders",
"Provenance that was not stored in a sidecar",
+ "Entity photo galleries, and the photos added from the computer",
+ "Saved analysis views",
+ "The graph arrangement, per lens",
],
"actions": [{"id": "rebuild", "label": "Rebuild database", "tone": "primary"}],
}
@@ -78,6 +87,7 @@ def scan(case: Case) -> dict[str, Any]:
try:
entities = list(_media_entities(case))
+ temporal_status = case.temporal_projection_status()
except (CaseError, OSError, sqlite3.Error) as exc:
return _report(case, manifest, [_database_issue(unreadable=str(exc))])
@@ -93,6 +103,25 @@ def scan(case: Case) -> dict[str, Any]:
]
issues: list[dict[str, Any]] = []
+ if not temporal_status["consistent"]:
+ issues.append(
+ {
+ "id": TEMPORAL_INDEX_STALE,
+ "kind": TEMPORAL_INDEX_STALE,
+ "severity": "warning",
+ "title": "Timeline index is out of date",
+ "detail": "The index does not match the case's Claims and media metadata.",
+ "expected": temporal_status["expected"],
+ "actual": temporal_status["actual"],
+ "actions": [
+ {
+ "id": "rebuild-timeline",
+ "label": "Rebuild Timeline index",
+ "tone": "primary",
+ }
+ ],
+ }
+ )
for entity in entities:
rel_path = str((entity.get("attrs") or {}).get("path") or "")
if rel_path and not case.resolve_inside(rel_path).is_file():
@@ -247,9 +276,26 @@ def rebuild_database(case: Case) -> dict[str, Any]:
for path in (staging, Path(f"{staging}-wal"), Path(f"{staging}-shm")):
path.unlink(missing_ok=True)
raise
+ _drop_orphaned_entity_photos(case)
return {"status": "rebuilt", "counts": counts}
+def _drop_orphaned_entity_photos(case: Case) -> None:
+ """Remove the private photos the rebuilt database can no longer own.
+
+ A photo added from the computer is bytes under `.data/entity-images/` plus a
+ row saying which entity shows it. The rebuild reads files, and that row was
+ never in one, so it does not come back — and the bytes left behind would be
+ files nothing displays, nothing deletes and every later bundle still carries.
+ The dialog names this loss before the analyst chooses the repair.
+
+ After the database is installed, never before: a crash between the two leaves
+ the case exactly as it was, with the photos and no database, and the next run
+ starts over.
+ """
+ shutil.rmtree(layout.entity_images(case.path), ignore_errors=True)
+
+
def require_missing_media(case: Case, entity_id: str) -> dict[str, Any]:
entity = case.get_entity(entity_id)
if entity is None or entity.get("type") not in {"media", "capture"}:
@@ -272,3 +318,9 @@ def require_unknown_media(case: Case, rel_path: str) -> Path:
if case.find_entity(attr="path", value=rel_path) is not None:
raise CaseError(f"media '{rel_path}' is already registered")
return path
+
+
+def require_stale_temporal_projection(case: Case) -> None:
+ """Refuse a Timeline repair unless the read-only check currently offers it."""
+ if case.temporal_projection_status()["consistent"]:
+ raise CaseError("the Timeline index is already current")
diff --git a/src/azimut/engine/enrich.py b/src/azimut/engine/enrich.py
index eea9179..92698f0 100644
--- a/src/azimut/engine/enrich.py
+++ b/src/azimut/engine/enrich.py
@@ -391,9 +391,10 @@ def _suggest_place(case: "CaseType", entity_id: str, gps: dict[str, float]) -> N
Places are deduplicated on a rounded coordinate key (about 1 m), so a roll
of photographs from one spot proposes one place rather than forty. The key
- is an attribute of the places enrichment mints; a place the analyst pinned
- by hand has none and is left alone, because merging the two is a judgement
- the Suggestions panel exists to let them make.
+ is ``satellite.COORD_KEY``, shared with the place a capture files, so a
+ photo's EXIF point and a capture framed on the same spot are one node. A
+ place the analyst pinned by hand carries no key and is left alone, because
+ merging the two is a judgement the Suggestions panel exists to let them make.
A relation already stated for this media wins over a later backfill. This is
especially important after importing a case from an older Azimut release:
@@ -406,15 +407,18 @@ def _suggest_place(case: "CaseType", entity_id: str, gps: dict[str, float]) -> N
if any(link["type"] == LOCATED_AT for link in case.links_of(entity_id)):
return
- key = f"{gps['lat']:.5f},{gps['lon']:.5f}"
- place = case.find_entity(attr="enrich_coord_key", value=key)
+ place = satellite_engine.place_at(case, gps["lat"], gps["lon"])
if place is None:
place = satellite_engine.save_place(
case,
gps["lat"],
gps["lon"],
by="enrich",
- extra_attrs={"enrich_coord_key": key},
+ extra_attrs={
+ satellite_engine.COORD_KEY: satellite_engine.coord_key(
+ gps["lat"], gps["lon"]
+ )
+ },
status="suggested",
)
case.add_link(
@@ -449,9 +453,12 @@ def _suggest_same_image(case: "CaseType", entity_id: str, rel: str, digest: str)
match_id = item.get("entity_id")
if not match_id:
continue
+ # Symmetric in meaning, canonical in storage. Sorting prevents a later
+ # enrichment pass from filing the same match in the reverse direction.
+ from_id, to_id = sorted((entity_id, match_id))
case.add_link(
- entity_id,
- match_id,
+ from_id,
+ to_id,
SAME_IMAGE_AS,
by="enrich",
status="suggested",
diff --git a/src/azimut/engine/entities.py b/src/azimut/engine/entities.py
new file mode 100644
index 0000000..6fd786b
--- /dev/null
+++ b/src/azimut/engine/entities.py
@@ -0,0 +1,945 @@
+"""The entity vocabulary: which types a case may hold, and what each one is.
+
+One registry, read by every surface. A type declares five things: how it reads in
+words, which **family** it belongs to, the **role** it plays once the case is drawn,
+the icon that stands for it, and the fields an analyst may fill on it.
+``GET /api/cases/entity-types`` serves it, so a create form is generated rather than
+written per type and no screen keeps its own copy of the vocabulary.
+
+The family is the load-bearing part. Relations start from families and may narrow
+an endpoint to explicit types (``engine/links.py``). Broad verbs therefore extend
+to a new family member, while type-specific verbs stay deliberately narrow:
+
+``actor``
+ A person or organization that can act or hold ownership.
+
+``asset``
+ It is owned, it appears in collected material, it sits somewhere. A vehicle, a
+ vessel, an aircraft, a building.
+
+``identifier``
+ A handle on some system, and **the value is the identity**: two ``email``
+ entities holding the same address are a bug, not two objects. This is the one
+ family where ONTOLOGY §2's "the label never defines identity" does not hold.
+
+``collected``
+ Bytes collected into the case: imported, downloaded, extracted or captured. Not
+ named ``imagery``, because ``media_kind`` also answers ``audio`` and ``file`` —
+ a PDF dropped into the Media Library is a ``media`` too — and not ``material``,
+ which was the first name and said nothing a reader could act on: every family
+ holds material of some sort. What unites these is that they were **gathered
+ rather than written**, so one of them may turn out to depict a place.
+
+``document``
+ It is read rather than gathered — made or merely consulted. A proof, a note, a
+ bookmarked URL. Two of its members are also *sources*, and carry how much they
+ are worth: see ``RELIABILITY_GRADES``.
+
+``place``
+ A point, never a thing. A building is an ``asset`` that *sits at* a place; if
+ ``place`` were also a thing, two families would carry geometry and "what is on
+ the map" would have two answers.
+
+``class``
+ A model or a class of thing, never one particular object: "T-72B3", not the tank
+ with turret number 214. It is **not a fact about the world under investigation,
+ it is a term the case counts with**, which is why it is not an ``asset``: the
+ three verbs an asset takes are all wrong for it — nobody owns a model, a model
+ sits nowhere, and letting one *appear in* footage would be a second way of saying
+ what a counted statement says better. Its whole vocabulary is being pointed at:
+ ``instance-of`` from an object that was actually named, and ``about`` from a
+ statement that counts. It lives in the case rather than in the workspace, because
+ a closed case folder is complete (SPEC §2) and statistics whose labels live
+ elsewhere do not travel.
+
+``claim``
+ A statement someone makes about the rest of the graph, carrying its own reasoning
+ and its own sources. This is followthemoney's reification: a claim that holds
+ values is a node with edges, never an edge with an attribute bag. It is a family
+ of its own because its verbs are the inverse of everyone else's — it points *at*
+ subjects rather than being pointed at.
+
+Splitting actor from asset is what keeps the layer honest. Held as one "subject"
+family, three verbs out of four would have had to narrow themselves back down —
+the picker would offer "this car owns this person" — and a family layer where
+every verb narrows is decoration. followthemoney draws the same line with
+``LegalEntity`` above ``Person`` and ``Company``; STIX draws it between a domain
+object and an observable.
+
+Beside its family, a type declares a **role**: what it is for once the case is
+*drawn* (``engine/graph.py``). A family says what a thing is and decides its verbs; a
+role says whether a picture of the case is about it. The line between the first two
+is the one that matters: **the file is a subject, its wrapper is an edge.**
+
+``subject``
+ A node. A video has content — it shows a place, it carries a geolocation — and so
+ does a person, an account or a statement.
+
+``attestation``
+ A wrapper around something the case already holds: a bookmark is a URL, a proof
+ is a rendering of media, a capture is a screenshot of a place. Drawn as a node
+ today, folded into the edge that carries its provenance later (SPEC §6).
+
+``annex``
+ Consulted rather than seen. It hangs off one node and carries no path through
+ itself, so it is fetched back rather than drawn by default.
+
+``deliverable``
+ What the case produced. Nothing cites a post.
+
+``manual`` was checked first and does not answer this: ``media`` and ``place`` are
+not manual and are subjects, ``post`` is not manual and is a deliverable, ``claim``
+is manual and is a subject. The two axes are independent.
+
+Adding a type is one entry here and one line in ``artifacts.NO_FILES``: the icon
+travels with the entry, so no screen keeps a list of its own. Adding a *family* is
+not cheap: its verbs have to be decided. The families are the commitment, the types
+are disposable.
+"""
+
+from __future__ import annotations
+
+import math
+from collections.abc import Callable, Mapping
+from dataclasses import dataclass
+from typing import Any
+
+from ..workspace import CaseError
+from .temporal import TemporalError, parse_temporal
+
+#: The families, in the order a menu should show them.
+ACTOR = "actor"
+ASSET = "asset"
+CLASS = "class"
+IDENTIFIER = "identifier"
+COLLECTED = "collected"
+DOCUMENT = "document"
+PLACE = "place"
+CLAIM = "claim"
+
+FAMILIES: tuple[str, ...] = (
+ ACTOR, ASSET, CLASS, IDENTIFIER, COLLECTED, DOCUMENT, PLACE, CLAIM,
+)
+
+#: The roles, in the order a case flows: sources feed statements, statements make
+#: outputs. What a type is for once the case is drawn — the axis a graph lens narrows
+#: nodes on, where the family decides verbs.
+SUBJECT = "subject"
+ATTESTATION = "attestation"
+ANNEX = "annex"
+DELIVERABLE = "deliverable"
+
+ROLES: tuple[str, ...] = (SUBJECT, ATTESTATION, ANNEX, DELIVERABLE)
+
+#: What each family means, in one clause, for the surface that has to explain itself.
+#: The families are the load-bearing idea of the vocabulary and the one part an
+#: analyst never types, so a menu naming them has to say what they are. Served with
+#: the registry for the reason every other reading is: one wording, not one per
+#: screen.
+FAMILY_READS: dict[str, str] = {
+ ACTOR: "a person or organization that can act or hold ownership",
+ ASSET: "a thing that is owned, appears in footage or sits somewhere",
+ CLASS: "a model the case counts with, rather than one particular object",
+ IDENTIFIER: "a handle on a system, where the value is the identity",
+ COLLECTED: "bytes gathered into the case rather than written, and one may show a place",
+ DOCUMENT: "something read rather than gathered, made or merely consulted",
+ PLACE: "a point on the map, never a thing standing on it",
+ CLAIM: "a statement about the rest of the case, carrying its own reasoning",
+}
+
+#: What an `attrs` field is edited as, and what the validator checks. Presentation
+#: only in the sense that everything is stored as written; a kind is added here when
+#: a type needs it, never in advance — an editor nothing uses is a screen nobody can
+#: reach. `temporal` holds the Claim profile parsed by ``engine.temporal``.
+#:
+#: `longtext` holds the same value as `text` and is checked by the same rule; what it
+#: says is that the field expects sentences. A quoted source and the reasoning behind
+#: a claim run to paragraphs, and a one-line box that scrolls sideways at eighty
+#: characters is a field nobody fills — the reason those two exist at all.
+ATTR_KINDS: tuple[str, ...] = (
+ "text", "longtext", "number", "url", "geojson", "choice", "temporal",
+)
+
+#: Longest a declared text field may be. Generous: `verbatim` quotes a source and
+#: `method` explains a match, and truncating either would defeat the point of
+#: keeping them.
+MAX_TEXT = 4000
+#: A radius wider than this is not a location. Half of Earth's meridian, so any
+#: honest "somewhere on this continent" still fits.
+MAX_RADIUS_M = 5_000_000
+#: Vertices a footprint may hold, summed over its rings. A drawn AOI uses tens; a
+#: traced coastline can use thousands; past this it is a payload, not a shape.
+MAX_FOOTPRINT_POINTS = 4096
+#: How many of a thing one statement may count. High enough for an order of battle
+#: or a crowd, low enough that a mistyped field is caught rather than stored.
+MAX_COUNT = 1_000_000
+
+#: Radius shortcuts, coarsest reading last. These exist because metres are the
+#: right thing to store and the wrong thing to ask for: an analyst knows "this
+#: block", not "100 m". Deriving them from Plus Code lengths instead would leave a
+#: hole — the valid lengths jump from 8 (~280 m cells) straight to 6 (~5.6 km),
+#: which is exactly the band a live geolocation lives in. So the rungs are the
+#: input and any Plus Code shown is derived from them, never the other way round.
+PRECISION_RUNGS: tuple[tuple[str, int], ...] = (
+ ("This building", 25),
+ ("This block", 100),
+ ("This neighbourhood", 500),
+ ("This town", 2_000),
+ ("This region", 10_000),
+)
+
+#: How much a source is worth, on the Admiralty/NATO letter scale — and it is a
+#: field of the *source*, never of the edge that cites it. The scheme exists to keep
+#: two axes apart: distrust of a source must not contaminate what it said, and an
+#: implausible claim from a reliable source stays implausible. Storing reliability on
+#: the entity and credibility on the link (``links.confidence``) makes combining them
+#: impossible rather than merely discouraged: they are not on the same object.
+#:
+#: The letters are the analyst's vocabulary, so they are what is stored. **F —
+#: "cannot be judged" — is deliberately left out**: an absent grade already says it,
+#: and a scale that spells one state twice is a scale nobody answers the same way
+#: twice. Same rule as the confidence ordinal, where "not assessed" is the lack of a
+#: value rather than a level.
+RELIABILITY_GRADES: tuple[tuple[str, str], ...] = (
+ ("A", "Completely reliable"),
+ ("B", "Usually reliable"),
+ ("C", "Fairly reliable"),
+ ("D", "Not usually reliable"),
+ ("E", "Unreliable"),
+)
+
+#: What state a thing is in, on the one scale two very different fields share.
+#:
+#: It sits on an ``asset``, where it is the **last known state** and a later
+#: observation overwrites it, and on a ``claim``, where it is the state **at the
+#: moment that statement describes**. Same word, two speakers — the pattern
+#: ``notes``/``verbatim``/``method`` already follows — and deliberately the same list,
+#: because a count that groups by condition has to reach both.
+#:
+#: **"Captured" is not here.** Changing hands is a change of owner, which ``owns``
+#: already states; folding it in would make the field a mixture of condition and
+#: possession, and a mixture does not aggregate. Absent means unknown, the same
+#: honest state an ungraded source is in.
+ASSET_CONDITIONS: tuple[tuple[str, str], ...] = (
+ ("intact", "Intact"),
+ ("damaged", "Damaged"),
+ ("destroyed", "Destroyed"),
+ ("abandoned", "Abandoned"),
+)
+
+#: Confidence belongs to a rich statement, not to its ``about``/``at``/``cites``
+#: connectors. Strings keep the stored value readable in a case export and avoid
+#: coupling entity attributes to the integer representation used by older edge
+#: ratings.
+CLAIM_CONFIDENCE: tuple[tuple[str, str], ...] = (
+ ("certain", "Certain"),
+ ("probable", "Probable"),
+ ("possible", "Possible"),
+ ("refuted", "Ruled out"),
+)
+
+#: Which question a Claim's date answers. Kept separate from confidence and source
+#: reliability: the same instant can be when a fact happened, when somebody saw it,
+#: or when a state held, and treating those as one event would move evidence in time.
+CLAIM_TIME_ROLES: tuple[tuple[str, str], ...] = (
+ ("occurred", "Occurred"),
+ ("observed", "Observed"),
+ ("valid", "Valid during"),
+)
+
+
+@dataclass(frozen=True)
+class Attr:
+ """One field an analyst may fill on an entity of this type.
+
+ Declaring them is what lets one generated form serve every hand-made type.
+ Nothing here is required: a type and a label are all an entity ever needs, and
+ an empty field means *unknown*, never *to be filled in*.
+
+ ``rungs`` are optional shortcut values for a numeric field, served with the
+ registry so the picker and the validator cannot drift apart. ``minimum`` and
+ ``maximum`` bound a number; both are served too, so the form refuses what the
+ API would refuse rather than finding out on submit.
+
+ ``options`` are the whole of what a ``choice`` field may hold, as
+ ``(stored, reading)`` pairs in scale order. Served for the same reason the rungs
+ are, and it is what makes the field closed: anything else is refused.
+
+ ``group`` heads this field and the ones after it that share it, which is what
+ lets one type hold several subjects: a Claim says *what* it states, *when* it
+ applies and *why* it is believed. Running every field under one heading would
+ file a count as reasoning. Empty means the field stands on its own label. Fields
+ sharing a heading are declared next to each other, since the heading is emitted
+ where the group changes rather than by regrouping the list — a form whose fields
+ reordered themselves would not be the registry's order any more.
+ """
+
+ key: str
+ label: str
+ kind: str = "text"
+ #: One clause saying what the field is for, shown where its label is. Empty
+ #: when the label already says it.
+ hint: str = ""
+ rungs: tuple[tuple[str, int], ...] = ()
+ minimum: float | None = None
+ maximum: float | None = None
+ #: A number with nothing between its values: two and a half destroyed tanks is
+ #: not a quantity anyone can defend, the same argument the zero radius makes.
+ whole: bool = False
+ options: tuple[tuple[str, str], ...] = ()
+ group: str = ""
+ #: Legacy fields remain readable without staying writable. A write may retain
+ #: the exact stored value, but creation and edits cannot introduce a new one.
+ editable: bool = True
+
+
+@dataclass(frozen=True)
+class EntityType:
+ """One type the vocabulary knows.
+
+ ``manual`` is whether an analyst creates these by hand. A ``media`` is born
+ from an import and a ``proof`` from an export, so neither belongs in a create
+ menu; a ``person`` exists only because someone typed it.
+
+ ``role`` is what the type is for once the case is drawn (see the module
+ docstring). It has no default: a new type has to decide whether a picture of the
+ case is about it, and a default would answer that question by omission.
+
+ Headings belong to the fields (``Attr.group``), not here: a place's four fields
+ do all answer one question, but a Claim's fields answer three.
+ """
+
+ type: str
+ label: str
+ family: str
+ icon: str
+ role: str
+ #: The field that becomes ``entity.label``. Calling every one "Name" hid the
+ #: actual identity field on identifiers: an IP address appeared to have no IP
+ #: box even though its value was stored in the label. These two readings let the
+ #: generated form name the field without duplicating the value into ``attrs``.
+ identity_label: str = "Title"
+ identity_placeholder: str = ""
+ attrs: tuple[Attr, ...] = ()
+ manual: bool = False
+ #: One clause saying what this type is, for the menus that offer it. The
+ #: vocabulary is deliberately terse — `capture`, `claim`, `collected` — and a
+ #: terse word nobody can look up is jargon.
+ hint: str = ""
+ #: Whether Details offers a photo gallery for this type. Explicit per type:
+ #: a future family member has to decide whether a representative image makes
+ #: sense rather than inheriting a UI it may not need.
+ image_gallery: bool = False
+
+
+#: The state an asset is in, declared once and shared by the whole family. Written
+#: out per type it would drift — a fifth level on one of the four, a different
+#: wording on another — and a scale that differs between two rows of the same list
+#: is a scale nothing can count over.
+_CONDITION = Attr(
+ "condition", "Condition",
+ hint="the last known state, overwritten by whatever is seen next",
+ kind="choice", options=ASSET_CONDITIONS,
+)
+
+
+#: The vocabulary, in menu order. Tool-born types are declared here too: the
+#: registry is the single truth for what a family a type sits in, and a relation
+#: cannot be validated against a type it has never heard of.
+ENTITY_TYPES: tuple[EntityType, ...] = (
+ # -- actors ---------------------------------------------------------------
+ EntityType(
+ "person", "Person", ACTOR, "user", SUBJECT,
+ identity_label="Full name", identity_placeholder="Name or known alias",
+ attrs=(
+ Attr("aliases", "Other names", hint="aliases, spellings or transliterations"),
+ Attr("role", "Role", hint="job, rank or public role"),
+ Attr("nationality", "Nationality"),
+ ),
+ manual=True, hint="a named individual", image_gallery=True,
+ ),
+ EntityType(
+ "organization", "Organization", ACTOR, "layers", SUBJECT, manual=True,
+ hint="a company, a ministry or a military unit",
+ identity_label="Organization name",
+ identity_placeholder="Name of the organization", image_gallery=True,
+ # A company, a ministry, and a military unit: all of them own things, post
+ # and turn up somewhere, so none of them needs a type of its own. `echelon`
+ # is what lets an order of battle render and sort — brigade above battalion
+ # above company — and the tree itself is `part-of` edges.
+ attrs=(
+ Attr("echelon", "Echelon",
+ hint="brigade, battalion, company: what lets an order of battle sort"),
+ Attr("country", "Country"),
+ ),
+ ),
+ # -- assets ---------------------------------------------------------------
+ # Every one of the four can be damaged, so `condition` is declared on the family
+ # rather than on the two types it was first wanted for. A field three members out
+ # of four carry is an inconsistency an analyst sees in the form.
+ EntityType(
+ "vehicle", "Vehicle", ASSET, "car", SUBJECT, manual=True,
+ hint="one particular vehicle, not a model", image_gallery=True,
+ identity_label="Vehicle name",
+ identity_placeholder="How this vehicle is known",
+ attrs=(
+ Attr("plate", "Plate", hint="the registration as read, not as guessed"),
+ Attr("make", "Make"),
+ Attr("model", "Model"),
+ Attr("colour", "Colour"),
+ _CONDITION,
+ ),
+ ),
+ EntityType(
+ "vessel", "Vessel", ASSET, "ship", SUBJECT, manual=True,
+ hint="one ship, identified by its IMO or its MMSI", image_gallery=True,
+ identity_label="Vessel name",
+ identity_placeholder="Name of the vessel",
+ # The IMO number is permanent, the MMSI changes with the flag. Both are
+ # fields of the vessel: an identifier entity is only worth minting the day
+ # a value turns up without its object, which is the AIS tracker's problem.
+ attrs=(
+ Attr("imo", "IMO number", hint="permanent, unlike the MMSI"),
+ Attr("mmsi", "MMSI", hint="changes with the flag"),
+ Attr("flag", "Flag state"),
+ Attr("kind", "Kind"),
+ _CONDITION,
+ ),
+ ),
+ EntityType(
+ "aircraft", "Aircraft", ASSET, "plane", SUBJECT, manual=True,
+ hint="one airframe, identified by its registration", image_gallery=True,
+ identity_label="Aircraft name",
+ identity_placeholder="How this airframe is known",
+ # Registration and the ICAO 24-bit address belong to the airframe. A
+ # callsign belongs to a flight, which is a dated claim and not a field.
+ attrs=(
+ Attr("registration", "Registration"),
+ Attr("icao24", "ICAO 24-bit address",
+ hint="belongs to the airframe, where a callsign belongs to a flight"),
+ Attr("model", "Model"),
+ _CONDITION,
+ ),
+ ),
+ EntityType(
+ "structure", "Structure", ASSET, "building", SUBJECT, manual=True,
+ hint="a building, bridge, mast or dam, placed by a relation rather than by coordinates",
+ image_gallery=True,
+ identity_label="Structure name",
+ identity_placeholder="How this structure is known",
+ # A building, and also a bridge, a mast, a dam. Its position is stated by
+ # `sited-at` rather than held here, so only `place` carries geometry.
+ attrs=(
+ Attr("kind", "Kind"),
+ Attr("address", "Address"),
+ _CONDITION,
+ ),
+ ),
+ # -- class ----------------------------------------------------------------
+ # The model an object is one of, and the thing a counted statement is about.
+ # Not an asset: nobody owns "T-72B3", and it sits nowhere. It exists so a case
+ # can say "two of these" without minting two anonymous vehicles — a fake
+ # identity per sighting is what makes a graph unreadable by the third month.
+ #
+ # One type, with `category` as a field rather than five types (`tank-type`,
+ # `gun-type`…): a count groups on that field, and five types would be five
+ # things to keep in step for no answer the field does not already give.
+ EntityType(
+ "equipment-type", "Equipment type", CLASS, "stack", SUBJECT, manual=True,
+ hint="a model or class, counted in statements rather than owned",
+ image_gallery=True,
+ identity_label="Model or class",
+ identity_placeholder="T-72B3, ZU-23-2, Mi-8",
+ attrs=(
+ Attr("category", "Category",
+ hint="what a count groups on: tank, air defence, artillery"),
+ Attr("aliases", "Other designations",
+ hint="the other names the same model is reported under"),
+ ),
+ ),
+ # -- identifiers ----------------------------------------------------------
+ EntityType(
+ "account", "Account", IDENTIFIER, "at", SUBJECT, manual=True,
+ hint="a profile or a bare username, whoever it turns out to belong to",
+ identity_label="Handle",
+ identity_placeholder="@account or username",
+ # `platform` is optional on purpose: a bare username is the same idea as a
+ # platform-bound account, and minting `alias` beside it would be a second
+ # type for one thing — the point where a vocabulary starts to bloat.
+ attrs=(
+ Attr("platform", "Platform"),
+ Attr("url", "Profile URL", kind="url"),
+ # An account is one of the two things a case actually sources from, so
+ # it carries the Admiralty grade. A claim cannot `cites` it directly —
+ # the verb reaches material and documents — but "who said it" is one hop
+ # back along `posted`, which is where the grade is read.
+ Attr(
+ "reliability", "Source reliability",
+ hint="how much this source is worth in general, never how sure one claim is",
+ kind="choice", options=RELIABILITY_GRADES,
+ ),
+ ),
+ ),
+ EntityType(
+ "email", "Email", IDENTIFIER, "mail", SUBJECT,
+ identity_label="Email address", identity_placeholder="[email protected]",
+ manual=True, hint="an address, which is its own identity",
+ ),
+ EntityType(
+ "phone", "Phone", IDENTIFIER, "phone", SUBJECT,
+ identity_label="Phone number", identity_placeholder="Include the country code",
+ attrs=(Attr("country", "Country"),),
+ manual=True, hint="a number, which is its own identity",
+ ),
+ EntityType(
+ "domain", "Domain", IDENTIFIER, "globe", SUBJECT,
+ identity_label="Domain", identity_placeholder="example.org",
+ attrs=(Attr("registrar", "Registrar"),),
+ manual=True, hint="a hostname, which is its own identity",
+ ),
+ EntityType(
+ "ip", "IP address", IDENTIFIER, "hash", SUBJECT,
+ identity_label="IP address", identity_placeholder="203.0.113.42",
+ attrs=(
+ Attr(
+ "network", "Legacy network",
+ hint="older free text, replaced by the In network relation",
+ editable=False,
+ ),
+ Attr("asn", "ASN", hint="the autonomous system number, if known"),
+ Attr("provider", "Provider"),
+ ),
+ manual=True, hint="an address, which is its own identity",
+ ),
+ EntityType(
+ "network", "Network", IDENTIFIER, "network", SUBJECT,
+ identity_label="Network or CIDR", identity_placeholder="203.0.113.0/24",
+ attrs=(
+ Attr("asn", "ASN", hint="the autonomous system number, if known"),
+ Attr("provider", "Provider"),
+ Attr("country", "Country"),
+ ),
+ manual=True, hint="an IP range, named by its network or CIDR",
+ ),
+ # -- material -------------------------------------------------------------
+ # `media` is whatever the library imported: image, video, audio or plain file.
+ # An imported PDF is one of these today; the `document` type that gives it a
+ # viewer and full-text search waits on text extraction (a native dependency on
+ # three platforms), which is the same gate as OCR.
+ EntityType("media", "Media", COLLECTED, "image", SUBJECT,
+ hint="a file the case collected: image, video, audio or document"),
+ EntityType("capture", "Capture", COLLECTED, "satellite", ATTESTATION,
+ hint="a map screenshot, with the provider and view it was taken from"),
+ # -- documents ------------------------------------------------------------
+ EntityType("proof", "Proof", DOCUMENT, "proof", ATTESTATION,
+ hint="a composed panel image, exported and still editable"),
+ EntityType("post", "Post", DOCUMENT, "post", DELIVERABLE,
+ hint="a prepared thread or report, saved rather than published"),
+ EntityType("note", "Note", DOCUMENT, "note", ANNEX,
+ hint="a Markdown page in the case notebook"),
+ EntityType("inspect-session", "Inspect session", DOCUMENT, "inspect", ANNEX,
+ hint="saved adjustments over one file, which die with it"),
+ # The page a claim rests on. `url` and `fetched_at` are written by whatever
+ # filed it — the extension is on the page, so the server stamps the moment it
+ # was seen — and are not declared here: a declared attr is a field an analyst
+ # fills, and neither of those is typed. What is typed is the archived copy,
+ # once someone has made one, and how much the source is worth.
+ EntityType(
+ "bookmark", "Bookmark", DOCUMENT, "bookmark", ATTESTATION,
+ hint="a page the case points at, stored as a link rather than a copy",
+ attrs=(
+ Attr("archive_url", "Archived copy", kind="url",
+ hint="a snapshot that survives the page being taken down"),
+ Attr(
+ "reliability", "Source reliability",
+ hint="how much this source is worth in general, never how sure one claim is",
+ kind="choice", options=RELIABILITY_GRADES,
+ ),
+ ),
+ ),
+ # -- place ----------------------------------------------------------------
+ # Only the precision fields are declared: `lat`, `lon`, `coords`, `plus_code`,
+ # `zoom`, `bearing`, `geo` and `notes` are the Satellite tool's, written by the
+ # save that made the point. A declared attr means "a field an analyst may fill",
+ # not "everything this type holds", so the tool's keys pass through untouched.
+ EntityType(
+ "place", "Place", PLACE, "pin", SUBJECT,
+ hint="a saved point, as exact or as vague as the evidence allows",
+ attrs=(
+ # Darwin Core's rule, kept verbatim: this is the radius of the smallest
+ # circle containing the whole location, not a standard deviation — so
+ # two analysts write the same number. And **zero is not valid**: an
+ # empty radius means *unknown*, which is a different and honest state,
+ # where `0` would claim infinite precision. Hence a minimum of one
+ # metre; below that there is no claim anyone can defend from imagery.
+ Attr(
+ "radius_m", "Uncertainty radius (m)", kind="number",
+ hint="the smallest circle that contains the whole location",
+ rungs=PRECISION_RUNGS, minimum=1, maximum=MAX_RADIUS_M,
+ group="How precise",
+ ),
+ Attr("footprint", "Footprint", kind="geojson",
+ hint="the shape itself, for a place a circle describes badly"),
+ Attr("verbatim", "As the source put it", kind="longtext",
+ hint="the original wording, which outlives every reinterpretation"),
+ Attr("method", "How this point was found", kind="longtext",
+ hint="what was matched against what, so the point can be audited"),
+ ),
+ ),
+ # -- claim ----------------------------------------------------------------
+ # The node that exists so connectors never carry statement metadata. It points
+ # `about` at its subject, `at` at places and `cites` at its sources; confidence
+ # belongs to this node, not to any one connector (`engine/links.py`).
+ #
+ # `count` and `condition` are what let a statement be counted: "two of these,
+ # destroyed". They sit on the node and not on `about`, because a Claim may point
+ # at several subjects and one number on the node could not say which it meant —
+ # so one statement counts one kind of thing, and a second kind is a second Claim
+ # with its own confidence. That is the same call §3 already makes for competing
+ # candidates, and it is what keeps every value on this node assessable as one.
+ EntityType(
+ "claim", "Claim", CLAIM, "quote", SUBJECT, manual=True,
+ hint="something you are saying about the case, with its reasoning and its sources",
+ identity_label="Statement",
+ identity_placeholder="What are you asserting?",
+ attrs=(
+ Attr(
+ "count", "How many", kind="number",
+ hint="how many of the one thing this statement counts",
+ minimum=1, maximum=MAX_COUNT, whole=True,
+ group="What it states",
+ ),
+ Attr(
+ "condition", "Condition",
+ hint="the state at the moment this statement describes",
+ kind="choice", options=ASSET_CONDITIONS,
+ ),
+ Attr(
+ "when", "When", kind="temporal",
+ hint="when this statement applies",
+ group="When",
+ ),
+ Attr(
+ "time_role", "Time role", kind="choice",
+ hint="what this value means for the statement",
+ options=CLAIM_TIME_ROLES,
+ ),
+ Attr(
+ "confidence", "Confidence",
+ hint="how strongly the statement is supported",
+ kind="choice", options=CLAIM_CONFIDENCE,
+ group="Reasoning",
+ ),
+ Attr("method", "How this was worked out", kind="longtext",
+ hint="the reasoning a reader would need to check this"),
+ Attr("verbatim", "As the source put it", kind="longtext",
+ hint="the original wording, quoted rather than paraphrased"),
+ ),
+ ),
+)
+
+_BY_TYPE: dict[str, EntityType] = {entry.type: entry for entry in ENTITY_TYPES}
+
+
+def entity_type(type_: str) -> EntityType | None:
+ """The registry entry for a type, or None when the vocabulary has none.
+
+ Free-string types stay storable (ONTOLOGY §2): they are a label in the graph
+ until a tool or this registry gives them a meaning. What they cannot be is the
+ end of a relation, since nothing states what they may join.
+ """
+ return _BY_TYPE.get(type_)
+
+
+def family_of(type_: str) -> str | None:
+ """Which family a type sits in, or None for an undeclared free type."""
+ entry = _BY_TYPE.get(type_)
+ return entry.family if entry else None
+
+
+#: Declared kinds whose value is worth finding an entity by. A plate, an IMO, a
+#: handle's platform and a claim's reasoning are what an analyst types into a search
+#: box; a radius in metres, a footprint's coordinates and a stored grade letter are
+#: not — matching "500" against every radius in the case would bury the rows that
+#: actually say 500.
+SEARCHABLE_KINDS: frozenset[str] = frozenset({"text", "longtext", "url"})
+
+
+def search_values(type_: str, attrs: Mapping[str, Any] | None) -> list[str]:
+ """The declared field values an entity should be findable by.
+
+ The label, the type and the notes were the whole index before this, which meant
+ a vehicle could not be found by the plate that identifies it and a claim not by
+ the wording it quotes — the fields the vocabulary went to the trouble of
+ declaring were the ones search could not see. Only declared keys are read, so a
+ tool's own payload (a spec, a sidecar path, a geometry) never enters the index.
+ """
+ entry = _BY_TYPE.get(type_)
+ if entry is None or not attrs:
+ return []
+ return [
+ str(attrs[attr.key])
+ for attr in entry.attrs
+ if attr.kind in SEARCHABLE_KINDS and attrs.get(attr.key) not in (None, "")
+ ]
+
+
+def search_matches(entity: Mapping[str, Any], query: str | None) -> list[dict[str, str]]:
+ """Which human-readable fields explain a text-search match.
+
+ The stored index stays the fast predicate. This is the small explanation added
+ only to rows that already matched it, so a plate hit can say ``Plate · AB-123``
+ instead of making the analyst open the entity to discover why it appeared.
+ """
+ terms = [term for term in str(query or "").casefold().split() if term]
+ if not terms:
+ return []
+ type_ = str(entity.get("type") or "")
+ raw_attrs = entity.get("attrs")
+ attrs: Mapping[str, Any] = raw_attrs if isinstance(raw_attrs, Mapping) else {}
+ entry = _BY_TYPE.get(type_)
+ fields: list[tuple[str, str, Any]] = [
+ ("label", "Name", entity.get("label")),
+ ("type", "Type", type_),
+ ("folder", "Folder", attrs.get("folder")),
+ ("notes", "Notes", attrs.get("notes")),
+ ]
+ if entry is not None:
+ fields.extend(
+ (attr.key, attr.label, attrs.get(attr.key))
+ for attr in entry.attrs
+ if attr.kind in SEARCHABLE_KINDS
+ )
+ matches: list[dict[str, str]] = []
+ covered: set[str] = set()
+ for key, label, value in fields:
+ if value in (None, ""):
+ continue
+ text = str(value)
+ folded = text.casefold()
+ hit = {term for term in terms if term in folded}
+ if not hit:
+ continue
+ covered.update(hit)
+ matches.append({"field": key, "label": label, "value": text[:300]})
+ return matches if covered == set(terms) else []
+
+
+#: Punctuation a phone number is spaced with rather than identified by. A number
+#: written `+33 6 12 34 56 78` and the same one written `+33612345678` are one
+#: identity; `+33612345678` and `0612345678` are **not**, because supplying a
+#: country code is a guess about what the analyst meant.
+_PHONE_NOISE = " \t-.()/"
+
+
+def identity_key(type_: str, label: str) -> str:
+ """What makes two records of an identifier the same record, or `""`.
+
+ The ``identifier`` family is the one place ONTOLOGY §2's "the label never
+ defines identity" does not hold: two ``email`` entities holding one address are
+ a bug rather than two objects (module docstring). Nothing else has this — two
+ people really can share a name — so every other family answers `""` and is never
+ compared.
+
+ **It catches the same value typed twice, not every spelling that resolves to the
+ same thing.** `203.0.113.42` is not compared against a padded IPv6 form and
+ `example.org` is not compared against `www.example.org`: those need a parser or a
+ guess, and a guard that guesses refuses two entities that are genuinely
+ different — which is a worse failure than missing one, since the analyst can see
+ a duplicate and cannot see a refusal that should not have happened.
+
+ Served through ``GET /cases/{id}/entities/twin`` rather than reimplemented in the
+ browser, so the form's warning and any later check compare the same way. The
+ create form used to lowercase the raw label and compare that, which let `@handle`
+ and `handle` sit side by side as two accounts.
+ """
+ entry = _BY_TYPE.get(type_)
+ if entry is None or entry.family != IDENTIFIER:
+ return ""
+ value = str(label).strip().casefold()
+ if not value:
+ return ""
+ if type_ == "account":
+ # A handle is written with or without its sigil by the same analyst on the
+ # same afternoon, and the platform is a separate field either way.
+ return value.lstrip("@")
+ if type_ == "phone":
+ return "".join(ch for ch in value if ch not in _PHONE_NOISE)
+ if type_ == "domain":
+ # The root label is optional in a fully-qualified name and means nothing here.
+ return value.rstrip(".")
+ return value
+
+
+def types_in(*families: str) -> frozenset[str]:
+ """Every declared type in these families.
+
+ This is what turns a relation declared against families into the concrete type
+ set the endpoint check compares against, resolved once at import.
+ """
+ wanted = set(families)
+ return frozenset(e.type for e in ENTITY_TYPES if e.family in wanted)
+
+
+def role_of(type_: str) -> str | None:
+ """What a type is for once the case is drawn, or None for a free type.
+
+ A free type has no role for the same reason it has no family: nothing declares
+ what it is. A drawing keeps it — leaving out what the vocabulary cannot speak for
+ would drop an entity nobody agreed to drop.
+ """
+ entry = _BY_TYPE.get(type_)
+ return entry.role if entry else None
+
+
+def types_with_role(*roles: str) -> frozenset[str]:
+ """Every declared type playing one of these roles.
+
+ The node half of a graph lens, resolved the same way ``types_in`` resolves the
+ endpoints of a verb: the vocabulary is stated once here, and a reading of the case
+ derives its type set from it rather than listing one of its own.
+ """
+ wanted = set(roles)
+ return frozenset(e.type for e in ENTITY_TYPES if e.role in wanted)
+
+
+# -- validation ---------------------------------------------------------------
+#
+# Only *declared* fields are checked. A tool's own keys on the same entity — a
+# place's `lat`, `geo` or `notes` — pass through untouched, because a declared attr
+# means "a field an analyst may fill", not "everything this type holds". That is
+# what makes this additive: no existing write can start failing.
+
+
+def check_attrs(
+ type_: str,
+ attrs: Mapping[str, Any],
+ *,
+ current: Mapping[str, Any] | None = None,
+) -> None:
+ """Raise ``CaseError`` on a malformed value in a declared field.
+
+ Clearing is always allowed: ``None`` and ``""`` mean *unknown*, which every
+ field may be, and refusing them would make "I do not know how precise this is"
+ impossible to say.
+ """
+ entry = _BY_TYPE.get(type_)
+ if entry is None:
+ return
+ for attr in entry.attrs:
+ if attr.key not in attrs:
+ continue
+ value = attrs[attr.key]
+ if not attr.editable and value not in (None, ""):
+ previous = (current or {}).get(attr.key)
+ if previous != value:
+ raise CaseError(f"'{attr.key}' is read-only legacy data")
+ if value is None or value == "":
+ continue
+ _CHECKS[attr.kind](attr, value)
+
+
+def _check_text(attr: Attr, value: Any) -> None:
+ if not isinstance(value, str):
+ raise CaseError(f"'{attr.key}' must be text")
+ if len(value) > MAX_TEXT:
+ raise CaseError(f"'{attr.key}' is longer than {MAX_TEXT} characters")
+
+
+def _check_number(attr: Attr, value: Any) -> None:
+ # bool is an int in Python, and `True` metres is not a radius.
+ if isinstance(value, bool) or not isinstance(value, (int, float)):
+ raise CaseError(f"'{attr.key}' must be a number")
+ if not math.isfinite(value):
+ raise CaseError(f"'{attr.key}' must be a finite number")
+ # A count has nothing between its values. Two and a half destroyed tanks is not
+ # a quantity anyone can defend, and stored once it would be summed with the rest.
+ if attr.whole and float(value) != int(value):
+ raise CaseError(f"'{attr.key}' must be a whole number")
+ if attr.minimum is not None and value < attr.minimum:
+ raise CaseError(f"'{attr.key}' must be at least {attr.minimum}")
+ if attr.maximum is not None and value > attr.maximum:
+ raise CaseError(f"'{attr.key}' must be at most {attr.maximum}")
+
+
+def _check_url(attr: Attr, value: Any) -> None:
+ _check_text(attr, value)
+ # A declared url is rendered as a link, so the scheme is checked at the edge
+ # rather than trusted: `javascript:` in an anchor is the whole reason.
+ if not str(value).lower().startswith(("http://", "https://")):
+ raise CaseError(f"'{attr.key}' must be an http or https URL")
+
+
+def _check_geojson(attr: Attr, value: Any) -> None:
+ """A footprint: one GeoJSON Polygon or MultiPolygon, and nothing exotic.
+
+ Darwin Core's `footprintWKT` in the shape the map already speaks. Points and
+ lines are refused because a footprint is an area — a point is what `lat`/`lon`
+ with a radius already says.
+ """
+ if not isinstance(value, dict):
+ raise CaseError(f"'{attr.key}' must be a GeoJSON geometry")
+ if value.get("type") not in ("Polygon", "MultiPolygon"):
+ raise CaseError(f"'{attr.key}' must be a Polygon or MultiPolygon")
+ rings = value.get("coordinates")
+ if not isinstance(rings, list) or not rings:
+ raise CaseError(f"'{attr.key}' has no coordinates")
+ points = _count_positions(rings, attr.key)
+ if points < 3:
+ raise CaseError(f"'{attr.key}' needs at least three points to be an area")
+ if points > MAX_FOOTPRINT_POINTS:
+ raise CaseError(f"'{attr.key}' holds more than {MAX_FOOTPRINT_POINTS} points")
+
+
+def _count_positions(node: Any, key: str, depth: int = 0) -> int:
+ """Count `[lon, lat]` pairs, checking each as it goes.
+
+ Recursive because a Polygon nests one level deeper than a MultiPolygon's rings,
+ and bounded by ``depth`` so a hand-made payload cannot nest its way past the
+ point cap.
+ """
+ if depth > 4:
+ raise CaseError(f"'{key}' is nested too deeply")
+ if not isinstance(node, list):
+ raise CaseError(f"'{key}' has a malformed coordinate")
+ # a position is the innermost list: two numbers, lon then lat
+ if node and all(isinstance(v, (int, float)) and not isinstance(v, bool) for v in node):
+ if len(node) < 2:
+ raise CaseError(f"'{key}' has a coordinate that is not a lon/lat pair")
+ lon, lat = float(node[0]), float(node[1])
+ if not (-180 <= lon <= 180 and -90 <= lat <= 90):
+ raise CaseError(f"'{key}' has a coordinate off the globe")
+ return 1
+ return sum(_count_positions(child, key, depth + 1) for child in node)
+
+
+def _check_choice(attr: Attr, value: Any) -> None:
+ """One of the readings the field declares, and nothing else.
+
+ A closed scale is only closed if the store enforces it: a grade the registry has
+ never heard of would render as itself in the panel and read as a sixth level
+ nobody agreed on.
+ """
+ # `isinstance` first: an unhashable body — a list, an object — would raise out
+ # of a set membership test instead of answering the 400 it deserves.
+ if not isinstance(value, str) or value not in {stored for stored, _ in attr.options}:
+ allowed = ", ".join(stored for stored, _ in attr.options)
+ raise CaseError(f"'{attr.key}' must be one of {allowed}, or nothing")
+
+
+def _check_temporal(attr: Attr, value: Any) -> None:
+ try:
+ parse_temporal(value)
+ except TemporalError as exc:
+ raise CaseError(f"'{attr.key}' {exc}") from exc
+
+
+_CHECKS: dict[str, Callable[[Attr, Any], None]] = {
+ "text": _check_text,
+ "longtext": _check_text,
+ "number": _check_number,
+ "url": _check_url,
+ "geojson": _check_geojson,
+ "choice": _check_choice,
+ "temporal": _check_temporal,
+}
diff --git a/src/azimut/engine/entity_images.py b/src/azimut/engine/entity_images.py
new file mode 100644
index 0000000..4bb4230
--- /dev/null
+++ b/src/azimut/engine/entity_images.py
@@ -0,0 +1,189 @@
+"""Presentation images attached to hand-made case entities.
+
+An image chosen from the Media Library stays a reference to that existing
+media. An image added from the computer is different: it is normalized into a
+private presentation file owned by the entity and never enters the Media
+Library or the media browse index.
+"""
+
+from __future__ import annotations
+
+import uuid
+from pathlib import Path
+from typing import Any, BinaryIO
+
+from PIL import Image, ImageOps, UnidentifiedImageError
+
+from .. import layout
+from ..repository import CaseRepository
+from ..workspace import Case, CaseError, _new_id, _replace_with_retry, ensure_dir
+from . import entities
+
+IMAGE_TYPES = frozenset({"media", "capture"})
+PHOTO_MAX = 2048
+THUMB_MAX = 512
+
+
+def supports(type_: str) -> bool:
+ entry = entities.entity_type(type_)
+ return bool(entry and entry.image_gallery)
+
+
+def _target(case: CaseRepository, entity_id: str) -> dict[str, Any]:
+ entity = case.get_entity(entity_id)
+ if entity is None:
+ raise CaseError(f"entity '{entity_id}' not found")
+ if not supports(str(entity.get("type") or "")):
+ raise CaseError("this entity type does not have a photo gallery")
+ return entity
+
+
+def _media(case: CaseRepository, media_ids: list[str]) -> list[str]:
+ unique = list(dict.fromkeys(media_ids))
+ kinds = case.media_kinds(unique)
+ for media_id in unique:
+ entity = case.get_entity(media_id)
+ if entity is None:
+ raise CaseError(f"entity '{media_id}' not found")
+ if entity.get("type") not in IMAGE_TYPES:
+ raise CaseError("only case images can be added to a photo gallery")
+ kind = kinds.get(media_id) or (entity.get("attrs") or {}).get("kind")
+ if kind != "image":
+ raise CaseError("only images can be added to a photo gallery")
+ return unique
+
+
+def _title(filename: str | None) -> str:
+ name = Path(filename or "").name
+ return (Path(name).stem.strip() or "Photo")[:300]
+
+
+def _write_photo(
+ source: BinaryIO,
+ photo_path: Path,
+ thumb_path: Path,
+) -> None:
+ photo_tmp = photo_path.with_name(f".{uuid.uuid4().hex}.tmp.jpg")
+ thumb_tmp = thumb_path.with_name(f".{uuid.uuid4().hex}.tmp.jpg")
+ try:
+ with Image.open(source) as opened:
+ photo = ImageOps.exif_transpose(opened).convert("RGB")
+ photo.thumbnail((PHOTO_MAX, PHOTO_MAX), Image.Resampling.LANCZOS)
+ thumb = photo.copy()
+ thumb.thumbnail((THUMB_MAX, THUMB_MAX), Image.Resampling.LANCZOS)
+ photo.save(photo_tmp, "JPEG", quality=90, optimize=True)
+ thumb.save(thumb_tmp, "JPEG", quality=82, optimize=True)
+ _replace_with_retry(photo_tmp, photo_path)
+ _replace_with_retry(thumb_tmp, thumb_path)
+ except (
+ OSError,
+ SyntaxError,
+ ValueError,
+ Image.DecompressionBombError,
+ Image.DecompressionBombWarning,
+ UnidentifiedImageError,
+ ) as exc:
+ photo_tmp.unlink(missing_ok=True)
+ thumb_tmp.unlink(missing_ok=True)
+ photo_path.unlink(missing_ok=True)
+ thumb_path.unlink(missing_ok=True)
+ raise CaseError("the selected file is not a readable image") from exc
+ except BaseException:
+ photo_tmp.unlink(missing_ok=True)
+ thumb_tmp.unlink(missing_ok=True)
+ photo_path.unlink(missing_ok=True)
+ thumb_path.unlink(missing_ok=True)
+ raise
+
+
+def import_photo(
+ case: Case,
+ entity_id: str,
+ source: BinaryIO,
+ filename: str | None,
+) -> dict[str, Any]:
+ """Store a bounded private photo without creating a Media entity or row."""
+ with case.lock:
+ _target(case, entity_id)
+ image_id = _new_id("i")
+ photo_rel = layout.entity_image_rel(image_id)
+ thumb_rel = layout.entity_image_thumb_rel(image_id)
+ ensure_dir(layout.entity_images(case.path))
+ ensure_dir(layout.entity_image_thumbs(case.path))
+ photo_path = case.resolve_inside(photo_rel)
+ thumb_path = case.resolve_inside(thumb_rel)
+ _write_photo(source, photo_path, thumb_path)
+ try:
+ case.add_entity_image_file(
+ entity_id, image_id, photo_rel, thumb_rel, _title(filename)
+ )
+ except BaseException:
+ photo_path.unlink(missing_ok=True)
+ thumb_path.unlink(missing_ok=True)
+ prune_empty_dirs(case)
+ raise
+ return {"added": 1, "images": case.entity_images(entity_id)}
+
+
+def prune_empty_dirs(case: Case) -> None:
+ """Remove the lazy gallery directories once their last private file is gone."""
+ for directory in (layout.entity_image_thumbs(case.path), layout.entity_images(case.path)):
+ try:
+ directory.rmdir()
+ except OSError:
+ pass
+
+
+def list_images(case: CaseRepository, entity_id: str) -> list[dict[str, Any]]:
+ _target(case, entity_id)
+ return case.entity_images(entity_id)
+
+
+def attach(
+ case: CaseRepository, entity_id: str, media_ids: list[str]
+) -> dict[str, Any]:
+ _target(case, entity_id)
+ images = _media(case, media_ids)
+ added = case.add_entity_images(entity_id, images)
+ return {"added": added, "images": case.entity_images(entity_id)}
+
+
+def set_primary(
+ case: CaseRepository, entity_id: str, image_id: str
+) -> list[dict[str, Any]]:
+ _target(case, entity_id)
+ case.set_primary_entity_image(entity_id, image_id)
+ return case.entity_images(entity_id)
+
+
+def detach(case: Case, entity_id: str, image_id: str) -> list[dict[str, Any]]:
+ """Remove a reference, or delete the private files owned by a direct photo."""
+ with case.lock:
+ _target(case, entity_id)
+ image = next(
+ (item for item in case.entity_images(entity_id) if item["id"] == image_id),
+ None,
+ )
+ if image is None:
+ raise CaseError("that image is not attached to this entity")
+ staged: list[tuple[Path, Path]] = []
+ if image.get("direct"):
+ for rel in (image.get("path"), image.get("thumbnail")):
+ if not isinstance(rel, str) or not rel:
+ continue
+ path = case.resolve_inside(rel)
+ if path.exists():
+ temporary = path.with_name(f".{uuid.uuid4().hex}.remove")
+ _replace_with_retry(path, temporary)
+ staged.append((path, temporary))
+ try:
+ case.remove_entity_image(entity_id, image_id)
+ except BaseException:
+ for original, temporary in reversed(staged):
+ if temporary.exists():
+ _replace_with_retry(temporary, original)
+ raise
+ for _original, temporary in staged:
+ temporary.unlink(missing_ok=True)
+ prune_empty_dirs(case)
+ return case.entity_images(entity_id)
diff --git a/src/azimut/engine/geo.py b/src/azimut/engine/geo.py
index da91ef0..ec49ce2 100644
--- a/src/azimut/engine/geo.py
+++ b/src/azimut/engine/geo.py
@@ -3,6 +3,8 @@
from __future__ import annotations
import re
+import threading
+import time
from typing import Any
import httpx
@@ -10,6 +12,57 @@ import httpx
from . import coords
from .tiles import USER_AGENT
+# -- Nominatim's pace ----------------------------------------------------------
+
+#: Nominatim asks for at most one request a second, and the penalty for going
+#: faster is a 429 on the whole address for a while. The floor therefore belongs
+#: **here**, in front of every request, rather than in whichever caller happens
+#: to loop: a country backfill paces itself between items, and then
+#: `locate_point` makes a second lookup for the English region name that no
+#: caller can see, and the two together were the real pace. One home for the
+#: rule, and no caller can break it.
+NOMINATIM_INTERVAL = 1.1
+#: How long a 429 is remembered, so a surface can say why nothing resolved
+#: instead of reporting a lookup failure the analyst cannot act on.
+THROTTLE_COOLDOWN = 60.0
+
+_pace_lock = threading.Lock()
+_last_request = 0.0
+_throttled_until = 0.0
+
+
+def _pace() -> None:
+ """Hold the caller until the interval since the last Nominatim request has
+ passed. Serialized, so two threads cannot both decide it is their turn."""
+ global _last_request
+ with _pace_lock:
+ wait = NOMINATIM_INTERVAL - (time.monotonic() - _last_request)
+ if wait > 0:
+ time.sleep(wait)
+ _last_request = time.monotonic()
+
+
+def _note_throttling(response: Any) -> None:
+ """Remember a 429. Reads the status defensively: the only thing this needs
+ from the response is a number, and a caller's stub may not carry one."""
+ global _throttled_until
+ if getattr(response, "status_code", None) == 429:
+ _throttled_until = time.monotonic() + THROTTLE_COOLDOWN
+
+
+def throttled() -> bool:
+ """Whether Nominatim answered 429 recently. A pass that resolved nothing
+ reads very differently depending on this, so a surface reports it."""
+ return time.monotonic() < _throttled_until
+
+
+def _reset_pace() -> None:
+ """Test seam: forget the last request and any throttling."""
+ global _last_request, _throttled_until
+ _last_request = 0.0
+ _throttled_until = 0.0
+
+
# -- parsing -------------------------------------------------------------------
_DEC = r"[-+]?\d{1,3}(?:\.\d+)?"
@@ -282,12 +335,14 @@ def geocode(query: str) -> dict[str, Any] | None:
and the analyst can tell they landed where they meant to.
"""
try:
+ _pace()
response = httpx.get(
"https://nominatim.openstreetmap.org/search",
params={"q": query, "format": "jsonv2", "limit": 1, "accept-language": "en"},
headers={"User-Agent": USER_AGENT},
timeout=8,
)
+ _note_throttling(response)
response.raise_for_status()
results = response.json()
if not results:
@@ -320,12 +375,14 @@ def reverse_geocode(
if language:
params["accept-language"] = language
try:
+ _pace()
response = httpx.get(
"https://nominatim.openstreetmap.org/reverse",
params=params,
headers={"User-Agent": USER_AGENT},
timeout=timeout,
)
+ _note_throttling(response)
response.raise_for_status()
data = response.json()
return {
diff --git a/src/azimut/engine/graph.py b/src/azimut/engine/graph.py
new file mode 100644
index 0000000..e90458f
--- /dev/null
+++ b/src/azimut/engine/graph.py
@@ -0,0 +1,2038 @@
+"""The case drawn as nodes and edges (SPEC §5, "Case graph").
+
+The Board already lists a case, and lists it better than any drawing would: it
+sorts, filters and shows columns. So this module deliberately does not answer
+"browse the case". It answers the four questions a table cannot:
+
+**the path** — how one gets from this account to that place · **the convergence**
+— what points at the same thing · **the independence** — whether three citations
+are three sources or one repeated · **the contradiction** — what stands against a
+statement.
+
+Two reads serve them, and the first is the entry point:
+
+``view``
+ The whole case, or as much of it as a first draw opens on. A case is a subject
+ before it is a set of statements — a conflict followed over months has no single
+ root to expand from — so the graph opens on everything and the analyst narrows.
+ ``OPENING_NODES`` is a comfort number rather than a ceiling: what a first draw
+ keeps is decided by degree, so the hubs stay and the picture is the case rather
+ than an arbitrary slice of it, and **everything after that first draw is
+ unbounded** — nothing the analyst asks for is refused for room.
+
+ It also **grows**, and the drawing is **a set the caller owns**. ``expand``
+ names the nodes whose neighbours join the picture, so opening one up adds to the
+ case on screen instead of replacing it with a different question. That is what
+ makes the graph a place to work rather than a thing to navigate: the shape you
+ were reading is still there when the answer arrives.
+
+ Two more lists edit that set by hand, and they are what keep an unbounded
+ drawing usable. ``keep`` draws a node and **nothing around it**, which is what a
+ route and a named entity actually want — a picture that dragged every route
+ node's whole neighbourhood in behind it answered a question with a crowd.
+ ``omit`` takes a node out — and with it whatever nothing else was holding —
+ whichever of the three put it there, so a drawing that can grow without limit has
+ a way back that is not "fold everything".
+
+``neighborhood``
+ One node and what surrounds it, hop by hop, for when the question does have a
+ root. Every frontier node reports its degree, so a click's cost is known
+ before it is paid.
+
+**Lenses are derived, never declared twice.** A lens is a set of verbs *and* a set of
+node roles, and both live in the registries: the verbs in ``engine/links.py``, the
+roles on ``EntityType``. Adding a relation or a type there puts it in the right lens
+here with no edit — a verb that lands on a ``place`` is geography, a verb an analyst
+states about a subject is the subject web, the rest follow their registry ``action``,
+and a type is drawn if its role says a picture of the case is about it. A lens the
+registries cannot derive would be a second vocabulary, which is the thing they exist
+to prevent.
+
+**A lens narrows nodes, not only verbs.** A case flows in one direction — sources,
+evidence, statements, deliverables — and the four stages are not four things to draw
+at the same rank. What the analyst *wrote* is the filing rather than the case: a post
+is cited by nothing, a note hangs off one node and is consulted rather than seen, so
+neither is in a reading of what the case is about. They are one lens away, not gone
+(``My work``). The narrowing reaches the **degree** as well as the drawing: a node
+stating a connection this reading cannot show would price a click that brings nothing.
+
+**The wrapper is an edge, and the count is what it says.** An attestation — a bookmark,
+a proof, a capture — is not a leaf: *this account posted it, this statement cites it* is
+a path through it, and that path is a fact about the case. Drawn as a node it says
+nothing and spends the budget; collapsed (``_fold``) the path survives and becomes
+legible as ``cites (3 sources · 1 account)``. "These three citations are one source"
+stops being a computation and becomes what the edge says, which is where the folding
+and the independence number meet. Nothing is removed silently: the edge names what it
+stands for, one click brings those nodes back, and a middle carrying anything an edge
+cannot say stays a node.
+
+**A step is an edge too, and it points one way.** A frame pulled out of a video and
+built into a proof is a node saying "there was a step here", and it costs a slot to say
+it — twelve saved frames draw as twelve pictures of one video. Collapsed (``_relay``)
+the step becomes what the edge is written with: *derived from 1 frame*. It folds on the
+same all-or-nothing rule, plus a direction guard the fold above does not need — a node
+with **two** outgoing chain edges is a confluence, not a passage, and collapsing a proof
+made from both a frame and an overhead capture would state that the capture came out of
+the footage. That is the false convergence, and it is the thing this reading is for.
+
+**And what came out of it and was not used is its own count.** Twelve frames saved off
+a video and cited by nothing draw as twelve pictures of that video; the video says *12
+frames* instead (``_roll``), and one click brings them back. Narrow on purpose: one
+edge, a chain verb, and the node is the end that was derived — a leaf with a single
+*relation* stays, because a person with one link is thin material the case has yet to
+exploit rather than clutter, and the direction decides which of a lone pair goes.
+
+**One finding on the ground is one arrow.** A proof concluding a coordinate states the
+point of the whole material behind it, so four arrows land on one dot and a reading of
+the ground draws no chain verb to say that three of them are the same picture. A reader
+counts four sources agreeing; there is one. ``_star`` groups them by their derivation —
+asked of the repository, since the redundancy is a fact the lens does not draw — and
+keeps the arrow on the **subject** root. A capture is the sharp case: pulled at the
+coordinates already suspected, it is the reference the comparison was made against
+rather than a witness, and the roles already say so (``media`` is a subject,
+``capture`` and ``proof`` are attestations). The place then reports what it really
+rests on, which is the geographic counterpart of the independence number.
+
+**On the arrangement.** A whole-case view also carries the nodes the analyst placed
+by hand (``pin``), because an arrangement somebody built is worth more than the one
+a relaxation computes, and losing it on reload would make dragging pointless. It is
+presentation, not a claim about the case, so it lives in its own table rather than on
+the entity, and it is **per lens**: a lens draws its own nodes and its own edges, so
+it clusters differently, and one shared arrangement would anchor every reading into
+the shape of whichever one it was built in. A neighbourhood carries none: distance
+from the root owns the horizontal axis there, and a pinned coordinate would
+contradict it.
+
+**On time.** No verb carries a date (ONTOLOGY §3) and dated statements are v4, so
+nothing here reads event time — that would be inventing a fact the case does not
+hold. What *is* real today is when work entered the case, and ``order="recent"``
+ranks on it. The seam is deliberate: a third ordering over stated time slots in
+beside these two without reshaping a response or a caller, because ordering is
+already the axis this module varies.
+"""
+
+from __future__ import annotations
+
+from dataclasses import dataclass
+from typing import Any
+
+from ..repository import CaseRepository
+from ..workspace import CaseError
+from . import entities, links
+
+#: **How many nodes a case opens on, not how many it may hold.** A ceiling that
+#: refuses is the app overruling the analyst about their own picture, and the drawing
+#: is a set they own: it grows from here without limit, and what a large one costs is
+#: said rather than prevented (UI *Graph*, the weight the drawing carries).
+#:
+#: An absolute count rather than a share of the case: a tenth of fifty entities is an
+#: empty picture and a tenth of ten thousand is a freeze. The case's own total is sent
+#: beside it — *300 of 1 050* — so a first draw states what it is a part of.
+OPENING_NODES = 300
+
+#: The largest first draw a caller may ask for. Not a ceiling on the drawing, which
+#: has none: it bounds one ranking query, so a typed URL cannot ask the database for
+#: a hundred thousand rows in one read.
+MAX_OPENING = 2000
+
+#: How far one expansion reaches. Two hops already fans out past what a screen
+#: holds on a well-linked case, so the budget stops the walk before the layout
+#: has to apologise for it.
+MAX_HOPS = 3
+
+#: How long a route between two entities may be before the answer stops being one.
+#: Four hops on a well-linked case reaches most of it, and a chain that long says
+#: "everything is connected to everything", which is true and useless.
+MAX_PATH_HOPS = 4
+
+#: How many equally-short routes are returned. Ties are the interesting case — two
+#: accounts reaching the same place by different sources is the finding — but past a
+#: dozen the answer is a hub, and the list stops being read.
+MAX_PATHS = 12
+
+#: Nodes one side of the search may load before it gives up. The guard against the
+#: hub: on a case where one account touches half the entities, an unbounded walk
+#: pulls the case into memory to answer a question about two of its nodes.
+MAX_PATH_VISIT = 4000
+
+#: Ranking, and with it which nodes a truncated view keeps.
+ORDERS: tuple[tuple[str, str, str], ...] = (
+ ("degree", "Most connected", "keeps the hubs, so a cut view still shows the shape"),
+ ("recent", "Latest work", "keeps what entered the case last"),
+)
+
+#: The roles a reading of the **case** draws. A deliverable carries nothing — nothing
+#: cites a post — and an annex hangs off one node, so neither belongs in a picture of
+#: what the case is about; both are drawn by the one lens that is about the filing.
+#: Attestations stay, because they are not leaves: a bookmark is a degree-2
+#: pass-through, and *this statement rests on this account* is a fact about the case.
+#: They leave the day the collapsed edge carries that path instead (SPEC §6).
+CASE_ROLES: tuple[str, ...] = (entities.SUBJECT, entities.ATTESTATION)
+
+#: The verbs that say where a source came from, and the only ones a collapse folds
+#: across. A statement rests on a source, and the source came from somewhere: an
+#: account published it, or it was made out of material the case already holds. That
+#: chain is what the collapsed edge carries.
+#:
+#: **The content verbs are deliberately absent.** `depicts`, `appears-in` and
+#: `located-at` say what is *in* the material, which is a subject-to-subject reading —
+#: a vehicle seen at a place is a finding, and folding the capture that shows both
+#: would state a claim about them the case never made. So an attestation holding one of
+#: those stays a node: it carries something the edge cannot say.
+PROVENANCE_VERBS: tuple[str, ...] = tuple(links.CHAIN_TYPES) + (links.POSTED,)
+
+#: How a collapsed edge's id is spelled. Deterministic from the pair and the verb, so
+#: the same case answers with the same id on every read and a selection survives a
+#: reload; prefixed because it is not a row anybody may write to, and the surfaces that
+#: confirm, rate or remove an edge have to be able to tell.
+FOLDED_PREFIX = "folded:"
+
+
+@dataclass(frozen=True)
+class Lens:
+ """One reading of the case: what it draws, and how it reads in words.
+
+ ``types`` is the **verbs**, resolved from the relation registry, and ``roles`` is
+ which **nodes**, resolved from the entity registry. Neither is listed, so the
+ vocabulary has exactly one home. ``hint`` is the one clause every other registry
+ carries, for the surface that has to explain itself.
+ """
+
+ id: str
+ label: str
+ hint: str
+ types: tuple[str, ...]
+ roles: tuple[str, ...]
+
+ @property
+ def hides(self) -> tuple[str, ...]:
+ """The declared entity types this reading leaves out of the drawing.
+
+ Stated as what is left out rather than as what is kept, and that is the load
+ bearing choice: a **free type** — one the vocabulary has never heard of — has
+ no role, so an allowlist resolved from the registry would silently drop an
+ entity nobody agreed to drop. An exclusion only ever removes what a role
+ explicitly claims.
+ """
+ left = set(entities.ROLES) - set(self.roles)
+ return tuple(sorted(entities.types_with_role(*left)))
+
+
+def _relation_verbs(predicate: Any) -> tuple[str, ...]:
+ return tuple(entry.type for entry in links.RELATION_TYPES if predicate(entry))
+
+
+def _lands_on_place(entry: links.RelationType) -> bool:
+ """Whether a verb's object is a point on the ground.
+
+ Geography is what a verb *targets*, not what it is called, so a relation
+ added later that puts something at a place joins the ground lens by itself.
+ """
+ return entry.action == "relation" and entities.PLACE in entry.to_families
+
+
+def lenses() -> tuple[Lens, ...]:
+ """The readings, in menu order: four of the case, then one of the filing.
+
+ Each is resolved from the two registries. The last one is not an extra control —
+ it is exactly the switch that lets the other four leave the analyst's own output
+ out of the drawing while keeping it one click away.
+ """
+ return (
+ Lens(
+ "all", "Everything",
+ "every connection between the things the case is about",
+ tuple(links.CHAIN_TYPES) + _relation_verbs(lambda e: True),
+ CASE_ROLES,
+ ),
+ Lens(
+ "subjects", "Subjects",
+ "who owns, belongs to, posted or appears in what",
+ # `same-image-as` is here rather than with the artifact chain: two files
+ # being one picture is a fact about the case, not about the filing, and
+ # `media` is a subject. Filed with the chain verbs it made one lens hold a
+ # derivation and a finding about the world at once.
+ _relation_verbs(lambda e: e.action == "relation" and not _lands_on_place(e)),
+ CASE_ROLES,
+ ),
+ Lens(
+ "ground", "Ground",
+ "what is tied to a place on the map",
+ _relation_verbs(_lands_on_place),
+ CASE_ROLES,
+ ),
+ Lens(
+ "claims", "Statements",
+ "what is asserted, and what it rests on",
+ _relation_verbs(lambda e: e.action == "claim"),
+ CASE_ROLES,
+ ),
+ # The filing, read on its own terms. `derived-from` and `depends-on` answer
+ # *what did I write, and out of what*, and `mentions` starts at a `document` by
+ # construction, so it has never held one subject-to-subject edge. Three verbs
+ # that are all one question, and they sat in the same menu as Subjects and
+ # Ground as though they were peers.
+ Lens(
+ "work", "My work",
+ "what you wrote, what it was made from, and what it points at",
+ tuple(links.CHAIN_TYPES) + _relation_verbs(lambda e: e.action == "mention"),
+ entities.ROLES,
+ ),
+ )
+
+
+def lens(lens_id: str) -> Lens:
+ """One lens by id, defaulting to everything when none was asked for."""
+ wanted = lens_id or "all"
+ found = next((entry for entry in lenses() if entry.id == wanted), None)
+ if found is None:
+ raise CaseError(f"'{lens_id}' is not a lens")
+ return found
+
+
+def view(
+ case: CaseRepository,
+ *,
+ lens_id: str = "all",
+ limit: int | None = None,
+ types: list[str] | None = None,
+ status: str | None = None,
+ query: str | None = None,
+ folder: str | None = None,
+ unfiled: bool = False,
+ recursive: bool = False,
+ attr: str | None = None,
+ attr_value: str | None = None,
+ linked: str | None = None,
+ unlinked: bool = False,
+ since: str | None = None,
+ until: str | None = None,
+ filed_by: list[str] | None = None,
+ temporal_since: str | None = None,
+ temporal_until: str | None = None,
+ temporal_categories: list[str] | None = None,
+ order: str = "degree",
+ keep: list[str] | None = None,
+ expand: list[str] | None = None,
+ omit: list[str] | None = None,
+) -> dict[str, Any]:
+ """The whole case as one bounded graph, and a set the caller may edit by hand.
+
+ Returns ``{lens, order, nodes, links, total, shown, truncated, isolated}``.
+ ``links`` is the closed set — both ends among the nodes returned — so nothing
+ drawn points at a node that was not sent.
+
+ ``isolated`` counts the entities this lens joins to nothing, which is the case's
+ unexploited material and the one number a table cannot show. It is a count over
+ the **case**, like ``total``, not over what was drawn: a node with no edge sorts
+ last, so a cut discards it first, and read off the returned nodes the number
+ reported zero on exactly the cases large enough to need it.
+
+ Three lists edit the ranked set, and the split between the first two is the point:
+ a node can be **drawn** without its neighbourhood being drawn with it.
+
+ ``keep``
+ these nodes are drawn, and nothing around them. A route through four nodes,
+ or one entity named in the search, is a small precise answer — expanded, each
+ of them dragged its whole neighbourhood in and buried it.
+ ``expand``
+ these, plus one hop each. The drill-down, unchanged.
+ ``omit``
+ these are not drawn, whichever of the ranking, ``keep`` or a hop put them
+ there, **and neither is the arrival no anchor still reaches**: what came in
+ because a node was opened leaves with it, or the picture keeps a handful of
+ dots joined to nothing. Applied last, so nothing can hand back a node the
+ analyst took out. This is what makes a drawing that grows without limit usable:
+ the way back was folding every expansion, which takes the reading down with it.
+
+ ``keep`` and ``expand`` arrive **beside** the case rather than instead of it, and
+ they ignore the filters: an analyst who named a node is asking about the case, not
+ about the narrowing they set earlier. The nodes named are kept even when the
+ ranking or the filters would have dropped them, or the view would answer a
+ question with the question missing from it.
+
+ **The lens outranks a named node**, which is the one place it differs from a
+ filter. A filter is a narrowing the analyst set earlier; a lens is the reading
+ itself, so a type it does not draw is not drawn because it was asked for by name
+ either — it is drawn by switching reading. What comes back says which nodes were
+ actually drawn by name (``kept``) and which were actually opened (``expanded``),
+ so a caller never holds one the drawing refused.
+ """
+ entry = lens(lens_id)
+ verbs = list(entry.types)
+ hidden = list(entry.hides)
+ bounded = max(1, min(int(OPENING_NODES if limit is None else limit), MAX_OPENING))
+ if order not in {value for value, _, _ in ORDERS}:
+ raise CaseError(f"'{order}' is not an ordering")
+
+ ranked = case.rank_entities(
+ limit=bounded, types=types, exclude_types=hidden, status=_status(status),
+ query=query, folder=folder, unfiled=unfiled, recursive=recursive,
+ attr=attr, attr_value=attr_value, linked=linked, unlinked_only=unlinked,
+ since=since, until=until, filed_by=filed_by,
+ temporal_since=temporal_since, temporal_until=temporal_until,
+ temporal_categories=temporal_categories,
+ link_types=verbs, order=order,
+ )
+ nodes = ranked["entities"]
+ degrees = dict(ranked["degrees"])
+ held, by_name = _hold(case, nodes, keep, verbs, hidden, degrees)
+ nodes = nodes + held
+ grown, opened = _grow(case, nodes, expand, verbs, hidden, degrees)
+ nodes = nodes + grown
+ ids = [node["id"] for node in nodes]
+ edges = case.links_among(ids, types=verbs) if ids else []
+ named = {
+ entity_id for entity_id in list(keep or []) + list(expand or []) if entity_id
+ }
+ # What arrived by a hop rather than by rank or by name. These are the only nodes a
+ # removal may take with it: a ranked node stands on its own — it is allowed to have
+ # no edge at all, which is what ``isolated`` counts — and a named one was asked for.
+ hops = {node["id"] for node in grown if node["id"] not in named}
+ taken = {entity_id for entity_id in (omit or []) if entity_id}
+ nodes, edges, severed = _take_out(nodes, edges, omit, degrees, hops)
+ nodes, edges, rests = _fold(case, entry, nodes, edges, degrees, named, taken, severed)
+ # Read before the relay pass rather than after it, because the passes spend them:
+ # a folded passage is off the drawing by the time the nodes are built, and the word
+ # its edge is written with — *1 frame* rather than *1 media* — is its own origin.
+ origins = _origins(case, nodes)
+ nodes, edges, agree = _star(case, entry, nodes, edges, named, opened, origins)
+ rests = {**rests, **agree}
+ nodes, edges = _relay(entry, nodes, edges, degrees, named, origins)
+ nodes, edges, rolled = _roll(entry, nodes, edges, named, opened, origins)
+ thumbs = _previews(case, nodes)
+ kinds = _kinds(case, nodes)
+ pins = case.graph_pins(entry.id)
+ arrived = {node["id"] for node in grown + held}
+ return {
+ "lens": entry.id,
+ "order": order,
+ "nodes": [
+ _node(
+ node, degrees.get(node["id"], 0),
+ thumb=thumbs.get(node["id"]), kind=kinds.get(node["id"]),
+ origin=origins.get(node["id"]),
+ pin=pins.get(node["id"]),
+ added=node["id"] in arrived,
+ rests=rests.get(node["id"]),
+ rolled=rolled.get(node["id"]),
+ query=query,
+ )
+ for node in nodes
+ ],
+ "links": edges,
+ "total": ranked["total"],
+ "shown": len(nodes),
+ "truncated": ranked["truncated"],
+ # Counted over the whole filtered case, never over what was drawn. A
+ # degree-0 entity sorts last, so a cut discards it first: read off the
+ # returned nodes, the case's unexploited material reported zero on exactly
+ # the cases too large to draw, which is the one place it is worth knowing.
+ "isolated": ranked["unlinked"],
+ # How many drawn statements rest on more than one source and yet on a single
+ # account. The independence number, and it is a **read over the edges** rather
+ # than a computation of its own: the collapsed edge already carries how many
+ # sources it stands for and how many accounts published them. Counted over the
+ # drawing, like the match count and unlike the total, because that is the set
+ # whose edges were read.
+ "single_account": sum(1 for held in rests.values() if held["one"]),
+ # The nodes actually drawn by name, and the nodes actually opened. Neither is
+ # always what was asked for: one deleted in another tab, or of a type this
+ # reading does not draw, is absent rather than reported held — so the caller's
+ # own list never keeps an id the drawing refused, and no control offers to fold
+ # or hand back a ghost. A removal needs no such answer: taking a node out of a
+ # picture always succeeds, which is why `omit` is not echoed.
+ "kept": by_name,
+ "expanded": opened,
+ # Every pin this lens holds, not only the ones on screen: the control that
+ # offers to undo the arrangement has to appear even when the pinned nodes
+ # were cut from this view or filtered out of it.
+ "pinned": len(pins),
+ }
+
+
+def snapshot_view(
+ snapshot: dict[str, Any], *, lens_id: str = "all", query: str | None = None
+) -> dict[str, Any]:
+ """Draw one immutable captured set without consulting the live case.
+
+ Snapshot entities and links were validated when the view was saved or duplicated.
+ The lens is still applied because it is part of how the reading was made, but no
+ current entity, relation, thumbnail or pin can rewrite what the capture contains.
+ """
+ entry = lens(lens_id)
+ hidden = set(entry.hides)
+ verbs = set(entry.types)
+ raw_nodes = [
+ entity for entity in snapshot.get("entities", [])
+ if entity.get("type") not in hidden
+ ]
+ ids = {entity["id"] for entity in raw_nodes}
+ raw_links = [
+ link for link in snapshot.get("links", [])
+ if link.get("from") in ids and link.get("to") in ids
+ and (not verbs or link.get("type") in verbs)
+ ]
+ degrees = {entity_id: 0 for entity_id in ids}
+ for link in raw_links:
+ degrees[link["from"]] += 1
+ degrees[link["to"]] += 1
+ nodes = [_node(entity, degrees[entity["id"]], query=query) for entity in raw_nodes]
+ return {
+ "lens": entry.id,
+ "order": "snapshot",
+ "nodes": nodes,
+ "links": raw_links,
+ "total": len(nodes),
+ "shown": len(nodes),
+ "truncated": False,
+ "isolated": sum(1 for degree in degrees.values() if degree == 0),
+ "single_account": 0,
+ "kept": [],
+ "expanded": [],
+ "pinned": 0,
+ "snapshot": True,
+ "captured_at": snapshot.get("captured_at"),
+ }
+
+
+def _hold(
+ case: CaseRepository,
+ ranked: list[dict[str, Any]],
+ keep: list[str] | None,
+ verbs: list[str],
+ hidden: list[str],
+ degrees: dict[str, int],
+) -> tuple[list[dict[str, Any]], list[str]]:
+ """The nodes named to be drawn, and **nothing around them**.
+
+ The half of the old ``expand`` that was never expressible: *draw this one*. Both
+ acts were one parameter, so every named node arrived with its whole
+ neighbourhood — which is right for opening a node and wrong for everything else.
+ A route of four nodes came in with four neighbourhoods around it and the answer
+ was buried in the crowd it brought.
+
+ Returns ``(arrivals, drawn)``. ``drawn`` is the ids the drawing actually holds, in
+ the order they were asked for, so a caller's own list can be pruned of what this
+ reading refuses: an entity the case no longer has, or one of a type the lens does
+ not draw. **Nothing here is refused for room**: the drawing has no ceiling, and a
+ node named by an analyst is the last thing that should be told there is no space.
+
+ Sorted by degree, then label, then id — the tie-break the layout and ``_grow``
+ already use — so the same case draws the same picture whatever order the database
+ returned.
+ """
+ wanted = [entity_id for entity_id in dict.fromkeys(keep or []) if entity_id]
+ if not wanted:
+ return [], []
+
+ present = {node["id"] for node in ranked}
+ left_out = set(hidden)
+ found = [
+ entity
+ for entity in case.entities_by_ids(wanted)
+ if entity["type"] not in left_out
+ ]
+ arrivals = [entity for entity in found if entity["id"] not in present]
+ if not arrivals:
+ already = {entity["id"] for entity in found}
+ return [], [i for i in wanted if i in already]
+
+ known = case.degrees_of(
+ [entity["id"] for entity in arrivals], types=verbs, exclude_types=hidden
+ )
+ arrivals.sort(
+ key=lambda entity: (
+ -known.get(entity["id"], 0),
+ str(entity["label"]),
+ entity["id"],
+ )
+ )
+ degrees.update({entity["id"]: known.get(entity["id"], 0) for entity in arrivals})
+ drawn = {entity["id"] for entity in found if entity["id"] in present}
+ drawn.update(entity["id"] for entity in arrivals)
+ return arrivals, [i for i in wanted if i in drawn]
+
+
+def _take_out(
+ nodes: list[dict[str, Any]],
+ edges: list[dict[str, Any]],
+ omit: list[str] | None,
+ degrees: dict[str, int],
+ hops: set[str],
+) -> tuple[list[dict[str, Any]], list[dict[str, Any]], list[dict[str, Any]]]:
+ """The nodes taken out of the drawing by hand, and the edges that went with them.
+
+ **Last, and over everything**, which is the whole of why it works: applied to the
+ ranking alone, a node removed came back the moment a neighbour was opened, and the
+ analyst was arguing with the ranking about their own picture.
+
+ ``degrees`` is corrected in place, for the same reason the fold corrects it: a
+ degree says what a click would bring in, and a removed node is not something a
+ click can bring back — a neighbour left offering to open it would answer with an
+ unchanged picture. What the removed node itself said no longer matters; it is not
+ drawn.
+
+ A middle taken out is still a middle. The fold runs after this and reads the case
+ rather than the drawing, so a bookmark removed by hand comes back as the edge it
+ always stood for — the path through it is a fact about the case, and this act was
+ about the picture. The edge names it, and one click draws it again.
+
+ **A ranked node is not taken by it.** One left with no edge after a removal is still
+ a node the case ranked, and its reason to be drawn was never the neighbour that
+ went: taking it too overrules the ranking, and on a small case removing one node
+ empties the picture. Only what arrived by a hop is held by what brought it.
+ """
+ out = {entity_id for entity_id in (omit or []) if entity_id}
+ if not out:
+ return nodes, edges, []
+
+ standing = []
+ severed = []
+ for link in edges:
+ ends = (link["from"], link["to"])
+ if not out.intersection(ends):
+ standing.append(link)
+ continue
+ severed.append(link)
+ for end in ends:
+ if end not in out and end in degrees:
+ degrees[end] = max(degrees[end] - 1, 0)
+ kept, standing = _stranded(
+ [node for node in nodes if node["id"] not in out], standing, hops
+ )
+ return kept, standing, severed
+
+
+def _stranded(
+ nodes: list[dict[str, Any]],
+ edges: list[dict[str, Any]],
+ hops: set[str],
+) -> tuple[list[dict[str, Any]], list[dict[str, Any]]]:
+ """What a removal leaves behind that nothing was holding but the node removed.
+
+ Taking a node out used to take only that node: the three media its expansion had
+ brought stayed drawn with no edge to anything, and the picture kept a handful of
+ dots whose only reason to be there had just left. The act says *this picture is not
+ about it*, and a neighbourhood nothing else reaches is not about anything either.
+
+ **It is reachability, not degree**, because the vocabulary ranks no edge above
+ another and there is no such thing as the link that holds a node. An arrival stays
+ while something standing on its own still reaches it, through however many other
+ arrivals: a pair that only holds each other is as adrift as a single dot, and
+ counting edges would keep it.
+
+ ``hops`` is what arrived by a hop. Everything else drawn is an anchor — a ranked
+ node, which is allowed to have no edge at all, or one named by ``keep`` or
+ ``expand``, which was asked for. Two anchors are the common way an arrival
+ survives: a second expansion that reached the same node, which is the convergence
+ the drawing exists to show, and an arrival joined to something the ranking drew.
+
+ No degree is corrected here. A node this drops is unreachable from every anchor, so
+ everything it touched is unreachable too and goes with it — no node still drawn
+ loses an edge.
+ """
+ drawn = {node["id"] for node in nodes}
+ reach = {entity_id for entity_id in drawn if entity_id not in hops}
+ if len(reach) == len(drawn):
+ return nodes, edges
+
+ near: dict[str, list[str]] = {}
+ for link in edges:
+ near.setdefault(link["from"], []).append(link["to"])
+ near.setdefault(link["to"], []).append(link["from"])
+ frontier = list(reach)
+ while frontier:
+ for far in near.get(frontier.pop(), ()):
+ if far in drawn and far not in reach:
+ reach.add(far)
+ frontier.append(far)
+ if len(reach) == len(drawn):
+ return nodes, edges
+ return (
+ [node for node in nodes if node["id"] in reach],
+ [link for link in edges if link["from"] in reach and link["to"] in reach],
+ )
+
+
+def _grow(
+ case: CaseRepository,
+ ranked: list[dict[str, Any]],
+ expand: list[str] | None,
+ verbs: list[str],
+ hidden: list[str],
+ degrees: dict[str, int],
+) -> tuple[list[dict[str, Any]], list[str]]:
+ """One hop around each opened node, as the entities the ranked set is missing.
+
+ Returns ``(arrivals, opened)`` and fills ``degrees`` for what it brings, so an
+ arrival states its own cost like every other node.
+
+ **Nothing is cut for room.** An expansion is the one thing in the tool the analyst
+ asked for outright, and the drawing has no ceiling to refuse it with: every missing
+ neighbour of an opened node arrives, so the node's own degree drops to what is
+ drawn and the control that offered the act stops offering it. Arrivals are still
+ sorted by degree, then label, then id — the tie-break the layout uses — so the same
+ case draws the same picture whatever order the database returned.
+
+ **``opened`` is what this reading drew, not what was asked for.** A type the lens
+ does not draw is refused here as it is everywhere else: the reading decides what is
+ on screen, and a named node is not an exception to it.
+ """
+ wanted = [entity_id for entity_id in dict.fromkeys(expand or []) if entity_id]
+ if not wanted:
+ return [], []
+
+ present = {node["id"] for node in ranked}
+ left_out = set(hidden)
+ # An opened node that the filters or the cut left out comes back first: a view
+ # answering "what touches this" without the node itself is a broken sentence. One
+ # this reading does not draw at all is not opened, and says so by its absence from
+ # what is returned.
+ opened = [
+ entity["id"]
+ for entity in case.entities_by_ids(wanted)
+ if entity["type"] not in left_out
+ ]
+ if not opened:
+ return [], []
+
+ reached: set[str] = set()
+ # An edge onto a node this reading leaves out never arrives here, so a neighbour
+ # the lens does not draw is not brought in by an expansion either: the reading
+ # decides what is on screen, and asking about one node is not a way around it.
+ for link in case.links_touching(opened, types=verbs, exclude_types=hidden):
+ for end in (link["from"], link["to"]):
+ if end not in present:
+ reached.add(end)
+ for entity_id in opened:
+ # An opened node the ranking or the filters left out is itself an arrival, and
+ # bringing it back is the expansion doing its job.
+ if entity_id not in present:
+ reached.add(entity_id)
+
+ found = case.entities_by_ids(sorted(reached))
+ if not found:
+ # Everything these nodes touch is already drawn: opened, with nothing to show
+ # for it, which is a true answer and not a failure. Returned here rather than
+ # falling through, to spare the degree query the common case does not need.
+ return [], opened
+
+ known = case.degrees_of(
+ [entity["id"] for entity in found], types=verbs, exclude_types=hidden
+ )
+ # An opened node still comes before the neighbours it brought, which is what makes
+ # the picture the same on every read of the same case.
+ order = {entity_id: 0 for entity_id in opened}
+ found.sort(
+ key=lambda entity: (
+ order.get(entity["id"], 1),
+ -known.get(entity["id"], 0),
+ str(entity["label"]),
+ entity["id"],
+ )
+ )
+ degrees.update({entity["id"]: known.get(entity["id"], 0) for entity in found})
+ return found, opened
+
+
+def _fold(
+ case: CaseRepository,
+ entry: Lens,
+ nodes: list[dict[str, Any]],
+ edges: list[dict[str, Any]],
+ degrees: dict[str, int],
+ named: set[str],
+ out: set[str],
+ severed: list[dict[str, Any]],
+) -> tuple[list[dict[str, Any]], list[dict[str, Any]], dict[str, dict[str, int]]]:
+ """Attestations on a statement→source chain, as one edge each instead of a node.
+
+ **The wrapper is an edge, and the count is what it says.** A bookmark is not a leaf:
+ ``account posted it`` and ``statement cites it`` is a path through it, and that path
+ is a fact about the case rather than about the filing. Drawn as a node it says
+ nothing and spends a third of the budget; collapsed, the same path becomes legible:
+
+ ::
+
+ before claim → bookmark → account A
+ bookmark → account A
+ bookmark → account A
+ after claim --cites (3 sources · 1 account)--> account A
+
+ "These three citations are one source" stops being a computation and becomes what
+ the edge says, which is where the folding and the independence number meet.
+
+ **Only across provenance, and only all of it** (``PROVENANCE_VERBS``). A middle
+ whose drawn edges are not every one either a statement's or a provenance verb's
+ stays a node: it is carrying something an edge between its two neighbours cannot
+ say. That is what keeps a capture showing a place from turning "this vehicle
+ appears in it" and "it shows this place" into a claim about the vehicle and the
+ place.
+
+ **A middle that is not drawn is still a middle.** Two things keep one out of the
+ picture, and neither is a reason to lose the path through it:
+
+ * its **type** is one this reading leaves out. A reconstructed case bends its own
+ types — an import can file an external source under a type meant for the
+ analyst's own output — so shape outranks the type name (SPEC §6).
+ * the **budget** cut it. This is the common one and the one that matters, because
+ the ranking cuts the least connected first, which is exactly the sources this
+ folds. Left out, the fold only kept its promise below the ceiling: on a case too
+ large to draw whole — the case that needed it — a statement resting on nine
+ sources and one account drew as a lone dot with both of its ends on screen and
+ nothing joining them.
+
+ One query answers both, and the guard is the same: the middle is not drawn, the
+ far end is. What that query cannot see is the middle's edges to nodes that are not
+ drawn either, and it does not need to — an edge with an undrawn end is not an edge
+ this picture could have shown, so "all of it, or none" is asked of everything the
+ reading can actually say.
+
+ **A named node is never folded**, which is also the way back: the collapsed edge
+ carries the ids it stands for, and asking for one of them by name draws it as a node
+ with its own edges again. That is what makes the collapse a reading rather than a
+ loss, and it is why a route through a bookmark still lands.
+
+ Returns ``(nodes, links, rests)``. ``rests`` is per drawn statement
+ ``{"sources": n, "accounts": m}`` — what the independence number is read off.
+ ``degrees`` is corrected in place: a claim whose three citations became one edge
+ would otherwise price a click at three and bring nothing, which is the failure the
+ honest degree exists to prevent.
+ """
+ drawn = {node["id"]: node for node in nodes}
+ claims = {
+ node_id
+ for node_id, node in drawn.items()
+ if entities.family_of(node["type"]) == entities.CLAIM
+ }
+ if not claims:
+ return nodes, edges, {}
+
+ hidden = list(entry.hides)
+ unseen = set(hidden)
+ kinds = {node_id: node["type"] for node_id, node in drawn.items()}
+ # Every edge a candidate middle holds, as (link, the node at its other end).
+ legs: dict[str, list[tuple[dict[str, Any], str]]] = {}
+ # ``severed`` too: a removal cuts the provenance edge before this runs, so read from
+ # the drawing alone the chain has already lost the leg that makes it one.
+ for link in list(edges) + list(severed):
+ for near, far in ((link["from"], link["to"]), (link["to"], link["from"])):
+ node = drawn.get(near)
+ if node is None or near in named or near in claims:
+ continue
+ if entities.role_of(node["type"]) != entities.ATTESTATION:
+ continue
+ legs.setdefault(near, []).append((link, far))
+
+ # One query for the edges that reach a middle this drawing does not hold: a type
+ # the reading leaves out, or an attestation the budget cut. Both legs of a bridge
+ # come back from it — each has one end drawn (the statement, the account) and the
+ # other end the middle — so the row names the bridge and what it bridges to at
+ # once. Rows whose middle *is* drawn come back too and are dropped here rather
+ # than in SQL: they are the ones the pass above already holds.
+ #
+ # Unmeasured, and worth measuring before it is defended: the list is never empty
+ # now, so the query runs in every lens rather than only where a type was left out,
+ # and on a case with many captures and proofs the rows it discards are a second scan
+ # of what the pass above already read.
+ bridging = sorted(unseen | entities.types_with_role(entities.ATTESTATION))
+ if bridging and drawn:
+ for link in case.links_touching(
+ list(drawn), types=list(entry.types), end_types=bridging
+ ):
+ middle = link["to"] if link["from"] in drawn else link["from"]
+ far = link["from"] if middle == link["to"] else link["to"]
+ # A named node is never folded, drawn or not. Absent, it was refused by the
+ # reading itself, and folding it would offer to hand back an id already in
+ # the expansion — a button that answers a click with nothing.
+ if middle in drawn or middle in named or far not in drawn:
+ continue
+ legs.setdefault(middle, []).append((link, far))
+ outside = [middle for middle in legs if middle not in drawn]
+ if outside:
+ kinds.update(
+ {entity["id"]: entity["type"] for entity in case.entities_by_ids(outside)}
+ )
+
+ held: dict[tuple[str, str, str], dict[str, Any]] = {}
+ gone: set[str] = set()
+ dropped: set[str] = set()
+ # What each statement turns out to rest on, kept as ids so a source folded onto two
+ # different accounts is one source rather than two. `attributed` is the sources whose
+ # publisher is known at all, which is what keeps "all on one account" from being
+ # claimed about a set half of which nobody has traced.
+ rests: dict[str, dict[str, set[str]]] = {
+ claim_id: {"sources": set(), "accounts": set(), "attributed": set()}
+ for claim_id in claims
+ }
+ for middle, incident in legs.items():
+ stated = [
+ (link, far)
+ for link, far in incident
+ if far in claims and link["type"] in links.CLAIM_CONNECTION_TYPES
+ ]
+ provenance = [
+ (link, far)
+ for link, far in incident
+ if link["type"] in PROVENANCE_VERBS
+ and (far in drawn or far in out)
+ and far not in claims
+ ]
+ if not stated or not provenance:
+ continue
+ # All of it, or none: a middle holding one edge this cannot express stays where
+ # it is rather than being folded into a picture that leaves that edge out.
+ if len(stated) + len(provenance) != len(incident):
+ continue
+ publishers = {far for link, far in provenance if link["type"] == links.POSTED}
+ gone.add(middle)
+ for link, _ in incident:
+ dropped.add(link["id"])
+ for near, claim_id in stated:
+ rests[claim_id]["sources"].add(middle)
+ rests[claim_id]["accounts"].update(publishers)
+ if publishers:
+ rests[claim_id]["attributed"].add(middle)
+ for far_link, far_id in provenance:
+ # Taken out by hand: the middle still goes, and no edge is drawn to a
+ # node that is not there. A removal must never *add* a node, and
+ # restoring the three bookmarks an account's fold stood for is exactly
+ # that — two nodes became four on the one act that promised fewer.
+ if far_id in out:
+ continue
+ key = (claim_id, far_id, near["type"])
+ folded = held.setdefault(
+ key,
+ {"middles": {}, "accounts": set(), "open": set(),
+ "at": "", "suggested": False},
+ )
+ folded["middles"][middle] = kinds.get(middle, "")
+ folded["accounts"].update(publishers)
+ # Offered back when this reading would draw the middle at all — which
+ # is a question about its type, not about whether it is on screen. A
+ # source the budget cut is handed back by the same `expand` that opens
+ # a node; one of a type the lens leaves out could only be refused, so
+ # the edge names the lens that does draw it instead.
+ if kinds.get(middle, "") not in unseen:
+ folded["open"].add(middle)
+ for one in (near, far_link):
+ folded["at"] = max(folded["at"], one["provenance"].get("at", ""))
+ if one["provenance"].get("status") == "suggested":
+ folded["suggested"] = True
+
+ # ``gone`` without ``held`` is the fold whose far end was taken out by hand: there
+ # is no edge to draw, and the middles still leave.
+ if not held and not gone:
+ return nodes, edges, _counted(rests, edges, claims, drawn)
+
+ # A degree says what a click would bring in, so it answers to what is drawn: three
+ # citations that became one edge are one connection now, and the two the fold
+ # removed must not go on being offered.
+ for link in edges:
+ if link["id"] not in dropped:
+ continue
+ for end in (link["from"], link["to"]):
+ if end in degrees and end not in gone:
+ degrees[end] = max(degrees[end] - 1, 0)
+
+ synthetic = [
+ {
+ "id": f"{FOLDED_PREFIX}{verb}:{from_id}:{to_id}",
+ "from": from_id,
+ "to": to_id,
+ "type": verb,
+ "folded": {
+ "sources": len(folded["middles"]),
+ "via": sorted({kind for kind in folded["middles"].values() if kind}),
+ "accounts": len(folded["accounts"]),
+ **({"open": sorted(folded["open"])} if folded["open"] else {}),
+ },
+ "provenance": {
+ # No author: nobody wrote this edge, the reading did. What it can say
+ # honestly is when the path was last stated, and that it is only as
+ # confirmed as its weakest part — a fold must not launder a proposal
+ # into a finding.
+ "by": "graph",
+ "at": folded["at"],
+ "status": "suggested" if folded["suggested"] else "confirmed",
+ },
+ }
+ for (from_id, to_id, verb), folded in sorted(held.items())
+ ]
+ for link in synthetic:
+ for end in (link["from"], link["to"]):
+ if end in degrees:
+ degrees[end] = degrees.get(end, 0) + 1
+
+ kept = [node for node in nodes if node["id"] not in gone]
+ standing = [link for link in edges if link["id"] not in dropped]
+ return kept, standing + synthetic, _counted(rests, standing, claims, drawn)
+
+
+def _star(
+ case: CaseRepository,
+ entry: Lens,
+ nodes: list[dict[str, Any]],
+ edges: list[dict[str, Any]],
+ named: set[str],
+ opened: list[str],
+ origins: dict[str, dict[str, str]],
+) -> tuple[list[dict[str, Any]], list[dict[str, Any]], dict[str, dict[str, int]]]:
+ """One finding on the ground drawn once, and what it actually rests on.
+
+ A proof concluding a coordinate states the point of **the whole material behind
+ it** — the frame, the collage, the video two hops up, the capture
+ (``satellite._state_point``). Four arrows then converge on one dot, and since a
+ reading of the ground draws no chain verb, nothing on screen says three of the four
+ are the same picture. A reader counts four sources that agree. There is one.
+
+ Clutter is annoying; a false independence claim is a finding the case never made.
+ That is what this collapses.
+
+ **The derivation is read even where the reading does not draw it.** Ground holds no
+ chain verb at all, and the redundancy is exactly a fact about the chain — so the
+ repository is asked, like the safeguard query in ``_fold`` already does. The lens
+ decides what is *drawn*, never what is *known*.
+
+ **One edge per root, and the roots are the subjects.** Group the nodes pointing at
+ the same place with the same verb, join them by their derivations, and the arrow
+ stays on the material the finding is about. The rest fold into it and come back with
+ a click.
+
+ A capture is the sharp case and it is why the roles decide. Pulled at the
+ coordinates already under suspicion, it is the **reference the comparison was made
+ against**, and its ``depicts`` is close to a tautology: counting it as a second
+ source states a corroboration nobody found. Shape cannot tell it from the footage —
+ in the worked example both have one chain leaving them and one arrow landing — but
+ the vocabulary already has: ``media`` is a ``subject``, ``capture`` and ``proof``
+ are ``attestation``, the role that means *a wrapper carrying a path*. So a subject
+ root keeps the arrow and an attestation root folds into it. A group with no subject
+ root keeps its own: a capture nobody made a proof from is the only thing saying
+ anything about that point, and it is drawn.
+
+ **All or nothing, as everywhere else here.** A member holding an edge this cannot
+ express — a second place, a claim citing it, a derivation reaching outside the
+ group — stays a node with its own arrow. It is carrying something the collapsed
+ line cannot say.
+
+ **The arrow that survives is the case's own row.** Not a synthetic id: the video
+ really does state that point, and an analyst has to be able to confirm or withdraw
+ it. So it is annotated (``merged``) rather than replaced, and the acts on it stay.
+
+ **The one fold whose degree is left alone, and expanding beats it.** Every other
+ collapse here hands its nodes back from a line that *touches* them: the bookmarks a
+ claim cited are on the claim's own edge, the step between a proof and a video is on
+ the line between the two. Not this one — a proof that stays drawn loses its
+ derivations to a frame and a capture now named on ``video → place``, **a line that
+ does not touch the proof at all**. Priced down to nothing, that node would say it has
+ no more connections while the analyst is looking straight at two that exist. So the
+ degree keeps counting them, and **what an opened node touches is never folded**: the
+ click is the analyst asking for exactly these, and it has to answer with them. Read
+ off the neighbours rather than off what the expansion *brought*, because on a case
+ that fits they are all drawn already and the expansion brings nothing at all — which
+ is precisely where the click used to answer with the picture it was pressed on.
+
+ Returns ``(nodes, links, agree)``. ``agree`` is per place ``{sources, accounts,
+ one}`` — how many independent origins land on it, the geographic counterpart of
+ ``single_account``, reported only where more than one arrow arrived and the number
+ is therefore a reading rather than a restatement of the picture.
+ """
+ landing = {item.type for item in links.RELATION_TYPES if _lands_on_place(item)}
+ landing &= set(entry.types)
+ if not landing:
+ return nodes, edges, {}
+
+ drawn = {node["id"]: node for node in nodes}
+ stars: dict[str, dict[str, list[dict[str, Any]]]] = {}
+ for link in edges:
+ if link["type"] not in landing or link.get("folded"):
+ continue
+ target = drawn.get(link["to"])
+ if target is None or entities.family_of(target["type"]) != entities.PLACE:
+ continue
+ if link["from"] in drawn and link["from"] != link["to"]:
+ stars.setdefault(link["to"], {}).setdefault(link["type"], []).append(link)
+ if not stars:
+ return nodes, edges, {}
+
+ # One read for every star at once. These are the edges the reading may not draw and
+ # the whole answer depends on: Ground holds no chain verb, so asked of the drawing
+ # alone, four arrows off one video are four unrelated sources.
+ everyone = sorted(
+ {link["from"] for verbs in stars.values() for group in verbs.values() for link in group}
+ )
+ chain = case.links_touching(everyone, types=list(links.CHAIN_TYPES))
+
+ incident: dict[str, list[dict[str, Any]]] = {}
+ for link in edges:
+ for end in (link["from"], link["to"]):
+ if end in drawn:
+ incident.setdefault(end, []).append(link)
+ spared = set(named) | {
+ (link["to"] if link["from"] == one else link["from"])
+ for one in opened
+ for link in incident.get(one, ())
+ }
+
+ landed: dict[str, int] = {}
+ behind: dict[str, set[str]] = {}
+ folding: set[str] = set()
+ # Keyed by the arrow that absorbs them: one node can state two points, and what it
+ # took on the first is not what it took on the second.
+ merged: dict[str, set[str]] = {}
+ for place_id, verbs in sorted(stars.items()):
+ # **The family is every arrow on the point, whatever verb it is written with.**
+ # Answering POV writes `located-at` on the material and leaves `depicts` on the
+ # composition and the capture, so one material arrives under two verbs. Read per
+ # verb, each half sees the other as outside itself, the all-or-nothing rule
+ # refuses both and nothing collapses at all — and the picture goes back to
+ # claiming two origins where the case has one.
+ family = {link["from"] for group in verbs.values() for link in group}
+ landed[place_id] = sum(len(group) for group in verbs.values())
+ arrows: dict[str, dict[str, str]] = {}
+ for verb, group in verbs.items():
+ for link in group:
+ arrows.setdefault(link["from"], {})[verb] = link["id"]
+
+ out: dict[str, set[str]] = {member: set() for member in family}
+ near: dict[str, set[str]] = {member: set() for member in family}
+ for link in chain:
+ source, holder = link["to"], link["from"]
+ if holder in family and source in family and holder != source:
+ out[holder].add(source)
+ near[holder].add(source)
+ near[source].add(holder)
+
+ def _roots(start: str, out: dict[str, set[str]] = out) -> set[str]:
+ """Where this one's derivation ends. Itself when it starts nowhere, and
+ when it runs in a circle — a loop names no origin, so nothing on it may
+ claim to be one."""
+ seen: set[str] = set()
+ found: set[str] = set()
+ frontier = [start]
+ while frontier:
+ current = frontier.pop()
+ if current in seen:
+ continue
+ seen.add(current)
+ if out[current]:
+ frontier.extend(out[current])
+ else:
+ found.add(current)
+ return found or {start}
+
+ kept: set[str] = set()
+ home: dict[str, set[str]] = {}
+ left = set(family)
+ while left:
+ frontier = [left.pop()]
+ component = set(frontier)
+ while frontier:
+ for far in near[frontier.pop()]:
+ if far not in component:
+ component.add(far)
+ frontier.append(far)
+ left -= component
+ roots = {member for member in component if not out[member]}
+ subjects = {
+ member
+ for member in roots
+ if entities.role_of(drawn[member]["type"]) != entities.ATTESTATION
+ }
+ # A component that is one derivation loop has no root at all. Nothing in it
+ # is an origin, so nothing in it is folded away either.
+ here = subjects or roots or component
+ kept |= here
+ for member in component:
+ home[member] = here
+ # What the point rests on is counted over the **family**, once, whatever verbs
+ # its arrows are written with: a capture reached through the same footage is the
+ # reference either way.
+ behind.setdefault(place_id, set()).update(kept)
+
+ for member in sorted(family - kept - spared):
+ # All or nothing: everything this one holds is one of its own arrows onto
+ # this point, or a derivation inside the family. Anything else — a second
+ # place, a statement citing it, a chain reaching outside — is something the
+ # collapsed line cannot say, so it stays a node with its arrows.
+ mine = set(arrows[member].values())
+ spare = [
+ link
+ for link in incident.get(member, ())
+ if link["id"] not in mine
+ and not (
+ link["type"] in links.CHAIN_TYPES
+ and (link["to"] if link["from"] == member else link["from"]) in family
+ )
+ ]
+ if spare:
+ continue
+ folding.add(member)
+ # Where its arrows go. Its own roots when they are kept; otherwise it is an
+ # attestation root itself — the capture — and it joins the material of the
+ # component it was compared against. **Whatever verb it was written with**:
+ # the surviving line is the root's own statement, the folded one is named on
+ # it, and one click brings it back saying exactly what it said.
+ for root in (_roots(member) & home[member]) or home[member]:
+ held = arrows[root]
+ for verb in arrows[member]:
+ landing_on = held.get(verb) or held[sorted(held)[0]]
+ merged.setdefault(landing_on, set()).add(member)
+
+ if not folding:
+ return nodes, edges, _agrees(landed, behind)
+
+ dropped = {link["id"] for member in folding for link in incident.get(member, ())}
+ standing = []
+ for link in edges:
+ if link["id"] in dropped:
+ continue
+ ids = merged.get(link["id"])
+ if not ids:
+ standing.append(link)
+ continue
+ standing.append(
+ {
+ **link,
+ # Annotated, never replaced: this row is the case's own statement, and
+ # confirming or withdrawing it has to stay possible.
+ "merged": {
+ "sources": len(ids),
+ "via": sorted({_act(drawn[one], origins) for one in ids}),
+ "open": sorted(ids),
+ },
+ }
+ )
+ return (
+ [node for node in nodes if node["id"] not in folding],
+ standing,
+ _agrees(landed, behind),
+ )
+
+
+def _agrees(
+ landed: dict[str, int], behind: dict[str, set[str]]
+) -> dict[str, dict[str, int]]:
+ """Per place, how many independent origins land on it.
+
+ Reported only where more than one arrow arrived: on a point stated once the number
+ restates the picture, and a count that says nothing is a count nobody reads. The
+ account clause is carried at zero so the surface that already reads a statement's
+ independence reads this one with no second branch — nobody publishes a coordinate.
+ """
+ return {
+ place_id: {"sources": len(behind.get(place_id, ())), "accounts": 0, "one": False}
+ for place_id, arrows in landed.items()
+ if arrows > 1 and behind.get(place_id)
+ }
+
+
+def _reads_the_case(entry: Lens) -> bool:
+ """Whether this reading collapses the derivation chain at all.
+
+ Two things make one a reading of the **case**: it draws the chain, and it leaves
+ the analyst's own output out. ``My work`` is the filing read on its own terms —
+ *what did I write, and out of what* is the question it exists to answer — so
+ collapsing the production chain there would collapse its answer. Asked of the lens
+ rather than of its id, because a lens is derived and a name is not.
+ """
+ return bool(set(links.CHAIN_TYPES) & set(entry.types)) and set(entry.roles) == set(
+ CASE_ROLES
+ )
+
+
+def _act(node: dict[str, Any], origins: dict[str, dict[str, str]]) -> str:
+ """What to call one derivative: the act when the case made it, the type otherwise.
+
+ *1 frame* says what *1 media* cannot, and the reading needs the word twice — on the
+ edge a step becomes and on the count a source carries — so it is resolved once here.
+ The words themselves live on the one surface that writes them (`entityIcon.js`):
+ this sends the act, not a second vocabulary's rendering of it.
+ """
+ op = (origins.get(node["id"]) or {}).get("op")
+ return op or str(node["type"])
+
+
+def _relay(
+ entry: Lens,
+ nodes: list[dict[str, Any]],
+ edges: list[dict[str, Any]],
+ degrees: dict[str, int],
+ named: set[str],
+ origins: dict[str, dict[str, str]],
+) -> tuple[list[dict[str, Any]], list[dict[str, Any]]]:
+ """A derivative that only relays its source to what was made from it, as an edge.
+
+ A frame is pulled out of a video and a proof is built on the frame. The frame is
+ three things at once — a node, a picture, a step — and only the third is a fact the
+ drawing has to state: *this proof was made out of that video*. Drawn as a node it
+ spends a slot to say "there was a step here", and a video with twelve saved frames
+ draws as thirteen pictures of the same thing.
+
+ ::
+
+ before proof --derived-from--> frame --derived-from--> video
+ after proof --derived-from (1 frame)----------------> video
+
+ **Every drawn edge a chain verb, and exactly one of them outgoing.** The first half
+ is the all-or-nothing rule ``_fold`` already keeps: a frame that shows a place, or
+ that a statement cites, carries something an edge between its neighbours cannot say,
+ so it stays a node. The second half is a direction guard, and it is what a plain
+ geolocation taught: a proof derived from **both** a frame and a capture is a
+ confluence, not a passage, and folding it would state ``capture derived-from video``
+ — a claim that the overhead imagery came out of the footage, which is false and is
+ exactly the false convergence this whole reading exists to stop.
+
+ **It must relay something.** A derivative nothing was made from is a chain leaf, not
+ a passage: folded here it would leave the drawing with nothing saying the video has
+ twelve frames at all. Rolling those onto their source with a count is its own act
+ (SPEC §6), and this pass leaves them where they are rather than dropping them
+ silently.
+
+ **Passages in a row resolve to the far end.** A frame adjusted and then built on is
+ two steps and one sentence, so the walk runs to the first node that is not itself a
+ passage and the edge names every step it went through. A derivation that loops back
+ on itself has no far end — nothing on it is a source — so none of it folds.
+
+ **Only in a reading of the case.** ``My work`` is the filing read on its own terms:
+ *what did I write, and out of what* is the question it exists to answer, and folding
+ the production chain there would fold the answer. So the pass asks the two things
+ that make a reading one of the case — that it draws the chain at all, and that it
+ leaves the analyst's own output out — rather than naming a lens.
+
+ A named node is never folded, which is the way back: the edge carries the ids it
+ stands for and ``expand`` draws them again, the same mechanism ``_fold`` uses.
+ ``degrees`` is corrected in place for the same reason it is there — a click that
+ would bring nothing must not be priced as though it would.
+ """
+ if not _reads_the_case(entry):
+ return nodes, edges
+
+ drawn = {node["id"]: node for node in nodes}
+ incident: dict[str, list[dict[str, Any]]] = {}
+ for link in edges:
+ for end in (link["from"], link["to"]):
+ if end in drawn:
+ incident.setdefault(end, []).append(link)
+
+ # Each passage with the one edge that leaves it: its source.
+ passage: dict[str, dict[str, Any]] = {}
+ for node_id, touching in incident.items():
+ if node_id in named:
+ continue
+ if any(link["type"] not in links.CHAIN_TYPES for link in touching):
+ continue
+ out = [link for link in touching if link["from"] == node_id and link["to"] != node_id]
+ if len(out) != 1 or len(touching) == len(out):
+ continue
+ passage[node_id] = out[0]
+ if not passage:
+ return nodes, edges
+
+ # A derivation that comes back to where it started names no source, so nothing on
+ # it is relaying anything. Every node on the loop stays drawn, and whatever hangs
+ # off it resolves onto the loop instead, which is where the walk now stops.
+ looping = set()
+ for start in passage:
+ seen: set[str] = set()
+ current = start
+ while current in passage:
+ if current in seen:
+ looping.add(start)
+ break
+ seen.add(current)
+ current = passage[current]["to"]
+ for node_id in looping:
+ passage.pop(node_id)
+ if not passage:
+ return nodes, edges
+
+ def _walk(start: str) -> tuple[str, list[str]]:
+ """The first node that is not a passage, and every step taken to reach it."""
+ steps: list[str] = []
+ current = start
+ while current in passage:
+ steps.append(current)
+ current = passage[current]["to"]
+ return current, steps
+
+ held: dict[tuple[str, str, str], dict[str, Any]] = {}
+ dropped = {link["id"] for middle in passage for link in incident[middle]}
+ for middle in passage:
+ for link in incident[middle]:
+ # Its own outgoing edge, and the consumers that are passages themselves:
+ # those arrive here through the one node at the end of their own walk.
+ if link["to"] != middle or link["from"] in passage:
+ continue
+ root, steps = _walk(middle)
+ folded = held.setdefault(
+ (link["from"], root, link["type"]),
+ {"middles": [], "at": "", "suggested": False},
+ )
+ for step in steps:
+ if step not in folded["middles"]:
+ folded["middles"].append(step)
+ for one in [link] + [passage[step] for step in steps]:
+ folded["at"] = max(folded["at"], one["provenance"].get("at", ""))
+ if one["provenance"].get("status") == "suggested":
+ folded["suggested"] = True
+
+ for link in edges:
+ if link["id"] not in dropped:
+ continue
+ for end in (link["from"], link["to"]):
+ if end in degrees and end not in passage:
+ degrees[end] = max(degrees[end] - 1, 0)
+
+ synthetic = [
+ {
+ "id": f"{FOLDED_PREFIX}{verb}:{from_id}:{to_id}",
+ "from": from_id,
+ "to": to_id,
+ "type": verb,
+ "folded": {
+ "sources": len(folded["middles"]),
+ "via": sorted({_act(drawn[step], origins) for step in folded["middles"]}),
+ # No publisher on this side: a derivation is the case's own act, and
+ # "0 accounts" would read as a gap rather than as "not that kind of
+ # step". The edge says one thing instead of two.
+ "accounts": 0,
+ "open": sorted(folded["middles"]),
+ },
+ "provenance": {
+ "by": "graph",
+ "at": folded["at"],
+ "status": "suggested" if folded["suggested"] else "confirmed",
+ },
+ }
+ for (from_id, to_id, verb), folded in sorted(held.items())
+ ]
+ for link in synthetic:
+ for end in (link["from"], link["to"]):
+ if end in degrees:
+ degrees[end] = degrees.get(end, 0) + 1
+
+ return (
+ [node for node in nodes if node["id"] not in passage],
+ [link for link in edges if link["id"] not in dropped] + synthetic,
+ )
+
+
+def _roll(
+ entry: Lens,
+ nodes: list[dict[str, Any]],
+ edges: list[dict[str, Any]],
+ named: set[str],
+ opened: list[str],
+ origins: dict[str, dict[str, str]],
+) -> tuple[list[dict[str, Any]], list[dict[str, Any]], dict[str, dict[str, Any]]]:
+ """Derivatives nothing was made from, as a count on the thing they came out of.
+
+ Twelve frames saved off a video and not used yet are twelve pictures of the same
+ video, and the drawing spends twelve slots saying "twelve frames exist". The video
+ already says it: *12 frames*, on the node they came out of, and one click brings
+ them back as nodes.
+
+ **Deliberately narrow, and the narrowness is the whole design.** One drawn edge, it
+ is a chain verb, and the node is the end that was **derived** — it points at its
+ source rather than being pointed at. Three consequences, each of them the point:
+
+ * a leaf with a single *relation* is untouched. Rolling those up would start putting
+ away a person with one link, which is a picture of the case with its thin material
+ hidden — and thin material is what the case has yet to exploit, not what it should
+ stop showing.
+ * the direction settles the pair. A video and its one unused frame are both
+ single-edge nodes; only the frame came out of the other, so only the frame rolls,
+ and the picture keeps the collected material rather than the derivative.
+ * a chain leaf that is also a passage has already gone (``_relay``), and what is
+ left here relays nothing by construction.
+
+ **Never across a collapsed step.** A leaf whose one edge is already a fold stays a
+ node: that line stands for something and offers it back, and burying it inside a
+ counter would put two acts behind one number and lose the way to the step.
+
+ **The count is a fact, not an offer.** The node goes on pricing those twelve among
+ the connections the drawing does not hold, and **what an opened node touches is
+ never rolled up**, so the one act that brings them is the one that brings every
+ other missing neighbour: *expand*. Priced down instead, the node reported four
+ connections away while offering twelve elsewhere, and the analyst read two counters
+ for one question — a distinction about the mechanism rather than about the case.
+
+ Returns ``(nodes, links, rolled)``, ``rolled`` being per surviving node
+ ``{count, via, open}`` — what came out of it, in the act's own word, with the ids
+ the sentence names.
+ """
+ if not _reads_the_case(entry):
+ return nodes, edges, {}
+
+ drawn = {node["id"]: node for node in nodes}
+ incident: dict[str, list[dict[str, Any]]] = {}
+ for link in edges:
+ for end in (link["from"], link["to"]):
+ if end in drawn:
+ incident.setdefault(end, []).append(link)
+
+ # Asking for a node is asking for what it touches, so an expansion outranks this
+ # the way it outranks the star fold: read off the neighbours rather than off what
+ # the expansion brought, since on a case that fits they are all drawn already.
+ spared = set(named) | {
+ (link["to"] if link["from"] == one else link["from"])
+ for one in opened
+ for link in incident.get(one, ())
+ }
+
+ onto: dict[str, list[str]] = {}
+ gone: dict[str, str] = {}
+ for node_id, held in incident.items():
+ # A node with no edge at all is not here: it is the case's unexploited
+ # material, it is what ``isolated`` counts, and it belongs to nobody.
+ if node_id in spared or len(held) != 1:
+ continue
+ link = held[0]
+ if link["type"] not in links.CHAIN_TYPES or link.get("folded"):
+ continue
+ if link["from"] != node_id or link["to"] not in drawn:
+ continue
+ onto.setdefault(link["to"], []).append(node_id)
+ gone[node_id] = link["id"]
+ if not gone:
+ return nodes, edges, {}
+
+ rolled = {
+ source_id: {
+ "count": len(leaves),
+ "via": sorted({_act(drawn[leaf], origins) for leaf in leaves}),
+ "open": sorted(leaves),
+ }
+ for source_id, leaves in onto.items()
+ }
+ dropped = set(gone.values())
+ return (
+ [node for node in nodes if node["id"] not in gone],
+ [link for link in edges if link["id"] not in dropped],
+ rolled,
+ )
+
+
+def _counted(
+ rests: dict[str, dict[str, set[str]]],
+ edges: list[dict[str, Any]],
+ claims: set[str],
+ drawn: dict[str, dict[str, Any]],
+) -> dict[str, dict[str, int]]:
+ """Per statement, how many sources it rests on and how many accounts published them.
+
+ Read off what the drawing can say, which is the honest scope: a cut view already
+ says it was cut. The sources a fold stands for are counted through the fold, and
+ the ones still drawn as nodes are counted where they are — so citing three
+ bookmarks reads as three sources whether or not they collapsed, and whether or not
+ the budget kept them, since a fold reaches a middle the drawing does not hold.
+
+ ``accounts`` is what makes the number worth having: three citations that all trace
+ back to one account are one source, and that is a measurement rather than a
+ judgement (SPEC anti-goals).
+ """
+ posted: dict[str, set[str]] = {}
+ for link in edges:
+ if link["type"] == links.POSTED:
+ posted.setdefault(link["to"], set()).add(link["from"])
+ for link in edges:
+ if link["type"] != links.CITES or link["from"] not in rests:
+ continue
+ source = link["to"]
+ if source not in drawn or source in claims:
+ continue
+ rests[link["from"]]["sources"].add(source)
+ rests[link["from"]]["accounts"].update(posted.get(source, ()))
+ if posted.get(source):
+ rests[link["from"]]["attributed"].add(source)
+ return {
+ claim_id: {
+ "sources": len(held["sources"]),
+ "accounts": len(held["accounts"]),
+ # Whether every one of those sources traces back to the same account, which
+ # is the finding. A set half of which nobody has traced is not it: the
+ # untraced half may well be independent, and saying otherwise would be a
+ # judgement rather than a measurement.
+ "one": len(held["sources"]) > 1
+ and len(held["accounts"]) == 1
+ and held["attributed"] == held["sources"],
+ }
+ for claim_id, held in rests.items()
+ if held["sources"]
+ }
+
+
+
+
+def neighborhood(
+ case: CaseRepository,
+ root_id: str,
+ *,
+ lens_id: str = "all",
+ hops: int = 1,
+ limit: int | None = None,
+) -> dict[str, Any]:
+ """One node, and what reaches it within ``hops``.
+
+ The walk stops on whichever comes first: the hop budget, or the node budget.
+ Stopping on the budget is reported rather than silently trimmed, because a
+ view that quietly dropped half a neighbourhood would read as a finding about
+ the case. Every node carries its full degree in this lens, so what a further
+ expansion would bring in is visible on the node itself.
+
+ **The edges are closed once, at the end, over everything the walk loaded.** The
+ walk finds nodes; it is a bad witness for edges, because an edge between two
+ nodes reached at the *same* hop touches neither of the frontiers that found them.
+ Collected hop by hop, the outermost ring came back with no edges inside it: a
+ triangle around a root drew as a star, and both its far nodes reported the edge
+ between them as a connection further out than the hops asked for.
+
+ The walk obeys the lens on both axes: it steps over its verbs and never onto a
+ node it does not draw. A root the lens leaves out is refused rather than drawn as
+ the one exception, because a reading with one node in it that does not belong to
+ that reading is not the reading it says it is.
+ """
+ entry = lens(lens_id)
+ verbs = list(entry.types)
+ hidden = list(entry.hides)
+ bounded = max(1, min(int(OPENING_NODES if limit is None else limit), MAX_OPENING))
+ depth = max(1, min(int(hops), MAX_HOPS))
+
+ root = case.get_entity(root_id)
+ if root is None:
+ raise CaseError(f"entity '{root_id}' not found")
+ _drawn(entry, root)
+
+ found: dict[str, dict[str, Any]] = {root_id: root}
+ distance = {root_id: 0}
+ frontier = [root_id]
+ truncated = False
+
+ for hop in range(1, depth + 1):
+ if not frontier or len(found) >= bounded:
+ break
+ reached: list[str] = []
+ for link in case.links_touching(frontier, types=verbs, exclude_types=hidden):
+ far = link["to"] if link["from"] in found else link["from"]
+ if far not in found:
+ if len(found) + len(reached) >= bounded:
+ truncated = True
+ continue
+ if far not in reached:
+ reached.append(far)
+ for entity in case.entities_by_ids(reached):
+ found[entity["id"]] = entity
+ distance[entity["id"]] = hop
+ frontier = [entity_id for entity_id in reached if entity_id in found]
+
+ ids = list(found)
+ # The same closed set `view` draws, asked once now that every node is known:
+ # both ends loaded, so nothing drawn dangles, and an edge inside the outermost
+ # ring is in the picture rather than reported as lying beyond it.
+ edges = case.links_among(ids, types=verbs)
+ degrees = case.degrees_of(ids, types=verbs, exclude_types=hidden)
+ walked = [found[i] for i in ids]
+ thumbs = _previews(case, walked)
+ kinds = _kinds(case, walked)
+ origins = _origins(case, walked)
+ return {
+ "lens": entry.id,
+ "root": root_id,
+ "hops": depth,
+ "nodes": [
+ _node(
+ found[i], degrees.get(i, 0), distance.get(i, 0),
+ thumb=thumbs.get(i), kind=kinds.get(i), origin=origins.get(i),
+ )
+ for i in ids
+ ],
+ "links": edges,
+ "shown": len(ids),
+ "truncated": truncated,
+ }
+
+
+
+
+def paths(
+ case: CaseRepository,
+ from_id: str,
+ to_id: str,
+ *,
+ lens_id: str = "all",
+ max_hops: int = MAX_PATH_HOPS,
+ limit: int = MAX_PATHS,
+) -> dict[str, Any]:
+ """How one entity reaches another: every shortest route between them.
+
+ **The question the tool existed without.** A case answers "what touches this"
+ one hop at a time, and an investigation asks "how does this reach that" — the
+ account and the place, the claim and the source. Held in the analyst's head
+ until now, one click at a time.
+
+ *Every* shortest route, not one of them, because the ties are the finding: two
+ accounts reaching the same place through two different sources is what
+ independence looks like, and an answer that picked one would hide the thing
+ worth seeing. Longer routes are not returned at all — once a shorter one exists
+ the long way round says nothing about how the two are connected.
+
+ **Searched from both ends.** A one-sided walk at four hops on a hub-heavy case
+ loads most of the case, because the hub is reached at hop one and everything it
+ touches at hop two. Meeting in the middle spends two hops a side instead of
+ four, which is the difference between a query and a stall. Whichever side has
+ fewer nodes to open is the one that grows, so a walk out of a quiet corner into
+ a busy one stays cheap.
+
+ Undirected, like every other reading of distance here: an arrowhead says what
+ the edge claims, not which way a route may run. The direction is kept on each
+ link so the sentence can read it back the way the case states it.
+
+ Bounded by the lens on both axes, like every other read: a route only ever runs
+ over verbs it draws and through nodes it draws, so the sentence it answers with is
+ one the drawing can show.
+ """
+ entry = lens(lens_id)
+ verbs = list(entry.types)
+ hidden = list(entry.hides)
+ depth = max(1, min(int(max_hops), MAX_PATH_HOPS))
+ wanted = max(1, min(int(limit), MAX_PATHS))
+
+ ends = {entity["id"]: entity for entity in case.entities_by_ids([from_id, to_id])}
+ for entity_id in (from_id, to_id):
+ if entity_id not in ends:
+ raise CaseError(f"entity '{entity_id}' not found")
+ _drawn(entry, ends[entity_id])
+
+ held: dict[str, dict[str, Any]] = {}
+ # One step back towards the node the walk started from, per side. A pair joined
+ # by two verbs records both: they are two different findings, and the sentence
+ # is where they read apart.
+ behind: list[dict[str, list[tuple[str, str]]]] = [{from_id: []}, {to_id: []}]
+ seen: list[dict[str, int]] = [{from_id: 0}, {to_id: 0}]
+ edge: list[list[str]] = [[from_id], [to_id]]
+ reach = 0
+ truncated = False
+ # Checked before the first step so that a node asked about against itself is a
+ # route of length zero rather than a walk looking for one.
+ met: list[str] = sorted(node for node in seen[0] if node in seen[1])
+
+ while not met and reach < depth and edge[0] and edge[1]:
+ # The cheaper side grows. A frontier of three against a frontier of four
+ # hundred is the whole reason this is not a one-sided walk.
+ side = 0 if len(edge[0]) <= len(edge[1]) else 1
+ if len(seen[side]) >= MAX_PATH_VISIT:
+ truncated = True
+ break
+ reach += 1
+ step = seen[side][edge[side][0]] + 1
+ ahead: list[str] = []
+ # A route through a node this reading does not draw is not a route it can
+ # show: the sentence would name a node that is not on screen, and the view
+ # that tried to bring it in would refuse for the same reason.
+ for link in case.links_touching(edge[side], types=verbs, exclude_types=hidden):
+ held[link["id"]] = link
+ near, far = link["from"], link["to"]
+ if near not in seen[side] or seen[side].get(near) != step - 1:
+ near, far = far, near
+ if seen[side].get(near) != step - 1 or far == near:
+ continue
+ if far in seen[side] and seen[side][far] < step:
+ continue
+ if far not in seen[side]:
+ if len(seen[side]) >= MAX_PATH_VISIT:
+ truncated = True
+ continue
+ seen[side][far] = step
+ behind[side].setdefault(far, [])
+ ahead.append(far)
+ behind[side][far].append((near, link["id"]))
+ edge[side] = ahead
+ met = sorted(node for node in seen[0] if node in seen[1])
+
+ if not met:
+ return _no_path(entry.id, from_id, to_id, depth, truncated)
+
+ shortest = min(seen[0][node] + seen[1][node] for node in met)
+ routes: list[dict[str, list[str]]] = []
+ for node in met:
+ if len(routes) >= wanted or seen[0][node] + seen[1][node] != shortest:
+ continue
+ # One side was walked out of `from`, the other out of `to`, so the second
+ # half arrives reversed. Its meeting node is dropped rather than written
+ # twice, and its links are read back in the order the route runs.
+ for head in _routes(behind[0], node, from_id, wanted):
+ for tail in _routes(behind[1], node, to_id, wanted):
+ if len(routes) >= wanted:
+ truncated = True
+ break
+ routes.append(
+ {
+ "nodes": head["nodes"] + list(reversed(tail["nodes"]))[1:],
+ "links": head["links"] + list(reversed(tail["links"])),
+ }
+ )
+
+ walked = [node for route in routes for node in route["nodes"]]
+ on_path = list(dict.fromkeys(walked))
+ used = list(dict.fromkeys(link for route in routes for link in route["links"]))
+ found = {entity["id"]: entity for entity in case.entities_by_ids(on_path)}
+ degrees = case.degrees_of(on_path, types=verbs, exclude_types=hidden)
+ kept = [found[i] for i in on_path if i in found]
+ thumbs = _previews(case, kept)
+ kinds = _kinds(case, kept)
+ origins = _origins(case, kept)
+ return {
+ "lens": entry.id,
+ "from": from_id,
+ "to": to_id,
+ "hops": shortest,
+ "found": True,
+ "routes": routes,
+ "nodes": [
+ _node(
+ found[i], degrees.get(i, 0), None,
+ thumb=thumbs.get(i), kind=kinds.get(i), origin=origins.get(i),
+ )
+ for i in on_path if i in found
+ ],
+ "links": [held[i] for i in used if i in held],
+ "searched": depth,
+ "truncated": truncated,
+ }
+
+
+def _no_path(
+ lens_id: str, from_id: str, to_id: str, depth: int, truncated: bool
+) -> dict[str, Any]:
+ """No route inside the budget, which is an answer and not a failure.
+
+ Said apart from "no such entity" and apart from "gave up": an analyst who
+ learns two entities are *not* connected within four hops has learned something
+ about the case, where an empty response would read as the tool having no
+ opinion.
+ """
+ return {
+ "lens": lens_id,
+ "from": from_id,
+ "to": to_id,
+ "hops": 0,
+ "found": False,
+ "routes": [],
+ "nodes": [],
+ "links": [],
+ "searched": depth,
+ "truncated": truncated,
+ }
+
+
+def _routes(
+ behind: dict[str, list[tuple[str, str]]], node: str, stop: str, wanted: int
+) -> list[dict[str, list[str]]]:
+ """Every way back from ``node`` to ``stop``, following one side's steps.
+
+ Walked backwards from the meeting point and then reversed by the caller, since
+ that is the direction the predecessors were recorded in. Capped on the way out
+ rather than after: a hub can hold thousands of equally short ways back, and
+ building them all to keep twelve is the cost this search exists to avoid.
+ """
+ if node == stop:
+ return [{"nodes": [node], "links": []}]
+ out: list[dict[str, list[str]]] = []
+ for prev, link_id in behind.get(node, []):
+ for route in _routes(behind, prev, stop, wanted):
+ if len(out) >= wanted:
+ return out
+ out.append({"nodes": route["nodes"] + [node], "links": route["links"] + [link_id]})
+ return out
+
+
+def _previews(case: CaseRepository, entities: list[dict[str, Any]]) -> dict[str, str]:
+ """The cached preview of each of these entities that has one, keyed by entity.
+
+ Two sources, one query. **Media** is in the browse index. **Anything else that
+ records a preview** carries the path on the entity itself, which is how a proof
+ reaches the graph without its spec file being opened — the copy onto the entity
+ is made by the caller that has the filesystem, since this module answers from
+ the database alone.
+
+ Nothing here renders anything. A read that draws does no CPU work, so an entity
+ whose picture was never cached has no preview and draws as its glyph.
+ """
+ ids = [entity["id"] for entity in entities]
+ found = dict(case.media_thumbs(ids)) if ids else {}
+ found.update(case.entity_image_thumbs(ids))
+ for entity in entities:
+ recorded = entity.get("attrs", {}).get("thumb")
+ if recorded and entity["id"] not in found:
+ found[entity["id"]] = recorded
+ return found
+
+
+def _kinds(case: CaseRepository, entities: list[dict[str, Any]]) -> dict[str, str]:
+ """What the bytes behind each media entity are: image, video, audio or file.
+
+ A drawn `media` node that cannot say which of those it holds is drawn with the
+ generic file glyph and reads as a document, which is the picture telling the
+ analyst something untrue about the case. One type covers all four, so the answer
+ is a property of the file rather than of the vocabulary.
+
+ Two sources, the same two as the previews. The **browse index** is the authority,
+ because the importer put the MIME-derived kind there. `attrs.kind` covers an
+ entity the index has never seen — one filed by a tool that writes the attr
+ without registering a browse row. Nothing here opens a file: a read that draws
+ does no I/O beyond the database.
+ """
+ ids = [entity["id"] for entity in entities if entity["type"] == "media"]
+ if not ids:
+ return {}
+ found = dict(case.media_kinds(ids))
+ for entity in entities:
+ stated = entity.get("attrs", {}).get("kind")
+ if stated and entity["id"] not in found:
+ found[entity["id"]] = stated
+ return found
+
+
+def _origins(case: CaseRepository, entities: list[dict[str, Any]]) -> dict[str, dict[str, str]]:
+ """Which of these nodes were **made here**, and by which act.
+
+ A frame pulled out of a video, an adjusted image, a collage: filed as ordinary
+ media, drawn with the same glyph as a photograph the case collected, and a video
+ with twelve saved frames draws as thirteen pictures with nothing saying which
+ twelve came out of the first. The material is not the finding, and a drawing that
+ cannot tell the two apart makes the analyst open files to find out.
+
+ Only ``links.MADE_HERE`` routes are carried, the same set the Media Library hides
+ on. The index knows how everything came in, but *how it was collected* is that
+ list's question — the graph asks the narrower one, so an upload carries nothing
+ rather than carrying "upload" for a reader to ignore.
+
+ One query, off indexed columns, and no fallback onto the entity: unlike the kind,
+ nothing writes this to ``attrs``, and a fallback nobody fills is a branch that
+ only ever lies. A node the index has never seen is silent.
+ """
+ ids = [entity["id"] for entity in entities]
+ if not ids:
+ return {}
+ return {
+ entity_id: origin
+ for entity_id, origin in case.media_origins(ids).items()
+ if origin.get("type") in links.MADE_HERE
+ }
+
+
+def _node(
+ entity: dict[str, Any],
+ degree: int,
+ distance: int | None = None,
+ *,
+ thumb: str | None = None,
+ kind: str | None = None,
+ origin: dict[str, str] | None = None,
+ pin: tuple[float, float] | None = None,
+ added: bool = False,
+ rests: dict[str, int] | None = None,
+ rolled: dict[str, Any] | None = None,
+ query: str | None = None,
+) -> dict[str, Any]:
+ """One entity as the graph needs it: identity, family, degree and a preview.
+
+ The family travels with the node so a client groups and colours without a
+ second lookup against the entity registry, and ``degree`` is what a node shows
+ before it is expanded.
+
+ ``thumb`` is the *cached thumbnail*, never the file itself: a case draws a few
+ hundred nodes at once, and a node that reached for its own full-size image
+ would download the case to draw it. An entity with no indexed media carries no
+ key at all, which is what lets a client tell "no picture" from "not loaded".
+
+ Two kinds of entity have one, read the same way for both. Media is in the browse
+ index, keyed by entity. A proof records its own on the entity, because a proof's
+ thumbnail otherwise lives in its spec file and reading a few hundred of those to
+ draw a graph is exactly the cost this argument exists to avoid. **Nothing here
+ ever generates a thumbnail** — a read that draws must not do CPU work — so an
+ entity whose picture was never cached draws as its glyph.
+
+ ``kind`` is what a media node actually holds — image, video, audio or file — and
+ is carried only for the one type where it is a real question: `media` covers all
+ four, so without it every one of them draws as a generic file and reads as a
+ document.
+
+ ``origin`` says the node was **made here** and by which act — ``{origin, op}``,
+ a frame or a collage out of material the case already holds. Carried only for
+ those, never for collected material, so its presence is the whole signal and a
+ client tests for it rather than comparing it against a list of routes.
+
+ ``pin`` is where the analyst dragged the node, absent when nobody has. It only
+ reaches a whole-case view: a neighbourhood gives the horizontal axis to distance
+ from the root, so a coordinate stated against the cluster would fight the one
+ thing that arrangement is for.
+
+ ``added`` marks a node an expansion brought in rather than the ranking. The
+ picture has to be able to say which nodes just arrived, or growing the view is
+ indistinguishable from the view having changed under the analyst.
+
+ ``rests`` is what a statement rests on — ``{sources, accounts}`` — carried on the
+ node because that is where it is read. Three citations tracing back to one account
+ are one source, and a node that cannot say so leaves the analyst counting bookmarks
+ by eye. Only a ``claim`` carries it, and only when it cites anything at all.
+
+ ``rolled`` is what came out of this one and was not used — ``{count, via, open}``.
+ Twelve frames off a video are the video's own fact, and the ids are the way back:
+ nothing is put away without the node that holds it saying so and offering it.
+ """
+ node: dict[str, Any] = {
+ "id": entity["id"],
+ "type": entity["type"],
+ "label": entity["label"],
+ "family": entities.family_of(entity["type"]),
+ "status": entity.get("provenance", {}).get("status", "confirmed"),
+ "at": entity.get("provenance", {}).get("at", ""),
+ "degree": degree,
+ }
+ folder = entity.get("attrs", {}).get("folder")
+ if folder:
+ node["folder"] = folder
+ preview = thumb or entity.get("thumb") or entity.get("attrs", {}).get("thumb")
+ if preview:
+ node["thumb"] = preview
+ if kind:
+ node["kind"] = kind
+ if origin:
+ node["origin"] = origin["type"]
+ if origin.get("op"):
+ node["op"] = origin["op"]
+ if pin is not None:
+ node["pin"] = [pin[0], pin[1]]
+ if added:
+ node["added"] = True
+ if rests:
+ node["rests"] = dict(rests)
+ if rolled:
+ node["rolled"] = dict(rolled)
+ if matches := entities.search_matches(entity, query):
+ node["matches"] = matches
+ if distance is not None:
+ node["hop"] = distance
+ return node
+
+
+def _drawn(entry: Lens, entity: dict[str, Any]) -> None:
+ """Refuse a node this reading does not draw, where one was named by id.
+
+ The whole-case view answers by leaving it out — it was ranking a set, and a set is
+ allowed to be missing a member. A neighbourhood and a route are named questions
+ about particular nodes, so there is no honest answer to give: drawing the node
+ would break the reading, and answering with an empty picture would read as a
+ finding about the case. Said in words instead, naming the lens that does draw it.
+ """
+ if entity["type"] in entry.hides:
+ raise CaseError(
+ f"the {entry.label} lens does not draw a {entity['type']}"
+ )
+
+
+def _status(value: str | None) -> Any:
+ return value if value in ("confirmed", "suggested") else None
diff --git a/src/azimut/engine/links.py b/src/azimut/engine/links.py
index 2bbbafd..4bd26ae 100644
--- a/src/azimut/engine/links.py
+++ b/src/azimut/engine/links.py
@@ -29,16 +29,22 @@ Everything else is a **relation**: a statement about the world rather than about
how a file was made. ``RELATION_TYPES`` below is the registry the UI offers and
the API validates against, so one vocabulary serves the Details panel, the map
and the case board rather than one per tool.
+
+Each relation starts from **families** in ``engine/entities.py`` and may narrow an
+endpoint to explicit types. A broad verb such as ``owns`` can therefore extend to
+new assets, while ``sited-at`` stays limited to a structure.
"""
from __future__ import annotations
+import mimetypes
from dataclasses import dataclass
from datetime import datetime, timezone
from typing import Any
from ..repository import CaseRepository
from ..workspace import CaseError
+from . import entities
DERIVED_FROM = "derived-from"
DEPENDS_ON = "depends-on"
@@ -53,9 +59,37 @@ TOMBSTONE_TYPES = (DERIVED_FROM,)
#: ``attrs`` key holding the tombstones. Additive — schema stays 0.
LOST = "lost_sources"
+#: The producing tools whose output was **made here** — composed out of material the
+#: case already holds, rather than collected. Matched against a media item's recorded
+#: ``source.type``, which the browse index carries as a column.
+#:
+#: Here rather than in either of the two modules that read it, because both would
+#: otherwise keep their own copy and one of them would be wrong: the graph marks these
+#: nodes and the Media Library hides these rows, and the two have to mean the same set
+#: or the picture and the list disagree about what the case collected. An upload, a
+#: download and a satellite capture are original material brought in, and are
+#: deliberately not here. A future tool that composes case material joins by stamping
+#: its own name and being added to this line.
+MADE_HERE: tuple[str, ...] = ("inspect",)
+
+#: Exact artifact contract. These are not ordinary relations: producing tools
+#: record them, and the pair decides delete behaviour. A file path resolving to an
+#: entity outside this matrix is a producer bug, not a reason to widen the graph.
+CHAIN_ENDPOINTS: dict[str, dict[str, frozenset[str]]] = {
+ DERIVED_FROM: {
+ "media": frozenset({"media", "capture"}),
+ "proof": frozenset({"media", "capture"}),
+ "post": frozenset({"proof", "media", "capture"}),
+ "note": frozenset({"post", "proof", "media", "capture"}),
+ },
+ DEPENDS_ON: {
+ "inspect-session": frozenset({"media", "capture"}),
+ },
+}
+
# -- relations: the non-chain edges (ONTOLOGY §3) -----------------------------
#
-# A relation says something about the world — this photo was shot there, these
+# A relation says something about the world — this photo was recorded there, these
# two files are the same picture — where a chain edge says something about how a
# file was produced. Nothing here cascades a delete or leaves a tombstone:
# removing either endpoint just drops the edge.
@@ -63,51 +97,352 @@ LOST = "lost_sources"
LOCATED_AT = "located-at"
SAME_IMAGE_AS = "same-image-as"
DEPICTS = "depicts"
+OWNS = "owns"
+PART_OF = "part-of"
+MEMBER_OF = "member-of"
+ASSOCIATED_WITH = "associated-with"
+POSTED = "posted"
+APPEARS_IN = "appears-in"
+SITED_AT = "sited-at"
+IN_NETWORK = "in-network"
+INSTANCE_OF = "instance-of"
+MENTIONS = "mentions"
+ABOUT = "about"
+AT = "at"
+CITES = "cites"
+CONTRADICTS = "contradicts"
+
+#: What a statement is built out of: its subjects, its place, its evidence. The
+#: verbs a source folds across (``engine/graph._fold``) and the ones the Claim
+#: editor owns. ``contradicts`` is deliberately **not** here: it joins two
+#: statements to each other rather than a statement to what it rests on, so a
+#: fold that walked it would collapse an argument into a citation.
+CLAIM_CONNECTION_TYPES = (ABOUT, AT, CITES)
+
+#: How sure the analyst is that an edge holds, as one closed ordinal (ONTOLOGY §3).
+#: No 0-100 slider: a number invites false precision, nobody calibrates it, and the
+#: standing criticism of vague estimative language is that it lets a report commit to
+#: nothing. Kent's words and ICD 203's bands are ordinal for the same reason.
+CERTAIN = 3
+PROBABLE = 2
+POSSIBLE = 1
+#: Ruled out — and that is a finding, not a deletion. "It is not this bridge" is half
+#: the work of a geolocation: twelve candidates are checked and eleven are eliminated.
+#: Without this state the only options are deleting the work or leaving it at
+#: `possible` and polluting the case.
+REFUTED = -1
+
+#: Each level with its reading and one clause placing it, served together so the
+#: picker, the tooltip and the validator are the same list. The words are ordinal on
+#: purpose: a percentage invites a precision nobody calibrates.
+CONFIDENCE_LEVELS: tuple[tuple[int, str, str], ...] = (
+ (CERTAIN, "Certain", "established and corroborated"),
+ (PROBABLE, "Probable", "more likely than not, and short of established"),
+ (POSSIBLE, "Possible", "roughly even odds, and it cannot be excluded"),
+ (REFUTED, "Ruled out", "checked and eliminated, which is a finding rather than a deletion"),
+)
+
+#: Every rating an edge may hold. Absent stays distinct from `POSSIBLE`: most edges in
+#: a live case have never been assessed, and assigning them a level manufactures
+#: opinions nobody holds.
+CONFIDENCE_STATES: tuple[int, ...] = tuple(value for value, _, _ in CONFIDENCE_LEVELS)
@dataclass(frozen=True)
class RelationType:
"""One relation the vocabulary knows, and what it may join.
- ``from_types``/``to_types`` are the entity types each end accepts, so the
- picker can only offer edges the ontology has a reading for and the API can
- refuse the rest. ``label`` completes the sentence *"<from> … <to>"* and is
- what every surface displays instead of the type slug. ``manual`` is whether
- an analyst may state it: some relations are only ever a machine's claim.
+ Each end starts as a set of **families** (``engine/entities.py``).
+ ``from_types`` and ``to_types`` resolve those families plus any narrowing to
+ the exact endpoint sets checked by the API and served to the frontend.
+
+ ``from_only``/``to_only`` narrow an end *inside* its family, for a verb
+ a whole family is too broad for. They intersect rather than replace, so a
+ narrowing can only ever remove a type — it cannot smuggle one in from another
+ family. ``from_exclude``/``to_exclude`` remove one invalid family member while
+ preserving inheritance for the rest.
+
+ ``label`` completes the sentence *"<from> … <to>"* and is what every surface
+ displays instead of the type slug. ``hint`` is one clause saying what the verb
+ means where the words alone are ambiguous — "is part of" against "owns" is the
+ distinction an order of battle turns on. ``manual`` is whether an analyst may
+ state it: some relations are only ever a machine's claim.
+
+ ``action`` keeps distinct gestures distinct. A document mentioning a subject
+ is a pointer, not a relation that can be restated into ownership or location,
+ so the UI gives it its own button and never mixes both sets in one select.
+
+ ``group`` heads the verb where it does not belong among the rest, the way
+ ``Attr.group`` heads a set of fields. Empty is the common case and means "with
+ the others". A verb that merely points — a document naming a place it was not
+ made from — reads as a finding when it sits in the same list as one, so the
+ heading is what keeps a pointer from being mistaken for a statement.
+
+ ``qualifier`` is how a free note on the edge is *labelled*, and empty means this
+ verb takes none — the same shape as ``ratable``, and the same guard. It exists
+ for `associated-with`, where the tie is real and its nature is a word only the
+ analyst has: sister, employer, business partner. **It belongs to the verb, never
+ to the edge.** A note every edge could carry would leave nothing saying what an
+ edge *is*, and the vocabulary would drain into free text within a case or two;
+ giving one to another verb later is a word here rather than a decision to retake.
"""
type: str
label: str
- from_types: frozenset[str]
- to_types: frozenset[str]
+ from_families: frozenset[str]
+ to_families: frozenset[str]
+ inverse_label: str = ""
+ hint: str = ""
+ group: str = ""
+ action: str = "relation"
+ ratable: bool = True
+ qualifier: str = ""
manual: bool = True
+ from_only: frozenset[str] = frozenset()
+ to_only: frozenset[str] = frozenset()
+ from_exclude: frozenset[str] = frozenset()
+ to_exclude: frozenset[str] = frozenset()
+ from_media_kinds: frozenset[str] = frozenset()
+ to_media_kinds: frozenset[str] = frozenset()
+
+ @property
+ def from_types(self) -> frozenset[str]:
+ return self._resolve(self.from_families, self.from_only, self.from_exclude)
+
+ @property
+ def to_types(self) -> frozenset[str]:
+ return self._resolve(self.to_families, self.to_only, self.to_exclude)
+
+ @staticmethod
+ def _resolve(
+ families: frozenset[str], only: frozenset[str], exclude: frozenset[str]
+ ) -> frozenset[str]:
+ types = entities.types_in(*families)
+ narrowed = types & only if only else types
+ return narrowed - exclude
#: The relation vocabulary, in menu order. Deliberately not every type in the
#: ONTOLOGY §3 table: a type reaches this tuple once an entity type exists at both
-#: ends, so nothing is offered that cannot be filed.
+#: ends, so nothing is offered that cannot be filed. `about`/`at`/`cites` wait on
+#: the claim node for the same reason.
RELATION_TYPES: tuple[RelationType, ...] = (
RelationType(
- LOCATED_AT,
- "was shot at",
- from_types=frozenset({"media", "capture"}),
- to_types=frozenset({"place"}),
+ LOCATED_AT, "was recorded at",
+ inverse_label="was recorded here",
+ hint="where the photo, video or audio was recorded",
+ from_families=frozenset({entities.COLLECTED}),
+ to_families=frozenset({entities.PLACE}),
+ from_only=frozenset({"media"}),
+ from_media_kinds=frozenset({"image", "video", "audio"}),
+ ),
+ # A `proof` is here beside the material it composes, and it is the one
+ # `document` the verb reaches. A proof is a rendered image: what it shows is a
+ # property of its pixels, exactly as it is for a frame or a crop. It is also
+ # where a geolocation is *concluded* — the composer's coordinate field is the
+ # analyst's own answer, and without this verb that answer could name no point.
+ # A note or a post gets `mentions` instead: they are read, not looked at.
+ RelationType(
+ DEPICTS, "shows",
+ inverse_label="is shown in",
+ hint="the place is visible in the image or video",
+ from_families=frozenset({entities.COLLECTED, entities.DOCUMENT}),
+ to_families=frozenset({entities.PLACE}),
+ from_only=frozenset({"media", "capture", "proof"}),
+ from_media_kinds=frozenset({"image", "video"}),
+ ),
+ RelationType(
+ OWNS, "owns",
+ inverse_label="is owned by",
+ hint="ownership rather than use, access or operational control",
+ from_families=frozenset({entities.ACTOR}),
+ to_families=frozenset({entities.ACTOR, entities.ASSET, entities.IDENTIFIER}),
+ to_exclude=frozenset({"person"}),
+ ),
+ RelationType(
+ PART_OF, "is part of",
+ inverse_label="contains",
+ hint="an internal unit inside its parent organization",
+ from_families=frozenset({entities.ACTOR}),
+ to_families=frozenset({entities.ACTOR}),
+ from_only=frozenset({"organization"}),
+ to_only=frozenset({"organization"}),
+ ),
+ RelationType(
+ MEMBER_OF, "is a member of",
+ inverse_label="has member",
+ hint="membership rather than internal containment",
+ from_families=frozenset({entities.ACTOR}),
+ to_families=frozenset({entities.ACTOR}),
+ to_only=frozenset({"organization"}),
),
+ # The tie between two actors that is neither containment, membership nor
+ # ownership — and until this existed the vocabulary had **no** person-to-person
+ # verb at all: `owns` refuses a person as its object, `member-of` and `part-of`
+ # both end at an organization. Stating that two people are connected, which is
+ # the first thing a case does, cost a whole Claim node.
+ #
+ # `ACTOR → ACTOR` and no wider. Opened to identifiers and assets it becomes the
+ # verb that swallows the rest of the vocabulary, and a registry where one entry
+ # answers everything is a registry that says nothing.
+ #
+ # **What kind of tie is the qualifier**, free text, because it is the one field a
+ # closed list cannot hold: maintaining a taxonomy of human relationships is a
+ # project of its own, and the first case needing "former sister-in-law" breaks
+ # it. What the verb asserts is that the tie exists; how sure the analyst is rides
+ # on the ordinal like any other relation.
+ #
+ # Symmetric, so the two readings are one word. `relationOptions` drops the
+ # duplicate rather than offering the same sentence twice.
RelationType(
- DEPICTS,
- "shows",
- from_types=frozenset({"media", "capture"}),
- to_types=frozenset({"place"}),
+ ASSOCIATED_WITH, "is associated with",
+ inverse_label="is associated with",
+ hint="a tie that exists, where what kind it is rides on the edge",
+ from_families=frozenset({entities.ACTOR}),
+ to_families=frozenset({entities.ACTOR}),
+ qualifier="How they are tied",
),
- # Enrichment's own claim: two files whose perceptual hashes are within
- # DHASH_MATCH bits. Named here so the UI can say it in words, never offered
- # by hand — a person comparing two pictures is not measuring a hash.
RelationType(
- SAME_IMAGE_AS,
- "is the same picture as",
- from_types=frozenset({"media"}),
- to_types=frozenset({"media"}),
+ POSTED, "posted",
+ inverse_label="was posted by",
+ hint="the account published the content or URL",
+ from_families=frozenset({entities.IDENTIFIER}),
+ to_families=frozenset({entities.COLLECTED, entities.DOCUMENT}),
+ from_only=frozenset({"account"}),
+ to_only=frozenset({"media", "bookmark"}),
+ ),
+ RelationType(
+ APPEARS_IN, "appears in",
+ inverse_label="shows",
+ hint="the entity or a recognizable representation is visible",
+ from_families=frozenset({entities.ACTOR, entities.ASSET, entities.IDENTIFIER}),
+ to_families=frozenset({entities.COLLECTED}),
+ to_only=frozenset({"media", "capture"}),
+ to_media_kinds=frozenset({"image", "video"}),
+ ),
+ RelationType(
+ SITED_AT, "is sited at",
+ inverse_label="is the site of",
+ hint="a permanent site rather than a dated presence",
+ from_families=frozenset({entities.ASSET}),
+ to_families=frozenset({entities.PLACE}),
+ from_only=frozenset({"structure"}),
+ ),
+ # The only verb the `class` family takes from below. It runs object → model,
+ # because a named tank is one of a model and never the other way round, and it is
+ # ratable: "this is probably a T-72B3" is a reading of the footage, not a fact
+ # the analyst either has or does not.
+ #
+ # An `equipment-type` deliberately takes no `appears-in`. A model cannot be
+ # visible — only one of its members can — and offering the verb would give the
+ # case two ways to say "this was in the video", one of which carries no number.
+ RelationType(
+ INSTANCE_OF, "is a",
+ inverse_label="is the model of",
+ hint="this particular object is one of that model",
+ from_families=frozenset({entities.ASSET}),
+ to_families=frozenset({entities.CLASS}),
+ ),
+ RelationType(
+ IN_NETWORK, "is in network",
+ inverse_label="contains",
+ hint="the address or subnet belongs inside this network",
+ from_families=frozenset({entities.IDENTIFIER}),
+ to_families=frozenset({entities.IDENTIFIER}),
+ from_only=frozenset({"ip", "network"}),
+ to_only=frozenset({"network"}),
+ ),
+ RelationType(
+ SAME_IMAGE_AS, "is the same image as",
+ inverse_label="is the same image as",
+ hint="enrichment matched the perceptual hashes",
+ from_families=frozenset({entities.COLLECTED}),
+ to_families=frozenset({entities.COLLECTED}),
manual=False,
+ ratable=False,
+ from_only=frozenset({"media"}),
+ to_only=frozenset({"media"}),
+ from_media_kinds=frozenset({"image"}),
+ to_media_kinds=frozenset({"image"}),
+ ),
+ RelationType(
+ MENTIONS, "mentions",
+ inverse_label="is mentioned by",
+ from_families=frozenset({entities.DOCUMENT}),
+ to_families=frozenset(entities.FAMILIES),
+ from_only=frozenset({"note", "post", "proof", "bookmark"}),
+ hint="the document refers to the entity",
+ group="Mentions",
+ action="mention",
+ ratable=False,
+ ),
+ RelationType(
+ ABOUT, "is about",
+ inverse_label="has claim",
+ hint="what the statement concerns",
+ from_families=frozenset({entities.CLAIM}),
+ # `class` is here because a counted statement has nowhere else to point: "two
+ # of these were destroyed" is about the model, not about two objects nobody
+ # can name.
+ to_families=frozenset({
+ entities.ACTOR, entities.ASSET, entities.CLASS, entities.IDENTIFIER,
+ entities.PLACE, entities.COLLECTED,
+ }),
+ action="claim",
+ ratable=False,
+ ),
+ RelationType(
+ AT, "places it at",
+ inverse_label="is a claim location",
+ hint="where the statement places its subject or event",
+ from_families=frozenset({entities.CLAIM}),
+ to_families=frozenset({entities.PLACE}),
+ action="claim",
+ ratable=False,
+ ),
+ RelationType(
+ CITES, "cites",
+ inverse_label="supports claim",
+ hint="the evidence the statement relies on",
+ from_families=frozenset({entities.CLAIM}),
+ # A statement rests on material, and it may rest on **another statement**: an
+ # intermediate conclusion is what the next one is built out of. Without it a
+ # case could say what stands *against* a statement (`contradicts`) and never
+ # what holds it up, so refuting the first left the second standing with nothing
+ # naming the loss. It is `cites` rather than a verb of its own because the
+ # question is the same one — what does this rest on — and the inverse reading
+ # was already written for it.
+ to_families=frozenset({entities.DOCUMENT, entities.COLLECTED, entities.CLAIM}),
+ to_only=frozenset({"bookmark", "note", "proof", "media", "capture", "claim"}),
+ action="claim",
+ ratable=False,
+ ),
+ # What stands against a statement, which the drawing has always said it reads
+ # (``engine/graph``'s four questions) and the vocabulary could not say. A
+ # `refuted` confidence records that a statement is dead; it names nothing that
+ # killed it, so the case kept the verdict and lost the argument.
+ #
+ # Statement to statement, both ends, because eliminating a candidate is the
+ # other half of a geolocation: twelve are checked and eleven are ruled out, and
+ # each of those eleven has its own reasoning and its own sources. Pointed at a
+ # subject instead it would say "this vehicle is contradicted", which is not a
+ # thing anyone can assess.
+ #
+ # **No cycle check, unlike `part-of` and `in-network`.** Two statements
+ # contradicting each other is not a loop to refuse, it is the ordinary shape of
+ # an open question, and it reads the same in both directions.
+ #
+ # Not ratable, like the three connectors above: how strongly each side is held
+ # is already on each Claim, and a third grade on the edge between them would be
+ # the mixture ONTOLOGY §3 keeps three assessments apart to prevent.
+ RelationType(
+ CONTRADICTS, "contradicts",
+ inverse_label="is contradicted by",
+ hint="the two statements cannot both hold",
+ from_families=frozenset({entities.CLAIM}),
+ to_families=frozenset({entities.CLAIM}),
+ action="claim",
+ ratable=False,
),
)
@@ -132,14 +467,41 @@ def add_relation(
if from_id == to_id:
raise CaseError("an entity cannot relate to itself")
_check_endpoints(case, spec, from_id, to_id)
+ _check_relation_cycle(case, spec.type, from_id, to_id)
return case.add_link(from_id, to_id, type_, by=by, unique=True)
+def check_relation_target(
+ case: CaseRepository,
+ source: dict[str, Any],
+ to_id: str,
+ type_: str,
+) -> None:
+ """Validate one prospective relation without writing it.
+
+ Atomic Claim creation needs to validate its connectors before the new Claim
+ exists in storage. Existing Claims also receive the normal cycle check.
+ """
+ spec = _statable(type_)
+ target = _entity(case, to_id)
+ source_id = str(source.get("id") or "")
+ if source_id and source_id == to_id:
+ raise CaseError("an entity cannot relate to itself")
+ if source.get("type") not in spec.from_types:
+ raise CaseError(f"a {source.get('type')} cannot be the subject of '{spec.type}'")
+ if target["type"] not in spec.to_types:
+ raise CaseError(f"a {target['type']} cannot be the object of '{spec.type}'")
+ _check_media_kind(source, spec.from_media_kinds, spec.type, "subject")
+ _check_media_kind(target, spec.to_media_kinds, spec.type, "object")
+ if source_id and case.get_entity(source_id) is not None:
+ _check_relation_cycle(case, spec.type, source_id, to_id)
+
+
def set_relation_type(case: CaseRepository, link_id: str, type_: str) -> dict[str, Any]:
"""Correct which relation an existing edge states.
The same two entities, a different reading — "shows this place" where the
- analyst first said "was shot at" — so it is one edge corrected rather than a
+ analyst first said "was recorded at" — so it is one edge corrected rather than a
delete and a re-statement, and the wrong reading leaves no trace. Same
validation as stating one, plus a refusal to collapse onto a relation the pair
already holds.
@@ -148,8 +510,14 @@ def set_relation_type(case: CaseRepository, link_id: str, type_: str) -> dict[st
link = case.get_link(link_id)
if link is None:
raise CaseError(f"link '{link_id}' not found")
- _statable(link["type"]) # a machine's claim is not the analyst's to reword
+ current = _statable(link["type"]) # a machine's claim is not the analyst's to reword
+ if current.action != spec.action:
+ raise CaseError("a connection cannot change into another kind")
+ # An older out-of-matrix connection stays readable and removable, but cannot
+ # be used as a shortcut to mint a new statement under today's rules.
+ _check_endpoints(case, current, link["from"], link["to"])
_check_endpoints(case, spec, link["from"], link["to"])
+ _check_relation_cycle(case, spec.type, link["from"], link["to"])
twin = any(
other["id"] != link_id
and other["from"] == link["from"]
@@ -159,13 +527,20 @@ def set_relation_type(case: CaseRepository, link_id: str, type_: str) -> dict[st
)
if twin:
raise CaseError("those two already hold that relation")
- return case.update_link(link_id, {"type": type_})
+ # A qualifier belongs to the verb (``RelationType.qualifier``), so correcting the
+ # reading to one that takes none takes it with it. Left behind it would be data
+ # no surface can show and no analyst can clear — the edge would go on privately
+ # holding "sister" while stating that one unit is part of another.
+ patch: dict[str, Any] = {"type": type_}
+ if not spec.qualifier and link.get("nature"):
+ patch["nature"] = None
+ return case.update_link(link_id, patch)
def confirm_relation(case: CaseRepository, link_id: str) -> dict[str, Any]:
"""Accept a proposed relation, and with it the entities it joins.
- The two halves of an enrichment suggestion are one claim: "this file was shot
+ The two halves of an enrichment suggestion are one claim: "this file was recorded
at this point" cannot be true while the point itself is still only proposed.
So confirming the edge confirms whichever endpoint is still `suggested` — the
mirror of confirming an entity, which confirms its incident suggestions
@@ -182,6 +557,70 @@ def confirm_relation(case: CaseRepository, link_id: str) -> dict[str, Any]:
return case.update_link(link_id, {"status": "confirmed"})
+def set_confidence(case: CaseRepository, link_id: str, value: int | None) -> dict[str, Any]:
+ """Rate how sure the analyst is that one relation holds, or clear the rating.
+
+ ``None`` returns the edge to *not assessed*, which is a state an analyst is
+ entitled to go back to: a level assigned by mistake must not be a hole they are
+ trapped out of. ``REFUTED`` is set the same way as any other level — eliminating
+ a candidate is a finding, so it is recorded, not deleted.
+
+ **A chain edge never takes a rating.** ``derived-from`` records a mechanical fact
+ of the analyst's own click; "this frame probably came from that video" is not a
+ thing the save could have been unsure about. And a machine's suggestion is not
+ rated either: the axes are separate — ``prov_status`` is whether the claim has
+ been reviewed, ``confidence`` is how sure the reviewer is — so a suggestion is
+ confirmed first, and rated after.
+ """
+ link = case.get_link(link_id)
+ if link is None:
+ raise CaseError(f"link '{link_id}' not found")
+ if link["type"] in CHAIN_TYPES:
+ raise CaseError(f"'{link['type']}' is a derivation, and carries no confidence")
+ spec = relation_type(str(link["type"]))
+ if spec is not None and not spec.ratable:
+ raise CaseError(f"'{link['type']}' is a pointer, and carries no confidence")
+ if value is not None:
+ # bool is an int in Python, and `True` is not a level.
+ if isinstance(value, bool) or value not in CONFIDENCE_STATES:
+ raise CaseError(f"confidence must be one of {list(CONFIDENCE_STATES)}, or nothing")
+ if link["provenance"]["status"] == "suggested":
+ raise CaseError("confirm this relation before rating it")
+ return case.update_link(link_id, {"confidence": value})
+
+
+#: Longest a qualifier may be. Short on purpose: "sister", "employer", "former
+#: business partner" are what this field is for, and a box that accepts a paragraph
+#: becomes the note on the edge that the qualifier belongs to a verb to avoid.
+#: Reasoning that runs to sentences is a Claim, which has a field for it.
+MAX_QUALIFIER = 120
+
+
+def set_qualifier(case: CaseRepository, link_id: str, value: str | None) -> dict[str, Any]:
+ """Say what kind of tie one edge states, or clear it.
+
+ Only a verb that declares a ``qualifier`` may carry one, exactly as only a
+ ``ratable`` verb may carry an ordinal — and refusing it here is what keeps the
+ column from becoming a note any edge can hold. An empty string and ``None`` both
+ clear it: unstated is a state, and an analyst who typed a word by mistake must
+ not be trapped with it.
+ """
+ link = case.get_link(link_id)
+ if link is None:
+ raise CaseError(f"link '{link_id}' not found")
+ spec = relation_type(str(link["type"]))
+ if spec is None or not spec.qualifier:
+ raise CaseError(f"'{link['type']}' carries no qualifier")
+ if value is None:
+ return case.update_link(link_id, {"nature": None})
+ if not isinstance(value, str):
+ raise CaseError("a qualifier must be text")
+ text = value.strip()
+ if len(text) > MAX_QUALIFIER:
+ raise CaseError(f"a qualifier is at most {MAX_QUALIFIER} characters")
+ return case.update_link(link_id, {"nature": text or None})
+
+
def remove_relation(case: CaseRepository, link_id: str) -> None:
"""Take back one relation.
@@ -234,6 +673,66 @@ def _check_endpoints(
raise CaseError(f"a {source['type']} cannot be the subject of '{spec.type}'")
if target["type"] not in spec.to_types:
raise CaseError(f"a {target['type']} cannot be the object of '{spec.type}'")
+ _check_media_kind(source, spec.from_media_kinds, spec.type, "subject")
+ _check_media_kind(target, spec.to_media_kinds, spec.type, "object")
+
+
+def media_kind(entity: dict[str, Any]) -> str | None:
+ if entity.get("type") != "media":
+ return None
+ attrs = entity.get("attrs") or {}
+ kind = attrs.get("kind")
+ if isinstance(kind, str) and kind:
+ return kind
+ path = attrs.get("path")
+ mime = mimetypes.guess_type(str(path or ""))[0] or ""
+ for candidate in ("image", "video", "audio"):
+ if mime.startswith(candidate):
+ return candidate
+ return "file"
+
+
+def _check_media_kind(
+ entity: dict[str, Any], allowed: frozenset[str], verb: str, end: str
+) -> None:
+ if not allowed or entity.get("type") != "media":
+ return
+ kind = media_kind(entity)
+ if kind not in allowed:
+ expected = ", ".join(sorted(allowed))
+ raise CaseError(f"the {end} of '{verb}' must be {expected} media")
+
+
+def _check_relation_cycle(
+ case: CaseRepository, type_: str, from_id: str, to_id: str
+) -> None:
+ """Keep the verbs that **stack** from closing on themselves.
+
+ Ownership and membership can contain real cross-holdings, so only the relations
+ whose meaning stacks are checked: strict containment, and a statement resting on
+ another. *A because B, B because A* is circular reasoning rather than a shape a
+ case may hold — where two statements contradicting each other is an open question
+ and is deliberately left unchecked (`contradicts`).
+
+ Walking `cites` costs nothing on the material end: only a claim may cite, so a
+ bookmark or a media has no outgoing edge of this type and the walk stops on it.
+ """
+ if type_ not in (PART_OF, IN_NETWORK, CITES):
+ return
+ frontier = [to_id]
+ seen: set[str] = set()
+ while frontier:
+ current = frontier.pop()
+ if current == from_id:
+ raise CaseError(f"'{type_}' cannot create a cycle")
+ if current in seen:
+ continue
+ seen.add(current)
+ frontier.extend(
+ link["to"]
+ for link in case.links_of(current)
+ if link["type"] == type_ and link["from"] == current
+ )
def _now() -> str:
@@ -276,6 +775,47 @@ def resolve(case: CaseRepository, rel_paths: list[str]) -> tuple[list[str], list
return found, missing
+def _validated_chain_targets(
+ case: CaseRepository, entity_id: str, type_: str, target_ids: list[str]
+) -> list[str]:
+ holder = _entity(case, entity_id)
+ allowed = CHAIN_ENDPOINTS.get(type_, {}).get(str(holder["type"]))
+ if allowed is None:
+ raise CaseError(f"a {holder['type']} cannot hold '{type_}' sources")
+ valid: list[str] = []
+ for target_id in dict.fromkeys(target_ids):
+ if target_id == entity_id:
+ # A derivative that deduplicates onto its input must not create a
+ # self-edge. The bytes still exist once, so there is no second artifact
+ # whose lineage could be represented.
+ continue
+ target = _entity(case, target_id)
+ if target["type"] not in allowed:
+ raise CaseError(
+ f"a {holder['type']} cannot be {type_} a {target['type']}"
+ )
+ _check_chain_cycle(case, entity_id, target_id)
+ valid.append(target_id)
+ return valid
+
+
+def _check_chain_cycle(case: CaseRepository, from_id: str, to_id: str) -> None:
+ frontier = [to_id]
+ seen: set[str] = set()
+ while frontier:
+ current = frontier.pop()
+ if current == from_id:
+ raise CaseError("artifact lineage cannot create a cycle")
+ if current in seen:
+ continue
+ seen.add(current)
+ frontier.extend(
+ link["to"]
+ for link in case.links_of(current)
+ if link["type"] in CHAIN_TYPES and link["from"] == current
+ )
+
+
def sync(
case: CaseRepository, entity_id: str, type_: str, rel_paths: list[str], *, by: str
) -> None:
@@ -286,11 +826,79 @@ def sync(
longer resolves cannot be linked, but the fact that it was used is kept as a
tombstone rather than dropped in silence.
"""
- found, missing = resolve(case, rel_paths)
- case.sync_links(entity_id, type_, found, by=by)
+ paths = [path for path in rel_paths if path]
+ holder = _entity(case, entity_id)
+ if not paths and CHAIN_ENDPOINTS.get(type_, {}).get(str(holder["type"])) is None:
+ # Registration is shared by every file-backed type. A capture with no case
+ # source has no lineage to write; it is not an invalid attempted edge.
+ return
+ found, missing = resolve(case, paths)
+ valid = _validated_chain_targets(case, entity_id, type_, found)
+ case.sync_links(entity_id, type_, valid, by=by)
add_tombstones(case, entity_id, [{"path": path} for path in missing])
+#: Derivation targets an artifact's own body can speak for. A note shows media,
+#: captures and proofs; the `post` draft it was composed in is filed by the composer
+#: at creation and is named nowhere in the Markdown, so a body-driven restatement
+#: must leave that edge alone rather than read its absence as a removal.
+EMBEDDED_TYPES = frozenset({"media", "capture", "proof"})
+
+
+def sync_embedded(
+ case: CaseRepository,
+ entity_id: str,
+ to_ids: list[str],
+ *,
+ by: str,
+ over: frozenset[str] = EMBEDDED_TYPES,
+) -> None:
+ """Restate the ``derived-from`` edges an artifact's own text names.
+
+ ``sync`` reconciles every edge of its type, which is right for a proof whose spec
+ lists all of its panels. A note's Markdown is narrower: it names the files it
+ shows and nothing else, so reconciling on it would drop the draft edge nothing in
+ the body could have restated. ``over`` is the set of target types the body speaks
+ for; an edge pointing anywhere else is left exactly as it is.
+
+ Called on every note save, so a case image inserted afterwards gets its edge and
+ one deleted from the text loses it. Without that, a hand-inserted image was a
+ dependency nothing in the graph knew about — deleting it left the note showing a
+ hole — and a removed one left a scar the note had stopped earning.
+
+ An id the vocabulary cannot join is skipped rather than refused: a body is prose,
+ and a note must not fail to save because a token points somewhere odd.
+ """
+ holder = _entity(case, entity_id)
+ allowed = CHAIN_ENDPOINTS.get(DERIVED_FROM, {}).get(str(holder["type"]))
+ if allowed is None:
+ return
+
+ wanted: list[str] = []
+ for to_id in dict.fromkeys(to_ids):
+ if to_id == entity_id:
+ continue
+ target = case.get_entity(to_id)
+ if target is None or target["type"] not in allowed or target["type"] not in over:
+ continue
+ try:
+ _check_chain_cycle(case, entity_id, to_id)
+ except CaseError:
+ continue # a note embedded inside its own source is prose, not a graph edit
+ wanted.append(to_id)
+
+ for link in case.links_of(entity_id):
+ if link["type"] != DERIVED_FROM or link["from"] != entity_id:
+ continue
+ if link["to"] in wanted:
+ continue
+ neighbour = case.get_entity(link["to"])
+ if neighbour is not None and neighbour["type"] in over:
+ case.remove_link(link["id"])
+ for to_id in wanted:
+ case.add_link(entity_id, to_id, DERIVED_FROM, by=by, unique=True)
+
+
def link_all(
case: CaseRepository, entity_id: str, type_: str, rel_paths: list[str], *, by: str
) -> None:
@@ -300,10 +908,14 @@ def link_all(
same bytes really can come from two different videos, and that entity keeps
both derivations.
"""
- found, missing = resolve(case, rel_paths)
- for to_id in found:
- if to_id != entity_id:
- case.add_link(entity_id, to_id, type_, by=by, unique=True)
+ paths = [path for path in rel_paths if path]
+ holder = _entity(case, entity_id)
+ if not paths and CHAIN_ENDPOINTS.get(type_, {}).get(str(holder["type"])) is None:
+ return
+ found, missing = resolve(case, paths)
+ valid = _validated_chain_targets(case, entity_id, type_, found)
+ for to_id in valid:
+ case.add_link(entity_id, to_id, type_, by=by, unique=True)
add_tombstones(case, entity_id, [{"path": path} for path in missing])
diff --git a/src/azimut/engine/media.py b/src/azimut/engine/media.py
index c5d2a7f..69462fb 100644
--- a/src/azimut/engine/media.py
+++ b/src/azimut/engine/media.py
@@ -308,6 +308,38 @@ def import_stream(case: Case, filename: str, stream: BinaryIO) -> dict[str, Any]
return _register(case, dest, {"type": "upload", "original_name": filename})
+def import_paste(
+ case: Case,
+ filename: str,
+ stream: BinaryIO,
+ *,
+ source_url: str = "",
+ title: str = "",
+) -> dict[str, Any]:
+ """File an image the analyst pasted out of the clipboard.
+
+ Its own entry rather than ``import_stream``'s: a paste has no file behind it to
+ be named after, and no origin the bytes can be read for. So the name comes from
+ the title typed in the dialog (a stamped one when nothing was typed — every
+ clipboard image is called ``image.png``), and the origin is whatever address was
+ typed beside it, which is the only chance to state one.
+
+ Recorded as ``clipboard`` and never as an upload: a screenshot with no stated
+ source must not read like a file somebody chose off a disk. Deduped like any
+ upload, so pasting the same crop twice is one file.
+ """
+ media_dir = case.subdir("media")
+ suffix = Path(safe_filename(filename)).suffix or ".png"
+ stamped = f"paste-{datetime.now(timezone.utc).strftime('%Y%m%d-%H%M%S')}"
+ dest = unique_path(media_dir, layout.visible_filename(title.strip() or stamped, suffix))
+ with dest.open("wb") as out:
+ shutil.copyfileobj(stream, out)
+ source: dict[str, Any] = {"type": "clipboard", "original_name": filename}
+ if source_url:
+ source["url"] = source_url
+ return _register(case, dest, source, by="paste")
+
+
def register_existing(case: Case, rel_path: str, *, by: str = "case-doctor") -> dict[str, Any]:
"""Adopt a file that was placed directly in this case's media directory.
diff --git a/src/azimut/engine/notes_pdf.py b/src/azimut/engine/notes_pdf.py
index 6e00290..f952594 100644
--- a/src/azimut/engine/notes_pdf.py
+++ b/src/azimut/engine/notes_pdf.py
@@ -102,6 +102,17 @@ WIDTH_PIXELS = re.compile(r"^(?:[2-9]\d|[1-9]\d{2}|1[0-5]\d{2}|1600)px$")
ALIGNMENTS = {"left": Align.L, "center": Align.C, "right": Align.R}
+
+def embedded_entity_ids(text: str) -> list[str]:
+ """The case artifacts a note shows, in the order they appear, deduplicated.
+
+ ``[[media:…]]`` only, never ``[[entity:…]]``: the first is the note *showing* a
+ file, which is a derivation, where the second is a pointer at a record, which is
+ a mention (ONTOLOGY §3). Reuses the renderer's own pattern, so what the chain
+ records and what the page draws can never become two readings of one note.
+ """
+ return list(dict.fromkeys(match.group(1) for match in MEDIA_REF.finditer(text or "")))
+
#: Heading sizes, h1 to h6, and the space above each.
HEADINGS = {
"h1": (16.0, 7.0),
diff --git a/src/azimut/engine/reveal.py b/src/azimut/engine/reveal.py
index 597e5ef..28f4c83 100644
--- a/src/azimut/engine/reveal.py
+++ b/src/azimut/engine/reveal.py
@@ -5,9 +5,13 @@ manager. The backend can, the same way ``launcher.py`` already opens the browser
tab, so "where are my files" is answered by the OS's own window instead of by a
path the analyst has to copy out of Settings by hand.
-Callers never pass a path the browser chose: the routes name *what* to show (a
-case, the workspace) and resolve the path here, so there is nothing to traverse
-out of. The containment check below is the belt on top of that.
+Two kinds of caller reach this, and each has its own guard. Most routes name
+*what* to show — a case, the workspace, the notes export folder — and resolve the
+path themselves, so there is nothing to traverse out of. One route takes a path
+the analyst pointed at (`POST /cases/{id}/media/reveal`); there the path is bounded
+and run through `Case.resolve_inside`, which resolves it and refuses anything
+landing outside the case, before it ever arrives here. The containment check below
+is the belt on top of both.
"""
from __future__ import annotations
diff --git a/src/azimut/engine/satellite.py b/src/azimut/engine/satellite.py
index e04bc4e..0fd7e1c 100644
--- a/src/azimut/engine/satellite.py
+++ b/src/azimut/engine/satellite.py
@@ -18,11 +18,12 @@ to).
from __future__ import annotations
+import json
from datetime import datetime, timezone
from typing import Any
from ..repository import EntityStatus
-from ..workspace import Case
+from ..workspace import Case, CaseError
from . import continents
from . import coords as coords_engine
from . import countries
@@ -89,6 +90,276 @@ def save_place(
return case.add_entity("place", label, attrs=attrs, by=by, status=status)
+#: Which attribute holds the rounded point two places are considered one at.
+#: Five decimals is about a metre. The name is import enrichment's, which wrote
+#: the key first, and it is **shared rather than copied**: a photo's EXIF point
+#: and a capture framed on the same spot have to land on one node, or the case
+#: grows two places nobody asked it to tell apart.
+COORD_KEY = "enrich_coord_key"
+
+
+def coord_key(lat: float, lon: float) -> str:
+ """The dedup key for a point, rounded to roughly one metre."""
+ return f"{float(lat):.5f},{float(lon):.5f}"
+
+
+def place_at(
+ case: Case, lat: float, lon: float, *, keyed_only: bool = True
+) -> dict[str, Any] | None:
+ """The place already standing at this point, or None.
+
+ ``keyed_only`` is the difference between a machine's reading and the
+ analyst's own gesture, and it decides whether a place they pinned by hand can
+ be reused.
+
+ **Enrichment keeps it on** (the default). A camera's EXIF proposing a point
+ must not attach itself to a pin somebody placed deliberately: those two may
+ be the same spot or may not, and deciding is a judgement the Suggestions
+ panel exists to let them make.
+
+ **A capture turns it off.** The analyst framed that view themselves, so the
+ pin already at that point is not somebody else's claim to be weighed — it is
+ the same act, made twice. Reusing it is what keeps one point from drawing as
+ two pins a metre apart.
+ """
+ key = coord_key(lat, lon)
+ found = case.find_entity(attr=COORD_KEY, value=key)
+ if found is not None or keyed_only:
+ return found
+ for place in _page_all(case, ["place"]):
+ attrs = place.get("attrs") or {}
+ if attrs.get("lat") is None or attrs.get("lon") is None:
+ continue
+ try:
+ if coord_key(attrs["lat"], attrs["lon"]) == key:
+ return place
+ except (TypeError, ValueError):
+ continue
+ return None
+
+
+def place_for_proof(
+ case: Case,
+ proof_id: str,
+ lat: float,
+ lon: float,
+ *,
+ pov: bool = False,
+ by: str = "proof-composer",
+) -> tuple[dict[str, Any], list[dict[str, Any]]]:
+ """File a proof's point as a ``place``, and join what the proof establishes.
+
+ **A geolocation is concluded in the composer, not while framing the map.** The
+ coordinates a proof carries are the analyst's answer — what they typed, or the
+ point their panels gave it and they left standing — where a capture is one of
+ the dozen views taken while looking. So the point becomes a node here, once,
+ at the moment somebody commits to it, rather than on every crop.
+
+ Filed ``confirmed``: whether it was typed or accepted from the panels, the
+ proof is the analyst's own act, and a review step over one's own answer is a
+ step over nothing.
+
+ **The proof itself always ``depicts``.** It was composed, never recorded
+ anywhere, so ``located-at`` is not a reading it can take — which is what the
+ registry says too. ``pov`` decides the verb for the *material*, and only there.
+
+ The caller decides *whether* to ask (``config.proof_place_auto``); this only
+ files. Callers check :func:`place_at` first, so a point already in the case is
+ never duplicated and never asked about.
+
+ Answers with the place and whatever the proof let go of to conclude on it
+ (:func:`restate_proof_point`).
+ """
+ place = save_place(
+ case, float(lat), float(lon), by=by,
+ extra_attrs={COORD_KEY: coord_key(float(lat), float(lon))},
+ )
+ return place, restate_proof_point(case, proof_id, place["id"], pov=pov, by=by)
+
+
+#: The two verbs a proof's point is stated with. `depicts` for the composition and
+#: for anything it shows; `located-at` for material POV says was recorded there.
+PLACE_VERBS = (links.DEPICTS, links.LOCATED_AT)
+
+
+def restate_proof_point(
+ case: Case,
+ proof_id: str,
+ place_id: str | None,
+ *,
+ pov: bool = False,
+ by: str = "proof-composer",
+) -> list[dict[str, Any]]:
+ """Make the graph say what this proof says now, and stop saying what it said.
+
+ **A proof states one point, and a save is the restatement of it** — the same
+ rule its panels already follow (``links.sync``, ONTOLOGY §3). Re-opening a
+ proof and correcting the coordinates is the analyst withdrawing an answer, so
+ the old edges go rather than piling up beside the new ones; toggling POV is
+ them saying the point means something else, so the verb on the material
+ changes. Without this a corrected proof read as two geolocations, and a POV
+ answer could only ever be given once.
+
+ ``place_id`` is the point the proof concludes on now, or ``None`` when it
+ concludes on none — a coordinate field cleared withdraws the claim rather than
+ freezing the last one.
+
+ **Only what the composer itself wrote is reconciled** (``by``). An edge the
+ analyst stated by hand in Details, or one import enrichment proposed from a
+ photo's EXIF, is a separate claim about the same file: saving a proof must not
+ silently drop it.
+
+ Answers with the places this proof let go of that nothing else holds — the
+ caller asks about deleting them (``api/proofs``), since a point nobody points
+ at is the analyst's own leftover to keep or drop, not ours to sweep.
+ """
+ material = [
+ entity
+ for entity in (links.derivation_subgraph(case, proof_id) or {}).get("entities", [])
+ if entity["id"] != proof_id
+ ]
+ released: list[dict[str, Any]] = []
+ for old_id in _stated_places(case, proof_id, by=by):
+ if old_id == place_id:
+ continue
+ _withdraw_point(case, proof_id, old_id, material, by=by)
+ old = case.get_entity(old_id)
+ if old is not None and not case.links_of(old_id):
+ released.append(old)
+ if place_id is not None:
+ _state_point(case, proof_id, place_id, material, pov=pov, by=by)
+ return released
+
+
+def _stated_places(case: Case, proof_id: str, *, by: str) -> list[str]:
+ """The points this proof currently concludes on, read off its own edges.
+
+ The proof is the only reliable record of where a save put its material: the
+ edges it wrote on a video carry no proof id, so what a re-save has to undo is
+ read from the composition that wrote them.
+ """
+ seen: list[str] = []
+ for link in case.links_of(proof_id):
+ if link["from"] != proof_id or link["type"] not in PLACE_VERBS:
+ continue
+ if (link.get("provenance") or {}).get("by") != by:
+ continue
+ target = case.get_entity(link["to"])
+ if target is not None and target["type"] == "place" and link["to"] not in seen:
+ seen.append(link["to"])
+ return seen
+
+
+def _other_proof_states(case: Case, place_id: str, proof_id: str, *, by: str) -> bool:
+ """True if another proof still concludes on this point.
+
+ Two proofs built from one video can land on the same roof, and the edges they
+ wrote on that video are indistinguishable. So a save withdraws its own point
+ only while it is the last one claiming it: dropping the material's edge here
+ would undo a conclusion this proof never made.
+ """
+ for link in case.links_of(place_id):
+ if link["to"] != place_id or link["type"] not in PLACE_VERBS or link["from"] == proof_id:
+ continue
+ if (link.get("provenance") or {}).get("by") != by:
+ continue
+ source = case.get_entity(link["from"])
+ if source is not None and source["type"] == "proof":
+ return True
+ return False
+
+
+def _drop_stated(case: Case, entity_id: str, place_id: str, verbs: tuple[str, ...], by: str) -> None:
+ """Remove this entity's own statements about a point, and nothing else's."""
+ for link in case.links_of(entity_id):
+ if link["from"] != entity_id or link["to"] != place_id or link["type"] not in verbs:
+ continue
+ if (link.get("provenance") or {}).get("by") == by:
+ case.remove_link(link["id"])
+
+
+def _withdraw_point(
+ case: Case, proof_id: str, place_id: str, material: list[dict[str, Any]], *, by: str
+) -> None:
+ """Take back a point this proof no longer concludes on, material included."""
+ shared = _other_proof_states(case, place_id, proof_id, by=by)
+ _drop_stated(case, proof_id, place_id, PLACE_VERBS, by)
+ if shared:
+ return
+ for entity in material:
+ _drop_stated(case, entity["id"], place_id, PLACE_VERBS, by)
+
+
+def _state_point(
+ case: Case,
+ proof_id: str,
+ place_id: str,
+ material: list[dict[str, Any]],
+ *,
+ pov: bool,
+ by: str,
+) -> None:
+ """Join the proof and the material it was composed from to the same point.
+
+ **The proof itself always ``depicts``.** It was composed, never recorded
+ anywhere, so ``located-at`` is not a reading it can take — which is what the
+ registry says too. ``pov`` decides the verb for the *material*, and only there.
+
+ A proof stating a point is the analyst's answer about **the footage**, not
+ about the composition: the whole reason the proof exists is to say where that
+ video was. So the files behind it carry the edge too — the frame, the collage,
+ the video two hops up, the capture — read off the derivation closure rather
+ than the panels alone, since a frame stands between a proof and the clip it
+ came from.
+
+ **``pov`` picks the verb, because the composition cannot.** Recorded-at and
+ shows are independent claims: a rooftop shot was recorded somewhere it never
+ shows, and a skyline is shown from kilometres away. Neither entails the other,
+ and a match between a frame and an imagery says only that they meet — not
+ whether the analyst located the camera or what it was pointed at. So the
+ composer asks once, and the answer travels in the spec:
+
+ - ``pov`` — the point is where the camera stood → ``located-at`` on the media
+ (an image, a video or a recording of the moment);
+ - otherwise — the point is what the frame shows → ``depicts``.
+
+ **A capture is never ``located-at``.** Orbital imagery was not recorded on the
+ ground, so it shows the place whichever answer the analyst gave.
+
+ Filed ``confirmed``, because composing is the assertion: putting a frame beside
+ a capture and writing the coordinates *is* the geolocation, and there is no
+ second opinion to collect from the person who just made it. A review everybody
+ clicks through is what makes ``suggested`` stop meaning anything where it is
+ real, on a camera's EXIF or a hash match (ONTOLOGY §4). Being wrong costs one
+ removal: a relation drops alone, cascading nothing and leaving no tombstone.
+
+ Only what the verb accepts. A PDF in the chain is skipped rather than refused,
+ and so is an audio file unless the point is where it was recorded.
+
+ **The verb is restated, not only added.** Answering POV differently on a
+ re-save is the analyst correcting what the point means, so the reading it
+ replaces goes: a video stops showing the place and is recorded there instead,
+ and an audio file drops the edge ``shows`` would refuse. A point another proof
+ still concludes on is left alone (:func:`_other_proof_states`) — the answer
+ being restated is this proof's, and it does not speak for that one.
+ """
+ verb = links.LOCATED_AT if pov else links.DEPICTS
+ kinds = ("image", "video", "audio") if pov else ("image", "video")
+ shared = _other_proof_states(case, place_id, proof_id, by=by)
+ case.add_link(proof_id, place_id, links.DEPICTS, by=by, unique=True)
+ for entity in material:
+ wanted: str | None = None
+ if entity["type"] == "capture":
+ wanted = links.DEPICTS
+ elif entity["type"] == "media" and links.media_kind(entity) in kinds:
+ wanted = verb
+ if not shared:
+ stale = tuple(v for v in PLACE_VERBS if v != wanted)
+ _drop_stated(case, entity["id"], place_id, stale, by)
+ if wanted is not None:
+ case.add_link(entity["id"], place_id, wanted, by=by, unique=True)
+
+
def is_capture(item: dict[str, Any]) -> bool:
"""True if a media listing item is a capture: a satellite crop, or an
external-map screenshot filed by the capture extension (api/ingest.py) —
@@ -225,6 +496,12 @@ def _saved_row(
"fetched_at": _saved_when(entity, capture),
"imagery_date": source.get("imagery_date"),
"notes": source.get("notes") or attrs.get("notes") or "",
+ # How tightly the point is pinned (ONTOLOGY §2). Carried in the index
+ # because the map overlay draws it: an approximate place is a circle or a
+ # polygon rather than a pin, and a pin on a guess is the lie this fixes.
+ # Absent stays absent — a point with no radius draws exactly as before.
+ "radius_m": attrs.get("radius_m"),
+ "footprint": attrs.get("footprint"),
# how many proofs were built on this point. `All` draws every point
# once, so a worked row is marked rather than doubled by a proof
# marker landing on the capture it composes.
@@ -253,7 +530,13 @@ def saved_index(case: Case) -> list[dict[str, Any]]:
# two grouped queries for the whole case rather than one per row: this list
# is read on case open and must not walk the graph row by row
worked = case.count_dependents(link_type=links.DERIVED_FROM, from_type="proof")
- related = case.count_incident_links(exclude_types=list(links.CHAIN_TYPES))
+ related = case.count_incident_links(
+ exclude_types=[
+ *links.CHAIN_TYPES,
+ links.MENTIONS,
+ *links.CLAIM_CONNECTION_TYPES,
+ ]
+ )
rows = []
for entity in saved_entities(case):
is_image = entity["type"] == "capture"
@@ -451,6 +734,158 @@ def proof_index(
return rows
+# -- placement: where the chain puts an entity (ONTOLOGY §3) ----------------------
+#
+# The chain is read backwards as geography: a proof with no point of its own stands
+# at the point of every capture it composes. `proof_index` does that one hop back
+# for the map. This walks the same edges in both directions and further, because
+# the artifact holding the point is rarely the one being read: a video reaches its
+# capture through a proof that composed a frame of it, three hops away through a
+# shared descendant. That V is what the geolocation gesture actually looks like —
+# putting a frame beside a satellite view *is* the assertion they are one place.
+
+#: How far a placement walk travels over chain edges. A note sits three hops above a
+#: capture (note → post → proof → capture) and a video three below one
+#: (video ← frame ← proof → capture), so four covers every shape `CHAIN_ENDPOINTS`
+#: declares with one hop to spare.
+PLACEMENT_DEPTH = 4
+#: Entities one walk may read, whatever the depth would allow. A video cut into forty
+#: frames across ten proofs must not turn opening a panel into a graph scan.
+PLACEMENT_NODES = 200
+#: Points one entity reports. Fifteen distinct placements is a case already
+#: contradicting itself; past that the panel is a wall rather than a reading.
+PLACEMENT_LIMIT = 15
+
+
+def _point(lat: Any, lon: Any) -> dict[str, float] | None:
+ if lat is None or lon is None:
+ return None
+ try:
+ return {"lat": float(lat), "lon": float(lon)}
+ except (TypeError, ValueError):
+ return None
+
+
+def _entity_point(case: Case, entity: dict[str, Any]) -> dict[str, float] | None:
+ """The point this entity carries itself, or None if it carries none.
+
+ Two types hold one inside a chain. A ``capture`` records the marker it was taken
+ at. A ``proof`` states its own through the composer, and ``own_point`` is what
+ decides which: what the analyst typed wins over what the panels froze. Reusing it
+ here is what keeps a video from reporting a capture's raw point while the proof
+ beside it shows the corrected one.
+ """
+ attrs = entity.get("attrs") or {}
+ if entity.get("type") == "capture":
+ return _point(attrs.get("lat"), attrs.get("lon"))
+ if entity.get("type") != "proof":
+ return None
+ spec_rel = attrs.get("spec")
+ if not isinstance(spec_rel, str) or not spec_rel:
+ return None
+ try:
+ spec = json.loads(case.resolve_inside(spec_rel).read_text(encoding="utf-8"))
+ except (OSError, ValueError, CaseError):
+ return None # a spec deleted or half-written places nothing
+ return own_point(spec) if isinstance(spec, dict) else None
+
+
+def _filed_at(entity: dict[str, Any]) -> str:
+ return str((entity.get("provenance") or {}).get("at") or "")
+
+
+def placements(
+ case: Case, entity_id: str, *, limit: int | None = None
+) -> dict[str, Any] | None:
+ """Where the derivation chain puts one entity, nearest placement first.
+
+ Breadth-first over ``derived-from``/``depends-on`` in both directions, so the
+ artifact that placed this one is found however far round the V it sits. Each
+ point comes back with the entity it was read off — the *via* the panel names —
+ and the entity's own point comes back with none, because nothing placed it.
+
+ **An artifact that carries a point is where the walk stops.** ``proof_index``
+ already settles this for the map — a proof that states where it is says it once,
+ rather than also drawing at the panels it overrode — and a panel that listed both
+ would contradict the map about the same proof. Stopping there is also what keeps
+ a video to its own argument: the capture behind its proof is reached, the second
+ proof that happens to reuse that capture is not.
+
+ Points are deduplicated on the exact pair, never on a rounded one: two captures
+ of the same roof are metres apart, and merging them would assert they are one
+ place, which is the analyst's call and not a rounding. The nearest hop wins a
+ repeated point, and the most recently filed artifact wins inside one hop.
+
+ A ``capture`` reports nothing at all. Its point is its own, written at the save
+ and already read under Info, so listing it here would show one datum twice in one
+ panel for the single type that never derived it.
+
+ Returns ``None`` when the entity is gone.
+ """
+ root = case.get_entity(entity_id)
+ if root is None:
+ return None
+ if root.get("type") == "capture":
+ return {"points": [], "truncated": False}
+
+ cap = PLACEMENT_LIMIT if limit is None else limit
+ found: dict[tuple[float, float], dict[str, Any]] = {}
+ seen: set[str] = {entity_id}
+ frontier = [root]
+ reads = 1
+ truncated = False
+ for depth in range(PLACEMENT_DEPTH + 1):
+ if not frontier:
+ break
+ # newest first inside one hop: when two artifacts state the same point, the
+ # freshest reading is the one worth attributing it to
+ frontier.sort(key=_filed_at, reverse=True)
+ neighbours: list[str] = []
+ for node in frontier:
+ point = _entity_point(case, node)
+ if point is not None:
+ key = (point["lat"], point["lon"])
+ if key in found: # a nearer artifact already stands here
+ continue
+ if len(found) >= cap:
+ truncated = True
+ else:
+ found[key] = {
+ "lat": point["lat"],
+ "lon": point["lon"],
+ "depth": depth,
+ "via": None
+ if node["id"] == entity_id
+ else {
+ "id": node["id"],
+ "type": node.get("type"),
+ "label": node.get("label"),
+ },
+ }
+ continue # this artifact is the placement; what it was made from is not
+ if depth == PLACEMENT_DEPTH:
+ continue
+ for link in case.links_of(node["id"]):
+ if link["type"] not in links.CHAIN_TYPES:
+ continue
+ other = link["to"] if link["from"] == node["id"] else link["from"]
+ if other in seen:
+ continue
+ seen.add(other)
+ neighbours.append(other)
+ nxt: list[dict[str, Any]] = []
+ for other_id in neighbours:
+ if reads >= PLACEMENT_NODES:
+ truncated = True # the walk stopped short, so the list may be partial
+ break
+ neighbour = case.get_entity(other_id)
+ reads += 1
+ if neighbour is not None:
+ nxt.append(neighbour)
+ frontier = nxt
+ return {"points": list(found.values()), "truncated": truncated}
+
+
def is_unlocated(entity: dict[str, Any]) -> bool:
"""True when geography was never resolved for this entity, or the lookup
failed. ``nocoords``/``nocountry``/``ok`` are settled and never retried."""
diff --git a/src/azimut/engine/sky.py b/src/azimut/engine/sky.py
index d92f13d..4437eea 100644
--- a/src/azimut/engine/sky.py
+++ b/src/azimut/engine/sky.py
@@ -588,6 +588,59 @@ def day_events(
return {"sun": sun, "twilight": twilight, "moon": moon}
+def daylight_spans(
+ lat: float,
+ lon: float,
+ start: datetime,
+ end: datetime,
+ threshold: float = SUN_HORIZON_DEG,
+ step_minutes: int = 1,
+) -> list[dict[str, datetime]]:
+ """The stretches of a window during which the sun stands above ``threshold``.
+
+ ``day_events`` above answers *when did the sun rise on this date*, which is an
+ almanac's question and is paired around one culmination. This answers a different
+ one: *over these days, when was it light* — a run of spans clipped to the window,
+ for a chronology that needs to place a timestamp against the daylight at the spot
+ it claims.
+
+ A span open at either edge is clipped to the window rather than reaching outside
+ it, and a window with no crossing at all is one span or none: polar day and polar
+ night are answers here too, and the caller cannot tell them apart from a missing
+ computation unless the whole window comes back covered or empty.
+ """
+ if end <= start:
+ return []
+ jd = _grid(start, end, max(1, step_minutes) * 60)
+ altitude = _positions(lat, lon, jd)["sun_altitude"]
+
+ def offset(point: float) -> float:
+ return float(_positions(lat, lon, np.array([point]))["sun_altitude"][0] - threshold)
+
+ rising, falling = _crossings(
+ jd, altitude - threshold, lambda low, high: _secant(offset, low, high)
+ )
+ first = _julian_day([start])[0]
+ last = _julian_day([end])[0]
+ edges = sorted(
+ [(point, True) for point in rising] + [(point, False) for point in falling]
+ )
+ spans: list[dict[str, datetime]] = []
+ # Where the window opens decides whether the first edge closes a span or opens
+ # one: a window starting at noon is inside daylight before anything crosses.
+ open_at: float | None = first if bool(altitude[0] > threshold) else None
+ for point, is_rise in edges:
+ if is_rise:
+ if open_at is None:
+ open_at = point
+ elif open_at is not None:
+ spans.append({"from": _to_datetime(open_at), "to": _to_datetime(point)})
+ open_at = None
+ if open_at is not None:
+ spans.append({"from": _to_datetime(open_at), "to": _to_datetime(last)})
+ return spans
+
+
def day_curve(
lat: float, lon: float, start: datetime, end: datetime, step_minutes: int = 10
) -> dict[str, Any]:
diff --git a/src/azimut/engine/tally.py b/src/azimut/engine/tally.py
new file mode 100644
index 0000000..8810145
--- /dev/null
+++ b/src/azimut/engine/tally.py
@@ -0,0 +1,297 @@
+"""What the case's statements add up to (ONTOLOGY §2, "Counting a model rather than
+minting objects").
+
+A case that follows a conflict writes the same statement over and over — *two of
+these destroyed here, filmed by that* — and the Board lists each one on its own row.
+Twenty rows later the question stops being what each says and becomes what they come
+to, which the table cannot answer: reading a total off it is the analyst adding up by
+hand.
+
+So this is the addition, over **the narrowing the analyst already set**. The same
+chips, answered a second way rather than listed a second time: grouped by what each
+statement is ``about``, summed over ``count``, split by ``condition``.
+
+Four rules keep the number honest, and every one of them is a call the vocabulary
+already made:
+
+**A statement ruled out is never inside a sum.** ``refuted`` reads *checked and
+eliminated*, so adding one to a total states the opposite of what the analyst
+concluded. Ruled-out statements are counted apart, on the row they belong to, because
+eliminating a candidate is work the case keeps rather than work it throws away.
+
+**An absent ``count`` is not one.** It means *seen, not counted*, a different and
+honest answer, so such a statement counts as a statement and stays out of the sum.
+Each row says how many of its statements carried a number, or the two would be
+indistinguishable in the total.
+
+**Nothing is added across subjects.** ``count`` sits on the node and not on ``about``,
+precisely because a statement may point at several subjects and one number could not
+say which it meant. Per subject the sum is what the statements say; added across
+subjects it would spend one statement twice. So there is no grand total here, by
+construction — the reading answers *how many of this*, never *how many altogether*.
+
+**It counts observations, not objects.** Two videos of one destroyed vehicle are two
+statements, and folding them into one is the open ``same-as`` question (ONTOLOGY §4).
+Every number is therefore worded as statements and what they assert.
+
+What it deliberately does not do is group above the subject. Three statements about
+three T-72 variants stay three rows, because no verb says one model is a variant of
+another (``instance-of`` runs asset → class and stops there). Whether that verb is
+worth adding is a question this reading is meant to answer, not to presume.
+"""
+
+from __future__ import annotations
+
+import math
+from typing import Any
+
+from ..repository import CaseRepository
+from . import entities, links
+
+#: How many statements one reading adds up. A statement is analyst-typed, so a case
+#: reaching this has thousands of them and a total over the first two thousand would
+#: be a number that looks whole and is not — hence the cut is reported rather than
+#: applied quietly.
+MAX_STATEMENTS = 2000
+
+#: The order conditions read in, from the registry rather than spelled again, with
+#: *unstated* last: it is the absence of an answer, not one of the answers.
+_CONDITION_ORDER = {value: rank for rank, (value, _) in enumerate(entities.ASSET_CONDITIONS)}
+_CONFIDENCE_ORDER = {value: rank for rank, (value, _) in enumerate(entities.CLAIM_CONFIDENCE)}
+
+#: The one level that leaves a statement out of every sum (ONTOLOGY §3).
+RULED_OUT = "refuted"
+
+
+def tally(
+ case: CaseRepository,
+ *,
+ types: list[str] | None = None,
+ status: str | None = None,
+ query: str | None = None,
+ folder: str | None = None,
+ unfiled: bool = False,
+ recursive: bool = False,
+ attr: str | None = None,
+ attr_value: str | None = None,
+ linked: str | None = None,
+ unlinked: bool = False,
+ since: str | None = None,
+ until: str | None = None,
+ filed_by: list[str] | None = None,
+ temporal_since: str | None = None,
+ temporal_until: str | None = None,
+ temporal_categories: list[str] | None = None,
+ limit: int = MAX_STATEMENTS,
+) -> dict[str, Any]:
+ """The statements in this narrowing, grouped by subject and added up.
+
+ Returns ``{rows, read, matched, truncated, unattributed}``. ``read`` is how many
+ statements the sums stand on and ``matched`` how many the narrowing holds: equal
+ unless the cut fell, which ``truncated`` says outright.
+
+ ``types`` is the analyst's own type chip and it **narrows rather than selects**:
+ the reading is of statements, so it intersects with ``claim`` instead of replacing
+ it. A chip that keeps only media leaves no statement, and answering that with
+ every statement in the case would be answering a question nobody asked.
+ """
+ wanted = ["claim"] if types is None else [name for name in types if name == "claim"]
+ if not wanted:
+ return {"rows": [], "read": 0, "matched": 0, "truncated": False, "unattributed": 0}
+
+ bounded = max(1, min(int(limit), MAX_STATEMENTS))
+ page = case.page_entities(
+ limit=bounded, types=wanted, status=_status(status), query=query,
+ folder=folder, unfiled=unfiled, recursive=recursive,
+ attr=attr, attr_value=attr_value, linked=linked, unlinked=unlinked,
+ since=since, until=until, filed_by=filed_by,
+ temporal_since=temporal_since, temporal_until=temporal_until,
+ temporal_categories=temporal_categories,
+ )
+ claims: list[dict[str, Any]] = page["items"]
+ matched = int(page["total"])
+ if not claims:
+ return {
+ "rows": [], "read": 0, "matched": matched,
+ "truncated": False, "unattributed": 0,
+ }
+
+ held = {claim["id"] for claim in claims}
+ subjects: dict[str, list[str]] = {}
+ for link in case.links_touching(list(held), types=[links.ABOUT]):
+ # `about` runs claim → subject, so the near end is the statement. Read off the
+ # edge rather than assumed: an older case may hold a direction the current
+ # registry would refuse, and it must not become a subject of itself.
+ if link["from"] in held and link["to"] not in held:
+ subjects.setdefault(link["from"], []).append(link["to"])
+
+ rows: dict[str, dict[str, Any]] = {}
+ unattributed = 0
+ for claim in claims:
+ targets = subjects.get(claim["id"], [])
+ if not targets:
+ # A statement about nothing. Not an error and not dropped: it is a row of
+ # the case that says what it concerns nowhere, and a reading that silently
+ # ignored it would make the sums look complete.
+ unattributed += 1
+ continue
+ for target in targets:
+ _fold_in(rows.setdefault(target, _empty_row(target)), claim)
+
+ named = {
+ entity["id"]: entity for entity in case.entities_by_ids(list(rows))
+ }
+ return {
+ "rows": _ordered(rows, named),
+ "read": len(claims),
+ "matched": matched,
+ "truncated": matched > len(claims),
+ "unattributed": unattributed,
+ }
+
+
+def for_subject(
+ case: CaseRepository, entity_id: str, *, limit: int = MAX_STATEMENTS
+) -> dict[str, Any] | None:
+ """What the statements about **one** subject come to, or nothing if there are none.
+
+ The panel already lists the statements pointing at an entity; this is the same set
+ added up, and it is the reading an analyst reaches for first — *what does the case
+ say about this model* is a question about one row, not about a narrowing.
+
+ It answers over the whole case rather than over any filter, because the panel is
+ not narrowed: a total that quietly obeyed a filter set on another screen would be
+ a different number under the same words.
+
+ The rules are the ones above, applied by the same code, so the two readings cannot
+ drift: a ruled-out statement stays outside the sum here too.
+ """
+ bounded = max(1, min(int(limit), MAX_STATEMENTS))
+ subject = case.get_entity(entity_id)
+ if subject is None:
+ return None
+
+ stating = [
+ link["from"]
+ for link in case.links_touching([entity_id], types=[links.ABOUT])
+ if link["to"] == entity_id and link["from"] != entity_id
+ ]
+ if not stating:
+ return None
+
+ kept = list(dict.fromkeys(stating))[:bounded]
+ row = _empty_row(entity_id)
+ for claim in case.entities_by_ids(kept):
+ if claim.get("type") == "claim":
+ _fold_in(row, claim)
+ built = _ordered({entity_id: row}, {entity_id: subject})[0]
+ return {**built, "read": len(kept), "matched": len(stating)}
+
+
+def _fold_in(row: dict[str, Any], claim: dict[str, Any]) -> None:
+ """One statement added to one subject's row, which is where every rule lands.
+
+ Shared by both readings on purpose: the tally and the panel would otherwise be two
+ implementations of *what may enter a sum*, and the day they disagreed the case
+ would have two totals for one question.
+ """
+ attrs = claim.get("attrs") or {}
+ confidence = _text(attrs.get("confidence"))
+ condition = _text(attrs.get("condition"))
+ count = _whole(attrs.get("count"))
+ if confidence == RULED_OUT:
+ row["refuted"] += 1
+ return
+ row["statements"] += 1
+ row["confidence"][confidence] = row["confidence"].get(confidence, 0) + 1
+ bucket = row["_conditions"].setdefault(
+ condition, {"value": condition, "total": 0, "statements": 0, "counted": 0}
+ )
+ bucket["statements"] += 1
+ if count is not None:
+ row["total"] += count
+ row["counted"] += 1
+ bucket["total"] += count
+ bucket["counted"] += 1
+
+
+def _empty_row(entity_id: str) -> dict[str, Any]:
+ return {
+ "id": entity_id,
+ "label": "",
+ "type": "",
+ "statements": 0,
+ "counted": 0,
+ "total": 0,
+ "refuted": 0,
+ "confidence": {},
+ "_conditions": {},
+ }
+
+
+def _ordered(
+ rows: dict[str, dict[str, Any]], named: dict[str, dict[str, Any]]
+) -> list[dict[str, Any]]:
+ """The rows as they are read: the biggest number first, the label as the tie-break.
+
+ Sorted here rather than in the browser, like every other list the server bounds:
+ a cut reading sorted by the client would rank the slice rather than the answer.
+ """
+ built: list[dict[str, Any]] = []
+ for entity_id, row in rows.items():
+ entity = named.get(entity_id)
+ conditions = sorted(
+ row.pop("_conditions").values(),
+ key=lambda bucket: (_CONDITION_ORDER.get(bucket["value"], len(_CONDITION_ORDER)),
+ bucket["value"]),
+ )
+ confidence = sorted(
+ ({"value": value, "statements": held} for value, held in row["confidence"].items()),
+ key=lambda level: (_CONFIDENCE_ORDER.get(level["value"], len(_CONFIDENCE_ORDER)),
+ level["value"]),
+ )
+ built.append({
+ **row,
+ "label": (entity or {}).get("label", ""),
+ "type": (entity or {}).get("type", ""),
+ "conditions": conditions,
+ "confidence": confidence,
+ })
+ built.sort(key=lambda row: (-row["total"], -row["statements"], row["label"].casefold(), row["id"]))
+ return built
+
+
+def _text(value: Any) -> str:
+ """A stored choice as the reading groups on it, and "" for every absence.
+
+ One spelling for *unstated*, so a key written as null, as an empty string or not
+ written at all is one bucket rather than three.
+ """
+ return str(value).strip() if isinstance(value, str) else ""
+
+
+def _whole(value: Any) -> int | None:
+ """A stored ``count`` as a number, or nothing at all.
+
+ Anything that is not a whole number of at least one is read as *not counted*
+ rather than repaired: the field is validated on the way in, so a value that got
+ past that is not a number this reading may guess at.
+
+ Infinity and NaN are refused before anything is done with them. The validator
+ already rejects both (`entities._check_number`), so they only arrive from a case
+ written elsewhere — an import, a hand-edited database — and there the reading has
+ to answer *not counted* rather than fail on the whole case.
+ """
+ if isinstance(value, bool) or not isinstance(value, (int, float, str)):
+ return None
+ try:
+ number = float(str(value).strip())
+ except (TypeError, ValueError):
+ return None
+ if not math.isfinite(number) or number != int(number):
+ return None
+ return int(number) if number >= 1 else None
+
+
+def _status(value: str | None) -> Any:
+ return value if value in ("confirmed", "suggested") else None
diff --git a/src/azimut/engine/temporal.py b/src/azimut/engine/temporal.py
new file mode 100644
index 0000000..b481c68
--- /dev/null
+++ b/src/azimut/engine/temporal.py
@@ -0,0 +1,286 @@
+"""Parse the small, explicit temporal profile Azimut stores on Claims.
+
+Reduced dates, date intervals and their final qualifiers follow EDTF's familiar
+surface. Exact timestamps follow ISO 8601. This module deliberately implements
+neither full EDTF nor timestamp intervals: every accepted value must yield honest,
+exclusive search bounds, or be marked as a local value that cannot join a UTC axis.
+"""
+
+from __future__ import annotations
+
+from dataclasses import dataclass
+from datetime import UTC, datetime, timedelta, timezone
+import re
+
+
+class TemporalError(ValueError):
+ """A temporal value is outside Azimut's announced profile."""
+
+
+@dataclass(frozen=True)
+class TemporalEndpoint:
+ """One date or timestamp and the bounds that can honestly be derived from it."""
+
+ raw: str
+ earliest: str | None
+ latest: str | None
+ precision: str
+ uncertain: bool
+ approximate: bool
+ zone: str
+ sortable: bool
+
+
+@dataclass(frozen=True)
+class TemporalValue:
+ """One temporal expression, retaining both ends when it is an interval."""
+
+ raw: str
+ start: TemporalEndpoint
+ end: TemporalEndpoint | None = None
+
+ @property
+ def shape(self) -> str:
+ return "interval" if self.end is not None else "instant"
+
+ @property
+ def earliest(self) -> str | None:
+ return self.start.earliest
+
+ @property
+ def latest(self) -> str | None:
+ if self.end is None:
+ return self.start.latest
+ # A reduced end date includes the whole stated civil period. A timestamp
+ # is already the exact, exclusive end of a period.
+ return self.end.latest if self.end.zone == "date-only" else self.end.earliest
+
+ @property
+ def precision(self) -> str:
+ if self.end is None or self.start.precision == self.end.precision:
+ return self.start.precision
+ return "mixed"
+
+ @property
+ def uncertain(self) -> bool:
+ return self.start.uncertain or bool(self.end and self.end.uncertain)
+
+ @property
+ def approximate(self) -> bool:
+ return self.start.approximate or bool(self.end and self.end.approximate)
+
+ @property
+ def zone(self) -> str:
+ if self.end is None or self.start.zone == self.end.zone:
+ return self.start.zone
+ return "mixed"
+
+ @property
+ def sortable(self) -> bool:
+ return self.start.sortable and bool(self.end is None or self.end.sortable)
+
+
+_DATE = re.compile(
+ r"(?P<year>\d{4})"
+ r"(?:-(?P<month>\d{2})(?:-(?P<day>\d{2}))?)?"
+ r"(?P<qualifier>[~?%])?\Z"
+)
+_TIMESTAMP = re.compile(
+ r"(?P<year>\d{4})-(?P<month>\d{2})-(?P<day>\d{2})"
+ r"T(?P<hour>\d{2}):(?P<minute>\d{2}):(?P<second>\d{2})"
+ r"(?:\.(?P<fraction>\d{1,6}))?"
+ r"(?P<zone>Z|(?P<sign>[+-])(?P<offset_hour>\d{2}):(?P<offset_minute>\d{2}))?\Z"
+)
+
+
+def parse_temporal(raw: object) -> TemporalValue:
+ """Parse one supported temporal value without rewriting what the analyst typed.
+
+ Bounds are half-open: ``earliest`` is inclusive and ``latest`` is exclusive.
+ A reduced month therefore ends at the start of the next month, and a timestamp
+ written to seconds ends one second later. Local timestamps remain valid but have
+ no UTC bounds until a timezone is known.
+ """
+ if not isinstance(raw, str):
+ raise TemporalError("a temporal value must be text")
+ if not raw or raw != raw.strip():
+ raise TemporalError("a temporal value cannot be empty or padded with spaces")
+
+ if "/" not in raw:
+ return TemporalValue(raw=raw, start=_parse_endpoint(raw))
+
+ if raw.count("/") != 1:
+ raise TemporalError("an interval must contain exactly two dates")
+ start_raw, end_raw = raw.split("/", 1)
+ if not start_raw or not end_raw or start_raw == ".." or end_raw == "..":
+ raise TemporalError("open intervals are not supported")
+
+ dates = bool(_DATE.fullmatch(start_raw) and _DATE.fullmatch(end_raw))
+ timestamps = bool(_TIMESTAMP.fullmatch(start_raw) and _TIMESTAMP.fullmatch(end_raw))
+ if not dates and not timestamps:
+ raise TemporalError("an interval needs two dates or two timestamps")
+ start = _parse_date(start_raw) if dates else _parse_timestamp(start_raw)
+ end = _parse_date(end_raw) if dates else _parse_timestamp(end_raw)
+ if start.earliest is None or end.earliest is None:
+ raise TemporalError("a timestamp interval needs a timezone on both bounds")
+ upper = end.latest if dates else end.earliest
+ if upper is None or start.earliest >= upper:
+ raise TemporalError("an interval cannot end before it starts")
+ return TemporalValue(raw=raw, start=start, end=end)
+
+
+def window_bound(raw: str, *, upper: bool) -> str:
+ """One end of a search window, read from a value the analyst may have typed short.
+
+ A reduced date names a whole civil period, so a window ending `2024-03` ends at the
+ start of April rather than of March. A timestamp already names an exact instant and
+ is taken as written, which is what lets the axis navigate at second scales without
+ a second being added to every window.
+
+ Every boundary in the app is read here — the live question, the saved view, the
+ capture it freezes — so a snapshot and the reading it was taken from cannot answer
+ the same window differently.
+ """
+ value = parse_temporal(raw)
+ bound = value.latest if upper and value.start.zone == "date-only" else value.earliest
+ if bound is None:
+ raise TemporalError("a window boundary needs a date or a timezone")
+ return bound
+
+
+def _parse_endpoint(raw: str) -> TemporalEndpoint:
+ if _DATE.fullmatch(raw):
+ return _parse_date(raw)
+ if _TIMESTAMP.fullmatch(raw):
+ return _parse_timestamp(raw)
+ raise TemporalError("the temporal value is outside the supported date and timestamp profile")
+
+
+def _parse_date(raw: str) -> TemporalEndpoint:
+ match = _DATE.fullmatch(raw)
+ if match is None:
+ raise TemporalError("date intervals accept dates, not timestamps or open bounds")
+
+ year = int(match.group("year"))
+ month_text = match.group("month")
+ day_text = match.group("day")
+ qualifier = match.group("qualifier")
+
+ try:
+ if day_text is not None:
+ month = int(month_text or 0)
+ day = int(day_text)
+ earliest = datetime(year, month, day, tzinfo=UTC)
+ latest = earliest + timedelta(days=1)
+ precision = "day"
+ elif month_text is not None:
+ month = int(month_text)
+ earliest = datetime(year, month, 1, tzinfo=UTC)
+ if month == 12:
+ latest = datetime(year + 1, 1, 1, tzinfo=UTC)
+ else:
+ latest = datetime(year, month + 1, 1, tzinfo=UTC)
+ precision = "month"
+ else:
+ earliest = datetime(year, 1, 1, tzinfo=UTC)
+ latest = datetime(year + 1, 1, 1, tzinfo=UTC)
+ precision = "year"
+ except (OverflowError, ValueError) as exc:
+ raise TemporalError("the date is not a valid Gregorian date with representable bounds") from exc
+
+ return TemporalEndpoint(
+ raw=raw,
+ earliest=_format_utc(earliest),
+ latest=_format_utc(latest),
+ precision=precision,
+ uncertain=qualifier in ("?", "%"),
+ approximate=qualifier in ("~", "%"),
+ zone="date-only",
+ sortable=True,
+ )
+
+
+def _parse_timestamp(raw: str) -> TemporalEndpoint:
+ match = _TIMESTAMP.fullmatch(raw)
+ if match is None: # guarded by `_parse_endpoint`, useful for direct maintenance
+ raise TemporalError("the timestamp is outside the supported ISO profile")
+
+ fraction = match.group("fraction") or ""
+ microsecond = int(fraction.ljust(6, "0")) if fraction else 0
+ zone_text = match.group("zone")
+
+ tz = None
+ zone = "local"
+ if zone_text == "Z":
+ tz = UTC
+ zone = "utc"
+ elif zone_text:
+ offset_hour = int(match.group("offset_hour") or 0)
+ offset_minute = int(match.group("offset_minute") or 0)
+ if offset_minute > 59 or offset_hour > 14 or (offset_hour == 14 and offset_minute):
+ raise TemporalError("a timezone offset must be between -14:00 and +14:00")
+ offset = timedelta(hours=offset_hour, minutes=offset_minute)
+ if match.group("sign") == "-":
+ offset = -offset
+ tz = timezone(offset)
+ zone = "offset"
+
+ try:
+ instant = datetime(
+ int(match.group("year")),
+ int(match.group("month")),
+ int(match.group("day")),
+ int(match.group("hour")),
+ int(match.group("minute")),
+ int(match.group("second")),
+ microsecond,
+ tzinfo=tz,
+ )
+ except ValueError as exc:
+ raise TemporalError("the timestamp is not a valid Gregorian date and time") from exc
+
+ if tz is None:
+ return TemporalEndpoint(
+ raw=raw,
+ earliest=None,
+ latest=None,
+ precision="subsecond" if fraction else "second",
+ uncertain=False,
+ approximate=False,
+ zone=zone,
+ sortable=False,
+ )
+
+ resolution = timedelta(
+ microseconds=10 ** (6 - len(fraction)) if fraction else 1_000_000
+ )
+ try:
+ earliest = instant.astimezone(UTC)
+ latest = earliest + resolution
+ except OverflowError as exc:
+ raise TemporalError("the timestamp has no representable exclusive upper bound") from exc
+ return TemporalEndpoint(
+ raw=raw,
+ earliest=_format_utc(earliest),
+ latest=_format_utc(latest),
+ precision="subsecond" if fraction else "second",
+ uncertain=False,
+ approximate=False,
+ zone=zone,
+ sortable=True,
+ )
+
+
+def _format_utc(value: datetime) -> str:
+ """Format every sortable bound to the same lexicographic width.
+
+ SQLite compares these values as text. Keeping ``.000000`` on whole seconds
+ is therefore as important as padding a sub-second value: without it,
+ ``...14.500000Z`` sorts before ``...14Z`` because ``.`` sorts before ``Z``.
+ """
+ value = value.astimezone(UTC)
+ base = (
+ f"{value.year:04d}-{value.month:02d}-{value.day:02d}"
+ f"T{value.hour:02d}:{value.minute:02d}:{value.second:02d}"
+ )
+ return f"{base}.{value.microsecond:06d}Z"
diff --git a/src/azimut/engine/timeline.py b/src/azimut/engine/timeline.py
new file mode 100644
index 0000000..dfb7faa
--- /dev/null
+++ b/src/azimut/engine/timeline.py
@@ -0,0 +1,191 @@
+"""Build the derived temporal rows served by Time and Timeline.
+
+Claims, media sidecars and entity provenance remain authoritative. The rows
+produced here are a search projection: they may be deleted and rebuilt without
+losing an analyst statement or changing file metadata.
+"""
+
+from __future__ import annotations
+
+from dataclasses import asdict, dataclass
+import re
+from typing import Any
+
+from .temporal import TemporalError, parse_temporal
+
+
+STATEMENT = "statement"
+MEDIA = "media"
+CASE_ACTIVITY = "case_activity"
+DEFAULT_CATEGORIES = (STATEMENT, MEDIA)
+ALL_CATEGORIES = (STATEMENT, MEDIA, CASE_ACTIVITY)
+
+
+@dataclass(frozen=True)
+class ProjectionRow:
+ """One homogeneous line, before it is written to the SQLite projection."""
+
+ id: str
+ owner_id: str
+ authority: str
+ category: str
+ kind: str
+ raw: str | None
+ earliest: str | None
+ latest: str | None
+ precision: str | None
+ shape: str | None
+ time_role: str | None
+ uncertain: bool
+ approximate: bool
+ zone: str | None
+ sortable: bool
+ status: str | None
+ confidence: str | None
+ parse_error: str | None
+
+ def record(self) -> dict[str, Any]:
+ return asdict(self)
+
+
+def _project_value(
+ *,
+ id: str,
+ owner_id: str,
+ authority: str,
+ category: str,
+ kind: str,
+ raw: object,
+ time_role: str | None = None,
+ status: str | None = None,
+ confidence: str | None = None,
+) -> ProjectionRow:
+ text = raw if isinstance(raw, str) and raw else None
+ if text is None:
+ return ProjectionRow(
+ id, owner_id, authority, category, kind, None, None, None, None,
+ None, time_role, False, False, None, False, status, confidence, None,
+ )
+ try:
+ value = parse_temporal(text)
+ except TemporalError as exc:
+ # Old cases may contain a field that predates the declared Claim contract.
+ # Keep it visible as unplaced and explain why it cannot be placed; a derived
+ # index must never make opening the case depend on repairing user data.
+ return ProjectionRow(
+ id, owner_id, authority, category, kind, text, None, None, None,
+ None, time_role, False, False, None, False, status, confidence, str(exc),
+ )
+ return ProjectionRow(
+ id=id,
+ owner_id=owner_id,
+ authority=authority,
+ category=category,
+ kind=kind,
+ raw=value.raw,
+ earliest=value.earliest,
+ latest=value.latest,
+ precision=value.precision,
+ shape=value.shape,
+ time_role=time_role,
+ uncertain=value.uncertain,
+ approximate=value.approximate,
+ zone=value.zone,
+ sortable=value.sortable,
+ status=status,
+ confidence=confidence,
+ parse_error=None,
+ )
+
+
+def project_entity(entity: dict[str, Any]) -> list[ProjectionRow]:
+ """Project one graph entity without reading any other case state."""
+ entity_id = str(entity["id"])
+ type_ = str(entity.get("type") or "")
+ raw_attrs = entity.get("attrs")
+ attrs: dict[str, Any] = raw_attrs if isinstance(raw_attrs, dict) else {}
+ raw_provenance = entity.get("provenance")
+ provenance: dict[str, Any] = (
+ raw_provenance if isinstance(raw_provenance, dict) else {}
+ )
+
+ if type_ == "claim":
+ role = attrs.get("time_role")
+ confidence = attrs.get("confidence")
+ return [
+ _project_value(
+ id=f"temporal:claim:{entity_id}",
+ owner_id=entity_id,
+ authority="entity",
+ category=STATEMENT,
+ kind="claim",
+ raw=attrs.get("when"),
+ time_role=role if isinstance(role, str) else None,
+ status=(
+ provenance.get("status")
+ if isinstance(provenance.get("status"), str)
+ else None
+ ),
+ confidence=confidence if isinstance(confidence, str) else None,
+ )
+ ]
+
+ # Media activity is projected from its sidecar below. This avoids showing
+ # the graph filing timestamp beside the more specific "Added to case" value.
+ if type_ in {"media", "capture"}:
+ return []
+ return [
+ _project_value(
+ id=f"temporal:activity:{entity_id}:filed",
+ owner_id=entity_id,
+ authority="entity",
+ category=CASE_ACTIVITY,
+ kind="filed",
+ raw=provenance.get("at"),
+ )
+ ]
+
+
+_COMPACT_DATE = re.compile(r"(?P<year>\d{4})(?P<month>\d{2})(?P<day>\d{2})\Z")
+
+
+def _media_date(raw: object) -> object:
+ """Turn yt-dlp's compact publication date into the announced date profile."""
+ if not isinstance(raw, str):
+ return raw
+ match = _COMPACT_DATE.fullmatch(raw)
+ if match is None:
+ return raw
+ return f"{match.group('year')}-{match.group('month')}-{match.group('day')}"
+
+
+def project_media(item: dict[str, Any], entity_id: str | None) -> list[ProjectionRow]:
+ """Project intrinsic and collection dates from one indexed media sidecar."""
+ if not entity_id:
+ return []
+ raw_source = item.get("source")
+ source: dict[str, Any] = raw_source if isinstance(raw_source, dict) else {}
+ rows: list[ProjectionRow] = []
+
+ def add(category: str, kind: str, raw: object) -> None:
+ if raw in (None, ""):
+ return
+ rows.append(
+ _project_value(
+ id=f"temporal:media:{entity_id}:{kind}",
+ owner_id=entity_id,
+ authority="media",
+ category=category,
+ kind=kind,
+ raw=raw,
+ )
+ )
+
+ # A file-carried capture time wins over a browser context timestamp. They
+ # describe the same reading, and showing both would look like two events.
+ add(MEDIA, "captured", item.get("taken_at") or source.get("captured_at"))
+ add(MEDIA, "published", _media_date(source.get("upload_date")))
+ add(MEDIA, "imagery", source.get("imagery_date"))
+ add(CASE_ACTIVITY, "collected", source.get("fetched_at"))
+ add(CASE_ACTIVITY, "added", item.get("added_at"))
+ return rows
diff --git a/src/azimut/engine/trash.py b/src/azimut/engine/trash.py
index 1b1410d..0e09dda 100644
--- a/src/azimut/engine/trash.py
+++ b/src/azimut/engine/trash.py
@@ -33,6 +33,7 @@ from typing import Any
from .. import layout
from ..workspace import Case, CaseError, _new_id, ensure_dir
from . import artifacts as artifact_engine
+from . import entity_images as entity_image_engine
from . import links as link_engine
from . import thumbnails as thumbnail_engine
@@ -88,7 +89,7 @@ def collect_links(case: Case, entity_ids: set[str]) -> list[dict[str, Any]]:
"""Every link incident to the group, deduped — chain edges *and* relations.
Relations are the loss nothing else records: a derivation leaves a tombstone
- on the survivor, but "this photo was shot at this place" vanishes without a
+ on the survivor, but "this photo was recorded at this place" vanishes without a
trace. So the payload carries all of them, and a restore puts back whichever
still has both ends.
"""
@@ -128,11 +129,13 @@ def send(
root = _group_dir(case, group_id)
ids = {e["id"] for e in entities}
links = collect_links(case, ids)
+ entity_images = case.entity_images_touching(list(ids))
files = _travelling_files(case, entities)
target = entities[0]
payload = {
"entities": entities,
"links": links,
+ "entity_images": entity_images,
"files": files,
"slots": slots_for(files),
"tombstones": tombstones,
@@ -154,12 +157,41 @@ def send(
if source.exists():
_move(source, root / slot)
case.prune_note_dirs(rel)
+ entity_image_engine.prune_empty_dirs(case)
return case.update_trash_group(group_id, size_bytes=_dir_size(root))
except Exception:
_rollback_delete(case, group)
raise
+def send_analysis_view(case: Case, view: dict[str, Any]) -> dict[str, Any]:
+ """Journal the deletion of one saved reading.
+
+ A view owns no file and is not an entity, but it is still case state the analyst
+ named. Keeping it in the same Trash journal gives the deletion the same way back
+ without polluting the semantic graph with presentation records.
+ """
+ with case.lock:
+ group_id = _new_id("t")
+ return case.add_trash_group(
+ group_id,
+ label=str(view.get("name") or view.get("id") or "Analysis view"),
+ type_="analysis-view",
+ item_count=1,
+ size_bytes=0,
+ payload={
+ "entities": [],
+ "links": [],
+ "entity_images": [],
+ "analysis_views": [view],
+ "files": [],
+ "slots": [],
+ "tombstones": [],
+ },
+ state="preparing",
+ )
+
+
def commit(case: Case, group_id: str) -> dict[str, Any]:
"""Publish a fully completed delete in the user-visible trash."""
with case.lock:
@@ -184,8 +216,8 @@ def restore(case: Case, group_id: str) -> dict[str, Any]:
than renaming an artifact behind the analyst;
2. the entities come back with their original ids, since the delete freed
them and every recorded path still points at them;
- 3. the links come back where both ends survived; the rest are counted and
- reported, not hidden;
+ 3. image galleries and links come back where both ends survived; losses are
+ counted rather than hidden;
4. the tombstones this delete wrote on survivors are lifted;
5. restored media are filed in the browse index again and their thumbnails
re-queued, because a thumbnail was dropped rather than moved.
@@ -242,7 +274,14 @@ def recover(case: Case) -> None:
f"trash group '{group['id']}' has an unknown state '{state}'"
)
entities = list((group.get("payload") or {}).get("entities") or [])
- if any(case.get_entity(entity["id"]) is not None for entity in entities):
+ views = list((group.get("payload") or {}).get("analysis_views") or [])
+ if (
+ any(case.get_entity(entity["id"]) is not None for entity in entities)
+ or any(
+ case.get_analysis_view(str(view.get("id") or "")) is not None
+ for view in views
+ )
+ ):
_rollback_delete(case, group)
else:
case.update_trash_group(group["id"], state="ready")
@@ -264,6 +303,10 @@ def _restore_records(case: Case, group: dict[str, Any]) -> dict[str, int]:
payload = group.get("payload") or {}
entities: list[dict[str, Any]] = list(payload.get("entities") or [])
result = case.reinsert(entities, list(payload.get("links") or []))
+ result.update(case.reinsert_entity_images(list(payload.get("entity_images") or [])))
+ result["analysis_views"] = case.reinsert_analysis_views(
+ list(payload.get("analysis_views") or [])
+ )
for scar in payload.get("tombstones") or []:
link_engine.remove_tombstone(case, scar["entity"], scar["path"])
for entity in entities:
diff --git a/src/azimut/layout.py b/src/azimut/layout.py
index c55aadb..925387e 100644
--- a/src/azimut/layout.py
+++ b/src/azimut/layout.py
@@ -60,6 +60,10 @@ META_DIR = ".meta"
#: The case database. Hidden because it is the one file whose loss costs
#: everything, and the one someone deletes to reclaim space.
DATA_DIR = ".data"
+#: Presentation photos imported directly into an entity. They are deliberately
+#: outside ``media/``: adding a portrait or logo must not create evidence in the
+#: Media Library. The database records their paths and the entity owns them.
+ENTITY_IMAGES_DIR = "entity-images"
#: Content directories, in birth order. The trash is deliberately not one of
#: them — see `TRASH_DIR`.
@@ -295,6 +299,24 @@ def database(root: Path) -> Path:
return data_dir(root) / "case.db"
+def entity_images(root: Path) -> Path:
+ """Private presentation photos imported directly into entity details."""
+ return data_dir(root) / ENTITY_IMAGES_DIR
+
+
+def entity_image_thumbs(root: Path) -> Path:
+ """Bounded previews for direct entity photos."""
+ return entity_images(root) / ".thumbs"
+
+
+def entity_image_rel(image_id: str) -> str:
+ return f"{DATA_DIR}/{ENTITY_IMAGES_DIR}/{image_id}.jpg"
+
+
+def entity_image_thumb_rel(image_id: str) -> str:
+ return f"{DATA_DIR}/{ENTITY_IMAGES_DIR}/.thumbs/{image_id}.jpg"
+
+
def notes_file(root: Path) -> Path:
"""The case's free-form scratchpad."""
return tool_root(root) / "notes.md"
diff --git a/src/azimut/repository.py b/src/azimut/repository.py
index bddfca8..c9ed2a8 100644
--- a/src/azimut/repository.py
+++ b/src/azimut/repository.py
@@ -59,27 +59,67 @@ class CaseRepository(Protocol):
folder: str | None = None,
unfiled: bool = False,
recursive: bool = False,
+ attr: str | None = None,
+ attr_value: str | None = None,
+ linked: str | None = None,
+ unlinked: bool = False,
+ since: str | None = None,
+ until: str | None = None,
+ filed_by: list[str] | None = None,
+ temporal_since: str | None = None,
+ temporal_until: str | None = None,
+ temporal_categories: list[str] | None = None,
+ order: str = "",
) -> dict[str, Any]:
"""A bounded, filtered slice of the catalog (Step 5, "Bounded loading").
- Returns ``{"items": [...], "next_cursor": str | None}`` in a stable
- insertion order. ``cursor`` is an opaque token from a previous page;
+ Returns ``{"items": [...], "next_cursor": str | None, "total": int}`` in a
+ stable order. ``cursor`` is an opaque token from a previous page;
``next_cursor`` is None on the last page. Filters (``types`` set,
- ``status``, a label/type/folder/notes ``query``, and folder —
+ ``status``, a label/type/folder/notes ``query``, folder —
``unfiled`` or an exact ``folder`` path, optionally including
- descendants) run in the backend so
- the caller never materialises the whole graph. The cursor keys on
- insertion order so a concurrent append never shifts a page already
- returned.
+ descendants — one stored field holding one value (``attr``/``attr_value``),
+ having a neighbour of a type (``linked``) or none at all (``unlinked``), and
+ when and by what the row was filed (``since``/``until``/``filed_by``)) run in
+ the backend so the caller never materialises the whole graph.
+
+ ``order`` sorts the whole filtered set — an empty one is the insertion order
+ the cursor has always paged. Whichever is asked for, the cursor keys on the
+ sort plus the row's own seat, so a concurrent append or delete never shifts a
+ page already returned.
+
+ ``total`` counts the whole filtered set, so the narrowing terms answer a
+ question rather than only shortening a list: *how many videos have
+ coordinates* is that number, and the page is which ones.
"""
...
def catalog_summary(self) -> dict[str, Any]:
- """Total plus per-type, per-status and per-folder counts, in the backend.
+ """Total plus per-type, per-status, per-folder and per-filer counts.
- Feeds the catalog's badges without shipping entities to the caller —
- ``{"total": int, "by_type": {type: n}, "by_status": {status: n},
- "by_folder": {path: n}}``.
+ Feeds the catalog's badges and its filter menus without shipping entities to
+ the caller — ``{"total": int, "by_type": {type: n}, "by_status": {status: n},
+ "by_folder": {path: n}, "by_source": {who: n}, "linked_to": {type: n},
+ "unlinked": int}``.
+
+ ``linked_to`` counts entities that **have a neighbour** of each type, which is
+ not how many of that type the case holds: it is what the "linked to" filter
+ asks, and pricing that menu with the other number is a count that looks like an
+ answer and is not one.
+ """
+ ...
+
+ def attr_facets(
+ self, *, types: list[str] | None = None, limit: int = 50
+ ) -> list[dict[str, Any]]:
+ """Which stored fields these entities hold, and which values, as a menu.
+
+ ``[{"key": str, "entities": n, "values": [{"value": str, "count": n}],
+ "truncated": bool}]``, most carried field first. This is what lets a field be
+ filtered on without a query language: both selects are populated from the case,
+ so every term is chosen rather than typed. Bounded — a field with more than
+ ``limit`` distinct values returns none of them and says it was cut, because a
+ menu of five thousand paths is not a way to choose.
"""
...
@@ -120,6 +160,168 @@ class CaseRepository(Protocol):
"""
...
+ # -- graph reads -------------------------------------------------------
+ #
+ # Drawing a case asks a different question from listing it: not "the next
+ # page" but "which nodes matter, and what joins them". These four answer it
+ # without ever reaching the whole graph — three take a bounded id set, the
+ # fourth an explicit limit.
+
+ def rank_entities(
+ self,
+ *,
+ limit: int = 200,
+ types: list[str] | None = None,
+ exclude_types: list[str] | None = None,
+ status: EntityStatus | None = None,
+ query: str | None = None,
+ folder: str | None = None,
+ unfiled: bool = False,
+ recursive: bool = False,
+ attr: str | None = None,
+ attr_value: str | None = None,
+ linked: str | None = None,
+ unlinked_only: bool = False,
+ since: str | None = None,
+ until: str | None = None,
+ filed_by: list[str] | None = None,
+ temporal_since: str | None = None,
+ temporal_until: str | None = None,
+ temporal_categories: list[str] | None = None,
+ link_types: list[str] | None = None,
+ order: str = "degree",
+ ) -> dict[str, Any]:
+ """``{entities, degrees, total, truncated, unlinked}`` — the most
+ significant entities first, bounded by ``limit``.
+
+ The narrowing terms are the catalog's own, so a filter set in the board and
+ the same filter drawn as a graph cannot mean two things.
+
+ ``order`` decides which nodes survive a case too large to draw whole:
+ ``degree`` keeps the hubs so the shape of the case stays legible,
+ ``recent`` keeps the latest work. ``link_types`` scopes the degree to one
+ lens, so a node isolated *in that lens* reads as isolated.
+
+ ``exclude_types`` is what that lens does not draw at all: those entities leave
+ the ranking, and the edges reaching them leave every degree counted here.
+
+ ``total`` and ``unlinked`` both count every entity matching the filters,
+ returned or not: a degree-0 entity is the first thing a cut discards, so
+ counting it off the page would report none of it on a large case.
+ """
+ ...
+
+ def entities_by_ids(self, ids: list[str]) -> list[dict[str, Any]]:
+ """A known set of entities in one read. Ids that no longer exist are
+ skipped rather than raising: an expansion races deletion elsewhere."""
+ ...
+
+ def labels_of_type(self, type_: str) -> list[tuple[str, str]]:
+ """Every entity of one type as ``(id, label)``, for comparing identities.
+
+ Labels only, off the type index: the caller is asking whether the case
+ already holds one identifier's value (``entities.identity_key``), and that
+ normalization is vocabulary, so it cannot be pushed into SQL without the
+ rules living in two places.
+ """
+ ...
+
+ def links_among(
+ self, ids: list[str], *, types: list[str] | None = None
+ ) -> list[dict[str, Any]]:
+ """Edges with both ends inside the set — the closed set a view can draw
+ without inventing the node at the far end."""
+ ...
+
+ def links_touching(
+ self,
+ ids: list[str],
+ *,
+ types: list[str] | None = None,
+ exclude_types: list[str] | None = None,
+ end_types: list[str] | None = None,
+ ) -> list[dict[str, Any]]:
+ """Edges with either end inside the set — one hop of an expansion.
+
+ ``exclude_types`` drops an edge whose far end this reading does not draw, so a
+ walk never steps onto one. ``end_types`` is the opposite question and the
+ collapse's probe: only the edges that *do* reach one of those types.
+ """
+ ...
+
+ def degrees_of(
+ self,
+ ids: list[str],
+ *,
+ types: list[str] | None = None,
+ exclude_types: list[str] | None = None,
+ ) -> dict[str, int]:
+ """``{entity_id: n}`` for exactly these ids, over one lens's verbs.
+
+ Every id asked for is present, zero included: this answers "how much
+ would expanding this bring in?", where absence would read as unknown
+ rather than as none — which is why ``exclude_types`` applies here too: a
+ connection to a node the lens leaves out is not one a click can bring in.
+ """
+ ...
+
+ # -- the graph's own arrangement ----------------------------------------
+ #
+ # Where a node was dragged to. Presentation rather than a statement about the
+ # case, which is why it is a table of its own and not a key in ``attrs``: an
+ # entity keeps identity, links and provenance (ONTOLOGY §1), a drag rewrites
+ # no entity row, and letting the layout take over again is one delete.
+ #
+ # Every one of these is scoped to a lens, because that is what an arrangement
+ # belongs to: a lens draws its own nodes and edges and clusters differently, so
+ # one shared arrangement would anchor every reading into the shape of whichever
+ # one it was built in.
+
+ def graph_pins(self, lens: str) -> dict[str, tuple[float, float]]:
+ """``{entity_id: (x, y)}`` for the nodes placed by hand in this lens.
+
+ Unbounded on purpose: a pin exists because somebody dragged something, so
+ the count follows the hand, not the size of the case.
+ """
+ ...
+
+ def pin_entities(self, lens: str, pins: dict[str, tuple[float, float]]) -> int:
+ """Fix these nodes at these canvas coordinates in this lens; returns how
+ many landed.
+
+ One transaction for the batch — a group drag is one act. An id that no
+ longer exists is skipped, since a drag can race a delete elsewhere.
+ """
+ ...
+
+ def unpin_entities(self, lens: str, ids: list[str]) -> int:
+ """Hand these nodes back to the computed layout in this lens; returns how
+ many were pinned in it."""
+ ...
+
+ def clear_graph_pins(self, lens: str) -> int:
+ """Drop this lens's arrangement; returns how many pins it held."""
+ ...
+
+ # -- saved analysis views --------------------------------------------
+
+ def list_analysis_views(self) -> list[dict[str, Any]]:
+ """Named Board and Graph readings, newest edit first."""
+ ...
+
+ def get_analysis_view(self, view_id: str) -> dict[str, Any] | None:
+ ...
+
+ def save_analysis_view(self, view: dict[str, Any]) -> dict[str, Any]:
+ ...
+
+ def remove_analysis_view(self, view_id: str) -> dict[str, Any] | None:
+ ...
+
+ def reinsert_analysis_views(self, views: list[dict[str, Any]]) -> int:
+ """Restore recipes removed by one recoverable delete action."""
+ ...
+
def get_entity(self, entity_id: str) -> dict[str, Any] | None:
...
@@ -129,6 +331,49 @@ class CaseRepository(Protocol):
def list_folders(self) -> list[str]:
...
+ # -- entity image galleries ------------------------------------------
+
+ def entity_images(self, entity_id: str) -> list[dict[str, Any]]:
+ """The entity's private photos and Media references in display order."""
+ ...
+
+ def entity_image_thumbs(self, entity_ids: list[str]) -> dict[str, str]:
+ """``{entity_id: thumbnail}`` for primary images with a cached thumb."""
+ ...
+
+ def entity_images_touching(self, entity_ids: list[str]) -> list[dict[str, Any]]:
+ """Gallery rows whose entity or optional media end is in ``entity_ids``.
+
+ Used by Trash to restore presentation state together with either end.
+ """
+ ...
+
+ def add_entity_images(self, entity_id: str, media_ids: list[str]) -> int:
+ """Attach new media in order; the first image becomes primary when needed."""
+ ...
+
+ def add_entity_image_file(
+ self,
+ entity_id: str,
+ image_id: str,
+ path: str,
+ thumbnail: str,
+ title: str,
+ ) -> None:
+ """Register one private presentation photo already written to disk."""
+ ...
+
+ def set_primary_entity_image(self, entity_id: str, image_id: str) -> None:
+ ...
+
+ def remove_entity_image(self, entity_id: str, image_id: str) -> dict[str, Any]:
+ """Detach one image, return its record and promote the next if needed."""
+ ...
+
+ def reinsert_entity_images(self, rows: list[dict[str, Any]]) -> dict[str, int]:
+ """Restore rows whose target and optional Media endpoint still exist."""
+ ...
+
# -- media browse index ------------------------------------------------
def upsert_media_item(self, item: dict[str, Any], *, entity_id: str | None = None) -> None:
@@ -144,6 +389,36 @@ class CaseRepository(Protocol):
def media_items_by_paths(self, paths: list[str]) -> list[dict[str, Any]]:
...
+ def media_thumbs(self, entity_ids: list[str]) -> dict[str, str]:
+ """The cached thumbnail of each of these entities that has one.
+
+ Keyed by entity rather than by path because the callers that draw an
+ entity — the graph among them — hold ids, and an entity with no indexed
+ media is simply absent rather than mapped to nothing.
+ """
+ ...
+
+ def media_kinds(self, entity_ids: list[str]) -> dict[str, str]:
+ """``{entity_id: kind}`` — image, video, audio or file — for the entities
+ the media index knows.
+
+ Keyed by entity like the thumbnails, because the surfaces that draw one hold
+ ids. An entity the index has never seen is absent rather than guessed at.
+ """
+ ...
+
+ def media_origins(self, entity_ids: list[str]) -> dict[str, dict[str, str]]:
+ """``{entity_id: {"type": …, "op": …}}`` — how the bytes behind each of these
+ entities came into the case.
+
+ ``type`` is the route (``upload``, ``download``, ``inspect``, ``satellite``…)
+ and ``op`` the act that produced it where the producer recorded one (a frame,
+ a collage). Keyed by entity like the kinds and the thumbnails, because the
+ surfaces that draw one hold ids. An entity the index has never seen, or one
+ whose row records no route, is absent rather than guessed at.
+ """
+ ...
+
def page_media_items(
self,
*,
@@ -152,6 +427,7 @@ class CaseRepository(Protocol):
category: str | None = None,
folder: str | None = None,
gps: bool = False,
+ collected_only: bool = False,
sort: str = "newest",
direction: str | None = None,
limit: int = 200,
@@ -160,9 +436,42 @@ class CaseRepository(Protocol):
"""Filter, sort and page media without scanning sidecar files.
``gps`` keeps only the items whose own metadata states a position.
+ ``collected_only`` drops what the case made out of its own material
+ (``links.MADE_HERE``) and scopes the facet counts with it, so no chooser
+ offers rows the switch is hiding. ``facets.made_here_count`` says how many
+ that is, on either setting.
+ """
+ ...
+
+ def timeline_page(
+ self,
+ *,
+ since: str | None = None,
+ until: str | None = None,
+ categories: list[str] | None = None,
+ entity_id: str | None = None,
+ include_undated: bool = True,
+ limit: int = 100,
+ cursor: str | None = None,
+ bucket: str | None = None,
+ track: dict[str, Any] | None = None,
+ spread: bool = False,
+ ) -> dict[str, Any]:
+ """One bounded temporal page plus optional density buckets.
+
+ ``spread`` samples the page across the whole window instead of taking its
+ front, for a reader that draws the page on an axis.
"""
...
+ def rebuild_temporal_projection(self) -> int:
+ """Recreate the derived temporal index from graph and media authorities."""
+ ...
+
+ def temporal_projection_status(self) -> dict[str, int | bool]:
+ """Compare the derived temporal index with its graph and media authorities."""
+ ...
+
# -- entity mutations --------------------------------------------------
def add_entity(
@@ -180,6 +489,19 @@ class CaseRepository(Protocol):
def update_entity(self, entity_id: str, patch: dict[str, Any]) -> dict[str, Any]:
...
+ def save_temporal_claim(
+ self,
+ *,
+ entity_id: str | None,
+ label: str,
+ attrs: dict[str, Any],
+ connectors: dict[str, list[str]] | None,
+ by: str,
+ status: EntityStatus = "confirmed",
+ ) -> dict[str, Any]:
+ """Create or replace a Claim and selected connectors atomically."""
+ ...
+
def remove_entity(self, entity_id: str) -> None:
...
diff --git a/src/azimut/server.py b/src/azimut/server.py
index 2849a0a..1e05206 100644
--- a/src/azimut/server.py
+++ b/src/azimut/server.py
@@ -232,12 +232,13 @@ def create_app() -> FastAPI:
)
from .api import (
- cases, drafts, events, files, folders, ingest, inspect, media, notes, proofs,
- satellite, settings, templates,
+ analysis_views, cases, drafts, events, files, folders, ingest, inspect, media,
+ notes, proofs, satellite, settings, templates,
)
app.include_router(cases.router)
app.include_router(cases.workspace_router)
+ app.include_router(analysis_views.router)
app.include_router(notes.router)
app.include_router(media.router)
app.include_router(inspect.router)
diff --git a/src/azimut/sqlite_backend.py b/src/azimut/sqlite_backend.py
index 3f427b6..180914f 100644
--- a/src/azimut/sqlite_backend.py
+++ b/src/azimut/sqlite_backend.py
@@ -8,20 +8,28 @@ small case manifest only identifies the case and selects this backend.
Frozen-binary constraints (see the doc): SQLite is the stdlib `sqlite3` module,
already bundled by PyInstaller, so this adds no runtime dependency. Anything
beyond core SQL (FTS5, JSON1, RTree) is per-binary and must be probed at runtime
-with a fallback before it enters the contract — this module stays on core SQL:
-`find_entity` scans and matches attrs in Python rather than relying on JSON1.
+with a fallback before it enters the contract. Two attribute reads live on that
+line: `find_entity` and `attr_facets` scan and match in Python, and the field
+filter asks JSON1 through `_has_json1()` with a `LIKE` spelling of the same
+question behind it.
"""
from __future__ import annotations
import json
+import re
import sqlite3
+from base64 import urlsafe_b64decode, urlsafe_b64encode
from contextlib import closing, contextmanager
from dataclasses import dataclass, field
+from functools import lru_cache
from pathlib import Path
from typing import TYPE_CHECKING, Any, Callable, Iterator, TypeVar
+from .engine import entities as entity_engine
+from .engine import links as link_engine
from .engine import mapsites
+from .engine import timeline as timeline_engine
from . import layout
from .repository import EntityStatus
from .workspace import Case, CaseError, _new_id, _now, _parse_cursor, _replace_with_retry
@@ -49,7 +57,35 @@ if TYPE_CHECKING:
# Schema 6 adds the `trash` journal: one row per delete action, holding the
# recipe to put it back. Schema 7 adds its recovery state so interrupted
# filesystem moves can be completed or rolled back on the next case open.
-SQLITE_SCHEMA = 7
+# Schema 8 adds relation confidence. Schema 9 rebuilds `search_text` so a case
+# search reaches the declared fields — a plate, an IMO, a claim's wording —
+# instead of stopping at label and notes.
+# Schema 10 adds `graph_pins`: where the analyst put a node on the graph canvas
+# by hand. Its own table rather than a key in `attrs` because a canvas coordinate
+# is not a fact about the entity (ONTOLOGY §1 keeps entities to identity, links
+# and provenance), because dragging thirty nodes would otherwise rewrite thirty
+# entity rows and their search text, and because dropping every pin at once is
+# then one statement. Those pins are keyed by lens as well as by entity: a lens is
+# a reading, it draws its own nodes and edges and so clusters differently, and one
+# shared arrangement would anchor every reading into the shape of whichever one it
+# was built in.
+# Schema 11 adds `links.nature`: what kind of tie one edge states, in the analyst's
+# own words. Only a verb declaring a `qualifier` may carry one (`engine/links.py`),
+# which is what keeps the column from becoming a note any edge can hold — the same
+# guard `confidence` gets from `ratable`.
+# Schema 12 adds `entity_images`: ordered private photos or existing Media
+# references attached to a hand-made entity, with at most one primary image.
+# They are not semantic graph links, and a computer import creates no Media row.
+# Schema 13 adds `analysis_views`: named, case-owned recipes for reopening a Board
+# or Graph reading. A snapshot keeps its captured entities and links inside the
+# recipe; a live view keeps only the question and presentation state. Its denormalised
+# count lets a bounded menu say how large a capture is without parsing its JSON.
+# Schema 14 indexes catalog ordering. Schema 15 adds the rebuildable temporal
+# projection used by Time and Timeline; Claims and media sidecars remain authoritative.
+# Schema 16 lets the existing Analysis View store own Timeline recipes and snapshots.
+# Schema 17 rebuilds the derived temporal projection with fixed-width UTC bounds, so
+# SQLite text ordering remains chronological at sub-second precision.
+SQLITE_SCHEMA = 17
_SCHEMA = """
CREATE TABLE meta (
@@ -80,7 +116,14 @@ CREATE TABLE links (
prov_by TEXT NOT NULL,
prov_at TEXT NOT NULL,
prov_status TEXT NOT NULL DEFAULT 'confirmed',
- prov_source TEXT
+ prov_source TEXT,
+ -- Optional confidence for ordinary semantic relations. Claim connectors,
+ -- mentions and artifact lineage never use it.
+ confidence INTEGER,
+ -- What kind of tie this edge states, where the verb alone cannot say it:
+ -- "sister", "employer". Only a verb declaring a `qualifier` may carry one, so
+ -- this is not a note every edge can hold.
+ nature TEXT
);
CREATE TABLE folders (
path TEXT PRIMARY KEY
@@ -107,6 +150,56 @@ CREATE TABLE trash (
state TEXT NOT NULL DEFAULT 'ready',
payload_json TEXT NOT NULL DEFAULT '{}'
);
+-- Where the analyst dragged a node on the graph canvas. Presentation, not an
+-- assertion about the case: the graph reads it as a fixed anchor and places
+-- everything else around it. Cascades with the entity, so a deleted node leaves
+-- no pin behind to resurrect at an id that has been taken again.
+--
+-- Keyed by lens as well as by entity, because a lens is a reading: it draws its
+-- own nodes and its own edges, so it clusters differently. One arrangement forced
+-- on every reading would anchor each of them into the shape of whichever one it
+-- was built in.
+CREATE TABLE graph_pins (
+ entity_id TEXT NOT NULL REFERENCES entities(id) ON DELETE CASCADE,
+ lens TEXT NOT NULL,
+ x REAL NOT NULL,
+ y REAL NOT NULL,
+ PRIMARY KEY (entity_id, lens)
+);
+CREATE INDEX idx_graph_pins_lens ON graph_pins(lens);
+CREATE TABLE entity_images (
+ entity_id TEXT NOT NULL REFERENCES entities(id) ON DELETE CASCADE,
+ image_id TEXT NOT NULL,
+ media_id TEXT REFERENCES entities(id) ON DELETE CASCADE,
+ path TEXT,
+ thumbnail TEXT,
+ title TEXT,
+ position INTEGER NOT NULL,
+ is_primary INTEGER NOT NULL DEFAULT 0 CHECK (is_primary IN (0, 1)),
+ PRIMARY KEY (entity_id, image_id),
+ CHECK (
+ (media_id IS NOT NULL AND path IS NULL AND thumbnail IS NULL)
+ OR (media_id IS NULL AND path IS NOT NULL AND thumbnail IS NOT NULL)
+ )
+);
+CREATE INDEX idx_entity_images_media ON entity_images(media_id);
+CREATE UNIQUE INDEX idx_entity_images_media_once
+ ON entity_images(entity_id, media_id) WHERE media_id IS NOT NULL;
+CREATE UNIQUE INDEX idx_entity_images_path
+ ON entity_images(path) WHERE path IS NOT NULL;
+CREATE UNIQUE INDEX idx_entity_images_primary
+ ON entity_images(entity_id) WHERE is_primary = 1;
+CREATE TABLE analysis_views (
+ id TEXT PRIMARY KEY,
+ name TEXT NOT NULL,
+ mode TEXT NOT NULL CHECK (mode IN ('live', 'snapshot')),
+ surface TEXT NOT NULL CHECK (surface IN ('board', 'graph', 'timeline')),
+ spec_json TEXT NOT NULL,
+ snapshot_count INTEGER NOT NULL DEFAULT 0,
+ created_at TEXT NOT NULL,
+ updated_at TEXT NOT NULL
+);
+CREATE INDEX idx_analysis_views_updated ON analysis_views(updated_at DESC);
CREATE TABLE media_items (
path TEXT PRIMARY KEY,
entity_id TEXT UNIQUE,
@@ -123,9 +216,37 @@ CREATE TABLE media_items (
imagery_mode TEXT,
has_gps INTEGER NOT NULL DEFAULT 0
);
+CREATE TABLE temporal_items (
+ id TEXT PRIMARY KEY,
+ owner_id TEXT NOT NULL REFERENCES entities(id) ON DELETE CASCADE,
+ authority TEXT NOT NULL CHECK (authority IN ('entity', 'media')),
+ category TEXT NOT NULL CHECK (
+ category IN ('statement', 'media', 'case_activity')
+ ),
+ kind TEXT NOT NULL,
+ raw TEXT,
+ earliest TEXT,
+ latest TEXT,
+ precision TEXT,
+ shape TEXT,
+ time_role TEXT,
+ uncertain INTEGER NOT NULL DEFAULT 0 CHECK (uncertain IN (0, 1)),
+ approximate INTEGER NOT NULL DEFAULT 0 CHECK (approximate IN (0, 1)),
+ zone TEXT,
+ sortable INTEGER NOT NULL DEFAULT 0 CHECK (sortable IN (0, 1)),
+ status TEXT,
+ confidence TEXT,
+ parse_error TEXT
+);
CREATE INDEX idx_entities_type ON entities(type);
CREATE INDEX idx_entities_status ON entities(prov_status);
CREATE INDEX idx_entities_folder ON entities(folder);
+-- The two columns the catalog orders the whole case by. Without them a sorted
+-- page scans the table and builds a temp B-tree, which is the cost the bounded
+-- catalog exists to avoid. The collation is part of the index because it is part
+-- of the ORDER BY: an index on the bare column cannot serve a NOCASE sort.
+CREATE INDEX idx_entities_label ON entities(label COLLATE NOCASE);
+CREATE INDEX idx_entities_filed ON entities(prov_at);
CREATE INDEX idx_links_from ON links(from_id);
CREATE INDEX idx_links_to ON links(to_id);
CREATE INDEX idx_links_type ON links(type);
@@ -139,6 +260,9 @@ CREATE INDEX idx_media_added ON media_items(added_at);
CREATE INDEX idx_media_source ON media_items(source_type);
CREATE INDEX idx_media_gps ON media_items(has_gps);
CREATE INDEX idx_trash_deleted ON trash(deleted_at);
+CREATE INDEX idx_temporal_window ON temporal_items(category, earliest, latest);
+CREATE INDEX idx_temporal_owner ON temporal_items(owner_id, category);
+CREATE INDEX idx_temporal_kind ON temporal_items(kind);
"""
# Job lifecycle (doc "Job states"): a fresh job is `queued`; the worker claims it
@@ -164,6 +288,385 @@ def _like_prefix(term: str) -> str:
return f"{escaped}%"
+#: How many ids one ``IN (…)`` clause carries. SQLite's compiled variable ceiling
+#: is 999 on the oldest builds still in the wild, and the widest query here binds
+#: an id set twice plus its type filter, so the chunk stays well under a third of
+#: it rather than assuming the modern 32 766.
+_ID_CHUNK = 250
+
+
+def _chunks(items: list[str]) -> Iterator[list[str]]:
+ """Split an id set into runs one SQL statement can bind."""
+ for start in range(0, len(items), _ID_CHUNK):
+ yield items[start : start + _ID_CHUNK]
+
+
+def _marks(values: list[str]) -> str:
+ return ", ".join("?" * len(values))
+
+
+#: The temp table an id set is asked through when ``IN (…)`` cannot hold it.
+_SCOPE = "scope"
+
+
+def _scope_table(conn: sqlite3.Connection, ids: list[str]) -> None:
+ """Put an id set in a temp table, so a query over it binds no ids at all.
+
+ The variable ceiling is what forces `_chunks`, and a chunk is a fine answer for a
+ question each chunk can settle alone. It is the wrong answer for one that needs
+ two ids at once: the closed edge set asked every pair of chunks, so a drawing of
+ 650 nodes cost nine statements and one of 5 000 would cost four hundred — the cost
+ the node ceiling was hiding rather than removing.
+
+ Handed to SQLite as a table instead, the same question is one statement at any
+ size, and the join uses the primary key. Temp tables belong to the connection, and
+ `_connect` opens a fresh one per operation, so this cannot leak into another read;
+ it is still emptied on the way in, because a helper that is only correct when
+ nobody calls it twice is a trap for the next caller.
+ """
+ conn.execute(
+ f"CREATE TEMP TABLE IF NOT EXISTS {_SCOPE}(id TEXT PRIMARY KEY) WITHOUT ROWID"
+ )
+ conn.execute(f"DELETE FROM {_SCOPE}")
+ conn.executemany(
+ f"INSERT OR IGNORE INTO {_SCOPE}(id) VALUES (?)", [(one,) for one in ids]
+ )
+
+
+#: How many distinct values a field may hold before a select stops being a way to
+#: choose one. Fifty platforms or conditions is a menu; five thousand file paths is a
+#: list nobody scrolls, and offering it would be the typed query this app refuses.
+MAX_ATTR_VALUES = 50
+
+#: How long a value may be and still be worth offering. A quoted paragraph and a
+#: traced footprint are stored values, not choices.
+MAX_ATTR_TEXT = 120
+
+#: What an attribute key may be made of. The key reaches SQL inside a JSON path — a
+#: string the database parses rather than a bound parameter — so the character set is
+#: closed rather than escaped, and anything else is refused rather than quoted.
+_ATTR_KEY = re.compile(r"^[A-Za-z0-9_.\-]{1,64}$")
+
+
+@lru_cache(maxsize=1)
+def _has_json1() -> bool:
+ """Whether this SQLite can read inside a JSON column, probed once.
+
+ The extension set is per-binary and not per-Python (see the module docstring):
+ `sqlite3` links whatever SQLite the build environment provided, so JSON1 can be
+ present on a dev machine and missing from a shipped binary. Present, an attribute
+ filter is an expression the database evaluates against the top-level field;
+ absent, it is the same question spelled as `LIKE` over the exact text
+ `json.dumps` wrote — which matches the field at any depth, so a nested object
+ holding the same key *and* the same value matches too. `tests/test_repository.py`
+ asserts the probe answers true, so CI proves on all three platforms that the
+ exact path is the one that ships.
+ """
+ conn = sqlite3.connect(":memory:")
+ try:
+ conn.execute("SELECT json_extract('{\"a\": 1}', '$.\"a\"')").fetchone()
+ except sqlite3.Error:
+ return False
+ finally:
+ conn.close()
+ return True
+
+
+def _attr_match(key: str, value: str) -> tuple[str, list[Any]]:
+ """One ``attrs`` field holding one value, as this SQLite can ask it.
+
+ The value is compared **as text**, because text is what a select can offer: the
+ values come back from the facet read as strings, so `kind` is `video` where
+ `radius_m` is `100`, and both sides of the control agree on the spelling.
+ """
+ if not _ATTR_KEY.match(key):
+ raise CaseError(f"'{key}' is not a field name")
+ if _has_json1():
+ return f"CAST(json_extract(attrs_json, '$.\"{key}\"') AS TEXT) = ?", [value]
+ # The stored text, as `json.dumps` writes it: `{"kind": "video", "path": "…"}`.
+ # A value runs up to the next comma or to the closing brace, and the terminator is
+ # part of the pattern — without it, `"radius_m": 1` also matched 100.
+ quoted = json.dumps(value, ensure_ascii=False)
+ patterns = [
+ _like_contains(f'"{key}": {written}{end}')
+ for written in (quoted, value)
+ for end in (",", "}")
+ ]
+ joined = " OR ".join("attrs_json LIKE ? ESCAPE '\\'" for _ in patterns)
+ return f"({joined})", patterns
+
+
+def _holds_number(key: str) -> str:
+ """One ``attrs`` field holding a *number*, as this SQLite can ask it.
+
+ Not ``_attr_match``, which compares against a chosen value: here nothing is being
+ matched, the question is whether a number was written at all. It is what tells a
+ statement that counts something from one that says *seen, not counted*, and both
+ spellings have to answer it the same way (module docstring).
+ """
+ if not _ATTR_KEY.match(key):
+ raise CaseError(f"'{key}' is not a field name")
+ if _has_json1():
+ return f"json_type(attrs_json, '$.\"{key}\"') IN ('integer', 'real')"
+ # `json.dumps` writes `{"count": 2}`. GLOB rather than LIKE because a digit has to
+ # be part of the pattern: `LIKE '%"count": %'` also matches a null and a string.
+ return f"attrs_json GLOB '*\"{key}\": [0-9]*'"
+
+
+def _facet_value(value: Any) -> str | None:
+ """One stored value as a menu can offer it, or None when it cannot.
+
+ The spelling has to match what the filter compares against, since one is the menu
+ and the other is the question it asks: a number reads as its own digits either
+ side. Booleans are refused because the two sides would not agree — SQLite casts
+ `true` to `1` where Python writes `True` — and no field in the vocabulary holds
+ one.
+ """
+ if isinstance(value, bool) or value is None or isinstance(value, (dict, list)):
+ return None
+ if isinstance(value, (int, float)):
+ return str(value)
+ if not isinstance(value, str) or not value or len(value) > MAX_ATTR_TEXT:
+ return None
+ return value
+
+
+def _linked_to(type_: str, alias: str) -> tuple[str, list[Any]]:
+ """Whether one hop from this entity reaches an entity of that type.
+
+ *Which videos have coordinates* is this test and nothing else, and until now it
+ could not be asked anywhere in the app: a case could show every video and every
+ place, and never the one set that is both. Undirected, because "linked to a place"
+ is a question about the pair rather than about which end states the verb.
+ """
+ return (
+ " EXISTS (SELECT 1 FROM links l JOIN entities far"
+ f" ON far.id = (CASE WHEN l.from_id = {alias}.id THEN l.to_id ELSE l.from_id END)"
+ f" WHERE (l.from_id = {alias}.id OR l.to_id = {alias}.id) AND far.type = ?)",
+ [type_],
+ )
+
+
+def _linked_at_all(alias: str) -> str:
+ """Whether anything at all links this entity to the rest of the case.
+
+ The complement of ``_linked_to`` with the type dropped, and the one question the
+ catalog could not ask: *what have I filed and never connected to anything.* The
+ graph counts that set — it is a case's unexploited material — but counting is not
+ reaching it, and until this existed the only way to a list was to read the drawing
+ for dots with no line on them.
+ """
+ return (
+ f" EXISTS (SELECT 1 FROM links l WHERE l.from_id = {alias}.id"
+ f" OR l.to_id = {alias}.id)"
+ )
+
+
+#: The character that sorts after every other, appended to an inclusive upper bound.
+#: ``prov_at`` holds a full ISO instant and a date range is asked in days, so
+#: ``until='2026-08-10'`` has to reach the whole of that day rather than stopping at
+#: its first microsecond. Lexicographic order is what ISO-8601 guarantees, so a
+#: sentinel above every timestamp starting with that date is the exact bound.
+_AFTER_ALL = "￿"
+
+#: How a catalog page may be ordered, beyond the insertion order it defaults to.
+#:
+#: Each entry is ``(sort expression, the column its key is read from, descending)``,
+#: and a leading ``-`` spells the descending reading of the same key. Insertion order
+#: is deliberately absent: it is the rowid keyset the cursor has always been, and it
+#: stays the default because a page that never reorders is what makes a background
+#: import safe to scroll past.
+#:
+#: **Each ordering pages on its own key plus the rowid.** An offset would skip a row
+#: whenever one was deleted between two pages, and a key on its own ties — a hundred
+#: entities filed in the same second, or two people with one name — so the rowid
+#: breaks it. That is what makes "newest first" an answer about the case rather than
+#: about the hundred rows a table happened to have loaded.
+_PAGE_ORDERS: dict[str, tuple[str, str, bool]] = {
+ "label": ("label COLLATE NOCASE", "label", False),
+ "-label": ("label COLLATE NOCASE", "label", True),
+ "created": ("prov_at", "prov_at", False),
+ "-created": ("prov_at", "prov_at", True),
+}
+
+
+def _page_cursor(cursor: str) -> tuple[int, str]:
+ """An ordered page's cursor: the rowid it stopped on, and that row's sort key.
+
+ Spelled ``<rowid>:<key>`` because the rowid is an integer and cannot hold the
+ separator, so the key takes the whole of the rest verbatim — a label with a colon
+ in it round-trips unharmed. Insertion order keeps the bare rowid it has always
+ used: it needs no second key, and every client that already round-trips one of
+ those is unaffected.
+ """
+ seat, separator, key = cursor.partition(":")
+ if not separator:
+ raise CaseError(f"invalid cursor '{cursor}'")
+ return _parse_cursor(seat), key
+
+
+def _entity_filters(
+ *,
+ types: list[str] | None = None,
+ exclude_types: list[str] | None = None,
+ status: str | None = None,
+ query: str | None = None,
+ folder: str | None = None,
+ unfiled: bool = False,
+ recursive: bool = False,
+ attr: str | None = None,
+ attr_value: str | None = None,
+ linked: str | None = None,
+ unlinked: bool = False,
+ since: str | None = None,
+ until: str | None = None,
+ filed_by: list[str] | None = None,
+ temporal_since: str | None = None,
+ temporal_until: str | None = None,
+ temporal_categories: list[str] | None = None,
+ alias: str = "entities",
+) -> tuple[str, list[Any]]:
+ """The shared ``WHERE`` over entities: type set, review status, folder, search.
+
+ One predicate for the board's page and the graph's ranking, so a filter can
+ never mean two things depending on which view asked.
+
+ ``types`` and ``exclude_types`` are two different questions and compose rather
+ than replace each other: the first is the narrowing a caller asked for, the second
+ is the set a graph lens does not draw at all (``engine/graph.py``). Stated as an
+ exclusion because a free-typed entity — one the vocabulary has never heard of —
+ has no role either, and an allowlist resolved from the registry would drop it.
+
+ ``attr``/``attr_value`` narrow on one stored field, and ``linked`` on having a
+ neighbour of a type. Together with the type set they are the sentence *media,
+ kind video, linked to a place* — every term chosen from what the case holds, none
+ of it typed as syntax (SPEC anti-goals). ``alias`` names the entity table in the
+ statement being built, because the one-hop test has to correlate to the outer row
+ and the two callers spell that table differently.
+
+ ``unlinked`` is that sentence's other half — *connected to nothing* — and
+ ``since``/``until``/``filed_by`` are the three terms about how a row got here
+ rather than about what it says: when it was filed, and by which tool or by hand.
+ Every one of them reads a column the entity already carries, so none of them costs
+ a scan the other terms were not already paying for.
+ """
+ where: list[str] = []
+ params: list[Any] = []
+ if types:
+ where.append(f"type IN ({_marks(types)})")
+ params.extend(types)
+ if exclude_types:
+ where.append(f"type NOT IN ({_marks(exclude_types)})")
+ params.extend(exclude_types)
+ if status is not None:
+ where.append("prov_status = ?")
+ params.append(status)
+ if unfiled:
+ where.append("folder IS NULL")
+ elif folder is not None:
+ if recursive:
+ where.append("(folder = ? OR folder LIKE ? ESCAPE '\\')")
+ params.extend((folder, _like_prefix(folder + "/")))
+ else:
+ where.append("folder = ?")
+ params.append(folder)
+ for term in (query or "").casefold().split():
+ where.append("search_text LIKE ? ESCAPE '\\'")
+ params.append(_like_contains(term))
+ # A field with no value chosen is not a term: it is the analyst having picked which
+ # field they are about to ask about, and answering it as "holds nothing" would empty
+ # the table between two clicks of one act.
+ if attr and attr_value is not None:
+ clause, bound = _attr_match(attr, attr_value)
+ where.append(clause)
+ params.extend(bound)
+ if linked:
+ clause, bound = _linked_to(linked, alias)
+ where.append(clause)
+ params.extend(bound)
+ if unlinked:
+ where.append(f" NOT{_linked_at_all(alias)}")
+ if since:
+ where.append("prov_at >= ?")
+ params.append(since)
+ if until:
+ where.append("prov_at <= ?")
+ params.append(until + _AFTER_ALL)
+ if filed_by:
+ where.append(f"prov_by IN ({_marks(filed_by)})")
+ params.extend(filed_by)
+ if temporal_since is not None or temporal_until is not None:
+ if temporal_since is None or temporal_until is None:
+ raise CaseError("a temporal filter needs both boundaries")
+ categories = list(dict.fromkeys(
+ temporal_categories or list(timeline_engine.DEFAULT_CATEGORIES)
+ ))
+ invalid = sorted(set(categories) - set(timeline_engine.ALL_CATEGORIES))
+ if invalid:
+ raise CaseError(f"unknown timeline category '{invalid[0]}'")
+ if not categories:
+ raise CaseError("a temporal filter needs a category")
+ where.append(
+ "EXISTS (SELECT 1 FROM temporal_items temporal_match"
+ " WHERE temporal_match.earliest IS NOT NULL"
+ " AND temporal_match.latest > ? AND temporal_match.earliest < ?"
+ f" AND temporal_match.category IN ({_marks(categories)})"
+ f" AND (temporal_match.owner_id = {alias}.id OR EXISTS ("
+ "SELECT 1 FROM links temporal_scope"
+ " WHERE temporal_scope.from_id = temporal_match.owner_id"
+ f" AND temporal_scope.to_id = {alias}.id"
+ " AND temporal_scope.type IN ('about', 'at', 'cites'))))"
+ )
+ params.extend((temporal_since, temporal_until, *categories))
+ return ((" WHERE " + " AND ".join(where)) if where else "", params)
+
+
+def _link_scope(
+ types: list[str] | None = None,
+ *,
+ ends_out: list[str] | None = None,
+ ends_in: list[str] | None = None,
+) -> tuple[str, list[Any]]:
+ """One lens's edges: its verbs, and which types may stand at an end.
+
+ Every half comes from the same reading (``engine/graph.py``). ``ends_out`` is what
+ keeps a **degree** honest now that a lens narrows nodes as well as verbs: counted
+ over every edge, a media whose only connections are to notes would read as
+ connected in a reading that draws neither the notes nor the edges to them, and the
+ control offering to open it could only ever appear to do nothing.
+
+ ``ends_in`` is the opposite question, and the one the collapse asks: *which edges
+ reach a type this reading leaves out.* One end at least is of those types, so paired
+ with an id set that holds none of them it names the bridge and the node it bridges
+ to in one row.
+
+ Any half may be empty, which means no narrowing on that axis.
+ """
+ where: list[str] = []
+ params: list[Any] = []
+ wanted = list(dict.fromkeys(types or []))
+ if wanted:
+ where.append(f"type IN ({_marks(wanted)})")
+ params.extend(wanted)
+ hidden = list(dict.fromkeys(ends_out or []))
+ if hidden:
+ marks = _marks(hidden)
+ where.append(
+ f"from_id NOT IN (SELECT id FROM entities WHERE type IN ({marks}))"
+ f" AND to_id NOT IN (SELECT id FROM entities WHERE type IN ({marks}))"
+ )
+ params.extend(hidden * 2)
+ reached = list(dict.fromkeys(ends_in or []))
+ if reached:
+ marks = _marks(reached)
+ where.append(
+ f"(from_id IN (SELECT id FROM entities WHERE type IN ({marks}))"
+ f" OR to_id IN (SELECT id FROM entities WHERE type IN ({marks})))"
+ )
+ params.extend(reached * 2)
+ return ((" WHERE " + " AND ".join(where)) if where else "", params)
+
+
def _folder_of(attrs: dict[str, Any] | None) -> str | None:
"""The indexed folder value for an entity: its ``attrs.folder`` path, or None
when unfiled — an absent or empty folder both read as unfiled."""
@@ -172,12 +675,18 @@ def _folder_of(attrs: dict[str, Any] | None) -> str | None:
def _entity_search_text(type_: str, label: str, attrs: dict[str, Any] | None) -> str:
+ """What a case search matches an entity against.
+
+ The label, the type, the folder and the notes, plus the type's own declared text
+ fields (``entities.search_values``): a vehicle is looked for by its plate and a
+ claim by the words it quotes, and neither was findable while the index stopped
+ at the notes. Recomputed on every write, and rebuilt for existing rows by the
+ schema-10 migration.
+ """
attrs = attrs or {}
- return "\n".join(
- str(value)
- for value in (label, type_, attrs.get("folder"), attrs.get("notes"))
- if value
- ).casefold()
+ fixed = (label, type_, attrs.get("folder"), attrs.get("notes"))
+ declared = entity_engine.search_values(type_, attrs)
+ return "\n".join(str(value) for value in (*fixed, *declared) if value).casefold()
def _replace_exact(value: Any, old: str, new: str) -> Any:
@@ -191,6 +700,192 @@ def _replace_exact(value: Any, old: str, new: str) -> Any:
return value
+_TEMPORAL_COLUMNS = (
+ "id", "owner_id", "authority", "category", "kind", "raw", "earliest",
+ "latest", "precision", "shape", "time_role", "uncertain", "approximate",
+ "zone", "sortable", "status", "confidence", "parse_error",
+)
+
+
+def _write_temporal_rows(
+ conn: sqlite3.Connection,
+ owner_id: str,
+ authority: str,
+ rows: list[timeline_engine.ProjectionRow],
+) -> None:
+ """Replace one authority's derived rows for one owner."""
+ conn.execute(
+ "DELETE FROM temporal_items WHERE owner_id = ? AND authority = ?",
+ (owner_id, authority),
+ )
+ placeholders = ", ".join("?" for _ in _TEMPORAL_COLUMNS)
+ for row in rows:
+ record = row.record()
+ conn.execute(
+ f"INSERT INTO temporal_items({', '.join(_TEMPORAL_COLUMNS)})"
+ f" VALUES({placeholders})",
+ tuple(record[column] for column in _TEMPORAL_COLUMNS),
+ )
+
+
+def _entity_for_projection(row: sqlite3.Row) -> dict[str, Any]:
+ entity: dict[str, Any] = {
+ "id": row["id"],
+ "type": row["type"],
+ "label": row["label"],
+ "attrs": json.loads(row["attrs_json"]),
+ "provenance": {
+ "by": row["prov_by"],
+ "at": row["prov_at"],
+ "status": row["prov_status"],
+ },
+ }
+ if row["prov_source"] is not None:
+ entity["provenance"]["source"] = row["prov_source"]
+ return entity
+
+
+def _sync_entity_temporal(conn: sqlite3.Connection, entity: dict[str, Any]) -> None:
+ _write_temporal_rows(
+ conn,
+ str(entity["id"]),
+ "entity",
+ timeline_engine.project_entity(entity),
+ )
+
+
+def _sync_media_temporal(
+ conn: sqlite3.Connection, item: dict[str, Any], entity_id: str | None
+) -> None:
+ if not entity_id:
+ return
+ # The media browse contract historically permits a row whose optional
+ # entity id no longer resolves (imports repair that association later).
+ # Temporal rows do carry a foreign key, so only project an owner that exists.
+ if conn.execute("SELECT 1 FROM entities WHERE id = ?", (entity_id,)).fetchone() is None:
+ return
+ _write_temporal_rows(
+ conn,
+ entity_id,
+ "media",
+ timeline_engine.project_media(item, entity_id),
+ )
+
+
+def _rebuild_temporal_projection_conn(conn: sqlite3.Connection) -> int:
+ """Rebuild the projection in the caller's transaction, returning its size."""
+ conn.execute("DELETE FROM temporal_items")
+ for row in conn.execute("SELECT * FROM entities ORDER BY rowid").fetchall():
+ _sync_entity_temporal(conn, _entity_for_projection(row))
+ for row in conn.execute(
+ "SELECT item_json, entity_id FROM media_items"
+ " WHERE entity_id IS NOT NULL ORDER BY rowid"
+ ).fetchall():
+ _sync_media_temporal(conn, json.loads(row["item_json"]), row["entity_id"])
+ return int(conn.execute("SELECT COUNT(*) FROM temporal_items").fetchone()[0])
+
+
+def _temporal_projection_status_conn(conn: sqlite3.Connection) -> dict[str, int | bool]:
+ """Compare the derived index with graph and media authorities without writing."""
+ expected: dict[str, tuple[Any, ...]] = {}
+
+ def remember(rows: list[timeline_engine.ProjectionRow]) -> None:
+ for row in rows:
+ record = row.record()
+ expected[row.id] = tuple(
+ int(record[column])
+ if column in {"uncertain", "approximate", "sortable"}
+ else record[column]
+ for column in _TEMPORAL_COLUMNS
+ )
+
+ entity_rows = conn.execute("SELECT * FROM entities ORDER BY rowid").fetchall()
+ entity_ids = {str(row["id"]) for row in entity_rows}
+ for row in entity_rows:
+ remember(timeline_engine.project_entity(_entity_for_projection(row)))
+ for row in conn.execute(
+ "SELECT item_json, entity_id FROM media_items"
+ " WHERE entity_id IS NOT NULL ORDER BY rowid"
+ ).fetchall():
+ entity_id = str(row["entity_id"])
+ if entity_id in entity_ids:
+ remember(timeline_engine.project_media(json.loads(row["item_json"]), entity_id))
+
+ actual = {
+ str(row["id"]): tuple(row[column] for column in _TEMPORAL_COLUMNS)
+ for row in conn.execute(
+ f"SELECT {', '.join(_TEMPORAL_COLUMNS)} FROM temporal_items"
+ ).fetchall()
+ }
+ missing = expected.keys() - actual.keys()
+ extra = actual.keys() - expected.keys()
+ changed = {
+ item_id for item_id in expected.keys() & actual.keys()
+ if expected[item_id] != actual[item_id]
+ }
+ return {
+ "consistent": not (missing or extra or changed),
+ "expected": len(expected),
+ "actual": len(actual),
+ "missing": len(missing),
+ "extra": len(extra),
+ "changed": len(changed),
+ }
+
+
+def _timeline_cursor(group: int, stamp: str, item_id: str) -> str:
+ body = json.dumps([group, stamp, item_id], separators=(",", ":")).encode()
+ return urlsafe_b64encode(body).decode().rstrip("=")
+
+
+def _timeline_phase_cursor(stride: int, phase: int) -> str:
+ body = json.dumps(["phase", stride, phase], separators=(",", ":")).encode()
+ return urlsafe_b64encode(body).decode().rstrip("=")
+
+
+def _decode_cursor(cursor: str) -> Any:
+ padded = cursor + "=" * (-len(cursor) % 4)
+ return json.loads(urlsafe_b64decode(padded.encode()).decode())
+
+
+def _parse_timeline_cursor(cursor: str | None) -> tuple[int, str, str] | None:
+ if cursor is None:
+ return None
+ try:
+ value = _decode_cursor(cursor)
+ if (
+ not isinstance(value, list)
+ or len(value) != 3
+ or value[0] not in (0, 1)
+ or not isinstance(value[1], str)
+ or not isinstance(value[2], str)
+ ):
+ raise ValueError
+ return int(value[0]), value[1], value[2]
+ except (ValueError, TypeError, UnicodeDecodeError, json.JSONDecodeError):
+ raise CaseError(f"invalid timeline cursor '{cursor}'") from None
+
+
+def _parse_timeline_phase(cursor: str | None) -> tuple[int, int] | None:
+ """Where a spread read resumes: which of ``stride`` interleaved slices is next."""
+ if cursor is None:
+ return None
+ try:
+ value = _decode_cursor(cursor)
+ if (
+ not isinstance(value, list)
+ or len(value) != 3
+ or value[0] != "phase"
+ or any(not isinstance(part, int) or isinstance(part, bool) for part in value[1:])
+ or not 1 <= value[1] <= 100_000
+ or not 0 <= value[2] < value[1]
+ ):
+ raise ValueError
+ return int(value[1]), int(value[2])
+ except (ValueError, TypeError, UnicodeDecodeError, json.JSONDecodeError):
+ raise CaseError(f"invalid timeline cursor '{cursor}'") from None
+
+
def _migrate_1_to_2(conn: sqlite3.Connection) -> None:
"""Add the ``folder`` column, backfill it from each entity's ``attrs.folder``
(in Python, no JSON1 dependency), and index it."""
@@ -284,9 +979,194 @@ def _migrate_6_to_7(conn: sqlite3.Connection) -> None:
conn.execute("ALTER TABLE trash ADD COLUMN state TEXT NOT NULL DEFAULT 'ready'")
+def _migrate_7_to_8(conn: sqlite3.Connection) -> None:
+ """Let an edge say how sure the analyst is (ONTOLOGY §3).
+
+ Nullable and unset, so every link already in the case reads as "not assessed",
+ which is the truth about them rather than a level invented on their behalf.
+ """
+ conn.execute("ALTER TABLE links ADD COLUMN confidence INTEGER")
+
+
+def _migrate_8_to_9(conn: sqlite3.Connection) -> None:
+ """Rebuild every entity's search text so the declared fields are in it.
+
+ The index is a stored column, so widening what goes into it only reaches rows
+ written afterwards: a case filed last week would keep answering searches from
+ its label alone. One pass, no shape change.
+ """
+ for row in conn.execute("SELECT id, type, label, attrs_json FROM entities").fetchall():
+ attrs = json.loads(row["attrs_json"])
+ conn.execute(
+ "UPDATE entities SET search_text = ? WHERE id = ?",
+ (_entity_search_text(row["type"], row["label"], attrs), row["id"]),
+ )
+
+
+def _migrate_9_to_10(conn: sqlite3.Connection) -> None:
+ """Let the analyst's own arrangement of the graph survive a reload.
+
+ One row per node *per lens*: a lens draws its own nodes and edges, so it
+ clusters differently, and a single arrangement would force every reading into
+ the shape of whichever one it was built in.
+
+ Nothing to backfill: a case opened before this had no way to move a node, so
+ every node in it is placed by the layout, which is what an empty table says.
+ """
+ conn.execute(
+ "CREATE TABLE graph_pins ("
+ " entity_id TEXT NOT NULL REFERENCES entities(id) ON DELETE CASCADE,"
+ " lens TEXT NOT NULL,"
+ " x REAL NOT NULL,"
+ " y REAL NOT NULL,"
+ " PRIMARY KEY (entity_id, lens)"
+ ")"
+ )
+ conn.execute("CREATE INDEX idx_graph_pins_lens ON graph_pins(lens)")
+
+
+def _migrate_10_to_11(conn: sqlite3.Connection) -> None:
+ """Let an edge say what kind of tie it states, where the verb cannot.
+
+ Nothing to backfill and no index: every existing edge is unqualified, which is
+ what a null column already says, and nothing filters or sorts on this — it is
+ read with the edge it sits on.
+ """
+ conn.execute("ALTER TABLE links ADD COLUMN nature TEXT")
+
+
+def _migrate_11_to_12(conn: sqlite3.Connection) -> None:
+ """Add galleries holding private photos or existing Media references."""
+ conn.execute(
+ "CREATE TABLE entity_images ("
+ " entity_id TEXT NOT NULL REFERENCES entities(id) ON DELETE CASCADE,"
+ " image_id TEXT NOT NULL,"
+ " media_id TEXT REFERENCES entities(id) ON DELETE CASCADE,"
+ " path TEXT,"
+ " thumbnail TEXT,"
+ " title TEXT,"
+ " position INTEGER NOT NULL,"
+ " is_primary INTEGER NOT NULL DEFAULT 0 CHECK (is_primary IN (0, 1)),"
+ " PRIMARY KEY (entity_id, image_id),"
+ " CHECK ((media_id IS NOT NULL AND path IS NULL AND thumbnail IS NULL)"
+ " OR (media_id IS NULL AND path IS NOT NULL AND thumbnail IS NOT NULL)))"
+ )
+ conn.execute("CREATE INDEX idx_entity_images_media ON entity_images(media_id)")
+ conn.execute(
+ "CREATE UNIQUE INDEX idx_entity_images_media_once"
+ " ON entity_images(entity_id, media_id) WHERE media_id IS NOT NULL"
+ )
+ conn.execute(
+ "CREATE UNIQUE INDEX idx_entity_images_path"
+ " ON entity_images(path) WHERE path IS NOT NULL"
+ )
+ conn.execute(
+ "CREATE UNIQUE INDEX idx_entity_images_primary"
+ " ON entity_images(entity_id) WHERE is_primary = 1"
+ )
+
+
+def _migrate_12_to_13(conn: sqlite3.Connection) -> None:
+ """Add named analysis readings, empty until the analyst saves one."""
+ conn.execute(
+ "CREATE TABLE analysis_views ("
+ " id TEXT PRIMARY KEY,"
+ " name TEXT NOT NULL,"
+ " mode TEXT NOT NULL CHECK (mode IN ('live', 'snapshot')),"
+ " surface TEXT NOT NULL CHECK ("
+ "surface IN ('board', 'graph')"
+ "),"
+ " spec_json TEXT NOT NULL,"
+ " snapshot_count INTEGER NOT NULL DEFAULT 0,"
+ " created_at TEXT NOT NULL,"
+ " updated_at TEXT NOT NULL"
+ ")"
+ )
+ conn.execute(
+ "CREATE INDEX idx_analysis_views_updated ON analysis_views(updated_at DESC)"
+ )
+
+
+def _migrate_13_to_14(conn: sqlite3.Connection) -> None:
+ """Index the two columns the catalog orders the whole case by.
+
+ Sorting by identity or by when a row was filed reads the whole filtered set,
+ not the page — which is the difference between *the newest in this case* and
+ *the newest of the hundred rows loaded*. Without an index to seek into, every
+ page of that read scanned the table and sorted it in a temp B-tree, so the
+ keyset cursor bounded what came back and not what it cost.
+
+ The label index carries `COLLATE NOCASE` because the ordering does: an index
+ on the bare column sorts by byte and cannot serve the query.
+ """
+ conn.execute("CREATE INDEX idx_entities_label ON entities(label COLLATE NOCASE)")
+ conn.execute("CREATE INDEX idx_entities_filed ON entities(prov_at)")
+
+
+def _migrate_14_to_15(conn: sqlite3.Connection) -> None:
+ """Add and backfill the rebuildable Time and Timeline search projection."""
+ conn.execute(
+ "CREATE TABLE temporal_items ("
+ " id TEXT PRIMARY KEY,"
+ " owner_id TEXT NOT NULL REFERENCES entities(id) ON DELETE CASCADE,"
+ " authority TEXT NOT NULL CHECK (authority IN ('entity', 'media')),"
+ " category TEXT NOT NULL CHECK ("
+ "category IN ('statement', 'media', 'case_activity')"
+ "),"
+ " kind TEXT NOT NULL, raw TEXT, earliest TEXT, latest TEXT, precision TEXT,"
+ " shape TEXT, time_role TEXT,"
+ " uncertain INTEGER NOT NULL DEFAULT 0 CHECK (uncertain IN (0, 1)),"
+ " approximate INTEGER NOT NULL DEFAULT 0 CHECK (approximate IN (0, 1)),"
+ " zone TEXT, sortable INTEGER NOT NULL DEFAULT 0 CHECK (sortable IN (0, 1)),"
+ " status TEXT, confidence TEXT, parse_error TEXT"
+ ")"
+ )
+ conn.execute(
+ "CREATE INDEX idx_temporal_window"
+ " ON temporal_items(category, earliest, latest)"
+ )
+ conn.execute(
+ "CREATE INDEX idx_temporal_owner ON temporal_items(owner_id, category)"
+ )
+ conn.execute("CREATE INDEX idx_temporal_kind ON temporal_items(kind)")
+ _rebuild_temporal_projection_conn(conn)
+
+
+def _migrate_15_to_16(conn: sqlite3.Connection) -> None:
+ """Extend the case-owned Analysis View contract to Timeline readings."""
+ conn.execute("ALTER TABLE analysis_views RENAME TO analysis_views_legacy")
+ conn.execute(
+ "CREATE TABLE analysis_views ("
+ " id TEXT PRIMARY KEY, name TEXT NOT NULL,"
+ " mode TEXT NOT NULL CHECK (mode IN ('live', 'snapshot')),"
+ " surface TEXT NOT NULL CHECK (surface IN ('board', 'graph', 'timeline')),"
+ " spec_json TEXT NOT NULL, snapshot_count INTEGER NOT NULL DEFAULT 0,"
+ " created_at TEXT NOT NULL, updated_at TEXT NOT NULL)"
+ )
+ # Named, not `SELECT *`: the legacy table's columns are in whatever order its own
+ # history left them, and a positional copy would silently rotate the last three.
+ conn.execute(
+ "INSERT INTO analysis_views"
+ " (id, name, mode, surface, spec_json, snapshot_count, created_at, updated_at)"
+ " SELECT id, name, mode, surface, spec_json, snapshot_count, created_at,"
+ " updated_at FROM analysis_views_legacy"
+ )
+ conn.execute("DROP TABLE analysis_views_legacy")
+ conn.execute(
+ "CREATE INDEX idx_analysis_views_updated ON analysis_views(updated_at DESC)"
+ )
+
+
+def _migrate_16_to_17(conn: sqlite3.Connection) -> None:
+ """Rewrite temporal bounds to their fixed-width sortable representation."""
+ _rebuild_temporal_projection_conn(conn)
+
+
# from_version -> function(conn) applying the in-place upgrade to from_version + 1.
-# Runs inside one transaction per step in `SqliteCase._upgrade`, which stamps the
-# new schema_version and records the migration; the step only reshapes the db.
+# The whole chain runs inside one immediate transaction in `SqliteCase._upgrade`,
+# which stamps each new schema_version and records each migration as it goes; a
+# failure at any step rolls the lot back and the next open replays from where the
+# database still says it is. A step only reshapes the db.
_SQLITE_MIGRATIONS: dict[int, Callable[[sqlite3.Connection], None]] = {
1: _migrate_1_to_2,
2: _migrate_2_to_3,
@@ -294,6 +1174,16 @@ _SQLITE_MIGRATIONS: dict[int, Callable[[sqlite3.Connection], None]] = {
4: _migrate_4_to_5,
5: _migrate_5_to_6,
6: _migrate_6_to_7,
+ 7: _migrate_7_to_8,
+ 8: _migrate_8_to_9,
+ 9: _migrate_9_to_10,
+ 10: _migrate_10_to_11,
+ 11: _migrate_11_to_12,
+ 12: _migrate_12_to_13,
+ 13: _migrate_13_to_14,
+ 14: _migrate_14_to_15,
+ 15: _migrate_15_to_16,
+ 16: _migrate_16_to_17,
}
_MEDIA_CATEGORIES = (
@@ -314,11 +1204,23 @@ _MEDIA_CATEGORY_SQL = {
"video": "kind = 'video'",
"collage": "source_op = 'collage'",
"satellite": _SATELLITE_SQL,
- "upload": "source_type = 'upload'",
+ # A paste and a drop are one facet: both are material the analyst brought in
+ # by hand, which is the question this filter asks. They stay two source types
+ # because only one of them can state where it came from.
+ "upload": "source_type IN ('upload', 'clipboard')",
"download": "source_type = 'download'",
"other": "kind NOT IN ('image', 'video')",
}
+#: Rows the case **made** rather than collected, as one predicate. The set is the
+#: relation layer's (`engine/links.py` MADE_HERE), so the list and the graph cannot
+#: come to disagree about what a case collected.
+_MADE_HERE_SQL = (
+ "COALESCE(source_type, '') IN ("
+ + ", ".join(f"'{route}'" for route in link_engine.MADE_HERE)
+ + ")"
+)
+
def _has_gps(item: dict[str, Any]) -> bool:
"""Whether an indexed media item carries a usable position.
@@ -501,10 +1403,16 @@ class SqliteCase:
return store
def _upgrade(self) -> None:
- """Bring an older `case.db` up to `SQLITE_SCHEMA`, each step in its own
- immediate transaction and rolled back on failure. Re-reads the version
- inside the transaction so a second opener that raced the first finds
- nothing left to apply rather than replaying a migration."""
+ """Bring an older `case.db` up to `SQLITE_SCHEMA` inside one immediate
+ transaction, rolled back whole on failure — a case that cannot finish the
+ chain stays exactly at the version it was, rather than at a half-applied
+ one no migration knows how to resume. Re-reads the version inside the
+ transaction so a second opener that raced the first finds nothing left to
+ apply rather than replaying a migration.
+
+ The cost of that guarantee is that a long step holds the write lock for
+ the whole chain: a case coming from several versions back rebuilds its
+ search index and creates its tables in one go."""
with self._connect() as conn:
conn.execute("BEGIN IMMEDIATE")
try:
@@ -673,6 +1581,14 @@ class SqliteCase:
}
if row["prov_source"] is not None:
link["provenance"]["source"] = row["prov_source"]
+ # Absent rather than null: "not assessed" is the absence of a key, so no
+ # reader has to tell an unevaluated edge from one someone rated as nothing.
+ if row["confidence"] is not None:
+ link["confidence"] = row["confidence"]
+ # Same rule: an edge nobody has qualified carries no key at all, so a reader
+ # never has to tell "unstated" from "stated as empty".
+ if row["nature"] is not None:
+ link["nature"] = row["nature"]
return link
@staticmethod
@@ -762,116 +1678,715 @@ class SqliteCase:
).fetchall()
return {r["id"]: int(r["n"]) for r in rows}
- def page_entities(
+ # -- graph reads (engine/graph.py) -------------------------------------
+ #
+ # The board pages entities in insertion order; a graph needs a different cut.
+ # Which nodes matter is a property of the edges, so these four read the graph
+ # shape rather than the list: rank by how connected a node is, fetch a known
+ # set, and resolve the edges inside or around it. Everything is bounded by an
+ # id set or an explicit limit, so no caller can reach the whole graph through
+ # them — `snapshot` stays the one deliberate whole-case read.
+
+ def rank_entities(
self,
*,
- limit: int = 100,
- cursor: str | None = None,
+ limit: int = 200,
types: list[str] | None = None,
+ exclude_types: list[str] | None = None,
status: EntityStatus | None = None,
query: str | None = None,
folder: str | None = None,
unfiled: bool = False,
recursive: bool = False,
+ attr: str | None = None,
+ attr_value: str | None = None,
+ linked: str | None = None,
+ unlinked_only: bool = False,
+ since: str | None = None,
+ until: str | None = None,
+ filed_by: list[str] | None = None,
+ temporal_since: str | None = None,
+ temporal_until: str | None = None,
+ temporal_categories: list[str] | None = None,
+ link_types: list[str] | None = None,
+ order: str = "degree",
) -> dict[str, Any]:
- """A bounded, cursor-paginated slice of entities in insertion order.
-
- The cursor keys on ``rowid`` (monotonic, primary-index-backed), so a
- background import appending rows never shifts a page the analyst already
- scrolled past — new rows land after the current tail. Filters compose in
- SQL: ``types`` (an ``IN`` set), ``status``, a case-insensitive ``query``
- over the label, and folder — either ``unfiled`` (no folder) or an exact
- ``folder`` path (or its descendants when ``recursive`` is true). One
- extra row is peeked to know whether a further page exists, so
- ``next_cursor`` is None exactly on the last page.
+ """The most significant entities first, bounded, with their degree.
+
+ Which nodes survive a truncated view is the whole question for a case too
+ large to draw. Ordering decides it: ``degree`` keeps the hubs, so the shape
+ of the case is what stays on screen rather than an arbitrary slice, and
+ ``recent`` keeps the latest work. ``link_types`` counts the degree over one
+ lens only, so a node reads as isolated in a lens it truly has no edge in, and
+ ``exclude_types`` is the set that lens does not draw at all: it leaves those
+ entities out of the ranking *and* out of every degree counted here, or a node
+ would state a connection to something the drawing has no room to show.
+
+ The narrowing terms are the catalog's own, so the board and the graph cannot
+ disagree about what *confirmed people in this folder, added this week* means:
+ one predicate answers both (``_entity_filters``).
+
+ Returns ``{entities, degrees, total, truncated, unlinked}``, where ``total``
+ and ``unlinked`` both count every entity matching the filters, whether it was
+ returned or not.
+
+ ``unlinked`` is counted here rather than off the returned rows for one
+ reason: a degree-0 entity sorts **last** under ``degree`` ordering, so it is
+ the first thing a cut discards. Counted on the page, "what nobody has
+ connected" reads zero on exactly the cases where it matters, which is worse
+ than not offering the number at all. Its degree is read over the lens's verbs
+ alone and says nothing about whether the far end of an edge was returned, so
+ a narrowing cannot inflate it either.
"""
- where: list[str] = []
- params: list[Any] = []
- if types:
- where.append(f"type IN ({', '.join('?' * len(types))})")
- params.extend(types)
- if status is not None:
- where.append("prov_status = ?")
- params.append(status)
- if unfiled:
- where.append("folder IS NULL")
- elif folder is not None:
- if recursive:
- where.append("(folder = ? OR folder LIKE ? ESCAPE '\\')")
- params.extend((folder, _like_prefix(folder + "/")))
- else:
- where.append("folder = ?")
- params.append(folder)
- for term in (query or "").casefold().split():
- where.append("search_text LIKE ? ESCAPE '\\'")
- params.append(_like_contains(term))
- filter_clause = (" WHERE " + " AND ".join(where)) if where else ""
- filter_params = list(params)
- if cursor is not None:
- where.append("rowid > ?")
- params.append(_parse_cursor(cursor))
- clause = (" WHERE " + " AND ".join(where)) if where else ""
- params.append(limit + 1)
+ clause, params = _entity_filters(
+ types=types, exclude_types=exclude_types, status=status, query=query,
+ folder=folder, unfiled=unfiled, recursive=recursive,
+ attr=attr, attr_value=attr_value, linked=linked, unlinked=unlinked_only,
+ since=since, until=until, filed_by=filed_by,
+ temporal_since=temporal_since, temporal_until=temporal_until,
+ temporal_categories=temporal_categories,
+ # This statement names the entity table `e`, and the shared predicate has
+ # one term that correlates to the outer row rather than reading a column.
+ alias="e",
+ )
+ link_clause, link_params = _link_scope(link_types, ends_out=exclude_types)
+ # A node with no edge has no row in the degree subquery, hence the join and
+ # the COALESCE: an isolated entity is degree 0, never missing.
+ degree_sql = (
+ "SELECT id, COUNT(*) AS n FROM ("
+ f" SELECT from_id AS id FROM links{link_clause}"
+ " UNION ALL"
+ f" SELECT to_id AS id FROM links{link_clause}"
+ ") GROUP BY id"
+ )
+ ordering = (
+ "e.prov_at DESC, e.rowid DESC" if order == "recent" else "degree DESC, e.rowid ASC"
+ )
with self._connect() as conn:
+ # Aliased `e` like the two statements below it: the shared predicate has
+ # terms that correlate to the outer row — *linked to a place*, *connected
+ # to nothing* — and they name the table they are counting.
total = int(
- conn.execute(
- f"SELECT COUNT(*) FROM entities{filter_clause}",
- filter_params,
- ).fetchone()[0]
+ conn.execute(f"SELECT COUNT(*) FROM entities e{clause}", params).fetchone()[0]
)
rows = conn.execute(
- f"SELECT rowid AS _rowid, * FROM entities{clause} ORDER BY rowid LIMIT ?",
- params,
+ "SELECT e.*, COALESCE(d.n, 0) AS degree FROM entities e"
+ f" LEFT JOIN ({degree_sql}) d ON d.id = e.id{clause}"
+ f" ORDER BY {ordering} LIMIT ?",
+ (*link_params, *link_params, *params, limit),
).fetchall()
- has_more = len(rows) > limit
- rows = rows[:limit]
- next_cursor = str(rows[-1]["_rowid"]) if has_more and rows else None
+ joined = f"{clause} AND" if clause else " WHERE"
+ unlinked = int(
+ conn.execute(
+ "SELECT COUNT(*) FROM entities e"
+ f" LEFT JOIN ({degree_sql}) d ON d.id = e.id{joined}"
+ " COALESCE(d.n, 0) = 0",
+ (*link_params, *link_params, *params),
+ ).fetchone()[0]
+ )
return {
- "items": [self._entity(r) for r in rows],
- "next_cursor": next_cursor,
+ "entities": [self._entity(r) for r in rows],
+ "degrees": {r["id"]: int(r["degree"]) for r in rows},
"total": total,
+ "truncated": total > len(rows),
+ "unlinked": unlinked,
}
- def catalog_summary(self) -> dict[str, Any]:
- """Total plus per-type, per-status and per-folder counts in grouped scans
- — the catalog's badges without materialising the graph."""
+ def graph_pins(self, lens: str) -> dict[str, tuple[float, float]]:
+ """The nodes placed by hand in one lens, as ``{entity_id: (x, y)}``.
+
+ Scoped to the lens because that is what an arrangement belongs to. Otherwise
+ unbounded, and deliberately: a pin exists only because somebody dragged a
+ node, so the row count follows the hand, not the size of the case.
+ """
with self._connect() as conn:
- total = conn.execute("SELECT COUNT(*) FROM entities").fetchone()[0]
- by_type = {
- r["type"]: r["n"]
- for r in conn.execute("SELECT type, COUNT(*) AS n FROM entities GROUP BY type")
- }
- by_status = {
- r["prov_status"]: r["n"]
- for r in conn.execute(
- "SELECT prov_status, COUNT(*) AS n FROM entities GROUP BY prov_status"
+ rows = conn.execute(
+ "SELECT entity_id, x, y FROM graph_pins WHERE lens = ?", (lens,)
+ ).fetchall()
+ return {r["entity_id"]: (float(r["x"]), float(r["y"])) for r in rows}
+
+ def pin_entities(self, lens: str, pins: dict[str, tuple[float, float]]) -> int:
+ """Record where these nodes were dropped in this lens, replacing any earlier
+ spot in it and leaving the other lenses alone.
+
+ One transaction for the whole batch, because a drag that moved a group is
+ one act: half of it landing would leave an arrangement nobody chose. An id
+ that does not exist is skipped rather than raising — a drag races a delete
+ made in another tab, and losing the pin is the right outcome there.
+ """
+ if not pins:
+ return 0
+
+ def op(conn: sqlite3.Connection) -> int:
+ written = 0
+ for entity_id, (x, y) in pins.items():
+ if conn.execute(
+ "SELECT 1 FROM entities WHERE id = ?", (entity_id,)
+ ).fetchone() is None:
+ continue
+ conn.execute(
+ "INSERT INTO graph_pins(entity_id, lens, x, y) VALUES(?, ?, ?, ?)"
+ " ON CONFLICT(entity_id, lens)"
+ " DO UPDATE SET x = excluded.x, y = excluded.y",
+ (entity_id, lens, float(x), float(y)),
)
- }
- by_folder = {
- r["folder"]: r["n"]
- for r in conn.execute(
- "SELECT folder, COUNT(*) AS n FROM entities"
- " WHERE folder IS NOT NULL GROUP BY folder"
+ written += 1
+ if written:
+ self._touch(conn)
+ return written
+
+ return self._write(op)
+
+ def unpin_entities(self, lens: str, ids: list[str]) -> int:
+ """Hand these nodes back to the layout in this lens. Ids with no pin in it
+ are simply absent."""
+ wanted = list(dict.fromkeys(ids))
+ if not wanted:
+ return 0
+
+ def op(conn: sqlite3.Connection) -> int:
+ dropped = 0
+ for chunk in _chunks(wanted):
+ cursor = conn.execute(
+ "DELETE FROM graph_pins WHERE lens = ?"
+ f" AND entity_id IN ({_marks(chunk)})",
+ (lens, *chunk),
)
- }
+ dropped += cursor.rowcount if cursor.rowcount > 0 else 0
+ if dropped:
+ self._touch(conn)
+ return dropped
+
+ return self._write(op)
+
+ def clear_graph_pins(self, lens: str) -> int:
+ """Drop this lens's arrangement, and only its own: the reading goes back to
+ the placement it computes while the others keep theirs."""
+
+ def op(conn: sqlite3.Connection) -> int:
+ cursor = conn.execute("DELETE FROM graph_pins WHERE lens = ?", (lens,))
+ dropped = cursor.rowcount if cursor.rowcount > 0 else 0
+ if dropped:
+ self._touch(conn)
+ return dropped
+
+ return self._write(op)
+
+ # -- saved analysis views ---------------------------------------------
+
+ @staticmethod
+ def _analysis_view(row: sqlite3.Row) -> dict[str, Any]:
+ spec = json.loads(row["spec_json"])
return {
- "total": total,
- "by_type": by_type,
- "by_status": by_status,
- "by_folder": by_folder,
+ "id": row["id"],
+ "name": row["name"],
+ "mode": row["mode"],
+ "surface": row["surface"],
+ "spec": spec,
+ "snapshot_count": int(row["snapshot_count"]),
+ "created_at": row["created_at"],
+ "updated_at": row["updated_at"],
}
- def get_entity(self, entity_id: str) -> dict[str, Any] | None:
- with self._connect() as conn:
- row = conn.execute("SELECT * FROM entities WHERE id = ?", (entity_id,)).fetchone()
- return self._entity(row) if row is not None else None
+ def list_analysis_views(self) -> list[dict[str, Any]]:
+ """Named readings, newest edit first.
- def note_ids_by_titles(self, titles: set[str]) -> dict[str, list[str]]:
- """Note ids grouped by case-folded title, for stable flat exports."""
- wanted = {title.casefold() for title in titles}
- grouped: dict[str, list[str]] = {title: [] for title in wanted}
- if not wanted:
- return grouped
+ The count is denormalised beside the JSON so naming a menu never parses or
+ ships every captured entity merely to say how large its snapshot is.
+ """
+ with self._connect() as conn:
+ rows = conn.execute(
+ "SELECT id, name, mode, surface, snapshot_count, created_at, updated_at"
+ " FROM analysis_views ORDER BY updated_at DESC, name COLLATE NOCASE"
+ ).fetchall()
+ return [dict(row) for row in rows]
+
+ def get_analysis_view(self, view_id: str) -> dict[str, Any] | None:
+ with self._connect() as conn:
+ row = conn.execute(
+ "SELECT * FROM analysis_views WHERE id = ?", (view_id,)
+ ).fetchone()
+ return self._analysis_view(row) if row is not None else None
+
+ def save_analysis_view(self, view: dict[str, Any]) -> dict[str, Any]:
+ """Insert or replace one validated recipe as a single transaction."""
+ spec = json.dumps(view["spec"], ensure_ascii=False, separators=(",", ":"))
+ snapshot = view["spec"].get("snapshot", {})
+ snapshot_count = len(
+ snapshot.get("timeline_items", snapshot.get("entities", []))
+ )
+
+ def op(conn: sqlite3.Connection) -> None:
+ conn.execute(
+ "INSERT INTO analysis_views"
+ " (id, name, mode, surface, spec_json, snapshot_count, created_at, updated_at)"
+ " VALUES (?, ?, ?, ?, ?, ?, ?, ?)"
+ " ON CONFLICT(id) DO UPDATE SET"
+ " name = excluded.name, mode = excluded.mode,"
+ " surface = excluded.surface, spec_json = excluded.spec_json,"
+ " snapshot_count = excluded.snapshot_count,"
+ " updated_at = excluded.updated_at",
+ (
+ view["id"], view["name"], view["mode"], view["surface"], spec,
+ snapshot_count,
+ view["created_at"], view["updated_at"],
+ ),
+ )
+ self._touch(conn)
+
+ self._write(op)
+ saved = self.get_analysis_view(view["id"])
+ if saved is None: # pragma: no cover - the insert above is the invariant
+ raise CaseError(f"analysis view '{view['id']}' was not saved")
+ return saved
+
+ def remove_analysis_view(self, view_id: str) -> dict[str, Any] | None:
+ """Remove one view and return the recipe Trash needs to restore it."""
+ existing = self.get_analysis_view(view_id)
+ if existing is None:
+ return None
+
+ def op(conn: sqlite3.Connection) -> None:
+ conn.execute("DELETE FROM analysis_views WHERE id = ?", (view_id,))
+ self._touch(conn)
+
+ self._write(op)
+ return existing
+
+ def reinsert_analysis_views(self, views: list[dict[str, Any]]) -> int:
+ """Restore saved readings whose ids have not been reused."""
+ restored = 0
+ for view in views:
+ if self.get_analysis_view(str(view.get("id") or "")) is not None:
+ continue
+ self.save_analysis_view(view)
+ restored += 1
+ return restored
+
+ def entities_by_ids(self, ids: list[str]) -> list[dict[str, Any]]:
+ """A known set of entities in one read, skipping ids that are gone."""
+ found: list[dict[str, Any]] = []
+ with self._connect() as conn:
+ for chunk in _chunks(list(dict.fromkeys(ids))):
+ rows = conn.execute(
+ f"SELECT * FROM entities WHERE id IN ({_marks(chunk)})", chunk
+ ).fetchall()
+ found.extend(self._entity(r) for r in rows)
+ return found
+
+ def labels_of_type(self, type_: str) -> list[tuple[str, str]]:
+ """Every entity of one type as ``(id, label)``, off ``idx_entities_type``.
+
+ Two columns and no payload: the caller compares identifier values
+ (``entities.identity_key``), and that normalization is vocabulary — pushed
+ into SQL it would be a second copy of the rules, drifting from the one the
+ create form is answered by.
+ """
+ with self._connect() as conn:
+ rows = conn.execute(
+ "SELECT id, label FROM entities WHERE type = ?", (type_,)
+ ).fetchall()
+ return [(row["id"], row["label"]) for row in rows]
+
+ def links_among(
+ self, ids: list[str], *, types: list[str] | None = None
+ ) -> list[dict[str, Any]]:
+ """Edges with **both** ends inside the set — what a drawn view may show.
+
+ An edge to a node that was not loaded cannot be drawn without inventing the
+ node at its far end, so the view asks for the closed set and gets it from the
+ database rather than filtering a wider one in Python.
+
+ It takes no ``exclude_types``, unlike the two reads below: both ends are
+ already nodes the caller resolved and drew, so a type the lens leaves out
+ cannot be one of them.
+ """
+ return self._links_in(ids, types=types, touching=False)
+
+ def links_touching(
+ self,
+ ids: list[str],
+ *,
+ types: list[str] | None = None,
+ exclude_types: list[str] | None = None,
+ end_types: list[str] | None = None,
+ ) -> list[dict[str, Any]]:
+ """Edges with **either** end inside the set — one hop of an expansion.
+
+ ``exclude_types`` drops an edge whose far end the lens does not draw, which is
+ what stops a walk from stepping onto one and reporting it as a neighbour.
+ ``end_types`` asks the opposite and is the collapse's probe: only edges that do
+ reach one of those types, so a bridge through a node the reading leaves out
+ comes back in one row instead of being looked for.
+ """
+ return self._links_in(
+ ids, types=types, exclude_types=exclude_types,
+ end_types=end_types, touching=True,
+ )
+
+ def degrees_of(
+ self,
+ ids: list[str],
+ *,
+ types: list[str] | None = None,
+ exclude_types: list[str] | None = None,
+ ) -> dict[str, int]:
+ """How many edges each of these nodes carries, over one lens.
+
+ What a node shows before it is expanded, so the analyst knows the size of
+ what a click is about to bring in — hence ``exclude_types``: a connection to a
+ node this reading leaves out is not something a click could bring in.
+ """
+ clause, params = _link_scope(types, ends_out=exclude_types)
+ counts: dict[str, int] = {}
+ with self._connect() as conn:
+ for chunk in _chunks(list(dict.fromkeys(ids))):
+ marks = _marks(chunk)
+ where = f"{clause} AND" if clause else " WHERE"
+ rows = conn.execute(
+ "SELECT id, COUNT(*) AS n FROM ("
+ f" SELECT from_id AS id FROM links{where} from_id IN ({marks})"
+ " UNION ALL"
+ f" SELECT to_id AS id FROM links{where} to_id IN ({marks})"
+ ") GROUP BY id",
+ (*params, *chunk, *params, *chunk),
+ ).fetchall()
+ for row in rows:
+ counts[row["id"]] = int(row["n"])
+ return {entity_id: counts.get(entity_id, 0) for entity_id in dict.fromkeys(ids)}
+
+ def _links_in(
+ self,
+ ids: list[str],
+ *,
+ types: list[str] | None,
+ touching: bool,
+ exclude_types: list[str] | None = None,
+ end_types: list[str] | None = None,
+ ) -> list[dict[str, Any]]:
+ """Edges over an id set, in one statement whatever the set's size.
+
+ **Both ends have to be asked at once**, and that is what the id set cannot be
+ chunked for. One end inside is a question a chunk can settle alone: an edge
+ either touches it or it does not. Both ends inside is not — the two ends can
+ fall in two different chunks, and then no chunk holds the edge and neither did
+ the answer. Asked chunk by chunk, a drawn view over `_ID_CHUNK` nodes lost
+ most of its edges: nodes drew as unconnected dots, and a node whose edges had
+ gone kept reporting them as connections still to open, under a control that
+ could never bring one in.
+
+ Asking every *pair* of chunks closed that hole and bought a worse one, which
+ the ceiling on the drawing was hiding: the statement count is the square of
+ the set. `_scope_table` is the answer that scales — the ids go in as rows, and
+ the closed set is a join on the primary key.
+
+ Rows come back in `rowid` order, so the edge order a caller sees is the order
+ the case recorded them in.
+ """
+ wanted = list(dict.fromkeys(ids))
+ if not wanted:
+ return []
+ clause, params = _link_scope(types, ends_out=exclude_types, ends_in=end_types)
+ # One end in the set, or both. The closed set says it as a join, because that
+ # is what a join is: the far end has to *exist* in the scope for the row to
+ # stand, and both ends are then one condition rather than two chunk lists.
+ if touching:
+ reaches = (
+ f" (links.from_id IN (SELECT id FROM {_SCOPE})"
+ f" OR links.to_id IN (SELECT id FROM {_SCOPE}))"
+ )
+ joined = ""
+ where = f"{clause} AND{reaches}" if clause else f" WHERE{reaches}"
+ else:
+ joined = (
+ f" JOIN {_SCOPE} near ON near.id = links.from_id"
+ f" JOIN {_SCOPE} far ON far.id = links.to_id"
+ )
+ where = clause
+ with self._connect() as conn:
+ _scope_table(conn, wanted)
+ rows = conn.execute(
+ f"SELECT links.* FROM links{joined}{where} ORDER BY links.rowid",
+ params,
+ ).fetchall()
+ return [self._link(row) for row in rows]
+
+ def page_entities(
+ self,
+ *,
+ limit: int = 100,
+ cursor: str | None = None,
+ types: list[str] | None = None,
+ status: EntityStatus | None = None,
+ query: str | None = None,
+ folder: str | None = None,
+ unfiled: bool = False,
+ recursive: bool = False,
+ attr: str | None = None,
+ attr_value: str | None = None,
+ linked: str | None = None,
+ unlinked: bool = False,
+ since: str | None = None,
+ until: str | None = None,
+ filed_by: list[str] | None = None,
+ temporal_since: str | None = None,
+ temporal_until: str | None = None,
+ temporal_categories: list[str] | None = None,
+ order: str = "",
+ ) -> dict[str, Any]:
+ """A bounded, cursor-paginated slice of entities, in insertion order or sorted.
+
+ The default cursor keys on ``rowid`` (monotonic, primary-index-backed), so a
+ background import appending rows never shifts a page the analyst already
+ scrolled past — new rows land after the current tail. Filters compose in
+ SQL: ``types`` (an ``IN`` set), ``status``, a case-insensitive ``query``
+ over the label, folder — either ``unfiled`` (no folder) or an exact
+ ``folder`` path (or its descendants when ``recursive`` is true) — one stored
+ field holding one value (``attr``/``attr_value``), having a neighbour of a
+ type (``linked``) or none at all (``unlinked``), and when and by what the row
+ was filed (``since``/``until``/``filed_by``). One extra row is peeked to know
+ whether a further page exists, so ``next_cursor`` is None exactly on the last
+ page.
+
+ ``order`` sorts the whole filtered set rather than the page (``_PAGE_ORDERS``),
+ which is the difference between *the newest in this case* and *the newest of
+ the hundred rows a table has loaded* — the second is what a client-side sort
+ can answer, and on a case worth paging it is the wrong answer.
+
+ ``total`` counts every row matching the same terms, which is what makes the
+ narrowing terms answer a question rather than only shorten a list: *how many
+ videos have coordinates* is that number.
+ """
+ if order and order not in _PAGE_ORDERS:
+ raise CaseError(f"'{order}' is not an ordering")
+ filter_clause, filter_params = _entity_filters(
+ types=types, status=status, query=query,
+ folder=folder, unfiled=unfiled, recursive=recursive,
+ attr=attr, attr_value=attr_value, linked=linked, unlinked=unlinked,
+ since=since, until=until, filed_by=filed_by,
+ temporal_since=temporal_since, temporal_until=temporal_until,
+ temporal_categories=temporal_categories,
+ )
+ clause, params = filter_clause, list(filter_params)
+ sort_key = ""
+ if order:
+ expression, sort_key, descending = _PAGE_ORDERS[order]
+ way = "<" if descending else ">"
+ if cursor is not None:
+ seat, key = _page_cursor(cursor)
+ joiner = " AND " if clause else " WHERE "
+ clause = (
+ f"{clause}{joiner}({expression} {way} ?"
+ f" OR ({expression} = ? AND rowid {way} ?))"
+ )
+ params.extend((key, key, seat))
+ direction = "DESC" if descending else "ASC"
+ ordering = f"{expression} {direction}, rowid {direction}"
+ else:
+ if cursor is not None:
+ joiner = " AND " if clause else " WHERE "
+ clause = f"{clause}{joiner}rowid > ?"
+ params.append(_parse_cursor(cursor))
+ ordering = "rowid"
+ params.append(limit + 1)
+ with self._connect() as conn:
+ total = int(
+ conn.execute(
+ f"SELECT COUNT(*) FROM entities{filter_clause}",
+ filter_params,
+ ).fetchone()[0]
+ )
+ rows = conn.execute(
+ f"SELECT rowid AS _rowid, * FROM entities{clause}"
+ f" ORDER BY {ordering} LIMIT ?",
+ params,
+ ).fetchall()
+ has_more = len(rows) > limit
+ rows = rows[:limit]
+ next_cursor = None
+ if has_more and rows:
+ tail = rows[-1]
+ next_cursor = (
+ f"{tail['_rowid']}:{tail[sort_key]}" if sort_key else str(tail["_rowid"])
+ )
+ return {
+ "items": [self._entity(r) for r in rows],
+ "next_cursor": next_cursor,
+ "total": total,
+ }
+
+ def catalog_summary(self) -> dict[str, Any]:
+ """Total plus per-type, per-status, per-folder and per-filer counts in grouped
+ scans — the catalog's badges without materialising the graph.
+
+ ``by_source`` is ``provenance.by``: which tool filed a row, or the analyst.
+ ``unlinked`` is how many the case connects to nothing, and it is here rather
+ than left to a query because it is a *menu* count — a filter menu that states
+ how much of an answer each term is before it is chosen is what stops the
+ analyst picking one and landing on an empty table.
+ """
+ with self._connect() as conn:
+ total = conn.execute("SELECT COUNT(*) FROM entities").fetchone()[0]
+ by_type = {
+ r["type"]: r["n"]
+ for r in conn.execute("SELECT type, COUNT(*) AS n FROM entities GROUP BY type")
+ }
+ by_status = {
+ r["prov_status"]: r["n"]
+ for r in conn.execute(
+ "SELECT prov_status, COUNT(*) AS n FROM entities GROUP BY prov_status"
+ )
+ }
+ by_folder = {
+ r["folder"]: r["n"]
+ for r in conn.execute(
+ "SELECT folder, COUNT(*) AS n FROM entities"
+ " WHERE folder IS NOT NULL GROUP BY folder"
+ )
+ }
+ by_source = {
+ r["prov_by"]: r["n"]
+ for r in conn.execute(
+ "SELECT prov_by, COUNT(*) AS n FROM entities GROUP BY prov_by"
+ )
+ }
+ unlinked = int(
+ conn.execute(
+ "SELECT COUNT(*) FROM entities"
+ f" WHERE NOT{_linked_at_all('entities')}"
+ ).fetchone()[0]
+ )
+ # How many entities have **a neighbour** of each type, which is a different
+ # number from how many of that type the case holds: four things pointing at
+ # one place is four here and one there. The filter asks the first, so the
+ # menu has to price the first — a count that answers the neighbouring
+ # question is worse than no count, because it looks like an answer.
+ #
+ # Distinct per near-end, since a media joined to one place by two verbs is
+ # one row that is linked to a place, not two.
+ linked_to = {
+ r["type"]: int(r["n"])
+ for r in conn.execute(
+ "SELECT far_type AS type, COUNT(DISTINCT near_id) AS n FROM ("
+ " SELECT l.from_id AS near_id, far.type AS far_type"
+ " FROM links l JOIN entities far ON far.id = l.to_id"
+ " UNION ALL"
+ " SELECT l.to_id AS near_id, near.type AS far_type"
+ " FROM links l JOIN entities near ON near.id = l.from_id"
+ ") GROUP BY far_type"
+ )
+ }
+ # How many statements would actually produce a row if the case were added
+ # up: one carrying a number, about something. Here for the same reason
+ # `unlinked` is — it prices a control before it is pressed, and the two
+ # halves are what make the row real. A statement with no number says
+ # *seen, not counted* and one about nothing has no subject to sit under,
+ # so neither draws a line, and a total offered over them opens on an empty
+ # answer that reads as a finding about the case.
+ countable = int(
+ conn.execute(
+ "SELECT COUNT(*) FROM entities e"
+ " WHERE e.type = 'claim'"
+ f" AND {_holds_number('count')}"
+ " AND EXISTS ("
+ " SELECT 1 FROM links l WHERE l.from_id = e.id AND l.type = ?"
+ " )",
+ (link_engine.ABOUT,),
+ ).fetchone()[0]
+ )
+ return {
+ "total": total,
+ "by_type": by_type,
+ "by_status": by_status,
+ "by_folder": by_folder,
+ "by_source": by_source,
+ "linked_to": linked_to,
+ "unlinked": unlinked,
+ "countable": countable,
+ }
+
+ def attr_facets(
+ self, *, types: list[str] | None = None, limit: int = MAX_ATTR_VALUES
+ ) -> list[dict[str, Any]]:
+ """Which stored fields these entities hold, and which values they hold.
+
+ What makes a field filterable without a query language: the select of fields
+ and the select of values are both **populated from the case**, so every term of
+ a search is chosen rather than typed (SPEC anti-goals). It also answers a
+ question the vocabulary cannot: `kind` is written by the importer and declared
+ nowhere, so a registry-driven menu would never have offered the one field an
+ analyst most wants to filter on.
+
+ Returns one entry per field, ``{key, entities, values, truncated}``, ordered by
+ how many entities carry it. Bounded twice over, because this is a menu and not
+ a report: a field holding more than ``limit`` distinct values comes back with
+ none of them and ``truncated`` true — five thousand file paths is not a choice —
+ and a value longer than ``MAX_ATTR_TEXT`` is left out for the same reason.
+ Objects, arrays and booleans are skipped: a footprint is a shape, and `True` is
+ not a word anyone picks off a menu.
+
+ Scanned in Python like ``find_entity``, deliberately: it is a bounded read
+ behind an explicit act, and a JSON1 grouping would put the one thing this
+ module refuses to depend on in the middle of a menu.
+
+ **What it costs, so no caller gates on case size again.** The scan is linear
+ in the rows the narrowing covers and small per row: measured at 6 ms for 1 000
+ entities, 0.3 s for 50 000 and 0.7 s for 100 000, with a distinct ``path`` and
+ ``sha256`` each — the shape that overflows ``limit`` and so pays the most.
+ The Board and the graph used to darken the field menu past five thousand,
+ which cost the cases that most need a field to narrow with the one filter that
+ scales for them. The bound that keeps a menu readable is the one on values,
+ above.
+ """
+ wanted = list(dict.fromkeys(types or []))
+ counts: dict[str, int] = {}
+ values: dict[str, dict[str, int]] = {}
+ overflowed: set[str] = set()
+ clause = f" WHERE type IN ({_marks(wanted)})" if wanted else ""
+ with self._connect() as conn:
+ for row in conn.execute(f"SELECT attrs_json FROM entities{clause}", wanted):
+ for key, value in json.loads(row["attrs_json"]).items():
+ text = _facet_value(value)
+ if text is None:
+ continue
+ counts[key] = counts.get(key, 0) + 1
+ held = values.setdefault(key, {})
+ if text in held:
+ held[text] += 1
+ elif len(held) < limit:
+ held[text] = 1
+ else:
+ overflowed.add(key)
+ return [
+ {
+ "key": key,
+ "entities": counts[key],
+ "values": (
+ []
+ if key in overflowed
+ else [
+ {"value": value, "count": count}
+ for value, count in sorted(
+ values[key].items(), key=lambda pair: (-pair[1], pair[0])
+ )
+ ]
+ ),
+ "truncated": key in overflowed,
+ }
+ for key in sorted(counts, key=lambda key: (-counts[key], key))
+ ]
+
+ def get_entity(self, entity_id: str) -> dict[str, Any] | None:
+ with self._connect() as conn:
+ row = conn.execute("SELECT * FROM entities WHERE id = ?", (entity_id,)).fetchone()
+ return self._entity(row) if row is not None else None
+
+ def note_ids_by_titles(self, titles: set[str]) -> dict[str, list[str]]:
+ """Note ids grouped by case-folded title, for stable flat exports."""
+ wanted = {title.casefold() for title in titles}
+ grouped: dict[str, list[str]] = {title: [] for title in wanted}
+ if not wanted:
+ return grouped
with self._connect() as conn:
rows = conn.execute(
"SELECT id, label FROM entities WHERE type = 'note' ORDER BY id"
@@ -899,6 +2414,301 @@ class SqliteCase:
for r in conn.execute("SELECT path FROM folders ORDER BY path COLLATE NOCASE")
]
+ # -- entity image galleries ------------------------------------------
+
+ @staticmethod
+ def _ensure_entity_image_primary(conn: sqlite3.Connection, entity_id: str) -> bool:
+ if conn.execute(
+ "SELECT 1 FROM entity_images WHERE entity_id = ? AND is_primary = 1",
+ (entity_id,),
+ ).fetchone() is not None:
+ return False
+ row = conn.execute(
+ "SELECT image_id FROM entity_images WHERE entity_id = ?"
+ " ORDER BY position, image_id LIMIT 1",
+ (entity_id,),
+ ).fetchone()
+ if row is None:
+ return False
+ conn.execute(
+ "UPDATE entity_images SET is_primary = 1"
+ " WHERE entity_id = ? AND image_id = ?",
+ (entity_id, row["image_id"]),
+ )
+ return True
+
+ def entity_images(self, entity_id: str) -> list[dict[str, Any]]:
+ with self._connect() as conn:
+ rows = conn.execute(
+ "SELECT ei.image_id, ei.media_id, ei.path, ei.thumbnail, ei.title,"
+ " ei.position, ei.is_primary, mi.item_json"
+ " FROM entity_images ei"
+ " LEFT JOIN media_items mi ON mi.entity_id = ei.media_id"
+ " WHERE ei.entity_id = ?"
+ " ORDER BY ei.position, ei.image_id",
+ (entity_id,),
+ ).fetchall()
+ images: list[dict[str, Any]] = []
+ for row in rows:
+ item = json.loads(row["item_json"]) if row["item_json"] else {}
+ direct = row["media_id"] is None
+ images.append(
+ {
+ **item,
+ "id": row["image_id"],
+ "media_id": row["media_id"],
+ "direct": direct,
+ "path": row["path"] if direct else item.get("path"),
+ "thumbnail": (
+ row["thumbnail"] if direct else item.get("thumbnail")
+ ),
+ "title": row["title"] if direct else item.get("title"),
+ "kind": "image",
+ "position": int(row["position"]),
+ "primary": bool(row["is_primary"]),
+ }
+ )
+ return images
+
+ def entity_image_thumbs(self, entity_ids: list[str]) -> dict[str, str]:
+ unique = list(dict.fromkeys(entity_ids))
+ if not unique:
+ return {}
+ found: dict[str, str] = {}
+ with self._connect() as conn:
+ for chunk in _chunks(unique):
+ rows = conn.execute(
+ "SELECT ei.entity_id, ei.thumbnail, mi.item_json"
+ " FROM entity_images ei"
+ " LEFT JOIN media_items mi ON mi.entity_id = ei.media_id"
+ " WHERE ei.is_primary = 1"
+ f" AND ei.entity_id IN ({_marks(chunk)})",
+ chunk,
+ ).fetchall()
+ for row in rows:
+ thumb = row["thumbnail"]
+ if not thumb and row["item_json"]:
+ thumb = json.loads(row["item_json"]).get("thumbnail")
+ if thumb:
+ found[row["entity_id"]] = thumb
+ return found
+
+ def entity_images_touching(self, entity_ids: list[str]) -> list[dict[str, Any]]:
+ unique = list(dict.fromkeys(entity_ids))
+ if not unique:
+ return []
+ found: dict[tuple[str, str], dict[str, Any]] = {}
+ with self._connect() as conn:
+ for chunk in _chunks(unique):
+ marks = _marks(chunk)
+ rows = conn.execute(
+ "SELECT entity_id, image_id, media_id, path, thumbnail, title,"
+ " position, is_primary"
+ " FROM entity_images"
+ f" WHERE entity_id IN ({marks}) OR media_id IN ({marks})",
+ (*chunk, *chunk),
+ ).fetchall()
+ for row in rows:
+ found[(row["entity_id"], row["image_id"])] = {
+ "entity_id": row["entity_id"],
+ "image_id": row["image_id"],
+ "media_id": row["media_id"],
+ "path": row["path"],
+ "thumbnail": row["thumbnail"],
+ "title": row["title"],
+ "position": int(row["position"]),
+ "primary": bool(row["is_primary"]),
+ }
+ return sorted(found.values(), key=lambda row: (row["entity_id"], row["position"]))
+
+ def add_entity_images(self, entity_id: str, media_ids: list[str]) -> int:
+ candidates = list(dict.fromkeys(media_ids))
+
+ def op(conn: sqlite3.Connection) -> int:
+ if conn.execute(
+ "SELECT 1 FROM entities WHERE id = ?", (entity_id,)
+ ).fetchone() is None:
+ raise CaseError(f"entity '{entity_id}' not found")
+ if not candidates:
+ return 0
+ present = {
+ row["id"]
+ for row in conn.execute(
+ f"SELECT id FROM entities WHERE id IN ({_marks(candidates)})",
+ candidates,
+ )
+ }
+ missing = next((media_id for media_id in candidates if media_id not in present), None)
+ if missing is not None:
+ raise CaseError(f"entity '{missing}' not found")
+ row = conn.execute(
+ "SELECT COALESCE(MAX(position), -1) AS position"
+ " FROM entity_images WHERE entity_id = ?",
+ (entity_id,),
+ ).fetchone()
+ position = int(row["position"]) + 1
+ added = 0
+ for media_id in candidates:
+ cursor = conn.execute(
+ "INSERT OR IGNORE INTO entity_images"
+ "(entity_id, image_id, media_id, position, is_primary)"
+ " VALUES(?, ?, ?, ?, 0)",
+ (entity_id, media_id, media_id, position),
+ )
+ if cursor.rowcount:
+ position += 1
+ added += 1
+ promoted = self._ensure_entity_image_primary(conn, entity_id)
+ if added or promoted:
+ self._touch(conn)
+ return added
+
+ return self._write(op)
+
+ def add_entity_image_file(
+ self,
+ entity_id: str,
+ image_id: str,
+ path: str,
+ thumbnail: str,
+ title: str,
+ ) -> None:
+ def op(conn: sqlite3.Connection) -> None:
+ if conn.execute(
+ "SELECT 1 FROM entities WHERE id = ?", (entity_id,)
+ ).fetchone() is None:
+ raise CaseError(f"entity '{entity_id}' not found")
+ row = conn.execute(
+ "SELECT COALESCE(MAX(position), -1) AS position"
+ " FROM entity_images WHERE entity_id = ?",
+ (entity_id,),
+ ).fetchone()
+ conn.execute(
+ "INSERT INTO entity_images"
+ "(entity_id, image_id, media_id, path, thumbnail, title, position, is_primary)"
+ " VALUES(?, ?, NULL, ?, ?, ?, ?, 0)",
+ (entity_id, image_id, path, thumbnail, title, int(row["position"]) + 1),
+ )
+ self._ensure_entity_image_primary(conn, entity_id)
+ self._touch(conn)
+
+ self._write(op)
+
+ def set_primary_entity_image(self, entity_id: str, image_id: str) -> None:
+ def op(conn: sqlite3.Connection) -> None:
+ row = conn.execute(
+ "SELECT is_primary FROM entity_images"
+ " WHERE entity_id = ? AND image_id = ?",
+ (entity_id, image_id),
+ ).fetchone()
+ if row is None:
+ raise CaseError("that image is not attached to this entity")
+ if row["is_primary"]:
+ return
+ conn.execute(
+ "UPDATE entity_images SET is_primary = 0 WHERE entity_id = ?",
+ (entity_id,),
+ )
+ conn.execute(
+ "UPDATE entity_images SET is_primary = 1"
+ " WHERE entity_id = ? AND image_id = ?",
+ (entity_id, image_id),
+ )
+ self._touch(conn)
+
+ self._write(op)
+
+ def remove_entity_image(self, entity_id: str, image_id: str) -> dict[str, Any]:
+ def op(conn: sqlite3.Connection) -> dict[str, Any]:
+ row = conn.execute(
+ "SELECT image_id, media_id, path, thumbnail, title, position, is_primary"
+ " FROM entity_images WHERE entity_id = ? AND image_id = ?",
+ (entity_id, image_id),
+ ).fetchone()
+ if row is None:
+ raise CaseError("that image is not attached to this entity")
+ conn.execute(
+ "DELETE FROM entity_images WHERE entity_id = ? AND image_id = ?",
+ (entity_id, image_id),
+ )
+ self._ensure_entity_image_primary(conn, entity_id)
+ self._touch(conn)
+ return {
+ "id": row["image_id"],
+ "media_id": row["media_id"],
+ "path": row["path"],
+ "thumbnail": row["thumbnail"],
+ "title": row["title"],
+ "position": int(row["position"]),
+ "primary": bool(row["is_primary"]),
+ }
+
+ return self._write(op)
+
+ def reinsert_entity_images(self, rows: list[dict[str, Any]]) -> dict[str, int]:
+ def op(conn: sqlite3.Connection) -> dict[str, int]:
+ entity_ids = list(
+ dict.fromkeys(
+ str(value)
+ for row in rows
+ for value in (row.get("entity_id"),)
+ if value is not None
+ )
+ )
+ media_ids = list(
+ dict.fromkeys(
+ str(row["media_id"])
+ for row in rows
+ if row.get("media_id") is not None
+ )
+ )
+ present: set[str] = set()
+ for chunk in _chunks([*entity_ids, *media_ids]):
+ present.update(
+ row["id"]
+ for row in conn.execute(
+ f"SELECT id FROM entities WHERE id IN ({_marks(chunk)})",
+ chunk,
+ )
+ )
+ kept = [
+ row
+ for row in rows
+ if row.get("entity_id") in present
+ and (row.get("media_id") is None or row.get("media_id") in present)
+ ]
+ primary_entities = {
+ str(row["entity_id"]) for row in kept if row.get("primary")
+ }
+ for entity_id in primary_entities:
+ conn.execute(
+ "UPDATE entity_images SET is_primary = 0 WHERE entity_id = ?",
+ (entity_id,),
+ )
+ for row in kept:
+ conn.execute(
+ "INSERT OR REPLACE INTO entity_images"
+ "(entity_id, image_id, media_id, path, thumbnail, title,"
+ " position, is_primary) VALUES(?, ?, ?, ?, ?, ?, ?, ?)",
+ (
+ row["entity_id"],
+ row.get("image_id") or row.get("media_id"),
+ row.get("media_id"),
+ row.get("path"),
+ row.get("thumbnail"),
+ row.get("title"),
+ int(row.get("position", 0)),
+ int(bool(row.get("primary"))),
+ ),
+ )
+ for entity_id in {str(row["entity_id"]) for row in kept}:
+ self._ensure_entity_image_primary(conn, entity_id)
+ if kept:
+ self._touch(conn)
+ return {"images": len(kept), "images_lost": len(rows) - len(kept)}
+
+ return self._write(op)
+
# -- media browse index ------------------------------------------------
@staticmethod
@@ -928,6 +2738,16 @@ class SqliteCase:
" has_gps = excluded.has_gps",
(values[0], entity_id, *values[1:]),
)
+ indexed = conn.execute(
+ "SELECT item_json, entity_id FROM media_items WHERE path = ?",
+ (values[0],),
+ ).fetchone()
+ assert indexed is not None
+ _sync_media_temporal(
+ conn,
+ json.loads(indexed["item_json"]),
+ indexed["entity_id"],
+ )
def upsert_media_item(
self, item: dict[str, Any], *, entity_id: str | None = None
@@ -939,7 +2759,16 @@ class SqliteCase:
def remove_media_item(self, path: str) -> None:
def op(conn: sqlite3.Connection) -> None:
+ row = conn.execute(
+ "SELECT entity_id FROM media_items WHERE path = ?", (path,)
+ ).fetchone()
conn.execute("DELETE FROM media_items WHERE path = ?", (path,))
+ if row is not None and row["entity_id"]:
+ conn.execute(
+ "DELETE FROM temporal_items"
+ " WHERE owner_id = ? AND authority = 'media'",
+ (row["entity_id"],),
+ )
self._write(op)
@@ -978,6 +2807,87 @@ class SqliteCase:
}
return [by_path[path] for path in unique if path in by_path]
+ def media_thumbs(self, entity_ids: list[str]) -> dict[str, str]:
+ """The cached thumbnail of each of these entities that has one.
+
+ Chunked like every other id lookup here, and like `media_kinds` beside it.
+ The bound this used to raise on was a statement-size bound wearing the
+ clothes of a policy: the caller is the graph, whose ceiling is its own
+ business, and refusing the read left a drawable case drawing nothing at all.
+ """
+ unique = list(dict.fromkeys(entity_ids))
+ if not unique:
+ return {}
+ rows: list[sqlite3.Row] = []
+ with self._connect() as conn:
+ for chunk in _chunks(unique):
+ rows.extend(
+ conn.execute(
+ "SELECT entity_id, item_json FROM media_items"
+ f" WHERE entity_id IN ({_marks(chunk)})",
+ chunk,
+ ).fetchall()
+ )
+ found: dict[str, str] = {}
+ for row in rows:
+ thumb = json.loads(row["item_json"]).get("thumbnail")
+ if thumb:
+ found[row["entity_id"]] = thumb
+ return found
+
+ def media_kinds(self, entity_ids: list[str]) -> dict[str, str]:
+ """What the bytes behind each of these entities are: image, video, audio…
+
+ Read off the indexed column rather than out of `item_json`, and keyed by
+ entity for the same reason the thumbnails are: the surfaces that draw an
+ entity hold ids. An entity with no indexed media is absent rather than
+ guessed at, which is what lets a caller tell "not media" from "unknown".
+ """
+ unique = list(dict.fromkeys(entity_ids))
+ if not unique:
+ return {}
+ found: dict[str, str] = {}
+ with self._connect() as conn:
+ for chunk in _chunks(unique):
+ rows = conn.execute(
+ "SELECT entity_id, kind FROM media_items"
+ f" WHERE entity_id IN ({_marks(chunk)})",
+ chunk,
+ ).fetchall()
+ for row in rows:
+ if row["kind"]:
+ found[row["entity_id"]] = row["kind"]
+ return found
+
+ def media_origins(self, entity_ids: list[str]) -> dict[str, dict[str, str]]:
+ """How each of these entities came into the case: the route, and the act that
+ produced it where there was one.
+
+ Read off the two indexed columns rather than out of `item_json`, and keyed by
+ entity for the same reason `media_kinds` beside it is. A row recording no
+ route is left out, so a caller can tell "came in by no stated route" from "the
+ index has never seen this entity".
+ """
+ unique = list(dict.fromkeys(entity_ids))
+ if not unique:
+ return {}
+ found: dict[str, dict[str, str]] = {}
+ with self._connect() as conn:
+ for chunk in _chunks(unique):
+ rows = conn.execute(
+ "SELECT entity_id, source_type, source_op FROM media_items"
+ f" WHERE entity_id IN ({_marks(chunk)})",
+ chunk,
+ ).fetchall()
+ for row in rows:
+ if not row["source_type"]:
+ continue
+ origin = {"type": row["source_type"]}
+ if row["source_op"]:
+ origin["op"] = row["source_op"]
+ found[row["entity_id"]] = origin
+ return found
+
def page_media_items(
self,
*,
@@ -986,6 +2896,7 @@ class SqliteCase:
category: str | None = None,
folder: str | None = None,
gps: bool = False,
+ collected_only: bool = False,
sort: str = "newest",
direction: str | None = None,
limit: int = 200,
@@ -1006,6 +2917,16 @@ class SqliteCase:
base_where.append("search_text LIKE ? ESCAPE '\\'")
base_params.append(_like_contains(term))
+ # "Only what the case collected" scopes the whole answer rather than
+ # refining it, the counts included: a case where 150 of 200 files are
+ # extracted frames is the one this exists for, and a facet still
+ # advertising 30 collages the switch is hiding is a chooser that lies.
+ # `made_here_count` says how many it is taking out, over the same
+ # narrowing, so nothing disappears without a number.
+ scope_where = list(base_where)
+ if collected_only:
+ base_where.append(f"NOT {_MADE_HERE_SQL}")
+
# Category and GPS are two independent refinements of that base. Each
# one's own facet count leaves itself out and applies the other, so a
# chooser always reports what clicking it would actually yield.
@@ -1084,6 +3005,17 @@ class SqliteCase:
base_params,
).fetchone()[0]
)
+ # What the switch stands to take out, under the narrowing already set.
+ # Counted whether it is on or off: off, it is what turning it on would
+ # hide, and on, it is what is being hidden — one number, honest both ways,
+ # and the reason the switch can never empty a list silently.
+ made_here_count = int(
+ conn.execute(
+ "SELECT COUNT(*) FROM media_items"
+ f"{clause([*scope_where, *([category_sql] if category_sql else []), *(['has_gps = 1'] if gps else []), _MADE_HERE_SQL])}",
+ base_params,
+ ).fetchone()[0]
+ )
next_offset = offset + len(rows)
return {
@@ -1095,9 +3027,377 @@ class SqliteCase:
"folder_counts": folder_counts,
"category_counts": category_counts,
"gps_count": gps_count,
+ "made_here_count": made_here_count,
+ },
+ }
+
+ # -- temporal projection ---------------------------------------------
+
+ @staticmethod
+ def _timeline_scope(
+ *, categories: list[str], entity_id: str | None,
+ track: dict[str, Any] | None = None,
+ ) -> tuple[list[str], list[Any]]:
+ invalid = sorted(set(categories) - set(timeline_engine.ALL_CATEGORIES))
+ if invalid:
+ raise CaseError(f"unknown timeline category '{invalid[0]}'")
+ if not categories:
+ raise CaseError("at least one timeline category is required")
+ placeholders = ", ".join("?" for _ in categories)
+ where = [f"t.category IN ({placeholders})"]
+ params: list[Any] = list(categories)
+ if entity_id:
+ where.append(
+ "(t.owner_id = ? OR EXISTS ("
+ "SELECT 1 FROM links temporal_link"
+ " WHERE temporal_link.from_id = t.owner_id"
+ " AND temporal_link.to_id = ?"
+ " AND temporal_link.type IN ('about', 'at', 'cites')))"
+ )
+ params.extend((entity_id, entity_id))
+ query: dict[str, Any] = track if isinstance(track, dict) else {}
+ roles = [
+ value for value in query.get("roles", [])
+ if value in {"occurred", "observed", "valid", "unset"}
+ ] if isinstance(query.get("roles"), list) else []
+ if roles:
+ role_values = [value for value in roles if value != "unset"]
+ role_parts = []
+ if role_values:
+ role_parts.append(f"t.time_role IN ({_marks(role_values)})")
+ params.extend(role_values)
+ if "unset" in roles:
+ role_parts.append("t.time_role IS NULL")
+ where.append("(" + " OR ".join(role_parts) + ")")
+
+ raw_terms: dict[Any, Any] = (
+ query["terms"] if isinstance(query.get("terms"), dict) else {}
+ )
+ terms = {str(key): value for key, value in raw_terms.items()}
+ has_terms = any(value not in (None, "", [], False) for value in terms.values())
+ relation_value = query.get("relation")
+ relation = relation_value if isinstance(relation_value, str) else None
+ relation_key = relation or "any"
+ if has_terms:
+ def term(key: str) -> str:
+ return str(terms.get(key) or "")[:1000]
+
+ types = [part for part in term("type").split(",") if part][:100]
+ filed_by = [part for part in term("by").split(",") if part][:100]
+ entity_clause, entity_params = _entity_filters(
+ types=types or None,
+ status=(
+ term("status")
+ if term("status") in {"confirmed", "suggested"}
+ else None
+ ),
+ query=term("q") or None,
+ folder=term("folder") or None,
+ unfiled=term("unfiled").lower() == "true",
+ recursive=term("recursive").lower() == "true",
+ attr=term("attr") or None,
+ attr_value=term("value") or None,
+ linked=term("linked") or None,
+ unlinked=term("unlinked").lower() == "true",
+ since=term("since") or None,
+ until=term("until") or None,
+ filed_by=filed_by or None,
+ alias="scope_entity",
+ )
+ match = entity_clause.removeprefix(" WHERE ") or "1"
+ relation_types = {
+ "about": ("about",),
+ "place": ("at",),
+ "source": ("cites",),
+ "owner": (),
+ "any": ("about", "at", "cites"),
+ }.get(relation_key, ("about", "at", "cites"))
+ reaches = ["scope_entity.id = t.owner_id"] if relation_key in {"any", "owner"} else []
+ if relation_types:
+ reaches.append(
+ "EXISTS (SELECT 1 FROM links track_link"
+ " WHERE track_link.from_id = t.owner_id"
+ " AND track_link.to_id = scope_entity.id"
+ f" AND track_link.type IN ({_marks(list(relation_types))}))"
+ )
+ entity_params.extend(relation_types)
+ where.append(
+ "EXISTS (SELECT 1 FROM entities scope_entity WHERE "
+ f"({match}) AND ({' OR '.join(reaches)}))"
+ )
+ params.extend(entity_params)
+ elif relation in {"about", "place", "source"}:
+ connector = {"about": "about", "place": "at", "source": "cites"}[relation]
+ where.append(
+ "EXISTS (SELECT 1 FROM links track_link"
+ " WHERE track_link.from_id = t.owner_id AND track_link.type = ?)"
+ )
+ params.append(connector)
+ hidden_raw: list[Any] = (
+ query["hidden"] if isinstance(query.get("hidden"), list) else []
+ )
+ hidden = [str(value) for value in hidden_raw[:500] if value]
+ if hidden:
+ where.append(f"t.id NOT IN ({_marks(hidden)})")
+ params.extend(hidden)
+ return where, params
+
+ @staticmethod
+ def _timeline_item(
+ row: sqlite3.Row, connectors: dict[str, dict[str, list[dict[str, str]]]]
+ ) -> dict[str, Any]:
+ joined = connectors.get(row["owner_id"], {})
+ return {
+ "id": row["id"],
+ "owner_id": row["owner_id"],
+ "authority": row["authority"],
+ "category": row["category"],
+ "kind": row["kind"],
+ "label": row["label"],
+ "raw": row["raw"],
+ "earliest": row["earliest"],
+ "latest": row["latest"],
+ "precision": row["precision"],
+ "shape": row["shape"],
+ "time_role": row["time_role"],
+ "uncertain": bool(row["uncertain"]),
+ "approximate": bool(row["approximate"]),
+ "zone": row["zone"],
+ "sortable": bool(row["sortable"]),
+ "status": row["status"],
+ "confidence": row["confidence"],
+ "parse_error": row["parse_error"],
+ "owner_type": row["owner_type"],
+ "subjects": [entry["id"] for entry in joined.get("about", [])],
+ "places": [entry["id"] for entry in joined.get("at", [])],
+ "sources": [entry["id"] for entry in joined.get("cites", [])],
+ "subject_entities": joined.get("about", []),
+ "place_entities": joined.get("at", []),
+ "source_entities": joined.get("cites", []),
+ }
+
+ def timeline_page(
+ self,
+ *,
+ since: str | None = None,
+ until: str | None = None,
+ categories: list[str] | None = None,
+ entity_id: str | None = None,
+ include_undated: bool = True,
+ limit: int = 100,
+ cursor: str | None = None,
+ bucket: str | None = None,
+ track: dict[str, Any] | None = None,
+ spread: bool = False,
+ ) -> dict[str, Any]:
+ """Return one indexed, homogeneous page for Time or Timeline.
+
+ ``since`` is inclusive and ``until`` exclusive. Rows intersect the
+ window. A local timestamp has no UTC bounds and travels as ``unplaced``
+ until its timezone is known; ``undated`` is reserved for an absent value.
+
+ A page is the front of the window unless ``spread`` asks otherwise, and
+ the front of a lopsided case is one corner of it: 200 rows off 273 media
+ that pile into January leave February onward empty, which reads as
+ missing data rather than as an unread page. A spread read cuts the same
+ ordering into ``stride`` interleaved slices and serves one per page, so
+ the first page samples the whole window at the density the overview
+ draws, and the rest fill it in without a repeat or a gap.
+ """
+ if not 1 <= limit <= 200:
+ raise CaseError("a timeline page holds between 1 and 200 items")
+ selected = list(dict.fromkeys(categories or timeline_engine.DEFAULT_CATEGORIES))
+ base_where, base_params = self._timeline_scope(
+ categories=selected, entity_id=entity_id, track=track
+ )
+ dated = ["t.earliest IS NOT NULL"]
+ dated_params: list[Any] = []
+ if since:
+ dated.append("t.latest > ?")
+ dated_params.append(since)
+ if until:
+ dated.append("t.earliest < ?")
+ dated_params.append(until)
+ time_scope = "(" + " AND ".join(dated) + ")"
+ if include_undated:
+ time_scope = f"({time_scope} OR t.earliest IS NULL)"
+ where = [*base_where, time_scope]
+ params = [*base_params, *dated_params]
+
+ parsed_cursor = None if spread else _parse_timeline_cursor(cursor)
+ phase_cursor = _parse_timeline_phase(cursor) if spread else None
+ group_sql = "CASE WHEN t.earliest IS NULL THEN 1 ELSE 0 END"
+ stamp_sql = "COALESCE(t.earliest, '')"
+ if parsed_cursor is not None:
+ group, stamp, item_id = parsed_cursor
+ where.append(
+ f"({group_sql} > ? OR ({group_sql} = ? AND "
+ f"({stamp_sql} > ? OR ({stamp_sql} = ? AND t.id > ?))))"
+ )
+ params.extend((group, group, stamp, stamp, item_id))
+
+ clause = " WHERE " + " AND ".join(where)
+ total_clause = " WHERE " + " AND ".join([*base_where, time_scope])
+ total_params = [*base_params, *dated_params]
+ with self._connect() as conn:
+ extent_row = conn.execute(
+ "SELECT MIN(t.earliest) AS first, MAX(t.latest) AS last"
+ " FROM temporal_items t WHERE "
+ + " AND ".join([*base_where, "t.earliest IS NOT NULL"]),
+ base_params,
+ ).fetchone()
+ total = int(
+ conn.execute(
+ f"SELECT COUNT(*) FROM temporal_items t{total_clause}",
+ total_params,
+ ).fetchone()[0]
+ )
+ undated = int(
+ conn.execute(
+ "SELECT COUNT(*) FROM temporal_items t WHERE "
+ + " AND ".join([*base_where, "t.raw IS NULL"]),
+ base_params,
+ ).fetchone()[0]
+ )
+ unplaced = int(
+ conn.execute(
+ "SELECT COUNT(*) FROM temporal_items t WHERE "
+ + " AND ".join(
+ [*base_where, "t.raw IS NOT NULL", "t.earliest IS NULL"]
+ ),
+ base_params,
+ ).fetchone()[0]
+ )
+ # `stride` slices of the same ordering, one per page. A slice holds
+ # ceil((total - phase) / stride) rows, which never exceeds the limit the
+ # stride was derived from, so a spread page needs no overflow row to know
+ # it is full — the phase says whether another slice is owed.
+ stride, phase = phase_cursor or (
+ max(1, -(-total // limit)) if spread else 1, 0
+ )
+ if stride > 1:
+ rows = conn.execute(
+ "WITH ranked AS (SELECT t.id AS ranked_id,"
+ f" ROW_NUMBER() OVER (ORDER BY {group_sql}, {stamp_sql}, t.id) - 1 AS rn"
+ f" FROM temporal_items t{clause})"
+ " SELECT t.*, e.label, e.type AS owner_type FROM ranked"
+ " JOIN temporal_items t ON t.id = ranked.ranked_id"
+ " JOIN entities e ON e.id = t.owner_id"
+ " WHERE ranked.rn % ? = ? ORDER BY ranked.rn LIMIT ?",
+ (*params, stride, phase, limit),
+ ).fetchall()
+ else:
+ rows = conn.execute(
+ "SELECT t.*, e.label, e.type AS owner_type FROM temporal_items t"
+ " JOIN entities e ON e.id = t.owner_id"
+ f"{clause} ORDER BY {group_sql}, {stamp_sql}, t.id LIMIT ?",
+ (*params, limit + 1),
+ ).fetchall()
+
+ page_rows = rows[:limit]
+ owner_ids = list(dict.fromkeys(str(row["owner_id"]) for row in page_rows))
+ connectors: dict[str, dict[str, list[dict[str, str]]]] = {}
+ if owner_ids:
+ placeholders = ", ".join("?" for _ in owner_ids)
+ for link in conn.execute(
+ "SELECT temporal_link.from_id, temporal_link.to_id,"
+ " temporal_link.type, target.label, target.type AS entity_type"
+ " FROM links temporal_link JOIN entities target"
+ " ON target.id = temporal_link.to_id"
+ f" WHERE temporal_link.from_id IN ({placeholders})"
+ " AND temporal_link.type IN ('about', 'at', 'cites')"
+ " ORDER BY temporal_link.rowid",
+ owner_ids,
+ ).fetchall():
+ by_type = connectors.setdefault(link["from_id"], {})
+ by_type.setdefault(link["type"], []).append({
+ "id": link["to_id"],
+ "label": link["label"],
+ "type": link["entity_type"],
+ })
+
+ buckets: list[dict[str, Any]] = []
+ buckets_truncated = False
+ if bucket is not None:
+ # `hour` cuts on the "T" boundary of the stored instant, which is what
+ # lets a window zoomed onto a single day still read as a histogram
+ # rather than as one column.
+ widths = {"year": 4, "month": 7, "day": 10, "hour": 13}
+ if bucket not in widths:
+ raise CaseError("a timeline bucket must be year, month, day or hour")
+ bucket_where = [*base_where, *dated]
+ bucket_params = [*base_params, *dated_params]
+ # A bucket also reports where its own entries actually sit. The period
+ # it names is the coarse thing — six August rows all falling in the
+ # first week are not "August" — and the overview draws each bar across
+ # that inner span, so the bars and the visible-range brush answer the
+ # same question on the same instants.
+ bucket_rows = conn.execute(
+ "SELECT substr(t.earliest, 1, ?) AS start, t.category,"
+ " COUNT(*) AS count, MIN(t.earliest) AS first, MAX(t.latest) AS last"
+ " FROM temporal_items t WHERE "
+ + " AND ".join(bucket_where)
+ + " GROUP BY start, t.category ORDER BY start, t.category LIMIT 3001",
+ (widths[bucket], *bucket_params),
+ ).fetchall()
+ grouped: dict[str, dict[str, Any]] = {}
+ for row in bucket_rows:
+ start = str(row["start"])
+ if start not in grouped and len(grouped) >= 1000:
+ buckets_truncated = True
+ break
+ target = grouped.setdefault(
+ start,
+ {"start": start, "count": 0, "categories": {}, "first": None, "last": None},
+ )
+ count = int(row["count"])
+ target["count"] += count
+ target["categories"][str(row["category"])] = count
+ first = row["first"]
+ last = row["last"]
+ if first is not None and (target["first"] is None or first < target["first"]):
+ target["first"] = first
+ # An open-ended row has no `latest`; the bar then reaches as far as
+ # what it is known to start at, never further.
+ reach = last if last is not None else first
+ if reach is not None and (target["last"] is None or reach > target["last"]):
+ target["last"] = reach
+ buckets = list(grouped.values())
+
+ next_cursor = None
+ if spread:
+ if phase + 1 < stride:
+ next_cursor = _timeline_phase_cursor(stride, phase + 1)
+ elif len(rows) > limit and page_rows:
+ last = page_rows[-1]
+ next_cursor = _timeline_cursor(
+ 1 if last["earliest"] is None else 0,
+ str(last["earliest"] or ""),
+ str(last["id"]),
+ )
+ return {
+ "items": [self._timeline_item(row, connectors) for row in page_rows],
+ "next_cursor": next_cursor,
+ "total": total,
+ "undated": undated,
+ "unplaced": unplaced,
+ "buckets": buckets,
+ "buckets_truncated": buckets_truncated,
+ "extent": {
+ "from": extent_row["first"] if extent_row is not None else None,
+ "to": extent_row["last"] if extent_row is not None else None,
},
}
+ def rebuild_temporal_projection(self) -> int:
+ """Explicitly recreate every derived temporal row in one transaction."""
+ return self._write(_rebuild_temporal_projection_conn)
+
+ def temporal_projection_status(self) -> dict[str, int | bool]:
+ """Report whether every derived temporal row still matches its authority."""
+ with self._connect() as conn:
+ return _temporal_projection_status_conn(conn)
+
def count_entities(self) -> int:
"""Entity total via one indexed count — the case switcher's per-case
badge without materialising the graph."""
@@ -1153,6 +3453,7 @@ class SqliteCase:
source or None,
),
)
+ _sync_entity_temporal(conn, entity)
self._touch(conn)
return entity
@@ -1186,15 +3487,153 @@ class SqliteCase:
entity_id,
),
)
+ _sync_entity_temporal(conn, entity)
self._touch(conn)
return entity
return self._write(op)
+ def save_temporal_claim(
+ self,
+ *,
+ entity_id: str | None,
+ label: str,
+ attrs: dict[str, Any],
+ connectors: dict[str, list[str]] | None,
+ by: str,
+ status: EntityStatus = "confirmed",
+ ) -> dict[str, Any]:
+ """Create or replace a Claim and selected connectors atomically."""
+ if connectors is not None:
+ invalid = set(connectors) - set(link_engine.CLAIM_CONNECTION_TYPES)
+ if invalid:
+ raise CaseError(f"unknown Claim connector '{sorted(invalid)[0]}'")
+
+ def op(conn: sqlite3.Connection) -> dict[str, Any]:
+ claim_id = entity_id or _new_id("e")
+ now = _now()
+ existing = conn.execute(
+ "SELECT * FROM entities WHERE id = ?", (claim_id,)
+ ).fetchone()
+ if entity_id is not None:
+ if existing is None:
+ raise CaseError(f"entity '{claim_id}' not found")
+ if existing["type"] != "claim":
+ raise CaseError(f"entity '{claim_id}' is not a Claim")
+ conn.execute(
+ "UPDATE entities SET label = ?, attrs_json = ?, folder = ?,"
+ " search_text = ?, prov_status = ? WHERE id = ?",
+ (
+ label,
+ json.dumps(attrs, ensure_ascii=False),
+ _folder_of(attrs),
+ _entity_search_text("claim", label, attrs),
+ status,
+ claim_id,
+ ),
+ )
+ provenance = {
+ "by": existing["prov_by"],
+ "at": existing["prov_at"],
+ "status": status,
+ }
+ if existing["prov_source"] is not None:
+ provenance["source"] = existing["prov_source"]
+ else:
+ conn.execute(
+ "INSERT INTO entities"
+ "(id, type, label, attrs_json, folder, search_text,"
+ " prov_by, prov_at, prov_status, prov_source)"
+ " VALUES(?, 'claim', ?, ?, ?, ?, ?, ?, ?, NULL)",
+ (
+ claim_id,
+ label,
+ json.dumps(attrs, ensure_ascii=False),
+ _folder_of(attrs),
+ _entity_search_text("claim", label, attrs),
+ by,
+ now,
+ status,
+ ),
+ )
+ provenance = {"by": by, "at": now, "status": status}
+
+ if connectors is not None:
+ for type_, raw_targets in connectors.items():
+ targets = [
+ target
+ for target in dict.fromkeys(raw_targets)
+ if target != claim_id
+ ]
+ present: set[str] = set()
+ if targets:
+ placeholders = ", ".join("?" for _ in targets)
+ present = {
+ row["id"]
+ for row in conn.execute(
+ f"SELECT id FROM entities WHERE id IN ({placeholders})",
+ targets,
+ )
+ }
+ missing = [target for target in targets if target not in present]
+ if missing:
+ raise CaseError(f"entity '{missing[0]}' not found")
+ existing_links = {
+ row["to_id"]: row
+ for row in conn.execute(
+ "SELECT * FROM links WHERE from_id = ? AND type = ?",
+ (claim_id, type_),
+ ).fetchall()
+ }
+ wanted = set(targets)
+ stale = [
+ (row["id"],)
+ for target, row in existing_links.items()
+ if target not in wanted
+ ]
+ if stale:
+ conn.executemany("DELETE FROM links WHERE id = ?", stale)
+ for target in targets:
+ if target in existing_links:
+ continue
+ conn.execute(
+ "INSERT INTO links"
+ "(id, from_id, to_id, type, prov_by, prov_at,"
+ " prov_status, prov_source)"
+ " VALUES(?, ?, ?, ?, ?, ?, ?, NULL)",
+ (_new_id("l"), claim_id, target, type_, by, _now(), status),
+ )
+
+ entity = {
+ "id": claim_id,
+ "type": "claim",
+ "label": label,
+ "attrs": attrs,
+ "provenance": provenance,
+ }
+ _sync_entity_temporal(conn, entity)
+ self._touch(conn)
+ links = conn.execute(
+ "SELECT * FROM links WHERE from_id = ?"
+ " AND type IN ('about', 'at', 'cites') ORDER BY rowid",
+ (claim_id,),
+ ).fetchall()
+ return {"entity": entity, "links": [self._link(row) for row in links]}
+
+ return self._write(op)
+
def remove_entity(self, entity_id: str) -> None:
def op(conn: sqlite3.Connection) -> None:
if conn.execute("SELECT 1 FROM entities WHERE id = ?", (entity_id,)).fetchone() is None:
raise CaseError(f"entity '{entity_id}' not found")
+ galleries = [
+ row["entity_id"]
+ for row in conn.execute(
+ "SELECT entity_id FROM entity_images"
+ " WHERE media_id = ? AND is_primary = 1",
+ (entity_id,),
+ ).fetchall()
+ ]
# Drop directly incident edges first: foreign keys forbid dangling
# links, and this is the repository-level cleanup, not the
# dependency-aware deep delete (that lives in engine/links.py).
@@ -1202,6 +3641,8 @@ class SqliteCase:
"DELETE FROM links WHERE from_id = ? OR to_id = ?", (entity_id, entity_id)
)
conn.execute("DELETE FROM entities WHERE id = ?", (entity_id,))
+ for gallery_id in galleries:
+ self._ensure_entity_image_primary(conn, gallery_id)
self._touch(conn)
self._write(op)
@@ -1322,9 +3763,17 @@ class SqliteCase:
if status not in ("confirmed", "suggested"):
status = row["prov_status"]
type_ = patch.get("type") or row["type"]
+ # Membership, not truthiness: `None` clears the rating back to "not
+ # assessed", and `-1` (refuted) is a value like any other. Which
+ # ordinals are legal, and which edges may carry one at all, is the
+ # vocabulary's call in `engine/links.py`.
+ confidence = patch["confidence"] if "confidence" in patch else row["confidence"]
+ # Membership again: `None` clears the qualifier, an absent key leaves it.
+ nature = patch["nature"] if "nature" in patch else row["nature"]
conn.execute(
- "UPDATE links SET prov_status = ?, type = ? WHERE id = ?",
- (status, type_, link_id),
+ "UPDATE links SET prov_status = ?, type = ?, confidence = ?, nature = ?"
+ " WHERE id = ?",
+ (status, type_, confidence, nature, link_id),
)
self._touch(conn)
updated = conn.execute("SELECT * FROM links WHERE id = ?", (link_id,)).fetchone()
@@ -1576,6 +4025,7 @@ class SqliteCase:
prov.get("source"),
),
)
+ _sync_entity_temporal(conn, entity)
present = {
r["id"]
for r in conn.execute("SELECT id FROM entities")
@@ -1587,12 +4037,16 @@ class SqliteCase:
prov = link.get("provenance") or {}
conn.execute(
"INSERT OR REPLACE INTO links"
- "(id, from_id, to_id, type, prov_by, prov_at, prov_status, prov_source)"
- " VALUES(?, ?, ?, ?, ?, ?, ?, ?)",
+ "(id, from_id, to_id, type, prov_by, prov_at, prov_status,"
+ " prov_source, confidence)"
+ " VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?)",
(
link["id"], link["from"], link["to"], link["type"],
prov.get("by", "user"), prov.get("at", _now()),
prov.get("status", "confirmed"), prov.get("source"),
+ # restoring an eliminated candidate must bring back the
+ # elimination: "I ruled these eleven out" is the finding
+ link.get("confidence"),
),
)
kept += 1
@@ -1930,6 +4384,7 @@ def _import_graph(conn: sqlite3.Connection, data: dict[str, Any], report: Migrat
prov.get("source"),
),
)
+ _sync_entity_temporal(conn, entity)
entity_ids.add(entity["id"])
for link in data.get("links", []):
if link["from"] not in entity_ids or link["to"] not in entity_ids:
diff --git a/src/azimut/workspace.py b/src/azimut/workspace.py
index 63241cf..6ec4af1 100644
--- a/src/azimut/workspace.py
+++ b/src/azimut/workspace.py
@@ -110,28 +110,6 @@ def _case_lock(path: Path) -> threading.RLock:
return lock
-# Extensible vocabulary (spec §5); free strings are accepted, these are the
-# well-known ones the UI knows how to render.
-ENTITY_TYPES = (
- "person",
- "organization",
- "alias",
- "account",
- "email",
- "phone",
- "domain",
- "ip",
- "vehicle",
- "place",
- "capture",
- "event",
- "media",
- "proof",
- "note",
- "bookmark",
-)
-
-
def _now() -> str:
return datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
@@ -756,9 +734,20 @@ class Case:
folder: str | None = None,
unfiled: bool = False,
recursive: bool = False,
+ attr: str | None = None,
+ attr_value: str | None = None,
+ linked: str | None = None,
+ unlinked: bool = False,
+ since: str | None = None,
+ until: str | None = None,
+ filed_by: list[str] | None = None,
+ temporal_since: str | None = None,
+ temporal_until: str | None = None,
+ temporal_categories: list[str] | None = None,
+ order: str = "",
) -> dict[str, Any]:
"""A bounded, filtered page of the catalog (Step 5), paged with an indexed
- rowid keyset."""
+ keyset over the ordering asked for."""
return self._graph().page_entities(
limit=limit,
cursor=cursor,
@@ -768,27 +757,119 @@ class Case:
folder=folder,
unfiled=unfiled,
recursive=recursive,
+ attr=attr,
+ attr_value=attr_value,
+ linked=linked,
+ unlinked=unlinked,
+ since=since,
+ until=until,
+ filed_by=filed_by,
+ temporal_since=temporal_since,
+ temporal_until=temporal_until,
+ temporal_categories=temporal_categories,
+ order=order,
)
def catalog_summary(self) -> dict[str, Any]:
- """Total plus per-type, per-status and per-folder counts."""
+ """Total plus per-type, per-status, per-folder and per-filer counts."""
return self._graph().catalog_summary()
+ def attr_facets(
+ self, *, types: list[str] | None = None, limit: int = 50
+ ) -> list[dict[str, Any]]:
+ """Which stored fields these entities hold, and which values, as a menu."""
+ return self._graph().attr_facets(types=types, limit=limit)
+
def list_links(self) -> list[dict[str, Any]]:
return self._graph().list_links()
+ def entity_images(self, entity_id: str) -> list[dict[str, Any]]:
+ return self._graph().entity_images(entity_id)
+
+ def entity_image_thumbs(self, entity_ids: list[str]) -> dict[str, str]:
+ return self._graph().entity_image_thumbs(entity_ids)
+
+ def entity_images_touching(self, entity_ids: list[str]) -> list[dict[str, Any]]:
+ return self._graph().entity_images_touching(entity_ids)
+
+ def add_entity_images(self, entity_id: str, media_ids: list[str]) -> int:
+ return self._graph().add_entity_images(entity_id, media_ids)
+
+ def add_entity_image_file(
+ self,
+ entity_id: str,
+ image_id: str,
+ path: str,
+ thumbnail: str,
+ title: str,
+ ) -> None:
+ self._graph().add_entity_image_file(
+ entity_id, image_id, path, thumbnail, title
+ )
+
+ def set_primary_entity_image(self, entity_id: str, image_id: str) -> None:
+ self._graph().set_primary_entity_image(entity_id, image_id)
+
+ def remove_entity_image(self, entity_id: str, image_id: str) -> dict[str, Any]:
+ return self._graph().remove_entity_image(entity_id, image_id)
+
+ def reinsert_entity_images(self, rows: list[dict[str, Any]]) -> dict[str, int]:
+ return self._graph().reinsert_entity_images(rows)
+
def upsert_media_item(self, item: dict[str, Any], *, entity_id: str | None = None) -> None:
self._graph().upsert_media_item(item, entity_id=entity_id)
def remove_media_item(self, path: str) -> None:
self._graph().remove_media_item(path)
+ def timeline_page(
+ self,
+ *,
+ since: str | None = None,
+ until: str | None = None,
+ categories: list[str] | None = None,
+ entity_id: str | None = None,
+ include_undated: bool = True,
+ limit: int = 100,
+ cursor: str | None = None,
+ bucket: str | None = None,
+ track: dict[str, Any] | None = None,
+ spread: bool = False,
+ ) -> dict[str, Any]:
+ return self._graph().timeline_page(
+ since=since,
+ until=until,
+ categories=categories,
+ entity_id=entity_id,
+ include_undated=include_undated,
+ limit=limit,
+ cursor=cursor,
+ bucket=bucket,
+ track=track,
+ spread=spread,
+ )
+
+ def rebuild_temporal_projection(self) -> int:
+ return self._graph().rebuild_temporal_projection()
+
+ def temporal_projection_status(self) -> dict[str, int | bool]:
+ return self._graph().temporal_projection_status()
+
def list_media_items(self) -> list[dict[str, Any]]:
return self._graph().list_media_items()
def media_items_by_paths(self, paths: list[str]) -> list[dict[str, Any]]:
return self._graph().media_items_by_paths(paths)
+ def media_thumbs(self, entity_ids: list[str]) -> dict[str, str]:
+ return self._graph().media_thumbs(entity_ids)
+
+ def media_kinds(self, entity_ids: list[str]) -> dict[str, str]:
+ return self._graph().media_kinds(entity_ids)
+
+ def media_origins(self, entity_ids: list[str]) -> dict[str, dict[str, str]]:
+ return self._graph().media_origins(entity_ids)
+
def page_media_items(
self,
*,
@@ -797,6 +878,7 @@ class Case:
category: str | None = None,
folder: str | None = None,
gps: bool = False,
+ collected_only: bool = False,
sort: str = "newest",
direction: str | None = None,
limit: int = 200,
@@ -808,6 +890,7 @@ class Case:
category=category,
folder=folder,
gps=gps,
+ collected_only=collected_only,
sort=sort,
direction=direction,
limit=limit,
@@ -826,6 +909,100 @@ class Case:
def count_incident_links(self, *, exclude_types: list[str]) -> dict[str, int]:
return self._graph().count_incident_links(exclude_types=exclude_types)
+ def rank_entities(
+ self,
+ *,
+ limit: int = 200,
+ types: list[str] | None = None,
+ exclude_types: list[str] | None = None,
+ status: EntityStatus | None = None,
+ query: str | None = None,
+ folder: str | None = None,
+ unfiled: bool = False,
+ recursive: bool = False,
+ attr: str | None = None,
+ attr_value: str | None = None,
+ linked: str | None = None,
+ unlinked_only: bool = False,
+ since: str | None = None,
+ until: str | None = None,
+ filed_by: list[str] | None = None,
+ temporal_since: str | None = None,
+ temporal_until: str | None = None,
+ temporal_categories: list[str] | None = None,
+ link_types: list[str] | None = None,
+ order: str = "degree",
+ ) -> dict[str, Any]:
+ return self._graph().rank_entities(
+ limit=limit, types=types, exclude_types=exclude_types, status=status,
+ query=query, folder=folder, unfiled=unfiled, recursive=recursive,
+ attr=attr, attr_value=attr_value, linked=linked, unlinked_only=unlinked_only,
+ since=since, until=until, filed_by=filed_by,
+ temporal_since=temporal_since, temporal_until=temporal_until,
+ temporal_categories=temporal_categories,
+ link_types=link_types, order=order,
+ )
+
+ def entities_by_ids(self, ids: list[str]) -> list[dict[str, Any]]:
+ return self._graph().entities_by_ids(ids)
+
+ def labels_of_type(self, type_: str) -> list[tuple[str, str]]:
+ return self._graph().labels_of_type(type_)
+
+ def links_among(
+ self, ids: list[str], *, types: list[str] | None = None
+ ) -> list[dict[str, Any]]:
+ return self._graph().links_among(ids, types=types)
+
+ def links_touching(
+ self,
+ ids: list[str],
+ *,
+ types: list[str] | None = None,
+ exclude_types: list[str] | None = None,
+ end_types: list[str] | None = None,
+ ) -> list[dict[str, Any]]:
+ return self._graph().links_touching(
+ ids, types=types, exclude_types=exclude_types, end_types=end_types
+ )
+
+ def degrees_of(
+ self,
+ ids: list[str],
+ *,
+ types: list[str] | None = None,
+ exclude_types: list[str] | None = None,
+ ) -> dict[str, int]:
+ return self._graph().degrees_of(ids, types=types, exclude_types=exclude_types)
+
+
+ def graph_pins(self, lens: str) -> dict[str, tuple[float, float]]:
+ return self._graph().graph_pins(lens)
+
+ def pin_entities(self, lens: str, pins: dict[str, tuple[float, float]]) -> int:
+ return self._graph().pin_entities(lens, pins)
+
+ def unpin_entities(self, lens: str, ids: list[str]) -> int:
+ return self._graph().unpin_entities(lens, ids)
+
+ def clear_graph_pins(self, lens: str) -> int:
+ return self._graph().clear_graph_pins(lens)
+
+ def list_analysis_views(self) -> list[dict[str, Any]]:
+ return self._graph().list_analysis_views()
+
+ def get_analysis_view(self, view_id: str) -> dict[str, Any] | None:
+ return self._graph().get_analysis_view(view_id)
+
+ def save_analysis_view(self, view: dict[str, Any]) -> dict[str, Any]:
+ return self._graph().save_analysis_view(view)
+
+ def remove_analysis_view(self, view_id: str) -> dict[str, Any] | None:
+ return self._graph().remove_analysis_view(view_id)
+
+ def reinsert_analysis_views(self, views: list[dict[str, Any]]) -> int:
+ return self._graph().reinsert_analysis_views(views)
+
def get_entity(self, entity_id: str) -> dict[str, Any] | None:
return self._graph().get_entity(entity_id)
@@ -1035,6 +1212,25 @@ class Case:
self._follow_named_artifact_rename(entity_id, patch)
return self._graph().update_entity(entity_id, patch)
+ def save_temporal_claim(
+ self,
+ *,
+ entity_id: str | None,
+ label: str,
+ attrs: dict[str, Any],
+ connectors: dict[str, list[str]] | None,
+ by: str,
+ status: EntityStatus = "confirmed",
+ ) -> dict[str, Any]:
+ return self._graph().save_temporal_claim(
+ entity_id=entity_id,
+ label=label,
+ attrs=attrs,
+ connectors=connectors,
+ by=by,
+ status=status,
+ )
+
def _follow_named_artifact_rename(self, entity_id: str, patch: dict[str, Any]) -> None:
"""Keep named tool files aligned with a label edited from Details.
diff --git a/tests/bigcase.py b/tests/bigcase.py
index 34c6892..817fe75 100644
--- a/tests/bigcase.py
+++ b/tests/bigcase.py
@@ -25,7 +25,7 @@ from azimut.workspace import Case, _slugify
# entity/link types stay valid" rule the ontology promises.
_SEMANTIC_TYPES = (
"person", "organization", "account", "email", "phone", "domain", "place",
- "event", "vehicle", "alias",
+ "ip", "vehicle", "vessel", "aircraft", "structure",
)
_UNKNOWN_TYPES = ("spacecraft", "widget", "signal")
_LINK_TYPES = ("appears-in", "located-at", "owns", "mentions", "posted", "same-as")
@@ -200,7 +200,7 @@ def build_big_case(
folder = pick_folder()
if folder:
attrs["folder"] = folder
- if etype in ("place", "event") and rng.random() < 0.5:
+ if etype == "place" and rng.random() < 0.5:
attrs["lat"] = round(rng.uniform(-60, 60), 6)
attrs["lon"] = round(rng.uniform(-180, 180), 6)
add({"id": eid, "type": etype, "label": f"{etype.title()} {i}", "attrs": attrs})
@@ -228,7 +228,7 @@ def build_big_case(
if kind == "proof":
attrs = {"spec": f"proofs/proof_{i:06d}.json"}
elif kind == "post":
- attrs = {"draft": f"exports/draft_{i:06d}.json"}
+ attrs = {"draft": f".drafts/draft_{i:06d}.json"}
else:
attrs = {"spec": f"inspect/session_{i:06d}.json"}
folder = pick_folder()
diff --git a/tests/conftest.py b/tests/conftest.py
index f0c2d47..b05e7f9 100644
--- a/tests/conftest.py
+++ b/tests/conftest.py
@@ -37,8 +37,15 @@ def offline_reverse_geocode(monkeypatch):
care about the located path stub ``geo.reverse_geocode`` themselves; every
other one gets the offline verdict (``failed``), which is what the app is
designed to survive.
+
+ Nominatim's one-per-second floor is neutralized with it: it is a politeness
+ rule about a network nobody here reaches, and paying it would make the suite
+ wait seconds per lookup. The tests that check the floor itself restore the
+ real pacer.
"""
monkeypatch.setattr(geo, "reverse_geocode", lambda lat, lon, timeout=8, language=None: None)
+ monkeypatch.setattr(geo, "_pace", lambda: None)
+ geo._reset_pace()
def _let_the_worker_finish() -> None:
diff --git a/tests/fullcase.py b/tests/fullcase.py
index ddf6c61..28eabd9 100644
--- a/tests/fullcase.py
+++ b/tests/fullcase.py
@@ -47,6 +47,22 @@ class FullCase:
note: str = "" # its case-relative path
place_id: str = ""
grid: str = ""
+ person_id: str = ""
+ org_id: str = ""
+ entity_photo_id: str = ""
+ entity_photo: str = ""
+ entity_photo_thumb: str = ""
+ account_id: str = ""
+ network_id: str = ""
+ vessel_id: str = ""
+ structure_id: str = ""
+ model_id: str = ""
+ bookmark_id: str = ""
+ claim_id: str = ""
+ counted_id: str = "" # the statement that counts a model rather than objects
+ pinned_id: str = "" # a node placed by hand on the graph canvas
+ analysis_view_id: str = "" # a named Board reading stored with the case
+ timeline_view_id: str = "" # a named Timeline reading stored with the case
entity_types: set[str] = field(default_factory=set)
@@ -130,6 +146,73 @@ def build_full_case(client, name: str = "Full case") -> FullCase:
)
assert related.status_code == 200, related.text
+ # -- the hand-made vocabulary: one entity per family, and the verbs ------
+ # These own nothing on disk, so they are here for the registry and bundle
+ # gates rather than for the file ones: a type that reaches the graph without
+ # deciding what it owns fails `test_every_type_in_a_full_case_declares...`.
+ def entity(type_: str, label: str, attrs: dict | None = None) -> str:
+ res = client.post(
+ f"/api/cases/{case_id}/entities",
+ json={"type": type_, "label": label, "attrs": attrs or {}},
+ )
+ assert res.status_code == 200, res.text
+ return res.json()["id"]
+
+ full.person_id = entity("person", "A. Nadeau")
+ full.org_id = entity("organization", "Northwind Shipping")
+ full.account_id = entity("account", "@harbourwatch", {})
+ full.network_id = entity("network", "203.0.113.0/24", {"asn": "AS64496"})
+ full.vessel_id = entity(
+ "vessel", "MV Aurora", {"imo": "9074729", "condition": "intact"}
+ )
+ full.structure_id = entity(
+ "structure", "Quay 4 warehouse", {"kind": "warehouse", "condition": "damaged"}
+ )
+ # A model rather than an object, and the one member of the `class` family: the
+ # bundle has to carry it, and the vessel above has to be able to say it is one.
+ full.model_id = entity(
+ "equipment-type", "Handysize bulker",
+ {"category": "cargo vessel", "aliases": "handy bulker"},
+ )
+
+ gallery = client.post(
+ f"/api/cases/{case_id}/entities/{full.person_id}/images",
+ json={"media_ids": [photo_entity["id"]]},
+ )
+ assert gallery.status_code == 200, gallery.text
+ assert gallery.json()["images"][0]["primary"] is True
+
+ direct_photo = client.post(
+ f"/api/cases/{case_id}/entities/{full.org_id}/images/upload",
+ files={
+ "file": (
+ "organization-logo.png",
+ io.BytesIO(_png(color=(70, 90, 120))),
+ "image/png",
+ )
+ },
+ )
+ assert direct_photo.status_code == 200, direct_photo.text
+ direct_item = direct_photo.json()["images"][0]
+ full.entity_photo_id = direct_item["id"]
+ full.entity_photo = direct_item["path"]
+ full.entity_photo_thumb = direct_item["thumbnail"]
+
+ for from_id, to_id, verb in (
+ (full.person_id, full.account_id, "owns"),
+ (full.person_id, full.network_id, "owns"),
+ (full.org_id, full.vessel_id, "owns"),
+ (full.account_id, photo_entity["id"], "posted"),
+ (full.vessel_id, photo_entity["id"], "appears-in"),
+ (full.vessel_id, full.model_id, "instance-of"),
+ (full.structure_id, full.place_id, "sited-at"),
+ ):
+ stated = client.post(
+ f"/api/cases/{case_id}/links",
+ json={"from_id": from_id, "to_id": to_id, "type": verb},
+ )
+ assert stated.status_code == 200, f"{verb}: {stated.text}"
+
# -- proof: one panel from the case, one pasted image ---------------------
pasted = _png(size=(40, 30), color=(220, 220, 40))
asset_name = f"{hashlib.sha256(pasted).hexdigest()[:16]}.png"
@@ -173,6 +256,58 @@ def build_full_case(client, name: str = "Full case") -> FullCase:
full.note = note.json()["attrs"]["path"]
client.put(f"/api/cases/{case_id}/notes", json={"text": "# Full case\n\nRunning notes.\n"})
+ # -- a claim, with its three dedicated connectors --------------------------
+ # The reified statement carries one confidence for the whole assertion. Its
+ # connectors only identify the subject, place and supporting material.
+ # The source it rests on, graded on the axis that is never multiplied into the
+ # edge's own rating: the bundle has to carry both and keep them apart.
+ full.bookmark_id = entity(
+ "bookmark",
+ "Harbour watch thread",
+ {
+ "url": "https://example.test/thread/48",
+ "fetched_at": "2026-08-01T09:12:00+00:00",
+ "archive_url": "https://web.archive.test/web/2026/https://example.test/thread/48",
+ "reliability": "B",
+ },
+ )
+
+ full.claim_id = entity(
+ "claim",
+ "Where was the photo taken?",
+ {
+ "when": "2026-08-01T09:12:00Z",
+ "time_role": "observed",
+ "method": "spans counted against Esri imagery",
+ "confidence": "probable",
+ },
+ )
+ for to_id, verb in (
+ (photo_entity["id"], "about"),
+ (full.place_id, "at"),
+ (full.note_id, "cites"),
+ (full.bookmark_id, "cites"),
+ ):
+ stated = client.post(
+ f"/api/cases/{case_id}/links",
+ json={"from_id": full.claim_id, "to_id": to_id, "type": verb},
+ )
+ assert stated.status_code == 200, f"{verb}: {stated.text}"
+
+ # The counted statement: how many of one model, in what state. One kind of thing
+ # per claim, so the number on the node is never ambiguous about what it counts.
+ full.counted_id = entity(
+ "claim",
+ "Two Handysize bulkers berthed at Quay 4",
+ {"count": 2, "condition": "intact", "confidence": "possible"},
+ )
+ for to_id, verb in ((full.model_id, "about"), (full.place_id, "at")):
+ stated = client.post(
+ f"/api/cases/{case_id}/links",
+ json={"from_id": full.counted_id, "to_id": to_id, "type": verb},
+ )
+ assert stated.status_code == 200, f"{verb}: {stated.text}"
+
grid = client.put(
f"/api/cases/{case_id}/search-grids/north-sweep",
json={
@@ -192,6 +327,59 @@ def build_full_case(client, name: str = "Full case") -> FullCase:
assert grid.status_code == 200, grid.text
full.grid = f".search/{grid.json()['name']}.json"
+ # -- the graph as the analyst arranged it ---------------------------------
+ # Not an artifact and not an assertion: where a node was dragged to, in one
+ # reading. Planted here so the trash and bundle gates cover it — a pin has to
+ # travel with the case and die with the entity it places.
+ full.pinned_id = full.person_id
+ pinned = client.put(
+ f"/api/cases/{case_id}/graph/pins",
+ json={"lens": "all", "pins": [{"id": full.person_id, "x": -220.5, "y": 118.25}]},
+ )
+ assert pinned.status_code == 200, pinned.text
+
+ saved_view = client.post(
+ f"/api/cases/{case_id}/analysis-views",
+ json={
+ "name": "People in review",
+ "mode": "live",
+ "surface": "board",
+ "spec": {
+ "query": {
+ "filter": {"families": ["actor"], "status": "suggested"},
+ "terms": {"type": "person,organization", "status": "suggested"},
+ },
+ "board": {"order": "-created", "sortKey": "created", "sortDesc": True},
+ },
+ },
+ )
+ assert saved_view.status_code == 200, saved_view.text
+ full.analysis_view_id = saved_view.json()["id"]
+
+ timeline_view = client.post(
+ f"/api/cases/{case_id}/analysis-views",
+ json={
+ "name": "Chronology in review",
+ "mode": "live",
+ "surface": "timeline",
+ "spec": {
+ "timeline": {
+ "from": "2026-08-01",
+ "to": "2026-08-02",
+ "tracks": [
+ {
+ "id": "events",
+ "label": "Events",
+ "categories": ["statement"],
+ }
+ ],
+ }
+ },
+ },
+ )
+ assert timeline_view.status_code == 200, timeline_view.text
+ full.timeline_view_id = timeline_view.json()["id"]
+
# Enrichment and thumbnails were queued along the way; let them land, or the
# caller's first delete races a background write into the same case.
workqueue.wait_until_idle(timeout=20)
diff --git a/tests/schema_rewind.py b/tests/schema_rewind.py
new file mode 100644
index 0000000..8f85f7f
--- /dev/null
+++ b/tests/schema_rewind.py
@@ -0,0 +1,81 @@
+"""Take a `case.db` back to an older shape, so a migration can be run for real.
+
+A test database is born at the current schema, so rewinding it has to undo the
+*shape* and not only the version number: every table, index and column a later
+migration creates is already there, and replaying that step onto its own work
+fails on an object that exists. One entry per object added after the version
+being rewound to, which is what keeps this file the single place a new migration
+has to be remembered.
+
+Columns are dropped by rebuilding the table rather than with `ALTER TABLE ...
+DROP COLUMN`, which needs SQLite 3.35 (2021): the backend matrix runs the Python
+3.11 floor against whatever libsqlite3 each platform ships, and a test needing a
+newer SQLite than the code does is a false alarm waiting to fire on one OS.
+"""
+
+from __future__ import annotations
+
+import sqlite3
+from contextlib import closing
+from pathlib import Path
+
+#: Objects created after schema 7, dropped newest first. A migration that adds a
+#: table or an index adds its line here in the same change.
+_AFTER_7 = (
+ "DROP TABLE IF EXISTS temporal_items",
+ "DROP INDEX IF EXISTS idx_entities_filed",
+ "DROP INDEX IF EXISTS idx_entities_label",
+ "DROP TABLE IF EXISTS analysis_views",
+ "DROP TABLE IF EXISTS entity_images",
+ "DROP TABLE IF EXISTS graph_pins",
+)
+
+#: The `links` table exactly as schema 7 shipped it: before `confidence` (8) and
+#: before `nature` (11).
+_LINKS_V7 = """
+CREATE TABLE links_rewound (
+ id TEXT PRIMARY KEY,
+ from_id TEXT NOT NULL REFERENCES entities(id),
+ to_id TEXT NOT NULL REFERENCES entities(id),
+ type TEXT NOT NULL,
+ prov_by TEXT NOT NULL,
+ prov_at TEXT NOT NULL,
+ prov_status TEXT NOT NULL DEFAULT 'confirmed',
+ prov_source TEXT
+);
+INSERT INTO links_rewound
+ SELECT id, from_id, to_id, type, prov_by, prov_at, prov_status, prov_source FROM links;
+DROP TABLE links;
+ALTER TABLE links_rewound RENAME TO links;
+CREATE INDEX idx_links_from ON links(from_id);
+CREATE INDEX idx_links_to ON links(to_id);
+CREATE INDEX idx_links_type ON links(type);
+"""
+
+#: The `links` table as schema 8 shipped it: `confidence` is in, `nature` is not.
+_LINKS_V8 = """
+CREATE TABLE links_rewound AS SELECT id, from_id, to_id, type, prov_by,
+ prov_at, prov_status, prov_source, confidence FROM links;
+DROP TABLE links;
+ALTER TABLE links_rewound RENAME TO links;
+CREATE INDEX idx_links_from ON links(from_id);
+CREATE INDEX idx_links_to ON links(to_id);
+CREATE INDEX idx_links_type ON links(type);
+"""
+
+
+def rewind(db: Path | str, version: int) -> None:
+ """Put `case.db` back at `version`, shape included, ready to be migrated up."""
+ if version not in (7, 8):
+ raise ValueError(f"no rewind to schema {version}")
+ with closing(sqlite3.connect(db)) as conn, conn:
+ conn.executescript(_LINKS_V7 if version == 7 else _LINKS_V8)
+ for statement in _AFTER_7:
+ conn.execute(statement)
+ conn.execute(
+ "UPDATE meta SET value = ? WHERE key = 'schema_version'", (str(version),)
+ )
+ conn.execute(
+ "DELETE FROM schema_migrations WHERE version > ?", (version,)
+ )
+ conn.commit()
diff --git a/tests/test_analysis_views.py b/tests/test_analysis_views.py
new file mode 100644
index 0000000..f4a2217
--- /dev/null
+++ b/tests/test_analysis_views.py
@@ -0,0 +1,547 @@
+"""Saved analysis readings: live recipes, immutable captures and Trash."""
+
+from __future__ import annotations
+
+import io
+
+from PIL import Image
+
+
+def _case(client, name: str = "View case") -> str:
+ return client.post("/api/cases", json={"name": name}).json()["id"]
+
+
+def _entity(client, case_id: str, type_: str, label: str, attrs=None) -> dict:
+ response = client.post(
+ f"/api/cases/{case_id}/entities",
+ json={"type": type_, "label": label, "attrs": attrs or {}},
+ )
+ assert response.status_code == 200, response.text
+ return response.json()
+
+
+def _body(name: str, *, mode: str = "live", surface: str = "board") -> dict:
+ return {
+ "name": name,
+ "mode": mode,
+ "surface": surface,
+ "spec": {
+ "query": {
+ "filter": {"q": "AB-123", "types": ["vehicle"]},
+ "terms": {"q": "AB-123", "type": "vehicle"},
+ "label": "AB-123 · Type: Vehicle",
+ },
+ "board": {"order": "label"},
+ "timeline": {"from": None, "to": None, "field": None},
+ },
+ }
+
+
+def test_live_view_crud_and_bounded_list(client):
+ case_id = _case(client)
+ created = client.post(
+ f"/api/cases/{case_id}/analysis-views", json=_body("Plate watch")
+ )
+ assert created.status_code == 200, created.text
+ view = created.json()
+ assert view["mode"] == "live"
+ assert view["snapshot_count"] == 0
+ # A Board or Graph view saves the period it was read through, and which temporal
+ # categories that period is asked of. Unset means the two the case states itself.
+ assert view["spec"]["timeline"] == {
+ "from": None,
+ "to": None,
+ "field": None,
+ "categories": ["statement", "media"],
+ }
+
+ listing = client.get(f"/api/cases/{case_id}/analysis-views").json()["views"]
+ assert listing == [{key: value for key, value in view.items() if key != "spec"}]
+
+ duplicate = client.post(
+ f"/api/cases/{case_id}/analysis-views", json=_body("plate WATCH")
+ )
+ assert duplicate.status_code == 409
+
+ changed = _body("Plate watch updated", surface="graph")
+ changed["spec"]["graph"] = {
+ "lens": "all",
+ "omitted": ["e_hidden"],
+ "collapsed": ["e_folded"],
+ "arrangement": [{"id": "e_pinned", "x": 120.5, "y": -42.0}],
+ "camera": {"x": 18.0, "y": 24.0, "zoom": 1.25},
+ }
+ updated = client.put(
+ f"/api/cases/{case_id}/analysis-views/{view['id']}", json=changed
+ )
+ assert updated.status_code == 200, updated.text
+ assert updated.json()["surface"] == "graph"
+ assert updated.json()["created_at"] == view["created_at"]
+ assert updated.json()["spec"]["graph"] == changed["spec"]["graph"]
+
+
+def test_snapshot_keeps_captured_entities_and_relations_after_live_delete(client):
+ case_id = _case(client)
+ truck = _entity(client, case_id, "vehicle", "White pickup", {"plate": "AB-123-CD"})
+ place = _entity(client, case_id, "organization", "Checkpoint team")
+ link = client.post(
+ f"/api/cases/{case_id}/links",
+ json={"from_id": place["id"], "to_id": truck["id"], "type": "owns"},
+ )
+ assert link.status_code == 200, link.text
+
+ body = _body("Captured plate", mode="snapshot", surface="graph")
+ # Capture the exact drawing rather than the query-only match, so its context
+ # relation and far end are frozen with it.
+ body["spec"]["capture_ids"] = [truck["id"], place["id"]]
+ saved = client.post(
+ f"/api/cases/{case_id}/analysis-views", json=body
+ )
+ assert saved.status_code == 200, saved.text
+ view = saved.json()
+ assert view["snapshot_count"] == 2
+ assert len(view["spec"]["snapshot"]["links"]) == 1
+
+ duplicate = client.post(
+ f"/api/cases/{case_id}/analysis-views/{view['id']}/duplicate",
+ json={"name": "Captured plate copy"},
+ )
+ assert duplicate.status_code == 200, duplicate.text
+ assert duplicate.json()["id"] != view["id"]
+ assert duplicate.json()["spec"]["snapshot"] == view["spec"]["snapshot"]
+
+ update = client.put(
+ f"/api/cases/{case_id}/analysis-views/{view['id']}", json=body
+ )
+ assert update.status_code == 409
+ assert "immutable" in update.json()["detail"]
+
+ other_case = _case(client, "Other case")
+ imported = _body("Detached capture", mode="snapshot", surface="graph")
+ imported["spec"]["snapshot"] = view["spec"]["snapshot"]
+ refused = client.post(
+ f"/api/cases/{other_case}/analysis-views", json=imported
+ )
+ assert refused.status_code == 400
+ assert "duplicated inside its case" in refused.json()["detail"]
+
+ deleted = client.delete(f"/api/cases/{case_id}/entities/{truck['id']}")
+ assert deleted.status_code == 200, deleted.text
+
+ page = client.get(
+ f"/api/cases/{case_id}/catalog/entities",
+ params={"view": view["id"], "limit": 100},
+ )
+ assert page.status_code == 200, page.text
+ assert {row["label"] for row in page.json()["items"]} == {
+ "White pickup", "Checkpoint team"
+ }
+
+ graph = client.get(
+ f"/api/cases/{case_id}/graph", params={"view": view["id"]}
+ )
+ assert graph.status_code == 200, graph.text
+ assert graph.json()["snapshot"] is True
+ assert {row["label"] for row in graph.json()["nodes"]} == {
+ "White pickup", "Checkpoint team"
+ }
+ assert len(graph.json()["links"]) == 1
+
+
+def test_snapshot_query_is_broad_search_and_explains_the_matching_field(client):
+ case_id = _case(client)
+ _entity(client, case_id, "vehicle", "White pickup", {"plate": "AB-123-CD"})
+ saved = client.post(
+ f"/api/cases/{case_id}/analysis-views",
+ json=_body("Plate snapshot", mode="snapshot"),
+ )
+ assert saved.status_code == 200, saved.text
+ view = saved.json()
+ assert view["snapshot_count"] == 1
+
+ page = client.get(
+ f"/api/cases/{case_id}/catalog/entities",
+ params={"view": view["id"], "q": "AB-123"},
+ ).json()
+ assert page["items"][0]["matches"] == [
+ {"field": "plate", "label": "Plate", "value": "AB-123-CD"}
+ ]
+
+
+def test_snapshot_embeds_gallery_previews_for_read_only_details(client):
+ case_id = _case(client)
+ person = _entity(client, case_id, "person", "Captured witness", {"role": "observer"})
+ pixels = io.BytesIO()
+ Image.new("RGB", (48, 36), (30, 60, 90)).save(pixels, "PNG")
+ uploaded = client.post(
+ f"/api/cases/{case_id}/entities/{person['id']}/images/upload",
+ files={"file": ("portrait.png", io.BytesIO(pixels.getvalue()), "image/png")},
+ )
+ assert uploaded.status_code == 200, uploaded.text
+ body = _body("Witness photo", mode="snapshot")
+ body["spec"]["capture_ids"] = [person["id"]]
+
+ saved = client.post(f"/api/cases/{case_id}/analysis-views", json=body)
+ assert saved.status_code == 200, saved.text
+ captured = saved.json()["spec"]["snapshot"]["entities"][0]
+ assert captured["attrs"]["role"] == "observer"
+ assert captured["thumb"].startswith("data:image/jpeg;base64,")
+ assert captured["snapshot_images"][0]["title"] == "portrait"
+
+ assert client.delete(
+ f"/api/cases/{case_id}/entities/{person['id']}"
+ ).status_code == 200
+ frozen = client.get(
+ f"/api/cases/{case_id}/catalog/entities",
+ params={"view": saved.json()["id"]},
+ ).json()["items"][0]
+ assert frozen["thumb"] == captured["thumb"]
+ assert frozen["snapshot_images"] == captured["snapshot_images"]
+
+
+def test_deleted_view_goes_to_trash_and_restores(client):
+ case_id = _case(client)
+ view = client.post(
+ f"/api/cases/{case_id}/analysis-views", json=_body("Recover me")
+ ).json()
+
+ deleted = client.delete(
+ f"/api/cases/{case_id}/analysis-views/{view['id']}"
+ )
+ assert deleted.status_code == 200, deleted.text
+ group = deleted.json()["trash"]
+ assert client.get(
+ f"/api/cases/{case_id}/analysis-views/{view['id']}"
+ ).status_code == 404
+
+ trash = client.get(f"/api/cases/{case_id}/trash").json()
+ assert trash["groups"][0]["type"] == "analysis-view"
+ restored = client.post(
+ f"/api/cases/{case_id}/trash/{group}/restore", json={}
+ )
+ assert restored.status_code == 200, restored.text
+ assert restored.json()["analysis_views"] == 1
+ assert client.get(
+ f"/api/cases/{case_id}/analysis-views/{view['id']}"
+ ).status_code == 200
+
+
+def test_a_board_snapshot_freezes_the_period_it_was_read_through(client):
+ """A Board view saved with a fact-time period captures what that period holds.
+
+ The window is written as a reduced date, which is where a capture and the live
+ question can disagree: `2024-03` is the whole of March on the axis, and a snapshot
+ that stopped at its first instant would freeze an emptier case than the one the
+ analyst was looking at.
+ """
+ case_id = _case(client, "Board period")
+ person = _entity(client, case_id, "person", "Witness")
+ march = client.post(
+ f"/api/cases/{case_id}/timeline/claims",
+ json={
+ "statement": "Witness reached the gate",
+ "when": "2024-03-05T10:00:00Z",
+ "about": [person["id"]],
+ },
+ ).json()
+ april = client.post(
+ f"/api/cases/{case_id}/timeline/claims",
+ json={"statement": "Later event", "when": "2024-04-05T10:00:00Z"},
+ ).json()
+
+ body = {
+ "name": "March",
+ "mode": "snapshot",
+ "surface": "board",
+ "spec": {
+ "query": {"filter": {}, "terms": {}, "label": ""},
+ "board": {"order": "label"},
+ "timeline": {
+ "from": "2024-03",
+ "to": "2024-03",
+ "field": "fact-time",
+ "categories": ["statement"],
+ },
+ },
+ }
+ created = client.post(f"/api/cases/{case_id}/analysis-views", json=body)
+ assert created.status_code == 200, created.text
+ view = created.json()
+ assert view["spec"]["timeline"]["from"] == "2024-03"
+
+ frozen = client.get(
+ f"/api/cases/{case_id}/catalog/entities", params={"view": view["id"]}
+ )
+ assert frozen.status_code == 200, frozen.text
+ frozen_ids = {entity["id"] for entity in frozen.json()["items"]}
+ assert frozen_ids == {march["entity"]["id"], person["id"]}
+ assert april["entity"]["id"] not in frozen_ids
+
+ # And it froze what the live question over the same period answers, rather than
+ # its own reading of the boundaries.
+ live = client.get(
+ f"/api/cases/{case_id}/catalog/entities",
+ params={
+ "temporal_from": "2024-03",
+ "temporal_to": "2024-03",
+ "temporal_category": "statement",
+ },
+ )
+ assert live.status_code == 200, live.text
+ assert {entity["id"] for entity in live.json()["items"]} == frozen_ids
+
+
+def test_a_saved_period_that_is_not_a_date_is_refused(client):
+ case_id = _case(client, "Bad period")
+ body = {
+ "name": "Nonsense",
+ "mode": "snapshot",
+ "surface": "board",
+ "spec": {
+ "query": {"filter": {}, "terms": {}, "label": ""},
+ "timeline": {"from": "last tuesday", "to": "2024-03", "categories": ["statement"]},
+ },
+ }
+ refused = client.post(f"/api/cases/{case_id}/analysis-views", json=body)
+ assert refused.status_code == 400, refused.text
+
+
+def test_timeline_snapshot_freezes_rows_and_track_assignments(client):
+ """A snapshot captures the window it was read through, track by track.
+
+ The window is in the past so the run date cannot change the answer: the case
+ activity of a case filed today falls outside it, which is exactly why the second
+ track comes back empty.
+ """
+ case_id = _case(client, "Timeline snapshot")
+ person = _entity(client, case_id, "person", "Witness")
+ saved_claim = client.post(
+ f"/api/cases/{case_id}/timeline/claims",
+ json={
+ "statement": "Witness reached the gate",
+ "when": "2024-03-05T10:00:00Z",
+ "about": [person["id"]],
+ },
+ )
+ assert saved_claim.status_code == 200, saved_claim.text
+ temporal_id = saved_claim.json()["temporal"]["id"]
+ body = {
+ "name": "Frozen chronology",
+ "mode": "snapshot",
+ "surface": "timeline",
+ "spec": {
+ "query": {"filter": {}, "terms": {}, "label": ""},
+ "timeline": {
+ "from": "2024-03-05T00:00:00Z",
+ "to": "2024-03-06T00:00:00Z",
+ "timezone": "Europe/Paris",
+ "zone_choice": "machine",
+ "group_by": "subject",
+ "visible_categories": ["statement"],
+ "tracks": [
+ {
+ "id": "people",
+ "label": "People",
+ "categories": ["statement"],
+ "query": {
+ "filter": {"types": ["person"]},
+ "terms": {"type": "person"},
+ "relation": "about",
+ },
+ "collapsed": False,
+ "hidden": [],
+ "pinned": [temporal_id],
+ },
+ {
+ "id": "activity",
+ "label": "Case activity",
+ "categories": ["case_activity"],
+ },
+ ],
+ },
+ },
+ }
+ response = client.post(f"/api/cases/{case_id}/analysis-views", json=body)
+ assert response.status_code == 200, response.text
+ view = response.json()
+ assert view["snapshot_count"] == 1
+ assert view["spec"]["timeline"]["timezone"] == "Europe/Paris"
+ assert view["spec"]["timeline"]["zone_choice"] == "machine"
+ assert view["spec"]["snapshot"]["timeline_tracks"] == {
+ "people": [temporal_id],
+ "activity": [],
+ }
+ frozen = view["spec"]["snapshot"]["timeline_items"][0]
+ assert frozen["label"] == "Witness reached the gate"
+ assert frozen["subject_entities"][0]["label"] == "Witness"
+
+ claim_id = saved_claim.json()["entity"]["id"]
+ assert client.delete(f"/api/cases/{case_id}/entities/{claim_id}").status_code == 200
+ reopened = client.get(
+ f"/api/cases/{case_id}/analysis-views/{view['id']}"
+ ).json()
+ assert reopened["spec"]["snapshot"]["timeline_items"][0] == frozen
+
+ duplicate = client.post(
+ f"/api/cases/{case_id}/analysis-views/{view['id']}/duplicate",
+ json={"name": "Frozen chronology copy"},
+ )
+ assert duplicate.status_code == 200, duplicate.text
+ assert duplicate.json()["spec"]["snapshot"] == view["spec"]["snapshot"]
+
+
+def test_a_track_captures_the_case_activity_it_asks_for(client):
+ """Tracks own category selection: there is no second global switch above them.
+
+ A lane declaring `case_activity` therefore freezes the filing dates, while a lane
+ declaring `statement` beside it freezes only the Claim.
+ """
+ case_id = _case(client, "Activity track")
+ person = _entity(client, case_id, "person", "Witness")
+ claim = client.post(
+ f"/api/cases/{case_id}/timeline/claims",
+ json={
+ "statement": "Witness reached the gate",
+ "when": "2024-03-05T10:00:00Z",
+ "about": [person["id"]],
+ },
+ )
+ assert claim.status_code == 200, claim.text
+
+ created = client.post(
+ f"/api/cases/{case_id}/analysis-views",
+ json={
+ "name": "Everything",
+ "mode": "snapshot",
+ "surface": "timeline",
+ "spec": {
+ "timeline": {
+ "tracks": [
+ {"id": "events", "label": "Events", "categories": ["statement"]},
+ {
+ "id": "activity",
+ "label": "Case activity",
+ "categories": ["case_activity"],
+ },
+ ],
+ },
+ },
+ },
+ )
+ assert created.status_code == 200, created.text
+ snapshot = created.json()["spec"]["snapshot"]
+
+ assert snapshot["timeline_tracks"] == {
+ "events": [claim.json()["temporal"]["id"]],
+ "activity": [f"temporal:activity:{person['id']}:filed"],
+ }
+ assert created.json()["snapshot_count"] == 2
+
+
+def test_empty_timeline_snapshot_duplicates_without_changing_its_tracks(client):
+ case_id = _case(client, "Empty Timeline snapshot")
+ created = client.post(
+ f"/api/cases/{case_id}/analysis-views",
+ json={
+ "name": "Empty chronology",
+ "mode": "snapshot",
+ "surface": "timeline",
+ "spec": {
+ "timeline": {
+ "tracks": [{
+ "id": "events",
+ "label": "Events",
+ "categories": ["statement"],
+ }],
+ },
+ },
+ },
+ )
+ assert created.status_code == 200, created.text
+ view = created.json()
+ assert view["spec"]["snapshot"]["timeline_tracks"] == {"events": []}
+
+ duplicate = client.post(
+ f"/api/cases/{case_id}/analysis-views/{view['id']}/duplicate",
+ json={"name": "Empty chronology copy"},
+ )
+ assert duplicate.status_code == 200, duplicate.text
+ assert duplicate.json()["spec"]["snapshot"] == view["spec"]["snapshot"]
+
+
+def test_a_name_is_claimed_inside_its_own_family(client):
+ """Board and Graph share one list of views; the Timeline has its own.
+
+ Refusing a name because it is taken on a list the analyst cannot see from here is
+ worse than allowing the repeat, so the check is scoped to the family.
+ """
+ case_id = _case(client, "Two families")
+ board = client.post(f"/api/cases/{case_id}/analysis-views", json=_body("Week one"))
+ assert board.status_code == 200, board.text
+
+ graph = client.post(
+ f"/api/cases/{case_id}/analysis-views", json=_body("week ONE", surface="graph")
+ )
+ assert graph.status_code == 409
+
+ timeline = client.post(
+ f"/api/cases/{case_id}/analysis-views",
+ json={
+ "name": "Week one",
+ "mode": "live",
+ "surface": "timeline",
+ "spec": {"timeline": {"tracks": []}},
+ },
+ )
+ assert timeline.status_code == 200, timeline.text
+ assert timeline.json()["surface"] == "timeline"
+
+ names = {
+ (view["surface"], view["name"])
+ for view in client.get(f"/api/cases/{case_id}/analysis-views").json()["views"]
+ }
+ assert names == {("board", "Week one"), ("timeline", "Week one")}
+
+
+def test_a_timeline_view_keeps_the_clock_and_the_colours_it_was_read_with(client):
+ case_id = _case(client, "Zone and colour")
+ body = {
+ "name": "Tokyo reading",
+ "mode": "live",
+ "surface": "timeline",
+ "spec": {
+ "timeline": {
+ "timezone": "Asia/Tokyo",
+ "zone_choice": "zone:Asia/Tokyo",
+ "tracks": [
+ {
+ "id": "vessels",
+ "label": "Vessels",
+ "categories": ["statement"],
+ "color": "blue",
+ },
+ {
+ "id": "media",
+ "label": "Media",
+ "categories": ["media"],
+ "color": "chartreuse",
+ },
+ ],
+ },
+ },
+ }
+ created = client.post(f"/api/cases/{case_id}/analysis-views", json=body)
+ assert created.status_code == 200, created.text
+ timeline = created.json()["spec"]["timeline"]
+
+ # a zone named outright travels: the view was read on it and must reopen on it
+ assert timeline["zone_choice"] == "zone:Asia/Tokyo"
+ assert [track["color"] for track in timeline["tracks"]] == ["blue", ""]
+
+ for refused in ("zone:../../etc/passwd", "zone:", "somewhere else"):
+ body["spec"]["timeline"]["zone_choice"] = refused
+ answer = client.put(
+ f"/api/cases/{case_id}/analysis-views/{created.json()['id']}", json=body
+ )
+ assert answer.status_code == 200, answer.text
+ assert answer.json()["spec"]["timeline"]["zone_choice"] == "utc"
diff --git a/tests/test_artifacts.py b/tests/test_artifacts.py
index 046ddcd..692a225 100644
--- a/tests/test_artifacts.py
+++ b/tests/test_artifacts.py
@@ -117,3 +117,15 @@ def test_the_registry_answers_for_one_media_and_its_companions(client):
assert layout.sidecar_rel(full.photo) in owned
assert all(not rel.startswith(CACHE) for rel in owned)
assert all(rel.startswith(CACHE) for rel in artifacts.caches(case, entity))
+
+
+def test_private_entity_photos_are_owned_by_their_entity(client):
+ full = fullcase.build_full_case(client)
+ case = Case.open(full.case_id)
+ entity = case.get_entity(full.org_id)
+
+ assert entity is not None
+ assert set(artifacts.owned(case, entity)) == {
+ full.entity_photo,
+ full.entity_photo_thumb,
+ }
diff --git a/tests/test_bundles.py b/tests/test_bundles.py
index 8e34825..9fbbb4c 100644
--- a/tests/test_bundles.py
+++ b/tests/test_bundles.py
@@ -12,9 +12,10 @@ from pathlib import Path
from types import SimpleNamespace
import pytest
+from PIL import Image
from azimut import config, layout
-from azimut.engine import bundles, workqueue
+from azimut.engine import bundles, entity_images, media as media_engine, workqueue
from azimut.workspace import Case
@@ -233,6 +234,112 @@ def test_export_import_round_trip_keeps_confirmed_relations(bundle_case):
assert imported.get_link(relation["id"])["provenance"]["status"] == "confirmed"
+def test_export_import_round_trip_keeps_and_rebuilds_temporal_rows(bundle_case):
+ subject = bundle_case.add_entity("person", "Witness", by="user")
+ saved = bundle_case.save_temporal_claim(
+ entity_id=None,
+ label="The witness arrived",
+ attrs={"when": "2026-08-11T10:32:14Z", "time_role": "occurred"},
+ connectors={"about": [subject["id"]], "at": [], "cites": []},
+ by="user",
+ )
+
+ exported = bundles.export_case(bundle_case)
+ destination = Case.create(bundles.imported_name("Source case"))
+ imported = Case.open(bundles.import_into(destination, exported)["case_id"])
+
+ before = imported.timeline_page(categories=["statement"])
+ assert before["items"][0]["owner_id"] == saved["entity"]["id"]
+ assert imported.rebuild_temporal_projection() >= 1
+ assert imported.timeline_page(categories=["statement"]) == before
+
+
+def test_export_import_round_trip_keeps_the_graph_as_it_was_arranged(bundle_case):
+ """A bundle is how a case reaches another machine, and an arrangement somebody
+ built by hand is work. Losing it on the way would make the graph redraw itself
+ from scratch on the far side, which is the one thing pinning exists to stop."""
+ node = bundle_case.add_entity("person", "Dragged", by="user")
+ bundle_case.pin_entities("all", {node["id"]: (-412.5, 987.25)})
+
+ exported = bundles.export_case(bundle_case)
+ destination = Case.create(bundles.imported_name("Source case"))
+ imported = Case.open(bundles.import_into(destination, exported)["case_id"])
+
+ assert imported.graph_pins("all") == {node["id"]: (-412.5, 987.25)}
+
+
+def test_export_import_round_trip_keeps_saved_analysis_views(bundle_case):
+ """Named readings are case state, so the raw database bundle carries them."""
+ live = bundle_case.save_analysis_view({
+ "id": "v_bundle",
+ "name": "Source accounts",
+ "mode": "live",
+ "surface": "graph",
+ "spec": {"version": 1, "query": {"terms": {"type": "account"}}},
+ "created_at": "2026-08-10T10:00:00Z",
+ "updated_at": "2026-08-10T10:00:00Z",
+ })
+ snapshot = bundle_case.save_analysis_view({
+ "id": "v_timeline_bundle",
+ "name": "Frozen chronology",
+ "mode": "snapshot",
+ "surface": "timeline",
+ "spec": {
+ "version": 1,
+ "timeline": {"tracks": [{"id": "events", "categories": ["statement"]}]},
+ "snapshot": {
+ "captured_at": "2026-08-12T10:00:00Z",
+ "entities": [],
+ "links": [],
+ "timeline_items": [],
+ "timeline_tracks": {"events": []},
+ },
+ },
+ "created_at": "2026-08-12T10:00:00Z",
+ "updated_at": "2026-08-12T10:00:00Z",
+ })
+
+ exported = bundles.export_case(bundle_case)
+ destination = Case.create(bundles.imported_name("Source case"))
+ imported = Case.open(bundles.import_into(destination, exported)["case_id"])
+
+ assert imported.get_analysis_view(live["id"]) == live
+ assert imported.get_analysis_view(snapshot["id"]) == snapshot
+
+
+def test_export_import_round_trip_keeps_entity_photo_galleries(bundle_case):
+ subject = bundle_case.add_entity("person", "Unknown subject", by="user")
+ organization = bundle_case.add_entity(
+ "organization", "Unknown organization", by="user"
+ )
+ uploaded = media_engine.import_stream(
+ bundle_case, "portrait.png", BytesIO(b"not a rendered test image")
+ )
+ media_id = uploaded["entity"]["id"]
+ bundle_case.add_entity_images(subject["id"], [media_id])
+ pixels = BytesIO()
+ Image.new("RGB", (80, 60), (30, 60, 90)).save(pixels, "PNG")
+ pixels.seek(0)
+ direct = entity_images.import_photo(
+ bundle_case, organization["id"], pixels, "logo.png"
+ )["images"][0]
+
+ exported = bundles.export_case(bundle_case)
+ destination = Case.create(bundles.imported_name("Source case"))
+ imported = Case.open(bundles.import_into(destination, exported)["case_id"])
+
+ gallery = imported.entity_images(subject["id"])
+ assert [(image["media_id"], image["primary"]) for image in gallery] == [
+ (media_id, True)
+ ]
+ private_gallery = imported.entity_images(organization["id"])
+ assert [(image["id"], image["direct"], image["primary"]) for image in private_gallery] == [
+ (direct["id"], True, True)
+ ]
+ assert imported.resolve_inside(private_gallery[0]["path"]).is_file()
+ assert imported.resolve_inside(private_gallery[0]["thumbnail"]).is_file()
+
+
def test_export_import_round_trip_keeps_the_analysts_free_zone(bundle_case):
materials = bundle_case.path / "Source material" / "Interview"
materials.mkdir(parents=True)
diff --git a/tests/test_cases_api.py b/tests/test_cases_api.py
index 19d8ab5..cedbd66 100644
--- a/tests/test_cases_api.py
+++ b/tests/test_cases_api.py
@@ -148,6 +148,139 @@ def test_filed_notes_are_markdown_files(client):
assert client.get(f"/api/cases/{cid}/notes/{note['id']}").json()["text"] == "Updated"
+def test_a_report_note_records_the_case_files_it_was_written_from(client):
+ """A note composed out of case files is an artifact made from them, and says so.
+
+ Without this the report note was the one filed artifact with no chain: its images
+ pointed at a proof and its media that nothing in the graph knew it depended on, so
+ Details showed "nothing filed against this" on a page full of evidence.
+ """
+ cid = client.post("/api/cases", json={"name": "Report chain"}).json()["id"]
+ case = Case.open(cid)
+ proof = case.add_entity("proof", "Convoy", {"path": "proofs/convoy.png"}, by="proof-composer")
+ photo = case.add_entity("media", "clip.jpg", {"path": "media/clip.jpg"}, by="user")
+
+ note = client.post(
+ f"/api/cases/{cid}/notes",
+ json={
+ "title": "Convoy report",
+ "content": "![](proofs/convoy.png)",
+ "sources": ["proofs/convoy.png", "media/clip.jpg"],
+ },
+ ).json()
+
+ chain = client.get(f"/api/cases/{cid}/entities/{note['id']}/chain").json()
+ assert {row["entity"]["id"] for row in chain["sources"]} == {proof["id"], photo["id"]}
+ assert {row["type"] for row in chain["sources"]} == {"derived-from"}
+ # and the other way round: the proof knows the report leans on it
+ proof_chain = client.get(f"/api/cases/{cid}/entities/{proof['id']}/chain").json()
+ assert [row["entity"]["id"] for row in proof_chain["dependents"]] == [note["id"]]
+
+
+def test_a_note_typed_by_hand_files_no_chain_at_all(client):
+ """Most notes are written, not composed. Sending no sources must leave the note
+ exactly as it has always been, with no edge invented for it."""
+ cid = client.post("/api/cases", json={"name": "Plain note"}).json()["id"]
+
+ note = client.post(f"/api/cases/{cid}/notes", json={"title": "Lead"}).json()
+
+ chain = client.get(f"/api/cases/{cid}/entities/{note['id']}/chain").json()
+ assert chain["sources"] == [] and chain["lost"] == []
+
+
+def test_a_report_source_that_is_already_gone_is_kept_as_a_tombstone(client):
+ """A proof deleted while the composer was open cannot be linked, but the fact that
+ the report was written from it is not dropped in silence."""
+ cid = client.post("/api/cases", json={"name": "Vanished source"}).json()["id"]
+
+ note = client.post(
+ f"/api/cases/{cid}/notes",
+ json={"title": "Report", "sources": ["proofs/gone.png"]},
+ ).json()
+
+ chain = client.get(f"/api/cases/{cid}/entities/{note['id']}/chain").json()
+ assert chain["sources"] == []
+ assert [lost["path"] for lost in chain["lost"]] == ["proofs/gone.png"]
+
+
+def _sources_of(client, cid, note_id):
+ chain = client.get(f"/api/cases/{cid}/entities/{note_id}/chain").json()
+ return {row["entity"]["id"] for row in chain["sources"]}
+
+
+def test_a_note_restates_its_chain_from_its_own_body_on_every_save(client):
+ """The Notebook inserts case media at any time, so birth is not when a note's
+ chain is settled.
+
+ An image added afterwards was a dependency nothing in the graph knew about —
+ deleting it left the note showing a hole — and one taken out of the text left a
+ scar the note had stopped earning.
+ """
+ cid = client.post("/api/cases", json={"name": "Note body chain"}).json()["id"]
+ case = Case.open(cid)
+ proof = case.add_entity("proof", "Convoy", {"path": "proofs/convoy.png"}, by="proof-composer")
+ photo = case.add_entity("media", "clip.jpg", {"path": "media/clip.jpg"}, by="user")
+ note = client.post(f"/api/cases/{cid}/notes", json={"title": "Lead"}).json()
+ assert _sources_of(client, cid, note["id"]) == set()
+
+ client.put(
+ f"/api/cases/{cid}/notes/{note['id']}",
+ json={"text": f"# Lead\n\n[[media:{proof['id']}|Convoy]]\n[[media:{photo['id']}|clip]]"},
+ )
+ assert _sources_of(client, cid, note["id"]) == {proof["id"], photo["id"]}
+
+ # the photo is taken back out: the edge goes with it
+ client.put(
+ f"/api/cases/{cid}/notes/{note['id']}",
+ json={"text": f"# Lead\n\n[[media:{proof['id']}|Convoy]]"},
+ )
+ assert _sources_of(client, cid, note["id"]) == {proof["id"]}
+
+
+def test_saving_a_report_keeps_the_draft_it_was_composed_in(client):
+ """The body names the files it shows; it cannot name the draft. So a body-driven
+ restatement reconciles only what the text speaks for, or the first edit to a
+ report would quietly drop the post it came out of."""
+ cid = client.post("/api/cases", json={"name": "Report draft"}).json()["id"]
+ case = Case.open(cid)
+ post = case.add_entity("post", "Thread", {"draft": ".drafts/thread.json"}, by="post-composer")
+ proof = case.add_entity("proof", "Convoy", {"path": "proofs/convoy.png"}, by="proof-composer")
+ note = client.post(
+ f"/api/cases/{cid}/notes",
+ json={"title": "Report", "sources": [".drafts/thread.json", "proofs/convoy.png"]},
+ ).json()
+ assert _sources_of(client, cid, note["id"]) == {post["id"], proof["id"]}
+
+ client.put(
+ f"/api/cases/{cid}/notes/{note['id']}",
+ json={"text": f"# Report\n\n[[media:{proof['id']}|Convoy]]"},
+ )
+
+ assert _sources_of(client, cid, note["id"]) == {post["id"], proof["id"]}
+
+
+def test_a_note_body_naming_something_unjoinable_still_saves(client):
+ """A body is prose. A token pointing at a place, at a missing id or at the note
+ itself is skipped, never a 400 that loses the analyst's writing."""
+ cid = client.post("/api/cases", json={"name": "Odd tokens"}).json()["id"]
+ case = Case.open(cid)
+ place = case.add_entity("place", "Quay", {"lat": 1.0, "lon": 2.0}, by="user")
+ note = client.post(f"/api/cases/{cid}/notes", json={"title": "Lead"}).json()
+
+ saved = client.put(
+ f"/api/cases/{cid}/notes/{note['id']}",
+ json={
+ "text": (
+ f"[[media:{place['id']}|Quay]] [[media:e_missing|Gone]] "
+ f"[[media:{note['id']}|Itself]] [[entity:{place['id']}|Quay]]"
+ )
+ },
+ )
+
+ assert saved.status_code == 200
+ assert _sources_of(client, cid, note["id"]) == set()
+
+
def test_deleting_filed_note_removes_markdown_file(client):
cid = client.post("/api/cases", json={"name": "Notebook delete"}).json()["id"]
@@ -275,6 +408,225 @@ def test_catalog_searches_notes_and_descendant_folders(client):
assert [entity["label"] for entity in page["items"]] == ["frame"]
+def test_catalog_answers_which_videos_have_coordinates(client):
+ """The sentence the Board can now ask, term by term, each chosen from the case:
+ *media, kind video, linked to a place.* The count is the answer and the page is
+ which ones — and neither was expressible anywhere in the app before."""
+ cid = client.post("/api/cases", json={"name": "Sentence"}).json()["id"]
+
+ def entity(type_, label, attrs=None):
+ return client.post(
+ f"/api/cases/{cid}/entities",
+ json={"type": type_, "label": label, "attrs": attrs or {}},
+ ).json()["id"]
+
+ placed = entity("media", "clip.mp4", {"kind": "video"})
+ entity("media", "orphan.mp4", {"kind": "video"})
+ entity("media", "still.jpg", {"kind": "image"})
+ quay = entity("place", "48.0, 2.0", {"lat": 48.0, "lon": 2.0})
+ client.post(
+ f"/api/cases/{cid}/links",
+ json={"from_id": placed, "to_id": quay, "type": "located-at"},
+ )
+
+ page = client.get(
+ f"/api/cases/{cid}/catalog/entities",
+ params={"type": "media", "attr": "kind", "value": "video", "linked": "place"},
+ ).json()
+ assert page["total"] == 1
+ assert [row["id"] for row in page["items"]] == [placed]
+
+
+def test_the_field_and_value_menus_are_populated_from_the_case(client):
+ """No query language: every term of a search is chosen from what the case holds.
+ Including `kind`, which the vocabulary declares nowhere."""
+ cid = client.post("/api/cases", json={"name": "Menus"}).json()["id"]
+ for label, kind in (("a.mp4", "video"), ("b.mp4", "video"), ("c.jpg", "image")):
+ client.post(
+ f"/api/cases/{cid}/entities",
+ json={"type": "media", "label": label, "attrs": {"kind": kind}},
+ )
+
+ body = client.get(
+ f"/api/cases/{cid}/catalog/attributes", params={"type": "media"}
+ ).json()
+ kinds = next(row for row in body["attrs"] if row["key"] == "kind")
+ assert kinds["entities"] == 3
+ assert kinds["values"] == [
+ {"value": "video", "count": 2},
+ {"value": "image", "count": 1},
+ ]
+
+
+def test_catalog_lists_what_the_case_connects_to_nothing(client):
+ """The case's unexploited material, and the one question the catalog could not
+ ask: the graph counts these, but counting is not reaching them."""
+ cid = client.post("/api/cases", json={"name": "Loose"}).json()["id"]
+
+ def entity(type_, label, attrs=None):
+ return client.post(
+ f"/api/cases/{cid}/entities",
+ json={"type": type_, "label": label, "attrs": attrs or {}},
+ ).json()["id"]
+
+ joined = entity("media", "clip.mp4", {"kind": "video"})
+ quay = entity("place", "48.0, 2.0", {"lat": 48.0, "lon": 2.0})
+ alone = entity("media", "orphan.mp4", {"kind": "video"})
+ linked = client.post(
+ f"/api/cases/{cid}/links",
+ json={"from_id": joined, "to_id": quay, "type": "located-at"},
+ )
+ assert linked.status_code == 200
+
+ page = client.get(
+ f"/api/cases/{cid}/catalog/entities", params={"unlinked": "true"}
+ ).json()
+ assert page["total"] == 1
+ assert [row["id"] for row in page["items"]] == [alone]
+ # and the summary states the same number, so the menu can price the term before
+ # it is chosen rather than landing the analyst on an empty table
+ assert client.get(f"/api/cases/{cid}/catalog/summary").json()["unlinked"] == 1
+
+
+def test_the_summary_prices_linked_to_by_what_it_would_answer_with(client):
+ """Four media pointing at one place is **four** under "linked to a place" and one
+ under "type: place". The filter asks the first, so the menu has to price the
+ first — a count answering the neighbouring question looks like an answer and is
+ not one, which is exactly how a menu stops being trusted."""
+ cid = client.post("/api/cases", json={"name": "Counts"}).json()["id"]
+
+ def entity(type_, label, attrs=None):
+ return client.post(
+ f"/api/cases/{cid}/entities",
+ json={"type": type_, "label": label, "attrs": attrs or {}},
+ ).json()["id"]
+
+ quay = entity("place", "48.0, 2.0", {"lat": 48.0, "lon": 2.0})
+ for i in range(4):
+ clip = entity("media", f"clip{i}.mp4", {"kind": "video"})
+ client.post(
+ f"/api/cases/{cid}/links",
+ json={"from_id": clip, "to_id": quay, "type": "located-at"},
+ )
+
+ summary = client.get(f"/api/cases/{cid}/catalog/summary").json()
+ assert summary["by_type"]["place"] == 1 # the case holds one place
+ assert summary["linked_to"]["place"] == 4 # four things touch it
+ assert summary["linked_to"]["media"] == 1 # and it touches four, which is one row
+
+ # and the filter itself answers with exactly what the menu promised
+ page = client.get(
+ f"/api/cases/{cid}/catalog/entities", params={"linked": "place"}
+ ).json()
+ assert page["total"] == 4
+
+
+def test_a_pair_joined_twice_counts_once_in_the_menu(client):
+ """A media joined to one place by two verbs is one row that is linked to a place,
+ not two — or the menu promises more than the table can hand back."""
+ cid = client.post("/api/cases", json={"name": "Twice"}).json()["id"]
+ clip = client.post(
+ f"/api/cases/{cid}/entities",
+ json={"type": "media", "label": "clip.mp4", "attrs": {"kind": "video"}},
+ ).json()["id"]
+ quay = client.post(
+ f"/api/cases/{cid}/entities",
+ json={"type": "place", "label": "48.0, 2.0", "attrs": {"lat": 48.0, "lon": 2.0}},
+ ).json()["id"]
+ for verb in ("located-at", "depicts"):
+ client.post(
+ f"/api/cases/{cid}/links", json={"from_id": clip, "to_id": quay, "type": verb}
+ )
+
+ summary = client.get(f"/api/cases/{cid}/catalog/summary").json()
+ assert summary["linked_to"]["place"] == 1
+ assert (
+ client.get(f"/api/cases/{cid}/catalog/entities", params={"linked": "place"}).json()[
+ "total"
+ ]
+ == 1
+ )
+
+
+def test_catalog_narrows_on_when_a_row_was_filed(client, monkeypatch):
+ """*What came in this week* is a question about the case, and `prov_at` already
+ holds the answer. A bare date reaches the whole of that day at both ends."""
+ cid = client.post("/api/cases", json={"name": "Dates"}).json()["id"]
+ for label, at in (
+ ("old", "2026-07-01T09:00:00Z"),
+ ("edge", "2026-08-10T23:59:59Z"),
+ ("new", "2026-08-11T08:00:00Z"),
+ ):
+ monkeypatch.setattr("azimut.sqlite_backend._now", lambda at=at: at)
+ client.post(f"/api/cases/{cid}/entities", json={"type": "person", "label": label})
+
+ page = client.get(
+ f"/api/cases/{cid}/catalog/entities",
+ params={"since": "2026-08-01", "until": "2026-08-10"},
+ ).json()
+ # the row filed a second before midnight is inside the day it was filed on
+ assert [row["label"] for row in page["items"]] == ["edge"]
+ assert page["total"] == 1
+
+
+def test_catalog_tells_what_a_tool_proposed_from_what_was_entered_by_hand(client):
+ """`provenance.by` is the difference between the case's own work and a machine's,
+ and the menu is populated from the case like every other term."""
+ cid = client.post("/api/cases", json={"name": "Filers"}).json()["id"]
+ client.post(f"/api/cases/{cid}/entities", json={"type": "person", "label": "typed"})
+ client.post(f"/api/cases/{cid}/entities", json={"type": "place", "label": "48.0, 2.0"})
+
+ summary = client.get(f"/api/cases/{cid}/catalog/summary").json()
+ assert summary["by_source"] == {"user": 2}
+
+ page = client.get(
+ f"/api/cases/{cid}/catalog/entities", params={"by": "user"}
+ ).json()
+ assert page["total"] == 2
+ assert client.get(
+ f"/api/cases/{cid}/catalog/entities", params={"by": "satellite"}
+ ).json()["total"] == 0
+
+
+def test_catalog_sorts_the_case_rather_than_the_page(client, monkeypatch):
+ """The difference an ordering makes: *the newest in this case* is not *the newest
+ of the rows one page happened to load*, which is all a client-side sort can say."""
+ cid = client.post("/api/cases", json={"name": "Order"}).json()["id"]
+ for label, at in (
+ ("first", "2026-07-01T09:00:00Z"),
+ ("second", "2026-07-02T09:00:00Z"),
+ ("third", "2026-07-03T09:00:00Z"),
+ ):
+ monkeypatch.setattr("azimut.sqlite_backend._now", lambda at=at: at)
+ client.post(f"/api/cases/{cid}/entities", json={"type": "person", "label": label})
+
+ page = client.get(
+ f"/api/cases/{cid}/catalog/entities", params={"order": "-created", "limit": 2}
+ ).json()
+ assert [row["label"] for row in page["items"]] == ["third", "second"]
+ rest = client.get(
+ f"/api/cases/{cid}/catalog/entities",
+ params={"order": "-created", "limit": 2, "cursor": page["next_cursor"]},
+ ).json()
+ assert [row["label"] for row in rest["items"]] == ["first"]
+ assert rest["next_cursor"] is None
+
+
+def test_catalog_refuses_an_ordering_it_does_not_have(client):
+ cid = client.post("/api/cases", json={"name": "BadOrder"}).json()["id"]
+ res = client.get(f"/api/cases/{cid}/catalog/entities", params={"order": "size"})
+ assert res.status_code == 400
+
+
+def test_a_field_name_the_store_cannot_ask_for_is_refused(client):
+ cid = client.post("/api/cases", json={"name": "BadField"}).json()["id"]
+ res = client.get(
+ f"/api/cases/{cid}/catalog/entities",
+ params={"attr": 'kind"] or 1=1 --', "value": "video"},
+ )
+ assert res.status_code == 400
+
+
def test_catalog_rejects_a_bad_cursor(client):
cid = client.post("/api/cases", json={"name": "BadCursor"}).json()["id"]
res = client.get(f"/api/cases/{cid}/catalog/entities", params={"cursor": "not-an-int"})
diff --git a/tests/test_confidence.py b/tests/test_confidence.py
new file mode 100644
index 0000000..2f415ef
--- /dev/null
+++ b/tests/test_confidence.py
@@ -0,0 +1,299 @@
+"""Confidence on statements and ordinary semantic relations (ONTOLOGY §3).
+
+A Claim carries one confidence for the whole statement. Its ``about``, ``at`` and
+``cites`` edges only connect that statement to subjects, places and evidence. An
+ordinary relation may still carry the older integer scale because it is itself the
+statement being assessed. Mentions, machine matches and lineage carry no rating.
+"""
+
+import pytest
+
+from azimut.engine import entities as entity_engine
+from azimut.engine import links as link_engine
+from azimut.workspace import Case, CaseError
+
+
+def _case(client, name):
+ return client.post("/api/cases", json={"name": name}).json()["id"]
+
+
+def _entity(client, cid, type_, label, attrs=None):
+ res = client.post(
+ f"/api/cases/{cid}/entities",
+ json={"type": type_, "label": label, "attrs": attrs or {}},
+ )
+ assert res.status_code == 200, res.text
+ return res.json()
+
+
+def _link(client, cid, from_id, to_id, type_):
+ res = client.post(
+ f"/api/cases/{cid}/links",
+ json={"from_id": from_id, "to_id": to_id, "type": type_},
+ )
+ assert res.status_code == 200, res.text
+ return res.json()
+
+
+def _rate(client, cid, link_id, value):
+ return client.patch(f"/api/cases/{cid}/links/{link_id}", json={"confidence": value})
+
+
+def _ordinary_relation(client, cid):
+ media = _entity(client, cid, "media", "Frame", {"path": "media/frame.jpg"})
+ place = _entity(client, cid, "place", "Quay", {"lat": 53.44, "lon": 14.55})
+ return _link(client, cid, media["id"], place["id"], "located-at")
+
+
+# -- Claim confidence ---------------------------------------------------------
+
+
+def test_claim_confidence_is_a_closed_entity_field(client):
+ rows = {row["type"]: row for row in client.get("/api/cases/entity-types").json()}
+ fields = {field["key"]: field for field in rows["claim"]["attrs"]}
+
+ assert set(fields) == {
+ "count", "condition", "when", "time_role", "confidence", "method", "verbatim",
+ }
+ assert fields["confidence"]["kind"] == "choice"
+ assert [option["value"] for option in fields["confidence"]["options"]] == [
+ "certain", "probable", "possible", "refuted",
+ ]
+ assert "exclusive" not in fields
+ assert [value for value, _ in entity_engine.CLAIM_CONFIDENCE] == [
+ "certain", "probable", "possible", "refuted",
+ ]
+
+
[email protected]("value", ["certain", "probable", "possible", "refuted"])
+def test_every_claim_confidence_round_trips(client, value):
+ cid = _case(client, f"Claim {value}")
+ claim = _entity(client, cid, "claim", "A statement", {"confidence": value})
+
+ assert claim["attrs"]["confidence"] == value
+ assert Case.open(cid).get_entity(claim["id"])["attrs"]["confidence"] == value
+
+
[email protected]("value", ["unknown", 3, -1, True, ["possible"]])
+def test_a_claim_confidence_outside_the_scale_is_refused(client, value):
+ cid = _case(client, "Invalid claim confidence")
+ res = client.post(
+ f"/api/cases/{cid}/entities",
+ json={"type": "claim", "label": "A statement", "attrs": {"confidence": value}},
+ )
+
+ assert res.status_code == 400
+
+
+def test_one_claim_confidence_applies_to_all_its_connectors(client):
+ cid = _case(client, "Claim connectors")
+ claim = _entity(
+ client,
+ cid,
+ "claim",
+ "The vessel reached the harbour",
+ {"confidence": "probable", "method": "two independent observations"},
+ )
+ vessel = _entity(client, cid, "vessel", "Cargo vessel")
+ place = _entity(client, cid, "place", "Harbour", {"lat": 1.0, "lon": 2.0})
+ bookmark = _entity(client, cid, "bookmark", "Port notice")
+ connectors = [
+ _link(client, cid, claim["id"], vessel["id"], "about"),
+ _link(client, cid, claim["id"], place["id"], "at"),
+ _link(client, cid, claim["id"], bookmark["id"], "cites"),
+ ]
+
+ assert all("confidence" not in connector for connector in connectors)
+ stored = Case.open(cid).get_entity(claim["id"])
+ assert stored["attrs"]["confidence"] == "probable"
+
+
+def test_no_claim_connector_can_be_rated(client):
+ """All four, and clearing is refused as flatly as setting.
+
+ This is what lets the Claim editor render a connector as a name and a Remove and
+ nothing else: there is no route that puts a rating on one, so there is no legacy
+ value for a surface to display or an analyst to be stuck with.
+ """
+ cid = _case(client, "Connector confidence")
+ claim = _entity(client, cid, "claim", "A statement")
+ rival = _entity(client, cid, "claim", "The other reading")
+ vessel = _entity(client, cid, "vessel", "Cargo vessel")
+ place = _entity(client, cid, "place", "Candidate", {"lat": 1.0, "lon": 2.0})
+ bookmark = _entity(client, cid, "bookmark", "Port notice")
+ connectors = [
+ _link(client, cid, claim["id"], vessel["id"], "about"),
+ _link(client, cid, claim["id"], place["id"], "at"),
+ _link(client, cid, claim["id"], bookmark["id"], "cites"),
+ # How strongly each side is held is already on each Claim; a grade on the
+ # edge between two of them would be the mixture the three homes prevent.
+ _link(client, cid, claim["id"], rival["id"], "contradicts"),
+ ]
+
+ for connector in connectors:
+ assert _rate(client, cid, connector["id"], 2).status_code == 400
+ assert _rate(client, cid, connector["id"], None).status_code == 400
+ assert "confidence" not in Case.open(cid).get_link(connector["id"])
+
+
+def test_claim_confidence_can_be_cleared(client):
+ cid = _case(client, "Clear claim confidence")
+ claim = _entity(client, cid, "claim", "A statement", {"confidence": "certain"})
+
+ cleared = client.patch(
+ f"/api/cases/{cid}/entities/{claim['id']}", json={"attrs": {"confidence": None}}
+ )
+
+ assert cleared.status_code == 200, cleared.text
+ assert not cleared.json()["attrs"].get("confidence")
+
+
+def test_legacy_exclusive_data_stays_readable_but_is_not_declared(client):
+ cid = _case(client, "Legacy exclusive")
+ case = Case.open(cid)
+ claim = case.add_entity(
+ "claim", "Which bridge?", {"exclusive": True, "method": "span count"}, by="user"
+ )
+
+ updated = client.patch(
+ f"/api/cases/{cid}/entities/{claim['id']}", json={"attrs": {"method": "pier count"}}
+ )
+
+ assert updated.status_code == 200
+ assert updated.json()["attrs"]["exclusive"] is True
+ fields = next(
+ row["attrs"] for row in client.get("/api/cases/entity-types").json()
+ if row["type"] == "claim"
+ )
+ assert "exclusive" not in {field["key"] for field in fields}
+
+
+def test_eliminated_candidates_are_separate_claims(client):
+ cid = _case(client, "Candidate bridges")
+ values = []
+ for index in range(3):
+ confidence = "probable" if index == 0 else "refuted"
+ claim = _entity(
+ client,
+ cid,
+ "claim",
+ f"Bridge {index} is the location",
+ {"confidence": confidence},
+ )
+ place = _entity(
+ client,
+ cid,
+ "place",
+ f"Bridge {index}",
+ {"lat": 53.4 + index / 100, "lon": 14.5},
+ )
+ _link(client, cid, claim["id"], place["id"], "at")
+ values.append(Case.open(cid).get_entity(claim["id"])["attrs"]["confidence"])
+
+ assert values == ["probable", "refuted", "refuted"]
+
+
+# -- ordinary relation confidence --------------------------------------------
+
+
+def test_a_new_ordinary_relation_is_not_assessed(client):
+ cid = _case(client, "Unrated relation")
+ edge = _ordinary_relation(client, cid)
+
+ assert "confidence" not in edge
+
+
[email protected]("value", [3, 2, 1, -1])
+def test_every_edge_confidence_round_trips(client, value):
+ cid = _case(client, f"Edge confidence {value}")
+ edge = _ordinary_relation(client, cid)
+
+ assert _rate(client, cid, edge["id"], value).json()["confidence"] == value
+ assert Case.open(cid).get_link(edge["id"])["confidence"] == value
+
+
+def test_an_edge_rating_can_be_cleared(client):
+ cid = _case(client, "Clear edge confidence")
+ edge = _ordinary_relation(client, cid)
+ _rate(client, cid, edge["id"], 3)
+
+ cleared = _rate(client, cid, edge["id"], None)
+
+ assert cleared.status_code == 200
+ assert "confidence" not in cleared.json()
+
+
[email protected]("value", [0, 4, -2, 100, 2.5, True])
+def test_an_edge_confidence_outside_the_scale_is_refused(client, value):
+ cid = _case(client, "Invalid edge confidence")
+ edge = _ordinary_relation(client, cid)
+
+ assert _rate(client, cid, edge["id"], value).status_code in (400, 422)
+ assert "confidence" not in Case.open(cid).get_link(edge["id"])
+
+
+def test_the_registry_marks_only_semantic_relations_ratable(client):
+ rows = {row["type"]: row for row in client.get("/api/cases/relation-types").json()}
+
+ assert rows["located-at"]["ratable"] is True
+ for type_ in ("mentions", "about", "at", "cites", "same-image-as"):
+ assert rows[type_]["ratable"] is False
+ assert "derived-from" not in rows
+
+
+def test_the_edge_levels_are_still_served_for_semantic_relations(client):
+ levels = client.get("/api/cases/confidence-levels").json()
+
+ assert [level["value"] for level in levels] == [3, 2, 1, -1]
+ assert [level["label"] for level in levels] == [
+ "Certain", "Probable", "Possible", "Ruled out",
+ ]
+
+
+def test_lineage_mentions_and_machine_matches_carry_no_rating(client):
+ cid = _case(client, "Non-ratable connections")
+ case = Case.open(cid)
+ first = case.add_entity("media", "First", {"path": "media/first.jpg"}, by="user")
+ second = case.add_entity("media", "Second", {"path": "media/second.jpg"}, by="user")
+ place = case.add_entity("place", "Place", {"lat": 1.0, "lon": 2.0}, by="user")
+ note = case.add_entity("note", "Note", {}, by="user")
+ edges = [
+ case.add_link(first["id"], second["id"], "derived-from", by="inspect"),
+ _link(client, cid, note["id"], place["id"], "mentions"),
+ case.add_link(first["id"], second["id"], "same-image-as", by="enrich"),
+ ]
+
+ for edge in edges:
+ assert _rate(client, cid, edge["id"], 2).status_code == 400
+ assert "confidence" not in Case.open(cid).get_link(edge["id"])
+
+
+def test_a_suggestion_is_confirmed_before_it_is_rated(client):
+ cid = _case(client, "Suggested relation")
+ case = Case.open(cid)
+ media = case.add_entity("media", "Frame", {"path": "media/frame.jpg"}, by="user")
+ place = case.add_entity("place", "Place", {"lat": 1.0, "lon": 2.0}, by="user")
+ edge = case.add_link(
+ media["id"], place["id"], "located-at", by="enrich", status="suggested"
+ )
+
+ assert _rate(client, cid, edge["id"], 2).status_code == 400
+ both = client.patch(
+ f"/api/cases/{cid}/links/{edge['id']}",
+ json={"status": "confirmed", "confidence": 2},
+ )
+ assert both.status_code == 200
+ assert both.json()["confidence"] == 2
+
+
+def test_rating_a_missing_link_is_a_404(client):
+ cid = _case(client, "Missing link")
+ assert _rate(client, cid, "l_missing", 2).status_code == 404
+
+
+def test_the_engine_refuses_a_value_outside_the_edge_scale(client):
+ cid = _case(client, "Engine validation")
+ edge = _ordinary_relation(client, cid)
+
+ with pytest.raises(CaseError, match="must be one of"):
+ link_engine.set_confidence(Case.open(cid), edge["id"], 7)
diff --git a/tests/test_doctor.py b/tests/test_doctor.py
index 47a5506..8c6be17 100644
--- a/tests/test_doctor.py
+++ b/tests/test_doctor.py
@@ -2,11 +2,15 @@
import io
import json
+import sqlite3
+from contextlib import closing
from azimut import layout
from azimut.engine import workqueue
from azimut.workspace import Case
+from fullcase import _png
+
def _new_case(client, name="Doctor case"):
return client.post("/api/cases", json={"name": name}).json()["id"]
@@ -31,6 +35,52 @@ def test_healthy_case_has_no_doctor_findings(client):
assert report["summary"] == {"errors": 0, "warnings": 0, "info": 0}
+def test_stale_timeline_index_is_diagnosed_then_explicitly_rebuilt(client):
+ case_id = _new_case(client, "Stale Timeline")
+ claim = client.post(
+ f"/api/cases/{case_id}/entities",
+ json={
+ "type": "claim",
+ "label": "The vessel arrived",
+ "attrs": {"when": "2026-08-11T10:32:14.5Z", "time_role": "observed"},
+ },
+ ).json()
+ case = Case.open(case_id)
+ with closing(sqlite3.connect(case.db_path)) as conn:
+ conn.execute(
+ "UPDATE temporal_items SET earliest = ? WHERE owner_id = ?",
+ ("2026-08-11T10:32:14.5Z", claim["id"]),
+ )
+ conn.commit()
+
+ report = client.get(f"/api/cases/{case_id}/doctor").json()
+
+ issue = next(item for item in report["issues"] if item["kind"] == "temporal-index-stale")
+ assert issue["actions"] == [
+ {
+ "id": "rebuild-timeline",
+ "label": "Rebuild Timeline index",
+ "tone": "primary",
+ }
+ ]
+ with closing(sqlite3.connect(case.db_path)) as conn:
+ assert conn.execute(
+ "SELECT earliest FROM temporal_items WHERE owner_id = ?", (claim["id"],)
+ ).fetchone()[0] == "2026-08-11T10:32:14.5Z"
+
+ repaired = client.post(
+ f"/api/cases/{case_id}/doctor/repair",
+ json={"action": "rebuild-timeline"},
+ ).json()
+
+ assert repaired["repair"]["status"] == "rebuilt"
+ assert repaired["report"]["status"] == "healthy"
+ with closing(sqlite3.connect(case.db_path)) as conn:
+ assert conn.execute(
+ "SELECT earliest FROM temporal_items WHERE owner_id = ?", (claim["id"],)
+ ).fetchone()[0] == "2026-08-11T10:32:14.500000Z"
+
+
def test_deleted_database_can_be_rebuilt_from_file_backed_artifacts(client):
case_id = _new_case(client, "Rebuildable")
uploaded = _upload(client, case_id, "Street clip.txt")
@@ -158,6 +208,9 @@ def test_doctor_refuses_repairs_that_the_current_damage_does_not_offer(client):
assert client.post(
f"/api/cases/{case_id}/doctor/repair", json={"action": "rebuild"}
).status_code == 409
+ assert client.post(
+ f"/api/cases/{case_id}/doctor/repair", json={"action": "rebuild-timeline"}
+ ).status_code == 409
assert client.post(
f"/api/cases/{case_id}/doctor/repair",
json={"action": "import", "path": "notes.md"},
@@ -195,3 +248,71 @@ def test_scratch_case_uses_the_same_doctor_and_rebuild(client):
).json()
assert repaired["report"]["status"] == "healthy"
assert repaired["report"]["scratch"] is True
+
+
+def test_the_rebuild_states_every_loss_and_leaves_no_photo_behind(client):
+ """A rebuild reads files, so anything that lived only in `case.db` is gone.
+
+ The dialog has to say so before the analyst chooses it, and the private photos
+ have to go with the rows that owned them: kept, they would be files nothing
+ displays, nothing deletes and every later bundle still carries.
+ """
+ case_id = _new_case(client, "Photo loss")
+ subject = client.post(
+ f"/api/cases/{case_id}/entities",
+ json={"type": "person", "label": "Unknown subject"},
+ ).json()
+ added = client.post(
+ f"/api/cases/{case_id}/entities/{subject['id']}/images/upload",
+ files={"file": ("portrait.png", io.BytesIO(_png()), "image/png")},
+ )
+ assert added.status_code == 200, added.text
+ case = Case.open(case_id)
+ photo = case.resolve_inside(added.json()["images"][0]["path"])
+ assert photo.is_file()
+ case.db_path.unlink()
+
+ issue = client.get(f"/api/cases/{case_id}/doctor").json()["issues"][0]
+ assert issue["losses"] == [
+ "Relations between entities",
+ "Catalog filing folders",
+ "Provenance that was not stored in a sidecar",
+ "Entity photo galleries, and the photos added from the computer",
+ "Saved analysis views",
+ "The graph arrangement, per lens",
+ ]
+ assert photo.is_file() # naming the loss changed nothing
+
+ client.post(f"/api/cases/{case_id}/doctor/repair", json={"action": "rebuild"})
+
+ assert not photo.exists()
+ assert not layout.entity_images(case.path).exists()
+ assert client.get(f"/api/cases/{case_id}/doctor").json()["status"] == "healthy"
+
+
+def test_a_rebuilt_case_is_shaped_like_a_new_one(client):
+ """The birth-state gate, from the other direction: after a rebuild the tool root
+ holds nothing a fresh case would not, so no orphan survives the repair."""
+ case_id = _new_case(client, "Shape after repair")
+ subject = client.post(
+ f"/api/cases/{case_id}/entities",
+ json={"type": "organization", "label": "Northwind"},
+ ).json()
+ client.post(
+ f"/api/cases/{case_id}/entities/{subject['id']}/images/upload",
+ files={"file": ("logo.png", io.BytesIO(_png()), "image/png")},
+ )
+ case = Case.open(case_id)
+ case.db_path.unlink()
+ client.post(f"/api/cases/{case_id}/doctor/repair", json={"action": "rebuild"})
+
+ born = Case.open(client.post("/api/cases", json={"name": "Newborn"}).json()["id"])
+
+ def tree(root):
+ return sorted(
+ path.relative_to(root).as_posix()
+ for path in root.rglob("*")
+ if path.name != "case.db"
+ )
+
+ assert tree(Case.open(case_id).tool_root) == tree(born.tool_root)
diff --git a/tests/test_enrich.py b/tests/test_enrich.py
index 9bff139..5b1cf67 100644
--- a/tests/test_enrich.py
+++ b/tests/test_enrich.py
@@ -347,9 +347,16 @@ def test_a_rescaled_copy_is_suggested_as_the_same_image(tmp_workspace, monkeypat
a = case.find_entity(attr="path", value=first)
b = case.find_entity(attr="path", value=second)
matches = [ln for ln in case.links_of(b["id"]) if ln["type"] == enrich.SAME_IMAGE_AS]
- assert [ln["to"] for ln in matches] == [a["id"]]
+ assert len(matches) == 1
+ assert {matches[0]["from"], matches[0]["to"]} == {a["id"], b["id"]}
assert matches[0]["provenance"]["status"] == "suggested"
+ # A later pass starting from the other endpoint resolves to the same canonical
+ # orientation, so a symmetric match can never be stored twice in reverse.
+ digest = next(item["dhash"] for item in case.list_media_items() if item["path"] == first)
+ enrich._suggest_same_image(case, a["id"], first, digest)
+ assert len([ln for ln in case.links_of(a["id"]) if ln["type"] == enrich.SAME_IMAGE_AS]) == 1
+
def test_unrelated_pictures_are_not_linked(tmp_workspace, monkeypatch, tmp_path):
from azimut.engine import media as media_engine
diff --git a/tests/test_entities.py b/tests/test_entities.py
new file mode 100644
index 0000000..55a7b06
--- /dev/null
+++ b/tests/test_entities.py
@@ -0,0 +1,848 @@
+"""The entity and connection vocabularies (ONTOLOGY §§2–3).
+
+Families organize the board; each verb still declares the concrete endpoints that
+make semantic sense. A new type therefore joins no connection accidentally. This
+file locks the exact matrix exposed by the API and enforced on writes.
+"""
+
+import pytest
+
+from azimut.engine import artifacts
+from azimut.engine import entities
+from azimut.engine import links as link_engine
+from azimut.workspace import Case, CaseError
+
+
+def _new_case(client, name):
+ return client.post("/api/cases", json={"name": name}).json()["id"]
+
+
+def _link(client, cid, from_id, to_id, type_):
+ return client.post(
+ f"/api/cases/{cid}/links",
+ json={"from_id": from_id, "to_id": to_id, "type": type_},
+ )
+
+
+# -- the registry -------------------------------------------------------------
+
+
+def test_the_vocabulary_says_each_types_family_reading_and_fields(client):
+ rows = {row["type"]: row for row in client.get("/api/cases/entity-types").json()}
+
+ assert rows["person"]["family"] == "actor"
+ assert rows["person"]["manual"] is True
+ assert rows["vessel"]["family"] == "asset"
+ assert rows["media"]["family"] == "collected"
+ assert rows["proof"]["family"] == "document"
+ assert rows["place"]["family"] == "place"
+ assert rows["person"]["identity_label"] == "Full name"
+ assert rows["ip"]["identity_label"] == "IP address"
+ assert rows["ip"]["identity_placeholder"] == "203.0.113.42"
+ # the fields are what lets one generated form serve every hand-made type
+ assert [attr["key"] for attr in rows["aircraft"]["attrs"]] == [
+ "registration",
+ "icao24",
+ "model",
+ "condition",
+ ]
+ kinds = {attr["key"]: attr["kind"] for attr in rows["account"]["attrs"]}
+ assert kinds["url"] == "url"
+
+
+def test_identifiers_expose_the_value_field_and_relevant_context(client):
+ rows = {row["type"]: row for row in client.get("/api/cases/entity-types").json()}
+
+ assert [attr["key"] for attr in rows["ip"]["attrs"]] == [
+ "network",
+ "asn",
+ "provider",
+ ]
+ assert rows["ip"]["attrs"][0]["editable"] is False
+ assert rows["network"]["identity_label"] == "Network or CIDR"
+ assert [attr["key"] for attr in rows["network"]["attrs"]] == [
+ "asn",
+ "provider",
+ "country",
+ ]
+ # The handle is the account's label. A second handle field could disagree.
+ assert "handle" not in {attr["key"] for attr in rows["account"]["attrs"]}
+
+
+def test_the_legacy_ip_network_field_is_read_only(client):
+ cid = _new_case(client, "Legacy IP field")
+ created = client.post(
+ f"/api/cases/{cid}/entities",
+ json={
+ "type": "ip",
+ "label": "203.0.113.42",
+ "attrs": {"network": "203.0.113.0/24"},
+ },
+ )
+ assert created.status_code == 400
+
+ case = Case.open(cid)
+ legacy = case.add_entity(
+ "ip", "203.0.113.43", {"network": "Old free text"}, by="user"
+ )
+ kept = client.patch(
+ f"/api/cases/{cid}/entities/{legacy['id']}",
+ json={"attrs": {"network": "Old free text", "provider": "Example"}},
+ )
+ changed = client.patch(
+ f"/api/cases/{cid}/entities/{legacy['id']}",
+ json={"attrs": {"network": "New free text"}},
+ )
+
+ assert kept.status_code == 200
+ assert changed.status_code == 400
+
+
+def test_a_field_that_opens_a_subject_says_what_heads_it(client):
+ """A place's four fields are all about how tightly the point is pinned, which is
+ worth saying once above them. A vessel's registration numbers are just its own
+ fields, so they head nothing — and the panel renders them bare.
+
+ The heading is on the field rather than on the type because one type can hold two
+ subjects: a Claim says *what* it states, *when* it applies and *why* that is
+ believed, and running them all under one word would file a count as reasoning."""
+ rows = {row["type"]: row for row in client.get("/api/cases/entity-types").json()}
+
+ heads = {attr["key"]: attr["group"] for attr in rows["place"]["attrs"]}
+ assert heads == {"radius_m": "How precise", "footprint": "", "verbatim": "", "method": ""}
+ assert {attr["group"] for attr in rows["vessel"]["attrs"]} == {""}
+ assert [attr["group"] for attr in rows["claim"]["attrs"]] == [
+ "What it states", "", "When", "", "Reasoning", "", "",
+ ]
+
+
+def test_a_heading_opens_its_block_once():
+ """A field with no group of its own continues whatever heading is open, which is
+ how a place states "How precise" once over four fields. What that costs is order:
+ reopening an earlier heading further down the list would draw it twice, so each
+ one may be opened once."""
+ for entry in entities.ENTITY_TYPES:
+ opened = [attr.group for attr in entry.attrs if attr.group]
+ assert len(opened) == len(set(opened)), (entry.type, opened)
+
+
+def test_a_heading_reads_as_a_heading_not_as_a_clause():
+ """Same rule the relation groups follow: it labels a block rather than
+ completing a label, so it opens upper-case and does not run to a sentence."""
+ headings = {attr.group for e in entities.ENTITY_TYPES for attr in e.attrs if attr.group}
+
+ assert headings
+ for group in headings:
+ assert group == group.strip() and group[0].isupper(), group
+ assert not group.endswith("."), group
+ assert len(group) <= 24, group
+
+
+def test_the_types_saved_through_a_tool_route_declare_no_fields():
+ """A cross-layer gate. Details saves a `capture` through `/satellite` and a
+ `media` through `/media`, and those routes write the sidecar with a title and
+ notes only — a declared field on either type would be typed into the panel and
+ silently dropped on Save. Declaring one means teaching that branch to patch the
+ entity too; this test is what says so out loud instead of losing the value."""
+ for type_ in ("capture", "media"):
+ entry = entities.entity_type(type_)
+ assert entry is not None and not entry.attrs, type_
+
+
+def test_only_hand_made_types_are_offered_for_creation(client):
+ rows = {row["type"]: row for row in client.get("/api/cases/entity-types").json()}
+
+ # a media is born from an import and a proof from an export, so neither
+ # belongs in a create menu
+ assert rows["media"]["manual"] is False
+ assert rows["proof"]["manual"] is False
+ assert rows["place"]["manual"] is False
+ assert rows["structure"]["manual"] is True
+
+
+def test_every_declared_type_sits_in_a_declared_family():
+ assert {entry.family for entry in entities.ENTITY_TYPES} <= set(entities.FAMILIES)
+ # and every family earns its place: an empty one is a verb nobody can use
+ for family in entities.FAMILIES:
+ assert entities.types_in(family), family
+
+
+def test_every_declared_type_says_what_it_is_for_when_the_case_is_drawn():
+ """The role is the axis a graph lens narrows nodes on, and it has no default: a
+ type that did not decide would answer "is a picture of the case about this?" by
+ omission. Every role earns its place too — an empty one is a treatment nothing
+ receives."""
+ assert {entry.role for entry in entities.ENTITY_TYPES} == set(entities.ROLES)
+ for role in entities.ROLES:
+ assert entities.types_with_role(role), role
+
+
+def test_the_role_is_not_the_manual_flag_under_another_name():
+ """The two axes are independent, which is why an existing field could not be
+ reused: `media` and `place` are tool-born subjects, `post` is tool-born and a
+ deliverable, `claim` is hand-made and a subject."""
+ roles = {entry.type: (entry.role, entry.manual) for entry in entities.ENTITY_TYPES}
+
+ assert roles["media"] == (entities.SUBJECT, False)
+ assert roles["place"] == (entities.SUBJECT, False)
+ assert roles["post"] == (entities.DELIVERABLE, False)
+ assert roles["claim"] == (entities.SUBJECT, True)
+
+
+def test_every_declared_field_uses_a_known_editor():
+ for entry in entities.ENTITY_TYPES:
+ for attr in entry.attrs:
+ assert attr.kind in entities.ATTR_KINDS, (entry.type, attr.key)
+
+
+def test_a_field_that_holds_sentences_says_so():
+ """A quoted source and the reasoning behind a claim run to paragraphs, and the
+ form has no other way to know a field wants more than a line."""
+ for type_, key in (("claim", "method"), ("claim", "verbatim"),
+ ("place", "method"), ("place", "verbatim")):
+ entry = entities.entity_type(type_)
+ attr = next(a for a in entry.attrs if a.key == key)
+ assert attr.kind == "longtext", (type_, key)
+ # and it is checked exactly as text is: same value, same bound
+ entities.check_attrs("claim", {"method": "x" * entities.MAX_TEXT})
+ with pytest.raises(CaseError):
+ entities.check_attrs("claim", {"method": "x" * (entities.MAX_TEXT + 1)})
+ with pytest.raises(CaseError):
+ entities.check_attrs("claim", {"verbatim": 12})
+
+
+def test_no_two_declared_types_share_an_icon():
+ """The icon is the whole of what tells two rows apart at a glance. A lorry, a
+ freighter and an airframe drawn as one symbol made a mixed list unreadable.
+
+ Every declared type, not just the ones an analyst creates: the board lists a
+ case whole, so a tool-born type sits in the same column as a hand-made one. That
+ is how a bookmark and a domain both drew a globe.
+ """
+ icons = [entry.icon for entry in entities.ENTITY_TYPES]
+
+ assert len(icons) == len(set(icons)), sorted(icons)
+
+
+def test_a_closed_field_declares_the_whole_of_what_it_may_hold():
+ """`choice` is the only kind whose validity is a list rather than a shape, so the
+ list has to exist and has to be the only thing carrying one. A choice with no
+ options renders as an empty dropdown; options on a text field are a scale the
+ validator would never apply."""
+ for entry in entities.ENTITY_TYPES:
+ for attr in entry.attrs:
+ if attr.kind == "choice":
+ assert attr.options, (entry.type, attr.key)
+ else:
+ assert not attr.options, (entry.type, attr.key)
+
+
+def test_every_declared_type_says_what_it_owns_on_disk():
+ """The registry-level twin of the full-case drift gate: a type cannot join the
+ vocabulary without deciding whether it is file-backed."""
+ undeclared = {e.type for e in entities.ENTITY_TYPES if not artifacts.declares(e.type)}
+
+ assert undeclared == set()
+
+
+def test_a_retired_type_leaves_nothing_behind():
+ """`alias` folded into `account` with an optional platform, and `event` was
+ replaced by the claim node. Neither was ever created by a tool, so the entries
+ that used to describe them are dead wiring."""
+ assert "alias" not in artifacts.NO_FILES
+ assert "event" not in artifacts.NO_FILES
+ assert entities.entity_type("alias") is None
+ assert entities.entity_type("event") is None
+
+
+def test_an_undeclared_free_type_has_no_family():
+ """Free-string types stay storable. What they cannot be is the end of a
+ relation, since nothing states what they may join."""
+ assert entities.family_of("cuneiform-tablet") is None
+ assert entities.entity_type("cuneiform-tablet") is None
+
+
+# -- the verbs declare their exact endpoints ----------------------------------
+
+
+def test_a_new_type_inherits_only_the_family_wide_relations(
+ client, monkeypatch
+):
+ """Broad verbs follow a family; narrowed verbs still need an explicit type."""
+ invented = entities.EntityType(
+ "drone", "Drone", entities.ASSET, "grip", entities.SUBJECT, manual=True
+ )
+ monkeypatch.setattr(entities, "ENTITY_TYPES", entities.ENTITY_TYPES + (invented,))
+
+ cid = _new_case(client, "Inherited verbs")
+ case = Case.open(cid)
+ person = case.add_entity("person", "Owner", {}, by="user")
+ drone = case.add_entity("drone", "Quadcopter", {}, by="user")
+ media = case.add_entity("media", "Clip", {"path": "media/clip.mp4"}, by="user")
+ place = case.add_entity("place", "Field", {"lat": 1.0, "lon": 2.0}, by="user")
+
+ assert _link(client, cid, person["id"], drone["id"], "owns").status_code == 200
+ assert _link(client, cid, drone["id"], media["id"], "appears-in").status_code == 200
+ assert _link(client, cid, drone["id"], place["id"], "sited-at").status_code == 400
+
+
+def test_the_shipped_relations_keep_the_endpoints_they_shipped_with():
+ """The material family *is* the old {media, capture} pair, and generalising to
+ families must never have widened these three by itself.
+
+ `depicts` gained `proof` since, and that one is a decision rather than a side
+ effect: a proof is a rendered image, so what it shows is a property of its
+ pixels, and it is where a geolocation is concluded (ONTOLOGY §3). The line the
+ guard still holds is the one below it — **`located-at` stays material-only**,
+ because a proof was composed, never recorded anywhere.
+ """
+ by_type = {entry.type: entry for entry in link_engine.RELATION_TYPES}
+
+ assert by_type["located-at"].from_types == frozenset({"media"})
+ assert by_type["located-at"].to_types == frozenset({"place"})
+ assert by_type["depicts"].from_types == frozenset({"media", "capture", "proof"})
+ assert by_type["depicts"].to_types == frozenset({"place"})
+ assert by_type["same-image-as"].from_types == frozenset({"media"})
+ assert by_type["same-image-as"].to_types == frozenset({"media"})
+
+
+def test_the_new_verbs_keep_the_approved_endpoint_matrix():
+ by_type = {entry.type: entry for entry in link_engine.RELATION_TYPES}
+
+ assert by_type["owns"].from_types == entities.types_in(entities.ACTOR)
+ assert by_type["owns"].to_types == frozenset({
+ "organization", "vehicle", "vessel", "aircraft", "structure",
+ "account", "email", "phone", "domain", "ip", "network",
+ })
+ assert by_type["posted"].from_types == frozenset({"account"})
+ assert by_type["posted"].to_types == frozenset({"media", "bookmark"})
+ assert by_type["appears-in"].from_types == entities.types_in(
+ entities.ACTOR, entities.ASSET, entities.IDENTIFIER
+ )
+ assert by_type["appears-in"].to_types == frozenset({"media", "capture"})
+ assert by_type["sited-at"].from_types == frozenset({"structure"})
+ assert by_type["sited-at"].to_types == frozenset({"place"})
+ assert by_type["part-of"].from_types == frozenset({"organization"})
+ assert by_type["part-of"].to_types == frozenset({"organization"})
+ assert by_type["member-of"].from_types == frozenset({"person", "organization"})
+ assert by_type["member-of"].to_types == frozenset({"organization"})
+ assert by_type["in-network"].from_types == frozenset({"ip", "network"})
+ assert by_type["in-network"].to_types == frozenset({"network"})
+ assert by_type["instance-of"].from_types == entities.types_in(entities.ASSET)
+ assert by_type["instance-of"].to_types == frozenset({"equipment-type"})
+ assert "equipment-type" in by_type["about"].to_types
+
+
+# -- what state a thing is in, and how many of it ------------------------------
+
+
+def test_every_asset_says_what_state_it_is_in(client):
+ """A bridge, a ship, an airframe and a lorry can all be damaged, so the field is
+ the family's rather than the two types it was first wanted for. One list, because
+ a count that groups by condition has to reach both the asset and the claim."""
+ rows = {row["type"]: row for row in client.get("/api/cases/entity-types").json()}
+
+ for type_ in entities.types_in(entities.ASSET):
+ field = next(a for a in rows[type_]["attrs"] if a["key"] == "condition")
+ assert field["kind"] == "choice"
+ assert [o["value"] for o in field["options"]] == [
+ "intact", "damaged", "destroyed", "abandoned",
+ ]
+
+ claim_condition = next(a for a in rows["claim"]["attrs"] if a["key"] == "condition")
+ assert claim_condition["options"] == field["options"]
+
+
+def test_changing_hands_is_not_a_condition():
+ """"Captured" is a change of owner, which `owns` already states. Folded into the
+ scale it would mix condition with possession, and a mixture does not aggregate."""
+ stored = {value for value, _ in entities.ASSET_CONDITIONS}
+
+ assert "captured" not in stored
+ assert "seized" not in stored
+
+
+def test_a_condition_outside_the_scale_is_refused(client):
+ cid = _new_case(client, "Condition scale")
+ good = client.post(
+ f"/api/cases/{cid}/entities",
+ json={"type": "structure", "label": "Rail bridge", "attrs": {"condition": "destroyed"}},
+ )
+ invented = client.post(
+ f"/api/cases/{cid}/entities",
+ json={"type": "structure", "label": "Road bridge", "attrs": {"condition": "scratched"}},
+ )
+ # absent is unknown, and an analyst is entitled to go back to it
+ cleared = client.patch(
+ f"/api/cases/{cid}/entities/{good.json()['id']}",
+ json={"attrs": {"condition": None}},
+ )
+
+ assert good.status_code == 200, good.text
+ assert invented.status_code == 400
+ assert cleared.status_code == 200
+ assert cleared.json()["attrs"].get("condition") in (None, "")
+
+
+def test_a_count_is_a_whole_number_of_at_least_one(client):
+ """Zero is not a count for the same reason zero is not a radius: absent already
+ says "seen, not counted", and half a destroyed tank is not a quantity anyone can
+ defend."""
+ cid = _new_case(client, "Counting")
+
+ def claim(attrs):
+ return client.post(
+ f"/api/cases/{cid}/entities",
+ json={"type": "claim", "label": "Two of these", "attrs": attrs},
+ )
+
+ assert claim({"count": 2}).status_code == 200
+ assert claim({"count": 2.0}).status_code == 200 # JSON has one number type
+ assert claim({"count": 0}).status_code == 400
+ assert claim({"count": -3}).status_code == 400
+ assert claim({"count": 2.5}).status_code == 400
+ assert claim({"count": True}).status_code == 400
+ assert claim({"count": entities.MAX_COUNT + 1}).status_code == 400
+ # absent is "seen, not counted", which is a different answer from one
+ assert claim({}).status_code == 200
+
+
+def test_a_count_says_it_steps_by_one(client):
+ """Served so the spinner and the validator cannot disagree about what a valid
+ quantity is."""
+ rows = {row["type"]: row for row in client.get("/api/cases/entity-types").json()}
+ count = next(a for a in rows["claim"]["attrs"] if a["key"] == "count")
+ radius = next(a for a in rows["place"]["attrs"] if a["key"] == "radius_m")
+
+ assert count["whole"] is True
+ assert count["minimum"] == 1
+ assert radius["whole"] is False # a metre is not the smallest honest step
+
+
+def test_a_claim_declares_when_its_statement_applies(client):
+ rows = {row["type"]: row for row in client.get("/api/cases/entity-types").json()}
+ fields = {field["key"]: field for field in rows["claim"]["attrs"]}
+
+ assert fields["when"]["kind"] == "temporal"
+ assert fields["when"]["group"] == "When"
+ assert fields["time_role"]["kind"] == "choice"
+ assert [option["value"] for option in fields["time_role"]["options"]] == [
+ "occurred", "observed", "valid",
+ ]
+
+
+def test_a_claim_keeps_only_supported_temporal_values(client):
+ cid = _new_case(client, "Temporal statement")
+
+ created = client.post(
+ f"/api/cases/{cid}/entities",
+ json={
+ "type": "claim",
+ "label": "The address appeared in the access log",
+ "attrs": {
+ "when": "2026-08-11T18:40:00+02:00",
+ "time_role": "observed",
+ },
+ },
+ )
+ assert created.status_code == 200, created.text
+ assert created.json()["attrs"]["when"] == "2026-08-11T18:40:00+02:00"
+
+ interval = client.patch(
+ f"/api/cases/{cid}/entities/{created.json()['id']}",
+ json={"attrs": {"when": "2026-08~/2026-10?", "time_role": "valid"}},
+ )
+ bad_date = client.patch(
+ f"/api/cases/{cid}/entities/{created.json()['id']}",
+ json={"attrs": {"when": "2026-02-29"}},
+ )
+ bad_role = client.patch(
+ f"/api/cases/{cid}/entities/{created.json()['id']}",
+ json={"attrs": {"time_role": "published"}},
+ )
+
+ assert interval.status_code == 200, interval.text
+ assert interval.json()["attrs"]["when"] == "2026-08~/2026-10?"
+ assert bad_date.status_code == 400
+ assert bad_role.status_code == 400
+
+
+def test_a_claim_may_keep_a_local_time_or_no_time_at_all(client):
+ cid = _new_case(client, "Local time statement")
+
+ local = client.post(
+ f"/api/cases/{cid}/entities",
+ json={
+ "type": "claim",
+ "label": "The camera clock showed this time",
+ "attrs": {"when": "2026-08-11T18:40:00"},
+ },
+ )
+ undated = client.post(
+ f"/api/cases/{cid}/entities",
+ json={"type": "claim", "label": "The date is not known", "attrs": {}},
+ )
+ cleared = client.patch(
+ f"/api/cases/{cid}/entities/{local.json()['id']}",
+ json={"attrs": {"when": None}},
+ )
+
+ assert local.status_code == 200, local.text
+ assert undated.status_code == 200, undated.text
+ assert cleared.status_code == 200, cleared.text
+
+
+# -- the class family ----------------------------------------------------------
+
+
+def test_a_model_is_its_own_family_and_not_an_asset(client):
+ """Nobody owns "T-72B3" and it sits nowhere, so the three verbs an asset takes
+ are all wrong for it. Held in `asset` the picker would offer them."""
+ rows = {row["type"]: row for row in client.get("/api/cases/entity-types").json()}
+ by_type = {entry.type: entry for entry in link_engine.RELATION_TYPES}
+
+ assert rows["equipment-type"]["family"] == "class"
+ assert entities.types_in(entities.CLASS) == frozenset({"equipment-type"})
+ for verb in ("owns", "appears-in", "sited-at"):
+ assert "equipment-type" not in by_type[verb].to_types, verb
+ assert "equipment-type" not in by_type[verb].from_types, verb
+
+
+def test_a_named_object_states_which_model_it_is(client):
+ cid = _new_case(client, "Order of battle kit")
+ case = Case.open(cid)
+ tank = case.add_entity("vehicle", "Turret 214", {"plate": "214"}, by="user")
+ model = case.add_entity("equipment-type", "T-72B3", {"category": "tank"}, by="user")
+ crew = case.add_entity("person", "Crew commander", {}, by="user")
+
+ stated = _link(client, cid, tank["id"], model["id"], "instance-of")
+
+ assert stated.status_code == 200, stated.text
+ # and it runs one way: a model is not an instance of the object
+ assert _link(client, cid, model["id"], tank["id"], "instance-of").status_code == 400
+ # a person is not a member of a class either
+ assert _link(client, cid, crew["id"], model["id"], "instance-of").status_code == 400
+ # "probably a T-72B3" is a reading of the footage, so the edge takes a rating
+ assert link_engine.relation_type("instance-of").ratable is True
+
+
+def test_a_statement_counts_a_model_rather_than_minting_anonymous_objects(client):
+ """The whole point of the class family: "two of these were destroyed here" with
+ no second vehicle entity that names nobody."""
+ cid = _new_case(client, "Counted losses")
+ case = Case.open(cid)
+ model = case.add_entity("equipment-type", "ZU-23-2", {"category": "air defence"}, by="user")
+ place = case.add_entity("place", "Crossroads", {"lat": 48.1, "lon": 37.6}, by="user")
+ video = case.add_entity("media", "Drone clip", {"path": "media/clip.mp4"}, by="user")
+ claim = case.add_entity(
+ "claim", "Two ZU-23-2 destroyed at the crossroads",
+ {"count": 2, "condition": "destroyed", "confidence": "probable"}, by="user",
+ )
+
+ for to_id, verb in ((model["id"], "about"), (place["id"], "at"), (video["id"], "cites")):
+ stated = _link(client, cid, claim["id"], to_id, verb)
+ assert stated.status_code == 200, f"{verb}: {stated.text}"
+
+ assert {link["type"] for link in case.links_of(claim["id"])} == {"about", "at", "cites"}
+ assert case.get_entity(claim["id"])["attrs"]["count"] == 2
+ # the count sits on the node, never on the connector it points through
+ assert all(link.get("confidence") is None for link in case.links_of(claim["id"]))
+
+
+def test_each_entity_type_declares_every_field_once():
+ for entry in entities.ENTITY_TYPES:
+ keys = [attr.key for attr in entry.attrs]
+ assert len(keys) == len(set(keys)), f"duplicate field on {entry.type}: {keys}"
+
+
+def test_mentions_are_a_separate_action_from_relations(client):
+ rows = {row["type"]: row for row in client.get("/api/cases/relation-types").json()}
+
+ assert rows["mentions"]["action"] == "mention"
+ assert rows["mentions"]["group"] == "Mentions"
+ assert rows["mentions"]["ratable"] is False
+ assert {type_ for type_, row in rows.items() if row["action"] == "claim"} == {
+ "about", "at", "cites", "contradicts"
+ }
+ assert rows["owns"]["ratable"] is True
+
+
+def test_an_order_of_battle_is_part_of_edges_between_organizations(client):
+ """The tree an OSINT conflict case is built on: a battalion inside a brigade
+ inside a corps. `owns` would read wrong — a brigade commands its battalions
+ rather than owning them — so containment is its own verb."""
+ cid = _new_case(client, "Order of battle")
+ case = Case.open(cid)
+ corps = case.add_entity("organization", "3rd Army Corps", {"echelon": "corps"}, by="user")
+ brigade = case.add_entity(
+ "organization", "72nd Motor Rifle Brigade", {"echelon": "brigade"}, by="user"
+ )
+ battalion = case.add_entity(
+ "organization", "1st Battalion", {"echelon": "battalion"}, by="user"
+ )
+ truck = case.add_entity("vehicle", "Ural-4320", {"plate": "AB 1234"}, by="user")
+ commander = case.add_entity("person", "Unit commander", {}, by="user")
+
+ assert _link(client, cid, battalion["id"], brigade["id"], "part-of").status_code == 200
+ assert _link(client, cid, brigade["id"], corps["id"], "part-of").status_code == 200
+ # the unit's kit is owned, never a part of it
+ assert _link(client, cid, brigade["id"], truck["id"], "owns").status_code == 200
+ assert _link(client, cid, commander["id"], brigade["id"], "member-of").status_code == 200
+ assert _link(client, cid, truck["id"], brigade["id"], "part-of").status_code == 400
+ assert _link(client, cid, brigade["id"], truck["id"], "part-of").status_code == 400
+
+ # containment never cascades: disbanding a brigade does not delete its corps
+ case.remove_entity(brigade["id"])
+ assert case.get_entity(corps["id"]) is not None
+ assert case.get_entity(battalion["id"]) is not None
+
+
+def test_a_narrowing_can_only_remove_never_widen():
+ """`from_only` intersects its families rather than replacing them, so a
+ narrowing cannot smuggle in a type from somewhere else."""
+ rogue = link_engine.RelationType(
+ "rogue",
+ "reaches for",
+ from_families=frozenset({entities.PLACE}),
+ to_families=frozenset({entities.PLACE}),
+ from_only=frozenset({"person"}),
+ )
+
+ assert rogue.from_types == frozenset()
+
+
+# -- what the vocabulary refuses ----------------------------------------------
+
+
+def test_the_new_verbs_refuse_the_pairs_that_read_backwards(client):
+ cid = _new_case(client, "Refused new verbs")
+ case = Case.open(cid)
+ person = case.add_entity("person", "Owner", {}, by="user")
+ vessel = case.add_entity("vessel", "Bulk carrier", {"imo": "9074729"}, by="user")
+ account = case.add_entity("account", "@harbourwatch", {}, by="user")
+ media = case.add_entity("media", "Clip", {"path": "media/clip.mp4"}, by="user")
+ place = case.add_entity("place", "Quay", {"lat": 1.0, "lon": 2.0}, by="user")
+
+ # an asset does not own its owner
+ assert _link(client, cid, vessel["id"], person["id"], "owns").status_code == 400
+ # a person does not post; the account they own does
+ assert _link(client, cid, person["id"], media["id"], "posted").status_code == 400
+ # a place is not somewhere a vessel appears
+ assert _link(client, cid, vessel["id"], place["id"], "appears-in").status_code == 400
+ # an identifier is not sited anywhere
+ assert _link(client, cid, account["id"], place["id"], "sited-at").status_code == 400
+
+ assert case.links_of(person["id"]) == []
+
+
+def test_an_undeclared_type_cannot_be_related(client):
+ """Storable, but not relatable: nothing in the vocabulary says what a free type
+ may join, so the API refuses rather than guessing."""
+ cid = _new_case(client, "Free type")
+ case = Case.open(cid)
+ tablet = case.add_entity("cuneiform-tablet", "Tablet 4", {}, by="user")
+ place = case.add_entity("place", "Dig site", {"lat": 1.0, "lon": 2.0}, by="user")
+
+ assert _link(client, cid, tablet["id"], place["id"], "sited-at").status_code == 400
+ assert case.get_entity(tablet["id"]) is not None
+
+
+def test_an_analyst_can_own_a_vessel_and_place_a_building(client):
+ """The vocabulary end to end: the two statements the new types exist for."""
+ cid = _new_case(client, "Harbour survey")
+ case = Case.open(cid)
+ company = case.add_entity("organization", "Northwind Shipping", {}, by="user")
+ vessel = case.add_entity("vessel", "MV Aurora", {"imo": "9074729"}, by="user")
+ warehouse = case.add_entity("structure", "Quay 4 warehouse", {"kind": "warehouse"}, by="user")
+ place = case.add_entity("place", "Quay 4", {"lat": 53.44, "lon": 14.55}, by="user")
+
+ owned = _link(client, cid, company["id"], vessel["id"], "owns")
+ sited = _link(client, cid, warehouse["id"], place["id"], "sited-at")
+
+ assert owned.status_code == 200, owned.text
+ assert sited.status_code == 200, sited.text
+ # stated by hand, so confirmed: there is nothing left to review
+ assert owned.json()["provenance"]["status"] == "confirmed"
+ assert {link["type"] for link in case.links_of(vessel["id"])} == {"owns"}
+
+
+def test_the_vocabulary_explains_itself_in_one_clause():
+ """The words are terse by design — `capture`, `claim`, `collected` — and a terse
+ word nobody can look up is jargon. Every type and every family says what it is,
+ and each says it the way the copy rules ask: one clause, no full stop, nothing
+ that grows into a paragraph in a tooltip."""
+ readings = [entry.hint for entry in entities.ENTITY_TYPES]
+ readings += list(entities.FAMILY_READS.values())
+ readings += [r.hint for r in link_engine.RELATION_TYPES]
+ readings += [hint for _, _, hint in link_engine.CONFIDENCE_LEVELS]
+ readings += [a.hint for e in entities.ENTITY_TYPES for a in e.attrs if a.hint]
+
+ assert readings, "nothing declares a reading"
+ for hint in readings:
+ assert hint, readings
+ assert not hint.endswith("."), hint # a clause, not a sentence
+ assert "—" not in hint, hint # no em-dash appositive
+ assert len(hint) <= 100, hint
+ assert hint[0].islower(), hint # it completes a label, it does not open one
+
+
+def test_every_family_and_verb_is_explained(client):
+ """A reading nobody serves is a reading nobody reads, and a family the menu names
+ without explaining is the jargon this exists to remove."""
+ assert set(entities.FAMILY_READS) == set(entities.FAMILIES)
+ for entry in link_engine.RELATION_TYPES:
+ assert entry.hint, entry.type
+
+ rows = client.get("/api/cases/entity-types").json()
+ assert all(row["hint"] and row["family_reads"] for row in rows)
+ verbs = client.get("/api/cases/relation-types").json()
+ assert all(row["hint"] for row in verbs)
+ levels = client.get("/api/cases/confidence-levels").json()
+ assert all(row["hint"] for row in levels)
+
+
+def test_a_document_mentions_what_it_refers_to(client):
+ """The verb that answers "this post is about that spot" without pretending the
+ post was made from it. It reaches `place` and `collected` as well as the subject
+ families, because a note about a point is the ordinary case and refusing it would
+ leave that expressible only as a claim."""
+ cid = _new_case(client, "Mentions")
+ case = Case.open(cid)
+ note = case.add_entity("note", "Field notes", {"path": "notes/field.md"}, by="user")
+ post = case.add_entity("post", "Thread", {"draft": ".drafts/t.json"}, by="user")
+ place = case.add_entity("place", "North quay", {"lat": 1.0, "lon": 2.0}, by="user")
+ photo = case.add_entity("media", "Frame", {"path": "media/f.jpg"}, by="user")
+ person = case.add_entity("person", "A driver", {}, by="user")
+ claim = case.add_entity("claim", "The driver used the quay", {}, by="user")
+
+ for from_id, to_id in (
+ (note["id"], place["id"]),
+ (note["id"], person["id"]),
+ (note["id"], post["id"]),
+ (note["id"], claim["id"]),
+ (post["id"], photo["id"]),
+ ):
+ assert _link(client, cid, from_id, to_id, "mentions").status_code == 200
+
+ # and it runs one way: material is gathered, so it refers to nothing
+ assert _link(client, cid, photo["id"], place["id"], "mentions").status_code == 400
+ assert _link(client, cid, note["id"], note["id"], "mentions").status_code == 400
+
+
+def test_a_pointer_is_headed_apart_from_the_findings(client):
+ """`mentions` says a document names something; every other verb says something
+ about the world. Run together in one list the weaker one borrows the weight of
+ the others, so the registry heads it and every surface obeys — the split is
+ declared once, not drawn per screen."""
+ headed = {entry.type: entry.group for entry in link_engine.RELATION_TYPES if entry.group}
+ assert headed == {"mentions": "Mentions"}
+
+ for group in headed.values():
+ # a heading, not a clause: it labels a section rather than completing a label
+ assert group == group.strip() and group[0].isupper(), group
+ assert not group.endswith("."), group
+ assert len(group) <= 24, group
+
+ rows = {row["type"]: row for row in client.get("/api/cases/relation-types").json()}
+ assert rows["mentions"]["group"] == "Mentions"
+ assert rows["located-at"]["group"] == ""
+
+
+def test_mentioning_is_not_being_made_from(client):
+ """The two live side by side on the same pair and answer different questions: the
+ chain says the file was built from that, the mention says it merely talks about
+ it. Only the chain leaves a scar when the target goes."""
+ cid = _new_case(client, "Mention beside chain")
+ case = Case.open(cid)
+ proof = case.add_entity("proof", "Match", {"spec": "proofs/.meta/m.json"}, by="user")
+ capture = case.add_entity("capture", "Overview", {"path": "captures/o.png"}, by="user")
+ case.add_link(proof["id"], capture["id"], "derived-from", by="proof-composer")
+
+ assert _link(client, cid, proof["id"], capture["id"], "mentions").status_code == 200
+
+ kinds = {link["type"] for link in case.links_of(proof["id"])}
+ assert kinds == {"derived-from", "mentions"}
+ # deleting the source scars the proof once, for the derivation and not the mention
+ client.delete(f"/api/cases/{cid}/entities/{capture['id']}")
+ lost = case.get_entity(proof["id"])["attrs"].get("lost_sources", [])
+ assert len(lost) == 1
+ assert not case.links_of(proof["id"])
+
+
+# -- when the case already holds the value ------------------------------------
+
+
+ "type_, one, other",
+ [
+ ("account", "@Handle", "handle"),
+ ("phone", "+33 6 12 34 56 78", "+33-612.345678"),
+ ("domain", "Example.org.", "example.org"),
+ ("ip", "203.0.113.42", "203.0.113.42 "),
+ ("network", "203.0.113.0/24", "203.0.113.0/24"),
+ ],
+)
+def test_one_identifier_written_two_ways_is_one_identity(type_, one, other):
+ key = entities.identity_key(type_, one)
+ assert key and key == entities.identity_key(type_, other)
+
+
+ "type_, one, other",
+ [
+ # Supplying a country code is a guess about what the analyst meant.
+ ("phone", "+33612345678", "0612345678"),
+ # A subdomain is its own hostname, not a spelling of the parent.
+ ("domain", "www.example.org", "example.org"),
+ ],
+)
+def test_two_values_that_only_look_alike_stay_two_identities(type_, one, other):
+ assert entities.identity_key(type_, one) != entities.identity_key(type_, other)
+
+
+def test_only_an_identifier_has_an_identity_a_label_can_duplicate():
+ """Two people really can share a name, and two claims really can be worded alike.
+
+ The `identifier` family is the one place the label *is* the identity (ONTOLOGY
+ §2), so it is the only one that answers here — a guard over the rest would refuse
+ entities that are genuinely different.
+ """
+ for entry in entities.ENTITY_TYPES:
+ answered = bool(entities.identity_key(entry.type, "Some value"))
+ assert answered == (entry.family == entities.IDENTIFIER), entry.type
+ assert entities.identity_key("email", " ") == ""
+ assert entities.identity_key("not-a-type", "anything") == ""
+
+
+def test_the_case_says_which_row_already_holds_an_identifier(client):
+ """It reports and never refuses: merging is not shipped, so a create that failed
+ would leave the analyst holding a value with nowhere to put it."""
+ cid = _new_case(client, "Twin identifiers")
+ case = Case.open(cid)
+ first = case.add_entity("account", "@osint_handle", {}, by="user")
+ person = case.add_entity("person", "A Name", {}, by="user")
+
+ def twin(type_, label, ignore=""):
+ return client.get(
+ f"/api/cases/{cid}/entities/twin",
+ params={"type": type_, "label": label, "ignore": ignore},
+ ).json()["entity"]
+
+ # the sigil is how the same handle gets filed twice a week apart
+ assert twin("account", "osint_handle")["id"] == first["id"]
+ assert twin("account", " @OSINT_Handle ")["id"] == first["id"]
+ assert twin("account", "someone_else") is None
+ # an entity is never its own twin, which is what makes this usable on a rename
+ assert twin("account", "@osint_handle", ignore=first["id"]) is None
+ # two people may share a name, so the question is not asked of them
+ assert twin("person", "A Name") is None
+ assert person["id"]
+
+ # and the value really can still be filed: this warns, it does not block
+ again = client.post(
+ f"/api/cases/{cid}/entities",
+ json={"type": "account", "label": "osint_handle", "attrs": {}},
+ )
+ assert again.status_code == 200
diff --git a/tests/test_entity_images.py b/tests/test_entity_images.py
new file mode 100644
index 0000000..696e163
--- /dev/null
+++ b/tests/test_entity_images.py
@@ -0,0 +1,268 @@
+"""Photo galleries on hand-made entities stay presentation state, not relations."""
+
+from __future__ import annotations
+
+import io
+
+from PIL import Image
+
+from azimut.sqlite_backend import SqliteCase
+
+
+GALLERY_TYPES = {
+ "person",
+ "organization",
+ "vehicle",
+ "vessel",
+ "aircraft",
+ "structure",
+ "equipment-type",
+}
+
+
+def _png(color: tuple[int, int, int]) -> bytes:
+ buffer = io.BytesIO()
+ Image.new("RGB", (48, 36), color).save(buffer, "PNG")
+ return buffer.getvalue()
+
+
+def _case(client, name: str = "Entity photos") -> str:
+ return client.post("/api/cases", json={"name": name}).json()["id"]
+
+
+def _entity(client, case_id: str, type_: str, label: str) -> dict:
+ response = client.post(
+ f"/api/cases/{case_id}/entities",
+ json={"type": type_, "label": label, "attrs": {}},
+ )
+ assert response.status_code == 200, response.text
+ return response.json()
+
+
+def _upload(client, case_id: str, name: str, color: tuple[int, int, int]) -> dict:
+ response = client.post(
+ f"/api/cases/{case_id}/media/upload",
+ files={"file": (name, io.BytesIO(_png(color)), "image/png")},
+ )
+ assert response.status_code == 200, response.text
+ return response.json()
+
+
+def _upload_direct(
+ client, case_id: str, entity_id: str, name: str, color: tuple[int, int, int]
+) -> dict:
+ response = client.post(
+ f"/api/cases/{case_id}/entities/{entity_id}/images/upload",
+ files={"file": (name, io.BytesIO(_png(color)), "image/png")},
+ )
+ assert response.status_code == 200, response.text
+ return response.json()
+
+
+def test_registry_marks_exactly_the_types_with_photo_galleries(client):
+ rows = client.get("/api/cases/entity-types").json()
+
+ assert {row["type"] for row in rows if row["image_gallery"]} == GALLERY_TYPES
+
+
+def test_repository_keeps_one_primary_and_promotes_the_next(tmp_path):
+ store = SqliteCase.create(tmp_path / "case.db", name="Gallery store")
+ subject = store.add_entity("person", "Unknown subject", by="user")
+ first = store.add_entity(
+ "media", "First", attrs={"path": "media/first.png", "kind": "image"}, by="user"
+ )
+ second = store.add_entity(
+ "media", "Second", attrs={"path": "media/second.png", "kind": "image"}, by="user"
+ )
+ for entity, filename in ((first, "first.png"), (second, "second.png")):
+ store.upsert_media_item(
+ {
+ "path": f"media/{filename}",
+ "filename": filename,
+ "kind": "image",
+ "thumbnail": f"media/.thumbs/{filename}.jpg",
+ },
+ entity_id=entity["id"],
+ )
+
+ assert store.add_entity_images(subject["id"], [first["id"], second["id"]]) == 2
+ assert [row["primary"] for row in store.entity_images(subject["id"])] == [True, False]
+ store.set_primary_entity_image(subject["id"], second["id"])
+ assert store.entity_image_thumbs([subject["id"]]) == {
+ subject["id"]: "media/.thumbs/second.png.jpg"
+ }
+ store.remove_entity(second["id"])
+
+ assert [row["media_id"] for row in store.entity_images(subject["id"])] == [first["id"]]
+ assert store.entity_images(subject["id"])[0]["primary"] is True
+
+
+def test_attach_choose_primary_and_detach_without_deleting_media(client):
+ case_id = _case(client)
+ subject = _entity(client, case_id, "person", "Unknown subject")
+ first = _upload(client, case_id, "first.png", (20, 30, 40))
+ second = _upload(client, case_id, "second.png", (80, 90, 100))
+ media_ids = [first["entity"]["id"], second["entity"]["id"]]
+
+ attached = client.post(
+ f"/api/cases/{case_id}/entities/{subject['id']}/images",
+ json={"media_ids": media_ids},
+ )
+
+ assert attached.status_code == 200, attached.text
+ assert attached.json()["added"] == 2
+ assert [image["media_id"] for image in attached.json()["images"]] == media_ids
+ assert [image["primary"] for image in attached.json()["images"]] == [True, False]
+ assert attached.json()["images"][0]["thumbnail"] == first["item"]["thumbnail"]
+ assert client.post(
+ f"/api/cases/{case_id}/entities/{subject['id']}/images",
+ json={"media_ids": media_ids},
+ ).json()["added"] == 0
+
+ promoted = client.put(
+ f"/api/cases/{case_id}/entities/{subject['id']}/images/{media_ids[1]}/primary"
+ )
+ assert [image["primary"] for image in promoted.json()["images"]] == [False, True]
+
+ detached = client.delete(
+ f"/api/cases/{case_id}/entities/{subject['id']}/images/{media_ids[1]}"
+ )
+ assert detached.status_code == 200, detached.text
+ assert detached.json()["images"][0]["media_id"] == media_ids[0]
+ assert detached.json()["images"][0]["primary"] is True
+ assert client.get(f"/files/{case_id}/{second['item']['path']}").status_code == 200
+
+
+def test_computer_upload_stays_out_of_media_library_and_deletes_private_files(client):
+ case_id = _case(client, "Private entity photo")
+ subject = _entity(client, case_id, "organization", "Unknown organization")
+
+ first = _upload_direct(client, case_id, subject["id"], "portrait.png", (20, 40, 60))
+ second = _upload_direct(client, case_id, subject["id"], "logo.png", (80, 100, 120))
+
+ assert client.get(f"/api/cases/{case_id}/media").json() == []
+ assert [image["primary"] for image in second["images"]] == [True, False]
+ assert all(image["direct"] for image in second["images"])
+ assert all(image["media_id"] is None for image in second["images"])
+ assert all(
+ image["path"].startswith(".data/entity-images/")
+ and image["thumbnail"].startswith(".data/entity-images/.thumbs/")
+ for image in second["images"]
+ )
+ catalog = client.get(f"/api/cases/{case_id}/catalog/entities").json()
+ assert [(item["id"], item["type"]) for item in catalog["items"]] == [
+ (subject["id"], "organization")
+ ]
+
+ private = first["images"][0]
+ rendered = client.get(f"/files/{case_id}/{private['path']}")
+ thumbnail = client.get(f"/files/{case_id}/{private['thumbnail']}")
+ assert rendered.status_code == 200
+ assert thumbnail.status_code == 200
+ with Image.open(io.BytesIO(rendered.content)) as image:
+ assert image.format == "JPEG"
+ assert max(image.size) <= 2048
+ with Image.open(io.BytesIO(thumbnail.content)) as image:
+ assert image.format == "JPEG"
+ assert max(image.size) <= 512
+
+ removed = client.delete(
+ f"/api/cases/{case_id}/entities/{subject['id']}/images/{private['id']}"
+ )
+ assert removed.status_code == 200, removed.text
+ assert removed.json()["images"][0]["primary"] is True
+ assert client.get(f"/files/{case_id}/{private['path']}").status_code == 404
+ assert client.get(f"/files/{case_id}/{private['thumbnail']}").status_code == 404
+
+
+def test_catalog_and_graph_use_the_primary_photo_thumbnail(client):
+ case_id = _case(client, "Photo previews")
+ subject = _entity(client, case_id, "aircraft", "Unknown airframe")
+ uploaded = _upload_direct(
+ client, case_id, subject["id"], "airframe.png", (40, 60, 80)
+ )
+
+ catalog = client.get(
+ f"/api/cases/{case_id}/catalog/entities", params={"type": "aircraft"}
+ ).json()
+ node = next(
+ node
+ for node in client.get(f"/api/cases/{case_id}/graph").json()["nodes"]
+ if node["id"] == subject["id"]
+ )
+
+ assert catalog["items"][0]["thumb"] == uploaded["images"][0]["thumbnail"]
+ assert node["thumb"] == uploaded["images"][0]["thumbnail"]
+
+
+def test_gallery_rejects_unsupported_entities_and_non_images(client, monkeypatch):
+ case_id = _case(client, "Photo validation")
+ unsupported = _entity(client, case_id, "account", "@unknown")
+ subject = _entity(client, case_id, "vehicle", "Unknown vehicle")
+ image = _upload(client, case_id, "vehicle.png", (10, 20, 30))
+ document = client.post(
+ f"/api/cases/{case_id}/media/upload",
+ files={"file": ("notes.txt", io.BytesIO(b"notes"), "text/plain")},
+ ).json()
+
+ wrong_target = client.post(
+ f"/api/cases/{case_id}/entities/{unsupported['id']}/images",
+ json={"media_ids": [image["entity"]["id"]]},
+ )
+ wrong_media = client.post(
+ f"/api/cases/{case_id}/entities/{subject['id']}/images",
+ json={"media_ids": [document["entity"]["id"]]},
+ )
+
+ assert wrong_target.status_code == 400
+ assert wrong_media.status_code == 400
+
+ unreadable = client.post(
+ f"/api/cases/{case_id}/entities/{subject['id']}/images/upload",
+ files={"file": ("broken.png", io.BytesIO(b"not an image"), "image/png")},
+ )
+ assert unreadable.status_code == 400
+ assert len(client.get(f"/api/cases/{case_id}/media").json()) == 2
+
+ monkeypatch.setattr(Image, "MAX_IMAGE_PIXELS", 800)
+ oversized = client.post(
+ f"/api/cases/{case_id}/entities/{subject['id']}/images/upload",
+ files={
+ "file": (
+ "oversized.png",
+ io.BytesIO(_png((30, 40, 50))),
+ "image/png",
+ )
+ },
+ )
+ assert oversized.status_code == 400
+
+
+def test_a_photo_past_the_limit_is_refused_before_anything_is_written(
+ client, monkeypatch, tmp_path
+):
+ """The same bound the two other image surfaces enforce, on the third.
+
+ The pixel clamp further in answers a decompression bomb; it does not answer a
+ file that is simply enormous, which would be buffered to disk and decoded
+ before anything looked at its size.
+ """
+ from azimut import layout
+ from azimut.api import cases
+ from azimut.workspace import Case
+
+ monkeypatch.setattr(cases, "MAX_IMAGE_BYTES", 100)
+ case_id = _case(client, "Bounded photos")
+ subject = _entity(client, case_id, "person", "Unknown subject")
+
+ refused = client.post(
+ f"/api/cases/{case_id}/entities/{subject['id']}/images/upload",
+ files={"file": ("huge.png", io.BytesIO(_png((10, 20, 30))), "image/png")},
+ )
+
+ assert refused.status_code == 413
+ assert "under" in refused.json()["detail"]
+ assert not layout.entity_images(Case.open(case_id).path).exists()
+ assert client.get(
+ f"/api/cases/{case_id}/entities/{subject['id']}/images"
+ ).json()["images"] == []
diff --git a/tests/test_files_api.py b/tests/test_files_api.py
index dc035ba..8382dab 100644
--- a/tests/test_files_api.py
+++ b/tests/test_files_api.py
@@ -64,3 +64,24 @@ def test_edited_file_is_served_fresh(client):
res = client.get(f"/files/{cid}/{item['path']}", headers={"If-None-Match": stale})
assert res.status_code == 200
assert res.headers["etag"] != stale
+
+
+def test_a_name_holding_a_hash_is_served_under_its_encoded_url(client):
+ """A TikTok download lands as `#3deenero2025.mp4`, and the name is kept.
+
+ Raw in a URL that `#` opens a fragment: the request arrives as the directory
+ and the browser never sees the file, which is how a downloaded video came to
+ play nowhere while its hash-named thumbnail showed fine. The UI encodes the
+ path (`lib/fileUrl.js`); this is the other half — the route resolving it back
+ to the file, rather than reading the escape as traversal.
+ """
+ cid = client.post("/api/cases", json={"name": "Files"}).json()["id"]
+ item = _upload(client, cid, name="#3deenero2025.png")
+ assert item["path"] == "media/#3deenero2025.png"
+
+ served = client.get(f"/files/{cid}/media/%233deenero2025.png")
+ assert served.status_code == 200
+ assert served.content == _png_bytes()
+
+ # what the browser asked for before the encoding: the directory, not a file
+ assert client.get(f"/files/{cid}/media/").status_code == 404
diff --git a/tests/test_geo_api.py b/tests/test_geo_api.py
index 4f34896..cc5fda7 100644
--- a/tests/test_geo_api.py
+++ b/tests/test_geo_api.py
@@ -2,6 +2,7 @@
import pytest
+from azimut.api import satellite
from azimut.engine import geo
# The suite's autouse fixture replaces geo.reverse_geocode with an offline stub,
@@ -299,6 +300,80 @@ def test_sky_validates_at_the_edge(client, params):
assert client.get("/api/geo/sky", params=params).status_code == 422
+# -- /api/geo/daylight ----------------------------------------------------------
+#
+# The geometry is covered in tests/test_sky.py. What matters here is the contract the
+# Timeline reads: the point's own civil zone beside the spans, UTC instants whatever
+# clock the axis is labelled with, and a window too wide answered as cut rather than
+# paid for.
+
+
+def test_daylight_carries_the_spans_and_the_point_s_own_zone(client):
+ response = client.get(
+ "/api/geo/daylight",
+ params={
+ "lat": 50.45, "lon": 30.52,
+ "from": "2026-06-20T00:00:00Z", "to": "2026-06-22T00:00:00Z",
+ },
+ )
+ assert response.status_code == 200
+ body = response.json()
+ assert body["zone"]["name"] == "Europe/Kyiv"
+ assert body["zone"]["abbreviation"] == "EEST"
+ assert body["zone"]["offset_minutes"] == 180
+ assert body["truncated"] is False
+ assert len(body["day"]) == 2
+ for span in body["day"]:
+ assert span["from"].endswith("Z") and span["to"].endswith("Z")
+ # dusk is not a line, so the two runs are both given and civil encloses the day
+ assert body["civil"][0]["from"] < body["day"][0]["from"]
+
+
+def test_daylight_says_a_window_was_too_wide_rather_than_paying_for_it(client):
+ body = client.get(
+ "/api/geo/daylight",
+ params={
+ "lat": 50.45, "lon": 30.52,
+ "from": "2026-01-01T00:00:00Z", "to": "2027-01-01T00:00:00Z",
+ },
+ ).json()
+ assert body["truncated"] is True
+ assert body["day"] == [] and body["civil"] == []
+ # the zone still answers: it is what the axis is labelled with, and it costs
+ # nothing to work out
+ assert body["zone"]["name"] == "Europe/Kyiv"
+
+
+ "params",
+ [
+ {"lat": 91, "lon": 0, "from": "2026-06-20T00:00:00Z", "to": "2026-06-21T00:00:00Z"},
+ {"lat": 0, "lon": 0, "from": "yesterday", "to": "2026-06-21T00:00:00Z"},
+ {"lat": 0, "lon": 0, "from": "2026-06-21T00:00:00Z", "to": "2026-06-20T00:00:00Z"},
+ {"lat": 0, "lon": 0, "from": "2026-06-21T00:00:00Z"},
+ ],
+)
+def test_daylight_validates_at_the_edge(client, params):
+ assert client.get("/api/geo/daylight", params=params).status_code == 422
+
+
+def test_daylight_does_not_touch_the_network(monkeypatch):
+ import socket
+
+ def explode(*args, **kwargs):
+ raise AssertionError("daylight must be computed offline")
+
+ monkeypatch.setattr(socket, "socket", explode)
+ monkeypatch.setattr(socket, "create_connection", explode)
+ body = satellite.daylight_for_window(
+ lat=48.8584,
+ lon=2.2945,
+ start="2026-07-30T00:00:00Z",
+ end="2026-07-31T00:00:00Z",
+ )
+ assert len(body["day"]) == 1
+
+
def test_sky_never_touches_the_network(client, monkeypatch):
"""Opening the panel must not phone out. The reverse geocode beside it in the
same tool does; this route is pure computation, and stays that way."""
diff --git a/tests/test_geo_locate.py b/tests/test_geo_locate.py
index 9230355..543c24d 100644
--- a/tests/test_geo_locate.py
+++ b/tests/test_geo_locate.py
@@ -2,6 +2,8 @@
(offline tables) and ``geo.locate_point`` (Nominatim behind a stub, never the
network)."""
+import httpx
+
from azimut.engine import continents, countries, geo
@@ -231,3 +233,107 @@ def test_locate_point_never_raises(monkeypatch):
monkeypatch.setattr(geo, "reverse_geocode", boom)
assert geo.locate_point(48.8, 2.3) == {"state": "failed"}
+
+
+# -- Nominatim's pace ---------------------------------------------------------
+# The usage policy is one request a second, and the penalty for exceeding it is a
+# 429 on the whole address. These hold the floor in front of *every* request
+# rather than in whichever caller loops: `locate_point` makes a second lookup for
+# the English region that no caller can see, and the two together were the pace
+# that got a 103-place backfill throttled.
+
+
+#: The real reverse geocoder, captured at import: conftest's autouse fixture
+#: replaces it with an offline stub before every test, and these are the tests
+#: that need the request path itself.
+_REAL_REVERSE = geo.reverse_geocode
+_REAL_PACE = geo._pace
+
+
+def _recording_httpx(monkeypatch, status=200, payload=None):
+ """Stub httpx.get, recording the delay each call was made to wait."""
+ waited: list[float] = []
+
+ class Response:
+ status_code = status
+
+ def raise_for_status(self):
+ if status >= 400:
+ raise httpx.HTTPStatusError("boom", request=None, response=None)
+
+ @staticmethod
+ def json():
+ return payload if payload is not None else {"address": {}}
+
+ monkeypatch.setattr(geo.httpx, "get", lambda *a, **k: Response())
+ monkeypatch.setattr(geo.time, "sleep", waited.append)
+ monkeypatch.setattr(geo, "reverse_geocode", _REAL_REVERSE)
+ monkeypatch.setattr(geo, "_pace", _REAL_PACE)
+ geo._reset_pace()
+ return waited
+
+
+def test_two_lookups_in_a_row_wait_for_the_interval(monkeypatch):
+ waited = _recording_httpx(monkeypatch)
+
+ geo.reverse_geocode(48.8, 2.3)
+ geo.reverse_geocode(48.9, 2.4)
+
+ assert len(waited) == 1 # the first call has nothing to wait for
+ assert 0 < waited[0] <= geo.NOMINATIM_INTERVAL
+
+
+def test_the_pace_is_held_per_request_not_per_caller(monkeypatch):
+ # the floor is in front of the request, so it holds however many callers,
+ # loops or hidden second lookups there are
+ _recording_httpx(monkeypatch)
+ slept: list[float] = []
+ monkeypatch.setattr(geo.time, "sleep", slept.append)
+
+ for _ in range(4):
+ _REAL_PACE()
+
+ assert len(slept) == 3
+ assert all(0 < delay <= geo.NOMINATIM_INTERVAL for delay in slept)
+
+
+def test_the_english_region_lookup_is_paced_too(monkeypatch):
+ # the bug this covers: `locate_point` made two requests back to back, so a
+ # caller pacing itself between items still ran at twice the allowed rate
+ waited = _recording_httpx(
+ monkeypatch,
+ payload={"address": {"country_code": "ve", "country": "Venezuela",
+ "state": "Distrito Capital"}},
+ )
+
+ geo.locate_point(10.4449, -66.9072)
+
+ assert len(waited) == 1
+ assert waited[0] > 0
+
+
+def test_the_forward_geocoder_shares_the_same_pace(monkeypatch):
+ waited = _recording_httpx(monkeypatch, payload=[{"lat": "1", "lon": "2"}])
+
+ geo.geocode("Caracas")
+ geo.geocode("Maracaibo")
+
+ assert len(waited) == 1
+
+
+def test_a_429_is_remembered_as_throttling(monkeypatch):
+ _recording_httpx(monkeypatch, status=429)
+ assert geo.throttled() is False
+
+ assert geo.locate_point(10.4449, -66.9072) == {"state": "failed"}
+
+ # a batch that resolved nothing because the address is in the penalty box is
+ # not the same event as a batch of genuine lookup failures
+ assert geo.throttled() is True
+
+
+def test_an_ordinary_failure_is_not_throttling(monkeypatch):
+ _recording_httpx(monkeypatch, status=500)
+
+ assert geo.locate_point(10.4449, -66.9072) == {"state": "failed"}
+ assert geo.throttled() is False
diff --git a/tests/test_graph.py b/tests/test_graph.py
new file mode 100644
index 0000000..519b824
--- /dev/null
+++ b/tests/test_graph.py
@@ -0,0 +1,2989 @@
+"""The case drawn as a graph (SPEC §6, v2 "Case graph"; `engine/graph.py`).
+
+Four rules carry this file.
+
+**A lens is derived, never declared twice.** The verbs live in the relation
+registry and the node roles on `EntityType`, so every verb must land in exactly one
+reading, every type must declare a role, and neither addition may need an edit here.
+A lens that had to be maintained by hand would be a second vocabulary, which is the
+thing the registries exist to prevent.
+
+**A lens narrows nodes, not only verbs.** What the analyst wrote is the filing rather
+than the case, so a post and a note leave the default drawing and one lens fetches
+them back. The narrowing reaches the degree too: a node may not state a connection
+this reading has no way to show.
+
+**Bounded means bounded.** No request may reach the whole graph, and a view that
+was cut has to say so rather than present a slice as the case.
+
+**A cut view keeps the hubs.** Which nodes survive truncation is the whole
+question for a case too large to draw: ordering by degree keeps the shape of the
+case on screen, where an arbitrary slice would misrepresent it.
+"""
+
+import io
+import json
+import sqlite3
+
+from bigcase import build_big_case
+from PIL import Image
+
+from azimut.engine import entities as entity_engine
+from azimut.engine import graph as graph_engine
+from azimut.engine import links as link_engine
+from azimut.workspace import Case
+
+
+def _case(client, name):
+ return client.post("/api/cases", json={"name": name}).json()["id"]
+
+
+def _entity(client, cid, type_, label, attrs=None):
+ res = client.post(
+ f"/api/cases/{cid}/entities",
+ json={"type": type_, "label": label, "attrs": attrs or {}},
+ )
+ assert res.status_code == 200, res.text
+ return res.json()["id"]
+
+
+def _media(client, cid, label):
+ """A picture the vocabulary accepts either end of: `depicts` and `appears-in` both
+ narrow to image or video, so a bare media entity is refused."""
+ return _entity(
+ client, cid, "media", label, {"path": f"media/{label}.jpg", "kind": "image"}
+ )
+
+
+def _link(client, cid, from_id, to_id, type_):
+ res = client.post(
+ f"/api/cases/{cid}/links",
+ json={"from_id": from_id, "to_id": to_id, "type": type_},
+ )
+ assert res.status_code == 200, res.text
+ return res.json()["id"]
+
+
+def _graph(client, cid, **params):
+ res = client.get(f"/api/cases/{cid}/graph", params=params)
+ assert res.status_code == 200, res.text
+ return res.json()
+
+
+def _ids(payload):
+ return {node["id"] for node in payload["nodes"]}
+
+
+def _node(payload, entity_id):
+ return next(node for node in payload["nodes"] if node["id"] == entity_id)
+
+
+# -- the lens vocabulary ------------------------------------------------------
+
+
+def test_every_verb_the_registry_knows_lands_in_exactly_one_lens():
+ """A verb in no lens is unreachable; a verb in two is an ambiguity the
+ analyst has to resolve. Both are the drift a derived lens exists to stop, so
+ adding a relation type without touching `graph.py` has to keep this green."""
+ every = set(link_engine.CHAIN_TYPES) | {e.type for e in link_engine.RELATION_TYPES}
+ homes: dict[str, list[str]] = {verb: [] for verb in every}
+ for lens in graph_engine.lenses():
+ if lens.id == "all":
+ continue
+ for verb in lens.types:
+ homes[verb].append(lens.id)
+ assert all(len(where) == 1 for where in homes.values()), homes
+
+
+def test_the_everything_lens_holds_every_verb():
+ every = set(link_engine.CHAIN_TYPES) | {e.type for e in link_engine.RELATION_TYPES}
+ assert set(graph_engine.lens("all").types) == every
+
+
+def test_geography_is_what_a_verb_targets_not_what_it_is_called():
+ """The ground lens is derived from the endpoint families, so a verb landing on
+ a place belongs to it whatever it is named."""
+ ground = set(graph_engine.lens("ground").types)
+ for entry in link_engine.RELATION_TYPES:
+ if entry.action == "relation" and entity_engine.PLACE in entry.to_families:
+ assert entry.type in ground
+
+
+def test_two_files_being_one_picture_is_a_fact_about_the_case():
+ """`same-image-as` says two pictures are one picture, and `media` is a subject.
+
+ Filed with the artifact chain it was a derivation defect: one lens holding *what
+ did I make, out of what* and a finding about the world at once. It is the mirror
+ detection the source-folding work needs, which is a reading of the case.
+ """
+ assert link_engine.SAME_IMAGE_AS in graph_engine.lens("subjects").types
+ assert link_engine.SAME_IMAGE_AS not in graph_engine.lens("work").types
+
+
+def test_the_readings_of_the_case_are_told_apart_from_the_reading_of_the_filing():
+ """Six lenses were two axes stacked in one menu. `derived-from`, `depends-on` and
+ `mentions` all answer *what did I write, and out of what*, which is a reading of
+ the filing — and `mentions` starts at a `document` by construction, so it has
+ never held one subject-to-subject edge. One lens, named for what it is."""
+ assert [entry.id for entry in graph_engine.lenses()] == [
+ "all", "subjects", "ground", "claims", "work",
+ ]
+ work = graph_engine.lens("work")
+ assert set(work.types) == {
+ link_engine.DERIVED_FROM, link_engine.DEPENDS_ON, link_engine.MENTIONS,
+ }
+
+
+def test_saying_which_model_a_thing_is_reads_with_the_subject_web():
+ """`instance-of` is an analyst's reading of an object, so it lands in Subjects by
+ the same derivation every other verb follows — no edit here was needed to place
+ it, which is the property the derived lenses exist for."""
+ assert link_engine.INSTANCE_OF in graph_engine.lens("subjects").types
+ assert link_engine.INSTANCE_OF not in graph_engine.lens("ground").types
+
+
+def test_an_unknown_lens_is_refused_rather_than_silently_widened(client):
+ cid = _case(client, "unknown lens")
+ res = client.get(f"/api/cases/{cid}/graph", params={"lens": "everything-ish"})
+ assert res.status_code == 400
+
+
+def test_the_lens_registry_is_served_with_its_bounds(client):
+ body = client.get("/api/cases/graph-lenses").json()
+ assert [entry["id"] for entry in body["lenses"]][0] == "all"
+ assert all(entry["hint"] for entry in body["lenses"])
+ assert body["max_hops"] == graph_engine.MAX_HOPS
+ # No node ceiling is served, because there is none: the drawing grows without
+ # limit, and a number the client could only use to refuse a click is not sent.
+ assert "max_nodes" not in body
+ assert {entry["value"] for entry in body["orders"]} == {"degree", "recent"}
+
+
+# -- which nodes a reading draws -----------------------------------------------
+
+
+def test_a_reading_of_the_case_leaves_out_what_the_analyst_wrote():
+ """The node half of a lens, and it is derived from the roles exactly as the verbs
+ are derived from the relation registry: a type added there lands in the right
+ readings with no edit here."""
+ filing = entity_engine.types_with_role(entity_engine.ANNEX, entity_engine.DELIVERABLE)
+ assert filing == {"note", "inspect-session", "post"}
+
+ for lens_id in ("all", "subjects", "ground", "claims"):
+ assert set(graph_engine.lens(lens_id).hides) == filing, lens_id
+ # And the one reading that is about the filing hides nothing at all: it is the
+ # switch that puts the others' omissions one click away.
+ assert graph_engine.lens("work").hides == ()
+
+
+def test_an_attestation_is_still_drawn_because_it_carries_a_path():
+ """A bookmark is not a leaf: *account posted it, statement cites it* is a path
+ through it, and that path is a fact about the case. It leaves the drawing the day
+ a collapsed edge can carry the same sentence, not before."""
+ for type_ in ("bookmark", "proof", "capture"):
+ assert entity_engine.entity_type(type_).role == entity_engine.ATTESTATION
+ assert type_ not in graph_engine.lens("all").hides
+
+
+def test_the_default_drawing_holds_the_case_and_the_other_lens_the_filing(client):
+ cid = _case(client, "roles")
+ person = _entity(client, cid, "person", "Subject")
+ note = _entity(client, cid, "note", "Working notes")
+ post = _entity(client, cid, "post", "Thread draft")
+ session = _entity(client, cid, "inspect-session", "Frame pass")
+
+ assert _ids(_graph(client, cid)) == {person}
+ assert _graph(client, cid)["total"] == 1
+ assert _ids(_graph(client, cid, lens="work")) == {person, note, post, session}
+
+
+def test_a_free_type_no_role_speaks_for_is_drawn_by_every_reading(client):
+ """A type the vocabulary has never heard of has no role, and leaving it out would
+ drop an entity nobody agreed to drop. Which is why a reading states what it
+ excludes rather than what it keeps."""
+ cid = _case(client, "free type")
+ tablet = _entity(client, cid, "cuneiform-tablet", "BM 92687")
+
+ assert _ids(_graph(client, cid)) == {tablet}
+ assert _ids(_graph(client, cid, lens="claims")) == {tablet}
+
+
+def test_a_degree_counts_only_the_connections_the_reading_can_show(client):
+ """The number that prices a click. Counted over every edge, a media whose only
+ connection is a note reads as connected in a reading that draws neither the note
+ nor the edge to it — and the control offering to open it can only ever appear to
+ do nothing."""
+ cid = _case(client, "honest degree")
+ media = _entity(client, cid, "media", "clip.mp4", {"path": "media/clip.mp4"})
+ note = _entity(client, cid, "note", "What the clip shows")
+ _link(client, cid, note, media, "mentions")
+
+ drawn = _graph(client, cid)
+ assert _node(drawn, media)["degree"] == 0
+ assert drawn["isolated"] == 1
+
+ work = _graph(client, cid, lens="work")
+ assert _node(work, media)["degree"] == 1
+ assert work["isolated"] == 0
+
+
+def test_opening_a_node_never_brings_in_what_the_reading_leaves_out(client):
+ cid = _case(client, "open past the reading")
+ media = _entity(client, cid, "media", "clip.mp4", {"path": "media/clip.mp4"})
+ note = _entity(client, cid, "note", "What the clip shows")
+ _link(client, cid, note, media, "mentions")
+
+ body = _graph(client, cid, expand=media)
+ assert _ids(body) == {media}
+ # Opened, with nothing to show for it: a true answer, and not a truncation. A view
+ # reporting itself cut because a lens left something out would read as a finding
+ # about the size of the case.
+ assert body["expanded"] == [media]
+ assert body["truncated"] is False
+
+
+def test_naming_a_node_the_reading_leaves_out_does_not_draw_it(client):
+ """The one place a lens outranks the rule that a named node survives the filters.
+ A filter is a narrowing set earlier; a lens is the reading itself."""
+ cid = _case(client, "named but not drawn")
+ person = _entity(client, cid, "person", "Subject")
+ post = _entity(client, cid, "post", "Thread draft")
+
+ body = _graph(client, cid, expand=post)
+ assert _ids(body) == {person}
+ assert body["expanded"] == []
+
+
+def test_a_neighbourhood_refuses_a_root_the_reading_does_not_draw(client):
+ """Said in words rather than answered with an empty picture, which would read as
+ a finding about the case."""
+ cid = _case(client, "hidden root")
+ note = _entity(client, cid, "note", "Working notes")
+
+ res = client.get(f"/api/cases/{cid}/graph/neighborhood", params={"root": note})
+ assert res.status_code == 400
+ assert "does not draw" in res.json()["detail"]
+
+ ok = client.get(
+ f"/api/cases/{cid}/graph/neighborhood", params={"root": note, "lens": "work"}
+ )
+ assert ok.status_code == 200
+
+
+def test_a_route_never_runs_through_a_node_the_reading_leaves_out(client):
+ """A sentence naming a node that is not on screen points at nothing, and the view
+ that tried to bring it in would refuse for the same reason."""
+ cid = _case(client, "route through the filing")
+ person = _entity(client, cid, "person", "Subject")
+ domain = _entity(client, cid, "domain", "example.test")
+ note = _entity(client, cid, "note", "Both are named here")
+ _link(client, cid, note, person, "mentions")
+ _link(client, cid, note, domain, "mentions")
+
+ def route(lens):
+ res = client.get(
+ f"/api/cases/{cid}/graph/paths",
+ params={"from": person, "to": domain, "lens": lens},
+ )
+ assert res.status_code == 200, res.text
+ return res.json()
+
+ assert route("all")["found"] is False
+ answered = route("work")
+ assert answered["found"] is True
+ assert note in {node["id"] for node in answered["nodes"]}
+
+
+# -- the wrapper is an edge ----------------------------------------------------
+#
+# An attestation on a statement→source chain is one edge, not a node. On a real case
+# that is a third of the drawing, and the path through it survives as what the edge
+# says rather than as a computation somebody has to do.
+
+
+def _derives(cid, from_id, to_id, type_):
+ """One derivation edge, filed the way a save files it.
+
+ Never through `POST /links`: a derivation is recorded by the save that produced the
+ artifact, and the API refuses to let it be asserted after the fact (`engine/links`).
+ """
+ Case.open(cid).add_link(from_id, to_id, type_, by="user")
+
+
+def _sourced(client, cid, *, sources=3, account="@harbourwatch"):
+ """A claim citing N bookmarks, all published by one account. The shape the
+ collapse exists for, and the shape the independence number is read off."""
+ claim = _entity(client, cid, "claim", "Shot at the quay")
+ who = _entity(client, cid, "account", account)
+ marks = []
+ for n in range(sources):
+ mark = _entity(client, cid, "bookmark", f"thread {n}", {"url": f"https://x.test/{n}"})
+ _link(client, cid, claim, mark, "cites")
+ _link(client, cid, who, mark, "posted")
+ marks.append(mark)
+ return claim, who, marks
+
+
+def _folded(payload):
+ return [link for link in payload["links"] if link.get("folded")]
+
+
+def test_three_citations_of_one_account_are_one_edge_that_says_so(client):
+ cid = _case(client, "fold sources")
+ claim, who, marks = _sourced(client, cid)
+
+ body = _graph(client, cid)
+ assert _ids(body) == {claim, who} # the three bookmarks are the edge now
+ edge = _folded(body)[0]
+ assert (edge["from"], edge["to"], edge["type"]) == (claim, who, "cites")
+ assert edge["folded"]["sources"] == 3
+ assert edge["folded"]["via"] == ["bookmark"]
+ assert edge["folded"]["accounts"] == 1
+ # Its id is stable and cannot be mistaken for a row: nothing may be written to it.
+ assert edge["id"] == f"{graph_engine.FOLDED_PREFIX}cites:{claim}:{who}"
+ assert client.delete(f"/api/cases/{cid}/links/{edge['id']}").status_code == 404
+
+
+def test_a_folded_edge_prices_the_click_it_leaves(client):
+ """The degree says what opening a node would bring in, so it answers to what is
+ drawn. Three citations that became one edge are one connection now, and the two the
+ fold removed must not go on being offered."""
+ cid = _case(client, "folded degree")
+ claim, who, _ = _sourced(client, cid)
+
+ body = _graph(client, cid)
+ assert _node(body, claim)["degree"] == 1
+ assert _node(body, who)["degree"] == 1
+
+
+def test_a_folded_edge_names_what_it_stands_for_and_hands_it_back(client):
+ """Expandable from the edge itself, and it is the same mechanism as opening a node:
+ a named node is never folded, so asking for one draws it with its own edges."""
+ cid = _case(client, "unfold")
+ claim, who, marks = _sourced(client, cid)
+
+ edge = _folded(_graph(client, cid))[0]
+ assert edge["folded"]["open"] == sorted(marks)
+
+ back = _graph(client, cid, expand=marks[0])
+ assert marks[0] in _ids(back)
+ # The one asked for is a node with its real edges; the other two are still the edge.
+ assert {link["type"] for link in back["links"] if not link.get("folded")} == {
+ "cites", "posted",
+ }
+ assert _folded(back)[0]["folded"]["sources"] == 2
+
+
+def test_an_attestation_nothing_states_anything_about_stays_a_node(client):
+ """The collapse is a reading of a statement→source chain, not of the type name. A
+ bookmark nobody cites is unexploited material, and unexploited material is exactly
+ what the drawing should show."""
+ cid = _case(client, "uncited")
+ mark = _entity(client, cid, "bookmark", "thread", {"url": "https://x.test/1"})
+ who = _entity(client, cid, "account", "@harbourwatch")
+ _link(client, cid, who, mark, "posted")
+
+ body = _graph(client, cid)
+ assert _ids(body) == {mark, who}
+ assert _folded(body) == []
+
+
+def test_a_middle_carrying_content_stays_a_node(client):
+ """A capture that shows a place holds something an edge between its neighbours
+ cannot say: folding it would turn "this vehicle appears in it" and "it shows this
+ place" into a claim about the vehicle and the place that nobody made."""
+ cid = _case(client, "content middle")
+ claim = _entity(client, cid, "claim", "The convoy passed here")
+ capture = _entity(
+ client, cid, "capture", "48.0, 2.0", {"path": "captures/x.png", "lat": 48.0}
+ )
+ place = _entity(client, cid, "place", "48.0, 2.0", {"lat": 48.0, "lon": 2.0})
+ proof = _entity(client, cid, "proof", "panel", {"spec": "proofs/x.json"})
+ _link(client, cid, claim, capture, "cites")
+ _link(client, cid, capture, place, "depicts")
+ # and the proof made from it is provenance, so that leg alone would have folded
+ _derives(cid, proof, capture, "derived-from")
+
+ body = _graph(client, cid)
+ assert capture in _ids(body)
+ assert _folded(body) == []
+
+
+def test_a_proof_between_a_statement_and_its_media_is_an_edge(client):
+ """The other provenance shape: a proof is a rendering of media the case already
+ holds, so the statement rests on the media through it."""
+ cid = _case(client, "fold proof")
+ claim = _entity(client, cid, "claim", "This is the same quay")
+ proof = _entity(client, cid, "proof", "panel", {"spec": "proofs/x.json"})
+ media = _entity(client, cid, "media", "quay.jpg", {"path": "media/quay.jpg"})
+ _link(client, cid, claim, proof, "cites")
+ _derives(cid, proof, media, "derived-from")
+
+ body = _graph(client, cid)
+ assert _ids(body) == {claim, media}
+ edge = _folded(body)[0]
+ assert (edge["from"], edge["to"]) == (claim, media)
+ # No account published a proof, so the edge says three words fewer.
+ assert edge["folded"]["accounts"] == 0
+
+
+def test_a_fold_is_only_as_confirmed_as_its_weakest_part(client):
+ """A proposal must not be laundered into a finding by being folded with a stated
+ edge: the path is not fully stated until both halves are."""
+ cid = _case(client, "fold status")
+ claim, who, marks = _sourced(client, cid, sources=1)
+ case = Case.open(cid)
+ edge = next(link for link in case.links_of(who) if link["type"] == "posted")
+ case.update_link(edge["id"], {"status": "suggested"})
+
+ assert _folded(_graph(client, cid))[0]["provenance"]["status"] == "suggested"
+
+
+def test_shape_outranks_the_type_name(client):
+ """SPEC §6's safeguard. A reconstructed case bends its own types — an import can
+ file an external source under a type meant for the analyst's own output — so a node
+ of a type this reading does not draw at all is collapsed when it turns out to lie on
+ the same chain, rather than dropped."""
+ cid = _case(client, "mislabelled source")
+ claim = _entity(client, cid, "claim", "Filmed from the bridge")
+ note = _entity(client, cid, "note", "imported source", {"path": "notes/x.md"})
+ media = _entity(client, cid, "media", "clip.mp4", {"path": "media/clip.mp4"})
+ _link(client, cid, claim, note, "cites")
+ _derives(cid, note, media, "derived-from")
+
+ body = _graph(client, cid)
+ assert _ids(body) == {claim, media}
+ edge = _folded(body)[0]
+ assert edge["folded"]["via"] == ["note"]
+ # Nothing to hand back: this reading does not draw a note at all, so the edge does
+ # not offer an act it would then refuse.
+ assert "open" not in edge["folded"]
+
+
+def test_a_fold_needs_both_ends_drawn(client):
+ """The closed set is the invariant: an edge whose far end was cut would have to
+ invent it. So the middle stays a node instead, and nothing is lost."""
+ cid = _case(client, "fold at the cut")
+ claim, who, marks = _sourced(client, cid, sources=1)
+
+ body = _graph(client, cid, limit=2) # the account does not fit
+ assert body["truncated"] is True
+ assert who not in _ids(body)
+ assert _folded(body) == []
+
+
+def test_a_source_the_budget_cut_still_joins_what_it_joined(client):
+ """The fold's promise held only under the ceiling until this.
+
+ The ranking cuts the least connected first, which is exactly the sources this
+ collapses — so on a case too large to draw whole, the case that needed it, a
+ statement resting on three sources and one account drew as a lone dot with both of
+ its ends on screen and nothing joining them. The middle being absent is not a
+ reason to lose the path through it: it is the reason the path has to be said as an
+ edge.
+ """
+ cid = _case(client, "cut middle")
+ claim, who, marks = _sourced(client, cid)
+
+ # The statement and the account carry three edges each, the bookmarks two, so the
+ # ranking keeps the two ends and cuts every middle.
+ body = _graph(client, cid, limit=2)
+ assert body["truncated"] is True
+ assert _ids(body) == {claim, who}
+
+ edge = _folded(body)[0]
+ assert (edge["from"], edge["to"], edge["type"]) == (claim, who, "cites")
+ assert edge["folded"]["sources"] == 3
+ assert edge["folded"]["via"] == ["bookmark"]
+ # And the finding is readable without opening anything, which is the whole point.
+ assert _node(body, claim)["rests"] == {"sources": 3, "accounts": 1, "one": True}
+ assert body["single_account"] == 1
+
+
+def test_a_source_the_budget_cut_is_handed_back_like_any_other(client):
+ """Whether an edge offers its sources back is a question about their **type**, not
+ about whether they are on screen: a bookmark cut by the budget is drawn by the same
+ `expand` that opens a node, where a type this reading leaves out could only be
+ refused."""
+ cid = _case(client, "hand back a cut source")
+ claim, who, marks = _sourced(client, cid)
+
+ edge = _folded(_graph(client, cid, limit=2))[0]
+ assert edge["folded"]["open"] == sorted(marks)
+
+ back = _graph(client, cid, limit=2, expand=marks[0])
+ assert marks[0] in _ids(back)
+ assert _folded(back)[0]["folded"]["sources"] == 2
+
+
+def test_the_click_a_folded_statement_offers_still_brings_what_it_says(client):
+ """The honest degree, through a middle that was never drawn. Nothing was removed
+ from the picture here — the three bookmarks were cut before the fold saw them — so
+ the count has to keep offering them while the edge stands for them."""
+ cid = _case(client, "cut middle degree")
+ claim, who, marks = _sourced(client, cid)
+
+ body = _graph(client, cid, limit=2)
+ # One edge drawn, and three sources plus the fold's own edge still to bring in.
+ assert _node(body, claim)["degree"] == 4
+
+ back = _graph(client, cid, limit=2, expand=",".join(marks))
+ assert set(marks) <= _ids(back)
+
+
+# -- independence --------------------------------------------------------------
+
+
+def test_a_statement_says_how_many_sources_and_how_many_accounts(client):
+ """The first independence number, and it falls out of the collapsed edge: "three
+ citations" is not "three sources" when one account published all three."""
+ cid = _case(client, "independence")
+ claim, who, _ = _sourced(client, cid)
+
+ body = _graph(client, cid)
+ assert _node(body, claim)["rests"] == {"sources": 3, "accounts": 1, "one": True}
+ assert body["single_account"] == 1
+
+
+def test_two_accounts_behind_the_same_statement_are_two_sources(client):
+ cid = _case(client, "two accounts")
+ claim = _entity(client, cid, "claim", "Two witnesses")
+ for n, handle in enumerate(("@one", "@two")):
+ who = _entity(client, cid, "account", handle)
+ mark = _entity(client, cid, "bookmark", f"post {n}", {"url": f"https://x.test/{n}"})
+ _link(client, cid, claim, mark, "cites")
+ _link(client, cid, who, mark, "posted")
+
+ body = _graph(client, cid)
+ assert _node(body, claim)["rests"] == {"sources": 2, "accounts": 2, "one": False}
+ # Two independent sources is not the finding, so the number stays at zero.
+ assert body["single_account"] == 0
+
+
+def test_a_source_still_drawn_as_a_node_is_counted_too(client):
+ """The number answers to the drawing, not to which nodes happened to collapse: an
+ uncollapsed citation is a source the statement rests on like any other."""
+ cid = _case(client, "counted whole")
+ claim = _entity(client, cid, "claim", "Two sources, one folded")
+ who = _entity(client, cid, "account", "@harbourwatch")
+ posted = _entity(client, cid, "bookmark", "thread", {"url": "https://x.test/1"})
+ lone = _entity(client, cid, "bookmark", "report", {"url": "https://x.test/2"})
+ _link(client, cid, claim, posted, "cites")
+ _link(client, cid, who, posted, "posted")
+ _link(client, cid, claim, lone, "cites")
+
+ body = _graph(client, cid)
+ assert lone in _ids(body) and posted not in _ids(body)
+ assert _node(body, claim)["rests"] == {"sources": 2, "accounts": 1, "one": False}
+ # One of the two sources has no account behind it, so this is not "all on one".
+ assert body["single_account"] == 0
+
+
+def test_resting_on_another_statement_is_not_resting_on_a_source(client):
+ """A cited statement is reasoning, not material, so it never lifts the number.
+
+ The independence count answers "three citations, how many sources" — a statement
+ built on another statement has found nothing new, and counting it would say the
+ opposite of what the graph is drawing.
+ """
+ cid = _case(client, "grounded on reasoning")
+ model = _entity(client, cid, "claim", "The vehicle is a T-72B3")
+ unit = _entity(client, cid, "claim", "The column is the 4th brigade")
+ video = _entity(client, cid, "media", "Column", {"path": "media/column.mp4"})
+ _link(client, cid, model, video, "cites")
+ _link(client, cid, unit, model, "cites")
+
+ body = _graph(client, cid)
+ # The one that reached material rests on it; the one that reached a statement
+ # rests on nothing of its own, which is the honest reading.
+ assert _node(body, model)["rests"] == {"sources": 1, "accounts": 0, "one": False}
+ assert "rests" not in _node(body, unit)
+ assert body["single_account"] == 0
+
+
+def test_a_statement_with_nothing_to_rest_on_says_nothing(client):
+ cid = _case(client, "no sources")
+ claim = _entity(client, cid, "claim", "Unsupported")
+ place = _entity(client, cid, "place", "1.0, 1.0", {"lat": 1.0, "lon": 1.0})
+ _link(client, cid, claim, place, "at")
+
+ body = _graph(client, cid)
+ assert "rests" not in _node(body, claim)
+ assert body["single_account"] == 0
+
+
+# -- the global view ----------------------------------------------------------
+
+
+def test_the_graph_opens_on_the_whole_case(client):
+ """A case is a subject before it is a set of statements — a conflict followed
+ over months has no single root — so the entry point is everything."""
+ cid = _case(client, "whole case")
+ unit = _entity(client, cid, "organization", "3rd Battalion")
+ driver = _entity(client, cid, "person", "Driver")
+ _link(client, cid, driver, unit, "member-of")
+ lone = _entity(client, cid, "domain", "example.test")
+
+ body = _graph(client, cid)
+ assert _ids(body) == {unit, driver, lone}
+ assert body["total"] == 3
+ assert body["truncated"] is False
+
+
+def test_a_lens_narrows_the_edges_and_keeps_a_subject_with_none(client):
+ """Narrowing the verbs must not hide a subject: an entity with no edge in this
+ lens is a real answer — it is what nobody has connected yet. What a lens does take
+ out of the drawing is a whole role, never one node for want of an edge."""
+ cid = _case(client, "lens edges")
+ unit = _entity(client, cid, "organization", "Brigade")
+ person = _entity(client, cid, "person", "Officer")
+ place = _entity(client, cid, "place", "48.0, 2.0")
+ _link(client, cid, person, unit, "member-of")
+
+ subjects = _graph(client, cid, lens="subjects")
+ assert _ids(subjects) == {unit, person, place}
+ assert [link["type"] for link in subjects["links"]] == ["member-of"]
+
+ ground = _graph(client, cid, lens="ground")
+ assert _ids(ground) == {unit, person, place}
+ assert ground["links"] == []
+
+
+def test_only_edges_with_both_ends_on_screen_are_returned(client):
+ """A drawn edge whose far node was never sent would have to invent it. The
+ closed set is what the view guarantees."""
+ cid = _case(client, "closed set")
+ hub = _entity(client, cid, "organization", "Hub")
+ others = [_entity(client, cid, "person", f"Member {n}") for n in range(6)]
+ for other in others:
+ _link(client, cid, other, hub, "member-of")
+
+ body = _graph(client, cid, limit=3)
+ shown = _ids(body)
+ assert len(shown) == 3
+ for link in body["links"]:
+ assert link["from"] in shown and link["to"] in shown
+
+
+def test_a_cut_view_keeps_the_hubs_and_says_it_was_cut(client):
+ """The whole point of ranking: what survives a truncated case is its shape."""
+ cid = _case(client, "hub first")
+ hub = _entity(client, cid, "organization", "Command")
+ for n in range(8):
+ member = _entity(client, cid, "person", f"Member {n}")
+ _link(client, cid, member, hub, "member-of")
+ for n in range(8):
+ _entity(client, cid, "domain", f"loose{n}.test")
+
+ body = _graph(client, cid, limit=4)
+ assert hub in _ids(body)
+ assert body["truncated"] is True
+ assert body["total"] == 17
+ assert body["shown"] == 4
+ degrees = [node["degree"] for node in body["nodes"]]
+ assert degrees == sorted(degrees, reverse=True)
+
+
+def test_ranking_by_recent_keeps_the_latest_work(client):
+ """The other honest cut, and the seam a stated-time ordering slots into: what
+ an analyst touched last is what they are still working on."""
+ cid = _case(client, "recent first")
+ first = _entity(client, cid, "person", "Filed first")
+ last = _entity(client, cid, "person", "Filed last")
+
+ body = _graph(client, cid, order="recent", limit=1)
+ assert _ids(body) == {last}
+ assert first not in _ids(body)
+
+
+def test_an_unknown_ordering_is_refused(client):
+ cid = _case(client, "bad order")
+ res = client.get(f"/api/cases/{cid}/graph", params={"order": "alphabetical"})
+ assert res.status_code == 400
+
+
+def test_the_node_budget_cannot_be_raised_past_the_ceiling(client, monkeypatch):
+ """No request reaches the whole graph, whatever it asks for. The clamp is
+ asserted on the limit that reaches storage, since a small fixture would pass
+ this on its size alone."""
+ cid = _case(client, "ceiling")
+ _entity(client, cid, "person", "Only one")
+
+ from azimut import workspace
+
+ asked: list[int] = []
+ original = workspace.Case.rank_entities
+
+ def record(self, **kwargs):
+ asked.append(kwargs["limit"])
+ return original(self, **kwargs)
+
+ monkeypatch.setattr(workspace.Case, "rank_entities", record)
+ _graph(client, cid, limit=10_000)
+ _graph(client, cid, limit=0)
+ assert asked == [graph_engine.MAX_OPENING, 1]
+
+
+def test_degree_counts_only_the_lens_being_read(client):
+ """A node reads as isolated in a lens it truly has no edge in, so the isolated
+ count means something rather than being a global figure repeated."""
+ cid = _case(client, "lens degree")
+ person = _entity(client, cid, "person", "Subject")
+ place = _entity(client, cid, "place", "1.0, 1.0")
+ unit = _entity(client, cid, "organization", "Unit")
+ _link(client, cid, person, unit, "member-of")
+
+ subjects = {n["id"]: n["degree"] for n in _graph(client, cid, lens="subjects")["nodes"]}
+ assert subjects[person] == 1 and subjects[place] == 0
+
+ ground = {n["id"]: n["degree"] for n in _graph(client, cid, lens="ground")["nodes"]}
+ assert ground[person] == 0
+
+
+def test_the_view_counts_what_nobody_has_connected(client):
+ """The case's unexploited material, and the one number a table cannot show."""
+ cid = _case(client, "isolated")
+ person = _entity(client, cid, "person", "Linked")
+ unit = _entity(client, cid, "organization", "Unit")
+ _link(client, cid, person, unit, "member-of")
+ for n in range(3):
+ _entity(client, cid, "domain", f"untouched{n}.test")
+
+ assert _graph(client, cid)["isolated"] == 3
+
+
+def test_what_nobody_connected_is_counted_over_the_case_not_the_drawing(client):
+ """The number a cut view must not lose, and used to.
+
+ An entity with no edge sorts last under `degree`, so it is the first thing a cut
+ discards — counted off the returned nodes, "what nobody has connected" reported
+ zero on exactly the cases too large to draw. Two linked entities and four loose
+ ones, drawn two at a time: the drawing holds the pair, and the count still says
+ four.
+ """
+ cid = _case(client, "isolated at scale")
+ person = _entity(client, cid, "person", "Linked")
+ unit = _entity(client, cid, "organization", "Unit")
+ _link(client, cid, person, unit, "member-of")
+ for n in range(4):
+ _entity(client, cid, "domain", f"loose{n}.test")
+
+ body = _graph(client, cid, limit=2)
+ assert body["truncated"] is True
+ assert _ids(body) == {person, unit}
+ assert body["isolated"] == 4
+
+
+def test_a_narrowing_cannot_inflate_what_nobody_connected(client):
+ """Hiding the far end of an edge must not make its near end read as unexploited.
+
+ The degree is read over the lens's verbs, never over whether the other end was
+ returned. So filtering the places out of the drawing leaves the media that was
+ recorded at one connected, which is the truth about the case.
+ """
+ cid = _case(client, "narrowed isolation")
+ media = _entity(
+ client, cid, "media", "quay.jpg", {"path": "media/quay.jpg", "kind": "image"}
+ )
+ place = _entity(client, cid, "place", "48.0, 2.0", {"lat": 48.0, "lon": 2.0})
+ _link(client, cid, media, place, "located-at")
+
+ body = _graph(client, cid, lens="ground", type="media")
+ assert _ids(body) == {media}
+ assert _node(body, media)["degree"] == 1
+ assert body["isolated"] == 0
+
+
+def test_the_catalog_filters_mean_the_same_thing_on_the_graph(client):
+ """The board and the graph must not disagree about "confirmed people here"."""
+ cid = _case(client, "shared filters")
+ _entity(client, cid, "person", "Kept")
+ _entity(client, cid, "domain", "dropped.test")
+
+ body = _graph(client, cid, type="person")
+ assert body["total"] == 1
+ assert [node["type"] for node in body["nodes"]] == ["person"]
+
+
+def test_a_node_carries_its_family_so_no_second_lookup_is_needed(client):
+ cid = _case(client, "family on node")
+ _entity(client, cid, "vessel", "Ship")
+ node = _graph(client, cid)["nodes"][0]
+ assert node["family"] == entity_engine.ASSET
+ assert node["status"] == "confirmed"
+ assert node["at"]
+
+
+def test_a_node_with_a_picture_carries_its_thumbnail_and_never_the_file(client):
+ """A card on the graph shows a preview, and the preview has to be the cached
+ thumbnail: a few hundred nodes reaching for their own full-size image would
+ download the case to draw it. An entity with no indexed media carries no key at
+ all, which is what lets a client tell "no picture" from "not loaded"."""
+ cid = _case(client, "previews")
+ buf = io.BytesIO()
+ Image.new("RGB", (64, 48), (30, 90, 160)).save(buf, "PNG")
+ client.post(
+ f"/api/cases/{cid}/media/upload",
+ files={"file": ("shot.png", io.BytesIO(buf.getvalue()), "image/png")},
+ )
+ _entity(client, cid, "person", "Nobody")
+
+ nodes = {node["label"]: node for node in _graph(client, cid)["nodes"]}
+ assert nodes["shot"]["thumb"].startswith("media/")
+ assert "thumb" not in nodes["Nobody"]
+ # The thumbnail, not the media file the entity points at.
+ assert nodes["shot"]["thumb"] != "media/shot.png"
+
+
+# -- the neighborhood ---------------------------------------------------------
+
+
+def _hood(client, cid, root, **params):
+ res = client.get(
+ f"/api/cases/{cid}/graph/neighborhood", params={"root": root, **params}
+ )
+ assert res.status_code == 200, res.text
+ return res.json()
+
+
+def test_one_hop_reaches_the_direct_neighbours_only(client):
+ cid = _case(client, "one hop")
+ person = _entity(client, cid, "person", "Root")
+ unit = _entity(client, cid, "organization", "Unit")
+ parent = _entity(client, cid, "organization", "Parent")
+ _link(client, cid, person, unit, "member-of")
+ _link(client, cid, unit, parent, "part-of")
+
+ body = _hood(client, cid, person)
+ assert _ids(body) == {person, unit}
+ assert {node["id"]: node["hop"] for node in body["nodes"]}[unit] == 1
+
+
+def test_a_second_hop_reaches_further_and_records_the_distance(client):
+ cid = _case(client, "two hops")
+ person = _entity(client, cid, "person", "Root")
+ unit = _entity(client, cid, "organization", "Unit")
+ parent = _entity(client, cid, "organization", "Parent")
+ _link(client, cid, person, unit, "member-of")
+ _link(client, cid, unit, parent, "part-of")
+
+ body = _hood(client, cid, person, hops=2)
+ assert _ids(body) == {person, unit, parent}
+ hops = {node["id"]: node["hop"] for node in body["nodes"]}
+ assert hops == {person: 0, unit: 1, parent: 2}
+
+
+def test_the_walk_is_bounded_by_hops_whatever_the_graph_holds(client):
+ cid = _case(client, "hop ceiling")
+ chain = [_entity(client, cid, "organization", f"Echelon {n}") for n in range(8)]
+ for lower, upper in zip(chain, chain[1:]):
+ _link(client, cid, lower, upper, "part-of")
+
+ body = _hood(client, cid, chain[0], hops=99)
+ assert body["hops"] == graph_engine.MAX_HOPS
+ assert body["shown"] == graph_engine.MAX_HOPS + 1
+
+
+def test_a_neighbour_reports_the_degree_an_expansion_would_cost(client):
+ """The click's price before it is paid — the guard against the hairball."""
+ cid = _case(client, "degree before expanding")
+ root = _entity(client, cid, "person", "Root")
+ unit = _entity(client, cid, "organization", "Busy unit")
+ _link(client, cid, root, unit, "member-of")
+ for n in range(5):
+ other = _entity(client, cid, "person", f"Other {n}")
+ _link(client, cid, other, unit, "member-of")
+
+ body = _hood(client, cid, root)
+ degrees = {node["id"]: node["degree"] for node in body["nodes"]}
+ assert degrees[unit] == 6 # one edge shown, five more behind it
+ assert body["shown"] == 2
+
+
+def test_the_node_budget_ending_a_walk_is_reported(client):
+ cid = _case(client, "hood budget")
+ hub = _entity(client, cid, "organization", "Hub")
+ for n in range(6):
+ member = _entity(client, cid, "person", f"Member {n}")
+ _link(client, cid, member, hub, "member-of")
+
+ body = _hood(client, cid, hub, limit=3)
+ assert body["shown"] == 3
+ assert body["truncated"] is True
+
+
+def test_a_neighborhood_returns_the_closed_edge_set(client):
+ cid = _case(client, "hood closed set")
+ hub = _entity(client, cid, "organization", "Hub")
+ for n in range(6):
+ member = _entity(client, cid, "person", f"Member {n}")
+ _link(client, cid, member, hub, "member-of")
+
+ body = _hood(client, cid, hub, limit=3)
+ shown = _ids(body)
+ for link in body["links"]:
+ assert link["from"] in shown and link["to"] in shown
+
+
+def test_the_outermost_ring_holds_the_edges_inside_it(client):
+ """Closed is half the promise; the other half is complete.
+
+ An edge between two nodes reached at the **same** hop touches neither of the
+ frontiers that found them, so a walk that collected edges hop by hop came back
+ with an outermost ring that had none inside it. A triangle around a root drew as
+ a star, and both far nodes reported the edge between them as a connection lying
+ further out than the hops asked for — a count no reachable control could settle.
+ """
+ cid = _case(client, "hood outer ring")
+ photo = _entity(
+ client, cid, "media", "roof.jpg", {"path": "media/roof.jpg", "kind": "image"}
+ )
+ account = _entity(client, cid, "account", "@poster")
+ person = _entity(client, cid, "person", "Poster")
+ _link(client, cid, account, photo, "posted")
+ _link(client, cid, person, photo, "appears-in")
+ # The edge the walk cannot witness, and on a worked case the finding: the person
+ # in the picture is the one who put it out.
+ across = _link(client, cid, person, account, "owns")
+
+ body = _hood(client, cid, photo, hops=1)
+
+ assert _ids(body) == {photo, account, person}
+ assert across in {link["id"] for link in body["links"]}
+ # And the degree each node states is now settled by what is drawn, which is what
+ # the panel subtracts to decide there is anything left to open.
+ for node in body["nodes"]:
+ assert node["degree"] == 2
+
+
+def test_a_lens_scopes_the_walk(client):
+ cid = _case(client, "hood lens")
+ person = _entity(client, cid, "person", "Root")
+ unit = _entity(client, cid, "organization", "Unit")
+ _link(client, cid, person, unit, "member-of")
+
+ assert _ids(_hood(client, cid, person, lens="ground")) == {person}
+
+
+def test_a_missing_root_is_a_404(client):
+ cid = _case(client, "no root")
+ res = client.get(
+ f"/api/cases/{cid}/graph/neighborhood", params={"root": "e_nope"}
+ )
+ assert res.status_code == 404
+
+
+def test_a_media_node_says_whether_it_is_a_video_or_a_picture(client):
+ """One `media` type covers images, video, audio and everything else, so a node
+ that cannot say which it holds draws as a generic file and reads as a document.
+ The browse index is the authority, because the importer put the kind there."""
+ cid = _case(client, "media kinds")
+ png = io.BytesIO()
+ Image.new("RGB", (8, 6), (10, 20, 30)).save(png, "PNG")
+ res = client.post(
+ f"/api/cases/{cid}/media/upload",
+ files={"file": ("frame.png", io.BytesIO(png.getvalue()), "image/png")},
+ )
+ assert res.status_code == 200, res.text
+ path = res.json()["item"]["path"]
+ entity = client.get(
+ f"/api/cases/{cid}/entities/lookup", params={"attr": "path", "value": path}
+ ).json()["entity"]
+
+ assert _node(_graph(client, cid), entity["id"])["kind"] == "image"
+
+
+def test_a_kind_is_carried_for_media_and_for_nothing_else(client):
+ """It answers a question only that type raises: a person is a person."""
+ cid = _case(client, "kind only for media")
+ person = _entity(client, cid, "person", "Not a file")
+
+ assert "kind" not in _node(_graph(client, cid), person)
+
+
+def test_a_media_entity_the_index_never_saw_still_says_what_it_is(client):
+ """A tool can file a media row without registering a browse row; the attr the
+ importer would have written is the fallback."""
+ cid = _case(client, "kind from attrs")
+ clip = _entity(client, cid, "media", "clip.mp4", {"path": "media/clip.mp4", "kind": "video"})
+
+ assert _node(_graph(client, cid), clip)["kind"] == "video"
+
+
+def test_a_neighbourhood_says_what_its_media_holds_too(client):
+ """The same question, asked from a root: an expansion that drew every file the
+ same would lose the reading the whole-case view gives."""
+ cid = _case(client, "hood kinds")
+ person = _entity(client, cid, "person", "Root")
+ clip = _entity(client, cid, "media", "clip.mp4", {"path": "media/clip.mp4", "kind": "video"})
+ _link(client, cid, person, clip, "appears-in")
+
+ assert _node(_hood(client, cid, person), clip)["kind"] == "video"
+
+
+# -- material the case made, told apart from material it collected -------------
+#
+# A frame, an adjustment, a collage: filed as ordinary media, and drawn with the
+# same glyph as a photograph somebody handed over. Nothing on the drawing says
+# which. The route is already in the browse index, so the node carries it, and it
+# carries it only for the tools that compose case material: "upload" on an upload
+# says nothing about the upload.
+
+
+def _upload(client, cid, name="shot.png", colour=(10, 20, 30)):
+ """One real file through the real importer — the index row is what this is for."""
+ png = io.BytesIO()
+ Image.new("RGB", (8, 6), colour).save(png, "PNG")
+ res = client.post(
+ f"/api/cases/{cid}/media/upload",
+ files={"file": (name, io.BytesIO(png.getvalue()), "image/png")},
+ )
+ assert res.status_code == 200, res.text
+ return res.json()["item"]
+
+
+def _entity_at(client, cid, path):
+ return client.get(
+ f"/api/cases/{cid}/entities/lookup", params={"attr": "path", "value": path}
+ ).json()["entity"]["id"]
+
+
+def _adjusted(client, cid, path, amount=1.4, label=None):
+ """A derivative through the real Inspect route, so this tests the wiring rather
+ than a hand-written index row."""
+ res = client.post(
+ f"/api/cases/{cid}/inspect/save-frames",
+ json={
+ "items": [
+ {
+ "path": path,
+ "ops": [{"op": "brightness", "params": {"amount": amount}}],
+ **({"label": label} if label else {}),
+ }
+ ]
+ },
+ )
+ assert res.status_code == 200, res.text
+ return res.json()["saved"][0]
+
+
+def test_a_node_made_here_says_which_act_made_it(client):
+ """The whole point of step one: a derivative and a photograph are the same node
+ today, so a video with twelve saved frames draws as thirteen pictures with
+ nothing saying which twelve came out of the first."""
+ cid = _case(client, "made here")
+ original = _upload(client, cid, "orig.png")
+ derived = _adjusted(client, cid, original["path"])["item"]
+
+ node = _node(_graph(client, cid), _entity_at(client, cid, derived["path"]))
+ assert node["origin"] == "inspect"
+ assert node["op"] == "adjust"
+
+
+def test_collected_material_carries_no_origin(client):
+ """Only the tools that compose case material mark their output. An upload came
+ from outside the case, and a node saying "upload" would be a mark on everything,
+ which is a mark on nothing."""
+ cid = _case(client, "collected")
+ original = _upload(client, cid, "orig.png")
+
+ node = _node(_graph(client, cid), _entity_at(client, cid, original["path"]))
+ assert "origin" not in node and "op" not in node
+
+
+def test_a_media_entity_the_index_never_saw_claims_no_origin(client):
+ """Unlike the kind, nothing writes the route to the entity, so there is no
+ fallback to read — and a default here would be the drawing inventing where a
+ file came from."""
+ cid = _case(client, "unindexed origin")
+ clip = _entity(client, cid, "media", "clip.mp4", {"path": "media/clip.mp4", "kind": "video"})
+
+ assert "origin" not in _node(_graph(client, cid), clip)
+
+
+def test_identical_bytes_arriving_later_do_not_rewrite_how_a_file_entered(client):
+ """Dedupe hands back the entity that is already there, and its row with it. The
+ file was made in Inspect; somebody importing the same bytes afterwards is a
+ second route to it, not a different origin — which is exactly why the origin is
+ read off the index rather than guessed from the links, where both are true."""
+ cid = _case(client, "deduped origin")
+ original = _upload(client, cid, "orig.png")
+ made = _adjusted(client, cid, original["path"])["item"]
+ same_bytes = client.get(f"/files/{cid}/{made['path']}").content
+
+ again = client.post(
+ f"/api/cases/{cid}/media/upload",
+ files={"file": ("handed-over.png", io.BytesIO(same_bytes), "image/png")},
+ )
+ assert again.status_code == 200, again.text
+ assert again.json()["duplicate"] is True
+
+ node = _node(_graph(client, cid), _entity_at(client, cid, made["path"]))
+ assert node["origin"] == "inspect"
+
+
+def test_a_neighbourhood_says_what_was_made_here_too(client):
+ """Read from a root, the derivation is the reading: this is the hop where an
+ analyst is following where a picture came from."""
+ cid = _case(client, "hood origins")
+ original = _upload(client, cid, "orig.png")
+ made = _adjusted(client, cid, original["path"])["item"]
+ source_id = _entity_at(client, cid, original["path"])
+ made_id = _entity_at(client, cid, made["path"])
+
+ assert _node(_hood(client, cid, source_id), made_id)["origin"] == "inspect"
+
+
+def test_a_route_says_what_was_made_here_too(client):
+ """A route through a derivative is the answer to "how did we get here", so the
+ node that says it was made here has to say it there as well."""
+ cid = _case(client, "route origins")
+ original = _upload(client, cid, "orig.png")
+ made = _adjusted(client, cid, original["path"])["item"]
+ source_id = _entity_at(client, cid, original["path"])
+ made_id = _entity_at(client, cid, made["path"])
+
+ res = client.get(
+ f"/api/cases/{cid}/graph/paths", params={"from": made_id, "to": source_id}
+ )
+ assert res.status_code == 200, res.text
+ body = res.json()
+ assert body["found"] is True
+ assert _node(body, made_id)["origin"] == "inspect"
+
+
+# -- a step is an edge too -----------------------------------------------------
+#
+# A frame pulled out of a video and built into a proof is a node saying "there was a
+# step here", and it spends a slot to say it. Collapsed, the step is what the edge is
+# written with. The direction guard is the load-bearing half: a node made from two
+# sources is a confluence, and folding it would say one of them came out of the other.
+
+
+def _proof(client, cid, label="panel"):
+ return _entity(client, cid, "proof", label, {"spec": f"proofs/{label}.json"})
+
+
+def _built_on(client, cid):
+ """A proof built on an adjustment of an uploaded picture, through the real Inspect
+ route, so the word the edge is written with comes from the act the case recorded
+ rather than from a fixture. Returns ``(source, step, proof)``."""
+ original = _upload(client, cid, "clip.png")
+ made = _adjusted(client, cid, original["path"])["item"]
+ source_id = _entity_at(client, cid, original["path"])
+ step_id = _entity_at(client, cid, made["path"])
+ proof = _proof(client, cid)
+ _derives(cid, proof, step_id, "derived-from")
+ return source_id, step_id, proof
+
+
+def test_an_adjustment_the_case_calls_the_same_picture_stays_a_node(client):
+ """Saving an adjustment files a mirror suggestion between it and the original, and
+ that is a finding about the world: an edge from the proof to the original cannot
+ say "these two are one picture", so the step is carrying something the fold would
+ drop."""
+ cid = _case(client, "mirrored step")
+ source_id, step_id, proof = _built_on(client, cid)
+
+ body = _graph(client, cid)
+ assert step_id in _ids(body)
+ assert _folded(body) == []
+ # The proof concludes nothing and nothing cites it, so it is what came out of the
+ # step and was not used: a count on it rather than a node of its own.
+ assert _node(body, step_id)["rolled"] == {"count": 1, "via": ["proof"], "open": [proof]}
+
+
+def test_a_step_between_a_source_and_what_was_made_from_it_is_an_edge(client):
+ """The shape the whole reading exists for. The mirror suggestion is dropped first,
+ the way an analyst who disagrees with it does — with nothing else on the step, it
+ relays the picture to the proof and says so as an edge."""
+ cid = _case(client, "fold a step")
+ source_id, step_id, proof = _built_on(client, cid)
+ mirror = next(
+ link for link in Case.open(cid).links_of(step_id)
+ if link["type"] == "same-image-as"
+ )
+ assert client.delete(f"/api/cases/{cid}/links/{mirror['id']}").status_code == 200
+
+ body = _graph(client, cid)
+ assert _ids(body) == {source_id, proof} # the step is the edge now
+ edge = _folded(body)[0]
+ assert (edge["from"], edge["to"], edge["type"]) == (proof, source_id, "derived-from")
+ assert edge["folded"]["sources"] == 1
+ # The act, not the type: "1 adjusted image" says what "1 media" cannot.
+ assert edge["folded"]["via"] == ["adjust"]
+ assert edge["folded"]["open"] == [step_id]
+ assert edge["id"] == (
+ f"{graph_engine.FOLDED_PREFIX}derived-from:{proof}:{source_id}"
+ )
+ # Nothing may be written to it: the case holds no such row.
+ assert client.delete(f"/api/cases/{cid}/links/{edge['id']}").status_code == 404
+
+
+def test_a_step_with_no_act_recorded_reads_as_what_it_is(client):
+ """A derivation the index never saw still folds — the shape is the rule, and the
+ origin only decides the word. It falls back to the type rather than going mute."""
+ cid = _case(client, "wordless step")
+ video = _media(client, cid, "clip")
+ frame = _media(client, cid, "frame")
+ proof = _proof(client, cid)
+ _derives(cid, frame, video, "derived-from")
+ _derives(cid, proof, frame, "derived-from")
+
+ edge = _folded(_graph(client, cid))[0]
+ assert edge["folded"]["via"] == ["media"]
+
+
+def test_a_node_made_from_two_sources_is_not_a_passage(client):
+ """The direction guard, and the reason it exists. A proof built from footage *and*
+ from overhead imagery is a confluence: collapsed, the edge left standing would say
+ the capture came out of the video, which is the false convergence this reading is
+ against."""
+ cid = _case(client, "confluence")
+ video = _media(client, cid, "clip")
+ capture = _entity(
+ client, cid, "capture", "48.0, 2.0", {"path": "captures/x.png", "lat": 48.0}
+ )
+ proof = _proof(client, cid)
+ _derives(cid, proof, video, "derived-from")
+ _derives(cid, proof, capture, "derived-from")
+
+ body = _graph(client, cid)
+ assert _ids(body) == {video, capture, proof}
+ assert _folded(body) == []
+
+
+def test_a_step_that_says_something_about_the_world_stays_a_node(client):
+ """All-or-nothing, the rule the fold above already keeps. A frame that shows a
+ place carries a finding, and an edge between the video and the proof cannot say
+ it."""
+ cid = _case(client, "geolocated step")
+ video = _media(client, cid, "clip")
+ frame = _media(client, cid, "frame")
+ place = _entity(client, cid, "place", "48.0, 2.0", {"lat": 48.0, "lon": 2.0})
+ proof = _proof(client, cid)
+ _derives(cid, frame, video, "derived-from")
+ _derives(cid, proof, frame, "derived-from")
+ _link(client, cid, frame, place, "depicts")
+
+ body = _graph(client, cid)
+ assert frame in _ids(body)
+ assert _folded(body) == []
+
+
+def test_two_steps_in_a_row_are_one_edge(client):
+ """A frame adjusted and then built on is two steps and one sentence. The walk runs
+ to the first node that is not itself a step, and the edge names what it went
+ through."""
+ cid = _case(client, "two steps")
+ video = _media(client, cid, "clip")
+ frame = _media(client, cid, "frame")
+ lighter = _media(client, cid, "frame lighter")
+ proof = _proof(client, cid)
+ _derives(cid, frame, video, "derived-from")
+ _derives(cid, lighter, frame, "derived-from")
+ _derives(cid, proof, lighter, "derived-from")
+
+ body = _graph(client, cid)
+ assert _ids(body) == {video, proof}
+ edge = _folded(body)[0]
+ assert (edge["from"], edge["to"]) == (proof, video)
+ assert edge["folded"]["sources"] == 2
+ assert edge["folded"]["open"] == sorted([frame, lighter])
+
+
+def test_a_derivative_nothing_was_made_from_is_not_a_passage(client):
+ """The boundary between the two acts. A chain leaf relays nothing, so no edge can
+ stand for it: it is a count on the node it came out of instead, and the drawing
+ never loses the fact that the video has a frame."""
+ cid = _case(client, "chain leaf")
+ video = _media(client, cid, "clip")
+ frame = _media(client, cid, "frame")
+ _derives(cid, frame, video, "derived-from")
+
+ body = _graph(client, cid)
+ assert _folded(body) == []
+ assert _node(body, video)["rolled"]["open"] == [frame]
+
+
+def test_a_folded_step_prices_the_click_it_leaves(client):
+ """The honest degree. Two chain edges became one, and the node must not go on
+ offering to bring in what is no longer there to bring."""
+ cid = _case(client, "step degree")
+ video = _media(client, cid, "clip")
+ frame = _media(client, cid, "frame")
+ proof = _proof(client, cid)
+ _derives(cid, frame, video, "derived-from")
+ _derives(cid, proof, frame, "derived-from")
+
+ body = _graph(client, cid)
+ assert _node(body, video)["degree"] == 1
+ assert _node(body, proof)["degree"] == 1
+
+
+def test_a_folded_step_hands_its_nodes_back(client):
+ """The same way back as every other fold: a named node is never folded, so asking
+ for the step draws it with its own edges again. The proof is built on an overhead
+ capture as well, which is what keeps it a node of its own on both reads."""
+ cid = _case(client, "unfold a step")
+ video = _media(client, cid, "clip")
+ frame = _media(client, cid, "frame")
+ capture = _entity(
+ client, cid, "capture", "48.0, 2.0", {"path": "captures/x.png", "lat": 48.0}
+ )
+ proof = _proof(client, cid)
+ _derives(cid, frame, video, "derived-from")
+ _derives(cid, proof, frame, "derived-from")
+ _derives(cid, proof, capture, "derived-from")
+
+ assert _ids(_graph(client, cid)) == {video, capture, proof}
+
+ back = _graph(client, cid, expand=frame)
+ assert _ids(back) == {video, capture, frame, proof}
+ assert _folded(back) == []
+ assert _node(back, frame)["degree"] == 2
+
+
+def test_a_folded_step_is_only_as_confirmed_as_its_weakest_part(client):
+ """A fold must not launder a proposal into a finding: the path is not stated until
+ every leg of it is."""
+ cid = _case(client, "step status")
+ video = _media(client, cid, "clip")
+ frame = _media(client, cid, "frame")
+ proof = _proof(client, cid)
+ _derives(cid, frame, video, "derived-from")
+ _derives(cid, proof, frame, "derived-from")
+ case = Case.open(cid)
+ edge = next(link for link in case.links_of(frame) if link["to"] == video)
+ case.update_link(edge["id"], {"status": "suggested"})
+
+ assert _folded(_graph(client, cid))[0]["provenance"]["status"] == "suggested"
+
+
+def test_the_filing_lens_draws_its_own_production_chain(client):
+ """`My work` answers *what did I write, and out of what*. Folding the production
+ chain there would fold the answer, so the pass asks what makes a reading one of the
+ case rather than naming a lens."""
+ cid = _case(client, "work keeps its steps")
+ video = _media(client, cid, "clip")
+ frame = _media(client, cid, "frame")
+ proof = _proof(client, cid)
+ _derives(cid, frame, video, "derived-from")
+ _derives(cid, proof, frame, "derived-from")
+
+ body = _graph(client, cid, lens="work")
+ assert {video, frame, proof} <= _ids(body)
+ assert _folded(body) == []
+
+
+def test_a_derivation_that_loops_back_folds_nothing(client):
+ """A loop names no source, so nothing on it relays anything. Filed straight into
+ the store, the way a broken producer would file it: the drawing has to hold rather
+ than walk it forever."""
+ cid = _case(client, "looping derivation")
+ first = _media(client, cid, "one")
+ second = _media(client, cid, "two")
+ _derives(cid, first, second, "derived-from")
+ _derives(cid, second, first, "derived-from")
+
+ body = _graph(client, cid)
+ assert _ids(body) == {first, second}
+ assert _folded(body) == []
+
+
+# -- what came out of it and was not used --------------------------------------
+#
+# Twelve frames saved off a video are twelve pictures of that video. The video already
+# says it, so the count goes there and the ids come back with one press. Narrow on
+# purpose: one edge, a chain verb, and the node is the end that was derived.
+
+
+def test_derivatives_nobody_used_are_a_count_on_what_they_came_out_of(client):
+ """The picture a case gets after an hour in Inspect: one video, a screenful of
+ frames, and nothing yet made from any of them."""
+ cid = _case(client, "unused frames")
+ video = _media(client, cid, "clip")
+ frames = [_media(client, cid, f"frame {n}") for n in range(3)]
+ for frame in frames:
+ _derives(cid, frame, video, "derived-from")
+
+ body = _graph(client, cid)
+ assert _ids(body) == {video}
+ rolled = _node(body, video)["rolled"]
+ assert rolled["count"] == 3
+ assert rolled["via"] == ["media"]
+ assert rolled["open"] == sorted(frames)
+
+
+def test_the_count_is_a_fact_and_the_offer_is_the_ordinary_one(client):
+ """The node goes on pricing them among the connections the drawing does not hold,
+ and the click that brings them is the one that brings every other missing
+ neighbour. Priced down instead, it reported *four away* while offering *twelve*
+ somewhere else — two counters for one question, and the difference between them was
+ about the mechanism rather than about the case.
+ """
+ cid = _case(client, "rolled degree")
+ video = _media(client, cid, "clip")
+ frames = [_media(client, cid, f"frame {n}") for n in range(3)]
+ for frame in frames:
+ _derives(cid, frame, video, "derived-from")
+
+ body = _graph(client, cid)
+ assert _ids(body) == {video}
+ assert _node(body, video)["degree"] == 3
+
+ # And expanding answers with them: what an opened node touches is never rolled up.
+ back = _graph(client, cid, expand=video)
+ assert _ids(back) == {video, *frames}
+ assert "rolled" not in _node(back, video)
+
+
+def test_the_count_hands_its_nodes_back(client):
+ """Named rather than opened, the same way back a folded edge offers: they are
+ wanted as themselves, not with whatever else they touch."""
+ cid = _case(client, "give the frames back")
+ video = _media(client, cid, "clip")
+ frames = [_media(client, cid, f"frame {n}") for n in range(3)]
+ for frame in frames:
+ _derives(cid, frame, video, "derived-from")
+
+ back = _graph(client, cid, keep=",".join(frames))
+ assert _ids(back) == {video, *frames}
+ assert "rolled" not in _node(back, video)
+ assert _node(back, video)["degree"] == 3
+
+
+def test_one_of_them_named_leaves_the_others_counted(client):
+ """The way back is per node, so asking for one frame is not asking for the pile."""
+ cid = _case(client, "one frame back")
+ video = _media(client, cid, "clip")
+ frames = [_media(client, cid, f"frame {n}") for n in range(3)]
+ for frame in frames:
+ _derives(cid, frame, video, "derived-from")
+
+ back = _graph(client, cid, keep=frames[0])
+ assert _ids(back) == {video, frames[0]}
+ assert _node(back, video)["rolled"]["count"] == 2
+
+
+def test_the_act_is_what_the_count_is_written_with(client):
+ """*3 frames* says what *3 medias* cannot, and it is the word the analyst named it
+ by in Inspect. Same resolution as the edge a collapsed step becomes."""
+ cid = _case(client, "counted in its own word")
+ original = _upload(client, cid, "clip.png")
+ made = _adjusted(client, cid, original["path"])["item"]
+ source_id = _entity_at(client, cid, original["path"])
+ step_id = _entity_at(client, cid, made["path"])
+ mirror = next(
+ link for link in Case.open(cid).links_of(step_id)
+ if link["type"] == "same-image-as"
+ )
+ assert client.delete(f"/api/cases/{cid}/links/{mirror['id']}").status_code == 200
+
+ body = _graph(client, cid)
+ assert _ids(body) == {source_id}
+ assert _node(body, source_id)["rolled"] == {
+ "count": 1, "via": ["adjust"], "open": [step_id]
+ }
+
+
+def test_a_leaf_that_says_something_about_the_world_is_not_rolled_up(client):
+ """One edge and it is a relation, not a step: a picture that shows a place is a
+ finding, and putting it away would hide the case's thin material rather than its
+ clutter."""
+ cid = _case(client, "one relation")
+ place = _entity(client, cid, "place", "48.0, 2.0", {"lat": 48.0, "lon": 2.0})
+ frame = _media(client, cid, "frame")
+ _link(client, cid, frame, place, "depicts")
+
+ body = _graph(client, cid)
+ assert _ids(body) == {place, frame}
+ assert "rolled" not in _node(body, place)
+
+
+def test_only_the_derivative_of_a_lone_pair_is_rolled_up(client):
+ """Both ends have one edge, so the direction is what decides. The frame came out of
+ the video: the collected material stays and the derivative is its count. The other
+ way round, a case would answer with the frames and hide the footage."""
+ cid = _case(client, "lone pair")
+ video = _media(client, cid, "clip")
+ frame = _media(client, cid, "frame")
+ _derives(cid, frame, video, "derived-from")
+
+ body = _graph(client, cid)
+ assert _ids(body) == {video}
+ assert _node(body, video)["rolled"]["count"] == 1
+
+
+def test_a_leaf_hanging_off_a_collapsed_step_stays_a_node(client):
+ """That line already stands for something and offers it back. Rolled up, the step
+ and the leaf would be two acts behind one number, and the way to the step would be
+ gone with it."""
+ cid = _case(client, "leaf past a fold")
+ video = _media(client, cid, "clip")
+ frame = _media(client, cid, "frame")
+ proof = _proof(client, cid)
+ _derives(cid, frame, video, "derived-from")
+ _derives(cid, proof, frame, "derived-from")
+
+ body = _graph(client, cid)
+ assert _ids(body) == {video, proof} # the frame is the edge, the proof is a node
+ assert _folded(body)[0]["folded"]["sources"] == 1
+ assert "rolled" not in _node(body, video)
+
+
+def test_an_entity_joined_to_nothing_belongs_to_nobody(client):
+ """A node with no edge at all is the case's unexploited material, which is what
+ `isolated` counts and the one thing a table cannot show."""
+ cid = _case(client, "isolated stays")
+ alone = _media(client, cid, "orphan")
+
+ body = _graph(client, cid)
+ assert _ids(body) == {alone}
+
+
+def test_the_filing_lens_keeps_what_was_made_and_not_used(client):
+ """`My work` answers what was made out of what, and the pile of unused frames is
+ half that answer."""
+ cid = _case(client, "work keeps its frames")
+ video = _media(client, cid, "clip")
+ frames = [_media(client, cid, f"frame {n}") for n in range(3)]
+ for frame in frames:
+ _derives(cid, frame, video, "derived-from")
+
+ body = _graph(client, cid, lens="work")
+ assert {video, *frames} <= _ids(body)
+ assert "rolled" not in _node(body, video)
+
+
+# -- one finding on the ground is one arrow -------------------------------------
+#
+# A proof concluding a coordinate states the point of everything behind it, so four
+# arrows land on one dot and nothing on screen says three of them are the same picture.
+# A reader counts four sources agreeing. There is one, and that is the finding the case
+# never made.
+
+
+def _geolocation(client, cid, *, pov=False):
+ """The worked example: a frame off a video, compared against a satellite capture,
+ and a proof concluding the point. Every one of the four states the place, which is
+ what `satellite._state_point` writes. Returns them in derivation order."""
+ video = _media(client, cid, "clip")
+ frame = _media(client, cid, "frame")
+ capture = _entity(
+ client, cid, "capture", "46.2, 61.7", {"path": "captures/x.png", "lat": 46.2}
+ )
+ proof = _proof(client, cid)
+ place = _entity(client, cid, "place", "40.2, 61.7", {"lat": 40.2, "lon": 61.7})
+ _derives(cid, frame, video, "derived-from")
+ _derives(cid, proof, frame, "derived-from")
+ _derives(cid, proof, capture, "derived-from")
+ for one in (video, frame, proof, capture):
+ _link(client, cid, one, place, "depicts")
+ return video, frame, capture, proof, place
+
+
+def _merged(payload):
+ return [link for link in payload["links"] if link.get("merged")]
+
+
+def test_four_arrows_on_one_point_are_one_finding(client):
+ """The false convergence, and the whole reason this reading exists. Three of the
+ four are the same picture; the drawing has to say the point rests on one."""
+ cid = _case(client, "false convergence")
+ video, frame, capture, proof, place = _geolocation(client, cid)
+
+ body = _graph(client, cid)
+ assert _ids(body) == {video, place}
+ edge = _merged(body)[0]
+ assert (edge["from"], edge["to"], edge["type"]) == (video, place, "depicts")
+ assert edge["merged"]["sources"] == 3
+ assert edge["merged"]["open"] == sorted([frame, proof, capture])
+ assert _node(body, place)["rests"]["sources"] == 1
+
+
+def test_pov_splits_the_verbs_and_the_material_is_still_one(client):
+ """The shape a real geolocation has, and it is the one that caught this.
+
+ Answering POV writes `located-at` on the material and leaves `depicts` on the
+ composition and the capture. Read per verb, each half sees the other as outside
+ itself, every member turns out to hold a derivation reaching "outside", and nothing
+ collapses at all — the picture goes back to claiming two origins where the case has
+ one. So the family is every arrow on the point, whatever verb it is written with:
+ the surviving line is the material's own statement and the rest are named on it.
+ """
+ cid = _case(client, "pov geolocation")
+ video, frame, capture, proof, place = _geolocation(client, cid)
+ case = Case.open(cid)
+ for holder in (video, frame):
+ edge = next(
+ link for link in case.links_of(holder)
+ if link["to"] == place and link["type"] == "depicts"
+ )
+ case.remove_link(edge["id"])
+ case.add_link(holder, place, "located-at", by="proof-composer")
+
+ body = _graph(client, cid)
+ assert _ids(body) == {video, place}
+ edge = _merged(body)[0]
+ assert (edge["from"], edge["type"]) == (video, "located-at")
+ assert edge["merged"]["open"] == sorted([frame, proof, capture])
+ assert _node(body, place)["rests"]["sources"] == 1
+
+
+def test_the_reading_that_draws_no_derivation_still_reads_it(client):
+ """Ground holds no chain verb at all, and the redundancy is a fact about the chain.
+ Asked of the drawing alone, four arrows off one video are four unrelated sources —
+ so the repository is asked instead. The lens decides what is drawn, not what is
+ known."""
+ cid = _case(client, "ground convergence")
+ video, frame, capture, proof, place = _geolocation(client, cid)
+
+ body = _graph(client, cid, lens="ground")
+ assert _ids(body) == {video, place}
+ assert _merged(body)[0]["merged"]["sources"] == 3
+
+
+def test_the_arrow_that_survives_stays_the_case_s_own_statement(client):
+ """Not a synthetic id: the video really does state that point, and withdrawing it
+ has to stay possible. The row is annotated, never replaced."""
+ cid = _case(client, "still a row")
+ video, _frame, _capture, _proof, place = _geolocation(client, cid)
+
+ edge = _merged(_graph(client, cid))[0]
+ assert not edge["id"].startswith(graph_engine.FOLDED_PREFIX)
+ assert client.delete(f"/api/cases/{cid}/links/{edge['id']}").status_code == 200
+
+
+def test_a_capture_pulled_at_the_point_is_the_reference_not_a_witness(client):
+ """The sharp case, and why the roles decide. Shape cannot tell the capture from the
+ footage — both have one chain leaving them and one arrow landing — but `media` is a
+ subject and `capture` is an attestation, the role that means a wrapper carrying a
+ path. Counting it would state a corroboration nobody found."""
+ cid = _case(client, "reference not witness")
+ video, _frame, capture, _proof, place = _geolocation(client, cid)
+
+ body = _graph(client, cid)
+ assert capture not in _ids(body)
+ assert _node(body, place)["rests"]["sources"] == 1
+
+
+def test_a_capture_nobody_made_a_proof_from_is_the_only_thing_saying_it(client):
+ """A group with no subject root keeps its own. Otherwise the one statement about
+ that point would leave with the node that made it."""
+ cid = _case(client, "lone capture")
+ video, _frame, _capture, _proof, place = _geolocation(client, cid)
+ alone = _entity(
+ client, cid, "capture", "40.2, 61.7", {"path": "captures/y.png", "lat": 40.2}
+ )
+ _link(client, cid, alone, place, "depicts")
+
+ body = _graph(client, cid)
+ assert _ids(body) == {video, alone, place}
+ assert _node(body, place)["rests"]["sources"] == 2
+
+
+def test_a_member_carrying_its_own_finding_stays_a_node(client):
+ """All or nothing, as everywhere else here. A capture that also shows a vehicle is
+ holding something the collapsed line cannot say — but it is still the reference the
+ comparison was made against, so the point still rests on one source."""
+ cid = _case(client, "capture with a finding")
+ video, _frame, capture, _proof, place = _geolocation(client, cid)
+ van = _entity(client, cid, "vehicle", "white van")
+ _link(client, cid, van, capture, "appears-in")
+
+ body = _graph(client, cid)
+ assert capture in _ids(body)
+ assert _merged(body)[0]["merged"]["sources"] == 2
+ assert _node(body, place)["rests"]["sources"] == 1
+
+
+def test_a_statement_citing_the_proof_brings_it_back(client):
+ """The guard the plan asked for by name: cited, the proof is carrying something the
+ arrow cannot say. It comes back as a node, and the point still rests on one."""
+ cid = _case(client, "cited proof")
+ video, _frame, _capture, proof, place = _geolocation(client, cid)
+ claim = _entity(client, cid, "claim", "The convoy passed here")
+ _link(client, cid, claim, proof, "cites")
+
+ body = _graph(client, cid)
+ assert proof in _ids(body)
+ assert _node(body, place)["rests"]["sources"] == 1
+
+
+def test_the_collapsed_arrow_hands_its_nodes_back(client):
+ """Named rather than opened, the one mechanism every hand-back here uses."""
+ cid = _case(client, "unfold the star")
+ video, frame, _capture, _proof, place = _geolocation(client, cid)
+
+ back = _graph(client, cid, keep=frame)
+ assert frame in _ids(back)
+ assert _merged(back)[0]["merged"]["sources"] == 2
+ # And it is a node with its own statement again, not a name with nothing on it.
+ assert _node(back, frame)["degree"] == 3
+
+
+def test_a_node_that_stays_keeps_counting_what_the_arrow_took(client):
+ """The one fold whose degree is left alone, and the reason is where the way back
+ sits. Every other collapse here hands its nodes back from a line that touches them;
+ this one names the frame and the capture on `video → place`, which does not touch
+ the proof at all. Priced down to nothing, the proof would say it has no more
+ connections while the analyst is looking straight at two that exist.
+ """
+ cid = _case(client, "expand past the fold")
+ video, frame, capture, proof, place = _geolocation(client, cid)
+ claim = _entity(client, cid, "claim", "The convoy passed here")
+ _link(client, cid, claim, proof, "cites")
+
+ body = _graph(client, cid)
+ assert proof in _ids(body)
+ assert not {frame, capture} & _ids(body)
+ # Cited, stating the point, and made from two things: all four still countable.
+ assert _node(body, proof)["degree"] == 4
+
+ # And the click answers with them, because it is the analyst asking for exactly
+ # these: a node an expansion brought in is never folded.
+ back = _graph(client, cid, expand=proof)
+ assert {frame, capture} <= _ids(back)
+
+
+def test_the_point_keeps_offering_what_landed_on_it(client):
+ """Same reading from the other end: four arrows arrived, one is drawn, and opening
+ the point is how the other three come back."""
+ cid = _case(client, "star degree")
+ video, frame, capture, proof, place = _geolocation(client, cid)
+
+ assert _node(_graph(client, cid), place)["degree"] == 4
+ assert {frame, capture, proof} <= _ids(_graph(client, cid, expand=place))
+
+
+def test_a_point_stated_once_says_nothing_about_independence(client):
+ """A count that restates the picture is a count nobody reads."""
+ cid = _case(client, "one arrow")
+ place = _entity(client, cid, "place", "48.0, 2.0", {"lat": 48.0, "lon": 2.0})
+ video = _media(client, cid, "clip")
+ _link(client, cid, video, place, "depicts")
+
+ assert "rests" not in _node(_graph(client, cid), place)
+
+
+def test_two_recordings_of_the_same_point_are_two_sources(client):
+ """The other half of the number, and the reason it is worth having. Two videos
+ nobody derived from each other agree, and that is the finding."""
+ cid = _case(client, "two witnesses")
+ place = _entity(client, cid, "place", "48.0, 2.0", {"lat": 48.0, "lon": 2.0})
+ first = _media(client, cid, "one")
+ second = _media(client, cid, "two")
+ for one in (first, second):
+ _link(client, cid, one, place, "depicts")
+
+ body = _graph(client, cid)
+ assert _ids(body) == {first, second, place}
+ assert _node(body, place)["rests"]["sources"] == 2
+ assert _merged(body) == []
+
+
+def test_a_reading_that_lands_on_no_place_leaves_the_star_alone(client):
+ """Subjects draws no verb that reaches a place, so there is no star to read."""
+ cid = _case(client, "no ground")
+ video, frame, _capture, _proof, _place = _geolocation(client, cid)
+
+ body = _graph(client, cid, lens="subjects")
+ assert {video, frame} <= _ids(body)
+ assert _merged(body) == []
+
+
+# -- the analyst's own arrangement --------------------------------------------
+#
+# A pin is where a hand put a node. It is presentation, not a statement about the
+# case, and the reason it is stored at all is that an arrangement somebody built
+# is worth more than the one a relaxation computes.
+
+
+def _pin(client, cid, *pins, lens="all"):
+ res = client.put(
+ f"/api/cases/{cid}/graph/pins",
+ json={"lens": lens, "pins": [{"id": i, "x": x, "y": y} for i, x, y in pins]},
+ )
+ assert res.status_code == 200, res.text
+ return res.json()
+
+
+def test_a_dragged_node_comes_back_exactly_where_it_was_put(client):
+ """Exactly, not approximately: an anchor that drifted would make the whole
+ feature feel broken, and the layout treats the pin as a fixed point."""
+ cid = _case(client, "pinned")
+ person = _entity(client, cid, "person", "Dragged")
+
+ _pin(client, cid, (person, -412.5, 987.25))
+
+ assert _node(_graph(client, cid), person)["pin"] == [-412.5, 987.25]
+
+
+def test_a_node_nobody_moved_carries_no_pin_at_all(client):
+ """Absent rather than zero: (0, 0) is a place on the canvas, and a node the
+ layout owns has to be told apart from one dropped at the origin."""
+ cid = _case(client, "unpinned")
+ person = _entity(client, cid, "person", "Placed by the layout")
+
+ payload = _graph(client, cid)
+ assert "pin" not in _node(payload, person)
+ assert payload["pinned"] == 0
+
+
+def test_dragging_the_same_node_twice_keeps_the_last_spot(client):
+ cid = _case(client, "moved twice")
+ person = _entity(client, cid, "person", "Moved")
+
+ _pin(client, cid, (person, 10, 10))
+ body = _pin(client, cid, (person, 300, -40))
+
+ assert body["pinned"] == 1
+ assert _node(_graph(client, cid), person)["pin"] == [300, -40]
+
+
+def test_the_whole_batch_lands_or_none_of_it_does(client):
+ """A drag that moved several nodes is one act."""
+ cid = _case(client, "batch")
+ a = _entity(client, cid, "person", "A")
+ b = _entity(client, cid, "person", "B")
+
+ _pin(client, cid, (a, 1, 2), (b, 3, 4))
+
+ payload = _graph(client, cid)
+ assert _node(payload, a)["pin"] == [1, 2]
+ assert _node(payload, b)["pin"] == [3, 4]
+ assert payload["pinned"] == 2
+
+
+def test_a_pin_for_an_entity_that_is_gone_is_skipped_not_an_error(client):
+ """A drag races a delete made in another tab, and losing that pin is the right
+ outcome — refusing the whole batch would lose the arrangement instead."""
+ cid = _case(client, "racing")
+ person = _entity(client, cid, "person", "Still here")
+
+ body = _pin(client, cid, (person, 5, 5), ("e_gone", 9, 9))
+
+ assert body["pinned"] == 1
+
+
+def test_the_count_of_pins_covers_the_case_not_just_what_is_drawn(client):
+ """The control that undoes an arrangement has to appear even when the pinned
+ nodes were cut from this view — otherwise the way back is hidden by the cut."""
+ cid = _case(client, "pins off screen")
+ hub = _entity(client, cid, "organization", "Hub")
+ far = _entity(client, cid, "person", "Cut from this view")
+ _pin(client, cid, (far, 100, 100))
+
+ payload = _graph(client, cid, limit=1)
+
+ assert _ids(payload) == {hub} or far not in _ids(payload)
+ assert payload["pinned"] == 1
+
+
+def test_one_node_can_be_handed_back_to_the_layout(client):
+ cid = _case(client, "unpin one")
+ a = _entity(client, cid, "person", "A")
+ b = _entity(client, cid, "person", "B")
+ _pin(client, cid, (a, 1, 1), (b, 2, 2))
+
+ res = client.delete(f"/api/cases/{cid}/graph/pins/{a}")
+ assert res.status_code == 200
+ assert res.json()["pinned"] == 1
+
+ payload = _graph(client, cid)
+ assert "pin" not in _node(payload, a)
+ assert _node(payload, b)["pin"] == [2, 2]
+
+
+def test_the_whole_arrangement_can_be_dropped_at_once(client):
+ """The way out of an arrangement that stopped helping. Pins are saved as they
+ are made, and an autosave with no way back is a trap."""
+ cid = _case(client, "reset layout")
+ a = _entity(client, cid, "person", "A")
+ b = _entity(client, cid, "person", "B")
+ _pin(client, cid, (a, 1, 1), (b, 2, 2))
+
+ res = client.delete(f"/api/cases/{cid}/graph/pins")
+ assert res.status_code == 200
+ assert res.json()["pinned"] == 0
+
+ payload = _graph(client, cid)
+ assert payload["pinned"] == 0
+ assert all("pin" not in node for node in payload["nodes"])
+
+
+def test_unpinning_what_was_never_pinned_is_not_an_error(client):
+ cid = _case(client, "idempotent unpin")
+ person = _entity(client, cid, "person", "Never moved")
+
+ assert client.delete(f"/api/cases/{cid}/graph/pins/{person}").status_code == 200
+ assert client.delete(f"/api/cases/{cid}/graph/pins").status_code == 200
+
+
+def test_a_deleted_node_leaves_no_pin_behind(client):
+ """Ids are taken again after a delete (`reinsert`), so a surviving pin would
+ place an unrelated entity at a spot nobody chose for it."""
+ cid = _case(client, "cascade")
+ person = _entity(client, cid, "person", "Doomed")
+ _pin(client, cid, (person, 50, 60))
+
+ assert client.delete(f"/api/cases/{cid}/entities/{person}").status_code == 200
+
+ assert _graph(client, cid)["pinned"] == 0
+
+
+def test_a_coordinate_from_nowhere_is_refused_at_the_edge(client):
+ """Nothing downstream clamps a coordinate: the layout would place a node at
+ 1e300 and the view would scale the case to a dot trying to frame it."""
+ cid = _case(client, "absurd")
+ person = _entity(client, cid, "person", "A")
+
+ res = client.put(
+ f"/api/cases/{cid}/graph/pins",
+ json={"pins": [{"id": person, "x": 1e300, "y": 0}]},
+ )
+ assert res.status_code == 422
+
+
+def test_no_more_pins_than_the_view_can_draw(client):
+ cid = _case(client, "too many pins")
+ person = _entity(client, cid, "person", "A")
+ res = client.put(
+ f"/api/cases/{cid}/graph/pins",
+ json={
+ "pins": [
+ {"id": person, "x": 0, "y": 0} for _ in range(graph_engine.MAX_OPENING + 1)
+ ]
+ },
+ )
+ assert res.status_code == 422
+
+
+def test_a_neighbourhood_carries_no_pin(client):
+ """Distance from the root owns the horizontal axis there, so a coordinate
+ stated against the cluster would contradict the arrangement being asked for."""
+ cid = _case(client, "hood pins")
+ person = _entity(client, cid, "person", "Root")
+ unit = _entity(client, cid, "organization", "Unit")
+ _link(client, cid, person, unit, "member-of")
+ _pin(client, cid, (person, 40, 40), (unit, 80, 80))
+
+ payload = _hood(client, cid, person)
+
+ assert all("pin" not in node for node in payload["nodes"])
+
+
+def test_each_lens_keeps_its_own_arrangement(client):
+ """A lens is a reading: it draws its own nodes and its own edges, so it clusters
+ differently. One arrangement shared by all of them would anchor every reading
+ into the shape of whichever one it happened to be built in."""
+ cid = _case(client, "per lens")
+ person = _entity(client, cid, "person", "Arranged")
+
+ _pin(client, cid, (person, 100, 100), lens="all")
+ _pin(client, cid, (person, -50, 900), lens="subjects")
+
+ assert _node(_graph(client, cid, lens="all"), person)["pin"] == [100, 100]
+ assert _node(_graph(client, cid, lens="subjects"), person)["pin"] == [-50, 900]
+ # And a reading nobody arranged is still the layout's to place.
+ assert "pin" not in _node(_graph(client, cid, lens="ground"), person)
+ assert _graph(client, cid, lens="ground")["pinned"] == 0
+
+
+def test_dropping_one_lens_arrangement_leaves_the_others(client):
+ cid = _case(client, "reset one lens")
+ person = _entity(client, cid, "person", "Arranged")
+ _pin(client, cid, (person, 1, 2), lens="all")
+ _pin(client, cid, (person, 3, 4), lens="subjects")
+
+ assert client.delete(
+ f"/api/cases/{cid}/graph/pins", params={"lens": "all"}
+ ).status_code == 200
+
+ assert _graph(client, cid, lens="all")["pinned"] == 0
+ assert _node(_graph(client, cid, lens="subjects"), person)["pin"] == [3, 4]
+
+
+def test_unpinning_one_node_is_scoped_to_its_reading(client):
+ cid = _case(client, "unpin per lens")
+ person = _entity(client, cid, "person", "Arranged")
+ _pin(client, cid, (person, 1, 2), lens="all")
+ _pin(client, cid, (person, 3, 4), lens="subjects")
+
+ assert client.delete(
+ f"/api/cases/{cid}/graph/pins/{person}", params={"lens": "all"}
+ ).status_code == 200
+
+ assert "pin" not in _node(_graph(client, cid, lens="all"), person)
+ assert _node(_graph(client, cid, lens="subjects"), person)["pin"] == [3, 4]
+
+
+def test_a_lens_nothing_can_draw_cannot_be_arranged(client):
+ """Pins filed under an unknown reading would sit in the case forever, with no
+ surface able to show them or clear them."""
+ cid = _case(client, "bad lens")
+ person = _entity(client, cid, "person", "A")
+
+ res = client.put(
+ f"/api/cases/{cid}/graph/pins",
+ json={"lens": "everything-ish", "pins": [{"id": person, "x": 0, "y": 0}]},
+ )
+ assert res.status_code == 400
+ assert client.delete(
+ f"/api/cases/{cid}/graph/pins", params={"lens": "everything-ish"}
+ ).status_code == 400
+
+
+def test_moving_a_node_says_nothing_about_the_case(client):
+ """A pin is where a hand put a dot. It must not touch the entity, its
+ provenance or its status, or the graph would be editing the case by drawing."""
+ cid = _case(client, "no statement")
+ person = _entity(client, cid, "person", "Untouched")
+ catalog = f"/api/cases/{cid}/catalog/entities"
+ before = client.get(catalog).json()
+
+ _pin(client, cid, (person, 123, 456))
+
+ assert client.get(catalog).json() == before
+
+
+# -- bounded reading ----------------------------------------------------------
+
+
+def test_no_graph_read_walks_the_whole_case(client, monkeypatch):
+ """The storage rule (STORAGE_AND_PERFORMANCE step 5): `snapshot` is the one
+ deliberate whole-case read, and drawing a case is not it."""
+ from azimut import workspace
+
+ def refuse(self): # pragma: no cover - the assertion is that it never runs
+ raise AssertionError("the graph must not snapshot the whole case")
+
+ cid = _case(client, "bounded")
+ person = _entity(client, cid, "person", "Root")
+ unit = _entity(client, cid, "organization", "Unit")
+ _link(client, cid, person, unit, "member-of")
+
+ monkeypatch.setattr(workspace.Case, "snapshot", refuse)
+ _graph(client, cid)
+ _hood(client, cid, person, hops=2)
+
+
+# -- growing the view ---------------------------------------------------------
+#
+# Opening a node adds to the case on screen instead of replacing it with a
+# different question. That is what makes the graph a place to work rather than a
+# thing to navigate, and every test here is about the picture surviving the act.
+
+
+def test_opening_a_node_adds_its_neighbours_to_the_view(client):
+ """The point of the whole change: what was on screen is still on screen."""
+ cid = _case(client, "grow")
+ person = _entity(client, cid, "person", "Root")
+ unit = _entity(client, cid, "organization", "Unit")
+ other = _entity(client, cid, "person", "Elsewhere")
+ _link(client, cid, person, unit, "member-of")
+
+ before = _ids(_graph(client, cid))
+ after = _graph(client, cid, expand=person)
+
+ assert before <= _ids(after)
+ assert {person, unit, other} <= _ids(after)
+ assert after["expanded"] == [person]
+
+
+def test_an_arrival_says_it_arrived(client):
+ """A node the expansion brought in has to be tellable from one the ranking
+ already held, or growing the view reads as the view changing underfoot."""
+ cid = _case(client, "arrivals")
+ person = _entity(client, cid, "person", "Root")
+ unit = _entity(client, cid, "organization", "Unit")
+ _link(client, cid, person, unit, "member-of")
+
+ # Filtered to people, so the unit can only be here because it was opened into.
+ payload = _graph(client, cid, type="person", expand=person)
+
+ assert _node(payload, unit)["added"] is True
+ assert "added" not in _node(payload, person)
+
+
+def test_an_expansion_ignores_the_filters_it_was_asked_from(client):
+ """An analyst who asked what touches this node is asking about the case, not
+ about the narrowing they set earlier."""
+ cid = _case(client, "past the filter")
+ person = _entity(client, cid, "person", "Root")
+ unit = _entity(client, cid, "organization", "Unit")
+ _link(client, cid, person, unit, "member-of")
+
+ narrowed = _graph(client, cid, type="person")
+ grown = _graph(client, cid, type="person", expand=person)
+
+ assert unit not in _ids(narrowed)
+ assert unit in _ids(grown)
+
+
+def test_the_node_opened_is_kept_even_when_the_filters_drop_it(client):
+ """A view answering "what touches this" without the node itself is a broken
+ sentence."""
+ cid = _case(client, "the question stays")
+ person = _entity(client, cid, "person", "Root")
+ unit = _entity(client, cid, "organization", "Unit")
+ _link(client, cid, person, unit, "member-of")
+
+ payload = _graph(client, cid, type="organization", expand=person)
+
+ assert person in _ids(payload)
+ assert _node(payload, person)["added"] is True
+
+
+def test_an_expansion_returns_the_closed_edge_set(client):
+ """The guarantee the view has always made, kept while it grows: nothing drawn
+ points at a node that was not sent."""
+ cid = _case(client, "closed while growing")
+ person = _entity(client, cid, "person", "Root")
+ unit = _entity(client, cid, "organization", "Unit")
+ _link(client, cid, person, unit, "member-of")
+
+ payload = _graph(client, cid, expand=person)
+ ids = _ids(payload)
+
+ assert all({link["from"], link["to"]} <= ids for link in payload["links"])
+
+
+def test_an_arrival_states_what_a_further_expansion_would_cost(client):
+ """A node that arrived by expansion prices its own next click like every
+ other node, or the second hop is the one that explodes."""
+ cid = _case(client, "priced arrivals")
+ person = _entity(client, cid, "person", "Root")
+ unit = _entity(client, cid, "organization", "Unit")
+ for at in range(3):
+ member = _entity(client, cid, "person", f"Member {at}")
+ _link(client, cid, member, unit, "member-of")
+ _link(client, cid, person, unit, "member-of")
+
+ payload = _graph(client, cid, limit=1, expand=person)
+
+ assert _node(payload, unit)["degree"] == 4
+
+
+def test_opening_a_node_that_is_gone_is_not_an_error(client):
+ """An expansion races a delete made in another tab. The view still draws."""
+ cid = _case(client, "ghost")
+ person = _entity(client, cid, "person", "Root")
+
+ payload = _graph(client, cid, expand="ent_nothing")
+
+ assert payload["expanded"] == []
+ assert person in _ids(payload)
+
+
+def test_an_expansion_stays_inside_the_lens(client):
+ """A lens is a reading. Growing it must not smuggle in verbs it excluded."""
+ cid = _case(client, "lens holds")
+ place = _entity(client, cid, "place", "Field")
+ unit = _entity(client, cid, "organization", "Unit")
+ depot = _entity(client, cid, "structure", "Depot")
+ _link(client, cid, unit, depot, "owns")
+ _link(client, cid, depot, place, "sited-at")
+
+ # No claim in the case, so the ranking brings nothing and everything on
+ # screen is what the expansion reached through this lens's verbs.
+ payload = _graph(client, cid, lens="ground", type="claim", expand=depot)
+
+ assert place in _ids(payload)
+ assert unit not in _ids(payload)
+
+
+def test_an_expansion_brings_every_missing_neighbour(client):
+ """Growth is unbounded, and this is the half that matters on screen: an expansion
+ that came back with part of an answer left the node still counting connections it
+ did not draw, under a control that had already agreed it was open."""
+ cid = _case(client, "unbounded growth")
+ hub = _entity(client, cid, "organization", "Hub")
+ for at in range(6):
+ member = _entity(client, cid, "person", f"Member {at}")
+ _link(client, cid, member, hub, "member-of")
+
+ payload = _graph(client, cid, limit=1, expand=hub)
+
+ # One node paid for by the first draw, and all six neighbours on top of it.
+ assert payload["shown"] == 7
+ assert payload["expanded"] == [hub]
+ # And the node stops asking: its degree is what the drawing now holds.
+ assert _node(payload, hub)["degree"] == 6
+ # `truncated` is the first draw's own answer and nothing else's: the ranking held
+ # one node of seven, which is the only cut the tool still makes.
+ assert payload["truncated"] is True
+
+
+# -- a comfort number, not a ceiling ------------------------------------------
+#
+# The drawing had a hard limit, and a limit that refuses is the app overruling the
+# analyst about their own picture: a full view refused an answer that had been asked
+# for outright, and refused it in silence. What is left is a count to open on, growth
+# without limit from there, and a client that says what a heavy drawing costs.
+
+
+def test_a_first_draw_opens_on_the_comfort_number(client, monkeypatch):
+ """The one cut the tool still makes, and it is the ranking's: the most connected
+ part of the case, said to be a part with the case's own total beside it."""
+ monkeypatch.setattr(graph_engine, "OPENING_NODES", 2)
+ cid = _case(client, "opens on a number")
+ hub = _entity(client, cid, "organization", "Hub")
+ for at in range(4):
+ member = _entity(client, cid, "person", f"Member {at}")
+ _link(client, cid, member, hub, "member-of")
+
+ payload = client.get(f"/api/cases/{cid}/graph").json()
+
+ assert payload["shown"] == 2
+ assert payload["total"] == 5
+ assert payload["truncated"] is True
+
+
+def test_the_drawing_states_no_ceiling_because_it_has_none(client):
+ """A number a client can only use to refuse a click is not sent. Growth is
+ unbounded, so there is nothing left to be full of."""
+ cid = _case(client, "no ceiling")
+ _entity(client, cid, "person", "Root")
+
+ payload = _graph(client, cid)
+
+ assert "room" not in payload
+
+
+def test_an_expansion_is_never_refused_for_room(client, monkeypatch):
+ """The failure this closes: drawing the case and asking what touches one node
+ shared one budget, the ranking spent it first, and the answer the analyst asked
+ for outright was the one refused."""
+ monkeypatch.setattr(graph_engine, "OPENING_NODES", 2)
+ cid = _case(client, "asked for outright")
+ hub = _entity(client, cid, "organization", "Hub")
+ members = [_entity(client, cid, "person", f"Member {at}") for at in range(6)]
+ for member in members:
+ _link(client, cid, member, hub, "member-of")
+
+ payload = _graph(client, cid, limit=2, expand=hub)
+
+ assert set(members) <= _ids(payload)
+ assert payload["expanded"] == [hub]
+
+
+def test_naming_a_node_is_never_refused_for_room_either(client, monkeypatch):
+ """`keep` is the other half of the same promise: a route and a name found in the
+ case are asked for outright, and a picture that came back short of one of them
+ answered the question with the question missing from it."""
+ monkeypatch.setattr(graph_engine, "OPENING_NODES", 1)
+ cid = _case(client, "named past the old ceiling")
+ named = [_entity(client, cid, "person", f"Person {at}") for at in range(3)]
+
+ payload = _graph(client, cid, limit=1, keep=",".join(named))
+
+ assert set(named) <= _ids(payload)
+ assert payload["kept"] == named
+
+
+def test_a_drawing_past_the_ranking_ceiling_still_draws(tmp_workspace):
+ """The regression the room kept for asking caused, and the reason it is tested
+ here rather than only where it broke: raising a ceiling in one module raises it
+ for every reader the node ids travel through, and one of them refused more than
+ 500 at a time. The whole tool drew nothing at all past that line."""
+ _, summary = build_big_case(
+ name="Past the ceiling", entities=700, links=1200, media=300,
+ notes=0, artifacts=0, write_media_files=False,
+ )
+ case = Case.open(summary.case_id)
+
+ ranked = graph_engine.view(case, limit=graph_engine.OPENING_NODES)
+ assert ranked["shown"] == graph_engine.OPENING_NODES
+
+ # Entities the ranking had no room for. Opened, they are kept whatever the cut
+ # decided — which is what carries the drawing past the ceiling it was cut to.
+ drawn = {node["id"] for node in ranked["nodes"]}
+ outside, cursor = [], None
+ while True:
+ page = case.page_entities(limit=250, cursor=cursor)
+ outside.extend(row["id"] for row in page["items"] if row["id"] not in drawn)
+ cursor = page["next_cursor"]
+ if not cursor:
+ break
+ assert len(outside) > 100, "the case has to outgrow the ranking for this to test anything"
+
+ grown = graph_engine.view(case, limit=graph_engine.OPENING_NODES, expand=outside[:100])
+
+ assert grown["shown"] > graph_engine.OPENING_NODES
+
+ # **Complete as well as closed.** Asserted here because this is the one test that
+ # draws a view large enough for the storage layer to read its ids in more than one
+ # statement, and reading them chunk by chunk dropped every edge whose two ends
+ # landed in two different chunks. Counted on `shown` alone this passed while two
+ # thirds of the edges were gone: nodes drew as unconnected dots, and each one went
+ # on reporting the lost edges as connections still to open.
+ ids = {node["id"] for node in grown["nodes"]}
+ verbs = set(graph_engine.lens("all").types)
+ owed = {
+ link["id"]
+ for link in case.list_links()
+ if link["type"] in verbs and link["from"] in ids and link["to"] in ids
+ }
+ assert owed, "the case has to link its drawn nodes for this to test anything"
+ assert {link["id"] for link in grown["links"]} == owed
+
+
+def test_a_node_with_everything_already_drawn_is_still_reported_open(client):
+ """Nothing arrived, and nothing was meant to. That is a true answer, and the
+ control that folds the expansion back has to know it is out."""
+ cid = _case(client, "nothing left to bring")
+ person = _entity(client, cid, "person", "Root")
+ unit = _entity(client, cid, "organization", "Unit")
+ _link(client, cid, person, unit, "member-of")
+
+ payload = _graph(client, cid, expand=person)
+
+ assert payload["expanded"] == [person]
+ assert payload["truncated"] is False
+
+
+# -- the drawing is a set you own ---------------------------------------------
+#
+# One list conflated two acts: *draw this node* and *draw this node and one hop*.
+# Split, a route or a named entity arrives as itself instead of dragging a
+# neighbourhood in behind it. And a third list takes any node out — not only one you
+# opened — which is what a drawing that can grow without limit needs: the way back was
+# folding every expansion, and that takes the reading down with it.
+
+
+def test_a_node_named_is_drawn_without_its_neighbourhood(client):
+ """The half of the old `expand` that was never expressible."""
+ cid = _case(client, "held alone")
+ person = _entity(client, cid, "person", "Root")
+ unit = _entity(client, cid, "organization", "Unit")
+ _link(client, cid, person, unit, "member-of")
+
+ # Filtered to a type neither of them holds, so anything on screen is named.
+ payload = _graph(client, cid, type="claim", keep=person)
+
+ assert _ids(payload) == {person}
+ assert payload["kept"] == [person]
+ assert _node(payload, person)["added"] is True
+
+
+def test_naming_a_route_draws_it_without_the_crowd_around_each_node(client):
+ """Why the split exists. A route is a small precise answer, and opened it arrived
+ with one whole neighbourhood per node — the crowd buried the sentence."""
+ cid = _case(client, "route without the crowd")
+ account = _entity(client, cid, "account", "@watcher")
+ media = _entity(client, cid, "media", "frame", {"path": "media/f.jpg", "kind": "image"})
+ place = _entity(client, cid, "place", "checkpoint north")
+ _link(client, cid, account, media, "posted")
+ _link(client, cid, media, place, "depicts")
+ for at in range(4):
+ other = _entity(client, cid, "media", f"other {at}", {"path": f"media/o{at}.jpg"})
+ _link(client, cid, account, other, "posted")
+
+ route = ",".join([account, media, place])
+ held = _graph(client, cid, type="claim", keep=route)
+ grown = _graph(client, cid, type="claim", expand=route)
+
+ assert _ids(held) == {account, media, place}
+ # The route still reads as a route: its own edges are drawn, closed as ever.
+ assert len(held["links"]) == 2
+ assert len(_ids(grown)) > len(_ids(held))
+
+
+def test_what_is_named_survives_the_narrowing_it_was_named_from(client):
+ """The same argument an expansion already makes: a name is a question about the
+ case, not about the filters set earlier."""
+ cid = _case(client, "named past the filter")
+ person = _entity(client, cid, "person", "Root")
+ unit = _entity(client, cid, "organization", "Unit")
+ _link(client, cid, person, unit, "member-of")
+
+ payload = _graph(client, cid, type="organization", keep=person)
+
+ assert {person, unit} <= _ids(payload)
+
+
+def test_the_lens_still_outranks_a_node_named_to_be_drawn(client):
+ """A reading that does not draw notes would stop being that reading with a note in
+ it, so this is the one narrowing a name cannot be brought past."""
+ cid = _case(client, "named but filed")
+ post = _entity(client, cid, "post", "Thread draft")
+
+ payload = _graph(client, cid, keep=post)
+
+ assert post not in _ids(payload)
+ assert payload["kept"] == []
+ assert post in _ids(_graph(client, cid, lens="work", keep=post))
+
+
+def test_naming_a_node_that_is_gone_is_not_an_error(client):
+ """A drawing races a delete made in another tab, and the answer is the picture
+ without it rather than a refusal."""
+ cid = _case(client, "named ghost")
+ person = _entity(client, cid, "person", "Still here")
+
+ payload = _graph(client, cid, keep="e_nothing")
+
+ assert payload["kept"] == []
+ assert person in _ids(payload)
+
+
+def test_a_node_named_prices_its_own_click_like_any_other(client):
+ """It arrived without its neighbours, so what it would bring in is the whole of
+ what it says: a node that cannot state its degree is a node nobody can decide to
+ open."""
+ cid = _case(client, "priced by name")
+ unit = _entity(client, cid, "organization", "Unit")
+ for at in range(3):
+ member = _entity(client, cid, "person", f"Member {at}")
+ _link(client, cid, member, unit, "member-of")
+
+ payload = _graph(client, cid, type="claim", keep=unit)
+
+ assert _node(payload, unit)["degree"] == 3
+
+
+def test_a_source_handed_back_is_drawn_rather_than_folded_away_again(client):
+ """How a collapsed edge hands its sources back. A named node is never folded, so
+ the same list that draws it has to be the one the fold reads — otherwise pressing
+ *show the source* answers with the edge it was pressed on."""
+ cid = _case(client, "handed back by name")
+ claim, who, marks = _sourced(client, cid)
+
+ assert _folded(_graph(client, cid))[0]["folded"]["open"] == sorted(marks)
+
+ back = _graph(client, cid, keep=marks[0])
+
+ assert marks[0] in _ids(back)
+ assert _folded(back)[0]["folded"]["sources"] == 2
+
+
+def test_any_node_can_be_taken_out_of_the_drawing(client):
+ """Not only one that was opened. The drawing is the analyst's, and the old way out
+ of a crowded one folded every expansion and took the reading with it."""
+ cid = _case(client, "take one out")
+ person = _entity(client, cid, "person", "Root")
+ unit = _entity(client, cid, "organization", "Unit")
+ _link(client, cid, person, unit, "member-of")
+
+ payload = _graph(client, cid, omit=unit)
+
+ assert _ids(payload) == {person}
+ assert payload["links"] == []
+
+
+def test_a_node_taken_out_stays_out_when_a_neighbour_is_opened(client):
+ """Applied last, and that is the whole of why it works: subtracted from the ranking
+ alone, a node came back the moment a neighbour was opened and the analyst was
+ arguing with the ranking about their own picture."""
+ cid = _case(client, "stays out")
+ person = _entity(client, cid, "person", "Root")
+ unit = _entity(client, cid, "organization", "Unit")
+ _link(client, cid, person, unit, "member-of")
+
+ payload = _graph(client, cid, type="person", expand=person, omit=unit)
+
+ assert person in _ids(payload)
+ assert unit not in _ids(payload)
+
+
+def test_a_neighbour_stops_offering_to_bring_back_what_was_taken_out(client):
+ """A degree says what a click would bring in, and nothing brings a removal back:
+ left standing, the count offers an act that answers with an unchanged picture —
+ the failure the honest degree exists to prevent."""
+ cid = _case(client, "honest after a removal")
+ person = _entity(client, cid, "person", "Root")
+ unit = _entity(client, cid, "organization", "Unit")
+ other = _entity(client, cid, "organization", "Other unit")
+ _link(client, cid, person, unit, "member-of")
+ _link(client, cid, person, other, "member-of")
+
+ assert _node(_graph(client, cid), person)["degree"] == 2
+ assert _node(_graph(client, cid, omit=unit), person)["degree"] == 1
+
+
+def test_taking_a_node_out_takes_it_off_the_count_as_well(client):
+ """The count beside the lens is what is drawn, so hiding one has to move it: a
+ number that argues with the picture is worse than no number."""
+ cid = _case(client, "one fewer drawn")
+ person = _entity(client, cid, "person", "Root")
+ unit = _entity(client, cid, "organization", "Unit")
+ _link(client, cid, person, unit, "member-of")
+
+ before = _graph(client, cid)
+ after = _graph(client, cid, omit=unit)
+
+ assert after["shown"] == before["shown"] - 1
+
+
+def test_a_source_taken_out_comes_back_as_the_edge_it_stood_for(client):
+ """A middle taken out is still a middle. The path through it is a fact about the
+ case where the act was about the picture, so it is said as an edge — which is what
+ the fold does for a source the budget cut, for the same reason."""
+ cid = _case(client, "removed middle")
+ claim, who, marks = _sourced(client, cid)
+
+ drawn = _graph(client, cid, keep=",".join(marks))
+ assert set(marks) <= _ids(drawn)
+
+ payload = _graph(client, cid, keep=",".join(marks[1:]), omit=marks[0])
+
+ assert marks[0] not in _ids(payload)
+ edge = _folded(payload)[0]
+ assert (edge["from"], edge["to"], edge["type"]) == (claim, who, "cites")
+ assert edge["folded"]["sources"] == 1
+ assert edge["folded"]["open"] == [marks[0]]
+
+
+def test_taking_out_an_id_the_case_never_had_changes_nothing(client):
+ cid = _case(client, "removed ghost")
+ person = _entity(client, cid, "person", "Still here")
+
+ payload = _graph(client, cid, omit="e_nothing")
+
+ assert _ids(payload) == {person}
+
+
+def test_taking_out_the_account_a_fold_lands_on_never_grows_the_drawing(client):
+ """A removal must never *add* a node. The fold reads the chain statement → source →
+ account, so taking the account out broke it, nothing folded, and the three bookmarks
+ that had never been drawn arrived as nodes: two on screen became four, on the one
+ act that promised fewer."""
+ cid = _case(client, "fold, then take the account out")
+ claim, who, _marks = _sourced(client, cid)
+
+ assert _ids(_graph(client, cid)) == {claim, who}
+
+ payload = _graph(client, cid, omit=who)
+
+ assert _ids(payload) == {claim}
+ assert payload["links"] == []
+
+
+def test_a_middle_a_removal_cut_is_still_a_middle(client):
+ """Which is why the fold reads the edges the removal cut. Read off the drawing
+ alone, the chain has already lost the leg that makes it one, and the bookmarks come
+ back as the nodes the fold exists to keep off the screen."""
+ cid = _case(client, "the cut leg still counts")
+ claim, who, marks = _sourced(client, cid)
+
+ payload = _graph(client, cid, omit=who)
+
+ for mark in marks:
+ assert mark not in _ids(payload)
+
+
+def test_a_node_taken_out_takes_what_only_it_was_holding(client):
+ """The half the removal was missing. Taking out the node you opened left its whole
+ neighbourhood drawn with no edge to anything — a handful of dots whose only reason
+ to be there had just gone."""
+ cid = _case(client, "the arrivals go too")
+ root = _entity(client, cid, "person", "Root")
+ hub = _entity(client, cid, "account", "@hub")
+ _link(client, cid, root, hub, "owns")
+ shots = [_entity(client, cid, "media", f"Shot {n}") for n in range(3)]
+ for shot in shots:
+ _link(client, cid, hub, shot, "posted")
+
+ # Only people are ranked, so the account and its media are there by the expansion
+ # alone.
+ opened = _graph(client, cid, type="person", expand=hub)
+ assert _ids(opened) == {root, hub, *shots}
+
+ payload = _graph(client, cid, type="person", expand=hub, omit=hub)
+
+ assert _ids(payload) == {root}
+
+
+def test_an_arrival_a_second_expansion_reaches_stays(client):
+ """The convergence the drawing exists to show. Two accounts posting the same media
+ is the finding, so taking one out must not take the media the other still holds."""
+ cid = _case(client, "two accounts, one frame")
+ root = _entity(client, cid, "person", "Root")
+ hub = _entity(client, cid, "account", "@hub")
+ other = _entity(client, cid, "account", "@other")
+ _link(client, cid, root, hub, "owns")
+ _link(client, cid, root, other, "owns")
+ shared = _entity(client, cid, "media", "Shared frame")
+ only_hub = _entity(client, cid, "media", "Hub frame")
+ for account in (hub, other):
+ _link(client, cid, account, shared, "posted")
+ _link(client, cid, hub, only_hub, "posted")
+
+ payload = _graph(client, cid, type="person", expand=f"{hub},{other}", omit=hub)
+
+ assert _ids(payload) == {root, other, shared}
+
+
+def test_an_arrival_the_ranking_already_reaches_stays(client):
+ """An arrival joined to something drawn on its own merits is not adrift, whichever
+ node brought it in."""
+ cid = _case(client, "held by the ranking")
+ root = _entity(client, cid, "person", "Root")
+ seen = _entity(client, cid, "person", "Also ranked")
+ hub = _entity(client, cid, "account", "@hub")
+ _link(client, cid, root, hub, "owns")
+ frame = _media(client, cid, "Frame")
+ adrift = _media(client, cid, "Adrift")
+ _link(client, cid, hub, frame, "posted")
+ _link(client, cid, hub, adrift, "posted")
+ _link(client, cid, seen, frame, "appears-in")
+
+ payload = _graph(client, cid, type="person", expand=hub, omit=hub)
+
+ assert _ids(payload) == {root, seen, frame}
+ assert adrift not in _ids(payload)
+
+
+def test_two_arrivals_holding_only_each_other_are_still_adrift(client):
+ """Why it is reachability and not a degree. Counting edges keeps a pair that holds
+ itself up, and the vocabulary ranks no edge above another — there is no such thing
+ as the link that holds a node."""
+ cid = _case(client, "a pair adrift")
+ # Only places are ranked, so nothing else in this case stands on its own.
+ spot = _entity(client, cid, "place", "Quay")
+ unit = _entity(client, cid, "organization", "Unit")
+ driver = _entity(client, cid, "person", "Driver")
+ truck = _entity(client, cid, "vehicle", "Truck")
+ _link(client, cid, driver, unit, "member-of")
+ _link(client, cid, unit, truck, "owns")
+ # Both arrived by the same hop, and they are joined to each other: once the unit
+ # goes each still has an edge, and neither has anything else.
+ _link(client, cid, driver, truck, "owns")
+
+ payload = _graph(client, cid, type="place", expand=unit, omit=unit)
+
+ assert _ids(payload) == {spot}
+
+
+def test_a_node_the_ranking_drew_is_never_dropped_for_standing_alone(client):
+ """A ranked node is allowed to have no edge at all — that is what `isolated`
+ counts. Only what arrived by a hop is held by what reaches it."""
+ cid = _case(client, "alone by right")
+ root = _entity(client, cid, "person", "Root")
+ lone = _entity(client, cid, "person", "Nobody linked me")
+ hub = _entity(client, cid, "account", "@hub")
+ _link(client, cid, root, hub, "owns")
+
+ payload = _graph(client, cid, type="person", expand=hub, omit=hub)
+
+ assert _ids(payload) == {root, lone}
+
+
+def test_a_node_named_to_be_drawn_survives_a_removal_beside_it(client):
+ """`keep` says draw this one and nothing around it, so it has no anchor by
+ definition. Dropping it for that would refuse the act that drew it."""
+ cid = _case(client, "named stands alone")
+ root = _entity(client, cid, "person", "Root")
+ hub = _entity(client, cid, "account", "@hub")
+ _link(client, cid, root, hub, "owns")
+ frame = _media(client, cid, "Frame")
+ _link(client, cid, hub, frame, "posted")
+ far = _entity(client, cid, "place", "Named on its own")
+
+ payload = _graph(client, cid, type="person", expand=hub, keep=far, omit=hub)
+
+ assert _ids(payload) == {root, far}
+
+
+# -- the path -----------------------------------------------------------------
+
+
+def _paths(client, cid, from_id, to_id, **params):
+ res = client.get(
+ f"/api/cases/{cid}/graph/paths",
+ params={"from": from_id, "to": to_id, **params},
+ )
+ assert res.status_code == 200, res.text
+ return res.json()
+
+
+def _chain(client, cid):
+ """account --posted--> media --depicts--> place, the shape an investigation walks."""
+ account = _entity(client, cid, "account", "@watcher")
+ media = _entity(
+ client, cid, "media", "harbour frame", {"path": "media/frame.jpg", "kind": "image"}
+ )
+ place = _entity(client, cid, "place", "checkpoint north")
+ _link(client, cid, account, media, "posted")
+ _link(client, cid, media, place, "depicts")
+ return account, media, place
+
+
+def test_a_path_is_the_question_the_case_could_not_be_asked(client):
+ """How one entity reaches another, which no single hop and no table answers."""
+ cid = _case(client, "a path")
+ account, media, place = _chain(client, cid)
+
+ payload = _paths(client, cid, account, place)
+
+ assert payload["found"] is True
+ assert payload["hops"] == 2
+ assert [route["nodes"] for route in payload["routes"]] == [[account, media, place]]
+ assert {node["id"] for node in payload["nodes"]} == {account, media, place}
+ assert len(payload["links"]) == 2
+
+
+def test_a_path_runs_against_an_arrow_as_readily_as_along_it(client):
+ """An arrowhead says what an edge claims, not which way a route may run: asked
+ the other way round, the same two entities are the same two hops apart."""
+ cid = _case(client, "either way")
+ account, media, place = _chain(client, cid)
+
+ payload = _paths(client, cid, place, account)
+
+ assert payload["hops"] == 2
+ assert payload["routes"][0]["nodes"] == [place, media, account]
+
+
+def test_every_shortest_route_is_returned_because_the_ties_are_the_finding(client):
+ """Two accounts reaching the same place by two sources is what independence
+ looks like, and an answer that picked one of them would hide it."""
+ cid = _case(client, "two sources")
+ account = _entity(client, cid, "account", "@watcher")
+ place = _entity(client, cid, "place", "checkpoint north")
+ for at in range(2):
+ media = _entity(
+ client, cid, "media", f"frame {at}", {"path": f"media/{at}.jpg", "kind": "image"}
+ )
+ _link(client, cid, account, media, "posted")
+ _link(client, cid, media, place, "depicts")
+
+ payload = _paths(client, cid, account, place)
+
+ assert payload["hops"] == 2
+ assert len(payload["routes"]) == 2
+ middles = {route["nodes"][1] for route in payload["routes"]}
+ assert len(middles) == 2
+
+
+def test_a_longer_way_round_is_not_returned_once_a_shorter_one_exists(client):
+ """Once two entities are joined directly, the scenic route says nothing about
+ how they are connected."""
+ cid = _case(client, "short and long")
+ account = _entity(client, cid, "account", "@watcher")
+ media = _entity(
+ client, cid, "media", "frame", {"path": "media/frame.jpg", "kind": "image"}
+ )
+ place = _entity(client, cid, "place", "checkpoint north")
+ # The media both shows the place and is the account's own post, so the account
+ # is one hop from the place through the picture and two through nothing else.
+ _link(client, cid, media, place, "located-at")
+ _link(client, cid, account, media, "posted")
+ _link(client, cid, media, place, "depicts")
+
+ payload = _paths(client, cid, media, place)
+
+ assert payload["hops"] == 1
+ assert all(len(route["nodes"]) == 2 for route in payload["routes"])
+
+
+def test_no_route_is_an_answer_rather_than_an_error(client):
+ """Learning that two entities are not connected within the budget is a finding
+ about the case, where an empty response would read as no opinion."""
+ cid = _case(client, "unconnected")
+ account = _entity(client, cid, "account", "@watcher")
+ place = _entity(client, cid, "place", "elsewhere")
+
+ payload = _paths(client, cid, account, place)
+
+ assert payload["found"] is False
+ assert payload["routes"] == []
+ assert payload["nodes"] == []
+ assert payload["hops"] == 0
+
+
+def test_a_lens_narrows_which_verbs_a_route_may_use(client):
+ """A route through a verb the reading excludes is not a route in that reading."""
+ cid = _case(client, "lensed path")
+ account, media, place = _chain(client, cid)
+
+ everything = _paths(client, cid, account, place, lens="all")
+ ground = _paths(client, cid, account, place, lens="ground")
+
+ assert everything["found"] is True
+ # `posted` is not a geography verb, so the account cannot be reached from there.
+ assert ground["found"] is False
+
+
+def test_a_route_stops_at_the_hop_budget(client):
+ """Four hops on a well-linked case reaches most of it, and a chain that long
+ says everything is connected to everything, which is true and useless."""
+ cid = _case(client, "too far")
+ made = [_entity(client, cid, "organization", f"Unit {at}") for at in range(7)]
+ for at in range(6):
+ _link(client, cid, made[at], made[at + 1], "part-of")
+
+ assert _paths(client, cid, made[0], made[6])["found"] is False
+ assert _paths(client, cid, made[0], made[4])["hops"] == 4
+
+
+def test_the_hop_budget_cannot_be_raised_past_the_ceiling(client):
+ """Asked for more than the ceiling, the read is bounded rather than refused —
+ the same contract every other budget here keeps."""
+ cid = _case(client, "ceiling")
+ made = [_entity(client, cid, "organization", f"Unit {at}") for at in range(7)]
+ for at in range(6):
+ _link(client, cid, made[at], made[at + 1], "part-of")
+
+ payload = _paths(client, cid, made[0], made[6], hops=40)
+
+ assert payload["searched"] == graph_engine.MAX_PATH_HOPS
+ assert payload["found"] is False
+
+
+def test_an_entity_that_is_not_there_is_said_rather_than_answered_with_nothing(client):
+ cid = _case(client, "missing end")
+ account = _entity(client, cid, "account", "@watcher")
+
+ res = client.get(
+ f"/api/cases/{cid}/graph/paths", params={"from": account, "to": "nope"}
+ )
+
+ assert res.status_code == 404
+
+
+def test_a_node_asked_about_against_itself_is_a_route_of_no_hops(client):
+ cid = _case(client, "itself")
+ account = _entity(client, cid, "account", "@watcher")
+
+ payload = _paths(client, cid, account, account)
+
+ assert payload["found"] is True
+ assert payload["hops"] == 0
+ assert payload["routes"] == [{"nodes": [account], "links": []}]
+
+
+# -- the board's own filter, drawn ------------------------------------------
+#
+# The two surfaces read one case, and until now they spoke different filters: the
+# table could ask *which videos have coordinates* and the drawing could not, so a
+# question worked out in one could never be looked at in the other.
+
+
+def test_the_drawing_answers_the_same_sentence_the_table_does(client):
+ """*media, kind video, linked to a place* — the catalog's own sentence, asked of
+ the graph. One predicate answers both, so the two cannot disagree."""
+ cid = _case(client, "sentence")
+ placed = _entity(client, cid, "media", "clip.mp4", {"kind": "video"})
+ _entity(client, cid, "media", "orphan.mp4", {"kind": "video"})
+ _entity(client, cid, "media", "still.jpg", {"kind": "image"})
+ quay = _entity(client, cid, "place", "48.0, 2.0", {"lat": 48.0, "lon": 2.0})
+ _link(client, cid, placed, quay, "located-at")
+
+ payload = _graph(client, cid, type="media", attr="kind", value="video", linked="place")
+
+ assert [node["id"] for node in payload["nodes"]] == [placed]
+ assert payload["total"] == 1
+
+
+def test_search_plus_reaches_a_typed_field_in_the_live_graph(client):
+ """A plate is searchable even when the graph node title does not contain it."""
+ cid = _case(client, "broad graph search")
+ vehicle = _entity(
+ client, cid, "vehicle", "White pickup", {"plate": "AX-904-ZT"}
+ )
+ _entity(client, cid, "person", "Unrelated witness")
+
+ payload = _graph(client, cid, q="AX-904-ZT")
+
+ assert [node["id"] for node in payload["nodes"]] == [vehicle]
+ assert payload["total"] == 1
+ assert payload["nodes"][0]["matches"] == [
+ {"field": "plate", "label": "Plate", "value": "AX-904-ZT"}
+ ]
+
+
+def test_the_drawing_can_be_asked_what_nothing_connects_to(client):
+ """The case's unexploited material, drawn rather than only counted."""
+ cid = _case(client, "loose")
+ joined = _media(client, cid, "clip")
+ quay = _entity(client, cid, "place", "48.0, 2.0", {"lat": 48.0, "lon": 2.0})
+ _link(client, cid, joined, quay, "depicts")
+ alone = _media(client, cid, "orphan")
+
+ payload = _graph(client, cid, unlinked="true")
+
+ assert [node["id"] for node in payload["nodes"]] == [alone]
+
+
+def test_the_drawing_narrows_on_when_a_row_was_filed(client, monkeypatch):
+ cid = _case(client, "dates")
+ monkeypatch.setattr("azimut.sqlite_backend._now", lambda: "2026-07-01T09:00:00Z")
+ _entity(client, cid, "person", "old")
+ monkeypatch.setattr("azimut.sqlite_backend._now", lambda: "2026-08-10T09:00:00Z")
+ recent = _entity(client, cid, "person", "new")
+
+ payload = _graph(client, cid, since="2026-08-01")
+
+ assert [node["id"] for node in payload["nodes"]] == [recent]
+
+
+def test_a_node_named_by_the_caller_is_drawn_beside_the_case_it_came_from(client):
+ """`keep` draws a node and nothing around it, and the case stays behind it: the
+ picture grows rather than being replaced by the answer to a smaller question."""
+ cid = _case(client, "named")
+ wanted = _media(client, cid, "clip")
+ quay = _entity(client, cid, "place", "48.0, 2.0", {"lat": 48.0, "lon": 2.0})
+ _link(client, cid, wanted, quay, "depicts")
+ _entity(client, cid, "person", "somebody else")
+
+ payload = _graph(client, cid, keep=wanted)
+
+ assert len(payload["nodes"]) == 3
+ assert payload["kept"] == [wanted]
+ assert payload["total"] == 3
+
+
+def test_a_proof_adopts_the_preview_its_spec_was_keeping_to_itself(client):
+ """A proof saved before the preview lived on the entity keeps it in its spec
+ file. The first draw that shows one reads the spec, records it on the row, and
+ every later draw finds it there like any other preview."""
+ cid = _case(client, "adopt preview")
+ case = Case.open(cid)
+ meta = case.resolve_inside("proofs/.meta")
+ meta.mkdir(parents=True, exist_ok=True)
+ meta.joinpath("Quay.json").write_text(
+ json.dumps({"azimut_proof": 1, "thumb": "media/.thumbs/quay-g1.jpg"}),
+ encoding="utf-8",
+ )
+ proof = _entity(
+ client, cid, "proof", "Quay", {"spec": "proofs/.meta/Quay.json"}
+ )
+ assert "thumb" not in (case.get_entity(proof)["attrs"])
+
+ assert _node(_graph(client, cid), proof)["thumb"] == "media/.thumbs/quay-g1.jpg"
+
+ assert Case.open(cid).get_entity(proof)["attrs"]["thumb"] == (
+ "media/.thumbs/quay-g1.jpg"
+ )
+
+
+def test_the_drawing_still_arrives_when_the_preview_cannot_be_recorded(
+ client, monkeypatch
+):
+ """The copy onto the entity is an optimisation, and a locked database must not
+ turn a read of the graph into an error. A background import or a mass delete
+ holding the write lock past `busy_timeout` is exactly that case."""
+ cid = _case(client, "locked preview")
+ case = Case.open(cid)
+ meta = case.resolve_inside("proofs/.meta")
+ meta.mkdir(parents=True, exist_ok=True)
+ meta.joinpath("Roof.json").write_text(
+ json.dumps({"azimut_proof": 1, "thumb": "media/.thumbs/roof-g1.jpg"}),
+ encoding="utf-8",
+ )
+ proof = _entity(
+ client, cid, "proof", "Roof", {"spec": "proofs/.meta/Roof.json"}
+ )
+
+ def locked(self, *args, **kwargs):
+ raise sqlite3.OperationalError("database is locked")
+
+ monkeypatch.setattr(Case, "update_entity", locked)
+
+ body = _graph(client, cid)
+
+ # 200, and the node still carries the preview it just read off the spec
+ assert _node(body, proof)["thumb"] == "media/.thumbs/roof-g1.jpg"
diff --git a/tests/test_layout.py b/tests/test_layout.py
index 07d64c9..04576ab 100644
--- a/tests/test_layout.py
+++ b/tests/test_layout.py
@@ -87,6 +87,8 @@ def _tool_relative(slug: int, media: int) -> dict[str, int]:
"sidecar": len(layout.sidecar_rel(f"media/{longest_media}")),
"download scratch": len("media/.dl/") + layout.DOWNLOAD_ID_LENGTH + 1 + media,
"thumbnail": len("media/.thumbs/") + THUMB_NAME,
+ "entity photo": len(layout.entity_image_rel("i_0123456789")),
+ "entity photo thumbnail": len(layout.entity_image_thumb_rel("i_0123456789")),
"note": len(layout.note_rel(longest_folder, longest_name)),
"proof asset": len(layout.proof_assets_rel(longest_name)) + 1 + ASSET_NAME,
"proof spec": len(layout.proof_spec_rel(longest_name)),
@@ -182,6 +184,8 @@ def test_layout_answers_are_all_under_the_root(tmp_path: Path) -> None:
answers = [
layout.manifest(root),
layout.database(root),
+ layout.entity_images(root),
+ layout.entity_image_thumbs(root),
layout.notes_file(root),
layout.media(root),
layout.notes(root),
diff --git a/tests/test_links_api.py b/tests/test_links_api.py
index f1ca9ef..9be3142 100644
--- a/tests/test_links_api.py
+++ b/tests/test_links_api.py
@@ -10,9 +10,10 @@ import base64
import io
from PIL import Image
+import pytest
from azimut.engine import links as link_engine
-from azimut.workspace import Case
+from azimut.workspace import Case, CaseError
import graph_read
@@ -230,6 +231,64 @@ def test_upload_and_download_emit_no_links(client):
assert _links(client, cid) == []
+def test_lineage_rejects_sources_outside_the_artifact_matrix(client):
+ cid = _new_case(client, "Lineage matrix")
+ case = Case.open(cid)
+ media = case.add_entity("media", "Image", {"path": "media/image.png"}, by="user")
+ proof = case.add_entity("proof", "Proof", {"spec": "proofs/.meta/proof.json"}, by="user")
+ case.add_entity(
+ "proof", "Other proof", {"spec": "proofs/.meta/other.json"}, by="user"
+ )
+ post = case.add_entity("post", "Post", {"draft": ".drafts/post.json"}, by="user")
+ session = case.add_entity(
+ "inspect-session", "Session", {"spec": ".inspect/session.json"}, by="user"
+ )
+
+ link_engine.sync(
+ case, proof["id"], link_engine.DERIVED_FROM, ["media/image.png"], by="proof-composer"
+ )
+ with pytest.raises(CaseError, match="proof cannot be derived-from a proof"):
+ link_engine.sync(
+ case,
+ proof["id"],
+ link_engine.DERIVED_FROM,
+ ["proofs/.meta/other.json"],
+ by="proof-composer",
+ )
+ with pytest.raises(CaseError, match="inspect-session cannot be depends-on a proof"):
+ link_engine.sync(
+ case,
+ session["id"],
+ link_engine.DEPENDS_ON,
+ ["proofs/.meta/proof.json"],
+ by="inspect",
+ )
+ with pytest.raises(CaseError, match="post cannot be derived-from a inspect-session"):
+ link_engine.sync(
+ case,
+ post["id"],
+ link_engine.DERIVED_FROM,
+ [".inspect/session.json"],
+ by="post-composer",
+ )
+ assert {link["to"] for link in case.links_of(proof["id"])} == {media["id"]}
+
+
+def test_lineage_cannot_create_a_cycle(client):
+ cid = _new_case(client, "Lineage cycle")
+ case = Case.open(cid)
+ first = case.add_entity("media", "First", {"path": "media/first.png"}, by="user")
+ second = case.add_entity("media", "Second", {"path": "media/second.png"}, by="user")
+
+ link_engine.link_all(
+ case, first["id"], link_engine.DERIVED_FROM, ["media/second.png"], by="inspect"
+ )
+ with pytest.raises(CaseError, match="cannot create a cycle"):
+ link_engine.link_all(
+ case, second["id"], link_engine.DERIVED_FROM, ["media/first.png"], by="inspect"
+ )
+
+
def test_a_source_deleted_before_the_save_leaves_a_tombstone(client):
# The tool was open when the panel's media was deleted elsewhere: the path
# resolves to nothing, so there is no edge to draw — but the fact that the
@@ -638,12 +697,19 @@ def test_derivation_endpoint_returns_the_closure_and_404s(client):
def test_relation_vocabulary_says_how_each_type_reads_and_who_may_state_it(client):
entries = {row["type"]: row for row in client.get("/api/cases/relation-types").json()}
- assert entries["located-at"]["label"] == "was shot at"
- assert entries["located-at"]["from_types"] == ["capture", "media"]
+ assert entries["located-at"]["label"] == "was recorded at"
+ assert entries["located-at"]["inverse_label"] == "was recorded here"
+ assert entries["located-at"]["from_types"] == ["media"]
assert entries["located-at"]["to_types"] == ["place"]
+ assert entries["located-at"]["from_media_kinds"] == ["audio", "image", "video"]
assert entries["located-at"]["manual"] is True
+ assert entries["in-network"]["from_types"] == ["ip", "network"]
+ assert entries["in-network"]["to_types"] == ["network"]
+ assert entries["mentions"]["action"] == "mention"
+ assert {entries[type_]["action"] for type_ in ("about", "at", "cites")} == {"claim"}
# enrichment's own claim: named so the UI can say it, never offered by hand
assert entries["same-image-as"]["manual"] is False
+ assert entries["same-image-as"]["from_media_kinds"] == ["image"]
def test_the_analyst_can_state_a_relation_and_it_lands_confirmed(client):
@@ -688,7 +754,7 @@ def test_a_stated_relation_is_refused_when_the_ontology_has_no_reading(client):
# a derivation records what a save did; it is never asserted after the fact
assert post(media["id"], place["id"], "derived-from").status_code == 400
- # the wrong way round: a place is not shot at a photo
+ # the wrong way round: a place is not recorded at a photo
assert post(place["id"], media["id"], "located-at").status_code == 400
# a perceptual-hash match is enrichment's claim, not a person's
assert post(media["id"], other["id"], "same-image-as").status_code == 400
@@ -701,6 +767,204 @@ def test_a_stated_relation_is_refused_when_the_ontology_has_no_reading(client):
assert case.links_of(media["id"]) == []
+def test_media_relations_respect_the_file_kind(client):
+ cid = _new_case(client, "Media kinds")
+ case = Case.open(cid)
+ image = case.add_entity("media", "Still", {"path": "media/still.jpg"}, by="user")
+ audio = case.add_entity("media", "Call", {"path": "media/call.wav"}, by="user")
+ document = case.add_entity("media", "Report", {"path": "media/report.pdf"}, by="user")
+ capture = case.add_entity("capture", "Map", {"path": "captures/map.png"}, by="user")
+ person = case.add_entity("person", "Witness", {}, by="user")
+ place = case.add_entity("place", "Station", {"lat": 1.0, "lon": 2.0}, by="user")
+
+ def post(from_id, to_id, type_):
+ return client.post(
+ f"/api/cases/{cid}/links",
+ json={"from_id": from_id, "to_id": to_id, "type": type_},
+ )
+
+ assert post(image["id"], place["id"], "located-at").status_code == 200
+ assert post(audio["id"], place["id"], "located-at").status_code == 200
+ assert post(document["id"], place["id"], "located-at").status_code == 400
+ assert post(capture["id"], place["id"], "located-at").status_code == 400
+ assert post(image["id"], place["id"], "depicts").status_code == 200
+ assert post(audio["id"], place["id"], "depicts").status_code == 400
+ assert post(person["id"], image["id"], "appears-in").status_code == 200
+ assert post(person["id"], audio["id"], "appears-in").status_code == 400
+
+
+def test_networks_link_ips_and_parent_networks_without_cycles(client):
+ cid = _new_case(client, "Networks")
+ case = Case.open(cid)
+ ip = case.add_entity("ip", "203.0.113.42", {}, by="user")
+ subnet = case.add_entity("network", "203.0.113.0/24", {}, by="user")
+ parent = case.add_entity("network", "203.0.112.0/23", {}, by="user")
+
+ assert client.post(
+ f"/api/cases/{cid}/links",
+ json={"from_id": ip["id"], "to_id": subnet["id"], "type": "in-network"},
+ ).status_code == 200
+ assert client.post(
+ f"/api/cases/{cid}/links",
+ json={"from_id": subnet["id"], "to_id": parent["id"], "type": "in-network"},
+ ).status_code == 200
+ assert client.post(
+ f"/api/cases/{cid}/links",
+ json={"from_id": parent["id"], "to_id": subnet["id"], "type": "in-network"},
+ ).status_code == 400
+
+
+def test_organization_containment_cannot_create_a_cycle(client):
+ cid = _new_case(client, "Organization cycle")
+ case = Case.open(cid)
+ unit = case.add_entity("organization", "Unit", {}, by="user")
+ command = case.add_entity("organization", "Command", {}, by="user")
+
+ assert client.post(
+ f"/api/cases/{cid}/links",
+ json={"from_id": unit["id"], "to_id": command["id"], "type": "part-of"},
+ ).status_code == 200
+ assert client.post(
+ f"/api/cases/{cid}/links",
+ json={"from_id": command["id"], "to_id": unit["id"], "type": "part-of"},
+ ).status_code == 400
+
+
+def test_a_statement_can_be_told_what_stands_against_it(client):
+ """`contradicts` runs claim → claim, both ways, and joins nothing else.
+
+ A `refuted` confidence records that a statement is dead and names nothing that
+ killed it. Ruling out eleven candidates is half of a geolocation, and each of the
+ eleven has its own reasoning — so what stands against a statement is another
+ statement, never a grade and never a subject.
+ """
+ cid = _new_case(client, "Contradiction")
+ case = Case.open(cid)
+ first = case.add_entity("claim", "The bridge at Kerch", {}, by="user")
+ second = case.add_entity("claim", "A different bridge", {}, by="user")
+ person = case.add_entity("person", "Witness", {}, by="user")
+
+ def post(from_id, to_id, type_="contradicts"):
+ return client.post(
+ f"/api/cases/{cid}/links",
+ json={"from_id": from_id, "to_id": to_id, "type": type_},
+ )
+
+ stated = post(first["id"], second["id"])
+ assert stated.status_code == 200, stated.text
+ assert stated.json()["provenance"]["status"] == "confirmed"
+
+ # Two statements contradicting each other is what an open question looks like,
+ # not a loop to refuse — unlike `part-of`, which is containment.
+ assert post(second["id"], first["id"]).status_code == 200
+
+ # "This vehicle is contradicted" is not something anyone can assess.
+ assert post(first["id"], person["id"]).status_code == 400
+ assert post(person["id"], first["id"]).status_code == 400
+ assert post(first["id"], first["id"]).status_code == 400
+
+
+def test_a_statement_may_rest_on_another_statement(client):
+ """`cites` reaches a claim, so an intermediate conclusion can carry the next one.
+
+ Without it a case could say what stands *against* a statement and never what holds
+ it up: refuting "the vehicle is a T-72B3" left "the column is the 4th brigade"
+ standing, with nothing in the graph naming what it had lost.
+ """
+ cid = _new_case(client, "Grounded reasoning")
+ case = Case.open(cid)
+ model = case.add_entity("claim", "The vehicle is a T-72B3", {}, by="user")
+ unit = case.add_entity("claim", "The column is the 4th brigade", {}, by="user")
+ video = case.add_entity("media", "Column", {"path": "media/column.mp4"}, by="user")
+
+ def post(from_id, to_id, type_="cites"):
+ return client.post(
+ f"/api/cases/{cid}/links",
+ json={"from_id": from_id, "to_id": to_id, "type": type_},
+ )
+
+ grounded = post(unit["id"], model["id"])
+ assert grounded.status_code == 200, grounded.text
+ assert grounded.json()["provenance"]["status"] == "confirmed"
+ # The material end is untouched by the widening.
+ assert post(model["id"], video["id"]).status_code == 200
+ # Only a statement may rest on something, and only a statement may be rested on
+ # among the types this verb reaches.
+ assert post(video["id"], model["id"]).status_code == 400
+
+
+def test_reasoning_may_not_close_on_itself(client):
+ """A because B, B because A is circular reasoning, not a shape a case may hold.
+
+ Unlike `contradicts`, where two statements standing against each other is an open
+ question and both directions are kept.
+ """
+ cid = _new_case(client, "Circular reasoning")
+ case = Case.open(cid)
+ first = case.add_entity("claim", "First", {}, by="user")
+ second = case.add_entity("claim", "Second", {}, by="user")
+ third = case.add_entity("claim", "Third", {}, by="user")
+
+ def cite(from_id, to_id):
+ return client.post(
+ f"/api/cases/{cid}/links",
+ json={"from_id": from_id, "to_id": to_id, "type": "cites"},
+ )
+
+ assert cite(first["id"], second["id"]).status_code == 200
+ assert cite(second["id"], first["id"]).status_code == 400
+ assert cite(first["id"], first["id"]).status_code == 400
+ # And around a longer way, which is the same fallacy with a step in it.
+ assert cite(second["id"], third["id"]).status_code == 200
+ assert cite(third["id"], first["id"]).status_code == 400
+
+
+def test_citing_material_still_costs_no_walk_worth_refusing(client):
+ """Only a claim may cite, so the walk stops on the first bookmark it meets."""
+ cid = _new_case(client, "Material citations")
+ case = Case.open(cid)
+ claim = case.add_entity("claim", "A statement", {}, by="user")
+ page = case.add_entity("bookmark", "A page", {"url": "https://example.org"}, by="user")
+
+ assert client.post(
+ f"/api/cases/{cid}/links",
+ json={"from_id": claim["id"], "to_id": page["id"], "type": "cites"},
+ ).status_code == 200
+ assert client.post(
+ f"/api/cases/{cid}/links",
+ json={"from_id": page["id"], "to_id": claim["id"], "type": "cites"},
+ ).status_code == 400
+
+
+def test_a_contradiction_is_not_what_a_statement_rests_on(client):
+ """It is a claim-action verb and deliberately not a claim *connector*.
+
+ The connectors say what a statement is built out of, and a source fold walks
+ them (`engine/graph._fold`). Walked across this one, an argument between two
+ statements would collapse into a citation.
+ """
+ assert link_engine.CONTRADICTS not in link_engine.CLAIM_CONNECTION_TYPES
+ spec = link_engine.relation_type(link_engine.CONTRADICTS)
+ assert spec is not None
+ assert spec.action == "claim" and spec.manual and not spec.ratable
+ assert spec.from_types == spec.to_types == frozenset({"claim"})
+
+
+def test_an_older_out_of_matrix_connection_is_removable_but_not_rewordable(client):
+ cid = _new_case(client, "Older connection")
+ case = Case.open(cid)
+ person = case.add_entity("person", "Member", {}, by="user")
+ organization = case.add_entity("organization", "Group", {}, by="user")
+ legacy = case.add_link(person["id"], organization["id"], "part-of", by="user")
+
+ refused = client.patch(
+ f"/api/cases/{cid}/links/{legacy['id']}", json={"type": "member-of"}
+ )
+ assert refused.status_code == 400
+ assert client.delete(f"/api/cases/{cid}/links/{legacy['id']}").status_code == 200
+ assert case.links_of(person["id"]) == []
+
+
def test_a_relation_can_be_restated_corrected_and_taken_back(client):
"""Relations are editable for as long as the case is open: a wrong reading is
corrected on the same edge — same id, same provenance — and any relation can be
@@ -760,7 +1024,7 @@ def test_restating_a_relation_is_refused_outside_the_vocabulary(client):
def test_confirming_a_relation_confirms_the_point_it_proposes(client):
"""The two halves of an enrichment suggestion are one claim, so the Suggestions
list and the relation rows never disagree about the same click: accepting "this
- file was shot at this point" accepts the point too."""
+ file was recorded at this point" accepts the point too."""
cid = _new_case(client, "Symmetric confirm")
case = Case.open(cid)
media = case.add_entity("media", "Photo", {"path": "media/photo.jpg"}, by="user")
@@ -863,3 +1127,92 @@ def test_confirming_an_entity_stops_at_one_hop(client):
assert case.get_entity(place["id"])["provenance"]["status"] == "confirmed"
assert case.get_link(far["id"])["provenance"]["status"] == "suggested"
assert case.get_entity(other["id"])["provenance"]["status"] == "suggested"
+
+
+def test_two_actors_can_be_tied_without_owning_or_containing_each_other(client):
+ """The verb the vocabulary had no way to say.
+
+ `owns` refuses a person as its object, `member-of` and `part-of` both end at an
+ organization — so until this existed, stating that two people are connected, the
+ first thing a case does, cost a whole Claim node.
+ """
+ cid = _new_case(client, "Association")
+ case = Case.open(cid)
+ one = case.add_entity("person", "First", {}, by="user")
+ two = case.add_entity("person", "Second", {}, by="user")
+ unit = case.add_entity("organization", "A unit", {}, by="user")
+ car = case.add_entity("vehicle", "A lorry", {}, by="user")
+
+ def post(from_id, to_id):
+ return client.post(
+ f"/api/cases/{cid}/links",
+ json={"from_id": from_id, "to_id": to_id, "type": "associated-with"},
+ )
+
+ assert post(one["id"], two["id"]).status_code == 200
+ assert post(one["id"], unit["id"]).status_code == 200
+ assert post(unit["id"], one["id"]).status_code == 200
+ # Opened past the actors it becomes the verb that swallows the vocabulary.
+ assert post(one["id"], car["id"]).status_code == 400
+ assert post(one["id"], one["id"]).status_code == 400
+
+
+def test_what_kind_of_tie_belongs_to_the_verb_and_not_to_the_edge(client):
+ """A note every edge could hold would leave nothing saying what an edge *is*.
+
+ So the qualifier is declared by the relation type, exactly as a rating is
+ declared by `ratable`, and the API refuses one anywhere else.
+ """
+ cid = _new_case(client, "Qualified tie")
+ case = Case.open(cid)
+ one = case.add_entity("person", "First", {}, by="user")
+ two = case.add_entity("person", "Second", {}, by="user")
+ unit = case.add_entity("organization", "A unit", {}, by="user")
+
+ tie = client.post(
+ f"/api/cases/{cid}/links",
+ json={"from_id": one["id"], "to_id": two["id"], "type": "associated-with"},
+ ).json()
+ member = client.post(
+ f"/api/cases/{cid}/links",
+ json={"from_id": one["id"], "to_id": unit["id"], "type": "member-of"},
+ ).json()
+
+ def qualify(link_id, value):
+ return client.patch(f"/api/cases/{cid}/links/{link_id}", json={"nature": value})
+
+ said = qualify(tie["id"], " sister ")
+ assert said.status_code == 200
+ assert said.json()["nature"] == "sister"
+ # unstated is a state to be able to return to, both ways of saying it
+ assert qualify(tie["id"], None).json().get("nature") is None
+ assert qualify(tie["id"], "employer").json()["nature"] == "employer"
+ assert qualify(tie["id"], " ").json().get("nature") is None
+ # a word, not a notes box
+ assert qualify(tie["id"], "x" * 200).status_code == 400
+ # and no other verb accepts one
+ assert qualify(member["id"], "sister").status_code == 400
+ assert "nature" not in Case.open(cid).get_link(member["id"])
+
+
+def test_rewording_a_tie_into_another_verb_takes_its_qualifier_with_it(client):
+ """Left behind it would be data no surface can show and nobody can clear: the
+ edge would privately hold "sister" while stating that one unit is part of
+ another."""
+ cid = _new_case(client, "Reworded tie")
+ case = Case.open(cid)
+ person = case.add_entity("person", "First", {}, by="user")
+ unit = case.add_entity("organization", "A unit", {}, by="user")
+
+ tie = client.post(
+ f"/api/cases/{cid}/links",
+ json={"from_id": person["id"], "to_id": unit["id"], "type": "associated-with"},
+ ).json()
+ client.patch(f"/api/cases/{cid}/links/{tie['id']}", json={"nature": "employer"})
+
+ reworded = client.patch(
+ f"/api/cases/{cid}/links/{tie['id']}", json={"type": "member-of"}
+ )
+ assert reworded.status_code == 200
+ assert "nature" not in reworded.json()
+ assert "nature" not in Case.open(cid).get_link(tie["id"])
diff --git a/tests/test_media_api.py b/tests/test_media_api.py
index fc16a31..158a676 100644
--- a/tests/test_media_api.py
+++ b/tests/test_media_api.py
@@ -339,6 +339,139 @@ def test_media_page_does_not_scan_sidecars_for_each_request(client, monkeypatch)
assert page["total"] == 1
+# -- what the case collected, apart from what it made ------------------------
+#
+# A geolocation case ends up with far more extracted frames than collected files,
+# and the chips cannot answer "what did we actually collect": they are
+# single-select and each says "show me only X". This is the other axis, so it is a
+# switch, and it scopes the counts as well as the page — a chooser still
+# advertising rows the switch is hiding is a chooser that lies.
+
+
+def _made_here(client, cid, source_path, *, name=None):
+ """One derivative through the real Inspect route.
+
+ The source colours matter: brightening a near-black pixel rounds back to
+ itself, the bytes match, and dedupe hands back the *upload* — which is correct
+ behaviour and a fixture that would test nothing.
+ """
+ res = client.post(
+ f"/api/cases/{cid}/inspect/save-frames",
+ json={
+ "items": [
+ {
+ "path": source_path,
+ "ops": [{"op": "brightness", "params": {"amount": 1.4}}],
+ **({"label": name} if name else {}),
+ }
+ ]
+ },
+ )
+ assert res.status_code == 200, res.text
+ saved = res.json()["saved"][0]
+ assert saved["duplicate"] is False, "fixture produced bytes the case already held"
+ return saved["item"]
+
+
+def test_media_page_can_leave_out_what_the_case_made(client):
+ cid = client.post("/api/cases", json={"name": "Collected"}).json()["id"]
+ original = _upload(client, cid, "orig.png", _png_bytes()).json()["item"]
+ made = _made_here(client, cid, original["path"])
+
+ everything = client.get(f"/api/cases/{cid}/media/page").json()
+ assert {item["path"] for item in everything["items"]} == {original["path"], made["path"]}
+ # The number is reported whether the switch is on or off: off, it is what
+ # turning it on would hide.
+ assert everything["facets"]["made_here_count"] == 1
+
+ collected = client.get(
+ f"/api/cases/{cid}/media/page", params={"collected_only": "true"}
+ ).json()
+ assert [item["path"] for item in collected["items"]] == [original["path"]]
+ assert collected["total"] == 1
+ assert collected["facets"]["made_here_count"] == 1
+
+
+def test_leaving_them_out_scopes_the_counts_too(client):
+ """Otherwise the Collages chip offers thirty rows and clicking it shows none."""
+ cid = client.post("/api/cases", json={"name": "Scoped counts"}).json()["id"]
+ original = _upload(client, cid, "orig.png", _png_bytes()).json()["item"]
+ _made_here(client, cid, original["path"])
+
+ page = client.get(f"/api/cases/{cid}/media/page", params={"collected_only": "true"}).json()
+ assert page["facets"]["category_counts"]["image"] == 1
+ assert page["facets"]["category_counts"]["upload"] == 1
+ assert page["facets"]["kind_counts"]["image"] == 1
+
+
+def test_leaving_them_out_does_not_touch_collected_material(client):
+ """A satellite capture is original imagery brought into the case, not something
+ composed out of what the case already holds. Same for a download and an import."""
+ from azimut.engine import media as media_engine
+ from azimut.workspace import Case
+
+ cid = client.post("/api/cases", json={"name": "Untouched"}).json()["id"]
+ upload = _upload(client, cid, "orig.png", _png_bytes()).json()["item"]
+ capture = media_engine.import_image(
+ Case.open(cid),
+ Image.new("RGB", (32, 24)),
+ "map.png",
+ {"type": "satellite"},
+ entity_type="capture",
+ dedupe=False,
+ )["item"]
+
+ page = client.get(f"/api/cases/{cid}/media/page", params={"collected_only": "true"}).json()
+ assert {item["path"] for item in page["items"]} == {upload["path"], capture["path"]}
+ assert page["facets"]["made_here_count"] == 0
+
+
+def test_the_switch_reads_how_a_file_entered_not_everything_true_about_it(client):
+ """Dedupe hands back the entity that is already there, and its row with it. Bytes
+ that arrived as an upload stay on the collected side even once Inspect produces
+ the same picture, because that is how they entered the case."""
+ cid = client.post("/api/cases", json={"name": "Entered by"}).json()["id"]
+ original = _upload(client, cid, "orig.png", _png_bytes()).json()["item"]
+ made = _made_here(client, cid, original["path"])
+ same_bytes = client.get(f"/files/{cid}/{made['path']}").content
+
+ again = _upload(client, cid, "handed-over.png", same_bytes).json()
+ assert again["duplicate"] is True
+
+ page = client.get(f"/api/cases/{cid}/media/page", params={"collected_only": "true"}).json()
+ # Still one made-here row, not two, and the import did not resurrect it.
+ assert [item["path"] for item in page["items"]] == [original["path"]]
+ assert page["facets"]["made_here_count"] == 1
+
+
+def test_leaving_them_out_pages_and_counts_together(client):
+ """The page and the total come from the same SQL, so a client-side filter would
+ have produced a right-looking first page and a wrong count under it."""
+ cid = client.post("/api/cases", json={"name": "Paged"}).json()["id"]
+ originals = [
+ _upload(client, cid, f"orig{i}.png", _png_bytes(color=(40 + i * 40, 20, 20))).json()["item"]
+ for i in range(3)
+ ]
+ for original in originals:
+ _made_here(client, cid, original["path"])
+
+ first = client.get(
+ f"/api/cases/{cid}/media/page", params={"collected_only": "true", "limit": 2}
+ ).json()
+ assert first["total"] == 3
+ assert len(first["items"]) == 2
+ assert first["next_cursor"] == "2"
+
+ rest = client.get(
+ f"/api/cases/{cid}/media/page",
+ params={"collected_only": "true", "limit": 2, "cursor": first["next_cursor"]},
+ ).json()
+ assert len(rest["items"]) == 1
+ assert rest["next_cursor"] is None
+ seen = {item["path"] for item in first["items"] + rest["items"]}
+ assert seen == {item["path"] for item in originals}
+
+
def test_media_metadata_returns_only_requested_paths(client):
cid = client.post("/api/cases", json={"name": "Metadata"}).json()["id"]
first = _upload(client, cid, "first.png", _png_bytes(color=(10, 0, 0))).json()["item"]
@@ -1613,3 +1746,126 @@ def test_enrich_counts_the_jobs_the_queue_took(client):
"queued": 1
}
workqueue.wait_until_idle()
+
+
+# ── clipboard paste ──────────────────────────────────────────────────────────
+# A screenshot taken with the system tool exists only in the clipboard, so there
+# is no file to drop and no name or origin to read off one. That is the whole
+# reason this route is not `upload`: the title and the source are stated in the
+# dialog or not at all, and the provenance must not claim a file was chosen.
+
+
+def _paste(client, cid, data=None, name="image.png", **fields):
+ return client.post(
+ f"/api/cases/{cid}/media/paste",
+ files={"file": (name, io.BytesIO(_png_bytes() if data is None else data), "image/png")},
+ data=fields,
+ )
+
+
+def test_paste_files_the_image_under_its_typed_title_and_source(client):
+ cid = client.post("/api/cases", json={"name": "Paste"}).json()["id"]
+
+ body = _paste(
+ client, cid, title="Front gate", source_url="https://example.com/page"
+ ).json()
+
+ assert body["duplicate"] is False
+ item = body["item"]
+ # the title names the file, because "image.png" is what every clipboard calls it
+ assert item["filename"] == "Front gate.png"
+ assert item["title"] == "Front gate"
+ assert item["kind"] == "image"
+ # recorded as a paste, never as an upload: a screenshot with no stated source
+ # must not read like a file somebody picked off a disk
+ assert item["source"]["type"] == "clipboard"
+ assert item["source"]["url"] == "https://example.com/page"
+ assert item["source"]["original_name"] == "image.png"
+
+ entity = graph_read.entities(cid)[0]
+ assert entity["type"] == "media"
+ assert entity["label"] == "Front gate"
+ assert entity["provenance"]["by"] == "paste"
+ assert entity["attrs"]["source_url"] == "https://example.com/page"
+ assert client.get(f"/files/{cid}/{item['path']}").status_code == 200
+
+
+def test_paste_without_a_title_is_stamped_rather_than_called_image(client):
+ cid = client.post("/api/cases", json={"name": "Unnamed paste"}).json()["id"]
+
+ item = _paste(client, cid).json()["item"]
+
+ assert item["filename"].startswith("paste-")
+ assert item["filename"].endswith(".png")
+ # nothing was stated, so nothing is claimed
+ assert "url" not in item["source"]
+
+
+def test_pasting_the_same_crop_twice_is_one_file(client):
+ """Deduped like any import: the bytes are the identity, whatever gesture
+ brought them in, and a second Ctrl+V is usually a doubt about the first."""
+ cid = client.post("/api/cases", json={"name": "Twice"}).json()["id"]
+ pixels = _png_bytes(color=(3, 9, 27))
+
+ first = _paste(client, cid, pixels, title="Gate").json()
+ again = _paste(client, cid, pixels, title="Gate again").json()
+
+ assert first["duplicate"] is False and again["duplicate"] is True
+ assert len(client.get(f"/api/cases/{cid}/media").json()) == 1
+
+
+def test_a_paste_and_a_drop_count_as_one_facet(client):
+ """Both are material the analyst brought in by hand, which is what the
+ Imports filter asks. They stay two source types because only one of them can
+ say where it came from."""
+ cid = client.post("/api/cases", json={"name": "Facet"}).json()["id"]
+ _upload(client, cid, "dropped.png", _png_bytes(color=(1, 2, 3)))
+ _paste(client, cid, _png_bytes(color=(4, 5, 6)), title="Pasted")
+
+ facets = client.get(f"/api/cases/{cid}/media/page").json()["facets"]
+ assert facets["category_counts"]["upload"] == 2
+
+ filtered = client.get(
+ f"/api/cases/{cid}/media/page", params={"category": "upload"}
+ ).json()
+ assert len(filtered["items"]) == 2
+
+
+def test_paste_refuses_anything_that_is_not_a_readable_image(client):
+ """The clipboard is not a file picker: a case takes a pasted screenshot, not
+ an arbitrary payload."""
+ cid = client.post("/api/cases", json={"name": "Not an image"}).json()["id"]
+
+ refused = _paste(client, cid, b"this is not a png", name="clip.txt")
+
+ assert refused.status_code == 422
+ assert "readable image" in refused.json()["detail"]
+ assert client.get(f"/api/cases/{cid}/media").json() == []
+
+
+def test_paste_refuses_a_source_that_is_not_an_http_url(client):
+ """The source is provenance. A `javascript:` or `data:` string is not one,
+ and it would be read back as a link in the details panel."""
+ cid = client.post("/api/cases", json={"name": "Bad source"}).json()["id"]
+
+ refused = _paste(client, cid, title="Gate", source_url="javascript:alert(1)")
+
+ assert refused.status_code == 422
+ assert "http(s)" in refused.json()["detail"]
+ assert client.get(f"/api/cases/{cid}/media").json() == []
+
+
+def test_paste_is_bounded_at_the_edge_like_every_other_swallowed_image(client, monkeypatch):
+ """Refusing early is what keeps a mistaken Ctrl+V from writing an enormous
+ temporary nobody asked for."""
+ from azimut.api import media as media_api
+ from azimut.workspace import Case
+
+ monkeypatch.setattr(media_api, "MAX_IMAGE_BYTES", 100)
+ cid = client.post("/api/cases", json={"name": "Bounded paste"}).json()["id"]
+
+ refused = _paste(client, cid, title="Huge")
+
+ assert refused.status_code == 413
+ assert "under" in refused.json()["detail"]
+ assert list(Case.open(cid).media_dir.glob("*.png")) == []
diff --git a/tests/test_migrations.py b/tests/test_migrations.py
index a2ffac9..e96d970 100644
--- a/tests/test_migrations.py
+++ b/tests/test_migrations.py
@@ -6,11 +6,15 @@ migrations to prove the runners, and pin the "same schema doesn't rewrite" and
import json
import shutil
+import sqlite3
+from contextlib import closing
import pytest
+import fullcase
from legacy_case import rewind_case, unwrap_case, write_legacy_json_case
from azimut import config, layout, workspace
+from azimut.sqlite_backend import SQLITE_SCHEMA
from azimut.engine import trash as trash_engine
from azimut.workspace import Case, CaseError, ensure_dir
@@ -596,3 +600,205 @@ def test_schema_seven_case_gets_a_readme_without_overwriting_one(tmp_workspace):
Case.open(case.id)
assert readme.read_text(encoding="utf-8") == "My own instructions\n"
+
+
+def test_a_whole_case_from_the_last_release_opens_on_the_current_schema(client):
+ """The upgrade people actually run: a case filed by the previous release,
+ opened by this one.
+
+ `tests/test_sqlite_backend.py` proves the chain on hand-built databases, one
+ step at a time. This proves it on a case with everything in it — media and
+ their sidecars, notes, proofs, places, claims, folders, links — and then reads
+ the surfaces that depend on what the chain created. A migration that leaves a
+ database technically at the right version but unreadable by the app would pass
+ every step-level test and fail here.
+
+ Schema 7 is what `v0.2.7` shipped, so this is the exact jump an installed copy
+ makes on its first open after the update.
+ """
+ import schema_rewind
+
+ full = fullcase.build_full_case(client)
+ case = Case.open(full.case_id)
+ before = {
+ entity["id"]: entity["label"] for entity in case.list_entities()
+ }
+ assert before, "the fixture planted nothing"
+ schema_rewind.rewind(case.db_path, 7)
+
+ reopened = Case.open(full.case_id)
+
+ with closing(sqlite3.connect(reopened.db_path)) as conn, conn:
+ assert conn.execute(
+ "SELECT value FROM meta WHERE key = 'schema_version'"
+ ).fetchone()[0] == str(SQLITE_SCHEMA)
+
+ # Nothing the case already held was dropped or renamed on the way up.
+ assert {e["id"]: e["label"] for e in reopened.list_entities()} == before
+ assert len(reopened.list_links()) == len(case.list_links())
+
+ # The catalog still pages, still counts, and still orders the whole case by
+ # the two columns schema 14 indexed.
+ page = reopened.page_entities(limit=5, order="label")
+ assert page["total"] == len(before)
+ assert [item["label"] for item in page["items"]] == sorted(
+ (label for label in before.values()), key=str.casefold
+ )[:5]
+ assert reopened.catalog_summary()["total"] == len(before)
+
+ # The tables the chain created answer, rather than raising "no such table".
+ assert reopened.list_analysis_views() == []
+ assert reopened.graph_pins("all") == {}
+ assert reopened.entity_images(full.org_id) == []
+ assert reopened.entity_image_thumbs(list(before)) == {}
+
+ # And the case draws, which is the read that touches most of them at once.
+ drawn = client.get(f"/api/cases/{full.case_id}/graph")
+ assert drawn.status_code == 200, drawn.text
+ assert drawn.json()["nodes"]
+
+
+def test_a_case_from_the_last_release_keeps_its_photos_and_readings_on_disk(client):
+ """The other half: what schema 7 could not hold is gone, and what the *files*
+ hold is not. A rewind drops the gallery rows, so the private photo bytes are
+ still there and the migration must neither resurrect a row for them nor
+ destroy them — only the Case Doctor is allowed to remove them, and it says so
+ first."""
+ import schema_rewind
+
+ full = fullcase.build_full_case(client)
+ case = Case.open(full.case_id)
+ photo = case.resolve_inside(full.entity_photo)
+ assert photo.is_file()
+ schema_rewind.rewind(case.db_path, 7)
+
+ reopened = Case.open(full.case_id)
+
+ assert reopened.entity_images(full.org_id) == []
+ assert photo.is_file()
+
+
+def test_schema_16_keeps_existing_views_and_accepts_timeline_readings(tmp_workspace):
+ case = Case.create("Timeline view migration")
+ existing = case.save_analysis_view({
+ "id": "v_existing",
+ "name": "Existing graph reading",
+ "mode": "live",
+ "surface": "graph",
+ "spec": {"version": 1, "query": {"terms": {}}},
+ "created_at": "2026-08-12T10:00:00Z",
+ "updated_at": "2026-08-12T10:00:00Z",
+ })
+ with closing(sqlite3.connect(case.db_path)) as conn, conn:
+ conn.execute("ALTER TABLE analysis_views RENAME TO analysis_views_current")
+ conn.execute(
+ "CREATE TABLE analysis_views ("
+ "id TEXT PRIMARY KEY, name TEXT NOT NULL,"
+ "mode TEXT NOT NULL CHECK (mode IN ('live', 'snapshot')),"
+ "surface TEXT NOT NULL CHECK (surface IN ('board', 'graph')),"
+ "spec_json TEXT NOT NULL, snapshot_count INTEGER NOT NULL DEFAULT 0,"
+ "created_at TEXT NOT NULL, updated_at TEXT NOT NULL)"
+ )
+ conn.execute("INSERT INTO analysis_views SELECT * FROM analysis_views_current")
+ conn.execute("DROP TABLE analysis_views_current")
+ conn.execute("CREATE INDEX idx_analysis_views_updated ON analysis_views(updated_at DESC)")
+ conn.execute("UPDATE meta SET value = '15' WHERE key = 'schema_version'")
+ conn.execute("DELETE FROM schema_migrations WHERE version >= 16")
+
+ reopened = Case.open(case.id)
+ assert reopened.get_analysis_view(existing["id"]) == existing
+ timeline = reopened.save_analysis_view({
+ "id": "v_timeline",
+ "name": "Timeline reading",
+ "mode": "live",
+ "surface": "timeline",
+ "spec": {"version": 1, "timeline": {"tracks": []}},
+ "created_at": "2026-08-12T11:00:00Z",
+ "updated_at": "2026-08-12T11:00:00Z",
+ })
+ assert timeline["surface"] == "timeline"
+
+
+def test_schema_16_copies_views_by_column_name_whatever_their_order(tmp_workspace):
+ """The legacy table's columns sit in whatever order its own history left them.
+
+ A case that gained `snapshot_count` by an `ALTER TABLE` carries it last, so the
+ positional copy the migration used to do rotated three values on every existing
+ row: the count came out holding a timestamp, and the view could no longer be read.
+ """
+ case = Case.create("View column order")
+ saved = case.save_analysis_view({
+ "id": "v_snap",
+ "name": "Frozen graph reading",
+ "mode": "snapshot",
+ "surface": "graph",
+ "spec": {
+ "version": 1,
+ "query": {"terms": {}},
+ "snapshot": {
+ "captured_at": "2026-08-10T21:02:40Z",
+ "entities": [
+ {"id": f"e{index}", "type": "person", "label": f"Person {index}"}
+ for index in range(3)
+ ],
+ "links": [],
+ },
+ },
+ "created_at": "2026-08-10T21:02:40Z",
+ "updated_at": "2026-08-10T21:02:45Z",
+ })
+ assert saved["snapshot_count"] == 3
+ with closing(sqlite3.connect(case.db_path)) as conn, conn:
+ # the pre-16 shape, with the count appended after the timestamps
+ conn.execute("ALTER TABLE analysis_views RENAME TO analysis_views_current")
+ conn.execute(
+ "CREATE TABLE analysis_views ("
+ "id TEXT PRIMARY KEY, name TEXT NOT NULL,"
+ "mode TEXT NOT NULL CHECK (mode IN ('live', 'snapshot')),"
+ "surface TEXT NOT NULL CHECK (surface IN ('board', 'graph')),"
+ "spec_json TEXT NOT NULL,"
+ "created_at TEXT NOT NULL, updated_at TEXT NOT NULL,"
+ "snapshot_count INTEGER NOT NULL DEFAULT 0)"
+ )
+ conn.execute(
+ "INSERT INTO analysis_views"
+ " (id, name, mode, surface, spec_json, created_at, updated_at, snapshot_count)"
+ " SELECT id, name, mode, surface, spec_json, created_at, updated_at,"
+ " snapshot_count FROM analysis_views_current"
+ )
+ conn.execute("DROP TABLE analysis_views_current")
+ conn.execute("CREATE INDEX idx_analysis_views_updated ON analysis_views(updated_at DESC)")
+ conn.execute("UPDATE meta SET value = '15' WHERE key = 'schema_version'")
+ conn.execute("DELETE FROM schema_migrations WHERE version >= 16")
+
+ reopened = Case.open(case.id)
+
+ assert reopened.get_analysis_view("v_snap") == saved
+ assert [view["snapshot_count"] for view in reopened.list_analysis_views()] == [3]
+
+
+def test_schema_17_rewrites_temporal_bounds_to_fixed_width(tmp_workspace):
+ case = Case.create("Variable temporal bounds")
+ claim = case.add_entity(
+ "claim",
+ "Subsecond observation",
+ {"when": "2026-08-11T10:32:14.5Z"},
+ by="user",
+ )
+ with closing(sqlite3.connect(case.db_path)) as conn, conn:
+ conn.execute(
+ "UPDATE temporal_items SET earliest = ?, latest = ? WHERE owner_id = ?",
+ (
+ "2026-08-11T10:32:14.5Z",
+ "2026-08-11T10:32:14.6Z",
+ claim["id"],
+ ),
+ )
+ conn.execute("UPDATE meta SET value = '16' WHERE key = 'schema_version'")
+ conn.execute("DELETE FROM schema_migrations WHERE version >= 17")
+
+ reopened = Case.open(case.id)
+
+ item = reopened.timeline_page(categories=["statement"])["items"][0]
+ assert item["earliest"] == "2026-08-11T10:32:14.500000Z"
+ assert item["latest"] == "2026-08-11T10:32:14.600000Z"
diff --git a/tests/test_place_precision.py b/tests/test_place_precision.py
new file mode 100644
index 0000000..46595e3
--- /dev/null
+++ b/tests/test_place_precision.py
@@ -0,0 +1,306 @@
+"""Approximate places (ONTOLOGY §2): a radius, a footprint, and how they got there.
+
+The rules under test come from Darwin Core, which settled this for biodiversity
+records two decades ago: the radius is the smallest circle containing the whole
+location, **zero is not a valid radius** because empty already means unknown, and
+the source's own wording outlives every reinterpretation of it.
+
+The other half is that none of it is required. A place saved the way Satellite has
+always saved one stays valid and complete, and an absent radius is a state rather
+than a gap to fill.
+"""
+
+import pytest
+
+from azimut.engine import entities
+from azimut.workspace import Case, CaseError
+
+
+def _new_case(client, name):
+ return client.post("/api/cases", json={"name": name}).json()["id"]
+
+
+def _place(client, cid, **attrs):
+ res = client.post(
+ f"/api/cases/{cid}/entities",
+ json={"type": "place", "label": "Quay 4", "attrs": {"lat": 53.44, "lon": 14.55, **attrs}},
+ )
+ return res
+
+
+def _patch(client, cid, eid, attrs):
+ return client.patch(f"/api/cases/{cid}/entities/{eid}", json={"attrs": attrs})
+
+
+# -- nothing is required ------------------------------------------------------
+
+
+def test_a_place_without_precision_is_still_valid(client):
+ """The rule the whole feature answers to: today's saved place is unchanged."""
+ cid = _new_case(client, "Plain place")
+
+ res = _place(client, cid)
+
+ assert res.status_code == 200, res.text
+ assert "radius_m" not in res.json()["attrs"]
+
+
+def test_clearing_a_field_is_how_unknown_is_written(client):
+ """Refusing an empty value would make "I do not know how precise this is"
+ impossible to say, which is the state most places are actually in."""
+ cid = _new_case(client, "Cleared radius")
+ eid = _place(client, cid, radius_m=100).json()["id"]
+
+ assert _patch(client, cid, eid, {"radius_m": None}).status_code == 200
+ assert _patch(client, cid, eid, {"verbatim": ""}).status_code == 200
+
+
+# -- the radius ---------------------------------------------------------------
+
+
+def test_a_radius_records_the_smallest_enclosing_circle(client):
+ cid = _new_case(client, "Approximate place")
+
+ res = _place(
+ client, cid,
+ radius_m=500,
+ verbatim="près du vieux port, côté nord",
+ method="roofline matched against Esri imagery 2023-06",
+ )
+
+ assert res.status_code == 200, res.text
+ attrs = res.json()["attrs"]
+ assert attrs["radius_m"] == 500
+ # the source's own wording, unaltered: the field people wish they had kept
+ assert attrs["verbatim"] == "près du vieux port, côté nord"
+ assert attrs["method"].startswith("roofline matched")
+ # and the tool's own keys are untouched by any of it
+ assert attrs["lat"] == 53.44
+
+
+def test_zero_is_not_a_valid_radius(client):
+ """Darwin Core's rule, and the reason for it: empty means *unknown*, where `0`
+ would claim infinite precision. They are different states and both are needed."""
+ cid = _new_case(client, "Zero radius")
+
+ assert _place(client, cid, radius_m=0).status_code == 400
+ assert _place(client, cid, radius_m=-50).status_code == 400
+
+
+def test_a_radius_must_be_a_finite_number(client):
+ cid = _new_case(client, "Odd radius")
+
+ assert _place(client, cid, radius_m="500").status_code == 400
+ # True is an int in Python, and `True` metres is not a radius
+ assert _place(client, cid, radius_m=True).status_code == 400
+ assert _place(client, cid, radius_m=entities.MAX_RADIUS_M + 1).status_code == 400
+
+
+def test_an_infinite_radius_cannot_sneak_in_as_a_json_literal(client):
+ """`json.dumps` refuses `inf`, so no ordinary client can send one — but
+ `json.loads` *accepts* the non-standard `Infinity` literal, which is how it would
+ actually arrive. Hence the finiteness check, tested through the real path."""
+ cid = _new_case(client, "Infinite radius")
+
+ res = client.post(
+ f"/api/cases/{cid}/entities",
+ content='{"type":"place","label":"Quay 4","attrs":{"radius_m":Infinity}}',
+ headers={"content-type": "application/json"},
+ )
+
+ assert res.status_code == 400, res.text
+
+
+def test_the_rungs_are_served_with_the_field(client):
+ """Metres are the right thing to store and the wrong thing to ask for, so the
+ ladder ships with the registry — one source for the picker and the validator."""
+ rows = {row["type"]: row for row in client.get("/api/cases/entity-types").json()}
+ radius = next(a for a in rows["place"]["attrs"] if a["key"] == "radius_m")
+
+ assert [rung["value"] for rung in radius["rungs"]] == [25, 100, 500, 2000, 10000]
+ assert radius["minimum"] == 1
+ assert radius["maximum"] == entities.MAX_RADIUS_M
+ # every rung is a value the API would accept
+ for rung in radius["rungs"]:
+ assert radius["minimum"] <= rung["value"] <= radius["maximum"]
+
+
+def test_the_ladder_is_not_derived_from_plus_code_lengths():
+ """Why the rungs are the input rather than the output: valid Plus Code lengths
+ jump from 8 (~280 m cells) straight to 6 (~5.6 km), and 300 m to 5 km is exactly
+ the band a live geolocation lives in. Two rungs sit inside that hole."""
+ values = [value for _, value in entities.PRECISION_RUNGS]
+
+ assert sorted(values) == values, "coarsest reading last"
+ assert [v for v in values if 280 < v < 5600] == [500, 2000]
+
+
+# -- the footprint ------------------------------------------------------------
+
+
+def test_a_footprint_holds_a_polygon_when_a_circle_is_the_wrong_shape(client):
+ cid = _new_case(client, "Footprint place")
+ ring = [[14.55, 53.44], [14.56, 53.44], [14.56, 53.45], [14.55, 53.44]]
+
+ res = _place(client, cid, footprint={"type": "Polygon", "coordinates": [ring]})
+
+ assert res.status_code == 200, res.text
+ assert res.json()["attrs"]["footprint"]["type"] == "Polygon"
+
+
+def test_a_footprint_must_be_an_area(client):
+ """A point is what lat/lon plus a radius already says, so a footprint that is
+ not an area carries no information the place did not have."""
+ cid = _new_case(client, "Not an area")
+
+ assert _place(
+ client, cid, footprint={"type": "Point", "coordinates": [14.55, 53.44]}
+ ).status_code == 400
+ assert _place(
+ client, cid,
+ footprint={"type": "LineString", "coordinates": [[14.55, 53.44], [14.56, 53.45]]},
+ ).status_code == 400
+ assert _place(
+ client, cid, footprint={"type": "Polygon", "coordinates": [[[14.55, 53.44]]]}
+ ).status_code == 400
+
+
+def test_a_footprint_is_refused_off_the_globe_or_malformed(client):
+ cid = _new_case(client, "Bad footprint")
+
+ def post(footprint):
+ return _place(client, cid, footprint=footprint).status_code
+
+ assert post("POLYGON((0 0))") == 400
+ assert post({"type": "Polygon"}) == 400
+ assert post({"type": "Polygon", "coordinates": []}) == 400
+ # lon then lat, and both on the globe
+ assert post({"type": "Polygon", "coordinates": [[[200, 0], [1, 1], [2, 2], [200, 0]]]}) == 400
+ assert post({"type": "Polygon", "coordinates": [[[0, 91], [1, 1], [2, 2], [0, 91]]]}) == 400
+ assert post({"type": "Polygon", "coordinates": [[[0], [1, 1], [2, 2], [0]]]}) == 400
+
+
+def test_a_footprint_is_bounded_in_size_and_depth(client):
+ """Validate at the edge: past a few thousand vertices this is a payload rather
+ than a shape, and nesting must not be a way around the count."""
+ cid = _new_case(client, "Huge footprint")
+ huge = [[0.001 * i, 0.001 * i] for i in range(entities.MAX_FOOTPRINT_POINTS + 2)]
+
+ assert _place(client, cid, footprint={"type": "Polygon", "coordinates": [huge]}).status_code == 400
+
+ deep = {"type": "Polygon", "coordinates": [[[[[[[0, 0]]]]]]]}
+ assert _place(client, cid, footprint=deep).status_code == 400
+
+
+# -- what validation does and does not reach ----------------------------------
+
+
+def test_a_tools_own_keys_are_never_judged():
+ """Only declared fields are checked. `notes`, `geo`, `plus_code` and the rest
+ belong to the save that made the point, so this stays additive: no write that
+ worked yesterday can start failing."""
+ entities.check_attrs("place", {"notes": 42, "geo": {"state": "ok"}, "zoom": "seventeen"})
+
+
+def test_an_undeclared_type_is_not_judged_either():
+ entities.check_attrs("cuneiform-tablet", {"radius_m": 0})
+
+
+def test_a_declared_url_must_be_http(client):
+ """A declared url is rendered as a link, so the scheme is checked at the edge
+ rather than trusted."""
+ cid = _new_case(client, "Account url")
+
+ def account(url):
+ return client.post(
+ f"/api/cases/{cid}/entities",
+ json={"type": "account", "label": "@x", "attrs": {"url": url}},
+ ).status_code
+
+ assert account("https://example.org/x") == 200
+ assert account("javascript:alert(1)") == 400
+ assert account("ftp://example.org/x") == 400
+
+
+def test_the_engine_raises_rather_than_returning_a_verdict():
+ with pytest.raises(CaseError, match="at least 1"):
+ entities.check_attrs("place", {"radius_m": 0})
+
+
+def test_every_editor_kind_is_used_by_some_field():
+ """A kind nothing declares is an editor no screen can reach. `date` is absent on
+ purpose until the claim node's EDTF needs it."""
+ used = {attr.kind for entry in entities.ENTITY_TYPES for attr in entry.attrs}
+
+ assert used == set(entities.ATTR_KINDS)
+
+
+# -- the update path ----------------------------------------------------------
+
+
+def test_precision_can_be_added_to_a_place_that_already_exists(client):
+ """The real workflow: a point is saved precisely, then the analyst admits it is
+ a guess. A partial patch must not disturb the geometry the tool wrote."""
+ cid = _new_case(client, "Later admission")
+ eid = _place(client, cid).json()["id"]
+
+ res = _patch(client, cid, eid, {"radius_m": 2000, "method": "caption only"})
+
+ assert res.status_code == 200, res.text
+ attrs = Case.open(cid).get_entity(eid)["attrs"]
+ assert attrs["radius_m"] == 2000
+ assert attrs["lat"] == 53.44 and attrs["lon"] == 14.55
+
+
+def test_a_bad_patch_is_a_bad_request_not_a_missing_entity(client):
+ cid = _new_case(client, "Bad patch")
+ eid = _place(client, cid).json()["id"]
+
+ assert _patch(client, cid, eid, {"radius_m": 0}).status_code == 400
+ assert _patch(client, cid, "e_ghost", {"radius_m": 100}).status_code == 404
+
+
+# -- reaching the map ---------------------------------------------------------
+
+
+def test_the_saved_index_carries_the_precision_to_the_map(client):
+ """The point of storing it: the overlay draws the circle, and it reads the saved
+ index rather than fetching each place. So precision that never reaches this row
+ is precision no analyst ever sees."""
+ cid = _new_case(client, "Index precision")
+ eid = _place(client, cid).json()["id"]
+ _patch(client, cid, eid, {"radius_m": 2000})
+
+ row = next(
+ r for r in client.get(f"/api/cases/{cid}/satellite/index").json() if r["id"] == eid
+ )
+
+ assert row["radius_m"] == 2000
+ assert row["footprint"] is None
+
+
+def test_a_footprint_reaches_the_index_whole(client):
+ """A traced shape says more than the circle around it, so the overlay gets the
+ geometry itself and not a bounding radius computed here."""
+ cid = _new_case(client, "Index footprint")
+ ring = [[14.55, 53.44], [14.56, 53.44], [14.56, 53.45], [14.55, 53.44]]
+ eid = _place(client, cid, footprint={"type": "Polygon", "coordinates": [ring]}).json()["id"]
+
+ row = next(
+ r for r in client.get(f"/api/cases/{cid}/satellite/index").json() if r["id"] == eid
+ )
+
+ assert row["footprint"] == {"type": "Polygon", "coordinates": [ring]}
+
+
+def test_a_place_with_no_precision_states_none_in_the_index(client):
+ """Absent is a state and travels as one: the overlay draws a plain pin for it,
+ which is how every place saved before this feature must keep rendering."""
+ cid = _new_case(client, "Index plain")
+ eid = _place(client, cid).json()["id"]
+
+ row = next(
+ r for r in client.get(f"/api/cases/{cid}/satellite/index").json() if r["id"] == eid
+ )
+
+ assert row["radius_m"] is None and row["footprint"] is None
diff --git a/tests/test_placement.py b/tests/test_placement.py
new file mode 100644
index 0000000..6efee01
--- /dev/null
+++ b/tests/test_placement.py
@@ -0,0 +1,312 @@
+"""Placement: where the derivation chain puts an entity (ONTOLOGY §3).
+
+The chain is read backwards as geography, and the artifact holding the point is
+rarely the one being read. A proof stands at the point of the capture it composes,
+one hop back — and a video reaches that same capture three hops away, through the
+proof that sat a frame of it beside the satellite view. That V is the geolocation
+gesture: putting a frame next to a capture *is* the assertion they are one place.
+
+What must hold: the point is found however far round the V it sits, the nearest
+artifact is the one credited, what the analyst typed beats what the panels froze,
+and nothing about this walks a relation or invents a point.
+"""
+
+import base64
+import io
+
+from PIL import Image
+import pytest
+
+from azimut.engine import media as media_engine
+from azimut.engine import satellite as satellite_engine
+from azimut.workspace import Case
+
+import graph_read
+
+
+def _png_bytes(color=(200, 30, 30), size=(64, 48)) -> bytes:
+ buf = io.BytesIO()
+ Image.new("RGB", size, color).save(buf, "PNG")
+ return buf.getvalue()
+
+
+def _png_b64() -> str:
+ return base64.b64encode(_png_bytes((10, 10, 10))).decode()
+
+
+def sat_tiles(monkeypatch):
+ """Captures without the network: every tile is a solid green square."""
+ from azimut.engine import tiles
+
+ monkeypatch.setattr(
+ tiles, "_default_fetch", lambda client, url: Image.new("RGB", (256, 256), (10, 120, 10))
+ )
+
+
+def _new_case(client, name="Placement"):
+ return client.post("/api/cases", json={"name": name}).json()["id"]
+
+
+def _upload(client, cid, name, color=(200, 30, 30)):
+ """A file collected into the case — the stand-in for a downloaded video."""
+ return client.post(
+ f"/api/cases/{cid}/media/upload",
+ files={"file": (name, io.BytesIO(_png_bytes(color)), "image/png")},
+ ).json()["item"]["path"]
+
+
+def _frame_of(cid, source_path, name="frame.png", color=(90, 90, 90)):
+ """A frame filed the way Inspect files one: the sidecar names what it was cut
+ from, and the link layer turns that path into the `derived-from` edge."""
+ return media_engine.import_image(
+ Case.open(cid),
+ Image.new("RGB", (32, 24), color),
+ name,
+ {"type": "inspect", "from": source_path},
+ by="inspect",
+ dedupe=False,
+ )["item"]["path"]
+
+
+def _sat(client, cid, lat, lon):
+ """A saved capture — the only collected type that records a point."""
+ return client.post(
+ f"/api/cases/{cid}/satellite/capture",
+ json={"lat": lat, "lon": lon, "zoom": 16, "width": 256, "height": 256},
+ ).json()["path"]
+
+
+def _save_proof(client, cid, title, srcs, **spec_extra):
+ spec = {"panels": [{"id": f"p{i}", "src": s} for i, s in enumerate(srcs)], **spec_extra}
+ return client.post(
+ f"/api/cases/{cid}/proofs",
+ json={"title": title, "spec": spec, "png_base64": _png_b64()},
+ ).json()
+
+
+def _id(cid, **attrs):
+ found = graph_read.entity(cid, **attrs)
+ assert found is not None, f"no entity with {attrs}"
+ return found["id"]
+
+
+def _placement(client, cid, entity_id):
+ res = client.get(f"/api/cases/{cid}/entities/{entity_id}/placement")
+ assert res.status_code == 200, res.text
+ return res.json()
+
+
+def _points(client, cid, entity_id):
+ return [(p["lat"], p["lon"]) for p in _placement(client, cid, entity_id)["points"]]
+
+
+# ── the one hop the map already reads ───────────────────────────────────────
+
+
+def test_a_proof_is_placed_at_the_capture_it_composes(client, sat_tiles):
+ cid = _new_case(client)
+ cap = _sat(client, cid, 50.4501, 30.5234)
+ _save_proof(client, cid, "Kyiv bridge", [cap])
+
+ found = _placement(client, cid, _id(cid, spec="proofs/.meta/Kyiv bridge.json"))
+ assert [(p["lat"], p["lon"]) for p in found["points"]] == [(50.4501, 30.5234)]
+ # the row names what carries the point, because nothing else in the panel does
+ assert found["points"][0]["via"]["type"] == "capture"
+ assert found["points"][0]["depth"] == 1
+ assert found["truncated"] is False
+
+
+def test_a_proof_states_its_own_point_over_the_one_its_panels_give(client, sat_tiles):
+ """What the analyst typed wins, it is credited to nobody — nothing placed it —
+ and the overridden panel is not listed underneath. A proof that says where it is
+ says it once, which is what the map already does with the same precedence."""
+ cid = _new_case(client)
+ cap = _sat(client, cid, 50.4501, 30.5234)
+ _save_proof(client, cid, "Corrected", [cap], coordsText="48.8584, 2.2945")
+
+ found = _placement(client, cid, _id(cid, spec="proofs/.meta/Corrected.json"))
+ assert [(p["lat"], p["lon"]) for p in found["points"]] == [(48.8584, 2.2945)]
+ assert found["points"][0]["via"] is None
+ assert found["points"][0]["depth"] == 0
+
+
+def test_a_capture_reports_nothing(client, sat_tiles):
+ """Its point is its own, written at the save and already read under Info. Listing
+ it here would show one datum twice in one panel, for the one type that never
+ derived it from anything."""
+ cid = _new_case(client)
+ cap = _sat(client, cid, 50.4501, 30.5234)
+
+ assert _placement(client, cid, _id(cid, path=cap)) == {"points": [], "truncated": False}
+
+
+# ── the V: what the panel could not show before ─────────────────────────────
+
+
+def test_a_video_is_placed_through_the_proof_that_used_its_frame(client, sat_tiles):
+ """video ◀ frame ◀ proof ▶ capture. Nothing joins the video to the capture, and
+ that is the whole point: they share a descendant, and sharing it is the claim."""
+ cid = _new_case(client)
+ video = _upload(client, cid, "clip.png")
+ frame = _frame_of(cid, video)
+ cap = _sat(client, cid, 50.4501, 30.5234)
+ # the composer freezes the panels' point into the spec, so the proof itself
+ # carries one — which is what makes it, not the capture, the nearest placement
+ _save_proof(client, cid, "Roofline", [frame, cap], coords={"lat": 50.4501, "lon": 30.5234})
+
+ found = _placement(client, cid, _id(cid, path=video))
+ assert [(p["lat"], p["lon"]) for p in found["points"]] == [(50.4501, 30.5234)]
+ assert found["points"][0]["via"]["type"] == "proof"
+ assert found["points"][0]["via"]["label"] == "Roofline"
+ assert found["points"][0]["depth"] == 2
+
+
+def test_a_video_reaches_the_capture_when_the_proof_states_no_point(client, sat_tiles):
+ """A proof saved with no frozen coordinates places nothing itself, so the walk
+ carries on to the capture and credits that instead. The row is still true — it
+ just names a different artifact."""
+ cid = _new_case(client)
+ video = _upload(client, cid, "clip.png")
+ frame = _frame_of(cid, video)
+ cap = _sat(client, cid, 50.4501, 30.5234)
+ _save_proof(client, cid, "Roofline", [frame, cap])
+
+ found = _placement(client, cid, _id(cid, path=video))
+ assert [(p["lat"], p["lon"]) for p in found["points"]] == [(50.4501, 30.5234)]
+ assert found["points"][0]["via"]["type"] == "capture"
+ assert found["points"][0]["depth"] == 3
+
+
+def test_an_inspect_session_is_placed_through_the_media_it_points_at(client, sat_tiles):
+ """`depends-on` is walked too: a session is a pointer at a file, and the file's
+ own placement is the session's."""
+ cid = _new_case(client)
+ video = _upload(client, cid, "clip.png")
+ frame = _frame_of(cid, video)
+ cap = _sat(client, cid, 50.4501, 30.5234)
+ _save_proof(client, cid, "Roofline", [frame, cap], coords={"lat": 50.4501, "lon": 30.5234})
+ client.post(
+ f"/api/cases/{cid}/inspect/sessions",
+ json={"title": "Pass", "spec": {"source": {"path": video, "kind": "image"}}},
+ )
+
+ assert _points(client, cid, _id(cid, spec=".inspect/Pass.json")) == [(50.4501, 30.5234)]
+
+
+# ── what the list refuses to do ─────────────────────────────────────────────
+
+
+def test_two_captures_of_one_roof_stay_two_points(client, sat_tiles):
+ """Metres apart is not the same point. Merging them would assert they are one
+ place, which is the analyst's call and not a rounding this may make."""
+ cid = _new_case(client)
+ a = _sat(client, cid, 50.45010, 30.52340)
+ b = _sat(client, cid, 50.45012, 30.52341)
+ _save_proof(client, cid, "Two views", [a, b])
+
+ assert len(_points(client, cid, _id(cid, spec="proofs/.meta/Two views.json"))) == 2
+
+
+def test_one_point_reached_twice_is_listed_once(client, sat_tiles):
+ """Two panels cropped from one capture are one point, and it comes back once."""
+ cid = _new_case(client)
+ cap = _sat(client, cid, 50.4501, 30.5234)
+ frame = _frame_of(cid, cap, "crop.png")
+ _save_proof(client, cid, "Same roof", [cap, frame])
+
+ assert _points(client, cid, _id(cid, spec="proofs/.meta/Same roof.json")) == [
+ (50.4501, 30.5234)
+ ]
+
+
+def test_the_walk_stops_at_the_artifact_holding_the_point(client, sat_tiles):
+ """A second proof reusing the same capture is somebody else's argument, not this
+ video's, so the walk does not carry on through the capture to collect it."""
+ cid = _new_case(client)
+ video = _upload(client, cid, "clip.png")
+ frame = _frame_of(cid, video)
+ shared = _sat(client, cid, 50.4501, 30.5234)
+ elsewhere = _sat(client, cid, 48.8584, 2.2945)
+ _save_proof(client, cid, "Mine", [frame, shared])
+ _save_proof(client, cid, "Somebody else's", [shared, elsewhere])
+
+ # the shared capture is reached and reported; what hangs off its far side is not
+ assert _points(client, cid, _id(cid, path=video)) == [(50.4501, 30.5234)]
+
+
+def test_a_relation_never_places_anything(client, sat_tiles):
+ """Only chain edges are geography. A stated relation is a claim about the world,
+ and walking one here would let an opinion place a file."""
+ cid = _new_case(client)
+ video = _upload(client, cid, "clip.png")
+ cap = _sat(client, cid, 50.4501, 30.5234)
+ case = Case.open(cid)
+ place = satellite_engine.save_place(case, 50.4501, 30.5234, title="Roof")
+ case.add_link(_id(cid, path=video), place["id"], "depicts", by="user")
+
+ assert _points(client, cid, _id(cid, path=video)) == []
+ assert _points(client, cid, _id(cid, path=cap)) == []
+
+
+def test_an_unlocated_chain_reports_no_point(client):
+ cid = _new_case(client)
+ photo = _upload(client, cid, "a.png")
+ _save_proof(client, cid, "Photos only", [photo])
+
+ assert _points(client, cid, _id(cid, path=photo)) == []
+
+
+def test_a_missing_entity_is_a_404(client):
+ cid = _new_case(client)
+ assert client.get(f"/api/cases/{cid}/entities/e_nope/placement").status_code == 404
+
+
+# ── bounds ──────────────────────────────────────────────────────────────────
+
+
+def test_the_list_is_capped_and_says_so(client, sat_tiles, monkeypatch):
+ """Past the cap the panel is a wall rather than a reading, so it stops and
+ reports that it stopped instead of trailing off in silence."""
+ monkeypatch.setattr(satellite_engine, "PLACEMENT_LIMIT", 3)
+ cid = _new_case(client)
+ caps = [_sat(client, cid, 50.0 + i / 100, 30.0) for i in range(5)]
+ _save_proof(client, cid, "Many", caps)
+
+ found = _placement(client, cid, _id(cid, spec="proofs/.meta/Many.json"))
+ assert len(found["points"]) == 3
+ assert found["truncated"] is True
+
+
+def test_the_walk_stops_before_the_far_side_of_a_long_chain(client, sat_tiles, monkeypatch):
+ """A bound that only capped the output would still read the whole graph to fill
+ it. This one stops the walk itself."""
+ monkeypatch.setattr(satellite_engine, "PLACEMENT_DEPTH", 1)
+ cid = _new_case(client)
+ video = _upload(client, cid, "clip.png")
+ frame = _frame_of(cid, video)
+ cap = _sat(client, cid, 50.4501, 30.5234)
+ _save_proof(client, cid, "Roofline", [frame, cap])
+
+ # the frame is one hop from the video; the proof and its capture are further
+ assert _points(client, cid, _id(cid, path=video)) == []
+ assert _points(client, cid, _id(cid, path=frame)) == []
+
+
+# ── outputs outlive their sources ───────────────────────────────────────────
+
+
+def test_a_deleted_capture_leaves_the_proof_its_frozen_point(client, sat_tiles):
+ """`derived-from` never cascades, and the spec keeps the coordinates the panels
+ gave it — so the proof stays placed, and so does the video behind it."""
+ cid = _new_case(client)
+ video = _upload(client, cid, "clip.png")
+ frame = _frame_of(cid, video)
+ cap = _sat(client, cid, 50.4501, 30.5234)
+ _save_proof(client, cid, "Roofline", [frame, cap], coords={"lat": 50.4501, "lon": 30.5234})
+
+ client.delete(f"/api/cases/{cid}/entities/{_id(cid, path=cap)}")
+
+ proof_id = _id(cid, spec="proofs/.meta/Roofline.json")
+ assert _points(client, cid, proof_id) == [(50.4501, 30.5234)]
+ assert _points(client, cid, _id(cid, path=video)) == [(50.4501, 30.5234)]
diff --git a/tests/test_proofs_api.py b/tests/test_proofs_api.py
index 6dfa19f..8ae916a 100644
--- a/tests/test_proofs_api.py
+++ b/tests/test_proofs_api.py
@@ -8,6 +8,7 @@ import io
import pytest
from PIL import Image
from azimut import layout
+from azimut.workspace import Case
def _png_b64() -> str:
@@ -245,6 +246,18 @@ def test_save_produces_a_thumbnail_of_the_export(client):
# the listing hands it to the open dialog, so the row never loads the export
assert client.get(f"/api/cases/{cid}/proofs").json()[0]["thumb"] == saved["thumb"]
+ # and the entity carries it too, so a surface drawing a few hundred entities at
+ # once — the graph — reads a preview off the row it already has instead of
+ # opening one spec file per proof
+ entity = case.find_entity(attr="spec", value=saved["spec_path"])
+ assert entity["attrs"]["thumb"] == saved["thumb"]
+ node = next(
+ row
+ for row in client.get(f"/api/cases/{cid}/graph").json()["nodes"]
+ if row["id"] == entity["id"]
+ )
+ assert node["thumb"] == saved["thumb"]
+
def test_listing_backfills_a_proof_saved_before_thumbnails(client):
import json
@@ -273,6 +286,40 @@ def test_listing_backfills_a_proof_saved_before_thumbnails(client):
assert json.loads(spec_path.read_text(encoding="utf-8"))["thumb"] == saved["thumb"]
+def test_the_graph_adopts_a_thumbnail_a_proof_only_recorded_in_its_spec(client):
+ """The migration has to cover the ordinary proof, not only the broken one.
+
+ A proof saved before the entity recorded a thumbnail still has a perfectly good
+ one in its spec, so nothing about it needs repairing — and it would draw as a
+ glyph forever if the only thing that copied the path across were the repair of a
+ missing thumbnail. The graph adopts it on the first view, then reads the row."""
+ from azimut.api.cases import get_case
+
+ cid = client.post("/api/cases", json={"name": "Proofs"}).json()["id"]
+ saved = client.post(
+ f"/api/cases/{cid}/proofs",
+ json={"title": "Older proof", "spec": SPEC, "png_base64": _big_png_b64()},
+ ).json()
+ case = get_case(cid)
+ entity = case.find_entity(attr="spec", value=saved["spec_path"])
+ # what an older save left behind: the spec knows its thumbnail, the entity does not
+ case.update_entity(entity["id"], {"attrs": {"thumb": ""}})
+
+ node = next(
+ row
+ for row in client.get(f"/api/cases/{cid}/graph").json()["nodes"]
+ if row["id"] == entity["id"]
+ )
+ assert node["thumb"] == saved["thumb"]
+ # recorded on the entity, so no later view opens the spec file again
+ assert case.get_entity(entity["id"])["attrs"]["thumb"] == saved["thumb"]
+
+ hood = client.get(
+ f"/api/cases/{cid}/graph/neighborhood", params={"root": entity["id"]}
+ ).json()
+ assert hood["nodes"][0]["thumb"] == saved["thumb"]
+
+
def test_listing_falls_back_to_the_export_when_no_thumbnail_can_be_made(client):
from azimut.api.cases import get_case
@@ -532,3 +579,377 @@ def test_index_carries_the_my_work_folder_of_the_proof(client, sat_tiles):
client.patch(f"/api/cases/{cid}/entities/{entity['id']}", json={"attrs": {"folder": "recon/bridges"}})
assert _proof_index(client, cid)[0]["folder"] == "recon/bridges"
+
+
+# -- the place a proof files (engine/satellite.place_for_proof) -----------------
+#
+# A geolocation is concluded in the composer, so the point becomes a node here
+# rather than on every capture taken while looking for it.
+
+
+def _depicts(cid):
+ return graph_read.links(cid, "depicts")
+
+
+def _places(cid):
+ return [e for e in graph_read.entities(cid) if e["type"] == "place"]
+
+
+def _save(client, cid, title, spec):
+ return client.post(f"/api/cases/{cid}/proofs", json={"title": title, "spec": spec}).json()
+
+
+def _with_coords(text=None, point=None, *srcs, pov=False):
+ spec = _panels(*srcs)
+ if text is not None:
+ spec["coordsText"] = text
+ if point is not None:
+ spec["coords"] = point
+ if pov:
+ spec["pov"] = True
+ return spec
+
+
+def _located_at(cid):
+ return graph_read.links(cid, "located-at")
+
+
+def test_saving_a_proof_files_the_point_it_carries(client):
+ cid = client.post("/api/cases", json={"name": "Proofs"}).json()["id"]
+ saved = _save(client, cid, "Roof match", _with_coords("50.4501, 30.5234"))
+
+ places = _places(cid)
+ assert len(places) == 1
+ assert (places[0]["attrs"]["lat"], places[0]["attrs"]["lon"]) == (50.4501, 30.5234)
+ # the analyst's own answer, so there is nothing left to review
+ assert places[0]["provenance"]["status"] == "confirmed"
+ assert saved["place"] == {"filed": True, "id": places[0]["id"], "label": places[0]["label"]}
+
+ # and the proof says it shows that place
+ edges = _depicts(cid)
+ assert len(edges) == 1
+ assert edges[0]["to"] == places[0]["id"]
+ assert edges[0]["provenance"]["status"] == "confirmed"
+
+
+def test_a_proof_with_no_point_files_nothing(client):
+ cid = client.post("/api/cases", json={"name": "Proofs"}).json()["id"]
+ assert _save(client, cid, "No point", _panels("media/frame.png"))["place"] is None
+ assert _places(cid) == []
+
+
+def test_the_typed_point_wins_over_the_one_the_panels_gave(client):
+ cid = client.post("/api/cases", json={"name": "Proofs"}).json()["id"]
+ _save(client, cid, "Corrected", _with_coords("50.4501, 30.5234", {"lat": 1.0, "lon": 2.0}))
+ # the composer's field is the analyst's correction; the frozen panel point loses
+ assert [(p["attrs"]["lat"], p["attrs"]["lon"]) for p in _places(cid)] == [(50.4501, 30.5234)]
+
+
+def test_a_point_the_case_already_holds_is_neither_filed_twice_nor_asked_about(client):
+ cid = client.post("/api/cases", json={"name": "Proofs"}).json()["id"]
+ client.post(
+ f"/api/cases/{cid}/satellite/place", json={"lat": 50.4501, "lon": 30.5234}
+ )
+ saved = _save(client, cid, "Same point", _with_coords("50.4501, 30.5234"))
+
+ assert saved["place"] is None # nothing to file, so nothing to ask
+ assert len(_places(cid)) == 1
+ # the pin was already there, so it is reused rather than minted again — but the
+ # proof still says it concludes there, or the point it states would be unreadable
+ assert [lk["to"] for lk in _depicts(cid)] == [_places(cid)[0]["id"]]
+
+
+def test_resaving_a_proof_stays_silent(client):
+ cid = client.post("/api/cases", json={"name": "Proofs"}).json()["id"]
+ spec = _with_coords("50.4501, 30.5234")
+ assert _save(client, cid, "Roof match", spec)["place"]["filed"] is True
+ # the point is in the case now: saving again must not ask, nor pin it twice
+ assert _save(client, cid, "Roof match", spec)["place"] is None
+ assert len(_places(cid)) == 1
+
+
+def test_the_composer_is_asked_when_the_setting_is_off(client):
+ client.put("/api/settings/prefs", json={"proof_place_auto": False})
+ cid = client.post("/api/cases", json={"name": "Proofs"}).json()["id"]
+ saved = _save(client, cid, "Roof match", _with_coords("50.4501, 30.5234"))
+
+ assert saved["place"] == {
+ "filed": False, "lat": 50.4501, "lon": 30.5234, "pov": False
+ }
+ assert _places(cid) == [] # nothing is written until the analyst says yes
+
+ filed = client.post(
+ f"/api/cases/{cid}/proofs/Roof match/place",
+ json={"lat": 50.4501, "lon": 30.5234},
+ ).json()
+ assert filed["type"] == "place"
+ assert _depicts(cid)[0]["from"] == graph_read.entity(cid, spec=layout.proof_spec_rel("Roof match"))["id"]
+
+
+def test_answering_twice_files_one_place(client):
+ """Two tabs answering the same question must not pin the point twice."""
+ client.put("/api/settings/prefs", json={"proof_place_auto": False})
+ cid = client.post("/api/cases", json={"name": "Proofs"}).json()["id"]
+ _save(client, cid, "Roof match", _with_coords("50.4501, 30.5234"))
+
+ body = {"lat": 50.4501, "lon": 30.5234}
+ first = client.post(f"/api/cases/{cid}/proofs/Roof match/place", json=body).json()
+ second = client.post(f"/api/cases/{cid}/proofs/Roof match/place", json=body).json()
+ assert first["id"] == second["id"]
+ assert len(_places(cid)) == 1
+
+
+def test_the_material_the_proof_composes_states_the_same_point(client, sat_tiles):
+ """The video the proof was built from says it too, and says it confirmed.
+
+ Putting a frame beside a capture and writing the coordinates *is* the
+ geolocation, so there is nothing left to review: asking the analyst to accept
+ their own act is the click that teaches people to click through the ones that
+ matter.
+ """
+ cid = client.post("/api/cases", json={"name": "Proofs"}).json()["id"]
+ case = Case.open(cid)
+ video = case.add_entity(
+ "media", "clip.mp4", {"path": "media/clip.mp4", "kind": "video"}, by="user"
+ )
+ frame = case.add_entity(
+ "media", "frame.png", {"path": "media/frame.png", "kind": "image"}, by="user"
+ )
+ case.add_link(frame["id"], video["id"], "derived-from", by="inspect")
+ cap = _sat(client, cid, 50.4501, 30.5234)
+
+ _save(client, cid, "Roof match", _with_coords(
+ "50.4501, 30.5234", None, "media/frame.png", cap["path"]
+ ))
+
+ place = _places(cid)[0]
+ stated = {
+ lk["from"]: lk["provenance"]["status"]
+ for lk in _depicts(cid)
+ if lk["to"] == place["id"]
+ }
+ # the frame, the capture, and the video two hops up
+ assert stated[frame["id"]] == "confirmed"
+ assert stated[video["id"]] == "confirmed"
+ assert stated[graph_read.entity(cid, path=cap["path"])["id"]] == "confirmed"
+
+
+def test_a_source_the_verb_does_not_accept_is_skipped(client):
+ cid = client.post("/api/cases", json={"name": "Proofs"}).json()["id"]
+ case = Case.open(cid)
+ audio = case.add_entity(
+ "media", "call.mp3", {"path": "media/call.mp3", "kind": "audio"}, by="user"
+ )
+ case.add_entity("media", "frame.png", {"path": "media/frame.png", "kind": "image"}, by="user")
+ _save(client, cid, "Roof match", _with_coords(
+ "50.4501, 30.5234", None, "media/frame.png", "media/call.mp3"
+ ))
+
+ # `shows` is about pixels: an audio file in the chain is skipped, not refused
+ assert audio["id"] not in {lk["from"] for lk in _depicts(cid)}
+
+
+def test_pov_says_the_footage_was_recorded_there(client, sat_tiles):
+ """The one thing a composition cannot deduce, so the composer asks it.
+
+ Recorded-at and shows are independent claims — a rooftop shot is recorded
+ somewhere it never shows — and a match between a frame and an imagery says
+ only that they meet, not whether the camera or its subject was located.
+ """
+ cid = client.post("/api/cases", json={"name": "Proofs"}).json()["id"]
+ case = Case.open(cid)
+ video = case.add_entity(
+ "media", "clip.mp4", {"path": "media/clip.mp4", "kind": "video"}, by="user"
+ )
+ cap = _sat(client, cid, 50.4501, 30.5234)
+
+ _save(client, cid, "From the roof", _with_coords(
+ "50.4501, 30.5234", None, "media/clip.mp4", cap["path"], pov=True
+ ))
+
+ place = _places(cid)[0]
+ assert [lk["from"] for lk in _located_at(cid)] == [video["id"]]
+ # the capture is orbital imagery and the proof was composed: neither was
+ # recorded anywhere, so both keep saying they show the place
+ shows = {lk["from"] for lk in _depicts(cid) if lk["to"] == place["id"]}
+ assert graph_read.entity(cid, path=cap["path"])["id"] in shows
+ assert video["id"] not in shows
+
+
+def test_without_pov_the_footage_only_shows_the_place(client):
+ cid = client.post("/api/cases", json={"name": "Proofs"}).json()["id"]
+ case = Case.open(cid)
+ video = case.add_entity(
+ "media", "clip.mp4", {"path": "media/clip.mp4", "kind": "video"}, by="user"
+ )
+ _save(client, cid, "Skyline", _with_coords("50.4501, 30.5234", None, "media/clip.mp4"))
+
+ assert _located_at(cid) == []
+ assert [lk["from"] for lk in _depicts(cid) if lk["from"] == video["id"]] == [video["id"]]
+
+
+def test_pov_reaches_a_recording_the_other_verb_refuses(client):
+ cid = client.post("/api/cases", json={"name": "Proofs"}).json()["id"]
+ case = Case.open(cid)
+ audio = case.add_entity(
+ "media", "call.mp3", {"path": "media/call.mp3", "kind": "audio"}, by="user"
+ )
+ _save(client, cid, "Where it was taped", _with_coords(
+ "50.4501, 30.5234", None, "media/call.mp3", pov=True
+ ))
+ # a recording has a place it was made, though it shows nothing
+ assert [lk["from"] for lk in _located_at(cid)] == [audio["id"]]
+
+
+def test_the_answer_to_the_question_reads_pov_off_the_saved_proof(client):
+ client.put("/api/settings/prefs", json={"proof_place_auto": False})
+ cid = client.post("/api/cases", json={"name": "Proofs"}).json()["id"]
+ case = Case.open(cid)
+ video = case.add_entity(
+ "media", "clip.mp4", {"path": "media/clip.mp4", "kind": "video"}, by="user"
+ )
+ saved = _save(client, cid, "From the roof", _with_coords(
+ "50.4501, 30.5234", None, "media/clip.mp4", pov=True
+ ))
+ assert saved["place"]["pov"] is True # so the question can say what it means
+
+ client.post(
+ f"/api/cases/{cid}/proofs/From the roof/place",
+ json={"lat": 50.4501, "lon": 30.5234},
+ )
+ # POV is a property of the proof, not of the answer: the body never carries it
+ assert [lk["from"] for lk in _located_at(cid)] == [video["id"]]
+
+
+# -- re-saving restates the point (engine/satellite.restate_proof_point) --------
+#
+# A proof states one point, and a save is the restatement of it — the rule its
+# panels already follow. Correcting the coordinates moves the edges rather than
+# leaving the case holding two answers, and POV changes the verb it wrote before.
+
+
+def _proof(cid):
+ return [e for e in graph_read.entities(cid) if e["type"] == "proof"][0]
+
+
+def _video(cid, name="clip.mp4"):
+ return Case.open(cid).add_entity(
+ "media", name, {"path": f"media/{name}", "kind": "video"}, by="user"
+ )
+
+
+def _place_by_lat(cid, lat):
+ return [p for p in _places(cid) if p["attrs"]["lat"] == lat][0]
+
+
+def test_correcting_the_coordinates_moves_the_point_instead_of_adding_one(client):
+ cid = client.post("/api/cases", json={"name": "Proofs"}).json()["id"]
+ video = _video(cid)
+ _save(client, cid, "Roof match", _with_coords("50.4501, 30.5234", None, "media/clip.mp4"))
+ _save(client, cid, "Roof match", _with_coords("48.8584, 2.2945", None, "media/clip.mp4"))
+
+ # the proof and the footage state the corrected point, and only it: a
+ # withdrawn answer is not a second geolocation
+ corrected = _place_by_lat(cid, 48.8584)
+ assert {lk["to"] for lk in _depicts(cid)} == {corrected["id"]}
+ assert {lk["from"] for lk in _depicts(cid)} == {_proof(cid)["id"], video["id"]}
+
+
+def test_the_point_it_moved_off_is_offered_for_deletion(client):
+ cid = client.post("/api/cases", json={"name": "Proofs"}).json()["id"]
+ _save(client, cid, "Roof match", _with_coords("50.4501, 30.5234"))
+ abandoned = _places(cid)[0]
+
+ saved = _save(client, cid, "Roof match", _with_coords("48.8584, 2.2945"))
+
+ # a point nobody points at is the analyst's leftover to keep or drop: the save
+ # names it and stops there rather than sweeping it
+ assert saved["orphans"] == [{"id": abandoned["id"], "label": abandoned["label"]}]
+ assert abandoned["id"] in {p["id"] for p in _places(cid)}
+
+
+def test_a_point_something_else_still_holds_is_neither_stripped_nor_offered(client):
+ cid = client.post("/api/cases", json={"name": "Proofs"}).json()["id"]
+ case = Case.open(cid)
+ photo = case.add_entity(
+ "media", "roof.jpg", {"path": "media/roof.jpg", "kind": "image"}, by="user"
+ )
+ _save(client, cid, "Roof match", _with_coords("50.4501, 30.5234"))
+ stays = _places(cid)[0]
+ # the analyst's own statement about the same point, made in Details
+ case.add_link(photo["id"], stays["id"], "depicts", by="user")
+
+ saved = _save(client, cid, "Roof match", _with_coords("48.8584, 2.2945"))
+
+ assert saved["orphans"] == [] # something still holds it, so there is nothing to ask
+ # and a claim the composer did not write is not the composer's to withdraw
+ assert [lk["from"] for lk in _depicts(cid) if lk["to"] == stays["id"]] == [photo["id"]]
+
+
+def test_toggling_pov_restates_the_verb_on_the_footage(client):
+ cid = client.post("/api/cases", json={"name": "Proofs"}).json()["id"]
+ video = _video(cid)
+ _save(client, cid, "Roof match", _with_coords("50.4501, 30.5234", None, "media/clip.mp4"))
+ assert [lk["from"] for lk in _depicts(cid)] == [_proof(cid)["id"], video["id"]]
+
+ _save(client, cid, "Roof match", _with_coords(
+ "50.4501, 30.5234", None, "media/clip.mp4", pov=True
+ ))
+
+ # the point still stands and was never filed twice; what changed is what it means
+ assert len(_places(cid)) == 1
+ assert [lk["from"] for lk in _located_at(cid)] == [video["id"]]
+ # the proof itself was composed, so it shows the place either way
+ assert [lk["from"] for lk in _depicts(cid)] == [_proof(cid)["id"]]
+
+ _save(client, cid, "Roof match", _with_coords("50.4501, 30.5234", None, "media/clip.mp4"))
+ assert _located_at(cid) == [] # and the answer can be taken back
+ assert {lk["from"] for lk in _depicts(cid)} == {_proof(cid)["id"], video["id"]}
+
+
+def test_turning_pov_off_drops_the_edge_the_other_verb_refuses(client):
+ cid = client.post("/api/cases", json={"name": "Proofs"}).json()["id"]
+ case = Case.open(cid)
+ case.add_entity("media", "call.mp3", {"path": "media/call.mp3", "kind": "audio"}, by="user")
+ spec = _with_coords("50.4501, 30.5234", None, "media/call.mp3", pov=True)
+ _save(client, cid, "Where it was taped", spec)
+ assert len(_located_at(cid)) == 1
+
+ _save(client, cid, "Where it was taped", _with_coords(
+ "50.4501, 30.5234", None, "media/call.mp3"
+ ))
+
+ # a recording shows nothing, so withdrawing "recorded there" leaves it unplaced
+ assert _located_at(cid) == []
+ assert [lk["from"] for lk in _depicts(cid)] == [_proof(cid)["id"]]
+
+
+def test_clearing_the_coordinates_withdraws_the_point(client):
+ cid = client.post("/api/cases", json={"name": "Proofs"}).json()["id"]
+ _video(cid)
+ _save(client, cid, "Roof match", _with_coords("50.4501, 30.5234", None, "media/clip.mp4"))
+ filed = _places(cid)[0]
+
+ saved = _save(client, cid, "Roof match", _panels("media/clip.mp4"))
+
+ # an emptied coordinate field is an answer taken back, not the last one frozen
+ assert _depicts(cid) == []
+ assert saved["orphans"] == [{"id": filed["id"], "label": filed["label"]}]
+
+
+def test_a_point_another_proof_still_concludes_on_keeps_its_material(client):
+ cid = client.post("/api/cases", json={"name": "Proofs"}).json()["id"]
+ video = _video(cid)
+ spec = _with_coords("50.4501, 30.5234", None, "media/clip.mp4")
+ _save(client, cid, "First", spec)
+ _save(client, cid, "Second", spec)
+ shared = _places(cid)[0]
+
+ saved = _save(client, cid, "Second", _with_coords("48.8584, 2.2945", None, "media/clip.mp4"))
+
+ # the edges two proofs wrote on one video are indistinguishable, so moving one
+ # off must not undo the conclusion the other still states
+ assert saved["orphans"] == []
+ holding = {lk["from"] for lk in _depicts(cid) if lk["to"] == shared["id"]}
+ assert video["id"] in holding
+ assert graph_read.entity(cid, spec=layout.proof_spec_rel("First"))["id"] in holding
diff --git a/tests/test_relaunch.py b/tests/test_relaunch.py
index 1f7362b..94205b6 100644
--- a/tests/test_relaunch.py
+++ b/tests/test_relaunch.py
@@ -1,9 +1,13 @@
from __future__ import annotations
+import contextlib
import importlib.util
import os
+import socket
import threading
+from collections.abc import Callable, Iterator
from pathlib import Path
+from typing import Any
import pytest
@@ -15,6 +19,22 @@ relaunch = importlib.util.module_from_spec(SPEC)
SPEC.loader.exec_module(relaunch)
+def monkeypatched(module: Any, **replacements: Callable[..., Any]) -> Iterator[None]:
+ originals = {name: getattr(module, name) for name in replacements}
+ for name, replacement in replacements.items():
+ setattr(module, name, replacement)
+ try:
+ yield
+ finally:
+ for name, original in originals.items():
+ setattr(module, name, original)
+
+
+def _never_called(*_args: Any, **_kwargs: Any) -> Any:
+ raise AssertionError("this helper should not have been called")
+
+
def test_control_socket_stops_only_the_matching_launcher(tmp_path: Path):
state_path = tmp_path / "state.json"
control = relaunch._ControlServer(state_path)
@@ -41,6 +61,104 @@ def test_stale_state_is_removed_without_stopping_a_process(tmp_path: Path):
assert not state_path.exists()
[email protected](("platform", "reuses"), [("posix", True), ("nt", False)])
+def test_probe_matches_the_way_the_server_binds(platform: str, reuses: bool):
+ assert relaunch._probe_reuses_address(platform) is reuses
+
+
[email protected](os.name == "nt", reason="POSIX-only TIME-WAIT semantics")
+def test_a_closed_server_leaves_the_port_free_despite_time_wait():
+ server = socket.socket()
+ server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
+ server.bind(("127.0.0.1", 0))
+ server.listen(1)
+ port = server.getsockname()[1]
+ client = socket.socket()
+ client.connect(("127.0.0.1", port))
+ accepted, _ = server.accept()
+ # Closing the server side first parks the connection in TIME-WAIT, which
+ # refuses a plain bind for minutes after the process is gone.
+ accepted.close()
+ server.close()
+ client.close()
+
+ assert relaunch._port_is_free(port) is True
+ with monkeypatched(relaunch, _listener_pids=_never_called):
+ assert relaunch._free_port(port, timeout=2) == []
+
+
+def test_free_port_stops_the_process_holding_the_port():
+ listener = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
+ listener.bind(("127.0.0.1", 0))
+ listener.listen(1)
+ port = listener.getsockname()[1]
+ assert relaunch._port_is_free(port) is False
+
+ fake_pid = 4242
+ killed: list[tuple[int, bool]] = []
+
+ def kill(pid: int, *, force: bool) -> None:
+ killed.append((pid, force))
+ listener.close()
+
+ with monkeypatched(relaunch, _listener_pids=lambda _port: {fake_pid}, _kill_pid=kill):
+ assert relaunch._free_port(port, timeout=2) == [fake_pid]
+
+ assert killed == [(fake_pid, False)]
+ assert relaunch._port_is_free(port) is True
+
+
+def test_free_port_is_a_no_op_when_nothing_listens():
+ with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as probe:
+ probe.bind(("127.0.0.1", 0))
+ port = probe.getsockname()[1]
+
+ with monkeypatched(relaunch, _listener_pids=_never_called):
+ assert relaunch._free_port(port, timeout=2) == []
+
+
+def test_free_port_reports_an_unidentifiable_owner():
+ listener = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
+ listener.bind(("127.0.0.1", 0))
+ listener.listen(1)
+ port = listener.getsockname()[1]
+
+ try:
+ with monkeypatched(relaunch, _listener_pids=lambda _port: set()):
+ with pytest.raises(RuntimeError, match="could not be identified"):
+ relaunch._free_port(port, timeout=0.5)
+ finally:
+ listener.close()
+
+
+def test_listener_pids_parses_windows_netstat(monkeypatch: pytest.MonkeyPatch):
+ output = (
+ "\r\nActive Connections\r\n\r\n"
+ " Proto Local Address Foreign Address State PID\r\n"
+ " TCP 127.0.0.1:8477 0.0.0.0:0 LISTENING 1234\r\n"
+ " TCP 127.0.0.1:8477 127.0.0.1:5500 ESTABLISHED 9999\r\n"
+ " TCP 0.0.0.0:445 0.0.0.0:0 LISTENING 4\r\n"
+ )
+ monkeypatch.setattr(relaunch, "_command_output", lambda _command: output)
+
+ assert relaunch._listener_pids(8477, "nt") == {1234}
+
+
+def test_listener_pids_falls_back_from_lsof_to_ss(monkeypatch: pytest.MonkeyPatch):
+ ss_output = (
+ "LISTEN 0 2048 127.0.0.1:8477 0.0.0.0:* "
+ 'users:(("python3",pid=7311,fd=9))\n'
+ "LISTEN 0 4096 0.0.0.0:22 0.0.0.0:* "
+ 'users:(("sshd",pid=812,fd=3))\n'
+ )
+ outputs = {"lsof": "", "ss": ss_output}
+ monkeypatch.setattr(
+ relaunch, "_command_output", lambda command: outputs[command[0]]
+ )
+
+ assert relaunch._listener_pids(8477, "posix") == {7311}
+
+
@pytest.mark.parametrize(
("platform", "relative"),
[("posix", Path(".venv/bin/python")), ("nt", Path(".venv/Scripts/python.exe"))],
diff --git a/tests/test_release_gate.py b/tests/test_release_gate.py
index c1172ce..e8f6d23 100644
--- a/tests/test_release_gate.py
+++ b/tests/test_release_gate.py
@@ -223,7 +223,7 @@ def test_release_tooling_is_bounded_and_built_from_the_lock():
assert "uv pip install . pyinstaller" not in workflow
assert "python -m build --no-isolation" in workflow
assert "--group release" in workflow
- assert workflow.count('node-version: "20.20.2"') == 2
+ assert workflow.count('node-version: "24.19.0"') == 2
assert "--no-build-isolation" in workflow
assert "--no-editable" in workflow
assert "uv run python" not in workflow
@@ -241,8 +241,8 @@ def test_release_tooling_is_bounded_and_built_from_the_lock():
assert "pytest tests/test_release_gate.py tests/test_updates.py" in workflow
assert "\n dist:\n" in workflow and "needs: guard" in workflow
release_job = workflow.split(" release:\n", maxsplit=1)[1]
- assert release_job.index("actions/checkout@v4") < release_job.index(
- "softprops/action-gh-release@v2"
+ assert release_job.index("actions/checkout@v7") < release_job.index(
+ "softprops/action-gh-release@v3"
)
assert (root / "docs" / "RELEASE_NOTES.md").is_file()
diff --git a/tests/test_repository.py b/tests/test_repository.py
index d5e2967..bd3bfe0 100644
--- a/tests/test_repository.py
+++ b/tests/test_repository.py
@@ -9,6 +9,8 @@ open; see tests/test_migrations.py).
from __future__ import annotations
+from contextlib import contextmanager
+
import pytest
from azimut.workspace import Case, CaseError
@@ -306,6 +308,164 @@ def test_catalog_summary_counts_by_folder(repo):
assert repo.catalog_summary()["by_folder"] == {"X": 2}
+# -- filtering on a field, and on having a neighbour ---------------------------
+#
+# Until these, a case could show every video and every place and never the set that
+# is both: `kind=video` was not expressible anywhere in the app.
+
+
+def test_the_store_that_ships_can_read_inside_a_stored_field():
+ """The exact path is the one that ships, proved per platform rather than assumed.
+
+ The extension set is per-binary (docs/STORAGE_AND_PERFORMANCE.md), so this runs in
+ CI on Windows, macOS, Linux and the 3.11 floor. The `LIKE` fallback beside it is
+ belt and braces, and it matches at any depth where this is top-level exact — so if
+ this ever fails on a platform, that difference is what ships there.
+ """
+ from azimut import sqlite_backend
+
+ assert sqlite_backend._has_json1() is True
+
+
+def test_page_entities_filters_on_one_stored_field(repo):
+ video = repo.add_entity("media", "clip", {"kind": "video"}, by="user")
+ repo.add_entity("media", "still", {"kind": "image"}, by="user")
+
+ page = repo.page_entities(limit=50, attr="kind", attr_value="video")
+ assert [e["id"] for e in page["items"]] == [video["id"]]
+ assert page["total"] == 1
+
+
+def test_a_field_filter_reaches_what_the_vocabulary_does_not_declare(repo):
+ """`kind` is written by the importer and declared nowhere, and it is the field an
+ analyst most wants to filter on. A registry-driven menu would never offer it."""
+ from azimut.engine import entities as entity_engine
+
+ assert entity_engine.entity_type("media").attrs == ()
+ repo.add_entity("media", "clip", {"kind": "video"}, by="user")
+
+ assert repo.page_entities(attr="kind", attr_value="video")["total"] == 1
+
+
+def test_a_number_in_a_field_is_matched_as_the_menu_spells_it(repo):
+ """The value select offers text, so both sides of the control have to agree on the
+ spelling. `100` also matching `1000` is the classic form of getting this wrong."""
+ hundred = repo.add_entity("place", "block", {"radius_m": 100}, by="user")
+ repo.add_entity("place", "town", {"radius_m": 1000}, by="user")
+
+ page = repo.page_entities(attr="radius_m", attr_value="100")
+ assert [e["id"] for e in page["items"]] == [hundred["id"]]
+
+
+def test_a_field_name_the_store_cannot_ask_for_is_refused(repo):
+ """The key reaches SQL inside a JSON path, which the database parses rather than
+ binds, so the character set is closed instead of escaped."""
+ with pytest.raises(CaseError):
+ repo.page_entities(attr='kind"] or 1=1 --', attr_value="video")
+
+
+def test_choosing_a_field_without_a_value_is_not_a_term(repo):
+ """Half of one act: the field is picked, the value select has just been populated.
+ Read as a term, the table would empty itself between two clicks."""
+ repo.add_entity("media", "clip", {"kind": "video"}, by="user")
+
+ assert repo.page_entities(attr="kind")["total"] == 1
+
+
+def test_page_entities_filters_on_having_a_neighbour(repo):
+ """*Which videos have coordinates* is this test and the field filter together, and
+ the count is the answer: the page is which ones."""
+ placed = repo.add_entity("media", "clip", {"kind": "video"}, by="user")
+ loose = repo.add_entity("media", "orphan", {"kind": "video"}, by="user")
+ place = repo.add_entity("place", "quay", {"lat": 1.0, "lon": 2.0}, by="user")
+ repo.add_link(placed["id"], place["id"], "located-at", by="user")
+
+ page = repo.page_entities(types=["media"], attr="kind", attr_value="video", linked="place")
+ assert [e["id"] for e in page["items"]] == [placed["id"]]
+ assert page["total"] == 1
+ assert loose["id"] not in {e["id"] for e in page["items"]}
+
+
+def test_having_a_neighbour_reads_the_pair_not_the_direction(repo):
+ """"Linked to a place" is a question about the pair. Which end states the verb is a
+ property of the vocabulary, and the analyst is not asking about the vocabulary."""
+ place = repo.add_entity("place", "quay", {"lat": 1.0, "lon": 2.0}, by="user")
+ media = repo.add_entity("media", "clip", {"path": "media/clip.mp4"}, by="user")
+ repo.add_link(media["id"], place["id"], "located-at", by="user")
+
+ assert repo.page_entities(types=["place"], linked="media")["total"] == 1
+ assert repo.page_entities(types=["media"], linked="place")["total"] == 1
+
+
+def test_attr_facets_offer_the_fields_and_values_the_case_holds(repo):
+ repo.add_entity("media", "a", {"kind": "video", "path": "media/a.mp4"}, by="user")
+ repo.add_entity("media", "b", {"kind": "video", "path": "media/b.mp4"}, by="user")
+ repo.add_entity("media", "c", {"kind": "image", "path": "media/c.jpg"}, by="user")
+ repo.add_entity("person", "d", {"nationality": "FR"}, by="user")
+
+ facets = {row["key"]: row for row in repo.attr_facets(types=["media"])}
+ assert "nationality" not in facets # narrowed to the type the menu is filtering
+ assert facets["kind"]["entities"] == 3
+ # Commonest value first, so the menu opens on the answer rather than on the
+ # alphabet.
+ assert facets["kind"]["values"] == [
+ {"value": "video", "count": 2},
+ {"value": "image", "count": 1},
+ ]
+
+
+def test_a_field_with_too_many_values_is_not_offered_as_a_menu(repo):
+ """A select over five thousand file paths is not a way to choose, and offering it
+ would be the typed query this app refuses. It says it was cut."""
+ for n in range(6):
+ repo.add_entity("media", f"m{n}", {"path": f"media/{n}.mp4"}, by="user")
+
+ facets = {row["key"]: row for row in repo.attr_facets(types=["media"], limit=3)}
+ assert facets["path"]["truncated"] is True
+ assert facets["path"]["values"] == []
+ assert facets["path"]["entities"] == 6
+
+
+def test_a_value_a_menu_cannot_show_is_not_offered(repo):
+ """A footprint is a shape and a quoted paragraph is a stored value; neither is a
+ choice. A boolean is left out because the two sides of the control would not agree
+ on how to spell it."""
+ ring = [[0.0, 0.0], [0.0, 1.0], [1.0, 1.0], [0.0, 0.0]]
+ repo.add_entity(
+ "place", "shape",
+ {
+ "footprint": {"type": "Polygon", "coordinates": [ring]},
+ "verbatim": "x" * 500,
+ "flagged": True,
+ "radius_m": 25,
+ },
+ by="user",
+ )
+
+ facets = {row["key"]: row for row in repo.attr_facets()}
+ assert set(facets) == {"radius_m"}
+ assert facets["radius_m"]["values"] == [{"value": "25", "count": 1}]
+
+
+def test_the_field_filter_answers_the_same_without_json1(repo, monkeypatch):
+ """The fallback is what a binary whose SQLite lacks JSON1 would run, so it is
+ exercised on every platform rather than only where it might one day be needed."""
+ from azimut import sqlite_backend
+
+ monkeypatch.setattr(sqlite_backend, "_has_json1", lambda: False)
+ video = repo.add_entity("media", "clip", {"kind": "video"}, by="user")
+ repo.add_entity("media", "still", {"kind": "image"}, by="user")
+ hundred = repo.add_entity("place", "block", {"radius_m": 100}, by="user")
+ repo.add_entity("place", "town", {"radius_m": 1000}, by="user")
+
+ assert [e["id"] for e in repo.page_entities(attr="kind", attr_value="video")["items"]] == [
+ video["id"]
+ ]
+ assert [
+ e["id"] for e in repo.page_entities(attr="radius_m", attr_value="100")["items"]
+ ] == [hundred["id"]]
+
+
def test_snapshot_carries_manifest_and_graph(repo):
repo.add_entity("person", "Ada", by="user")
snap = repo.snapshot()
@@ -451,3 +611,182 @@ def test_count_incident_links_groups_relations_in_either_direction(repo):
# excluding nothing counts every edge, chain included
assert repo.count_incident_links(exclude_types=[])[proof["id"]] == 1
+
+
+def test_links_among_holds_an_edge_whose_ends_bind_in_two_statements(repo):
+ """The closed set must not thin out as the set it closes over grows.
+
+ An id set larger than one SQL statement can bind cannot go into an ``IN (…)``,
+ and an edge with **both** ends in the set has ends that can fall in two different
+ chunks of it. Asked chunk by chunk, no chunk held such an edge and neither did the
+ answer: a drawn view past the chunk size lost most of its edges, its nodes drew as
+ unconnected dots, and each one went on reporting the lost edges as connections
+ still to open under a control that could never bring one in.
+ """
+ from azimut.sqlite_backend import _ID_CHUNK
+
+ hub = repo.add_entity("person", "hub", by="user")["id"]
+ # One chunk over the boundary, so the star's arms are bound in three statements
+ # while the hub is bound in one.
+ spokes = [
+ repo.add_entity("person", f"spoke {i:04d}", by="user")["id"]
+ for i in range(_ID_CHUNK * 2 + 1)
+ ]
+ for spoke in spokes:
+ repo.add_link(hub, spoke, "owns", by="user")
+
+ among = repo.links_among([hub, *spokes])
+
+ assert len(among) == len(spokes)
+ # Recorded order survives being read in several statements: parallel edges are
+ # bowed to their own side of the line in payload order, so a set of edges that
+ # came back shuffled would redraw the picture differently on every read.
+ assert among == repo.links_among([hub, *spokes])
+ assert [link["id"] for link in among] == [
+ link["id"] for link in repo.list_links() if link["from"] == hub
+ ]
+ # Still closed: an id nobody passed in cannot arrive at the far end of an edge.
+ assert repo.links_among([hub, *spokes[:3]]) == among[:3]
+
+
+@contextmanager
+def _statements(case):
+ """Every SQL statement one case runs, in order. What proves a read is bounded."""
+ seen: list[str] = []
+ plain = case._sqlite._connect
+
+ @contextmanager
+ def traced():
+ with plain() as conn:
+ conn.set_trace_callback(seen.append)
+ yield conn
+
+ case._sqlite._connect = traced
+ try:
+ yield seen
+ finally:
+ del case._sqlite._connect
+
+
+def test_the_closed_set_costs_one_statement_whatever_the_drawing_holds(repo):
+ """The cost the node ceiling was hiding rather than removing.
+
+ Closing over an id set by asking every **pair** of chunks is the square of the
+ set: nine statements at 650 nodes, four hundred at 5 000. Lifting the ceiling on
+ top of that would have moved the freeze from the canvas to the database, which is
+ why this lands with the limit and not after it.
+ """
+ from azimut.sqlite_backend import _ID_CHUNK
+
+ hub = repo.add_entity("person", "hub", by="user")["id"]
+ spokes = [
+ repo.add_entity("person", f"spoke {i:04d}", by="user")["id"]
+ for i in range(_ID_CHUNK * 3)
+ ]
+ for spoke in spokes:
+ repo.add_link(hub, spoke, "owns", by="user")
+
+ with _statements(repo) as ran:
+ among = repo.links_among([hub, *spokes])
+
+ assert len(among) == len(spokes)
+ # Four chunks would have been sixteen statements. The scope table is filled with
+ # one `executemany`, and the question itself is asked once.
+ reads = [sql for sql in ran if sql.lstrip().upper().startswith("SELECT")]
+ assert len(reads) == 1
+ assert "JOIN scope" in reads[0]
+
+
+def test_one_hop_costs_one_statement_too(repo):
+ """The open set could always be chunked, and is asked through the same table."""
+ from azimut.sqlite_backend import _ID_CHUNK
+
+ hub = repo.add_entity("person", "hub", by="user")["id"]
+ spokes = [
+ repo.add_entity("person", f"spoke {i:04d}", by="user")["id"]
+ for i in range(_ID_CHUNK * 2)
+ ]
+ for spoke in spokes:
+ repo.add_link(hub, spoke, "owns", by="user")
+
+ with _statements(repo) as ran:
+ touching = repo.links_touching(spokes)
+
+ assert len(touching) == len(spokes)
+ assert len([sql for sql in ran if sql.lstrip().upper().startswith("SELECT")]) == 1
+
+
+def test_the_scope_table_does_not_survive_the_read_that_filled_it(repo):
+ """A temp table left standing would answer the next question with the last one's
+ ids. It belongs to the connection, and each read opens its own."""
+ from azimut.sqlite_backend import _SCOPE
+
+ hub = repo.add_entity("person", "hub", by="user")["id"]
+ other = repo.add_entity("person", "other", by="user")["id"]
+ repo.add_link(hub, other, "owns", by="user")
+ assert len(repo.links_among([hub, other])) == 1
+
+ with repo._sqlite._connect() as conn:
+ left = conn.execute(
+ "SELECT name FROM temp.sqlite_master WHERE name = ?", (_SCOPE,)
+ ).fetchall()
+ assert left == []
+
+ # And two reads in a row see their own set, not the one before it.
+ assert repo.links_among([hub]) == []
+ assert len(repo.links_among([hub, other])) == 1
+
+
+def test_every_case_wide_ordering_is_served_by_an_index(repo):
+ """The catalog orders the *whole case* by identity and by when a row was filed,
+ so those two pages have to cost what a page costs and not what the case costs.
+
+ Without an index behind the ordering the keyset cursor bounds what comes back
+ and not what it takes to find it: SQLite reads the filtered set and sorts it in
+ a temp B-tree for every page. This holds the plan to the index, in both
+ directions and with a cursor in hand, which is the shape a second page runs.
+ """
+ from azimut.sqlite_backend import _PAGE_ORDERS
+
+ repo.add_entity("person", "Ada", by="user")
+ plans: dict[str, list[str]] = {}
+ with repo._sqlite._connect() as conn:
+ for order, (expression, _key, descending) in _PAGE_ORDERS.items():
+ way = "<" if descending else ">"
+ direction = "DESC" if descending else "ASC"
+ sql = (
+ "SELECT rowid AS _rowid, * FROM entities"
+ f" WHERE ({expression} {way} ? OR ({expression} = ? AND rowid {way} ?))"
+ f" ORDER BY {expression} {direction}, rowid {direction} LIMIT ?"
+ )
+ plans[order] = [
+ row[-1] for row in conn.execute(
+ "EXPLAIN QUERY PLAN " + sql, ("a", "a", 1, 101)
+ )
+ ]
+
+ assert set(plans) == set(_PAGE_ORDERS)
+ for order, plan in plans.items():
+ detail = " | ".join(plan)
+ assert "TEMP B-TREE" not in detail.upper(), f"{order} sorts in memory: {detail}"
+ assert "USING INDEX" in detail.upper(), f"{order} has no index to walk: {detail}"
+
+
+def test_an_ordered_page_reads_the_case_in_order_and_pages_without_repeating(repo):
+ """The ordering covers the whole case rather than the page, and the cursor keys
+ on the sort plus the row's own seat, so the second page starts where the first
+ stopped even when two rows share a label."""
+ for label in ("delta", "Alpha", "charlie", "Alpha", "bravo"):
+ repo.add_entity("person", label, by="user")
+
+ first = repo.page_entities(limit=2, order="label")
+ second = repo.page_entities(limit=2, cursor=first["next_cursor"], order="label")
+ third = repo.page_entities(limit=2, cursor=second["next_cursor"], order="label")
+
+ seen = [e["label"] for e in (*first["items"], *second["items"], *third["items"])]
+ assert seen == ["Alpha", "Alpha", "bravo", "charlie", "delta"]
+ assert first["total"] == 5
+ assert third["next_cursor"] is None
+ assert [e["label"] for e in repo.page_entities(order="-label")["items"]] == [
+ "delta", "charlie", "bravo", "Alpha", "Alpha",
+ ]
diff --git a/tests/test_reveal.py b/tests/test_reveal.py
index 22cece3..1e308d9 100644
--- a/tests/test_reveal.py
+++ b/tests/test_reveal.py
@@ -248,3 +248,32 @@ def test_a_refusal_reaches_the_ui_as_a_reason(client, monkeypatch):
assert res.status_code == 409
assert "xdg-open" in res.json()["detail"]
+
+
+def test_media_route_shows_the_folder_a_file_sits_in(client, shown):
+ """A PDF or a spreadsheet has no viewer here, so the folder is the answer.
+
+ What opens is the folder, never the file: revealing is "where is this", and
+ launching whatever program claims a `.docx` is a different, riskier thing.
+ """
+ cid = client.post("/api/cases", json={"name": "Reveal media"}).json()["id"]
+ client.post(
+ f"/api/cases/{cid}/media/upload",
+ files={"file": ("site plan.pdf", b"%PDF-1.4 fixture", "application/pdf")},
+ )
+
+ res = client.post(f"/api/cases/{cid}/media/reveal", json={"path": "media/site plan.pdf"})
+
+ assert res.status_code == 200
+ assert shown[0].name == "media"
+ assert shown[0].resolve().is_relative_to((config.cases_dir() / cid).resolve())
+ assert res.json()["path"].endswith("media")
+
+
+def test_media_route_refuses_a_path_that_leaves_the_case(client, shown):
+ cid = client.post("/api/cases", json={"name": "Reveal escape"}).json()["id"]
+
+ for attempt in ("../../etc", "/etc", "media/../../..", "media/nothing.pdf"):
+ res = client.post(f"/api/cases/{cid}/media/reveal", json={"path": attempt})
+ assert res.status_code in (400, 404), attempt
+ assert not shown
diff --git a/tests/test_satellite_api.py b/tests/test_satellite_api.py
index 7f60a85..eda9c3a 100644
--- a/tests/test_satellite_api.py
+++ b/tests/test_satellite_api.py
@@ -70,12 +70,10 @@ def _places(client, cid):
return _of_type(client, cid, "place")
-def test_capture_creates_capture_entity_not_place(client, monkeypatch):
+def test_capture_creates_its_own_entity(client, monkeypatch):
monkeypatch.setattr(tiles, "_default_fetch", _fake_tile)
cid = client.post("/api/cases", json={"name": "Sat"}).json()["id"]
cap = _capture(client, cid, 48.8584, 2.2945)
- # a capture is an image entity, not a navigable place
- assert _places(client, cid) == []
caps = _captures(client, cid)
assert len(caps) == 1
# the entity is tied to this exact capture by path, titled with its coords
@@ -993,7 +991,7 @@ def test_a_save_succeeds_when_the_lookup_fails(client, monkeypatch):
# …and a later Locate pass resolves what the failure left behind
monkeypatch.setattr(geo, "reverse_geocode", _UKRAINE)
assert client.post(f"/api/cases/{cid}/satellite/locate").json() == {
- "located": 2, "failed": 0, "remaining": 0,
+ "located": 2, "failed": 0, "remaining": 0, "throttled": False,
}
assert {r["geo"]["country"] for r in _index(client, cid)} == {"Ukraine"}
@@ -1032,40 +1030,47 @@ def _places_at(client, cid, count):
def test_locate_works_through_the_backlog_and_reports_what_is_left(client, monkeypatch):
- monkeypatch.setattr(satellite_api, "NOMINATIM_INTERVAL", 0)
cid = client.post("/api/cases", json={"name": "Sat"}).json()["id"]
_places_at(client, cid, 5) # all saved offline → all failed
monkeypatch.setattr(geo, "reverse_geocode", _UKRAINE)
first = client.post(f"/api/cases/{cid}/satellite/locate", params={"limit": 2}).json()
- assert first == {"located": 2, "failed": 0, "remaining": 3}
+ assert first == {"located": 2, "failed": 0, "remaining": 3, "throttled": False}
second = client.post(f"/api/cases/{cid}/satellite/locate", params={"limit": 25}).json()
- assert second == {"located": 3, "failed": 0, "remaining": 0}
+ assert second == {"located": 3, "failed": 0, "remaining": 0, "throttled": False}
# settled items are never looked up again — re-running is a no-op
assert client.post(f"/api/cases/{cid}/satellite/locate").json() == {
- "located": 0, "failed": 0, "remaining": 0,
+ "located": 0, "failed": 0, "remaining": 0, "throttled": False,
}
def test_locate_leaves_a_failure_for_the_next_pass(client, monkeypatch):
- monkeypatch.setattr(satellite_api, "NOMINATIM_INTERVAL", 0)
cid = client.post("/api/cases", json={"name": "Sat"}).json()["id"]
_places_at(client, cid, 2)
assert client.post(f"/api/cases/{cid}/satellite/locate").json() == {
- "located": 0, "failed": 2, "remaining": 2,
+ "located": 0, "failed": 2, "remaining": 2, "throttled": False,
}
+def test_locate_reports_that_nominatim_is_throttling(client, monkeypatch):
+ """A 429 is not an ordinary lookup failure: the analyst has to be told to
+ wait rather than to run the pass again, so the verdict travels."""
+ cid = client.post("/api/cases", json={"name": "Sat"}).json()["id"]
+ _places_at(client, cid, 1)
+
+ monkeypatch.setattr(geo, "throttled", lambda: True)
+ assert client.post(f"/api/cases/{cid}/satellite/locate").json()["throttled"] is True
+
+
def test_locate_settles_open_sea_without_retrying_it(client, monkeypatch):
- monkeypatch.setattr(satellite_api, "NOMINATIM_INTERVAL", 0)
cid = client.post("/api/cases", json={"name": "Sat"}).json()["id"]
client.post(f"/api/cases/{cid}/satellite/place", json={"lat": 0.0, "lon": -30.0})
monkeypatch.setattr(geo, "reverse_geocode", _address({}))
assert client.post(f"/api/cases/{cid}/satellite/locate").json() == {
- "located": 1, "failed": 0, "remaining": 0,
+ "located": 1, "failed": 0, "remaining": 0, "throttled": False,
}
assert _index(client, cid)[0]["geo"] == {"state": "nocountry"}
assert _index(client, cid)[0]["continent"] is None
diff --git a/tests/test_sky.py b/tests/test_sky.py
index 036e894..e0ec91b 100644
--- a/tests/test_sky.py
+++ b/tests/test_sky.py
@@ -438,6 +438,64 @@ def test_local_noon_is_midday_on_the_clock():
assert moment == datetime(2026, 1, 15, 11, 0, tzinfo=UTC)
+# -- daylight over a window ----------------------------------------------------
+#
+# A different question from the almanac above: not *when did the sun rise on this
+# date* but *over these days, when was it light*. Held to the same standard — the
+# altitude at each returned edge is the horizon — plus the two things a run of spans
+# can get wrong that a single day cannot: the clipping at each end of the window, and
+# a window with no crossing in it at all.
+
+
+def test_daylight_spans_one_per_day_and_each_edge_is_the_horizon():
+ start = datetime(2026, 6, 20, tzinfo=UTC)
+ spans = sky.daylight_spans(*PARIS, start, start + timedelta(days=3))
+ assert len(spans) == 3
+ for span in spans:
+ assert span["from"] < span["to"]
+ for edge in (span["from"], span["to"]):
+ assert _altitude(*PARIS, edge) == pytest.approx(sky.SUN_HORIZON_DEG, abs=0.01)
+ # midsummer in Paris: a good sixteen hours of it
+ assert 15.5 < (spans[0]["to"] - spans[0]["from"]).total_seconds() / 3600 < 16.5
+
+
+def test_daylight_clips_to_the_window_instead_of_reaching_outside_it():
+ """A window opening at noon is already inside daylight, and a chronology drawing
+ the ribbon must not be handed a sunrise that happened before the axis starts."""
+ noon = datetime(2026, 6, 20, 12, tzinfo=UTC)
+ spans = sky.daylight_spans(*PARIS, noon, noon + timedelta(hours=4))
+ assert len(spans) == 1
+ assert spans[0]["from"] == noon
+ assert spans[0]["to"] == noon + timedelta(hours=4)
+
+
+def test_polar_day_is_one_span_and_polar_night_is_none():
+ """The two answers a caller cannot tell from a failed computation unless the
+ window comes back either wholly covered or wholly empty."""
+ midsummer = datetime(2026, 6, 20, tzinfo=UTC)
+ covered = sky.daylight_spans(*TROMSO, midsummer, midsummer + timedelta(days=3))
+ assert covered == [{"from": midsummer, "to": midsummer + timedelta(days=3)}]
+
+ midwinter = datetime(2026, 12, 20, tzinfo=UTC)
+ assert sky.daylight_spans(*TROMSO, midwinter, midwinter + timedelta(days=3)) == []
+
+
+def test_civil_twilight_encloses_the_daylight_it_surrounds():
+ start = datetime(2026, 6, 20, tzinfo=UTC)
+ day = sky.daylight_spans(*PARIS, start, start + timedelta(days=1))[0]
+ civil = sky.daylight_spans(
+ *PARIS, start, start + timedelta(days=1), sky.TWILIGHTS["civil"]
+ )[0]
+ assert civil["from"] < day["from"]
+ assert civil["to"] > day["to"]
+
+
+def test_a_window_that_ends_before_it_starts_has_no_spans():
+ start = datetime(2026, 6, 20, tzinfo=UTC)
+ assert sky.daylight_spans(*PARIS, start, start) == []
+ assert sky.daylight_spans(*PARIS, start, start - timedelta(days=1)) == []
+
+
# -- nothing reaches the network -----------------------------------------------
diff --git a/tests/test_sources.py b/tests/test_sources.py
new file mode 100644
index 0000000..2b2c446
--- /dev/null
+++ b/tests/test_sources.py
@@ -0,0 +1,279 @@
+"""Where a claim rests, and what its source is worth (ONTOLOGY §2, §3).
+
+One rule carries this file, and it is the reason the Admiralty scheme exists at all:
+**reliability and credibility are two axes, and they never combine.** Reliability is
+what the source is worth and lives on the source entity; credibility is what one
+statement is worth and lives on the Claim entity. Multiplying them into a single number is
+precisely what the scheme was written to prevent, so the model makes it impossible
+rather than discouraged — the two values are not on the same object, and no route
+returns a third.
+
+The rest is the shape of a source: a page, when it was seen, the archived copy that
+outlives it, and the fact that a claim never needs one.
+"""
+
+import pytest
+
+from azimut import config
+from azimut.engine import entities as entity_engine
+from azimut.engine import links as link_engine
+
+
+def _case(client, name):
+ return client.post("/api/cases", json={"name": name}).json()["id"]
+
+
+def _entity(client, cid, type_, label, attrs=None):
+ res = client.post(
+ f"/api/cases/{cid}/entities",
+ json={"type": type_, "label": label, "attrs": attrs or {}},
+ )
+ assert res.status_code == 200, res.text
+ return res.json()["id"]
+
+
+def _patch(client, cid, entity_id, attrs):
+ return client.patch(f"/api/cases/{cid}/entities/{entity_id}", json={"attrs": attrs})
+
+
+def _link(client, cid, from_id, to_id, type_):
+ res = client.post(
+ f"/api/cases/{cid}/links",
+ json={"from_id": from_id, "to_id": to_id, "type": type_},
+ )
+ assert res.status_code == 200, res.text
+ return res.json()["id"]
+
+
+def _read(client, cid, entity_id):
+ return client.get(f"/api/cases/{cid}/entities/{entity_id}/chain").json()
+
+
+# -- the scale ----------------------------------------------------------------
+
+
+def test_the_registry_serves_the_grades_so_no_surface_spells_them(client):
+ """The picker offers exactly what the validator accepts, which is what the radius
+ rungs and the confidence levels are served for. It rides with the entity registry
+ rather than on a route of its own: reliability belongs to an entity, so it travels
+ with the entity vocabulary."""
+ rows = {row["type"]: row for row in client.get("/api/cases/entity-types").json()}
+
+ for type_ in ("bookmark", "account"):
+ field = next(a for a in rows[type_]["attrs"] if a["key"] == "reliability")
+ assert field["kind"] == "choice"
+ assert [option["value"] for option in field["options"]] == ["A", "B", "C", "D", "E"]
+ assert field["options"][0]["label"] == "Completely reliable"
+
+
+def test_the_scale_stops_at_e_because_absent_already_says_cannot_be_judged():
+ """Admiralty's sixth grade is "reliability cannot be judged", which is what an
+ empty field says — and this model never spells one state twice. The same call the
+ confidence ordinal makes, where "not assessed" is the lack of a level rather than
+ a fifth one."""
+ assert [grade for grade, _ in entity_engine.RELIABILITY_GRADES] == list("ABCDE")
+
+
+def test_only_a_source_is_graded(client):
+ """The grade sits on the bookmark or the account cited, and nowhere else. Putting
+ it on the whole `document` family would ask an analyst how reliable their own
+ proof is; SPEC's open question reopens this the day a source is neither."""
+ rows = {row["type"]: row for row in client.get("/api/cases/entity-types").json()}
+ graded = {
+ row["type"] for row in rows.values()
+ if any(attr["key"] == "reliability" for attr in row["attrs"])
+ }
+
+ assert graded == {"bookmark", "account"}
+
+
[email protected]("grade", ["F", "a", "AA", 1, True, ["A"]])
+def test_a_grade_outside_the_scale_is_refused(client, grade):
+ """A closed scale is only closed if the store says so: an unknown letter would
+ render as itself and read as a level nobody agreed on. `F` is in this list rather
+ than in the scale on purpose — Admiralty's "cannot be judged" is what an empty
+ field already says."""
+ cid = _case(client, f"Grade {grade}")
+ bookmark = _entity(client, cid, "bookmark", "Leak site", {"url": "https://example.test/"})
+
+ assert _patch(client, cid, bookmark, {"reliability": grade}).status_code == 400
+
+
+def test_a_grade_is_cleared_back_to_ungraded(client):
+ """Ungraded is the normal state of a source and one to be able to return to. It is
+ the absence of a judgement, not a sixth grade, so it is stored as nothing."""
+ cid = _case(client, "Ungrade")
+ bookmark = _entity(client, cid, "bookmark", "Leak site", {"url": "https://example.test/"})
+ assert _patch(client, cid, bookmark, {"reliability": "B"}).status_code == 200
+
+ cleared = _patch(client, cid, bookmark, {"reliability": None})
+ blanked = _patch(client, cid, bookmark, {"reliability": ""})
+
+ assert cleared.status_code == 200, cleared.text
+ assert blanked.status_code == 200, blanked.text
+ assert not blanked.json()["attrs"].get("reliability")
+
+
+# -- the two axes -------------------------------------------------------------
+
+
+def test_reliability_and_credibility_are_two_fields_on_two_objects(client):
+ """The heart of it. A claim cites a source and rates the statement; the grade of
+ the source and the confidence of the Claim arrive on different objects, and neither
+ route can be made to write the other."""
+ cid = _case(client, "Two axes")
+ claim = _entity(
+ client, cid, "claim", "The convoy passed on the 3rd", {"confidence": "possible"}
+ )
+ bookmark = _entity(
+ client, cid, "bookmark", "Local paper",
+ {"url": "https://example.test/report", "reliability": "B"},
+ )
+ cites = _link(client, cid, claim, bookmark, "cites")
+
+ chain = _read(client, cid, claim)
+ row = next(r for r in chain["relations"] if r["link"]["id"] == cites)
+
+ # what the source is worth: on the entity
+ assert row["entity"]["attrs"]["reliability"] == "B"
+ # what this one statement is worth: on the Claim
+ assert chain["entity"]["attrs"]["confidence"] == "possible"
+ assert "confidence" not in row["link"]
+ # and nothing anywhere is the two of them folded together
+ assert "reliability" not in row["link"]
+ assert "confidence" not in row["entity"]["attrs"]
+
+
+def test_rating_the_citation_leaves_the_source_alone_and_the_reverse(client):
+ """A well-graded source can carry a claim nobody believes, and a poor source can
+ carry one that checks out. Neither write may drag the other with it."""
+ cid = _case(client, "Independent")
+ claim = _entity(
+ client, cid, "claim", "Filmed from the north bank", {"confidence": "certain"}
+ )
+ bookmark = _entity(
+ client, cid, "bookmark", "Anonymous channel",
+ {"url": "https://example.test/post", "reliability": "E"},
+ )
+ cites = _link(client, cid, claim, bookmark, "cites")
+
+ # an unreliable source, and a statement of theirs that was corroborated anyway
+ graded = client.get(f"/api/cases/{cid}/entities/{bookmark}/chain").json()["entity"]
+ assert graded["attrs"]["reliability"] == "E"
+
+ # and re-grading the source does not touch what was said about the statement
+ _patch(client, cid, bookmark, {"reliability": "A"})
+ chain = _read(client, cid, claim)
+ row = next(r for r in chain["relations"] if r["link"]["id"] == cites)
+ assert chain["entity"]["attrs"]["confidence"] == "certain"
+ assert "confidence" not in row["link"]
+ assert row["entity"]["attrs"]["reliability"] == "A"
+
+
+def test_neither_axis_is_declared_where_the_other_lives():
+ """A registry-level gate, so the separation cannot be undone by a stray field.
+ An entity that declared `confidence` or a relation that carried `reliability`
+ would be the first half of the merged score the scheme exists to prevent."""
+ holders = {
+ entry.type for entry in entity_engine.ENTITY_TYPES
+ if any(attr.key == "confidence" for attr in entry.attrs)
+ }
+ assert holders == {"claim"}
+ for relation in link_engine.RELATION_TYPES:
+ assert not hasattr(relation, "reliability"), relation.type
+
+
+def test_a_link_patch_cannot_carry_a_grade(client):
+ """The edge accepts one closed ordinal and nothing else (ONTOLOGY §3). A body
+ reaching for the source's axis changes nothing rather than quietly landing."""
+ cid = _case(client, "Edge fields")
+ claim = _entity(client, cid, "claim", "Shot at dawn")
+ bookmark = _entity(client, cid, "bookmark", "Thread", {"url": "https://example.test/t"})
+ cites = _link(client, cid, claim, bookmark, "cites")
+
+ res = client.patch(f"/api/cases/{cid}/links/{cites}", json={"reliability": "A"})
+
+ assert res.status_code == 400 # nothing to update: the field is not the edge's
+ row = next(r for r in _read(client, cid, claim)["relations"] if r["link"]["id"] == cites)
+ assert "reliability" not in row["link"]
+
+
+# -- a source is never required -----------------------------------------------
+
+
+def test_a_claim_with_no_source_stays_valid_and_ratable(client):
+ """Nothing in this model is compulsory. A statement with no citation is a normal
+ statement — an unsourced reading of an image is most of a live case — and it is
+ rated like any other. Requiring a source would make the field a gate rather than
+ a record."""
+ cid = _case(client, "Unsourced")
+ claim = _entity(
+ client, cid, "claim", "This is the same bridge", {"confidence": "probable"}
+ )
+ place = _entity(client, cid, "place", "48.85, 2.29", {"lat": 48.85, "lon": 2.29})
+ _link(client, cid, claim, place, "at")
+ chain = _read(client, cid, claim)
+ assert [row["link"]["type"] for row in chain["relations"]] == ["at"]
+ assert chain["entity"]["attrs"]["confidence"] == "probable"
+
+
+def test_an_ungraded_source_is_a_source(client):
+ """Most bookmarks are never graded, and that has to cost nothing: the citation
+ holds, the rating holds, and nothing on the read path reports the absence."""
+ cid = _case(client, "Ungraded source")
+ claim = _entity(client, cid, "claim", "Posted the same day", {"confidence": "probable"})
+ bookmark = _entity(client, cid, "bookmark", "Mirror", {"url": "https://example.test/m"})
+ cites = _link(client, cid, claim, bookmark, "cites")
+
+ chain = _read(client, cid, claim)
+ row = next(r for r in chain["relations"] if r["link"]["id"] == cites)
+
+ assert "reliability" not in row["entity"]["attrs"]
+ assert "confidence" not in row["link"]
+ assert chain["entity"]["attrs"]["confidence"] == "probable"
+
+
+# -- the page, and the copy that outlives it ----------------------------------
+
+
+def test_the_extension_stamps_when_the_page_was_seen(client):
+ """`fetched_at` is written by the route that was standing on the page, in UTC and
+ from the server's clock: the moment is known rather than typed, and a browser
+ clock is not a source. It is what an archived copy is later dated against."""
+ cid = _case(client, "Fetched")
+ token = config.ingest_token()
+ res = client.post(
+ "/api/ingest/bookmark",
+ data={"url": "https://example.test/page", "case_id": cid, "title": "Leak"},
+ headers={"X-Azimut-Token": token},
+ )
+ assert res.status_code == 200, res.text
+
+ entity = client.get(f"/api/cases/{cid}/entities/{res.json()['entity_id']}/chain").json()
+ fetched = entity["entity"]["attrs"]["fetched_at"]
+ assert fetched.startswith("20") and fetched.endswith("+00:00")
+
+
+def test_a_bookmark_typed_by_hand_was_never_fetched(client):
+ """Nothing went and looked at the page, so there is no moment to record — and an
+ empty field is never flagged. Absence is a state, not a gap."""
+ cid = _case(client, "Hand-typed")
+ bookmark = _entity(client, cid, "bookmark", "To read", {"url": "https://example.test/x"})
+
+ entity = client.get(f"/api/cases/{cid}/entities/{bookmark}/chain").json()["entity"]
+
+ assert "fetched_at" not in entity["attrs"]
+
+
+def test_an_archived_copy_is_a_url_or_it_is_refused(client):
+ """The field is rendered as a link, so the scheme is checked at the edge rather
+ than trusted — the same reason the account's profile URL is."""
+ cid = _case(client, "Archive")
+ bookmark = _entity(client, cid, "bookmark", "Deleted post", {"url": "https://example.test/p"})
+
+ assert _patch(
+ client, cid, bookmark,
+ {"archive_url": "https://web.archive.test/web/2026/https://example.test/p"},
+ ).status_code == 200
+ assert _patch(client, cid, bookmark, {"archive_url": "javascript:alert(1)"}).status_code == 400
+ assert _patch(client, cid, bookmark, {"archive_url": None}).status_code == 200
diff --git a/tests/test_sqlite_backend.py b/tests/test_sqlite_backend.py
index 3f1f770..c4ca18f 100644
--- a/tests/test_sqlite_backend.py
+++ b/tests/test_sqlite_backend.py
@@ -12,13 +12,15 @@ from __future__ import annotations
import sqlite3
import threading
+from contextlib import closing
import pytest
from bigcase import build_big_case
+import schema_rewind
from legacy_case import legacy_manifest_path, read_legacy_manifest, write_legacy_json_case
from azimut import layout
-from azimut.sqlite_backend import SqliteCase, convert_json_to_sqlite
+from azimut.sqlite_backend import SQLITE_SCHEMA, SqliteCase, convert_json_to_sqlite
from azimut.workspace import CaseError
@@ -74,7 +76,7 @@ def test_open_missing_db_raises(tmp_path):
def test_open_refuses_newer_schema(tmp_path):
db = tmp_path / "case.db"
SqliteCase.create(db, name="From the future")
- with sqlite3.connect(db) as conn:
+ with closing(sqlite3.connect(db)) as conn, conn:
conn.execute("UPDATE meta SET value = ? WHERE key = 'schema_version'", ("99",))
with pytest.raises(CaseError, match="newer Azimut"):
SqliteCase.open(db)
@@ -145,14 +147,17 @@ INSERT INTO entities(id, type, label, attrs_json, prov_by, prov_at)
def test_open_upgrades_a_v1_db_through_every_migration(tmp_path):
"""A schema-1 case.db is upgraded on open through the whole chain: the folder
column is added and backfilled (1->2), the jobs table is created (2->3),
- search/media browse indexes arrive in schema 4, the position flag in 5 and
- the trash journal in 6 and its recovery state in 7. A second open applies
- nothing."""
+ search/media browse indexes arrive in schema 4, the position flag in 5, the
+ trash journal in 6, its recovery state in 7, link confidence in 8, the
+ search-index rebuild in 9, the graph's hand-placed nodes, one arrangement
+ per lens, in 10, what kind of tie an edge states in 11, entity photo
+ galleries in 12, saved analysis views in 13, and the indexes the catalog
+ orders the whole case by in 14. A second open applies nothing."""
db = tmp_path / "case.db"
- with sqlite3.connect(db) as conn:
+ with closing(sqlite3.connect(db)) as conn, conn:
conn.executescript(_SCHEMA_V1)
- # runs 1 -> 2 -> 3 -> 4 -> 5 -> 6 -> 7 in place. The media directory is
+ # runs 1 -> 2 -> ... -> the current schema in place. The media directory is
# passed because the backend never guesses the case layout; it is empty
# here, so the schema-4 backfill marks itself done with no rows.
store = SqliteCase.open(db, media_dir=tmp_path / "media")
@@ -163,12 +168,14 @@ def test_open_upgrades_a_v1_db_through_every_migration(tmp_path):
# 2 -> 3: the durable jobs table exists and works.
store.enqueue_job("thumbnail", key="media/x.jpg")
assert store.count_jobs() == {"queued": 1}
- with sqlite3.connect(db) as conn:
- assert conn.execute("SELECT value FROM meta WHERE key='schema_version'").fetchone()[0] == "7"
+ with closing(sqlite3.connect(db)) as conn, conn:
+ assert conn.execute(
+ "SELECT value FROM meta WHERE key='schema_version'"
+ ).fetchone()[0] == str(SQLITE_SCHEMA)
applied = {
r[0] for r in conn.execute("SELECT version FROM schema_migrations").fetchall()
}
- assert {2, 3, 4, 5, 6, 7} <= applied
+ assert set(range(2, SQLITE_SCHEMA + 1)) <= applied
columns = {
row[1] for row in conn.execute("PRAGMA table_info(entities)").fetchall()
}
@@ -183,15 +190,162 @@ def test_open_upgrades_a_v1_db_through_every_migration(tmp_path):
row[1] for row in conn.execute("PRAGMA table_info(trash)").fetchall()
}
assert "state" in trash_columns
+ # 7 -> 8: an edge can carry how sure the analyst is.
+ link_columns = {
+ row[1] for row in conn.execute("PRAGMA table_info(links)").fetchall()
+ }
+ assert "confidence" in link_columns
+ # 10 -> 11: an edge can say what kind of tie it states. Nothing to backfill —
+ # every edge filed before this is unqualified, which is what a null says.
+ assert "nature" in link_columns
+ assert not conn.execute("SELECT 1 FROM links WHERE nature IS NOT NULL").fetchall()
+ # 9 -> 10: the graph can remember where a node was dragged to, per lens, and
+ # a case that never could reads as one nobody has arranged.
+ assert store.graph_pins("all") == {}
+ pin_columns = {
+ row[1] for row in conn.execute("PRAGMA table_info(graph_pins)").fetchall()
+ }
+ assert "lens" in pin_columns
+ # 11 -> 12: galleries hold private photos or existing Media references.
+ image_columns = {
+ row[1] for row in conn.execute("PRAGMA table_info(entity_images)").fetchall()
+ }
+ assert image_columns == {
+ "entity_id",
+ "image_id",
+ "media_id",
+ "path",
+ "thumbnail",
+ "title",
+ "position",
+ "is_primary",
+ }
+ # 12 -> 13: named Board/Graph readings are case-owned rows. The count lets
+ # their bounded menu avoid parsing snapshot JSON.
+ view_columns = {
+ row[1] for row in conn.execute("PRAGMA table_info(analysis_views)").fetchall()
+ }
+ assert view_columns == {
+ "id", "name", "mode", "surface", "spec_json", "snapshot_count",
+ "created_at", "updated_at",
+ }
SqliteCase.open(db, media_dir=tmp_path / "media") # idempotent — applies nothing
- with sqlite3.connect(db) as conn:
- for version in (2, 3, 4, 5, 6, 7):
+ with closing(sqlite3.connect(db)) as conn, conn:
+ for version in (2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13):
assert conn.execute(
"SELECT COUNT(*) FROM schema_migrations WHERE version = ?", (version,)
).fetchone()[0] == 1
+def _rewind_to_schema_7(db):
+ schema_rewind.rewind(db, 7)
+
+
+def test_a_real_schema_7_case_keeps_every_link_through_the_confidence_migration(tmp_path):
+ """The upgrade people will actually run when they download the next release: a
+ case built by the shipped code, migrated in place. Every edge survives with its
+ id, type and provenance, and none of them acquires a rating — an existing link
+ reads as *not assessed*, which is the truth about it.
+
+ Written as a real case rather than a hand-authored schema-7 dump so it exercises
+ the same `ALTER TABLE` the shipped binary will run, whatever the platform: the
+ step is one SQL statement in one transaction, with no file moved or replaced, so
+ it carries none of the Windows rename-not-delete hazards a file swap would.
+ """
+ db = tmp_path / "case.db"
+ store = SqliteCase.create(db, name="Before the upgrade")
+ a = store.add_entity("media", "clip.mp4", by="user")["id"]
+ b = store.add_entity("place", "the quay", by="user")["id"]
+ edge = store.add_link(a, b, "located-at", by="user")
+ suggested = store.add_link(a, b, "depicts", by="enrich", status="suggested")
+ _rewind_to_schema_7(db)
+
+ reopened = SqliteCase.open(db, media_dir=tmp_path / "media")
+
+ links = {link["id"]: link for link in reopened.list_links()}
+ assert set(links) == {edge["id"], suggested["id"]}
+ assert links[edge["id"]]["type"] == "located-at"
+ assert links[edge["id"]]["provenance"]["status"] == "confirmed"
+ # the enrichment suggestion is still awaiting review: the two axes are separate
+ assert links[suggested["id"]]["provenance"]["status"] == "suggested"
+ assert links[suggested["id"]]["provenance"]["by"] == "enrich"
+ # absent, not null: no reader has to tell unevaluated from rated-as-nothing
+ for link in links.values():
+ assert "confidence" not in link
+
+
+def test_the_confidence_migration_runs_on_a_case_with_no_links_at_all(tmp_path):
+ """The other real shape: most cases hold entities and no relations yet. `ALTER
+ TABLE` on an empty table is still a schema change, and the version has to move
+ or every later open would retry it."""
+ db = tmp_path / "case.db"
+ store = SqliteCase.create(db, name="No relations")
+ store.add_entity("media", "lonely.jpg", by="user")
+ _rewind_to_schema_7(db)
+
+ reopened = SqliteCase.open(db, media_dir=tmp_path / "media")
+
+ assert reopened.list_links() == []
+ with closing(sqlite3.connect(db)) as conn, conn:
+ assert conn.execute(
+ "SELECT value FROM meta WHERE key = 'schema_version'"
+ ).fetchone()[0] == str(SQLITE_SCHEMA)
+
+
+def _rewind_to_schema_8(db):
+ schema_rewind.rewind(db, 8)
+
+
+def test_a_case_search_reaches_the_fields_the_vocabulary_declares(tmp_path):
+ """A vehicle is looked for by its plate and a claim by the words it quotes.
+
+ Both were unfindable while the index stopped at the label, the type, the folder
+ and the notes — the declared fields, the ones the registry went to the trouble
+ of naming, were exactly what search could not see.
+ """
+ db = tmp_path / "case.db"
+ store = SqliteCase.create(db, name="Declared fields")
+ truck = store.add_entity(
+ "vehicle", "Truck 12", {"plate": "AB-123-CD", "make": "Kamaz"}, by="user"
+ )
+ claim = store.add_entity(
+ "claim", "Filmed at the quay", {"verbatim": "on the north jetty"}, by="user"
+ )
+ place = store.add_entity("place", "Quay 4", {"radius_m": 500}, by="user")
+
+ assert [e["id"] for e in store.page_entities(query="AB-123")["items"]] == [truck["id"]]
+ assert [e["id"] for e in store.page_entities(query="kamaz")["items"]] == [truck["id"]]
+ assert [e["id"] for e in store.page_entities(query="north jetty")["items"]] == [claim["id"]]
+ # a stored number is not text to match on: "500" against every radius in the
+ # case would bury the rows that actually say 500
+ assert store.page_entities(query="500")["items"] == []
+ assert [e["id"] for e in store.page_entities(query="quay 4")["items"]] == [place["id"]]
+
+
+def test_schema_9_rebuilds_the_index_for_rows_written_before_it(tmp_path):
+ """The index is a stored column, so widening it only reaches later writes.
+
+ Without the rebuild a case filed last week would go on answering searches from
+ its label alone, which is indistinguishable from the bug being unfixed.
+ """
+ db = tmp_path / "case.db"
+ store = SqliteCase.create(db, name="Old rows")
+ truck = store.add_entity("vehicle", "Truck 12", {"plate": "AB-123-CD"}, by="user")
+ with closing(sqlite3.connect(db)) as conn, conn:
+ # exactly what schema 8 stored: label, type, folder, notes
+ conn.execute("UPDATE entities SET search_text = 'truck 12\nvehicle'")
+ conn.commit()
+ assert SqliteCase.open(db, media_dir=tmp_path / "media").page_entities(
+ query="AB-123"
+ )["items"] == []
+
+ _rewind_to_schema_8(db)
+ reopened = SqliteCase.open(db, media_dir=tmp_path / "media")
+
+ assert [e["id"] for e in reopened.page_entities(query="AB-123")["items"]] == [truck["id"]]
+
+
# A schema-4 media index: the browse table as it shipped, before the position
# flag. `media_index_ready` is set because a real v4 case has already backfilled;
# without it, open would rescan the (absent) media folder and clear these rows.
@@ -241,7 +395,7 @@ def test_open_backfills_the_position_flag_from_already_indexed_items(tmp_path):
"""4 -> 5 reads the sidecar JSON already in the row, so a case enriched before
the column existed gains its GPS filter on open — no file scan, no re-enrich."""
db = tmp_path / "case.db"
- with sqlite3.connect(db) as conn:
+ with closing(sqlite3.connect(db)) as conn, conn:
conn.executescript(_SCHEMA_V4_MEDIA)
store = SqliteCase.open(db)
@@ -260,7 +414,7 @@ def test_open_without_a_media_dir_defers_the_backfill(tmp_path):
moves.
"""
db = tmp_path / "case.db"
- with sqlite3.connect(db) as conn:
+ with closing(sqlite3.connect(db)) as conn, conn:
conn.executescript(_SCHEMA_V1) # predates the index, so it needs the backfill
media_dir = tmp_path / "elsewhere"
(media_dir / layout.META_DIR).mkdir(parents=True)
@@ -272,7 +426,7 @@ def test_open_without_a_media_dir_defers_the_backfill(tmp_path):
)
SqliteCase.open(db)
- with sqlite3.connect(db) as conn:
+ with closing(sqlite3.connect(db)) as conn, conn:
assert conn.execute("SELECT value FROM meta WHERE key='media_index_ready'").fetchone() is None
store = SqliteCase.open(db, media_dir=media_dir)
@@ -406,6 +560,43 @@ def test_pagination_keys_on_rowid_so_a_deletion_does_not_skip(tmp_path):
assert [e["id"] for e in page2["items"]] == ids[2:] # nothing skipped
+def test_an_ordered_page_keys_on_its_sort_and_never_ties_itself_into_a_loop(tmp_path):
+ """A sort has to page on its own key *and* the rowid. Every one of these four
+ entities was filed in the same second — which is what a bulk import looks like —
+ so a cursor holding the date alone would hand back the same page forever."""
+ store = SqliteCase.create(tmp_path / "case.db", name="Ordered")
+ ids = [store.add_entity("person", f"P{i}", by="user")["id"] for i in range(4)]
+
+ seen: list[str] = []
+ cursor = None
+ while True:
+ page = store.page_entities(limit=2, cursor=cursor, order="-created")
+ seen.extend(entity["id"] for entity in page["items"])
+ cursor = page["next_cursor"]
+ if cursor is None:
+ break
+ assert seen == list(reversed(ids)) # every row once, newest first
+
+
+def test_an_ordered_cursor_survives_a_key_holding_its_own_separator(tmp_path):
+ """The cursor is spelled `<rowid>:<key>`, and a label may hold a colon. The rowid
+ cannot, so the key takes the whole of the rest and a name round-trips unharmed."""
+ store = SqliteCase.create(tmp_path / "case.db", name="Colons")
+ for label in ("aa: one", "bb: two", "cc: three"):
+ store.add_entity("person", label, by="user")
+
+ first = store.page_entities(limit=2, order="label")
+ assert [entity["label"] for entity in first["items"]] == ["aa: one", "bb: two"]
+ rest = store.page_entities(limit=2, cursor=first["next_cursor"], order="label")
+ assert [entity["label"] for entity in rest["items"]] == ["cc: three"]
+
+
+def test_an_ordering_the_store_does_not_have_is_refused(tmp_path):
+ store = SqliteCase.create(tmp_path / "case.db", name="BadOrder")
+ with pytest.raises(CaseError):
+ store.page_entities(order="size")
+
+
# -- converter -------------------------------------------------------------
@@ -527,3 +718,45 @@ def test_a_media_row_carries_the_entity_it_belongs_to(tmp_workspace):
assert by_path["media/loose.jpg"]["entity_id"] is None
assert case.media_items_by_paths(["media/photo.jpg"])[0]["entity_id"] == photo["id"]
assert case.page_media_items()["items"][0]["entity_id"] in (photo["id"], None)
+
+
+def test_the_index_says_how_each_file_came_into_the_case(tmp_workspace):
+ """Read off the two indexed columns, keyed by entity, because the surfaces that
+ draw one hold ids. A row recording no route is left out rather than mapped to an
+ empty one: a caller has to be able to tell "came in by no stated route" from "the
+ index has never seen this entity"."""
+ from azimut.workspace import Case
+
+ case = Case.create("Origins")
+ frame = case.add_entity("media", "Frame", attrs={"path": "media/frame.png"}, by="inspect")
+ photo = case.add_entity("media", "Photo", attrs={"path": "media/photo.jpg"}, by="test")
+ mystery = case.add_entity("media", "Mystery", attrs={"path": "media/x.jpg"}, by="test")
+ case.upsert_media_item(
+ {
+ "path": "media/frame.png",
+ "filename": "frame.png",
+ "kind": "image",
+ "source": {"type": "inspect", "op": "frame", "from": "media/clip.mp4"},
+ },
+ entity_id=frame["id"],
+ )
+ case.upsert_media_item(
+ {
+ "path": "media/photo.jpg",
+ "filename": "photo.jpg",
+ "kind": "image",
+ "source": {"type": "upload"},
+ },
+ entity_id=photo["id"],
+ )
+ case.upsert_media_item(
+ {"path": "media/x.jpg", "filename": "x.jpg", "kind": "image"},
+ entity_id=mystery["id"],
+ )
+
+ found = case.media_origins([frame["id"], photo["id"], mystery["id"], "e_nope"])
+ assert found[frame["id"]] == {"type": "inspect", "op": "frame"}
+ # An upload has a route and no act: nothing composed it, so there is no `op`.
+ assert found[photo["id"]] == {"type": "upload"}
+ assert mystery["id"] not in found and "e_nope" not in found
+ assert case.media_origins([]) == {}
diff --git a/tests/test_tally.py b/tests/test_tally.py
new file mode 100644
index 0000000..d99d5d1
--- /dev/null
+++ b/tests/test_tally.py
@@ -0,0 +1,428 @@
+"""Adding up what the case's statements say (ONTOLOGY §2, "Counting a model").
+
+The Board lists one statement per row; this is the same narrowing added up, grouped
+by what each statement is ``about``. Every test here holds one of the four rules that
+make the number honest: a ruled-out statement is outside every sum, an absent count is
+not one, nothing is totalled across subjects, and the words are observations rather
+than objects.
+"""
+
+from azimut.engine import tally as tally_engine
+from azimut.workspace import Case
+
+
+def _case(client, name):
+ return client.post("/api/cases", json={"name": name}).json()["id"]
+
+
+def _entity(client, cid, type_, label, attrs=None):
+ res = client.post(
+ f"/api/cases/{cid}/entities",
+ json={"type": type_, "label": label, "attrs": attrs or {}},
+ )
+ assert res.status_code == 200, res.text
+ return res.json()
+
+
+def _link(client, cid, from_id, to_id, type_):
+ res = client.post(
+ f"/api/cases/{cid}/links",
+ json={"from_id": from_id, "to_id": to_id, "type": type_},
+ )
+ assert res.status_code == 200, res.text
+ return res.json()
+
+
+def _claim_about(client, cid, subject_id, label, attrs):
+ claim = _entity(client, cid, "claim", label, attrs)
+ _link(client, cid, claim["id"], subject_id, "about")
+ return claim
+
+
+def _tally(client, cid, **params):
+ res = client.get(f"/api/cases/{cid}/catalog/tally", params=params)
+ assert res.status_code == 200, res.text
+ return res.json()
+
+
+def _row(body, entity_id):
+ return next(row for row in body["rows"] if row["id"] == entity_id)
+
+
+def _condition(row, value):
+ return next(bucket for bucket in row["conditions"] if bucket["value"] == value)
+
+
+# -- what a row says ----------------------------------------------------------
+
+
+def test_statements_about_one_subject_add_up_per_condition(client):
+ cid = _case(client, "Adding up")
+ model = _entity(client, cid, "equipment-type", "T-72B3", {"category": "tank"})
+ _claim_about(client, cid, model["id"], "Two burnt out", {"count": 2, "condition": "destroyed"})
+ _claim_about(client, cid, model["id"], "Three more", {"count": 3, "condition": "destroyed"})
+ _claim_about(client, cid, model["id"], "One hit", {"count": 1, "condition": "damaged"})
+
+ body = _tally(client, cid)
+ row = _row(body, model["id"])
+
+ assert row["label"] == "T-72B3"
+ assert row["type"] == "equipment-type"
+ assert row["total"] == 6
+ assert row["statements"] == 3
+ assert row["counted"] == 3
+ assert _condition(row, "destroyed") == {
+ "value": "destroyed", "total": 5, "statements": 2, "counted": 2,
+ }
+ assert _condition(row, "damaged")["total"] == 1
+
+
+def test_the_biggest_number_reads_first(client):
+ cid = _case(client, "Ordering")
+ few = _entity(client, cid, "equipment-type", "BMP-2")
+ many = _entity(client, cid, "equipment-type", "T-72B3")
+ _claim_about(client, cid, few["id"], "One", {"count": 1, "condition": "destroyed"})
+ _claim_about(client, cid, many["id"], "Nine", {"count": 9, "condition": "destroyed"})
+
+ assert [row["label"] for row in _tally(client, cid)["rows"]] == ["T-72B3", "BMP-2"]
+
+
+def test_the_reading_is_not_only_for_models(client):
+ """``about`` reaches every subject family, so the addition does too."""
+ cid = _case(client, "Any subject")
+ person = _entity(client, cid, "person", "The driver")
+ _claim_about(client, cid, person["id"], "Seen twice", {"count": 2})
+
+ row = _row(_tally(client, cid), person["id"])
+
+ assert row["type"] == "person"
+ assert row["total"] == 2
+
+
+# -- a statement ruled out is outside every sum -------------------------------
+
+
+def test_a_ruled_out_statement_is_counted_apart_and_never_summed(client):
+ cid = _case(client, "Ruled out")
+ model = _entity(client, cid, "equipment-type", "T-72B3")
+ _claim_about(
+ client, cid, model["id"], "Held", {"count": 2, "condition": "destroyed", "confidence": "probable"},
+ )
+ _claim_about(
+ client, cid, model["id"], "Dead", {"count": 5, "condition": "destroyed", "confidence": "refuted"},
+ )
+
+ row = _row(_tally(client, cid), model["id"])
+
+ assert row["total"] == 2
+ assert row["statements"] == 1
+ assert row["refuted"] == 1
+ assert _condition(row, "destroyed")["statements"] == 1
+ assert [level["value"] for level in row["confidence"]] == ["probable"]
+
+
+def test_a_subject_holding_only_ruled_out_statements_still_has_a_row(client):
+ """Eliminating a candidate is work the case keeps, so it is reported, not dropped."""
+ cid = _case(client, "All eliminated")
+ model = _entity(client, cid, "equipment-type", "T-90M")
+ _claim_about(client, cid, model["id"], "No", {"count": 4, "confidence": "refuted"})
+
+ row = _row(_tally(client, cid), model["id"])
+
+ assert row["refuted"] == 1
+ assert row["total"] == 0
+ assert row["statements"] == 0
+ assert row["conditions"] == []
+
+
+# -- an absent count is not one ----------------------------------------------
+
+
+def test_a_statement_without_a_count_is_seen_and_not_counted(client):
+ cid = _case(client, "Seen")
+ model = _entity(client, cid, "equipment-type", "T-72B3")
+ _claim_about(client, cid, model["id"], "Two", {"count": 2, "condition": "destroyed"})
+ _claim_about(client, cid, model["id"], "Some", {"condition": "destroyed"})
+
+ row = _row(_tally(client, cid), model["id"])
+
+ assert row["total"] == 2
+ assert row["statements"] == 2
+ assert row["counted"] == 1
+ assert _condition(row, "destroyed") == {
+ "value": "destroyed", "total": 2, "statements": 2, "counted": 1,
+ }
+
+
+def test_an_unstated_condition_is_its_own_bucket_and_reads_last(client):
+ cid = _case(client, "Unstated")
+ model = _entity(client, cid, "equipment-type", "T-72B3")
+ _claim_about(client, cid, model["id"], "Plain", {"count": 1})
+ _claim_about(client, cid, model["id"], "Wrecked", {"count": 1, "condition": "destroyed"})
+
+ row = _row(_tally(client, cid), model["id"])
+
+ assert [bucket["value"] for bucket in row["conditions"]] == ["destroyed", ""]
+
+
+def test_a_count_that_is_not_a_whole_number_is_read_as_no_count(client):
+ """The field is validated on the way in, so a value past it is not one to guess at."""
+ assert tally_engine._whole(3) == 3
+ assert tally_engine._whole("3") == 3
+ assert tally_engine._whole(3.0) == 3
+ assert tally_engine._whole(2.5) is None
+ assert tally_engine._whole(0) is None
+ assert tally_engine._whole(-1) is None
+ assert tally_engine._whole(True) is None
+ assert tally_engine._whole(None) is None
+ assert tally_engine._whole("") is None
+ assert tally_engine._whole("two") is None
+
+
+def test_a_count_that_is_not_finite_is_read_as_no_count(client):
+ """A case written somewhere else must not take the reading down with it.
+
+ The validator refuses both spellings, so these only arrive from an import or a
+ database edited by hand — and there the answer is *not counted*, not a failure
+ that costs the analyst every other number on the screen.
+ """
+ for value in ("inf", "-inf", "nan", "1e400", float("inf"), float("nan")):
+ assert tally_engine._whole(value) is None
+
+
+# -- nothing is totalled across subjects --------------------------------------
+
+
+def test_one_statement_about_two_subjects_lands_in_both_rows(client):
+ """And there is no grand total, which is exactly why: it would spend it twice."""
+ cid = _case(client, "Two subjects")
+ first = _entity(client, cid, "equipment-type", "T-72B3")
+ second = _entity(client, cid, "equipment-type", "BMP-2")
+ claim = _entity(client, cid, "claim", "Both", {"count": 2, "condition": "destroyed"})
+ _link(client, cid, claim["id"], first["id"], "about")
+ _link(client, cid, claim["id"], second["id"], "about")
+
+ body = _tally(client, cid)
+
+ assert _row(body, first["id"])["total"] == 2
+ assert _row(body, second["id"])["total"] == 2
+ assert body["read"] == 1
+ assert "total" not in body
+
+
+def test_a_statement_about_nothing_is_reported_rather_than_ignored(client):
+ cid = _case(client, "About nothing")
+ model = _entity(client, cid, "equipment-type", "T-72B3")
+ _claim_about(client, cid, model["id"], "Counted", {"count": 2})
+ _entity(client, cid, "claim", "Floating", {"count": 9})
+
+ body = _tally(client, cid)
+
+ assert body["unattributed"] == 1
+ assert body["read"] == 2
+ assert [row["id"] for row in body["rows"]] == [model["id"]]
+
+
+def test_only_about_groups_a_statement(client):
+ """``at`` and ``cites`` say where and on what, never what it counts."""
+ cid = _case(client, "Other connectors")
+ model = _entity(client, cid, "equipment-type", "T-72B3")
+ place = _entity(client, cid, "place", "Crossroads", {"lat": 50.4, "lon": 30.5})
+ claim = _entity(client, cid, "claim", "Two there", {"count": 2, "condition": "destroyed"})
+ _link(client, cid, claim["id"], model["id"], "about")
+ _link(client, cid, claim["id"], place["id"], "at")
+
+ body = _tally(client, cid)
+
+ assert [row["id"] for row in body["rows"]] == [model["id"]]
+
+
+# -- it answers the narrowing the analyst set ---------------------------------
+
+
+def test_the_filters_are_the_ones_the_board_already_sets(client):
+ cid = _case(client, "Narrowed")
+ model = _entity(client, cid, "equipment-type", "T-72B3")
+ _claim_about(
+ client, cid, model["id"], "Sure", {"count": 2, "condition": "destroyed", "confidence": "certain"},
+ )
+ _claim_about(
+ client, cid, model["id"], "Maybe", {"count": 7, "condition": "destroyed", "confidence": "possible"},
+ )
+
+ whole = _tally(client, cid)
+ narrowed = _tally(client, cid, attr="confidence", value="certain")
+
+ assert _row(whole, model["id"])["total"] == 9
+ assert _row(narrowed, model["id"])["total"] == 2
+ assert narrowed["read"] == 1
+
+
+def test_a_type_chip_narrows_the_reading_and_never_widens_it(client):
+ cid = _case(client, "Type chip")
+ model = _entity(client, cid, "equipment-type", "T-72B3")
+ _claim_about(client, cid, model["id"], "Two", {"count": 2})
+
+ assert _tally(client, cid, type="claim")["rows"]
+ assert _tally(client, cid, type="claim,media")["read"] == 1
+ empty = _tally(client, cid, type="media")
+ assert empty["rows"] == []
+ assert empty["read"] == 0
+ assert empty["matched"] == 0
+
+
+def test_a_case_with_no_statement_answers_with_nothing(client):
+ cid = _case(client, "Quiet")
+ _entity(client, cid, "equipment-type", "T-72B3")
+
+ body = _tally(client, cid)
+
+ assert body == {
+ "rows": [], "read": 0, "matched": 0, "truncated": False, "unattributed": 0,
+ }
+
+
+# -- whether adding up would draw anything ------------------------------------
+
+
+def _countable(client, cid):
+ return client.get(f"/api/cases/{cid}/catalog/summary").json()["countable"]
+
+
+def test_a_statement_counting_something_about_a_subject_is_countable(client):
+ cid = _case(client, "Countable")
+ model = _entity(client, cid, "equipment-type", "T-72B3")
+ assert _countable(client, cid) == 0
+
+ _claim_about(client, cid, model["id"], "Two", {"count": 2, "condition": "destroyed"})
+
+ assert _countable(client, cid) == 1
+
+
+def test_a_statement_with_no_number_draws_no_line_and_is_not_counted(client):
+ """*Seen, not counted* is an answer, and it is not a row of a total."""
+ cid = _case(client, "No number")
+ model = _entity(client, cid, "equipment-type", "T-72B3")
+ _claim_about(client, cid, model["id"], "Seen", {"condition": "destroyed"})
+
+ assert _countable(client, cid) == 0
+
+
+def test_a_statement_about_nothing_draws_no_line_either(client):
+ cid = _case(client, "About nothing")
+ _entity(client, cid, "claim", "Floating", {"count": 9})
+
+ assert _countable(client, cid) == 0
+
+
+def test_a_count_that_is_not_a_number_never_reaches_the_case(client):
+ """So the only shapes the reading meets are a number or nothing at all."""
+ cid = _case(client, "Not a number")
+ refused = client.post(
+ f"/api/cases/{cid}/entities",
+ json={"type": "claim", "label": "Words", "attrs": {"count": "a few"}},
+ )
+
+ assert refused.status_code == 400
+ assert "must be a number" in refused.text
+ assert _countable(client, cid) == 0
+
+
+def test_only_about_makes_a_statement_countable(client):
+ cid = _case(client, "At only")
+ place = _entity(client, cid, "place", "Crossroads", {"lat": 50.4, "lon": 30.5})
+ claim = _entity(client, cid, "claim", "Two there", {"count": 2})
+ _link(client, cid, claim["id"], place["id"], "at")
+
+ assert _countable(client, cid) == 0
+
+
+# -- one subject, read where that subject is ----------------------------------
+
+
+def _subject_tally(client, cid, entity_id):
+ res = client.get(f"/api/cases/{cid}/entities/{entity_id}/tally")
+ assert res.status_code == 200, res.text
+ return res.json()
+
+
+def test_a_subject_adds_up_the_statements_pointing_at_it(client):
+ cid = _case(client, "One subject")
+ model = _entity(client, cid, "equipment-type", "T-72B3")
+ _claim_about(client, cid, model["id"], "Two", {"count": 2, "condition": "destroyed"})
+ _claim_about(client, cid, model["id"], "One", {"count": 1, "condition": "damaged"})
+ _claim_about(client, cid, model["id"], "Seen", {"condition": "destroyed"})
+ _claim_about(client, cid, model["id"], "No", {"count": 9, "confidence": "refuted"})
+
+ row = _subject_tally(client, cid, model["id"])
+
+ assert row["label"] == "T-72B3"
+ assert row["total"] == 3
+ assert row["statements"] == 3
+ assert row["counted"] == 2
+ assert row["refuted"] == 1
+ assert _condition(row, "destroyed") == {
+ "value": "destroyed", "total": 2, "statements": 2, "counted": 1,
+ }
+ assert row["read"] == 4
+
+
+def test_the_panel_and_the_board_cannot_drift(client):
+ """One implementation of *what may enter a sum*, or the case holds two totals."""
+ cid = _case(client, "Same rules")
+ model = _entity(client, cid, "equipment-type", "T-72B3")
+ _claim_about(client, cid, model["id"], "Two", {"count": 2, "condition": "destroyed"})
+ _claim_about(client, cid, model["id"], "Dead", {"count": 5, "confidence": "refuted"})
+ _claim_about(client, cid, model["id"], "Seen", {"condition": "destroyed"})
+
+ board = _row(_tally(client, cid), model["id"])
+ panel = _subject_tally(client, cid, model["id"])
+
+ for key in ("total", "statements", "counted", "refuted", "conditions", "confidence"):
+ assert panel[key] == board[key], key
+
+
+def test_the_panel_ignores_a_narrowing_set_on_another_screen(client):
+ """It is a fact about the row, so it answers over the whole case."""
+ cid = _case(client, "Unnarrowed")
+ model = _entity(client, cid, "equipment-type", "T-72B3")
+ _claim_about(
+ client, cid, model["id"], "Sure", {"count": 2, "confidence": "certain"},
+ )
+ _claim_about(
+ client, cid, model["id"], "Maybe", {"count": 7, "confidence": "possible"},
+ )
+
+ assert _subject_tally(client, cid, model["id"])["total"] == 9
+
+
+def test_only_about_counts_toward_a_subject(client):
+ """A place reached by ``at`` and a source reached by ``cites`` say no numbers."""
+ cid = _case(client, "Not about")
+ place = _entity(client, cid, "place", "Crossroads", {"lat": 50.4, "lon": 30.5})
+ claim = _entity(client, cid, "claim", "Two there", {"count": 2, "condition": "destroyed"})
+ _link(client, cid, claim["id"], place["id"], "at")
+
+ assert client.get(f"/api/cases/{cid}/entities/{place['id']}/tally").status_code == 404
+
+
+def test_an_entity_no_statement_is_about_answers_404(client):
+ cid = _case(client, "Nothing stated")
+ model = _entity(client, cid, "equipment-type", "T-72B3")
+
+ assert client.get(f"/api/cases/{cid}/entities/{model['id']}/tally").status_code == 404
+ assert client.get(f"/api/cases/{cid}/entities/e_missing/tally").status_code == 404
+
+
+def test_the_cut_is_reported_rather_than_applied_quietly(client):
+ cid = _case(client, "Cut")
+ model = _entity(client, cid, "equipment-type", "T-72B3")
+ for index in range(3):
+ _claim_about(client, cid, model["id"], f"Statement {index}", {"count": 1})
+
+ body = tally_engine.tally(Case.open(cid), limit=2)
+
+ assert body["read"] == 2
+ assert body["matched"] == 3
+ assert body["truncated"] is True
+ assert _row(body, model["id"])["total"] == 2
diff --git a/tests/test_temporal.py b/tests/test_temporal.py
new file mode 100644
index 0000000..c848226
--- /dev/null
+++ b/tests/test_temporal.py
@@ -0,0 +1,178 @@
+"""The deliberately small temporal syntax accepted by Azimut.
+
+The contract borrows reduced dates, intervals and qualifiers from EDTF, and exact
+timestamps from ISO 8601. It does not claim full EDTF support: accepting a form in
+this file means the parser can derive honest search bounds from it.
+"""
+
+import pytest
+
+from azimut.engine.temporal import TemporalError, parse_temporal
+
+
+ ("raw", "earliest", "latest", "precision", "zone"),
+ [
+ ("2026", "2026-01-01T00:00:00.000000Z", "2027-01-01T00:00:00.000000Z", "year", "date-only"),
+ ("2026-08", "2026-08-01T00:00:00.000000Z", "2026-09-01T00:00:00.000000Z", "month", "date-only"),
+ ("2024-02-29", "2024-02-29T00:00:00.000000Z", "2024-03-01T00:00:00.000000Z", "day", "date-only"),
+ (
+ "2026-08-11T16:40:00Z",
+ "2026-08-11T16:40:00.000000Z",
+ "2026-08-11T16:40:01.000000Z",
+ "second",
+ "utc",
+ ),
+ (
+ "2026-08-11T18:40:00+02:00",
+ "2026-08-11T16:40:00.000000Z",
+ "2026-08-11T16:40:01.000000Z",
+ "second",
+ "offset",
+ ),
+ (
+ "2026-08-11T16:40:00.123Z",
+ "2026-08-11T16:40:00.123000Z",
+ "2026-08-11T16:40:00.124000Z",
+ "subsecond",
+ "utc",
+ ),
+ ],
+)
+def test_a_supported_value_has_exclusive_search_bounds(
+ raw, earliest, latest, precision, zone
+):
+ value = parse_temporal(raw)
+
+ assert value.raw == raw
+ assert value.shape == "instant"
+ assert value.earliest == earliest
+ assert value.latest == latest
+ assert value.precision == precision
+ assert value.zone == zone
+ assert value.sortable is True
+ assert value.uncertain is False
+ assert value.approximate is False
+ assert value.start.raw == raw
+ assert value.end is None
+
+
+def test_a_local_time_is_kept_without_being_falsely_put_on_the_utc_axis():
+ value = parse_temporal("2026-08-11T18:40:00")
+
+ assert value.raw == "2026-08-11T18:40:00"
+ assert value.precision == "second"
+ assert value.zone == "local"
+ assert value.sortable is False
+ assert value.earliest is None
+ assert value.latest is None
+
+
+ ("raw", "uncertain", "approximate"),
+ [
+ ("2026-08~", False, True),
+ ("2026-08?", True, False),
+ ("2026-08%", True, True),
+ ],
+)
+def test_edtf_qualifiers_are_retained_without_inventing_wider_bounds(
+ raw, uncertain, approximate
+):
+ value = parse_temporal(raw)
+
+ assert value.raw == raw
+ assert value.earliest == "2026-08-01T00:00:00.000000Z"
+ assert value.latest == "2026-09-01T00:00:00.000000Z"
+ assert value.uncertain is uncertain
+ assert value.approximate is approximate
+ assert value.start.uncertain is uncertain
+ assert value.start.approximate is approximate
+
+
+def test_a_date_interval_uses_the_lower_start_and_exclusive_upper_end():
+ value = parse_temporal("2026-08/2026-10")
+
+ assert value.shape == "interval"
+ assert value.earliest == "2026-08-01T00:00:00.000000Z"
+ assert value.latest == "2026-11-01T00:00:00.000000Z"
+ assert value.precision == "month"
+ assert value.zone == "date-only"
+ assert value.sortable is True
+ assert value.start.raw == "2026-08"
+ assert value.end is not None
+ assert value.end.raw == "2026-10"
+
+
+def test_an_interval_keeps_each_ends_qualifier_and_reports_mixed_precision():
+ value = parse_temporal("2026~/2027-02?")
+
+ assert value.precision == "mixed"
+ assert value.approximate is True
+ assert value.uncertain is True
+ assert value.start.approximate is True
+ assert value.start.uncertain is False
+ assert value.end is not None
+ assert value.end.approximate is False
+ assert value.end.uncertain is True
+
+
+def test_a_timestamp_interval_uses_exact_zoned_bounds():
+ value = parse_temporal(
+ "2026-08-11T18:15:00+02:00/2026-08-11T19:40:00+02:00"
+ )
+
+ assert value.shape == "interval"
+ assert value.earliest == "2026-08-11T16:15:00.000000Z"
+ assert value.latest == "2026-08-11T17:40:00.000000Z"
+ assert value.precision == "second"
+ assert value.zone == "offset"
+ assert value.sortable is True
+
+
+ "raw",
+ [
+ "",
+ " 2026",
+ "2026 ",
+ "0000",
+ "20260",
+ "2026-8",
+ "2026-13",
+ "2026-08-1",
+ "2026-02-29",
+ "2026-08-11T18:40",
+ "2026-08-11T24:00:00Z",
+ "2026-08-11T18:40:60Z",
+ "2026-08-11T18:40:00z",
+ "2026-08-11T18:40:00+02",
+ "2026-08-11T18:40:00+14:01",
+ "2026-08-11T18:40:00+14:30",
+ "2026-08-11T18:40:00+15:00",
+ "2026-08-11T18:40:00.1234567Z",
+ "2026-08-11T18:40:00Z~",
+ "2026-08-11T18:40:00Z?",
+ "2026/",
+ "/2026",
+ "../2026",
+ "2026/..",
+ "2026/2025",
+ "2026-08-11T18:00:00/2026-08-11T19:00:00",
+ "2026-08-11/2026-08-11T19:00:00Z",
+ "2026-08-11T19:00:00Z/2026-08-11T18:00:00Z",
+ "2026-21",
+ "-0044",
+ "202X",
+ "[2025,2026]",
+ ],
+)
+def test_unsupported_or_ambiguous_forms_are_refused(raw):
+ with pytest.raises(TemporalError):
+ parse_temporal(raw)
+
+
[email protected]("raw", [None, 2026, True, [], {}])
+def test_a_temporal_value_is_always_text(raw):
+ with pytest.raises(TemporalError):
+ parse_temporal(raw)
diff --git a/tests/test_timeline.py b/tests/test_timeline.py
new file mode 100644
index 0000000..bb4632c
--- /dev/null
+++ b/tests/test_timeline.py
@@ -0,0 +1,241 @@
+"""Derived temporal rows: Claims, media metadata and rebuild semantics."""
+
+import pytest
+
+from azimut.engine import timeline
+from azimut.sqlite_backend import SqliteCase, convert_json_to_sqlite
+from azimut.workspace import CaseError
+
+
+def test_a_dated_claim_keeps_raw_syntax_and_normalized_bounds():
+ rows = timeline.project_entity(
+ {
+ "id": "e_claim",
+ "type": "claim",
+ "label": "A vehicle was present",
+ "attrs": {
+ "when": "2026-08~",
+ "time_role": "observed",
+ "confidence": "probable",
+ },
+ "provenance": {
+ "by": "user",
+ "at": "2026-08-11T10:00:00Z",
+ "status": "confirmed",
+ },
+ }
+ )
+
+ assert [row.id for row in rows] == ["temporal:claim:e_claim"]
+ assert rows[0].raw == "2026-08~"
+ assert rows[0].earliest == "2026-08-01T00:00:00.000000Z"
+ assert rows[0].latest == "2026-09-01T00:00:00.000000Z"
+ assert rows[0].approximate is True
+ assert rows[0].time_role == "observed"
+
+
+def test_an_undated_claim_is_projected_for_the_undated_group():
+ row = timeline.project_entity(
+ {
+ "id": "e_claim",
+ "type": "claim",
+ "attrs": {},
+ "provenance": {"status": "suggested", "at": "2026-08-11T10:00:00Z"},
+ }
+ )[0]
+
+ assert row.raw is None
+ assert row.earliest is None
+ assert row.sortable is False
+ assert row.status == "suggested"
+
+
+def test_a_local_media_time_is_known_but_not_invented_on_the_utc_axis():
+ row = timeline.project_media(
+ {"taken_at": "2021-04-24T14:52:29"},
+ "e_media",
+ )[0]
+
+ assert row.raw == "2021-04-24T14:52:29"
+ assert row.zone == "local"
+ assert row.earliest is None
+ assert row.sortable is False
+
+
+def test_media_dates_keep_world_time_separate_from_case_activity():
+ rows = timeline.project_media(
+ {
+ "taken_at": "2024-02-03T10:11:12Z",
+ "added_at": "2026-08-11T10:00:00Z",
+ "source": {
+ "upload_date": "20240204",
+ "imagery_date": "2024-02",
+ "fetched_at": "2026-08-11T09:59:00+00:00",
+ },
+ },
+ "e_media",
+ )
+ by_kind = {row.kind: row for row in rows}
+
+ assert by_kind["captured"].category == "media"
+ assert by_kind["published"].raw == "2024-02-04"
+ assert by_kind["imagery"].category == "media"
+ assert by_kind["collected"].category == "case_activity"
+ assert by_kind["added"].category == "case_activity"
+
+
+def test_old_malformed_time_stays_visible_without_blocking_a_rebuild():
+ row = timeline.project_entity(
+ {
+ "id": "e_old",
+ "type": "claim",
+ "attrs": {"when": "late summer"},
+ "provenance": {"at": "2026-08-11T10:00:00Z", "status": "confirmed"},
+ }
+ )[0]
+
+ assert row.raw == "late summer"
+ assert row.earliest is None
+ assert row.parse_error
+
+
+def test_large_projection_stays_bounded_and_pages_without_duplicates(tmp_path):
+ store = SqliteCase.create(tmp_path / "case.db", name="Large timeline")
+ for index in range(205):
+ store.add_entity(
+ "claim",
+ f"Event {index:03d}",
+ {"when": f"2026-{index % 12 + 1:02d}-{index % 28 + 1:02d}"},
+ by="user",
+ )
+
+ labels = []
+ cursor = None
+ while True:
+ page = store.timeline_page(
+ categories=["statement"], limit=37, cursor=cursor, bucket="year"
+ )
+ labels.extend(item["label"] for item in page["items"])
+ cursor = page["next_cursor"]
+ if cursor is None:
+ break
+
+ assert len(labels) == 205
+ assert len(set(labels)) == 205
+ assert page["total"] == 205
+ assert page["buckets"] == [
+ {
+ "start": "2026",
+ "count": 205,
+ "categories": {"statement": 205},
+ "first": "2026-01-01T00:00:00.000000Z",
+ "last": "2026-12-29T00:00:00.000000Z",
+ }
+ ]
+
+
+def _lopsided_case(tmp_path):
+ """230 rows in January and 40 in July: a page off the front never reaches July."""
+ store = SqliteCase.create(tmp_path / "case.db", name="Lopsided timeline")
+ for index in range(230):
+ store.add_entity(
+ "claim", f"Jan {index:03d}", {"when": f"2026-01-{index % 28 + 1:02d}"}, by="user"
+ )
+ for index in range(40):
+ store.add_entity(
+ "claim", f"Jul {index:03d}", {"when": f"2026-07-{index % 28 + 1:02d}"}, by="user"
+ )
+ return store
+
+
+def test_a_spread_page_samples_the_whole_window_where_a_plain_one_takes_its_front(tmp_path):
+ store = _lopsided_case(tmp_path)
+
+ front = store.timeline_page(categories=["statement"], limit=100)
+ spread = store.timeline_page(categories=["statement"], limit=100, spread=True)
+
+ assert front["total"] == spread["total"] == 270
+ assert {item["earliest"][:7] for item in front["items"]} == {"2026-01"}
+ # 270 rows over a 100-row page is one row in three, so the sample keeps January's
+ # share of the case rather than flattening it into July's.
+ assert len(spread["items"]) == 90
+ assert {item["earliest"][:7] for item in spread["items"]} == {"2026-01", "2026-07"}
+ assert sum(item["earliest"][:7] == "2026-07" for item in spread["items"]) == 13
+
+
+def test_spread_pages_partition_the_window_without_a_repeat_or_a_gap(tmp_path):
+ store = _lopsided_case(tmp_path)
+
+ labels = []
+ pages = 0
+ cursor = None
+ while True:
+ page = store.timeline_page(
+ categories=["statement"], limit=100, cursor=cursor, spread=True
+ )
+ labels.extend(item["label"] for item in page["items"])
+ pages += 1
+ cursor = page["next_cursor"]
+ if cursor is None:
+ break
+
+ assert pages == 3
+ assert len(labels) == len(set(labels)) == 270
+
+
+def test_a_window_that_fits_the_limit_is_served_whole_and_asks_for_nothing_more(tmp_path):
+ store = _lopsided_case(tmp_path)
+
+ page = store.timeline_page(
+ categories=["statement"], limit=200, spread=True, since="2026-07"
+ )
+
+ # Under the limit there is nothing to sample, so the window arrives in one page.
+ assert page["total"] == 40
+ assert len(page["items"]) == 40
+ assert page["next_cursor"] is None
+
+
+def test_a_cursor_from_the_other_kind_of_read_is_refused(tmp_path):
+ store = _lopsided_case(tmp_path)
+
+ front = store.timeline_page(categories=["statement"], limit=100)
+ spread = store.timeline_page(categories=["statement"], limit=100, spread=True)
+
+ with pytest.raises(CaseError):
+ store.timeline_page(
+ categories=["statement"], limit=100, cursor=front["next_cursor"], spread=True
+ )
+ with pytest.raises(CaseError):
+ store.timeline_page(categories=["statement"], limit=100, cursor=spread["next_cursor"])
+
+
+def test_json_conversion_builds_the_projection_with_the_graph(tmp_path):
+ db = tmp_path / "case.db"
+ convert_json_to_sqlite(
+ {
+ "name": "Legacy",
+ "created_at": "2026-01-01T00:00:00Z",
+ "updated_at": "2026-01-02T00:00:00Z",
+ "folders": [],
+ "links": [],
+ "entities": [
+ {
+ "id": "e_claim",
+ "type": "claim",
+ "label": "Existing observation",
+ "attrs": {"when": "2026-08"},
+ "provenance": {
+ "by": "user",
+ "at": "2026-08-11T10:00:00Z",
+ "status": "confirmed",
+ },
+ }
+ ],
+ },
+ db,
+ )
+
+ item = SqliteCase.open(db).timeline_page(categories=["statement"])["items"][0]
+ assert item["owner_id"] == "e_claim"
+ assert item["earliest"] == "2026-08-01T00:00:00.000000Z"
diff --git a/tests/test_timeline_api.py b/tests/test_timeline_api.py
new file mode 100644
index 0000000..5fbd421
--- /dev/null
+++ b/tests/test_timeline_api.py
@@ -0,0 +1,669 @@
+"""Public Time and Timeline API, including atomic Temporal Claim writes."""
+
+from __future__ import annotations
+
+import json
+import sqlite3
+from contextlib import closing
+
+import pytest
+from fastapi import HTTPException
+
+from azimut.api.cases import timeline
+from azimut.sqlite_backend import SQLITE_SCHEMA
+from azimut.workspace import Case
+
+
+def _case(client, name="Timeline"):
+ return client.post("/api/cases", json={"name": name}).json()["id"]
+
+
+def _entity(client, case_id, type_, label, attrs=None):
+ response = client.post(
+ f"/api/cases/{case_id}/entities",
+ json={"type": type_, "label": label, "attrs": attrs or {}},
+ )
+ assert response.status_code == 200, response.text
+ return response.json()
+
+
+def test_atomic_create_returns_a_normalized_claim_and_connectors(client):
+ case_id = _case(client)
+ subject = _entity(client, case_id, "ip", "203.0.113.42")
+ source = _entity(client, case_id, "bookmark", "Access log", {"url": "https://x.test"})
+
+ created = client.post(
+ f"/api/cases/{case_id}/timeline/claims",
+ json={
+ "statement": "This address appeared in the access log",
+ "when": "2026-08-11T10:32:14Z",
+ "time_role": "observed",
+ "confidence": "probable",
+ "about": [subject["id"]],
+ "cites": [source["id"]],
+ },
+ )
+
+ assert created.status_code == 200, created.text
+ body = created.json()
+ assert body["entity"]["attrs"]["when"] == "2026-08-11T10:32:14Z"
+ assert {(link["type"], link["to"]) for link in body["links"]} == {
+ ("about", subject["id"]),
+ ("cites", source["id"]),
+ }
+ assert body["temporal"]["earliest"] == "2026-08-11T10:32:14.000000Z"
+ assert body["temporal"]["latest"] == "2026-08-11T10:32:15.000000Z"
+ assert body["temporal"]["subjects"] == [subject["id"]]
+ assert body["temporal"]["sources"] == [source["id"]]
+
+
+def test_a_bad_connector_rolls_back_the_whole_claim(client):
+ case_id = _case(client)
+ person = _entity(client, case_id, "person", "Witness")
+
+ refused = client.post(
+ f"/api/cases/{case_id}/timeline/claims",
+ json={"statement": "Invalid evidence", "cites": [person["id"]]},
+ )
+
+ assert refused.status_code == 400
+ entities = Case.open(case_id).list_entities()
+ assert [entity["type"] for entity in entities] == ["person"]
+
+
+def test_subsecond_bounds_sort_filter_and_measure_the_extent_chronologically(client):
+ case_id = _case(client, "Subsecond order")
+ for statement, when in (
+ ("Whole second", "2026-08-11T10:32:14Z"),
+ ("One half", "2026-08-11T10:32:14.5Z"),
+ ("Five decimal places", "2026-08-11T10:32:14.50001Z"),
+ ):
+ response = client.post(
+ f"/api/cases/{case_id}/timeline/claims",
+ json={"statement": statement, "when": when},
+ )
+ assert response.status_code == 200, response.text
+
+ page = client.get(
+ f"/api/cases/{case_id}/timeline",
+ params={"category": "statement", "include_undated": "false"},
+ ).json()
+
+ assert [item["label"] for item in page["items"]] == [
+ "Whole second",
+ "One half",
+ "Five decimal places",
+ ]
+ assert [item["earliest"] for item in page["items"]] == [
+ "2026-08-11T10:32:14.000000Z",
+ "2026-08-11T10:32:14.500000Z",
+ "2026-08-11T10:32:14.500010Z",
+ ]
+ assert page["extent"] == {
+ "from": "2026-08-11T10:32:14.000000Z",
+ "to": "2026-08-11T10:32:15.000000Z",
+ }
+
+ narrow = client.get(
+ f"/api/cases/{case_id}/timeline",
+ params={
+ "from": "2026-08-11T10:32:14.500005Z",
+ "to": "2026-08-11T10:32:14.500009Z",
+ "category": "statement",
+ "include_undated": "false",
+ },
+ ).json()
+ assert [item["label"] for item in narrow["items"]] == [
+ "Whole second",
+ "One half",
+ ]
+
+
+def test_timeline_filters_intersections_categories_entities_and_undated(client):
+ case_id = _case(client)
+ subject = _entity(client, case_id, "person", "Witness")
+ other = _entity(client, case_id, "person", "Other")
+ for statement, when, about in (
+ ("During August", "2026-08/2026-09", subject["id"]),
+ ("One day elsewhere", "2026-07-01", other["id"]),
+ ("Not dated yet", None, subject["id"]),
+ ):
+ payload = {"statement": statement, "about": [about]}
+ if when:
+ payload["when"] = when
+ response = client.post(f"/api/cases/{case_id}/timeline/claims", json=payload)
+ assert response.status_code == 200, response.text
+
+ page = client.get(
+ f"/api/cases/{case_id}/timeline",
+ params={
+ "from": "2026-08-15",
+ "to": "2026-08-20",
+ "entity": subject["id"],
+ "category": "statement",
+ "include_undated": "true",
+ "bucket": "month",
+ },
+ )
+
+ assert page.status_code == 200, page.text
+ body = page.json()
+ assert [item["label"] for item in body["items"]] == ["During August", "Not dated yet"]
+ assert body["undated"] == 1
+ assert body["unplaced"] == 0
+ # A bucket carries the span of its own entries beside the count: the overview
+ # opens a clicked bar onto what it holds rather than onto the whole month.
+ assert body["buckets"] == [
+ {
+ "start": "2026-08",
+ "count": 1,
+ "categories": {"statement": 1},
+ "first": "2026-08-01T00:00:00.000000Z",
+ "last": "2026-10-01T00:00:00.000000Z",
+ }
+ ]
+ assert body["window"] == {
+ "from": "2026-08-15T00:00:00.000000Z",
+ "to": "2026-08-21T00:00:00.000000Z",
+ }
+ assert body["extent"] == {
+ "from": "2026-08-01T00:00:00.000000Z",
+ "to": "2026-10-01T00:00:00.000000Z",
+ }
+
+
+def test_local_time_is_counted_as_unplaced_instead_of_undated(client):
+ case_id = _case(client)
+ created = client.post(
+ f"/api/cases/{case_id}/timeline/claims",
+ json={"statement": "Local observation", "when": "2021-04-24T14:52:29"},
+ )
+ assert created.status_code == 200, created.text
+
+ body = client.get(
+ f"/api/cases/{case_id}/timeline",
+ params={"category": "statement", "include_undated": "true"},
+ ).json()
+ assert body["undated"] == 0
+ assert body["unplaced"] == 1
+ assert body["items"][0]["raw"] == "2021-04-24T14:52:29"
+ assert body["items"][0]["zone"] == "local"
+
+
+def test_timestamp_window_uses_the_given_second_as_its_upper_boundary(client):
+ case_id = _case(client)
+ for second in (0, 1):
+ response = client.post(
+ f"/api/cases/{case_id}/timeline/claims",
+ json={
+ "statement": f"Observation {second}",
+ "when": f"2026-08-12T10:00:{second:02d}Z",
+ },
+ )
+ assert response.status_code == 200, response.text
+
+ response = client.get(
+ f"/api/cases/{case_id}/timeline",
+ params={
+ "category": "statement",
+ "from": "2026-08-12T10:00:00Z",
+ "to": "2026-08-12T10:00:01Z",
+ },
+ )
+
+ assert response.status_code == 200, response.text
+ assert [item["label"] for item in response.json()["items"]] == ["Observation 0"]
+ assert response.json()["window"]["to"] == "2026-08-12T10:00:01.000000Z"
+
+
+def test_a_spread_read_reaches_the_far_end_of_a_lopsided_window(client):
+ case_id = _case(client)
+ for index in range(30):
+ _entity(client, case_id, "claim", f"Jan {index:02d}", {"when": f"2026-01-{index % 28 + 1:02d}"})
+ for index in range(5):
+ _entity(client, case_id, "claim", f"Jul {index:02d}", {"when": f"2026-07-{index + 1:02d}"})
+
+ params = {"category": "statement", "limit": 20}
+ front = client.get(f"/api/cases/{case_id}/timeline", params=params).json()
+ spread = client.get(
+ f"/api/cases/{case_id}/timeline", params={**params, "spread": "true"}
+ ).json()
+
+ assert front["total"] == spread["total"] == 35
+ assert {item["earliest"][:7] for item in front["items"]} == {"2026-01"}
+ assert {item["earliest"][:7] for item in spread["items"]} == {"2026-01", "2026-07"}
+
+ seen = list(spread["items"])
+ cursor = spread["next_cursor"]
+ while cursor:
+ page = client.get(
+ f"/api/cases/{case_id}/timeline",
+ params={**params, "spread": "true", "cursor": cursor},
+ ).json()
+ seen.extend(page["items"])
+ cursor = page["next_cursor"]
+ assert len({item["id"] for item in seen}) == 35
+
+
+def test_a_time_assessment_about_a_claim_explains_the_single_date_rule(client):
+ case_id = _case(client)
+ original = client.post(
+ f"/api/cases/{case_id}/timeline/claims",
+ json={"statement": "A vehicle crossed the gate", "when": "2026-08-12"},
+ ).json()["entity"]
+
+ response = client.post(
+ f"/api/cases/{case_id}/timeline/claims",
+ json={
+ "statement": "The crossing occurred later",
+ "when": "2026-08-13",
+ "about": [original["id"]],
+ },
+ )
+
+ assert response.status_code == 400
+ assert response.json()["detail"] == (
+ "A Claim has one date or range. Edit its date, or create a separate Claim."
+ )
+
+
+def test_timeline_uses_keyset_pagination(client):
+ case_id = _case(client)
+ for day in range(1, 6):
+ response = client.post(
+ f"/api/cases/{case_id}/timeline/claims",
+ json={"statement": f"Event {day}", "when": f"2026-08-{day:02d}"},
+ )
+ assert response.status_code == 200, response.text
+
+ first = client.get(
+ f"/api/cases/{case_id}/timeline",
+ params={"category": "statement", "limit": 2},
+ ).json()
+ second = client.get(
+ f"/api/cases/{case_id}/timeline",
+ params={"category": "statement", "limit": 2, "cursor": first["next_cursor"]},
+ ).json()
+
+ assert [item["label"] for item in first["items"]] == ["Event 1", "Event 2"]
+ assert [item["label"] for item in second["items"]] == ["Event 3", "Event 4"]
+ assert first["total"] == 5
+
+
+def test_update_delete_undo_and_rebuild_keep_the_projection_in_step(client):
+ case_id = _case(client)
+ subject = _entity(client, case_id, "person", "Witness")
+ created = client.post(
+ f"/api/cases/{case_id}/timeline/claims",
+ json={"statement": "First reading", "when": "2026-08", "about": [subject["id"]]},
+ ).json()
+ claim_id = created["entity"]["id"]
+
+ updated = client.patch(
+ f"/api/cases/{case_id}/timeline/claims/{claim_id}",
+ json={"statement": "Corrected reading", "when": "2026-09?", "about": []},
+ )
+ assert updated.status_code == 200, updated.text
+ assert updated.json()["temporal"]["raw"] == "2026-09?"
+ assert updated.json()["temporal"]["subjects"] == []
+
+ case = Case.open(case_id)
+ before = case.timeline_page(categories=["statement"])
+ assert case.rebuild_temporal_projection() >= before["total"]
+ assert case.timeline_page(categories=["statement"]) == before
+
+ deleted = client.delete(f"/api/cases/{case_id}/timeline/claims/{claim_id}").json()
+ assert case.timeline_page(categories=["statement"])["total"] == 0
+ restored = client.post(f"/api/cases/{case_id}/trash/{deleted['trash']}/restore")
+ assert restored.status_code == 200, restored.text
+ assert case.timeline_page(categories=["statement"])["items"][0]["raw"] == "2026-09?"
+
+
+def test_a_heavily_cited_claim_still_answers_with_its_own_row(client):
+ """The entity scope returns every statement resting on this one, ordered by
+ date — so the Claim being written can sit past the first page of its own
+ response, which used to fail a write that had already been committed."""
+ case_id = _case(client)
+ created = client.post(
+ f"/api/cases/{case_id}/timeline/claims",
+ json={"statement": "The convoy passed the bridge", "when": "2030-01-01"},
+ )
+ claim_id = created.json()["entity"]["id"]
+ case = Case.open(case_id)
+ for index in range(201):
+ case.save_temporal_claim(
+ entity_id=None,
+ label=f"Supporting reading {index:03d}",
+ attrs={"when": "2020-01-01"},
+ connectors={"cites": [claim_id]},
+ by="user",
+ )
+
+ updated = client.patch(
+ f"/api/cases/{case_id}/timeline/claims/{claim_id}", json={"when": "2030-02-02"}
+ )
+
+ assert updated.status_code == 200, updated.text
+ assert updated.json()["temporal"]["owner_id"] == claim_id
+ assert updated.json()["temporal"]["raw"] == "2030-02-02"
+
+
+def test_media_metadata_and_case_activity_are_separate_categories(client):
+ case_id = _case(client)
+ case = Case.open(case_id)
+ media = case.add_entity(
+ "media", "Clip", {"path": "media/clip.mp4", "kind": "video"}, by="user"
+ )
+ case.upsert_media_item(
+ {
+ "path": "media/clip.mp4",
+ "filename": "clip.mp4",
+ "kind": "video",
+ "taken_at": "2024-02-03T10:11:12Z",
+ "added_at": "2026-08-11T10:00:00Z",
+ "source": {"type": "download", "upload_date": "20240204"},
+ },
+ entity_id=media["id"],
+ )
+
+ default = client.get(f"/api/cases/{case_id}/timeline").json()
+ activity = client.get(
+ f"/api/cases/{case_id}/timeline", params={"category": "case_activity"}
+ ).json()
+
+ assert {item["kind"] for item in default["items"]} == {"captured", "published"}
+ assert [item["kind"] for item in activity["items"]] == ["added"]
+
+
+def test_schema_15_backfills_existing_claims_and_media(tmp_path):
+ db = tmp_path / "case.db"
+ from azimut.sqlite_backend import SqliteCase
+
+ store = SqliteCase.create(db, name="Migration")
+ claim = store.add_entity(
+ "claim", "Existing event", {"when": "2026-08-11"}, by="user"
+ )
+ media = store.add_entity(
+ "media", "Existing photo", {"path": "media/photo.jpg", "kind": "image"}, by="user"
+ )
+ store.upsert_media_item(
+ {
+ "path": "media/photo.jpg",
+ "filename": "photo.jpg",
+ "kind": "image",
+ "taken_at": "2024-02-03T10:11:12Z",
+ "added_at": "2026-08-11T10:00:00Z",
+ "source": {"type": "upload"},
+ },
+ entity_id=media["id"],
+ )
+ with closing(sqlite3.connect(db)) as conn, conn:
+ conn.execute("DROP TABLE temporal_items")
+ conn.execute("UPDATE meta SET value = '14' WHERE key = 'schema_version'")
+ conn.execute("DELETE FROM schema_migrations WHERE version >= 15")
+
+ reopened = SqliteCase.open(db)
+
+ assert SQLITE_SCHEMA >= 15, "the projection this test rewinds past is gone"
+ items = reopened.timeline_page(categories=["statement", "media"])["items"]
+ assert {(item["owner_id"], item["kind"]) for item in items} == {
+ (claim["id"], "claim"),
+ (media["id"], "captured"),
+ }
+
+
+def test_timeline_track_filters_through_named_claim_connectors(client):
+ case_id = _case(client, "Track query")
+ person = _entity(client, case_id, "person", "Witness")
+ place = _entity(client, case_id, "place", "North gate", {"lat": 1, "lon": 2})
+ source = _entity(
+ client, case_id, "bookmark", "Archived report", {"url": "https://example.test"}
+ )
+ first = client.post(
+ f"/api/cases/{case_id}/timeline/claims",
+ json={
+ "statement": "Witness reached the gate",
+ "when": "2026-08-12T10:00:00Z",
+ "about": [person["id"]],
+ "at": [place["id"]],
+ "cites": [source["id"]],
+ },
+ ).json()["temporal"]
+ client.post(
+ f"/api/cases/{case_id}/timeline/claims",
+ json={"statement": "Unrelated event", "when": "2026-08-12T11:00:00Z"},
+ )
+
+ people = client.get(
+ f"/api/cases/{case_id}/timeline",
+ params={
+ "category": "statement",
+ "track": json.dumps({"relation": "about", "terms": {"type": "person"}}),
+ },
+ )
+ assert people.status_code == 200, people.text
+ assert [item["id"] for item in people.json()["items"]] == [first["id"]]
+ assert people.json()["items"][0]["subject_entities"] == [
+ {"id": person["id"], "label": "Witness", "type": "person"}
+ ]
+
+ sourced = client.get(
+ f"/api/cases/{case_id}/timeline",
+ params={"category": "statement", "track": json.dumps({"relation": "source"})},
+ )
+ assert [item["id"] for item in sourced.json()["items"]] == [first["id"]]
+
+
+def test_timeline_track_can_filter_role_and_hide_one_entry(client):
+ case_id = _case(client, "Track role")
+ observed = client.post(
+ f"/api/cases/{case_id}/timeline/claims",
+ json={
+ "statement": "Observed event",
+ "when": "2026-08-12T10:00:00Z",
+ "time_role": "observed",
+ },
+ ).json()["temporal"]
+ client.post(
+ f"/api/cases/{case_id}/timeline/claims",
+ json={
+ "statement": "Occurred event",
+ "when": "2026-08-12T11:00:00Z",
+ "time_role": "occurred",
+ },
+ )
+ response = client.get(
+ f"/api/cases/{case_id}/timeline",
+ params={
+ "category": "statement",
+ "track": json.dumps({"roles": ["observed"], "hidden": [observed["id"]]}),
+ },
+ )
+ assert response.status_code == 200, response.text
+ assert response.json()["items"] == []
+
+
+def test_timeline_rejects_an_oversized_track_query(client):
+ case_id = _case(client, "Large track query")
+ with pytest.raises(HTTPException) as raised:
+ timeline(
+ case_id,
+ from_=None,
+ to=None,
+ category=None,
+ entity=None,
+ include_undated=True,
+ limit=100,
+ cursor=None,
+ bucket=None,
+ track=json.dumps({"terms": {"q": "x" * (64 * 1024)}}),
+ )
+
+ assert raised.value.status_code == 400
+ assert raised.value.detail == "timeline track query is too large"
+
+
+def test_board_graph_and_map_share_the_same_fact_time_window(client):
+ case_id = _case(client, "Timeline handoffs")
+ person = _entity(client, case_id, "person", "Witness")
+ place = _entity(
+ client,
+ case_id,
+ "place",
+ "North gate",
+ {"lat": 48.8566, "lon": 2.3522},
+ )
+ source = _entity(
+ client,
+ case_id,
+ "bookmark",
+ "Camera log",
+ {"url": "https://example.test/log"},
+ )
+ inside = client.post(
+ f"/api/cases/{case_id}/timeline/claims",
+ json={
+ "statement": "Witness reached the gate",
+ "when": "2026-08-12T10:00:00Z",
+ "about": [person["id"]],
+ "at": [place["id"]],
+ "cites": [source["id"]],
+ },
+ ).json()
+ outside = client.post(
+ f"/api/cases/{case_id}/timeline/claims",
+ json={"statement": "Later event", "when": "2026-08-13T10:00:00Z"},
+ ).json()
+ params = {
+ "temporal_from": "2026-08-12T09:00:00Z",
+ "temporal_to": "2026-08-12T11:00:00Z",
+ "temporal_category": "statement",
+ }
+
+ board = client.get(f"/api/cases/{case_id}/catalog/entities", params=params)
+ assert board.status_code == 200, board.text
+ board_ids = {entity["id"] for entity in board.json()["items"]}
+ assert board_ids == {
+ inside["entity"]["id"], person["id"], place["id"], source["id"]
+ }
+ assert outside["entity"]["id"] not in board_ids
+
+ graph = client.get(f"/api/cases/{case_id}/graph", params=params)
+ assert graph.status_code == 200, graph.text
+ assert {node["id"] for node in graph.json()["nodes"]} == board_ids
+
+ mapped = client.get(
+ f"/api/cases/{case_id}/timeline/map",
+ params={"from": "2026-08-12T09:00:00Z", "to": "2026-08-12T11:00:00Z"},
+ )
+ assert mapped.status_code == 200, mapped.text
+ body = mapped.json()
+ assert body["matched"] == 1
+ assert body["mapped"] == 1
+ assert body["marks"] == 1
+ assert body["items"][0]["owner_id"] == inside["entity"]["id"]
+ assert body["items"][0]["place_entities"] == [{
+ "id": place["id"],
+ "label": "North gate",
+ "lat": 48.8566,
+ "lon": 2.3522,
+ "radius_m": None,
+ "footprint": None,
+ }]
+
+
+def test_map_layer_answers_every_way_the_case_puts_something_on_the_ground(client):
+ """A window of photographs is a window with places in it.
+
+ `at` is a Claim's connector and nothing else carries it, so a layer that asked
+ for it alone answered a case full of located photographs with an empty map and
+ the words "nothing carries a place".
+ """
+ case_id = _case(client, "Placed by every verb")
+ case = Case.open(case_id)
+ quay = _entity(client, case_id, "place", "Quay", {"lat": 43.29, "lon": 5.37})
+ yard = _entity(client, case_id, "place", "Yard", {"lat": 43.31, "lon": 5.39})
+
+ photo = case.add_entity(
+ "media", "Quayside", {"path": "media/quay.jpg", "kind": "image"}, by="user"
+ )
+ case.upsert_media_item(
+ {
+ "path": "media/quay.jpg",
+ "filename": "quay.jpg",
+ "kind": "image",
+ "taken_at": "2026-08-12T10:30:00Z",
+ "added_at": "2026-08-12T10:30:00Z",
+ "source": {"type": "upload"},
+ },
+ entity_id=photo["id"],
+ )
+ case.add_link(photo["id"], quay["id"], "located-at", by="user")
+
+ shed = _entity(client, case_id, "structure", "Shed")
+ case.add_link(shed["id"], yard["id"], "sited-at", by="user")
+ # A note merely referring to a place was never there, so `mentions` stays out.
+ note = case.add_entity("note", "Desk note", {}, by="user")
+ case.add_link(note["id"], quay["id"], "mentions", by="user")
+
+ window = {"from": "2026-08-12T00:00:00Z", "to": "2026-08-13T00:00:00Z"}
+ body = client.get(f"/api/cases/{case_id}/timeline/map", params=window).json()
+
+ placed = {item["owner_id"]: item for item in body["items"]}
+ assert photo["id"] in placed, "a located photograph belongs on the map"
+ assert [place["id"] for place in placed[photo["id"]]["place_entities"]] == [quay["id"]]
+ assert note["id"] not in placed
+
+ # Whatever the case has sited somewhere lands there too, in the category that
+ # holds it: the structure is on the ground even though nothing was claimed of it.
+ # Filing stamps the row with the wall clock, so this window is the case's life.
+ filed = client.get(
+ f"/api/cases/{case_id}/timeline/map",
+ params={"from": "2000-01-01", "to": "2999-01-01", "category": "case_activity"},
+ ).json()
+ sited = {item["owner_id"]: item for item in filed["items"]}
+ assert [place["id"] for place in sited[shed["id"]]["place_entities"]] == [yard["id"]]
+
+ # The owner travels with the mark, so the card can hand the row back to the tool
+ # that owns it and show a photograph as a photograph.
+ owner = placed[photo["id"]]["owner"]
+ assert owner["type"] == "media"
+ assert owner["attrs"]["path"] == "media/quay.jpg"
+
+ # Categories are the caller's, not this route's: asking for statements alone
+ # leaves the photograph out.
+ claims_only = client.get(
+ f"/api/cases/{case_id}/timeline/map", params={**window, "category": "statement"}
+ ).json()
+ assert photo["id"] not in {item["owner_id"] for item in claims_only["items"]}
+
+ bad = client.get(
+ f"/api/cases/{case_id}/timeline/map", params={**window, "category": "nonsense"}
+ )
+ assert bad.status_code == 400
+
+
+def test_fact_time_filter_is_not_the_filing_date_filter(client):
+ case_id = _case(client, "Separate time meanings")
+ claim = client.post(
+ f"/api/cases/{case_id}/timeline/claims",
+ json={"statement": "Historical event", "when": "1999-01-01"},
+ ).json()["entity"]
+
+ response = client.get(
+ f"/api/cases/{case_id}/catalog/entities",
+ params={
+ "temporal_from": "1999-01-01",
+ "temporal_to": "1999-01-01",
+ "temporal_category": "statement",
+ },
+ )
+ assert response.status_code == 200, response.text
+ assert [entity["id"] for entity in response.json()["items"]] == [claim["id"]]
+
+ filed = client.get(
+ f"/api/cases/{case_id}/catalog/entities",
+ params={"since": "1999-01-01", "until": "1999-01-01"},
+ )
+ assert filed.status_code == 200, filed.text
+ assert filed.json()["items"] == []
diff --git a/tests/test_trash.py b/tests/test_trash.py
index 99e302e..f4b172a 100644
--- a/tests/test_trash.py
+++ b/tests/test_trash.py
@@ -63,9 +63,37 @@ def test_undo_brings_back_the_entity_its_id_and_its_file(client):
# and it is browsable again — the media index row came back with it
listed = client.get(f"/api/cases/{full.case_id}/media").json()
assert any(item["path"] == full.photo for item in listed)
+ gallery = client.get(
+ f"/api/cases/{full.case_id}/entities/{full.person_id}/images"
+ ).json()["images"]
+ assert [(image["media_id"], image["primary"]) for image in gallery] == [
+ (photo["id"], True)
+ ]
assert trash_of(client, full.case_id)["groups"] == []
+def test_undo_restores_private_entity_photos(client):
+ full = fullcase.build_full_case(client)
+ case = Case.open(full.case_id)
+
+ group = client.delete(
+ f"/api/cases/{full.case_id}/entities/{full.org_id}"
+ ).json()["trash"]
+ assert not case.resolve_inside(full.entity_photo).exists()
+ assert not case.resolve_inside(full.entity_photo_thumb).exists()
+
+ restored = client.post(f"/api/cases/{full.case_id}/trash/{group}/restore")
+ assert restored.status_code == 200, restored.text
+ gallery = client.get(
+ f"/api/cases/{full.case_id}/entities/{full.org_id}/images"
+ ).json()["images"]
+ assert [(image["id"], image["direct"], image["primary"]) for image in gallery] == [
+ (full.entity_photo_id, True, True)
+ ]
+ assert case.resolve_inside(full.entity_photo).is_file()
+ assert case.resolve_inside(full.entity_photo_thumb).is_file()
+
+
def test_a_cascade_comes_back_as_one_piece(client):
"""An Inspect session only depends on its subject, so deleting the photo
takes the session too. Undo has to bring both, or the analyst gets half a
@@ -118,6 +146,26 @@ def test_a_relation_survives_the_round_trip(client):
assert [r["entity"]["id"] for r in stated] == [full.place_id]
+def test_a_restored_node_comes_back_placed_by_the_layout(client):
+ """Where a node sat on the canvas does not survive its own deletion, and that is
+ the deliberate half of the bargain: the pin cascades with the entity so a
+ reissued id can never inherit a spot chosen for something else. The entity, its
+ files and its links all come back — the graph simply places it again."""
+ full = fullcase.build_full_case(client)
+ case = Case.open(full.case_id)
+ assert case.graph_pins("all") == {full.pinned_id: (-220.5, 118.25)}
+
+ group = client.delete(
+ f"/api/cases/{full.case_id}/entities/{full.pinned_id}"
+ ).json()["trash"]
+ assert case.graph_pins("all") == {}
+
+ client.post(f"/api/cases/{full.case_id}/trash/{group}/restore")
+
+ assert case.get_entity(full.pinned_id) is not None
+ assert case.graph_pins("all") == {}
+
+
def test_a_proof_takes_its_pasted_images_into_the_trash_and_back(client):
full = fullcase.build_full_case(client)
case = Case.open(full.case_id)
diff --git a/tests/test_updates.py b/tests/test_updates.py
index 442e948..190f680 100644
--- a/tests/test_updates.py
+++ b/tests/test_updates.py
@@ -7,11 +7,15 @@ shouldn't be reached."""
from __future__ import annotations
+import hashlib
+import json
+from pathlib import PurePosixPath
+
import httpx
import pytest
from azimut import __version__
-from azimut.api.ingest import bundled_extension_version
+from azimut.api.ingest import _extension_dir, bundled_extension_version, shipped_extension_files
from azimut.engine import updates
@@ -131,12 +135,91 @@ def test_update_endpoint_with_check_queries_github(client, monkeypatch):
# -- bundled extension version --------------------------------------------
+# The extension carries the Azimut version whose release last changed it, not
+# the current one. Settings turns "bundled > installed" into "replace the
+# unpacked folder and reload", so bumping this in lock-step with __version__
+# would send every user through a reinstall for a byte-identical zip.
+#
+# The pair below is the contract, and it moves in one direction only: when a
+# shipped file really changes, set the manifest to the current __version__ and
+# record the new digest here (the failing test prints it).
+EXTENSION_VERSION = "0.2.5"
+EXTENSION_PAYLOAD = "f8141fe57fed06b98f373446d8fc19e932a988d1cc27fdcc7d632ae1b65bb198"
+
+# Text is digested by its line content: a Windows checkout can carry CRLF, and
+# the gate has to reach the same verdict on the three CI platforms.
+_TEXT_SUFFIXES = {".js", ".json", ".css", ".html", ".md", ".txt"}
+
+
+def _extension_payload_digest() -> str:
+ """Digest everything ``extension.zip`` ships, minus the manifest's own
+ ``version``.
+
+ Leaving the version out is what makes the gate cut both ways: with it in,
+ any bump would change the digest and a gratuitous one would look exactly
+ like a real change."""
+ src = _extension_dir()
+ assert src is not None, "no extension bundled with this checkout"
+ digest = hashlib.sha256()
+ for name, path in shipped_extension_files(src):
+ if name == "manifest.json":
+ manifest = json.loads(path.read_text(encoding="utf-8"))
+ manifest.pop("version", None)
+ data = json.dumps(manifest, sort_keys=True).encode("utf-8")
+ else:
+ data = path.read_bytes()
+ if PurePosixPath(name).suffix in _TEXT_SUFFIXES:
+ data = data.replace(b"\r\n", b"\n")
+ digest.update(f"{name}\0".encode() + data + b"\0")
+ return digest.hexdigest()
+
+
+def test_the_shipped_listing_reads_the_same_on_every_platform():
+ """The digest above folds the names in order, so the order is part of the gate.
+
+ Sorting `Path` objects would not do: comparing them is case-insensitive on
+ Windows and case-sensitive everywhere else, which puts `README.md` first on
+ Linux and mid-list on Windows — three CI platforms disagreeing about one
+ unchanged extension. Sorted by the posix name instead, which is the same
+ string on all three.
+ """
+ src = _extension_dir()
+ assert src is not None
+ names = [name for name, _ in shipped_extension_files(src)]
+ assert names == sorted(names)
+ assert all("\\" not in name for name in names)
+
+
+def test_the_extension_version_moves_only_when_the_extension_does():
+ """Both halves of the drift, in one gate.
+
+ A shipped file changed without a version bump: the installed extension and
+ the bundled one report the same version while differing, so Settings stays
+ quiet and the user keeps running a stale bridge. A version bump with no
+ change: everyone is told to reinstall the zip they already have, and a nag
+ that cries wolf is a nag nobody reads."""
+ digest = _extension_payload_digest()
+ version = bundled_extension_version()
+
+ assert digest == EXTENSION_PAYLOAD, (
+ f"the shipped extension changed. Set extension/manifest.json to the current "
+ f'__version__ ({__version__}) and record EXTENSION_VERSION = "{__version__}", '
+ f'EXTENSION_PAYLOAD = "{digest}" here.'
+ )
+ assert version == EXTENSION_VERSION, (
+ f"the extension is unchanged but its version moved to {version}. Put "
+ f"extension/manifest.json back to {EXTENSION_VERSION} — a bump users can't "
+ f"see is a reinstall prompt they don't need."
+ )
+
-def test_bundled_extension_version_matches_manifest():
- # The repo checkout's extension/manifest.json is the source of truth here.
- assert bundled_extension_version() == __version__
+def test_the_bundled_extension_is_never_ahead_of_the_app():
+ """It is stamped with the Azimut version that shipped it, so it can lag by
+ several releases but never lead — a version no release ever carried would
+ make the Settings comparison meaningless."""
+ assert not updates.is_newer(EXTENSION_VERSION, __version__)
def test_settings_reports_extension_version(client):
body = client.get("/api/settings").json()
- assert body["extension_version"] == __version__
+ assert body["extension_version"] == EXTENSION_VERSION