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
33.5 KB
Raw Blame
"""One case holding an artifact from every tool, built through the real API.

The gates that keep the trash and the bundle honest all need the same thing: a
case that actually contains what a case can contain. Building it once, through
the endpoints the app itself serves, is what makes those gates cheap — a new
tool adds its artifact here and the gates cover it for free.

Nothing is written by hand. If a tool changes where it files its work, this
fixture changes with it, and the gates read the result rather than a
hand-maintained list of paths.

Standard library plus Pillow, and it lives under ``tests/`` so hatchling never
packages it into the wheel or the frozen binaries.
"""

from __future__ import annotations

import base64
import hashlib
import io
import zipfile
from dataclasses import dataclass, field
from pathlib import Path

from PIL import Image
from jobwait import WAIT
from azimut import layout


def _png(size: tuple[int, int] = (80, 60), color: tuple[int, int, int] = (120, 60, 30)) -> bytes:
    buf = io.BytesIO()
    Image.new("RGB", size, color).save(buf, "PNG")
    return buf.getvalue()


def _kml() -> bytes:
    """A small KML with one folder, which is one legend category and two marks.

    Its mark points at an icon beside it, so the KMZ below has pictograms of its
    own to compose — which is what puts a `.icons` companion in the full case
    without any gate needing the network.
    """
    return (
        '<?xml version="1.0" encoding="UTF-8"?>'
        '<kml xmlns="http://www.opengis.net/kml/2.2"><Document><name>Checkpoints</name>'
        '<Style id="red"><IconStyle><color>ff0000ff</color>'
        "<Icon><href>images/gate.png</href></Icon>"
        '<hotSpot x="0.5" xunits="fraction" y="0" yunits="fraction"/>'
        "</IconStyle></Style>"
        "<Folder><name>Roadblocks</name>"
        "<Placemark><name>North gate</name><styleUrl>#red</styleUrl>"
        "<Point><coordinates>2.3522,48.8566,0</coordinates></Point></Placemark>"
        "<Placemark><name>Riverside</name>"
        "<LineString><coordinates>2.30,48.85 2.32,48.86</coordinates></LineString>"
        "</Placemark></Folder></Document></kml>"
    ).encode()


def _kmz() -> bytes:
    """The same map, zipped with the icon it names. The whole of a layer's
    pictograms without a byte leaving the machine."""
    buf = io.BytesIO()
    with zipfile.ZipFile(buf, "w", zipfile.ZIP_DEFLATED) as archive:
        archive.writestr("doc.kml", _kml())
        archive.writestr("images/gate.png", _png((24, 24), (255, 255, 255)))
    return buf.getvalue()


@dataclass
class FullCase:
    """What was planted, so a gate can name it rather than rediscover it."""

    case_id: str
    photo: str = ""
    piece: str = ""
    collage: str = ""  # the exported picture, which is media
    collage_doc: str = ""  # the layout it was exported from
    collage_thumb: str = ""  # the layout's preview, which travels with it
    capture: str = ""
    session: str = ""  # the photo's Inspect work
    compare_session: str = ""
    compare_image: str = ""  # the session's render, a media working file
    horizon_view: str = ""  # a saved Horizon view, matched on the photo
    horizon_thumb: str = ""  # its preview, which travels with it
    horizon_find: str = ""  # a search for where the photo was taken, run to its end
    horizon_work: str = ""  # the work on Horizon's bench, kept so a reload brings it back
    map_plate: str = ""  # a page laid out round a map of the case
    map_plate_thumb: str = ""  # its preview, which travels with it
    analyzer_zones: str = ""
    analyzer_area: str = ""
    analyzer_followup: str = ""
    analyzer_run: str = ""
    proof: str = ""
    proof_asset: str = ""
    draft: str = ""
    note_id: str = ""
    note: str = ""  # its case-relative path
    sheet_id: str = ""
    sheet: str = ""  # the CSV, which is the sheet
    sheet_meta: str = ""  # the sidecar beside it
    place_id: str = ""
    grid: str = ""
    layer_id: str = ""
    editable_layer_id: str = ""
    editable_layer: str = ""
    layer: str = ""  # the spec, which is what the entity points at
    layer_snapshot: str = ""  # the bytes as received, which travel with it
    layer_icons: str = ""  # the source's own pictograms, which travel too
    layer_cache: str = ""  # the parsed copy, which does not
    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)


