The OSINT investigator's workbench. One case, one folder, every tool. Local-first: your media and your investigations never leave your machine.
JavaScript
M7: A case folder the analyst owns, and a workspace they can move (#44)
OsintMeThat1a8e0343f36e
diff --git a/README.md b/README.mdindex 03d10ab..0f4d01e 100644--- a/README.md+++ b/README.md@@ -33,6 +33,20 @@ extension, and cross-platform binaries with a bundled ffmpeg.Every tool works one-shot (a scratch session, no setup) or inside a case, aplain directory holding the whole investigation.+Inside a case, Azimut owns only the `azimut/` directory. `README.txt` explains+the boundary; anything else at the case root is yours and travels with the case+bundle.++The workspace root stays equally readable: permanent case folders sit directly+under `~/Azimut`. Azimut keeps scratch sessions, bundles, settings, runtime+tools and tile caches under the hidden `~/Azimut/.azimut/` directory. Settings →+About moves that folder anywhere you like, 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.+New in v0.2.6:- Export a complete case as an integrity-checked bundle, then import it as a@@ -214,7 +228,8 @@ One-time setup: register the repo as a1. No account, telemetry or automatic upload. The server binds to`127.0.0.1`, and Azimut never posts on your behalf.2. A case contains the investigation's files and SQLite graph. A closed case- folder is complete and portable; ZIP import/export is planned.+ folder is complete and portable; bundle export carries both Azimut's files+ and anything kept beside them.3. One tab = one tool, useful in 30 seconds.4. Azimut integrates specialized services instead of recreating them.5. The analyst decides; tools do not produce automated verdicts.diff --git a/docs/ONTOLOGY.md b/docs/ONTOLOGY.mdindex 74a00c3..385f275 100644--- a/docs/ONTOLOGY.md+++ b/docs/ONTOLOGY.md@@ -5,11 +5,15 @@> new vocabulary. Tool proposals enter as `suggested` and remain distinct from> analyst-confirmed findings.-**Storage schema: `3`.** The manifest carries `{"azimut": {"schema": 3,-"storage": "sqlite"}}`; schema 3 moved the graph from `case.json` to per-case-`case.db`. The entity/link shape is unchanged since v1. Breaking changes require-a manifest schema bump and migration. The internal SQLite schema is version 5;-it adds search and media browse indexes without changing this logical model.+**Storage schema: `9`.** The manifest carries `{"azimut": {"schema": 9,+"storage": "sqlite"}}`. Schema 3 moved the graph from `case.json` to per-case+`case.db`; schema 9 gives that case its final folder layout and aligns each+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.Legend: ✅ implemented in code · 🔶 machinery exists, unused · ⬜ proposed.diff --git a/docs/SPEC.md b/docs/SPEC.mdindex 08ed1a7..055c3e0 100644--- a/docs/SPEC.md+++ b/docs/SPEC.md@@ -41,25 +41,32 @@ Key constraints:## 3. The case workspace-A directory per investigation (`~/Azimut/cases/<case>/` by default):+The workspace is `~/Azimut` unless it was moved: `AZIMUT_HOME` wins, then a+one-line pointer file at the platform's configuration location, then the+default. A directory per investigation (`~/Azimut/<case>/` by default):```-case.json # small manifest: name, dates, storage format + schema-case.db # authoritative SQLite graph: entities, links, folders-notes.md # free-form case notes (markdown)-notes/ # filed note bodies (Markdown)-media/ # source + captured + extracted media, with metadata + sha256-proofs/ # composed proofs: exported PNGs + editable JSON specs- # <name>.assets/ holds images pasted into that proof only-exports/ # post drafts and reports-inspect/ # saved Inspect session specs-.trash/ # recoverable artifact payloads+README.txt # which half of the folder is whose+azimut/ # everything Azimut owns; the rest of the folder is yours+ case.json # small manifest: name, dates, storage format + schema+ notes.md # free-form case notes (markdown)+ notes/ # note bodies, named after their title, filed as in the notebook+ media/ # source + captured + extracted media; .meta/ holds the sidecars+ proofs/ # exported PNGs; .meta/ holds the specs and pasted images+ exports/ # yours to fill+ .data/ # case.db: authoritative SQLite graph+ .drafts/ # post drafts+ .inspect/ # saved Inspect session specs+ .search/ # saved Grid Search state+ .trash/ # recoverable artifact payloads, in numbered slots```Tools use `CaseRepository` for structured state. Media, notes and proofs remainfiles. Legacy JSON graphs migrate to SQLite on open with a retained backup.One-shot work uses the same code path in a promotable scratch case. Exported-case bundles live in the workspace-level `bundles/` directory.+case bundles live under the workspace's hidden `.azimut/` directory.+App-wide settings, scratch cases, caches and runtime tools also stay under+`.azimut/`, so the visible workspace root contains only permanent cases.## 4. Data model@@ -114,17 +121,23 @@ proof for publication.| ✅ **Notebook diagrams** | Draws ```mermaid fences in the preview and the PDF, loading the library only when a note holds one. || ✅ **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 integrity-checked case snapshots, with optional whole-bundle password protection. |+| ✅ **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** | About 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 workspace-level proof and post presets through export and import. |+| ✅ **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 the workspace to it, verifies, switches a pointer kept outside it and keeps the old copy until dropped. A configured folder that has gone stops startup instead of being recreated. |+| ✅ **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. |---@@ -146,11 +159,6 @@ Each version delivers one complete daily workflow. Firm ideas move here from| **Capture scale and north** | Preference-controlled scale bar, north arrow and graticule on app and extension captures. || **Notes to PDF** | Ticks notes in a dialog and writes one file per note, named after the note, into the case's export destination. Rendered server-side so no print dialog is involved, which means carrying fonts: a bundled Noto set, the system font for CJK, and a named error rather than empty boxes for a script nobody covers. || **Export destination** | A folder of the analyst's own, remembered per case, where notes, proofs and map exports land instead of only the case's `exports/`. Validated when set, never deleted from, and a re-export overwrites rather than accumulates. |-| **Case doctor** | Compares a case folder against its graph — missing `case.db`, files unknown to it, entities pointing at deleted files — and offers each repair as a choice. Prerequisite for letting the workspace move. |-| **Workspace folder** | Settings moves the whole workspace, keys and presets included, by copying, verifying, switching a pointer kept outside it, then keeping the old copy until the analyst drops it. Covers adopting a hand-moved folder and a root that has gone missing. |--Toward v2: reveal a case's folder in the system file manager; a lock so two-Azimut instances can't share one workspace.### v3: GEOINT expansion@@ -256,6 +264,7 @@ Google Photorealistic 3D Tiles.No version yet. Promote an idea when its workflow is clear; delete it when itstops 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.- **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.@@ -300,11 +309,15 @@ stops making sense.- **Security posture** (single-user localhost): `127.0.0.1` bind + Host/Originguard (DNS rebinding), 0600/0700 perms, hard 100 MP Pillow limit, content-hashednames for images pasted into a proof (no client-chosen path), token-gated- ingest island for the extension. Accepted risks recorded here: cleartext keys over+ ingest island for the extension. The workspace pointer is the one file written+ outside the workspace, 0600 and holding a path; deleting the copy a move set+ aside acts on this process's own memory, never on a path from the request.+ Accepted risks recorded here: cleartext keys overlocalhost, the hash-verified scraper updater, and tile/media URL fetches (SSRFonly matters if the localhost assumption breaks). The startup update check isthe one on-mount network call: opt-out and read-only against GitHub's releases- feed, notes rendered as text (no HTML injection). Remote images embedded in a+ feed, notes rendered through the Notebook's DOMPurify-sanitized Markdown+ renderer rather than as raw HTML. Remote images embedded in aNotebook note contact their host whenever the preview opens; Notebook warnsabout that behavior and local Case media avoids it. Notebook diagrams are theone markup DOMPurify does not clear: Mermaid draws its SVG into the previewdiff --git a/docs/STORAGE_AND_PERFORMANCE.md b/docs/STORAGE_AND_PERFORMANCE.mdindex b615ca6..e90843b 100644--- a/docs/STORAGE_AND_PERFORMANCE.md+++ b/docs/STORAGE_AND_PERFORMANCE.md@@ -7,36 +7,142 @@ SQLite is complete.Structured case data lives in SQLite. Images, videos, proof PNGs, drafts, savedInspect sessions and note bodies remain ordinary files inside the case folder.+## The shape of the workspace++```text+<workspace>/+ <case>/ # one visible folder per permanent investigation+ .azimut/ # hidden application machinery+ bundles/ # exported bundles and transient imports+ cache/tiles/ # disposable map tile cache+ lock # held by the one Azimut using this workspace+ runtime/ # updated scraper distributions+ scratch/ # complete, promotable one-shot cases+ settings/ # preferences, templates, branding and cookies+```++Startup migrates the former `cases/`, `scratch/`, `bundles/`, `runtime/` and+`tile-cache/` directories with restartable renames. Permanent cases move to the+workspace root; scratch cases move under `.azimut/scratch/` and then run through+the same case-schema migration as permanent cases before cleanup. Different+entries at the same destination stop the move without overwriting either copy.++## Where the workspace is++Nothing inside a workspace records where it is: media are stored as+`media/photo.png`, and settings hold keys and preferences. So the answer lives+outside it, in a one-line pointer file at the platform's own configuration+location — `$XDG_CONFIG_HOME/azimut/location` on Linux, `~/Library/Application+Support/Azimut/location` on macOS, `%APPDATA%\Azimut\location` on Windows.+Resolution order is `AZIMUT_HOME`, then that pointer, then `~/Azimut`. The+environment variable stays in front so a workspace on a stick keeps working+without rewriting the machine's configuration, and a stale pointer cannot stop a+run that was told where to look.++A lost or unreadable pointer costs an address, not data: Azimut falls back to+the default root, and pointing it at the real folder again is one action. A+pointer naming a folder that is *not there* is the other case, and it stops+startup: nothing is created, case routes answer 503, and the browser shows where+the folder was expected. Recreating it silently is how someone concludes their+work is gone.++### One Azimut per workspace++A workspace holds `.azimut/lock`, and the process that opens it holds an advisory+lock on that file — `fcntl.flock` on Linux and macOS, `msvcrt.locking` on+Windows. The reason it is an OS lock rather than a file Azimut writes and deletes+is that **the kernel drops it when the process dies**, so a crash can never leave+a workspace nobody can open. It is taken before startup migrates anything, since+two processes renaming case directories at once is the damage it exists to+prevent, and it moves with the root when a folder is adopted or a move finishes.++That lock is unreliable on exactly the filesystems this matters for, NFS, SMB and+cloud-sync folders, so the file also carries who holds it and a heartbeat rewritten+every 30 seconds. The two are read together: a refused lock means someone holds+it; a granted lock over a payload from *another* machine whose heartbeat is under+five minutes old means the lock was probably a no-op, so the payload wins; an+older heartbeat, or any payload naming this machine, is a corpse to take over.+Two machines' clocks can disagree in a way nothing here can fix, so Settings can+always overrule the verdict.++The port was never this guarantee. A second instance on the same machine failed+to bind 8477 and died, which protects the port; `azimut --port 8478` and two+machines on one share never noticed. What breaks without the lock is not SQLite,+whose own locking and `busy_timeout` hold on a local disk, but everything around+it: `settings.json` read-modify-written per process loses an API key to the last+writer, and startup migrations race over the same renames.++Settings can adopt a folder as it is, or move the workspace into it. Adopting+writes the pointer and nothing else, which is what a folder moved by hand needs.+A move copies, verifies file names and sizes, renames the copy into place, then+writes the pointer — that write is the whole switch, so an interruption before+it leaves the old folder authoritative and one after leaves the new one, both+complete. The old folder is then renamed `<name>.old-<date>` and kept until the+analyst drops it. The tile cache is not copied, being disposable by contract,+and a destination that already holds other files gets an `Azimut` subfolder+rather than settling among them. Choosing a root is also where the path budget+below is enforced: `layout.room_for_workspace_root()` refuses a root too long+for a case to fit under it on Windows, and names it as a warning elsewhere.+## The shape of a case```text-case.json # small manifest: name, dates, storage format and schema-case.db # entities, links, folders, catalog and jobs (SQLite)-notes.md # case-wide Markdown note-notes/ # filed Markdown note bodies (one file per note entity)-media/ # imported, downloaded and derived media + sidecars- .dl/ # in-progress downloads (transient)- .thumbs/ # disposable thumbnail cache-proofs/ # editable proof specs and rendered PNGs-exports/ # post drafts and reports-inspect/ # saved Inspect session specs-search/ # saved Grid Search state-.trash/ # deleted artifacts grouped by delete action+<case>/ # the analyst's: Azimut writes nothing here but azimut/+ README.txt # which half of the folder is whose+ azimut/+ case.json # small manifest: name, dates, storage format and schema+ notes.md # case-wide Markdown note+ notes/ # note bodies, named after their title, filed as in the notebook+ media/ # imported, downloaded and derived media+ .meta/ # one sidecar per media+ .dl/ # in-progress downloads (transient)+ .thumbs/ # disposable thumbnail cache+ proofs/ # rendered PNGs+ .meta/ # editable specs and pasted assets+ exports/ # what the analyst exports; empty until they do+ .data/ # case.db: entities, links, folders, catalog and jobs (SQLite)+ .drafts/ # post drafts+ .inspect/ # saved Inspect session specs+ .search/ # saved Grid Search state+ .trash/ # deleted artifacts grouped by delete action, in numbered slots```+Paths are stored relative to `azimut/`, not to the case folder: a media is+`media/x.png` in the graph, in its sidecar and in a bundle. That is what let the+wrapper arrive without rewriting a stored path, and what keeps bundles written+before it importable after it.++Visible means openable and useful in another program; a dot-directory means only+Azimut reads it. `ensure_dir` sets `FILE_ATTRIBUTE_HIDDEN` on those, since a+leading dot means nothing to Windows Explorer.++`layout.py` owns this shape. It answers where each file goes for a given case+root and carries the path budget — the caps on case, media, document and folder+names that keep a case's longest path inside Windows' 260-character limit.+`tests/test_layout.py` recomputes the budget from those caps and fails when a+new directory level or a raised cap breaks it.+`case.json` is the discovery manifest: name, creation date, and the storage andschema fields. It no longer holds the graph, so the case switcher can identify acase without opening its database. `case.db` is the source of truth for mutablestructured state (entities, links, folders, jobs). The files under `media/`,-`proofs/`, `exports/`, `inspect/` and `notes/` are the source of truth for their+`proofs/`, `.drafts/`, `.inspect/` and `notes/` are the source of truth for theirown content.-Under `proofs/`, `exports/` and `inspect/`, a file's stem is the name shown at the-top of its tool, slugified (`api/naming.slugify`, mirrored in `lib/naming.js`).-Renaming therefore moves the file: the save carries the slug it was bound to, and-the endpoint writes the new one, moves the proof's PNG with it, rebinds the same-entity and deletes the old file. A rename onto a name another item holds is-refused (409) — two entities pointing at one spec has no sane merge.+App-wide preferences stay outside cases under `<workspace>/.azimut/settings/`:+`settings.json`, `templates.json`, `signature.png` and the optional+`cookies.txt`. Startup moves the former workspace-root or `.settings/` files+there with independent atomic renames, so a partial move resumes. If both+locations differ, the current hidden file wins and the legacy copy is retained+beside it under a `.legacy` name.++For media, proof PNGs, notes, drafts and Inspect sessions, the human-readable+filename stem is the name Azimut shows. Spaces, case and Unicode survive;+characters forbidden by Windows are replaced and the returned canonical stem+is written back to the UI. Renaming moves the file and its companions, rewrites+exact stored paths in the graph, jobs, sidecars and tool specs, and rebinds the+same entity. A rename onto a name another item holds is refused before anything+moves.Every mutation used to re-read and rewrite the whole `case.json` under a per-caselock. At 10k entities that rewrote megabytes per edit and shipped the entire@@ -51,6 +157,26 @@ database plus declared files under a SHA-256 manifest. Rollback journaling leaveno WAL checkpoint outside the case folder. Media, proofs and note bodies remaininspectable files.+## Case Doctor++The case switcher can inspect a permanent or scratch case without opening its+database. Discovery reads `case.json`, so renaming the outer case folder does+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.++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+place only after the rebuild completes. Relations, catalog folders and+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.+## Ownership rulesEach value has one owner. Cached copies may exist, but they are disposable and@@ -60,17 +186,18 @@ 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 labels and notes | `case.db` | Indexed for catalog search |-| Media title, notes and folder | Media sidecar | Mirrored to the graph and browse index |+| 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 || Image, video and audio bytes | Filesystem | Never stored as database blobs || Proof and session content | Their JSON/PNG files | Registered as artifacts in the database || Acquisition provenance | Media sidecar | Immutable after registration || Media browse fields | `case.db` (`media_items`) | Search index mirrored from sidecars || Background jobs | `case.db` (`jobs`) | Durable, recoverable, one worker || Trash journal | `case.db` (`trash`) | One row per delete action; payload loaded only for restore |-| Deleted artifact bytes | `.trash/<group>/` | Original relative paths, retained until purge |+| Deleted artifact bytes | `.trash/<group>/` | Numbered slots paired to their origin by the journal, retained until purge || Thumbnails | `media/.thumbs/` | Cache; safe to remove at any time |-| Note bodies | `notes.md`, `notes/<id>.md` | Graph keeps only id, title, folder, path |+| Note bodies | `notes.md`, `notes/<folder>/<title>.md` | Graph keeps only id, title, folder, path; uniqueness is per folder |## Packaging and frozen-binary constraints@@ -115,6 +242,15 @@ review.`CASE_SCHEMA`: the manifest's `azimut.storage` field selects the backend, and eachformat 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+and never became public formats. `FolderMigration` therefore declares a target+schema instead of assuming `+1`: every schema-3 case and any development case at+4–8 runs the same idempotent normalizer and is stamped 9 only after the whole+layout and visible-name contract are valid. A stopped migration keeps its older+stamp and resumes the same normalizer on the next open. Media moves additionally+use `.data/rename.json`, so a restart can finish references after the bytes moved.+### Tables`meta`@@ -185,30 +321,42 @@ sync.`engine/artifacts.py` is the single declaration of files owned by each entitytype. Delete writes a recovery journal before moving files to `.trash/<group>/`-and removing graph rows. 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 case open; an interrupted restore is-completed. Shared thumbnails do not move; they are discarded and queued again+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+case open; an interrupted restore is completed.+Shared thumbnails do not move; they are discarded and queued againafter restore. Purge removes the journal only after its directory is gone, so aWindows file lock leaves a retryable group instead of orphaned bytes.## Case bundlesExports run as `bundle-export` jobs and write atomically to-`<workspace>/bundles/`, then stream to the browser as an attachment. The first+`<workspace>/.azimut/bundles/`, then stream to the browser as an attachment. The firstZIP member is `bundle-header.json`; the last is `bundle.json`, which lists everyother member with its size and SHA-256. The database is copied consistently,its trash and unfinished jobs are removed, and it is vacuumed before packaging.`.trash/`, `media/.thumbs/` and `media/.dl/` never travel.Export also reserves filesystem headroom before writing its temporary output.+Bundle format 2 carries the complete case under a `case/` member prefix:+`case/azimut/` for application state and every regular entry beside it for the+analyst's free zone. The prefix keeps the bundle metadata outside that free+zone, so even analyst files called `bundle.json` or `bundle-header.json` round+trip. A case-root name that case-insensitively collides with `azimut/` is+refused, as are symbolic links on both export and import. There is no fixed size+ceiling: exports and imports use current free space plus a safety reserve, and+the import dialog warns when the temporary requirement reaches 10 GiB.+Password protection encrypts the complete ZIP in 1 MiB AES-256-GCM chunks. Thekey comes from scrypt (`n=2^15`, `r=8`, `p=1`), and only the envelope parametersremain clear. Passwords live in a process-memory map keyed by job id, never inthe durable payload.Import pre-flights format and database versions before creating a destination.-The browser file picker uploads to `<workspace>/bundles/.imports/`; rejected and+The browser file picker uploads to `<workspace>/.azimut/bundles/.imports/`; rejected andcancelled uploads are removed immediately, completed imports remove their source,and abandoned uploads expire after 24 hours.It verifies unique safe member names, declared and actual byte counts, archive@@ -216,7 +364,7 @@ member count, and rejects symlinks. It extracts only the manifest allowlistafter each hash matches. There is no small fixed case-size cap: preview andimport compare the required temporary space with current filesystem capacity,keep a safety reserve, and warn for imports above 10 GiB. Work is staged under-`cases/<id>.incoming/`; the existing shell and completed staging directory are+`<workspace>/<id>.incoming/`; the existing shell and completed staging directory areswapped by rename for Windows compatibility. Every import creates a new case andrecords `origin_case_id` plus `imported_at` in database metadata.Entities and links keep their original ids, provenance and confirmation status.diff --git a/docs/UI.md b/docs/UI.mdindex c2f8c27..70ea888 100644--- a/docs/UI.md+++ b/docs/UI.md@@ -82,7 +82,15 @@ remembered per workspace for the current session. Reloading restores the default## Case switcher-The switcher creates, renames, opens and deletes cases. **Export this case**+The switcher creates, renames, opens and deletes cases. The menu leads with the+list, since switching is what it is opened for: search on top, cases and scratch+sessions in one scrolling list, and every action in a one-line footer — **New+case** labelled, then import, open folder, export and close as icons, each with+its tooltip. The Case Doctor shield sits with those case-level actions. A case+whose database cannot be opened stays in the list with **Needs attention** and+its own Doctor button, so repairing it does not require opening it first.+Five stacked verbs no longer push the list below the fold.+**Export this case**starts a durable job, then downloads the `.azimut.zip` through the browser.Optional password protection downloads `.azimut.enc`; the dialog states oncethat a lost password cannot be recovered.@@ -94,6 +102,38 @@ always creates a new case, waits for the durableimport job, then opens it. It never replaces or merges an existing case.Confirmed entities and relations remain confirmed in the imported case.+**Folders in the workspace** that are not cases sit at the end of the same+list, dimmed, marked **Not a case yet**. Clicking one makes it a case where it+is: nothing moves, and what was already in the folder stays in the analyst's+half. A folder holding a case that lost its manifest reads **Case to recover**+and opens the Doctor once the manifest is back. A name no case folder can carry+reads **Rename to use** and does nothing until it is renamed.++**Case Doctor** checks without writing. A healthy case gets one short result;+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.++## Workspace folder++Settings → About holds the folder. There is no native picker, so the path is+typed and **Check** reads it before anything is offered: refusals in red,+warnings in amber, and the folder Azimut would actually use when that differs+from the one typed. Two actions follow, never merged, because their outcomes+differ. **Use this folder** switches and moves nothing, and says how many cases+would stay behind. **Move everything here** copies, and while it runs the tab+shows the step and the bytes while Azimut refuses other work. Afterwards the old+folder is named, with one button to delete it. A folder set through+`AZIMUT_HOME` is shown without any of this: the variable wins every launch.++A full-screen panel replaces the app when the workspace can't be worked in, with+the same picker inside it and a different sentence for each reason. **Gone**:+where it was expected, and that nothing has been deleted or recreated.+**Held by another Azimut**: which machine and port has it, what two instances+would cost, and Reload. **Take it anyway** is there for a lock that outlived its+process, warned once and never presented as the ordinary way out.+## RelationsRelations (ONTOLOGY §3) render through one component wherever they appear — the@@ -125,6 +165,12 @@ files beyond the loaded page after a case import. Thumbnail failures are scopedto their case, so switching cases always reloads previews even when relativepaths match. Enrich respects an existing confirmed GPS relation during backfill.+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+characters or resolving a case-insensitive collision. Downloads keep dates and+remote ids in provenance instead of appending them to the visible name.+## MapSaved work — places, captures and screenshots filed by the extension — lives indiff --git a/frontend/e2e/app.fixture.js b/frontend/e2e/app.fixture.jsindex 5d407c9..c694f5f 100644--- a/frontend/e2e/app.fixture.js+++ b/frontend/e2e/app.fixture.js@@ -58,6 +58,23 @@ const settings = {month: '2026-07',};+// A workspace that is present and nobody else's, so the app runs instead of+// showing the stopped screen (GET /settings/workspace), and no folder in it is+// waiting to become a case (GET /workspace/folders).+const workspaceStatus = {+ locked_by: null,+ locked_detail: '',+ root: '/tmp/azimut-browser-fixture',+ default_root: '/tmp/azimut-browser-fixture',+ pointed: false,+ environment: false,+ missing: false,+ moving: false,+ cases: 1,+ move: null,+};+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 },@@ -141,6 +158,10 @@ export async function installAppFixture(page, options = {}) {return route.fulfill({ status: 404, body: '' });}if (path === '/api/settings') return json(route, settings);+ // Asked on mount, before any tool: the app has to know the workspace is+ // there and whether a folder in it is still waiting to become a case.+ if (path === '/api/settings/workspace') return json(route, workspaceStatus);+ 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/bundles/inspect' && request.method() === 'POST') {diff --git a/frontend/src/App.svelte b/frontend/src/App.svelteindex 9460c61..520532e 100644--- a/frontend/src/App.svelte+++ b/frontend/src/App.svelte@@ -25,6 +25,8 @@import CaseSidebar from './components/CaseSidebar.svelte';import Toasts from './components/Toasts.svelte';import UpdateModal from './components/UpdateModal.svelte';+ import WorkspaceStopped from './components/WorkspaceStopped.svelte';+ import { readStatus, stoppedBecause } from './lib/workspace.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@@ -105,6 +107,18 @@void ensureTool(id);});+ // A workspace that can't be worked in replaces the app rather than letting+ // every tool fail one request at a time: a folder that is gone, or one+ // another Azimut holds. The backend refuses case work in both states and+ // touches neither folder, so what is left to do is explain and offer the way+ // out.+ let workspaceStopped = $state(null);+ readStatus()+ .then((status) => {+ workspaceStopped = stoppedBecause(status);+ })+ .catch(() => {});+// 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@@ -222,6 +236,10 @@<Toasts />+{#if workspaceStopped}+ <WorkspaceStopped {...workspaceStopped} />+{/if}+{#if updateState.show}<UpdateModal />{/if}diff --git a/frontend/src/app.css b/frontend/src/app.cssindex 963f31f..53fbe8a 100644--- a/frontend/src/app.css+++ b/frontend/src/app.css@@ -455,3 +455,86 @@ a:hover {min-height: 0;overflow: auto;}++/* Rendered Markdown, from lib/markdown.js. Shared by the Notebook preview and+ the release notes in the update pop-up; anything specific to one of them+ (entity references, diagrams) stays in that component. */+.markdown {+ color: var(--text-1);+ line-height: 1.65;+ overflow-wrap: anywhere;+}+.markdown h1,+.markdown h2,+.markdown h3 {+ margin: 0 0 12px;+ line-height: 1.25;+}+.markdown p,+.markdown ul,+.markdown ol,+.markdown blockquote {+ margin: 0 0 12px;+}+.markdown ul,+.markdown ol {+ padding-left: 20px;+}+.markdown blockquote {+ padding-left: 12px;+ border-left: 2px solid var(--border);+ color: var(--text-2);+}+.markdown code {+ padding: 1px 4px;+ border-radius: 3px;+ background: var(--bg-2);+ font-family: var(--mono);+}+.markdown pre {+ margin: 0 0 12px;+ padding: 12px;+ overflow: auto;+ border: 1px solid var(--border);+ border-radius: var(--r-sm);+ background: var(--bg-1);+}+.markdown pre code {+ padding: 0;+ background: transparent;+}+.markdown table {+ width: 100%;+ margin: 0 0 12px;+ border-collapse: collapse;+ font-size: var(--fs-sm);+}+.markdown th,+.markdown td {+ padding: 7px 9px;+ border: 1px solid var(--border);+ text-align: left;+ vertical-align: top;+}+.markdown th {+ background: var(--bg-2);+}+.markdown input[type='checkbox'] {+ margin-right: 6px;+ accent-color: var(--accent);+}+.markdown img,+.markdown video {+ display: block;+ max-width: 100%;+ height: auto;+ margin: 0 0 12px;+ border-radius: var(--r-sm);+ border: 1px solid var(--border);+}+.markdown a {+ color: var(--accent);+}+.markdown > :last-child {+ margin-bottom: 0;+}diff --git a/frontend/src/components/CaseSwitcher.svelte b/frontend/src/components/CaseSwitcher.svelteindex 37c2da8..a46e8c6 100644--- a/frontend/src/components/CaseSwitcher.svelte+++ b/frontend/src/components/CaseSwitcher.svelte@@ -5,6 +5,8 @@refreshCaseList,openCase,createCase,+ adoptFolder,+ recoverFolder,promoteCase,renameCase,closeCase,@@ -19,6 +21,8 @@startBundleImport,waitForBundle,} from '../lib/bundles.js';+ import { checkCase, repairCase } from '../lib/doctor.js';+ import { revealCaseFolder } from '../lib/reveal.js';import { formatSize } from '../lib/trash.js';import Icon from './Icon.svelte';import Modal from './Modal.svelte';@@ -38,9 +42,85 @@let bundlePreview = $state(null);let bundleError = $state('');let bundleJobController = null;+ let doctorTarget = $state(null);+ let doctorReport = $state(null);+ let doctorBusy = $state(false);+ let doctorError = $state('');+ let doctorReplacements = $state({});+ let doctorConfirm = $state(null);onDestroy(() => bundleJobController?.abort());+ // Nothing opens in the tab, so say something either way: a file manager window+ // can land behind the browser, and a headless box has none at all.+ async function revealFolder() {+ open = false;+ const id = caseState.current?.id;+ if (!id) return;+ try {+ await revealCaseFolder(id);+ toast('Opened the case folder', 'ok', 2500);+ } catch (error) {+ toast(error.message || 'Could not open the folder', 'danger', 7000);+ }+ }++ async function openDoctor(c = caseState.current) {+ if (!c) return;+ open = false;+ doctorTarget = { id: c.id, name: c.name ?? c.id };+ doctorReport = null;+ doctorError = '';+ doctorReplacements = {};+ doctorConfirm = null;+ doctorBusy = true;+ try {+ doctorReport = await checkCase(c.id);+ } catch (error) {+ doctorError = error.message || 'Could not check this case';+ } finally {+ doctorBusy = false;+ }+ }++ function closeDoctor() {+ if (doctorBusy) return;+ doctorTarget = null;+ doctorReport = null;+ doctorError = '';+ }++ async function runDoctorRepair(issue, action) {+ if (!doctorTarget || doctorBusy) return;+ if (action.id === 'drop' && doctorConfirm !== issue.id) {+ doctorConfirm = issue.id;+ return;+ }+ const repair = { action: action.id };+ if (issue.entity_id) repair.entity_id = issue.entity_id;+ if (action.id === 'import') repair.path = issue.path;+ if (action.id === 'relink') {+ repair.replacement = doctorReplacements[issue.id];+ if (!repair.replacement) return;+ }+ doctorBusy = true;+ doctorError = '';+ try {+ const result = await repairCase(doctorTarget.id, repair);+ doctorReport = result.report;+ doctorConfirm = null;+ await refreshCaseList();+ if (caseState.current?.id === doctorTarget.id) {+ await openCase(doctorTarget.id);+ }+ toast('Case repair complete', 'ok', 3000);+ } catch (error) {+ doctorError = error.message || 'Could not repair this case';+ } finally {+ doctorBusy = false;+ }+ }+function openBundle(kind) {open = false;bundleModal = kind;@@ -260,8 +340,49 @@}}+ // A folder the analyst made in the workspace from their file manager. Using+ // it fills in `azimut/` and leaves everything else exactly where it is; one+ // that lost its manifest is recovered instead, then handed to the Doctor.+ let folderBusy = $state(false);++ const folderNote = (f) =>+ f.state === 'broken'+ ? 'Case to recover'+ : f.state === 'unusable-name'+ ? 'Rename to use'+ : 'Not a case yet';++ const folderTitle = (f) =>+ f.state === 'broken'+ ? 'Recover the case in this folder'+ : f.state === 'unusable-name'+ ? 'Rename this folder to use it'+ : 'Make this folder a case';++ async function useFolder(folder) {+ if (folderBusy || folder.state === 'unusable-name') return;+ folderBusy = true;+ try {+ if (folder.state === 'broken') {+ const recovered = await recoverFolder(folder.name);+ toast(`Recovered “${recovered.name}”`, 'ok');+ await openDoctor({ id: recovered.id, name: recovered.name });+ } else {+ open = false;+ const adopted = await adoptFolder(folder.name);+ toast(`Case “${adopted.name ?? folder.name}” created`, 'ok');+ }+ } catch (error) {+ toast(error.message || 'Could not use this folder', 'danger', 7000);+ } finally {+ folderBusy = false;+ }+ }+const named = $derived(caseState.list.filter((c) => !c.scratch));const scratches = $derived(caseState.list.filter((c) => c.scratch));+ const folders = $derived(caseState.folders);+ const visibleFolders = $derived(folders.filter(matchesSearch));// Filtered views for the menu list (the unfiltered `named` still backs the// duplicate-name guard below, which must see every case).const visibleNamed = $derived(named.filter(matchesSearch));@@ -306,41 +427,31 @@{#if open}<button class="backdrop" onclick={() => (open = false)} aria-label="Close menu"></button><div class="menu card">- <button- class="item new"- onclick={() => {- open = false;- modal = 'create';- nameInput = '';- }}- >- <Icon name="plus" size={15} /> New case…- </button>- <button class="item" onclick={() => openBundle('import')}>- <Icon name="upload" size={15} /> Import case…- </button>- {#if caseState.current}- <button class="item" onclick={() => openBundle('export')}>- <Icon name="download" size={15} /> Export this case…- </button>- <button class="item" onclick={() => { closeCase(); open = false; }}>- <Icon name="x" size={15} /> Close case (one-shot mode)- </button>- {/if}{#if named.length + scratches.length > 6 || search.trim()}<div class="search-row"><SearchInput bind:value={search} placeholder="Find a case…" width="100%" /></div>{/if}- {#if visibleNamed.length}- <div class="section">Cases</div>+ <div class="list">{#each visibleNamed as c (c.id)}<div class="row" class:active={c.id === caseState.current?.id}><button class="item" onclick={() => pick(c.id)}><Icon name="folder" size={15} /><span class="grow">{c.name}</span>- <span class="meta">{c.entity_count} entities</span>+ <span class="meta">+ {c.health === 'needs-attention' ? 'Needs attention' : `${c.entity_count} entities`}+ </span></button>+ {#if c.health === 'needs-attention'}+ <button+ class="del doctor attention"+ title="Check case"+ aria-label="Check case"+ onclick={() => openDoctor(c)}+ >+ <Icon name="alert" size={14} />+ </button>+ {/if}<button class="del rename" title="Rename case" onclick={() => askRename(c)}><Icon name="edit" size={14} /></button>@@ -349,26 +460,106 @@</button></div>{/each}- {/if}- {#if visibleScratches.length}- <div class="section">Scratch sessions</div>{#each visibleScratches as c (c.id)}<div class="row" class:active={c.id === caseState.current?.id}><button class="item" onclick={() => pick(c.id)}><Icon name="clock" size={15} /><span class="grow">{c.id}</span>+ <span class="badge accent">scratch</span></button>+ {#if c.health === 'needs-attention'}+ <button+ class="del doctor attention"+ title="Check session"+ aria-label="Check session"+ onclick={() => openDoctor(c)}+ >+ <Icon name="alert" size={14} />+ </button>+ {/if}<button class="del" title="Delete session" onclick={() => askDelete(c)}><Icon name="trash" size={14} /></button></div>{/each}- {/if}- {#if !named.length && !scratches.length}- <div class="hint">No cases yet. Tools work without one.</div>- {:else if !visibleNamed.length && !visibleScratches.length}- <div class="hint">No case matches “{search.trim()}”.</div>- {/if}+ {#each visibleFolders as f (f.name)}+ <div class="row folder">+ <button+ class="item"+ title={folderTitle(f)}+ disabled={folderBusy || f.state === 'unusable-name'}+ onclick={() => useFolder(f)}+ >+ <Icon name="folder" size={15} />+ <span class="grow">{f.name}</span>+ <span class="meta">{folderNote(f)}</span>+ </button>+ </div>+ {/each}+ {#if !named.length && !scratches.length && !folders.length}+ <div class="hint">No cases yet. Tools work without one.</div>+ {:else if !visibleNamed.length && !visibleScratches.length && !visibleFolders.length}+ <div class="hint">No case matches “{search.trim()}”.</div>+ {/if}+ </div>+ <div class="foot">+ <button+ class="foot-btn new"+ onclick={() => {+ open = false;+ modal = 'create';+ nameInput = '';+ }}+ >+ <Icon name="plus" size={15} /> New case+ </button>+ <!-- Icon-only past this point: the labels ride in the tooltip so the+ whole row fits on one line. Keep every one of them titled. -->+ <div class="foot-icons">+ <button+ class="foot-btn icon"+ title="Import case…"+ aria-label="Import case…"+ onclick={() => openBundle('import')}+ >+ <Icon name="upload" size={16} />+ </button>+ {#if caseState.current}+ <button+ class="foot-btn icon"+ title="Check this case"+ aria-label="Check this case"+ onclick={() => openDoctor()}+ >+ <Icon name="shield" size={16} />+ </button>+ <button+ class="foot-btn icon"+ title="Open case folder"+ aria-label="Open case folder"+ onclick={revealFolder}+ >+ <Icon name="folderOpen" size={16} />+ </button>+ <button+ class="foot-btn icon"+ title="Export this case…"+ aria-label="Export this case…"+ onclick={() => openBundle('export')}+ >+ <Icon name="download" size={16} />+ </button>+ <button+ class="foot-btn icon"+ title="Close case (one-shot mode)"+ aria-label="Close case (one-shot mode)"+ onclick={() => { closeCase(); open = false; }}+ >+ <Icon name="x" size={16} />+ </button>+ {/if}+ </div>+ </div></div>{/if}</div>@@ -514,6 +705,94 @@</Modal>{/if}+{#if doctorTarget}+ <Modal title="Case Doctor" onclose={closeDoctor}>+ <p class="doctor-intro">Checks “{doctorTarget.name}” without changing it.</p>+ {#if doctorBusy && !doctorReport}+ <div class="doctor-empty">Checking…</div>+ {:else if doctorError && !doctorReport}+ <p class="err">{doctorError}</p>+ {:else if doctorReport?.status === 'healthy'}+ <div class="doctor-healthy">+ <span><Icon name="check" size={18} /></span>+ <div>+ <strong>No problems found</strong>+ <p>The database and media records match the case files.</p>+ </div>+ </div>+ {:else if doctorReport}+ <div class="doctor-list">+ {#each doctorReport.issues as issue (issue.id)}+ <section class="doctor-issue" class:error={issue.severity === 'error'}>+ <div class="doctor-heading">+ <Icon name={issue.severity === 'error' ? 'alert' : 'info'} size={17} />+ <div>+ <strong>{issue.title}</strong>+ <p>{issue.detail}</p>+ </div>+ </div>+ {#if issue.losses?.length}+ <div class="doctor-losses">+ <span>Cannot be recovered:</span>+ <ul>+ {#each issue.losses as loss}<li>{loss}</li>{/each}+ </ul>+ </div>+ {/if}+ {#if issue.actions.some((action) => action.id === 'relink')}+ <label class="label" for={`doctor-replacement-${issue.entity_id}`}>+ Replacement file+ </label>+ <select+ id={`doctor-replacement-${issue.entity_id}`}+ class="input"+ value={doctorReplacements[issue.id] ?? ''}+ onchange={(event) => {+ doctorReplacements[issue.id] = event.currentTarget.value;+ }}+ >+ <option value="">Choose a file from media…</option>+ {#each issue.replacements ?? [] as replacement}+ <option value={replacement}>{replacement.replace('media/', '')}</option>+ {/each}+ </select>+ {#if !issue.replacements?.length}+ <p class="doctor-help">Add the replacement to the media folder, then check again.</p>+ {/if}+ {/if}+ <div class="doctor-actions">+ {#each issue.actions as action}+ <button+ type="button"+ class="btn btn-sm"+ class:btn-primary={action.tone === 'primary'}+ class:btn-danger={action.tone === 'danger'}+ disabled={doctorBusy ||+ (action.id === 'relink' && !doctorReplacements[issue.id])}+ onclick={() => runDoctorRepair(issue, action)}+ >+ {action.id === 'drop' && doctorConfirm === issue.id+ ? 'Remove record?'+ : action.label}+ </button>+ {/each}+ </div>+ </section>+ {/each}+ </div>+ {#if doctorError}<p class="err">{doctorError}</p>{/if}+ {/if}+ <div class="actions">+ {#if doctorReport?.status === 'issues'}+ <button type="button" class="btn" disabled={doctorBusy} onclick={() => openDoctor(doctorTarget)}>+ Check again+ </button>+ {/if}+ <button type="button" class="btn" disabled={doctorBusy} onclick={closeDoctor}>Close</button>+ </div>+ </Modal>+{/if}+{#if delTarget}<Modal title="Delete case" onclose={() => (delTarget = null)}><div class="warn">@@ -595,23 +874,60 @@position: absolute;top: calc(100% + 6px);left: 0;- min-width: 300px;- max-height: 420px;- overflow: auto;+ min-width: 320px;+ max-height: 460px;+ display: flex;+ flex-direction: column;+ overflow: hidden;z-index: 100;box-shadow: var(--shadow-2);+ padding: 0;+ }+ /* Only the list scrolls: the search stays reachable at the top and the+ actions stay reachable at the bottom, however long the list gets. */+ .list {+ flex: 1;+ min-height: 0;+ overflow: auto;padding: 6px;}.search-row {- padding: 6px 6px 8px;+ padding: 8px 8px 4px;}- .section {- font-size: var(--fs-xs);- font-weight: 700;- text-transform: uppercase;- letter-spacing: 0.07em;+ .foot {+ display: flex;+ align-items: center;+ gap: 4px;+ padding: 6px;+ border-top: 1px solid var(--border);+ }+ .foot-btn {+ display: flex;+ align-items: center;+ gap: 7px;+ padding: 7px 10px;+ border-radius: var(--r-sm);+ font-size: var(--fs-sm);+ color: var(--text-2);+ white-space: nowrap;+ }+ .foot-btn:hover {+ background: var(--bg-2);+ color: var(--text-1);+ }+ .foot-btn.new {+ color: var(--accent);+ font-weight: 600;+ }+ .foot-icons {+ display: flex;+ align-items: center;+ gap: 2px;+ margin-left: auto;+ }+ .foot-btn.icon {+ padding: 7px 9px;color: var(--text-3);- padding: 10px 10px 4px;}.row {display: flex;@@ -650,6 +966,20 @@.del:hover {color: var(--danger, #e5484d);}+ /* A folder is not a case yet: dimmed until using it makes one. */+ .row.folder .item {+ color: var(--text-2);+ }+ .row.folder .item:disabled {+ color: var(--text-3);+ }+ .row .doctor.attention {+ opacity: 1;+ color: var(--warn, #d8a03d);+ }+ .row .doctor:hover {+ color: var(--text-1);+ }.item {display: flex;align-items: center;@@ -700,10 +1030,6 @@.btn-danger:hover:not(:disabled) {filter: brightness(1.08);}- .item.new {- color: var(--accent);- font-weight: 600;- }.grow {flex: 1;overflow: hidden;@@ -757,6 +1083,57 @@}.bundle-preview .bundle-space.warn { color: var(--warn); }.bundle-preview .bundle-space.danger { color: var(--danger); }+ .doctor-intro {+ margin: 0 0 14px;+ color: var(--text-3);+ font-size: var(--fs-xs);+ }+ .doctor-empty {+ padding: 18px 0;+ color: var(--text-3);+ font-size: var(--fs-sm);+ }+ .doctor-healthy {+ display: flex;+ align-items: flex-start;+ gap: 11px;+ padding: 12px;+ border: 1px solid color-mix(in srgb, var(--ok) 35%, var(--border));+ border-radius: var(--r-sm);+ color: var(--ok);+ }+ .doctor-healthy strong { color: var(--text-1); font-size: var(--fs-sm); }+ .doctor-healthy p { margin: 3px 0 0; color: var(--text-3); font-size: var(--fs-xs); }+ .doctor-list {+ display: grid;+ gap: 10px;+ max-height: 52vh;+ overflow: auto;+ }+ .doctor-issue {+ padding: 12px;+ border: 1px solid var(--border);+ border-radius: var(--r-sm);+ }+ .doctor-issue.error { border-color: color-mix(in srgb, var(--danger) 35%, var(--border)); }+ .doctor-heading { display: flex; align-items: flex-start; gap: 9px; color: var(--warn); }+ .doctor-heading strong { color: var(--text-1); font-size: var(--fs-sm); }+ .doctor-heading p {+ margin: 3px 0 0;+ color: var(--text-3);+ font-size: var(--fs-xs);+ overflow-wrap: anywhere;+ }+ .doctor-losses {+ margin: 10px 0;+ padding: 8px 10px;+ background: var(--bg-2);+ color: var(--text-2);+ font-size: var(--fs-xs);+ }+ .doctor-losses ul { margin: 5px 0 0; padding-left: 18px; }+ .doctor-help { margin: 6px 0 0; color: var(--text-3); font-size: var(--fs-xs); }+ .doctor-actions { display: flex; justify-content: flex-end; gap: 7px; margin-top: 10px; }.actions {display: flex;justify-content: flex-end;diff --git a/frontend/src/components/CaseSwitcher.test.js b/frontend/src/components/CaseSwitcher.test.jsindex 3b9ad86..41f90fb 100644--- a/frontend/src/components/CaseSwitcher.test.js+++ b/frontend/src/components/CaseSwitcher.test.js@@ -28,6 +28,75 @@ describe('CaseSwitcher search', () => {});});+describe('menu layout', () => {+ it('puts the case list first and the verbs in a footer', () => {+ const list = source.indexOf('<div class="list">');+ const foot = source.indexOf('<div class="foot">');+ expect(list).toBeGreaterThan(-1);+ expect(list).toBeLessThan(foot);+ // the two global verbs live in the footer, below the list+ expect(source.indexOf('New case')).toBeGreaterThan(foot);+ expect(source.indexOf('Import case…')).toBeGreaterThan(foot);+ });++ it('scrolls the list alone, so search and actions stay reachable', () => {+ const style = source.slice(source.indexOf('<style>'));+ expect(style).toMatch(/\.menu \{[^}]*overflow: hidden/);+ expect(style).toMatch(/\.list \{[^}]*overflow: auto/);+ });++ it('puts every case action in the footer, icon-only past New case', () => {+ const icons = source.indexOf('<div class="foot-icons">');+ expect(icons).toBeGreaterThan(-1);+ for (const label of [+ 'Import case…',+ 'Check this case',+ 'Open case folder',+ 'Export this case…',+ 'Close case (one-shot mode)',+ ]) {+ expect(source.indexOf(label)).toBeGreaterThan(icons);+ }+ // New case keeps its label; it anchors the row+ expect(source).toContain('New case\n');+ });++ it('names every icon-only button twice, for the tooltip and for a reader', () => {+ const foot = source.slice(source.indexOf('<div class="foot-icons">'), source.indexOf('</div>\n </div>'));+ const titles = foot.match(/title="/g) ?? [];+ const labels = foot.match(/aria-label="/g) ?? [];+ expect(titles.length).toBe(5);+ expect(labels.length).toBe(titles.length);+ });++ it('shows scratch sessions inline with a badge instead of their own section', () => {+ expect(source).not.toContain('Scratch sessions');+ const scratchRow = source.indexOf('{#each visibleScratches');+ expect(source.indexOf('badge accent', scratchRow)).toBeGreaterThan(scratchRow);+ });+});++describe('Case Doctor', () => {+ it('keeps a damaged case actionable even when opening it would fail', () => {+ expect(source).toContain("c.health === 'needs-attention'");+ expect(source).toContain('Needs attention');+ expect(source).toContain('onclick={() => openDoctor(c)}');+ });++ it('diagnoses before offering explicit repairs', () => {+ expect(source).toContain('doctorReport = await checkCase(c.id)');+ expect(source).toContain('Checks “{doctorTarget.name}” without changing it.');+ expect(source).toContain('Cannot be recovered:');+ expect(source).toContain('repairCase(doctorTarget.id, repair)');+ });++ it('requires a replacement for relink and a second click for record removal', () => {+ expect(source).toContain("action.id === 'relink' && !doctorReplacements[issue.id]");+ expect(source).toContain("action.id === 'drop' && doctorConfirm !== issue.id");+ expect(source).toContain('Remove record?');+ });+});+describe('Case bundles', () => {it('offers import globally and export for the open case', () => {expect(source).toContain("openBundle('import')");@@ -68,14 +137,103 @@ describe('refreshCaseList', () => {vi.doMock('../lib/api.js', () => ({ api: { get, post: vi.fn(), del: vi.fn() } }));const { refreshCaseList } = await import('../lib/state.svelte.js');+ get.mockClear();await refreshCaseList();- expect(get).toHaveBeenLastCalledWith('/api/cases');+ expect(get).toHaveBeenNthCalledWith(1, '/api/cases');+ get.mockClear();await refreshCaseList({ q: 'kharkiv strike' });- expect(get).toHaveBeenLastCalledWith('/api/cases?q=kharkiv%20strike');+ expect(get).toHaveBeenNthCalledWith(1, '/api/cases?q=kharkiv%20strike');+ get.mockClear();await refreshCaseList({ q: ' ' });- expect(get).toHaveBeenLastCalledWith('/api/cases');+ expect(get).toHaveBeenNthCalledWith(1, '/api/cases');+ vi.doUnmock('../lib/api.js');+ });++ it('loads the workspace folders alongside the cases, unfiltered', async () => {+ vi.resetModules();+ const get = vi.fn().mockResolvedValue([]);+ vi.doMock('../lib/api.js', () => ({ api: { get, post: vi.fn(), del: vi.fn() } }));+ const { refreshCaseList } = await import('../lib/state.svelte.js');++ get.mockClear();+ await refreshCaseList({ q: 'kharkiv strike' });++ // the folder list is not a case list: the name query does not apply to it+ expect(get).toHaveBeenNthCalledWith(2, '/api/workspace/folders');vi.doUnmock('../lib/api.js');});++ it('still lists the cases when the folder scan fails', async () => {+ vi.resetModules();+ const get = vi.fn(async (url) => {+ if (url === '/api/workspace/folders') throw new Error('nope');+ return [{ id: 'coast', name: 'Coast' }];+ });+ vi.doMock('../lib/api.js', () => ({ api: { get, post: vi.fn(), del: vi.fn() } }));+ const { refreshCaseList, caseState } = await import('../lib/state.svelte.js');++ await refreshCaseList();++ expect(caseState.list).toHaveLength(1);+ expect(caseState.folders).toEqual([]);+ vi.doUnmock('../lib/api.js');+ });+});++describe('workspace folders', () => {+ it('offers a folder the analyst made, and says it is not a case yet', () => {+ expect(source).toContain('visibleFolders');+ expect(source).toContain("'Not a case yet'");+ expect(source).toContain("'Make this folder a case'");+ // listed after the cases, since it is not one+ expect(source.indexOf('visibleFolders as f')).toBeGreaterThan(+ source.indexOf('visibleScratches as c')+ );+ });++ it('recovers a folder whose case lost its manifest, then hands it to the Doctor', () => {+ expect(source).toContain('recoverFolder(folder.name)');+ expect(source).toContain('openDoctor({ id: recovered.id, name: recovered.name })');+ });++ it('asks for a rename instead of offering a name a case folder cannot carry', () => {+ expect(source).toContain("'Rename this folder to use it'");+ expect(source).toContain("f.state === 'unusable-name'");+ expect(source).toMatch(/disabled=\{folderBusy \|\| f\.state === 'unusable-name'\}/);+ });++ it('adopts in place through the API, without touching what is in the folder', async () => {+ vi.resetModules();+ const post = vi.fn().mockResolvedValue({ id: 'Oceanside match', name: 'Oceanside match' });+ const get = vi.fn().mockResolvedValue([]);+ vi.doMock('../lib/api.js', () => ({ api: { get, post, del: vi.fn() } }));+ const { adoptFolder, caseState } = await import('../lib/state.svelte.js');++ await adoptFolder('Oceanside match');++ expect(post).toHaveBeenCalledWith('/api/workspace/folders/adopt', { name: 'Oceanside match' });+ expect(get).toHaveBeenLastCalledWith('/api/cases/Oceanside match');+ expect(caseState.current).toBeTruthy();+ vi.doUnmock('../lib/api.js');+ });+});++describe('open case folder', () => {+ it('sits with the other case-level actions and only when a case is open', () => {+ expect(source).toContain("import { revealCaseFolder } from '../lib/reveal.js'");+ expect(source).toContain('Open case folder');+ // inside the {#if caseState.current} block, above Export this case…+ const guard = source.indexOf('{#if caseState.current}');+ const reveal = source.indexOf('Open case folder');+ const exportItem = source.indexOf('Export this case…');+ expect(guard).toBeLessThan(reveal);+ expect(reveal).toBeLessThan(exportItem);+ });++ it('says something either way, since nothing opens in the tab', () => {+ expect(source).toContain("toast('Opened the case folder'");+ expect(source).toContain("toast(error.message || 'Could not open the folder'");+ });});diff --git a/frontend/src/components/UpdateModal.svelte b/frontend/src/components/UpdateModal.svelteindex 9939f24..772a1e5 100644--- a/frontend/src/components/UpdateModal.svelte+++ b/frontend/src/components/UpdateModal.svelte@@ -1,22 +1,25 @@<script>import Modal from './Modal.svelte';import Icon from './Icon.svelte';+ import { markdownHtml } from '../lib/markdown.js';import { updateState, dismissUpdate } from '../lib/state.svelte.js';let mute = $state(false);+ const notes = $derived(markdownHtml(updateState.notes));+function close() {dismissUpdate(mute);}</script>-<Modal title="{updateState.latest} is live" onclose={close} width="520px">+<Modal title="{updateState.latest} is live" onclose={close} width="600px"><p class="lead">A newer version of Azimut is out. Grab it to stay current.</p>{#if updateState.notes}- <!-- release body from our own GitHub release; rendered as plain text, never- as HTML, so there is nothing to inject -->- <pre class="notes">{updateState.notes}</pre>+ <!-- Release body from our own GitHub release, written in Markdown. It goes+ through the same renderer as the Notebook, which strips unsafe HTML. -->+ <div class="notes markdown">{@html notes}</div>{/if}<div class="actions">@@ -48,7 +51,7 @@}.notes {margin: 12px 0;- padding: 10px 12px;+ padding: 12px 14px;max-height: 40vh;overflow: auto;background: var(--bg-0);@@ -56,9 +59,17 @@border-radius: var(--r-md);color: var(--text-2);font-size: var(--fs-sm);- line-height: 1.5;- white-space: pre-wrap;- word-break: break-word;+ }+ /* A release note leads with its own headings, which would otherwise shout+ over the modal title. */+ .notes :global(h1),+ .notes :global(h2) {+ font-size: var(--fs-md);+ font-weight: 600;+ }+ .notes :global(h3) {+ font-size: var(--fs-sm);+ font-weight: 600;}.actions {display: flex;diff --git a/frontend/src/components/UpdateModal.test.js b/frontend/src/components/UpdateModal.test.jsnew file mode 100644index 0000000..277a01f--- /dev/null+++ b/frontend/src/components/UpdateModal.test.js@@ -0,0 +1,33 @@+import { describe, expect, it } from 'vitest';+import { readFileSync } from 'node:fs';+import { markdownHtml } from '../lib/markdown.js';++const source = readFileSync(new URL('./UpdateModal.svelte', import.meta.url), 'utf8');++describe('release notes', () => {+ it('renders the release body as Markdown, through the shared renderer', () => {+ expect(source).toContain("import { markdownHtml } from '../lib/markdown.js'");+ expect(source).toContain('markdownHtml(updateState.notes)');+ expect(source).toContain('<div class="notes markdown">{@html notes}</div>');+ });++ it('scrolls a long note inside the pop-up', () => {+ expect(source).toMatch(/\.notes \{[^}]*max-height: 40vh;[^}]*overflow: auto;/s);+ });++ it('turns a release body into headings, lists and links', () => {+ const html = markdownHtml("## What's new\n\n- A [fix](https://example.invalid/pr/1)\n");+ expect(html).toContain("<h2>What's new</h2>");+ expect(html).toContain('<li>A <a href="https://example.invalid/pr/1" target="_blank" rel="noreferrer">fix</a></li>');+ });++ it('drops HTML a release body should never carry', () => {+ const html = markdownHtml('<script>alert(1)</script>\n\n[bad](javascript:alert(1))');+ expect(html).not.toContain('<script>');+ expect(html).not.toContain('javascript:');+ });++ it('shows nothing when the release has no body', () => {+ expect(source).toContain('{#if updateState.notes}');+ });+});diff --git a/frontend/src/components/WorkspaceFolder.svelte b/frontend/src/components/WorkspaceFolder.sveltenew file mode 100644index 0000000..c581ef5--- /dev/null+++ b/frontend/src/components/WorkspaceFolder.svelte@@ -0,0 +1,313 @@+<script>+ import Icon from './Icon.svelte';+ import { pollWhile } from '../lib/poll.js';+ import {+ discardOldWorkspace,+ humanBytes,+ inspectFolder,+ moveProgress,+ moveWorkspace,+ offers,+ readStatus,+ useDefaultFolder,+ useFolder,+ } from '../lib/workspace.js';++ let { onchange } = $props();++ let status = $state(null);+ let path = $state('');+ let verdict = $state(null);+ let busy = $state(false);+ let error = $state('');+ let stop = () => {};++ const move = $derived(status?.move ?? null);+ const progress = $derived(moveProgress(move));+ const can = $derived(offers(verdict));++ $effect(() => {+ refresh();+ return () => stop();+ });++ async function refresh() {+ try {+ status = await readStatus();+ } catch (e) {+ error = e.message || 'Could not read the workspace';+ return;+ }+ stop();+ if (status.moving) {+ stop = pollWhile(+ () => true,+ async () => {+ status = await readStatus();+ if (!status.moving) {+ stop();+ verdict = null;+ path = '';+ onchange?.(status);+ }+ },+ 500+ );+ }+ }++ async function run(action) {+ busy = true;+ error = '';+ try {+ return await action();+ } catch (e) {+ error = e.message || 'That did not work';+ return null;+ } finally {+ busy = false;+ }+ }++ async function check() {+ verdict = await run(() => inspectFolder(path));+ }++ async function use() {+ const next = await run(() => useFolder(verdict.root));+ if (next) settle(next);+ }++ async function goDefault() {+ const next = await run(() => useDefaultFolder());+ if (next) settle(next);+ }++ async function start() {+ const started = await run(() => moveWorkspace(verdict.root));+ if (started) await refresh();+ }++ async function discard() {+ await run(() => discardOldWorkspace());+ await refresh();+ }++ function settle(next) {+ status = next;+ verdict = null;+ path = '';+ onchange?.(next);+ }+</script>++<section class="group">+ <h3>Workspace folder</h3>++ {#if status?.environment}+ <p class="note">+ AZIMUT_HOME is set, so this run uses <span class="mono">{status.root}</span>. Unset it to+ choose a folder here.+ </p>+ {:else}+ <dl class="facts">+ <dt>Current</dt>+ <dd class="mono">{status?.root ?? '—'}</dd>+ <dt>Holds</dt>+ <dd>{status?.cases ?? 0} case{status?.cases === 1 ? '' : 's'}</dd>+ </dl>++ {#if move && !move.done}+ <div class="progress" role="status">+ <div class="bar"><div class="fill" style:width="{progress.percent}%"></div></div>+ <span class="step">+ {progress.label}+ {#if move.step === 'copying' && move.total_bytes}+ <span class="sub">+ {humanBytes(move.copied_bytes)} of {humanBytes(move.total_bytes)}+ </span>+ {/if}+ </span>+ </div>+ <p class="note">Leave this tab open. Azimut is closed to other work until it finishes.</p>+ {:else}+ {#if move?.error}+ <p class="problem">The move stopped: {move.error}. Nothing was lost.</p>+ {/if}++ <div class="picker">+ <input+ class="input mono"+ bind:value={path}+ placeholder="/path/to/a/folder"+ aria-label="Folder"+ onkeydown={(e) => e.key === 'Enter' && check()}+ />+ <button class="btn btn-sm" onclick={check} disabled={busy || !path.trim()}>Check</button>+ </div>++ {#if verdict}+ <div class="verdict">+ {#each verdict.problems as problem}+ <p class="problem">{problem}</p>+ {/each}+ {#each verdict.warnings as warning}+ <p class="warning">{warning}</p>+ {/each}+ {#if verdict.ok}+ {#if verdict.nested}+ <p class="note">+ That folder holds other files, so Azimut would use+ <span class="mono">{verdict.root}</span> inside it.+ </p>+ {/if}+ {#if verdict.state === 'workspace'}+ <p class="note">+ Already an Azimut workspace, with {verdict.cases} case{verdict.cases === 1+ ? ''+ : 's'}.+ </p>+ {/if}+ {#if can.strands}+ <p class="warning">+ Using it leaves {can.strands} case{can.strands === 1 ? '' : 's'} in the current+ folder.+ </p>+ {/if}+ <div class="actions">+ {#if can.use}+ <button class="btn btn-sm" onclick={use} disabled={busy}>+ <Icon name="folderOpen" size={13} /> Use this folder+ </button>+ {/if}+ {#if can.move}+ <button class="btn btn-sm btn-primary" onclick={start} disabled={busy}>+ Move everything here+ </button>+ {/if}+ </div>+ {/if}+ </div>+ {/if}++ {#if move?.done && !move.error && move.kept_aside}+ <div class="kept">+ <p class="note">+ The old folder is still at <span class="mono">{move.kept_aside}</span>.+ </p>+ <button class="btn btn-sm btn-danger" onclick={discard} disabled={busy}>+ Delete the old copy+ </button>+ </div>+ {/if}++ {#if status?.pointed}+ <button class="btn btn-ghost btn-sm" onclick={goDefault} disabled={busy}>+ Back to {status.default_root}+ </button>+ {/if}+ {/if}++ {#if error}+ <p class="problem">{error}</p>+ {/if}+ {/if}+</section>++<style>+ /* This block sits inside Settings' About tab and inside the stopped-workspace+ panel. Neither parent's scoped styles reach in here, so the group heading,+ the fact list and the notes are restated with the shared tokens — same+ shape as every other Settings group. */+ .group {+ padding: 14px 0 18px;+ }+ h3 {+ font-size: var(--fs-xs);+ font-weight: 700;+ text-transform: uppercase;+ letter-spacing: 0.06em;+ color: var(--text-3);+ margin-bottom: 12px;+ }+ .facts {+ display: grid;+ grid-template-columns: max-content 1fr;+ gap: 6px 18px;+ margin: 0;+ font-size: var(--fs-sm);+ }+ .facts dt {+ color: var(--text-3);+ font-size: var(--fs-xs);+ align-self: center;+ }+ .facts dd {+ margin: 0;+ color: var(--text-1);+ overflow-wrap: anywhere;+ }+ .note {+ color: var(--text-3);+ font-size: var(--fs-xs);+ line-height: 1.5;+ margin-top: 8px;+ }+ .picker {+ display: flex;+ gap: 8px;+ margin-top: 10px;+ }+ .picker .input {+ flex: 1;+ min-width: 0;+ }+ .verdict {+ margin-top: 10px;+ display: flex;+ flex-direction: column;+ gap: 6px;+ }+ .actions,+ .kept {+ display: flex;+ gap: 8px;+ align-items: center;+ flex-wrap: wrap;+ margin-top: 6px;+ }+ .problem {+ color: var(--danger);+ font-size: var(--fs-xs);+ margin: 0;+ }+ .warning {+ color: var(--warn);+ font-size: var(--fs-xs);+ margin: 0;+ }+ .progress {+ margin-top: 10px;+ display: flex;+ flex-direction: column;+ gap: 6px;+ }+ .bar {+ height: 6px;+ border-radius: 3px;+ background: var(--bg-2);+ overflow: hidden;+ }+ .fill {+ height: 100%;+ background: var(--accent);+ transition: width 0.2s linear;+ }+ .step {+ font-size: var(--fs-xs);+ color: var(--text-2);+ }+ .step .sub {+ color: var(--text-3);+ }+</style>diff --git a/frontend/src/components/WorkspaceFolder.test.js b/frontend/src/components/WorkspaceFolder.test.jsnew file mode 100644index 0000000..ffce3b1--- /dev/null+++ b/frontend/src/components/WorkspaceFolder.test.js@@ -0,0 +1,100 @@+import { describe, expect, it } from 'vitest';+import { readFileSync } from 'node:fs';++const source = readFileSync(new URL('./WorkspaceFolder.svelte', import.meta.url), 'utf8');+const stopped = readFileSync(new URL('./WorkspaceStopped.svelte', import.meta.url), 'utf8');++describe('picking a workspace folder', () => {+ it('checks a folder before offering anything to do with it', () => {+ expect(source).toContain('inspectFolder(path)');+ expect(source).toContain('{#if verdict}');+ expect(source).toContain('{#each verdict.problems as problem}');+ expect(source).toContain('{#each verdict.warnings as warning}');+ });++ it('acts on the folder the backend resolved, not the one that was typed', () => {+ // a destination holding other files is redirected into an `Azimut` subfolder+ expect(source).toContain('useFolder(verdict.root)');+ expect(source).toContain('moveWorkspace(verdict.root)');+ expect(source).toContain('{#if verdict.nested}');+ });++ it('separates using a folder from moving into it', () => {+ expect(source).toContain('{#if can.use}');+ expect(source).toContain('{#if can.move}');+ expect(source).toContain('Use this folder');+ expect(source).toContain('Move everything here');+ });++ it('says how many cases would stay behind', () => {+ expect(source).toContain('{#if can.strands}');+ expect(source).toMatch(/Using it leaves \{can\.strands\} case/);+ });+});++describe('a move in progress', () => {+ it('polls while the backend reports one running', () => {+ expect(source).toContain("import { pollWhile } from '../lib/poll.js'");+ expect(source).toContain('if (status.moving)');+ });++ it('names the step and follows the bytes', () => {+ expect(source).toContain('moveProgress(move)');+ expect(source).toContain('{progress.label}');+ expect(source).toContain('humanBytes(move.copied_bytes)');+ });++ it('says the app is closed to other work rather than letting tools fail', () => {+ expect(source).toContain('closed to other work');+ });++ it('offers the old copy for deletion, and only after a clean move', () => {+ expect(source).toContain('{#if move?.done && !move.error && move.kept_aside}');+ expect(source).toContain('discardOldWorkspace()');+ });++ it('states that a stopped move lost nothing', () => {+ expect(source).toContain('{#if move?.error}');+ expect(source).toContain('Nothing was lost');+ });+});++describe('a folder set from the environment', () => {+ it('shows the path and hides the actions, since the env var wins every launch', () => {+ expect(source).toContain('{#if status?.environment}');+ expect(source).toContain('AZIMUT_HOME is set');+ });+});++describe('the stop screen', () => {+ it('names the folder Azimut expected and reuses the same picker', () => {+ expect(stopped).toContain("import WorkspaceFolder from './WorkspaceFolder.svelte'");+ expect(stopped).toContain('{root}');+ expect(stopped).toContain("The workspace folder isn't there");+ });++ it('says nothing was deleted or recreated', () => {+ expect(stopped).toContain('Nothing has been deleted or recreated');+ });++ it('reloads once a folder is chosen, so the app opens against the new root', () => {+ expect(stopped).toContain('onchange={() => location.reload()}');+ });++ it('tells a folder another Azimut holds from a folder that is gone', () => {+ expect(stopped).toContain("{#if reason === 'locked'}");+ expect(stopped).toContain('Another Azimut has this workspace');+ expect(stopped).toContain('{detail}');+ });++ it('says what two instances would cost, then offers to close the other one', () => {+ expect(stopped).toMatch(/lose settings and can leave a case half-migrated/);+ expect(stopped).toContain('Close the other Azimut and reload');+ });++ it('keeps the escape hatch, and warns before it', () => {+ expect(stopped).toContain('takeWorkspaceLock()');+ expect(stopped).toContain('Take it anyway');+ expect(stopped).toContain('Take it only if that Azimut is gone');+ });+});diff --git a/frontend/src/components/WorkspaceStopped.svelte b/frontend/src/components/WorkspaceStopped.sveltenew file mode 100644index 0000000..4dc587a--- /dev/null+++ b/frontend/src/components/WorkspaceStopped.svelte@@ -0,0 +1,127 @@+<script>+ /**+ * Shown instead of the app when the workspace can't be worked in.+ *+ * Two reasons, and they need different sentences. A folder that isn't there+ * is never recreated: an empty workspace where an investigation used to be is+ * the fastest way to conclude the work is gone. A folder another Azimut holds+ * is fine — it just isn't ours, and the way out is to close the other one, or+ * to say it is a ghost and take it.+ *+ * Either way the picker Settings uses is right here, so pointing somewhere+ * else is one action away.+ */+ import Logo from './Logo.svelte';+ import Wordmark from './Wordmark.svelte';+ import WorkspaceFolder from './WorkspaceFolder.svelte';+ import { takeWorkspaceLock } from '../lib/workspace.js';++ let { reason, root, detail = '' } = $props();++ let busy = $state(false);+ let error = $state('');++ async function take() {+ busy = true;+ error = '';+ try {+ await takeWorkspaceLock();+ location.reload();+ } catch (e) {+ error = e.message || 'Could not take the workspace';+ busy = false;+ }+ }+</script>++<div class="stop">+ <div class="panel">+ <div class="brand">+ <Logo size={30} />+ <Wordmark height={14} />+ </div>++ {#if reason === 'locked'}+ <h2>Another Azimut has this workspace</h2>+ <p class="where">{detail}</p>+ <p class="note">+ Two instances writing one workspace lose settings and can leave a case half-migrated, so+ this one hasn't touched it. Close the other Azimut and reload.+ </p>+ <div class="actions">+ <button class="btn btn-sm" onclick={() => location.reload()} disabled={busy}>Reload</button>+ <button class="btn btn-sm btn-danger" onclick={take} disabled={busy}>+ Take it anyway+ </button>+ </div>+ <p class="note">+ Take it only if that Azimut is gone. A lock can outlive it on a synced folder, or when two+ machines disagree about the time.+ </p>+ {#if error}+ <p class="problem">{error}</p>+ {/if}+ {:else}+ <h2>The workspace folder isn't there</h2>+ <p class="where">Azimut expected it at <span class="mono">{root}</span>.</p>+ <p class="note">+ An external drive that isn't plugged in, a folder that was renamed, or a sync client that+ hasn't finished. Nothing has been deleted or recreated.+ </p>+ {/if}++ <WorkspaceFolder onchange={() => location.reload()} />+ </div>+</div>++<style>+ .stop {+ position: fixed;+ inset: 0;+ display: flex;+ align-items: center;+ justify-content: center;+ background: var(--bg-0);+ padding: 24px;+ overflow: auto;+ z-index: 950;+ }+ .panel {+ width: min(560px, 100%);+ background: var(--bg-1);+ border: 1px solid var(--border);+ border-radius: var(--r-lg);+ padding: 24px;+ }+ .brand {+ display: flex;+ align-items: center;+ gap: 9px;+ margin-bottom: 18px;+ }+ h2 {+ margin: 0 0 6px;+ font-size: var(--fs-lg);+ font-weight: 600;+ }+ .where {+ margin: 0 0 10px;+ font-size: var(--fs-sm);+ }+ .note {+ color: var(--text-3);+ font-size: var(--fs-xs);+ line-height: 1.5;+ margin-top: 8px;+ }+ .actions {+ display: flex;+ gap: 8px;+ margin: 10px 0;+ }+ .problem {+ color: var(--danger);+ font-size: var(--fs-xs);+ margin: 0;+ }+</style>diff --git a/frontend/src/lib/doctor.js b/frontend/src/lib/doctor.jsnew file mode 100644index 0000000..2be5b4c--- /dev/null+++ b/frontend/src/lib/doctor.js@@ -0,0 +1,11 @@+import { api } from './api.js';++const casePath = (caseId) => `/api/cases/${encodeURIComponent(caseId)}/doctor`;++export function checkCase(caseId) {+ return api.get(casePath(caseId));+}++export function repairCase(caseId, repair) {+ return api.post(`${casePath(caseId)}/repair`, repair);+}diff --git a/frontend/src/lib/doctor.test.js b/frontend/src/lib/doctor.test.jsnew file mode 100644index 0000000..eb5c58a--- /dev/null+++ b/frontend/src/lib/doctor.test.js@@ -0,0 +1,28 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++const get = vi.fn();+const post = vi.fn();++vi.mock('./api.js', () => ({ api: { get, post } }));++const { checkCase, repairCase } = await import('./doctor.js');++describe('Case Doctor API', () => {+ beforeEach(() => {+ get.mockReset();+ post.mockReset();+ });++ it('encodes case ids in diagnostic and repair paths', async () => {+ get.mockResolvedValue({ status: 'healthy' });+ post.mockResolvedValue({ report: { status: 'healthy' } });++ await checkCase('scratch / 1');+ await repairCase('scratch / 1', { action: 'rebuild' });++ expect(get).toHaveBeenCalledWith('/api/cases/scratch%20%2F%201/doctor');+ expect(post).toHaveBeenCalledWith('/api/cases/scratch%20%2F%201/doctor/repair', {+ action: 'rebuild',+ });+ });+});diff --git a/frontend/src/lib/naming.js b/frontend/src/lib/naming.jsindex d5a2cbe..1f28f90 100644--- a/frontend/src/lib/naming.js+++ b/frontend/src/lib/naming.js@@ -2,27 +2,38 @@* Naming rules shared by everything the analyst saves under a name: inspect* sessions, proofs and post drafts.*- * The rule is one line: **the name is the filename**. What the header shows is- * slugified into the file that holds it, so renaming moves the file (the- * backend does the move — see `api/naming.py`, which mirrors `slugify` exactly).- * That is why the collision checks here matter: the frontend can tell before it- * posts whether a name is free.+ * The rule is one line: **the name is the filename stem**. The human-readable+ * text in the header becomes the file stem, with only cross-platform forbidden+ * characters replaced. Renaming moves the file (the backend does the move —+ * see `api/naming.py`, which mirrors `slugify` exactly). That is why collision+ * checks here matter: the frontend can tell before it posts whether a name is+ * free.*/-// Long enough to stay readable, short enough that the path survives Windows'-// 260-character limit under a deep workspace root. Mirrors api/naming.py.-export const MAX_SLUG = 80;+// Long enough to stay readable, short enough that the case's longest path stays+// inside Windows' 260-character limit. Mirrors MAX_SLUG in azimut/layout.py,+// which owns the whole path budget.+export const MAX_SLUG = 68;/** What a fresh item of each kind is called until the analyst renames it. */-export const NAME_PREFIX = { session: 'Inspect', proof: 'Proof', draft: 'Post' };+export const NAME_PREFIX = { session: 'Inspect', proof: 'Proof', draft: 'Post', note: 'Note' };-/** URL- and filesystem-safe stem from free text — mirror of the backend `slugify`. */+/** Human-readable cross-platform filename stem — mirror of backend `slugify`. */export function slugify(text, fallback) {- const slug = (text ?? '')- .toLowerCase()- .replace(/[^a-z0-9]+/g, '-')- .replace(/^-+|-+$/g, '');- return slug.slice(0, MAX_SLUG) || fallback;+ let name = String(text ?? '')+ .normalize('NFC')+ .replace(/\s+/g, ' ')+ .trim()+ .replace(/[<>:"/\\|?*\u0000-\u001f]+/g, '_')+ .replace(/^[ .]+|[ .]+$/g, '')+ .replace(/\.{2,}/g, '_')+ .slice(0, MAX_SLUG)+ .replace(/[ .]+$/g, '');+ if (!name) name = String(fallback ?? 'file').slice(0, MAX_SLUG).replace(/[ .]+$/g, '') || 'file';+ if (/^(con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\.|$)/i.test(name)) {+ name = `_${name}`.slice(0, MAX_SLUG).replace(/[ .]+$/g, '');+ }+ return name;}/**diff --git a/frontend/src/lib/naming.test.js b/frontend/src/lib/naming.test.jsindex 05f672d..7173ad6 100644--- a/frontend/src/lib/naming.test.js+++ b/frontend/src/lib/naming.test.js@@ -5,15 +5,15 @@ import {} from './naming.js';describe('slugify — mirrors the backend api/naming.slugify', () => {- it('lowercases, hyphenates runs of non-alphanumerics, trims edges', () => {- expect(slugify('Inspect 1', 'session')).toBe('inspect-1');- expect(slugify(' Rooftop! @ 12:30 ', 'proof')).toBe('rooftop-12-30');- expect(slugify('Café déjà', 'proof')).toBe('caf-d-j');+ it('preserves human text and replaces only forbidden filename characters', () => {+ expect(slugify('Inspect 1', 'session')).toBe('Inspect 1');+ expect(slugify(' Rooftop! @ 12:30 ', 'proof')).toBe('Rooftop! @ 12_30');+ expect(slugify('Café déjà', 'proof')).toBe('Café déjà');});it('falls back to the caller word when nothing survives, and caps the length', () => {expect(slugify('', 'proof')).toBe('proof');- expect(slugify('!!!', 'session')).toBe('session');+ expect(slugify('!!!', 'session')).toBe('!!!');expect(slugify(null, 'draft')).toBe('draft');expect(slugify('a'.repeat(200), 'proof')).toHaveLength(MAX_SLUG);});@@ -36,7 +36,7 @@ describe('nextName — the default name of a fresh item', () => {});it('numbers a name that still slugs to a distinct filename', () => {- expect(slugify(nextName('proof', ['Proof 1']), 'proof')).toBe('proof-2');+ expect(slugify(nextName('proof', ['Proof 1']), 'proof')).toBe('Proof 2');});});@@ -113,6 +113,8 @@ describe('saved-item case queries', () => {describe('every kind names its work the same way', () => {it('has one prefix per kind and no other', () => {- expect(Object.keys(NAME_PREFIX).sort()).toEqual(['draft', 'proof', 'session']);+ // Notes joined the convention: their file is named after the title too,+ // so a fresh one is 'Note 1' the way a fresh session is 'Inspect 1'.+ expect(Object.keys(NAME_PREFIX).sort()).toEqual(['draft', 'note', 'proof', 'session']);});});diff --git a/frontend/src/lib/reveal.js b/frontend/src/lib/reveal.jsnew file mode 100644index 0000000..f83ff8c--- /dev/null+++ b/frontend/src/lib/reveal.js@@ -0,0 +1,17 @@+/**+ * Open a folder in the system's own file manager.+ *+ * The browser can't do this, so the backend does it (`engine/reveal.py`). Neither+ * call sends a path: the case id, or nothing at all for the workspace, is the+ * whole input, so the button can only ever open the folder it names.+ */++import { api } from './api.js';++export function revealCaseFolder(caseId) {+ return api.post(`/api/cases/${encodeURIComponent(caseId)}/reveal`);+}++export function revealWorkspaceFolder() {+ return api.post('/api/settings/reveal-workspace');+}diff --git a/frontend/src/lib/reveal.test.js b/frontend/src/lib/reveal.test.jsnew file mode 100644index 0000000..7ebae41--- /dev/null+++ b/frontend/src/lib/reveal.test.js@@ -0,0 +1,24 @@+import { beforeEach, expect, it, vi } from 'vitest';+import { api } from './api.js';+import { revealCaseFolder, revealWorkspaceFolder } from './reveal.js';++vi.mock('./api.js', () => ({ api: { post: vi.fn() } }));++beforeEach(() => {+ vi.clearAllMocks();+});++it('asks the backend to open a case by id, never by path', async () => {+ await revealCaseFolder('case-1');+ expect(api.post).toHaveBeenCalledWith('/api/cases/case-1/reveal');+});++it('escapes the id, so it cannot carry a path into the URL', async () => {+ await revealCaseFolder('../etc');+ expect(api.post).toHaveBeenCalledWith('/api/cases/..%2Fetc/reveal');+});++it('opens the workspace with no argument at all', async () => {+ await revealWorkspaceFolder();+ expect(api.post).toHaveBeenCalledWith('/api/settings/reveal-workspace');+});diff --git a/frontend/src/lib/state.svelte.js b/frontend/src/lib/state.svelte.jsindex 6fa5e65..e68c21a 100644--- a/frontend/src/lib/state.svelte.js+++ b/frontend/src/lib/state.svelte.js@@ -36,7 +36,7 @@ export const updateState = $state({show: false,latest: '', // the newer release tag, e.g. "v0.2.0"url: '', // where to download it- notes: '', // the release body (rendered as plain text)+ notes: '', // the release body, Markdown});/** Render a lat/lon the way the user asked for it. The tools' one entry point. */@@ -112,6 +112,7 @@ export async function dismissUpdate(mute = false) {export const caseState = $state({current: null, // { id, name, scratch, entities, links, ... }list: [],+ folders: [], // workspace folders that are not cases yet: { name, state }loading: false,rev: 0, // bumped on every reload so tools can re-fetch their own artifacts});@@ -215,6 +216,31 @@ export function toast(message, kind = 'info', timeout = 3800, action = null) {export async function refreshCaseList({ q } = {}) {const query = q?.trim();caseState.list = await api.get(`/api/cases${query ? `?q=${encodeURIComponent(query)}` : ''}`);+ // Folders the analyst made in the workspace and Azimut has not been told+ // about yet. Not a case list, so it takes no query; the switcher filters it.+ try {+ caseState.folders = await api.get('/api/workspace/folders');+ } catch {+ caseState.folders = []; // never keep the switcher from listing real cases+ }+}++/**+ * Make a case out of a workspace folder, in place. Nothing inside it moves:+ * the files stay in the analyst's half of the case folder.+ */+export async function adoptFolder(name) {+ const adopted = await api.post('/api/workspace/folders/adopt', { name });+ await refreshCaseList();+ await openCase(adopted.id);+ return adopted;+}++/** Write back the manifest of a folder holding a case that lost it. */+export async function recoverFolder(name) {+ const recovered = await api.post('/api/workspace/folders/recover', { name });+ await refreshCaseList();+ return recovered;}// Remember the last open case across page reloads so work is never "lost".diff --git a/frontend/src/lib/workspace.js b/frontend/src/lib/workspace.jsnew file mode 100644index 0000000..3bf6b1a--- /dev/null+++ b/frontend/src/lib/workspace.js@@ -0,0 +1,83 @@+import { api } from './api.js';++const base = '/api/settings/workspace';++export const readStatus = () => api.get(base);+export const inspectFolder = (path) => api.post(`${base}/inspect`, { path });+export const useFolder = (path) => api.post(`${base}/use`, { path });+export const useDefaultFolder = () => api.post(`${base}/default`);+export const moveWorkspace = (path) => api.post(`${base}/move`, { path });+export const discardOldWorkspace = () => api.post(`${base}/discard-old`);+export const takeWorkspaceLock = () => api.post(`${base}/take`);++/**+ * Why the app is closed, when it is: a folder that isn't there, or one another+ * Azimut holds. Null means the workspace is ours to work in.+ */+export function stoppedBecause(status) {+ if (!status) return null;+ if (status.missing) return { reason: 'missing', root: status.root, detail: '' };+ if (status.locked_by) {+ return { reason: 'locked', root: status.root, detail: status.locked_detail };+ }+ return null;+}++/** The move's steps, named as the analyst reads them. Mirrors `STEPS` in+ * `engine/workspacemove.py`. */+export const STEP_LABELS = {+ checking: 'Checking the folder',+ settling: 'Finishing background work',+ copying: 'Copying',+ verifying: 'Verifying the copy',+ switching: 'Switching over',+ opening: 'Opening the new folder',+ tidying: 'Setting the old folder aside',+};++/**+ * What the dialog may offer for a folder that was just inspected.+ *+ * The two actions are not alternatives with the same outcome, which is why the+ * copy has to separate them: using a folder leaves the current cases where they+ * are, and moving carries them over.+ */+export function offers(verdict) {+ if (!verdict || !verdict.ok) return { use: false, move: false, strands: 0 };+ return {+ use: true,+ // The backend refuses this too; hiding the button is how the analyst finds+ // out before typing rather than after.+ move: verdict.state !== 'workspace',+ // Cases that would stay behind if they used this folder as it is.+ strands: verdict.cases === 0 ? verdict.current_cases : 0,+ };+}++/** Progress of a running move: a percentage while bytes are moving, and the+ * step's own name the rest of the time. */+export function moveProgress(move) {+ if (!move) return { percent: 0, label: '', done: false };+ const label = STEP_LABELS[move.step] ?? move.step;+ if (move.done) return { percent: 100, label, done: true };+ if (move.step !== 'copying') {+ return { percent: move.step === 'checking' || move.step === 'settling' ? 0 : 100, label, done: false };+ }+ const percent = move.total_bytes+ ? Math.min(100, Math.round((move.copied_bytes / move.total_bytes) * 100))+ : 0;+ return { percent, label, done: false };+}++/** Bytes as the dialog prints them. */+export function humanBytes(count) {+ if (!count) return '0 B';+ const units = ['B', 'KB', 'MB', 'GB', 'TB'];+ let value = count;+ let unit = 0;+ while (value >= 1024 && unit < units.length - 1) {+ value /= 1024;+ unit += 1;+ }+ return `${unit === 0 ? value : value.toFixed(1)} ${units[unit]}`;+}diff --git a/frontend/src/lib/workspace.test.js b/frontend/src/lib/workspace.test.jsnew file mode 100644index 0000000..e4b18ea--- /dev/null+++ b/frontend/src/lib/workspace.test.js@@ -0,0 +1,134 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++const get = vi.fn();+const post = vi.fn();++vi.mock('./api.js', () => ({ api: { get, post } }));++const {+ readStatus,+ inspectFolder,+ useFolder,+ useDefaultFolder,+ moveWorkspace,+ discardOldWorkspace,+ offers,+ moveProgress,+ humanBytes,+} = await import('./workspace.js');++const verdict = (over = {}) => ({+ ok: true,+ state: 'empty',+ cases: 0,+ current_cases: 0,+ problems: [],+ warnings: [],+ ...over,+});++describe('workspace folder API', () => {+ beforeEach(() => {+ get.mockReset();+ post.mockReset();+ });++ it('reads and inspects without changing anything', async () => {+ get.mockResolvedValue({ root: '/home/a/Azimut' });+ post.mockResolvedValue(verdict());++ await readStatus();+ await inspectFolder('/tmp/target');++ expect(get).toHaveBeenCalledWith('/api/settings/workspace');+ expect(post).toHaveBeenCalledWith('/api/settings/workspace/inspect', { path: '/tmp/target' });+ });++ it('sends each action to its own route', async () => {+ post.mockResolvedValue({});++ await useFolder('/tmp/here');+ await useDefaultFolder();+ await moveWorkspace('/tmp/there');+ await discardOldWorkspace();++ expect(post.mock.calls.map(([path]) => path)).toEqual([+ '/api/settings/workspace/use',+ '/api/settings/workspace/default',+ '/api/settings/workspace/move',+ '/api/settings/workspace/discard-old',+ ]);+ });+});++describe('what a folder may be used for', () => {+ it('offers nothing for a folder that was refused', () => {+ expect(offers(verdict({ ok: false, problems: ['that folder is a file'] }))).toEqual({+ use: false,+ move: false,+ strands: 0,+ });+ expect(offers(null).use).toBe(false);+ });++ it('offers both actions for a usable empty folder', () => {+ expect(offers(verdict())).toMatchObject({ use: true, move: true });+ });++ it('will not move onto a folder that already holds a workspace', () => {+ expect(offers(verdict({ state: 'workspace', cases: 3 }))).toMatchObject({+ use: true,+ move: false,+ });+ });++ it('counts the cases that would stay behind', () => {+ expect(offers(verdict({ current_cases: 4 })).strands).toBe(4);+ expect(offers(verdict({ current_cases: 4, cases: 2 })).strands).toBe(0);+ });+});++describe('move progress', () => {+ it('is nothing before a move starts', () => {+ expect(moveProgress(null)).toEqual({ percent: 0, label: '', done: false });+ });++ it('follows the bytes while copying', () => {+ const progress = moveProgress({+ step: 'copying',+ copied_bytes: 512,+ total_bytes: 2048,+ done: false,+ });++ expect(progress).toEqual({ percent: 25, label: 'Copying', done: false });+ });++ it('does not divide by an empty workspace', () => {+ expect(moveProgress({ step: 'copying', copied_bytes: 0, total_bytes: 0 }).percent).toBe(0);+ });++ it('names each later step and holds the bar full', () => {+ expect(moveProgress({ step: 'verifying' })).toEqual({+ percent: 100,+ label: 'Verifying the copy',+ done: false,+ });+ expect(moveProgress({ step: 'tidying', done: true }).label).toBe(+ 'Setting the old folder aside',+ );+ });++ it('shows a step it does not know rather than nothing', () => {+ expect(moveProgress({ step: 'inventing' }).label).toBe('inventing');+ });+});++describe('sizes', () => {+ it('prints what a person would say', () => {+ expect(humanBytes(0)).toBe('0 B');+ expect(humanBytes(512)).toBe('512 B');+ expect(humanBytes(2048)).toBe('2.0 KB');+ expect(humanBytes(5 * 1024 ** 3)).toBe('5.0 GB');+ });+});diff --git a/frontend/src/tools/Inspector.svelte b/frontend/src/tools/Inspector.svelteindex a108f9b..31e18c9 100644--- a/frontend/src/tools/Inspector.svelte+++ b/frontend/src/tools/Inspector.svelte@@ -1099,7 +1099,8 @@const res = await api.post(`/api/cases/${caseState.current.id}/inspect/sessions`, {rename_from: openedSession?.name ?? null, title, spec: sessionSpec(),});- openedSession = { name: res.name, title };+ sessionName = res.title;+ openedSession = { name: res.name, title: res.title };savedSignature = signature();await reloadCase();toast('Session saved. Reopen it from the sidebar', 'ok');@@ -1538,7 +1539,7 @@<span class="source-copy"><span class="source-title">{m.title || m.filename}</span><span class="source-meta">- {sourceCategory(m)}{m.folder ? ` · ${m.folder}` : ''}{m.title && m.filename !== m.title ? ` · ${m.filename}` : ''}+ {sourceCategory(m)}{m.folder ? ` · ${m.folder}` : ''}</span></span></button>diff --git a/frontend/src/tools/Inspector.test.js b/frontend/src/tools/Inspector.test.jsindex 8bebe08..1eafa08 100644--- a/frontend/src/tools/Inspector.test.js+++ b/frontend/src/tools/Inspector.test.js@@ -21,6 +21,8 @@ describe('Inspect sessions', () => {expect(source).toContain('<input class="input title-input" bind:value={sessionName}');expect(source).toContain('aria-label="Session name"');expect(source).toContain('rename_from: openedSession?.name ?? null, title, spec: sessionSpec()');+ expect(source).toContain('sessionName = res.title;');+ expect(source).toContain('openedSession = { name: res.name, title: res.title };');expect(source).not.toContain("sessionModal.mode = 'save'");expect(source).not.toContain('placeholder="Session name"');});diff --git a/frontend/src/tools/MediaLibrary.svelte b/frontend/src/tools/MediaLibrary.svelteindex 57efeec..3605eae 100644--- a/frontend/src/tools/MediaLibrary.svelte+++ b/frontend/src/tools/MediaLibrary.svelte@@ -831,9 +831,6 @@</div><span class="media-col-name" title={item.filename}><span class="list-name">{item.title ?? item.filename}</span>- {#if item.title}- <span class="list-filename">{item.filename}</span>- {/if}</span><span class="media-col-type">{mediaDisplayKind(item)}</span><span class="media-col-size">{fmtSize(item.size)}</span>@@ -1606,21 +1603,14 @@.list-preview.clickable {cursor: zoom-in;}- .list-name,- .list-filename {+ .list-name {display: block;overflow: hidden;text-overflow: ellipsis;white-space: nowrap;- }- .list-name {color: var(--text-1);font-weight: 600;}- .list-filename {- color: var(--text-3);- font-size: var(--fs-xs);- }.media-col-actions {display: flex;align-items: center;diff --git a/frontend/src/tools/MediaLibrary.test.js b/frontend/src/tools/MediaLibrary.test.jsindex 481a537..9fedc14 100644--- a/frontend/src/tools/MediaLibrary.test.js+++ b/frontend/src/tools/MediaLibrary.test.js@@ -122,6 +122,13 @@ describe('Media Library positions', () => {});});+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>');+ expect(source).not.toContain('class="list-filename"');+ });+});+describe('Media Library bounded loading', () => {it('browses via the bounded /media/page endpoint, not the unbounded list', () => {expect(source).toContain('createPagedList');diff --git a/frontend/src/tools/Notebook.svelte b/frontend/src/tools/Notebook.svelteindex 69c43e9..32e0d26 100644--- a/frontend/src/tools/Notebook.svelte+++ b/frontend/src/tools/Notebook.svelte@@ -868,26 +868,16 @@ flowchart LR.reference-row small { color: var(--text-3); font-size: var(--fs-xs); }.preview-toggle { margin: -6px -7px -6px 0; }.preview-actions { display: flex; align-items: center; gap: 2px; }- .markdown { margin-top: 10px; color: var(--text-1); line-height: 1.65; overflow-wrap: anywhere; }- .markdown :global(h1), .markdown :global(h2), .markdown :global(h3) { margin: 0 0 12px; line-height: 1.25; }- .markdown :global(p), .markdown :global(ul), .markdown :global(ol), .markdown :global(blockquote) { margin: 0 0 12px; }- .markdown :global(blockquote) { padding-left: 12px; border-left: 2px solid var(--border); color: var(--text-2); }- .markdown :global(code) { padding: 1px 4px; border-radius: 3px; background: var(--bg-2); font-family: var(--mono); }- .markdown :global(pre) { margin: 0 0 12px; padding: 12px; overflow: auto; border: 1px solid var(--border); border-radius: var(--r-sm); background: var(--bg-1); }- .markdown :global(pre code) { padding: 0; background: transparent; }- .markdown :global(table) { width: 100%; margin: 0 0 12px; border-collapse: collapse; font-size: var(--fs-sm); }- .markdown :global(th), .markdown :global(td) { padding: 7px 9px; border: 1px solid var(--border); text-align: left; vertical-align: top; }- .markdown :global(th) { background: var(--bg-2); }- .markdown :global(input[type='checkbox']) { margin-right: 6px; accent-color: var(--accent); }+ /* The shared rendered-Markdown rules live in app.css; what follows is what+ only the Notebook preview shows. */+ .markdown { margin-top: 10px; }.markdown :global(.entity-ref) { color: var(--accent); font-weight: 600; }.markdown :global(.broken-ref) { color: var(--text-3); font-style: italic; text-decoration: line-through; }- .markdown :global(img), .markdown :global(video) { display: block; max-width: 100%; height: auto; margin: 0 0 12px; border-radius: var(--r-sm); border: 1px solid var(--border); }.markdown :global(video) { background: #000; }.markdown :global(.markdown-image.align-center) { margin-right: auto; margin-left: auto; }.markdown :global(.markdown-image.align-right) { margin-right: 0; margin-left: auto; }.markdown :global(.markdown-align.align-center) { text-align: center; }.markdown :global(.markdown-align.align-right) { text-align: right; }- .markdown :global(a) { color: var(--accent); }/* Diagrams are drawn light so they stay readable in the PDF export. */.markdown :global(.mermaid-diagram) { margin: 0 0 12px; padding: 12px; border: 1px solid var(--border); border-radius: var(--r-sm); background: #fff; text-align: center; overflow-x: auto; }.markdown :global(.mermaid-diagram svg) { max-width: 100%; height: auto; }diff --git a/frontend/src/tools/PostComposer.svelte b/frontend/src/tools/PostComposer.svelteindex ebda8bc..82ce4c2 100644--- a/frontend/src/tools/PostComposer.svelte+++ b/frontend/src/tools/PostComposer.svelte@@ -692,6 +692,7 @@state: snapshot(),});draftName = r.name;+ postName = r.title;await reloadCase(); // surface the post entity in the sidebartoast('Draft saved', 'ok', 1600);} catch (e) {diff --git a/frontend/src/tools/PostComposer.test.js b/frontend/src/tools/PostComposer.test.jsindex b80f2c8..55024fc 100644--- a/frontend/src/tools/PostComposer.test.js+++ b/frontend/src/tools/PostComposer.test.js@@ -52,6 +52,7 @@ describe('Post naming', () => {it('renames in place: saving sends the bound slug so the backend moves the file', () => {expect(source).toContain('rename_from: draftName,');expect(source).toContain('title: postName.trim(),');+ expect(source).toContain('postName = r.title;');});it('asks before an unbound draft takes a name another draft holds', () => {diff --git a/frontend/src/tools/ProofComposer.svelte b/frontend/src/tools/ProofComposer.svelteindex 9333edc..e9b5044 100644--- a/frontend/src/tools/ProofComposer.svelte+++ b/frontend/src/tools/ProofComposer.svelte@@ -2265,12 +2265,13 @@if (entry) entry.pending = false;}savedName = result.name;+ proof.title = result.title;dirty = false;await reloadCase();toast(`Proof saved: ${result.png}`, 'ok');if (andPost) {uiState.postProof = {- title: proof.title,+ title: result.title,coordsText: displayedCoords,source: displayedSource,attribution: attributionLine(proof.panels),diff --git a/frontend/src/tools/ProofComposer.test.js b/frontend/src/tools/ProofComposer.test.jsindex 17f3b16..bdcc1db 100644--- a/frontend/src/tools/ProofComposer.test.js+++ b/frontend/src/tools/ProofComposer.test.js@@ -44,6 +44,12 @@ describe('Proof Composer header', () => {});});+describe('Proof Composer naming', () => {+ it('adopts the canonical filename stem returned by the backend', () => {+ expect(source).toContain('proof.title = result.title;');+ });+});+describe('Proof Composer pickers', () => {it('searches the panel picker and the saved-proof list only past six entries', () => {expect(source).toContain("import SearchInput from '../components/SearchInput.svelte'");diff --git a/frontend/src/tools/ReverseSearch.svelte b/frontend/src/tools/ReverseSearch.svelteindex 1907c12..045bd12 100644--- a/frontend/src/tools/ReverseSearch.svelte+++ b/frontend/src/tools/ReverseSearch.svelte@@ -407,7 +407,7 @@<span class="picker-copy"><span class="picker-title">{item.title || item.filename}</span><span class="picker-meta">- {mediaCategory(item)}{item.folder ? ` · ${item.folder}` : ''}{item.title && item.filename !== item.title ? ` · ${item.filename}` : ''}+ {mediaCategory(item)}{item.folder ? ` · ${item.folder}` : ''}</span></span></button>diff --git a/frontend/src/tools/ReverseSearch.test.js b/frontend/src/tools/ReverseSearch.test.jsindex d55a8ae..a9c38d9 100644--- a/frontend/src/tools/ReverseSearch.test.js+++ b/frontend/src/tools/ReverseSearch.test.js@@ -13,6 +13,7 @@ describe('Reverse Search case picker', () => {expect(source).toContain('placeholder="Search names…"');expect(source).toContain('function matchesMediaName(item, query)');expect(source).toContain("matchesTerms(item.title || item.filename || '', query)");+ expect(source).not.toContain("item.filename !== item.title");});it('separates reverse-search sources by media type and provenance', () => {diff --git a/frontend/src/tools/Settings.svelte b/frontend/src/tools/Settings.svelteindex f96a534..e56306c 100644--- a/frontend/src/tools/Settings.svelte+++ b/frontend/src/tools/Settings.svelte@@ -21,11 +21,13 @@FREE_TIER,} from '../lib/usage.js';import { probeKey, googleMapsLoadedKey } from '../lib/gmaps.js';+ import { revealWorkspaceFolder } from '../lib/reveal.js';import { extensionVersion, extensionOutdated } from '../lib/extBridge.js';import Icon from '../components/Icon.svelte';import ProofTemplateEditor from '../components/ProofTemplateEditor.svelte';import PostTemplateEditor from '../components/PostTemplateEditor.svelte';import ConfirmDialog from '../components/ConfirmDialog.svelte';+ import WorkspaceFolder from '../components/WorkspaceFolder.svelte';// Imagery keys and their usage meters share one card per provider.const TABS = [@@ -490,6 +492,17 @@}}+ // The path is printed right there, but copying it into a file manager by hand+ // is exactly what the first analyst to ask ended up doing.+ async function revealWorkspace() {+ try {+ await revealWorkspaceFolder();+ toast('Opened the workspace folder', 'ok', 2500);+ } catch (e) {+ toast(e.message || 'Could not open the folder', 'danger', 7000);+ }+ }+// a live sample so the format choice is legible before it's applied elsewhereconst coordSample = $derived(formatCoords(Number(home.lat) || 48.8584, Number(home.lon) || 2.2945, prefs.coordFormat)@@ -1123,7 +1136,12 @@<dt>Version</dt><dd class="mono">{about.version || '—'}</dd><dt>Workspace</dt>- <dd class="mono">{about.workspace_root || '—'}</dd>+ <dd class="mono workspace-fact">+ <span>{about.workspace_root || '—'}</span>+ <button class="btn btn-ghost btn-sm" onclick={revealWorkspace} title="Open this folder">+ <Icon name="folderOpen" size={13} /> Open+ </button>+ </dd><dt>ffmpeg</dt><dd class="mono" title={ffmpeg.path || ''}>{#if ffmpeg.available}@@ -1150,6 +1168,8 @@</div></section>+ <WorkspaceFolder onchange={(status) => (about.workspace_root = status.root)} />+<section class="group"><h3>Updates</h3><div class="row">@@ -1690,6 +1710,13 @@color: var(--text-1);overflow-wrap: anywhere;}+ /* The path can be long, so the button sits after it and never squeezes it. */+ .workspace-fact {+ display: flex;+ align-items: center;+ gap: 8px;+ flex-wrap: wrap;+ }.links {display: flex;gap: 8px;diff --git a/frontend/src/tools/Settings.test.js b/frontend/src/tools/Settings.test.jsindex 882914c..353bdba 100644--- a/frontend/src/tools/Settings.test.js+++ b/frontend/src/tools/Settings.test.js@@ -53,3 +53,16 @@ describe('Backup', () => {expect(source).toContain('Import backup');});});++describe('Workspace folder', () => {+ it('puts an Open button beside the path About already prints', () => {+ expect(source).toContain("import { revealWorkspaceFolder } from '../lib/reveal.js'");+ expect(source).toContain('<dt>Workspace</dt>');+ expect(source).toContain('onclick={revealWorkspace}');+ });++ it('reports the outcome, since the window opens outside the browser', () => {+ expect(source).toContain("toast('Opened the workspace folder'");+ expect(source).toContain("toast(e.message || 'Could not open the folder'");+ });+});diff --git a/src/azimut/api/cases.py b/src/azimut/api/cases.pyindex 4bc22da..2df4c70 100644--- a/src/azimut/api/cases.py+++ b/src/azimut/api/cases.py@@ -2,6 +2,7 @@from __future__ import annotations+import sqlite3from pathlib import Pathfrom typing import Any, cast@@ -9,15 +10,25 @@ from fastapi import APIRouter, File, Form, HTTPException, UploadFilefrom fastapi.responses import FileResponsefrom pydantic import BaseModel, Field-from .. import config+from .. import config, workspacefrom ..engine import bundles as bundle_engine+from ..engine import doctor as doctor_enginefrom ..engine import links as link_engine+from ..engine import media as media_engine+from ..engine import reveal as reveal_enginefrom ..engine import trash as trash_enginefrom ..repository import EntityStatusfrom ..workspace import Case, CaseErrorrouter = APIRouter(prefix="/api/cases", tags=["cases"])+#: Folders in the workspace that are not cases yet. Deliberately *not* under+#: `/api/cases`: a case's id is its folder name, so a literal segment there is a+#: name someone can give a folder — `/api/cases/folders` is already the case+#: named "Folders" (`tests/test_cases_api.py`). These operate on the workspace+#: anyway, one level above any case.+workspace_router = APIRouter(prefix="/api/workspace", tags=["cases"])+def get_case(case_id: str) -> Case:try:@@ -188,6 +199,13 @@ class FolderIn(BaseModel):name: str = Field(min_length=1, max_length=120)+class FolderName(BaseModel):+ """A directory name in the workspace root, never a path: what it may hold is+ `layout.usable_case_name`'s answer, checked where the folder is opened."""++ name: str = Field(min_length=1, max_length=120)++class BundlePassword(BaseModel):password: str | None = Field(default=None, max_length=1024)@@ -196,6 +214,13 @@ class BundleUpload(BundlePassword):upload_id: str = Field(min_length=32, max_length=32)+class DoctorRepair(BaseModel):+ action: str = Field(min_length=1, max_length=20)+ entity_id: str | None = Field(default=None, max_length=64)+ path: str | None = Field(default=None, max_length=300)+ replacement: str | None = Field(default=None, max_length=300)++@router.get("")def list_cases(q: str | None = None, limit: int | None = None) -> list[dict[str, Any]]:return Case.list_all(q=q, limit=limit)@@ -211,6 +236,37 @@ def create_case(body: CreateCase) -> dict[str, Any]:return {"id": case.id, **case.overview()}+@workspace_router.get("/folders")+def list_workspace_folders() -> list[dict[str, Any]]:+ """Folders sitting in the workspace that are not cases yet, and their state."""+ return workspace.list_workspace_folders()+++@workspace_router.post("/folders/adopt")+def adopt_folder(body: FolderName) -> dict[str, Any]:+ """Make a case out of one of those folders, where it already is."""+ _ensure_name_free(body.name)+ try:+ case = Case.adopt(body.name)+ except CaseError as exc:+ raise HTTPException(status_code=409, detail=str(exc)) from exc+ return {"id": case.id, **case.overview()}+++@workspace_router.post("/folders/recover")+def recover_folder(body: FolderName) -> dict[str, Any]:+ """Write back the manifest of a folder holding a case that lost it.++ The manifest and nothing else: the case is reachable again after this, and+ anything still damaged belongs to the Doctor, which the caller opens next.+ """+ try:+ case = workspace.restore_manifest(body.name)+ except CaseError as exc:+ raise HTTPException(status_code=409, detail=str(exc)) from exc+ return {"id": case.id, "name": case.read().get("name", case.id)}++@router.post("/scratch")def create_scratch() -> dict[str, Any]:case = Case.create("Scratch session", scratch=True)@@ -283,6 +339,46 @@ def relation_types() -> list[dict[str, Any]]:][email protected]("/{case_id}/doctor")+def doctor_report(case_id: str) -> dict[str, Any]:+ """Inspect a case even when its database is missing."""+ try:+ return doctor_engine.scan(Case.locate(case_id))+ except CaseError as exc:+ raise HTTPException(status_code=404, detail=str(exc)) from exc++[email protected]("/{case_id}/doctor/repair")+def doctor_repair(case_id: str, body: DoctorRepair) -> dict[str, Any]:+ """Apply one repair that the current Doctor report explicitly offers."""+ try:+ located = Case.locate(case_id)+ if body.action == "rebuild":+ result = doctor_engine.rebuild_database(located)+ case = located+ else:+ case = Case.open(case_id)+ if 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:+ doctor_engine.require_missing_media(case, body.entity_id)+ result = delete_entity_deep(case, body.entity_id)+ elif body.action == "relink" and body.entity_id and body.replacement:+ doctor_engine.require_missing_media(case, body.entity_id)+ doctor_engine.require_unknown_media(case, body.replacement)+ result = media_engine.relink_existing(+ case,+ body.entity_id,+ body.replacement,+ )+ else:+ raise CaseError("this repair action is not valid")+ return {"repair": result, "report": doctor_engine.scan(case)}+ except (CaseError, OSError, ValueError, sqlite3.Error) as exc:+ raise HTTPException(status_code=409, detail=str(exc)) from exc++@router.get("/{case_id}")def read_case(case_id: str) -> dict[str, Any]:case = get_case(case_id)@@ -314,6 +410,21 @@ def delete_case(case_id: str) -> dict[str, str]:return {"status": "deleted"}[email protected]("/{case_id}/reveal")+def reveal_case_folder(case_id: str) -> dict[str, str]:+ """Open this case's folder in the system file manager.++ The route takes no path: the case id is enough to find the folder, so nothing+ the browser sends can point somewhere else.+ """+ case = get_case(case_id)+ try:+ reveal_engine.reveal(case.path)+ except reveal_engine.RevealError as exc:+ raise HTTPException(status_code=409, detail=str(exc)) from exc+ return {"path": str(case.path)}++@router.post("/{case_id}/bundle/export")def export_bundle(case_id: str, body: BundlePassword) -> dict[str, Any]:case = get_case(case_id)diff --git a/src/azimut/api/drafts.py b/src/azimut/api/drafts.pyindex 05e6942..be3c9fa 100644--- a/src/azimut/api/drafts.py+++ b/src/azimut/api/drafts.py@@ -22,6 +22,7 @@ from ..engine import links as link_enginefrom ..workspace import CaseErrorfrom .cases import delete_by_path, get_casefrom .naming import read_created_at, slugify+from .. import layoutrouter = APIRouter(prefix="/api", tags=["drafts"])@@ -34,7 +35,7 @@ MAX_ARTIFACT_PATH_LENGTH = 512class DraftIn(BaseModel):# The filename always follows the title, so renaming a saved draft moves its- # file. ``rename_from`` is the slug the composer is currently bound to+ # file. ``rename_from`` is the stem the composer is currently bound to# (absent on a first save); a save that lands elsewhere renames that file in# place instead of leaving a copy behind under the old name.rename_from: str | None = None@@ -118,7 +119,7 @@ def _draft_source_paths(state: dict[str, Any]) -> list[str]:def list_drafts(case_id: str) -> list[dict[str, Any]]:case = get_case(case_id)drafts = []- for path in sorted(case.subdir("exports").glob("*.json")):+ for path in sorted(case.subdir(layout.DRAFTS_DIR).glob("*.json")):try:data = json.loads(path.read_text(encoding="utf-8"))except (OSError, json.JSONDecodeError):@@ -145,7 +146,7 @@ def list_drafts(case_id: str) -> list[dict[str, Any]]:def load_draft(case_id: str, name: str) -> dict[str, Any]:case = get_case(case_id)try:- path = case.resolve_inside(f"exports/{name}.json")+ path = case.resolve_inside(layout.draft_rel(name))except CaseError as exc:raise HTTPException(status_code=403, detail=str(exc)) from excif not path.exists():@@ -156,25 +157,25 @@ def load_draft(case_id: str, name: str) -> dict[str, Any]:@router.post("/cases/{case_id}/drafts")def save_draft(case_id: str, body: DraftIn) -> dict[str, Any]:case = get_case(case_id)- name = slugify(body.title, "draft")- exports_dir = case.subdir("exports")+ name = slugify(body.title, "Post")+ case.subdir(layout.DRAFTS_DIR) # born on first save, so the folder existssource_paths = _draft_source_paths(body.state)- rel = f"exports/{name}.json"- path = exports_dir / f"{name}.json"+ rel = layout.draft_rel(name)+ path = case.resolve_inside(rel)# A rename lands on a free name or not at all: taking a name another draft# holds would leave two entities pointing at one file, and there is no sane# merge of the two. The first save of an unbound composer still writes over# a same-named draft — there the analyst is updating that one.old = slugify(body.rename_from, "draft") if body.rename_from else None- old_rel = f"exports/{old}.json" if old and old != name else None+ old_rel = layout.draft_rel(old) if old and old != name else Noneif old_rel and path.exists():raise HTTPException(status_code=409, detail="another draft already uses that name")data = {"azimut_draft": DRAFT_MARKER,- "title": body.title,- "created_at": read_created_at(exports_dir / f"{old or name}.json") or _now(),+ "title": name,+ "created_at": read_created_at(case.resolve_inside(layout.draft_rel(old or name))) or _now(),"updated_at": _now(),"state": body.state,}@@ -187,7 +188,7 @@ def save_draft(case_id: str, body: DraftIn) -> dict[str, Any]:# keeps its folder, notes and links.existing = case.find_entity(attr="draft", value=old_rel or rel)if existing:- patch: dict[str, Any] = {"label": body.title}+ patch: dict[str, Any] = {"label": name}if old_rel:patch["attrs"] = {"draft": rel}case.update_entity(existing["id"], patch)@@ -195,12 +196,12 @@ def save_draft(case_id: str, body: DraftIn) -> dict[str, Any]:else:entity_id = case.add_entity("post",- body.title,+ name,attrs={"draft": rel},by="post-composer",)["id"]if old_rel:- (exports_dir / f"{old}.json").unlink(missing_ok=True)+ case.resolve_inside(layout.draft_rel(str(old))).unlink(missing_ok=True)# A post is derived from the proof it announces and the media it attaches —# it carries their coordinates and source in its own text, so it outlives@@ -213,13 +214,13 @@ def save_draft(case_id: str, body: DraftIn) -> dict[str, Any]:by="post-composer",)- return {"name": name, "draft": rel}+ return {"name": name, "title": name, "draft": rel}@router.delete("/cases/{case_id}/drafts/{name}")def delete_draft(case_id: str, name: str) -> dict[str, Any]:case = get_case(case_id)- rel = f"exports/{name}.json"+ rel = layout.draft_rel(name)try:case.resolve_inside(rel)except CaseError as exc:diff --git a/src/azimut/api/inspect.py b/src/azimut/api/inspect.pyindex 5023141..3af54eb 100644--- a/src/azimut/api/inspect.py+++ b/src/azimut/api/inspect.py@@ -21,6 +21,7 @@ from ..engine import links as link_enginefrom ..workspace import CaseErrorfrom .cases import delete_by_path, get_casefrom .naming import read_created_at, slugify+from .. import layoutrouter = APIRouter(prefix="/api", tags=["inspect"])@@ -106,7 +107,7 @@ class AnalyzeIn(BaseModel):class SessionIn(BaseModel):# The filename always follows the title, so renaming a saved session moves- # its file. ``rename_from`` is the slug the workspace is currently bound to+ # its file. ``rename_from`` is the stem the workspace is currently bound to# (absent on a first save); a save that lands elsewhere renames that file in# place instead of leaving a copy behind under the old name.rename_from: str | None = None@@ -290,7 +291,7 @@ def _now() -> str:def list_sessions(case_id: str) -> list[dict[str, Any]]:case = get_case(case_id)out = []- for spec_path in sorted(case.subdir("inspect").glob("*.json")):+ for spec_path in sorted(case.subdir(layout.INSPECT_DIR).glob("*.json")):try:spec = json.loads(spec_path.read_text(encoding="utf-8"))except (OSError, json.JSONDecodeError):@@ -319,7 +320,7 @@ def list_sessions(case_id: str) -> list[dict[str, Any]]:def load_session(case_id: str, name: str) -> dict[str, Any]:case = get_case(case_id)try:- spec_path = case.resolve_inside(f"inspect/{name}.json")+ spec_path = case.resolve_inside(layout.session_rel(name))except CaseError as exc:raise HTTPException(status_code=403, detail=str(exc)) from excif not spec_path.exists():@@ -330,24 +331,25 @@ def load_session(case_id: str, name: str) -> dict[str, Any]:@router.post("/cases/{case_id}/inspect/sessions")def save_session(case_id: str, body: SessionIn) -> dict[str, Any]:case = get_case(case_id)- sessions_dir = case.subdir("inspect")- name = slugify(body.title, "session")- rel = f"inspect/{name}.json"- spec_path = sessions_dir / f"{name}.json"+ case.subdir(layout.INSPECT_DIR) # born on first save, so the folder exists+ name = slugify(body.title, "Inspect")+ rel = layout.session_rel(name)+ spec_path = case.resolve_inside(rel)# A rename lands on a free name or not at all: taking a name another session# holds would leave two entities pointing at one file, and there is no sane# merge of the two. The first save of an unbound workspace still writes over# a same-named session — there the analyst is updating that one.old = slugify(body.rename_from, "session") if body.rename_from else None- old_rel = f"inspect/{old}.json" if old and old != name else None+ old_rel = layout.session_rel(old) if old and old != name else Noneif old_rel and spec_path.exists():raise HTTPException(status_code=409, detail="another session already uses that name")spec = dict(body.spec)spec["azimut_inspect"] = 1- spec["title"] = body.title- spec.setdefault("created_at", read_created_at(sessions_dir / f"{old or name}.json") or _now())+ spec["title"] = name+ previous = case.resolve_inside(layout.session_rel(old or name))+ spec.setdefault("created_at", read_created_at(previous) or _now())spec["updated_at"] = _now()spec_path.write_text(json.dumps(spec, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")@@ -355,17 +357,17 @@ def save_session(case_id: str, body: SessionIn) -> dict[str, Any]:# rename keeps the session's folder, notes and links.existing = case.find_entity(attr="spec", value=old_rel or rel)if existing:- patch: dict[str, Any] = {"label": body.title}+ patch: dict[str, Any] = {"label": name}if old_rel:patch["attrs"] = {"spec": rel}case.update_entity(existing["id"], patch)entity_id = existing["id"]else:entity_id = case.add_entity(- "inspect-session", body.title, attrs={"spec": rel}, by="inspect"+ "inspect-session", name, attrs={"spec": rel}, by="inspect")["id"]if old_rel:- (sessions_dir / f"{old}.json").unlink(missing_ok=True)+ case.resolve_inside(layout.session_rel(str(old))).unlink(missing_ok=True)# A session is only adjustments and crops over its subject — nothing usable# is left of it once the subject is gone, so it depends on it and is deleted@@ -378,13 +380,13 @@ def save_session(case_id: str, body: SessionIn) -> dict[str, Any]:[spec.get("source", {}).get("path")],by="inspect",)- return {"name": name, "spec_path": rel}+ return {"name": name, "title": name, "spec_path": rel}@router.delete("/cases/{case_id}/inspect/sessions/{name}")def delete_session(case_id: str, name: str) -> dict[str, Any]:case = get_case(case_id)- rel = f"inspect/{name}.json"+ rel = layout.session_rel(name)try:case.resolve_inside(rel)except CaseError as exc:diff --git a/src/azimut/api/naming.py b/src/azimut/api/naming.pyindex 34af4a2..d47576c 100644--- a/src/azimut/api/naming.py+++ b/src/azimut/api/naming.py@@ -4,29 +4,21 @@ Inspect sessions, proofs, post drafts and satellite grids all turn a free-texttitle into the filename that holds it. They must agree: a session and a proofcalled "Rooftop angle" land on the same stem, and the frontend mirrors this in``lib/naming.js`` so it can predict a collision before it posts.++`slugify` and its length cap live in `layout.py` with the rest of the path+budget: how a name becomes a path, and how long it may be, are facts about the+case folder's shape."""from __future__ import annotationsimport json-import refrom pathlib import Pathfrom typing import Any-# Long enough to stay readable, short enough that the path survives Windows'-# 260-character limit under a deep workspace root.-MAX_SLUG = 80-+from ..layout import MAX_SLUG, slugify-def slugify(text: str | None, fallback: str) -> str:- """URL- and filesystem-safe stem from free text.-- Everything outside ``[a-z0-9]`` collapses to a single dash, so accents and- punctuation drop out rather than reaching the filesystem. Text that leaves- nothing behind ("!!!", "") falls back to the caller's word.- """- slug = re.sub(r"[^a-z0-9]+", "-", (text or "").lower()).strip("-")- return slug[:MAX_SLUG] or fallback+__all__ = ["MAX_SLUG", "slugify", "read_created_at"]def read_created_at(path: Path) -> str | None:diff --git a/src/azimut/api/proofs.py b/src/azimut/api/proofs.pyindex 3b50b77..0fce0d0 100644--- a/src/azimut/api/proofs.py+++ b/src/azimut/api/proofs.py@@ -30,10 +30,11 @@ from ..engine import links as link_enginefrom ..engine import media as media_enginefrom ..engine import satellite as satellite_enginefrom ..engine import thumbnails as thumbnail_engine-from ..workspace import Case, CaseError+from ..workspace import Case, CaseError, ensure_dirfrom .cases import delete_by_path, get_casefrom .drafts import list_draftsfrom .naming import read_created_at, slugify+from .. import layoutrouter = APIRouter(prefix="/api", tags=["proofs"])@@ -58,7 +59,7 @@ class AssetIn(BaseModel):class ProofIn(BaseModel):# The filename always follows the title, so renaming a saved proof moves its- # spec and its export. ``rename_from`` is the slug the composer is currently+ # spec and its export. ``rename_from`` is the stem the composer is currently# bound to (absent on a first save); a save that lands elsewhere renames# those files in place instead of leaving a copy under the old name.rename_from: str | None = None@@ -76,6 +77,7 @@ def _now() -> str:def _write_spec(path: Path, spec: dict[str, Any]) -> None:+ ensure_dir(path.parent)path.write_text(json.dumps(spec, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")@@ -88,7 +90,7 @@ def _proof_thumb(case: Case, name: str, data: bytes | None = None) -> str | NoneURL, and disposable, so eviction just means the next listing regenerates it.``data`` skips re-reading bytes we already hold (the save path)."""- png_rel = f"proofs/{name}.png"+ png_rel = layout.proof_export_rel(name)path = case.resolve_inside(png_rel)if not path.is_file():return None@@ -189,7 +191,7 @@ def proof_index(case_id: str) -> list[dict[str, Any]]:def list_proofs(case_id: str) -> list[dict[str, Any]]:case = get_case(case_id)proofs = []- for spec_path in sorted(case.subdir("proofs").glob("*.json")):+ for spec_path in sorted(case.subdir("proofs").joinpath(layout.META_DIR).glob("*.json")):try:spec = json.loads(spec_path.read_text(encoding="utf-8"))except (OSError, json.JSONDecodeError):@@ -197,7 +199,7 @@ def list_proofs(case_id: str) -> list[dict[str, Any]]:if spec.get("azimut_proof") != 1:continuename = spec_path.stem- png = spec_path.with_suffix(".png")+ png = case.resolve_inside(layout.proof_export_rel(name))# Proofs saved before thumbnails existed (or whose cached file was# evicted) produce one here and record it, so this costs a hash of the# export once per proof rather than a full-size download per open.@@ -219,9 +221,9 @@ def list_proofs(case_id: str) -> list[dict[str, Any]]:# the point the proof states for itself, read before its# derivation so it keeps it when the capture is deleted"coords": satellite_engine.own_point(spec),- "png": f"proofs/{png.name}" if png.exists() else None,+ "png": layout.proof_export_rel(png.stem) if png.exists() else None,"thumb": thumb,- "spec_path": f"proofs/{spec_path.name}",+ "spec_path": layout.proof_spec_rel(spec_path.stem),})proofs.sort(key=lambda p: p.get("updated_at") or "", reverse=True)@@ -232,7 +234,7 @@ def list_proofs(case_id: str) -> list[dict[str, Any]]:def load_proof(case_id: str, name: str) -> dict[str, Any]:case = get_case(case_id)try:- spec_path = case.resolve_inside(f"proofs/{name}.json")+ spec_path = case.resolve_inside(layout.proof_spec_rel(name))except CaseError as exc:raise HTTPException(status_code=403, detail=str(exc)) from excif not spec_path.exists():@@ -243,17 +245,17 @@ def load_proof(case_id: str, name: str) -> dict[str, Any]:@router.post("/cases/{case_id}/proofs")def save_proof(case_id: str, body: ProofIn) -> dict[str, Any]:case = get_case(case_id)- name = slugify(body.title, "proof")- proofs_dir = case.subdir("proofs")- rel = f"proofs/{name}.json"- spec_path = proofs_dir / f"{name}.json"+ name = slugify(body.title, "Proof")+ case.subdir("proofs") # born on first save, so the visible folder exists+ rel = layout.proof_spec_rel(name)+ spec_path = case.resolve_inside(rel)# A rename lands on a free name or not at all: taking a name another proof# holds would leave two entities pointing at one spec, and there is no sane# merge of the two. The first save of an unbound composer still writes over# a same-named proof — there the analyst is updating that one.old = slugify(body.rename_from, "proof") if body.rename_from else None- old_rel = f"proofs/{old}.json" if old and old != name else None+ old_rel = layout.proof_spec_rel(old) if old and old != name else Noneif old_rel and spec_path.exists():raise HTTPException(status_code=409, detail="another proof already uses that name")@@ -262,16 +264,17 @@ def save_proof(case_id: str, body: ProofIn) -> dict[str, Any]:# The export moves with the spec, so a rename saved without fresh pixels# keeps the PNG the proof already had rather than dropping it.- if old_rel:- old_png = proofs_dir / f"{old}.png"+ if old_rel and old:+ old_png = case.resolve_inside(layout.proof_export_rel(old))if old_png.exists():if body.png_base64:old_png.unlink()else:- old_png.replace(proofs_dir / f"{name}.png")+ old_png.replace(case.resolve_inside(layout.proof_export_rel(name)))# the pasted images follow the proof, exactly as its export does_move_assets(- proofs_dir / f"{old}{ASSETS_SUFFIX}", proofs_dir / f"{name}{ASSETS_SUFFIX}"+ case.resolve_inside(layout.proof_assets_rel(old)),+ case.resolve_inside(layout.proof_assets_rel(name)),)# the export lands first: its thumbnail is recorded in the spec written below@@ -281,17 +284,18 @@ def save_proof(case_id: str, body: ProofIn) -> dict[str, Any]:png_bytes = base64.b64decode(body.png_base64, validate=True)except (binascii.Error, ValueError) as exc:raise HTTPException(status_code=422, detail="invalid PNG payload") from exc- (proofs_dir / f"{name}.png").write_bytes(png_bytes)- png_rel = f"proofs/{name}.png"+ case.resolve_inside(layout.proof_export_rel(name)).write_bytes(png_bytes)+ png_rel = layout.proof_export_rel(name)thumb_rel = _proof_thumb(case, name, png_bytes)- elif old_rel and (proofs_dir / f"{name}.png").exists():- png_rel = f"proofs/{name}.png"+ elif old_rel and case.resolve_inside(layout.proof_export_rel(name)).exists():+ png_rel = layout.proof_export_rel(name)thumb_rel = _proof_thumb(case, name)spec = dict(body.spec)spec["azimut_proof"] = 1- spec["title"] = body.title- spec.setdefault("created_at", read_created_at(proofs_dir / f"{old or name}.json") or _now())+ spec["title"] = name+ previous = case.resolve_inside(layout.proof_spec_rel(old or name))+ spec.setdefault("created_at", read_created_at(previous) or _now())spec["updated_at"] = _now()if png_rel:spec["thumb"] = thumb_rel@@ -301,7 +305,7 @@ def save_proof(case_id: str, body: ProofIn) -> dict[str, Any]:# The spec is the truth about which pasted images the proof shows, so its# folder is reconciled against what we just wrote._write_assets(- proofs_dir / f"{name}{ASSETS_SUFFIX}", incoming, _referenced_assets(spec)+ case.resolve_inside(layout.proof_assets_rel(name)), incoming, _referenced_assets(spec))# upsert the proof entity (analyst action → confirmed). A rename rebinds the@@ -309,7 +313,7 @@ def save_proof(case_id: str, body: ProofIn) -> dict[str, Any]:# keeps its folder, notes and links.existing = case.find_entity(attr="spec", value=old_rel or rel)if existing:- patch: dict[str, Any] = {"label": body.title}+ patch: dict[str, Any] = {"label": name}attrs: dict[str, Any] = {"spec": rel} if old_rel else {}if png_rel and existing["attrs"].get("path") != png_rel:# a spec-only proof exported later gains its PNG here — without the@@ -322,12 +326,12 @@ def save_proof(case_id: str, body: ProofIn) -> dict[str, Any]:else:entity_id = case.add_entity("proof",- body.title,+ name,attrs={"spec": rel, **({"path": png_rel} if png_rel else {})},by="proof-composer",)["id"]if old_rel:- (proofs_dir / f"{old}.json").unlink(missing_ok=True)+ case.resolve_inside(layout.proof_spec_rel(str(old))).unlink(missing_ok=True)# A proof is derived from the panels it composes: the same click that saves# it files the chain (ONTOLOGY §3). Restated on every save, so a panel@@ -342,6 +346,7 @@ def save_proof(case_id: str, body: ProofIn) -> dict[str, Any]:return {"name": name,+ "title": name,"png": png_rel,"thumb": thumb_rel,"spec_path": rel,@@ -351,7 +356,7 @@ def save_proof(case_id: str, body: ProofIn) -> dict[str, Any]:@router.delete("/cases/{case_id}/proofs/{name}")def delete_proof(case_id: str, name: str) -> dict[str, Any]:case = get_case(case_id)- rel = f"proofs/{name}.json"+ rel = layout.proof_spec_rel(name)try:case.resolve_inside(rel)except CaseError as exc:diff --git a/src/azimut/api/satellite.py b/src/azimut/api/satellite.pyindex bb8ba3c..fcb4d53 100644--- a/src/azimut/api/satellite.py+++ b/src/azimut/api/satellite.py@@ -37,6 +37,7 @@ from .cases import delete_by_path, get_casefrom .limits import MAX_IMAGE_BYTESfrom .naming import slugifyfrom .media import with_thumb_state+from .. import layoutrouter = APIRouter(prefix="/api", tags=["satellite"])@@ -994,7 +995,7 @@ def list_search_grids(case_id: str) -> list[dict[str, Any]]:"""Summaries of every saved grid, newest first, for the picker."""case = get_case(case_id)out = []- for spec_path in case.subdir("search").glob("*.json"):+ for spec_path in case.subdir(layout.SEARCH_DIR).glob("*.json"):try:spec = _read_grid(spec_path)except ValueError:@@ -1017,7 +1018,7 @@ def get_search_grid(case_id: str, name: str) -> dict[str, Any]:"""One saved grid's full spec."""case = get_case(case_id)try:- spec_path = case.resolve_inside(f"search/{name}.json")+ spec_path = case.resolve_inside(layout.grid_rel(name))except CaseError as exc:raise HTTPException(status_code=403, detail=str(exc)) from excif not spec_path.exists():@@ -1055,7 +1056,7 @@ def save_search_grid(case_id: str, name: str, body: GridSaveIn) -> dict[str, Any_validate_grid_spec(spec)except ValueError as exc:raise HTTPException(status_code=422, detail=str(exc)) from exc- spec_path = case.subdir("search") / f"{slug}.json"+ spec_path = case.resolve_inside(layout.grid_rel(slug))_write_grid_atomic(spec_path, spec)return {"name": slug, "title": spec["title"], "updated_at": spec["updated_at"]}@@ -1065,7 +1066,7 @@ def delete_search_grid(case_id: str, name: str) -> dict[str, Any]:"""Discard one saved grid."""case = get_case(case_id)try:- spec_path = case.resolve_inside(f"search/{name}.json")+ spec_path = case.resolve_inside(layout.grid_rel(name))except CaseError as exc:raise HTTPException(status_code=403, detail=str(exc)) from excexisted = spec_path.exists()diff --git a/src/azimut/api/settings.py b/src/azimut/api/settings.pyindex d66b372..7240a10 100644--- a/src/azimut/api/settings.py+++ b/src/azimut/api/settings.py@@ -1,6 +1,7 @@"""REST API for app-wide keys, preferences, usage and proof branding.-Keys and branding stay beside settings.json, outside cases and exports.+Keys and branding stay together under ``.azimut/settings/`` in the workspace+directory, outside cases and exports."""from __future__ import annotations@@ -17,7 +18,17 @@ from fastapi.responses import FileResponsefrom pydantic import BaseModel, ConfigDict, Field, field_validator, model_validatorfrom .. import __version__, config-from ..engine import diagnostics, ffmpeg, google_tiles, scrapers, sentinel, tiles, updates+from ..engine import (+ diagnostics,+ ffmpeg,+ google_tiles,+ reveal,+ scrapers,+ sentinel,+ tiles,+ updates,+ workspacemove,+)from .ingest import bundled_extension_versionfrom .templates import MAX_PER_KIND as MAX_TEMPLATES_PER_KIND@@ -186,7 +197,9 @@ def put_prefs(body: PrefsIn) -> dict[str, Any]:def _apply_prefs(settings: dict[str, Any], body: PrefsIn) -> None:if body.providers_enabled is not None:merged = dict(settings.get("providers_enabled", {}))- merged.update({k: bool(v) for k, v in body.providers_enabled.items() if k in KEYED_PROVIDERS})+ merged.update(+ {k: bool(v) for k, v in body.providers_enabled.items() if k in KEYED_PROVIDERS}+ )settings["providers_enabled"] = mergedif body.usage_overrides is not None:merged = dict(settings.get("usage_overrides", {}))@@ -275,6 +288,95 @@ class StatusIn(BaseModel):detail: str = ""[email protected]("/settings/reveal-workspace")+def reveal_workspace() -> dict[str, str]:+ """Open the workspace folder in the system file manager.++ About already prints the path; this saves copying it into a file manager by+ hand, which is what the first analyst to ask ended up doing with a shortcut.+ """+ root = config.workspace_root()+ try:+ reveal.reveal(root)+ except reveal.RevealError as exc:+ raise HTTPException(status_code=409, detail=str(exc)) from exc+ return {"path": str(root)}+++class FolderIn(BaseModel):+ """A folder the analyst typed. There is no native picker — the GUI-toolkit+ rule forbids one and a browser cannot hand back a real path — so the path+ arrives as text and every check happens server-side."""++ path: str++[email protected]("/settings/workspace")+def workspace_status() -> dict[str, Any]:+ """Where the workspace is, and how a move in progress is going."""+ return workspacemove.status()++[email protected]("/settings/workspace/inspect")+def inspect_workspace_target(body: FolderIn) -> dict[str, Any]:+ """Read a candidate folder without touching it: what Azimut would do with+ it, what it refuses, and what it wants to warn about first."""+ return workspacemove.inspect_target(body.path)++[email protected]("/settings/workspace/use")+def use_workspace_folder(body: FolderIn) -> dict[str, Any]:+ """Use a folder as it is, moving nothing.++ The likely path: someone who already moved the folder by hand, or who wants+ a second workspace. Cases in the current folder stay where they are.+ """+ try:+ return workspacemove.adopt(body.path)+ except workspacemove.MoveError as exc:+ raise HTTPException(status_code=409, detail=str(exc)) from exc++[email protected]("/settings/workspace/default")+def use_default_workspace() -> dict[str, Any]:+ """Forget the configured location and go back to the default folder."""+ return workspacemove.use_default()++[email protected]("/settings/workspace/move")+def move_workspace(body: FolderIn) -> dict[str, Any]:+ """Copy the workspace to a new folder, then switch to it.++ Returns as soon as the work is queued; `GET /settings/workspace` reports+ each step. The old folder is kept until the analyst drops it.+ """+ try:+ return workspacemove.start(body.path)+ except workspacemove.MoveError as exc:+ raise HTTPException(status_code=409, detail=str(exc)) from exc++[email protected]("/settings/workspace/take")+def take_the_workspace_lock() -> dict[str, Any]:+ """Open a workspace another Azimut appears to hold.++ The last word on a verdict this side of a network share cannot always get+ right: two machines' clocks, or a lock file nobody is left to clear.+ """+ return workspacemove.take_the_lock()++[email protected]("/settings/workspace/discard-old")+def discard_old_workspace() -> dict[str, str]:+ """Delete the folder the last move set aside."""+ try:+ return {"path": workspacemove.discard_old()}+ except workspacemove.MoveError as exc:+ raise HTTPException(status_code=409, detail=str(exc)) from exc+ except OSError as exc:+ raise HTTPException(status_code=409, detail=f"could not remove it: {exc}") from exc++@router.post("/settings/ingest-token/rotate")def rotate_ingest_token() -> dict[str, Any]:"""Mint a fresh capture-extension pairing token, orphaning every extension@@ -424,9 +526,7 @@ class ImportedSettings(BaseModel):)tile_providers: list[ImportedTileProvider] = Field(default_factory=list, max_length=100)api_keys: dict[ShortId, SecretValue] = Field(default_factory=dict, max_length=128)- usage: dict[ShortId, dict[UsageMonth, UsageCount]] = Field(- default_factory=dict, max_length=128- )+ usage: dict[ShortId, dict[UsageMonth, UsageCount]] = Field(default_factory=dict, max_length=128)providers_enabled: dict[ShortId, bool] = Field(default_factory=dict, max_length=128)usage_overrides: dict[ShortId, bool] = Field(default_factory=dict, max_length=128)free_tiers: dict[ShortId, FreeTier] = Field(default_factory=dict, max_length=128)diff --git a/src/azimut/config.py b/src/azimut/config.pyindex 79c9f80..3345dec 100644--- a/src/azimut/config.py+++ b/src/azimut/config.py@@ -1,15 +1,24 @@"""Application configuration and workspace-root resolution.-Everything Azimut persists lives under one root directory (default ``~/Azimut``,-overridable with the ``AZIMUT_HOME`` environment variable):+Everything Azimut persists lives under one root directory. Where that root is+cannot be recorded inside it, so the answer comes from three places, in order:+``AZIMUT_HOME`` in the environment, then the pointer file this module writes at+the platform's conventional location, then ``~/Azimut``. Nothing else in the app+asks the question — every path is built from :func:`workspace_root`.~/Azimut/- ├── cases/ # named investigations- ├── scratch/ # one-shot sessions (promotable to cases)- ├── runtime/ # newer scrapers fetched at runtime (engine/scrapers.py)- ├── signature.png # optional analyst logo, stamped onto proofs- ├── settings.json- └── templates.json # reusable proof and post styles+ ├── named-investigation/ # one folder per permanent case+ └── .azimut/ # app machinery, hidden from normal browsing+ ├── bundles/+ ├── cache/tiles/+ ├── lock # held by the one Azimut using this workspace+ ├── runtime/ # newer scrapers fetched at runtime+ ├── scratch/ # one-shot sessions, promotable to cases+ └── settings/+ ├── cookies.txt+ ├── signature.png+ ├── settings.json+ └── templates.jsonNo external database server; the workspace remains self-contained (spec §4)."""@@ -21,6 +30,7 @@ import jsonimport loggingimport osimport re+import sysimport tempfileimport threadingfrom datetime import datetime, timezone@@ -116,7 +126,7 @@ DEFAULT_SETTINGS: dict[str, Any] = {# - {"source": "none"} — off (default)# - {"source": "browser", "browser": name} — read the browser's live cookies# (yt-dlp's names: firefox, chrome, chromium, edge, brave, opera, safari, …)- # - {"source": "file", "file": "cookies.txt"} — a workspace-relative export,+ # - {"source": "file", "file": "cookies.txt"} — an export kept in settings,# the fallback where reading the browser can't work (Chromium on Windows)."download_cookies": {"source": "none"},}@@ -151,22 +161,162 @@ BLOCK_SHARE = 0.9ECO_MAX_ZOOM = 15+# -- where the workspace is ---------------------------------------------------+#+# The workspace can be moved anywhere the analyst likes, so its address is the+# one piece of state that cannot live inside it. It goes in a one-line file at+# the platform's conventional configuration location, and writing that file is+# the entire act of switching workspaces: die just before it and the old folder+# is authoritative, die just after and the new one is. Both are complete, and+# there is no third state to interpret.+#+# `AZIMUT_HOME` stays ahead of the pointer. It is an instruction given on every+# launch, which is what makes a workspace on a USB stick or a second profile+# work without touching the machine's configuration.++#: Where a workspace is created when nobody has said otherwise.+DEFAULT_ROOT = Path("~/Azimut")++#: The pointer's filename. Its directory is platform-specific (`pointer_path`).+POINTER_NAME = "location"+++def _pointer_dir() -> Path:+ """The platform's own place for a small application configuration file.++ Deliberately outside the workspace and outside the program: the frozen+ binary may sit on read-only media, and a pointer stored in the folder it+ points at answers nothing.+ """+ if sys.platform == "win32":+ base = os.environ.get("APPDATA")+ return Path(base) / "Azimut" if base else Path("~/AppData/Roaming/Azimut").expanduser()+ if sys.platform == "darwin":+ return Path("~/Library/Application Support/Azimut").expanduser()+ base = os.environ.get("XDG_CONFIG_HOME")+ return (Path(base) if base else Path("~/.config").expanduser()) / "azimut"+++def pointer_path() -> Path:+ return _pointer_dir() / POINTER_NAME+++def read_pointer() -> Path | None:+ """The workspace the pointer names, or None when there is no usable pointer.++ Unreadable, empty or missing all mean the same thing on purpose. A lost+ pointer costs an address, never data: Azimut falls back to the default root+ and "use an existing folder" re-points the real one.+ """+ try:+ raw = pointer_path().read_text(encoding="utf-8").strip()+ except (OSError, UnicodeDecodeError, ValueError):+ return None+ return Path(raw).expanduser() if raw else None+++def write_pointer(root: Path) -> None:+ """Point Azimut at *root*, atomically. This is the switch, and the whole of it."""+ path = pointer_path()+ path.parent.mkdir(parents=True, exist_ok=True)+ fd, tmp_name = tempfile.mkstemp(prefix=f".{path.name}.", suffix=".tmp", dir=path.parent)+ tmp_path = Path(tmp_name)+ try:+ with os.fdopen(fd, "w", encoding="utf-8") as handle:+ handle.write(f"{Path(root)}\n")+ handle.flush()+ os.fsync(handle.fileno())+ _restrict(tmp_path, 0o600)+ os.replace(tmp_path, path)+ _restrict(path, 0o600)+ finally:+ tmp_path.unlink(missing_ok=True)+ forget_workspace_root()+++def clear_pointer() -> None:+ """Forget a configured location and go back to the default root."""+ pointer_path().unlink(missing_ok=True)+ forget_workspace_root()+++# Resolved once per process rather than per path lookup: `workspace_root()` is+# called on the way to every file Azimut touches, and reading a file each time+# to learn where the other files are would be absurd. Only our own writes change+# the answer, and they invalidate this.+_root_cache: Path | None = None+_root_pointed = False+_root_lock = threading.Lock()+++def forget_workspace_root() -> None:+ """Re-resolve the root on the next call. Follows a pointer write."""+ global _root_cache+ with _root_lock:+ _root_cache = None++def workspace_root() -> Path:- root = Path(os.environ.get("AZIMUT_HOME", "~/Azimut")).expanduser()- return root+ global _root_cache, _root_pointed+ override = os.environ.get("AZIMUT_HOME")+ if override:+ return Path(override).expanduser()+ cached = _root_cache+ if cached is not None:+ return cached+ with _root_lock:+ if _root_cache is None:+ pointed = read_pointer()+ _root_pointed = pointed is not None+ _root_cache = pointed or DEFAULT_ROOT.expanduser()+ return _root_cache+++def workspace_missing() -> bool:+ """True when a workspace was configured and is not there any more.++ Only the pointer can say this. It is written after a folder has been+ verified, so a pointer naming nothing means the folder was renamed, deleted+ or is on a drive that is not plugged in — never a first run. Recreating it+ silently would be the fastest way to make someone believe they lost+ everything, so startup stops instead (`server.py`).++ ``AZIMUT_HOME`` keeps its create-on-demand behaviour: it is given again on+ every launch, which is what makes a portable workspace work. It also settles+ the question by itself — when it is set the pointer is not consulted at all,+ so a stale one left by an earlier run must not stop this one.++ Asked on every API request (`server.install_availability_guard`), so it+ reads the resolved root rather than the pointer file: one stat, and the+ answer stays stable for the run the way a startup decision should.+ """+ if os.environ.get("AZIMUT_HOME"):+ return False+ root = workspace_root()+ return _root_pointed and not root.is_dir()def cases_dir() -> Path:- return workspace_root() / "cases"+ """Parent of permanent cases.++ Cases live directly under the workspace so opening it in a file manager+ shows the analyst's investigations rather than Azimut's machinery.+ """+ return workspace_root()+++def internal_dir() -> Path:+ """Hidden root for every workspace-wide implementation detail."""+ return workspace_root() / ".azimut"def scratch_dir() -> Path:- return workspace_root() / "scratch"+ return internal_dir() / "scratch"def bundles_dir() -> Path:"""Portable case bundles exported by the user."""- return workspace_root() / "bundles"+ return internal_dir() / "bundles"def runtime_dir() -> Path:@@ -176,11 +326,21 @@ def runtime_dir() -> Path:directory we know is user-writable: the frozen binary can sit in/usr/local/bin or Program Files, and its own contents are read-only."""- return workspace_root() / "runtime"+ return internal_dir() / "runtime"+++def settings_dir() -> Path:+ """Hidden app-wide preferences and branding, outside every case."""+ return internal_dir() / "settings"+++def tile_cache_dir() -> Path:+ """Disposable map imagery cache, outside every case and backup."""+ return internal_dir() / "cache" / "tiles"def settings_path() -> Path:- return workspace_root() / "settings.json"+ return settings_dir() / "settings.json"def signature_path() -> Path:@@ -192,7 +352,7 @@ def signature_path() -> Path:because that file goes to the user's own second machine, not to a thirdparty (api/settings.py export/import)."""- return workspace_root() / "signature.png"+ return settings_dir() / "signature.png"def templates_path() -> Path:@@ -203,7 +363,7 @@ def templates_path() -> Path:backup for the same reason. Kept out of settings.json itself so the secretsfile stays small and single-purpose."""- return workspace_root() / "templates.json"+ return settings_dir() / "templates.json"# Browsers yt-dlp can read a login session from (cookiesfrombrowser). The@@ -217,7 +377,7 @@ COOKIE_BROWSERS = frozenset(def cookies_file_path() -> Path:"""A user-exported cookies.txt for gated downloads. Holds a live loginsession, so it stays 0600 beside settings.json, never inside a case."""- return workspace_root() / "cookies.txt"+ return settings_dir() / "cookies.txt"# Refuse anything larger as a signature: a logo is a small badge on a composite,@@ -237,14 +397,19 @@ def valid_signature(data: bytes) -> bool:def ensure_workspace() -> None:- """Create the workspace skeleton if missing (idempotent)."""- cases_dir().mkdir(parents=True, exist_ok=True)- scratch_dir().mkdir(parents=True, exist_ok=True)- bundles_dir().mkdir(parents=True, exist_ok=True)+ """Create and migrate the workspace skeleton (idempotent and lossless)."""+ workspace_root().mkdir(parents=True, exist_ok=True)+ internal_dir().mkdir(parents=True, exist_ok=True)# The workspace holds API keys and the pairing token — keep it owner-only# so another account on a shared machine can't read them. Best-effort:# Windows ignores POSIX modes, which is fine (its ACLs already scope $HOME)._restrict(workspace_root(), 0o700)+ _restrict(internal_dir(), 0o700)+ _hide_if_dotted(internal_dir())+ _migrate_workspace_settings()+ _migrate_workspace_directories()+ for directory in (scratch_dir(), bundles_dir(), runtime_dir(), tile_cache_dir()):+ directory.mkdir(parents=True, exist_ok=True)if not settings_path().exists():save_settings(DEFAULT_SETTINGS)return@@ -267,6 +432,134 @@ def _restrict(path: Path, mode: int) -> None:pass+def _hide_if_dotted(path: Path) -> None:+ """Make a dot-directory hidden in Windows Explorer too."""+ if sys.platform != "win32" or not path.name.startswith("."):+ return+ import ctypes++ file_attribute_hidden = 0x02+ try:+ ctypes.windll.kernel32.SetFileAttributesW(str(path), file_attribute_hidden)+ except (AttributeError, OSError): # pragma: no cover - Windows only+ pass+++def _legacy_destination(path: Path) -> Path:+ """A lossless home for a legacy file when the new location already differs."""+ candidate = path.with_name(f"{path.stem}.legacy{path.suffix}")+ index = 2+ while candidate.exists():+ candidate = path.with_name(f"{path.stem}.legacy-{index}{path.suffix}")+ index += 1+ return candidate+++def _migrate_workspace_settings() -> None:+ """Move old workspace settings under ``.azimut/settings/``.++ Each file is an independent atomic rename, so a stopped startup simply+ resumes with whichever legacy names remain. The current location wins if a+ user somehow has both; a differing legacy file is retained beside it under+ a ``.legacy`` name rather than overwritten or discarded.+ """+ directory = settings_dir()+ directory.mkdir(parents=True, exist_ok=True)+ _restrict(directory, 0o700)+ _hide_if_dotted(directory)+ for source_dir in (workspace_root(), workspace_root() / ".settings"):+ for name in ("settings.json", "templates.json", "signature.png", "cookies.txt"):+ source = source_dir / name+ if not source.is_file():+ continue+ destination = directory / name+ if destination.exists():+ if source.read_bytes() == destination.read_bytes():+ source.unlink()+ _restrict(destination, 0o600)+ continue+ destination = _legacy_destination(destination)+ source.rename(destination)+ _restrict(destination, 0o600)+ old_directory = workspace_root() / ".settings"+ if old_directory.is_dir() and not any(old_directory.iterdir()):+ old_directory.rmdir()+++class WorkspaceMigrationError(RuntimeError):+ """A workspace move stopped because two different entries would collide."""+++def _merge_legacy_directory(source: Path, destination: Path) -> None:+ """Move ``source`` into ``destination`` without overwriting anything.++ Moving one child at a time makes a killed migration restartable. Identical+ files left by a previous partial copy collapse safely; different entries+ stop the migration with both originals intact for the future doctor.+ """+ if not source.exists():+ return+ if not source.is_dir() or source.is_symlink():+ raise WorkspaceMigrationError(f"workspace migration expected a directory: {source}")+ destination.mkdir(parents=True, exist_ok=True)+ for child in sorted(source.iterdir(), key=lambda path: path.name):+ target = destination / child.name+ if not target.exists():+ child.rename(target)+ continue+ if (+ child.is_dir()+ and target.is_dir()+ and not child.is_symlink()+ and not target.is_symlink()+ ):+ _merge_legacy_directory(child, target)+ continue+ if child.is_file() and target.is_file() and child.read_bytes() == target.read_bytes():+ child.unlink()+ continue+ raise WorkspaceMigrationError(+ f"workspace migration cannot merge different entries: {child} and {target}"+ )+ source.rmdir()+++def _move_case_directories(source: Path, destination: Path) -> None:+ """Move case folders one by one, refusing even a merge-shaped collision."""+ if not source.exists():+ return+ if not source.is_dir() or source.is_symlink():+ raise WorkspaceMigrationError(f"workspace migration expected a directory: {source}")+ destination.mkdir(parents=True, exist_ok=True)+ for child in sorted(source.iterdir(), key=lambda path: path.name):+ target = destination / child.name+ if target.exists():+ raise WorkspaceMigrationError(+ f"workspace migration refuses to merge case directories: {child} and {target}"+ )+ child.rename(target)+ source.rmdir()+++def _migrate_workspace_directories() -> None:+ """Flatten old ``cases/`` and hide all workspace machinery.++ Directory renames are used rather than replacement or deletion, including+ for scratch cases, so the operation is portable to Windows and resumes+ cleanly after an interrupted startup.+ """+ root = workspace_root()+ _move_case_directories(root / "scratch", scratch_dir())+ for legacy_name, destination in (+ (".settings", settings_dir()),+ ("bundles", bundles_dir()),+ ("runtime", runtime_dir()),+ ("tile-cache", tile_cache_dir()),+ ):+ _merge_legacy_directory(root / legacy_name, destination)+ _move_case_directories(root / "cases", root)++# from_version -> function(data) returning settings reshaped for from_version+1.# The runner (migrate_settings) stamps the new number, so a migration only# rewrites fields. Empty while we're on the first schema.@@ -422,9 +715,7 @@ def save_templates(templates: dict[str, Any]) -> None:path = templates_path()path.parent.mkdir(parents=True, exist_ok=True)_restrict(path.parent, 0o700)- payload = json.dumps(- templates, indent=2, ensure_ascii=False, allow_nan=False- ) + "\n"+ payload = json.dumps(templates, indent=2, ensure_ascii=False, allow_nan=False) + "\n"fd, tmp_name = tempfile.mkstemp(prefix=f".{path.name}.", suffix=".tmp", dir=path.parent)tmp_path = Path(tmp_name)try:diff --git a/src/azimut/engine/artifacts.py b/src/azimut/engine/artifacts.pyindex e1a9d6b..320cded 100644--- a/src/azimut/engine/artifacts.py+++ b/src/azimut/engine/artifacts.py@@ -20,10 +20,12 @@ would blank a surviving row.from __future__ import annotationsimport shutil+from collections.abc import Callablefrom dataclasses import dataclass, field-from pathlib import Path+from pathlib import Path, PurePosixPathfrom typing import TYPE_CHECKING, Any, ClassVar+from .. import layoutfrom ..workspace import CaseErrorfrom . import media as media_engine@@ -45,22 +47,25 @@ class Companion:@dataclass(frozen=True)class Sidecar(Companion):- """The media sidecar sitting beside the file, ``<name>.azimut.json``."""+ """The media sidecar, out of the listing in ``media/.meta/``."""def resolve(self, case: "Case", main: str) -> str | None:- return main + media_engine.SIDECAR_SUFFIX+ return layout.sidecar_rel(main)@dataclass(frozen=True)-class Swap(Companion):- """A companion named after the main artifact with its suffix swapped —- ``proofs/x.json`` → ``proofs/x.png``, or the ``proofs/x.assets`` folder."""+class Named(Companion):+ """A companion the layout names after the main artifact's stem.- old: str- new: str+ A proof's spec lives in ``proofs/.meta/`` while the PNG it renders stays+ visible in ``proofs/``, so "same name, swapped suffix" stopped being enough+ — where each one goes is `layout`'s answer, not a string operation.+ """++ build: Callable[[str], str]def resolve(self, case: "Case", main: str) -> str | None:- return main.removesuffix(self.old) + self.new+ return self.build(PurePosixPath(main).stem)@dataclass(frozen=True)@@ -97,7 +102,10 @@ KINDS: dict[str, Kind] = {"capture": Kind(path_attr="path", companions=(Sidecar(), SharedThumb()), indexed=True),"proof": Kind(path_attr="spec",- companions=(Swap(".json", ".png"), Swap(".json", ".assets")),+ companions=(+ Named(layout.proof_export_rel),+ Named(layout.proof_assets_rel),+ ),),"post": Kind(path_attr="draft"),"inspect-session": Kind(path_attr="spec"),@@ -253,3 +261,4 @@ def delete(case: "Case", entity: dict[str, Any]) -> None:path = _resolve(case, rel)if path is not None:_remove(path)+ case.prune_note_dirs(rel)diff --git a/src/azimut/engine/bundles.py b/src/azimut/engine/bundles.pyindex 73ad1a5..bea17c1 100644--- a/src/azimut/engine/bundles.py+++ b/src/azimut/engine/bundles.py@@ -4,6 +4,14 @@ A plain bundle is a ZIP whose first member is a small compatibility header andwhose last member is the SHA-256 manifest. A sealed bundle encrypts that wholeZIP as an AES-256-GCM stream, so filenames and sizes are not left in the ZIPcentral directory for other programs to read.++**A bundle is the case folder.** Format 2 puts it under one `case/` member+prefix, so unzipping one by hand gives back one directory: `azimut/` holding the+tool's state, and beside it whatever the analyst keeps there. The prefix also+keeps the bundle's own two metadata members outside the case, so files called+`bundle.json` and `bundle-header.json` remain valid analyst files. Format 1+named members relative to the tool root and carried only the tool's half; those+bundles still import, and the folder migration reshapes them on first open."""from __future__ import annotations@@ -23,17 +31,21 @@ import zipfilefrom contextlib import closingfrom datetime import datetime, timezonefrom pathlib import Path, PurePosixPath-from typing import Any, BinaryIO, Iterator+from typing import Any, BinaryIO, Callable, Iterable, Iteratorfrom cryptography.exceptions import InvalidTagfrom cryptography.hazmat.primitives.ciphers.aead import AESGCM-from .. import __version__, config+from .. import __version__, config, layoutfrom ..sqlite_backend import SQLITE_SCHEMA, SqliteCase-from ..workspace import Case, CaseError, _now, _replace_with_retry+from ..workspace import Case, CaseError, _now, _replace_with_retry, ensure_dirfrom . import workqueue-BUNDLE_FORMAT = 1+BUNDLE_FORMAT = 2+#: The format from which members are named relative to the case root rather than+#: the tool root, which is what lets a bundle carry the analyst's own folders.+WRAPPED_MEMBERS = 2+BUNDLE_ROOT = "case"HEADER_NAME = "bundle-header.json"MANIFEST_NAME = "bundle.json"MAGIC = b"AZIMUT-BUNDLE\0"@@ -56,15 +68,36 @@ _ZIP_LOCAL = struct.Struct("<4s5H3I2H")_ZIP_LOCAL_MAGIC = b"PK\x03\x04"_ZIP_DESCRIPTOR_MAGIC = b"PK\x07\x08"+#: What the *tool root* holds that travels. Anything else there is a cache or+#: the trash, and `classify_case_entry` must have an answer for it.BUNDLED_ROOTS = frozenset(- {"case.json", "case.db", "notes.md", "notes", "media", "proofs", "exports", "inspect", "search"}+ {"case.json", "notes.md", layout.DATA_DIR, *layout.CASE_SUBDIRS})++#: What a format-1 *import* accepts on top of that: the names the tool root used+#: before the database and the session directories were hidden. A bundle written+#: by an older Azimut must still land, and the folder migration reshapes it on+#: first open — refusing the member outright would strand every bundle already+#: exported. Format 2 never uses these, so this set dies with format 1.+IMPORTABLE_ROOTS = BUNDLED_ROOTS | {"case.db", "exports", "inspect", "search"}NOT_BUNDLED = {".trash": "deleted artifacts do not travel","media/.thumbs": "content-addressed thumbnails are rebuilt","media/.dl": "in-progress downloads belong to this machine",}+#: Extensions whose bytes are already compressed. Deflating them burns CPU on+#: every export and saves nothing, and the free zone is where a case's largest+#: files land.+_PRECOMPRESSED = frozenset(+ {+ ".jpg", ".jpeg", ".png", ".gif", ".webp", ".avif", ".heic",+ ".mp4", ".m4v", ".mov", ".mkv", ".webm", ".avi",+ ".mp3", ".m4a", ".aac", ".ogg", ".opus", ".flac",+ ".zip", ".gz", ".bz2", ".xz", ".zst", ".7z", ".rar",+ }+)+EXPORT_JOB = "bundle-export"IMPORT_JOB = "bundle-import"_secret_lock = threading.Lock()@@ -118,7 +151,7 @@ def stage_upload(source: BinaryIO) -> tuple[str, Path]:directory.mkdir(parents=True, exist_ok=True)cleanup_uploads()usage = shutil.disk_usage(directory)- reserve = _disk_reserve(usage.total)+ reserve = disk_reserve(usage.total)budget = max(0, usage.free - reserve)upload_id = uuid.uuid4().hexdestination = _upload_path(upload_id)@@ -194,6 +227,14 @@ def _portable_member_key(name: str) -> str:def _validate_member_names(names: list[str]) -> None:+ # Checked on the way out as well as on the way in: an export that produced+ # more members than an import accepts would write a bundle nobody could+ # open, and the free zone is where a case first gets enough files for that+ # to be reachable.+ if len(names) > MAX_BUNDLE_MEMBERS:+ raise BundleError(+ f"a bundle carries at most {MAX_BUNDLE_MEMBERS} files, and this case has {len(names)}"+ )if any(not _safe_member(name) for name in names):raise BundleError("the bundle contains a path that is not portable")portable = [_portable_member_key(name) for name in names]@@ -201,7 +242,7 @@ def _validate_member_names(names: list[str]) -> None:raise BundleError("the bundle contains paths that collide on another operating system")-def _disk_reserve(total: int) -> int:+def disk_reserve(total: int) -> int:"""Leave a small recovery margin without imposing a fixed bundle-size cap."""return min(MAX_DISK_RESERVE, max(MIN_DISK_RESERVE, total // 100))@@ -217,7 +258,7 @@ def _space_preview(source: Path, header: dict[str, Any]) -> dict[str, Any]:# A sealed bundle is decrypted to a temporary ZIP before extraction. A plain# ZIP is read in place, so only its extracted payload needs additional space.estimated = payload + (source_size if header.get("sealed") else 0)- reserve = _disk_reserve(usage.total)+ reserve = disk_reserve(usage.total)return {"estimated_import_bytes": estimated,"free_space_bytes": usage.free,@@ -240,7 +281,7 @@ def _require_extract_space(target: Path, total_size: int) -> None:usage = shutil.disk_usage(target)except OSError as exc:raise BundleError("could not check free space for bundle extraction") from exc- if total_size + _disk_reserve(usage.total) > usage.free:+ if total_size + disk_reserve(usage.total) > usage.free:raise BundleError("not enough free space to extract this bundle while keeping a disk safety reserve")@@ -251,7 +292,7 @@ def _require_export_space(target: Path, total_size: int) -> None:usage = shutil.disk_usage(target.parent)except OSError as exc:raise BundleError("could not check free space for bundle export") from exc- if total_size + _disk_reserve(usage.total) > usage.free:+ if total_size + disk_reserve(usage.total) > usage.free:raise BundleError("not enough free space to export this case while keeping a disk safety reserve")@@ -267,6 +308,20 @@ def _included(rel: str) -> bool:return PurePosixPath(rel).parts[0] in BUNDLED_ROOTS+def _importable(rel: str, version: int) -> bool:+ """Whether a bundle member may land, at the naming its format declares."""+ if version < WRAPPED_MEMBERS:+ return PurePosixPath(rel).parts[0] in IMPORTABLE_ROOTS+ parts = PurePosixPath(rel).parts+ if len(parts) < 2 or parts[0] != BUNDLE_ROOT:+ return False+ head = parts[1]+ inside = "/".join(parts[2:])+ if head == layout.TOOL_DIR:+ return bool(inside) and _included(inside)+ return not layout.is_tool_dir(head)++def classify_case_entry(rel: str) -> str | None:"""Return ``bundled``/``not-bundled`` for declared case state."""if _included(rel):@@ -276,13 +331,67 @@ def classify_case_entry(rel: str) -> str | None:return None-def _case_files(case: Case) -> Iterator[tuple[str, Path]]:- for path in sorted(case.path.rglob("*")):- if not path.is_file():+def _walk(+ entries: Iterable[Path], base: Path, keep: Callable[[str], bool]+) -> Iterator[tuple[str, Path]]:+ """(`base`-relative name, path) for every file under `entries` that `keep` keeps.++ A directory `keep` rejects is never descended into, so skipping a cache+ costs nothing.++ Symlinks are refused rather than followed. `rglob` walks into a linked+ directory and `is_file()` follows a linked file, so the previous walk would+ have copied a link's *target* into the bundle under a name saying it was the+ analyst's own file — which turns "the free zone travels" into a way to read+ anything the account can reach. A bundle carries what the folder holds.+ """+ for entry in sorted(entries):+ rel = entry.relative_to(base).as_posix()+ if not keep(rel):continue- rel = path.relative_to(case.path).as_posix()- if _included(rel) and rel not in {"case.json", "case.db"}:- yield rel, path+ if entry.is_symlink():+ raise BundleError(f"'{rel}' is a symbolic link; a bundle carries files, not links")+ if entry.is_dir():+ yield from _walk(entry.iterdir(), base, keep)+ elif entry.is_file():+ yield rel, entry+ else:+ raise BundleError(f"'{rel}' is not a regular file")+++def _check_free_name(name: str) -> None:+ """The one name the analyst's half of a case folder cannot use."""+ if layout.is_tool_dir(name):+ raise BundleError(+ f"'{name}' collides with Azimut's own folder on Windows and macOS; "+ "rename it before exporting"+ )+++def _case_files(case: Case) -> Iterator[tuple[str, Path]]:+ """Every file a bundle carries, named the way the bundle names it.++ Members sit under the bundle's `case/` prefix: `case/azimut/media/x.png` for+ the tool's own state, and the analyst's folders under the names they gave+ them. A bundle should carry the whole investigation rather than the half+ Azimut happened to author. The prefix makes an unzipped bundle one folder+ and leaves the bundle's metadata names outside the analyst's free zone.++ The manifest and the database are not in here. The export writes them+ itself, the database after cleaning this machine's state out of it.+ """+ tool = case.tool_root+ written_apart = {+ path.relative_to(tool).as_posix() for path in (case.json_path, case.db_path)+ }+ for rel, path in _walk(tool.iterdir(), tool, _included):+ if rel not in written_apart:+ yield f"{BUNDLE_ROOT}/{layout.TOOL_DIR}/{rel}", path+ free = case.free_entries()+ for entry in free:+ _check_free_name(entry.name)+ for rel, path in _walk(free, case.path, lambda _rel: True):+ yield f"{BUNDLE_ROOT}/{rel}", pathdef _clean_database(source: Path, target: Path) -> None:@@ -314,7 +423,11 @@ def _zip_info(name: str, *, compressed: bool) -> zipfile.ZipInfo:def _compress_member(name: str) -> bool:- return name != HEADER_NAME and not name.startswith("media/")+ if name == HEADER_NAME:+ return False+ if name.startswith(f"{BUNDLE_ROOT}/{layout.TOOL_DIR}/media/"):+ return False+ return PurePosixPath(name).suffix.lower() not in _PRECOMPRESSEDdef _write_bytes(@@ -464,11 +577,17 @@ def export_case(clean_db = Path(db_name)try:- _clean_database(case.path / "case.db", clean_db)+ _clean_database(case.db_path, clean_db)case_json = case.json_path.read_bytes()files = list(_case_files(case))+ # The two members the export writes itself, named the way every other+ # member is: where they sit in the case folder.+ manifest_member = (+ f"{BUNDLE_ROOT}/{case.json_path.relative_to(case.path).as_posix()}"+ )+ db_member = f"{BUNDLE_ROOT}/{case.db_path.relative_to(case.path).as_posix()}"_validate_member_names(- [HEADER_NAME, "case.json", "case.db", *(rel for rel, _ in files), MANIFEST_NAME]+ [HEADER_NAME, manifest_member, db_member, *(rel for rel, _ in files), MANIFEST_NAME])total_size = len(case_json) + clean_db.stat().st_sizetotal_size += sum(path.stat().st_size for _, path in files)@@ -492,8 +611,8 @@ def export_case(records: list[dict[str, Any]] = []with zipfile.ZipFile(target, "w", allowZip64=True) as archive:_write_bytes(archive, HEADER_NAME, _json_bytes(header), records)- _write_bytes(archive, "case.json", case_json, records)- _write_file(archive, "case.db", clean_db, records)+ _write_bytes(archive, manifest_member, case_json, records)+ _write_file(archive, db_member, clean_db, records)for rel, path in files:_write_file(archive, rel, path, records)archive.writestr(@@ -654,18 +773,19 @@ def _decrypt_to(source: Path, target: Path, password: str) -> None:stream.write(chunk)-def _manifest(archive: zipfile.ZipFile) -> tuple[list[zipfile.ZipInfo], dict[str, Any]]:+def _manifest(+ archive: zipfile.ZipFile, version: int+) -> tuple[list[zipfile.ZipInfo], dict[str, Any]]:infos = archive.infolist()- if len(infos) > MAX_BUNDLE_MEMBERS:- raise BundleError("the bundle contains too many members")names = [info.filename for info in infos]if len(names) != len(set(names)):raise BundleError("the bundle contains duplicate member names")if not names or names[0] != HEADER_NAME or names[-1] != MANIFEST_NAME:raise BundleError("the bundle header or manifest is out of place")_validate_member_names(names)- if any(name != HEADER_NAME and not _included(name) for name in names[:-1]):- raise BundleError("the bundle contains undeclared case state")+ for name in names[1:-1]:+ if not _importable(name, version):+ raise BundleError("the bundle contains undeclared case state")if any((info.external_attr >> 16) & 0o170000 == 0o120000 for info in infos):raise BundleError("the bundle contains a symbolic link")if any(info.is_dir() for info in infos):@@ -681,7 +801,7 @@ def _manifest(archive: zipfile.ZipFile) -> tuple[list[zipfile.ZipInfo], dict[strrecords = manifest.get("members") if isinstance(manifest, dict) else Noneif not isinstance(records, list):raise BundleError("invalid bundle manifest")- if manifest.get("format_version") != BUNDLE_FORMAT:+ if manifest.get("format_version") != version:raise BundleError("unsupported bundle manifest")by_name: dict[str, dict[str, Any]] = {}for record in records:@@ -696,9 +816,18 @@ def _manifest(archive: zipfile.ZipFile) -> tuple[list[zipfile.ZipInfo], dict[strreturn infos[:-1], by_name-def _verify_and_extract(archive_path: Path, target: Path) -> dict[str, Any]:+def _verify_and_extract(+ archive_path: Path, case_root: Path, *, declared: int+) -> dict[str, Any]:+ """Check every member against the manifest, then write them out.++ `declared` is the format the pre-flight header announced, and it decides+ both which member names are legal and where they land. It is not trusted on+ that word alone: the header is verified against the manifest below, and the+ version it really carries has to be the one the names were checked against.+ """with zipfile.ZipFile(archive_path) as archive:- infos, records = _manifest(archive)+ infos, records = _manifest(archive, declared)for info in infos:record = records[info.filename]expected_size = record.get("size")@@ -729,6 +858,12 @@ def _verify_and_extract(archive_path: Path, target: Path) -> dict[str, Any]:header = _validate_header(json.loads(data))except (UnicodeDecodeError, json.JSONDecodeError) as exc:raise BundleError("invalid bundle header") from exc+ if header["format_version"] != declared:+ raise BundleError("the bundle format does not match its verified header")+ # Format 1 named its members relative to the tool root and carried only+ # the tool's half of the case; format 2 names them relative to the case+ # folder and carries all of it.+ target = case_root if declared >= WRAPPED_MEMBERS else layout.tool_root(case_root)declared_total = sum(records[info.filename]["size"] for info in infos[1:])if declared_total != header["total_size"]:@@ -741,7 +876,11 @@ def _verify_and_extract(archive_path: Path, target: Path) -> dict[str, Any]:expected_size = record["size"]digest = hashlib.sha256()size = 0- destination = target / PurePosixPath(info.filename)+ relative = PurePosixPath(info.filename)+ if declared >= WRAPPED_MEMBERS:+ # `_importable` proved the first component is exactly `case`.+ relative = PurePosixPath(*relative.parts[1:])+ destination = target / relativedestination.parent.mkdir(parents=True, exist_ok=True)with archive.open(info) as src:sink: BinaryIO = destination.open("wb")@@ -765,6 +904,7 @@ def _verify_and_extract(archive_path: Path, target: Path) -> dict[str, Any]:def _prepare_import_database(db_path: Path,*,+ media_dir: Path,declared_schema: int,origin_case_id: str,name: str,@@ -777,7 +917,7 @@ def _prepare_import_database(raise BundleError("the case database failed its integrity check")if conn.execute("PRAGMA foreign_key_check").fetchone() is not None:raise BundleError("the case database has broken references")- SqliteCase.open(db_path)+ SqliteCase.open(db_path, media_dir=media_dir)with closing(sqlite3.connect(db_path)) as conn:for key, value in (("name", name),@@ -848,34 +988,52 @@ def import_into(if staging.exists():raise BundleError(f"import staging path '{staging.name}' already exists")staging.mkdir()+ # A format-1 bundle names its members relative to the tool root, so the+ # directory they extract into has to exist first. A format-2 bundle carries+ # `azimut/` itself and this is a no-op it does not mind.+ layout.tool_root(staging).mkdir()archive_path = sourcedecrypted = staging / ".bundle.zip"try:if header["sealed"]:_decrypt_to(source, decrypted, password or "")archive_path = decrypted- verified = _verify_and_extract(archive_path, staging)+ verified = _verify_and_extract(+ archive_path, staging, declared=int(header["format_version"])+ )decrypted.unlink(missing_ok=True)- if not (staging / "case.json").is_file() or not (staging / "case.db").is_file():+ # The staging directory is a case shell, not a case yet, so it is+ # addressed through `layout` against its own root rather than through a+ # `Case`.+ staged_manifest = layout.manifest(staging)+ staged_db = layout.extracted_database(staging)+ if not staged_manifest.is_file() or not staged_db.is_file():raise BundleError("the bundle does not contain a complete case")name = case.read().get("name", imported_name(verified["case_name"]))- manifest = json.loads((staging / "case.json").read_text(encoding="utf-8"))+ manifest = json.loads(staged_manifest.read_text(encoding="utf-8"))manifest["name"] = namemanifest["updated_at"] = _now()- (staging / "case.json").write_bytes(_json_bytes(manifest))+ staged_manifest.write_bytes(_json_bytes(manifest))_prepare_import_database(- staging / "case.db",+ staged_db,+ media_dir=layout.media(staging),declared_schema=verified["case_db_schema"],origin_case_id=str(verified.get("origin_case_id") or ""),name=name,)if job is not None:- _install_running_job(staging / "case.db", job)- for subdir in ("notes", "media", "proofs", "exports", "inspect", "search"):- (staging / subdir).mkdir(exist_ok=True)+ _install_running_job(staged_db, job)case.path.rename(old)staging.rename(case.path)imported = Case.open(case.id)+ # After the open, because opening is what migrates a case from an older+ # release: a `.inspect/` created here first would sit in the way of the+ # `inspect/` that step still has to rename. A ZIP carries no empty+ # directories, so this is also what gives the case the ones it is born+ # with — through `ensure_dir`, so the dot-directories are hidden.+ ensure_dir(layout.data_dir(imported.path))+ for directory in layout.content_dirs(imported.path):+ ensure_dir(directory)from . import thumbnailsfor item in imported.list_media_items():diff --git a/src/azimut/engine/diagnostics.py b/src/azimut/engine/diagnostics.pyindex ab4b51b..ee18e7e 100644--- a/src/azimut/engine/diagnostics.py+++ b/src/azimut/engine/diagnostics.py@@ -36,6 +36,7 @@ import loggingimport osimport platformimport re+import socketimport sysfrom collections import dequefrom pathlib import Path@@ -84,6 +85,7 @@ MAX_SUMMARY_CHARS = 2000_PLACEHOLDER = "<user>"_CASE_PLACEHOLDER = "<case>"_WORKSPACE_PLACEHOLDER = "<workspace>"+_MACHINE_PLACEHOLDER = "<machine>"_REDACTED = "<redacted>"#: Query parameters whose value is a credential. A keyed imagery or geocoding@@ -188,10 +190,13 @@ def scrub(text: str) -> str:Each pass exists because the report is published:- - the home directory collapses to ``~``- the workspace root collapses to ``<workspace>``, which catches a portableinstall living outside the home directory entirely+ - the remaining home directory collapses to ``~``- the account name becomes ``<user>``+ - this machine's name becomes ``<machine>``. The workspace lock names the+ host holding a folder, which on a corporate laptop is an asset tag and a+ company domain.- a case folder becomes ``<case>``. A case directory is a slug of the name theanalyst gave it (``workspace._slugify``), and in this tool that name isroutinely a subject's — so the segment goes even though the path around it@@ -201,22 +206,32 @@ def scrub(text: str) -> str:None of this makes an arbitrary string safe to publish; it removes what thisapp's own log lines are known to carry."""- try:- home = str(Path.home())- except Exception: # no home to hide- home = ""- if home:- text = _path_pattern(home).sub("~", text)try:root = str(config.workspace_root())except Exception:root = ""if root and root not in ("~", "/"):text = _path_pattern(root).sub(_WORKSPACE_PLACEHOLDER, text)+ # Permanent cases now sit directly below the workspace root. The one+ # reserved first segment is `.azimut`; every other directory there is+ # an analyst-named case and must not reach a public issue report.+ workspace = re.escape(_WORKSPACE_PLACEHOLDER)+ text = re.sub(+ rf"({workspace})([/\\])(?!\.azimut(?:[/\\]|$))[^/\\\s\"'<>]+",+ rf"\1\2{_CASE_PLACEHOLDER}",+ text,+ )+ try:+ home = str(Path.home())+ except Exception: # no home to hide+ home = ""+ if home:+ text = _path_pattern(home).sub("~", text)name = _account_name()# Two characters or fewer would match far too much ordinary prose.if len(name) > 2:text = text.replace(name, _PLACEHOLDER)+ text = _hide_machine_name(text)for directory in _case_parents():segment = re.escape(directory.name)text = re.sub(@@ -227,11 +242,30 @@ def scrub(text: str) -> str:return _CREDENTIAL_PARAM.sub(rf"\1={_REDACTED}", text)+def _hide_machine_name(text: str) -> str:+ """Replace this host's name, and the bare form of it.++ The workspace lock reports which machine holds a folder, so a "close the+ other Azimut" warning carries the hostname into the log tail a bug report+ publishes. On a work laptop that is an asset tag and an internal domain.+ """+ try:+ host = socket.gethostname()+ except Exception: # pragma: no cover - no name to hide+ return text+ # Longest first, so `laptop.corp.example` never leaves `.corp.example`+ # behind after `laptop` was replaced inside it.+ for candidate in sorted({host, host.split(".", 1)[0]}, key=len, reverse=True):+ if len(candidate) > 2:+ text = text.replace(candidate, _MACHINE_PLACEHOLDER)+ return text++def _case_parents() -> tuple[Path, ...]:"""The workspace directories a case folder sits in. Read from config ratherthan spelled out, so moving either one keeps the scrub honest."""try:- return (config.cases_dir(), config.scratch_dir())+ return (config.scratch_dir(),)except Exception:return ()diff --git a/src/azimut/engine/doctor.py b/src/azimut/engine/doctor.pynew file mode 100644index 0000000..61e05c7--- /dev/null+++ b/src/azimut/engine/doctor.py@@ -0,0 +1,274 @@+"""Read-only case diagnostics and explicit, narrowly-scoped repairs."""++from __future__ import annotations++import json+import sqlite3+import uuid+from pathlib import Path+from typing import Any, Iterator++from .. import layout+from ..sqlite_backend import SqliteCase+from ..workspace import Case, CaseError+from . import media as media_engine++DATABASE_MISSING = "database-missing"+DATABASE_UNREADABLE = "database-unreadable"+MEDIA_MISSING = "media-missing"+MEDIA_UNKNOWN = "media-unknown"+++def _media_files(case: Case) -> Iterator[Path]:+ """Visible files the media pipeline can adopt, without creating folders."""+ directory = case.media_dir+ if not directory.is_dir():+ return+ for path in sorted(directory.iterdir(), key=lambda item: item.name.casefold()):+ if path.is_file() and not path.is_symlink() and not path.name.startswith("."):+ yield path+++def _media_entities(case: Case) -> Iterator[dict[str, Any]]:+ cursor: str | None = None+ while True:+ page = case.page_entities(+ limit=500,+ cursor=cursor,+ types=["media", "capture"],+ )+ yield from page["items"]+ cursor = page.get("next_cursor")+ if cursor is None:+ return+++def _database_issue(*, unreadable: str | None = None) -> dict[str, Any]:+ if unreadable is not None:+ return {+ "id": DATABASE_UNREADABLE,+ "kind": DATABASE_UNREADABLE,+ "severity": "error",+ "title": "Case database cannot be read",+ "detail": unreadable,+ "actions": [],+ }+ return {+ "id": DATABASE_MISSING,+ "kind": DATABASE_MISSING,+ "severity": "error",+ "title": "Case database is missing",+ "detail": (+ "Azimut can rebuild media, notes and proofs from their files and sidecars."+ ),+ "losses": [+ "Relations between entities",+ "Catalog filing folders",+ "Provenance that was not stored in a sidecar",+ ],+ "actions": [{"id": "rebuild", "label": "Rebuild database", "tone": "primary"}],+ }+++def scan(case: Case) -> dict[str, Any]:+ """Inspect one case without changing its filesystem or database."""+ manifest = case.read()+ if not case.db_path.is_file():+ return _report(case, manifest, [_database_issue()])++ try:+ entities = list(_media_entities(case))+ except (CaseError, OSError, sqlite3.Error) as exc:+ return _report(case, manifest, [_database_issue(unreadable=str(exc))])++ known_paths = {+ str((entity.get("attrs") or {}).get("path"))+ for entity in entities+ if (entity.get("attrs") or {}).get("path")+ }+ unknown_paths = [+ path.relative_to(case.tool_root).as_posix()+ for path in _media_files(case)+ if path.relative_to(case.tool_root).as_posix() not in known_paths+ ]++ issues: list[dict[str, Any]] = []+ 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():+ issues.append(+ {+ "id": f"{MEDIA_MISSING}:{entity['id']}",+ "kind": MEDIA_MISSING,+ "severity": "warning",+ "state": "missing",+ "title": f"{entity.get('label') or 'Media'} is missing",+ "detail": rel_path,+ "entity_id": entity["id"],+ "path": rel_path,+ "replacements": unknown_paths,+ "actions": [+ {"id": "relink", "label": "Use replacement", "tone": "primary"},+ {"id": "drop", "label": "Remove record", "tone": "danger"},+ ],+ }+ )++ for rel_path in unknown_paths:+ issues.append(+ {+ "id": f"{MEDIA_UNKNOWN}:{rel_path}",+ "kind": MEDIA_UNKNOWN,+ "severity": "info",+ "title": f"{Path(rel_path).stem} is not imported",+ "detail": rel_path,+ "path": rel_path,+ "actions": [{"id": "import", "label": "Import file", "tone": "primary"}],+ }+ )+ return _report(case, manifest, issues)+++def _report(case: Case, manifest: dict[str, Any], issues: list[dict[str, Any]]) -> dict[str, Any]:+ return {+ "case_id": case.id,+ "case_name": manifest.get("name", case.id),+ "scratch": case.is_scratch,+ "status": "issues" if issues else "healthy",+ "summary": {+ "errors": sum(issue["severity"] == "error" for issue in issues),+ "warnings": sum(issue["severity"] == "warning" for issue in issues),+ "info": sum(issue["severity"] == "info" for issue in issues),+ },+ "issues": issues,+ }+++def _sidecar(case: Case, rel_path: str) -> dict[str, Any]:+ try:+ item = media_engine.read_item(case, rel_path)+ except (OSError, json.JSONDecodeError, CaseError):+ item = None+ return item or {}+++def _capture_attrs(source: dict[str, Any]) -> dict[str, Any]:+ keys = ("coords", "lat", "lon", "plus_code", "zoom", "bearing", "provider")+ return {key: source[key] for key in keys if source.get(key) is not None}+++def rebuild_database(case: Case) -> dict[str, Any]:+ """Rebuild only file-backed entities, then atomically install the database."""+ with case.lock:+ if case.db_path.exists():+ raise CaseError("the case database already exists")+ manifest = case.read()+ case.db_path.parent.mkdir(parents=True, exist_ok=True)+ staging = case.db_path.with_name(f".{case.db_path.name}.doctor-{uuid.uuid4().hex}.tmp")+ counts = {"media": 0, "notes": 0, "proofs": 0}+ try:+ store = SqliteCase.create(+ staging,+ name=str(manifest.get("name") or case.id),+ created_at=manifest.get("created_at"),+ updated_at=manifest.get("updated_at"),+ )+ for path in _media_files(case):+ rel_path = path.relative_to(case.tool_root).as_posix()+ previous = _sidecar(case, rel_path)+ source = previous.get("source")+ if not isinstance(source, dict):+ source = {"type": "manual", "original_name": path.name}+ digest = media_engine.sha256_file(path)+ kind = media_engine.media_kind(path.name)+ item = {+ **previous,+ "filename": path.name,+ "title": path.stem,+ "kind": kind,+ "sha256": digest,+ "size": path.stat().st_size,+ "added_at": previous.get("added_at") or manifest.get("updated_at"),+ "source": source,+ "thumbnail": previous.get("thumbnail"),+ "path": rel_path,+ }+ entity_type = "capture" if source.get("type") == "satellite" else "media"+ attrs = {"path": rel_path, "sha256": digest, "kind": kind}+ if source.get("url"):+ attrs["source_url"] = source["url"]+ if entity_type == "capture":+ attrs.update(_capture_attrs(source))+ entity = store.add_entity(+ entity_type,+ path.stem,+ attrs,+ by="case-doctor",+ source=source.get("url"),+ )+ store.upsert_media_item(item, entity_id=entity["id"])+ counts["media"] += 1++ notes = case.note_dir+ if notes.is_dir():+ for path in sorted(notes.rglob("*.md")):+ if path.is_symlink():+ continue+ rel_path = path.relative_to(case.tool_root).as_posix()+ folder = path.parent.relative_to(notes).as_posix()+ store.add_entity(+ "note",+ path.stem,+ {"path": rel_path, "folder": "" if folder == "." else folder},+ by="case-doctor",+ )+ counts["notes"] += 1++ proof_meta = case.resolve_inside(f"proofs/{layout.META_DIR}")+ if proof_meta.is_dir():+ for path in sorted(proof_meta.glob("*.json")):+ if path.is_symlink():+ continue+ try:+ spec = json.loads(path.read_text(encoding="utf-8"))+ except (OSError, json.JSONDecodeError):+ continue+ if spec.get("azimut_proof") != 1:+ continue+ attrs = {"spec": layout.proof_spec_rel(path.stem)}+ png = case.resolve_inside(layout.proof_export_rel(path.stem))+ if png.is_file():+ attrs["path"] = layout.proof_export_rel(path.stem)+ store.add_entity("proof", path.stem, attrs, by="case-doctor")+ counts["proofs"] += 1++ staging.replace(case.db_path)+ except BaseException:+ for path in (staging, Path(f"{staging}-wal"), Path(f"{staging}-shm")):+ path.unlink(missing_ok=True)+ raise+ return {"status": "rebuilt", "counts": counts}+++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"}:+ raise CaseError(f"media entity '{entity_id}' not found")+ rel_path = str((entity.get("attrs") or {}).get("path") or "")+ if not rel_path or case.resolve_inside(rel_path).is_file():+ raise CaseError(f"media entity '{entity_id}' is not missing")+ return entity+++def require_unknown_media(case: Case, rel_path: str) -> Path:+ raw_path = case.tool_root / rel_path+ path = case.resolve_inside(rel_path)+ if (+ raw_path.is_symlink()+ or path.parent.resolve() != case.media_dir.resolve()+ or not path.is_file()+ ):+ raise CaseError("the file is not an unknown media file")+ if case.find_entity(attr="path", value=rel_path) is not None:+ raise CaseError(f"media '{rel_path}' is already registered")+ return pathdiff --git a/src/azimut/engine/inspect.py b/src/azimut/engine/inspect.pyindex f9776ec..d1fa016 100644--- a/src/azimut/engine/inspect.py+++ b/src/azimut/engine/inspect.py@@ -493,7 +493,7 @@ def _apply_meta("""patch = {k: v for k, v in (("title", label), ("folder", folder), ("notes", notes)) if v}if patch:- media_engine.update_media(case, result["item"]["path"], patch)+ result["item"] = media_engine.update_media(case, result["item"]["path"], patch)def scan_focus(diff --git a/src/azimut/engine/media.py b/src/azimut/engine/media.pyindex 8512872..c5d2a7f 100644--- a/src/azimut/engine/media.py+++ b/src/azimut/engine/media.py@@ -19,8 +19,8 @@ from typing import Any, BinaryIOfrom PIL import Image-from .. import config-from ..workspace import Case, ensure_dir+from .. import config, layout+from ..workspace import Case, CaseError, ensure_dirfrom . import enrich as enrich_enginefrom . import ffmpeg as ffmpeg_enginefrom . import links as link_engine@@ -30,7 +30,6 @@ from . import thumbnails as thumbnail_engine# model and cache budgeting are owned by `thumbnails.py`. Re-exported for the# test fixtures that build a case's `.thumbs/` directly.THUMB_DIR = thumbnail_engine.THUMB_DIR-SIDECAR_SUFFIX = ".azimut.json"# Attachment collections fit under this limit. Larger collections use the# playlist path and select the first item.MAX_PICKER_ITEMS = 20@@ -73,10 +72,18 @@ def _is_gallery_auth_error(exc: BaseException) -> bool:def _resolve_cookie_file(file: str) -> Path:- """A stored cookies.txt is referenced by a workspace-relative path; an- externally supplied one may be absolute."""+ """Resolve the stored cookie filename to its protected settings location.++ Absolute paths remain supported for direct engine callers, but the Settings+ API stores only ``cookies.txt`` and that name must follow the workspace+ migration rather than resolving back to the now-empty visible root.+ """path = Path(file)- return path if path.is_absolute() else config.workspace_root() / path+ if path.is_absolute():+ return path+ if path == Path(config.cookies_file_path().name):+ return config.cookies_file_path()+ return config.workspace_root() / pathdef _cookie_ydl_opts(cookies: dict[str, Any] | None) -> dict[str, Any]:@@ -137,30 +144,26 @@ def media_kind(filename: str) -> str:return "file"-# Windows refuses these as a filename whatever the extension follows, and a case-# folder has to open on all three platforms: an item someone titles "AUX" files-# happily on Linux and then breaks the copy opened on Windows.-_WINDOWS_RESERVED = frozenset(- ["con", "prn", "aux", "nul"]- + [f"com{n}" for n in range(1, 10)]- + [f"lpt{n}" for n in range(1, 10)]-)--def safe_filename(name: str) -> str:- name = Path(name).name # strip any path component- name = re.sub(r"[^\w.\- ]+", "_", name).strip(" .") or "file"- if name.split(".", 1)[0].lower() in _WINDOWS_RESERVED:- name = f"_{name}"- return name[:150]+ """Safe imported filename whose stem is also its visible Azimut name."""+ leaf = Path(name).name+ return layout.visible_filename(Path(leaf).stem, Path(leaf).suffix)++def unique_path(directory: Path, filename: str, *, taken_by: Path | None = None) -> Path:+ """Return a case-insensitively non-colliding path in ``directory``.-def unique_path(directory: Path, filename: str) -> Path:- """Return a non-colliding path in directory for filename."""+ Linux would allow ``Clip.mp4`` beside ``clip.mp4``; Windows and the default+ macOS filesystem would merge them. Cases travel between all three, so the+ stricter rule is the portable one. ``taken_by`` is the file being renamed.+ """stem, suffix = Path(filename).stem, Path(filename).suffix+ occupied = {+ path.name.casefold() for path in directory.iterdir() if taken_by is None or path != taken_by+ }candidate = directory / filenamecounter = 1- while candidate.exists():+ while candidate.name.casefold() in occupied:candidate = directory / f"{stem}-{counter}{suffix}"counter += 1return candidate@@ -171,7 +174,7 @@ def ffmpeg_available() -> bool:def _sidecar_path(media_path: Path) -> Path:- return media_path.with_name(media_path.name + SIDECAR_SUFFIX)+ return media_path.parent / layout.META_DIR / (media_path.name + ".json")#: Prefix and suffix of the scratch file a sidecar write goes through. Named so@@ -185,6 +188,7 @@ SIDECAR_TMP_SUFFIX = ".tmp"def _write_sidecar(media_path: Path, data: dict[str, Any]) -> None:sidecar = _sidecar_path(media_path)+ ensure_dir(sidecar.parent)temporary = sidecar.with_name(f"{SIDECAR_TMP_PREFIX}{sidecar.name}.{uuid.uuid4().hex}{SIDECAR_TMP_SUFFIX}")@@ -229,8 +233,8 @@ def _register(output). ``entity_type`` lets a producer file the item under a more specifictype than the generic ``media`` (e.g. a satellite ``capture``) while it stilllives in ``media/`` and shows up in the Media Library; ``extra_attrs`` are- merged onto that entity (coordinates, zoom, …) and ``title`` seeds the display- label/sidecar title. ``dedupe=False`` keeps every registration a distinct+ merged onto that entity (coordinates, zoom, …) and ``title`` chooses the+ canonical filename before registration. ``dedupe=False`` keeps every registration a distinctitem even when the bytes match an existing one — satellite captures are 1:1with their entity (spec §3.5), so re-capturing the same view is two captures."""@@ -245,7 +249,11 @@ def _register(link_engine.link_all(case, existing["id"], link_engine.DERIVED_FROM, _source_paths(source), by=by)- return {"duplicate": True, "entity": existing, "item": read_item(case, existing["attrs"]["path"])}+ return {+ "duplicate": True,+ "entity": existing,+ "item": read_item(case, existing["attrs"]["path"]),+ }rel_path = f"media/{media_path.name}"kind = media_kind(media_path.name)@@ -254,8 +262,10 @@ def _register(# fills the sidecar in later via `set_thumbnail`.thumb_rel = thumbnail_engine.on_register(case, rel_path, digest, kind)+ display_name = media_path.stemsidecar = {"filename": media_path.name,+ "title": display_name,"kind": kind,"sha256": digest,"size": media_path.stat().st_size,@@ -263,13 +273,11 @@ def _register("source": source,"thumbnail": thumb_rel,}- if title:- sidecar["title"] = title_write_sidecar(media_path, sidecar)entity = case.add_entity(entity_type,- title or media_path.name,+ display_name,attrs={"path": rel_path,"sha256": digest,@@ -287,9 +295,7 @@ def _register(enrich_engine.on_register(case, rel_path, kind, entity["id"])# Every media derivative is filed through here, so the derivation chain is# wired once for every tool that produces imagery — present and future.- link_engine.link_all(- case, entity["id"], link_engine.DERIVED_FROM, _source_paths(source), by=by- )+ link_engine.link_all(case, entity["id"], link_engine.DERIVED_FROM, _source_paths(source), by=by)return {"duplicate": False, "entity": entity, "item": indexed}@@ -302,6 +308,109 @@ def import_stream(case: Case, filename: str, stream: BinaryIO) -> dict[str, Any]return _register(case, dest, {"type": "upload", "original_name": filename})+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.++ The Doctor calls this only after showing the file as unknown and receiving+ an explicit import action. Keeping the registration in the regular media+ chokepoint gives the adopted file the same hash, sidecar, thumbnail,+ enrichment and provenance as an upload.+ """+ raw_path = case.tool_root / rel_path+ media_path = case.resolve_inside(rel_path)+ if (+ raw_path.is_symlink()+ or media_path.parent.resolve() != case.media_dir.resolve()+ or not media_path.is_file()+ ):+ raise CaseError("the file must be directly inside this case's media folder")+ if case.find_entity(attr="path", value=rel_path) is not None:+ raise CaseError(f"media '{rel_path}' is already registered")+ return _register(+ case,+ media_path,+ {"type": "manual", "original_name": media_path.name},+ by=by,+ )+++def relink_existing(+ case: Case,+ entity_id: str,+ rel_path: str,+) -> dict[str, Any]:+ """Point a missing media entity at an unregistered replacement file.++ The entity and its relations survive. Only an existing file directly under+ ``media/`` is accepted, so the browser cannot turn this repair into an+ arbitrary filesystem read.+ """+ with case.lock:+ entity = case.get_entity(entity_id)+ if entity is None or entity.get("type") not in {"media", "capture"}:+ raise CaseError(f"media entity '{entity_id}' not found")+ old_rel = str((entity.get("attrs") or {}).get("path") or "")+ if not old_rel:+ raise CaseError(f"media entity '{entity_id}' has no path")+ if case.resolve_inside(old_rel).is_file():+ raise CaseError(f"media '{old_rel}' is not missing")++ raw_path = case.tool_root / rel_path+ media_path = case.resolve_inside(rel_path)+ if (+ raw_path.is_symlink()+ or media_path.parent.resolve() != case.media_dir.resolve()+ or not media_path.is_file()+ ):+ raise CaseError("the replacement must be directly inside this case's media folder")+ claimed = case.find_entity(attr="path", value=rel_path)+ if claimed is not None and claimed.get("id") != entity_id:+ raise CaseError(f"media '{rel_path}' is already registered")++ replacement_item = read_item(case, rel_path)+ old_item = read_item(case, old_rel)+ previous = replacement_item or old_item or {}+ source = previous.get("source")+ if not isinstance(source, dict):+ source = {"type": "manual", "original_name": media_path.name}++ digest = sha256_file(media_path)+ kind = media_kind(media_path.name)+ thumbnail = previous.get("thumbnail")+ if not thumbnail or not case.resolve_inside(str(thumbnail)).is_file():+ thumbnail = thumbnail_engine.on_register(case, rel_path, digest, kind)+ sidecar = {+ **previous,+ "filename": media_path.name,+ "title": media_path.stem,+ "kind": kind,+ "sha256": digest,+ "size": media_path.stat().st_size,+ "added_at": previous.get("added_at") or _now(),+ "source": source,+ "thumbnail": thumbnail,+ }+ sidecar.pop("path", None)+ _write_sidecar(media_path, sidecar)++ case.replace_path_references(old_rel, rel_path)+ updated = case.update_entity(+ entity_id,+ {+ "label": media_path.stem,+ "attrs": {"path": rel_path, "sha256": digest, "kind": kind},+ },+ )+ case.remove_media_item(old_rel)+ indexed = {**sidecar, "path": rel_path}+ case.upsert_media_item(indexed, entity_id=entity_id)+ old_sidecar = _sidecar_path(case.resolve_inside(old_rel))+ if old_sidecar != _sidecar_path(media_path):+ old_sidecar.unlink(missing_ok=True)+ enrich_engine.on_register(case, rel_path, kind, entity_id)+ return {"entity": updated, "item": indexed}++def import_image(case: Case,image: Image.Image,@@ -324,16 +433,24 @@ def import_image(carrying its coordinates while still landing in ``media/``."""media_dir = case.subdir("media")- name = safe_filename(filename)- if not name.lower().endswith(".png"):- name = f"{Path(name).stem}.png"+ name = (+ layout.visible_filename(title, ".png")+ if title+ else layout.visible_filename(Path(safe_filename(filename)).stem, ".png")+ )dest = unique_path(media_dir, name)# Preserve an alpha channel (e.g. a transparent collage canvas); everything# else is flattened to RGB. The thumbnail stage composites alpha over black.image.save(dest, "PNG") if image.mode == "RGBA" else image.convert("RGB").save(dest, "PNG")return _register(- case, dest, source, by=by, entity_type=entity_type,- extra_attrs=extra_attrs, title=title, dedupe=dedupe,+ case,+ dest,+ source,+ by=by,+ entity_type=entity_type,+ extra_attrs=extra_attrs,+ title=title,+ dedupe=dedupe,)@@ -383,10 +500,16 @@ def _register_downloaded_item(and apply the display title — same bookkeeping ``download_url`` does forits own yt-dlp path, minus the yt-dlp-specific extraction bits."""media_dir = case.subdir("media")- tmp_dir = media_dir / ".dl" / uuid.uuid4().hex+ tmp_dir = media_dir / ".dl" / uuid.uuid4().hex[: layout.DOWNLOAD_ID_LENGTH]ensure_dir(tmp_dir)+ display_title = (title or "").strip() or source_extra.get("title")try:- fname = safe_filename(filename)+ original = safe_filename(filename)+ fname = (+ layout.visible_filename(str(display_title), Path(original).suffix)+ if display_title+ else original+ )tmp_path = tmp_dir / fnametmp_path.write_bytes(content)dest = unique_path(media_dir, fname)@@ -396,9 +519,6 @@ def _register_downloaded_item(source = {"type": "download", "url": post_url, "webpage_url": post_url, **source_extra}result = _register(case, dest, source)- display_title = (title or "").strip() or source_extra.get("title")- if not result["duplicate"] and display_title:- result["item"] = update_media(case, result["item"]["path"], {"title": display_title})result["multi"] = Falsereturn result@@ -418,7 +538,9 @@ def _gallery_dl_item(file_url: str, kwdict: dict[str, Any]) -> dict[str, Any]:"title": first_line or filename,"description": content or None,"uploader": author.get("nick") or author.get("name"),- "upload_date": date.strftime("%Y%m%d") if date is not None and hasattr(date, "strftime") else None,+ "upload_date": date.strftime("%Y%m%d")+ if date is not None and hasattr(date, "strftime")+ else None,}@@ -521,7 +643,9 @@ def _register_telegram_photo(resp = requests.get(photo["url"], headers={"User-Agent": "Mozilla/5.0"}, timeout=30)resp.raise_for_status()- ext = mimetypes.guess_extension((resp.headers.get("content-type") or "").split(";")[0]) or ".jpg"+ ext = (+ mimetypes.guess_extension((resp.headers.get("content-type") or "").split(";")[0]) or ".jpg"+ )return _register_downloaded_item(case,post_url,@@ -598,7 +722,7 @@ def download_url(# a unique subdir per call — concurrent downloads (the multi-item picker# fires one per selected item) must not share a scratch dir, or the first# one to finish rmtree()s it out from under the others still writing to it- tmp_dir = media_dir / ".dl" / uuid.uuid4().hex+ tmp_dir = media_dir / ".dl" / uuid.uuid4().hex[: layout.DOWNLOAD_ID_LENGTH]ensure_dir(tmp_dir)extra_photos = _telegram_extra_photos(url) # [] — and free — for non-Telegram links@@ -675,7 +799,12 @@ def download_url(else:yt_items = []photo_items = [- {"index": yt_count + i, "title": "Telegram photo", "thumbnail": p["url"], "kind": "image"}+ {+ "index": yt_count + i,+ "title": "Telegram photo",+ "thumbnail": p["url"],+ "kind": "image",+ }for i, p in enumerate(extra_photos, start=1)]return {"multi": True, "items": yt_items + photo_items}@@ -703,11 +832,18 @@ def download_url(raise RuntimeError("yt-dlp reported success but no file was produced")downloaded = candidates[-1]- dest = unique_path(media_dir, safe_filename(downloaded.name))+ extracted_title = info.get("title")+ display_title = (title or "").strip() or extracted_title+ original = safe_filename(downloaded.name)+ filename = (+ layout.visible_filename(str(display_title), Path(original).suffix)+ if display_title+ else original+ )+ dest = unique_path(media_dir, filename)shutil.move(str(downloaded), str(dest))shutil.rmtree(tmp_dir, ignore_errors=True)- extracted_title = info.get("title")source = {"type": "download","url": url,@@ -721,14 +857,201 @@ def download_url("duration": info.get("duration"),}result = _register(case, dest, source)-- display_title = (title or "").strip() or extracted_title- if not result["duplicate"] and display_title:- result["item"] = update_media(case, result["item"]["path"], {"title": display_title})result["multi"] = Falsereturn result+def _replace_exact(value: Any, old: str, new: str) -> Any:+ """Recursively replace strings equal to ``old``; never edit prose."""+ if isinstance(value, str):+ return new if value == old else value+ if isinstance(value, list):+ return [_replace_exact(item, old, new) for item in value]+ if isinstance(value, dict):+ return {key: _replace_exact(item, old, new) for key, item in value.items()}+ return value+++def write_json_atomic(path: Path, data: dict[str, Any]) -> None:+ ensure_dir(path.parent)+ temporary = path.with_name(f".{path.name}.{uuid.uuid4().hex}.tmp")+ try:+ temporary.write_text(+ json.dumps(data, indent=2, ensure_ascii=False) + "\n",+ encoding="utf-8",+ )+ temporary.replace(path)+ finally:+ temporary.unlink(missing_ok=True)+++def rename_path(source: Path, destination: Path) -> None:+ """Rename one file, including a case-only rename on Windows/macOS."""+ if source == destination:+ return+ ensure_dir(destination.parent)+ if (+ source.name.casefold() == destination.name.casefold()+ and source.parent == destination.parent+ ):+ temporary = source.with_name(f".azimut-rename-{uuid.uuid4().hex}.tmp")+ source.rename(temporary)+ try:+ temporary.rename(destination)+ except Exception:+ temporary.rename(source)+ raise+ return+ if destination.exists():+ raise CaseError(f"a file named '{destination.name}' already exists")+ source.rename(destination)+++def _rename_journal(case: Case) -> Path:+ return case.resolve_inside(f"{layout.DATA_DIR}/rename.json")+++def _structured_record_paths(case: Case) -> list[Path]:+ tool = case.tool_root+ roots = (+ layout.subdir(case.path, "proofs") / layout.META_DIR,+ tool / layout.INSPECT_DIR,+ tool / layout.DRAFTS_DIR,+ tool / layout.SEARCH_DIR,+ )+ return [path for root in roots if root.is_dir() for path in sorted(root.glob("*.json"))]+++def rewrite_file_references(case: Case, old: str, new: str) -> None:+ """Rewrite exact paths in sidecars and tool specs after a media move."""+ media_dir = case.subdir("media")+ sidecars = media_dir / layout.META_DIR+ if sidecars.is_dir():+ for sidecar in sorted(sidecars.glob("*.json")):+ try:+ data = json.loads(sidecar.read_text(encoding="utf-8"))+ except (OSError, json.JSONDecodeError):+ continue+ replaced = _replace_exact(data, old, new)+ if replaced == data:+ continue+ write_json_atomic(sidecar, replaced)+ media_name = sidecar.name.removesuffix(".json")+ entity = case.find_entity(attr="path", value=f"media/{media_name}")+ case.upsert_media_item(+ {**replaced, "path": f"media/{media_name}"},+ entity_id=entity["id"] if entity else None,+ )++ for path in _structured_record_paths(case):+ try:+ data = json.loads(path.read_text(encoding="utf-8"))+ except (OSError, json.JSONDecodeError):+ continue+ replaced = _replace_exact(data, old, new)+ if replaced != data:+ write_json_atomic(path, replaced)+++def _finish_media_rename(case: Case, record: dict[str, str]) -> dict[str, Any]:+ """Complete one journalled media rename. Safe to call repeatedly."""+ old = record["old"]+ new = record["new"]+ title = record["title"]+ old_path = case.resolve_inside(old)+ new_path = case.resolve_inside(new)+ old_sidecar = _sidecar_path(old_path)+ new_sidecar = _sidecar_path(new_path)++ if old != new:+ if old_path.exists():+ rename_path(old_path, new_path)+ elif not new_path.exists():+ raise CaseError(f"media rename lost both '{old}' and '{new}'")+ if old_sidecar.exists():+ rename_path(old_sidecar, new_sidecar)+ elif not new_sidecar.exists():+ raise CaseError(f"media rename lost the sidecar for '{old}'")++ if not new_path.exists() or not new_sidecar.exists():+ raise CaseError(f"media rename is incomplete for '{new}'")++ data = json.loads(new_sidecar.read_text(encoding="utf-8"))+ data["filename"] = new_path.name+ data["title"] = title+ _write_sidecar(new_path, data)++ owner = case.find_entity(attr="path", value=old) or case.find_entity(attr="path", value=new)+ owner_id = owner["id"] if owner else None+ case.remove_media_item(old)+ case.replace_path_references(old, new)+ if owner_id:+ case.update_entity(owner_id, {"label": title})+ indexed = {**data, "path": new}+ case.upsert_media_item(indexed, entity_id=owner_id)+ rewrite_file_references(case, old, new)+ _rename_journal(case).unlink(missing_ok=True)+ return indexed+++def recover_media_rename(case: Case) -> None:+ """Finish a rename interrupted between filesystem and database updates."""+ journal = _rename_journal(case)+ if not journal.exists():+ return+ try:+ record = json.loads(journal.read_text(encoding="utf-8"))+ except (OSError, json.JSONDecodeError) as exc:+ raise CaseError("the media rename journal is unreadable") from exc+ if not all(isinstance(record.get(key), str) for key in ("old", "new", "title")):+ raise CaseError("the media rename journal is invalid")+ _finish_media_rename(case, record)+++#: How long a rename waits for the background worker to put the file down.+#:+#: The wait itself is required: a thumbnail or enrichment job holds the media+#: open, and Windows cannot move a file another handle has open. What the number+#: has to cover is a slow machine — `wait_until_idle`'s own default is 5 seconds,+#: which is right for the shutdown it was written for and too short here. An+#: import queues enrichment, and the Save gate names the item it just filed, so+#: the two meet on every single save; 5 seconds turned that into "try the rename+#: again" on a name the analyst had already committed to, and the same+#: contention surfaced as a locked database in the write that followed. Matches+#: the workspace move's settle step, which waits for the worker for the same+#: reason.+RENAME_SETTLE_SECONDS = 30.0+++def rename_media(+ case: Case,+ rel_path: str,+ requested_title: str | None,+ *,+ settle_worker: bool = True,+) -> dict[str, Any]:+ """Rename a media file and every stored reference to its canonical stem."""+ from . import workqueue++ if settle_worker and not workqueue.wait_until_idle(timeout=RENAME_SETTLE_SECONDS):+ raise CaseError("background media work is still running; try the rename again")+ with case.lock:+ recover_media_rename(case)+ media_path = case.resolve_inside(rel_path)+ if not media_path.exists():+ raise ValueError(f"no media found for {rel_path!r}")+ requested = (requested_title or "").strip() or media_path.stem+ filename = layout.visible_filename(requested, media_path.suffix)+ destination = unique_path(media_path.parent, filename, taken_by=media_path)+ record = {+ "old": rel_path,+ "new": f"media/{destination.name}",+ "title": destination.stem,+ }+ write_json_atomic(_rename_journal(case), record)+ return _finish_media_rename(case, record)++def merge_item(case: Case, rel_path: str, patch: dict[str, Any]) -> dict[str, Any] | None:"""Merge ``patch`` into a media item's sidecar and mirror it onto the indexrow. Returns the merged item, or None when the sidecar is gone.@@ -773,8 +1096,7 @@ def list_media(case: Case) -> list[dict[str, Any]]:def update_media(case: Case, rel_path: str, patch: dict[str, Any]) -> dict[str, Any]:- """Update mutable sidecar fields (notes, folder, title) and mirror them onto- the media entity so the case sidebar stays in sync.+ """Update mutable sidecar fields and mirror them onto the media entity.Under the case lock, like every other sidecar write: the Save gate names anitem immediately after filing it, while the enrichment job queued by that@@ -782,14 +1104,22 @@ def update_media(case: Case, rel_path: str, patch: dict[str, Any]) -> dict[str,Unguarded, whichever finished second dropped the other's fields — and the oneusers noticed was the name they had just typed."""+ if "title" in patch:+ renamed = rename_media(case, rel_path, patch["title"])+ rel_path = renamed["path"]+ patch = {key: value for key, value in patch.items() if key != "title"}+ if not patch:+ return renamed+with case.lock:+ recover_media_rename(case)media_path = case.resolve_inside(rel_path)sidecar = _sidecar_path(media_path)if not sidecar.exists():raise ValueError(f"no sidecar found for {rel_path!r}")data = json.loads(sidecar.read_text(encoding="utf-8"))- for key in ("notes", "folder", "title"):+ for key in ("notes", "folder"):if key in patch:val = patch[key]if val is None or val == "":@@ -803,10 +1133,6 @@ def update_media(case: Case, rel_path: str, patch: dict[str, Any]) -> dict[str,entity = case.find_entity(attr="path", value=rel_path)if entity:entity_patch: dict[str, Any] = {}- if "title" in patch:- # a cleared title falls back to the filename, like a fresh import —- # the sidebar label must never freeze on a title that no longer exists- entity_patch["label"] = str(patch["title"] or "") or media_path.nameattrs: dict[str, Any] = {}if "folder" in patch:attrs["folder"] = patch["folder"] or ""diff --git a/src/azimut/engine/reveal.py b/src/azimut/engine/reveal.pynew file mode 100644index 0000000..8b91c21--- /dev/null+++ b/src/azimut/engine/reveal.py@@ -0,0 +1,82 @@+"""Show a folder in the system's own file manager.++Azimut is a local server plus a browser tab, and a browser cannot open a file+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.+"""++from __future__ import annotations++import os+import subprocess+import sys+from pathlib import Path++from .. import config+++class RevealError(Exception):+ """The folder can't be shown, with a reason fit to put in front of a user."""+++def _has_desktop_session() -> bool:+ """Whether this Linux/BSD process has a graphical session to open into.++ Azimut over SSH or as a service has none, and `xdg-open` there fails quietly.+ Windows and macOS always have one, so this is only asked of the rest.+ """+ return bool(os.environ.get("DISPLAY") or os.environ.get("WAYLAND_DISPLAY"))+++def _within_workspace(target: Path) -> bool:+ try:+ target.relative_to(config.workspace_root().expanduser().resolve())+ except ValueError:+ return False+ return True+++def reveal(path: Path) -> None:+ """Open ``path`` in Explorer, Finder or the Linux desktop's file manager.++ Raises :class:`RevealError` for a folder outside the workspace, a folder that+ isn't there, or a Linux box with no ``xdg-open`` — a headless server being the+ one place this genuinely cannot work.+ """+ target = Path(path).expanduser().resolve()+ if not _within_workspace(target):+ raise RevealError("that folder is outside the workspace")+ if not target.is_dir():+ raise RevealError("that folder no longer exists")++ if sys.platform == "win32":+ try:+ # The stdlib shell-open: no command line is built, so a folder name+ # holding spaces or an ampersand needs no quoting.+ os.startfile(target)+ except OSError as exc:+ raise RevealError(f"Windows could not open that folder ({exc})") from None+ return++ if sys.platform != "darwin" and not _has_desktop_session():+ # xdg-open on a headless box exits without opening anything, and with+ # stderr silenced the UI would report success that never happened.+ raise RevealError("no desktop session to open a file manager in")++ opener = "open" if sys.platform == "darwin" else "xdg-open"+ try:+ # A fixed argv, never a shell. Detached and silenced: the file manager+ # outlives the request, and its chatter goes nowhere anyone reads.+ subprocess.Popen(+ [opener, str(target)],+ stdout=subprocess.DEVNULL,+ stderr=subprocess.DEVNULL,+ start_new_session=True,+ )+ except FileNotFoundError:+ raise RevealError(f"no file manager found ({opener} is missing)") from Nonediff --git a/src/azimut/engine/satellite.py b/src/azimut/engine/satellite.pyindex 70f9523..766ca33 100644--- a/src/azimut/engine/satellite.py+++ b/src/azimut/engine/satellite.py@@ -29,6 +29,7 @@ from . import countriesfrom . import geo as geo_enginefrom . import linksfrom . import media as media_engine+from .. import layout# Saved work is places plus captures; a screenshot filed by the capture# extension is a capture with a different origin, not a third entity type.@@ -341,7 +342,7 @@ def _linked_posts(draft = draft or {}draft_name = draft.get("name")if not draft_name and isinstance(draft_path, str):- draft_name = draft_path.removeprefix("exports/").removesuffix(".json")+ draft_name = draft_path.removeprefix(layout.DRAFTS_DIR + "/").removesuffix(".json")linked.append({"id": entity["id"],@@ -423,7 +424,7 @@ def proof_index(}post_entities = {entity["id"]: entity for entity in _page_all(case, ["post"])}drafts = {- f"exports/{draft['name']}.json": draft for draft in (draft_listing or [])+ layout.draft_rel(draft["name"]): draft for draft in (draft_listing or [])}rows: list[dict[str, Any]] = []for proof in listing:diff --git a/src/azimut/engine/scrapers.py b/src/azimut/engine/scrapers.pyindex f4e4d50..2223725 100644--- a/src/azimut/engine/scrapers.py+++ b/src/azimut/engine/scrapers.py@@ -10,7 +10,7 @@ the read-only PyInstaller archive.So Azimut fetches newer copies into the workspace (config.runtime_dir()) andprefers them over whatever is bundled:- ~/Azimut/runtime/+ ~/Azimut/.azimut/runtime/├── yt-dlp/ # one directory per distribution, so an│ ├── yt_dlp/ # update is a whole-directory swap and a│ └── yt_dlp-2026.7.4.dist-info/ # half-written one can't shadow anythingdiff --git a/src/azimut/engine/thumbnails.py b/src/azimut/engine/thumbnails.pyindex fb10e13..613a097 100644--- a/src/azimut/engine/thumbnails.py+++ b/src/azimut/engine/thumbnails.py@@ -35,6 +35,7 @@ from PIL import Imagefrom ..workspace import ensure_dirfrom . import ffmpeg as ffmpeg_enginefrom . import workqueue+from .. import layoutif TYPE_CHECKING:from ..workspace import Case as CaseType@@ -211,7 +212,7 @@ def _proof_thumbs(case: "CaseType") -> set[str]:their exports share this cache, so the sweep below has to count them asreferenced or it would delete every one of them."""names = set()- for spec_path in case.subdir("proofs").glob("*.json"):+ for spec_path in case.subdir("proofs").joinpath(layout.META_DIR).glob("*.json"):try:spec = json.loads(spec_path.read_text(encoding="utf-8"))except (OSError, json.JSONDecodeError):diff --git a/src/azimut/engine/tilecache.py b/src/azimut/engine/tilecache.pyindex e10b1a0..58b9269 100644--- a/src/azimut/engine/tilecache.py+++ b/src/azimut/engine/tilecache.py@@ -1,6 +1,6 @@"""Disk tile cache for providers whose terms allow it (docs/IMAGERY_PROVIDERS.md).-Layout: ``<workspace>/tile-cache/<provider_id>/<z>/<x>_<y>.<ext>`` — plain+Layout: ``<workspace>/.azimut/cache/tiles/<provider_id>/<z>/<x>_<y>.<ext>`` — plainfiles, rebuildable, safe to delete wholesale. Only providers with``cacheable=True`` land here: Google is excluded by its Map Tiles API terms(encoded as ``cacheable=False`` on the provider, enforced by the callers).@@ -23,7 +23,7 @@ _TYPE = {ext: media for media, ext in _EXT.items()}def _tile_dir(provider_id: str, z: int) -> Path:- return config.workspace_root() / "tile-cache" / provider_id / str(int(z))+ return config.tile_cache_dir() / provider_id / str(int(z))def get(provider_id: str, z: int, x: int, y: int) -> tuple[bytes, str] | None:diff --git a/src/azimut/engine/trash.py b/src/azimut/engine/trash.pyindex 16d11f7..1b1410d 100644--- a/src/azimut/engine/trash.py+++ b/src/azimut/engine/trash.py@@ -2,10 +2,17 @@The live graph keeps hard-deleting. What a delete leaves behind is a journalrow holding the recipe to undo it, and the files moved aside into-``.trash/<group_id>/`` under their original case-relative names. Nothing else-in the app learns that a trash exists — no catalog query, no search, no picker,-no future tool has to remember to filter out deleted rows. That is the whole-reason a journal was chosen over a ``trashed`` status.+``.trash/<group_id>/`` under numbered slots. Nothing else in the app learns that+a trash exists — no catalog query, no search, no picker, no future tool has to+remember to filter out deleted rows. That is the whole reason a journal was+chosen over a ``trashed`` status.++**Slots, not mirrored paths.** The group directory used to reproduce each+artifact's case-relative path under itself, which stacked two case trees on top+of each other and made the trash the longest path the app could produce — enough+to break the 260-character Windows limit on its own. The journal already records+where every file came from, so the directory holds ``0``, ``1``, ``2`` and the+payload's ``slots`` list says which is which.One row is one **delete action**, not one entity: deleting a video that carriesthree Inspect sessions writes a single group, and restoring it brings the whole@@ -23,6 +30,7 @@ import shutilfrom pathlib import Pathfrom typing import Any+from .. import layoutfrom ..workspace import Case, CaseError, _new_id, ensure_dirfrom . import artifacts as artifact_enginefrom . import links as link_engine@@ -37,9 +45,29 @@ def _group_dir(case: Case, group_id: str) -> Path:"""if not group_id or "/" in group_id or "\\" in group_id or group_id.startswith("."):raise CaseError(f"invalid trash group '{group_id}'")- from ..workspace import TRASH_DIR+ return case.resolve_inside(f"{layout.TRASH_DIR}/{group_id}")- return case.resolve_inside(f"{TRASH_DIR}/{group_id}")++def slots_for(files: list[str]) -> list[str]:+ """The in-group name each file waits under. Positional, so the payload's+ ``files`` and ``slots`` lists line up index for index."""+ return [str(index) for index, _ in enumerate(files)]+++def _moved(payload: dict[str, Any]) -> list[tuple[str, str]]:+ """(case-relative path, slot) pairs for one group.++ A group written before the slots existed is not readable here — the schema-4+ migration flattens every one of them on open, so a payload without ``slots``+ means the migration did not run and silence would restore nothing.+ """+ files: list[str] = list(payload.get("files") or [])+ if not files:+ return []+ slots: list[str] = list(payload.get("slots") or [])+ if len(slots) != len(files):+ raise CaseError("trash group predates numbered slots and was not migrated")+ return list(zip(files, slots))def _dir_size(path: Path) -> int:@@ -106,6 +134,7 @@ def send("entities": entities,"links": links,"files": files,+ "slots": slots_for(files),"tombstones": tombstones,}group = case.add_trash_group(@@ -120,10 +149,11 @@ def send(try:for entity in entities:artifact_engine.unfile(case, entity)- for rel in files:+ for rel, slot in _moved(payload):source = case.resolve_inside(rel)if source.exists():- _move(source, root / rel)+ _move(source, root / slot)+ case.prune_note_dirs(rel)return case.update_trash_group(group_id, size_bytes=_dir_size(root))except Exception:_rollback_delete(case, group)@@ -166,10 +196,9 @@ def restore(case: Case, group_id: str) -> dict[str, Any]:raise CaseError(f"trash group '{group_id}' not found")payload = group.get("payload") or {}root = _group_dir(case, group_id)- files: list[str] = list(payload.get("files") or [])occupied = [- rel for rel in files- if (root / rel).exists() and case.resolve_inside(rel).exists()+ rel for rel, slot in _moved(payload)+ if (root / slot).exists() and case.resolve_inside(rel).exists()]if occupied:raise CaseError(@@ -222,8 +251,8 @@ def recover(case: Case) -> None:def _restore_files(case: Case, group: dict[str, Any]) -> None:payload = group.get("payload") or {}root = _group_dir(case, group["id"])- for rel in payload.get("files") or []:- source = root / rel+ for rel, slot in _moved(payload):+ source = root / slotdestination = case.resolve_inside(rel)if source.exists():_move(source, destination)diff --git a/src/azimut/engine/updates.py b/src/azimut/engine/updates.pyindex 5a545eb..c37fae0 100644--- a/src/azimut/engine/updates.py+++ b/src/azimut/engine/updates.py@@ -23,6 +23,19 @@ RELEASES_PAGE_URL = "https://github.com/OsintMeThat/azimut/releases/latest"NOTES_LIMIT = 4000+def _clip(notes: str) -> str:+ """Cap the release body so a runaway note never bloats the response.++ Cutting mid-line would leave the pop-up rendering half a heading or an+ unclosed code fence, so an over-long note is trimmed back to its last+ complete line."""+ if len(notes) <= NOTES_LIMIT:+ return notes+ clipped = notes[:NOTES_LIMIT]+ head, newline, _ = clipped.rpartition("\n")+ return (head if newline else clipped).rstrip()++def _parse(version: str) -> tuple[int, ...]:"""A tag like ``v0.1.2`` (or a bare ``0.1.2``) as a comparable tuple.@@ -71,7 +84,7 @@ def check(current: str, *, timeout: float = 6.0) -> dict[str, object]:if body.get("html_url"):result["url"] = str(body["html_url"])# The release body, shown in the startup pop-up. Markdown from our own- # releases; the UI renders it as plain text (no HTML injection), so we- # just cap the length to keep the payload sane.- result["notes"] = str(body.get("body") or "").strip()[:NOTES_LIMIT]+ # releases, rendered by the UI through the same sanitizing renderer as+ # the Notebook.+ result["notes"] = _clip(str(body.get("body") or "").strip())return resultdiff --git a/src/azimut/engine/workqueue.py b/src/azimut/engine/workqueue.pyindex b4d92b3..e2434a6 100644--- a/src/azimut/engine/workqueue.py+++ b/src/azimut/engine/workqueue.py@@ -151,6 +151,26 @@ def wake(case: "CaseType") -> None:threading.Thread(target=_run_loop, name="azimut-worker", daemon=True).start()+def recover_all() -> None:+ """Return jobs a crashed process left ``running`` to the queue, and wake the+ worker for every case that still has pending work.++ A `running` row nothing owns would otherwise stall forever. Called at+ startup, and again whenever the workspace root changes: the cases at a new+ location have their own queues, and this process has never seen them.+ """+ from ..workspace import Case++ for row in Case.list_all():+ try:+ case = Case.open(row["id"])+ case.recover_jobs()+ except Exception: # one unreadable case must not stall every other queue+ continue+ if has_queued(case):+ wake(case)++def wait_until_idle(timeout: float = 5.0) -> bool:"""Wait for the shared worker to finish its current queue, if any.diff --git a/src/azimut/engine/workspacelock.py b/src/azimut/engine/workspacelock.pynew file mode 100644index 0000000..816acf3--- /dev/null+++ b/src/azimut/engine/workspacelock.py@@ -0,0 +1,395 @@+"""One Azimut per workspace, across processes.++Until the workspace could move, two instances were unlikely and mostly harmless:+the second one failed to bind port 8477 and died. That protects the *port*, not+the workspace — `azimut --port 8478` never noticed, and neither did two machines+opening one folder on a network or cloud-synced share, which is exactly what+letting people choose the folder makes common.++What actually breaks with two instances is not SQLite. Its own file locking plus+`busy_timeout` holds up on a local disk, and jobs are claimed in a transaction.+It is everything around it: `settings.json` is read-modify-written under an+*in-process* lock, so the second instance silently drops an API key or a usage+counter; startup migrations rename directories, and two of those racing is how a+case gets half-moved; and a workspace move copies a tree the other instance is+still writing into.++## How the lock works, and where it doesn't++The real mechanism is an advisory lock the operating system holds on an open+file: `fcntl.flock` on Linux and macOS, `msvcrt.locking` on Windows. What makes+it the right primitive is not that it excludes — it is that **the OS drops it+when the process dies**. A crashed Azimut can never leave a workspace bolted+shut, which is the failure mode a hand-rolled lock file always ends up having.++That lock is reliable on a local filesystem and unreliable on exactly the+filesystem this feature exists for: NFS, SMB and cloud-sync folders may honour+it partially, or not at all. So the file also carries a small payload — who,+where, since when — with a heartbeat, and the two are read together:++* the lock was refused → someone holds it, name them from the payload;+* the lock was granted and the payload names another host with a beating heart →+ the lock was probably a no-op on this filesystem, so believe the payload;+* the lock was granted and the heartbeat has stopped → take it over;+* the lock was granted and the payload names this host → a previous run of ours+ crashed, and the OS just proved nobody holds it. Take it over.++Clock skew between two machines is real and unfixable from here, which is why+`take_over()` exists: the analyst can always overrule this, and that escape+hatch is what keeps a bad verdict from bricking a workspace.+"""++from __future__ import annotations++import json+import logging+import os+import socket+import threading+from dataclasses import dataclass+from datetime import datetime, timezone+from pathlib import Path+from typing import Any++from .. import __version__, config++logger = logging.getLogger(__name__)++#: The lock file, in the workspace it locks. Two workspaces are two locks, which+#: is what lets someone run a work instance and a personal one side by side.+LOCK_NAME = "lock"++#: How often the holder rewrites its timestamp. Short enough that a stale lock+#: clears in minutes, long enough to be nothing on a synced folder.+HEARTBEAT_SECONDS = 30.0++#: A heartbeat older than this, from another machine, is treated as gone. Sync+#: clients can take minutes to propagate a small file, so this is deliberately+#: several heartbeats rather than two.+STALE_AFTER_SECONDS = 300.0+++class WorkspaceBusy(Exception):+ """Another Azimut holds this workspace."""++ def __init__(self, holder: dict[str, Any]):+ self.holder = holder+ super().__init__(describe(holder))+++def describe(holder: dict[str, Any]) -> str:+ """The holder as a sentence, for a dialog or a console line."""+ if not holder:+ return "another Azimut is using this workspace"+ host = holder.get("host") or "another machine"+ port = holder.get("port")+ where = f"{host}:{port}" if port else host+ return f"another Azimut has this workspace open on {where}"+++def lock_path(root: Path | None = None) -> Path:+ """The lock of *root*, or of the workspace in use.++ Takes a root because a folder is inspected before it is adopted: "another+ Azimut has that one" belongs in the dialog, not in a failure after the+ button.+ """+ base = config.internal_dir() if root is None else root / ".azimut"+ return base / LOCK_NAME+++def _root_key(root: Path) -> Path:+ """A root in the one spelling two of them can be compared in.++ Every question here is "is this the workspace I already hold", and the two+ sides arrive differently: what this process locked comes from the pointer,+ while a folder being inspected has been through `resolve()`. One symlink+ above the workspace makes those different strings for one directory — macOS+ reaches `/tmp` and every temporary directory as `/private/var`, and a synced+ or linked folder does it anywhere — and the mismatch answers "not mine".+ Which is the worst possible answer: the lock file is then opened a second+ time, our *own* handle refuses the second lock, and the analyst is told+ another Azimut has the workspace they are already using.+ """+ try:+ return root.expanduser().resolve()+ except OSError: # pragma: no cover - a path the OS refuses to resolve+ return root.expanduser()+++# -- the operating system's half ----------------------------------------------+#+# Resolved once, by what imports, rather than per call by `sys.platform`. Two+# reasons: a stdlib module that is missing should degrade to the payload rather+# than raise from inside a lock attempt, and code elsewhere legitimately fakes+# `sys.platform` to exercise a Windows path — which must not decide whether this+# module can call `msvcrt`.++try: # POSIX+ import fcntl+except ImportError: # pragma: no cover - exercised on Windows+ fcntl = None # type: ignore[assignment]++try: # Windows+ import msvcrt+except ImportError: # pragma: no cover - exercised on POSIX+ msvcrt = None # type: ignore[assignment]+++#: Where the Windows byte-range lock sits: far past the payload, and past the+#: end of the file.+#:+#: `flock` on POSIX is advisory — it excludes another *locker* and lets everyone+#: else read the bytes. `msvcrt.locking` is **mandatory**: the range it holds is+#: unreadable and unwritable to every other handle, including this process's own.+#: Locking byte 0, where the payload begins, therefore broke the two things the+#: payload exists for. A second instance could not read who holds the workspace,+#: so Windows lost the one message that names the other Azimut. And a workspace+#: move, which copies the folder file by file, could not read its own lock:+#: `copy2` came back with "another process has locked a portion of the file" and+#: the move failed on Windows and nowhere else.+#:+#: A region beyond EOF can be locked and does not extend the file, so the lock+#: keeps excluding a second instance while the bytes anyone actually reads stay+#: outside it.+LOCK_REGION_OFFSET = 1 << 30+++def _try_lock(handle: Any) -> bool:+ """Take the OS lock without waiting. False means someone else holds it.++ True on a platform with neither primitive: there is no verdict to give, and+ the payload below is then the only thing standing between two instances.+ """+ try:+ if fcntl is not None:+ fcntl.flock(handle.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB)+ elif msvcrt is not None:+ handle.seek(LOCK_REGION_OFFSET)+ msvcrt.locking(handle.fileno(), msvcrt.LK_NBLCK, 1)+ except OSError:+ return False+ return True+++def _unlock(handle: Any) -> None:+ try:+ if fcntl is not None:+ fcntl.flock(handle.fileno(), fcntl.LOCK_UN)+ elif msvcrt is not None:+ handle.seek(LOCK_REGION_OFFSET) # the region taken above, exactly+ msvcrt.locking(handle.fileno(), msvcrt.LK_UNLCK, 1)+ except OSError: # pragma: no cover - the close below releases it anyway+ pass+++# -- the payload's half --------------------------------------------------------+++def _now() -> str:+ return datetime.now(timezone.utc).isoformat(timespec="seconds")+++def _mine(port: int | None) -> dict[str, Any]:+ return {+ "pid": os.getpid(),+ "host": socket.gethostname(),+ "port": port,+ "version": __version__,+ "since": _now(),+ "at": _now(),+ }+++def _read(handle: Any) -> dict[str, Any]:+ try:+ handle.seek(0)+ raw = handle.read()+ except OSError:+ return {}+ if not raw.strip():+ return {}+ try:+ payload = json.loads(raw)+ except (json.JSONDecodeError, UnicodeDecodeError):+ return {}+ return payload if isinstance(payload, dict) else {}+++def _write(handle: Any, payload: dict[str, Any]) -> None:+ """Rewrite the payload in place. Binary throughout: the handle is unbuffered+ so the heartbeat lands on disk rather than in a buffer nobody flushes."""+ handle.seek(0)+ handle.write((json.dumps(payload, indent=2) + "\n").encode("utf-8"))+ try:+ handle.truncate()+ os.fsync(handle.fileno())+ except OSError: # pragma: no cover - a share that refuses either is fine+ pass+++def _age(payload: dict[str, Any]) -> float | None:+ """Seconds since the holder last wrote its heartbeat, if it can be read."""+ stamp = payload.get("at")+ if not isinstance(stamp, str):+ return None+ try:+ beat = datetime.fromisoformat(stamp)+ except ValueError:+ return None+ if beat.tzinfo is None:+ beat = beat.replace(tzinfo=timezone.utc)+ return (datetime.now(timezone.utc) - beat).total_seconds()+++def _is_another_live_machine(payload: dict[str, Any]) -> bool:+ """Whether a payload we could still lock over should be believed anyway.++ Only ever true for another host: on this machine the OS lock is the+ authority, and having been granted it proves the previous holder is gone.+ """+ if not payload or payload.get("host") == socket.gethostname():+ return False+ age = _age(payload)+ return age is not None and age < STALE_AFTER_SECONDS+++# -- holding it ----------------------------------------------------------------+++@dataclass+class Held:+ root: Path+ handle: Any+ payload: dict[str, Any]+ stop: threading.Event+++_held: Held | None = None+_guard = threading.Lock()+++def held() -> bool:+ """Whether this process holds the workspace in use. Memory only, no I/O:+ it is asked on the way into every request."""+ with _guard:+ return _held is not None and _held.root == _root_key(config.workspace_root())+++def holder(root: Path | None = None) -> dict[str, Any] | None:+ """Who holds a workspace, when it isn't us. None means it is free."""+ target = _root_key(root if root is not None else config.workspace_root())+ with _guard:+ if _held is not None and _held.root == target:+ return None+ path = lock_path(root)+ if not path.exists():+ return None+ try:+ with open(path, "r+b", buffering=0) as handle:+ taken = _try_lock(handle)+ payload = _read(handle)+ if taken:+ _unlock(handle)+ return payload if _is_another_live_machine(payload) else None+ return payload+ except OSError:+ return None+++def acquire(port: int | None = None, *, force: bool = False) -> None:+ """Take this workspace for this process, or raise :class:`WorkspaceBusy`.++ Called before startup migrates anything: two processes renaming case+ directories at once is the damage this exists to prevent, so the lock has to+ come first.+ """+ global _held+ # Stored resolved, so `held()` and `holder()` compare like with like whatever+ # spelling of the root they are handed (`_root_key`).+ root = _root_key(config.workspace_root())+ with _guard:+ if _held is not None:+ if _held.root == root:+ return+ _release_locked()++ path = lock_path()+ path.parent.mkdir(parents=True, exist_ok=True)+ handle = open(path, "r+b" if path.exists() else "w+b", buffering=0)+ try:+ taken = _try_lock(handle)+ payload = _read(handle)+ if not taken:+ if not force:+ raise WorkspaceBusy(payload)+ # Forced: the OS says another process holds the file, and the+ # analyst says otherwise. We cannot steal the OS lock, so the+ # payload is rewritten and this instance proceeds — the escape+ # hatch for a share where the lock is held by a ghost.+ logger.warning("taking a workspace lock held by %s", describe(payload))+ elif _is_another_live_machine(payload) and not force:+ _unlock(handle)+ raise WorkspaceBusy(payload)++ mine = _mine(port)+ _write(handle, mine)+ stop = threading.Event()+ _held = Held(root=root, handle=handle, payload=mine, stop=stop)+ threading.Thread(+ target=_beat, args=(_held,), name="azimut-workspace-lock", daemon=True+ ).start()+ except BaseException:+ handle.close()+ raise+++def _beat(held: Held) -> None:+ """Keep the heartbeat fresh so another machine can tell live from crashed."""+ while not held.stop.wait(HEARTBEAT_SECONDS):+ with _guard:+ if _held is not held:+ return+ held.payload["at"] = _now()+ try:+ _write(held.handle, held.payload)+ except (OSError, ValueError): # the volume went away; startup will say so+ return+++def release() -> None:+ """Give the workspace back, and leave no payload behind to age.++ The OS would drop the lock on exit anyway. Clearing the file is what saves+ the next run from computing whether a corpse is stale.+ """+ with _guard:+ _release_locked()+++def _release_locked() -> None:+ global _held+ if _held is None:+ return+ held, _held = _held, None+ held.stop.set()+ try:+ _write(held.handle, {})+ _unlock(held.handle)+ except (OSError, ValueError):+ pass+ finally:+ try:+ held.handle.close()+ except OSError:+ pass+++def take_over(port: int | None = None) -> None:+ """Take the workspace whatever the lock says.++ Two machines' clocks disagree, and a sync client can leave a file behind+ that never ages out of view. Without this the verdict above could make a+ workspace permanently unopenable, so the analyst gets the last word.+ """+ acquire(port, force=True)diff --git a/src/azimut/engine/workspacemove.py b/src/azimut/engine/workspacemove.pynew file mode 100644index 0000000..b852a1b--- /dev/null+++ b/src/azimut/engine/workspacemove.py@@ -0,0 +1,689 @@+"""Choosing where the workspace lives, and moving it there.++Two operations, and the difference between them is the whole feature:++*Adopt* points Azimut at a folder that is already where the analyst wants it.+Nothing is copied. It is the likely path — someone who moved the folder by hand+while the app was closed, or who wants a fresh workspace somewhere else — so it+is the cheap one.++*Move* copies the current workspace to a new location, verifies the copy, and+only then writes the pointer. The old folder is never deleted: it is renamed+aside and the analyst decides. Every failure mode below therefore ends with at+least one complete workspace on disk, and usually two.++Nothing inside a workspace records where it is (media are stored as+`media/photo.png`, settings hold keys and preferences), so a move is a directory+copy with no rewriting inside it. What cannot travel is the answer to "where is+the workspace" — that is `config`'s pointer file, and writing it is the switch.+"""++from __future__ import annotations++import logging+import os+import shutil+import sys+import tempfile+import threading+import time+from dataclasses import dataclass, field+from datetime import datetime+from pathlib import Path+from typing import Any, Callable++from .. import config, layout+from . import workspacelock+from .bundles import disk_reserve++logger = logging.getLogger(__name__)+++class MoveError(Exception):+ """A workspace operation refused, with a reason fit to put in front of a user."""+++#: Suffix of the directory a move copies into. It sits beside the destination+#: rather than inside it so the final step is a rename on the same volume, and+#: so a killed copy is obvious rather than mistaken for a workspace.+STAGING_SUFFIX = ".azimut-incoming"++#: Folder names that mean the destination is inside a sync client's tree. Each+#: case carries a SQLite database, and a sync client writing underneath one can+#: corrupt it. Worth saying out loud; not worth refusing, since plenty of people+#: deliberately keep their work there.+CLOUD_MARKERS = (+ "onedrive",+ "dropbox",+ "google drive",+ "googledrive",+ "grive",+ "icloud drive",+ "com~apple~clouddocs",+ "nextcloud",+ "owncloud",+ "pcloud",+ "mega",+ "yandex.disk",+ "yandexdisk",+)++#: Not copied, because it is a cache: `tile_cache_dir()` is disposable by+#: contract (STORAGE_AND_PERFORMANCE), and it is also the largest thing in a+#: workspace that nobody would miss. Rebuilt by browsing the map.+SKIPPED_DIRS = ("cache",)++#: Not copied either, and this one is not optional. The lock names the process+#: using *this* folder on *this* machine, so carrying it to the destination would+#: copy a statement that stops being true on arrival. It is also the one file in+#: the workspace that cannot be read while it is held: on Windows the lock is a+#: mandatory range lock, and `copy2` on it failed the whole move with "another+#: process has locked a portion of the file".+SKIPPED_FILES = (workspacelock.LOCK_NAME,)+++# -- comparing two paths on three operating systems ---------------------------+++def _normal(path: Path) -> str:+ """A path in the form this filesystem would compare it in.++ `os.path.normcase` lowercases and unifies separators on Windows and does+ nothing on POSIX, which is right for Linux and wrong for macOS: HFS+ and+ APFS are case-insensitive by default, so `~/Azimut` and `~/azimut` are one+ folder there and refusing to notice would let a move copy a workspace onto+ itself.+ """+ text = os.path.normcase(str(path))+ return text.casefold() if sys.platform == "darwin" else text+++def _same_folder(left: Path, right: Path) -> bool:+ """Whether two paths name one directory, asked the strongest way available."""+ if left == right:+ return True+ try:+ if left.exists() and right.exists() and left.samefile(right):+ return True+ except OSError:+ pass+ return _normal(left) == _normal(right)+++def _inside(child: Path, parent: Path) -> bool:+ """Whether *child* sits under *parent*, in the same spelling of both.++ Resolved first, because a candidate folder always arrives resolved+ (`_resolve`) while the current root is whatever the pointer says. One symlink+ above the workspace makes those two spellings of one path — `/var` and+ `/private/var` on macOS, a linked or synced folder anywhere — and the string+ comparison would then answer "not inside" about a folder that is, which is+ how a workspace ends up nested in itself.+ """+ inner, outer = _normal(child.resolve()), _normal(parent.resolve())+ return inner == outer or inner.startswith(outer.rstrip(os.sep) + os.sep)+++def _resolve(raw: str) -> Path:+ """What the analyst typed, as a path this machine can act on."""+ text = (raw or "").strip().strip('"')+ if not text:+ raise MoveError("name a folder")+ path = Path(text).expanduser()+ try:+ resolved = path.resolve()+ except OSError as exc: # a broken mount point, mostly+ raise MoveError(f"that path can't be read: {exc}") from exc+ if not resolved.is_absolute():+ raise MoveError("give a full path, starting from the drive or from ~")+ return resolved+++# -- reading a candidate folder ------------------------------------------------+++def _writable(directory: Path) -> bool:+ """Whether Azimut can actually create a file here, asked by trying."""+ try:+ with tempfile.NamedTemporaryFile(dir=directory, prefix=".azimut-probe-"):+ return True+ except OSError:+ return False+++def _count_cases(root: Path) -> int:+ """Permanent cases directly under *root*, found by manifest as everywhere else."""+ try:+ children = sorted(root.iterdir())+ except OSError:+ return 0+ return sum(1 for child in children if child.is_dir() and layout.is_case(child))+++def _looks_like_workspace(root: Path) -> bool:+ return (root / ".azimut").is_dir() or _count_cases(root) > 0+++def _is_empty(directory: Path) -> bool:+ try:+ return not any(directory.iterdir())+ except OSError:+ return False+++def _cloud_warning(root: Path) -> str:+ lowered = [part.casefold() for part in root.parts]+ for marker in CLOUD_MARKERS:+ if any(marker in part for part in lowered):+ return (+ "This looks like a synced folder. A sync client writing into a case "+ "can corrupt its database while Azimut has it open."+ )+ return ""+++def measure(root: Path) -> tuple[int, int]:+ """Files and bytes Azimut would copy out of *root*."""+ files = 0+ total = 0+ for path in _copyable_files(root):+ files += 1+ try:+ total += path.stat().st_size+ except OSError:+ pass+ return files, total+++def _walk(root: Path):+ """The tree a move carries: every directory, and the files inside it.++ Symlinks are skipped rather than followed: a workspace is meant to be a+ self-contained tree, and copying through a link would either duplicate+ something outside it or walk into a loop. Bundles already refuse them for+ the same reason.+ """+ skip = {root / ".azimut" / name for name in SKIPPED_DIRS}+ skip_files = {root / ".azimut" / name for name in SKIPPED_FILES}+ for directory, subdirs, names in os.walk(root, followlinks=False):+ here = Path(directory)+ subdirs[:] = sorted(+ name+ for name in subdirs+ if not (here / name).is_symlink()+ and not any(_same_folder(here / name, skipped) for skipped in skip)+ and not name.endswith(STAGING_SUFFIX)+ )+ files = []+ for name in sorted(names):+ candidate = here / name+ if candidate in skip_files:+ continue+ if not candidate.is_symlink() and candidate.is_file():+ files.append(candidate)+ yield here, files+++def _copyable_dirs(root: Path):+ """Every directory a move carries, parents before children.++ Yielded separately because an *empty* one still has to arrive: a case is+ born with `exports/` and the two `.meta/` directories, and a workspace with+ `.azimut/bundles/`. Recreating only the parents of files would quietly+ return a moved case to a shape it was never in.+ """+ for directory, _files in _walk(root):+ yield directory+++def _copyable_files(root: Path):+ """Every regular file a move carries, in a stable order."""+ for _directory, files in _walk(root):+ yield from files+++def inspect_target(raw: str) -> dict[str, Any]:+ """Everything the dialog needs to decide, in one read-only pass.++ Returns the folder Azimut would actually use, which is not always the one+ that was typed: a destination that already holds someone else's files gets+ an `Azimut` subfolder rather than settling among them.+ """+ current = config.workspace_root().expanduser()+ try:+ target = _resolve(raw)+ except MoveError as exc:+ return _verdict(raw, current, problems=[str(exc)])++ problems: list[str] = []+ warnings: list[str] = []++ if target.exists() and not target.is_dir():+ return _verdict(raw, current, root=target, problems=["that path is a file, not a folder"])++ nested = False+ root = target+ if target.is_dir() and not _is_empty(target) and not _looks_like_workspace(target):+ root = target / "Azimut"+ nested = True++ state = "missing"+ if root.is_dir():+ state = "workspace" if _looks_like_workspace(root) else ("empty" if _is_empty(root) else "occupied")++ if state == "occupied":+ problems.append("that folder already holds other files")++ if state == "workspace":++ if (busy := workspacelock.holder(root)) is not None:+ problems.append(workspacelock.describe(busy))++ if _same_folder(root, current):+ problems.append("that is already the workspace")+ elif _inside(root, current):+ problems.append("that folder is inside the current workspace")+ elif _inside(current, root):+ problems.append("that folder contains the current workspace")++ overflow = layout.root_overflow(root)+ if overflow:+ message = (+ f"that path is {overflow} characters too long: Windows refuses a file path over "+ f"{layout.WINDOWS_MAX_PATH + 1}, and a case needs {layout.IN_CASE_BUDGET} of them"+ )+ # Refused where it breaks, said out loud everywhere else: a case written+ # under a long root on Linux stops opening the day it is copied to a+ # Windows machine, which is exactly the trip a portable case is for.+ (problems if sys.platform == "win32" else warnings).append(message)++ probe = root if root.is_dir() else _existing_parent(root)+ if probe is None:+ problems.append("none of the folders on that path exist")+ elif not _writable(probe):+ problems.append("that folder can't be written to")++ if cloud := _cloud_warning(root):+ warnings.append(cloud)++ # A staging directory can only outlive its move if the process was killed:+ # a move that merely fails clears it. Saying so is what turns "there is a+ # strange folder next to mine" into a fact the analyst already knew.+ if (root.parent / f"{root.name}{STAGING_SUFFIX}").is_dir():+ warnings.append("a copy from an interrupted move is here, and starting again discards it")++ verdict = _verdict(+ raw,+ current,+ root=root,+ state=state,+ nested=nested,+ problems=problems,+ warnings=warnings,+ )+ if probe is not None and not problems:+ needed = verdict["needed_bytes"]+ free = shutil.disk_usage(probe)+ reserve = disk_reserve(free.total)+ verdict["free_bytes"] = free.free+ if needed + reserve > free.free:+ short = needed + reserve - free.free+ verdict["problems"].append(f"not enough free space: {_size(short)} short")+ verdict["ok"] = False+ return verdict+++def _existing_parent(path: Path) -> Path | None:+ for candidate in [path, *path.parents]:+ if candidate.is_dir():+ return candidate+ return None+++def _verdict(+ raw: str,+ current: Path,+ *,+ root: Path | None = None,+ state: str = "missing",+ nested: bool = False,+ problems: list[str] | None = None,+ warnings: list[str] | None = None,+) -> dict[str, Any]:+ problems = problems or []+ files, needed = measure(current) if current.is_dir() else (0, 0)+ return {+ "path": raw,+ "root": str(root) if root else "",+ "state": state,+ "nested": nested,+ "ok": not problems,+ "problems": problems,+ "warnings": warnings or [],+ "cases": _count_cases(root) if root and root.is_dir() else 0,+ "current_root": str(current),+ "current_cases": _count_cases(current),+ "current_files": files,+ "needed_bytes": needed,+ "free_bytes": 0,+ }+++def _size(count: int) -> str:+ value = float(count)+ for unit in ("B", "KB", "MB", "GB"):+ if value < 1024 or unit == "GB":+ return f"{value:.0f} {unit}" if unit == "B" else f"{value:.1f} {unit}"+ value /= 1024+ return f"{value:.1f} GB"+++# -- adopting a folder ---------------------------------------------------------+++def adopt(raw: str) -> dict[str, Any]:+ """Use *raw* as the workspace from now on, without moving anything.++ Covers both folders that already hold cases and an empty folder someone+ wants to start fresh in. The cases in the *current* workspace stay where+ they are, which is why the caller has to have said so out loud first.+ """++ verdict = inspect_target(raw)+ if not verdict["ok"]:+ raise MoveError(verdict["problems"][0])+ root = Path(verdict["root"])+ root.mkdir(parents=True, exist_ok=True)+ config.write_pointer(root)+ try:+ _settle_into_new_root()+ except workspacelock.WorkspaceBusy as busy:+ # Lost the race between inspecting the folder and taking it. The pointer+ # already moved, so say so plainly rather than pretending it didn't.+ raise MoveError(str(busy)) from busy+ return status()+++def use_default() -> dict[str, Any]:+ """Forget a configured location and go back to ``~/Azimut``."""++ config.clear_pointer()+ try:+ _settle_into_new_root()+ except workspacelock.WorkspaceBusy as busy:+ raise MoveError(str(busy)) from busy+ return status()+++def take_the_lock() -> dict[str, Any]:+ """Open the workspace despite the lock, because the analyst says so.++ The verdict can be wrong in one direction that matters: two machines whose+ clocks disagree, or a sync client leaving a file nobody will ever clear.+ Without a way to overrule it, either would make a workspace unopenable.+ """++ workspacelock.take_over(_serving_port())+ from ..workspace import open_workspace++ open_workspace()+ return status()+++def _settle_into_new_root() -> None:+ """Open the new location as a workspace, with everything startup would do.++ The folder may hold cases this process has never seen, written by an older+ Azimut, so it gets the same treatment as a cold start rather than a bare+ `mkdir`. Local import: `workspace` sits above the engine.+ """+ from ..workspace import open_workspace++ config.forget_workspace_root()+ # The lock belongs to a folder, not to the process, so it moves with the+ # root and before the migrations — same order as startup, same reason.+ workspacelock.acquire(_serving_port())+ open_workspace()+++def _serving_port() -> int | None:+ from .. import server++ return server.SERVE_PORT+++# -- moving the workspace ------------------------------------------------------++#: In order, and named as the analyst sees them.+STEPS = ("checking", "settling", "copying", "verifying", "switching", "opening", "tidying")+++@dataclass+class Move:+ source: Path+ root: Path+ step: str = STEPS[0]+ files: int = 0+ copied_files: int = 0+ total_bytes: int = 0+ copied_bytes: int = 0+ error: str = ""+ kept_aside: str = ""+ done: bool = False+ started_at: float = field(default_factory=time.monotonic)++ def snapshot(self) -> dict[str, Any]:+ return {+ "step": self.step,+ "files": self.files,+ "copied_files": self.copied_files,+ "total_bytes": self.total_bytes,+ "copied_bytes": self.copied_bytes,+ "error": self.error,+ "kept_aside": self.kept_aside,+ "done": self.done,+ "source": str(self.source),+ "root": str(self.root),+ }+++_move: Move | None = None+_move_lock = threading.Lock()+++def in_progress() -> bool:+ """Whether a move is running. Case routes refuse while it is."""+ with _move_lock:+ return _move is not None and not _move.done+++def status() -> dict[str, Any]:+ """Where the workspace is, and how the last move went."""++ root = config.workspace_root().expanduser()+ with _move_lock:+ move = _move.snapshot() if _move else None+ busy = workspacelock.holder()+ return {+ "locked_by": busy,+ "locked_detail": workspacelock.describe(busy) if busy else "",+ "root": str(root),+ "default_root": str(config.DEFAULT_ROOT.expanduser()),+ "pointed": config.read_pointer() is not None,+ # An address given on every launch cannot be changed from inside the+ # app, so the UI shows the folder and hides the buttons.+ "environment": bool(os.environ.get("AZIMUT_HOME")),+ "missing": config.workspace_missing(),+ "moving": _move is not None and not _move.done,+ "cases": _count_cases(root),+ "move": move,+ }+++def start(raw: str) -> dict[str, Any]:+ """Begin a move to *raw* in the background. Refuses a second one."""+ global _move+ verdict = inspect_target(raw)+ if not verdict["ok"]:+ raise MoveError(verdict["problems"][0])+ if verdict["state"] == "workspace":+ raise MoveError("that folder already holds a workspace; use it as it is instead")+ source = config.workspace_root().expanduser()+ with _move_lock:+ if _move is not None and not _move.done:+ raise MoveError("a move is already running")+ _move = Move(source=source, root=Path(verdict["root"]))+ move = _move+ threading.Thread(target=_run, args=(move,), name="azimut-workspace-move", daemon=True).start()+ return move.snapshot()+++def _run(move: Move) -> None:+ from . import workqueue++ resume_workers = workqueue.start_workers+ staging = move.root.parent / f"{move.root.name}{STAGING_SUFFIX}"+ try:+ _step_settle(move, workqueue)+ _step_copy(move, staging)+ _step_verify(move, staging)+ _step_switch(move, staging)+ _step_open(move)+ _step_tidy(move)+ move.done = True+ except Exception as exc: # one failure surface: the analyst reads `error`+ logger.warning("workspace move failed at %s: %s", move.step, exc)+ move.error = str(exc) or exc.__class__.__name__+ move.done = True+ shutil.rmtree(staging, ignore_errors=True)+ finally:+ workqueue.start_workers = resume_workers+++def _step_settle(move: Move, workqueue: Any) -> None:+ """Stop background work before anything is copied.++ Mandatory on Windows, which refuses to move a file another handle has open,+ and worth doing everywhere: a thumbnail written into the source while the+ copy walks past it is a file the verification would then reject.+ """+ move.step = "settling"+ workqueue.start_workers = False+ if not workqueue.wait_until_idle(timeout=30.0):+ raise MoveError("background work is still running; try again in a moment")+++def _step_copy(move: Move, staging: Path) -> None:+ move.step = "copying"+ # A leftover from an interrupted attempt is incomplete by definition: the+ # pointer only ever names a folder that passed verification.+ shutil.rmtree(staging, ignore_errors=True)+ move.files, move.total_bytes = measure(move.source)+ staging.mkdir(parents=True)+ for source_dir in _copyable_dirs(move.source):+ (staging / source_dir.relative_to(move.source)).mkdir(parents=True, exist_ok=True)+ for source_file in _copyable_files(move.source):+ destination = staging / source_file.relative_to(move.source)+ shutil.copy2(source_file, destination)+ move.copied_files += 1+ move.copied_bytes += destination.stat().st_size+++def _step_verify(move: Move, staging: Path) -> None:+ """Every file, by name and by size. Until this passes the old folder is+ still the workspace, and nothing has been switched."""+ move.step = "verifying"+ for source_dir in _copyable_dirs(move.source):+ if not (staging / source_dir.relative_to(move.source)).is_dir():+ raise MoveError(f"the copy is missing the {source_dir.name} folder")+ for source_file in _copyable_files(move.source):+ copied = staging / source_file.relative_to(move.source)+ try:+ expected = source_file.stat().st_size+ actual = copied.stat().st_size+ except OSError as exc:+ raise MoveError(f"the copy is missing {source_file.name}") from exc+ if expected != actual:+ raise MoveError(f"the copy of {source_file.name} is a different size")+++def _step_switch(move: Move, staging: Path) -> None:+ """Put the copy in its final place, then write the pointer.++ The rename comes first so the pointer never names a half-built folder, and+ it is a rename rather than a replace because Windows will not let+ `os.replace` overwrite a directory. Dying between the two leaves the new+ folder complete but unused, and the old one still authoritative.+ """+ move.step = "switching"+ if move.root.is_dir():+ if not _is_empty(move.root):+ raise MoveError("something was written into the destination while the copy ran")+ move.root.rmdir()+ move.root.parent.mkdir(parents=True, exist_ok=True)+ staging.rename(move.root)+ config.write_pointer(move.root)+++def _step_open(move: Move) -> None:+ move.step = "opening"+ _settle_into_new_root()+ if not config.settings_path().exists():+ raise MoveError("the new workspace did not open; the old folder is untouched")+++def _step_tidy(move: Move) -> None:+ """Keep the old folder, renamed, until the analyst says otherwise."""+ move.step = "tidying"+ stamp = datetime.now().strftime("%Y-%m-%d")+ candidate = move.source.with_name(f"{move.source.name}.old-{stamp}")+ index = 2+ while candidate.exists():+ candidate = move.source.with_name(f"{move.source.name}.old-{stamp}-{index}")+ index += 1+ try:+ move.source.rename(candidate)+ move.kept_aside = str(candidate)+ except OSError as exc:+ # The move itself succeeded; failing to rename the leftovers is a+ # tidiness problem, and saying where they are beats failing here.+ logger.warning("could not set the old workspace aside: %s", exc)+ move.kept_aside = str(move.source)+++def discard_old() -> str:+ """Delete the folder the last move set aside, if the analyst asks.++ Only that folder: the path comes from this process's own memory, never from+ the request, so there is no route here that deletes an arbitrary directory.+ After a restart the memory is gone and the folder is theirs to remove.+ """+ with _move_lock:+ move = _move+ if move is None or not move.done or move.error or not move.kept_aside:+ raise MoveError("there is no old workspace to remove")+ old = Path(move.kept_aside)+ if _same_folder(old, config.workspace_root().expanduser()):+ raise MoveError("that folder is the workspace")+ _rmtree(old)+ move.kept_aside = ""+ return str(old)+++def _force_remove(func: Callable[..., Any], path: str, _info: Any) -> None:+ """Clear the read-only bit and retry, the one thing Windows needs here."""+ try:+ os.chmod(path, 0o700)+ func(path)+ except OSError:+ pass+++def _rmtree(path: Path) -> None:+ # `onexc` replaced `onerror` in 3.12 and we still support 3.11; the hook+ # ignores the third argument, which is all that differs between them. Same+ # shape, and the same reason, as `scrapers._rmtree`.+ if sys.version_info >= (3, 12):+ shutil.rmtree(path, onexc=_force_remove)+ else:+ shutil.rmtree(path, onerror=_force_remove)diff --git a/src/azimut/launcher.py b/src/azimut/launcher.pyindex 813c6a6..4d761ed 100644--- a/src/azimut/launcher.py+++ b/src/azimut/launcher.py@@ -14,6 +14,7 @@ the browser anyway.from __future__ import annotations+import atexitimport threadingimport timeimport webbrowser@@ -52,6 +53,15 @@ def _open_when_ready(server: uvicorn.Server, url: str) -> None:def serve(port: int, *, open_browser: bool = True) -> None:"""Run the server (blocking) and, unless told not to, open the browser tab."""+ from . import server as server_module+ from .engine import workspacelock++ # The app is built by uvicorn's factory, which takes no arguments, so the+ # port is left here for it: a second instance names the holder by host and+ # port, and "on this machine, port 8477" is what sends someone to the right+ # tab.+ server_module.SERVE_PORT = port+ atexit.register(workspacelock.release)server = _build_server(port)if open_browser:_open_when_ready(server, f"http://127.0.0.1:{port}")diff --git a/src/azimut/layout.py b/src/azimut/layout.pynew file mode 100644index 0000000..fa24829--- /dev/null+++ b/src/azimut/layout.py@@ -0,0 +1,466 @@+"""Where things live inside a case folder.++One module owns the on-disk shape. Before this, fourteen modules each knew a+piece of it — `workspace.py` built `case.json` and `case.db` by hand, the sqlite+backend guessed the media folder from the database's parent, and the bundle+importer rebuilt the whole tree from string literals. Moving a directory meant+finding all of them.++Everything here takes a case root and returns a path under it. Nothing touches+the filesystem: these are answers to "where would it be", not "is it there".+Creation and traversal guards stay in `Case`, which is the only thing that owns+a real case on disk.++The bundle importer is the reason these take a root rather than a `Case`: it+builds a case shell in a staging directory that is not a case yet.++**The case root belongs to the analyst; `azimut/` belongs to the tool.** A case+folder holds one directory Azimut writes into, and whatever else its owner wants+to keep beside it. Before the wrapper, every directory in a case was ours, so a+folder someone created for their own material either had nowhere to go or+collided with a tool directory — a user-made `notes/` merging into the app's.+One boundary removes the whole class.++Paths inside a case stay relative to the *tool* root: a media is `media/x.png`+in the graph, in a sidecar and in a bundle, whatever the tree above it looks+like. That is what let the wrapper land without rewriting a single stored path,+and what keeps a bundle portable between versions.+"""++from __future__ import annotations++import re+import unicodedata+from pathlib import Path, PurePosixPath++#: What the tool owns inside a case folder. Everything beside it is the+#: analyst's, and Azimut neither reads nor writes there.+TOOL_DIR = "azimut"++# -- what is visible, and what is not ----------------------------------------+#+# Visible means openable and useful in another program: the media themselves,+# the note bodies, a rendered proof, the manifest that says what this folder is.+# Hidden means only Azimut can read it — session specs, post drafts, saved grid+# state, the sidecars, the database.+#+# `media/` used to interleave as many `.azimut.json` sidecars as real files, and+# `exports/` held post drafts rather than exports, so its name lied. Both are+# fixed here.++#: Post drafts. Named for what they are; `exports/` is now free to mean exports.+DRAFTS_DIR = ".drafts"+#: Saved Inspect session specs.+INSPECT_DIR = ".inspect"+#: Saved Grid Search state.+SEARCH_DIR = ".search"+#: Machinery that belongs to a visible sibling: `media/.meta/` holds sidecars,+#: `proofs/.meta/` holds the editable specs and pasted assets.+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"++#: Content directories, in birth order. The trash is deliberately not one of+#: them — see `TRASH_DIR`.+CASE_SUBDIRS = (+ "media",+ "notes",+ "proofs",+ "exports",+ DRAFTS_DIR,+ INSPECT_DIR,+ SEARCH_DIR,+)++#: Deleted artifacts wait here, hidden at the case root. Outside `CASE_SUBDIRS`+#: on purpose: it is not case content, and the bundle leaves it behind.+TRASH_DIR = ".trash"+++# -- how long a path may get -------------------------------------------------+#+# Windows refuses a path over 260 characters, and a case is written by a Python+# process *and* read by a bundled ffmpeg subprocess, so relying on the opt-in+# long-path support is relying on someone else's manifest. The app stays inside+# the limit instead.+#+# The budget is one subtraction. Every name below is capped, so the longest path+# a case can ever produce is a constant, and the only variable left is where the+# workspace lives:+#+# len(workspace root) + IN_CASE_BUDGET <= WINDOWS_MAX_PATH+#+# `tests/test_layout.py` recomputes IN_CASE_BUDGET from these caps and fails if+# a new directory level or a raised cap breaks the sum. Raising one means+# lowering another.++#: Usable length of a Windows path (260 counts the null terminator).+WINDOWS_MAX_PATH = 259++#: The case folder's own name. Uncapped until the budget was computed, which+#: made a long case name enough to break a case on Windows all by itself.+MAX_CASE_SLUG = 48++#: A media filename, extension included. The visible title is its stem, so both+#: are shortened together rather than allowed to drift.+MAX_MEDIA_NAME = 90++#: The stem of anything the analyst saves under a name — notes, proofs, inspect+#: sessions, post drafts. Mirrored in `frontend/src/lib/naming.js`.+MAX_SLUG = 68++#: A note's filing folder: total path length, and how deep it may nest.+MAX_FOLDER_PATH = 40+MAX_FOLDER_DEPTH = 4++#: The scratch directory one download works in. A full uuid4 hex bought nothing+#: but 20 characters of the budget.+DOWNLOAD_ID_LENGTH = 12++#: The deepest path a permanent case can hold, counted from the directory that+#: holds the case folder. A constant, because every name inside it is capped.+#:+#: It lives here rather than only in the test that proves it because choosing a+#: workspace root has to enforce it: a folder the analyst picks is the last+#: variable left in the subtraction, and refusing it at that moment is the only+#: place the limit can be explained. `tests/test_layout.py` rebuilds both numbers+#: from the caps and the real directory names, so a new directory level or a+#: raised cap fails there rather than at write time on someone's machine.+IN_CASE_BUDGET = 174++#: The same for a scratch case, which pays for the `.azimut/scratch/` prefix but+#: spends less on its own name: a short generated id rather than a case slug.+IN_SCRATCH_BUDGET = 160+++def room_for_workspace_root() -> int:+ """How long a workspace root may be before a case inside it can break.++ The separator between the root and the case folder is counted here, so a+ caller compares this against `len(str(root))` and nothing else.+ """+ return WINDOWS_MAX_PATH - 1 - max(IN_CASE_BUDGET, IN_SCRATCH_BUDGET)+++def root_overflow(root: Path | str) -> int:+ """Characters by which *root* is too long to hold cases, 0 when it fits."""+ return max(0, len(str(root)) - room_for_workspace_root())+++# -- the note left at the case root ------------------------------------------+#+# The boundary above only works if the person opening the folder knows it is+# there. Hidden directories and a wrapper make damage unlikely; a sentence+# saying which half is theirs is what makes it unnecessary. It is also the+# cheapest part of the whole design.++README_NAME = "README.txt"++#: Built from the constants above so a renamed directory cannot leave the note+#: describing a tree that no longer exists.+README_TEXT = f"""This folder is an Azimut case.++ {TOOL_DIR}/ Azimut's files.+ everything else here is yours.++Azimut does not read your folders, index them or clean them up. They travel+with the case when you export it.++Three things worth knowing:++ Do not move or rename anything inside {TOOL_DIR}/ while Azimut is running.+ Do not name a folder "{TOOL_DIR}" here. Windows would merge it with ours.+ Keep folder names short. A full path over 260 characters breaks on Windows.++To move this case, move the whole folder. To send it somewhere, export it+from Azimut instead of zipping this one: the export is checksummed, and it+can carry a password.+"""+++def readme(root: Path) -> Path:+ return root / README_NAME+++def is_tool_dir(name: str) -> bool:+ """Whether a case-root entry name is the tool's own, or collides with it.++ Case-folded because Windows and macOS are case-insensitive: an `Azimut/`+ the analyst creates sits beside ours on Linux and merges into it there. The+ bundle refuses to carry one, and the doctor reports one it finds.+ """+ return name.casefold() == TOOL_DIR+++_INVALID_NAME = re.compile(r'[<>:"/\\|?*\x00-\x1f]+')+_WINDOWS_RESERVED = frozenset(+ ["con", "prn", "aux", "nul"]+ + [f"com{number}" for number in range(1, 10)]+ + [f"lpt{number}" for number in range(1, 10)]+)+++def slugify(text: str | None, fallback: str, *, limit: int = MAX_SLUG) -> str:+ """A human-readable, cross-platform filename stem.++ The historical function name stays because every save route already shares+ it, but the result is no longer a URL slug. The filesystem stem is the name+ Azimut shows, so case, spaces and Unicode survive. Only characters Windows+ forbids are replaced. The returned value is the canonical visible name.+ """+ value = unicodedata.normalize("NFC", str(text or ""))+ value = re.sub(r"\s+", " ", value).strip()+ value = _INVALID_NAME.sub("_", value).strip(" .")+ while ".." in value:+ value = value.replace("..", "_")+ value = value[:limit].rstrip(" .")+ if not value:+ value = fallback[:limit].rstrip(" .") or "file"+ if value.split(".", 1)[0].casefold() in _WINDOWS_RESERVED:+ value = f"_{value}"[:limit].rstrip(" .")+ return value+++def visible_filename(title: str | None, suffix: str, fallback: str = "file") -> str:+ """Canonical visible filename for ``title`` while preserving ``suffix``."""+ clean_suffix = suffix if suffix.startswith(".") else f".{suffix}" if suffix else ""+ stem_limit = max(1, MAX_MEDIA_NAME - len(clean_suffix))+ return f"{slugify(title, fallback, limit=stem_limit)}{clean_suffix}"+++#: Characters a case folder's name may not hold, on top of everything `slugify`+#: already replaces: the folder name *is* the case id, and the id travels in a+#: URL path, where `#` cuts the rest off and `%` opens an escape. A generated+#: slug never contains either; a folder the analyst named can.+URL_HOSTILE_CHARS = "#%"++#: The same rule spelled for a person, so the message and the check cannot drift.+UNUSABLE_NAME_CHARS = '\\ / : * ? " < > | # %'+++def usable_case_name(name: str) -> bool:+ """Whether a folder can hold a case under the name it already has.++ A case made in the app is named by `Case.create`, which slugs whatever was+ typed. A folder the analyst made themselves arrives already named, and+ adopting it must not rename it — so the name has to clear on its own the bar+ a slug clears by construction: inside `MAX_CASE_SLUG` (the path budget above+ is computed from it), no character Windows refuses, no reserved device name,+ no leading dot, no trailing dot or space.++ `slugify` encodes every one of those rules, so the question is whether the+ name is already its own slug. Compared against the composed form because+ macOS hands back decomposed names from a directory listing, and "Café" is+ not two different folders.+ """+ if not name or name in {".", ".."}:+ return False+ if set(name) & set(URL_HOSTILE_CHARS):+ return False+ return slugify(name, "", limit=MAX_CASE_SLUG) == unicodedata.normalize("NFC", name)+++class LayoutError(ValueError):+ """A name that is not part of the case layout."""+++def tool_root(root: Path) -> Path:+ """The directory Azimut owns inside a case folder.++ Every other answer in this module is relative to this one, so the wrapper is+ one join rather than a prefix repeated everywhere.+ """+ return root / TOOL_DIR+++def manifest(root: Path) -> Path:+ """The case manifest, and the file that makes a directory a case.++ Stays visible at the tool root while the database goes into `.data/`. It is+ small, readable, and it is what identifies the folder — the doctor finds a+ case renamed from outside by reading it. Hiding it would also mean a second+ migration keyed on the filesystem, since nothing could read the schema that+ says to run it.+ """+ return tool_root(root) / "case.json"+++def data_dir(root: Path) -> Path:+ return tool_root(root) / DATA_DIR+++def database(root: Path) -> Path:+ """The case database: entities, links, folders, jobs and the trash journal."""+ return data_dir(root) / "case.db"+++def notes_file(root: Path) -> Path:+ """The case's free-form scratchpad."""+ return tool_root(root) / "notes.md"+++def subdir(root: Path, name: str) -> Path:+ """One content directory, refusing a name that is not part of the layout."""+ if name not in CASE_SUBDIRS:+ raise LayoutError(f"unknown case subdir '{name}'")+ return tool_root(root) / name+++def media(root: Path) -> Path:+ """The media directory. Named because several callers need it without+ wanting the string."""+ return subdir(root, "media")+++def notes(root: Path) -> Path:+ """The note bodies directory."""+ return subdir(root, "notes")+++def trash(root: Path) -> Path:+ return tool_root(root) / TRASH_DIR+++# -- case-relative paths -----------------------------------------------------+#+# What the graph stores, what a sidecar records and what a bundle names. They+# are built here so a directory rename is one edit, not thirty.+++def sidecar_rel(media_rel: str) -> str:+ """A media's sidecar, out of the way in `media/.meta/`.++ It used to sit beside the file as `<name>.azimut.json`, which put one JSON+ file in the listing for every real one. It still travels with the case, and+ it is still what rebuilds the index when the database is gone.+ """+ return f"media/{META_DIR}/{PurePosixPath(media_rel).name}.json"+++def proof_spec_rel(name: str) -> str:+ """The editable spec behind a proof. Internal, unlike the PNG it renders."""+ return f"proofs/{META_DIR}/{name}.json"+++def proof_export_rel(name: str) -> str:+ """The rendered proof, which is the whole point of the folder."""+ return f"proofs/{name}.png"+++def proof_assets_rel(name: str) -> str:+ """Images pasted into one proof, kept with its spec."""+ return f"proofs/{META_DIR}/{name}.assets"+++def note_rel(folder: str, name: str) -> str:+ """A note body, mirroring the notebook's filing tree.++ Notes were named after their entity id — visible in `notes/` and illegible,+ the cost of being in the way without the benefit of being readable. They now+ follow the rule every other document already obeys (`api/naming.py`): the+ name is the filename.++ The folder is mirrored rather than flattened because notes are the only+ document type with a filing tree, and flat storage would make two notes+ called "Summary" in two different folders illegal — which guts the feature+ at the exact moment an analyst's workflow is one folder per video. So+ uniqueness is scoped to the folder, not the case.+ """+ parts = [+ slugify(segment, "folder") for segment in folder.split("/") if segment.strip()+ ]+ return "/".join(["notes", *parts, f"{name}.md"])+++def draft_rel(name: str) -> str:+ return f"{DRAFTS_DIR}/{name}.json"+++def session_rel(name: str) -> str:+ return f"{INSPECT_DIR}/{name}.json"+++def grid_rel(name: str) -> str:+ return f"{SEARCH_DIR}/{name}.json"+++def content_dirs(root: Path) -> tuple[Path, ...]:+ """Every directory a case is born with.++ The `.meta/` pair is in here so a case's birth state already has the shape+ its first sidecar or proof spec would create — otherwise emptying a case+ would not return it to the state it was born in, which is a gate the repo+ keeps green (`tests/test_artifacts.py`).+ """+ dirs = [tool_root(root) / name for name in CASE_SUBDIRS]+ dirs += [media(root) / META_DIR, subdir(root, "proofs") / META_DIR]+ return tuple(dirs)+++def unwrapped_manifest(root: Path) -> Path:+ """Where the manifest sat before the case gained its `azimut/` wrapper.++ Its presence is the whole signal for the schema-5 migration: a case folder+ with a manifest at its own root has not been wrapped yet.+ """+ return root / "case.json"+++#: What an unwrapped case holds at its own root, and therefore all the wrapper+#: migration may move. Anything else there was put by the analyst and stays+#: where they left it — sweeping someone's folder into `azimut/` would be the+#: exact opposite of what the wrapper is for. Names only: this module does not+#: read the filesystem, the caller checks what exists.+#: Spelled out rather than derived from `CASE_SUBDIRS`: this is the shape of a+#: case *before* the wrapper, and it must not follow the current layout as that+#: keeps moving. `inspect/` and `search/` were still visible back then.+UNWRAPPED_ENTRIES = (+ "case.db",+ "notes.md",+ TRASH_DIR,+ "media",+ "notes",+ "proofs",+ "exports",+ "inspect",+ "search",+)++#: Migration backups (`case.pre-migrate-v2.json`), which are ours too.+UNWRAPPED_BACKUP_GLOB = "case.*.json"++#: Where the machinery sat before it was hidden, for the migration that moves+#: it. Old shapes are named here rather than spelled out at the call site, so+#: `tests/test_layout.py`'s guard stays meaningful: nothing else in the app may+#: build these paths.+PRE_HIDDEN_DB = "case.db"+PRE_HIDDEN_SIDECAR_SUFFIX = ".azimut.json"+PRE_HIDDEN_DIRS = {"inspect": INSPECT_DIR, "search": SEARCH_DIR, "exports": DRAFTS_DIR}+++def needs_wrapper(root: Path) -> bool:+ """Whether this case folder still holds the tool's files at its own root."""+ return not manifest(root).is_file() and unwrapped_manifest(root).is_file()+++def is_case(root: Path) -> bool:+ """Whether this directory holds a case, wrapped or not.++ Cases are found by their manifest, never by folder name, so a case renamed+ from outside is still found. An unwrapped case answers yes as well, or it+ could never be opened to be migrated.+ """+ return manifest(root).is_file() or unwrapped_manifest(root).is_file()+++def extracted_database(root: Path) -> Path:+ """The case database in a freshly extracted bundle, whatever its vintage.++ A bundle written before the machinery was hidden carries `case.db` at the+ tool root, and the folder migration moves it into `.data/` the first time+ the case is opened. The import has to read the database *before* that, to+ stamp the destination's name into it, so it needs the old address too.+ """+ current = database(root)+ return current if current.is_file() else tool_root(root) / PRE_HIDDEN_DBdiff --git a/src/azimut/repository.py b/src/azimut/repository.pyindex fe7bde2..bddfca8 100644--- a/src/azimut/repository.py+++ b/src/azimut/repository.py@@ -312,3 +312,7 @@ class CaseRepository(Protocol):def prune_jobs(self, *, kind: str | None = None) -> int:...++ def replace_path_references(self, old: str, new: str) -> None:+ """Replace one exact case-relative path in entity attrs and job records."""+ ...diff --git a/src/azimut/server.py b/src/azimut/server.pyindex a62a638..ad49e11 100644--- a/src/azimut/server.py+++ b/src/azimut/server.py@@ -2,16 +2,28 @@from __future__ import annotations+import logging+import threading+from contextlib import asynccontextmanagerfrom pathlib import Path+from typing import Any, AsyncIteratorfrom fastapi import FastAPI, Requestfrom fastapi.responses import FileResponse, JSONResponse, PlainTextResponsefrom fastapi.staticfiles import StaticFilesfrom . import __version__, config+from .engine import workspacelock, workspacemove++logger = logging.getLogger(__name__)STATIC_DIR = Path(__file__).parent / "static"+#: The port this run serves on, set by `launcher.serve` before the app is built.+#: Only used to name ourselves in the workspace lock, so another instance can+#: say *which* Azimut has the folder rather than only that one does.+SERVE_PORT: int | None = None+# The server binds localhost only, but that alone doesn't stop a web page the# browser has open from reaching it — a page can hit 127.0.0.1 directly (its# own Origin travels along), or point a name it controls at 127.0.0.1 (DNS@@ -61,66 +73,106 @@ def install_local_guard(app: FastAPI) -> None:return await call_next(request)-def _recover_jobs() -> None:- """On startup, return jobs a crashed process left ``running`` to the queue and- wake the worker for any case that still has pending work. A `running` row- nothing owns would otherwise stall forever; recovery resumes it."""- from .engine import workqueue- from .workspace import Case+#: Reachable while the workspace is not: everything the stop screen and the+#: recovery dialog need, and nothing that would touch a case.+ALWAYS_AVAILABLE = ("/api/health", "/api/settings/workspace")- for row in Case.list_all():- try:- case = Case.open(row["id"])- case.recover_jobs()- except Exception:- continue- if workqueue.has_queued(case):- workqueue.wake(case)+_opening = threading.Lock()-def create_app() -> FastAPI:- config.ensure_workspace()- # Start keeping the tail of the warning log, so "Report an issue" has- # something to say about a run that already went wrong (engine/diagnostics).- from .engine import diagnostics+def open_workspace_if_free() -> dict[str, Any] | None:+ """Hold the workspace and open it, or say who has it instead.- diagnostics.install()- # Before any router can import a scraper: point yt-dlp/gallery-dl at the- # newer copies in the workspace, if the user has fetched any. No network.- from .engine import scrapers+ Asked on the way into every case request, and cheap once it has succeeded —+ holding the lock is a fact in memory. Retrying matters because the answer+ changes without this process restarting: someone closes the other Azimut,+ presses reload, and the tab has to come back to life. Until then nothing is+ served, because a workspace this process never opened is one whose+ migrations never ran.+ """+ if workspacelock.held():+ return None+ with _opening:+ if workspacelock.held():+ return None+ try:+ workspacelock.acquire(SERVE_PORT)+ except workspacelock.WorkspaceBusy as busy:+ return busy.holder or {}+ from .workspace import open_workspace- scrapers.activate()+ open_workspace()+ return None- # Reap stale empty scratch sessions; never let housekeeping block startup.- from .workspace import Case- try:- Case.cleanup_scratch()- except OSError:- pass+def install_availability_guard(app: FastAPI) -> None:+ """Refuse case work while there is no workspace to do it in.++ Three states share one answer. A configured folder that is gone must never+ be silently recreated — that is the fastest way to make someone believe they+ lost everything. A workspace being copied to a new volume must not be+ written to half way through. And a workspace another Azimut holds is not+ ours to touch. All three leave the recovery routes reachable, so the browser+ can show what happened and offer the way out.+ """++ @app.middleware("http")+ async def guard(request, call_next): # type: ignore[no-untyped-def]+ path = request.url.path+ if path.startswith("/api/") and not path.startswith(ALWAYS_AVAILABLE):+ if config.workspace_missing():+ return JSONResponse(+ {"detail": "the workspace folder is not available", "workspace": "missing"},+ status_code=503,+ )+ if workspacemove.in_progress():+ return JSONResponse(+ {"detail": "the workspace is being moved", "workspace": "moving"},+ status_code=503,+ )+ if (busy := open_workspace_if_free()) is not None:+ return JSONResponse(+ {"detail": workspacelock.describe(busy), "workspace": "locked"},+ status_code=503,+ )+ return await call_next(request)- # Bundle handlers must exist before crash recovery sees their queued jobs.- # The same pass removes browser uploads abandoned by a previous run.- from .engine import bundles- try:- bundles.cleanup_uploads()- except OSError:- pass+def create_app() -> FastAPI:+ # Start keeping the tail of the warning log, so "Report an issue" has+ # something to say about a run that already went wrong (engine/diagnostics).+ from .engine import diagnostics- # Reclaim background jobs a previous run left mid-flight and resume any- # pending thumbnail work through the single worker. Best-effort: housekeeping- # must never block or crash startup.- try:- _recover_jobs()- except Exception:- pass+ diagnostics.install()- app = FastAPI(title="Azimut", version=__version__, docs_url="/api/docs")+ # A configured folder that is gone stops here: no skeleton is created, no+ # case is migrated, and the browser gets the stop screen instead of an empty+ # workspace that looks like lost work.+ #+ # The lock comes before the housekeeping for the same reason it exists: two+ # processes running the case migrations at once is renames racing over the+ # same directories. A workspace another Azimut holds is left exactly as it+ # is, and the tab that opens explains who has it.+ if not config.workspace_missing() and (busy := open_workspace_if_free()):+ logger.warning("workspace not opened: %s", workspacelock.describe(busy))++ @asynccontextmanager+ async def lifespan(_app: FastAPI) -> AsyncIterator[None]:+ yield+ # Give the workspace back on the way out. The OS would drop the lock+ # when the process dies anyway; releasing it here clears the payload, so+ # the next run has nothing to judge the staleness of, and closes the+ # handle, which is what lets Windows delete the folder afterwards.+ workspacelock.release()++ app = FastAPI(+ title="Azimut", version=__version__, docs_url="/api/docs", lifespan=lifespan+ )from .api import cases, drafts, events, files, ingest, inspect, media, proofs, satellite, settings, templatesapp.include_router(cases.router)+ app.include_router(cases.workspace_router)app.include_router(media.router)app.include_router(inspect.router)app.include_router(satellite.router)@@ -133,6 +185,9 @@ def create_app() -> FastAPI:app.include_router(templates.router)# extension-origin CORS, /api/ingest/* only (see ingest.install_cors)ingest.install_cors(app)+ # Inside the local guard: a request that isn't allowed to reach the app at+ # all should not learn whether the workspace is there.+ install_availability_guard(app)# last, so it wraps everything: refuse non-loopback Host / cross-origin webinstall_local_guard(app)diff --git a/src/azimut/sqlite_backend.py b/src/azimut/sqlite_backend.pyindex 773cc3b..d1d5932 100644--- a/src/azimut/sqlite_backend.py+++ b/src/azimut/sqlite_backend.py@@ -16,12 +16,13 @@ from __future__ import annotationsimport jsonimport sqlite3-from contextlib import contextmanager+from contextlib import closing, contextmanagerfrom dataclasses import dataclass, fieldfrom pathlib import Pathfrom typing import TYPE_CHECKING, Any, Callable, Iterator, TypeVarfrom .engine import mapsites+from . import layoutfrom .repository import EntityStatusfrom .workspace import Case, CaseError, _new_id, _now, _parse_cursor, _replace_with_retry@@ -179,6 +180,17 @@ def _entity_search_text(type_: str, label: str, attrs: dict[str, Any] | None) ->).casefold()+def _replace_exact(value: Any, old: str, new: str) -> Any:+ """Recursively replace strings equal to ``old``; never edit prose."""+ if isinstance(value, str):+ return new if value == old else value+ if isinstance(value, list):+ return [_replace_exact(item, old, new) for item in value]+ if isinstance(value, dict):+ return {key: _replace_exact(item, old, new) for key, item in value.items()}+ return value++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."""@@ -396,6 +408,24 @@ def _normalise_media_item(item: dict[str, Any]) -> tuple[dict[str, Any], tuple[A)+def read_meta(db_path: Path) -> dict[str, str]:+ """The `meta` table of a case database, without opening the case.++ `SqliteCase.open` would upgrade the schema on the way in, which is the wrong+ move on a database whose case cannot even be read yet — the caller is+ `workspace.restore_manifest`, recovering the name and dates of a case that+ lost its manifest. So this is a peek, read-only and best effort: a missing+ file, a foreign format or a database that needs recovery all answer with+ nothing, and the caller falls back to the folder's own name.+ """+ try:+ with closing(sqlite3.connect(f"{db_path.as_uri()}?mode=ro", uri=True)) as conn:+ rows = conn.execute("SELECT key, value FROM meta")+ return {str(key): str(value) for key, value in rows}+ except (sqlite3.Error, ValueError, OSError):+ return {}++class SqliteCase:"""SQLite implementation of `CaseRepository` over one `case.db` file."""@@ -440,13 +470,17 @@ class SqliteCase:return store@classmethod- def open(cls, db_path: Path) -> "SqliteCase":+ def open(cls, db_path: Path, *, media_dir: Path | None = None) -> "SqliteCase":"""Open an existing `case.db`, upgrading an older schema and refusing anewer one.Mirrors `Case.migrate`'s forward-compat guarantee for the JSON format: adatabase written by a newer Azimut is refused rather than mangled, and anolder one is brought up to `SQLITE_SCHEMA` in order before use.++ `media_dir` is where the one-time sidecar backfill reads from. The+ backend is not told the case layout anywhere else and must not guess it,+ so an open without it leaves the backfill for a later open that has it."""db_path = Path(db_path)if not db_path.exists():@@ -462,7 +496,8 @@ class SqliteCase:)if version < SQLITE_SCHEMA:store._upgrade()- store._ensure_media_index()+ if media_dir is not None:+ store._ensure_media_index(media_dir)return storedef _upgrade(self) -> None:@@ -494,12 +529,29 @@ class SqliteCase:conn.execute("ROLLBACK")raise- def _ensure_media_index(self) -> None:+ def forget_media_index(self) -> None:+ """Drop the one-time backfill marker so the next open rebuilds the index.++ The folder migration moves the sidecars, and the backfill may already+ have run — and stamped itself done — while they were still at their old+ location. Without this the browse index of every migrating case would+ come out empty, silently.+ """++ def op(conn: sqlite3.Connection) -> None:+ conn.execute("DELETE FROM meta WHERE key = 'media_index_ready'")++ self._write(op)++ def _ensure_media_index(self, media_dir: Path) -> None:"""Backfill media sidecars once after schema 4 reaches a case.The marker is written in the same transaction as the rows, so aninterrupted scan is retried rather than leaving a partial index active.Normal media writes keep the index current after this one-time pass.++ `media_dir` comes from the caller: where media live is the case layout's+ business, not the database's."""with self._connect() as conn:ready = conn.execute(@@ -515,9 +567,8 @@ class SqliteCase:entity_by_path[path] = row["id"]rows: list[tuple[dict[str, Any], str | None]] = []- media_dir = self.db_path.parent / "media"- for sidecar in sorted(media_dir.glob("*.azimut.json")):- media_name = sidecar.name[: -len(".azimut.json")]+ for sidecar in sorted((media_dir / layout.META_DIR).glob("*.json")):+ media_name = sidecar.stemif not (media_dir / media_name).is_file():continuetry:@@ -1725,6 +1776,54 @@ class SqliteCase:return self._write(op)+ def replace_path_references(self, old: str, new: str) -> None:+ """Rewrite an exact case-relative path in graph attrs and durable jobs.++ One SQLite transaction keeps structured references coherent. File specs+ and sidecars live outside the database and are handled by the artifact+ rename journal that calls this method.+ """+ def op(conn: sqlite3.Connection) -> None:+ for row in conn.execute(+ "SELECT id, type, label, attrs_json FROM entities"+ ).fetchall():+ attrs = json.loads(row["attrs_json"])+ replaced = _replace_exact(attrs, old, new)+ if replaced == attrs:+ continue+ conn.execute(+ "UPDATE entities SET attrs_json = ?, folder = ?, search_text = ?"+ " WHERE id = ?",+ (+ json.dumps(replaced, ensure_ascii=False),+ _folder_of(replaced),+ _entity_search_text(row["type"], row["label"], replaced),+ row["id"],+ ),+ )++ for row in conn.execute(+ "SELECT id, job_key, payload_json FROM jobs"+ ).fetchall():+ payload = json.loads(row["payload_json"])+ replaced = _replace_exact(payload, old, new)+ key = new if row["job_key"] == old else row["job_key"]+ if key == row["job_key"] and replaced == payload:+ continue+ conn.execute(+ "UPDATE jobs SET job_key = ?, payload_json = ?, updated_at = ?"+ " WHERE id = ?",+ (+ key,+ json.dumps(replaced, ensure_ascii=False),+ _now(),+ row["id"],+ ),+ )+ self._touch(conn)++ self._write(op)+# -- JSON -> SQLite conversion ---------------------------------------------diff --git a/src/azimut/workspace.py b/src/azimut/workspace.pyindex 7ebb5c5..b282132 100644--- a/src/azimut/workspace.py+++ b/src/azimut/workspace.py@@ -1,65 +1,78 @@"""Create, list and open case and scratch workspaces.-A case is a plain directory (spec §4):-- <case>/- ├── case.json # case manifest- ├── case.db # entities, links, folders, jobs and the trash journal- ├── notes.md # free-form case notes- ├── media/ # imported/downloaded media + satellite crops + sidecars- ├── proofs/ # composed proofs (PNG + editable JSON spec)- ├── exports/ # post drafts, reports- └── .trash/ # deleted artifacts, one directory per delete action--One-shot mode uses the same layout under ``scratch/`` and can be promoted into-``cases/`` (spec §3.3).+A case is a plain directory (spec §4). What sits inside it is `layout.py`'s+answer, not this module's: `Case` owns creation, locking and traversal guards,+and asks `layout` where each file goes.++One-shot mode uses the same layout under ``.azimut/scratch/`` and can be+promoted into a permanent case at the workspace root (spec §3.3)."""from __future__ import annotationsimport json+import loggingimport reimport shutil+import sysimport sqlite3import threadingimport timeimport uuid+from dataclasses import dataclassfrom datetime import datetime, timezonefrom pathlib import Pathfrom typing import TYPE_CHECKING, Any, Callable-from . import config+from . import config, layout+from .layout import MAX_CASE_SLUGfrom .repository import EntityStatus+logger = logging.getLogger(__name__)+if TYPE_CHECKING:from .repository import CaseRepositoryfrom .sqlite_backend import SqliteCase-CASE_SUBDIRS = ("media", "notes", "proofs", "exports", "inspect", "search")--#: Deleted artifacts wait here, mirroring the case tree under one directory per-#: delete action. Outside `CASE_SUBDIRS` on purpose: it is not case content, and-#: the bundle leaves it behind.-TRASH_DIR = ".trash"-# On-disk schema. Older cases migrate on open; newer schemas are refused.# Bump CASE_SCHEMA with every migration.#-# Schema 3 moves the graph from case.json into case.db. JSON_SCHEMA marks the-# last JSON graph schema used by migration.+# A case migrates in three passes, because the three kinds of change need+# different tools:+#+# 1..JSON_SCHEMA field reshapes inside case.json CASE_MIGRATIONS+# ..STORAGE_SCHEMA the graph moves into case.db _activate_sqlite+# ..CASE_SCHEMA the case *folder* changes shape FOLDER_MIGRATIONS+#+# The third pass reshapes the case tree. Folder migrations declare their target+# schema explicitly: several green implementation checkpoints may collapse into+# one public jump before release, rather than becoming compatibility contracts+# nobody has on disk.JSON_SCHEMA = 2-CASE_SCHEMA = 3+STORAGE_SCHEMA = 3+CASE_SCHEMA = 9# from_version -> function(data) returning data reshaped for from_version + 1.# The runner (Case.migrate) owns stamping the new schema number, so a migration-# only rewrites fields. These cover json-shape upgrades within case.json (up to-# JSON_SCHEMA); the storage activation to schema 3 is not a field reshape and is-# handled specially by migrate() via _activate_sqlite, not through this table.+# only rewrites fields.CASE_MIGRATIONS: dict[int, Callable[[dict[str, Any]], dict[str, Any]]] = {1: lambda data: data,}+@dataclass(frozen=True)+class FolderMigration:+ """One folder-shape migration, which may jump over unreleased schemas."""++ target: int+ migrate: Callable[["Case"], None]+++# from_version -> migration to a declared later version. Populated below the+# class, once `Case` exists.+FOLDER_MIGRATIONS: dict[int, FolderMigration] = {}++def _case_schema(data: dict[str, Any]) -> int:"""The schema a loaded case.json declares. Legacy/untagged files predate thetag and are treated as the first schema."""@@ -68,6 +81,7 @@ def _case_schema(data: dict[str, Any]) -> int:return meta["schema"]return 1+# Empty scratch sessions older than this are reaped at startup (spec §9).SCRATCH_MAX_AGE_DAYS = 14@@ -96,11 +110,25 @@ def _case_lock(path: Path) -> threading.RLock:_case_locks[key] = lockreturn 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",+ "person",+ "organization",+ "alias",+ "account",+ "email",+ "phone",+ "domain",+ "ip",+ "vehicle",+ "place",+ "capture",+ "event",+ "media",+ "proof",+ "note","bookmark",)@@ -111,7 +139,7 @@ def _now() -> str:def _slugify(name: str) -> str:slug = re.sub(r"[^a-z0-9]+", "-", name.lower()).strip("-")- return slug or "case"+ return slug[:MAX_CASE_SLUG].strip("-") or "case"def _new_id(prefix: str) -> str:@@ -131,6 +159,7 @@ def ensure_dir(path: Path) -> Path:for attempt in range(20):try:path.mkdir(parents=True, exist_ok=True)+ _hide_if_dotted(path)return pathexcept PermissionError:if path.is_dir():@@ -141,6 +170,41 @@ def ensure_dir(path: Path) -> Path:return path # pragma: no cover - loop always returns or raises above+def _hide_if_dotted(path: Path) -> None:+ """Make a dot-directory actually hidden on Windows.++ A leading dot hides a directory on Linux and macOS and means nothing to+ Windows Explorer, which needs `FILE_ATTRIBUTE_HIDDEN` set. Without this the+ whole visible/hidden split in `layout.py` would work on two platforms out of+ three, and `.data` — the case database — would sit in plain view on the one+ where people are most likely to go tidying.++ Best effort: a filesystem that refuses the attribute (a network share, a FAT+ stick) is not a reason to fail a directory creation.+ """+ if sys.platform != "win32" or not path.name.startswith("."):+ return+ import ctypes++ FILE_ATTRIBUTE_HIDDEN = 0x02+ try:+ ctypes.windll.kernel32.SetFileAttributesW(str(path), FILE_ATTRIBUTE_HIDDEN)+ except (AttributeError, OSError): # pragma: no cover - Windows only+ pass+++def write_readme(root: Path) -> None:+ """Leave the note that says which half of the case folder is whose.++ Only when there is none. The file sits in the analyst's half, so once it is+ there it is theirs: an edited or deleted README is a choice, not damage, and+ rewriting it on every open would undo it.+ """+ readme = layout.readme(root)+ if not readme.exists():+ readme.write_text(layout.README_TEXT, encoding="utf-8")++def _replace_with_retry(src: Path, dst: Path) -> None:"""``src.replace(dst)`` with a brief retry for a transient Windows``PermissionError``. The case lock already keeps our own threads off the@@ -228,8 +292,16 @@ class Case:if isinstance(meta, dict) and meta.get("storage") == "sqlite":# `.open` (not the bare constructor) so an older `case.db` schema is# upgraded in place on first access — the storage-format equivalent- # of `Case.migrate` for the manifest.- return SqliteCase.open(self.path / "case.db")+ # of `Case.migrate` for the manifest. The media directory is passed+ # in because the backend must not have to guess the case layout.+ # A released schema-3 case still keeps `case.db` at the tool root+ # after the wrapper pre-step. The final layout moves it into+ # `.data/`, but the normalizer needs the graph before that move to+ # flatten its trash. Resolve current-then-legacy during migration.+ return SqliteCase.open(+ layout.extracted_database(self.path),+ media_dir=self.media_dir,+ )return None# -- identity ---------------------------------------------------------@@ -248,8 +320,6 @@ class Case:def create(cls, name: str, *, scratch: bool = False) -> "Case":"""Create a new case. Every case is born on the SQLite backend; a legacyjson case only ever arrives from disk and is converted on open."""- from .sqlite_backend import SqliteCase-parent = config.scratch_dir() if scratch else config.cases_dir()parent.mkdir(parents=True, exist_ok=True)slug = _new_id("scratch") if scratch else _slugify(name)@@ -257,10 +327,52 @@ class Case:if path.exists():raise CaseError(f"case '{slug}' already exists")path.mkdir()- for sub in CASE_SUBDIRS:- (path / sub).mkdir()+ return cls._born(path, name)++ @classmethod+ def adopt(cls, name: str) -> "Case":+ """Make a case out of a folder the analyst put in the workspace.++ The whole feature is that the folder is not moved, renamed or read: a+ case is a directory holding `azimut/`, so filling that one directory in+ is all adoption is. Whatever was already there stays in the analyst's+ half of the case (`free_entries`), exactly as if they had dropped it in+ after the fact — the app does not import it, and the README that lands+ beside it says so.++ Refuses a folder that already holds the tool's files. An `azimut/` with+ content and no manifest is a case that lost it, not a folder waiting to+ become one, and being born over it would write a new database on top of+ the work. `restore_manifest` is that folder's path back.+ """+ _require_case_folder_name(name)+ path = config.cases_dir() / name+ if not path.is_dir():+ raise CaseError(f"folder '{name}' is not in the workspace")+ if layout.is_case(path):+ raise CaseError(f"folder '{name}' is already a case")+ if tool_dir_holds_content(path):+ raise CaseError(f"folder '{name}' holds a case that lost its manifest")+ return cls._born(path, name)++ @classmethod+ def _born(cls, path: Path, name: str) -> "Case":+ """Give an existing directory everything a case is born with.++ Shared by `create` and `adopt` so an adopted folder is a case in the+ same sense as one made in the app, down to the birth state the artifact+ registry is gated on (`tests/test_artifacts.py`). Two spellings of it+ would drift the day a tool adds a directory.+ """+ from .sqlite_backend import SqliteCase++ ensure_dir(layout.tool_root(path))+ for directory in layout.content_dirs(path):+ ensure_dir(directory) # `ensure_dir`, so a dot-directory is hidden+ ensure_dir(layout.data_dir(path))+ write_readme(path)case = cls(path)- case._sqlite_cache = SqliteCase.create(path / "case.db", name=name)+ case._sqlite_cache = SqliteCase.create(case.db_path, name=name)case._write_json({"azimut": {"schema": CASE_SCHEMA, "storage": "sqlite"},@@ -269,22 +381,32 @@ class Case:"updated_at": _now(),})- (path / "notes.md").write_text(f"# {name}\n\n", encoding="utf-8")+ case.notes_path.write_text(f"# {name}\n\n", encoding="utf-8")return case@classmethod- def open(cls, case_id: str) -> "Case":+ def locate(cls, case_id: str) -> "Case":+ """Find a case from its manifest without opening its database.++ Normal callers want :meth:`open`. The Case Doctor deliberately needs a+ weaker primitive: a missing ``case.db`` is one of the failures it must+ be able to inspect and repair.+ """for parent in (config.cases_dir(), config.scratch_dir()):path = parent / case_id- if (path / "case.json").exists():- case = cls(path)- case.migrate()- from .engine import trash as trash_engine-- trash_engine.recover(case)- return case+ if layout.is_case(path):+ return cls(path)raise CaseError(f"case '{case_id}' not found")+ @classmethod+ def open(cls, case_id: str) -> "Case":+ case = cls.locate(case_id)+ case.migrate()+ from .engine import trash as trash_engine++ trash_engine.recover(case)+ return case+def migrate(self) -> dict[str, Any]:"""Bring case.json up to ``CASE_SCHEMA`` on open, and return the data.@@ -296,6 +418,9 @@ class Case:update instead (spec §7)."""with self._lock:+ # Before anything can be read: an unwrapped case keeps its manifest+ # at the case root, so `self.read()` would not find it at all.+ _wrap_case_folder(self)data = self.read()version = _case_schema(data)if version == CASE_SCHEMA:@@ -308,19 +433,47 @@ class Case:storage = data.get("azimut", {}).get("storage")self._backup(f"pre-migrate-v{version}")# 1) json-shape migrations, up to the last json-storage schema.- for step in range(version, min(CASE_SCHEMA, JSON_SCHEMA)):- migrate = CASE_MIGRATIONS.get(step)- if migrate is None:- raise CaseError(f"no migration for case schema {step}")- data = migrate(data)- data.setdefault("azimut", {})["schema"] = step + 1- self._materialize_note_content(data)- self._write_json(data)+ # A released SQLite case starts at schema 3, so it skips this whole+ # write: its manifest is stamped only once, after the final folder+ # layout is valid.+ if version <= JSON_SCHEMA:+ for step in range(version, min(CASE_SCHEMA, JSON_SCHEMA)):+ migrate = CASE_MIGRATIONS.get(step)+ if migrate is None:+ raise CaseError(f"no migration for case schema {step}")+ data = migrate(data)+ data.setdefault("azimut", {})["schema"] = step + 1+ self._materialize_note_content(data)+ self._write_json(data)# 2) storage activation: json graph -> sqlite (case.db), manifest last.- if CASE_SCHEMA > JSON_SCHEMA and storage != "sqlite":+ if storage != "sqlite":self._activate_sqlite(self.read())- return self.snapshot()- return data+ # 3) folder-shape steps, on a case that is now on sqlite.+ self._migrate_folder()+ return self.snapshot()++ def _migrate_folder(self) -> None:+ """Run folder-shape migrations up to `CASE_SCHEMA`.++ A migration declares its target rather than implicitly advancing by one.+ This lets unreleased implementation checkpoints share one idempotent+ normalizer and one final stamp. If a process stops during that work, the+ old schema remains in the manifest and the same normalizer resumes.+ """+ while True:+ data = self.read()+ version = _case_schema(data)+ if version >= CASE_SCHEMA:+ return+ migration = FOLDER_MIGRATIONS.get(version)+ if migration is None:+ raise CaseError(f"no migration for case schema {version}")+ if not version < migration.target <= CASE_SCHEMA:+ raise CaseError(f"invalid folder migration {version} -> {migration.target}")+ migration.migrate(self)+ data = self.read()+ data.setdefault("azimut", {})["schema"] = migration.target+ self._write_json(data)def _activate_sqlite(self, data: dict[str, Any]) -> None:"""Convert a note-materialized json case (schema JSON_SCHEMA) into the@@ -333,10 +486,11 @@ class Case:"""from .sqlite_backend import convert_json_to_sqlite- convert_json_to_sqlite(data, self.path / "case.db")+ ensure_dir(self.db_path.parent)+ convert_json_to_sqlite(data, self.db_path)self._write_json({- "azimut": {"schema": CASE_SCHEMA, "storage": "sqlite"},+ "azimut": {"schema": STORAGE_SCHEMA, "storage": "sqlite"},"name": data.get("name", self.id),"created_at": data.get("created_at"),"updated_at": data.get("updated_at") or _now(),@@ -364,10 +518,10 @@ class Case:brought back, so reaping the case around it would delete recoverable workwithout anyone asking."""- if (path / TRASH_DIR).is_dir() and any((path / TRASH_DIR).iterdir()):+ trash = layout.trash(path)+ if trash.is_dir() and any(trash.iterdir()):return True- for sub in CASE_SUBDIRS:- directory = path / sub+ for directory in layout.content_dirs(path):if not directory.is_dir():continuefor candidate in directory.rglob("*"):@@ -379,6 +533,32 @@ class Case:return Truereturn False+ @classmethod+ def migrate_all(cls) -> list[tuple[str, str]]:+ """Upgrade every discovered permanent and scratch case in place.++ Workspace startup calls this before scratch cleanup. One damaged case+ is reported and skipped rather than preventing every healthy case from+ opening; the future doctor can then handle the isolated failure.+ """+ failures: list[tuple[str, str]] = []+ from .engine import trash as trash_engine++ for parent in (config.cases_dir(), config.scratch_dir()):+ if not parent.is_dir():+ continue+ for path in sorted(parent.iterdir(), key=lambda candidate: candidate.name):+ if not layout.is_case(path):+ continue+ case = cls(path)+ try:+ case.migrate()+ trash_engine.recover(case)+ except Exception as exc:+ failures.append((case.id, str(exc)))+ logger.warning("could not migrate case %s: %s", case.id, exc)+ return failures+@classmethoddef cleanup_scratch(cls, max_age_days: int = SCRATCH_MAX_AGE_DAYS) -> int:"""Delete scratch cases that hold nothing and haven't been touched in@@ -395,7 +575,7 @@ class Case:cutoff = datetime.now(timezone.utc).timestamp() - max_age_days * 86400removed = 0for path in list(parent.iterdir()):- if not (path / "case.json").exists():+ if not layout.is_case(path):continuecase = cls(path)try:@@ -422,21 +602,28 @@ class Case:return removed@classmethod- def list_all(- cls, *, q: str | None = None, limit: int | None = None- ) -> list[dict[str, Any]]:+ def list_all(cls, *, q: str | None = None, limit: int | None = None) -> list[dict[str, Any]]:out: list[dict[str, Any]] = []for parent, scratch in ((config.cases_dir(), False), (config.scratch_dir(), True)):if not parent.is_dir():continuefor path in sorted(parent.iterdir()):- if not (path / "case.json").exists():+ if not layout.is_case(path):continuecase = cls(path)data = case.read()updated_at = data.get("updated_at")- if case._sqlite is not None:- updated_at = case._sqlite.updated_at() or updated_at+ health = "ok"+ try:+ if case._sqlite is not None:+ updated_at = case._sqlite.updated_at() or updated_at+ entity_count: int | None = case.entity_count()+ except (CaseError, OSError, sqlite3.Error):+ # Keep a damaged case reachable from the switcher. Opening+ # it normally may fail, but the Doctor still locates it from+ # the manifest and can offer a repair.+ health = "needs-attention"+ entity_count = Noneout.append({"id": case.id,@@ -444,7 +631,8 @@ class Case:"scratch": scratch,"created_at": data.get("created_at"),"updated_at": updated_at,- "entity_count": case.entity_count(),+ "entity_count": entity_count,+ "health": health,})out.sort(key=lambda c: c.get("updated_at") or "", reverse=True)@@ -457,9 +645,33 @@ class Case:# -- json io -----------------------------------------------------------+ @property+ def tool_root(self) -> Path:+ """The directory Azimut owns. `self.path` is the case folder, whose+ other contents belong to the analyst and are never touched."""+ return layout.tool_root(self.path)+@propertydef json_path(self) -> Path:- return self.path / "case.json"+ return layout.manifest(self.path)++ @property+ def db_path(self) -> Path:+ return layout.database(self.path)++ @property+ def media_dir(self) -> Path:+ return layout.media(self.path)++ def free_entries(self) -> list[Path]:+ """What the analyst keeps beside `azimut/`, in the half they own.++ Azimut never looks inside these. The one thing it does with them is+ carry them in a bundle, so that a case travels whole rather than+ travelling as the part the tool happened to author. Listed here so+ "everything that is not `azimut/`" has a single definition.+ """+ return sorted(entry for entry in self.path.iterdir() if entry.name != layout.TOOL_DIR)def read(self) -> dict[str, Any]:# Under the lock so a concurrent write can't be replacing case.json@@ -538,8 +750,14 @@ class Case:"""A bounded, filtered page of the catalog (Step 5), paged with an indexedrowid keyset."""return self._graph().page_entities(- limit=limit, cursor=cursor, types=types, status=status,- query=query, folder=folder, unfiled=unfiled, recursive=recursive,+ limit=limit,+ cursor=cursor,+ types=types,+ status=status,+ query=query,+ folder=folder,+ unfiled=unfiled,+ recursive=recursive,)def catalog_summary(self) -> dict[str, Any]:@@ -549,9 +767,7 @@ class Case:def list_links(self) -> list[dict[str, Any]]:return self._graph().list_links()- def upsert_media_item(- self, item: dict[str, Any], *, entity_id: str | None = None- ) -> None:+ 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:@@ -611,7 +827,7 @@ class Case:@propertydef notes_path(self) -> Path:- return self.path / "notes.md"+ return layout.notes_file(self.path)def read_notes(self) -> str:try:@@ -624,7 +840,7 @@ class Case:@propertydef note_dir(self) -> Path:- return self.path / "notes"+ return layout.notes(self.path)def _note_entity(self, entity_id: str) -> dict[str, Any]:entity = self.get_entity(entity_id)@@ -651,6 +867,48 @@ class Case:note_path.parent.mkdir(parents=True, exist_ok=True)note_path.write_text(str(content or ""), encoding="utf-8")+ def prune_note_dirs(self, rel: str) -> None:+ """Drop the mirrored folder directories a removed note left empty.++ Called wherever a note's file stops being there — a delete, or a move+ into the trash. A mirror that keeps every directory a note ever lived in+ stops being a mirror, and the birth-state gate counts each one.+ """+ if not rel.startswith("notes/"):+ return+ _prune_empty_note_dirs(self.note_dir, self.resolve_inside(rel).parent)++ def note_target(self, folder: str, label: str, *, taken_by: str | None = None) -> str:+ """A free case-relative path for a note called `label` in `folder`.++ The name is the filename, as it already is for proofs, sessions and+ drafts. Uniqueness is scoped to the folder, so "Summary" can exist under+ two different videos — the whole reason the tree is mirrored on disk.++ A name already used in that folder gets a numbered suffix rather than a+ refusal: a note is the most frequent thing an analyst creates, and the+ front already proposes free names (`lib/naming.js`, `uniqueName`).+ `taken_by` is the note being renamed, which does not collide with itself.+ """+ stem = layout.slugify(label, "note")+ candidate = layout.note_rel(folder, stem)+ directory = self.resolve_inside(candidate).parent+ occupied = (+ {+ path.name.casefold()+ for path in directory.iterdir()+ if taken_by is None or path != self.resolve_inside(taken_by)+ }+ if directory.is_dir()+ else set()+ )+ index = 2+ while True:+ if Path(candidate).name.casefold() not in occupied:+ return candidate+ candidate = layout.note_rel(folder, f"{stem}-{index}")+ index += 1+def create_note(self,label: str,@@ -662,16 +920,15 @@ class Case:source: str | None = None,) -> dict[str, Any]:with self._lock:+ canonical = layout.slugify(label, "Note")# The graph row goes to case.db; the body stays a file on the shell.- # Add the row to mint an id, write notes/<id>.md, then record its- # relative path on the row.graph = self._graph()entity = graph.add_entity(- "note", label, {"folder": folder}, by=by, status=status, source=source+ "note", canonical, {"folder": folder}, by=by, status=status, source=source)- rel = f"notes/{entity['id']}.md"+ rel = self.note_target(folder, canonical)note_path = self.resolve_inside(rel)- note_path.parent.mkdir(parents=True, exist_ok=True)+ ensure_dir(note_path.parent)note_path.write_text(content, encoding="utf-8")return graph.update_entity(entity["id"], {"attrs": {"path": rel}})@@ -717,7 +974,7 @@ class Case:workqueue.wait_until_idle()def promote(self, name: str) -> "Case":- """Move a scratch case into cases/ under a proper name (spec §3.3)."""+ """Move a scratch case to the workspace root under a proper name."""if not self.is_scratch:raise CaseError("only scratch cases can be promoted")slug = _slugify(name)@@ -760,7 +1017,142 @@ class Case:return self._graph().add_entity(type_, label, attrs, by=by, status=status, source=source)def update_entity(self, entity_id: str, patch: dict[str, Any]) -> dict[str, Any]:- return self._graph().update_entity(entity_id, patch)+ with self._lock:+ self._follow_note_rename(entity_id, patch)+ self._follow_named_artifact_rename(entity_id, patch)+ return self._graph().update_entity(entity_id, patch)++ 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.++ Tool-specific saves already carry their old filename and perform the+ same move. This hook closes the other route: the shared Details editor+ patches an entity directly. Explicitly supplying the path attribute+ means the caller already owns the move, so this does nothing.+ """+ entity = self.get_entity(entity_id)+ if entity is None or "label" not in patch:+ return+ rules: dict[str, tuple[str, Callable[[str], str], str]] = {+ "proof": ("spec", layout.proof_spec_rel, "Proof"),+ "inspect-session": ("spec", layout.session_rel, "Inspect"),+ "post": ("draft", layout.draft_rel, "Post"),+ }+ rule = rules.get(str(entity.get("type") or ""))+ if rule is None:+ return+ attribute, build, fallback = rule+ incoming = patch.get("attrs") or {}+ if attribute in incoming:+ return+ current = (entity.get("attrs") or {}).get(attribute)+ if not isinstance(current, str):+ return++ from .engine import media as media_engine++ canonical = layout.slugify(str(patch["label"]), fallback)+ target = build(canonical)+ source_path = self.resolve_inside(current)+ target_path = self.resolve_inside(target)+ occupied = {+ path.name.casefold() for path in target_path.parent.iterdir() if path != source_path+ }+ if target_path.name.casefold() in occupied:+ raise CaseError(f"another {entity['type']} already uses that name")++ moves: list[tuple[Path, Path]] = [(source_path, target_path)]+ replacements: list[tuple[str, str]] = [(current, target)]+ attrs = {attribute: target}+ if entity["type"] == "proof":+ old_name = Path(current).stem+ old_export = layout.proof_export_rel(old_name)+ new_export = layout.proof_export_rel(canonical)+ moves.extend(+ [+ (+ self.resolve_inside(old_export),+ self.resolve_inside(new_export),+ ),+ (+ self.resolve_inside(layout.proof_assets_rel(old_name)),+ self.resolve_inside(layout.proof_assets_rel(canonical)),+ ),+ ]+ )+ replacements.append((old_export, new_export))+ if (entity.get("attrs") or {}).get("path") == old_export:+ attrs["path"] = new_export++ moved: list[tuple[Path, Path]] = []+ applied: list[tuple[str, str]] = []+ try:+ for source, destination in moves:+ if source.exists() and source != destination:+ media_engine.rename_path(source, destination)+ moved.append((source, destination))+ for old, new in replacements:+ if old == new:+ continue+ self.replace_path_references(old, new)+ media_engine.rewrite_file_references(self, old, new)+ applied.append((old, new))+ if target_path.exists():+ try:+ data = json.loads(target_path.read_text(encoding="utf-8"))+ except (OSError, json.JSONDecodeError):+ data = None+ if isinstance(data, dict):+ data["title"] = canonical+ media_engine.write_json_atomic(target_path, data)+ except Exception:+ for old, new in reversed(applied):+ self.replace_path_references(new, old)+ media_engine.rewrite_file_references(self, new, old)+ for source, destination in reversed(moved):+ if destination.exists() and not source.exists():+ media_engine.rename_path(destination, source)+ raise++ patch["label"] = canonical+ if attrs:+ patch.setdefault("attrs", {}).update(attrs)++ def _follow_note_rename(self, entity_id: str, patch: dict[str, Any]) -> None:+ """Move a note's file when its title or its folder changes.++ The name is the filename, so renaming a note in the notebook moves the+ markdown on disk — the same rule proofs, sessions and drafts follow, and+ the reason `notes/` is worth keeping visible at all. The patch is+ completed with the new path, so the graph row and the file never+ disagree.+ """+ entity = self.get_entity(entity_id)+ if entity is None or entity.get("type") != "note":+ return+ attrs = entity.get("attrs") or {}+ incoming = patch.get("attrs") or {}+ if incoming.get("path"):+ return # the caller is stating where the file is, not renaming it+ label = patch.get("label", entity.get("label"))+ folder = incoming.get("folder", attrs.get("folder") or "")+ current = attrs.get("path")+ if not isinstance(current, str):+ return+ target = self.note_target(str(folder), str(label), taken_by=current)+ canonical = Path(target).stem+ if target == current:+ if patch.get("label") != canonical and entity.get("label") != canonical:+ patch["label"] = canonical+ return+ source = self.resolve_inside(current)+ destination = self.resolve_inside(target)+ if source.exists():+ ensure_dir(destination.parent)+ shutil.move(str(source), str(destination))+ _prune_empty_note_dirs(self.note_dir, source.parent)+ patch.setdefault("attrs", {})["path"] = target+ patch["label"] = canonicaldef remove_entity(self, entity_id: str) -> None:self._graph().remove_entity(entity_id)@@ -820,7 +1212,14 @@ class Case:parts = [p for p in parts if p]if not parts:raise CaseError("folder name is required")- return "/".join(parts)+ # Folders nest, so without a bound the deepest path in a case is+ # unbounded too — and note files will mirror this tree on disk.+ if len(parts) > layout.MAX_FOLDER_DEPTH:+ raise CaseError(f"a folder nests at most {layout.MAX_FOLDER_DEPTH} deep")+ path = "/".join(parts)+ if len(path) > layout.MAX_FOLDER_PATH:+ raise CaseError(f"a folder path is at most {layout.MAX_FOLDER_PATH} characters")+ return pathdef list_folders(self) -> list[str]:return self._graph().list_folders()@@ -897,7 +1296,7 @@ class Case:"""Where deleted artifacts wait. Hidden, at the case root, and never a`CASE_SUBDIRS` member: nothing that walks a case's content should walkinto it."""- return self.path / TRASH_DIR+ return layout.trash(self.path)# -- durable jobs (thumbnail and background-job model) -------------------@@ -909,9 +1308,7 @@ class Case:payload: dict[str, Any] | None = None,max_attempts: int = 3,) -> dict[str, Any]:- return self._graph().enqueue_job(- kind, key=key, payload=payload, max_attempts=max_attempts- )+ return self._graph().enqueue_job(kind, key=key, payload=payload, max_attempts=max_attempts)def claim_job(self, *, kinds: list[str] | None = None) -> dict[str, Any] | None:return self._graph().claim_job(kinds=kinds)@@ -942,21 +1339,465 @@ class Case:def prune_jobs(self, *, kind: str | None = None) -> int:return self._graph().prune_jobs(kind=kind)+ def replace_path_references(self, old: str, new: str) -> None:+ self._graph().replace_path_references(old, new)+# -- helpers -------------------------------------------------------------def subdir(self, name: str) -> Path:- if name not in CASE_SUBDIRS:- raise CaseError(f"unknown case subdir '{name}'")- return ensure_dir(self.path / name)+ try:+ directory = layout.subdir(self.path, name)+ except layout.LayoutError as exc:+ raise CaseError(str(exc)) from exc+ return ensure_dir(directory)def resolve_inside(self, relative: str) -> Path:- """Resolve a case-relative path, refusing traversal outside the case."""- candidate = (self.path / relative).resolve()- if not candidate.is_relative_to(self.path.resolve()):+ """Resolve a case-relative path, refusing traversal outside the case.++ Relative means relative to what the tool owns, not to the case folder:+ `media/x.png` is what the graph, the sidecars and the bundles all say,+ and it kept meaning that when the `azimut/` wrapper arrived. The guard+ is against the tool root too, so a doctored path cannot climb out into+ the analyst's own files sitting beside it.+ """+ root = self.tool_root+ candidate = (root / relative).resolve()+ if not candidate.is_relative_to(root.resolve()):raise CaseError("path escapes the case directory")return candidate+# -- folders in the workspace that are not cases yet --------------------------+#+# Cases are found by their manifest, so a folder someone creates in `~/Azimut`+# from their file manager is invisible to `Case.list_all` — which is correct+# until they made it *to be* a case. Rather than ask them to recreate it in the+# app, the switcher offers what is already on disk, and a click fills it in.+#+# Three answers, because two of them must not lead to the same move: a folder+# with nothing of ours in it can be born into (`new`), one whose name a case+# folder cannot carry has to be renamed first (`unusable-name`), and one holding+# the tool's files without a manifest is damaged goods (`broken`) that only+# `restore_manifest` may touch.++FOLDER_NEW = "new"+FOLDER_UNUSABLE_NAME = "unusable-name"+FOLDER_BROKEN = "broken"++#: Files an operating system drops into any folder someone opens. A folder+#: holding only these was never filled by the analyst, so they do not make an+#: `azimut/` directory look inhabited.+_OS_JUNK = frozenset({".ds_store", "thumbs.db", "desktop.ini"})+++def _require_case_folder_name(name: str) -> None:+ """Refuse a folder name no case can live under, and say what to do instead.++ The remedy is always the same and it is not Azimut's to apply: the folder is+ the analyst's, so it is renamed in their file manager, not behind their back.+ """+ if not layout.usable_case_name(name):+ raise CaseError(+ f"'{name}' cannot name a case folder. Rename it: {MAX_CASE_SLUG} characters "+ f"at most, and none of {layout.UNUSABLE_NAME_CHARS}"+ )+++def tool_dir_holds_content(root: Path) -> bool:+ """Whether this folder's `azimut/` holds anything the tool wrote.++ Deliberately generous about what counts: the question is only ever asked to+ decide whether it is safe to create a case here, and the cost of a false+ "empty" is someone's database written over.+ """+ tool = layout.tool_root(root)+ if not tool.is_dir():+ return False+ return any(+ path.is_file() and path.name.casefold() not in _OS_JUNK for path in tool.rglob("*")+ )+++def folder_state(root: Path) -> str:+ """What Azimut can do with a workspace folder that is not a case.++ The name is checked first: a folder Windows could not hold a case in has to+ be renamed whether it is empty or damaged, so saying so once is clearer than+ offering a repair that would then refuse.+ """+ if not layout.usable_case_name(root.name):+ return FOLDER_UNUSABLE_NAME+ if tool_dir_holds_content(root):+ return FOLDER_BROKEN+ return FOLDER_NEW+++def list_workspace_folders() -> list[dict[str, Any]]:+ """Every folder sitting in the workspace that is not a case, with its state.++ Dotted names are skipped: `.azimut/` is the workspace's own machinery, and+ nothing else hidden was put there to be seen. Files are skipped too — a case+ is a directory.+ """+ parent = config.cases_dir()+ if not parent.is_dir():+ return []+ return [+ {"name": path.name, "state": folder_state(path)}+ for path in sorted(parent.iterdir(), key=lambda item: item.name.casefold())+ if path.is_dir() and not path.name.startswith(".") and not layout.is_case(path)+ ]+++def restore_manifest(name: str) -> "Case":+ """Give a case folder back the manifest it lost.++ Without `case.json` a folder is not a case to anything: the switcher, the+ startup migration and the Doctor all walk past it, and adoption must refuse+ it, so a whole investigation can sit in the workspace unreachable. Writing+ the manifest is what puts it back in everyone's view, and it is deliberately+ the smallest possible move — the name and the dates come from the database+ when it can be read, and every other repair stays where it belongs, in the+ Doctor, on a case that is now openable.++ Stamped at `STORAGE_SCHEMA` rather than the current schema. The folder was+ shaped by whichever Azimut wrote it, and claiming it is already current+ would skip the folder migrations that make it so.+ """+ from .sqlite_backend import read_meta++ _require_case_folder_name(name)+ path = config.cases_dir() / name+ if not path.is_dir():+ raise CaseError(f"folder '{name}' is not in the workspace")+ if layout.is_case(path):+ raise CaseError(f"folder '{name}' already holds a case")+ if not tool_dir_holds_content(path):+ raise CaseError(f"folder '{name}' holds no case to recover")+ meta = read_meta(layout.extracted_database(path))+ case = Case(path)+ case._write_json(+ {+ "azimut": {"schema": STORAGE_SCHEMA, "storage": "sqlite"},+ "name": meta.get("name") or name,+ "created_at": meta.get("created_at") or _now(),+ "updated_at": meta.get("updated_at") or _now(),+ }+ )+ write_readme(path)+ return case+++def _wrap_case_folder(case: "Case") -> None:+ """Move the tool's files into `azimut/`.++ What this buys is in `layout.py`: the case root becomes the analyst's, and a+ folder they create there can no longer collide with one of ours.++ Nothing inside is rewritten. Paths are stored relative to the tool root+ (`media/x.png`), so they go on meaning the same thing one level down — the+ database, the sidecars and any bundle are untouched.++ **Only the tool's own entries move** (`layout.UNWRAPPED_ENTRIES`). Nothing+ stopped an analyst from keeping their own folder beside a case before this,+ and carrying it into `azimut/` would contradict the very boundary being+ drawn. Anything unrecognised stays at the case root, which is where it now+ belongs anyway.++ **The manifest moves last.** While it is still at the case root the move is+ unfinished, and that is exactly what `layout.needs_wrapper` reads, so a+ power cut mid-move is resumed rather than half-applied. Runs before anything+ reads the manifest, which is why it is keyed on the filesystem rather than+ on a schema number nobody could load yet.+ """+ root = case.path+ if not layout.needs_wrapper(root):+ return+ tool = layout.tool_root(root)+ tool.mkdir(exist_ok=True)+ ours = [root / name for name in layout.UNWRAPPED_ENTRIES]+ ours += sorted(root.glob(layout.UNWRAPPED_BACKUP_GLOB))+ for entry in dict.fromkeys(ours):+ destination = tool / entry.name+ if not entry.exists() or destination.exists():+ continue # absent, or already carried over by an interrupted run+ shutil.move(str(entry), str(destination))+ shutil.move(str(layout.unwrapped_manifest(root)), str(layout.manifest(root)))+ case._sqlite_cache = _UNSET # the database is at a new path now+++def _flatten_trash(case: "Case") -> None:+ """Make trash groups stop mirroring the case tree.++ A group used to hold ``media/clip.mp4`` under its own directory, stacking+ two case trees and making the trash the longest path Azimut could write —+ on its own enough to pass Windows' 260-character limit. The journal already+ knows where each file came from, so the files move to numbered slots and the+ payload gains the ``slots`` list that pairs with ``files``.++ Idempotent: a file already in its slot is left alone, so an interrupted run+ resumes.+ """+ from .engine.trash import slots_for++ groups = [g["id"] for g in case.list_trash()]+ groups += [g["id"] for g in case.list_incomplete_trash()]+ for group_id in dict.fromkeys(groups):+ group = case.get_trash_group(group_id)+ if group is None:+ continue+ payload = dict(group.get("payload") or {})+ files = [str(rel) for rel in (payload.get("files") or [])]+ slots = slots_for(files)+ root = case.trash_dir / group_id+ for rel, slot in zip(files, slots):+ source = root / rel+ destination = root / slot+ if source.exists() and not destination.exists():+ shutil.move(str(source), str(destination))+ _drop_empty_dirs(root)+ payload["slots"] = slots+ case.update_trash_group(group_id, payload=payload)+++def _drop_empty_dirs(root: Path) -> None:+ """Remove the directories a mirrored group left behind, deepest first."""+ if not root.is_dir():+ return+ for path in sorted(root.rglob("*"), key=lambda p: len(p.parts), reverse=True):+ if path.is_dir() and not any(path.iterdir()):+ path.rmdir()+++def _prune_empty_note_dirs(root: Path, directory: Path) -> None:+ """Drop the folder directories a moved note left empty, up to `notes/`.++ A mirrored tree that keeps every directory a note ever passed through stops+ being a mirror. Stops at `notes/` itself, which is born with the case.++ Both paths are resolved before they are compared. Callers hand in the note+ directory as the case knows it and the note's own parent as+ `resolve_inside` returned it, which are the same directory in two spellings+ the moment a symlink sits anywhere above the workspace: macOS reaches every+ temporary directory through `/var` → `/private/var`, and a workspace under a+ synced or linked folder does the same on any platform. Comparing the two+ spellings makes the containment check say "outside", and the loop that+ should prune then does nothing at all.+ """+ root = root.resolve()+ directory = directory.resolve()+ while directory != root and directory.is_relative_to(root):+ try:+ if any(directory.iterdir()):+ return+ directory.rmdir()+ except OSError:+ return+ directory = directory.parent+++def _move_into(source: Path, destination: Path) -> None:+ """Carry one entry over, skipping what an interrupted run already moved."""+ if not source.exists() or destination.exists():+ return+ ensure_dir(destination.parent)+ shutil.move(str(source), str(destination))+++def _hide_the_machinery(case: "Case") -> None:+ """Move what only Azimut can read out of the way.++ The rule is in `layout.py`: visible means openable in another program.+ Applied here it moves the database into `.data/`, the media sidecars into+ `media/.meta/`, the proof specs and their pasted assets into+ `proofs/.meta/`, and renames `inspect/` and `search/` to dot-directories.++ `exports/` is the one that changes meaning rather than place. It held post+ drafts — its name was wrong — so the drafts become `.drafts/` and a fresh,+ empty `exports/` is left behind for what the word actually promises.++ This is the first folder step that rewrites *stored* paths: a proof's+ ``spec``, a session's ``spec`` and a post's ``draft`` all name a directory+ that just moved.+ """+ root = case.path+ tool = layout.tool_root(root)++ # The database first, and with no connection open: on Windows an open file+ # cannot be moved. Nothing holds one here — every backend connection is+ # scoped to its own `with` — but the cached handle is dropped anyway so the+ # next access re-resolves against the new path.+ _move_into(tool / layout.PRE_HIDDEN_DB, layout.database(root))+ case._sqlite_cache = _UNSET++ # Sidecars: `media/clip.mp4.azimut.json` -> `media/.meta/clip.mp4.json`.+ media_dir = layout.media(root)+ if media_dir.is_dir():+ suffix = layout.PRE_HIDDEN_SIDECAR_SUFFIX+ for sidecar in sorted(media_dir.glob(f"*{suffix}")):+ name = sidecar.name[: -len(suffix)]+ _move_into(sidecar, case.resolve_inside(layout.sidecar_rel(name)))++ # Proof specs and pasted assets join them; the rendered PNG stays visible.+ proofs_dir = layout.subdir(root, "proofs")+ if proofs_dir.is_dir():+ for spec in sorted(proofs_dir.glob("*.json")):+ _move_into(spec, case.resolve_inside(layout.proof_spec_rel(spec.stem)))+ for assets in sorted(proofs_dir.glob("*.assets")):+ _move_into(assets, case.resolve_inside(layout.proof_assets_rel(assets.stem)))++ # The sidecars just moved, and the one-time browse-index backfill may have+ # already run against their old location. Forget it, so the reopen below+ # rebuilds the index from where they are now.+ store = case._sqlite+ if store is not None:+ store.forget_media_index()+ case._sqlite_cache = _UNSET++ for old, new in layout.PRE_HIDDEN_DIRS.items():+ _move_into(tool / old, tool / new)+ for directory in layout.content_dirs(root):+ ensure_dir(directory)++ _rewrite_moved_paths(case)+++#: entity type -> (attribute holding a case-relative path, old prefix, rebuild).+_MOVED_ATTRS: dict[str, tuple[str, str, Callable[[str], str]]] = {+ "proof": ("spec", "proofs/", layout.proof_spec_rel),+ "inspect-session": ("spec", "inspect/", layout.session_rel),+ "post": ("draft", "exports/", layout.draft_rel),+}+++def _rewrite_moved_paths(case: "Case") -> None:+ """Point the graph at the directories the migration just renamed.++ Only entities still naming the old location are touched, so a re-run after+ an interruption rewrites nothing twice.+ """+ for entity in case.list_entities():+ rule = _MOVED_ATTRS.get(str(entity.get("type") or ""))+ if rule is None:+ continue+ attribute, prefix, rebuild = rule+ current = (entity.get("attrs") or {}).get(attribute)+ if not isinstance(current, str) or not current.startswith(prefix):+ continue+ stem = Path(current).stem+ case.update_entity(entity["id"], {"attrs": {attribute: rebuild(stem)}})+++def _name_notes_after_their_titles(case: "Case") -> None:+ """Make notes stop being named after their entity id.++ `notes/e_03aeb50d41.md` was visible and illegible — in the way without being+ readable. Every other document already follows "the name is the filename";+ notes were the only holdout, and only because they are generic entities with+ their path hardcoded rather than a tool of their own.++ Titles are not unique, so a collision inside one folder takes a numbered+ suffix, exactly as a new note would.++ An empty patch is the whole migration: `update_entity` already moves a note+ whose title or folder no longer matches its filename. Once moved, the+ current path is reserved for that note, so a resumed pass leaves the path+ and any collision suffix unchanged.+ """+ for entity in case.list_entities():+ if entity.get("type") == "note":+ case.update_entity(entity["id"], {})+++def _leave_a_readme(case: "Case") -> None:+ """Teach a case that predates the free zone which half is whose.++ The wrapper gave the analyst the case root three schemas ago; nothing on+ disk told them. This is the step that does, and it is the only migration+ here that writes into their half of the folder rather than ours.+ """+ write_readme(case.path)+++def _align_visible_names(case: "Case") -> None:+ """Make every analyst-visible filename stem the name Azimut displays.++ Uploads belong to the analyst, so their existing filename wins. Downloads,+ captures and derived media belong to an Azimut save gate, so their stored+ title wins and machine timestamps/remote ids remain provenance. Named+ documents run through their existing rename hooks, which also repairs a+ Details edit that changed only the graph label.+ """+ from .engine import media as media_engine++ media_engine.recover_media_rename(case)+ for item in list(case.list_media_items()):+ path = str(item.get("path") or "")+ if not path:+ continue+ source: dict[str, Any] = item["source"] if isinstance(item.get("source"), dict) else {}+ entity = case.find_entity(attr="path", value=path)+ if source.get("type") == "upload":+ desired = Path(path).stem+ else:+ desired = str(item.get("title") or (entity or {}).get("label") or Path(path).stem)+ # `Case.migrate` already owns the case lock. An older case cannot have+ # live work in this process; waiting here would deadlock a test that+ # deliberately rewinds a just-created case while its worker is draining.+ media_engine.rename_media(case, path, desired, settle_worker=False)++ for entity in list(case.list_entities()):+ if entity.get("type") in {"note", "proof", "inspect-session", "post"}:+ case.update_entity(entity["id"], {"label": entity.get("label") or ""})+++def _normalize_case_layout(case: "Case") -> None:+ """Bring every unreleased folder checkpoint to the final layout.++ Schemas 4 through 7 were useful while building the layout, but no released+ Azimut wrote them. One normalizer accepts schema 3 and those development+ states, applies every operation in dependency order, then the runner stamps+ the current schema once. Each operation is idempotent, so an interrupted+ pass restarts here without guessing which line completed.+ """+ _wrap_case_folder(case)+ _flatten_trash(case)+ _hide_the_machinery(case)+ _name_notes_after_their_titles(case)+ _leave_a_readme(case)+ _align_visible_names(case)+++def open_workspace() -> None:+ """Bring the workspace at the current root into a state routes can serve.++ Startup does this once, and so does anything that changes where the root is+ — adopting a folder or finishing a move lands on cases this process has+ never looked at, which may have been written by an older Azimut. Each step+ is best-effort on purpose: housekeeping must never be the reason the app+ won't open.++ Imports are local because the modules below sit above this one; calling them+ at import time would close the circle.+ """+ from .engine import bundles, scrapers, workqueue++ config.ensure_workspace()+ scrapers.activate()+ Case.migrate_all()+ for housekeeping in (Case.cleanup_scratch, bundles.cleanup_uploads, workqueue.recover_all):+ try:+ housekeeping()+ except Exception: # noqa: BLE001 - see the docstring+ logger.warning("workspace housekeeping step failed", exc_info=True)+++_FINAL_LAYOUT_MIGRATION = FolderMigration(CASE_SCHEMA, _normalize_case_layout)+FOLDER_MIGRATIONS.update(+ {version: _FINAL_LAYOUT_MIGRATION for version in range(STORAGE_SCHEMA, CASE_SCHEMA)}+)++if TYPE_CHECKING:# `Case` conforms to `CaseRepository` (it delegates the graph to `SqliteCase`).# This fails type-check if a graph method ever drifts from the boundarydiff --git a/tests/bigcase.py b/tests/bigcase.pyindex 0b67f3d..34c6892 100644--- a/tests/bigcase.py+++ b/tests/bigcase.py@@ -16,8 +16,10 @@ from dataclasses import dataclass, fieldfrom datetime import datetime, timedelta, timezonefrom azimut import config-from azimut.engine.media import SIDECAR_SUFFIX, THUMB_DIR-from azimut.workspace import CASE_SUBDIRS, Case, _slugify+from azimut.engine.media import THUMB_DIR+from azimut.layout import PRE_HIDDEN_SIDECAR_SUFFIX+from legacy_case import LEGACY_SUBDIRS+from azimut.workspace import Case, _slugify# Well-known + deliberately unknown types, so the fixture exercises the "unknown# entity/link types stay valid" rule the ontology promises.@@ -95,7 +97,9 @@ def build_big_case(parent.mkdir(parents=True, exist_ok=True)path = parent / _slugify(name)path.mkdir()- for sub in CASE_SUBDIRS:+ # The flat, unwrapped shape on purpose: this is a legacy import source, and+ # opening it is what exercises the wrapper migration.+ for sub in LEGACY_SUBDIRS:(path / sub).mkdir()(path / "notes.md").write_text(f"# {name}\n\n", encoding="utf-8")case = Case(path)@@ -126,7 +130,7 @@ def build_big_case(# ~30% unfiled, the rest spread across the tree.return None if rng.random() < 0.3 else rng.choice(_FOLDER_TREE)- media_dir = case.subdir("media")+ media_dir = path / "media" # flat: this fixture predates the wrapperthumb_dir = media_dir / THUMB_DIR# -- media entities (+ sidecars, placeholder bytes, thumbnail states) -----@@ -161,7 +165,7 @@ def build_big_case("source": {"url": attrs.get("source_url")} if "source_url" in attrs else {},"thumbnail": f"media/{THUMB_DIR}/{fname}.jpg",}- (media_dir / (fname + SIDECAR_SUFFIX)).write_text(+ (media_dir / (fname + PRE_HIDDEN_SIDECAR_SUFFIX)).write_text( # legacy shapejson.dumps(sidecar, ensure_ascii=False), encoding="utf-8")roll = rng.random()@@ -175,12 +179,12 @@ def build_big_case(summary.media = media# -- file-backed notes ----------------------------------------------------- note_dir = case.note_dir+ note_dir = path / "notes"note_dir.mkdir(parents=True, exist_ok=True)for i in range(notes):eid = f"e_note_{i:06d}"rel = f"notes/{eid}.md"- (case.path / rel).write_text(f"# Note {i}\n\nSynthetic body {i}.\n", encoding="utf-8")+ (path / rel).write_text(f"# Note {i}\n\nSynthetic body {i}.\n", encoding="utf-8")attrs = {"folder": pick_folder() or "", "path": rel}add({"id": eid, "type": "note", "label": f"Note {i}", "attrs": attrs})summary.notes = notes@@ -280,7 +284,8 @@ def build_big_case("entities": rows,"links": links_rows,}- case.json_path.write_text(+ # `path` is shadowed by the folder loop above; the case root is `case.path`.+ (case.path / "case.json").write_text( # still the unwrapped locationjson.dumps(data, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")diff --git a/tests/conftest.py b/tests/conftest.pyindex 1838aab..f0c2d47 100644--- a/tests/conftest.py+++ b/tests/conftest.py@@ -3,9 +3,31 @@ import tempfileimport pytestfrom fastapi.testclient import TestClient+from azimut import configfrom azimut.engine import geo[email protected](autouse=True)+def isolated_workspace_pointer(monkeypatch, tmp_path_factory):+ """No test may read or write this machine's real workspace.++ Two addresses have to be redirected, because the app resolves its root from+ both. The pointer deliberately lives outside the workspace, so a temporary+ ``AZIMUT_HOME`` does not contain it: without this, one test writing a pointer+ would re-point the developer's own Azimut at a directory pytest deletes on+ the way out. ``DEFAULT_ROOT`` is the fallback the app lands on the moment a+ test clears that pointer, and opening a workspace migrates every case in it —+ so leaving it at ``~/Azimut`` would run the suite's migrations over the+ developer's real cases.+ """+ directory = tmp_path_factory.mktemp("pointer")+ monkeypatch.setattr(config, "_pointer_dir", lambda: directory)+ monkeypatch.setattr(config, "DEFAULT_ROOT", tmp_path_factory.mktemp("default-root"))+ config.forget_workspace_root()+ yield+ config.forget_workspace_root()++@pytest.fixture(autouse=True)def offline_reverse_geocode(monkeypatch):"""Nominatim is unreachable unless a test says otherwise.@@ -33,6 +55,25 @@ def _let_the_worker_finish() -> None:workqueue.wait_until_idle(timeout=10)+def _settle_before_the_workspace_goes() -> None:+ """Everything that must let go of a throwaway workspace before it is deleted.++ Both holds are file handles, and Windows refuses to delete a file another+ handle has open, so a test that keeps one fails the *teardown* — sometimes+ its own, sometimes a later test's. The worker is waited out; the workspace+ lock is released, which is what closes its handle.++ Not an autouse fixture on purpose: an autouse fixture is set up before the+ one that owns the temporary directory and therefore torn down *after* it, so+ the release would come too late to be the point of it. Called from the+ fixtures that own the directory instead, where the order is guaranteed.+ """+ from azimut.engine import workspacelock++ _let_the_worker_finish()+ workspacelock.release()++@pytest.fixture()def tmp_workspace(monkeypatch):"""A throwaway workspace root — for engine tests that read/write settings."""@@ -41,7 +82,7 @@ def tmp_workspace(monkeypatch):try:yield homefinally:- _let_the_worker_finish()+ _settle_before_the_workspace_goes()@pytest.fixture()@@ -57,4 +98,4 @@ def client(monkeypatch):with TestClient(create_app(), base_url="http://127.0.0.1") as c:yield cfinally:- _let_the_worker_finish()+ _settle_before_the_workspace_goes()diff --git a/tests/fullcase.py b/tests/fullcase.pyindex 7f30f8c..ddf6c61 100644--- a/tests/fullcase.py+++ b/tests/fullcase.py@@ -21,6 +21,7 @@ import iofrom dataclasses import dataclass, fieldfrom PIL import Image+from azimut import layoutdef _png(size: tuple[int, int] = (80, 60), color: tuple[int, int, int] = (120, 60, 30)) -> bytes:@@ -43,6 +44,7 @@ class FullCase:proof_asset: str = ""draft: str = ""note_id: str = ""+ note: str = "" # its case-relative pathplace_id: str = ""grid: str = ""entity_types: set[str] = field(default_factory=set)@@ -110,7 +112,7 @@ def build_full_case(client, name: str = "Full case") -> FullCase:},)assert session.status_code == 200, session.text- full.session = f"inspect/{session.json()['name']}.json"+ full.session = f".inspect/{session.json()['name']}.json"# -- a place, and a relation to the photo ---------------------------------place = client.post(@@ -147,7 +149,7 @@ def build_full_case(client, name: str = "Full case") -> FullCase:)assert proof.status_code == 200, proof.textfull.proof = proof.json()["spec_path"]- full.proof_asset = f"proofs/{proof.json()['name']}.assets/{asset_name}"+ full.proof_asset = f"{layout.proof_assets_rel(proof.json()['name'])}/{asset_name}"# -- post: derived from the proof and the photo ---------------------------draft = client.post(@@ -168,6 +170,7 @@ def build_full_case(client, name: str = "Full case") -> FullCase:)assert note.status_code == 200, note.textfull.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"})grid = client.put(@@ -187,7 +190,7 @@ 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"+ full.grid = f".search/{grid.json()['name']}.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.diff --git a/tests/legacy_case.py b/tests/legacy_case.pyindex 209b7b6..8b34bc2 100644--- a/tests/legacy_case.py+++ b/tests/legacy_case.py@@ -1,20 +1,25 @@-"""Write a legacy json-storage case on disk, for the migration tests.--`Case.create` only makes SQLite cases now — the live in-file JSON graph backend-was removed once every case runs on `case.db`. The JSON→SQLite importer and the-on-open migration stay, so a legacy json case still has to be openable; it just-never originates from the app any more, only from an older release's files. This-helper writes that file (schema ``JSON_SCHEMA`` by default) so `Case.open` can-migrate it, and the converter tests can read it.+"""Cases in the shapes older releases wrote them, for whatever has to still+read one: the migration tests, and the bundle tests that prove a bundle+exported by an earlier release still imports.++Two shapes, and they are different things. `write_legacy_json_case` writes a+case whose *graph* lives inline in `case.json` — `Case.create` only makes SQLite+cases now, so that file never originates from the app any more, only from an+older release. `rewind_case` takes a current case and reconstructs one of the+unreleased folder checkpoints; `unwrap_case` is its schema-4 shorthand."""from __future__ import annotationsimport json+import shutilfrom typing import Any-from azimut import config-from azimut.workspace import CASE_SUBDIRS, JSON_SCHEMA, Case, _now, _slugify+from azimut import config, layout, workspace+from azimut.workspace import JSON_SCHEMA, Case, _now, _slugify++#: The content directories as they were before the `azimut/` wrapper.+LEGACY_SUBDIRS = ("media", "notes", "proofs", "exports", "inspect", "search")def write_legacy_json_case(@@ -33,7 +38,11 @@ def write_legacy_json_case(parent.mkdir(parents=True, exist_ok=True)path = parent / _slugify(name)path.mkdir()- for sub in CASE_SUBDIRS:+ # Deliberately the flat, unwrapped shape: the tool's files sit at the case+ # root, the way every release before the `azimut/` wrapper wrote them. This+ # is a historical format, so it is spelled out here rather than asked of+ # `layout` — which now answers for the current one.+ for sub in LEGACY_SUBDIRS:(path / sub).mkdir()(path / "notes.md").write_text(f"# {name}\n\n", encoding="utf-8")data = {@@ -49,3 +58,141 @@ def write_legacy_json_case(json.dumps(data, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")return Case(path)+++def read_legacy_manifest(case: Case) -> dict[str, Any]:+ """The manifest of a case that has not been opened yet.++ An unwrapped case keeps `case.json` at its own root, so `Case.read()` cannot+ find it — that is the whole reason the wrapper migration runs before+ anything reads the manifest. A test asserting on the *fixture's* content+ rather than on the migrated result reads it from here.+ """+ return json.loads((case.path / "case.json").read_text(encoding="utf-8"))+++def legacy_manifest_path(case: Case):+ """Where an unopened case still keeps its manifest."""+ return case.path / "case.json"+++def _rewind_notes(case: Case) -> None:+ for entity in case.list_entities():+ if entity.get("type") != "note":+ continue+ current = (entity.get("attrs") or {}).get("path")+ if not isinstance(current, str):+ continue+ legacy = f"notes/{entity['id']}.md"+ source = case.resolve_inside(current)+ destination = case.resolve_inside(legacy)+ destination.parent.mkdir(parents=True, exist_ok=True)+ if source.exists() and source != destination:+ shutil.move(str(source), str(destination))+ case.update_entity(entity["id"], {"attrs": {"path": legacy}})+ notes = case.note_dir+ for directory in sorted(+ (path for path in notes.rglob("*") if path.is_dir()),+ key=lambda path: len(path.parts),+ reverse=True,+ ):+ if not any(directory.iterdir()):+ directory.rmdir()+++def _rewind_moved_paths(case: Case) -> None:+ rules = {+ "proof": ("spec", "proofs/.meta/", "proofs/"),+ "inspect-session": ("spec", ".inspect/", "inspect/"),+ "post": ("draft", ".drafts/", "exports/"),+ }+ for entity in case.list_entities():+ rule = rules.get(str(entity.get("type") or ""))+ if rule is None:+ continue+ attribute, current_prefix, legacy_prefix = rule+ current = (entity.get("attrs") or {}).get(attribute)+ if not isinstance(current, str) or not current.startswith(current_prefix):+ continue+ case.update_entity(+ entity["id"],+ {"attrs": {attribute: legacy_prefix + current.removeprefix(current_prefix)}},+ )+++def _rewind_trash(case: Case) -> None:+ groups = [*case.list_trash(), *case.list_incomplete_trash()]+ for group in groups:+ payload = dict(group.get("payload") or {})+ files = [str(path) for path in payload.get("files") or []]+ slots = [str(path) for path in payload.get("slots") or []]+ if len(files) != len(slots):+ continue+ root = case.trash_dir / group["id"]+ for relative, slot in zip(files, slots):+ source = root / slot+ destination = root / relative+ if source.exists():+ destination.parent.mkdir(parents=True, exist_ok=True)+ shutil.move(str(source), str(destination))+ payload.pop("slots", None)+ case.update_trash_group(group["id"], payload=payload)+++def _rewind_hidden_layout(case: Case) -> None:+ tool = case.tool_root+ _rewind_moved_paths(case)+ shutil.move(str(layout.database(case.path)), str(tool / layout.PRE_HIDDEN_DB))+ layout.data_dir(case.path).rmdir()+ meta = tool / "media" / layout.META_DIR+ if meta.is_dir():+ for sidecar in sorted(meta.iterdir()):+ name = sidecar.name.removesuffix(".json")+ shutil.move(+ str(sidecar),+ str(tool / "media" / (name + layout.PRE_HIDDEN_SIDECAR_SUFFIX)),+ )+ meta.rmdir()+ proof_meta = tool / "proofs" / layout.META_DIR+ if proof_meta.is_dir():+ for entry in sorted(proof_meta.iterdir()):+ shutil.move(str(entry), str(tool / "proofs" / entry.name))+ proof_meta.rmdir()+ for old, new in layout.PRE_HIDDEN_DIRS.items():+ if (tool / old).is_dir():+ (tool / old).rmdir() # the empty `exports/` the migration left+ shutil.move(str(tool / new), str(tool / old))+ case._sqlite_cache = workspace._UNSET+++def rewind_case(case: Case, schema: int) -> None:+ """Reconstruct one folder checkpoint from the final schema-9 layout.++ These shapes were never released, but the consolidated normalizer accepts+ them so a case opened by a development build cannot be stranded.+ """+ if not workspace.STORAGE_SCHEMA <= schema < workspace.CASE_SCHEMA:+ raise ValueError("folder checkpoint must be between storage and current schema")++ layout.readme(case.path).unlink(missing_ok=True)+ if schema < workspace.STORAGE_SCHEMA + 4:+ _rewind_notes(case)+ if schema < workspace.STORAGE_SCHEMA + 3:+ _rewind_hidden_layout(case)+ if schema < workspace.STORAGE_SCHEMA + 1:+ _rewind_trash(case)++ manifest = case.read()+ manifest["azimut"]["schema"] = schema+ case._write_json(manifest)+ if schema < workspace.STORAGE_SCHEMA + 2:+ tool = case.tool_root+ for entry in sorted(tool.iterdir()):+ shutil.move(str(entry), str(case.path / entry.name))+ tool.rmdir()+ case._sqlite_cache = workspace._UNSET+++def unwrap_case(case: Case) -> None:+ """Put a case back at the checkpoint immediately before the wrapper."""+ rewind_case(case, workspace.STORAGE_SCHEMA + 1)diff --git a/tests/test_artifacts.py b/tests/test_artifacts.pyindex 3bbb766..046ddcd 100644--- a/tests/test_artifacts.py+++ b/tests/test_artifacts.py@@ -14,6 +14,7 @@ there.from pathlib import Pathimport fullcase+from azimut import layoutfrom azimut.engine import artifactsfrom azimut.workspace import Case@@ -67,7 +68,9 @@ def test_deleting_everything_returns_the_case_to_its_birth_state(client):client.delete(f"/api/cases/{full.case_id}/trash")emptied = Case.open(full.case_id)- assert tree(emptied.path) == tree(born.path)+ # The tool root, not the case folder: what the analyst keeps beside it is+ # theirs, and a gate on files Azimut never wrote would be meaningless.+ assert tree(emptied.tool_root) == tree(born.tool_root)def test_deleting_a_proof_takes_its_pasted_images(client):@@ -111,6 +114,6 @@ def test_the_registry_answers_for_one_media_and_its_companions(client):owned = artifacts.owned(case, entity)assert owned[0] == full.photo- assert full.photo + ".azimut.json" in owned+ assert layout.sidecar_rel(full.photo) in ownedassert all(not rel.startswith(CACHE) for rel in owned)assert all(rel.startswith(CACHE) for rel in artifacts.caches(case, entity))diff --git a/tests/test_bigcase.py b/tests/test_bigcase.pyindex e0f049f..efdfa46 100644--- a/tests/test_bigcase.py+++ b/tests/test_bigcase.py@@ -10,7 +10,9 @@ import jsonfrom azimut.engine import links as link_enginefrom azimut.workspace import Case+from azimut.layout import PRE_HIDDEN_SIDECAR_SUFFIXfrom bigcase import build_big_case+from legacy_case import read_legacy_manifestdef _build(**kw):@@ -35,7 +37,7 @@ def test_builds_a_case_that_opens_with_matching_counts(tmp_workspace):def test_folder_tree_is_well_formed(tmp_workspace):case, _ = _build()- data = case.read()+ data = read_legacy_manifest(case)folders = set(data["folders"])# every folder an entity is filed under exists as a nodefor entity in data["entities"]:@@ -51,7 +53,9 @@ def test_folder_tree_is_well_formed(tmp_workspace):def test_notes_are_file_backed_not_inline(tmp_workspace):case, _ = _build()- note_entities = [e for e in case.read()["entities"] if e["type"] == "note"]+ note_entities = [+ e for e in read_legacy_manifest(case)["entities"] if e["type"] == "note"+ ]assert note_entitiesfor note in note_entities:assert "content" not in note["attrs"] # body lives on disk, not in the graph@@ -63,9 +67,9 @@ def test_media_sidecars_present_and_some_files_missing(tmp_workspace):case, summary = _build(seed=7)# the fixture deliberately models missing source filesassert summary.media_files_missing > 0- media_dir = case.subdir("media")+ media_dir = case.path / "media" # not opened yet, so still unwrappedpresent = list(media_dir.glob("img_*.jpg"))- sidecars = list(media_dir.glob("*.azimut.json"))+ sidecars = list(media_dir.glob("*" + PRE_HIDDEN_SIDECAR_SUFFIX)) # legacy fixtureassert present and len(sidecars) == len(present)assert len(present) == summary.media - summary.media_files_missing@@ -91,7 +95,7 @@ def test_generation_is_deterministic_for_a_seed(tmp_workspace):notes=10, artifacts=20, seed=42)b, _ = build_big_case(name="Case B", entities=200, links=250, media=60,notes=10, artifacts=20, seed=42)- da, db = a.read(), b.read()+ da, db = read_legacy_manifest(a), read_legacy_manifest(b)# identical graph regardless of the case nameassert json.dumps(da["entities"]) == json.dumps(db["entities"])assert json.dumps(da["links"]) == json.dumps(db["links"])diff --git a/tests/test_bulk_trash.py b/tests/test_bulk_trash.pyindex a1fca66..68a6813 100644--- a/tests/test_bulk_trash.py+++ b/tests/test_bulk_trash.py@@ -62,7 +62,11 @@ def test_recovery_finishes_a_partially_moved_restore(tmp_workspace):note = case.create_note("Note", "", "kept")deleted = delete_entities_deep(case, [note["id"]])rel = note["attrs"]["path"]- source = case.trash_dir / deleted["trash"] / rel+ # The file waits under its numbered slot, and the journal is what pairs the+ # two — so a half-finished restore is simulated by moving the slot back.+ payload = case.get_trash_group(deleted["trash"])["payload"]+ slot = payload["slots"][payload["files"].index(rel)]+ source = case.trash_dir / deleted["trash"] / slotdestination = case.resolve_inside(rel)case.update_trash_group(deleted["trash"], state="restoring")diff --git a/tests/test_bundles.py b/tests/test_bundles.pyindex 0121d8a..8e34825 100644--- a/tests/test_bundles.py+++ b/tests/test_bundles.py@@ -13,7 +13,7 @@ from types import SimpleNamespaceimport pytest-from azimut import config+from azimut import config, layoutfrom azimut.engine import bundles, workqueuefrom azimut.workspace import Case@@ -25,10 +25,10 @@ def bundle_case(tmp_workspace, monkeypatch) -> Case:case.create_note("Witness", "", content="# Witness\n")(case.trash_dir / "old").mkdir(parents=True)(case.trash_dir / "old" / "gone.txt").write_text("gone", encoding="utf-8")- (case.path / "media" / ".thumbs").mkdir()- (case.path / "media" / ".thumbs" / "cache.jpg").write_bytes(b"cache")- (case.path / "media" / ".dl").mkdir()- (case.path / "media" / ".dl" / "partial").write_bytes(b"partial")+ (case.subdir("media") / ".thumbs").mkdir()+ (case.subdir("media") / ".thumbs" / "cache.jpg").write_bytes(b"cache")+ (case.subdir("media") / ".dl").mkdir()+ (case.subdir("media") / ".dl" / "partial").write_bytes(b"partial")case.add_trash_group("old",label="Gone",@@ -70,15 +70,20 @@ def test_plain_bundle_has_ordered_manifests_and_a_clean_database(bundle_case):names = archive.namelist()assert names[0] == bundles.HEADER_NAMEassert names[-1] == bundles.MANIFEST_NAME- assert not any(name.startswith(".trash/") for name in names)- assert not any(name.startswith("media/.thumbs/") for name in names)- assert not any(name.startswith("media/.dl/") for name in names)+ prefix = f"{bundles.BUNDLE_ROOT}/azimut/"+ assert not any(name.startswith(prefix + ".trash/") for name in names)+ assert not any(name.startswith(prefix + "media/.thumbs/") for name in names)+ assert not any(name.startswith(prefix + "media/.dl/") for name in names)manifest = json.loads(archive.read(bundles.MANIFEST_NAME))assert [member["path"] for member in manifest["members"]] == names[:-1]extracted = config.bundles_dir() / "clean.db"- extracted.write_bytes(archive.read("case.db"))+ member = (+ f"{bundles.BUNDLE_ROOT}/"+ f"{bundle_case.db_path.relative_to(bundle_case.path).as_posix()}"+ )+ extracted.write_bytes(archive.read(member))with closing(sqlite3.connect(extracted)) as conn:assert conn.execute("SELECT COUNT(*) FROM trash").fetchone()[0] == 0assert conn.execute(@@ -111,7 +116,7 @@ def test_sealed_bundle_hides_the_zip_and_rejects_a_wrong_password(bundle_case):def test_sealed_chunks_detect_truncation_before_any_case_swap(bundle_case):payload = os.urandom(2 * bundles.CHUNK_SIZE + 123)- (bundle_case.path / "media" / "large.bin").write_bytes(payload)+ (bundle_case.subdir("media") / "large.bin").write_bytes(payload)exported = bundles.export_case(bundle_case, password="secret")truncated = config.bundles_dir() / "truncated.azimut.enc"truncated.write_bytes(exported.read_bytes()[:-1])@@ -137,12 +142,68 @@ def test_export_import_round_trip_creates_a_new_case(bundle_case, password):assert [entity["label"] for entity in imported.list_entities()] == ["Witness"]note_path = imported.list_entities()[0]["attrs"]["path"]assert imported.resolve_inside(note_path).read_text(encoding="utf-8") == "# Witness\n"- with closing(sqlite3.connect(imported.path / "case.db")) as conn:+ with closing(sqlite3.connect(imported.db_path)) as conn:meta = dict(conn.execute("SELECT key, value FROM meta"))assert meta["origin_case_id"] == bundle_case.idassert meta["imported_at"]+def test_format_one_bundle_still_imports(bundle_case):+ """The new `case/` prefix must not strand bundles written before it."""+ exported = bundles.export_case(bundle_case)+ legacy = config.bundles_dir() / "legacy-format-one.azimut.zip"+ tool_prefix = f"{bundles.BUNDLE_ROOT}/azimut/"+ with zipfile.ZipFile(exported) as source:+ header = json.loads(source.read(bundles.HEADER_NAME))+ members = [+ (name.removeprefix(tool_prefix), source.read(name))+ for name in source.namelist()+ if name.startswith(tool_prefix)+ ]+ header["format_version"] = 1+ header["total_size"] = sum(len(body) for _, body in members)+ records = []+ with zipfile.ZipFile(legacy, "w") as archive:+ bundles._write_bytes(+ archive,+ bundles.HEADER_NAME,+ bundles._json_bytes(header),+ records,+ )+ for name, body in members:+ bundles._write_bytes(archive, name, body, records)+ archive.writestr(+ bundles._zip_info(bundles.MANIFEST_NAME, compressed=True),+ bundles._json_bytes({"format_version": 1, "members": records}),+ )++ destination = Case.create("Legacy format import")+ imported = Case.open(bundles.import_into(destination, legacy)["case_id"])++ assert imported.read()["name"] == "Legacy format import"+ assert [entity["label"] for entity in imported.list_entities()] == ["Witness"]+ assert imported.read_note(imported.list_entities()[0]["id"]) == "# Witness\n"+++def test_import_reapplies_the_hidden_attribute_to_the_data_directory(+ bundle_case, monkeypatch+):+ exported = bundles.export_case(bundle_case)+ destination = Case.create("Hidden database import")+ ensured = []+ real_ensure_dir = bundles.ensure_dir++ def remember(path):+ ensured.append(path)+ return real_ensure_dir(path)++ monkeypatch.setattr(bundles, "ensure_dir", remember)++ imported = Case.open(bundles.import_into(destination, exported)["case_id"])++ assert layout.data_dir(imported.path) in ensured++def test_export_import_round_trip_keeps_confirmed_relations(bundle_case):media = bundle_case.add_entity("media",@@ -172,6 +233,52 @@ 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_the_analysts_free_zone(bundle_case):+ materials = bundle_case.path / "Source material" / "Interview"+ materials.mkdir(parents=True)+ (materials / "transcript.txt").write_text("Unedited source\n", encoding="utf-8")+ # These names belong to the ZIP container too. The `case/` member prefix+ # keeps them valid in the analyst's half of the folder.+ (bundle_case.path / bundles.HEADER_NAME).write_text("analyst file\n", encoding="utf-8")+ (bundle_case.path / bundles.MANIFEST_NAME).write_text("analyst file\n", encoding="utf-8")++ exported = bundles.export_case(bundle_case)+ with zipfile.ZipFile(exported) as archive:+ assert (+ f"{bundles.BUNDLE_ROOT}/Source material/Interview/transcript.txt"+ in archive.namelist()+ )+ assert f"{bundles.BUNDLE_ROOT}/{bundles.HEADER_NAME}" in archive.namelist()+ assert f"{bundles.BUNDLE_ROOT}/{bundles.MANIFEST_NAME}" in archive.namelist()+ destination = Case.create(bundles.imported_name("Source case"))+ imported = Case.open(bundles.import_into(destination, exported)["case_id"])++ assert (+ imported.path / "Source material" / "Interview" / "transcript.txt"+ ).read_text(encoding="utf-8") == "Unedited source\n"+ assert (imported.path / bundles.HEADER_NAME).read_text(encoding="utf-8") == "analyst file\n"+ assert (imported.path / bundles.MANIFEST_NAME).read_text(encoding="utf-8") == "analyst file\n"+++def test_export_refuses_a_symbolic_link_in_the_free_zone(bundle_case, tmp_path):+ outside = tmp_path / "outside.txt"+ outside.write_text("must not be followed\n", encoding="utf-8")+ link = bundle_case.path / "linked-source.txt"+ try:+ link.symlink_to(outside)+ except OSError:+ pytest.skip("symbolic links are unavailable on this filesystem")++ with pytest.raises(bundles.BundleError, match="symbolic link"):+ bundles.export_case(bundle_case)++[email protected]("name", ["Azimut", "AZIMUT"])+def test_free_zone_refuses_a_portable_tool_folder_collision(name):+ with pytest.raises(bundles.BundleError, match="collides"):+ bundles._check_free_name(name)++def test_manifest_is_an_allowlist_not_a_hint(bundle_case):exported = bundles.export_case(bundle_case)tampered = config.bundles_dir() / "tampered.azimut.zip"@@ -192,7 +299,11 @@ def test_manifest_sizes_are_checked_before_extraction(bundle_case):with zipfile.ZipFile(exported) as source, zipfile.ZipFile(tampered, "w") as target:infos = source.infolist()manifest = json.loads(source.read(bundles.MANIFEST_NAME))- record = next(item for item in manifest["members"] if item["path"] == "case.db")+ db_member = (+ f"{bundles.BUNDLE_ROOT}/"+ f"{bundle_case.db_path.relative_to(bundle_case.path).as_posix()}"+ )+ record = next(item for item in manifest["members"] if item["path"] == db_member)record["size"] += 1for info in infos[:-1]:target.writestr(info, source.read(info))@@ -205,6 +316,27 @@ def test_manifest_sizes_are_checked_before_extraction(bundle_case):assert destination.list_entities() == []+def test_import_refuses_a_bundle_member_marked_as_a_symbolic_link(bundle_case):+ free_file = bundle_case.path / "source.txt"+ free_file.write_text("source\n", encoding="utf-8")+ exported = bundles.export_case(bundle_case)+ tampered = config.bundles_dir() / "symlink.azimut.zip"+ member_name = f"{bundles.BUNDLE_ROOT}/source.txt"+ with zipfile.ZipFile(exported) as source, zipfile.ZipFile(tampered, "w") as target:+ for info in source.infolist():+ body = source.read(info)+ if info.filename == member_name:+ info.external_attr = 0o120777 << 16+ target.writestr(info, body)++ destination = Case.create("Symlink import")+ with pytest.raises(bundles.BundleError, match="symbolic link"):+ bundles.import_into(destination, tampered)++ assert destination.path.exists()+ assert destination.list_entities() == []++def test_bundle_header_bounds_names_and_total_sizes():base = {"format_version": bundles.BUNDLE_FORMAT,@@ -274,7 +406,7 @@ def test_staged_upload_stops_before_consuming_the_disk_reserve(tmp_workspace, monkeypatch):total = 10 * 1024 * 1024 * 1024- reserve = bundles._disk_reserve(total)+ reserve = bundles.disk_reserve(total)monkeypatch.setattr(bundles.shutil,"disk_usage",@@ -290,7 +422,7 @@ def test_staged_upload_stops_before_consuming_the_disk_reserve(def test_export_stops_before_consuming_the_disk_reserve(bundle_case, monkeypatch):total = 10 * 1024 * 1024 * 1024- reserve = bundles._disk_reserve(total)+ reserve = bundles.disk_reserve(total)monkeypatch.setattr(bundles.shutil,"disk_usage",@@ -304,9 +436,16 @@ def test_export_stops_before_consuming_the_disk_reserve(bundle_case, monkeypatchdef test_every_top_level_case_entry_has_a_bundle_decision(bundle_case):+ """The drift gate: a new directory in the case ships in the bundle or is+ listed as deliberately left behind, never silently dropped.++ It reads the tool root, because that is what a bundle carries and how it+ names its members. What sits beside it in the case folder is the analyst's+ and answers to its own rule.+ """assert all(bundles.classify_case_entry(path.name) is not None- for path in bundle_case.path.iterdir()+ for path in bundle_case.tool_root.iterdir())@@ -324,11 +463,11 @@ def test_passwords_never_enter_durable_job_payloads(bundle_case):assert "password" not in export_job["payload"]assert import_job["payload"]["sealed"] is Trueassert "password" not in import_job["payload"]- with closing(sqlite3.connect(bundle_case.path / "case.db")) as conn:+ with closing(sqlite3.connect(bundle_case.db_path)) as conn:export_payload = conn.execute("SELECT payload_json FROM jobs WHERE id = ?", (export_job["id"],)).fetchone()[0]- with closing(sqlite3.connect(imported.path / "case.db")) as conn:+ with closing(sqlite3.connect(imported.db_path)) as conn:import_payload = conn.execute("SELECT payload_json FROM jobs WHERE id = ?", (import_job["id"],)).fetchone()[0]diff --git a/tests/test_cases_api.py b/tests/test_cases_api.pyindex 4b56946..19d8ab5 100644--- a/tests/test_cases_api.py+++ b/tests/test_cases_api.py@@ -1,6 +1,13 @@"""Case lifecycle, notes, entities and links through the REST API."""+import json+from pathlib import Path+import graph_read+from fastapi.testclient import TestClient++from azimut import layout+from azimut.workspace import Casedef test_health(client):@@ -123,7 +130,6 @@ def test_notes_roundtrip(client):def test_filed_notes_are_markdown_files(client):- import azimut.config as cfgcid = client.post("/api/cases", json={"name": "Notebook"}).json()["id"]note = client.post(@@ -131,8 +137,11 @@ def test_filed_notes_are_markdown_files(client):json={"title": "Lead", "folder": "Research", "content": "# First lead"},).json()- assert note["attrs"] == {"folder": "Research", "path": f"notes/{note['id']}.md"}- assert (cfg.cases_dir() / cid / note["attrs"]["path"]).read_text(encoding="utf-8") == "# First lead"+ # the name is the filename, and the notebook's folder is mirrored on disk+ assert note["attrs"] == {"folder": "Research", "path": "notes/Research/Lead.md"}+ assert Case.open(cid).resolve_inside(note["attrs"]["path"]).read_text(+ encoding="utf-8"+ ) == "# First lead"assert client.get(f"/api/cases/{cid}/notes/{note['id']}").json()["text"] == "# First lead"client.put(f"/api/cases/{cid}/notes/{note['id']}", json={"text": "Updated"})@@ -140,11 +149,10 @@ def test_filed_notes_are_markdown_files(client):def test_deleting_filed_note_removes_markdown_file(client):- import azimut.config as cfgcid = client.post("/api/cases", json={"name": "Notebook delete"}).json()["id"]note = client.post(f"/api/cases/{cid}/notes", json={"title": "Disposable"}).json()- path = cfg.cases_dir() / cid / note["attrs"]["path"]+ path = Case.open(cid).resolve_inside(note["attrs"]["path"])assert path.exists()client.delete(f"/api/cases/{cid}/entities/{note['id']}")@@ -487,7 +495,7 @@ def test_cleanup_scratch_reaps_only_old_empty_sessions(tmp_workspace):_age(with_entity)# old but holding a media file → keptwith_file = Case.create("Scratch session", scratch=True)- (with_file.path / "media" / "shot.png").write_bytes(b"png")+ (with_file.subdir("media") / "shot.png").write_bytes(b"png")_age(with_file)# fresh and empty → kept (it may be in use right now)empty_new = Case.create("Scratch session", scratch=True)@@ -508,10 +516,167 @@ def test_cleanup_scratch_treats_a_stranded_sidecar_temp_file_as_debris(tmp_worksfrom azimut.workspace import Casestranded = Case.create("Scratch session", scratch=True)- (stranded.path / "media" / ".shot.png.azimut.json.deadbeef.tmp").write_bytes(b"{}")+ (stranded.subdir("media") / ".shot.png.azimut.json.deadbeef.tmp").write_bytes(b"{}")data = jsonlib.loads(stranded.json_path.read_text(encoding="utf-8"))data["updated_at"] = "2000-01-01T00:00:00Z"stranded.json_path.write_text(jsonlib.dumps(data), encoding="utf-8")assert Case.cleanup_scratch() == 1assert not stranded.path.exists()+++def test_renaming_a_note_moves_its_file(client):+ """The name is the filename, as it already is for proofs, sessions and+ drafts. Notes were the last holdout."""+ cid = client.post("/api/cases", json={"name": "Renames"}).json()["id"]+ note = client.post(+ f"/api/cases/{cid}/notes",+ json={"title": "Draft lead", "folder": "Research", "content": "# body"},+ ).json()+ case = Case.open(cid)+ assert note["attrs"]["path"] == "notes/Research/Draft lead.md"++ renamed = client.patch(+ f"/api/cases/{cid}/entities/{note['id']}", json={"label": "Confirmed lead"}+ ).json()++ assert renamed["attrs"]["path"] == "notes/Research/Confirmed lead.md"+ assert case.resolve_inside(renamed["attrs"]["path"]).read_text(encoding="utf-8") == "# body"+ assert not case.resolve_inside(note["attrs"]["path"]).exists()+++def test_moving_a_note_between_folders_moves_its_file(client):+ """The notebook's tree is mirrored on disk, so filing a note is a move."""+ cid = client.post("/api/cases", json={"name": "Filing"}).json()["id"]+ note = client.post(+ f"/api/cases/{cid}/notes", json={"title": "Summary", "folder": "Video 1"}+ ).json()+ case = Case.open(cid)+ assert note["attrs"]["path"] == "notes/Video 1/Summary.md"++ moved = client.patch(+ f"/api/cases/{cid}/entities/{note['id']}", json={"attrs": {"folder": "Video 2"}}+ ).json()++ assert moved["attrs"]["path"] == "notes/Video 2/Summary.md"+ # the emptied folder does not linger: a mirror that keeps every directory a+ # note passed through stops being a mirror+ assert not case.resolve_inside("notes/Video 1").exists()+++def test_a_note_moves_cleanly_under_a_symlinked_workspace(monkeypatch, tmp_path):+ """The same move, reached through a symlink, still prunes what it emptied.++ macOS reaches every temporary directory as `/var` → `/private/var`, and a+ workspace under a linked or synced folder does the same anywhere. The case+ knows its directory by the path it was given while `resolve_inside` hands+ back the resolved one, so a containment check comparing the two spellings+ answers "outside" about a directory that is inside — and the pruning it+ guards silently stops happening.+ """+ real = tmp_path / "real"+ real.mkdir()+ linked = tmp_path / "linked"+ linked.symlink_to(real, target_is_directory=True)+ monkeypatch.setenv("AZIMUT_HOME", str(linked))+ from azimut.server import create_app++ with TestClient(create_app(), base_url="http://127.0.0.1") as client:+ cid = client.post("/api/cases", json={"name": "Filing"}).json()["id"]+ note = client.post(+ f"/api/cases/{cid}/notes", json={"title": "Summary", "folder": "Video 1"}+ ).json()+ case = Case.open(cid)+ assert case.resolve_inside(note["attrs"]["path"]).is_file()++ client.patch(+ f"/api/cases/{cid}/entities/{note['id']}", json={"attrs": {"folder": "Video 2"}}+ )++ assert not case.resolve_inside("notes/Video 1").exists()+++def test_the_same_title_lives_in_two_folders(client):+ """Uniqueness is scoped to the folder. This is why the tree is mirrored at+ all: one folder per video is the analyst's whole workflow."""+ cid = client.post("/api/cases", json={"name": "Two videos"}).json()["id"]+ first = client.post(+ f"/api/cases/{cid}/notes", json={"title": "Summary", "folder": "Video 1"}+ ).json()+ second = client.post(+ f"/api/cases/{cid}/notes", json={"title": "Summary", "folder": "Video 2"}+ ).json()++ assert first["attrs"]["path"] == "notes/Video 1/Summary.md"+ assert second["attrs"]["path"] == "notes/Video 2/Summary.md"+++def test_the_same_title_twice_in_one_folder_takes_a_suffix(client):+ """A note is the most frequent thing an analyst creates, so a taken name is+ numbered rather than refused."""+ cid = client.post("/api/cases", json={"name": "Same name"}).json()["id"]+ first = client.post(f"/api/cases/{cid}/notes", json={"title": "Lead", "folder": ""}).json()+ second = client.post(f"/api/cases/{cid}/notes", json={"title": "Lead", "folder": ""}).json()++ assert first["attrs"]["path"] == "notes/Lead.md"+ assert second["attrs"]["path"] == "notes/Lead-2.md"+ assert Case.open(cid).resolve_inside(second["attrs"]["path"]).exists()+++def test_details_title_edit_moves_every_named_tool_file(client):+ """The shared Details editor bypasses the tool-specific save routes, so its+ generic entity patch must still keep labels and filenames aligned."""+ cid = client.post("/api/cases", json={"name": "Details renames"}).json()["id"]+ case = Case.open(cid)+ fixtures = [+ (+ "proof",+ "spec",+ layout.proof_spec_rel("Old proof"),+ "New proof",+ layout.proof_spec_rel("New proof"),+ ),+ (+ "inspect-session",+ "spec",+ layout.session_rel("Old inspect"),+ "New inspect",+ layout.session_rel("New inspect"),+ ),+ (+ "post",+ "draft",+ layout.draft_rel("Old post"),+ "New post",+ layout.draft_rel("New post"),+ ),+ ]+ entities = []+ for type_, attribute, old, new_label, new in fixtures:+ path = case.resolve_inside(old)+ path.parent.mkdir(parents=True, exist_ok=True)+ path.write_text(json.dumps({"title": Path(old).stem}), encoding="utf-8")+ attrs = {attribute: old}+ if type_ == "proof":+ export = layout.proof_export_rel("Old proof")+ case.resolve_inside(export).write_bytes(b"png")+ attrs["path"] = export+ entity = case.add_entity(type_, Path(old).stem, attrs, by="user")+ entities.append((entity, old, new_label, new))++ for entity, old, new_label, new in entities:+ updated = client.patch(+ f"/api/cases/{cid}/entities/{entity['id']}",+ json={"label": new_label},+ ).json()+ attribute = "draft" if entity["type"] == "post" else "spec"+ assert updated["label"] == new_label+ assert updated["attrs"][attribute] == new+ assert not case.resolve_inside(old).exists()+ assert case.resolve_inside(new).is_file()+ body = json.loads(case.resolve_inside(new).read_text(encoding="utf-8"))+ assert body["title"] == new_label++ proof = next(entity for entity in case.list_entities() if entity["type"] == "proof")+ assert proof["attrs"]["path"] == layout.proof_export_rel("New proof")+ assert case.resolve_inside(proof["attrs"]["path"]).is_file()diff --git a/tests/test_config.py b/tests/test_config.pyindex 5637110..80ab2d1 100644--- a/tests/test_config.py+++ b/tests/test_config.py@@ -15,11 +15,155 @@ def test_default_settings_has_usage_and_api_keys():def test_ensure_workspace_writes_defaults(monkeypatch, tmp_path):monkeypatch.setenv("AZIMUT_HOME", str(tmp_path))config.ensure_workspace()+ assert config.cases_dir() == tmp_path+ assert config.internal_dir() == tmp_path / ".azimut"+ assert config.settings_dir() == tmp_path / ".azimut" / "settings"+ assert config.scratch_dir() == tmp_path / ".azimut" / "scratch"+ assert config.bundles_dir() == tmp_path / ".azimut" / "bundles"+ assert config.runtime_dir() == tmp_path / ".azimut" / "runtime"+ assert config.tile_cache_dir() == tmp_path / ".azimut" / "cache" / "tiles"+ assert config.settings_path().parent == config.settings_dir()saved = json.loads(config.settings_path().read_text(encoding="utf-8"))assert saved["usage"] == {}assert saved["tile_providers"] == []+def test_ensure_workspace_moves_legacy_settings_files_once(monkeypatch, tmp_path):+ monkeypatch.setenv("AZIMUT_HOME", str(tmp_path))+ legacy = {+ "settings.json": json.dumps({**config.DEFAULT_SETTINGS, "units": "imperial"}).encode(),+ "templates.json": b'{"schema": 1, "proof": [], "post": []}\n',+ "signature.png": config.PNG_MAGIC + b"logo",+ "cookies.txt": b"# Netscape HTTP Cookie File\n",+ }+ for name, content in legacy.items():+ (tmp_path / name).write_bytes(content)++ config.ensure_workspace()++ assert config.load_settings()["units"] == "imperial"+ assert config.templates_path().read_bytes() == legacy["templates.json"]+ assert config.signature_path().read_bytes() == legacy["signature.png"]+ assert config.cookies_file_path().read_bytes() == legacy["cookies.txt"]+ assert not any((tmp_path / name).exists() for name in legacy)+ before = {path.name: path.read_bytes() for path in config.settings_dir().iterdir()}++ config.ensure_workspace()++ assert {path.name: path.read_bytes() for path in config.settings_dir().iterdir()} == before+++def test_workspace_settings_migration_preserves_a_conflicting_legacy_file(monkeypatch, tmp_path):+ monkeypatch.setenv("AZIMUT_HOME", str(tmp_path))+ config.settings_dir().mkdir(parents=True)+ config.settings_path().write_text(+ json.dumps({**config.DEFAULT_SETTINGS, "units": "metric"}),+ encoding="utf-8",+ )+ legacy = json.dumps({**config.DEFAULT_SETTINGS, "units": "imperial"}).encode()+ (tmp_path / "settings.json").write_bytes(legacy)++ config.ensure_workspace()++ assert config.load_settings()["units"] == "metric"+ assert not (tmp_path / "settings.json").exists()+ assert (config.settings_dir() / "settings.legacy.json").read_bytes() == legacy+++def test_workspace_settings_migration_resumes_after_a_partial_move(monkeypatch, tmp_path):+ monkeypatch.setenv("AZIMUT_HOME", str(tmp_path))+ config.settings_dir().mkdir(parents=True)+ config.settings_path().write_text(json.dumps(config.DEFAULT_SETTINGS), encoding="utf-8")+ (tmp_path / "templates.json").write_text(json.dumps(config.DEFAULT_TEMPLATES), encoding="utf-8")+ (tmp_path / "signature.png").write_bytes(config.PNG_MAGIC + b"logo")++ config.ensure_workspace()++ assert config.settings_path().is_file()+ assert config.templates_path().is_file()+ assert config.signature_path().is_file()+ assert not (tmp_path / "templates.json").exists()+ assert not (tmp_path / "signature.png").exists()+++def test_workspace_settings_migration_absorbs_the_intermediate_dot_directory(monkeypatch, tmp_path):+ monkeypatch.setenv("AZIMUT_HOME", str(tmp_path))+ intermediate = tmp_path / ".settings"+ intermediate.mkdir()+ (intermediate / "settings.json").write_text(+ json.dumps({**config.DEFAULT_SETTINGS, "units": "imperial"}),+ encoding="utf-8",+ )+ (intermediate / "extra.txt").write_text("preserved", encoding="utf-8")++ config.ensure_workspace()++ assert config.load_settings()["units"] == "imperial"+ assert (config.settings_dir() / "extra.txt").read_text(encoding="utf-8") == "preserved"+ assert not intermediate.exists()+++def test_workspace_layout_migration_flattens_cases_and_hides_machinery(monkeypatch, tmp_path):+ monkeypatch.setenv("AZIMUT_HOME", str(tmp_path))+ old_case = tmp_path / "cases" / "harbour"+ old_case.mkdir(parents=True)+ (old_case / "case.json").write_text("case", encoding="utf-8")+ for name, marker in (+ ("scratch", "session"),+ ("bundles", "export.azimut.zip"),+ ("runtime", "yt-dlp"),+ ("tile-cache", "tile.jpg"),+ ):+ directory = tmp_path / name / marker+ directory.parent.mkdir(parents=True, exist_ok=True)+ directory.write_text(name, encoding="utf-8")++ config.ensure_workspace()++ assert (tmp_path / "harbour" / "case.json").read_text(encoding="utf-8") == "case"+ assert (config.scratch_dir() / "session").read_text(encoding="utf-8") == "scratch"+ assert (config.bundles_dir() / "export.azimut.zip").read_text(encoding="utf-8") == "bundles"+ assert (config.runtime_dir() / "yt-dlp").read_text(encoding="utf-8") == "runtime"+ assert (config.tile_cache_dir() / "tile.jpg").read_text(encoding="utf-8") == "tile-cache"+ assert not any(+ (tmp_path / name).exists()+ for name in ("cases", "scratch", "bundles", "runtime", "tile-cache")+ )+++def test_workspace_layout_migration_resumes_a_partially_moved_directory(monkeypatch, tmp_path):+ monkeypatch.setenv("AZIMUT_HOME", str(tmp_path))+ old = tmp_path / "scratch" / "old-session"+ old.mkdir(parents=True)+ (old / "case.json").write_text("old", encoding="utf-8")+ current = config.scratch_dir() / "current-session"+ current.mkdir(parents=True)+ (current / "case.json").write_text("current", encoding="utf-8")++ config.ensure_workspace()+ config.ensure_workspace()++ assert (config.scratch_dir() / "old-session" / "case.json").is_file()+ assert (config.scratch_dir() / "current-session" / "case.json").is_file()+ assert not (tmp_path / "scratch").exists()+++def test_workspace_layout_migration_refuses_to_overwrite_a_case_collision(monkeypatch, tmp_path):+ monkeypatch.setenv("AZIMUT_HOME", str(tmp_path))+ legacy = tmp_path / "cases" / "same-name"+ current = tmp_path / "same-name"+ legacy.mkdir(parents=True)+ current.mkdir()+ (legacy / "case.json").write_text("legacy", encoding="utf-8")+ (current / "case.json").write_text("current", encoding="utf-8")++ with pytest.raises(config.WorkspaceMigrationError, match="refuses to merge"):+ config.ensure_workspace()++ assert (legacy / "case.json").read_text(encoding="utf-8") == "legacy"+ assert (current / "case.json").read_text(encoding="utf-8") == "current"++def test_load_settings_roundtrips_usage_counters(monkeypatch, tmp_path):monkeypatch.setenv("AZIMUT_HOME", str(tmp_path))config.save_settings(@@ -83,21 +227,28 @@ def test_save_settings_is_atomic_when_replace_fails(monkeypatch, tmp_path):config.save_settings({**config.DEFAULT_SETTINGS, "units": "imperial"})assert config.settings_path().read_bytes() == before- assert list(tmp_path.glob(".settings.json.*.tmp")) == []+ assert list(config.settings_dir().glob(".settings.json.*.tmp")) == []@pytest.mark.parametrize("content",- ["[]", "{", '{"schema": 2, "proof": [], "post": []}', '{"schema": 1, "proof": [42], "post": []}'],+ [+ "[]",+ "{",+ '{"schema": 2, "proof": [], "post": []}',+ '{"schema": 1, "proof": [42], "post": []}',+ ],)def test_load_templates_recovers_from_malformed_stores(monkeypatch, tmp_path, content):monkeypatch.setenv("AZIMUT_HOME", str(tmp_path))+ config.templates_path().parent.mkdir(parents=True)config.templates_path().write_text(content, encoding="utf-8")assert config.load_templates() == config.DEFAULT_TEMPLATESdef test_load_templates_filters_bad_records_and_duplicate_ids(monkeypatch, tmp_path):monkeypatch.setenv("AZIMUT_HOME", str(tmp_path))+ config.templates_path().parent.mkdir(parents=True)config.templates_path().write_text(json.dumps({@@ -134,4 +285,4 @@ def test_save_templates_is_atomic_when_replace_fails(monkeypatch, tmp_path):)assert config.templates_path().read_bytes() == before- assert list(tmp_path.glob(".templates.json.*.tmp")) == []+ assert list(config.settings_dir().glob(".templates.json.*.tmp")) == []diff --git a/tests/test_diagnostics.py b/tests/test_diagnostics.pyindex f47fff9..ad69a54 100644--- a/tests/test_diagnostics.py+++ b/tests/test_diagnostics.py@@ -98,12 +98,17 @@ def test_install_is_idempotent(monkeypatch):def test_scrub_replaces_home_and_account_name(monkeypatch, tmp_path):monkeypatch.setattr(diagnostics.Path, "home", staticmethod(lambda: tmp_path / "gwen"))monkeypatch.setattr(diagnostics, "_account_name", lambda: "gwen")+ monkeypatch.setattr(+ diagnostics.config,+ "workspace_root",+ lambda: tmp_path / "gwen" / "Azimut",+ )- scrubbed = diagnostics.scrub(f"failed to open {tmp_path}/gwen/Azimut/cases/kyiv — gwen")+ scrubbed = diagnostics.scrub(f"failed to open {tmp_path}/gwen/Azimut/kyiv — gwen")assert "gwen" not in scrubbed# the path stays useful, but the case segment is a name the analyst chose and# this text is on its way to a public tracker- assert "~/Azimut/cases/<case>" in scrubbed+ assert "<workspace>/<case>" in scrubbedassert "kyiv" not in scrubbedassert "<user>" in scrubbed@@ -134,6 +139,42 @@ def test_scrub_keeps_a_very_short_account_name(monkeypatch):assert diagnostics.scrub("an unexpected answer") == "an unexpected answer"+def test_scrub_replaces_this_machines_name(monkeypatch):+ """The workspace lock names the host holding a folder, and that warning goes+ into the log tail a bug report publishes. On a work laptop it is an asset tag+ and an internal domain."""+ monkeypatch.setattr(diagnostics.socket, "gethostname", lambda: "lt-4471.corp.example")++ scrubbed = diagnostics.scrub(+ "another Azimut has this workspace open on lt-4471.corp.example:8477"+ )++ assert scrubbed == "another Azimut has this workspace open on <machine>:8477"+++def test_scrub_replaces_the_short_form_of_the_machine_name_too(monkeypatch):+ """The lock records `gethostname()`, but a log line elsewhere may carry only+ the leading label — replacing the long form first must not leave it behind."""+ monkeypatch.setattr(diagnostics.socket, "gethostname", lambda: "lt-4471.corp.example")++ assert diagnostics.scrub("connecting to lt-4471") == "connecting to <machine>"+ assert "corp.example" not in diagnostics.scrub("host lt-4471.corp.example")+++def test_scrub_keeps_a_very_short_machine_name(monkeypatch):+ monkeypatch.setattr(diagnostics.socket, "gethostname", lambda: "pc")++ assert diagnostics.scrub("a pc somewhere") == "a pc somewhere"+++def test_scrub_survives_a_nameless_machine(monkeypatch):+ monkeypatch.setattr(+ diagnostics.socket, "gethostname", lambda: (_ for _ in ()).throw(OSError)+ )++ assert diagnostics.scrub("plain text") == "plain text"++def test_scrub_survives_a_homeless_environment(monkeypatch):monkeypatch.setattr(diagnostics.Path, "home", staticmethod(lambda: (_ for _ in ()).throw(RuntimeError))@@ -365,8 +406,8 @@ def test_a_case_name_never_reaches_the_tracker(ring, tmp_workspace):assert "operation-blue-heron" not in capturedassert "scratch_9f2c" not in captured- assert "cases/<case>/case.db" in captured.replace("\\", "/")- assert "scratch/<case>/media/a.jpg" in captured.replace("\\", "/")+ assert "<workspace>/<case>/case.db" in captured.replace("\\", "/")+ assert ".azimut/scratch/<case>/media/a.jpg" in captured.replace("\\", "/")def test_a_credential_in_a_logged_url_is_redacted(ring, tmp_workspace):diff --git a/tests/test_doctor.py b/tests/test_doctor.pynew file mode 100644index 0000000..47a5506--- /dev/null+++ b/tests/test_doctor.py@@ -0,0 +1,197 @@+"""The Case Doctor diagnoses damage first and repairs only on request."""++import io+import json++from azimut import layout+from azimut.engine import workqueue+from azimut.workspace import Case+++def _new_case(client, name="Doctor case"):+ return client.post("/api/cases", json={"name": name}).json()["id"]+++def _upload(client, case_id, name="evidence.txt", content=b"evidence"):+ result = client.post(+ f"/api/cases/{case_id}/media/upload",+ files={"file": (name, io.BytesIO(content), "text/plain")},+ ).json()+ assert workqueue.wait_until_idle(timeout=10)+ return result+++def test_healthy_case_has_no_doctor_findings(client):+ case_id = _new_case(client)++ report = client.get(f"/api/cases/{case_id}/doctor").json()++ assert report["status"] == "healthy"+ assert report["issues"] == []+ assert report["summary"] == {"errors": 0, "warnings": 0, "info": 0}+++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")+ client.post(+ f"/api/cases/{case_id}/notes",+ json={"title": "Witness note", "folder": "Leads", "content": "Body"},+ )+ case = Case.open(case_id)+ proof_meta = case.resolve_inside(f"proofs/{layout.META_DIR}")+ proof_meta.mkdir(parents=True, exist_ok=True)+ proof_meta.joinpath("Timeline.json").write_text(+ json.dumps({"azimut_proof": 1, "title": "Timeline", "panels": []}),+ encoding="utf-8",+ )+ case.resolve_inside("proofs/Timeline.png").write_bytes(b"rendered proof")+ case.db_path.unlink()++ listed = next(item for item in client.get("/api/cases").json() if item["id"] == case_id)+ assert listed["health"] == "needs-attention"+ assert listed["entity_count"] is None+ report = client.get(f"/api/cases/{case_id}/doctor").json()+ issue = report["issues"][0]+ assert issue["kind"] == "database-missing"+ assert issue["actions"] == [+ {"id": "rebuild", "label": "Rebuild database", "tone": "primary"}+ ]+ assert "Relations between entities" in issue["losses"]+ assert not case.db_path.exists() # diagnosis stayed read-only++ repaired = client.post(+ f"/api/cases/{case_id}/doctor/repair",+ json={"action": "rebuild"},+ ).json()++ assert repaired["repair"]["counts"] == {"media": 1, "notes": 1, "proofs": 1}+ assert repaired["report"]["status"] == "healthy"+ rebuilt = Case.open(case_id)+ entities = rebuilt.list_entities()+ assert {(item["type"], item["label"]) for item in entities} == {+ ("media", "Street clip"),+ ("note", "Witness note"),+ ("proof", "Timeline"),+ }+ media = next(item for item in entities if item["type"] == "media")+ assert media["attrs"]["path"] == uploaded["item"]["path"]+ assert media["provenance"]["by"] == "case-doctor"+++def test_missing_media_can_be_relinked_without_replacing_its_entity(client):+ case_id = _new_case(client)+ uploaded = _upload(client, case_id, "Original.txt")+ entity_id = uploaded["entity"]["id"]+ case = Case.open(case_id)+ original = case.resolve_inside(uploaded["item"]["path"])+ original.unlink()+ replacement = case.media_dir / "Replacement.txt"+ replacement.write_bytes(b"replacement")++ report = client.get(f"/api/cases/{case_id}/doctor").json()+ missing = next(issue for issue in report["issues"] if issue["kind"] == "media-missing")+ unknown = next(issue for issue in report["issues"] if issue["kind"] == "media-unknown")+ assert {action["id"] for action in missing["actions"]} == {"relink", "drop"}+ assert missing["state"] == "missing"+ assert missing["replacements"] == ["media/Replacement.txt"]+ assert unknown["actions"][0]["id"] == "import"++ repaired = client.post(+ f"/api/cases/{case_id}/doctor/repair",+ json={+ "action": "relink",+ "entity_id": entity_id,+ "replacement": "media/Replacement.txt",+ },+ ).json()++ assert repaired["report"]["status"] == "healthy"+ entity = Case.open(case_id).get_entity(entity_id)+ assert entity is not None+ assert entity["label"] == "Replacement"+ assert entity["attrs"]["path"] == "media/Replacement.txt"+++def test_missing_media_record_can_be_explicitly_removed(client):+ case_id = _new_case(client)+ uploaded = _upload(client, case_id)+ Case.open(case_id).resolve_inside(uploaded["item"]["path"]).unlink()++ repaired = client.post(+ f"/api/cases/{case_id}/doctor/repair",+ json={"action": "drop", "entity_id": uploaded["entity"]["id"]},+ ).json()++ assert repaired["repair"]["status"] == "deleted"+ assert repaired["report"]["status"] == "healthy"+++def test_file_dropped_into_media_is_imported_only_after_explicit_action(client):+ case_id = _new_case(client)+ case = Case.open(case_id)+ dropped = case.media_dir / "Hand dropped.txt"+ dropped.write_bytes(b"manual")+ database_before = case.db_path.read_bytes()++ report = client.get(f"/api/cases/{case_id}/doctor").json()+ assert report["issues"][0]["kind"] == "media-unknown"+ assert Case.open(case_id).list_entities() == []+ assert case.db_path.read_bytes() == database_before+ assert not case.resolve_inside("media/.meta/Hand dropped.txt.json").exists()++ repaired = client.post(+ f"/api/cases/{case_id}/doctor/repair",+ json={"action": "import", "path": "media/Hand dropped.txt"},+ ).json()++ assert repaired["report"]["status"] == "healthy"+ entity = Case.open(case_id).list_entities()[0]+ assert entity["label"] == "Hand dropped"+ assert entity["provenance"]["by"] == "case-doctor"+++def test_doctor_refuses_repairs_that_the_current_damage_does_not_offer(client):+ case_id = _new_case(client)+ uploaded = _upload(client, case_id)++ 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": "import", "path": "notes.md"},+ ).status_code == 409+ assert client.post(+ f"/api/cases/{case_id}/doctor/repair",+ json={"action": "drop", "entity_id": uploaded["entity"]["id"]},+ ).status_code == 409+++def test_case_renamed_outside_azimut_is_found_from_its_manifest(client):+ case_id = _new_case(client, "Original folder")+ case = Case.open(case_id)+ renamed = case.path.with_name("renamed-by-user")+ case.path.rename(renamed)++ assert client.get(f"/api/cases/{case_id}/doctor").status_code == 404+ report = client.get("/api/cases/renamed-by-user/doctor").json()+ assert report["status"] == "healthy"+ assert report["case_name"] == "Original folder"+ assert client.get("/api/cases/renamed-by-user").status_code == 200+++def test_scratch_case_uses_the_same_doctor_and_rebuild(client):+ case_id = client.post("/api/cases/scratch").json()["id"]+ case = Case.open(case_id)+ case.db_path.unlink()++ report = client.get(f"/api/cases/{case_id}/doctor").json()+ assert report["scratch"] is True+ assert report["issues"][0]["kind"] == "database-missing"++ repaired = client.post(+ f"/api/cases/{case_id}/doctor/repair", json={"action": "rebuild"}+ ).json()+ assert repaired["report"]["status"] == "healthy"+ assert repaired["report"]["scratch"] is Truediff --git a/tests/test_drafts_api.py b/tests/test_drafts_api.pyindex 46c7329..5a0aba0 100644--- a/tests/test_drafts_api.py+++ b/tests/test_drafts_api.py@@ -27,15 +27,15 @@ def test_save_load_roundtrip(client):f"/api/cases/{cid}/drafts",json={"title": "Helicopter formation", "state": STATE},).json()- assert saved["name"] == "helicopter-formation"- assert saved["draft"] == "exports/helicopter-formation.json"+ assert saved["name"] == "Helicopter formation"+ assert saved["draft"] == ".drafts/Helicopter formation.json"listed = client.get(f"/api/cases/{cid}/drafts").json()assert len(listed) == 1assert listed[0]["title"] == "Helicopter formation"assert listed[0]["target"] == "bluesky"- draft = client.get(f"/api/cases/{cid}/drafts/helicopter-formation").json()+ draft = client.get(f"/api/cases/{cid}/drafts/{saved['name']}").json()assert draft["title"] == "Helicopter formation"assert draft["state"]["place"] == "Los Anacuos, Miranda, Venezuela"assert draft["state"]["target"] == "bluesky"@@ -57,7 +57,7 @@ def test_draft_filed_as_post_entity_and_updated_on_resave(client):)posts = [e for e in graph_read.entities(cid) if e["type"] == "post"]assert len(posts) == 1- assert posts[0]["attrs"]["draft"] == "exports/first-title.json"+ assert posts[0]["attrs"]["draft"] == ".drafts/First title.json"def test_draft_rename_moves_the_file_and_keeps_one_entity(client):@@ -71,57 +71,63 @@ def test_draft_rename_moves_the_file_and_keeps_one_entity(client):f"/api/cases/{cid}/drafts",json={"rename_from": saved["name"], "title": "Helicopter thread", "state": STATE},).json()- assert renamed["name"] == "helicopter-thread"- assert client.get(f"/api/cases/{cid}/drafts/post-1").status_code == 404+ assert renamed["name"] == "Helicopter thread"+ assert client.get(f"/api/cases/{cid}/drafts/{saved['name']}").status_code == 404posts = [e for e in graph_read.entities(cid) if e["type"] == "post"]assert len(posts) == 1assert posts[0]["id"] == before["id"]assert posts[0]["label"] == "Helicopter thread"- assert posts[0]["attrs"]["draft"] == "exports/helicopter-thread.json"+ assert posts[0]["attrs"]["draft"] == ".drafts/Helicopter thread.json"def test_draft_rename_onto_a_taken_name_is_refused(client):cid = client.post("/api/cases", json={"name": "Drafts"}).json()["id"]client.post(f"/api/cases/{cid}/drafts", json={"title": "Post 1", "state": STATE})- client.post(f"/api/cases/{cid}/drafts", json={"title": "Post 2", "state": STATE})+ second = client.post(+ f"/api/cases/{cid}/drafts", json={"title": "Post 2", "state": STATE}+ ).json()res = client.post(f"/api/cases/{cid}/drafts",- json={"rename_from": "post-2", "title": "Post 1", "state": STATE},+ json={"rename_from": second["name"], "title": "Post 1", "state": STATE},)assert res.status_code == 409listed = client.get(f"/api/cases/{cid}/drafts").json()- assert sorted(d["name"] for d in listed) == ["post-1", "post-2"]+ assert sorted(d["name"] for d in listed) == ["Post 1", "Post 2"]def test_created_at_preserved_on_resave_and_rename(client):cid = client.post("/api/cases", json={"name": "Drafts"}).json()["id"]- client.post(f"/api/cases/{cid}/drafts", json={"title": "Keep created", "state": STATE})- first = client.get(f"/api/cases/{cid}/drafts/keep-created").json()+ saved = client.post(+ f"/api/cases/{cid}/drafts", json={"title": "Keep created", "state": STATE}+ ).json()+ first = client.get(f"/api/cases/{cid}/drafts/{saved['name']}").json()client.post(f"/api/cases/{cid}/drafts",- json={"rename_from": "keep-created", "title": "Keep created", "state": STATE},+ json={"rename_from": saved["name"], "title": "Keep created", "state": STATE},)- second = client.get(f"/api/cases/{cid}/drafts/keep-created").json()+ second = client.get(f"/api/cases/{cid}/drafts/{saved['name']}").json()assert first["created_at"] == second["created_at"]client.post(f"/api/cases/{cid}/drafts",- json={"rename_from": "keep-created", "title": "Moved along", "state": STATE},+ json={"rename_from": saved["name"], "title": "Moved along", "state": STATE},)- third = client.get(f"/api/cases/{cid}/drafts/moved-along").json()+ third = client.get(f"/api/cases/{cid}/drafts/Moved along").json()assert third["created_at"] == first["created_at"]def test_delete_removes_file_and_entity(client):cid = client.post("/api/cases", json={"name": "Drafts"}).json()["id"]- client.post(f"/api/cases/{cid}/drafts", json={"title": "To delete", "state": STATE})+ saved = client.post(+ f"/api/cases/{cid}/drafts", json={"title": "To delete", "state": STATE}+ ).json()- r = client.delete(f"/api/cases/{cid}/drafts/to-delete")+ r = client.delete(f"/api/cases/{cid}/drafts/{saved['name']}")assert r.json()["status"] == "deleted"assert client.get(f"/api/cases/{cid}/drafts").json() == []- assert client.get(f"/api/cases/{cid}/drafts/to-delete").status_code == 404+ assert client.get(f"/api/cases/{cid}/drafts/{saved['name']}").status_code == 404posts = [e for e in graph_read.entities(cid) if e["type"] == "post"]assert posts == []diff --git a/tests/test_folder_adoption.py b/tests/test_folder_adoption.pynew file mode 100644index 0000000..40ce148--- /dev/null+++ b/tests/test_folder_adoption.py@@ -0,0 +1,163 @@+"""A folder the analyst drops in the workspace becomes a case on one click."""++from pathlib import Path++from azimut import config, layout+from azimut.workspace import Case+++def tree(root: Path) -> set[str]:+ """Every path under a directory, as relative posix strings."""+ return {path.relative_to(root).as_posix() for path in root.rglob("*")}+++def folders(client) -> dict[str, str]:+ return {f["name"]: f["state"] for f in client.get("/api/workspace/folders").json()}+++def make_folder(name: str, *files: str) -> Path:+ """A folder created the way a file manager would create it."""+ path = config.cases_dir() / name+ path.mkdir(parents=True)+ for filename in files:+ path.joinpath(filename).write_bytes(b"analyst material")+ return path+++def test_a_folder_in_the_workspace_is_offered_and_becomes_a_case(client):+ make_folder("Oceanside match", "shore.jpg")++ assert folders(client)["Oceanside match"] == "new"++ adopted = client.post("/api/workspace/folders/adopt", json={"name": "Oceanside match"})++ assert adopted.status_code == 200+ assert adopted.json()["id"] == "Oceanside match"+ assert adopted.json()["name"] == "Oceanside match"+ listed = client.get("/api/cases").json()+ assert [(c["id"], c["entity_count"]) for c in listed] == [("Oceanside match", 0)]+ # and it stops being offered, because it is a case now+ assert folders(client) == {}+++def test_adoption_leaves_the_analysts_files_where_they_are(client):+ """The whole promise of the case folder: `azimut/` is ours, the rest theirs.++ Adoption fills in our half and does not read, move or import the other one —+ the files are still where they were put, and the case is empty until the+ analyst says otherwise.+ """+ folder = make_folder("Coast survey", "shore.jpg", "notes.docx")++ client.post("/api/workspace/folders/adopt", json={"name": "Coast survey"})++ assert folder.joinpath("shore.jpg").is_file()+ assert folder.joinpath("notes.docx").is_file()+ assert client.get("/api/cases/Coast survey/media").json() == []+ assert list(layout.media(folder).iterdir()) == [layout.media(folder) / layout.META_DIR]+ # the note that says which half is whose lands beside their files+ assert layout.readme(folder).is_file()+++def test_adoption_keeps_a_readme_the_analyst_already_wrote(client):+ folder = make_folder("Notes first")+ layout.readme(folder).write_text("mine\n", encoding="utf-8")++ client.post("/api/workspace/folders/adopt", json={"name": "Notes first"})++ assert layout.readme(folder).read_text(encoding="utf-8") == "mine\n"+++def test_an_adopted_case_is_born_exactly_like_one_made_in_the_app(client):+ """The gate that keeps adoption from inventing a second kind of case: the+ tool root has to match a fresh case's, or every registry, trash and bundle+ guarantee written against the birth state stops holding for adopted ones."""+ make_folder("Adopted", "shore.jpg")+ client.post("/api/workspace/folders/adopt", json={"name": "Adopted"})+ born = Case.open(client.post("/api/cases", json={"name": "Newborn"}).json()["id"])++ assert tree(Case.open("Adopted").tool_root) == tree(born.tool_root)+++def test_a_folder_holding_a_case_that_lost_its_manifest_is_recovered_not_reborn(client):+ """The dangerous half of "or the folder is badly filled": being born over a+ database would write a new empty one on top of somebody's investigation."""+ case_id = client.post("/api/cases", json={"name": "Lost manifest"}).json()["id"]+ client.post(f"/api/cases/{case_id}/notes", json={"title": "Lead", "content": "Body"})+ layout.manifest(config.cases_dir() / case_id).unlink()++ assert folders(client)[case_id] == "broken"+ refused = client.post("/api/workspace/folders/adopt", json={"name": case_id})+ assert refused.status_code == 409+ assert "lost its manifest" in refused.json()["detail"]++ recovered = client.post("/api/workspace/folders/recover", json={"name": case_id})++ assert recovered.status_code == 200+ # the name comes back from the database, not from the folder's slug+ assert recovered.json() == {"id": case_id, "name": "Lost manifest"}+ assert folders(client) == {}+ reopened = client.get(f"/api/cases/{case_id}").json()+ assert reopened["name"] == "Lost manifest"+ assert reopened["azimut"]["schema"] == 9+ notes = client.get(f"/api/cases/{case_id}/catalog/entities?type=note").json()+ assert [n["label"] for n in notes["items"]] == ["Lead"]+++def test_recovery_refuses_a_folder_that_never_held_a_case(client):+ make_folder("Just a folder", "shore.jpg")++ refused = client.post("/api/workspace/folders/recover", json={"name": "Just a folder"})++ assert refused.status_code == 409+ assert "no case to recover" in refused.json()["detail"]+++def test_a_name_a_case_folder_cannot_carry_asks_for_a_rename(client):+ """Adoption keeps the name the analyst chose, so the name has to be one a+ case folder can hold on every platform — Windows' path budget included."""+ too_long = "a" * (layout.MAX_CASE_SLUG + 1)+ make_folder(too_long)++ assert folders(client)[too_long] == "unusable-name"+ refused = client.post("/api/workspace/folders/adopt", json={"name": too_long})+ assert refused.status_code == 409+ assert "Rename it" in refused.json()["detail"]+++def test_a_name_that_would_break_its_own_url_asks_for_a_rename(client):+ """The folder name is the case id, and the id travels in a URL path: `#`+ would cut every later request to this case short."""+ make_folder("Sortie #4")++ assert folders(client)["Sortie #4"] == "unusable-name"+ assert client.post("/api/workspace/folders/adopt", json={"name": "Sortie #4"}).status_code == 409+++def test_adoption_refuses_a_name_another_case_already_uses(client):+ client.post("/api/cases", json={"name": "Coast match"})+ make_folder("Coast match") # the case above lives under its slug, `coast-match`++ refused = client.post("/api/workspace/folders/adopt", json={"name": "Coast match"})++ assert refused.status_code == 409+ assert "already exists" in refused.json()["detail"]+++def test_only_visible_directories_are_offered(client):+ """`.azimut/` is the workspace's own machinery and a file is not a case."""+ make_folder("A folder")+ config.cases_dir().joinpath("stray.zip").write_bytes(b"zip")++ assert folders(client) == {"A folder": "new"}+++def test_a_folder_is_not_adopted_without_being_asked(client):+ """Nothing turns a folder into a case on startup: someone may have parked it+ there for an afternoon, and a case is a deliberate act."""+ make_folder("Parked here", "shore.jpg")++ Case.migrate_all()++ assert client.get("/api/cases").json() == []+ assert not layout.tool_root(config.cases_dir() / "Parked here").exists()diff --git a/tests/test_hardening.py b/tests/test_hardening.pyindex 293d2b6..e822242 100644--- a/tests/test_hardening.py+++ b/tests/test_hardening.py@@ -22,8 +22,7 @@ def test_decompression_bomb_guard_is_set():assert Image.MAX_IMAGE_PIXELS == 100_000_000assert any(- action == "error"- and category is Image.DecompressionBombWarning+ action == "error" and category is Image.DecompressionBombWarningfor action, _message, category, _module, _line in warnings.filters)@@ -32,4 +31,6 @@ def test_decompression_bomb_guard_is_set():def test_settings_and_workspace_are_owner_only(tmp_workspace):config.ensure_workspace()assert stat.S_IMODE(os.stat(config.workspace_root()).st_mode) == 0o700+ assert stat.S_IMODE(os.stat(config.internal_dir()).st_mode) == 0o700+ assert stat.S_IMODE(os.stat(config.settings_dir()).st_mode) == 0o700assert stat.S_IMODE(os.stat(config.settings_path()).st_mode) == 0o600diff --git a/tests/test_inspect_api.py b/tests/test_inspect_api.pyindex 7d66f8f..4e676f3 100644--- a/tests/test_inspect_api.py+++ b/tests/test_inspect_api.py@@ -788,7 +788,7 @@ def test_session_save_list_load_delete_roundtrip(client):saved = client.post(f"/api/cases/{cid}/inspect/sessions", json={"title": "My session", "spec": spec}).json()- assert saved["name"] == "my-session"+ assert saved["name"] == "My session"listing = client.get(f"/api/cases/{cid}/inspect/sessions").json()assert len(listing) == 1 and listing[0]["title"] == "My session" and listing[0]["frames"] == 1@@ -796,9 +796,9 @@ def test_session_save_list_load_delete_roundtrip(client):# an inspect-session entity is upserted so it reopens from the sidebarentities = graph_read.entities(cid)ent = next(e for e in entities if e["type"] == "inspect-session")- assert ent["attrs"]["spec"] == "inspect/my-session.json"+ assert ent["attrs"]["spec"] == ".inspect/My session.json"- loaded = client.get(f"/api/cases/{cid}/inspect/sessions/my-session").json()+ loaded = client.get(f"/api/cases/{cid}/inspect/sessions/{saved['name']}").json()assert loaded["azimut_inspect"] == 1assert loaded["frames"][0]["adjust"]["brightness"] == 1.4@@ -807,7 +807,7 @@ def test_session_save_list_load_delete_roundtrip(client):entities = graph_read.entities(cid)assert sum(1 for e in entities if e["type"] == "inspect-session") == 1- client.delete(f"/api/cases/{cid}/inspect/sessions/my-session")+ client.delete(f"/api/cases/{cid}/inspect/sessions/{saved['name']}")assert client.get(f"/api/cases/{cid}/inspect/sessions").json() == []entities = graph_read.entities(cid)assert not any(e["type"] == "inspect-session" for e in entities)@@ -880,7 +880,7 @@ def test_session_rename_moves_the_spec_and_keeps_one_entity(client):first = client.post(f"/api/cases/{cid}/inspect/sessions", json={"title": "Original", "spec": spec}).json()- assert first["name"] == "original"+ assert first["name"] == "Original"before = next(e for e in graph_read.entities(cid) if e["type"] == "inspect-session")client.patch(f"/api/cases/{cid}/entities/{before['id']}", json={"attrs": {"folder": "Angles"}})@@ -888,17 +888,17 @@ def test_session_rename_moves_the_spec_and_keeps_one_entity(client):f"/api/cases/{cid}/inspect/sessions",json={"rename_from": first["name"], "title": "Rooftop angle", "spec": spec},).json()- assert renamed["name"] == "rooftop-angle"+ assert renamed["name"] == "Rooftop angle"listing = client.get(f"/api/cases/{cid}/inspect/sessions").json()assert len(listing) == 1- assert listing[0]["name"] == "rooftop-angle" and listing[0]["title"] == "Rooftop angle"- assert client.get(f"/api/cases/{cid}/inspect/sessions/original").status_code == 404+ assert listing[0]["name"] == "Rooftop angle" and listing[0]["title"] == "Rooftop angle"+ assert client.get(f"/api/cases/{cid}/inspect/sessions/{first['name']}").status_code == 404after = [e for e in graph_read.entities(cid) if e["type"] == "inspect-session"]assert len(after) == 1assert after[0]["id"] == before["id"] # same entity, so its filing survives- assert after[0]["attrs"]["spec"] == "inspect/rooftop-angle.json"+ assert after[0]["attrs"]["spec"] == ".inspect/Rooftop angle.json"assert after[0]["attrs"]["folder"] == "Angles"@@ -907,14 +907,20 @@ def test_session_rename_keeps_the_creation_date(client):item = _upload(client, cid, "clip.png")spec = {"source": {"path": item["path"], "kind": "image"}, "frames": [], "collage": {"nodes": []}}- client.post(f"/api/cases/{cid}/inspect/sessions", json={"title": "Original", "spec": spec})- born = client.get(f"/api/cases/{cid}/inspect/sessions/original").json()["created_at"]+ original = client.post(+ f"/api/cases/{cid}/inspect/sessions", json={"title": "Original", "spec": spec}+ ).json()+ born = client.get(+ f"/api/cases/{cid}/inspect/sessions/{original['name']}"+ ).json()["created_at"]client.post(f"/api/cases/{cid}/inspect/sessions",- json={"rename_from": "original", "title": "Renamed", "spec": spec},+ json={"rename_from": original["name"], "title": "Renamed", "spec": spec},)- assert client.get(f"/api/cases/{cid}/inspect/sessions/renamed").json()["created_at"] == born+ assert client.get(+ f"/api/cases/{cid}/inspect/sessions/Renamed"+ ).json()["created_at"] == borndef test_session_rename_onto_a_taken_name_is_refused(client):@@ -925,16 +931,18 @@ def test_session_rename_onto_a_taken_name_is_refused(client):spec = {"source": {"path": item["path"], "kind": "image"}, "frames": [], "collage": {"nodes": []}}client.post(f"/api/cases/{cid}/inspect/sessions", json={"title": "Inspect 1", "spec": spec})- client.post(f"/api/cases/{cid}/inspect/sessions", json={"title": "Inspect 2", "spec": spec})+ second = client.post(+ f"/api/cases/{cid}/inspect/sessions", json={"title": "Inspect 2", "spec": spec}+ ).json()res = client.post(f"/api/cases/{cid}/inspect/sessions",- json={"rename_from": "inspect-2", "title": "Inspect 1", "spec": spec},+ json={"rename_from": second["name"], "title": "Inspect 1", "spec": spec},)assert res.status_code == 409listing = client.get(f"/api/cases/{cid}/inspect/sessions").json()- assert sorted(s["name"] for s in listing) == ["inspect-1", "inspect-2"]+ assert sorted(s["name"] for s in listing) == ["Inspect 1", "Inspect 2"]assert sum(1 for e in graph_read.entities(cid) if e["type"] == "inspect-session") == 2@@ -1048,12 +1056,12 @@ def test_saved_frame_name_is_scrubbed_for_the_filesystem(client):name = res["item"]["path"].rsplit("/", 1)[-1]assert not set(name) & set('/:*?"<>|\\')- # the title keeps what was typed; only the file on disk is scrubbed+ # The canonical, portable stem is both the filename and the title.media = next(m for m in client.get(f"/api/cases/{cid}/media").json()if m["path"] == res["item"]["path"])- assert media["title"] == 'a/b:c*d?"e'+ assert media["title"] == "a_b_c_d_e"def test_unnamed_frame_keeps_the_source_stem_and_tag(client):@@ -1121,11 +1129,12 @@ def test_duplicate_save_renames_the_media_it_landed_on(client):body["label"] = "Second name"again = client.post(f"/api/cases/{cid}/inspect/compose", json=body).json()assert again["duplicate"] is True- assert again["item"]["path"] == first["item"]["path"]+ assert again["item"]["path"] == "media/Second name.png"+ assert again["item"]["path"] != first["item"]["path"]media = next(m for m in client.get(f"/api/cases/{cid}/media").json()- if m["path"] == first["item"]["path"]+ if m["path"] == again["item"]["path"])assert media["title"] == "Second name"diff --git a/tests/test_layout.py b/tests/test_layout.pynew file mode 100644index 0000000..07d64c9--- /dev/null+++ b/tests/test_layout.py@@ -0,0 +1,237 @@+"""`layout.py` is the only module that knows the shape of a case folder.++The layout is about to move (the case tree gains a wrapper, several directories+become hidden), and that change is only cheap while every path has one origin.+The guard below is what keeps it that way: a module that joins a layout name+onto a path by hand fails this test, so the knowledge cannot leak back out one+drive-by at a time.+"""++from __future__ import annotations++import re+from pathlib import Path++import pytest++from azimut import layout+from azimut.api.naming import slugify+from azimut.engine.media import safe_filename+from azimut.engine.thumbnails import THUMB_GEN+from azimut.layout import CASE_SUBDIRS, TRASH_DIR+from azimut.workspace import Case, CaseError, _slugify++SOURCE = Path(__file__).resolve().parents[1] / "src" / "azimut"++#: Names that address something inside a case. Joining one of these onto a path+#: outside `layout.py` is what the guard refuses.+LAYOUT_NAMES = ("case.json", "case.db", "notes.md", TRASH_DIR, *CASE_SUBDIRS)++#: Matches path construction only — `staging / "case.db"`. An archive member or+#: a dict key spelled the same way is not a path and is left alone.+JOINS_LAYOUT_NAME = re.compile(+ r"/\s*[\"'](?:" + "|".join(re.escape(name) for name in LAYOUT_NAMES) + r")[\"']"+)+++def test_no_module_builds_a_case_path_by_hand() -> None:+ offenders = []+ for path in sorted(SOURCE.rglob("*.py")):+ if path.name == "layout.py":+ continue+ for number, line in enumerate(path.read_text(encoding="utf-8").splitlines(), 1):+ if JOINS_LAYOUT_NAME.search(line):+ offenders.append(f"{path.relative_to(SOURCE)}:{number}: {line.strip()}")+ assert not offenders, (+ "these build a case path by hand instead of asking `layout`:\n " + "\n ".join(offenders)+ )+++#: The longest path each family of artifact can produce, as a function of the+#: caps. Every level of directory the case tree gains has to appear here, or the+#: budget stops describing reality.+#:+#: Fixed lengths, from the code that writes them: a thumbnail is+#: `<sha256[:24]>-g<gen>.jpg` (`thumbnails.py`), a pasted proof asset is 16 hex+#: plus its extension (`api/proofs.py` ASSET_NAME), a trash group id is+#: `_new_id("t")`.+THUMB_NAME = 24 + len(f"-g{THUMB_GEN}") + len(".jpg")+ASSET_NAME = 16 + len(".webp")+TRASH_GROUP_ID = len("t_0123456789")+TRASH_SLOT = 3 # "999" worth of artifacts in one delete+++def _branches() -> dict[str, int]:+ """Length of the deepest path in each family, from the case root down.++ Includes the `azimut/` wrapper: every level the tree gains is spent out of+ the same budget, which is the point of recomputing it here rather than+ trusting a number written down once.+ """+ slug, media = layout.MAX_SLUG, layout.MAX_MEDIA_NAME+ wrapper = len(layout.TOOL_DIR) + 1+ return {name: wrapper + length for name, length in _tool_relative(slug, media).items()}+++def _tool_relative(slug: int, media: int) -> dict[str, int]:+ """Each branch spelled from the builders in `layout.py`, not from memory.++ A worst-case name is fed through the real function, so a directory that gets+ renamed or hidden moves this table by itself.+ """+ longest_media = "m" * media+ longest_name = "n" * slug+ longest_folder = "f" * layout.MAX_FOLDER_PATH+ return {+ "media file": len(f"media/{longest_media}"),+ "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,+ "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)),+ "proof export": len(layout.proof_export_rel(longest_name)),+ "draft": len(layout.draft_rel(longest_name)),+ "session": len(layout.session_rel(longest_name)),+ "grid": len(layout.grid_rel(longest_name)),+ "trash slot": len(f"{layout.TRASH_DIR}/") + TRASH_GROUP_ID + 1 + TRASH_SLOT,+ }+++def in_case_budget() -> int:+ """The longest path a case can hold, from its parent directory down."""+ return layout.MAX_CASE_SLUG + 1 + max(_branches().values())+++def in_scratch_budget() -> int:+ """The longest generated scratch path, from the workspace root down."""+ scratch_id = len("scratch_") + 10+ return len(".azimut/scratch/") + scratch_id + 1 + max(_branches().values())+++def test_the_shipped_budget_matches_the_tree_it_describes() -> None:+ """`layout.IN_CASE_BUDGET` is what Settings refuses a too-long root with, so+ a number that has drifted from the actual tree is worse than no number: it+ would approve a root that breaks cases on Windows.++ This is the only place the two can be compared, because the constant has to+ be available without walking a case.+ """+ assert layout.IN_CASE_BUDGET == in_case_budget(), (+ f"layout.IN_CASE_BUDGET says {layout.IN_CASE_BUDGET}, the tree needs "+ f"{in_case_budget()}. Update the constant, or shorten a branch:\n "+ + "\n ".join(f"{v:>4} {k}" for k, v in sorted(_branches().items(), key=lambda kv: -kv[1]))+ )+ assert layout.IN_SCRATCH_BUDGET == in_scratch_budget()+++def test_the_path_budget_leaves_room_for_a_real_workspace_root() -> None:+ """The whole Windows story is this subtraction.++ A case's longest path is a constant once every name is capped, so the only+ question left is where the workspace lives. Keep enough room for a genuinely+ deep root — a corporate OneDrive path runs to about 62 characters — and the+ limit stops being something to discover at write time.+ """+ room_for_the_root = layout.room_for_workspace_root()+ assert room_for_the_root >= 70, (+ f"the case tree needs {in_case_budget()} characters, leaving only "+ f"{room_for_the_root} for the workspace root. Lower a cap in layout.py, "+ f"or shorten a branch:\n "+ + "\n ".join(f"{v:>4} {k}" for k, v in sorted(_branches().items(), key=lambda kv: -kv[1]))+ )+++def test_the_root_that_fits_is_the_one_whose_deepest_case_path_fits() -> None:+ """The separator between the root and the case folder is counted once, in+ `room_for_workspace_root()`. Off by one here is a case that writes fine+ everywhere except the machine the budget exists for."""+ exactly = "r" * layout.room_for_workspace_root()+ assert layout.root_overflow(exactly) == 0+ assert len(f"{exactly}/") + in_case_budget() <= layout.WINDOWS_MAX_PATH+ assert layout.root_overflow(exactly + "r") == 1+++def test_the_trash_is_no_longer_the_longest_branch() -> None:+ """It was, before it stopped mirroring the case tree, and by enough to break+ Windows on its own. A change that puts it back on top is a regression."""+ branches = _branches()+ worst = max(branches, key=lambda name: branches[name])+ assert worst != "trash slot"+ assert branches["trash slot"] < branches["note"]+++def test_every_capped_name_is_actually_capped() -> None:+ """The caps are only real if the functions that build names apply them."""+ assert len(_slugify("x" * 300)) <= layout.MAX_CASE_SLUG+ assert len(slugify("x" * 300, "fallback")) <= layout.MAX_SLUG+ assert len(safe_filename("x" * 300 + ".mp4")) <= layout.MAX_MEDIA_NAME+++def test_a_folder_deeper_or_longer_than_the_budget_is_refused(tmp_workspace: str) -> None:+ case = Case.create("Folder bounds")+ case.add_folder("a/b/c/d") # at the depth limit, accepted+ with pytest.raises(CaseError):+ case.add_folder("a/b/c/d/e")+ with pytest.raises(CaseError):+ case.add_folder("x" * (layout.MAX_FOLDER_PATH + 1))+++def test_layout_answers_are_all_under_the_root(tmp_path: Path) -> None:+ root = tmp_path / "a-case"+ answers = [+ layout.manifest(root),+ layout.database(root),+ layout.notes_file(root),+ layout.media(root),+ layout.notes(root),+ layout.trash(root),+ *layout.content_dirs(root),+ ]+ for answer in answers:+ assert answer.is_relative_to(root)+++def test_content_dirs_covers_every_subdir_and_the_meta_pair(tmp_path: Path) -> None:+ root = tmp_path / "a-case"+ born = layout.content_dirs(root)+ assert [d.name for d in born[: len(CASE_SUBDIRS)]] == list(CASE_SUBDIRS)+ # the `.meta/` directories are born too, so an emptied case matches a new one+ assert set(born[len(CASE_SUBDIRS) :]) == {+ layout.media(root) / layout.META_DIR,+ layout.subdir(root, "proofs") / layout.META_DIR,+ }+ assert layout.trash(root).name not in CASE_SUBDIRS+++def test_subdir_refuses_a_name_outside_the_layout(tmp_path: Path) -> None:+ with pytest.raises(layout.LayoutError):+ layout.subdir(tmp_path, "elsewhere")+++def test_case_subdir_still_refuses_the_same_name(tmp_workspace: str) -> None:+ """`Case.subdir` speaks `CaseError` to its callers, whatever `layout` raises."""+ case = Case.create("Layout")+ with pytest.raises(CaseError):+ case.subdir("elsewhere")+++def test_layout_does_not_touch_the_filesystem(tmp_path: Path) -> None:+ """Answers are addresses, not creations — `Case` owns making directories."""+ root = tmp_path / "never-created"+ layout.media(root)+ layout.manifest(root)+ layout.content_dirs(root)+ assert not root.exists()+++def test_a_case_is_found_by_its_manifest(tmp_workspace: str) -> None:+ case = Case.create("Found by manifest")+ assert layout.is_case(case.path)++ renamed = case.path.with_name("renamed-from-outside")+ case.path.rename(renamed)+ assert layout.is_case(renamed)++ layout.manifest(renamed).unlink()+ assert not layout.is_case(renamed)diff --git a/tests/test_links_api.py b/tests/test_links_api.pyindex 633c2d5..f1ca9ef 100644--- a/tests/test_links_api.py+++ b/tests/test_links_api.py@@ -55,8 +55,7 @@ def _new_case(client, name):return client.post("/api/cases", json={"name": name}).json()["id"]-# The filename follows the title everywhere (api/naming.slugify), so these pass-# short titles and read the slug straight off them.+# The filename stem is the title everywhere, preserving its readable spelling.def _save_proof(client, cid, title, srcs):spec = {"panels": [{"id": f"p{i}", "src": s} for i, s in enumerate(srcs)]}body = {"title": title, "spec": spec, "png_base64": _png_b64()}@@ -78,7 +77,7 @@ def test_proof_save_links_to_its_panels(client):_save_proof(client, cid, "Strike proof", [a, b])- proof = _entity(client, cid, spec="proofs/strike-proof.json")+ proof = _entity(client, cid, spec="proofs/.meta/Strike proof.json")targets = {lk["to"] for lk in _links(client, cid, "derived-from") if lk["from"] == proof["id"]}assert targets == {_entity(client, cid, path=a)["id"], _entity(client, cid, path=b)["id"]}@@ -129,13 +128,13 @@ def test_post_save_links_to_its_proof_and_media(client):client.post(f"/api/cases/{cid}/drafts",- json={"title": "Thread", "state": {"proofPng": "proofs/p.png", "mediaPath": a}},+ json={"title": "Thread", "state": {"proofPng": "proofs/P.png", "mediaPath": a}},)- post = _entity(client, cid, draft="exports/thread.json")+ post = _entity(client, cid, draft=".drafts/Thread.json")targets = {lk["to"] for lk in _links(client, cid, "derived-from") if lk["from"] == post["id"]}assert targets == {- _entity(client, cid, spec="proofs/p.json")["id"],+ _entity(client, cid, spec="proofs/.meta/P.json")["id"],_entity(client, cid, path=a)["id"],}@@ -156,7 +155,7 @@ def test_post_save_links_to_every_selected_media_file(client):},)- post = _entity(client, cid, draft="exports/thread.json")+ post = _entity(client, cid, draft=".drafts/Thread.json")targets = {lk["to"] for lk in _links(client, cid, "derived-from") if lk["from"] == post["id"]}assert targets == {_entity(client, cid, path=a)["id"], _entity(client, cid, path=b)["id"]}@@ -167,7 +166,7 @@ def test_session_save_depends_on_its_subject(client):_save_session(client, cid, "Look at a", a)- session = _entity(client, cid, spec="inspect/look-at-a.json")+ session = _entity(client, cid, spec=".inspect/Look at a.json")depends = _links(client, cid, "depends-on")assert len(depends) == 1assert depends[0]["from"] == session["id"]@@ -241,7 +240,7 @@ def test_a_source_deleted_before_the_save_leaves_a_tombstone(client):_save_proof(client, cid, "P", [a])- proof = _entity(client, cid, spec="proofs/p.json")+ proof = _entity(client, cid, spec="proofs/.meta/P.json")assert _links(client, cid) == []assert proof["attrs"]["lost_sources"] == [{"path": a, "at": proof["attrs"]["lost_sources"][0]["at"]}@@ -288,12 +287,12 @@ def test_deleting_a_subject_deletes_its_session_but_spares_its_outputs(client):assert res["status"] == "deleted"# the session is nothing without its subject: it goes, file and all- assert _entity(client, cid, spec="inspect/s.json") is None- assert client.get(f"/api/cases/{cid}/inspect/sessions/s").status_code == 404+ assert _entity(client, cid, spec=".inspect/S.json") is None+ assert client.get(f"/api/cases/{cid}/inspect/sessions/S").status_code == 404# the proof stands on its own: it stays, and its export is untouched- proof = _entity(client, cid, spec="proofs/p.json")+ proof = _entity(client, cid, spec="proofs/.meta/P.json")assert proof is not None- assert client.get(f"/files/{cid}/proofs/p.png").status_code == 200+ assert client.get(f"/files/{cid}/proofs/P.png").status_code == 200def test_a_survivor_keeps_a_tombstone_of_what_it_lost(client):@@ -305,12 +304,12 @@ def test_a_survivor_keeps_a_tombstone_of_what_it_lost(client):client.delete(f"/api/cases/{cid}/entities/{subject['id']}")- lost = _entity(client, cid, spec="proofs/p.json")["attrs"]["lost_sources"]+ lost = _entity(client, cid, spec="proofs/.meta/P.json")["attrs"]["lost_sources"]assert len(lost) == 1# sha256 + path are what make the loss auditable six months laterassert lost[0]["sha256"] == shaassert lost[0]["path"] == a- assert lost[0]["label"] == "strike.png"+ assert lost[0]["label"] == "strike"assert lost[0]["at"].endswith("Z")@@ -325,7 +324,7 @@ def test_a_survivor_is_only_scarred_by_what_it_derived_from(client):client.delete(f"/api/cases/{cid}/entities/{_entity(client, cid, path=a)['id']}")- lost = _entity(client, cid, spec="proofs/p.json")["attrs"]["lost_sources"]+ lost = _entity(client, cid, spec="proofs/.meta/P.json")["attrs"]["lost_sources"]assert [t["path"] for t in lost] == [a]@@ -339,7 +338,7 @@ def test_tombstones_never_stack_on_a_second_delete(client):_save_proof(client, cid, "P", [a, b]) # re-save still names the dead pathclient.delete(f"/api/cases/{cid}/entities/{_entity(client, cid, path=b)['id']}")- lost = _entity(client, cid, spec="proofs/p.json")["attrs"]["lost_sources"]+ lost = _entity(client, cid, spec="proofs/.meta/P.json")["attrs"]["lost_sources"]assert sorted(t["path"] for t in lost) == [a, b]@@ -351,16 +350,16 @@ def test_deleting_a_proof_spares_the_post_that_announces_it(client):_save_proof(client, cid, "P", [a])client.post(f"/api/cases/{cid}/drafts",- json={"title": "T", "state": {"proofPng": "proofs/p.png", "description": "kept"}},+ json={"title": "T", "state": {"proofPng": "proofs/P.png", "description": "kept"}},)- client.delete(f"/api/cases/{cid}/entities/{_entity(client, cid, spec='proofs/p.json')['id']}")+ client.delete(f"/api/cases/{cid}/entities/{_entity(client, cid, spec='proofs/.meta/P.json')['id']}")- post = _entity(client, cid, draft="exports/t.json")+ post = _entity(client, cid, draft=".drafts/T.json")assert post is not None- assert post["attrs"]["lost_sources"][0]["path"] == "proofs/p.png"+ assert post["attrs"]["lost_sources"][0]["path"] == "proofs/P.png"# the thread text itself is untouched- assert client.get(f"/api/cases/{cid}/drafts/t").json()["state"]["description"] == "kept"+ assert client.get(f"/api/cases/{cid}/drafts/T").json()["state"]["description"] == "kept"def test_cascade_is_transitive_through_depends_on(client):@@ -369,17 +368,17 @@ def test_cascade_is_transitive_through_depends_on(client):_save_session(client, cid, "S1", a)# a second session opened over the first one's spec — contrived, but it is# what a future tool nesting sessions would produce, and it must follow.- s1 = _entity(client, cid, spec="inspect/s1.json")+ s1 = _entity(client, cid, spec=".inspect/S1.json")s2 = client.post(f"/api/cases/{cid}/entities",- json={"type": "inspect-session", "label": "S2", "attrs": {"spec": "inspect/s2.json"}},+ json={"type": "inspect-session", "label": "S2", "attrs": {"spec": ".inspect/s2.json"}},).json()_add_link(cid, s2["id"], s1["id"], "depends-on")client.delete(f"/api/cases/{cid}/entities/{_entity(client, cid, path=a)['id']}")- assert _entity(client, cid, spec="inspect/s1.json") is None- assert _entity(client, cid, spec="inspect/s2.json") is None+ assert _entity(client, cid, spec=".inspect/S1.json") is None+ assert _entity(client, cid, spec=".inspect/s2.json") is Nonedef test_a_session_over_a_frame_survives_the_frames_video_going(client):@@ -400,8 +399,8 @@ def test_a_session_over_a_frame_survives_the_frames_video_going(client):client.delete(f"/api/cases/{cid}/entities/{_entity(client, cid, path=video)['id']}")- assert _entity(client, cid, spec="inspect/on-the-video.json") is None- assert _entity(client, cid, spec="inspect/on-the-frame.json") is not None+ assert _entity(client, cid, spec=".inspect/On the video.json") is None+ assert _entity(client, cid, spec=".inspect/On the frame.json") is not Noneassert _entity(client, cid, path=frame) is not None@@ -428,8 +427,8 @@ def test_the_media_library_delete_honours_the_graph(client):client.delete(f"/api/cases/{cid}/media?path={a}")- assert _entity(client, cid, spec="inspect/s.json") is None- assert _entity(client, cid, spec="proofs/p.json")["attrs"]["lost_sources"][0]["path"] == a+ assert _entity(client, cid, spec=".inspect/S.json") is None+ assert _entity(client, cid, spec="proofs/.meta/P.json")["attrs"]["lost_sources"][0]["path"] == adef test_the_inspect_delete_honours_the_graph(client):@@ -437,10 +436,10 @@ def test_the_inspect_delete_honours_the_graph(client):a = _upload(client, cid, "a.png")["item"]["path"]_save_session(client, cid, "S", a)- client.delete(f"/api/cases/{cid}/inspect/sessions/s")+ client.delete(f"/api/cases/{cid}/inspect/sessions/S")# a session deleted on its own takes nothing with it: its subject stands- assert _entity(client, cid, spec="inspect/s.json") is None+ assert _entity(client, cid, spec=".inspect/S.json") is Noneassert _entity(client, cid, path=a) is not Noneassert _links(client, cid) == []@@ -452,7 +451,7 @@ def test_the_satellite_delete_honours_the_graph(client):client.delete(f"/api/cases/{cid}/satellite?path={a}")- assert _entity(client, cid, spec="inspect/s.json") is None+ assert _entity(client, cid, spec=".inspect/S.json") is Nonedef test_a_tool_delete_still_drops_an_unfiled_artifact(client):@@ -460,13 +459,13 @@ def test_a_tool_delete_still_drops_an_unfiled_artifact(client):cid = _new_case(client, "Orphan")case = client.get(f"/api/cases/{cid}").json()client.post(f"/api/cases/{cid}/proofs", json={"title": "P", "spec": {"panels": []}, "name": "p"})- proof = _entity(client, cid, spec="proofs/p.json")+ proof = _entity(client, cid, spec="proofs/.meta/P.json")client.delete(f"/api/cases/{cid}/entities/{proof['id']}") # entity + files gone# re-create the file alone, with no entity behind itclient.post(f"/api/cases/{cid}/proofs", json={"title": "P", "spec": {"panels": []}, "name": "p"})- client.delete(f"/api/cases/{cid}/entities/{_entity(client, cid, spec='proofs/p.json')['id']}")- assert client.get(f"/api/cases/{cid}/proofs/p").status_code == 404+ client.delete(f"/api/cases/{cid}/entities/{_entity(client, cid, spec='proofs/.meta/P.json')['id']}")+ assert client.get(f"/api/cases/{cid}/proofs/P").status_code == 404assert case["id"] == cid@@ -511,7 +510,7 @@ def test_chain_endpoint_reads_sources_and_dependents(client):_save_proof(client, cid, "P", [a])media = _entity(client, cid, path=a)- proof = _entity(client, cid, spec="proofs/p.json")+ proof = _entity(client, cid, spec="proofs/.meta/P.json")proof_chain = client.get(f"/api/cases/{cid}/entities/{proof['id']}/chain").json()assert proof_chain["entity"]["id"] == proof["id"]@@ -532,7 +531,7 @@ def test_chain_endpoint_includes_lost_sources_and_404s(client):client.delete(f"/api/cases/{cid}/media?path={a}")_save_proof(client, cid, "P", [a]) # source gone → tombstone, no edge- proof = _entity(client, cid, spec="proofs/p.json")+ proof = _entity(client, cid, spec="proofs/.meta/P.json")chain = client.get(f"/api/cases/{cid}/entities/{proof['id']}/chain").json()assert [t["path"] for t in chain["lost"]] == [a]assert chain["empty"] is False@@ -623,7 +622,7 @@ def test_derivation_endpoint_returns_the_closure_and_404s(client):a = _upload(client, cid, "a.png", _png_bytes((1, 2, 3)))["item"]["path"]b = _upload(client, cid, "b.png", _png_bytes((4, 5, 6)))["item"]["path"]_save_proof(client, cid, "P", [a, b])- proof = _entity(client, cid, spec="proofs/p.json")+ proof = _entity(client, cid, spec="proofs/.meta/P.json")sub = client.get(f"/api/cases/{cid}/entities/{proof['id']}/derivation").json()ids = {e["id"] for e in sub["entities"]}diff --git a/tests/test_media_api.py b/tests/test_media_api.pyindex 3d8817a..fc16a31 100644--- a/tests/test_media_api.py+++ b/tests/test_media_api.py@@ -1,8 +1,10 @@"""Media Library: upload, dedupe, listing, file serving, deletion."""import io+import jsonimport graph_read+import pytestimport timefrom PIL import Image@@ -44,6 +46,8 @@ def test_upload_and_list(client):assert res["duplicate"] is Falseitem = res["item"]assert item["kind"] == "image"+ assert item["title"] == "frame one"+ assert item["filename"] == "frame one.png"assert len(item["sha256"]) == 64assert item["thumbnail"] # Pillow thumbnail for images always works@@ -53,6 +57,7 @@ def test_upload_and_list(client):# media entity was filed with provenanceentities = graph_read.entities(cid)assert entities[0]["type"] == "media"+ assert entities[0]["label"] == "frame one"assert entities[0]["provenance"]["by"] == "media-library"# the file and its thumbnail are served@@ -230,8 +235,14 @@ def test_media_page_query_matches_title_notes_folder(client):# folder + a source/title term both matchassert client.get(f"/api/cases/{cid}/media/page", params={"q": "harbour"}).json()["total"] == 1# two space-split terms must both be present (AND)- assert client.get(f"/api/cases/{cid}/media/page", params={"q": "bridge river"}).json()["total"] == 1- assert client.get(f"/api/cases/{cid}/media/page", params={"q": "bridge harbour"}).json()["total"] == 0+ assert (+ client.get(f"/api/cases/{cid}/media/page", params={"q": "bridge river"}).json()["total"]+ == 1+ )+ assert (+ client.get(f"/api/cases/{cid}/media/page", params={"q": "bridge harbour"}).json()["total"]+ == 0+ )def test_media_page_kind_and_folder_filters(client):@@ -241,15 +252,17 @@ def test_media_page_kind_and_folder_filters(client):_set(client, cid, a["path"], folder="kyiv")assert client.get(f"/api/cases/{cid}/media/page", params={"kind": "image"}).json()["total"] == 2- assert client.get(f"/api/cases/{cid}/media/page", params={"folder": "kyiv"}).json()["total"] == 1+ assert (+ client.get(f"/api/cases/{cid}/media/page", params={"folder": "kyiv"}).json()["total"] == 1+ )def test_media_page_sort_name_and_size(client):cid = client.post("/api/cases", json={"name": "Sort"}).json()["id"]small = _upload(client, cid, "s.png", _png_bytes(color=(5, 0, 0), size=(16, 16))).json()["item"]big = _upload(client, cid, "b.png", _png_bytes(color=(6, 0, 0), size=(256, 256))).json()["item"]- _set(client, cid, small["path"], title="Zebra")- _set(client, cid, big["path"], title="Alpha")+ small = _set(client, cid, small["path"], title="Zebra")+ big = _set(client, cid, big["path"], title="Alpha")by_name = client.get(f"/api/cases/{cid}/media/page", params={"sort": "name"}).json()assert [i["title"] for i in by_name["items"]] == ["Alpha", "Zebra"]@@ -307,9 +320,7 @@ def test_media_page_filters_categories_without_page_local_counts(client):assert images["facets"]["category_counts"]["image"] == 1assert images["facets"]["category_counts"]["satellite"] == 1- maps = client.get(- f"/api/cases/{cid}/media/page", params={"category": "satellite"}- ).json()+ maps = client.get(f"/api/cases/{cid}/media/page", params={"category": "satellite"}).json()assert [item["path"] for item in maps["items"]] == [satellite["path"]]@@ -421,6 +432,9 @@ def test_update_media_notes_and_folder(client):def test_update_media_title(client):+ from azimut import layout+ from azimut.workspace import Case+cid = client.post("/api/cases", json={"name": "Title"}).json()["id"]item = _upload(client, cid, "img.png", _png_bytes()).json()["item"]@@ -430,21 +444,154 @@ def test_update_media_title(client):).json()# the media's own title lives on the sidecar (shown in the Media tab)assert updated["title"] == "Strike video — Kharkiv"+ assert updated["filename"] == "Strike video — Kharkiv.png"+ assert updated["path"] == "media/Strike video — Kharkiv.png"+ case = Case.open(cid)+ assert not case.resolve_inside(item["path"]).exists()+ assert not case.resolve_inside(layout.sidecar_rel("img.png")).exists()+ assert case.resolve_inside(updated["path"]).is_file()+ assert case.resolve_inside(layout.sidecar_rel(updated["filename"])).is_file()# the entity label mirrors the title so the case sidebar stays in syncentities = graph_read.entities(cid)assert entities[0]["label"] == "Strike video — Kharkiv"- # clearing the title reverts to no custom title+ # An empty edit keeps the current filename stem: media no longer have a+ # second, nullable display name that can drift from the file.cleared = client.patch(- f"/api/cases/{cid}/media", json={"path": item["path"], "title": ""}+ f"/api/cases/{cid}/media", json={"path": updated["path"], "title": ""}).json()- assert "title" not in cleared+ assert cleared["title"] == "Strike video — Kharkiv"+ assert cleared["filename"] == "Strike video — Kharkiv.png"+ assert cleared["path"] == "media/Strike video — Kharkiv.png"- # the entity label falls back to the filename — it must not freeze on the- # old title once that title is gone+ # The graph label is the same stem too.entities = graph_read.entities(cid)- assert entities[0]["label"] == item["path"].rsplit("/", 1)[-1]+ assert entities[0]["label"] == "Strike video — Kharkiv"+++def test_media_rename_rewrites_exact_references_everywhere(client):+ from azimut import layout+ from azimut.engine import media as media_engine+ from azimut.workspace import Case++ cid = client.post("/api/cases", json={"name": "Rename references"}).json()["id"]+ source = _upload(client, cid, "source.png", _png_bytes()).json()["item"]+ derived = _upload(client, cid, "derived.png", _png_bytes(color=(20, 40, 60))).json()["item"]+ case = Case.open(cid)+ old = source["path"]+ sentence = f"Analyst prose mentions {old} but is not a path field."+ media_engine.merge_item(+ case,+ derived["path"],+ {+ "source": {+ "type": "inspect",+ "from": old,+ "sources": [old],+ "description": sentence,+ }+ },+ )+ reference = case.add_entity(+ "bookmark",+ "Reference",+ {"path": old, "nested": [old], "notes": sentence},+ by="user",+ )+ job = case.enqueue_job(+ "thumbnail",+ key=old,+ payload={"path": old, "nested": [old], "notes": sentence},+ )+ records = {+ layout.proof_spec_rel("Ref proof"): {"panels": [{"src": old}], "notes": sentence},+ layout.session_rel("Ref inspect"): {"source": {"path": old}, "notes": sentence},+ layout.draft_rel("Ref post"): {+ "state": {"mediaPath": old, "mediaPaths": [old]},+ "notes": sentence,+ },+ layout.grid_rel("ref-search"): {"source": old, "notes": sentence},+ }+ for rel, data in records.items():+ path = case.resolve_inside(rel)+ path.parent.mkdir(parents=True, exist_ok=True)+ path.write_text(json.dumps(data), encoding="utf-8")++ renamed = media_engine.update_media(case, old, {"title": "Canonical source"})+ new = renamed["path"]++ dependent = media_engine.read_item(case, derived["path"])+ assert dependent["source"]["from"] == new+ assert dependent["source"]["sources"] == [new]+ assert dependent["source"]["description"] == sentence+ entity = case.get_entity(reference["id"])+ assert entity["attrs"]["path"] == new+ assert entity["attrs"]["nested"] == [new]+ assert entity["attrs"]["notes"] == sentence+ queued = case.get_job(job["id"])+ assert queued["key"] == new+ assert queued["payload"]["path"] == new+ assert queued["payload"]["nested"] == [new]+ assert queued["payload"]["notes"] == sentence+ proof = json.loads(+ case.resolve_inside(layout.proof_spec_rel("Ref proof")).read_text(encoding="utf-8")+ )+ inspect = json.loads(+ case.resolve_inside(layout.session_rel("Ref inspect")).read_text(encoding="utf-8")+ )+ post = json.loads(case.resolve_inside(layout.draft_rel("Ref post")).read_text(encoding="utf-8"))+ search = json.loads(+ case.resolve_inside(layout.grid_rel("ref-search")).read_text(encoding="utf-8")+ )+ assert proof["panels"][0]["src"] == new+ assert inspect["source"]["path"] == new+ assert post["state"]["mediaPath"] == new+ assert post["state"]["mediaPaths"] == [new]+ assert search["source"] == new+ assert {proof["notes"], inspect["notes"], post["notes"], search["notes"]} == {sentence}+++def test_media_rename_recovers_after_files_moved_before_database_update(client, monkeypatch):+ from azimut import layout+ from azimut.engine import media as media_engine+ from azimut.workspace import Case++ cid = client.post("/api/cases", json={"name": "Rename recovery"}).json()["id"]+ item = _upload(client, cid, "before.png", _png_bytes()).json()["item"]+ case = Case.open(cid)+ real_replace = Case.replace_path_references++ def interrupt(_case, _old, _new):+ raise RuntimeError("simulated interruption")++ monkeypatch.setattr(Case, "replace_path_references", interrupt)+ with pytest.raises(RuntimeError, match="simulated interruption"):+ media_engine.rename_media(case, item["path"], "After")++ journal = case.resolve_inside(f"{layout.DATA_DIR}/rename.json")+ assert journal.is_file()+ assert case.resolve_inside("media/After.png").is_file()+ assert not case.resolve_inside(item["path"]).exists()++ monkeypatch.setattr(Case, "replace_path_references", real_replace)+ media_engine.recover_media_rename(case)++ recovered = media_engine.read_item(case, "media/After.png")+ assert recovered["title"] == "After"+ assert case.find_entity(attr="path", value="media/After.png")["label"] == "After"+ assert not journal.exists()+++def test_media_rename_uses_portable_case_insensitive_collisions(client):+ cid = client.post("/api/cases", json={"name": "Portable names"}).json()["id"]+ _upload(client, cid, "Clip.png", _png_bytes()).json()["item"]+ other = _upload(client, cid, "other.png", _png_bytes(color=(90, 80, 70))).json()["item"]++ renamed = _set(client, cid, other["path"], title="clip")++ assert renamed["title"] == "clip-1"+ assert renamed["filename"] == "clip-1.png"def test_update_media_clear_notes(client):@@ -584,7 +731,10 @@ def test_download_reports_multi_without_downloading(client, monkeypatch):"id": "p2","title": "photo 2","ext": "jpg",- "thumbnails": [{"url": "https://x.test/p2-small.jpg"}, {"url": "https://x.test/p2.jpg"}],+ "thumbnails": [+ {"url": "https://x.test/p2-small.jpg"},+ {"url": "https://x.test/p2.jpg"},+ ],},{"id": "p3", "title": None, "ext": "mp4"},]@@ -894,7 +1044,10 @@ def test_download_picks_telegram_photo_from_mixed_post(client, monkeypatch):cid = client.post("/api/cases", json={"name": "TelegramPickPhoto"}).json()["id"]case = Case.open(cid)- entries = [{"id": "v1", "title": "clip one", "ext": "mp4"}, {"id": "v2", "title": "clip two", "ext": "mp4"}]+ entries = [+ {"id": "v1", "title": "clip one", "ext": "mp4"},+ {"id": "v2", "title": "clip two", "ext": "mp4"},+ ]_install_fake_ydl(monkeypatch, lambda ydl, url, download: {"_type": "playlist", "entries": entries})@@ -926,7 +1079,10 @@ def test_download_picks_yt_dlp_video_from_mixed_post(client, monkeypatch):cid = client.post("/api/cases", json={"name": "TelegramPickVideo"}).json()["id"]case = Case.open(cid)- entries = [{"id": "v1", "title": "clip one", "ext": "mp4"}, {"id": "v2", "title": "clip two", "ext": "mp4"}]+ entries = [+ {"id": "v1", "title": "clip one", "ext": "mp4"},+ {"id": "v2", "title": "clip two", "ext": "mp4"},+ ]_install_fake_ydl(monkeypatch, lambda ydl, url, download: {"_type": "playlist", "entries": entries})@@ -965,7 +1121,9 @@ def test_concurrent_downloads_dont_lose_entities(client, monkeypatch):# via sha256 and mask what this test is actually checking (entity loss,# not the separate dedup-check race)_install_fake_ydl(- monkeypatch, extract_info, content_fn=lambda info: _png_bytes(color=(int(info["id"][4:]), 0, 0))+ monkeypatch,+ extract_info,+ content_fn=lambda info: _png_bytes(color=(int(info["id"][4:]), 0, 0)),)errors = []@@ -1140,10 +1298,10 @@ def test_windows_chromium_returns_guidance(client, monkeypatch):def test_cookies_file_threads_absolute_cookiefile(client, monkeypatch):- """A cookies.txt source hands yt-dlp an absolute cookiefile path (resolved- against the workspace when relative)."""+ """A cookies.txt source hands yt-dlp its protected absolute path."""import os+ from azimut import configfrom azimut.engine import media as media_enginefrom azimut.workspace import Case@@ -1152,7 +1310,7 @@ def test_cookies_file_threads_absolute_cookiefile(client, monkeypatch):def extract_info(ydl, url, download):assert os.path.isabs(ydl.opts["cookiefile"])- assert ydl.opts["cookiefile"].endswith("cookies.txt")+ assert ydl.opts["cookiefile"] == str(config.cookies_file_path())return {"id": "abc123", "title": "Gated via file"}_install_fake_ydl(monkeypatch, extract_info)@@ -1296,25 +1454,41 @@ def test_naming_an_item_survives_the_enrichment_of_the_same_sidecar(client, monkrel = _upload(client, cid, "shot.png", _png_bytes()).json()["item"]["path"]case = Case.open(cid)- start = threading.Barrier(2)+ enrichment_started = threading.Event()+ let_enrichment_finish = threading.Event()+ real_write = media_engine._write_sidecar+ blocked_once = False++ def block_enrichment_write(path, data):+ nonlocal blocked_once+ if data.get("dhash") and not blocked_once:+ blocked_once = True+ enrichment_started.set()+ assert let_enrichment_finish.wait(timeout=5)+ real_write(path, data)++ monkeypatch.setattr(media_engine, "_write_sidecar", block_enrichment_write)+ enrich_thread = threading.Thread(+ target=media_engine.merge_item,+ args=(case, rel, {"dhash": "ff00ff00ff00ff00"}),+ )+ enrich_thread.start()+ assert enrichment_started.wait(timeout=5)- def name_it():- start.wait(timeout=5)- for _ in range(20):- media_engine.update_media(case, rel, {"title": "Yard panorama"})+ renamed = {}- def enrich_it():- start.wait(timeout=5)- for _ in range(20):- media_engine.merge_item(case, rel, {"dhash": "ff00ff00ff00ff00"})+ def name_it():+ renamed.update(media_engine.update_media(case, rel, {"title": "Yard panorama"}))- threads = [threading.Thread(target=name_it), threading.Thread(target=enrich_it)]- for t in threads:- t.start()- for t in threads:- t.join(timeout=10)+ name_thread = threading.Thread(target=name_it)+ name_thread.start()+ let_enrichment_finish.set()+ enrich_thread.join(timeout=10)+ name_thread.join(timeout=10)+ assert not enrich_thread.is_alive()+ assert not name_thread.is_alive()- item = media_engine.read_item(case, rel)+ item = media_engine.read_item(case, renamed["path"])assert item["title"] == "Yard panorama"assert item["dhash"] == "ff00ff00ff00ff00"@@ -1409,8 +1583,14 @@ def test_the_browse_index_leaves_the_metadata_dumps_to_the_per_item_read(client)def test_the_per_item_read_refuses_a_path_outside_the_case(client):cid = client.post("/api/cases", json={"name": "Traversal"}).json()["id"]- assert client.get(f"/api/cases/{cid}/media/item", params={"path": "../../etc/passwd"}).status_code == 400- assert client.get(f"/api/cases/{cid}/media/item", params={"path": "media/gone.png"}).status_code == 404+ assert (+ client.get(f"/api/cases/{cid}/media/item", params={"path": "../../etc/passwd"}).status_code+ == 400+ )+ assert (+ client.get(f"/api/cases/{cid}/media/item", params={"path": "media/gone.png"}).status_code+ == 404+ )def test_enrich_counts_the_jobs_the_queue_took(client):@@ -1426,10 +1606,10 @@ def test_enrich_counts_the_jobs_the_queue_took(client):).json()["item"]assert audio["kind"] not in ("image", "video")- assert client.post(- f"/api/cases/{cid}/media/enrich", json={"path": audio["path"]}- ).json() == {"queued": 0}- assert client.post(- f"/api/cases/{cid}/media/enrich", json={"path": image["path"]}- ).json() == {"queued": 1}+ assert client.post(f"/api/cases/{cid}/media/enrich", json={"path": audio["path"]}).json() == {+ "queued": 0+ }+ assert client.post(f"/api/cases/{cid}/media/enrich", json={"path": image["path"]}).json() == {+ "queued": 1+ }workqueue.wait_until_idle()diff --git a/tests/test_migrations.py b/tests/test_migrations.pyindex 39763bf..a2ffac9 100644--- a/tests/test_migrations.py+++ b/tests/test_migrations.py@@ -5,12 +5,14 @@ migrations to prove the runners, and pin the "same schema doesn't rewrite" and"newer is refused" invariants that hold with zero migrations."""import json+import shutilimport pytest-from legacy_case import write_legacy_json_case+from legacy_case import rewind_case, unwrap_case, write_legacy_json_case-from azimut import config, workspace-from azimut.workspace import Case, CaseError+from azimut import config, layout, workspace+from azimut.engine import trash as trash_engine+from azimut.workspace import Case, CaseError, ensure_dir# -- case.json ------------------------------------------------------------@@ -25,10 +27,36 @@ def test_open_current_schema_does_not_rewrite(tmp_workspace):reopened = Case.open(case.id)assert reopened.read()["updated_at"] == before- backups = list(case.path.glob("case.pre-migrate*.json"))+ backups = list(case.tool_root.glob("case.pre-migrate*.json"))assert backups == []+def test_startup_migrates_old_permanent_and_scratch_cases_as_one_pass(tmp_workspace):+ permanent = write_legacy_json_case("Old permanent")+ scratch = write_legacy_json_case("Old scratch", scratch=True)+ root = config.workspace_root()+ old_cases = root / "cases"+ old_scratch = root / "scratch"+ old_cases.mkdir()+ old_scratch.mkdir()+ permanent.path.rename(old_cases / permanent.id)+ scratch.path.rename(old_scratch / scratch.id)++ from azimut.server import create_app++ create_app()++ migrated_permanent = Case.open(permanent.id)+ migrated_scratch = Case.open(scratch.id)+ assert migrated_permanent.path == root / permanent.id+ assert migrated_scratch.path == config.scratch_dir() / scratch.id+ assert migrated_scratch.is_scratch is True+ assert migrated_permanent.read()["azimut"]["schema"] == workspace.CASE_SCHEMA+ assert migrated_scratch.read()["azimut"]["schema"] == workspace.CASE_SCHEMA+ assert not (root / "cases").exists()+ assert not (root / "scratch").exists()++def test_open_newer_schema_is_refused(tmp_workspace):case = Case.create("From the future")data = case.read()@@ -56,7 +84,7 @@ def test_open_older_schema_migrates_and_backs_up(tmp_workspace, monkeypatch):assert migrated["azimut"]["schema"] == 2assert migrated["attrs"]["migrated"] is True- backup = case.path / "case.pre-migrate-v1.json"+ backup = case.tool_root / "case.pre-migrate-v1.json"assert backup.exists()assert json.loads(backup.read_text())["azimut"]["schema"] == 1@@ -71,7 +99,7 @@ def test_migration_backup_is_not_overwritten(tmp_workspace, monkeypatch):monkeypatch.setattr(workspace, "CASE_MIGRATIONS", {1: lambda d: d})Case.open(case.id)- backup = case.path / "case.pre-migrate-v1.json"+ backup = case.tool_root / "case.pre-migrate-v1.json"first = backup.read_text()# Force another migration pass from the same starting schema.@@ -87,19 +115,25 @@ def test_note_bodies_migrate_out_of_case_json(tmp_workspace):case = write_legacy_json_case("Legacy notes",schema=1,- entities=[{- "id": "e_note", "type": "note", "label": "Lead",- "attrs": {"folder": "Research", "content": "# Saved lead"},- "provenance": {"by": "user", "at": "2026-01-01T00:00:00Z", "status": "confirmed"},- }],+ entities=[+ {+ "id": "e_note",+ "type": "note",+ "label": "Lead",+ "attrs": {"folder": "Research", "content": "# Saved lead"},+ "provenance": {"by": "user", "at": "2026-01-01T00:00:00Z", "status": "confirmed"},+ }+ ],)migrated = Case.open(case.id).snapshot()note = migrated["entities"][0]- assert note["attrs"] == {"folder": "Research", "path": "notes/e_note.md"}- assert (case.path / "notes/e_note.md").read_text(encoding="utf-8") == "# Saved lead"- assert (case.path / "case.pre-migrate-v1.json").exists()+ # The body left case.json, and the layout normalizer named the file after+ # the note's title inside its folder.+ assert note["attrs"] == {"folder": "Research", "path": "notes/Research/Lead.md"}+ assert case.resolve_inside(note["attrs"]["path"]).read_text(encoding="utf-8") == "# Saved lead"+ assert (case.tool_root / "case.pre-migrate-v1.json").exists()# -- storage activation: legacy json -> sqlite on open --------------------@@ -112,7 +146,13 @@ def test_open_activates_sqlite_and_preserves_the_graph(tmp_workspace):legacy = write_legacy_json_case("To migrate",entities=[- {"id": "e_a", "type": "person", "label": "Ada", "attrs": {"handle": "@ada"}, "provenance": prov},+ {+ "id": "e_a",+ "type": "person",+ "label": "Ada",+ "attrs": {"handle": "@ada"},+ "provenance": prov,+ },{"id": "e_b", "type": "account", "label": "acct", "attrs": {}, "provenance": prov},],links=[{"id": "l_1", "from": "e_a", "to": "e_b", "type": "owns", "provenance": prov}],@@ -124,8 +164,8 @@ def test_open_activates_sqlite_and_preserves_the_graph(tmp_workspace):manifest = opened.read()assert manifest["azimut"] == {"schema": workspace.CASE_SCHEMA, "storage": "sqlite"}assert "entities" not in manifest # case.json is a manifest now- assert (opened.path / "case.db").exists()- assert (opened.path / "case.pre-migrate-v2.json").exists()+ assert opened.db_path.exists()+ assert (opened.tool_root / "case.pre-migrate-v2.json").exists()snap = opened.snapshot()assert {e["id"] for e in snap["entities"]} == {"e_a", "e_b"}@@ -173,7 +213,7 @@ def test_failed_activation_leaves_the_json_case_usable(tmp_workspace, monkeypatcreopened_json = json.loads(legacy.json_path.read_text(encoding="utf-8"))assert reopened_json["azimut"]["storage"] == "json"assert reopened_json["entities"][0]["label"] == "Ada"- assert not (legacy.path / "case.db").exists()+ assert not legacy.db_path.exists()# with the fault cleared (restore just the converter, not the whole# monkeypatch — undo() would also revert tmp_workspace's AZIMUT_HOME), a@@ -182,6 +222,264 @@ def test_failed_activation_leaves_the_json_case_usable(tmp_workspace, monkeypatcassert [e["label"] for e in Case.open(legacy.id).list_entities()] == ["Ada"]+# -- consolidated folder migration: released schema 3 / dev schemas 4–7 ----+++def _case_at_folder_checkpoint(schema: int) -> tuple[Case, dict[str, str]]:+ case = Case.create(f"Folder checkpoint {schema}")+ note = case.create_note("Bridge sighting", "Video 1", "# note")+ old_paths = {+ "proof": layout.proof_spec_rel("proof"),+ "inspect": layout.session_rel("session"),+ "draft": layout.draft_rel("draft"),+ "media": "media/clip.jpg",+ "sidecar": layout.sidecar_rel("clip.jpg"),+ }+ for key in ("proof", "inspect", "draft", "sidecar"):+ path = case.resolve_inside(old_paths[key])+ path.parent.mkdir(parents=True, exist_ok=True)+ data = (+ {+ "filename": "clip.jpg",+ "title": "Clip",+ "source": {"type": "download"},+ }+ if key == "sidecar"+ else {"title": key}+ )+ path.write_text(json.dumps(data) + "\n", encoding="utf-8")+ case.resolve_inside(old_paths["media"]).write_bytes(b"image")+ case.add_entity("proof", "Proof", {"spec": old_paths["proof"]}, by="user")+ case.add_entity("inspect-session", "Session", {"spec": old_paths["inspect"]}, by="user")+ case.add_entity("post", "Draft", {"draft": old_paths["draft"]}, by="user")+ rewind_case(case, schema)+ return case, {+ "proof": layout.proof_spec_rel("Proof"),+ "inspect": layout.session_rel("Session"),+ "draft": layout.draft_rel("Draft"),+ "media": "media/Clip.jpg",+ "sidecar": layout.sidecar_rel("Clip.jpg"),+ "note_id": note["id"],+ }++[email protected]("schema", range(workspace.STORAGE_SCHEMA, workspace.CASE_SCHEMA))+def test_every_unreleased_folder_checkpoint_jumps_to_the_final_layout(tmp_workspace, schema):+ case, expected = _case_at_folder_checkpoint(schema)+ legacy_manifest = (+ layout.manifest(case.path)+ if layout.manifest(case.path).is_file()+ else layout.unwrapped_manifest(case.path)+ )+ assert json.loads(legacy_manifest.read_text(encoding="utf-8"))["azimut"]["schema"] == schema++ opened = Case.open(case.id)++ assert opened.read()["azimut"]["schema"] == workspace.CASE_SCHEMA+ assert opened.read_note(expected["note_id"]) == "# note"+ for key in ("proof", "inspect", "draft", "media", "sidecar"):+ assert opened.resolve_inside(expected[key]).exists()+ attrs = {+ entity["type"]: entity["attrs"]+ for entity in opened.list_entities()+ if entity["type"] in {"proof", "inspect-session", "post"}+ }+ assert attrs["proof"]["spec"] == expected["proof"]+ assert attrs["inspect-session"]["spec"] == expected["inspect"]+ assert attrs["post"]["draft"] == expected["draft"]+ assert sorted(path.name for path in opened.path.iterdir()) == ["README.txt", "azimut"]+++def test_released_schema_three_is_stamped_only_once(tmp_workspace, monkeypatch):+ case, _ = _case_at_folder_checkpoint(workspace.STORAGE_SCHEMA)+ writes = []+ real_write = Case._write_json++ def remember_write(self, data):+ if self.path == case.path:+ writes.append(data["azimut"]["schema"])+ real_write(self, data)++ monkeypatch.setattr(Case, "_write_json", remember_write)++ Case.open(case.id)++ assert writes == [workspace.CASE_SCHEMA]+++ "stage",+ [+ "_wrap_case_folder",+ "_flatten_trash",+ "_hide_the_machinery",+ "_name_notes_after_their_titles",+ "_leave_a_readme",+ ],+)+def test_folder_normalizer_resumes_after_each_stage(tmp_workspace, monkeypatch, stage):+ case, expected = _case_at_folder_checkpoint(workspace.STORAGE_SCHEMA)+ real_stage = getattr(workspace, stage)++ def stop_after_stage(current):+ real_stage(current)+ raise RuntimeError(f"stop after {stage}")++ monkeypatch.setattr(workspace, stage, stop_after_stage)+ with pytest.raises(RuntimeError, match="stop after"):+ Case.open(case.id)++ manifest = (+ layout.manifest(case.path)+ if layout.manifest(case.path).is_file()+ else layout.unwrapped_manifest(case.path)+ )+ assert json.loads(manifest.read_text(encoding="utf-8"))["azimut"]["schema"] == (+ workspace.STORAGE_SCHEMA+ )++ monkeypatch.setattr(workspace, stage, real_stage)+ opened = Case.open(case.id)++ assert opened.read()["azimut"]["schema"] == workspace.CASE_SCHEMA+ assert opened.read_note(expected["note_id"]) == "# note"+ proof = json.loads(opened.resolve_inside(expected["proof"]).read_text(encoding="utf-8"))+ assert proof["title"] == "Proof"+++# -- folder normalizer: trash stops mirroring the case tree ----------------+++def _mirrored_trash_group(case: Case, rel: str, body: bytes) -> str:+ """Write a schema-3 trash group by hand: the file waits under a copy of its+ own case-relative path, which is what the app did before slots."""+ group_id = "t_legacy0001"+ waiting = case.trash_dir / group_id / rel+ waiting.parent.mkdir(parents=True, exist_ok=True)+ waiting.write_bytes(body)+ case.add_trash_group(+ group_id,+ label="Old delete",+ type_="media",+ item_count=1,+ size_bytes=len(body),+ payload={"entities": [], "links": [], "files": [rel], "tombstones": []},+ state="ready",+ )+ return group_id+++def test_open_flattens_a_mirrored_trash_group_into_slots(tmp_workspace):+ """The normalizer moves each waiting file to a numbered slot and records the+ pairing, so the trash stops stacking a second case tree under itself."""+ case = Case.create("Has an old delete")+ rel = "media/clip.mp4"+ group_id = _mirrored_trash_group(case, rel, b"payload")+ manifest = case.read()+ manifest["azimut"]["schema"] = workspace.STORAGE_SCHEMA+ case._write_json(manifest)++ opened = Case.open(case.id)++ assert opened.read()["azimut"]["schema"] == workspace.CASE_SCHEMA+ group_dir = opened.trash_dir / group_id+ assert [p.name for p in group_dir.iterdir()] == ["0"]+ assert (group_dir / "0").read_bytes() == b"payload"+ group = opened.get_trash_group(group_id)+ assert group["payload"]["files"] == [rel]+ assert group["payload"]["slots"] == ["0"]+++def test_a_flattened_group_still_restores_to_its_original_path(tmp_workspace):+ """The point of recording the pairing: the file goes back where it was, not+ where it waited."""+ case = Case.create("Restores after migrating")+ rel = "media/clip.mp4"+ group_id = _mirrored_trash_group(case, rel, b"payload")+ manifest = case.read()+ manifest["azimut"]["schema"] = workspace.STORAGE_SCHEMA+ case._write_json(manifest)++ opened = Case.open(case.id)+ trash_engine.restore(opened, group_id)++ assert opened.resolve_inside(rel).read_bytes() == b"payload"+ assert not (opened.trash_dir / group_id).exists()+++def test_migrating_twice_leaves_the_slots_alone(tmp_workspace):+ """Idempotence, because an interrupted upgrade reopens and runs again."""+ case = Case.create("Migrated twice")+ group_id = _mirrored_trash_group(case, "media/clip.mp4", b"payload")+ manifest = case.read()+ manifest["azimut"]["schema"] = workspace.STORAGE_SCHEMA+ case._write_json(manifest)++ Case.open(case.id)+ reopened = Case.open(case.id)++ group_dir = reopened.trash_dir / group_id+ assert [p.name for p in group_dir.iterdir()] == ["0"]+ assert (group_dir / "0").read_bytes() == b"payload"+++# -- folder normalizer: the tool's files move into `azimut/` ----------------+++def test_open_wraps_a_flat_case_and_keeps_every_artifact(tmp_workspace):+ """The case root becomes the analyst's, and nothing inside is rewritten:+ stored paths are relative to the tool root, so they go on meaning the same+ thing one level down."""+ case = Case.create("Flat on disk")+ note = case.create_note("Lead", "Research", "# body")+ rel = note["attrs"]["path"]+ unwrap_case(case)+ assert (case.path / "case.json").is_file() # genuinely the old shape++ opened = Case.open(case.id)++ assert opened.read()["azimut"]["schema"] == workspace.CASE_SCHEMA+ assert sorted(entry.name for entry in opened.path.iterdir()) == ["README.txt", "azimut"]+ assert opened.resolve_inside(rel).read_text(encoding="utf-8") == "# body"+ assert opened.get_entity(note["id"])["attrs"]["path"] == rel # untouched+++def test_an_interrupted_wrap_is_resumed_not_half_applied(tmp_workspace):+ """The manifest moves last, so its presence at the case root is what says+ the move never finished. A run that died after carrying the media over must+ pick up from there rather than refuse or duplicate."""+ case = Case.create("Interrupted wrap")+ case.subdir("media").joinpath("clip.mp4").write_bytes(b"payload")+ unwrap_case(case)+ # simulate the crash: media carried over, manifest still at the root+ tool = case.path / "azimut"+ tool.mkdir()+ shutil.move(str(case.path / "media"), str(tool / "media"))+ assert (case.path / "case.json").is_file()++ opened = Case.open(case.id)++ assert sorted(entry.name for entry in opened.path.iterdir()) == ["README.txt", "azimut"]+ assert opened.resolve_inside("media/clip.mp4").read_bytes() == b"payload"+++def test_the_analysts_own_files_are_left_at_the_case_root(tmp_workspace):+ """The whole point of the wrapper. A folder someone keeps beside the case+ does not get swept into the tool's directory by the migration."""+ case = Case.create("Has company")+ unwrap_case(case)+ (case.path / "my rushes").mkdir()+ (case.path / "my rushes" / "raw.mp4").write_bytes(b"mine")++ opened = Case.open(case.id)++ assert (opened.path / "my rushes" / "raw.mp4").read_bytes() == b"mine"+ assert not (opened.tool_root / "my rushes").exists()+ # and the tool's own files did move, so the case is properly wrapped+ assert opened.db_path.is_file()+ assert opened.read()["azimut"]["schema"] == workspace.CASE_SCHEMA++# -- settings.json --------------------------------------------------------@@ -217,3 +515,84 @@ def test_ensure_workspace_upgrades_settings_in_place(monkeypatch, tmp_path):saved = json.loads(config.settings_path().read_text(encoding="utf-8"))assert saved["schema"] == 2assert saved["post_mention"] == "@new"+++def test_open_names_notes_after_their_titles(tmp_workspace):+ """A note used to be `notes/<entity-id>.md`: visible in the case folder and+ illegible, which is the cost of being in the way without the benefit of+ being readable."""+ case = Case.create("Notes to rename")+ note = case.create_note("Bridge sighting", "Video 1", "# body")+ id_named = f"notes/{note['id']}.md"+ moved = case.resolve_inside(id_named)+ ensure_dir(moved.parent)+ shutil.move(str(case.resolve_inside(note["attrs"]["path"])), str(moved))+ case.update_entity(note["id"], {"attrs": {"path": id_named}})+ manifest = case.read()+ manifest["azimut"]["schema"] = workspace.STORAGE_SCHEMA + 3 # before the note rename+ case._write_json(manifest)++ opened = Case.open(case.id)++ renamed = opened.get_entity(note["id"])+ assert renamed["attrs"]["path"] == "notes/Video 1/Bridge sighting.md"+ assert opened.read_note(note["id"]) == "# body"+ assert not opened.resolve_inside(id_named).exists()+++def test_two_notes_with_one_title_survive_the_rename(tmp_workspace):+ """Titles are not unique and the migration cannot refuse anything, so the+ second one takes a suffix rather than overwriting the first."""+ case = Case.create("Duplicate titles")+ first = case.create_note("Summary", "", "# first")+ second = case.create_note("Summary", "", "# second")+ for entity, body in ((first, "# first"), (second, "# second")):+ rel = f"notes/{entity['id']}.md"+ shutil.move(+ str(case.resolve_inside(entity["attrs"]["path"])), str(case.resolve_inside(rel))+ )+ case.update_entity(entity["id"], {"attrs": {"path": rel}})+ assert case.resolve_inside(rel).read_text(encoding="utf-8") == body+ manifest = case.read()+ manifest["azimut"]["schema"] = workspace.STORAGE_SCHEMA + 3 # before the note rename+ case._write_json(manifest)++ opened = Case.open(case.id)++ paths = sorted(opened.get_entity(e["id"])["attrs"]["path"] for e in (first, second))+ assert paths == ["notes/Summary-2.md", "notes/Summary.md"]+ assert opened.read_note(first["id"]) == "# first"+ assert opened.read_note(second["id"]) == "# second"+++# -- folder normalizer: explain the free zone -------------------------------+++def test_a_new_case_explains_which_half_of_the_folder_is_free(tmp_workspace):+ case = Case.create("Readable boundary")++ assert layout.readme(case.path).read_text(encoding="utf-8") == layout.README_TEXT+ assert "everything else here is yours" in layout.README_TEXT+++def test_schema_seven_case_gets_a_readme_without_overwriting_one(tmp_workspace):+ case = Case.create("Readme migration")+ readme = layout.readme(case.path)+ readme.unlink()+ manifest = case.read()+ manifest["azimut"]["schema"] = workspace.CASE_SCHEMA - 1+ case._write_json(manifest)++ opened = Case.open(case.id)++ assert readme.read_text(encoding="utf-8") == layout.README_TEXT+ assert opened.read()["azimut"]["schema"] == workspace.CASE_SCHEMA++ readme.write_text("My own instructions\n", encoding="utf-8")+ manifest = opened.read()+ manifest["azimut"]["schema"] = workspace.CASE_SCHEMA - 1+ opened._write_json(manifest)++ Case.open(case.id)++ assert readme.read_text(encoding="utf-8") == "My own instructions\n"diff --git a/tests/test_naming.py b/tests/test_naming.pyindex c589fd4..a4b1865 100644--- a/tests/test_naming.py+++ b/tests/test_naming.py@@ -1,4 +1,4 @@-"""Shared naming rules: the slug every saved item's filename follows.+"""Shared naming rules: the visible stem every saved item's filename follows.The frontend mirrors `slugify` in `lib/naming.js` so it can tell before it postswhether a name is free. These cases are the contract both sides implement.@@ -9,22 +9,22 @@ import jsonfrom azimut.api.naming import MAX_SLUG, read_created_at, slugify-def test_slug_lowercases_hyphenates_and_trims():- assert slugify("Inspect 1", "session") == "inspect-1"- assert slugify(" Rooftop! @ 12:30 ", "proof") == "rooftop-12-30"- assert slugify("Café déjà", "proof") == "caf-d-j"+def test_visible_stem_preserves_human_text_and_replaces_forbidden_characters():+ assert slugify("Inspect 1", "session") == "Inspect 1"+ assert slugify(" Rooftop! @ 12:30 ", "proof") == "Rooftop! @ 12_30"+ assert slugify("Café déjà", "proof") == "Café déjà"def test_slug_falls_back_per_caller_and_is_bounded():assert slugify("", "proof") == "proof"- assert slugify("!!!", "session") == "session"+ assert slugify("!!!", "session") == "!!!"assert slugify(None, "draft") == "draft"assert len(slugify("a" * 200, "proof")) == MAX_SLUGdef test_slug_cannot_reach_outside_its_folder():- # The slug is the only guard on a client-supplied `rename_from`: nothing but- # [a-z0-9-] survives it, so no separator or dot-dot can reach the filesystem.+ # The canonical stem is the guard on a client-supplied `rename_from`.+ # Separators and parent traversal never reach the filesystem.for hostile in ("../../etc/passwd", "..\\..\\windows", "a/b", "."):assert "/" not in slugify(hostile, "proof")assert "\\" not in slugify(hostile, "proof")diff --git a/tests/test_proofs_api.py b/tests/test_proofs_api.pyindex 5b7a4d1..6dfa19f 100644--- a/tests/test_proofs_api.py+++ b/tests/test_proofs_api.py@@ -7,6 +7,7 @@ import ioimport pytestfrom PIL import Image+from azimut import layoutdef _png_b64() -> str:@@ -42,14 +43,14 @@ def test_save_load_roundtrip(client):f"/api/cases/{cid}/proofs",json={"title": "Kharkiv strike proof", "spec": SPEC, "png_base64": _png_b64()},).json()- assert saved["name"] == "kharkiv-strike-proof"- assert saved["png"] == "proofs/kharkiv-strike-proof.png"+ assert saved["name"] == "Kharkiv strike proof"+ assert saved["png"] == "proofs/Kharkiv strike proof.png"listed = client.get(f"/api/cases/{cid}/proofs").json()assert len(listed) == 1assert listed[0]["panels"] == 2 and listed[0]["shapes"] == 1- spec = client.get(f"/api/cases/{cid}/proofs/kharkiv-strike-proof").json()+ spec = client.get(f"/api/cases/{cid}/proofs/{saved['name']}").json()assert spec["title"] == "Kharkiv strike proof"assert spec["shapes"][0]["comment"] == "blue roof"assert spec["notes"] == {"#ff5252": "blue roof matches"} # legend text is per color@@ -101,7 +102,7 @@ def test_resave_with_png_adds_the_path_to_the_entity(client):entity = next(e for e in graph_read.entities(cid) if e["type"] == "proof")- assert entity["attrs"]["path"] == f"proofs/{saved['name']}.png"+ assert entity["attrs"]["path"] == layout.proof_export_rel(saved['name'])def test_invalid_png_rejected(client):@@ -134,17 +135,17 @@ def test_rename_moves_the_spec_and_the_export(client):"png_base64": _png_b64(),},).json()- assert renamed["name"] == "rooftop-angle"- assert renamed["png"] == "proofs/rooftop-angle.png"- assert client.get(f"/api/cases/{cid}/proofs/proof-1").status_code == 404- assert client.get(f"/files/{cid}/proofs/proof-1.png").status_code == 404- assert client.get(f"/files/{cid}/proofs/rooftop-angle.png").status_code == 200+ assert renamed["name"] == "Rooftop angle"+ assert renamed["png"] == "proofs/Rooftop angle.png"+ assert client.get(f"/api/cases/{cid}/proofs/{saved['name']}").status_code == 404+ assert client.get(f"/files/{cid}/proofs/{saved['name']}.png").status_code == 404+ assert client.get(f"/files/{cid}/proofs/{renamed['name']}.png").status_code == 200proofs = [e for e in graph_read.entities(cid) if e["type"] == "proof"]assert len(proofs) == 1assert proofs[0]["id"] == before["id"]- assert proofs[0]["attrs"]["spec"] == "proofs/rooftop-angle.json"- assert proofs[0]["attrs"]["path"] == "proofs/rooftop-angle.png"+ assert proofs[0]["attrs"]["spec"] == "proofs/.meta/Rooftop angle.json"+ assert proofs[0]["attrs"]["path"] == "proofs/Rooftop angle.png"assert proofs[0]["attrs"]["folder"] == "Reports"@@ -152,20 +153,20 @@ def test_rename_without_fresh_pixels_carries_the_export_along(client):# A save that ships no PNG (spec-only) must not strand the export under the# old name — the proof would lose its picture on a pure rename.cid = client.post("/api/cases", json={"name": "CarryPng"}).json()["id"]- client.post(+ saved = client.post(f"/api/cases/{cid}/proofs",json={"title": "Proof 1", "spec": SPEC, "png_base64": _png_b64()},- )+ ).json()renamed = client.post(f"/api/cases/{cid}/proofs",- json={"rename_from": "proof-1", "title": "Carried", "spec": SPEC},+ json={"rename_from": saved["name"], "title": "Carried", "spec": SPEC},).json()- assert renamed["png"] == "proofs/carried.png"- assert client.get(f"/files/{cid}/proofs/carried.png").status_code == 200- assert client.get(f"/files/{cid}/proofs/proof-1.png").status_code == 404+ assert renamed["png"] == "proofs/Carried.png"+ assert client.get(f"/files/{cid}/proofs/Carried.png").status_code == 200+ assert client.get(f"/files/{cid}/proofs/{saved['name']}.png").status_code == 404entity = next(e for e in graph_read.entities(cid) if e["type"] == "proof")- assert entity["attrs"]["path"] == "proofs/carried.png"+ assert entity["attrs"]["path"] == "proofs/Carried.png"def test_rename_onto_a_taken_name_is_refused(client):@@ -174,15 +175,15 @@ def test_rename_onto_a_taken_name_is_refused(client):f"/api/cases/{cid}/proofs",json={"title": "Proof 1", "spec": SPEC, "png_base64": _png_b64()},)- client.post(+ second = client.post(f"/api/cases/{cid}/proofs",json={"title": "Proof 2", "spec": SPEC, "png_base64": _png_b64()},- )+ ).json()res = client.post(f"/api/cases/{cid}/proofs",json={- "rename_from": "proof-2",+ "rename_from": second["name"],"title": "Proof 1","spec": SPEC,"png_base64": _png_b64(),@@ -190,20 +191,22 @@ def test_rename_onto_a_taken_name_is_refused(client):)assert res.status_code == 409listed = sorted(p["name"] for p in client.get(f"/api/cases/{cid}/proofs").json())- assert listed == ["proof-1", "proof-2"]- assert client.get(f"/files/{cid}/proofs/proof-2.png").status_code == 200+ assert listed == ["Proof 1", "Proof 2"]+ assert client.get(f"/files/{cid}/proofs/{second['name']}.png").status_code == 200def test_rename_keeps_the_creation_date(client):cid = client.post("/api/cases", json={"name": "BornProof"}).json()["id"]- client.post(f"/api/cases/{cid}/proofs", json={"title": "Proof 1", "spec": SPEC})- born = client.get(f"/api/cases/{cid}/proofs/proof-1").json()["created_at"]+ saved = client.post(+ f"/api/cases/{cid}/proofs", json={"title": "Proof 1", "spec": SPEC}+ ).json()+ born = client.get(f"/api/cases/{cid}/proofs/{saved['name']}").json()["created_at"]client.post(f"/api/cases/{cid}/proofs",- json={"rename_from": "proof-1", "title": "Renamed", "spec": SPEC},+ json={"rename_from": saved["name"], "title": "Renamed", "spec": SPEC},)- assert client.get(f"/api/cases/{cid}/proofs/renamed").json()["created_at"] == born+ assert client.get(f"/api/cases/{cid}/proofs/Renamed").json()["created_at"] == borndef test_delete_proof(client):@@ -349,7 +352,7 @@ def test_index_inherits_the_point_from_the_capture_it_composes(client, sat_tilesrow = _proof_index(client, cid)[0]assert row["kind"] == "proof"assert row["title"] == "Kyiv bridge"- assert row["name"] == "kyiv-bridge"+ assert row["name"] == "Kyiv bridge"assert (row["lat"], row["lon"]) == (50.4501, 30.5234)assert row["notes"] == ""assert row["folder"] == "" # unfiled, never null@@ -450,8 +453,8 @@ def test_index_lists_the_posts_written_from_a_proof(client, sat_tiles):"mastodon",}assert {post["name"] for post in row["linked_posts"]} == {- "first-thread",- "follow-up",+ "First thread",+ "Follow-up",}diff --git a/tests/test_proofs_assets_api.py b/tests/test_proofs_assets_api.pyindex e8e791c..4e79a43 100644--- a/tests/test_proofs_assets_api.py+++ b/tests/test_proofs_assets_api.py@@ -1,6 +1,6 @@"""Pasted images: pixels a proof shows that the case does not hold.-A paste rides along with the save, lands in ``proofs/<name>.assets/`` under its+A paste rides along with the save, lands in ``proofs/.meta/<name>.assets/`` under itsown hash, follows the proof through a rename, and goes away with it. What it mustnever do is claim a source: no media, no entity, no ``derived-from`` edge."""@@ -11,6 +11,7 @@ import ioimport graph_readfrom PIL import Image+from azimut import layoutdef _png(size=(60, 40), color=(90, 30, 30)) -> bytes:@@ -60,7 +61,7 @@ def test_a_pasted_image_lands_beside_the_proof_and_is_served(client):json={"title": "Pasted proof", "spec": _spec(asset["name"]), "assets": [asset]},).json()- rel = f"proofs/{saved['name']}.assets/{asset['name']}"+ rel = f"{layout.proof_assets_rel(saved['name'])}/{asset['name']}"served = client.get(f"/files/{cid}/{rel}")assert served.status_code == 200assert served.content == data # the exact bytes, so reopening renders the paste@@ -96,7 +97,7 @@ def test_dropping_a_paste_takes_its_file_and_its_folder(client):saved = client.post(f"/api/cases/{cid}/proofs", json={**body, "assets": [keep, drop]}).json()- folder = f"proofs/{saved['name']}.assets"+ folder = layout.proof_assets_rel(saved['name'])assert client.get(f"/files/{cid}/{folder}/{drop['name']}").status_code == 200# resave with only one paste left: the other file goes, no new upload needed@@ -120,20 +121,22 @@ def test_dropping_a_paste_takes_its_file_and_its_folder(client):def test_rename_carries_the_pasted_images(client):cid = _case(client, "RenamePastes")asset = _asset(_png())- client.post(+ saved = client.post(f"/api/cases/{cid}/proofs",json={"title": "Before", "spec": _spec(asset["name"]), "assets": [asset]},- )+ ).json()# renamed with no fresh upload: the folder moves rather than the paste dyingrenamed = client.post(f"/api/cases/{cid}/proofs",- json={"rename_from": "before", "title": "After", "spec": _spec(asset["name"])},+ json={"rename_from": saved["name"], "title": "After", "spec": _spec(asset["name"])},).json()- assert renamed["name"] == "after"- assert client.get(f"/files/{cid}/proofs/after.assets/{asset['name']}").status_code == 200- assert client.get(f"/files/{cid}/proofs/before.assets/{asset['name']}").status_code == 404+ assert renamed["name"] == "After"+ after = layout.proof_assets_rel("After")+ before = layout.proof_assets_rel("Before")+ assert client.get(f"/files/{cid}/{after}/{asset['name']}").status_code == 200+ assert client.get(f"/files/{cid}/{before}/{asset['name']}").status_code == 404def test_delete_removes_the_pasted_images(client):@@ -147,26 +150,27 @@ def test_delete_removes_the_pasted_images(client):).json()client.delete(f"/api/cases/{cid}/proofs/{saved['name']}")- assert not get_case(cid).resolve_inside(f"proofs/{saved['name']}.assets").exists()+ assert not get_case(cid).resolve_inside(layout.proof_assets_rel(saved['name'])).exists()def test_the_same_paste_reuploaded_lands_once(client):cid = _case(client, "Idempotent")asset = _asset(_png())+ saved = Nonefor _ in range(2):- client.post(+ saved = client.post(f"/api/cases/{cid}/proofs",json={- "rename_from": "same",+ "rename_from": saved["name"] if saved else None,"title": "Same","spec": _spec(asset["name"]),"assets": [asset],},- )+ ).json()from azimut.api.cases import get_case- folder = get_case(cid).resolve_inside("proofs/same.assets")+ folder = get_case(cid).resolve_inside(layout.proof_assets_rel("Same"))assert [p.name for p in folder.iterdir()] == [asset["name"]]@@ -214,25 +218,26 @@ def test_a_refused_batch_writes_nothing(client):"""Assets are decoded before the spec is touched, so a bad save is a no-op."""cid = _case(client, "AllOrNothing")good = _asset(_png())- client.post(+ saved = client.post(f"/api/cases/{cid}/proofs",json={"title": "Kept", "spec": _spec(good["name"]), "assets": [good]},- )- before = client.get(f"/api/cases/{cid}/proofs/kept").json()+ ).json()+ before = client.get(f"/api/cases/{cid}/proofs/{saved['name']}").json()res = client.post(f"/api/cases/{cid}/proofs",json={- "rename_from": "kept",+ "rename_from": saved["name"],"title": "Kept","spec": _spec(good["name"], "0123456789abcdef.png"),"assets": [good, {"name": "0123456789abcdef.png", "data": "not base64!!"}],},)assert res.status_code == 422- after = client.get(f"/api/cases/{cid}/proofs/kept").json()+ after = client.get(f"/api/cases/{cid}/proofs/{saved['name']}").json()assert after == before # untouched, down to updated_at- assert client.get(f"/files/{cid}/proofs/kept.assets/{good['name']}").status_code == 200+ kept = layout.proof_assets_rel("Kept")+ assert client.get(f"/files/{cid}/{kept}/{good['name']}").status_code == 200def test_a_proof_without_pastes_keeps_no_assets_folder(client):@@ -242,4 +247,4 @@ def test_a_proof_without_pastes_keeps_no_assets_folder(client):client.post(f"/api/cases/{cid}/proofs", json={"title": "Plain", "spec": _spec(panels=["media/a.jpg"])})- assert not get_case(cid).resolve_inside("proofs/plain.assets").exists()+ assert not get_case(cid).resolve_inside(layout.proof_assets_rel("Plain")).exists()diff --git a/tests/test_release_gate.py b/tests/test_release_gate.pyindex 620d326..2a59447 100644--- a/tests/test_release_gate.py+++ b/tests/test_release_gate.py@@ -22,7 +22,7 @@ from pathlib import Pathfrom bigcase import build_big_casefrom legacy_case import write_legacy_json_case-from azimut import workspace+from azimut import layout, workspacefrom azimut.engine import links as link_enginefrom azimut.engine import media as media_enginefrom azimut.engine import thumbnails@@ -51,7 +51,7 @@ def test_legacy_json_case_migrates_and_every_workflow_answers(tmp_workspace):)# a real media file + sidecar so the media listing has something to read(legacy.path / "media" / "shot.jpg").write_bytes(b"\xff\xd8\xff\xe0jpeg")- (legacy.path / "media" / ("shot.jpg" + media_engine.SIDECAR_SUFFIX)).write_text(+ (legacy.path / "media" / ("shot.jpg" + layout.PRE_HIDDEN_SIDECAR_SUFFIX)).write_text('{"filename": "shot.jpg", "kind": "image", "sha256": "%s", "size": 5,'' "added_at": "2026-01-01T00:00:00Z", "source": {}, "thumbnail": null}' % ("a" * 64),encoding="utf-8",@@ -61,7 +61,7 @@ def test_legacy_json_case_migrates_and_every_workflow_answers(tmp_workspace):# storage flipped, graph preserved, backup recoverableassert case.read()["azimut"] == {"schema": workspace.CASE_SCHEMA, "storage": "sqlite"}- assert (case.path / "case.pre-migrate-v2.json").exists()+ assert (case.tool_root / "case.pre-migrate-v2.json").exists()assert {e["id"] for e in case.snapshot()["entities"]} == {"e_p", "e_m", "e_pr"}# bounded reads@@ -184,7 +184,7 @@ def test_chromium_cookie_decrypt_dependency_ships_on_linux():def test_case_db_lives_under_the_workspace_root(tmp_workspace):case = Case.create("Where")assert case.path.is_relative_to(workspace.config.workspace_root())- assert (case.path / "case.db").exists() # beside the case, never beside the binary+ assert case.db_path.exists() # beside the case, never beside the binary# thumbnails cache under the case's media dir, also inside the workspaceassert thumbnails._thumb_dir(case).is_relative_to(workspace.config.workspace_root())diff --git a/tests/test_repository.py b/tests/test_repository.pyindex 2aea14f..d5e2967 100644--- a/tests/test_repository.py+++ b/tests/test_repository.py@@ -91,7 +91,7 @@ def test_update_link_changes_suggestion_status_without_rebuilding_edge(repo):def test_sync_links_restates_a_source_set(repo):- src = repo.add_entity("proof", "P", {"spec": "proofs/p.json"}, by="user")+ src = repo.add_entity("proof", "P", {"spec": "proofs/.meta/p.json"}, by="user")m1 = repo.add_entity("media", "m1", by="user")m2 = repo.add_entity("media", "m2", by="user")m3 = repo.add_entity("media", "m3", by="user")@@ -134,7 +134,7 @@ def test_links_of_returns_only_incident_edges(repo):def test_derivation_subgraph_walks_the_derived_from_closure(repo):from azimut.engine import links as link_engine- proof = repo.add_entity("proof", "P", {"spec": "proofs/p.json"}, by="user")+ proof = repo.add_entity("proof", "P", {"spec": "proofs/.meta/p.json"}, by="user")frame = repo.add_entity("media", "frame", {"path": "media/f.jpg"}, by="user")video = repo.add_entity("media", "clip", {"path": "media/c.mp4"}, by="user")other = repo.add_entity("media", "unrelated", {"path": "media/o.jpg"}, by="user")@@ -158,10 +158,10 @@ def test_count_dependents_groups_incoming_edges_by_target(repo):quiet = repo.add_entity("capture", "untouched", {"lat": 51.5}, by="user")photo = repo.add_entity("media", "photo", {"path": "media/x.jpg"}, by="user")for name in ("P1", "P2"):- proof = repo.add_entity("proof", name, {"spec": f"proofs/{name}.json"}, by="user")+ proof = repo.add_entity("proof", name, {"spec": f"proofs/.meta/{name}.json"}, by="user")repo.add_link(proof["id"], capture["id"], "derived-from", by="user")repo.add_link(photo["id"], capture["id"], "derived-from", by="user") # wrong source type- post = repo.add_entity("post", "draft", {"draft": "exports/d.json"}, by="user")+ post = repo.add_entity("post", "draft", {"draft": ".drafts/d.json"}, by="user")repo.add_link(post["id"], capture["id"], "mentions", by="user") # wrong link typecounts = repo.count_dependents(link_type="derived-from", from_type="proof")@@ -332,6 +332,33 @@ def test_enqueue_is_idempotent_on_key(repo):assert repo.count_jobs(kind="enrich") == {"queued": 1}+def test_replace_path_references_updates_exact_structured_values(repo):+ old = "media/before.png"+ new = "media/After.png"+ sentence = f"Prose mentions {old} and must remain unchanged."+ entity = repo.add_entity(+ "bookmark",+ "Reference",+ {"path": old, "nested": [old, {"again": old}], "notes": sentence},+ by="user",+ )+ job = repo.enqueue_job(+ "thumbnail",+ key=old,+ payload={"path": old, "nested": [old], "notes": sentence},+ )++ repo.replace_path_references(old, new)++ attrs = repo.get_entity(entity["id"])["attrs"]+ assert attrs["path"] == new+ assert attrs["nested"] == [new, {"again": new}]+ assert attrs["notes"] == sentence+ queued = repo.get_job(job["id"])+ assert queued["key"] == new+ assert queued["payload"] == {"path": new, "nested": [new], "notes": sentence}++def test_claim_takes_one_queued_job_oldest_first(repo):a = repo.enqueue_job("thumbnail", key="media/a.jpg")repo.enqueue_job("thumbnail", key="media/b.jpg")@@ -408,7 +435,7 @@ def test_count_incident_links_groups_relations_in_either_direction(repo):other = repo.add_entity("media", "other", {"path": "media/y.jpg"}, by="user")place = repo.add_entity("place", "point", {"lat": 48.0}, by="user")quiet = repo.add_entity("place", "untouched", {"lat": 49.0}, by="user")- proof = repo.add_entity("proof", "P", {"spec": "proofs/p.json"}, by="user")+ proof = repo.add_entity("proof", "P", {"spec": "proofs/.meta/p.json"}, by="user")repo.add_link(photo["id"], place["id"], "located-at", by="enrich", status="suggested")repo.add_link(photo["id"], other["id"], "same-image-as", by="enrich", status="suggested")diff --git a/tests/test_reveal.py b/tests/test_reveal.pynew file mode 100644index 0000000..22cece3--- /dev/null+++ b/tests/test_reveal.py@@ -0,0 +1,250 @@+"""Showing a folder in the system file manager (engine/reveal.py + its routes).++The spawn is always faked: a real `xdg-open` in CI would either fail or, worse,+succeed and open a window on someone's desktop.+"""++import subprocess+import sys++import pytest++from azimut import config+from azimut.engine import reveal+++def spawns(monkeypatch):+ """Record what would have been launched, launching nothing.++ A graphical session is faked too, so the Linux tests behave the same whether+ CI runs them headless or a developer runs them on a desktop.+ """+ calls = []++ class FakePopen:+ def __init__(self, argv, **kwargs):+ calls.append({"argv": argv, "kwargs": kwargs})++ monkeypatch.setattr(reveal.subprocess, "Popen", FakePopen)+ monkeypatch.setattr(reveal.os, "startfile", lambda path: calls.append({"startfile": path}),+ raising=False)+ monkeypatch.setenv("DISPLAY", ":0")+ return calls+++def _workspace_dir(tmp_path, monkeypatch):+ monkeypatch.setenv("AZIMUT_HOME", str(tmp_path))+ (tmp_path / "cases" / "demo").mkdir(parents=True)+ return tmp_path / "cases" / "demo"+++def test_linux_hands_the_folder_to_xdg_open(tmp_path, monkeypatch, spawns):+ folder = _workspace_dir(tmp_path, monkeypatch)+ monkeypatch.setattr(sys, "platform", "linux")++ reveal.reveal(folder)++ assert spawns[0]["argv"] == ["xdg-open", str(folder.resolve())]+++def test_macos_uses_open(tmp_path, monkeypatch, spawns):+ folder = _workspace_dir(tmp_path, monkeypatch)+ monkeypatch.setattr(sys, "platform", "darwin")++ reveal.reveal(folder)++ assert spawns[0]["argv"] == ["open", str(folder.resolve())]+++def test_windows_goes_through_the_stdlib_shell_open(tmp_path, monkeypatch, spawns):+ """os.startfile rather than an argv: nothing to quote, so nothing to inject."""+ folder = _workspace_dir(tmp_path, monkeypatch)+ monkeypatch.setattr(sys, "platform", "win32")++ reveal.reveal(folder)++ assert spawns[0]["startfile"] == folder.resolve()+++def test_never_runs_through_a_shell_and_never_waits(tmp_path, monkeypatch, spawns):+ """A file manager outlives the request, and a shell would take the path apart."""+ folder = _workspace_dir(tmp_path, monkeypatch)+ monkeypatch.setattr(sys, "platform", "linux")++ reveal.reveal(folder)++ kwargs = spawns[0]["kwargs"]+ assert "shell" not in kwargs+ assert kwargs["start_new_session"] is True+ assert kwargs["stdout"] is subprocess.DEVNULL and kwargs["stderr"] is subprocess.DEVNULL+++def test_a_folder_name_with_spaces_stays_one_argument(tmp_path, monkeypatch, spawns):+ monkeypatch.setenv("AZIMUT_HOME", str(tmp_path))+ folder = tmp_path / "cases" / "Convoy dashcam & co"+ folder.mkdir(parents=True)+ monkeypatch.setattr(sys, "platform", "linux")++ reveal.reveal(folder)++ assert spawns[0]["argv"][1] == str(folder.resolve())+++def test_refuses_a_folder_outside_the_workspace(tmp_path, monkeypatch, spawns):+ monkeypatch.setenv("AZIMUT_HOME", str(tmp_path / "home"))+ (tmp_path / "home").mkdir()+ elsewhere = tmp_path / "elsewhere"+ elsewhere.mkdir()++ with pytest.raises(reveal.RevealError, match="outside the workspace"):+ reveal.reveal(elsewhere)+ assert not spawns+++def test_refuses_to_climb_out_with_dot_dot(tmp_path, monkeypatch, spawns):+ home = tmp_path / "home"+ home.mkdir()+ monkeypatch.setenv("AZIMUT_HOME", str(home))++ with pytest.raises(reveal.RevealError, match="outside the workspace"):+ reveal.reveal(home / ".." / "somewhere-else")+ assert not spawns+++def test_reports_a_folder_that_has_gone(tmp_path, monkeypatch, spawns):+ monkeypatch.setenv("AZIMUT_HOME", str(tmp_path))++ with pytest.raises(reveal.RevealError, match="no longer exists"):+ reveal.reveal(tmp_path / "cases" / "deleted-by-hand")+ assert not spawns+++def test_names_the_missing_opener_when_xdg_utils_is_absent(tmp_path, monkeypatch, spawns):+ folder = _workspace_dir(tmp_path, monkeypatch)+ monkeypatch.setattr(sys, "platform", "linux")++ def no_opener(*_args, **_kwargs):+ raise FileNotFoundError("xdg-open")++ monkeypatch.setattr(reveal.subprocess, "Popen", no_opener)++ with pytest.raises(reveal.RevealError, match="xdg-open is missing"):+ reveal.reveal(folder)+++def test_refuses_on_a_linux_box_with_no_graphical_session(tmp_path, monkeypatch, spawns):+ """Over SSH or as a service, xdg-open exits without opening anything.++ Silenced stderr plus a detached process means we'd never hear about it, so the+ UI would report a window that never appeared. Better to say so up front.+ """+ folder = _workspace_dir(tmp_path, monkeypatch)+ monkeypatch.setattr(sys, "platform", "linux")+ monkeypatch.delenv("DISPLAY", raising=False)+ monkeypatch.delenv("WAYLAND_DISPLAY", raising=False)++ with pytest.raises(reveal.RevealError, match="no desktop session"):+ reveal.reveal(folder)+ assert not spawns+++def test_wayland_alone_counts_as_a_session(tmp_path, monkeypatch, spawns):+ folder = _workspace_dir(tmp_path, monkeypatch)+ monkeypatch.setattr(sys, "platform", "linux")+ monkeypatch.delenv("DISPLAY", raising=False)+ monkeypatch.setenv("WAYLAND_DISPLAY", "wayland-0")++ reveal.reveal(folder)++ assert spawns[0]["argv"][0] == "xdg-open"+++def test_macos_never_asks_about_a_display(tmp_path, monkeypatch, spawns):+ """A Mac always has a Finder, and it exports no DISPLAY."""+ folder = _workspace_dir(tmp_path, monkeypatch)+ monkeypatch.setattr(sys, "platform", "darwin")+ monkeypatch.delenv("DISPLAY", raising=False)+ monkeypatch.delenv("WAYLAND_DISPLAY", raising=False)++ reveal.reveal(folder)++ assert spawns[0]["argv"][0] == "open"+++def test_windows_never_asks_about_a_display(tmp_path, monkeypatch, spawns):+ folder = _workspace_dir(tmp_path, monkeypatch)+ monkeypatch.setattr(sys, "platform", "win32")+ monkeypatch.delenv("DISPLAY", raising=False)+ monkeypatch.delenv("WAYLAND_DISPLAY", raising=False)++ reveal.reveal(folder)++ assert spawns[0]["startfile"] == folder.resolve()+++def test_windows_refusal_becomes_a_reason_not_a_traceback(tmp_path, monkeypatch, spawns):+ folder = _workspace_dir(tmp_path, monkeypatch)+ monkeypatch.setattr(sys, "platform", "win32")++ def refuse(_path):+ raise OSError("[WinError 1155] No application is associated")++ monkeypatch.setattr(reveal.os, "startfile", refuse, raising=False)++ with pytest.raises(reveal.RevealError, match="Windows could not open"):+ reveal.reveal(folder)+++# -- the routes --------------------------------------------------------------+++def shown(monkeypatch):+ """What the routes asked to reveal, without revealing it."""+ seen = []+ monkeypatch.setattr(reveal, "reveal", lambda path: seen.append(path))+ return seen+++def test_case_route_reveals_that_case_and_nothing_else(client, shown):+ cid = client.post("/api/cases", json={"name": "Reveal"}).json()["id"]++ res = client.post(f"/api/cases/{cid}/reveal")++ assert res.status_code == 200+ assert res.json()["path"].endswith(cid)+ assert shown == [config.cases_dir() / cid]+++def test_case_route_takes_no_path_from_the_caller(client, shown):+ """The id is the whole input, and it has to resolve to a case that exists.++ A caller cannot name a folder, only a case, so there is no path to traverse+ out of. Anything that isn't a case is turned away before the file manager is+ reached; the containment check itself is covered against the engine above.+ """+ for attempt in ("no-such-case", "..", "....", "etc"):+ res = client.post(f"/api/cases/{attempt}/reveal")+ assert res.status_code != 200, attempt+ assert not shown+++def test_workspace_route_reveals_the_root(client, shown):+ res = client.post("/api/settings/reveal-workspace")++ assert res.status_code == 200+ assert res.json()["path"] == str(config.workspace_root())+ assert shown == [config.workspace_root()]+++def test_a_refusal_reaches_the_ui_as_a_reason(client, monkeypatch):+ def refuse(_path):+ raise reveal.RevealError("no file manager found (xdg-open is missing)")++ monkeypatch.setattr(reveal, "reveal", refuse)++ res = client.post("/api/settings/reveal-workspace")++ assert res.status_code == 409+ assert "xdg-open" in res.json()["detail"]diff --git a/tests/test_satellite_api.py b/tests/test_satellite_api.pyindex b453743..fdc6b4f 100644--- a/tests/test_satellite_api.py+++ b/tests/test_satellite_api.py@@ -7,6 +7,7 @@ import pytestimport graph_readfrom PIL import Image+from azimut import layoutfrom azimut.api import satellite as satellite_apifrom azimut.engine import geo, tiles@@ -358,7 +359,10 @@ def test_edit_title_renames_capture_entity(client, monkeypatch):assert listed[0]["title"] == "Eiffel Tower"# clearing the title falls back to the coordinates on both sides- client.patch(f"/api/cases/{cid}/satellite", json={"path": cap["path"], "title": " "})+ client.patch(+ f"/api/cases/{cid}/satellite",+ json={"path": updated["path"], "title": " "},+ )assert _captures(client, cid)[0]["label"] == "48.858400, 2.294500"@@ -406,7 +410,7 @@ def test_changing_the_format_never_rewrites_existing_titles(client, monkeypatch)json={"lat": 40.6892, "lon": -74.0445, "zoom": 16, "width": 512, "height": 512},)titles = {c["title"] for c in client.get(f"/api/cases/{cid}/satellite").json()}- assert titles == {"48.858370, 2.294481", "40°41'21.12\"N 74°02'40.20\"W"}+ assert titles == {"48.858370, 2.294481", "40°41'21.12_N 74°02'40.20_W"}def test_place_label_follows_the_coordinate_format(client):@@ -699,7 +703,7 @@ def test_search_grid_corruption_is_skipped_in_picker_and_reported_on_open(clientfrom azimut.workspace import Casecid = client.post("/api/cases", json={"name": "Grid"}).json()["id"]- path = Case.open(cid).subdir("search") / "broken.json"+ path = Case.open(cid).subdir(layout.SEARCH_DIR) / "broken.json"path.write_text('["not", "an", "object"]', encoding="utf-8")assert client.get(f"/api/cases/{cid}/search-grids").json() == []@@ -714,7 +718,7 @@ def test_search_grid_write_is_atomic(client, monkeypatch):cid = client.post("/api/cases", json={"name": "Grid"}).json()["id"]client.put(f"/api/cases/{cid}/search-grids/g", json=_rect_grid(title="Before"))- path = Case.open(cid).subdir("search") / "g.json"+ path = Case.open(cid).subdir(layout.SEARCH_DIR) / "g.json"before = path.read_bytes()def fail_replace(_source, _target):diff --git a/tests/test_settings_api.py b/tests/test_settings_api.pyindex b01bfa4..c50008c 100644--- a/tests/test_settings_api.py+++ b/tests/test_settings_api.py@@ -75,12 +75,19 @@ def test_keys_never_reach_a_case_folder(client, monkeypatch):cid = client.post("/api/cases", json={"name": "K"}).json()["id"]client.post(f"/api/cases/{cid}/satellite/capture",- json={"lat": 48.85, "lon": 2.29, "zoom": 15, "width": 512, "height": 512,- "provider": "mapbox-satellite"},+ json={+ "lat": 48.85,+ "lon": 2.29,+ "zoom": 15,+ "width": 512,+ "height": 512,+ "provider": "mapbox-satellite",+ },)case_dir = config.cases_dir() / cidhits = [- p for p in case_dir.rglob("*")+ p+ for p in case_dir.rglob("*")if p.is_file() and p.suffix in (".json", ".md") and "pk.SECRET" in p.read_text()]assert hits == []@@ -90,7 +97,8 @@ def _upstream(status=200, content=b"JPEGDATA", headers=None):def get(url, **kwargs):get.urls.append(url)return httpx.Response(- status, content=content,+ status,+ content=content,headers={"content-type": "image/jpeg", **(headers or {})},request=httpx.Request("GET", url),)@@ -170,7 +178,9 @@ def test_tile_proxy_google_remints_session_on_403(client, monkeypatch):def get(url, **kwargs):status = 403 if "session=tok-stale" in url else 200return httpx.Response(- status, content=b"TILE", headers={"content-type": "image/jpeg"},+ status,+ content=b"TILE",+ headers={"content-type": "image/jpeg"},request=httpx.Request("GET", url),)@@ -268,6 +278,7 @@ def test_tile_proxy_disk_cache_serves_repeats_without_rebilling(client, monkeypaassert r.status_code == 200assert r.content == b"JPEGDATA"assert len(upstream.urls) == 1 # second hit came from the disk cache+ assert (config.tile_cache_dir() / "mapbox-satellite").is_dir()body = client.get("/api/settings").json()assert body["usage"]["mapbox"][body["month"]] == 1 # cache hits aren't billed@@ -283,7 +294,7 @@ def test_tile_proxy_never_caches_google(client, monkeypatch):client.get("/api/tiles/google-satellite/15/16597/11278")client.get("/api/tiles/google-satellite/15/16597/11278")assert len(upstream.urls) == 2 # terms forbid a disk cache — always upstream- assert not (config.workspace_root() / "tile-cache" / "google-satellite").exists()+ assert not (config.tile_cache_dir() / "google-satellite").exists()body = client.get("/api/settings").json()assert body["usage"]["google"][body["month"]] == 2@@ -307,7 +318,9 @@ def test_tile_proxy_overzoom_fills_coverage_gaps(client, monkeypatch):if "/tile/19/" in url:return httpx.Response(404, content=b"", request=httpx.Request("GET", url))return httpx.Response(- 200, content=parent_png, headers={"content-type": "image/png"},+ 200,+ content=parent_png,+ headers={"content-type": "image/png"},request=httpx.Request("GET", url),)@@ -343,7 +356,9 @@ def test_tile_proxy_placeholder_tile_triggers_overzoom(client, monkeypatch):(placeholder, "image/jpeg") if "/tile/19/" in url else (parent_png, "image/png"))return httpx.Response(- 200, content=body, headers={"content-type": ctype},+ 200,+ content=body,+ headers={"content-type": ctype},request=httpx.Request("GET", url),)@@ -499,9 +514,7 @@ def test_sentinel_layers_check_falls_back_to_the_catalogue_and_says_why(client,def test_sentinel_dates_lists_passes_and_counts_the_request(client, monkeypatch):client.put("/api/settings/keys", json={"sentinelhub": "inst-uuid"})- payload = (- '{"features": [{"properties": {"date": "2026-05-11", "cloudCoverPercentage": 4}}]}'- )+ payload = '{"features": [{"properties": {"date": "2026-05-11", "cloudCoverPercentage": 4}}]}'def get(url, **kwargs):assert "/ogc/wfs/inst-uuid" in url@@ -509,8 +522,7 @@ def test_sentinel_dates_lists_passes_and_counts_the_request(client, monkeypatch)monkeypatch.setattr(httpx, "get", get)body = client.get(- "/api/satellite/sentinel/dates"- "?lat=48.8584&lon=2.2945&start=2026-05-01&end=2026-05-31"+ "/api/satellite/sentinel/dates?lat=48.8584&lon=2.2945&start=2026-05-01&end=2026-05-31").json()assert body["dates"] == [{"date": "2026-05-11", "cloud": 4.0, "granules": 1}]# a WFS query is ~0.01 PU but one whole request against the request quota —@@ -520,9 +532,12 @@ def test_sentinel_dates_lists_passes_and_counts_the_request(client, monkeypatch)def test_sentinel_dates_without_a_key_is_a_404(client):- assert client.get(- "/api/satellite/sentinel/dates?lat=1&lon=1&start=2026-05-01&end=2026-05-31"- ).status_code == 404+ assert (+ client.get(+ "/api/satellite/sentinel/dates?lat=1&lon=1&start=2026-05-01&end=2026-05-31"+ ).status_code+ == 404+ )def test_sentinel_coverage_checks_the_layer_and_counts_the_request(client, monkeypatch):@@ -561,9 +576,7 @@ def test_sentinel_coverage_defaults_to_no_cloud_filter(client, monkeypatch):return {"available": True, "coverage": 1.0, "date": day, "layer": layer, "maxcc": maxcc}monkeypatch.setattr(sentinel, "coverage", check)- client.get(- "/api/satellite/sentinel/coverage?lat=48&lon=2&layer=SWIR&date=2026-05-11"- )+ client.get("/api/satellite/sentinel/coverage?lat=48&lon=2&layer=SWIR&date=2026-05-11")assert calls == [100]@@ -571,8 +584,7 @@ def test_sentinel_coverage_refuses_a_ceiling_outside_the_scale(client):client.put("/api/settings/keys", json={"sentinelhub": "inst-uuid"})# refused before anything is sent: no request, no chargeresponse = client.get(- "/api/satellite/sentinel/coverage"- "?lat=48&lon=2&layer=SWIR&date=2026-05-11&maxcc=150"+ "/api/satellite/sentinel/coverage?lat=48&lon=2&layer=SWIR&date=2026-05-11&maxcc=150")assert response.status_code == 422assert client.get("/api/settings").json()["usage"] == {}@@ -586,8 +598,7 @@ def test_sentinel_coverage_rejects_bad_input_without_counting(client, monkeypatcmonkeypatch.setattr(sentinel, "coverage", reject)response = client.get(- "/api/satellite/sentinel/coverage"- "?lat=48.8584&lon=2.2945&layer=bad&date=2026-05-11"+ "/api/satellite/sentinel/coverage?lat=48.8584&lon=2.2945&layer=bad&date=2026-05-11")assert response.status_code == 422assert client.get("/api/settings").json()["usage"] == {}@@ -601,8 +612,7 @@ def test_sentinel_coverage_failure_is_upstream_error(client, monkeypatch):monkeypatch.setattr(sentinel, "coverage", fail)response = client.get(- "/api/satellite/sentinel/coverage"- "?lat=48.8584&lon=2.2945&layer=SWIR&date=2026-05-11"+ "/api/satellite/sentinel/coverage?lat=48.8584&lon=2.2945&layer=SWIR&date=2026-05-11")assert response.status_code == 502assert client.get("/api/settings").json()["usage"] == {}@@ -668,7 +678,8 @@ def test_google_key_test_speaks_googles_own_words(client, monkeypatch):def blocked(url, **kwargs):return httpx.Response(- 403, content=eea.encode(),+ 403,+ content=eea.encode(),headers={"content-type": "application/json"},request=httpx.Request("POST", url),)@@ -696,15 +707,18 @@ def test_google_js_key_is_tested_in_the_browser(client):ids = {p["id"] for p in client.get("/api/satellite/providers").json()}assert "google-js" not in ids # benched by the browser's verdict- assert client.post(- "/api/settings/keys/nope/status", json={"ok": True, "detail": ""}- ).status_code == 404+ assert (+ client.post("/api/settings/keys/nope/status", json={"ok": True, "detail": ""}).status_code+ == 404+ )def test_per_provider_eco_thresholds(client):"""Each tile API gets its own eco threshold; the widget is not tunable(an eco swap re-bills a map load) and unknown names are ignored."""- client.put("/api/settings/keys", json={"mapbox": "pk.x", "sentinelhub": "inst", "google_js": "AIza.js"})+ client.put(+ "/api/settings/keys", json={"mapbox": "pk.x", "sentinelhub": "inst", "google_js": "AIza.js"}+ )r = client.put("/api/settings/prefs",json={"eco_max_zooms": {"mapbox": 12, "sentinelhub": 0, "google_js": 9, "bogus": 3}},@@ -844,7 +858,9 @@ def test_signature_delete_is_idempotent(client):def test_signature_rejects_non_png(client):# the bytes are what count, not the name or the content-type the browser sent- body = client.post("/api/settings/signature", files={"file": ("logo.png", b"GIF89a...", "image/png")})+ body = client.post(+ "/api/settings/signature", files={"file": ("logo.png", b"GIF89a...", "image/png")}+ )assert body.status_code == 422assert "PNG" in body.json()["detail"]assert client.get("/api/settings").json()["signature"] is False@@ -938,7 +954,7 @@ def test_signature_never_lands_in_a_case(client):"""It is workspace-level, like the API keys — a case folder never sees it."""client.post("/api/settings/signature", files={"file": ("logo.png", PNG, "image/png")})assert config.signature_path().is_file()- assert config.signature_path().parent == config.workspace_root()+ assert config.signature_path().parent == config.settings_dir()case_id = client.post("/api/cases", json={"name": "Signed"}).json()["id"]case_dir = config.cases_dir() / case_idassert not list(case_dir.rglob("signature.png"))@@ -1015,4 +1031,4 @@ def test_update_then_reset_round_trip(client, monkeypatch):def test_scrapers_live_in_the_workspace_not_the_install(client):"""The runtime dir has to be somewhere writable — the binary's own dir isn't."""- assert config.runtime_dir().parent == config.workspace_root()+ assert config.runtime_dir().parent == config.internal_dir()diff --git a/tests/test_settings_backup.py b/tests/test_settings_backup.pyindex b953ccc..6c0ffb8 100644--- a/tests/test_settings_backup.py+++ b/tests/test_settings_backup.py@@ -133,6 +133,23 @@ def test_export_leaves_the_login_session_behind(client):assert "Netscape" not in raw+def test_export_leaves_the_workspace_location_behind(client, tmp_path):+ """Where the workspace is, is an address on *this* machine.++ A backup exists to carry keys and presets to another computer, where that+ path may be a drive letter that doesn't exist or someone else's home. So the+ pointer stays put, and it is deliberately not a settings key — which is why+ the drift gate above cannot be the thing that catches this.+ """+ pointed = tmp_path / "somewhere" / "Azimut"+ pointed.mkdir(parents=True)+ config.write_pointer(pointed)++ blob = bundle_of(client)++ assert "somewhere" not in str(blob)++def test_the_browser_login_choice_travels_but_a_missing_file_does_not(client):client.put("/api/settings/prefs",diff --git a/tests/test_sqlite_backend.py b/tests/test_sqlite_backend.pyindex 1a12d97..3f1f770 100644--- a/tests/test_sqlite_backend.py+++ b/tests/test_sqlite_backend.py@@ -15,8 +15,9 @@ import threadingimport pytestfrom bigcase import build_big_case-from legacy_case import write_legacy_json_case+from legacy_case import legacy_manifest_path, read_legacy_manifest, write_legacy_json_case+from azimut import layoutfrom azimut.sqlite_backend import SqliteCase, convert_json_to_sqlitefrom azimut.workspace import CaseError@@ -151,7 +152,10 @@ def test_open_upgrades_a_v1_db_through_every_migration(tmp_path):with sqlite3.connect(db) as conn:conn.executescript(_SCHEMA_V1)- store = SqliteCase.open(db) # runs 1 -> 2 -> 3 -> 4 -> 5 -> 6 -> 7 in place+ # runs 1 -> 2 -> 3 -> 4 -> 5 -> 6 -> 7 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")# 1 -> 2: the folder column is backfilled and pages by folder.assert [e["id"] for e in store.page_entities(folder="Sources/Telegram")["items"]] == ["e1"]@@ -180,7 +184,7 @@ def test_open_upgrades_a_v1_db_through_every_migration(tmp_path):}assert "state" in trash_columns- SqliteCase.open(db) # idempotent — the second open applies nothing+ SqliteCase.open(db, media_dir=tmp_path / "media") # idempotent — applies nothingwith sqlite3.connect(db) as conn:for version in (2, 3, 4, 5, 6, 7):assert conn.execute(@@ -247,6 +251,34 @@ def test_open_backfills_the_position_flag_from_already_indexed_items(tmp_path):assert store.page_media_items()["facets"]["gps_count"] == 1+def test_open_without_a_media_dir_defers_the_backfill(tmp_path):+ """The backend is never told the case layout, so it must not invent one.++ An open with no media directory leaves the sidecar backfill undone and its+ marker unset, and a later open that knows where media live performs it.+ Anything else would silently index the wrong folder once the case tree+ moves.+ """+ db = tmp_path / "case.db"+ with sqlite3.connect(db) as 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)+ (media_dir / "shot.png").write_bytes(b"x")+ (media_dir / layout.META_DIR / "shot.png.json").write_text(+ '{"filename": "shot.png", "kind": "image", "size": 1,'+ ' "added_at": "2026", "source": {"type": "upload"}}',+ encoding="utf-8",+ )++ SqliteCase.open(db)+ with sqlite3.connect(db) as conn:+ assert conn.execute("SELECT value FROM meta WHERE key='media_index_ready'").fetchone() is None++ store = SqliteCase.open(db, media_dir=media_dir)+ assert [item["path"] for item in store.list_media_items()] == ["media/shot.png"]++def test_media_browse_index_pages_searches_and_counts_categories(tmp_path):store = SqliteCase.create(tmp_path / "case.db", name="Media index")store.upsert_media_item(@@ -318,11 +350,11 @@ def test_concurrent_first_open_cannot_replace_registered_media_rows(tmp_path):db = tmp_path / "case.db"SqliteCase.create(db, name="Concurrent index")media_dir = tmp_path / "media"- media_dir.mkdir()+ (media_dir / layout.META_DIR).mkdir(parents=True)for i in range(8):name = f"item-{i}.png"(media_dir / name).write_bytes(bytes([i]))- (media_dir / f"{name}.azimut.json").write_text(+ (media_dir / layout.META_DIR / f"{name}.json").write_text(('{"filename": "%s", "kind": "image", "size": 1,'' "added_at": "2026", "source": {"type": "upload"}}'@@ -335,7 +367,7 @@ def test_concurrent_first_open_cannot_replace_registered_media_rows(tmp_path):def open_and_register(i: int) -> None:try:- store = SqliteCase.open(db)+ store = SqliteCase.open(db, media_dir=media_dir)store.upsert_media_item({"path": f"media/live-{i}.png",@@ -356,7 +388,7 @@ def test_concurrent_first_open_cannot_replace_registered_media_rows(tmp_path):worker.join()assert errors == []- assert len(SqliteCase.open(db).list_media_items()) == 16+ assert len(SqliteCase.open(db, media_dir=media_dir).list_media_items()) == 16def test_pagination_keys_on_rowid_so_a_deletion_does_not_skip(tmp_path):@@ -449,12 +481,12 @@ def test_convert_writes_only_the_target_db(tmp_workspace, tmp_path):"Live",entities=[{"id": "e_a", "type": "person", "label": "Ada", "attrs": {}, "provenance": prov}],)- before = case.json_path.read_bytes()+ before = legacy_manifest_path(case).read_bytes()- convert_json_to_sqlite(case.read(), tmp_path / "case.db")+ convert_json_to_sqlite(read_legacy_manifest(case), tmp_path / "case.db")# the converter only reads the graph; it never rewrites the source case.json- assert case.json_path.read_bytes() == before+ assert legacy_manifest_path(case).read_bytes() == beforeassert (tmp_path / "case.db").exists()@@ -463,7 +495,7 @@ def test_convert_a_large_case_is_intact(tmp_workspace, tmp_path):name="Big", entities=300, links=400, media=100, notes=20, artifacts=30,write_media_files=False,)- report = convert_json_to_sqlite(case.read(), tmp_path / "case.db")+ report = convert_json_to_sqlite(read_legacy_manifest(case), tmp_path / "case.db")assert report.integrity_okassert report.entities == summary.entitiesdiff --git a/tests/test_thumbnails.py b/tests/test_thumbnails.pyindex 85e9b8e..98eaf3f 100644--- a/tests/test_thumbnails.py+++ b/tests/test_thumbnails.py@@ -17,6 +17,7 @@ import timeimport pytestfrom PIL import Image+from azimut import layoutfrom azimut.engine import media as media_enginefrom azimut.engine import thumbnails, workqueuefrom azimut.workspace import Case@@ -96,7 +97,7 @@ def test_a_failing_render_retries_then_fails_without_looping(case, monkeypatch):def test_drain_cancels_a_job_whose_media_is_gone(case):_register_video(case)(case.subdir("media") / "clip.mp4").unlink()- (case.subdir("media") / ("clip.mp4" + media_engine.SIDECAR_SUFFIX)).unlink()+ case.resolve_inside(layout.sidecar_rel("media/clip.mp4")).unlink()workqueue.drain(case)assert case.list_jobs(kind=thumbnails.THUMB_KIND)[0]["state"] == "cancelled"@@ -176,15 +177,15 @@ def test_deleting_one_of_two_media_sharing_a_thumbnail_keeps_it(case):def test_startup_recovers_interrupted_jobs(case, monkeypatch):- """The server's startup pass returns a job an earlier run left `running` back- to the queue, so pending thumbnail work resumes instead of stalling."""- from azimut import server-+ """The startup pass returns a job an earlier run left `running` back to the+ queue, so pending thumbnail work resumes instead of stalling. Also runs when+ the workspace root changes, which is why it belongs to the queue rather than+ to the server."""_register_video(case)running = case.claim_job() # simulate a crash mid-renderassert running["state"] == "running"- server._recover_jobs() # what create_app runs on boot (worker disabled here)+ workqueue.recover_all() # what opening a workspace runs (worker disabled here)assert case.get_job(running["id"])["state"] == "queued"diff --git a/tests/test_trash.py b/tests/test_trash.pyindex 709eea3..99e302e 100644--- a/tests/test_trash.py+++ b/tests/test_trash.py@@ -5,7 +5,10 @@ still hard-deletes, so nothing else has to filter deleted rows out, and the undoputs back the entity, its files, its links and the scars its delete wrote."""+from pathlib import Path+import fullcase+from azimut import layoutfrom azimut.engine import workqueuefrom azimut.workspace import Case@@ -23,7 +26,7 @@ def trash_of(client, case_id: str) -> dict:def test_a_deleted_artifact_waits_in_the_trash_instead_of_going(client):full = fullcase.build_full_case(client)case = Case.open(full.case_id)- note = entity_of(client, full.case_id, "path", f"notes/{full.note_id}.md")+ note = entity_of(client, full.case_id, "path", full.note)deleted = client.delete(f"/api/cases/{full.case_id}/entities/{note['id']}").json()@@ -36,7 +39,11 @@ def test_a_deleted_artifact_waits_in_the_trash_instead_of_going(client):assert listed["groups"][0]["label"] == note["label"]assert listed["items"] == 1assert listed["size_bytes"] > 0- assert (case.trash_dir / deleted["trash"] / note["attrs"]["path"]).is_file()+ # ...under a numbered slot, not under a copy of the case tree: the group+ # directory is flat, so the trash can never be the longest path in the case.+ group_dir = case.trash_dir / deleted["trash"]+ assert [p.name for p in group_dir.iterdir()] == ["0"]+ assert (group_dir / "0").is_file()def test_undo_brings_back_the_entity_its_id_and_its_file(client):@@ -52,7 +59,7 @@ def test_undo_brings_back_the_entity_its_id_and_its_file(client):# the same id: every spec, draft and link recorded elsewhere still points at itassert back["id"] == photo["id"]assert case.resolve_inside(full.photo).is_file()- assert case.resolve_inside(full.photo + ".azimut.json").is_file()+ assert case.resolve_inside(layout.sidecar_rel(full.photo)).is_file()# and it is browsable again — the media index row came back with itlisted = client.get(f"/api/cases/{full.case_id}/media").json()assert any(item["path"] == full.photo for item in listed)@@ -117,7 +124,11 @@ def test_a_proof_takes_its_pasted_images_into_the_trash_and_back(client):proof = entity_of(client, full.case_id, "spec", full.proof)group = client.delete(f"/api/cases/{full.case_id}/entities/{proof['id']}").json()["trash"]- assert (case.trash_dir / group / full.proof_asset).is_file()+ # The assets folder travels whole, as one slot — a directory the group holds+ # under a number, with the pasted image still inside it.+ group_dir = case.trash_dir / group+ asset_name = Path(full.proof_asset).name+ assert [p.name for p in sorted(group_dir.rglob(asset_name))] == [asset_name]assert not case.resolve_inside(full.proof_asset).exists()client.post(f"/api/cases/{full.case_id}/trash/{group}/restore")@@ -129,11 +140,15 @@ def test_restoring_onto_an_occupied_path_refuses_rather_than_renames(client):clear failure, so the whole group refuses and names the file."""full = fullcase.build_full_case(client)case = Case.open(full.case_id)- note = entity_of(client, full.case_id, "path", f"notes/{full.note_id}.md")+ note = entity_of(client, full.case_id, "path", full.note)rel = note["attrs"]["path"]group = client.delete(f"/api/cases/{full.case_id}/entities/{note['id']}").json()["trash"]- case.resolve_inside(rel).write_text("something else wrote here", encoding="utf-8")+ # the delete pruned the note's mirrored folder, so re-make it to put+ # something in the way+ occupied = case.resolve_inside(rel)+ occupied.parent.mkdir(parents=True, exist_ok=True)+ occupied.write_text("something else wrote here", encoding="utf-8")refused = client.post(f"/api/cases/{full.case_id}/trash/{group}/restore")assert refused.status_code == 409@@ -147,7 +162,7 @@ def test_restoring_onto_an_occupied_path_refuses_rather_than_renames(client):def test_purging_is_where_the_bytes_go(client):full = fullcase.build_full_case(client)case = Case.open(full.case_id)- note = entity_of(client, full.case_id, "path", f"notes/{full.note_id}.md")+ note = entity_of(client, full.case_id, "path", full.note)group = client.delete(f"/api/cases/{full.case_id}/entities/{note['id']}").json()["trash"]assert client.delete(f"/api/cases/{full.case_id}/trash/{group}").status_code == 200@@ -194,7 +209,7 @@ def test_deleting_a_case_takes_its_trash_with_it(client):there is nothing left to hold anything for."""full = fullcase.build_full_case(client)case = Case.open(full.case_id)- note = entity_of(client, full.case_id, "path", f"notes/{full.note_id}.md")+ note = entity_of(client, full.case_id, "path", full.note)client.delete(f"/api/cases/{full.case_id}/entities/{note['id']}")assert client.delete(f"/api/cases/{full.case_id}").status_code == 200diff --git a/tests/test_updates.py b/tests/test_updates.pyindex 0a5e1fd..442e948 100644--- a/tests/test_updates.py+++ b/tests/test_updates.py@@ -64,16 +64,27 @@ def test_check_reports_a_newer_release(monkeypatch):def test_check_carries_release_notes_capped(monkeypatch):+ body = " ## What's new\n- stuff\n" + "".join(f"- entry {i}\n" for i in range(900))monkeypatch.setattr(updates.httpx,"get",- lambda *a, **k: FakeResponse(- {"tag_name": "v9.9.9", "body": " ## What's new\n- stuff " + "x" * 9000}- ),+ lambda *a, **k: FakeResponse({"tag_name": "v9.9.9", "body": body}),)result = updates.check("0.1.1")- assert result["notes"].startswith("## What's new") # stripped- assert len(result["notes"]) == updates.NOTES_LIMIT # capped+ notes = result["notes"]+ assert notes.startswith("## What's new") # stripped+ assert len(notes) <= updates.NOTES_LIMIT # capped+ # cut on a line boundary, so the pop-up never renders half a line+ assert notes.splitlines()[-1] in body.splitlines()+++def test_check_caps_a_release_note_with_no_line_break(monkeypatch):+ monkeypatch.setattr(+ updates.httpx,+ "get",+ lambda *a, **k: FakeResponse({"tag_name": "v9.9.9", "body": "x" * 9000}),+ )+ assert len(updates.check("0.1.1")["notes"]) == updates.NOTES_LIMITdef test_check_up_to_date(monkeypatch):diff --git a/tests/test_workspace_api.py b/tests/test_workspace_api.pynew file mode 100644index 0000000..c15a1c0--- /dev/null+++ b/tests/test_workspace_api.py@@ -0,0 +1,318 @@+"""The workspace-folder routes, and the two states that close the app down.++A configured folder that is gone and a workspace being copied are the same+answer to a case route: 503, with the recovery routes still reachable so the+browser can say what happened and offer the way out.+"""++from __future__ import annotations++import shutil+import tempfile+import time+from pathlib import Path++import pytest+from fastapi.testclient import TestClient++from azimut import config+from azimut.engine import workspacemove+from azimut.workspace import Case++[email protected](autouse=True)+def forget_the_last_move():+ workspacemove._move = None+ yield+ workspacemove._move = None+++def tmp_path():+ """A base directory short enough that a case fits under it on Windows.++ Shadows pytest's own for this module, for the reason spelled out in+ `tests/test_workspace_move.py`: pytest's temp path is longer than the Windows+ path budget leaves for a workspace root, so every folder these routes are+ offered would be refused as too long rather than exercised.+ """+ base = Path(tempfile.mkdtemp()).resolve()+ try:+ yield base+ finally:+ shutil.rmtree(base, ignore_errors=True)+++def pointed_client(monkeypatch, tmp_path):+ """A client whose workspace is found through the pointer, as in the field.++ The ``client`` fixture pins ``AZIMUT_HOME``, which deliberately overrides+ the pointer — it would hide every effect these routes have.+ """+ monkeypatch.delenv("AZIMUT_HOME", raising=False)+ root = tmp_path / "home" / "Azimut"+ root.mkdir(parents=True)+ config.write_pointer(root)+ from azimut.server import create_app++ with TestClient(create_app(), base_url="http://127.0.0.1") as client:+ yield client, root+++def _wait_for_the_move(client, timeout: float = 20.0) -> dict:+ deadline = time.monotonic() + timeout+ while time.monotonic() < deadline:+ move = client.get("/api/settings/workspace").json()["move"]+ if move and move["done"]:+ return move+ time.sleep(0.01)+ raise AssertionError("the move never finished")+++def test_the_status_names_the_folder_and_its_cases(pointed_client):+ client, root = pointed_client+ Case.create("Harbour survey")++ body = client.get("/api/settings/workspace").json()++ assert body["root"] == str(root)+ assert body["cases"] == 1+ assert body["pointed"] is True+ assert body["move"] is None+++def test_inspecting_a_folder_reports_rather_than_fails(pointed_client, tmp_path):+ client, root = pointed_client++ body = client.post(+ "/api/settings/workspace/inspect", json={"path": str(root / "inside")}+ ).json()++ assert body["ok"] is False+ assert body["problems"] == ["that folder is inside the current workspace"]+++def test_inspecting_touches_nothing(pointed_client, tmp_path):+ client, _root = pointed_client+ target = tmp_path / "never-created"++ client.post("/api/settings/workspace/inspect", json={"path": str(target)})++ assert not target.exists()+++def test_using_a_folder_switches_without_moving_anything(pointed_client, tmp_path):+ client, root = pointed_client+ Case.create("Harbour survey")+ fresh = tmp_path / "fresh"++ body = client.post("/api/settings/workspace/use", json={"path": str(fresh)}).json()++ assert body["root"] == str(fresh)+ assert body["cases"] == 0+ assert (root / "harbour-survey").is_dir()+ assert client.get("/api/cases").json() == []+++def test_using_a_refused_folder_is_a_conflict(pointed_client):+ client, root = pointed_client++ response = client.post("/api/settings/workspace/use", json={"path": str(root)})++ assert response.status_code == 409+ assert "already the workspace" in response.json()["detail"]+++def test_going_back_to_the_default_folder(pointed_client):+ client, _root = pointed_client++ body = client.post("/api/settings/workspace/default").json()++ assert body["pointed"] is False+ assert config.read_pointer() is None+++def test_moving_the_workspace_end_to_end(pointed_client, tmp_path):+ client, root = pointed_client+ Case.create("Harbour survey")+ target = tmp_path / "volume" / "Azimut"++ queued = client.post("/api/settings/workspace/move", json={"path": str(target)})+ assert queued.status_code == 200+ move = _wait_for_the_move(client)++ assert not move["error"]+ assert client.get("/api/settings/workspace").json()["root"] == str(target)+ assert [row["name"] for row in client.get("/api/cases").json()] == ["Harbour survey"]++ removed = client.post("/api/settings/workspace/discard-old")++ assert removed.status_code == 200+ assert not (root.parent / f"{root.name}.old-{time.strftime('%Y-%m-%d')}").exists()+++def test_discarding_nothing_is_a_conflict(pointed_client):+ client, _root = pointed_client++ response = client.post("/api/settings/workspace/discard-old")++ assert response.status_code == 409+++def test_a_move_onto_an_existing_workspace_is_a_conflict(pointed_client, tmp_path):+ client, _root = pointed_client+ other = tmp_path / "other"+ (other / ".azimut").mkdir(parents=True)++ response = client.post("/api/settings/workspace/move", json={"path": str(other)})++ assert response.status_code == 409+++# -- the two closed states -----------------------------------------------------+++def _make_the_workspace_vanish(root) -> None:+ """Take the folder away the way an unplugged drive does.++ The lock has to go first, and not to make the test pass: Windows cannot+ delete a file another handle has open, so the folder could not be removed at+ all while Azimut held it. That is faithful rather than convenient — a drive+ that leaves takes the handle with it, and a folder renamed from outside is+ only possible when nothing inside is open.+ """+ import shutil++ from azimut.engine import workspacelock++ workspacelock.release()+ shutil.rmtree(root)+++def test_a_workspace_that_is_gone_stops_the_app_without_recreating_it(pointed_client):+ """The drive was unplugged, or the folder renamed. Recreating it silently is+ how someone concludes they lost everything."""+ client, root = pointed_client++ _make_the_workspace_vanish(root)++ refused = client.get("/api/cases")++ assert refused.status_code == 503+ assert refused.json()["workspace"] == "missing"+ assert not root.exists()+++def test_the_recovery_routes_stay_reachable_when_the_workspace_is_gone(pointed_client, tmp_path):+ client, root = pointed_client++ _make_the_workspace_vanish(root)++ status = client.get("/api/settings/workspace")++ assert status.status_code == 200+ assert status.json()["missing"] is True+ assert client.get("/api/health").status_code == 200++ adopted = client.post("/api/settings/workspace/use", json={"path": str(tmp_path / "again")})++ assert adopted.status_code == 200+ assert client.get("/api/cases").status_code == 200+++def test_a_workspace_another_azimut_holds_is_left_alone(monkeypatch, tmp_path):+ """Not "stopped because the folder is missing" — the folder is fine, it just+ isn't ours. Nothing is migrated and nothing is written."""+ import json++ from azimut.engine import workspacelock++ monkeypatch.delenv("AZIMUT_HOME", raising=False)+ root = tmp_path / "shared" / "Azimut"+ (root / ".azimut").mkdir(parents=True)+ workspacelock.lock_path(root).write_text(+ json.dumps({"host": "other-laptop", "pid": 4321, "port": 8477, "at": workspacelock._now()}),+ encoding="utf-8",+ )+ config.write_pointer(root)+ from azimut.server import create_app++ with TestClient(create_app(), base_url="http://127.0.0.1") as client:+ refused = client.get("/api/cases")++ assert refused.status_code == 503+ assert refused.json()["workspace"] == "locked"+ assert "other-laptop" in refused.json()["detail"]++ status = client.get("/api/settings/workspace").json()+ assert status["locked_by"]["host"] == "other-laptop"+ assert "other-laptop" in status["locked_detail"]+ assert not config.settings_path().exists(), "a locked workspace must not be written to"++ taken = client.post("/api/settings/workspace/take")++ assert taken.status_code == 200+ assert taken.json()["locked_by"] is None+ assert client.get("/api/cases").status_code == 200+ assert config.settings_path().exists()+++def test_the_tab_comes_back_when_the_other_azimut_closes(monkeypatch, tmp_path):+ """"Close the other Azimut and reload" has to actually work. The lock is+ retried on the next request rather than decided once at startup — but a+ workspace this process never opened is one whose migrations never ran, so+ the retry opens it before serving anything."""+ import json++ from azimut.engine import workspacelock++ monkeypatch.delenv("AZIMUT_HOME", raising=False)+ root = tmp_path / "shared" / "Azimut"+ (root / ".azimut").mkdir(parents=True)+ lock = workspacelock.lock_path(root)+ lock.write_text(+ json.dumps({"host": "other-laptop", "pid": 4321, "at": workspacelock._now()}),+ encoding="utf-8",+ )+ config.write_pointer(root)+ from azimut.server import create_app++ with TestClient(create_app(), base_url="http://127.0.0.1") as client:+ assert client.get("/api/cases").status_code == 503++ lock.write_text("{}", encoding="utf-8") # the other one exited++ assert client.get("/api/cases").status_code == 200+ assert config.settings_path().exists(), "the workspace was opened, not just unlocked"+++def test_case_work_is_refused_while_the_workspace_is_being_moved(+ pointed_client, tmp_path, monkeypatch+):+ client, _root = pointed_client+ reached = {"copying": False}+ real_copy = workspacemove._step_copy++ def slow_copy(move, staging):+ reached["copying"] = True+ time.sleep(0.4)+ real_copy(move, staging)++ monkeypatch.setattr(workspacemove, "_step_copy", slow_copy)+ queued = client.post("/api/settings/workspace/move", json={"path": str(tmp_path / "volume")})+ assert queued.status_code == 200, queued.json()+ # Bounded: a move refused before it copies would spin here forever, and a+ # hung test costs a whole CI job rather than one red line.+ deadline = time.monotonic() + 20+ while not reached["copying"]:+ assert time.monotonic() < deadline, "the move never reached the copy step"+ time.sleep(0.01)++ refused = client.get("/api/cases")++ assert refused.status_code == 503+ assert refused.json()["workspace"] == "moving"+ assert client.get("/api/settings/workspace").status_code == 200++ _wait_for_the_move(client)diff --git a/tests/test_workspace_lock.py b/tests/test_workspace_lock.pynew file mode 100644index 0000000..007391f--- /dev/null+++ b/tests/test_workspace_lock.py@@ -0,0 +1,288 @@+"""One Azimut per workspace, across processes.++The exclusion tests use a real child process, because that is the only way to+test the property the design rests on: the operating system drops the lock when+the holder dies, so a crash can never leave a workspace bolted shut. Simulating+it in-process would test `flock`'s same-process semantics, which differ between+Linux and Windows and are not what the app relies on.++The payload tests are in-process, because a foreign machine is not something a+child can be — a hand-written payload is exactly what a synced folder delivers.+"""++from __future__ import annotations++import json+import os+import socket+import subprocess+import sys+import textwrap+import time+from datetime import datetime, timedelta, timezone+from pathlib import Path++import pytest++from azimut.engine import workspacelock+from azimut.engine.workspacelock import WorkspaceBusy++SRC = str(Path(__file__).resolve().parents[1] / "src")++[email protected](autouse=True)+def release_between_tests():+ workspacelock.release()+ yield+ workspacelock.release()+++def workspace(monkeypatch, tmp_path):+ monkeypatch.setenv("AZIMUT_HOME", str(tmp_path))+ (tmp_path / ".azimut").mkdir()+ return tmp_path+++def _payload(root: Path) -> dict:+ return json.loads(workspacelock.lock_path(root).read_text(encoding="utf-8"))+++def _write_payload(root: Path, **fields) -> None:+ workspacelock.lock_path(root).write_text(json.dumps(fields), encoding="utf-8")+++def _holder_process(root: Path) -> subprocess.Popen:+ """A child that takes the lock and keeps it until it is killed."""+ child = subprocess.Popen(+ [+ sys.executable,+ "-c",+ textwrap.dedent(+ f"""+ import os, sys, time+ sys.path.insert(0, {SRC!r})+ os.environ["AZIMUT_HOME"] = {str(root)!r}+ from azimut.engine import workspacelock+ workspacelock.acquire(8477)+ print("held", flush=True)+ time.sleep(60)+ """+ ),+ ],+ stdout=subprocess.PIPE,+ text=True,+ )+ assert child.stdout is not None+ assert child.stdout.readline().strip() == "held", "the child never took the lock"+ return child+++# -- another process -----------------------------------------------------------+++def test_a_second_instance_is_refused_and_names_the_holder(workspace):+ child = _holder_process(workspace)+ try:+ with pytest.raises(WorkspaceBusy) as refused:+ workspacelock.acquire(8478)+ finally:+ child.kill()+ child.wait(timeout=10)++ # A pid, not *this* pid: on Windows the interpreter Popen starts is not always+ # the process that ends up running the code, so `child.pid` can name a+ # launcher while the payload names the python behind it. What the payload owes+ # the analyst is the identity of the holder — the machine and the port it+ # serves on, which is what the dialog shows — and that it names a process at+ # all rather than an empty file.+ assert isinstance(refused.value.holder["pid"], int)+ assert refused.value.holder["host"] == socket.gethostname()+ assert "8477" in str(refused.value)+++def test_the_lock_dies_with_the_process(workspace):+ """The whole reason it is an OS lock rather than a file we write and delete:+ a crashed Azimut must never leave a workspace nobody can open."""+ child = _holder_process(workspace)+ child.kill()+ child.wait(timeout=10)++ workspacelock.acquire(8478) # no exception: the OS let go on its own++ assert workspacelock.holder() is None+++def test_a_clean_exit_leaves_no_payload_to_age(workspace):+ child = _holder_process(workspace)+ child.terminate()+ child.wait(timeout=10)++ # The child's atexit-free path still releases via the OS; what matters is+ # that the next run can take it without judging a corpse.+ workspacelock.acquire(8478)++ assert _payload(workspace)["pid"] == os.getpid()+++# -- another machine, seen through a synced folder -----------------------------+++def test_a_beating_heart_on_another_machine_is_believed(workspace):+ """On a share where `flock` is a no-op, the payload is all there is. A lock+ we *could* take is still refused when someone else is plainly using it."""+ _write_payload(workspace, host="other-laptop", pid=999, port=8477, at=workspacelock._now())++ with pytest.raises(WorkspaceBusy, match="other-laptop"):+ workspacelock.acquire(8478)+++def test_a_stopped_heart_on_another_machine_is_taken_over(workspace):+ gone = datetime.now(timezone.utc) - timedelta(+ seconds=workspacelock.STALE_AFTER_SECONDS + 60+ )+ _write_payload(+ workspace, host="other-laptop", pid=999, at=gone.isoformat(timespec="seconds")+ )++ workspacelock.acquire(8478)++ assert _payload(workspace)["host"] == socket.gethostname()+++def test_our_own_crashed_run_is_taken_over_whatever_its_heartbeat_says(workspace):+ """On this machine the OS lock is the authority. Being granted it proves the+ process that wrote this payload is gone, however recent the timestamp."""+ _write_payload(workspace, host=socket.gethostname(), pid=999, at=workspacelock._now())++ workspacelock.acquire(8478)++ assert _payload(workspace)["pid"] == os.getpid()+++def test_the_workspace_we_hold_is_ours_under_any_spelling_of_its_path(monkeypatch, tmp_path):+ """A folder reached through a symlink is the same folder.++ `holder()` is asked about a path that has been resolved, while what this+ process locked came from the pointer. If those two spellings are not brought+ together, the lock file is opened a second time, our own handle refuses the+ second lock, and Settings tells the analyst another Azimut is using the+ workspace they are working in. macOS reaches every temporary directory that+ way (`/var` → `/private/var`), and so does a synced or linked folder anywhere.+ """+ real = tmp_path / "real"+ (real / ".azimut").mkdir(parents=True)+ linked = tmp_path / "linked"+ linked.symlink_to(real, target_is_directory=True)+ monkeypatch.setenv("AZIMUT_HOME", str(linked))++ workspacelock.acquire(8477)++ assert workspacelock.held()+ assert workspacelock.holder(linked) is None+ assert workspacelock.holder(real) is None, "the resolved path is the same workspace"+++def test_an_unreadable_lock_file_never_stops_the_app(workspace):+ workspacelock.lock_path(workspace).write_bytes(b"\x00\xff not json at all")++ workspacelock.acquire(8478)++ assert _payload(workspace)["pid"] == os.getpid()+++def test_the_analyst_can_overrule_the_verdict(workspace):+ """Two machines' clocks disagree, and a sync client can leave a file nobody+ is left to clear. Without this, either would make a workspace unopenable."""+ _write_payload(workspace, host="other-laptop", pid=999, at=workspacelock._now())++ workspacelock.take_over(8478)++ assert _payload(workspace)["host"] == socket.gethostname()+++def test_forcing_past_a_process_that_really_holds_it_still_reports_the_truth(workspace):+ """Forcing rewrites the payload; it cannot steal the OS lock, and does not+ pretend to. The escape hatch is for ghosts, not for races."""+ child = _holder_process(workspace)+ try:+ workspacelock.take_over(8478)+ assert _payload(workspace)["pid"] == os.getpid()+ finally:+ child.kill()+ child.wait(timeout=10)+++# -- holding, releasing, heartbeat ---------------------------------------------+++def test_holding_it_is_idempotent(workspace):+ workspacelock.acquire(8477)+ workspacelock.acquire(8477)++ assert workspacelock.holder() is None+++def test_releasing_clears_the_payload(workspace):+ workspacelock.acquire(8477)++ workspacelock.release()++ assert _payload(workspace) == {}+ assert workspacelock.holder() is None+++def test_the_heartbeat_is_refreshed_while_it_is_held(workspace, monkeypatch):+ monkeypatch.setattr(workspacelock, "HEARTBEAT_SECONDS", 0.05)+ workspacelock.acquire(8477)+ first = _payload(workspace)["at"]++ deadline = time.monotonic() + 5+ while time.monotonic() < deadline and _payload(workspace)["at"] == first:+ time.sleep(0.05)++ assert _payload(workspace)["at"] != first+++def test_two_workspaces_do_not_block_each_other(monkeypatch, tmp_path):+ """A work workspace and a personal one are two folders, so two locks."""+ first, second = tmp_path / "work", tmp_path / "personal"+ monkeypatch.setenv("AZIMUT_HOME", str(first))+ workspacelock.acquire(8477)++ monkeypatch.setenv("AZIMUT_HOME", str(second))+ workspacelock.acquire(8477)++ assert workspacelock.holder() is None+ assert _payload(first) == {}, "the first lock should have been given back"+++def test_a_folder_can_be_asked_about_before_it_is_adopted(workspace, tmp_path):+ """What the Settings dialog needs: the lock of a folder that is not ours."""+ elsewhere = tmp_path / "elsewhere"+ (elsewhere / ".azimut").mkdir(parents=True)+ _write_payload(elsewhere, host="other-laptop", pid=999, at=workspacelock._now())++ assert workspacelock.holder(elsewhere)["host"] == "other-laptop"+ assert workspacelock.holder(workspace) is None+++def test_a_folder_with_no_lock_file_is_free(tmp_path):+ assert workspacelock.holder(tmp_path / "never-used") is None+++def test_the_locking_primitive_is_chosen_by_what_imports(workspace, monkeypatch):+ """Not by `sys.platform`, which other tests fake to exercise Windows paths —+ and which would then have this module reach for a module that isn't there.+ A platform with neither primitive degrades to the payload rather than+ raising from inside a lock attempt."""+ monkeypatch.setattr("sys.platform", "win32")+ workspacelock.acquire(8477) # would have raised ModuleNotFoundError++ workspacelock.release()+ monkeypatch.setattr(workspacelock, "fcntl", None)+ monkeypatch.setattr(workspacelock, "msvcrt", None)++ workspacelock.acquire(8477)++ assert _payload(workspace)["pid"] == os.getpid()diff --git a/tests/test_workspace_move.py b/tests/test_workspace_move.pynew file mode 100644index 0000000..4a92432--- /dev/null+++ b/tests/test_workspace_move.py@@ -0,0 +1,547 @@+"""Choosing where the workspace lives, and moving it there.++Two rules run through every test here. A folder the analyst configured is never+recreated or deleted behind their back, and at no point in a move is there less+than one complete workspace on disk.++The tests drive the pointer rather than ``AZIMUT_HOME`` because that is what a+move actually switches; the env var deliberately overrides it and would hide+the very thing under test.+"""++from __future__ import annotations++import shutil+import tempfile+import time+from pathlib import Path++import pytest++from azimut import config+from azimut.engine import workspacelock, workspacemove+from azimut.engine.workspacemove import MoveError+from azimut.workspace import Case++[email protected](autouse=True)+def forget_the_last_move():+ """One process holds one move. Nothing may inherit the previous one's+ leftovers — `discard_old` acts on that memory, and stale memory would name+ a folder from another run."""+ workspacemove._move = None+ yield+ workspacemove._move = None+++def tmp_path():+ """A base directory short enough that a case fits under it on Windows.++ Deliberately shadows pytest's own `tmp_path` for this module. That one spends+ around 100 characters on the test's name before the workspace even begins,+ and `layout.room_for_workspace_root()` leaves 84 — so on Windows every folder+ offered here would be refused as too long, correctly, and these tests would+ only ever exercise the refusal. A real root is short: `C:\\Users\\alice\\Azimut`+ is 21 characters, which is what this imitates.++ The budget stays live and enforced. What holds it is+ `test_a_path_too_long_for_windows_is_refused_there_and_named_elsewhere`+ below, which builds a deep path on purpose, and `tests/test_layout.py`,+ which recomputes the number from the tree.+ """+ base = Path(tempfile.mkdtemp()).resolve()+ try:+ yield base+ finally:+ shutil.rmtree(base, ignore_errors=True)+++def workspace(monkeypatch, tmp_path):+ """A workspace Azimut found through its pointer, as it does in the field."""+ monkeypatch.delenv("AZIMUT_HOME", raising=False)+ root = tmp_path / "home" / "Azimut"+ root.mkdir(parents=True)+ config.write_pointer(root)+ config.ensure_workspace()+ yield root+ # Adopting a folder or finishing a move takes the workspace lock, and the+ # lock is an open file handle: Windows cannot delete the directory around it.+ workspacelock.release()+++def _finish(timeout: float = 20.0) -> dict:+ deadline = time.monotonic() + timeout+ while time.monotonic() < deadline:+ move = workspacemove.status()["move"]+ if move and move["done"]:+ return move+ time.sleep(0.01)+ raise AssertionError("the move never finished")+++# -- reading a candidate folder ------------------------------------------------+++def test_a_blank_path_is_refused(workspace):+ assert workspacemove.inspect_target(" ")["problems"] == ["name a folder"]+++def test_a_file_is_not_a_folder(workspace, tmp_path):+ target = tmp_path / "notes.txt"+ target.write_text("", encoding="utf-8")++ assert workspacemove.inspect_target(str(target))["problems"] == [+ "that path is a file, not a folder"+ ]+++def test_a_folder_inside_the_workspace_is_refused(workspace):+ verdict = workspacemove.inspect_target(str(workspace / "inside"))++ assert verdict["problems"] == ["that folder is inside the current workspace"]+++def test_a_folder_containing_the_workspace_is_refused(workspace):+ """Copying a tree into one of its own ancestors is how a move eats itself.+ Reachable when the ancestor reads as a workspace, so nesting leaves it alone."""+ (workspace.parent / ".azimut").mkdir()++ verdict = workspacemove.inspect_target(str(workspace.parent))++ assert verdict["problems"] == ["that folder contains the current workspace"]+++def test_naming_the_folder_above_the_workspace_points_back_at_it(workspace):+ """Typing `~` when the workspace is `~/Azimut` is not an error to explain at+ length: the subfolder rule lands on the workspace itself, and saying so is+ the shortest true answer."""+ verdict = workspacemove.inspect_target(str(workspace.parent))++ assert verdict["problems"] == ["that is already the workspace"]+++def test_the_current_workspace_is_refused(workspace):+ assert workspacemove.inspect_target(str(workspace))["problems"] == [+ "that is already the workspace"+ ]+++def test_a_destination_holding_other_files_gets_its_own_subfolder(workspace, tmp_path):+ """Settling among someone's documents would make the workspace impossible to+ tell apart from them."""+ target = tmp_path / "OSINT"+ target.mkdir()+ (target / "case-notes.docx").write_text("", encoding="utf-8")++ verdict = workspacemove.inspect_target(str(target))++ assert verdict["ok"]+ assert verdict["nested"]+ assert Path(verdict["root"]) == target / "Azimut"+++def test_an_empty_destination_is_used_as_it_is(workspace, tmp_path):+ target = tmp_path / "empty"+ target.mkdir()++ verdict = workspacemove.inspect_target(str(target))++ assert verdict["ok"] and not verdict["nested"]+ assert verdict["state"] == "empty"+++def test_a_destination_that_does_not_exist_yet_is_offered(workspace, tmp_path):+ verdict = workspacemove.inspect_target(str(tmp_path / "new" / "Azimut"))++ assert verdict["ok"]+ assert verdict["state"] == "missing"+++def test_a_path_whose_parents_are_all_missing_is_refused(workspace, tmp_path):+ missing_root = "Z:\\gone\\Azimut" if Path("Z:/").drive else "/nonexistent-root/x/Azimut"++ verdict = workspacemove.inspect_target(missing_root)++ assert not verdict["ok"]+++def test_an_existing_workspace_is_recognised(workspace, tmp_path, monkeypatch):+ """The hand-moved folder: it already holds cases, and adopting it is the point."""+ Case.create("Harbour survey")+ moved = tmp_path / "moved-by-hand"+ shutil.move(str(workspace), str(moved))+ config.write_pointer(tmp_path / "somewhere-else")+ config.ensure_workspace()++ verdict = workspacemove.inspect_target(str(moved))++ assert verdict["state"] == "workspace"+ assert verdict["cases"] == 1+++def test_a_synced_folder_is_flagged_and_still_allowed(workspace, tmp_path):+ target = tmp_path / "OneDrive" / "Azimut"+ target.mkdir(parents=True)++ verdict = workspacemove.inspect_target(str(target))++ assert verdict["ok"]+ assert any("synced folder" in warning for warning in verdict["warnings"])+++def test_a_path_too_long_for_windows_is_refused_there_and_named_elsewhere(+ workspace, tmp_path, monkeypatch+):+ """The budget from `layout` is finally enforced here: this is the last free+ variable in the subtraction that keeps a case openable on Windows."""+ deep = tmp_path / ("d" * 60) / ("e" * 60) / ("f" * 60) / ("g" * 60)++ monkeypatch.setattr("sys.platform", "win32")+ refused = workspacemove.inspect_target(str(deep))+ monkeypatch.setattr("sys.platform", "linux")+ allowed = workspacemove.inspect_target(str(deep))++ assert not refused["ok"]+ assert "too long" in refused["problems"][0]+ assert any("too long" in warning for warning in allowed["warnings"])+++def test_a_destination_without_room_is_refused(workspace, tmp_path, monkeypatch):+ target = tmp_path / "tiny"+ target.mkdir()+ monkeypatch.setattr(+ shutil, "disk_usage", lambda _path: shutil._ntuple_diskusage(1_000_000, 999_000, 1_000)+ )++ verdict = workspacemove.inspect_target(str(target))++ assert not verdict["ok"]+ assert "not enough free space" in verdict["problems"][0]+++# -- adopting a folder ---------------------------------------------------------+++def test_adopting_a_hand_moved_folder_finds_its_cases(workspace, tmp_path):+ Case.create("Harbour survey")+ moved = tmp_path / "OSINT" / "Azimut"+ moved.parent.mkdir()+ shutil.move(str(workspace), str(moved))+ config.write_pointer(tmp_path / "gone")++ workspacemove.adopt(str(moved))++ assert config.workspace_root() == moved+ assert [row["name"] for row in Case.list_all()] == ["Harbour survey"]+++def test_adopting_an_empty_folder_leaves_the_old_cases_where_they_are(workspace, tmp_path):+ Case.create("Harbour survey")+ fresh = tmp_path / "fresh"++ workspacemove.adopt(str(fresh))++ assert config.workspace_root() == fresh+ assert Case.list_all() == []+ assert (workspace / "harbour-survey").is_dir()+++def test_adopting_creates_the_skeleton_and_keeps_the_workspace_private(workspace, tmp_path):+ workspacemove.adopt(str(tmp_path / "fresh"))++ assert config.settings_path().is_file()+ assert config.scratch_dir().is_dir()+ assert config.bundles_dir().is_dir()+++def test_going_back_to_the_default_root_clears_the_pointer(workspace, tmp_path):+ workspacemove.use_default()++ assert config.read_pointer() is None+ assert config.workspace_root() == config.DEFAULT_ROOT.expanduser()+++def test_adopting_a_refused_folder_raises(workspace):+ with pytest.raises(MoveError):+ workspacemove.adopt(str(workspace / "inside"))+++# -- moving --------------------------------------------------------------------+++def test_a_move_copies_verifies_switches_and_keeps_the_old_folder(workspace, tmp_path):+ case = Case.create("Harbour survey")+ (case.path / "analyst-notes.txt").write_text("mine", encoding="utf-8")+ target = tmp_path / "elsewhere" / "Azimut"++ workspacemove.start(str(target))+ move = _finish()++ assert not move["error"]+ assert config.workspace_root() == target+ assert config.read_pointer() == target+ assert [row["name"] for row in Case.list_all()] == ["Harbour survey"]+ assert (target / "harbour-survey" / "analyst-notes.txt").read_text(encoding="utf-8") == "mine"+ assert Path(move["kept_aside"]).is_dir()+ assert not workspace.exists()+++def test_the_old_folder_is_kept_complete_until_the_analyst_drops_it(workspace, tmp_path):+ Case.create("Harbour survey")++ workspacemove.start(str(tmp_path / "elsewhere"))+ move = _finish()++ kept = Path(move["kept_aside"])+ assert (kept / "harbour-survey" / "azimut" / "case.json").is_file()++ removed = workspacemove.discard_old()++ assert removed == str(kept)+ assert not kept.exists()+++def test_a_move_does_not_carry_the_tile_cache(workspace, tmp_path):+ """Disposable by contract, and the largest thing nobody would miss."""+ cached = config.tile_cache_dir() / "esri" / "12" / "2048.png"+ cached.parent.mkdir(parents=True, exist_ok=True)+ cached.write_bytes(b"tile")+ target = tmp_path / "elsewhere"++ workspacemove.start(str(target))+ _finish()++ assert config.tile_cache_dir().is_dir()+ assert not (target / ".azimut" / "cache" / "tiles" / "esri" / "12" / "2048.png").exists()+++def test_a_move_does_not_carry_the_lock(workspace, tmp_path):+ """The lock names a process on this machine, so it says nothing true in the+ new folder. It is also the one file that cannot be read while it is held:+ Windows makes the locked range mandatory, and copying it failed the move+ there with "another process has locked a portion of the file"."""+ workspacelock.acquire(8477)+ target = tmp_path / "elsewhere"+ carried = [path.name for path in workspacemove._copyable_files(workspace)]++ workspacemove.start(str(target))+ move = _finish()++ assert workspacelock.LOCK_NAME not in carried+ # The destination holds a lock of its own afterwards, taken when the new+ # location was opened. What must not happen is the copy, which is why the+ # move completing at all is half of what this asserts.+ assert not move["error"], move["error"]+++def test_a_move_carries_settings_keys_and_presets(workspace, tmp_path):+ config.update_settings(lambda s: s["api_keys"].update({"mapbox": "pk.secret"}))+ config.save_templates({"schema": 1, "proof": [], "post": []})++ workspacemove.start(str(tmp_path / "elsewhere"))+ _finish()++ assert config.load_settings()["api_keys"]["mapbox"] == "pk.secret"+ assert config.templates_path().is_file()+++def test_a_move_carries_the_empty_directories_a_case_is_born_with(workspace, tmp_path):+ """`exports/` and the two `.meta/` folders hold nothing until they do.+ Recreating only the parents of files would return a moved case to a shape it+ was never in, and the birth-state gate counts every one of them."""+ from azimut import layout++ case = Case.create("Harbour survey")+ born = sorted(+ directory.relative_to(case.path)+ for directory in layout.content_dirs(case.path)+ if not any(directory.iterdir())+ )+ assert born, "this test needs at least one directory that starts empty"+ target = tmp_path / "elsewhere"++ workspacemove.start(str(target))+ _finish()++ moved = target / "harbour-survey"+ assert sorted(d for d in born if (moved / d).is_dir()) == born+ assert (target / ".azimut" / "bundles").is_dir()+++def test_a_move_carries_scratch_cases(workspace, tmp_path):+ Case.create("One shot", scratch=True)++ workspacemove.start(str(tmp_path / "elsewhere"))+ _finish()++ assert len(list(config.scratch_dir().iterdir())) == 1+++def test_a_move_onto_an_existing_workspace_is_refused(workspace, tmp_path):+ other = tmp_path / "other"+ other.mkdir()+ (other / ".azimut").mkdir()++ with pytest.raises(MoveError, match="use it as it is"):+ workspacemove.start(str(other))+++def test_a_second_move_is_refused_while_one_runs(workspace, tmp_path, monkeypatch):+ started = {"copying": False}+ real_copy = workspacemove._step_copy++ def slow_copy(move, staging):+ started["copying"] = True+ time.sleep(0.3)+ real_copy(move, staging)++ monkeypatch.setattr(workspacemove, "_step_copy", slow_copy)+ workspacemove.start(str(tmp_path / "first"))+ # Bounded, like `_finish`: a move that never reaches the copy step must fail+ # this test rather than hang the run.+ deadline = time.monotonic() + 20+ while not started["copying"]:+ assert time.monotonic() < deadline, "the move never reached the copy step"+ time.sleep(0.01)++ assert workspacemove.in_progress()+ with pytest.raises(MoveError, match="already running"):+ workspacemove.start(str(tmp_path / "second"))++ _finish()+++def test_there_is_nothing_to_discard_before_a_move(workspace):+ with pytest.raises(MoveError):+ workspacemove.discard_old()+++# -- killed part way through ---------------------------------------------------+#+# The steps are driven by hand here rather than through the worker thread, so a+# "kill" is the real thing: execution stops and nothing unwinds. What is+# asserted after each one is the same sentence in every case — restart Azimut+# and the case is still there, opened from a complete workspace.+++def _drive(move, staging, workqueue, upto: int) -> None:+ steps = (+ lambda: workspacemove._step_settle(move, workqueue),+ lambda: workspacemove._step_copy(move, staging),+ lambda: workspacemove._step_verify(move, staging),+ lambda: workspacemove._step_switch(move, staging),+ lambda: workspacemove._step_open(move),+ lambda: workspacemove._step_tidy(move),+ )+ for step in steps[:upto]:+ step()++[email protected]("killed_after", range(7))+def test_a_kill_at_any_step_leaves_a_complete_workspace(workspace, tmp_path, killed_after):+ from azimut.engine import workqueue++ case = Case.create("Harbour survey")+ (case.path / "analyst-notes.txt").write_text("mine", encoding="utf-8")+ target = tmp_path / "elsewhere" / "Azimut"+ move = workspacemove.Move(source=workspace, root=target)+ staging = target.parent / f"{target.name}{workspacemove.STAGING_SUFFIX}"++ resume = workqueue.start_workers+ try:+ _drive(move, staging, workqueue, killed_after)+ finally:+ workqueue.start_workers = resume++ # Restart: the pointer is the only thing that survives the process.+ config.forget_workspace_root()+ root = config.workspace_root()++ assert root.is_dir(), "startup would have nothing to open"+ assert [row["name"] for row in Case.list_all()] == ["Harbour survey"]+ notes = root / "harbour-survey" / "analyst-notes.txt"+ assert notes.read_text(encoding="utf-8") == "mine"+ assert config.settings_path().is_file()++[email protected]("killed_after", range(4))+def test_nothing_is_removed_before_the_copy_is_verified(workspace, tmp_path, killed_after):+ """Steps 1 to 3 must leave the source untouched: until verification passes,+ it is still the only complete workspace."""+ from azimut.engine import workqueue++ Case.create("Harbour survey")+ target = tmp_path / "elsewhere" / "Azimut"+ move = workspacemove.Move(source=workspace, root=target)+ staging = target.parent / f"{target.name}{workspacemove.STAGING_SUFFIX}"++ resume = workqueue.start_workers+ try:+ _drive(move, staging, workqueue, killed_after)+ finally:+ workqueue.start_workers = resume++ assert (workspace / "harbour-survey" / "azimut" / "case.json").is_file()+ assert config.read_pointer() == workspace+++def test_a_half_copy_left_by_a_kill_is_named_before_the_next_attempt(workspace, tmp_path):+ """Only a killed process can leave one behind; a move that fails clears it.+ So it is reported rather than silently overwritten — otherwise the analyst+ finds a folder beside theirs that nothing accounts for."""+ target = tmp_path / "elsewhere" / "Azimut"+ staging = target.parent / f"{target.name}{workspacemove.STAGING_SUFFIX}"+ staging.mkdir(parents=True)++ verdict = workspacemove.inspect_target(str(target))++ assert verdict["ok"]+ assert any("interrupted move" in warning for warning in verdict["warnings"])+++def test_a_half_copy_left_by_a_kill_is_discarded_by_the_next_attempt(workspace, tmp_path):+ """A staging directory is incomplete by definition — the pointer only ever+ names a folder that passed verification — so the next attempt starts clean+ rather than trusting bytes nobody vouched for."""+ Case.create("Harbour survey")+ target = tmp_path / "elsewhere" / "Azimut"+ staging = target.parent / f"{target.name}{workspacemove.STAGING_SUFFIX}"+ staging.mkdir(parents=True)+ (staging / "half-written.bin").write_bytes(b"\0" * 16)++ workspacemove.start(str(target))+ move = _finish()++ assert not move["error"]+ assert not (target / "half-written.bin").exists()+ assert (target / "harbour-survey" / "azimut" / "case.json").is_file()+++def test_a_move_interrupted_between_the_rename_and_the_pointer_keeps_both_folders(+ workspace, tmp_path+):+ """The one window where two complete workspaces exist. The old one is still+ authoritative, which is what makes the pointer write the whole switch."""+ from azimut.engine import workqueue++ Case.create("Harbour survey")+ target = tmp_path / "elsewhere" / "Azimut"+ move = workspacemove.Move(source=workspace, root=target)+ staging = target.parent / f"{target.name}{workspacemove.STAGING_SUFFIX}"++ resume = workqueue.start_workers+ try:+ workspacemove._step_settle(move, workqueue)+ workspacemove._step_copy(move, staging)+ workspacemove._step_verify(move, staging)+ staging.rename(target) # the switch, stopped before the pointer write+ finally:+ workqueue.start_workers = resume++ config.forget_workspace_root()++ assert config.workspace_root() == workspace+ assert (workspace / "harbour-survey" / "azimut" / "case.json").is_file()+ assert (target / "harbour-survey" / "azimut" / "case.json").is_file()diff --git a/tests/test_workspace_pointer.py b/tests/test_workspace_pointer.pynew file mode 100644index 0000000..8d349e3--- /dev/null+++ b/tests/test_workspace_pointer.py@@ -0,0 +1,191 @@+"""Where Azimut looks for its workspace, and what happens when it isn't there.++The pointer is the one piece of state that cannot live inside the workspace, so+it is also the only thing that can tell a moved folder from a lost one. These+tests pin the resolution order, the platform locations, and the rule that a+configured folder is never silently recreated.++Every test here runs the same on Windows, macOS and Linux: the platform-specific+paths are exercised by faking ``sys.platform`` rather than by skipping.+"""++from __future__ import annotations++from pathlib import Path++import pytest++from azimut import config++#: Captured at import, before the suite-wide fixture redirects them into+#: temporary directories. The platform test below needs the real pointer+#: location, and the default root is the one literal path this file still has to+#: pin: every other test compares against `config.DEFAULT_ROOT`, which the+#: fixture moves so that no test can open the developer's own workspace.+REAL_POINTER_DIR = config._pointer_dir+REAL_DEFAULT_ROOT = config.DEFAULT_ROOT++[email protected](autouse=True)+def no_environment_override(monkeypatch):+ """These tests are about the pointer, so the env var must be out of the way."""+ monkeypatch.delenv("AZIMUT_HOME", raising=False)+ config.forget_workspace_root()+++def test_the_default_root_is_the_home_folder_azimut_names():+ assert REAL_DEFAULT_ROOT == Path("~/Azimut")+++def test_the_default_root_is_used_when_nothing_says_otherwise():+ assert config.workspace_root() == config.DEFAULT_ROOT.expanduser()+++def test_the_pointer_moves_the_workspace(tmp_path):+ config.write_pointer(tmp_path / "elsewhere")++ assert config.workspace_root() == tmp_path / "elsewhere"+ assert config.internal_dir() == tmp_path / "elsewhere" / ".azimut"+++def test_the_environment_wins_over_the_pointer(monkeypatch, tmp_path):+ """A USB stick or a second profile is an instruction given on every launch;+ it must not need the machine's configuration rewritten to work."""+ config.write_pointer(tmp_path / "pointed")+ monkeypatch.setenv("AZIMUT_HOME", str(tmp_path / "portable"))++ assert config.workspace_root() == tmp_path / "portable"+++def test_clearing_the_pointer_returns_to_the_default_root(tmp_path):+ config.write_pointer(tmp_path / "elsewhere")+ assert config.workspace_root() == tmp_path / "elsewhere"++ config.clear_pointer()++ assert config.workspace_root() == config.DEFAULT_ROOT.expanduser()+++def test_a_lost_pointer_costs_an_address_and_nothing_else(tmp_path):+ """Unreadable, empty and absent are one case on purpose: fall back, don't fail."""+ config.write_pointer(tmp_path / "elsewhere")+ config.pointer_path().write_text(" \n", encoding="utf-8")+ config.forget_workspace_root()++ assert config.workspace_root() == config.DEFAULT_ROOT.expanduser()+++def test_an_unreadable_pointer_falls_back_too():+ """A directory in the pointer's place is the portable way to be unreadable:+ POSIX raises IsADirectoryError, Windows raises PermissionError, and Azimut+ treats both the same as no pointer at all."""+ config.pointer_path().mkdir(parents=True, exist_ok=True)+ config.forget_workspace_root()++ assert config.workspace_root() == config.DEFAULT_ROOT.expanduser()+++def test_the_pointer_is_one_line_of_plain_text(tmp_path):+ """Small enough that a human can read it, and fix it, with any editor."""+ config.write_pointer(tmp_path / "elsewhere")++ written = config.pointer_path().read_text(encoding="utf-8")++ assert written.splitlines() == [str(tmp_path / "elsewhere")]+++def test_writing_the_pointer_replaces_it_atomically(tmp_path):+ config.write_pointer(tmp_path / "first")+ config.write_pointer(tmp_path / "second")++ assert config.read_pointer() == tmp_path / "second"+ leftovers = [p.name for p in config.pointer_path().parent.iterdir() if p.name.endswith(".tmp")]+ assert leftovers == []+++def test_a_home_relative_pointer_is_expanded(tmp_path):+ config.pointer_path().parent.mkdir(parents=True, exist_ok=True)+ config.pointer_path().write_text("~/Somewhere\n", encoding="utf-8")+ config.forget_workspace_root()++ assert config.workspace_root() == Path("~/Somewhere").expanduser()+++# -- the platform locations ---------------------------------------------------+++def test_the_pointer_sits_where_each_platform_keeps_configuration(monkeypatch, tmp_path):+ """One file per platform convention, never beside the program: a frozen+ binary can live somewhere read-only."""+ monkeypatch.setattr(config, "_pointer_dir", REAL_POINTER_DIR)++ monkeypatch.setattr("sys.platform", "win32")+ monkeypatch.setenv("APPDATA", str(tmp_path / "Roaming"))+ assert config.pointer_path() == tmp_path / "Roaming" / "Azimut" / "location"++ monkeypatch.setattr("sys.platform", "darwin")+ assert (+ config.pointer_path()+ == Path("~/Library/Application Support/Azimut").expanduser() / "location"+ )++ monkeypatch.setattr("sys.platform", "linux")+ monkeypatch.setenv("XDG_CONFIG_HOME", str(tmp_path / "xdg"))+ assert config.pointer_path() == tmp_path / "xdg" / "azimut" / "location"+++def test_linux_falls_back_to_dot_config_without_xdg(monkeypatch):+ monkeypatch.setattr(config, "_pointer_dir", REAL_POINTER_DIR)+ monkeypatch.setattr("sys.platform", "linux")+ monkeypatch.delenv("XDG_CONFIG_HOME", raising=False)++ assert config.pointer_path() == Path("~/.config").expanduser() / "azimut" / "location"+++def test_windows_falls_back_to_the_roaming_profile_without_appdata(monkeypatch):+ monkeypatch.setattr(config, "_pointer_dir", REAL_POINTER_DIR)+ monkeypatch.setattr("sys.platform", "win32")+ monkeypatch.delenv("APPDATA", raising=False)++ assert config.pointer_path() == Path("~/AppData/Roaming/Azimut").expanduser() / "location"+++# -- a configured folder that is gone -----------------------------------------+++def test_a_configured_folder_that_is_gone_is_reported_missing(tmp_path):+ """Never silently recreated: that is how someone concludes they lost everything."""+ workspace = tmp_path / "on-a-drive"+ workspace.mkdir()+ config.write_pointer(workspace)+ assert not config.workspace_missing()++ workspace.rmdir()++ assert config.workspace_missing()+++def test_a_first_run_is_not_a_missing_workspace(monkeypatch, tmp_path):+ """No pointer means nobody has configured anything, so there is nothing to lose."""+ assert not config.workspace_missing()++ monkeypatch.setenv("AZIMUT_HOME", str(tmp_path / "brand-new"))++ assert not config.workspace_missing()+++def test_the_environment_settles_it_even_with_a_stale_pointer(monkeypatch, tmp_path):+ """A pointer left by an earlier run names a folder this run never uses. It+ must not be able to stop the app that was told where to look."""+ config.write_pointer(tmp_path / "long-gone")+ monkeypatch.setenv("AZIMUT_HOME", str(tmp_path))++ assert not config.workspace_missing()+++def test_a_file_where_the_workspace_should_be_counts_as_missing(tmp_path):+ target = tmp_path / "not-a-folder"+ target.write_text("", encoding="utf-8")+ config.write_pointer(target)++ assert config.workspace_missing()