def build_full_case(
    client, name: str = "Full case", *, subject_changes: bool = True, personal_layers: bool = True,
    horizon_find: bool = True,
) -> FullCase:
    """Fill one case through every tool that files an artifact.

    Returns once the background queue is idle, so a caller can move or delete the
    case directory without racing an enrichment or a thumbnail write.
    """
    from azimut.engine import workqueue

    case_id = client.post("/api/cases", json={"name": name}).json()["id"]
    full = FullCase(case_id=case_id)

    # Checklists are manifest metadata, with no graph entity or owned files.
    response = client.put(f"/api/cases/{case_id}/todos", json={
        "revision": 0,
        "lists": [{"id": "checks", "name": "Checks", "tasks": [
            {"id": "source", "text": "Verify source", "done": True},
        ]}],
    })
    assert response.status_code == 200, response.text

    # -- media: two uploads, and a collage composed from both ----------------
    def upload(filename: str, data: bytes) -> str:
        res = client.post(
            f"/api/cases/{case_id}/media/upload",
            files={"file": (filename, io.BytesIO(data), "image/png")},
        )
        assert res.status_code == 200, res.text
        return res.json()["item"]["path"]

    full.photo = upload("photo.png", _png(color=(10, 20, 30)))
    full.piece = upload("piece.png", _png(color=(200, 100, 50), size=(60, 60)))

    collage = client.post(
        f"/api/cases/{case_id}/inspect/compose",
        json={
            "width": 200,
            "height": 120,
            "nodes": [
                {"src": {"path": full.photo},
                 "quad": [[5, 5], [95, 5], [95, 110], [5, 110]]},
                {"src": {"path": full.piece},
                 "quad": [[105, 5], [195, 5], [195, 110], [105, 110]]},
            ],
            "label": "Collage",
        },
    )
    assert collage.status_code == 200, collage.text
    full.collage = collage.json()["item"]["path"]

    # -- capture: a screenshot, which needs no network ------------------------
    client.put("/api/settings/keys", json={"google_js": "AIza.js"})
    shot = client.post(
        f"/api/cases/{case_id}/satellite/screenshot",
        files={"image": ("shot.png", _png(color=(40, 80, 40)), "image/png")},
        data={"lat": "48.8584", "lon": "2.2945", "zoom": "18",
              "provider": "google-js", "bearing": "45"},
    )
    assert shot.status_code == 200, shot.text
    full.capture = client.get(f"/api/cases/{case_id}/satellite").json()[0]["path"]

    # -- inspect work: the photo's edits (depends-on) --------------------------
    work = client.put(
        f"/api/cases/{case_id}/inspect/work",
        json={
            "path": full.photo,
            "spec": {"frames": [{
                "id": "fr_1", "path": full.photo, "time": None,
                "adjust": {"brightness": 1.2}, "crop": {"x": 0.1, "y": 0.1, "w": 0.5, "h": 0.5},
            }], "marks": [{"id": "mk_1", "time": 1.5, "label": "Plate visible"}]},
        },
    )
    assert work.status_code == 200, work.text
    full.session = f".inspect/{work.json()['name']}.json"

    # -- a collage layout: pieces from both uploads, its own document ---------
    layout_doc = client.post(
        f"/api/cases/{case_id}/collages",
        json={
            "title": "Harbour strip",
            "spec": {"width": 400, "height": 200, "nodes": [
                {"id": "nd_1", "save": {"path": full.photo, "time": None, "ops": []},
                 "w": 80, "h": 60, "quad": [[0, 0], [80, 0], [80, 60], [0, 60]]},
                {"id": "nd_2", "save": {"path": full.piece, "time": None, "ops": []},
                 "w": 60, "h": 60, "quad": [[90, 0], [150, 0], [150, 60], [90, 60]]},
            ]},
        },
    )
    assert layout_doc.status_code == 200, layout_doc.text
    full.collage_doc = f".collages/{layout_doc.json()['name']}.json"
    preview = client.put(
        f"/api/cases/{case_id}/collages/{layout_doc.json()['name']}/thumb",
        files={"file": ("preview.png", io.BytesIO(_png((160, 80))), "image/png")},
    )
    assert preview.status_code == 200, preview.text
    full.collage_thumb = preview.json()["thumb"]

    comparison = client.post(
        f"/api/cases/{case_id}/compare/sessions",
        json={
            "title": "Harbour change",
            "spec": {
                "version": 2,
                "camera": {"lat": 48.8584, "lon": 2.2945, "zoom": 17, "bearing": 0},
                "mode": "swipe",
                "divider": 55,
                "opacity": 50,
                "a": {"present": True, "provider": "esri-world-imagery", "overlays": []},
                "b": {"present": True, "provider": "osm", "overlays": ["boundaries"]},
            },
        },
    )
    assert comparison.status_code == 200, comparison.text
    full.compare_session = f".compare/{comparison.json()['name']}.json"
    rendered = client.post(
        f"/api/cases/{case_id}/compare/sessions/{comparison.json()['name']}/preview",
        files={"image_a": ("comparison.png", _png(color=(90, 60, 30)), "image/png")},
        data={"format": "png"},
    )
    assert rendered.status_code == 200, rendered.text
    full.compare_image = rendered.json()["path"]

    view = client.post(
        f"/api/cases/{case_id}/horizon/views",
        json={
            "title": "North ridge",
            "spec": {
                "eye": {"lat": 46.5586, "lon": 7.8353, "mode": "ground", "height": 1.7},
                "look": {"heading": 95, "tilt": 2, "fov": 60},
                "picture": {"ground": "imagery", "imagery": "esri-world-imagery"},
                "photo": {
                    "path": full.photo, "kind": "image", "mix": 0.6,
                    "strokes": [[{"u": 0.1, "v": 0.4}, {"u": 0.5, "v": 0.35}]],
                },
            },
            "made": {"terrain": [{"label": "Mapterhorn", "attribution": "© Mapterhorn"}],
                     "resolution_m": 9.6, "refraction": 0.13},
            "footprint": [[7.8353, 46.5586], [7.95, 46.6], [7.96, 46.5]],
        },
    )
    assert view.status_code == 200, view.text
    full.horizon_view = view.json()["spec_path"]
    view_thumb = client.put(
        f"/api/cases/{case_id}/horizon/views/{view.json()['name']}/thumb",
        files={"file": ("preview.png", io.BytesIO(_png((160, 80))), "image/png")},
    )
    assert view_thumb.status_code == 200, view_thumb.text
    full.horizon_thumb = view_thumb.json()["thumb"]

    # A search for where the photo was taken, run on flat relief drawn here: no network.
    if horizon_find:
        _add_horizon_find(client, case_id, full)

    # The bench Horizon keeps while the analyst works: the photo laid and Find's area.
    bench = client.put(
        f"/api/cases/{case_id}/horizon/work",
        json={
            "view": view.json()["name"],
            "photo": {"path": full.photo, "kind": "image", "strokes": [[{"u": 0.1, "v": 0.4}, {"u": 0.5, "v": 0.35}]]},
            "find": {"area": [{"lat": 46.0, "lon": 7.0}, {"lat": 46.0, "lon": 7.01}, {"lat": 46.01, "lon": 7.01}]},
        },
    )
    assert bench.status_code == 200, bench.text
    full.horizon_work = ".horizon/.work.json"

    # A map plate: one map, its legend and a title. Drawn by the browser; only the layout is kept.
    plate = client.post(
        f"/api/cases/{case_id}/map-plates",
        json={"title": "Situation", "spec": {"elements": [
            {"id": "map", "kind": "map", "box": [10, 20, 200, 150],
             "view": {"lat": 48.85, "lon": 2.29, "zoom": 12}},
            {"id": "legend", "kind": "legend", "box": [215, 20, 70, 60], "of": "map"},
            {"id": "title", "kind": "text", "box": [10, 6, 200, 12], "text": "Situation", "size": 18, "weight": 700},
        ]}},
    )
    assert plate.status_code == 200, plate.text
    full.map_plate = plate.json()["spec_path"]
    plate_thumb = client.put(
        f"/api/cases/{case_id}/map-plates/{plate.json()['name']}/thumb",
        files={"file": ("preview.png", io.BytesIO(_png((160, 110))), "image/png")},
    )
    assert plate_thumb.status_code == 200, plate_thumb.text
    full.map_plate_thumb = plate_thumb.json()["thumb"]

    # -- a place, and a relation to the photo ---------------------------------
    place = client.post(
        f"/api/cases/{case_id}/satellite/place",
        json={"lat": 48.8584, "lon": 2.2945, "zoom": 17, "title": "Tower"},
    )
    assert place.status_code == 200, place.text
    full.place_id = place.json()["id"]
    photo_entity = client.get(
        f"/api/cases/{case_id}/entities/lookup", params={"attr": "path", "value": full.photo}
    ).json()["entity"]
    related = client.post(
        f"/api/cases/{case_id}/links",
        json={"from_id": photo_entity["id"], "to_id": full.place_id, "type": "located-at"},
    )
    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"
    proof = client.post(
        f"/api/cases/{case_id}/proofs",
        json={
            "title": "Convoy proof",
            "png_base64": base64.b64encode(_png(size=(200, 120))).decode(),
            "spec": {
                "panels": [{"id": "p0", "src": full.photo, "natural": [80, 60]}],
                "shapes": [],
                "pastes": [{"id": "x0", "asset": asset_name, "natural": [40, 30],
                            "x": 10, "y": 10, "scale": 1}],
            },
            "assets": [{"name": asset_name, "data": base64.b64encode(pasted).decode()}],
        },
    )
    assert proof.status_code == 200, proof.text
    full.proof = proof.json()["spec_path"]
    full.proof_asset = f"{layout.proof_assets_rel(proof.json()['name'])}/{asset_name}"

    # -- post: derived from the proof and the photo ---------------------------
    draft = client.post(
        f"/api/cases/{case_id}/drafts",
        json={
            "title": "Thread draft",
            "state": {"proofPng": proof.json()["png"], "mediaPaths": [full.photo]},
        },
    )
    assert draft.status_code == 200, draft.text
    full.draft = draft.json()["draft"]

    # -- a filed note, the free-form notes, a folder, and a saved grid --------
    client.post(f"/api/cases/{case_id}/folders", json={"name": "Sources/Telegram"})
    note = client.post(
        f"/api/cases/{case_id}/notes",
        json={"title": "Witness", "folder": "Sources/Telegram", "content": "# Witness\n"},
    )
    assert note.status_code == 200, note.text
    full.note_id = note.json()["id"]
    full.note = note.json()["attrs"]["path"]
    client.put(f"/api/cases/{case_id}/notes", json={"text": "# Full case\n\nRunning notes.\n"})

    # -- a sheet: a CSV in the case, and the sidecar that paints it ------------
    sheet = client.post(f"/api/cases/{case_id}/sheets", json={"title": "Candidates"})
    assert sheet.status_code == 200, sheet.text
    full.sheet_id = sheet.json()["id"]
    full.sheet = sheet.json()["attrs"]["path"]
    full.sheet_meta = layout.sheet_meta_rel(Path(full.sheet).stem)
    # The sidecar carries what the app knows about a column as well as how it looks — a
    # role, its vocabulary, a line of instruction, and which column the progress is read
    # off — so the bundle gates see all of it and not only the colours.
    saved_sheet = client.put(
        f"/api/cases/{case_id}/sheets/{full.sheet_id}",
        json={
            "columns": [
                "id", "Subject", "Status", "Coordinates", "Added", "On map",
                "Links with others", "start synchro",
            ],
            "rows": [
                ["r1", "Quai sud", "ruled out", "48.85660, 2.35220", "", "", "", "-00:01:50"],
                ["r2", "Pont nord", "to do", "", "", "", "Quai sud", "00:04:04"],
            ],
            "meta": {
                "colours": {"r1": "grey"},
                "widths": {"Subject": 220},
                "frozen": "Subject",
                "roles": {
                    "Status": {"kind": "state", "values": ["to do", "done", "ruled out"]},
                    "Coordinates": {"kind": "latlon"},
                    "Added": {"kind": "stamped"},
                    "On map": {"kind": "computed", "of": "has_point"},
                    "Links with others": {"kind": "row", "of": "Subject", "multi": ", "},
                    "start synchro": {"kind": "offset", "anchor": "IGLA launch"},
                },
                "notes": {"Status": "where this candidate got to"},
                "progress": "Coordinates",
                # The three tables the bridge to the case writes, each a different grain:
                # a named moment several videos are lined up on, a case file a row carries,
                # and what a column's words mean in the graph.
                "anchors": {"IGLA launch": {"at": "2026-01-03T01:57:00Z"}},
                "attachments": {"r1": [photo_entity["id"]]},
                "values": {"Subject": {"Quai sud": full.structure_id}},
                "description": "What is left to geolocate.",
            },
        },
    )
    assert saved_sheet.status_code == 200, saved_sheet.text
    assert saved_sheet.json()["rows"][0][4], "a stamped column is dated by the save"
    assert saved_sheet.json()["meta"]["anchors"]["IGLA launch"]["at"]
    assert saved_sheet.json()["meta"]["attachments"] == {"r1": [photo_entity["id"]]}

    # -- 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={
            "title": "North sweep",
            "spec": {
                "azimut_grid": 1,
                "cell_m": 500,
                "anchor": {"lat": 48.0, "lon": 2.0},
                "lat_step": 0.0045,
                "lon_step": 0.0067,
                "aoi": {"type": "rect",
                        "bounds": {"south": 48.0, "west": 2.0, "north": 48.02, "east": 2.02}},
                "statuses": {"0:0": "cleared"},
            },
        },
    )
    assert grid.status_code == 200, grid.text
    full.grid = f".search/{grid.json()['name']}.json"

    # -- a map layer: somebody else's file, drawn over the case's own map ------
    # Four files with two different answers to "does this travel?", which is why
    # it is here: the spec, the snapshot and the composed icons are the case's,
    # the parsed copy is a cache the gates must see dropped rather than carried.
    # A KMZ rather than a KML so the icons are real without a fetch.
    layer = client.post(
        f"/api/cases/{case_id}/map-layers/upload",
        files={"file": ("checkpoints.kmz", io.BytesIO(_kmz()), "application/vnd.google-earth.kmz")},
        data={"title": "Checkpoints", "icons": "true"},
    )
    assert layer.status_code == 200, layer.text
    assert layer.json()["icons"] == 1, "the KMZ's own pictogram was composed"
    layer_name = layer.json()["name"]
    full.layer = layout.layer_spec_rel(layer_name)
    full.layer_snapshot = layout.layer_snapshot_rel(layer_name)
    full.layer_icons = layout.layer_icons_rel(layer_name)
    full.layer_cache = layout.layer_cache_rel(layer_name)
    full.layer_id = client.get(
        f"/api/cases/{case_id}/entities/lookup", params={"attr": "spec", "value": full.layer}
    ).json()["entity"]["id"]

    # A personal layer owns its edited collection as well as the original KMZ.
    if personal_layers:
        personal = client.post(
            f"/api/cases/{case_id}/map-layers/{layer_name}/editable-copy",
            json={"title": "Working checkpoints"},
        )
        assert personal.status_code == 200, personal.text
        personal_name = personal.json()["name"]
        group = client.post(f"/api/cases/{case_id}/map-layers/{personal_name}/groups",
                            json={"name": "Reviewed"})
        assert group.status_code == 200, group.text
        group_id = group.json()["group"]["id"]
        styled = client.patch(f"/api/cases/{case_id}/map-layers/{personal_name}/groups/{group_id}",
                              json={"colour": "#009e73", "symbol": "badge-building", "size": 1.75, "stroke": 4})
        assert styled.status_code == 200, styled.text
        shared = client.post(f"/api/cases/{case_id}/map-layers/{personal_name}/links",
                             json={"items": [{"id": full.place_id, "lat": 48.8584, "lon": 2.2945}], "group": group_id})
        assert shared.status_code == 200, shared.text
        added = client.post(f"/api/cases/{case_id}/map-layers/{personal_name}/markers",
                            json={"lat": 48.8, "lon": 2.3, "name": "Review point", "symbol": "star"})
        assert added.status_code == 200, added.text
        # A marker in the analyst's own icon: the layer takes its copy, so the case
        # carries the picture and how it is drawn wherever it goes.
        mark = Image.new("RGBA", (40, 40), (0, 0, 0, 0))
        mark.paste((200, 30, 30, 255), (8, 8, 32, 32))
        drawn = io.BytesIO()
        mark.save(drawn, "PNG")
        library = client.post("/api/icons", files=[("files", ("full-case-mark.png", drawn.getvalue(), "image/png"))])
        assert library.status_code == 200, library.text
        icon_key = next(icon["key"] for icon in library.json()["icons"] if icon["name"] == "Full case mark")
        worn = client.post(f"/api/cases/{case_id}/map-layers/{personal_name}/markers",
                           json={"lat": 48.81, "lon": 2.31, "name": "Own icon", "icon": icon_key})
        assert worn.status_code == 200, worn.text
        ordered = client.post(f"/api/cases/{case_id}/map-layers/{personal_name}/groups/order",
                              json={"ids": [group_id, *[g["id"] for g in styled.json()["groups"]
                                                        if g["id"] != group_id]]})
        assert ordered.status_code == 200, ordered.text
        shape = client.post(f"/api/cases/{case_id}/map-layers/{personal_name}/shapes", json={
            "geometry": {"type": "Polygon", "coordinates": [[[2.3, 48.8], [2.4, 48.8],
                                                               [2.4, 48.9], [2.3, 48.8]]]},
            "name": "Review area", "group": group_id,
        })
        assert shape.status_code == 200, shape.text
        checkpoint = client.post(f"/api/cases/{case_id}/map-layers/{personal_name}/edit")
        assert checkpoint.status_code == 200, checkpoint.text
        full.editable_layer = layout.layer_spec_rel(personal_name)
        full.editable_layer_id = client.get(
            f"/api/cases/{case_id}/entities/lookup", params={"attr": "spec", "value": full.editable_layer}
        ).json()["entity"]["id"]

    # -- 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"]

    # Analyzer input tiles are deterministic cached provider responses; all
    # permanent case artifacts are still produced through the public API.
    from analyzerfixture import sample_input, seed_images
    analysis = sample_input()
    seed_images(analysis)
    from azimut.engine.analysis_models import Zone
    ring = Zone.model_validate(analysis["zones"][0]).ring()
    area = client.post(f"/api/cases/{case_id}/analysis/areas", json={
        "name": "Port", "colour": "#38bdf8", "geometry": {
            "type": "Polygon", "coordinates": [ring + [ring[0]]]},
    })
    assert area.status_code == 200, area.text
    full.analyzer_area = f"{layout.ANALYSIS_DIR}/areas-{area.json()['id']}.json"
    for kind, body, attr in (
        ("zones", {"title": "Port areas", "area_ids": [area.json()["id"]]}, "analyzer_zones"),
        ("followups", analysis, "analyzer_followup"),
        ("runs", analysis, "analyzer_run"),
    ):
        saved = client.post(f"/api/cases/{case_id}/analysis/{kind}", json=body)
        assert saved.status_code == 200, saved.text
        setattr(full, attr, f"{layout.ANALYSIS_DIR}/{kind}-{saved.json()['id']}.json")

    # 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.
    assert workqueue.wait_until_idle(timeout=WAIT)
    run_id = Path(full.analyzer_run).stem.split("-", 1)[1]
    result = client.get(f"/api/cases/{case_id}/analysis/runs/{run_id}").json()
    assert result["status"] == "ready", result

    # Exercise the local merge journal, portable redirects, and retained fields in
    # the same birth-state and bundle gates as every other case artifact.
    if subject_changes:
        first = entity("vehicle", "Unclassified subject")
        changed = client.patch(f"/api/cases/{case_id}/entities/{first}", json={"type": "vessel"})
        assert changed.status_code == 200, changed.text
        duplicate = entity("vessel", "Duplicate subject")
        merged = client.post(f"/api/cases/{case_id}/entities/{first}/merge", json={"other": duplicate})
        assert merged.status_code == 200, merged.text

    entities = client.get(
        f"/api/cases/{case_id}/catalog/entities", params={"limit": 500}
    ).json()["items"]
    full.entity_types = {e["type"] for e in entities}
    return full


def _add_horizon_find(client, case_id: str, full: FullCase) -> None:
    """A search for where the photo was taken, run to its end on flat relief drawn here: no network."""
    from azimut.engine import terrain, workqueue
    from fakerelief import Relief

    terrain.forget_decoded()

    fetch, terrain.tile = terrain.tile, Relief(peaks=(), plain=500.0, ripple=0.5)
    try:
        ring = [(46.0, 7.0), (46.0, 7.008), (46.006, 7.008), (46.006, 7.0)]
        searched = client.post(
            f"/api/cases/{case_id}/horizon/finds",
            json={
                "title": "North ridge search",
                "photo": {"path": full.photo, "kind": "image", "title": "summit"},
                "trace": {"x": [-0.8, -0.4, 0.0, 0.3, 0.6, 0.9], "y": [0.1, 0.12, 0.15, 0.11, 0.09, 0.1],
                          "half_width": 600, "fov": 60, "known": True},
                "area": [{"lat": lat, "lon": lon} for lat, lon in ring],
                "reach": 5000,
                "spacing": 500,
            },
        )
        assert searched.status_code == 200, searched.text
        assert workqueue.wait_until_idle(timeout=WAIT)
    finally:
        terrain.tile = fetch
        terrain.forget_decoded()
    full.horizon_find = f".horizon/finds/{searched.json()['name']}.json"