The OSINT investigator's workbench. One case, one folder, every tool. Local-first: your media and your investigations never leave your machine.
JavaScript
M6: Portable case bundles and recoverable deletion (#41)
OsintMeThatc08c9bd43d38
diff --git a/README.md b/README.mdindex 7e648da..5591f72 100644--- a/README.md+++ b/README.md@@ -9,7 +9,7 @@ case is a plain folder that can be reopened, archived or shared.*The name is the French word for azimuth, the compass bearing you sight alongto fix a point on the map.*-## v0.2.5: Notebook diagrams and clearer Sentinel imagery+## v0.2.6: Portable cases and recoverable deletion[](https://github.com/OsintMeThat/azimut/releases/download/v0.2.5/azimut-demo-1920x1080.mp4)@@ -33,15 +33,19 @@ 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.-New in v0.2.5:+New in v0.2.6:-- Notebook notes render `mermaid` fences as diagrams, in the preview and in the- PDF. The library loads only when a note holds one, and it draws offline.-- Sentinel-2 imagery shows cloudy passes by default, with a slider to set the- cloud ceiling. The tiles, the date calendar and "most recent" all follow it.-- The logo is redrawn as a north arrow that stays legible at favicon size.-- Thumbnails no longer fail with a path error when several downloads finish at- once on Windows.+- Export a complete case as an integrity-checked bundle, then import it as a+ new case on another machine. Bundles can be protected with a password.+- Delete files, notes, proofs and their dependent records into Trash, then+ restore them or remove them permanently when the work is no longer needed.+- Select several Files entries before deleting them, with one confirmation and+ one restore point for the complete action.+- Enrich imported images and videos locally with readable metadata, GPS+ suggestions and media filters that open stated locations on the map.+- Create and review typed relations from Details or a saved place on the map.+- Keep reusable proof and post presets in Settings backups, and report an issue+ from About with scrubbed diagnostics.## Install & run@@ -198,7 +202,7 @@ wheel + Windows/Linux/macOS binaries, attaches them to a GitHub release, andpublishes to PyPI. **Don't publish by hand.**```bash-git tag v0.2.4 && git push origin v0.2.4+git tag v0.2.6 && git push origin v0.2.6```One-time setup: register the repo as adiff --git a/docs/RELEASE_NOTES.md b/docs/RELEASE_NOTES.mdindex 372fb22..2843b74 100644--- a/docs/RELEASE_NOTES.md+++ b/docs/RELEASE_NOTES.md@@ -1,4 +1,4 @@-# Azimut v0.2.5+# Azimut v0.2.6## OSINT toolkit at a glance@@ -13,7 +13,70 @@- **Publishing:** build annotated Geo Proofs and prepare evidence-linked GeoReports for X, Bluesky or Mastodon without posting automatically.-## What changed in v0.2.5+## What changed in v0.2.6++### Portable case bundles++- **Export a complete case.** The Case switcher now exports a portable+ `.azimut.zip` snapshot containing the case database and its declared files.+ The bundle has a SHA-256 manifest, so import rejects incomplete or modified+ content rather than opening it as a plausible-looking case.+- **Import without overwriting.** Choose a bundle from the Case switcher to+ inspect its name, size, temporary-space requirement and protection state,+ then import it as a new case. Existing cases remain untouched; imported+ entities, links and confirmation state stay intact.+- **Optional password protection.** A password encrypts the complete bundle,+ including filenames. Passwords are not retained by Azimut and cannot be+ recovered. Thumbnails, deleted files and unfinished background jobs stay out+ of bundles.++### Recoverable deletion++- **Trash for case artifacts.** Deleting a note, media item, proof or related+ record now moves its registered files and recovery record to Trash. Restore+ returns the artifact and its surviving links; permanent deletion and Empty+ Trash remain explicit actions.+- **One undo point for multi-select.** Files can delete a selection together,+ with one confirmation, one Trash entry and one restore action for the whole+ operation.+- **Safer interrupted work.** Delete and restore actions record their progress+ before moving data, so opening a case resolves an interrupted action instead+ of leaving a half-deleted artifact behind.++### Reliability++- **Case-aware media refresh.** Thumbnail polling follows pending work after a+ bundle import and reloads previews when switching cases, even where relative+ file paths match.+- **Preserved confirmed locations.** Metadata backfill does not replace a+ location relation the analyst has already confirmed.+- **Predictable map opening.** A saved place without its own recorded zoom now+ keeps the map's normal starting zoom instead of unexpectedly changing it.++### Media evidence and relations++- **Automatic media enrichment.** Image imports read EXIF and a perceptual+ hash locally; video imports read container, stream and tag metadata. Details+ keeps the readable fields together, and media with stated coordinates can be+ filtered and opened on the map.+- **GPS suggestions that respect analyst work.** Parsed coordinates propose a+ linked place for review. A confirmed location always wins over a later+ backfill.+- **Shared relation vocabulary.** Details and saved-place cards can create,+ review, confirm or remove the same typed relations, with a consistent reading+ of each edge.++### Support and continuity++- **Settings backups keep presets.** Exporting and importing Settings now+ carries reusable proof and post presets with the workspace configuration.+- **Report an issue from About.** The form opens a prepared GitHub issue with+ the version, operating system and recent warnings. Workspace paths and account+ details are scrubbed before it leaves the app.+- **A working product tour.** The README walkthrough now renders on GitHub and+ PyPI instead of leaving an empty video element.++## Also in v0.2.5Mostly additions, with two fixes.diff --git a/docs/SPEC.md b/docs/SPEC.mdindex 2dc4810..cd88912 100644--- a/docs/SPEC.md+++ b/docs/SPEC.md@@ -51,13 +51,15 @@ notes/ # filed note bodies (Markdown)media/ # source + captured + extracted media, with metadata + sha256proofs/ # composed proofs: exported PNGs + editable JSON specs# <name>.assets/ holds images pasted into that proof only-exports/ # post drafts, reports, shared bundles+exports/ # post drafts and reportsinspect/ # saved Inspect session specs+.trash/ # recoverable artifact payloads```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.+One-shot work uses the same code path in a promotable scratch case. Exported+case bundles live in the workspace-level `bundles/` directory.## 4. Data model@@ -88,7 +90,7 @@ proof for publication.| ✅ **Media Library** | Imports or downloads case media with metadata, SHA-256, notes, provenance and multi-attachment selection. || ✅ **Inspect** | Reviews images and video, including saved orientation (±90°/±180°), frame selection, adjustments, crops, collages, auto-stitch, ELA hints and sessions. || ✅ **Satellite** | Saves places and attributed map captures with provider, date, rotation, measure and reference tools. |-| ✅ **Saved work navigation** | Groups a case's places, captures and filed screenshots by continent/country/region (labelled in English and the local language) or by My-work folder, searchable in either spelling with previews and shown on the map. |+| ✅ **Saved work navigation** | Groups a case's places, captures and filed screenshots by continent/country/region (labelled in English and the local language) or by My-work folder, searchable in either spelling with previews and shown on the map at its default zoom when none was saved. || ✅ **Geo Proof** | Composes templated grid or free-layout panels with annotations, coloured frames and pasted overlays that stay out of the case, and exports a PNG with an editable spec. || ✅ **Geo Report** | Prepares sourced proof threads and saved drafts without posting automatically. || ✅ **Case sidebar** | Searches and filters the case, manages notes, suggestions, folders, multi-row filing, a details drawer and synchronized artifact deletion. |@@ -110,10 +112,13 @@ 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. |+| ✅ **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. || ✅ **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. |@@ -132,8 +137,6 @@ Each version delivers one complete daily workflow. Firm ideas move here from| Tool | What it does ||------|--------------|-| **Case bundle** | Exports a case to one ZIP (clean SQLite copy, keys excluded) and imports it back. |-| **Trash** | Undoes a delete and holds removed artifacts before they go for good. || **Case Board / Relations** | Browses, creates and merges entities; graph view over the schema filled since v1, on the shipped relation vocabulary. || **Case Sheet** | The same case as a table: a row is an entity, columns are its attributes plus free ones the analyst adds, sorted, filtered and edited in place. Imports a CSV as loose rows that stay out of the graph until promoted, and exports back to CSV or GeoJSON. || **Camera Resection (GCP)** | Marks matching points photo↔map, then solves camera position, viewing azimuth and rough FOV (OpenCV `solvePnP`) and saves the match as evidence. |@@ -263,10 +266,12 @@ stops making sense.- **Dependencies:** ranges in `pyproject.toml`, exact pins in `uv.lock`; yt-dlp+ gallery-dl unbounded on purpose; scraper self-update keeps an old binary useful.- **Storage:** per-case SQLite `case.db` is the authoritative graph (files for- media/notes/proofs; a closed folder is a complete copy); legacy `case.json` cases migrate- on open; case open and lists use bounded, cursor-paged queries; thumbnails and- background work run through a durable, recoverable per-case job queue drained by- one worker. Details in [STORAGE_AND_PERFORMANCE.md](STORAGE_AND_PERFORMANCE.md).+ media/notes/proofs); deleted artifacts wait in `.trash/`, and portable case+ bundles carry a cleaned database plus declared files under a SHA-256 manifest.+ Legacy `case.json` cases migrate on open; case open and lists use bounded,+ cursor-paged queries; thumbnails and background work run through a durable,+ recoverable per-case job queue drained by one worker. Details in+ [STORAGE_AND_PERFORMANCE.md](STORAGE_AND_PERFORMANCE.md).- **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@@ -279,9 +284,13 @@ stops making sense.about that behavior and local Case media avoids it. Notebook diagrams are theone markup DOMPurify does not clear: Mermaid draws its SVG into the previewafter sanitizing, under its own `strict` level, which escapes labels and drops- click handlers. User-initiated imports,- downloads and generated files have no app quota and can fill the workspace- filesystem; disk capacity remains the user's responsibility.+ click handlers. Case imports extract only unique, non-symlink members declared+ by the manifest and matching its SHA-256. Password-protected bundles seal the+ complete ZIP with chunked AES-256-GCM and a scrypt-derived key; filenames stay+ encrypted and the password is never persisted in a job. Import temporarily+ stages a decrypted ZIP inside the incoming case directory. Imports validate+ declared and actual sizes, reserve filesystem headroom and warn above 10 GiB;+ downloads and generated files still have no app quota.## 10. Open questionsdiff --git a/docs/STORAGE_AND_PERFORMANCE.md b/docs/STORAGE_AND_PERFORMANCE.mdindex 71fe317..b615ca6 100644--- a/docs/STORAGE_AND_PERFORMANCE.md+++ b/docs/STORAGE_AND_PERFORMANCE.md@@ -21,6 +21,7 @@ proofs/ # editable proof specs and rendered PNGsexports/ # post drafts and reportsinspect/ # saved Inspect session specssearch/ # saved Grid Search state+.trash/ # deleted artifacts grouped by delete action````case.json` is the discovery manifest: name, creation date, and the storage and@@ -45,11 +46,10 @@ graph.## Source of truth-`case.db` owns the graph. Portability currently means copying the complete case-folder while it is closed; rollback journaling leaves no WAL checkpoint outside-that folder. Media, proofs and note bodies remain inspectable files. A future-case ZIP workflow will package and import this same folder without creating a-second writable copy.+`case.db` owns the graph. A case bundle is the portable snapshot: a cleaned+database plus declared files under a SHA-256 manifest. Rollback journaling leaves+no WAL checkpoint outside the case folder. Media, proofs and note bodies remain+inspectable files.## Ownership rules@@ -67,6 +67,8 @@ carry enough information to detect staleness.| 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 || Thumbnails | `media/.thumbs/` | Cache; safe to remove at any time || Note bodies | `notes.md`, `notes/<id>.md` | Graph keeps only id, title, folder, path |@@ -75,10 +77,10 @@ carry enough information to detect staleness.The same storage layer serves `pip install azimut` and PyInstaller binaries forWindows, macOS and Linux:-- **No runtime dependency was added.** SQLite is the stdlib `sqlite3` module,- already bundled by PyInstaller; the durable queue and thumbnail worker use only- `threading`/`subprocess`/`sqlite3` plus the already-declared Pillow. The three- binaries build unchanged. `tests/test_release_gate.py` guards this.+- **Bundle encryption uses `cryptography`.** Intel macOS resolves the latest+ compatible 48.x universal wheel; other platforms resolve 49.x. Both ranges+ are bounded below the next untested major. SQLite remains the stdlib+ `sqlite3` module.- **Feature availability is per-binary, not per-Python.** `sqlite3` links whateverSQLite the build environment provides, so FTS5, JSON1 and RTree can be presenton the dev machine yet missing from a shipped binary. The store stays on core@@ -109,7 +111,7 @@ review.## Database shape-`case.db` is at SQLite schema 5. The schema counter is independent of the JSON+`case.db` is at SQLite schema 7. The schema counter is independent of the JSON`CASE_SCHEMA`: the manifest's `azimut.storage` field selects the backend, and eachformat counts its own shape upgrades.@@ -141,6 +143,11 @@ format counts its own shape upgrades.`attempts`, `max_attempts`, `payload_json`, `error` and timestamps. See"Thumbnails and background jobs".+`trash`+: One head row per delete action (`id`, time, label, type, item count and byte+ size), a recovery state and a JSON restore recipe. Sidebar listing reads only+ completed groups and never loads the recipe.+`media_items`: Queryable browse metadata mirrored from each media sidecar. It indexes path,kind, folder, display name, size, date, source, imagery mode, the media entity@@ -164,7 +171,8 @@ through `_SQLITE_MIGRATIONS`, each step in its own immediate transaction, re-reathe version inside the transaction so a raced second opener applies nothing; anewer schema is refused rather than mangled. The shipped migrations add theindexed `folder` column (1→2), the `jobs` table (2→3), entity search text and-the media browse index (3→4), then the `has_gps` flag (4→5). The 4→5 backfill+the media browse index (3→4), the `has_gps` flag (4→5), the trash journal+(5→6), then interrupted-operation recovery state (6→7). The 4→5 backfillreads the sidecar JSON already held in each index row, so a case enriched beforethe column existed gains its position filter on open with no file scan.@@ -173,6 +181,46 @@ marker and index rows commit together, so an interrupted backfill retries safelyNormal media creation, edits, thumbnail changes and deletion keep the index insync.+## Trash and artifact ownership++`engine/artifacts.py` is the single declaration of files owned by each entity+type. 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+after restore. Purge removes the journal only after its directory is gone, so a+Windows file lock leaves a retryable group instead of orphaned bytes.++## Case bundles++Exports run as `bundle-export` jobs and write atomically to+`<workspace>/bundles/`, then stream to the browser as an attachment. The first+ZIP member is `bundle-header.json`; the last is `bundle.json`, which lists every+other 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.++Password protection encrypts the complete ZIP in 1 MiB AES-256-GCM chunks. The+key comes from scrypt (`n=2^15`, `r=8`, `p=1`), and only the envelope parameters+remain clear. Passwords live in a process-memory map keyed by job id, never in+the durable payload.++Import pre-flights format and database versions before creating a destination.+The browser file picker uploads to `<workspace>/bundles/.imports/`; rejected and+cancelled 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+member count, and rejects symlinks. It extracts only the manifest allowlist+after each hash matches. There is no small fixed case-size cap: preview and+import 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+swapped by rename for Windows compatibility. Every import creates a new case and+records `origin_case_id` plus `imported_at` in database metadata.+Entities and links keep their original ids, provenance and confirmation status.+Geographic, temporal and full-text projections are deferred until a query needsthem. Each projection requires its own migration and tests.diff --git a/docs/UI.md b/docs/UI.mdindex aeb2b95..ddcef08 100644--- a/docs/UI.md+++ b/docs/UI.md@@ -56,14 +56,18 @@ remembered per workspace for the current session. Reloading restores the defaultstill open. Search matches labels (plus folder and type in a case small enoughto filter in memory), not note contents — the **Files** tab searches those.Browse order is **Suggestions** (tool-proposed entities to confirm or dismiss,- a node only when non-empty), the analyst's nested folders, then the **Unfiled**- inbox. `+ Folder` and `+ Note` sit above them.+ a node only when non-empty), the analyst's nested folders, **Unfiled**, then+ **Trash** when it holds a delete. Trash shows its item count and size; each+ group can be restored or deleted permanently, and the node can be emptied.+ `+ Folder` and `+ Note` sit above the tree.- **Filing** — drag rows onto a folder, or drop them on Unfiled to unfile.Ctrl/cmd-click and shift-click select several rows first, and the drag carriesall of them; folders are targets, never cargo. The tree scrolls itself when thepointer nears an edge mid-drag, since a native drag swallows the wheel.Unfiling does not delete data. The **Files** tab presents the same tree with- tiles, multi-select and context actions.+ tiles, multi-select and context actions. It also exposes Trash with the same+ restore, permanent-delete and empty actions as the sidebar. Delete sends the+ current selection through the standard confirmation.- **Details** — a drawer over the sidebar, closed with the back arrow or Escape,so selecting a row never pushes the case out of view. It edits an artifact'spreview, title, notes, provenance, derivation chain and folder, and provides@@ -71,6 +75,24 @@ remembered per workspace for the current session. Reloading restores the default`EntityDetails.svelte`. Image Details include a closed EXIF section with theparsed capture date, GPS and every readable tag. Video Details use the samepattern for local ffprobe container, stream and tag fields.+- **Delete** — deleting an artifact moves its registered files and cascade into+ Trash and shows an **Undo** toast. The confirmation uses the neutral tone and+ states what can be restored. Red is reserved for deleting a case, purging a+ trash group and emptying Trash.++## Case switcher++The switcher creates, renames, opens and deletes cases. **Export this case**+starts a durable job, then downloads the `.azimut.zip` through the browser.+Optional password protection downloads `.azimut.enc`; the dialog states once+that a lost password cannot be recovered.++**Import case** opens the browser's file picker for `.zip` and `.enc`, uploads+the selected bundle for a pre-flight check, and shows its case name, size,+temporary disk requirement, available space and protection state. Confirmation+always creates a new case, waits for the durable+import job, then opens it. It never replaces or merges an existing case.+Confirmed entities and relations remain confirmed in the imported case.## Relations@@ -98,7 +120,10 @@ current version. A **GPS** toggle beside the type and folder filters narrows thelist to the files whose own metadata states a position, and appears only in a casethat holds some; how many is in its tooltip, not in its label. Those rows carryone pin glyph — coordinates in the tooltip, not in the title — and clicking it-flies the map there.+flies the map there. Thumbnail polling follows all pending case jobs, including+files beyond the loaded page after a case import. Thumbnail failures are scoped+to their case, so switching cases always reloads previews even when relative+paths match. Enrich respects an existing confirmed GPS relation during backfill.## Mapdiff --git a/extension/manifest.json b/extension/manifest.jsonindex 31bd11f..f30fe57 100644--- a/extension/manifest.json+++ b/extension/manifest.json@@ -1,7 +1,7 @@{"manifest_version": 3,"name": "Azimut Capture",- "version": "0.2.5",+ "version": "0.2.6","description": "File into Azimut: screenshot the map you are looking at (coordinates from the URL), or save any other page as a bookmark.","permissions": ["activeTab", "scripting", "storage", "notifications"],"host_permissions": ["http://127.0.0.1/*", "http://localhost/*"],diff --git a/frontend/e2e/app.fixture.js b/frontend/e2e/app.fixture.jsindex d611add..5d407c9 100644--- a/frontend/e2e/app.fixture.js+++ b/frontend/e2e/app.fixture.js@@ -98,6 +98,11 @@ export async function installAppFixture(page, options = {}) {const savedIndexDelays = options.savedIndexDelays ?? {};const proofIndexDelays = options.proofIndexDelays ?? {};const fixtureDrafts = options.drafts ?? {};+ const trashGroups = [...(options.trashGroups ?? [])];+ const trashWrites = [];+ const bundleCalls = [];+ const bundlePreview = options.bundlePreview;+ const bundleJob = options.bundleJob ?? { state: 'ready' };// Relations, keyed by entity id: what the bounded chain endpoint answers for// the row whose relations a surface asked for.const fixtureChains = options.chains ?? {};@@ -138,6 +143,10 @@ export async function installAppFixture(page, options = {}) {if (path === '/api/settings') return json(route, settings);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') {+ bundleCalls.push({ kind: 'inspect' });+ return json(route, bundlePreview ?? { detail: 'No bundle fixture' }, bundlePreview ? 200 : 400);+ }if (path === '/api/cases') {return json(route, fixtureCases.map((item) => ({ entity_count: 1, ...item })));}@@ -162,6 +171,37 @@ export async function installAppFixture(page, options = {}) {if (caseId && path === `/api/cases/${caseId}/catalog/entities`) {return json(route, { items: [], next_cursor: null });}+ if (caseId && path === `/api/cases/${caseId}/trash`) {+ if (request.method() === 'DELETE') {+ trashWrites.push({ kind: 'empty' });+ const purged = trashGroups.length;+ trashGroups.splice(0);+ return json(route, { purged });+ }+ return json(route, {+ groups: trashGroups,+ items: trashGroups.reduce((total, group) => total + group.item_count, 0),+ size_bytes: trashGroups.reduce((total, group) => total + group.size_bytes, 0),+ });+ }+ const trashMatch = caseId && path.match(new RegExp(`^/api/cases/${caseId}/trash/([^/]+)(/restore)?$`));+ if (trashMatch) {+ const groupId = trashMatch[1];+ const index = trashGroups.findIndex((group) => group.id === groupId);+ if (index < 0) return json(route, { detail: 'Trash group not found' }, 404);+ const kind = trashMatch[2] ? 'restore' : 'purge';+ trashWrites.push({ kind, groupId });+ trashGroups.splice(index, 1);+ return json(route, kind === 'restore' ? { status: 'restored' } : { status: 'purged' });+ }+ if (caseId && path === `/api/cases/${caseId}/bundle/export` && request.method() === 'POST') {+ bundleCalls.push({ kind: 'export', body: request.postDataJSON() });+ return json(route, { job_id: 'bundle-job' });+ }+ if (caseId && path === `/api/cases/${caseId}/bundle/jobs/bundle-job`) {+ bundleCalls.push({ kind: 'job' });+ return json(route, bundleJob);+ }if (caseId && path === `/api/cases/${caseId}/search-grids`) return json(route, []);const chainMatch = caseId && path.match(new RegExp(`^/api/cases/${caseId}/entities/(.+)/chain$`));if (chainMatch) {@@ -238,6 +278,8 @@ export async function installAppFixture(page, options = {}) {captures,proofSaves,linkWrites,+ trashWrites,+ bundleCalls,expectNoUnexpectedRequests: () => expect(unexpected).toEqual([]),};}diff --git a/frontend/e2e/bundle-trash.spec.js b/frontend/e2e/bundle-trash.spec.jsnew file mode 100644index 0000000..0054798--- /dev/null+++ b/frontend/e2e/bundle-trash.spec.js@@ -0,0 +1,74 @@+import { test, expect } from '@playwright/test';+import { CASE_ID, installAppFixture } from './app.fixture.js';++test('keeps a failed export visible after its dialog closes', async ({ page }) => {+ const fixture = await installAppFixture(page, {+ bundleJob: { state: 'failed', error: 'Export failed safely' },+ });++ await page.goto('/#files');+ await page.getByTitle('Switch case').click();+ await page.getByRole('button', { name: 'Export this case…' }).click();+ await page.getByRole('button', { name: 'Export', exact: true }).click();++ await expect(page.getByText('Export failed safely', { exact: true })).toBeVisible();+ await expect(page.getByRole('heading', { name: 'Export case' })).toHaveCount(0);+ expect(fixture.bundleCalls.map((call) => call.kind)).toEqual(['export', 'job']);+ fixture.expectNoUnexpectedRequests();+});++test('shows disk capacity before importing a large bundle', async ({ page }) => {+ const fixture = await installAppFixture(page, {+ bundlePreview: {+ upload_id: 'upload-1',+ case_name: 'Large archive',+ total_size: 20 * 1024 ** 3,+ sealed: true,+ estimated_import_bytes: 42 * 1024 ** 3,+ free_space_bytes: 30 * 1024 ** 3,+ space_reserve_bytes: 512 * 1024 ** 2,+ space_ok: false,+ large_bundle: true,+ },+ });++ await page.goto('/#files');+ await page.getByTitle('Switch case').click();+ await page.getByRole('button', { name: 'Import case…' }).click();+ await page.locator('#bundle-import-file').setInputFiles({+ name: 'large.azimut.enc',+ mimeType: 'application/octet-stream',+ buffer: Buffer.from('fixture'),+ });+ await page.getByRole('button', { name: 'Check bundle' }).click();++ await expect(page.getByText('Not enough free space.', { exact: false })).toBeVisible();+ await expect(page.getByRole('button', { name: 'Import', exact: true })).toBeDisabled();+ expect(fixture.bundleCalls.map((call) => call.kind)).toEqual(['inspect']);+ fixture.expectNoUnexpectedRequests();+});++test('restores a trash group with keyboard-reachable actions', async ({ page }) => {+ const fixture = await installAppFixture(page, {+ trashGroups: [{+ id: 'trash-1',+ label: 'Field note',+ type: 'note',+ item_count: 1,+ size_bytes: 256,+ deleted_at: '2026-07-29T20:00:00Z',+ }],+ });++ await page.goto('/#files');+ await page.locator('button.trash-toggle').click();+ const restore = page.getByRole('button', { name: 'Restore Field note' });+ await restore.focus();+ await expect(restore).toBeFocused();+ await restore.press('Enter');++ await expect(page.getByText('Restored “Field note”', { exact: true })).toBeVisible();+ await expect(page.locator('button.trash-toggle')).toHaveCount(0);+ expect(fixture.trashWrites).toEqual([{ kind: 'restore', groupId: 'trash-1' }]);+ fixture.expectNoUnexpectedRequests();+});diff --git a/frontend/e2e/media-case-switch.spec.js b/frontend/e2e/media-case-switch.spec.jsnew file mode 100644index 0000000..927b742--- /dev/null+++ b/frontend/e2e/media-case-switch.spec.js@@ -0,0 +1,100 @@+import { test, expect } from '@playwright/test';+import { CASE_ID, installAppFixture } from './app.fixture.js';++const SECOND_CASE = 'browser-test-b';+const MEDIA_PATH = 'media/shared.jpg';+const THUMB_PATH = 'media/.thumbs/shared.svg';+const THUMB_SVG = `+ <svg xmlns="http://www.w3.org/2000/svg" width="320" height="200">+ <rect width="320" height="200" fill="#4f8f67"/>+ </svg>`;++function mediaPage(title) {+ return {+ items: [{+ path: MEDIA_PATH,+ filename: 'shared.jpg',+ title,+ kind: 'image',+ width: 320,+ height: 200,+ size: 128,+ sha256: '0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef',+ source: { type: 'upload' },+ thumbnail: THUMB_PATH,+ thumb_state: 'ready',+ enrich_state: 'ready',+ folder: '',+ notes: '',+ }],+ next_cursor: null,+ total: 1,+ facets: {+ category_counts: { image: 1, upload: 1 },+ folder_counts: {},+ gps_count: 0,+ thumbnail_pending: 0,+ },+ };+}++test('reloads a same-path thumbnail when switching cases', async ({ page }) => {+ const fixture = await installAppFixture(page, {+ cases: [+ { id: CASE_ID, name: 'Case A', scratch: false, folders: [] },+ { id: SECOND_CASE, name: 'Case B', scratch: false, folders: [] },+ ],+ });++ let releaseFirstThumbnail;+ let firstThumbnailStarted;+ const firstStarted = new Promise((resolve) => (firstThumbnailStarted = resolve));+ let firstThumbnailSettled;+ const firstSettled = new Promise((resolve) => (firstThumbnailSettled = resolve));++ await page.route('**/api/cases/*/media/page*', async (route) => {+ const caseId = new URL(route.request().url()).pathname.split('/')[3];+ const pageBody = mediaPage(caseId === CASE_ID ? 'Case A image' : 'Case B image');+ await route.fulfill({+ contentType: 'application/json',+ body: JSON.stringify(pageBody),+ });+ });+ await page.route('**/files/*/media/.thumbs/shared.svg', async (route) => {+ const caseId = new URL(route.request().url()).pathname.split('/')[2];+ if (caseId === CASE_ID) {+ firstThumbnailStarted();+ await new Promise((resolve) => (releaseFirstThumbnail = resolve));+ try {+ await route.fulfill({ status: 404, body: '' });+ } catch {+ // Changing src may cancel the old request before its delayed response.+ } finally {+ firstThumbnailSettled();+ }+ return;+ }+ await route.fulfill({ contentType: 'image/svg+xml', body: THUMB_SVG });+ });++ await page.goto('/#media');+ await expect(page.getByText('Case A image', { exact: true })).toBeVisible();+ await firstStarted;++ await page.getByTitle('Switch case').click();+ await page.locator('.menu .item').filter({ hasText: 'Case B' }).click();+ await expect(page.getByText('Case B image', { exact: true })).toBeVisible();+ const currentThumb = page.locator('.media-card img');+ await expect(currentThumb).toHaveAttribute(+ 'src',+ `/files/${SECOND_CASE}/${THUMB_PATH}`+ );++ releaseFirstThumbnail();+ await firstSettled;+ await expect(currentThumb).toBeVisible();+ await expect.poll(+ () => currentThumb.evaluate((image) => image.complete && image.naturalWidth > 0)+ ).toBe(true);+ fixture.expectNoUnexpectedRequests();+});diff --git a/frontend/playwright.config.js b/frontend/playwright.config.jsindex ebfc808..56b0c4b 100644--- a/frontend/playwright.config.js+++ b/frontend/playwright.config.js@@ -5,7 +5,10 @@ export default defineConfig({fullyParallel: false,forbidOnly: !!process.env.CI,retries: process.env.CI ? 1 : 0,- workers: process.env.CI ? 1 : undefined,+ // Canvas-heavy browser specs compete for CPU under Playwright's default of+ // one worker per core. Four keeps local runs parallel without turning normal+ // Leaflet/Konva startup into a timeout; CI stays fully deterministic.+ workers: process.env.CI ? 1 : 4,reporter: process.env.CI ? 'github' : 'list',use: {baseURL: 'http://127.0.0.1:18477',diff --git a/frontend/src/components/CaseSidebar.svelte b/frontend/src/components/CaseSidebar.svelteindex 327dda6..a4bda6f 100644--- a/frontend/src/components/CaseSidebar.svelte+++ b/frontend/src/components/CaseSidebar.svelte@@ -17,6 +17,7 @@import { assignFolder as fileEntity, assignFolderBatch } from '../lib/filing.js';import { createNote } from '../lib/notes.js';import { openEntity, openNotebook } from '../lib/navigate.js';+ import { emptyTrash, purgeGroup, readTrash, restoreGroup, undoAction } from '../lib/trash.js';import Icon from './Icon.svelte';import Modal from './Modal.svelte';import ConfirmDialog from './ConfirmDialog.svelte';@@ -76,6 +77,62 @@return loadSection(folderData[path], { status: 'confirmed', folder: path }, { more });}+ // ── the trash node ────────────────────────────────────────────────────────+ // Head rows only: the recipe to undo a delete never leaves the backend, so+ // this stays one indexed query however much is waiting in there.+ const emptyTrashState = () => ({ groups: [], items: 0, size_bytes: 0 });+ let trashData = $state(emptyTrashState());+ let trashOpen = $state(false);++ async function loadTrash(id, mySeq) {+ try {+ const listed = await readTrash(id);+ if (mySeq === seq) trashData = listed;+ } catch {+ if (mySeq === seq) trashData = emptyTrashState();+ }+ }++ async function restoreTrashGroup(group) {+ try {+ await restoreGroup(caseState.current.id, group.id);+ toast(`Restored “${group.label}”`, 'ok', 2200);+ } catch (e) {+ toast(e.message, 'danger');+ }+ }++ function askPurge(group) {+ confirmState = {+ title: 'Delete permanently?',+ message: `“${group.label}” will be gone for good.`,+ detail: 'The files will be deleted from disk.',+ confirmLabel: 'Delete permanently',+ tone: 'danger',+ icon: 'trash',+ action: async () => {+ await purgeGroup(caseState.current.id, group.id);+ await reloadCase();+ },+ };+ }++ function askEmptyTrash() {+ const noun = trashData.items === 1 ? 'item' : 'items';+ confirmState = {+ title: 'Empty the trash?',+ message: `${trashData.items} ${noun} will be gone for good.`,+ detail: 'The files will be deleted from disk.',+ confirmLabel: 'Empty the trash',+ tone: 'danger',+ icon: 'trash',+ action: async () => {+ await emptyTrash(caseState.current.id);+ await reloadCase();+ },+ };+ }+async function loadSummary(id, mySeq) {try {const s = await api.get(`/api/cases/${id}/catalog/summary`);@@ -103,12 +160,15 @@typeFilter = null;suggestedData = emptySection();unfiledData = emptySection();+ trashData = emptyTrashState();+ trashOpen = false;}if (!id) {summary = null;return;}loadSummary(id, seq);+ loadTrash(id, seq);loadSuggested();loadUnfiled();for (const path of Object.keys(expanded)) if (expanded[path]) loadFolder(path);@@ -168,10 +228,13 @@}// Dismiss a suggestion outright (quick triage — no heavy confirmation).+ // It goes through the same delete as everything else, so a dismissal that+ // turns out to have been a good lead comes back from the toast.async function dismissSuggestion(entity) {- await api.del(`/api/cases/${caseState.current.id}/entities/${entity.id}`);+ const caseId = caseState.current.id;+ const result = await api.del(`/api/cases/${caseId}/entities/${entity.id}`);await reloadCase();- toast(`Dismissed "${entity.label}"`, 'info');+ toast(`Dismissed “${entity.label}”`, 'info', 7000, undoAction(caseId, result));}// Clicking a row opens its owning workspace; notes share the Notebook.@@ -526,6 +589,12 @@onconfirm={confirmEntity}ondismiss={dismissSuggestion}ondragactive={onDragActive}+ trash={trashData}+ {trashOpen}+ ontoggletrash={() => (trashOpen = !trashOpen)}+ onrestore={restoreTrashGroup}+ onpurge={askPurge}+ onempty={askEmptyTrash}/>{/if}</div>@@ -562,6 +631,7 @@message={confirmState.message}detail={confirmState.detail}consequences={confirmState.consequences}+ restorable={confirmState.restorable ?? ''}confirmLabel={confirmState.confirmLabel}tone={confirmState.tone}icon={confirmState.icon}diff --git a/frontend/src/components/CaseSidebar.test.js b/frontend/src/components/CaseSidebar.test.jsindex f909b32..861cffc 100644--- a/frontend/src/components/CaseSidebar.test.js+++ b/frontend/src/components/CaseSidebar.test.js@@ -46,12 +46,34 @@ describe('sidebar shell', () => {'typeFilter = null','suggestedData = emptySection()','unfiledData = emptySection()',+ 'trashData = emptyTrashState()',+ 'trashOpen = false',]) {expect(reset).toContain(line);}});});+describe('trash node', () => {+ it('loads bounded head rows on every case refresh', () => {+ expect(shell).toContain('loadTrash(id, seq)');+ expect(shell).toContain('readTrash(id)');+ expect(tree).toContain('{#if trash.groups.length > 0}');+ expect(tree).toContain('{formatSize(trash.size_bytes)}');+ });++ it('offers restore, permanent deletion and emptying', () => {+ expect(tree).toContain('onclick={() => onrestore(group)}');+ expect(tree).toContain('onclick={() => onpurge(group)}');+ expect(tree).toContain('title="Empty the trash"');+ expect(shell).toContain('tone: \'danger\'');+ });++ it('offers undo after dismissing a suggestion', () => {+ expect(shell).toContain('undoAction(caseId, result)');+ });+});+describe('browse vs. results', () => {it('shows the tree until something is filtered, then a flat list', () => {expect(shell).toContain('const filtering = $derived(isFiltering({ query, type: typeFilter }))');diff --git a/frontend/src/components/CaseSwitcher.svelte b/frontend/src/components/CaseSwitcher.svelteindex ddbaccb..37c2da8 100644--- a/frontend/src/components/CaseSwitcher.svelte+++ b/frontend/src/components/CaseSwitcher.svelte@@ -1,4 +1,5 @@<script>+ import { onDestroy } from 'svelte';import {caseState,refreshCaseList,@@ -10,6 +11,15 @@deleteCase,toast,} from '../lib/state.svelte.js';+ import {+ discardBundleUpload,+ downloadBundle as triggerBundleDownload,+ inspectBundle,+ startBundleExport,+ startBundleImport,+ waitForBundle,+ } from '../lib/bundles.js';+ import { formatSize } from '../lib/trash.js';import Icon from './Icon.svelte';import Modal from './Modal.svelte';import SearchInput from './SearchInput.svelte';@@ -20,6 +30,149 @@let nameInput = $state('');let busy = $state(false);let renameId = $state(null); // id of the case being renamed (modal === 'rename')+ let bundleModal = $state(null); // 'export' | 'import' | null+ let bundleFile = $state(null);+ let bundlePassword = $state('');+ let protectBundle = $state(false);+ let bundleBusy = $state(false);+ let bundlePreview = $state(null);+ let bundleError = $state('');+ let bundleJobController = null;++ onDestroy(() => bundleJobController?.abort());++ function openBundle(kind) {+ open = false;+ bundleModal = kind;+ bundleFile = null;+ bundlePassword = '';+ protectBundle = false;+ bundlePreview = null;+ bundleError = '';+ }++ function closeBundle() {+ if (bundleBusy) return;+ if (bundlePreview?.upload_id) {+ void discardBundleUpload(bundlePreview.upload_id);+ }+ bundleModal = null;+ bundleFile = null;+ bundlePreview = null;+ bundleError = '';+ }++ async function exportBundle() {+ const current = caseState.current;+ if (!current || bundleBusy) return;+ bundleBusy = true;+ bundleError = '';+ let started;+ try {+ started = await startBundleExport(+ current.id,+ protectBundle ? bundlePassword : ''+ );+ } catch (error) {+ bundleError = error.message;+ bundleBusy = false;+ return;+ }+ bundleModal = null;+ bundlePassword = '';+ protectBundle = false;+ toast('Export started', 'info', 1800);+ bundleJobController?.abort();+ bundleJobController = new AbortController();+ try {+ const job = await waitForBundle(current.id, started.job_id, {+ signal: bundleJobController.signal,+ });+ if (job.state === 'ready') {+ triggerBundleDownload(current.id, started.job_id);+ toast('Download started', 'ok', 4000);+ } else {+ toast(job.error || 'Could not export the case', 'danger', 7000);+ }+ } catch (error) {+ if (error.name !== 'AbortError') {+ toast(error.message || 'Could not export the case', 'danger', 7000);+ }+ } finally {+ bundleJobController = null;+ bundleBusy = false;+ }+ }++ function chooseBundle(event) {+ if (bundlePreview?.upload_id) {+ void discardBundleUpload(bundlePreview.upload_id);+ }+ bundleFile = event.currentTarget.files?.[0] ?? null;+ bundlePreview = null;+ bundleError = '';+ }++ function resetBundlePreview() {+ if (bundlePreview?.upload_id) {+ void discardBundleUpload(bundlePreview.upload_id);+ }+ bundlePreview = null;+ }++ async function checkBundle() {+ if (!bundleFile || bundleBusy) return;+ bundleBusy = true;+ bundleError = '';+ try {+ bundlePreview = await inspectBundle(bundleFile, bundlePassword);+ } catch (error) {+ bundlePreview = null;+ bundleError = error.message;+ } finally {+ bundleBusy = false;+ }+ }++ async function importBundle() {+ if (!bundlePreview || bundleBusy) return;+ bundleBusy = true;+ bundleError = '';+ let started;+ try {+ started = await startBundleImport(bundlePreview.upload_id, bundlePassword);+ } catch (error) {+ bundleError = error.message;+ bundleBusy = false;+ return;+ }+ bundleModal = null;+ bundleFile = null;+ bundlePassword = '';+ bundlePreview = null;+ toast('Import started', 'info', 1800);+ bundleJobController?.abort();+ bundleJobController = new AbortController();+ try {+ const job = await waitForBundle(started.case_id, started.job_id, {+ signal: bundleJobController.signal,+ });+ if (job.state !== 'ready') {+ toast(job.error || 'Could not import the case', 'danger', 7000);+ return;+ }+ await refreshCaseList();+ await openCase(started.case_id);+ toast(`Imported “${started.name}”`, 'ok', 4000);+ } catch (error) {+ if (error.name !== 'AbortError') {+ toast(error.message || 'Could not import the case', 'danger', 7000);+ }+ } finally {+ bundleJobController = null;+ bundleBusy = false;+ }+ }function askRename(c) {open = false;@@ -163,7 +316,13 @@><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>@@ -255,6 +414,106 @@</Modal>{/if}+{#if bundleModal === 'export'}+ <Modal title="Export case" onclose={closeBundle}>+ <p class="bundle-note">+ Includes the case and its files. Trash and thumbnails stay on this device.+ </p>+ <label class="check-row">+ <input type="checkbox" bind:checked={protectBundle} />+ Protect with a password+ </label>+ {#if protectBundle}+ <label class="label" for="bundle-export-password">Password</label>+ <input+ id="bundle-export-password"+ class="input"+ type="password"+ bind:value={bundlePassword}+ autocomplete="new-password"+ />+ <p class="bundle-note">A lost password cannot be recovered.</p>+ {/if}+ {#if bundleError}<p class="err">{bundleError}</p>{/if}+ <div class="actions">+ <button type="button" class="btn" onclick={closeBundle} disabled={bundleBusy}>Cancel</button>+ <button+ type="button"+ class="btn btn-primary"+ onclick={exportBundle}+ disabled={bundleBusy || (protectBundle && !bundlePassword)}+ >+ {bundleBusy ? 'Starting…' : 'Export'}+ </button>+ </div>+ </Modal>+{/if}++{#if bundleModal === 'import'}+ <Modal title="Import case" onclose={closeBundle}>+ <label class="label" for="bundle-import-file">Case bundle</label>+ <input+ id="bundle-import-file"+ class="input"+ type="file"+ accept=".zip,.enc"+ onchange={chooseBundle}+ />+ <label class="label" for="bundle-import-password">Password (if protected)</label>+ <input+ id="bundle-import-password"+ class="input"+ type="password"+ bind:value={bundlePassword}+ oninput={resetBundlePreview}+ autocomplete="current-password"+ />+ {#if bundlePreview}+ <div class="bundle-preview">+ <strong>{bundlePreview.case_name}</strong>+ <span>{formatSize(bundlePreview.total_size)}</span>+ <span>{bundlePreview.sealed ? 'Password protected' : 'No password'}</span>+ <p>Imports as a new case.</p>+ {#if !bundlePreview.space_ok}+ <p class="bundle-space danger">+ Not enough free space. This import needs about+ {formatSize(bundlePreview.estimated_import_bytes)} plus a safety reserve;+ {formatSize(bundlePreview.free_space_bytes)} is available.+ </p>+ {:else if bundlePreview.large_bundle}+ <p class="bundle-space warn">+ Large import: about {formatSize(bundlePreview.estimated_import_bytes)} of+ temporary space, with {formatSize(bundlePreview.free_space_bytes)} available.+ </p>+ {/if}+ </div>+ {/if}+ {#if bundleError}<p class="err">{bundleError}</p>{/if}+ <div class="actions">+ <button type="button" class="btn" onclick={closeBundle} disabled={bundleBusy}>Cancel</button>+ {#if bundlePreview}+ <button+ type="button"+ class="btn btn-primary"+ onclick={importBundle}+ disabled={bundleBusy || !bundlePreview.space_ok}+ >+ {bundleBusy ? 'Starting…' : 'Import'}+ </button>+ {:else}+ <button+ type="button"+ class="btn btn-primary"+ onclick={checkBundle}+ disabled={bundleBusy || !bundleFile}+ >+ {bundleBusy ? 'Checking…' : 'Check bundle'}+ </button>+ {/if}+ </div>+ </Modal>+{/if}+{#if delTarget}<Modal title="Delete case" onclose={() => (delTarget = null)}><div class="warn">@@ -465,6 +724,39 @@color: var(--danger, #e5484d);margin-top: 8px;}+ .bundle-note {+ margin: 0 0 12px;+ color: var(--text-3);+ font-size: var(--fs-xs);+ line-height: 1.45;+ }+ .check-row {+ display: flex;+ align-items: center;+ gap: 8px;+ margin: 10px 0 12px;+ color: var(--text-2);+ font-size: var(--fs-sm);+ }+ .bundle-preview {+ display: grid;+ grid-template-columns: 1fr auto;+ gap: 5px 12px;+ margin-top: 14px;+ padding: 10px 12px;+ border: 1px solid var(--border);+ border-radius: var(--r-sm);+ color: var(--text-2);+ font-size: var(--fs-xs);+ }+ .bundle-preview strong { color: var(--text-1); }+ .bundle-preview p { grid-column: 1 / -1; margin: 4px 0 0; color: var(--text-3); }+ .bundle-preview .bundle-space {+ padding-top: 6px;+ border-top: 1px solid var(--border);+ }+ .bundle-preview .bundle-space.warn { color: var(--warn); }+ .bundle-preview .bundle-space.danger { color: var(--danger); }.actions {display: flex;justify-content: flex-end;diff --git a/frontend/src/components/CaseSwitcher.test.js b/frontend/src/components/CaseSwitcher.test.jsindex b8c4199..3b9ad86 100644--- a/frontend/src/components/CaseSwitcher.test.js+++ b/frontend/src/components/CaseSwitcher.test.js@@ -28,6 +28,39 @@ describe('CaseSwitcher search', () => {});});+describe('Case bundles', () => {+ it('offers import globally and export for the open case', () => {+ expect(source).toContain("openBundle('import')");+ expect(source).toContain('Import case…');+ expect(source).toContain("openBundle('export')");+ expect(source).toContain('Export this case…');+ });++ it('pre-flights an import before it creates the new case', () => {+ expect(source).toContain('type="file"');+ expect(source).toContain('accept=".zip,.enc"');+ expect(source).toContain('bundlePreview = await inspectBundle(bundleFile');+ expect(source).toContain('{#if bundlePreview}');+ expect(source).toContain('Imports as a new case.');+ expect(source).toContain('disabled={bundleBusy || !bundlePreview.space_ok}');+ });++ it('keeps password protection optional and states the recovery limit once', () => {+ expect(source).toContain('bind:checked={protectBundle}');+ expect(source).toContain('protectBundle ? bundlePassword');+ expect(source).toContain('A lost password cannot be recovered.');+ });++ it('waits for durable export and import jobs', () => {+ expect(source).toContain('waitForBundle(current.id, started.job_id, {');+ expect(source).toContain('waitForBundle(started.case_id, started.job_id, {');+ expect(source).toContain('signal: bundleJobController.signal');+ expect(source).toContain('triggerBundleDownload(current.id, started.job_id)');+ expect(source).toContain("toast(error.message || 'Could not export the case'");+ expect(source).toContain("toast(error.message || 'Could not import the case'");+ });+});+describe('refreshCaseList', () => {it('passes a name query through to the API, or omits it when empty', async () => {vi.resetModules();diff --git a/frontend/src/components/ConfirmDialog.svelte b/frontend/src/components/ConfirmDialog.svelteindex d1a982a..673ad18 100644--- a/frontend/src/components/ConfirmDialog.svelte+++ b/frontend/src/components/ConfirmDialog.svelte@@ -3,19 +3,22 @@import { portal } from '../lib/fullscreen.js';// A small, styled confirmation dialog — replaces the browser confirm() popup.- // Tone drives the accent so a destructive action reads differently from a- // reversible one.- // tone: 'danger' → deletes everywhere (irreversible, drops files)- // tone: 'default' → reversible (unfile, remove a folder)- // `consequences` spells out what else a delete touches, so an irreversible- // click is never a guess: what goes with it, and what stays behind scarred.- // The two lists carry their own tone — "kept" must not read as a warning.+ // Tone drives the accent so an irreversible action reads differently from one+ // that can be taken back.+ // tone: 'danger' → nothing comes back (purge, empty the trash, delete a case)+ // tone: 'default' → reversible (delete an artifact, unfile, remove a folder)+ // Deleting an artifact left this tone when the trash arrived: it still drops+ // files, but the case holds them until someone empties it.+ // `consequences` spells out what else a delete touches, so the click is never+ // a guess: what goes with it, what stays behind scarred, and what can be+ // brought back.// { cascade: [{ label }], tombstone: [{ label }] }let {title,message,detail = '',consequences = null,+ restorable = '',confirmLabel = 'Confirm',tone = 'default', // 'danger' | 'default'icon = tone === 'danger' ? 'trash' : 'folderMinus',@@ -77,6 +80,14 @@</ul></div>{/if}+ {#if restorable}+ <div class="conseq restorable">+ <div class="conseq-h">+ <Icon name="undo" size={12} />+ <span>{restorable}</span>+ </div>+ </div>+ {/if}<div class="actions"><button class="btn" onclick={oncancel} disabled={busy}>Cancel</button><button@@ -168,6 +179,8 @@.conseq.danger {background: color-mix(in srgb, var(--danger, #e5484d) 9%, transparent);}+ /* what can be brought back reads as reassurance, not as a warning */+ .conseq.restorable .conseq-h { color: var(--text-2); }.conseq-h {display: flex;align-items: center;diff --git a/frontend/src/components/ConfirmDialog.test.js b/frontend/src/components/ConfirmDialog.test.jsnew file mode 100644index 0000000..6e50c55--- /dev/null+++ b/frontend/src/components/ConfirmDialog.test.js@@ -0,0 +1,18 @@+import { describe, expect, it } from 'vitest';+import { readFileSync } from 'node:fs';++const source = readFileSync(new URL('./ConfirmDialog.svelte', import.meta.url), 'utf8');++describe('confirmation register', () => {+ it('shows the recoverable consequence separately from losses and scars', () => {+ expect(source).toContain("restorable = ''");+ expect(source).toContain('{#if restorable}');+ expect(source).toContain('class="conseq restorable"');+ expect(source).toContain('<Icon name="undo"');+ });++ it('reserves danger for actions that cannot be restored', () => {+ expect(source).toContain("tone: 'danger' → nothing comes back");+ expect(source).toContain("tone: 'default' → reversible");+ });+});diff --git a/frontend/src/components/EntityDetails.svelte b/frontend/src/components/EntityDetails.svelteindex 35c5b9d..de8115e 100644--- a/frontend/src/components/EntityDetails.svelte+++ b/frontend/src/components/EntityDetails.svelte@@ -18,6 +18,7 @@import { loadRelationTypes, relatableTypes, saveRelation } from '../lib/relations.svelte.js';import { openEntity, gotoCapture, ENTITY_TOOL } from '../lib/navigate.js';import { pollWhile } from '../lib/poll.js';+ import { deletedToast, RESTORABLE } from '../lib/trash.js';import Icon from './Icon.svelte';import ConfirmDialog from './ConfirmDialog.svelte';import FolderSelect from './FolderSelect.svelte';@@ -206,7 +207,7 @@}}- // ── delete everywhere (irreversible; spells out what it touches) ───────────+ // ── delete everywhere (recoverable from the case trash) ───────────────────let confirmState = $state(null);let confirmBusy = $state(false);@@ -227,13 +228,15 @@title: 'Delete everywhere?',message: `“${e.label}” will be removed from the case and its tool.`,detail: FILE_BACKED.has(e.type)- ? 'Deletes the underlying files from disk and cannot be undone.'- : 'Removes it from the case and cannot be undone.',+ ? 'Moves the item and its files to the case trash.'+ : 'Moves the item to the case trash.',consequences,+ restorable: RESTORABLE,action: async () => {- await api.del(`/api/cases/${caseState.current.id}/entities/${e.id}`);+ const caseId = caseState.current.id;+ const result = await api.del(`/api/cases/${caseId}/entities/${e.id}`);await reloadCase();- toast(`Deleted "${e.label}"`, 'info');+ deletedToast(caseId, result, e.label);ondeleted?.();},};@@ -507,8 +510,9 @@message={confirmState.message}detail={confirmState.detail}consequences={confirmState.consequences}+ restorable={confirmState.restorable}confirmLabel="Delete everywhere"- tone="danger"+ tone="default"icon="trash"busy={confirmBusy}onconfirm={runConfirm}diff --git a/frontend/src/components/sidebar/SidebarTree.svelte b/frontend/src/components/sidebar/SidebarTree.svelteindex 7f24207..2b09f85 100644--- a/frontend/src/components/sidebar/SidebarTree.svelte+++ b/frontend/src/components/sidebar/SidebarTree.svelte@@ -3,6 +3,7 @@// foldable row. Suggestions is a node here, not a section above the tree, so// nothing below it shifts when its count crosses zero.import { subtreeCountFrom } from '../../lib/folderTree.js';+ import { formatSize } from '../../lib/trash.js';import { dragPayload, rangeSelected, toggleSelected } from '../../lib/rowSelect.js';import Icon from '../Icon.svelte';import EntityRow from './EntityRow.svelte';@@ -33,6 +34,12 @@onconfirm = () => {},ondismiss = () => {},ondragactive = () => {},+ trash = { groups: [], items: 0, size_bytes: 0 },+ trashOpen = false,+ ontoggletrash = () => {},+ onrestore = () => {},+ onpurge = () => {},+ onempty = () => {},} = $props();let addingUnder = $state(undefined); // folder path currently gaining a child@@ -196,7 +203,63 @@{/if}{/if}- {#if tree.length === 0 && unfiled.items.length === 0 && suggestedCount === 0}+ <!-- Deleted work waits here until it is restored or the trash is emptied.+ Rendered only when it holds something, so an untouched case shows nothing+ about deletion. -->+ {#if trash.groups.length > 0}+ <div class="trash-head">+ <button+ class="frow trash-toggle"+ type="button"+ onclick={ontoggletrash}+ aria-expanded={trashOpen}+ >+ <Icon name={trashOpen ? 'chevronDown' : 'chevronRight'} size={12} />+ <Icon name="trash" size={13} />+ <span class="fname">Trash</span>+ <span class="fcount">{trash.items} · {formatSize(trash.size_bytes)}</span>+ </button>+ <button+ class="fact fdel trash-empty"+ type="button"+ title="Empty the trash"+ aria-label="Empty the trash"+ onclick={onempty}+ >+ <Icon name="trash" size={12} />+ </button>+ </div>+ {#if trashOpen}+ {#each trash.groups as group (group.id)}+ <div class="trow">+ <span class="tname" title={group.label}>{group.label}</span>+ {#if group.item_count > 1}+ <span class="tcount">+{group.item_count - 1}</span>+ {/if}+ <button+ class="tact"+ type="button"+ title="Restore"+ aria-label={`Restore ${group.label}`}+ onclick={() => onrestore(group)}+ >+ <Icon name="undo" size={12} />+ </button>+ <button+ class="tact tdel"+ type="button"+ title="Delete permanently"+ aria-label={`Delete ${group.label} permanently`}+ onclick={() => onpurge(group)}+ >+ <Icon name="trash" size={12} />+ </button>+ </div>+ {/each}+ {/if}+ {/if}++ {#if tree.length === 0 && unfiled.items.length === 0 && suggestedCount === 0 && trash.groups.length === 0}<div class="none">Everything you save lands here; create folders to organize it.</div>{/if}</div>@@ -316,6 +379,12 @@.fact:hover { color: var(--text-1); }.fdel:hover { color: var(--danger, #e55); }.frow:hover .fact { opacity: 1; }+ .trash-head { display: flex; align-items: center; position: relative; }+ .trash-toggle { padding-right: 34px; }+ .trash-empty { position: absolute; right: 12px; }+ .trash-head:hover .trash-empty,+ .trash-head:focus-within .trash-empty,+ .trash-empty:focus-visible { opacity: 1; }.new-folder { display: flex; gap: 6px; padding: 2px 8px 4px; }.new-folder .input { flex: 1; font-size: var(--fs-xs); }.more {@@ -333,4 +402,22 @@.more:hover { color: var(--text-1); border-color: var(--border-strong); }.more:disabled { opacity: 0.5; cursor: default; }.none { font-size: var(--fs-xs); color: var(--text-3); padding: 4px 8px 12px; line-height: 1.45; }+ .trow {+ display: flex;+ align-items: center;+ gap: 6px;+ padding: 5px 8px 5px 30px;+ border-radius: var(--r-sm);+ color: var(--text-3);+ font-size: var(--fs-xs);+ }+ .trow:hover { background: var(--bg-2); }+ .tname { flex: 1; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }+ .tcount { font-weight: 600; }+ .tact { opacity: 0; color: var(--text-3); display: flex; padding: 2px; border-radius: 4px; cursor: pointer; }+ .trow:hover .tact,+ .trow:focus-within .tact,+ .tact:focus-visible { opacity: 1; }+ .tact:hover { color: var(--text-1); }+ .tdel:hover { color: var(--danger, #e55); }</style>diff --git a/frontend/src/lib/bundles.js b/frontend/src/lib/bundles.jsnew file mode 100644index 0000000..1e86213--- /dev/null+++ b/frontend/src/lib/bundles.js@@ -0,0 +1,86 @@+import { api } from './api.js';++export function inspectBundle(file, password = '') {+ const body = new FormData();+ body.append('file', file);+ if (password) body.append('password', password);+ return api.post('/api/cases/bundles/inspect', body);+}++export function startBundleImport(uploadId, password = '') {+ return api.post('/api/cases/bundles/import', {+ upload_id: uploadId,+ password: password || null,+ });+}++export function discardBundleUpload(uploadId) {+ if (!uploadId) return Promise.resolve();+ return api.del(`/api/cases/bundles/uploads/${uploadId}`);+}++export function startBundleExport(caseId, password = '') {+ return api.post(`/api/cases/${caseId}/bundle/export`, {+ password: password || null,+ });+}++export function readBundleJob(caseId, jobId) {+ return api.get(`/api/cases/${caseId}/bundle/jobs/${jobId}`);+}++export function bundleDownloadUrl(caseId, jobId) {+ return `/api/cases/${encodeURIComponent(caseId)}/bundle/jobs/${encodeURIComponent(jobId)}/download`;+}++export function downloadBundle(caseId, jobId) {+ const link = document.createElement('a');+ link.href = bundleDownloadUrl(caseId, jobId);+ link.download = '';+ document.body.append(link);+ link.click();+ link.remove();+}++function aborted() {+ const error = new Error('Bundle job cancelled');+ error.name = 'AbortError';+ return error;+}++function wait(delay, signal) {+ if (signal?.aborted) return Promise.reject(aborted());+ return new Promise((resolve, reject) => {+ const finish = () => {+ signal?.removeEventListener('abort', onAbort);+ resolve();+ };+ const onAbort = () => {+ clearTimeout(timer);+ signal?.removeEventListener('abort', onAbort);+ reject(aborted());+ };+ const timer = setTimeout(finish, delay);+ signal?.addEventListener('abort', onAbort, { once: true });+ });+}++export async function waitForBundle(caseId, jobId, options = {}) {+ const config = typeof options === 'number' ? { pause: options } : options;+ const {+ pause = 500,+ maxPause = 5000,+ timeout = 24 * 60 * 60 * 1000,+ signal,+ } = config;+ const deadline = Date.now() + timeout;+ let delay = pause;+ while (true) {+ if (signal?.aborted) throw aborted();+ if (Date.now() >= deadline) throw new Error('Bundle job timed out');+ const job = await readBundleJob(caseId, jobId);+ if (['ready', 'failed', 'cancelled'].includes(job.state)) return job;+ await wait(delay, signal);+ delay = Math.min(maxPause, Math.max(pause, Math.round(delay * 1.5)));+ }+}diff --git a/frontend/src/lib/bundles.test.js b/frontend/src/lib/bundles.test.jsnew file mode 100644index 0000000..04d89d8--- /dev/null+++ b/frontend/src/lib/bundles.test.js@@ -0,0 +1,85 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';+import { api } from './api.js';+import {+ bundleDownloadUrl,+ discardBundleUpload,+ inspectBundle,+ readBundleJob,+ startBundleExport,+ startBundleImport,+ waitForBundle,+} from './bundles.js';++vi.mock('./api.js', () => ({+ api: {+ del: vi.fn(),+ get: vi.fn(),+ post: vi.fn(),+ },+}));++beforeEach(() => {+ vi.clearAllMocks();+});++it('uploads the selected file and keeps passwords out of URLs', async () => {+ const file = new Blob(['bundle']);+ await inspectBundle(file, 'secret');+ await startBundleImport('a'.repeat(32), 'secret');+ await startBundleExport('case-1', 'secret');++ const inspectBody = api.post.mock.calls[0][1];+ expect(api.post.mock.calls[0][0]).toBe('/api/cases/bundles/inspect');+ expect(inspectBody).toBeInstanceOf(FormData);+ expect(inspectBody.get('file')).toBeInstanceOf(Blob);+ expect(inspectBody.get('file').size).toBe(file.size);+ expect(inspectBody.get('password')).toBe('secret');+ expect(api.post).toHaveBeenNthCalledWith(2, '/api/cases/bundles/import', {+ upload_id: 'a'.repeat(32),+ password: 'secret',+ });+ expect(api.post).toHaveBeenNthCalledWith(3, '/api/cases/case-1/bundle/export', {+ password: 'secret',+ });+});++it('builds a same-origin download and can discard an unused upload', async () => {+ expect(bundleDownloadUrl('case one', 'job/two')).toBe(+ '/api/cases/case%20one/bundle/jobs/job%2Ftwo/download'+ );+ await discardBundleUpload('a'.repeat(32));+ expect(api.del).toHaveBeenCalledWith(`/api/cases/bundles/uploads/${'a'.repeat(32)}`);+});++it('polls the destination case until the durable job settles', async () => {+ api.get+ .mockResolvedValueOnce({ state: 'running' })+ .mockResolvedValueOnce({ state: 'ready' });++ await expect(waitForBundle('case-1', 'job-1', 0)).resolves.toEqual({ state: 'ready' });+ expect(readBundleJob).toBeTypeOf('function');+ expect(api.get).toHaveBeenCalledTimes(2);+ expect(api.get).toHaveBeenLastCalledWith('/api/cases/case-1/bundle/jobs/job-1');+});++it('can stop polling when its component goes away', async () => {+ const controller = new AbortController();+ api.get.mockResolvedValue({ state: 'running' });++ const waiting = waitForBundle('case-1', 'job-1', {+ pause: 10_000,+ signal: controller.signal,+ });+ await Promise.resolve();+ controller.abort();++ await expect(waiting).rejects.toMatchObject({ name: 'AbortError' });+});++it('bounds a job that never settles', async () => {+ api.get.mockResolvedValue({ state: 'running' });++ await expect(+ waitForBundle('case-1', 'job-1', { pause: 0, maxPause: 0, timeout: 0 })+ ).rejects.toThrow('timed out');+});diff --git a/frontend/src/lib/navigate.js b/frontend/src/lib/navigate.jsindex d9ae52a..68fa484 100644--- a/frontend/src/lib/navigate.js+++ b/frontend/src/lib/navigate.js@@ -6,6 +6,17 @@*/import { uiState } from './state.svelte.js';+/**+ * A number an entity actually recorded, or NaN when it recorded nothing.+ *+ * `Number(null)` is 0, and a zoom of 0 is the whole globe — so a place minted+ * from a photo's EXIF (which knows coordinates but no zoom) would fly the map+ * all the way out instead of falling back to the Satellite tool's own default.+ */+function recorded(value) {+ return value === null || value === undefined || value === '' ? NaN : Number(value);+}+/** Tool a given entity type opens in (also gates the "Open in tool" button). */export const ENTITY_TOOL = {media: 'media',@@ -50,8 +61,8 @@ export function openEntity(entity) {uiState.gotoCoords = {lat,lon,- zoom: Number(entity.attrs?.zoom),- bearing: Number(entity.attrs?.bearing),+ zoom: recorded(entity.attrs?.zoom),+ bearing: recorded(entity.attrs?.bearing),};}uiState.tool = 'satellite';@@ -72,8 +83,8 @@ export function openEntity(entity) {uiState.gotoCoords = {lat,lon,- zoom: Number(entity.attrs?.zoom),- bearing: Number(entity.attrs?.bearing),+ zoom: recorded(entity.attrs?.zoom),+ bearing: recorded(entity.attrs?.bearing),provider: entity.attrs?.provider,};uiState.focusCapture = entity.attrs?.path ?? null;@@ -117,8 +128,8 @@ export function gotoCapture(entity) {uiState.gotoCoords = {lat,lon,- zoom: Number(entity.attrs?.zoom),- bearing: Number(entity.attrs?.bearing),+ zoom: recorded(entity.attrs?.zoom),+ bearing: recorded(entity.attrs?.bearing),};uiState.tool = 'satellite';}diff --git a/frontend/src/lib/navigate.test.js b/frontend/src/lib/navigate.test.jsindex f27e66d..32ad143 100644--- a/frontend/src/lib/navigate.test.js+++ b/frontend/src/lib/navigate.test.js@@ -1,6 +1,6 @@import { beforeEach, describe, expect, it, vi } from 'vitest';import { uiState } from './state.svelte.js';-import { gotoPoint, openEntity } from './navigate.js';+import { gotoCapture, gotoPoint, openEntity } from './navigate.js';beforeEach(() => {uiState.tool = 'media';@@ -30,6 +30,33 @@ describe('openEntity', () => {lat: 48.8584, lon: 2.2945, zoom: 17, bearing: 30, provider: 'esri-world-imagery',});});++ it('leaves the zoom to the map when a place records none', () => {+ // enrichment mints a place from a photo's EXIF: coordinates, no zoom. A+ // zoom of 0 is the whole globe, so an absent one must stay absent (NaN)+ // and let the Satellite tool pick its own close-in default.+ openEntity({ type: 'place', attrs: { lat: 48.8584, lon: 2.2945, zoom: null, bearing: null } });++ expect(uiState.tool).toBe('satellite');+ expect(uiState.gotoCoords.lat).toBe(48.8584);+ expect(uiState.gotoCoords.zoom).toBeNaN();+ expect(uiState.gotoCoords.bearing).toBeNaN();+ });++ it('keeps the zoom a place did record', () => {+ openEntity({ type: 'place', attrs: { lat: 48.8584, lon: 2.2945, zoom: 19, bearing: 0 } });++ expect(uiState.gotoCoords).toEqual({ lat: 48.8584, lon: 2.2945, zoom: 19, bearing: 0 });+ });+});++describe('gotoCapture', () => {+ it('leaves the zoom to the map when the capture records none', () => {+ gotoCapture({ type: 'capture', attrs: { lat: 48.8584, lon: 2.2945, zoom: null } });++ expect(uiState.tool).toBe('satellite');+ expect(uiState.gotoCoords.zoom).toBeNaN();+ });});describe('gotoPoint', () => {diff --git a/frontend/src/lib/trash.js b/frontend/src/lib/trash.jsnew file mode 100644index 0000000..c913363--- /dev/null+++ b/frontend/src/lib/trash.js@@ -0,0 +1,77 @@+/**+ * The case trash, from the UI side.+ *+ * A delete answers with the group it went into, so the toast that follows can+ * offer to undo it. The server is what decides: no group in the response means+ * nothing was kept — an artifact the graph never claimed — and the toast says so+ * by simply not offering an undo.+ *+ * The copy below is shared so every tool says the same thing about the same+ * gesture. Deleting an artifact is recoverable; emptying the trash, purging one+ * group and deleting a case are not.+ */+import { api } from './api.js';+import { reloadCase, toast } from './state.svelte.js';++/** What a delete dialog promises when the artifact goes to the trash. */+export const RESTORABLE = 'You can restore it from Trash until you empty it.';++export function trashUrl(caseId) {+ return `/api/cases/${caseId}/trash`;+}++/** Read the trash: its groups, how many items they hold and their size. */+export function readTrash(caseId) {+ return api.get(trashUrl(caseId));+}++export async function restoreGroup(caseId, groupId) {+ const result = await api.post(`${trashUrl(caseId)}/${groupId}/restore`, {});+ await reloadCase();+ return result;+}++export async function purgeGroup(caseId, groupId) {+ await api.del(`${trashUrl(caseId)}/${groupId}`);+}++export async function emptyTrash(caseId) {+ return api.del(trashUrl(caseId));+}++/** Bytes as the node shows them: whole units, no decimals below a megabyte. */+export function formatSize(bytes) {+ const n = Number(bytes) || 0;+ if (n < 1024) return `${n} B`;+ if (n < 1024 * 1024) return `${Math.round(n / 1024)} KB`;+ if (n < 1024 * 1024 * 1024) return `${Math.round(n / (1024 * 1024))} MB`;+ return `${(n / (1024 * 1024 * 1024)).toFixed(1)} GB`;+}++/**+ * The way back from a delete, or null when the server kept nothing.+ *+ * `result` is the delete response. Restoring reloads the case itself, so a+ * caller only has to hand over what it just deleted.+ */+export function undoAction(caseId, result) {+ if (!result?.trash) return null;+ return {+ label: 'Undo',+ onClick: async () => {+ try {+ await restoreGroup(caseId, result.trash);+ toast('Restored', 'ok', 2200);+ } catch (e) {+ toast(e.message, 'danger');+ }+ },+ };+}++/** Say what was deleted, and offer the way back when there is one. */+export function deletedToast(caseId, result, label) {+ const count = result?.deleted?.length ?? 0;+ const message = count > 1 ? `Deleted ${count} items` : `Deleted “${label}”`;+ toast(message, 'info', 7000, undoAction(caseId, result));+}diff --git a/frontend/src/lib/trash.test.js b/frontend/src/lib/trash.test.jsnew file mode 100644index 0000000..3aa628b--- /dev/null+++ b/frontend/src/lib/trash.test.js@@ -0,0 +1,80 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';+import { api } from './api.js';+import { reloadCase, toast } from './state.svelte.js';+import {+ deletedToast,+ emptyTrash,+ formatSize,+ purgeGroup,+ readTrash,+ restoreGroup,+ trashUrl,+ undoAction,+} from './trash.js';++vi.mock('./api.js', () => ({+ api: {+ get: vi.fn(),+ post: vi.fn(),+ del: vi.fn(),+ },+}));++vi.mock('./state.svelte.js', () => ({+ reloadCase: vi.fn(),+ toast: vi.fn(),+}));++beforeEach(() => {+ vi.clearAllMocks();+});++describe('case trash API', () => {+ it('uses one case-scoped endpoint for list, restore, purge and empty', async () => {+ await readTrash('case-1');+ await restoreGroup('case-1', 'trash-1');+ await purgeGroup('case-1', 'trash-1');+ await emptyTrash('case-1');++ expect(trashUrl('case-1')).toBe('/api/cases/case-1/trash');+ expect(api.get).toHaveBeenCalledWith('/api/cases/case-1/trash');+ expect(api.post).toHaveBeenCalledWith('/api/cases/case-1/trash/trash-1/restore', {});+ expect(api.del).toHaveBeenCalledWith('/api/cases/case-1/trash/trash-1');+ expect(api.del).toHaveBeenCalledWith('/api/cases/case-1/trash');+ expect(reloadCase).toHaveBeenCalledOnce();+ });++ it('only offers undo when the delete returned a trash group', async () => {+ expect(undoAction('case-1', { deleted: ['e1'] })).toBeNull();++ const action = undoAction('case-1', { trash: 'trash-1' });+ expect(action.label).toBe('Undo');+ await action.onClick();++ expect(api.post).toHaveBeenCalledWith('/api/cases/case-1/trash/trash-1/restore', {});+ expect(toast).toHaveBeenCalledWith('Restored', 'ok', 2200);+ });++ it('counts a cascade in the delete toast and attaches its undo', () => {+ deletedToast('case-1', { deleted: ['e1', 'e2'], trash: 'trash-1' }, 'Source');++ expect(toast).toHaveBeenCalledWith(+ 'Deleted 2 items',+ 'info',+ 7000,+ expect.objectContaining({ label: 'Undo' })+ );+ });+});++describe('trash size labels', () => {+ it.each([+ [0, '0 B'],+ [1023, '1023 B'],+ [1024, '1 KB'],+ [1024 * 1024, '1 MB'],+ [1.5 * 1024 * 1024 * 1024, '1.5 GB'],+ ])('formats %s bytes as %s', (bytes, label) => {+ expect(formatSize(bytes)).toBe(label);+ });+});diff --git a/frontend/src/tools/Files.svelte b/frontend/src/tools/Files.svelteindex f1776d0..ee77708 100644--- a/frontend/src/tools/Files.svelte+++ b/frontend/src/tools/Files.svelte@@ -9,7 +9,7 @@* lib/filing.js); the selection math is pure and unit-tested (lib/gridSelect.js).*/import { api } from '../lib/api.js';- import { caseState, reloadCase, toast } from '../lib/state.svelte.js';+ import { caseState, reloadCase, toast, uiState } from '../lib/state.svelte.js';import { buildTree, subtreeCount, folderOf, flattenPaths, isInFolderSubtree } from '../lib/folderTree.js';import { assignFolderBatch } from '../lib/filing.js';import { createNote } from '../lib/notes.js';@@ -18,6 +18,15 @@import { marqueeRect, marqueeHits, toggleSelection } from '../lib/gridSelect.js';import { buildCatalogQuery, fetchAllEntities } from '../lib/catalog.js';import { sortFileEntities } from '../lib/fileSort.js';+ import {+ deletedToast,+ emptyTrash,+ formatSize,+ purgeGroup,+ readTrash,+ restoreGroup,+ RESTORABLE,+ } from '../lib/trash.js';import { createPagedList } from '../lib/pagedList.svelte.js';import Icon from '../components/Icon.svelte';import SearchInput from '../components/SearchInput.svelte';@@ -57,6 +66,9 @@});const confirmed = $derived(pl.items);let summary = $state(null); // { total, by_type, by_status, by_folder }+ const emptyTrashState = () => ({ groups: [], items: 0, size_bytes: 0 });+ let trashData = $state(emptyTrashState());+ let trashRun = 0;let loadedFor = null; // non-reactive: only the load effect reads/writes it$effect(() => {const id = caseState.current?.id;@@ -64,18 +76,32 @@if (!id) {pl.clear();summary = null;+ trashData = emptyTrashState();+ showTrash = false;return;}if (id !== loadedFor) {loadedFor = id;pl.clear();+ showTrash = false;}pl.reload();api.get(`/api/cases/${id}/catalog/summary`).then((s) => (summary = s)).catch(() => (summary = null));+ loadTrash(id);});++ async function loadTrash(id) {+ const run = ++trashRun;+ try {+ const listed = await readTrash(id);+ if (run === trashRun && caseState.current?.id === id) trashData = listed;+ } catch {+ if (run === trashRun && caseState.current?.id === id) trashData = emptyTrashState();+ }+ }$effect(() => {pl.setQuery(query);});@@ -104,6 +130,7 @@// ── navigation ──────────────────────────────────────────────────────────────let cwd = $state(''); // '' = root ("All")let showUnfiled = $state(false);+ let showTrash = $state(false);function nodeAt(path) {if (!path) return { path: '', children: tree, entities: [] };@@ -254,22 +281,33 @@const ctxParent = $derived(showUnfiled || searching ? '' : cwd);function openFolder(path) {+ showTrash = false;showUnfiled = false;cwd = path;if (searching && pl.serverMode) pl.reload();}function openUnfiled() {+ showTrash = false;showUnfiled = true;if (searching && pl.serverMode) pl.reload();}+ function openTrash() {+ showTrash = true;+ showUnfiled = false;+ cwd = '';+ query = '';+ }+// ── selection ────────────────────────────────────────────────────────────────let selected = $state([]);let anchor = null;+ let deleteShortcutPending = false;// clear the selection whenever the view changes$effect(() => {cwd;showUnfiled;+ showTrash;query;selected = [];anchor = null;@@ -281,6 +319,32 @@anchor = r.anchor;}+ function onFilesKeydown(event) {+ if (+ event.key !== 'Delete' ||+ event.repeat ||+ uiState.tool !== 'files' ||+ showTrash ||+ !selected.length ||+ confirmState ||+ deleteShortcutPending+ ) {+ return;+ }+ const target = event.target;+ if (+ target instanceof HTMLElement &&+ (target.matches('input, textarea, select') || target.isContentEditable)+ ) {+ return;+ }+ event.preventDefault();+ deleteShortcutPending = true;+ Promise.resolve(askDeleteEntities([...selected])).finally(() => {+ deleteShortcutPending = false;+ });+ }+// ── marquee (rubber-band) ─────────────────────────────────────────────────────let gridEl = $state(null);let marquee = $state(null); // {left, top, width, height} in the grid's content space@@ -433,6 +497,46 @@}}+ async function restoreTrashItem(group) {+ try {+ await restoreGroup(caseState.current.id, group.id);+ toast(`Restored “${group.label}”`, 'ok', 2200);+ } catch (e) {+ toast(e.message, 'danger');+ }+ }++ function askPurgeTrashItem(group) {+ confirmState = {+ title: 'Delete permanently?',+ message: `“${group.label}” will be gone for good.`,+ detail: 'The files will be deleted from disk.',+ confirmLabel: 'Delete permanently',+ tone: 'danger',+ icon: 'trash',+ action: async () => {+ await purgeGroup(caseState.current.id, group.id);+ await reloadCase();+ },+ };+ }++ function askEmptyFilesTrash() {+ const noun = trashData.items === 1 ? 'item' : 'items';+ confirmState = {+ title: 'Empty the trash?',+ message: `${trashData.items} ${noun} will be gone for good.`,+ detail: 'The files will be deleted from disk.',+ confirmLabel: 'Empty the trash',+ tone: 'danger',+ icon: 'trash',+ action: async () => {+ await emptyTrash(caseState.current.id);+ await reloadCase();+ },+ };+ }+async function askDeleteEntities(ids) {const ents = confirmed.filter((e) => ids.includes(e.id));if (!ents.length) return;@@ -455,17 +559,21 @@? `${ents.length} items will be removed from the case and their tools.`: `“${ents[0].label}” will be removed from the case and its tool.`,detail: ents.some((e) => FILE_BACKED.has(e.type))- ? 'Deletes the underlying files from disk and cannot be undone.'- : `${multi ? 'Removes them' : 'Removes it'} from the case and cannot be undone.`,+ ? `Moves ${multi ? 'the items and their files' : 'the item and its files'} to the case trash.`+ : `Moves ${multi ? 'the items' : 'the item'} to the case trash.`,consequences,+ restorable: RESTORABLE,confirmLabel: multi ? 'Delete all' : 'Delete everywhere',- tone: 'danger',+ tone: 'default',icon: 'trash',action: async () => {- for (const e of ents) await api.del(`/api/cases/${caseState.current.id}/entities/${e.id}`);+ const caseId = caseState.current.id;+ const result = multi+ ? await api.post(`/api/cases/${caseId}/entities/delete`, { ids: ents.map((e) => e.id) })+ : await api.del(`/api/cases/${caseId}/entities/${ents[0].id}`);await reloadCase();selected = [];- toast(multi ? `Deleted ${ents.length} items` : `Deleted “${ents[0].label}”`, 'info');+ deletedToast(caseId, result, ents[0].label);},};}@@ -678,43 +786,53 @@});</script>+<svelte:window onkeydown={onFilesKeydown} />+<div class="tool"><div class="tool-header"><h2>Files</h2><span class="sub">Organize My work</span><div class="spacer"></div>- <SearchInput- bind:value={query}- placeholder={cwd ? 'Search this folder…' : 'Search My work…'}- width="160px"- />- {#if view !== 'list'}- <select class="select sort-select" value={sort} onchange={onSortSelect} title="Sort order">- {#each SORTS as s (s.id)}- <option value={s.id}>{sortOptionLabel(s)}</option>+ {#if showTrash}+ {#if trashData.groups.length}+ <button class="btn btn-danger" onclick={askEmptyFilesTrash}>+ <Icon name="trash" size={14} /> Empty trash+ </button>+ {/if}+ {:else}+ <SearchInput+ bind:value={query}+ placeholder={cwd ? 'Search this folder…' : 'Search My work…'}+ width="160px"+ />+ {#if view !== 'list'}+ <select class="select sort-select" value={sort} onchange={onSortSelect} title="Sort order">+ {#each SORTS as s (s.id)}+ <option value={s.id}>{sortOptionLabel(s)}</option>+ {/each}+ </select>+ {/if}+ <div class="view-switch" role="group" aria-label="View">+ {#each VIEWS as v (v.id)}+ <button+ class="view-btn"+ class:active={view === v.id}+ title={`${v.label} view`}+ aria-pressed={view === v.id}+ onclick={() => (view = v.id)}+ >+ <Icon name={v.icon} size={14} /> {v.label}+ </button>{/each}- </select>- {/if}- <div class="view-switch" role="group" aria-label="View">- {#each VIEWS as v (v.id)}- <button- class="view-btn"- class:active={view === v.id}- title={`${v.label} view`}- aria-pressed={view === v.id}- onclick={() => (view = v.id)}- >- <Icon name={v.icon} size={14} /> {v.label}+ </div>+ <span class="bar-sep"></span>+ <form class="new-folder" onsubmit={(e) => { e.preventDefault(); createFolder(); }}>+ <input class="input" placeholder="New folder…" bind:value={newFolder} />+ <button class="btn" type="submit" disabled={!newFolder.trim()}>+ <Icon name="folder" size={14} /> Add</button>- {/each}- </div>- <span class="bar-sep"></span>- <form class="new-folder" onsubmit={(e) => { e.preventDefault(); createFolder(); }}>- <input class="input" placeholder="New folder…" bind:value={newFolder} />- <button class="btn" type="submit" disabled={!newFolder.trim()}>- <Icon name="folder" size={14} /> Add- </button>- </form>+ </form>+ {/if}</div>{#if !caseState.current}@@ -729,7 +847,7 @@<aside class="tree-rail"><divclass="trow"- class:active={cwd === '' && !showUnfiled}+ class:active={cwd === '' && !showUnfiled && !showTrash}class:dropping={dropTarget === ''}role="button"tabindex="0"@@ -766,13 +884,30 @@<span class="tname">Unfiled</span><span class="tcount">{unfiled.length}</span></div>++ <div+ class="trow"+ class:active={showTrash}+ role="button"+ tabindex="0"+ onclick={openTrash}+ onkeydown={(e) => e.key === 'Enter' && openTrash()}+ >+ <Icon name="trash" size={14} />+ <span class="tname">Trash</span>+ <span class="tcount">{trashData.items}</span>+ </div></aside><!-- right: the desktop surface --><section class="grid-pane"><div class="crumbs"><button class="crumb" onclick={() => openFolder('')}>All</button>- {#if showUnfiled}+ {#if showTrash}+ <Icon name="chevronRight" size={12} />+ <span class="crumb here">Trash</span>+ <span class="trash-summary">{trashData.items} item{trashData.items === 1 ? '' : 's'} · {formatSize(trashData.size_bytes)}</span>+ {:else if showUnfiled}<Icon name="chevronRight" size={12} /><span class="crumb here">Unfiled</span>{:else}@@ -791,7 +926,39 @@{/if}</div>- {#if view === 'list'}+ {#if showTrash}+ <div class="trash-pane">+ {#if trashData.groups.length}+ {#each trashData.groups as group (group.id)}+ <div class="trash-item">+ <span class="trash-icon"><Icon name="trash" size={18} /></span>+ <div class="trash-copy">+ <strong>{group.label}</strong>+ <span>+ {group.item_count} item{group.item_count === 1 ? '' : 's'}+ · {formatSize(group.size_bytes)}+ · {group.type}+ </span>+ </div>+ <button class="btn btn-sm" onclick={() => restoreTrashItem(group)}>+ <Icon name="undo" size={13} /> Restore+ </button>+ <button+ class="btn btn-danger btn-sm"+ onclick={() => askPurgeTrashItem(group)}+ >+ <Icon name="trash" size={13} /> Delete permanently+ </button>+ </div>+ {/each}+ {:else}+ <div class="grid-empty">+ <Icon name="trash" size={34} />+ <p>Trash is empty.</p>+ </div>+ {/if}+ </div>+ {:else if view === 'list'}<!-- Details list: rows with columns (Name · Type · Size · Added). --><!-- svelte-ignore a11y_no_static_element_interactions --><div@@ -1007,7 +1174,7 @@{/if}</div>{/if}- {#if pl.hasMore}+ {#if !showTrash && pl.hasMore}<div class="show-more"><button class="btn" onclick={() => pl.loadMore()} disabled={pl.loading}>{pl.loading ? 'Loading…' : 'Show more'}@@ -1122,6 +1289,7 @@message={confirmState.message}detail={confirmState.detail}consequences={confirmState.consequences}+ restorable={confirmState.restorable}confirmLabel={confirmState.confirmLabel}tone={confirmState.tone}icon={confirmState.icon}@@ -1395,12 +1563,59 @@.crumbs > :global(svg) {color: var(--text-3);}+ .trash-summary {+ margin-left: 8px;+ color: var(--text-3);+ font-size: var(--fs-xs);+ }.sel-count {font-size: var(--fs-xs);color: var(--accent);font-weight: 600;}+ .trash-pane {+ flex: 1;+ min-height: 0;+ overflow: auto;+ padding: 12px 14px;+ }+ .trash-item {+ display: flex;+ align-items: center;+ gap: 10px;+ padding: 10px 12px;+ border-bottom: 1px solid var(--border);+ }+ .trash-icon {+ display: grid;+ place-items: center;+ width: 32px;+ height: 32px;+ flex: 0 0 auto;+ border-radius: var(--r-sm);+ background: var(--bg-2);+ color: var(--text-3);+ }+ .trash-copy {+ display: flex;+ flex: 1;+ min-width: 0;+ flex-direction: column;+ gap: 2px;+ }+ .trash-copy strong {+ overflow: hidden;+ color: var(--text-1);+ font-size: var(--fs-sm);+ text-overflow: ellipsis;+ white-space: nowrap;+ }+ .trash-copy span {+ color: var(--text-3);+ font-size: var(--fs-xs);+ }+/* segmented view switch (Small · Large · List) */.view-switch {display: flex;diff --git a/frontend/src/tools/Files.test.js b/frontend/src/tools/Files.test.jsindex 0d273dd..bb0e053 100644--- a/frontend/src/tools/Files.test.js+++ b/frontend/src/tools/Files.test.js@@ -13,7 +13,7 @@ describe('Files bounded loading', () => {});it('offers Show more with an honest filtered total', () => {- expect(source).toContain('{#if pl.hasMore}');+ expect(source).toContain('{#if !showTrash && pl.hasMore}');expect(source).toContain('pl.loadMore()');expect(source).toContain('Showing {confirmed.length} of {total}');expect(source).toContain('/catalog/summary');@@ -70,7 +70,7 @@ describe('Files desktop affordances', () => {});it('renders the list view with Name/Type/Size/Added columns', () => {- expect(source).toContain("{#if view === 'list'}");+ expect(source).toContain("{:else if view === 'list'}");expect(source).toContain("{ id: 'name', label: 'Name' }");expect(source).toContain("{ id: 'type', label: 'Type' }");expect(source).toContain("{ id: 'size', label: 'Size' }");@@ -103,3 +103,44 @@ describe('Files desktop affordances', () => {expect(source).toContain('{#if tileThumb(e)}');});});++describe('Files trash', () => {+ it('shows the trash as a first-class Files location', () => {+ expect(source).toContain('onclick={openTrash}');+ expect(source).toContain('<span class="tname">Trash</span>');+ expect(source).toContain('{#if showTrash}');+ expect(source).toContain('{formatSize(trashData.size_bytes)}');+ });++ it('offers the same restore and permanent actions as the sidebar', () => {+ expect(source).toContain('restoreGroup(caseState.current.id, group.id)');+ expect(source).toContain('purgeGroup(caseState.current.id, group.id)');+ expect(source).toContain('emptyTrash(caseState.current.id)');+ expect(source).toContain('onclick={() => restoreTrashItem(group)}');+ expect(source).toContain('onclick={() => askPurgeTrashItem(group)}');+ expect(source).toContain('onclick={askEmptyFilesTrash}');+ });++ it('keeps permanent deletion behind the danger confirmation', () => {+ expect(source).toContain("title: 'Delete permanently?'");+ expect(source).toContain("title: 'Empty the trash?'");+ expect(source).toContain("detail: 'The files will be deleted from disk.'");+ expect(source).toContain("tone: 'danger'");+ });+});++describe('Files delete shortcut', () => {+ it('routes Delete through the existing grouped confirmation', () => {+ expect(source).toContain('<svelte:window onkeydown={onFilesKeydown} />');+ expect(source).toContain("event.key !== 'Delete'");+ expect(source).toContain('askDeleteEntities([...selected])');+ expect(source).toContain('event.preventDefault()');+ });++ it('does nothing in fields, Trash, or outside Files', () => {+ expect(source).toContain("uiState.tool !== 'files'");+ expect(source).toContain('showTrash');+ expect(source).toContain("target.matches('input, textarea, select')");+ expect(source).toContain('target.isContentEditable');+ });+});diff --git a/frontend/src/tools/Inspector.svelte b/frontend/src/tools/Inspector.svelteindex 0ec21f1..acb494d 100644--- a/frontend/src/tools/Inspector.svelte+++ b/frontend/src/tools/Inspector.svelte@@ -10,6 +10,7 @@} from '../lib/inspect.js';import { isDefaultName, nextName, savedSlugs, savedTitles, savedTitle, slugify } from '../lib/naming.js';import { createHistory } from '../lib/history.js';+ import { deletedToast } from '../lib/trash.js';import { IDENTITY, matrixCss, rotateAbout, isIdentity, matrixAngleDeg, pointerAngleDeg } from '../lib/frameRotate.js';import Icon from '../components/Icon.svelte';import SearchInput from '../components/SearchInput.svelte';@@ -1193,10 +1194,13 @@async function deleteSession(name) {try {- await api.del(`/api/cases/${caseState.current.id}/inspect/sessions/${name}`);+ const caseId = caseState.current.id;+ const session = sessionModal.list.find((item) => item.name === name);+ const result = await api.del(`/api/cases/${caseId}/inspect/sessions/${name}`);sessionModal.list = sessionModal.list.filter((s) => s.name !== name);if (openedSession?.name === name) openedSession = null;await reloadCase();+ deletedToast(caseId, result, session?.title ?? name);} catch (e) {toast(e.message, 'danger');}diff --git a/frontend/src/tools/MediaLibrary.svelte b/frontend/src/tools/MediaLibrary.svelteindex befbf21..57efeec 100644--- a/frontend/src/tools/MediaLibrary.svelte+++ b/frontend/src/tools/MediaLibrary.svelte@@ -15,6 +15,7 @@SORTS,} from '../lib/mediaFilter.js';import { gotoPoint } from '../lib/navigate.js';+ import { deletedToast, RESTORABLE } from '../lib/trash.js';import Icon from '../components/Icon.svelte';import SearchInput from '../components/SearchInput.svelte';import Modal from '../components/Modal.svelte';@@ -267,8 +268,14 @@// render) falls back to the type icon, reported once by dropping the path in// here — it does not retry on every render.let brokenThumbs = $state(new Set());+ const mediaKey = (item) => `${caseState.current?.id ?? ''}/${item.path}`;+ function markBrokenThumb(event) {+ const key = event.currentTarget.dataset.mediaKey;+ if (key) brokenThumbs = new Set(brokenThumbs).add(key);+ }const thumbsPending = $derived(- items.some((i) => i.thumb_state === 'queued' || i.thumb_state === 'running')+ (pl.facets?.thumbnail_pending ?? 0) > 0 ||+ items.some((i) => i.thumb_state === 'queued' || i.thumb_state === 'running'));const enrichmentPending = $derived(items.some((i) => i.enrich_state === 'queued' || i.enrich_state === 'running')@@ -527,7 +534,7 @@}}- // Deleting media drops the file (evidence!) — always behind a confirm.+ // Deleting media moves the file to the case trash.let deleteTarget = $state(null);let deleteBusy = $state(false);@@ -535,11 +542,12 @@if (!deleteTarget || deleteBusy) return;deleteBusy = true;try {- await api.del(+ const caseId = caseState.current.id;+ const result = await api.del(`/api/cases/${caseState.current.id}/media?path=${encodeURIComponent(deleteTarget.path)}`);await Promise.all([refresh(), reloadCase()]);- toast(`Removed ${deleteTarget.filename}`, 'info');+ deletedToast(caseId, result, deleteTarget.title ?? deleteTarget.filename);deleteTarget = null;} catch (e) {toast(e.message, 'danger');@@ -785,7 +793,7 @@{/each}<span class="media-col-actions" aria-label="Actions"></span></div>- {#each filteredItems as item (item.path)}+ {#each filteredItems as item (mediaKey(item))}<div class="media-row" class:focused={item.path === focusedPath} data-path={item.path} role="row"><!-- The preview remains an image-only control; the row itself is not a card. --><!-- svelte-ignore a11y_no_noninteractive_tabindex -->@@ -798,13 +806,14 @@onkeydown={(e) => e.key === 'Enter' && item.kind === 'image' && (lightboxItem = item)}aria-label={item.kind === 'image' ? `Preview ${item.filename}` : undefined}>- {#if item.thumbnail && item.thumb_state === 'ready' && !brokenThumbs.has(item.path)}+ {#if item.thumbnail && item.thumb_state === 'ready' && !brokenThumbs.has(mediaKey(item))}<imgsrc={`/files/${caseState.current.id}/${item.thumbnail}`}+ data-media-key={mediaKey(item)}alt=""loading="lazy"decoding="async"- onerror={() => (brokenThumbs = new Set(brokenThumbs).add(item.path))}+ onerror={markBrokenThumb}/>{:else if item.thumb_state === 'failed'}<button@@ -871,7 +880,7 @@</div>{:else}<div class="grid" class:compact={view === 'small'}>- {#each filteredItems as item (item.path)}+ {#each filteredItems as item (mediaKey(item))}<divclass="media-card card"class:focused={item.path === focusedPath}@@ -889,13 +898,14 @@onkeydown={(e) => e.key === 'Enter' && item.kind === 'image' && (lightboxItem = item)}aria-label={item.kind === 'image' ? `Preview ${item.filename}` : undefined}>- {#if item.thumbnail && item.thumb_state === 'ready' && !brokenThumbs.has(item.path)}+ {#if item.thumbnail && item.thumb_state === 'ready' && !brokenThumbs.has(mediaKey(item))}<imgsrc={`/files/${caseState.current.id}/${item.thumbnail}`}+ data-media-key={mediaKey(item)}alt={item.filename}loading="lazy"decoding="async"- onerror={() => (brokenThumbs = new Set(brokenThumbs).add(item.path))}+ onerror={markBrokenThumb}/>{:else if item.thumb_state === 'queued' || item.thumb_state === 'running'}<div class="thumb-status">@@ -1161,14 +1171,15 @@</div>{/if}-<!-- delete confirm: the file on disk goes with the entity -->+<!-- delete confirm: the file waits in the case trash with the entity -->{#if deleteTarget}<ConfirmDialogtitle="Delete this media?"message={`“${deleteTarget.title ?? deleteTarget.filename}” and its entity will be removed from the case.`}- detail="Deletes the file from disk and cannot be undone."+ detail="Moves the media and its file to the case trash."+ restorable={RESTORABLE}confirmLabel="Delete"- tone="danger"+ tone="default"busy={deleteBusy}onconfirm={confirmDelete}oncancel={() => (deleteTarget = null)}diff --git a/frontend/src/tools/MediaLibrary.test.js b/frontend/src/tools/MediaLibrary.test.jsindex f24d461..481a537 100644--- a/frontend/src/tools/MediaLibrary.test.js+++ b/frontend/src/tools/MediaLibrary.test.js@@ -35,10 +35,11 @@ describe('Media Library thumbnail layout', () => {describe('Media Library thumbnail states', () => {it('shows the image only when its thumbnail is ready and not broken', () => {- // the ready branch is gated on thumb_state and the broken-thumb fallback set- expect(source).toContain("item.thumb_state === 'ready' && !brokenThumbs.has(item.path)");- // a broken <img> reports once into brokenThumbs rather than retrying- expect(source).toContain('onerror={() => (brokenThumbs = new Set(brokenThumbs).add(item.path))}');+ // The ready branch and broken-thumb key include the case id: two cases may+ // legitimately use the same relative media path.+ expect(source).toContain("item.thumb_state === 'ready' && !brokenThumbs.has(mediaKey(item))");+ expect(source).toContain('data-media-key={mediaKey(item)}');+ expect(source).toContain('onerror={markBrokenThumb}');// lazy + async decode per the doc's UI failure behaviourexpect(source).toContain('loading="lazy"');expect(source).toContain('decoding="async"');@@ -52,11 +53,16 @@ describe('Media Library thumbnail states', () => {});it('polls while thumbnails are pending and only while the tool is visible', () => {+ expect(source).toContain("(pl.facets?.thumbnail_pending ?? 0) > 0");expect(source).toContain("i.thumb_state === 'queued' || i.thumb_state === 'running'");expect(source).toContain("if (!thumbsPending || uiState.tool !== 'media' || !caseState.current) return;");expect(source).toContain('/media/thumbnails/regenerate');});+ it('keeps polling for jobs outside the loaded media page', () => {+ expect(source).toContain('pl.facets?.thumbnail_pending');+ });+it('repeats the poll (not a one-shot timer that leaves a slow thumbnail stuck)', () => {// a self-repeating poll, so a thumbnail slower than one tick still resolves// without a page reload; the effect alone would not re-arm while pending@@ -148,6 +154,11 @@ describe('Media Library bounded loading', () => {expect(effect).toContain('pl.clear()');expect(effect).toContain('brokenThumbs = new Set()');});++ it('recreates media rows when the case changes even if relative paths match', () => {+ expect(source).toContain('{#each filteredItems as item (mediaKey(item))}');+ expect(source).toContain("const mediaKey = (item) => `${caseState.current?.id ?? ''}/${item.path}`");+ });});describe('Media Library search empty state', () => {diff --git a/frontend/src/tools/Notebook.svelte b/frontend/src/tools/Notebook.svelteindex 5aedf62..69c43e9 100644--- a/frontend/src/tools/Notebook.svelte+++ b/frontend/src/tools/Notebook.svelte@@ -13,6 +13,7 @@import { insertNotebookText, notebookImageMarkdown, notebookMediaMarkdown } from '../lib/notebookContent.js';import { caseTab, closeNotebookTab, openNotebookTab } from '../lib/notebookTabs.js';import { openEntity } from '../lib/navigate.js';+ import { deletedToast, RESTORABLE } from '../lib/trash.js';import { matchesTerms } from '../lib/folderBrowse.js';import Icon from '../components/Icon.svelte';import SearchInput from '../components/SearchInput.svelte';@@ -283,10 +284,11 @@cancelPendingSave();try {if (action.kind === 'delete') {- await deleteNote(caseState.current.id, action.noteId);+ const caseId = caseState.current.id;+ const result = await deleteNote(caseId, action.noteId);closeDeletedNote(action.noteId);await reloadCase();- toast(`Deleted "${action.label}"`, 'info');+ deletedToast(caseId, result, action.label);} else {await resetCaseNotes(caseState.current.id);text = '';@@ -755,10 +757,11 @@ flowchart LR? `Are you sure you want to delete “${noteAction.label}”?`: 'Are you sure you want to reset the content of this note?'}detail={noteAction.kind === 'delete'- ? 'Removes the note and its contents and cannot be undone.'+ ? 'Moves the note and its contents to the case trash.': 'The case note will remain, but its content will be cleared.'}+ restorable={noteAction.kind === 'delete' ? RESTORABLE : ''}confirmLabel={noteAction.kind === 'delete' ? 'Delete' : 'Reset'}- tone={noteAction.kind === 'delete' ? 'danger' : 'default'}+ tone="default"icon={noteAction.kind === 'delete' ? 'trash' : 'reset'}busy={noteActionBusy}onconfirm={confirmNoteAction}diff --git a/frontend/src/tools/PostComposer.svelte b/frontend/src/tools/PostComposer.svelteindex ae2a537..ebda8bc 100644--- a/frontend/src/tools/PostComposer.svelte+++ b/frontend/src/tools/PostComposer.svelte@@ -5,6 +5,7 @@import { templatesState } from '../lib/state.svelte.js';import { createNote } from '../lib/notes.js';import { openNotebook } from '../lib/navigate.js';+ import { deletedToast, RESTORABLE } from '../lib/trash.js';import { proofCoordsText, proofSource } from '../lib/composer.js';import { isDefaultName, nextName, savedSlugs, savedTitles, savedTitle, slugify } from '../lib/naming.js';import {@@ -715,9 +716,10 @@const entry = deleteEntry;deleteEntry = null;try {- await api.del(`/api/cases/${caseState.current.id}/drafts/${entry.name}`);+ const caseId = caseState.current.id;+ const result = await api.del(`/api/cases/${caseId}/drafts/${entry.name}`);await Promise.all([openDraftList(), reloadCase()]);- toast(`Deleted "${entry.title}"`, 'info');+ deletedToast(caseId, result, entry.title);} catch (e) {toast(e.message, 'danger');}@@ -1375,9 +1377,10 @@<ConfirmDialogtitle="Delete this draft?"message={`“${deleteEntry.title}” will be removed from the case.`}- detail="Deletes the saved draft and cannot be undone."+ detail="Moves the saved draft to the case trash."+ restorable={RESTORABLE}confirmLabel="Delete"- tone="danger"+ tone="default"icon="trash"onconfirm={deleteSavedDraft}oncancel={() => (deleteEntry = null)}diff --git a/frontend/src/tools/ProofComposer.svelte b/frontend/src/tools/ProofComposer.svelteindex d4e84ba..9333edc 100644--- a/frontend/src/tools/ProofComposer.svelte+++ b/frontend/src/tools/ProofComposer.svelte@@ -5,6 +5,7 @@import { lookupEntity, fetchAllEntities } from '../lib/catalog.js';import { matchesTerms } from '../lib/folderBrowse.js';import { isSatelliteMedia } from '../lib/mediaFilter.js';+ import { deletedToast, RESTORABLE } from '../lib/trash.js';import { caseState, uiState, ensureCase, reloadCase, toast, prefs, fmtCoords } from '../lib/state.svelte.js';import { templatesState } from '../lib/state.svelte.js';import Icon from '../components/Icon.svelte';@@ -2344,9 +2345,10 @@const entry = deleteEntry;deleteEntry = null;try {- await api.del(`/api/cases/${caseState.current.id}/proofs/${entry.name}`);+ const caseId = caseState.current.id;+ const result = await api.del(`/api/cases/${caseId}/proofs/${entry.name}`);await Promise.all([openProofList(), reloadCase()]);- toast(`Deleted "${entry.title}"`, 'info');+ deletedToast(caseId, result, entry.title);} catch (e) {toast(e.message, 'danger');}@@ -2886,9 +2888,10 @@<ConfirmDialogtitle="Delete this proof?"message={`“${deleteEntry.title}” will be removed from the case.`}- detail="Deletes the PNG and editable proof and cannot be undone."+ detail="Moves the PNG and editable proof to the case trash."+ restorable={RESTORABLE}confirmLabel="Delete"- tone="danger"+ tone="default"icon="trash"onconfirm={deleteSavedProof}oncancel={() => (deleteEntry = null)}diff --git a/frontend/src/tools/Satellite.svelte b/frontend/src/tools/Satellite.svelteindex 2e0734f..3a2fd9c 100644--- a/frontend/src/tools/Satellite.svelte+++ b/frontend/src/tools/Satellite.svelte@@ -16,6 +16,7 @@import { assignFolder } from '../lib/filing.js';import { saveRelation } from '../lib/relations.svelte.js';import { openEntity } from '../lib/navigate.js';+ import { deletedToast, RESTORABLE } from '../lib/trash.js';import { isRegistered, sourceRect, frameFitsView } from '../lib/screenCrop.js';import { extensionVersion, captureTab, onActivated } from '../lib/extBridge.js';import {@@ -2386,15 +2387,18 @@deleteBusy = true;const row = deleteTarget;try {+ const caseId = caseState.current.id;+ let result;if (row.kind === 'place') {- await api.del(`/api/cases/${caseState.current.id}/entities/${row.id}`);+ result = await api.del(`/api/cases/${caseId}/entities/${row.id}`);} else {- await api.del(- `/api/cases/${caseState.current.id}/satellite?path=${encodeURIComponent(row.path)}`+ result = await api.del(+ `/api/cases/${caseId}/satellite?path=${encodeURIComponent(row.path)}`);}deleteTarget = null;await reloadCase(); // re-reads the saved index and the case sidebar+ deletedToast(caseId, result, row.title || coordsLabel(row));} catch (e) {toast(e.message, 'danger');} finally {@@ -3220,10 +3224,11 @@title={deleteTarget.kind === 'place' ? 'Delete this place?' : 'Delete this capture?'}message={`“${deleteTarget.title || coordsLabel(deleteTarget)}” will be removed from the case.`}detail={deleteTarget.kind === 'place'- ? 'Removes the saved point and cannot be undone.'- : 'Deletes the image from disk and cannot be undone.'}+ ? 'Moves the saved point to the case trash.'+ : 'Moves the capture and its image to the case trash.'}+ restorable={RESTORABLE}confirmLabel="Delete"- tone="danger"+ tone="default"busy={deleteBusy}onconfirm={confirmDelete}oncancel={() => (deleteTarget = null)}diff --git a/pyproject.toml b/pyproject.tomlindex fd4e18e..c676f46 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -37,6 +37,10 @@ dependencies = ["numpy>=1.26,<3","requests>=2.31,<3","python-multipart>=0.0.9,<1.0",+ # Whole-bundle AES-GCM encryption. Version 49 dropped Intel macOS wheels,+ # while the other release targets can stay current within the tested major.+ "cryptography>=45,<49; sys_platform == 'darwin' and platform_machine == 'x86_64'",+ "cryptography>=45,<50; sys_platform != 'darwin' or platform_machine != 'x86_64'",# Unbounded ON PURPOSE. These two race against sites that change without# notice, so an old version is a broken version — the usual "pin for# reproducibility" logic inverts here. Azimut can also fetch newer copiesdiff --git a/src/azimut/__init__.py b/src/azimut/__init__.pyindex 709b639..ce2ce2b 100644--- a/src/azimut/__init__.py+++ b/src/azimut/__init__.py@@ -9,7 +9,7 @@ from PIL import Image as _Image# extension manifest is kept in lock-step by a test, so a release is bumped in# exactly one place. Getting this wrong nags every user with a false update# (the binary's self-check compares this against the latest GitHub tag).-__version__ = "0.2.5"+__version__ = "0.2.6"# Cap the pixels Pillow will decode from a file, process-wide. A tiny,# highly-compressed image can otherwise expand to gigabytes in memory and takediff --git a/src/azimut/api/cases.py b/src/azimut/api/cases.pyindex 848b536..4bc22da 100644--- a/src/azimut/api/cases.py+++ b/src/azimut/api/cases.py@@ -2,13 +2,17 @@from __future__ import annotations+from pathlib import Pathfrom typing import Any, cast-from fastapi import APIRouter, HTTPException+from fastapi import APIRouter, File, Form, HTTPException, UploadFile+from fastapi.responses import FileResponsefrom pydantic import BaseModel, Field+from .. import config+from ..engine import bundles as bundle_enginefrom ..engine import links as link_engine-from ..engine import media as media_engine+from ..engine import trash as trash_enginefrom ..repository import EntityStatusfrom ..workspace import Case, CaseError@@ -34,36 +38,8 @@ def _ensure_name_free(name: str, *, exclude_id: str | None = None) -> None:raise HTTPException(status_code=409, detail=f"a case named '{name}' already exists")-def _unlink_inside(case: Case, rel_path: str) -> None:- try:- case.resolve_inside(rel_path).unlink(missing_ok=True)- except CaseError:- pass---def _delete_artifact_files(case: Case, entity: dict[str, Any]) -> None:- """Drop the on-disk artifact an entity stands for (spec §6 delete/edit sync).-- A bare ``place`` has no file; an unknown (free-typed) entity is assumed to- have none either, so a future type files its own deletion here or not at all.- """- etype = entity.get("type")- attrs = entity.get("attrs", {})- if etype in ("media", "capture") and attrs.get("path"):- media_engine.delete_media_files(case, attrs["path"])- elif etype == "proof" and attrs.get("spec"):- _unlink_inside(case, attrs["spec"])- _unlink_inside(case, attrs["spec"].removesuffix(".json") + ".png")- elif etype == "post" and attrs.get("draft"):- _unlink_inside(case, attrs["draft"])- elif etype == "inspect-session" and attrs.get("spec"):- _unlink_inside(case, attrs["spec"])- elif etype == "note" and attrs.get("path"):- _unlink_inside(case, attrs["path"])---def delete_entity_deep(case: Case, entity_id: str) -> dict[str, Any]:- """Delete an entity, its artifact, and whatever cannot outlive it.+def delete_entities_deep(case: Case, entity_ids: list[str]) -> dict[str, Any]:+ """Delete one UI action and everything that cannot outlive its targets.The one door every delete goes through — sidebar, Media Library, a tool'sown list — so the rules hold wherever the click came from:@@ -72,34 +48,65 @@ def delete_entity_deep(case: Case, entity_id: str) -> dict[str, Any]:is only adjustments over a video), transitively;- artifacts ``derived-from`` it are never touched, and are scarred with atombstone first, while the target can still describe itself.++ The whole action lands in the trash as one group, so undoing it brings the+ cascade back together or not at all. The graph rows are still hard-deleted:+ what is kept is the recipe, not a hidden state every other query would have+ to filter out."""- plan = link_engine.plan_delete(case, entity_id)- target = case.get_entity(entity_id)- if target is None:- raise CaseError(f"entity '{entity_id}' not found")- going = [target, *plan["cascade"]]-- # Scar the survivors first, while the doomed can still describe themselves.- for survivor_id, lost_sources in link_engine.losses(- case, {e["id"] for e in going}- ).items():- for lost in lost_sources:- info = link_engine.tombstone_of(lost)- if info.get("path"):- link_engine.add_tombstone(case, survivor_id, info)-- for entity in going:- _delete_artifact_files(case, entity)+ with case.lock:+ going_by_id: dict[str, dict[str, Any]] = {}+ tombstoned: set[str] = set()+ for entity_id in dict.fromkeys(entity_ids):+ plan = link_engine.plan_delete(case, entity_id)+ target = case.get_entity(entity_id)+ if target is None:+ raise CaseError(f"entity '{entity_id}' not found")+ for entity in (target, *plan["cascade"]):+ going_by_id[entity["id"]] = entity+ tombstoned.update(entity["id"] for entity in plan["tombstone"])+ going = list(going_by_id.values())++ scars: list[dict[str, str]] = []+ losses = link_engine.losses(case, {e["id"] for e in going})+ for survivor_id, lost_sources in losses.items():+ survivor = case.get_entity(survivor_id)+ existing = {+ item.get("path")+ for item in (survivor or {}).get("attrs", {}).get(link_engine.LOST, [])+ }+ for lost in lost_sources:+ path = link_engine.tombstone_of(lost).get("path")+ if path and path not in existing:+ scars.append({"entity": survivor_id, "path": path})+ existing.add(path)++ group = trash_engine.send(case, going, scars)try:- case.remove_entity(entity["id"])- except CaseError:- pass # a cascade may already have taken it+ for survivor_id, lost_sources in losses.items():+ link_engine.add_tombstones(+ case,+ survivor_id,+ [link_engine.tombstone_of(source) for source in lost_sources],+ )+ for entity in going:+ if case.get_entity(entity["id"]) is not None:+ case.remove_entity(entity["id"])+ trash_engine.commit(case, group["id"])+ except Exception:+ trash_engine.rollback(case, group["id"])+ raise++ return {+ "status": "deleted",+ "deleted": [e["id"] for e in going],+ "tombstoned": sorted(tombstoned - set(going_by_id)),+ "trash": group["id"],+ }- return {- "status": "deleted",- "deleted": [e["id"] for e in going],- "tombstoned": [e["id"] for e in plan["tombstone"]],- }++def delete_entity_deep(case: Case, entity_id: str) -> dict[str, Any]:+ return delete_entities_deep(case, [entity_id])def _summary(entity: dict[str, Any]) -> dict[str, Any]:@@ -160,6 +167,10 @@ class EntityPatch(BaseModel):status: EntityStatus | None = None+class EntityDeleteIn(BaseModel):+ ids: list[str] = Field(min_length=1, max_length=200)++class LinkIn(BaseModel):# `from`/`to` are the link's own field names, but `from` is a Python keyword;# the request spells them out rather than aliasing around it.@@ -177,6 +188,14 @@ class FolderIn(BaseModel):name: str = Field(min_length=1, max_length=120)+class BundlePassword(BaseModel):+ password: str | None = Field(default=None, max_length=1024)+++class BundleUpload(BundlePassword):+ upload_id: str = Field(min_length=32, max_length=32)++@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)@@ -198,6 +217,51 @@ def create_scratch() -> dict[str, Any]:return {"id": case.id, **case.overview()}[email protected]("/bundles/inspect")+def inspect_bundle(+ file: UploadFile = File(),+ password: str | None = Form(default=None, max_length=1024),+) -> dict[str, Any]:+ upload_id: str | None = None+ try:+ upload_id, path = bundle_engine.stage_upload(file.file)+ preview = bundle_engine.inspect_bundle(path, password=password)+ except CaseError as exc:+ if upload_id is not None:+ bundle_engine.discard_upload(upload_id)+ raise HTTPException(status_code=400, detail=str(exc)) from exc+ preview.pop("path", None)+ return {**preview, "upload_id": upload_id}++[email protected]("/bundles/import")+def import_bundle(body: BundleUpload) -> dict[str, Any]:+ try:+ source = bundle_engine.uploaded_bundle(body.upload_id)+ case, job = bundle_engine.queue_import(+ source,+ password=body.password,+ cleanup_source=True,+ )+ except CaseError as exc:+ raise HTTPException(status_code=400, detail=str(exc)) from exc+ return {+ "case_id": case.id,+ "name": case.read().get("name", case.id),+ "job_id": job["id"],+ "state": job["state"],+ }++[email protected]("/bundles/uploads/{upload_id}")+def discard_bundle_upload(upload_id: str) -> dict[str, str]:+ try:+ bundle_engine.discard_upload(upload_id)+ except CaseError as exc:+ raise HTTPException(status_code=400, detail=str(exc)) from exc+ return {"status": "discarded"}++@router.get("/relation-types")def relation_types() -> list[dict[str, Any]]:"""The relation vocabulary (ONTOLOGY §3): how each type reads in words, the@@ -250,6 +314,59 @@ def delete_case(case_id: str) -> dict[str, str]:return {"status": "deleted"}[email protected]("/{case_id}/bundle/export")+def export_bundle(case_id: str, body: BundlePassword) -> dict[str, Any]:+ case = get_case(case_id)+ try:+ job = bundle_engine.queue_export(case, password=body.password)+ except CaseError as exc:+ raise HTTPException(status_code=400, detail=str(exc)) from exc+ return {+ "case_id": case.id,+ "job_id": job["id"],+ "state": job["state"],+ }++[email protected]("/{case_id}/bundle/jobs/{job_id}")+def bundle_job(case_id: str, job_id: str) -> dict[str, Any]:+ job = bundle_engine.job_status(case_id, job_id)+ if job is None or job.get("kind") not in {+ bundle_engine.EXPORT_JOB,+ bundle_engine.IMPORT_JOB,+ }:+ raise HTTPException(status_code=404, detail=f"bundle job '{job_id}' not found")+ return {+ "id": job["id"],+ "kind": job["kind"],+ "state": job["state"],+ "error": job.get("error"),+ }++[email protected]("/{case_id}/bundle/jobs/{job_id}/download")+def download_bundle(case_id: str, job_id: str) -> FileResponse:+ job = bundle_engine.job_status(case_id, job_id)+ if (+ job is None+ or job.get("kind") != bundle_engine.EXPORT_JOB+ or job.get("state") != "ready"+ ):+ raise HTTPException(status_code=404, detail="bundle download not ready")+ path = Path(job.get("payload", {}).get("output", ""))+ try:+ allowed = path.resolve().parent == config.bundles_dir().resolve()+ except OSError:+ allowed = False+ if not allowed or not path.is_file():+ raise HTTPException(status_code=404, detail="bundle download not found")+ return FileResponse(+ path,+ filename=path.name,+ media_type="application/octet-stream",+ )++@router.get("/{case_id}/notes")def read_notes(case_id: str) -> dict[str, str]:return {"text": get_case(case_id).read_notes()}@@ -466,6 +583,65 @@ def remove_entity(case_id: str, entity_id: str) -> dict[str, Any]:raise HTTPException(status_code=404, detail=str(exc)) from exc[email protected]("/{case_id}/entities/delete")+def remove_entities(case_id: str, body: EntityDeleteIn) -> dict[str, Any]:+ """Delete a multi-selection as one recoverable trash group."""+ case = get_case(case_id)+ try:+ return delete_entities_deep(case, body.ids)+ except CaseError as exc:+ raise HTTPException(status_code=404, detail=str(exc)) from exc++[email protected]("/{case_id}/trash")+def list_trash(case_id: str) -> dict[str, Any]:+ """What the case is holding for you, newest first.++ Head columns only — no payload is read here, so the node costs one indexed+ query however much is waiting in it.+ """+ case = get_case(case_id)+ summary = case.trash_summary()+ return {+ "groups": case.list_trash(),+ "items": summary["items"],+ "size_bytes": summary["size_bytes"],+ }++[email protected]("/{case_id}/trash/{group_id}/restore")+def restore_trash(case_id: str, group_id: str) -> dict[str, Any]:+ """Take one delete back, all of it or none.++ A 409 means a file is back at a path the group wants: restoring would have to+ rename an artifact behind the analyst, so it refuses and names the path+ instead.+ """+ case = get_case(case_id)+ try:+ return trash_engine.restore(case, group_id)+ except CaseError as exc:+ message = str(exc)+ status = 404 if "not found" in message else 409+ raise HTTPException(status_code=status, detail=message) from exc++[email protected]("/{case_id}/trash/{group_id}")+def purge_trash(case_id: str, group_id: str) -> dict[str, str]:+ """Drop one group for good. This is where the bytes actually go."""+ case = get_case(case_id)+ try:+ trash_engine.purge(case, group_id)+ except CaseError as exc:+ raise HTTPException(status_code=404, detail=str(exc)) from exc+ return {"status": "purged"}++[email protected]("/{case_id}/trash")+def empty_trash(case_id: str) -> dict[str, int]:+ return {"purged": trash_engine.empty(get_case(case_id))}++@router.get("/{case_id}/folders")def list_folders(case_id: str) -> list[str]:return get_case(case_id).list_folders()diff --git a/src/azimut/api/drafts.py b/src/azimut/api/drafts.pyindex bb53a05..05e6942 100644--- a/src/azimut/api/drafts.py+++ b/src/azimut/api/drafts.py@@ -17,6 +17,7 @@ from typing import Anyfrom fastapi import APIRouter, HTTPExceptionfrom pydantic import BaseModel, Field+from ..engine import artifacts as artifact_enginefrom ..engine import links as link_enginefrom ..workspace import CaseErrorfrom .cases import delete_by_path, get_case@@ -218,11 +219,12 @@ def save_draft(case_id: str, body: DraftIn) -> dict[str, Any]:@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"try:- path = case.resolve_inside(f"exports/{name}.json")+ case.resolve_inside(rel)except CaseError as exc:raise HTTPException(status_code=403, detail=str(exc)) from exc- result = delete_by_path(case, f"exports/{name}.json")+ result = delete_by_path(case, rel)if not result["deleted"]: # never filed as an entity: drop the file anyway- path.unlink(missing_ok=True)+ artifact_engine.delete(case, {"type": "post", "attrs": {"draft": rel}})return resultdiff --git a/src/azimut/api/inspect.py b/src/azimut/api/inspect.pyindex a134a00..5023141 100644--- a/src/azimut/api/inspect.py+++ b/src/azimut/api/inspect.py@@ -15,6 +15,7 @@ from fastapi import APIRouter, HTTPException, Responsefrom pydantic import BaseModel, Fieldfrom .. import jobs+from ..engine import artifacts as artifact_enginefrom ..engine import inspect as inspect_enginefrom ..engine import links as link_enginefrom ..workspace import CaseError@@ -383,11 +384,12 @@ def save_session(case_id: str, body: SessionIn) -> dict[str, Any]:@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"try:- spec_path = case.resolve_inside(f"inspect/{name}.json")+ case.resolve_inside(rel)except CaseError as exc:raise HTTPException(status_code=403, detail=str(exc)) from exc- result = delete_by_path(case, f"inspect/{name}.json")+ result = delete_by_path(case, rel)if not result["deleted"]: # never filed as an entity: drop the file anyway- spec_path.unlink(missing_ok=True)+ artifact_engine.delete(case, {"type": "inspect-session", "attrs": {"spec": rel}})return resultdiff --git a/src/azimut/api/media.py b/src/azimut/api/media.pyindex cf7afe7..951e0db 100644--- a/src/azimut/api/media.py+++ b/src/azimut/api/media.py@@ -128,6 +128,10 @@ def page_media(offset=offset,)result["items"] = with_thumb_state(case, result["items"])+ thumb_jobs = case.count_jobs(kind=thumbnail_engine.THUMB_KIND)+ result.setdefault("facets", {})["thumbnail_pending"] = (+ thumb_jobs.get("queued", 0) + thumb_jobs.get("running", 0)+ )return resultdiff --git a/src/azimut/api/proofs.py b/src/azimut/api/proofs.pyindex 4116d2f..3b50b77 100644--- a/src/azimut/api/proofs.py+++ b/src/azimut/api/proofs.py@@ -25,6 +25,7 @@ from typing import Anyfrom fastapi import APIRouter, HTTPExceptionfrom pydantic import BaseModel, Field+from ..engine import artifacts as artifact_enginefrom ..engine import links as link_enginefrom ..engine import media as media_enginefrom ..engine import satellite as satellite_engine@@ -350,15 +351,14 @@ 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"try:- spec_path = case.resolve_inside(f"proofs/{name}.json")+ case.resolve_inside(rel)except CaseError as exc:raise HTTPException(status_code=403, detail=str(exc)) from exc- result = delete_by_path(case, f"proofs/{name}.json")+ result = delete_by_path(case, rel)if not result["deleted"]: # never filed as an entity: drop the files anyway- spec_path.unlink(missing_ok=True)- spec_path.with_suffix(".png").unlink(missing_ok=True)- # The graph knows the spec and the export; the pasted images are known only- # by where they sit, so they are dropped here either way.- shutil.rmtree(spec_path.with_suffix(ASSETS_SUFFIX), ignore_errors=True)+ # The registry knows what a proof owns — spec, export and the pasted+ # images beside them — so this path and the chokepoint cannot drift.+ artifact_engine.delete(case, {"type": "proof", "attrs": {"spec": rel}})return resultdiff --git a/src/azimut/config.py b/src/azimut/config.pyindex 1d03499..79c9f80 100644--- a/src/azimut/config.py+++ b/src/azimut/config.py@@ -164,6 +164,11 @@ def scratch_dir() -> Path:return workspace_root() / "scratch"+def bundles_dir() -> Path:+ """Portable case bundles exported by the user."""+ return workspace_root() / "bundles"++def runtime_dir() -> Path:"""Where updated scrapers land (engine/scrapers.py).@@ -235,6 +240,7 @@ 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)# 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).diff --git a/src/azimut/engine/artifacts.py b/src/azimut/engine/artifacts.pynew file mode 100644index 0000000..e1a9d6b--- /dev/null+++ b/src/azimut/engine/artifacts.py@@ -0,0 +1,255 @@+"""What an entity owns on disk.++One declaration per entity type, read by everything that has to move an+artifact's files. Before this module the knowledge sat in a single ``elif``+chain in ``api/cases.py``, and that chain already had a hole: deleting a proof+dropped its spec and its export but left ``proofs/<name>.assets/`` behind, so+pasted images outlived the composition they belonged to.++A type that owns nothing on disk says so in `NO_FILES`, with the reason beside+it. A type in neither table is an oversight, and `tests/test_artifacts.py` fails+on it: a new tool declares what it writes, or it does not ship.++Companions are the files named after the main artifact — a media's sidecar, a+proof's export and its assets folder. A companion that does not `travels` is a+disposable cache: it is dropped on delete and never carried aside, because a+content-addressed thumbnail is shared between identical media and moving one+would blank a surviving row.+"""++from __future__ import annotations++import shutil+from dataclasses import dataclass, field+from pathlib import Path+from typing import TYPE_CHECKING, Any, ClassVar++from ..workspace import CaseError+from . import media as media_engine++if TYPE_CHECKING:+ from ..workspace import Case+++@dataclass(frozen=True)+class Companion:+ """A file an entity owns whose name follows its main artifact."""++ #: False for a disposable, possibly shared cache: dropped on delete, never+ #: moved aside with the artifact.+ travels: ClassVar[bool] = True++ def resolve(self, case: "Case", main: str) -> str | None:+ raise NotImplementedError+++@dataclass(frozen=True)+class Sidecar(Companion):+ """The media sidecar sitting beside the file, ``<name>.azimut.json``."""++ def resolve(self, case: "Case", main: str) -> str | None:+ return main + media_engine.SIDECAR_SUFFIX+++@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."""++ old: str+ new: str++ def resolve(self, case: "Case", main: str) -> str | None:+ return main.removesuffix(self.old) + self.new+++@dataclass(frozen=True)+class SharedThumb(Companion):+ """The cached thumbnail a media's sidecar records.++ Content-addressed, so two identical files share one, which is exactly why it+ never travels: moving it aside would blank whatever else points at it.+ """++ travels: ClassVar[bool] = False++ def resolve(self, case: "Case", main: str) -> str | None:+ item = media_engine.read_item(case, main)+ thumb = (item or {}).get("thumbnail")+ return thumb if isinstance(thumb, str) and thumb else None+++@dataclass(frozen=True)+class Kind:+ """One entity type's files: the attribute holding its main artifact, and+ whatever is named after it."""++ path_attr: str+ companions: tuple[Companion, ...] = field(default_factory=tuple)+ #: True when the media browse index holds a row keyed by the main path, so a+ #: delete has to unfile it and a restore has to file it again.+ indexed: bool = False+++#: Entity type -> what it owns. The only place these rules live.+KINDS: dict[str, Kind] = {+ "media": Kind(path_attr="path", companions=(Sidecar(), SharedThumb()), indexed=True),+ "capture": Kind(path_attr="path", companions=(Sidecar(), SharedThumb()), indexed=True),+ "proof": Kind(+ path_attr="spec",+ companions=(Swap(".json", ".png"), Swap(".json", ".assets")),+ ),+ "post": Kind(path_attr="draft"),+ "inspect-session": Kind(path_attr="spec"),+ "note": Kind(path_attr="path"),+}++#: Types that own nothing on disk, and why. A free-typed entity the analyst+#: invents needs no entry — it is a label in the graph until a tool gives it a+#: file, and that tool declares it in `KINDS`.+NO_FILES: dict[str, str] = {+ "place": "coordinates and a label",+ "event": "a date and a label",+ "person": "an identity in the graph",+ "organization": "an identity in the graph",+ "alias": "an identity in the graph",+ "account": "an identity in the graph",+ "email": "an identifier in the graph",+ "phone": "an identifier in the graph",+ "domain": "an identifier in the graph",+ "ip": "an identifier in the graph",+ "vehicle": "an identity in the graph",+ "bookmark": "a URL in the graph",+}+++def declares(type_: str) -> bool:+ """Whether this entity type has decided what it owns on disk."""+ return type_ in KINDS or type_ in NO_FILES+++def _resolve(case: "Case", rel: str) -> Path | None:+ """The absolute path of a case-relative artifact, or None when a doctored+ attribute addresses something outside the case."""+ try:+ return case.resolve_inside(rel)+ except CaseError:+ return None+++def _main_path(entity: dict[str, Any]) -> tuple[Kind, str] | None:+ kind = KINDS.get(str(entity.get("type") or ""))+ if kind is None:+ return None+ main = (entity.get("attrs") or {}).get(kind.path_attr)+ if not isinstance(main, str) or not main:+ return None+ return kind, main+++def _paths(case: "Case", entity: dict[str, Any], *, travelling: bool) -> list[str]:+ found = _main_path(entity)+ if found is None:+ return []+ kind, main = found+ rels = [main] if travelling else []+ for companion in kind.companions:+ if companion.travels != travelling:+ continue+ rel = companion.resolve(case, main)+ if rel:+ rels.append(rel)+ out = []+ for rel in dict.fromkeys(rels):+ path = _resolve(case, rel)+ if path is not None and path.exists():+ out.append(rel)+ return out+++def owned(case: "Case", entity: dict[str, Any]) -> list[str]:+ """The case-relative files and folders this entity owns, that exist now.++ These are what a delete removes and what the trash moves aside.+ """+ return _paths(case, entity, travelling=True)+++def caches(case: "Case", entity: dict[str, Any]) -> list[str]:+ """The disposable, possibly shared caches this entity points at.++ Dropped when nothing else still uses them, and regenerated on demand — never+ moved aside, so a restore re-queues rather than restores them.+ """+ return _paths(case, entity, travelling=False)+++def _drop_cache(case: "Case", rel: str) -> None:+ if any(item.get("thumbnail") == rel for item in case.list_media_items()):+ return # another media still shows this thumbnail+ path = _resolve(case, rel)+ if path is not None:+ path.unlink(missing_ok=True)+++def _remove(path: Path) -> None:+ if path.is_dir():+ shutil.rmtree(path, ignore_errors=True)+ else:+ path.unlink(missing_ok=True)+++def refile(case: "Case", entity: dict[str, Any]) -> str | None:+ """File a restored artifact back into whatever index tracks it.++ Today that is the media browse index, whose row a delete unfiled. The+ sidecar travelled with the file, so the row is rebuilt from it rather than+ from anything the trash had to remember. Returns the media path when one was+ refiled, so the caller can re-queue its thumbnail.+ """+ found = _main_path(entity)+ if found is None:+ return None+ kind, main = found+ if not kind.indexed:+ return None+ item = media_engine.read_item(case, main)+ if item is None:+ return None+ case.upsert_media_item(item, entity_id=entity.get("id"))+ return main+++def unfile(case: "Case", entity: dict[str, Any]) -> None:+ """Take an artifact out of the indexes and caches that track it, without+ touching the files it owns.++ What a delete does before the files go anywhere — dropped, or moved into the+ trash. The order matters: the caches are read while the sidecar is still+ there, and the browse index row goes before the sharing check, so a+ thumbnail this media was the last user of is actually reclaimed.+ """+ found = _main_path(entity)+ if found is None:+ return+ kind, main = found+ shared = caches(case, entity)+ if kind.indexed:+ case.remove_media_item(main)+ for rel in shared:+ _drop_cache(case, rel)+++def delete(case: "Case", entity: dict[str, Any]) -> None:+ """Drop everything an entity owns on disk, leaving the graph alone.++ The hard delete, for an artifact the graph never claimed — a file a tool+ wrote and no entity points at. Anything the graph does hold goes through the+ delete chokepoint instead, which moves the same files into the trash so the+ analyst can take the delete back.+ """+ unfile(case, entity)+ for rel in owned(case, entity):+ path = _resolve(case, rel)+ if path is not None:+ _remove(path)diff --git a/src/azimut/engine/bundles.py b/src/azimut/engine/bundles.pynew file mode 100644index 0000000..73ad1a5--- /dev/null+++ b/src/azimut/engine/bundles.py@@ -0,0 +1,1006 @@+"""Portable, integrity-checked case bundles.++A plain bundle is a ZIP whose first member is a small compatibility header and+whose last member is the SHA-256 manifest. A sealed bundle encrypts that whole+ZIP as an AES-256-GCM stream, so filenames and sizes are not left in the ZIP+central directory for other programs to read.+"""++from __future__ import annotations++import hashlib+import json+import os+import shutil+import sqlite3+import struct+import tempfile+import threading+import time+import unicodedata+import uuid+import zipfile+from contextlib import closing+from datetime import datetime, timezone+from pathlib import Path, PurePosixPath+from typing import Any, BinaryIO, Iterator++from cryptography.exceptions import InvalidTag+from cryptography.hazmat.primitives.ciphers.aead import AESGCM++from .. import __version__, config+from ..sqlite_backend import SQLITE_SCHEMA, SqliteCase+from ..workspace import Case, CaseError, _now, _replace_with_retry+from . import workqueue++BUNDLE_FORMAT = 1+HEADER_NAME = "bundle-header.json"+MANIFEST_NAME = "bundle.json"+MAGIC = b"AZIMUT-BUNDLE\0"+ENVELOPE_VERSION = 1+KDF_SCRYPT = 1+SCRYPT_LOG_N = 15+SCRYPT_R = 8+SCRYPT_P = 1+SCRYPT_MAXMEM = 64 * 1024 * 1024+CHUNK_SIZE = 1024 * 1024+MAX_MANIFEST_SIZE = 16 * 1024 * 1024+MAX_BUNDLE_MEMBERS = 100_000+MAX_DECLARED_SIZE = (1 << 63) - 1+MAX_CASE_NAME = 120+LARGE_BUNDLE_SIZE = 10 * 1024 * 1024 * 1024+MIN_DISK_RESERVE = 64 * 1024 * 1024+MAX_DISK_RESERVE = 512 * 1024 * 1024+_ENVELOPE = struct.Struct(">14sBBBII16sI4s")+_ZIP_LOCAL = struct.Struct("<4s5H3I2H")+_ZIP_LOCAL_MAGIC = b"PK\x03\x04"+_ZIP_DESCRIPTOR_MAGIC = b"PK\x07\x08"++BUNDLED_ROOTS = frozenset(+ {"case.json", "case.db", "notes.md", "notes", "media", "proofs", "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",+}++EXPORT_JOB = "bundle-export"+IMPORT_JOB = "bundle-import"+_secret_lock = threading.Lock()+_job_secrets: dict[str, str] = {}+_removed_jobs: dict[str, dict[str, Any]] = {}+_MAX_MEMORY_JOBS = 100+UPLOAD_MAX_AGE = 24 * 60 * 60+_WINDOWS_RESERVED = frozenset(+ {"CON", "PRN", "AUX", "NUL"}+ | {f"COM{index}" for index in range(1, 10)}+ | {f"LPT{index}" for index in range(1, 10)}+)+_WINDOWS_FORBIDDEN = frozenset('<>:"|?*')+++class BundleError(CaseError):+ """A bundle is invalid, incompatible, or cannot be opened."""+++def _uploads_dir() -> Path:+ return config.bundles_dir() / ".imports"+++def _upload_path(upload_id: str) -> Path:+ try:+ normalized = uuid.UUID(upload_id).hex+ except (ValueError, AttributeError) as exc:+ raise BundleError("invalid bundle upload") from exc+ if normalized != upload_id:+ raise BundleError("invalid bundle upload")+ return _uploads_dir() / f"{normalized}.bundle"+++def cleanup_uploads(*, now: float | None = None) -> None:+ """Remove abandoned browser uploads after a bounded recovery window."""+ directory = _uploads_dir()+ if not directory.is_dir():+ return+ cutoff = (time.time() if now is None else now) - UPLOAD_MAX_AGE+ for path in directory.glob("*.bundle"):+ try:+ if path.stat().st_mtime < cutoff:+ path.unlink()+ except FileNotFoundError:+ pass+++def stage_upload(source: BinaryIO) -> tuple[str, Path]:+ """Copy one browser upload to durable local staging without buffering it."""+ directory = _uploads_dir()+ directory.mkdir(parents=True, exist_ok=True)+ cleanup_uploads()+ usage = shutil.disk_usage(directory)+ reserve = _disk_reserve(usage.total)+ budget = max(0, usage.free - reserve)+ upload_id = uuid.uuid4().hex+ destination = _upload_path(upload_id)+ temporary = destination.with_suffix(".tmp")+ written = 0+ try:+ with temporary.open("xb") as target:+ while chunk := source.read(CHUNK_SIZE):+ current_free = shutil.disk_usage(directory).free+ if (+ written + len(chunk) > budget+ or current_free - len(chunk) < reserve+ ):+ raise BundleError(+ "not enough free space to stage this bundle without filling the disk"+ )+ target.write(chunk)+ written += len(chunk)+ _replace_with_retry(temporary, destination)+ except BaseException:+ temporary.unlink(missing_ok=True)+ destination.unlink(missing_ok=True)+ raise+ return upload_id, destination+++def uploaded_bundle(upload_id: str) -> Path:+ path = _upload_path(upload_id)+ if not path.is_file():+ raise BundleError("bundle upload not found")+ return path+++def discard_upload(upload_id: str) -> None:+ _upload_path(upload_id).unlink(missing_ok=True)+++def _json_bytes(value: Any) -> bytes:+ return (json.dumps(value, ensure_ascii=False, indent=2) + "\n").encode("utf-8")+++def _sha256(data: bytes) -> str:+ return hashlib.sha256(data).hexdigest()+++def _safe_member(name: str) -> bool:+ path = PurePosixPath(name)+ if (+ not name+ or path.is_absolute()+ or path.as_posix() != name+ or "\\" in name+ or "\0" in name+ ):+ return False+ for part in path.parts:+ if (+ part in {".", ".."}+ or part.endswith((" ", "."))+ or any(ord(char) < 32 or char in _WINDOWS_FORBIDDEN for char in part)+ or part.split(".", 1)[0].upper() in _WINDOWS_RESERVED+ ):+ return False+ return True+++def _portable_member_key(name: str) -> str:+ """The name Windows and macOS use for collision checks."""+ return "/".join(+ unicodedata.normalize("NFC", part).casefold()+ for part in PurePosixPath(name).parts+ )+++def _validate_member_names(names: list[str]) -> None:+ 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]+ if len(portable) != len(set(portable)):+ raise BundleError("the bundle contains paths that collide on another operating system")+++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))+++def _space_preview(source: Path, header: dict[str, Any]) -> dict[str, Any]:+ """Estimate peak extra space for an import on the workspace filesystem."""+ try:+ usage = shutil.disk_usage(config.workspace_root())+ source_size = source.stat().st_size+ except OSError as exc:+ raise BundleError("could not check free space for this bundle") from exc+ payload = int(header["total_size"])+ # 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)+ return {+ "estimated_import_bytes": estimated,+ "free_space_bytes": usage.free,+ "space_reserve_bytes": reserve,+ "space_ok": estimated + reserve <= usage.free,+ "large_bundle": payload >= LARGE_BUNDLE_SIZE or estimated * 2 >= max(usage.free, 1),+ }+++def _require_import_space(source: Path, header: dict[str, Any]) -> None:+ preview = _space_preview(source, header)+ if not preview["space_ok"]:+ raise BundleError(+ "not enough free space to import this bundle while keeping a disk safety reserve"+ )+++def _require_extract_space(target: Path, total_size: int) -> None:+ try:+ 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:+ raise BundleError(+ "not enough free space to extract this bundle while keeping a disk safety reserve"+ )+++def _require_export_space(target: Path, total_size: int) -> None:+ try:+ 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:+ raise BundleError(+ "not enough free space to export this case while keeping a disk safety reserve"+ )+++def _included(rel: str) -> bool:+ if rel == ".trash" or rel.startswith(".trash/"):+ return False+ if rel in {"media/.thumbs", "media/.dl"}:+ return False+ if rel.startswith("media/.thumbs/") or rel.startswith("media/.dl/"):+ return False+ return PurePosixPath(rel).parts[0] in BUNDLED_ROOTS+++def classify_case_entry(rel: str) -> str | None:+ """Return ``bundled``/``not-bundled`` for declared case state."""+ if _included(rel):+ return "bundled"+ if any(rel == path or rel.startswith(path + "/") for path in NOT_BUNDLED):+ return "not-bundled"+ return None+++def _case_files(case: Case) -> Iterator[tuple[str, Path]]:+ for path in sorted(case.path.rglob("*")):+ if not path.is_file():+ continue+ rel = path.relative_to(case.path).as_posix()+ if _included(rel) and rel not in {"case.json", "case.db"}:+ yield rel, path+++def _clean_database(source: Path, target: Path) -> None:+ """Take a consistent copy, remove local machine state, then compact it."""+ src = sqlite3.connect(source)+ dst = sqlite3.connect(target)+ try:+ src.backup(dst)+ finally:+ dst.close()+ src.close()++ conn = sqlite3.connect(target)+ try:+ conn.execute("PRAGMA foreign_keys = ON")+ conn.execute("DELETE FROM trash")+ conn.execute("DELETE FROM jobs WHERE state IN ('queued', 'running')")+ conn.commit()+ conn.execute("VACUUM")+ finally:+ conn.close()+++def _zip_info(name: str, *, compressed: bool) -> zipfile.ZipInfo:+ info = zipfile.ZipInfo(name, datetime.now().timetuple()[:6])+ info.compress_type = zipfile.ZIP_DEFLATED if compressed else zipfile.ZIP_STORED+ info.external_attr = 0o600 << 16+ return info+++def _compress_member(name: str) -> bool:+ return name != HEADER_NAME and not name.startswith("media/")+++def _write_bytes(+ archive: zipfile.ZipFile,+ name: str,+ data: bytes,+ records: list[dict[str, Any]],+) -> None:+ archive.writestr(_zip_info(name, compressed=_compress_member(name)), data)+ records.append({"path": name, "size": len(data), "sha256": _sha256(data)})+++def _write_file(+ archive: zipfile.ZipFile,+ name: str,+ source: Path,+ records: list[dict[str, Any]],+) -> None:+ digest = hashlib.sha256()+ size = 0+ with source.open("rb") as src, archive.open(+ _zip_info(name, compressed=_compress_member(name)), "w"+ ) as dst:+ while chunk := src.read(1024 * 1024):+ digest.update(chunk)+ size += len(chunk)+ dst.write(chunk)+ records.append({"path": name, "size": size, "sha256": digest.hexdigest()})+++def _derive_key(password: str, salt: bytes, *, log_n: int, r: int, p: int) -> bytes:+ if not password:+ raise BundleError("password required")+ try:+ return hashlib.scrypt(+ password.encode("utf-8"),+ salt=salt,+ n=1 << log_n,+ r=r,+ p=p,+ maxmem=SCRYPT_MAXMEM,+ dklen=32,+ )+ except (ValueError, OSError) as exc:+ raise BundleError(f"could not derive the bundle key: {exc}") from exc+++def _aad(header: bytes, index: int, final: bool) -> bytes:+ return hashlib.sha256(header).digest() + index.to_bytes(8, "big") + bytes([final])+++class _EnvelopeWriter:+ """Unseekable ZIP target that encrypts while bytes arrive."""++ def __init__(self, raw: BinaryIO, password: str):+ self.raw = raw+ salt = os.urandom(16)+ self.nonce_prefix = os.urandom(4)+ self.header = _ENVELOPE.pack(+ MAGIC,+ ENVELOPE_VERSION,+ KDF_SCRYPT,+ SCRYPT_LOG_N,+ SCRYPT_R,+ SCRYPT_P,+ salt,+ CHUNK_SIZE,+ self.nonce_prefix,+ )+ self.raw.write(self.header)+ self.cipher = AESGCM(+ _derive_key(+ password,+ salt,+ log_n=SCRYPT_LOG_N,+ r=SCRYPT_R,+ p=SCRYPT_P,+ )+ )+ self.buffer = bytearray()+ self.index = 0+ self.position = 0+ self.finished = False++ def writable(self) -> bool:+ return True++ def seekable(self) -> bool:+ return False++ def tell(self) -> int:+ return self.position++ def write(self, data: bytes | bytearray) -> int:+ if self.finished:+ raise ValueError("bundle envelope is closed")+ incoming = bytes(data)+ self.buffer.extend(incoming)+ self.position += len(incoming)+ while len(self.buffer) > CHUNK_SIZE:+ chunk = bytes(self.buffer[:CHUNK_SIZE])+ del self.buffer[:CHUNK_SIZE]+ self._seal(chunk, final=False)+ return len(incoming)++ def _seal(self, chunk: bytes, *, final: bool) -> None:+ nonce = self.nonce_prefix + self.index.to_bytes(8, "big")+ self.raw.write(self.cipher.encrypt(nonce, chunk, _aad(self.header, self.index, final)))+ self.index += 1++ def finish(self) -> None:+ if self.finished:+ return+ self._seal(bytes(self.buffer), final=True)+ self.buffer.clear()+ self.raw.flush()+ self.finished = True++ def flush(self) -> None:+ self.raw.flush()+++def _bundle_name(case: Case, sealed: bool) -> str:+ date = datetime.now(timezone.utc).strftime("%Y-%m-%d")+ suffix = ".azimut.enc" if sealed else ".azimut.zip"+ return f"{case.id}-{date}{suffix}"+++def bundle_path(case: Case, *, sealed: bool) -> Path:+ return config.bundles_dir() / _bundle_name(case, sealed)+++def export_case(+ case: Case,+ *,+ password: str | None = None,+ output: Path | None = None,+) -> Path:+ """Write one complete bundle atomically and return its path."""+ config.bundles_dir().mkdir(parents=True, exist_ok=True)+ output = Path(output) if output is not None else bundle_path(case, sealed=bool(password))+ if output.parent.resolve() != config.bundles_dir().resolve():+ raise BundleError("bundle output must stay inside the workspace bundle directory")+ temp_output = output.with_name(f".{output.name}.{uuid.uuid4().hex}.tmp")+ fd, db_name = tempfile.mkstemp(prefix="azimut-bundle-db-", suffix=".db", dir=config.bundles_dir())+ os.close(fd)+ clean_db = Path(db_name)++ try:+ _clean_database(case.path / "case.db", clean_db)+ case_json = case.json_path.read_bytes()+ files = list(_case_files(case))+ _validate_member_names(+ [HEADER_NAME, "case.json", "case.db", *(rel for rel, _ in files), MANIFEST_NAME]+ )+ total_size = len(case_json) + clean_db.stat().st_size+ total_size += sum(path.stat().st_size for _, path in files)+ _require_export_space(temp_output, total_size)+ header = {+ "format_version": BUNDLE_FORMAT,+ "azimut_version": __version__,+ "case_db_schema": SQLITE_SCHEMA,+ "case_name": case.read().get("name", case.id),+ "origin_case_id": case.id,+ "created_at": _now(),+ "total_size": total_size,+ }++ envelope: _EnvelopeWriter | None = None+ with temp_output.open("wb") as raw:+ target: Any = raw+ if password:+ envelope = _EnvelopeWriter(raw, password)+ target = envelope+ 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)+ for rel, path in files:+ _write_file(archive, rel, path, records)+ archive.writestr(+ _zip_info(MANIFEST_NAME, compressed=True),+ _json_bytes({"format_version": BUNDLE_FORMAT, "members": records}),+ )+ if envelope is not None:+ envelope.finish()+ _replace_with_retry(temp_output, output)+ return output+ except BaseException:+ temp_output.unlink(missing_ok=True)+ raise+ finally:+ clean_db.unlink(missing_ok=True)+++def _read_envelope(source: Path) -> tuple[bytes, dict[str, Any]]:+ with source.open("rb") as stream:+ raw = stream.read(_ENVELOPE.size)+ if len(raw) != _ENVELOPE.size:+ raise BundleError("the encrypted bundle header is incomplete")+ magic, version, kdf, log_n, r, p, salt, chunk_size, nonce_prefix = _ENVELOPE.unpack(raw)+ if magic != MAGIC or version != ENVELOPE_VERSION or kdf != KDF_SCRYPT:+ raise BundleError("unsupported encrypted bundle")+ if (log_n, r, p) != (SCRYPT_LOG_N, SCRYPT_R, SCRYPT_P):+ raise BundleError("unsupported encrypted bundle key parameters")+ if chunk_size != CHUNK_SIZE:+ raise BundleError("unsupported encrypted bundle chunk size")+ return raw, {+ "log_n": log_n,+ "r": r,+ "p": p,+ "salt": salt,+ "chunk_size": chunk_size,+ "nonce_prefix": nonce_prefix,+ }+++def _decrypt_chunks(source: Path, password: str) -> Iterator[bytes]:+ header, params = _read_envelope(source)+ remaining = source.stat().st_size - _ENVELOPE.size+ if remaining <= 16:+ raise BundleError("the encrypted bundle is incomplete")+ key = _derive_key(+ password,+ params["salt"],+ log_n=params["log_n"],+ r=params["r"],+ p=params["p"],+ )+ cipher = AESGCM(key)+ full = params["chunk_size"] + 16+ with source.open("rb") as stream:+ stream.seek(_ENVELOPE.size)+ index = 0+ while remaining:+ take = min(full, remaining)+ final = remaining <= full+ sealed = stream.read(take)+ if len(sealed) != take or take <= 16:+ raise BundleError("the encrypted bundle is incomplete")+ nonce = params["nonce_prefix"] + index.to_bytes(8, "big")+ try:+ yield cipher.decrypt(nonce, sealed, _aad(header, index, final))+ except InvalidTag as exc:+ raise BundleError("wrong password or damaged bundle") from exc+ remaining -= take+ index += 1+++def _first_zip_member(data: bytes) -> tuple[str, bytes]:+ if len(data) < _ZIP_LOCAL.size:+ raise BundleError("the bundle header is incomplete")+ signature, _, flags, compression, _, _, _, packed, _, name_len, extra_len = _ZIP_LOCAL.unpack(+ data[: _ZIP_LOCAL.size]+ )+ if signature != _ZIP_LOCAL_MAGIC or compression != zipfile.ZIP_STORED:+ raise BundleError("the bundle header is not the first stored ZIP member")+ start = _ZIP_LOCAL.size + name_len + extra_len+ if len(data) < start:+ raise BundleError("the bundle header is incomplete")+ name = data[_ZIP_LOCAL.size : _ZIP_LOCAL.size + name_len].decode("utf-8")+ if flags & 0x08:+ end = data.find(_ZIP_DESCRIPTOR_MAGIC, start)+ if end < 0:+ raise BundleError("the bundle header exceeds the pre-flight window")+ else:+ end = start + packed+ return name, data[start:end]+++def _validate_header(header: Any) -> dict[str, Any]:+ if not isinstance(header, dict):+ raise BundleError("invalid bundle header")+ version = header.get("format_version")+ db_schema = header.get("case_db_schema")+ if not isinstance(version, int) or not 1 <= version <= BUNDLE_FORMAT:+ raise BundleError("this bundle needs a newer Azimut bundle format")+ if not isinstance(db_schema, int) or not 1 <= db_schema <= SQLITE_SCHEMA:+ raise BundleError("this bundle needs a newer Azimut case database")+ case_name = header.get("case_name")+ if (+ not isinstance(case_name, str)+ or not case_name.strip()+ or len(case_name) > MAX_CASE_NAME+ ):+ raise BundleError("the bundle has no case name")+ total_size = header.get("total_size")+ if (+ not isinstance(total_size, int)+ or isinstance(total_size, bool)+ or not 0 <= total_size <= MAX_DECLARED_SIZE+ ):+ raise BundleError("the bundle has an invalid total size")+ origin = header.get("origin_case_id")+ if origin is not None and (not isinstance(origin, str) or len(origin) > MAX_CASE_NAME):+ raise BundleError("the bundle has an invalid origin case")+ return {**header, "case_name": case_name.strip()}+++def inspect_bundle(source: Path, *, password: str | None = None) -> dict[str, Any]:+ """Read only enough for the import confirmation."""+ source = Path(source).expanduser()+ if not source.is_file():+ raise BundleError(f"bundle '{source}' not found")+ with source.open("rb") as stream:+ sealed = stream.read(len(MAGIC)) == MAGIC+ if sealed:+ first = next(_decrypt_chunks(source, password or ""))+ name, data = _first_zip_member(first)+ if name != HEADER_NAME:+ raise BundleError("bundle-header.json is not the first member")+ try:+ header = json.loads(data)+ except (UnicodeDecodeError, json.JSONDecodeError) as exc:+ raise BundleError("invalid bundle header") from exc+ else:+ try:+ with zipfile.ZipFile(source) as archive:+ infos = archive.infolist()+ if not infos or infos[0].filename != HEADER_NAME:+ raise BundleError("bundle-header.json is not the first member")+ with archive.open(infos[0]) as member:+ data = member.read(CHUNK_SIZE + 1)+ if len(data) > CHUNK_SIZE:+ raise BundleError("the bundle header is too large")+ header = json.loads(data)+ except (OSError, zipfile.BadZipFile, UnicodeDecodeError, json.JSONDecodeError) as exc:+ raise BundleError("invalid case bundle") from exc+ preview = {**_validate_header(header), "sealed": sealed, "path": str(source)}+ return {**preview, **_space_preview(source, preview)}+++def _decrypt_to(source: Path, target: Path, password: str) -> None:+ with target.open("wb") as stream:+ for chunk in _decrypt_chunks(source, password):+ stream.write(chunk)+++def _manifest(archive: zipfile.ZipFile) -> 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")+ 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):+ raise BundleError("the bundle contains directory members")+ try:+ with archive.open(MANIFEST_NAME) as member:+ raw_manifest = member.read(MAX_MANIFEST_SIZE + 1)+ if len(raw_manifest) > MAX_MANIFEST_SIZE:+ raise BundleError("the bundle manifest is too large")+ manifest = json.loads(raw_manifest)+ except (KeyError, UnicodeDecodeError, json.JSONDecodeError) as exc:+ raise BundleError("invalid bundle manifest") from exc+ records = manifest.get("members") if isinstance(manifest, dict) else None+ if not isinstance(records, list):+ raise BundleError("invalid bundle manifest")+ if manifest.get("format_version") != BUNDLE_FORMAT:+ raise BundleError("unsupported bundle manifest")+ by_name: dict[str, dict[str, Any]] = {}+ for record in records:+ if not isinstance(record, dict) or not isinstance(record.get("path"), str):+ raise BundleError("invalid bundle manifest member")+ name = record["path"]+ if name in by_name:+ raise BundleError("the bundle manifest contains duplicate paths")+ by_name[name] = record+ if set(by_name) != set(names[:-1]):+ raise BundleError("the bundle members do not match its manifest")+ return infos[:-1], by_name+++def _verify_and_extract(archive_path: Path, target: Path) -> dict[str, Any]:+ with zipfile.ZipFile(archive_path) as archive:+ infos, records = _manifest(archive)+ for info in infos:+ record = records[info.filename]+ expected_size = record.get("size")+ expected_hash = record.get("sha256")+ if (+ not isinstance(expected_size, int)+ or isinstance(expected_size, bool)+ or not 0 <= expected_size <= MAX_DECLARED_SIZE+ or not isinstance(expected_hash, str)+ or len(expected_hash) != 64+ or any(char not in "0123456789abcdef" for char in expected_hash)+ or info.file_size != expected_size+ ):+ raise BundleError("invalid bundle manifest member")++ header_info = infos[0]+ header_record = records[HEADER_NAME]+ with archive.open(header_info) as member:+ data = member.read(CHUNK_SIZE + 1)+ if len(data) > CHUNK_SIZE:+ raise BundleError("the bundle header is too large")+ if (+ len(data) != header_record["size"]+ or hashlib.sha256(data).hexdigest() != header_record["sha256"]+ ):+ raise BundleError("bundle-header.json failed verification")+ try:+ header = _validate_header(json.loads(data))+ except (UnicodeDecodeError, json.JSONDecodeError) as exc:+ raise BundleError("invalid bundle header") from exc++ declared_total = sum(records[info.filename]["size"] for info in infos[1:])+ if declared_total != header["total_size"]:+ raise BundleError("the bundle total size does not match its manifest")+ _require_extract_space(target, declared_total)++ total_written = 0+ for info in infos[1:]:+ record = records[info.filename]+ expected_size = record["size"]+ digest = hashlib.sha256()+ size = 0+ destination = target / PurePosixPath(info.filename)+ destination.parent.mkdir(parents=True, exist_ok=True)+ with archive.open(info) as src:+ sink: BinaryIO = destination.open("wb")+ with sink:+ while chunk := src.read(CHUNK_SIZE):+ if size + len(chunk) > expected_size:+ raise BundleError(+ f"bundle member '{info.filename}' exceeds its declared size"+ )+ digest.update(chunk)+ size += len(chunk)+ total_written += len(chunk)+ if total_written > declared_total:+ raise BundleError("the bundle exceeds its declared total size")+ sink.write(chunk)+ if size != expected_size or digest.hexdigest() != record["sha256"]:+ raise BundleError(f"bundle member '{info.filename}' failed verification")+ return header+++def _prepare_import_database(+ db_path: Path,+ *,+ declared_schema: int,+ origin_case_id: str,+ name: str,+) -> None:+ with closing(sqlite3.connect(db_path)) as conn:+ row = conn.execute("SELECT value FROM meta WHERE key = 'schema_version'").fetchone()+ if row is None or int(row[0]) != declared_schema:+ raise BundleError("the case database does not match the bundle header")+ if conn.execute("PRAGMA integrity_check").fetchone()[0] != "ok":+ 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)+ with closing(sqlite3.connect(db_path)) as conn:+ for key, value in (+ ("name", name),+ ("origin_case_id", origin_case_id),+ ("imported_at", _now()),+ ):+ conn.execute(+ "INSERT INTO meta(key, value) VALUES(?, ?)"+ " ON CONFLICT(key) DO UPDATE SET value = excluded.value",+ (key, value),+ )+ conn.commit()+++def imported_name(name: str) -> str:+ return f"{name} (imported)"+++def create_import_case(name: str) -> Case:+ """Create a distinct destination, adding a number only when needed."""+ base = imported_name(name)+ candidate = base+ index = 2+ while True:+ try:+ return Case.create(candidate)+ except CaseError:+ pass+ candidate = f"{base} {index}"+ index += 1+++def _install_running_job(db_path: Path, job: dict[str, Any]) -> None:+ """Carry the import job through the final directory swap."""+ with closing(sqlite3.connect(db_path)) as conn:+ conn.execute(+ "INSERT OR REPLACE INTO jobs"+ "(id, kind, job_key, state, attempts, max_attempts, payload_json,"+ " error, created_at, updated_at)"+ " VALUES(?, ?, ?, 'running', ?, ?, ?, NULL, ?, ?)",+ (+ job["id"],+ job["kind"],+ job.get("key"),+ job.get("attempts", 1),+ job.get("max_attempts", 1),+ json.dumps(job.get("payload") or {}, ensure_ascii=False),+ job.get("created_at") or _now(),+ _now(),+ ),+ )+ conn.commit()+++def import_into(+ case: Case,+ source: Path,+ *,+ password: str | None = None,+ job: dict[str, Any] | None = None,+) -> dict[str, Any]:+ """Verify a bundle in staging, then swap it over a fresh destination shell."""+ source = Path(source).expanduser()+ header = inspect_bundle(source, password=password)+ _require_import_space(source, header)+ staging = case.path.with_name(f"{case.id}.incoming")+ old = case.path.with_name(f"{case.id}.import-shell-{uuid.uuid4().hex}")+ if staging.exists():+ raise BundleError(f"import staging path '{staging.name}' already exists")+ staging.mkdir()+ archive_path = source+ decrypted = staging / ".bundle.zip"+ try:+ if header["sealed"]:+ _decrypt_to(source, decrypted, password or "")+ archive_path = decrypted+ verified = _verify_and_extract(archive_path, staging)+ decrypted.unlink(missing_ok=True)+ if not (staging / "case.json").is_file() or not (staging / "case.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["name"] = name+ manifest["updated_at"] = _now()+ (staging / "case.json").write_bytes(_json_bytes(manifest))+ _prepare_import_database(+ staging / "case.db",+ 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)+ case.path.rename(old)+ staging.rename(case.path)+ imported = Case.open(case.id)+ from . import thumbnails++ for item in imported.list_media_items():+ if item.get("kind") in thumbnails.THUMBNAILED_KINDS:+ if job is None:+ thumbnails.enqueue(imported, item["path"])+ else:+ imported.enqueue_job(+ thumbnails.THUMB_KIND,+ key=item["path"],+ payload={"path": item["path"]},+ )+ shutil.rmtree(old)+ return {"case_id": imported.id, "name": name, "origin_case_id": verified["origin_case_id"]}+ except BaseException:+ shutil.rmtree(staging, ignore_errors=True)+ if old.exists() and not case.path.exists():+ old.rename(case.path)+ raise+++def _remember_secret(job_id: str, password: str | None) -> None:+ if not password:+ return+ with _secret_lock:+ _job_secrets[job_id] = password+ while len(_job_secrets) > _MAX_MEMORY_JOBS:+ _job_secrets.pop(next(iter(_job_secrets)))+++def _take_secret(job_id: str) -> str | None:+ with _secret_lock:+ return _job_secrets.pop(job_id, None)+++def queue_export(case: Case, *, password: str | None = None) -> dict[str, Any]:+ """Queue an export without ever persisting its password."""+ sealed = bool(password)+ job = case.enqueue_job(+ EXPORT_JOB,+ payload={"sealed": sealed, "output": str(bundle_path(case, sealed=sealed))},+ max_attempts=1 if sealed else 3,+ )+ _remember_secret(job["id"], password)+ workqueue.wake(case)+ return job+++def queue_import(+ source: Path,+ *,+ password: str | None = None,+ cleanup_source: bool = False,+) -> tuple[Case, dict[str, Any]]:+ """Pre-flight, create the new case shell, then queue its import."""+ header = inspect_bundle(source, password=password)+ _require_import_space(Path(source), header)+ case = create_import_case(header["case_name"])+ job = case.enqueue_job(+ IMPORT_JOB,+ payload={+ "source": str(Path(source).expanduser()),+ "sealed": header["sealed"],+ "cleanup_source": cleanup_source,+ },+ max_attempts=1,+ )+ _remember_secret(job["id"], password)+ workqueue.wake(case)+ return case, job+++def job_status(case_id: str, job_id: str) -> dict[str, Any] | None:+ """Read a live durable job, or the terminal error of a removed import shell."""+ with _secret_lock:+ removed = _removed_jobs.get(job_id)+ if removed is not None and removed.get("case_id") == case_id:+ return dict(removed)+ try:+ case = Case.open(case_id)+ except CaseError:+ return None+ return case.get_job(job_id)+++def _handle_export(case: Case, job: dict[str, Any]) -> None:+ sealed = bool(job["payload"].get("sealed"))+ password = _take_secret(job["id"])+ if sealed and not password:+ raise workqueue.JobFailed("Password expired; restart the export")+ export_case(case, password=password, output=Path(job["payload"]["output"]))+++def _handle_import(case: Case, job: dict[str, Any]) -> None:+ sealed = bool(job["payload"].get("sealed"))+ source = Path(job["payload"]["source"])+ password = _take_secret(job["id"])+ try:+ if sealed and not password:+ error = "Password expired; restart the import"+ else:+ import_into(+ case,+ source,+ password=password,+ job=job,+ )+ return+ except Exception as exc:+ error = str(exc)+ finally:+ if job["payload"].get("cleanup_source"):+ source.unlink(missing_ok=True)+ with _secret_lock:+ _removed_jobs[job["id"]] = {+ **job,+ "case_id": case.id,+ "state": "failed",+ "error": error,+ }+ while len(_removed_jobs) > _MAX_MEMORY_JOBS:+ _removed_jobs.pop(next(iter(_removed_jobs)))+ case.delete()+ raise workqueue.JobRemoved(error)+++workqueue.register(EXPORT_JOB, _handle_export)+workqueue.register(IMPORT_JOB, _handle_import)diff --git a/src/azimut/engine/enrich.py b/src/azimut/engine/enrich.pyindex 4862960..eea9179 100644--- a/src/azimut/engine/enrich.py+++ b/src/azimut/engine/enrich.py@@ -394,9 +394,18 @@ def _suggest_place(case: "CaseType", entity_id: str, gps: dict[str, float]) -> Nis an attribute of the places enrichment mints; a place the analyst pinnedby hand has none and is left alone, because merging the two is a judgementthe Suggestions panel exists to let them make.++ A relation already stated for this media wins over a later backfill. This is+ especially important after importing a case from an older Azimut release:+ its media may need the current enrichment pass, but its confirmed+ ``Relate to`` choices are investigation state and must not return as a new+ GPS suggestion."""from . import satellite as satellite_engine+ if any(link["type"] == LOCATED_AT for link in case.links_of(entity_id)):+ return+key = f"{gps['lat']:.5f},{gps['lon']:.5f}"place = case.find_entity(attr="enrich_coord_key", value=key)if place is None:diff --git a/src/azimut/engine/links.py b/src/azimut/engine/links.pyindex 9b219b9..2bbbafd 100644--- a/src/azimut/engine/links.py+++ b/src/azimut/engine/links.py@@ -326,31 +326,55 @@ def tombstone_of(entity: dict[str, Any]) -> dict[str, Any]:return {k: v for k, v in fields.items() if v}-def add_tombstone(case: CaseRepository, entity_id: str, info: dict[str, Any]) -> None:+def add_tombstone(case: CaseRepository, entity_id: str, info: dict[str, Any]) -> bool:"""Record on an artifact that one of its sources is gone.Keyed by path, so re-saving or a second delete never stacks duplicates.+ False means this scar was already there — which is what the trash needs to+ know, so an undo only lifts the scars its own delete wrote."""- add_tombstones(case, entity_id, [info])+ return bool(add_tombstones(case, entity_id, [info]))-def add_tombstones(case: CaseRepository, entity_id: str, infos: list[dict[str, Any]]) -> None:- """Record several lost sources with one case read and at most one write."""+def add_tombstones(+ case: CaseRepository, entity_id: str, infos: list[dict[str, Any]]+) -> list[str]:+ """Record several lost sources with one case read and at most one write.++ Returns the paths actually written, skipping the ones already scarred.+ """if not infos:- return+ return []entity = _entity(case, entity_id)lost = list(entity.get("attrs", {}).get(LOST, []))paths = {item.get("path") for item in lost}- changed = False+ added: list[str] = []for info in infos:path = info.get("path")if path in paths:continuelost.append({**info, "at": info.get("at") or _now()})paths.add(path)- changed = True- if changed:+ added.append(str(path))+ if added:case.update_entity(entity_id, {"attrs": {LOST: lost}})+ return added+++def remove_tombstone(case: CaseRepository, entity_id: str, path: str) -> None:+ """Lift a scar, because the source it recorded came back.++ Keyed by path like `add_tombstone`, and silent when the entity or the scar is+ already gone: restoring a group whose survivor was deleted in the meantime is+ not an error, there is simply nothing left to unscar.+ """+ entity = case.get_entity(entity_id)+ if entity is None:+ return+ lost = list(entity.get("attrs", {}).get(LOST, []))+ kept = [item for item in lost if item.get("path") != path]+ if len(kept) != len(lost):+ case.update_entity(entity_id, {"attrs": {LOST: kept}})def losses(case: CaseRepository, doomed_ids: set[str]) -> dict[str, list[dict[str, Any]]]:diff --git a/src/azimut/engine/media.py b/src/azimut/engine/media.pyindex df81639..ac7d404 100644--- a/src/azimut/engine/media.py+++ b/src/azimut/engine/media.py@@ -813,21 +813,12 @@ def update_media(case: Case, rel_path: str, patch: dict[str, Any]) -> dict[str,def delete_media_files(case: Case, rel_path: str) -> None:"""Drop a media's file, sidecar and thumbnail, leaving its entity alone.- The entity side is the delete chokepoint's business (``api.cases``), which- has to tombstone the dependents before anything is removed.+ For a media the case never filed as an entity — the caller found no graph to+ honour and drops the files itself. What those files are is the artifact+ registry's answer, not this module's, so the two paths cannot drift; the+ entity side is the delete chokepoint's business (``api.cases``), which has to+ tombstone the dependents before anything is removed."""- media_path = case.resolve_inside(rel_path)- sidecar = _sidecar_path(media_path)- data = None- if sidecar.exists():- data = json.loads(sidecar.read_text(encoding="utf-8"))- case.remove_media_item(rel_path)- media_path.unlink(missing_ok=True)- sidecar.unlink(missing_ok=True)- if data and data.get("thumbnail"):- # Thumbnails are content-addressed, so identical-bytes captures can share- # one file (satellite re-captures dedupe to the same sha). Drop the cached- # thumbnail only when no surviving sidecar still points at it.- thumb = data["thumbnail"]- if not any(it.get("thumbnail") == thumb for it in list_media(case)):- case.resolve_inside(thumb).unlink(missing_ok=True)+ from . import artifacts++ artifacts.delete(case, {"type": "media", "attrs": {"path": rel_path}})diff --git a/src/azimut/engine/trash.py b/src/azimut/engine/trash.pynew file mode 100644index 0000000..16d11f7--- /dev/null+++ b/src/azimut/engine/trash.py@@ -0,0 +1,270 @@+"""Deleting an artifact stops being final.++The live graph keeps hard-deleting. What a delete leaves behind is a journal+row 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.++One row is one **delete action**, not one entity: deleting a video that carries+three Inspect sessions writes a single group, and restoring it brings the whole+cascade back at once.++What travels: everything the artifact registry says an entity owns. What does+not: thumbnails, which are a shared content-addressed cache — moving one aside+would blank a surviving row, so a delete drops it as before and a restore+re-queues it.+"""++from __future__ import annotations++import shutil+from pathlib import Path+from typing import Any++from ..workspace import Case, CaseError, _new_id, ensure_dir+from . import artifacts as artifact_engine+from . import links as link_engine+from . import thumbnails as thumbnail_engine+++def _group_dir(case: Case, group_id: str) -> Path:+ """The directory one delete action's files wait in.++ Resolved through the case so a group id from a request can never address+ anything outside it.+ """+ 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"{TRASH_DIR}/{group_id}")+++def _dir_size(path: Path) -> int:+ if not path.is_dir():+ return 0+ return sum(p.stat().st_size for p in path.rglob("*") if p.is_file())+++def _move(src: Path, dst: Path) -> None:+ """Move one path without ever overwriting an unrelated artifact."""+ ensure_dir(dst.parent)+ if dst.exists():+ raise CaseError(f"'{dst}' already exists")+ shutil.move(str(src), str(dst))+++def collect_links(case: Case, entity_ids: set[str]) -> list[dict[str, Any]]:+ """Every link incident to the group, deduped — chain edges *and* relations.++ Relations are the loss nothing else records: a derivation leaves a tombstone+ on the survivor, but "this photo was shot at this place" vanishes without a+ trace. So the payload carries all of them, and a restore puts back whichever+ still has both ends.+ """+ seen: dict[str, dict[str, Any]] = {}+ for entity_id in entity_ids:+ for link in case.links_of(entity_id):+ seen[link["id"]] = link+ return list(seen.values())+++def _travelling_files(case: Case, entities: list[dict[str, Any]]) -> list[str]:+ """Return existing owned paths without children already covered by a folder."""+ paths = list(+ dict.fromkeys(+ rel+ for entity in entities+ for rel in artifact_engine.owned(case, entity)+ )+ )+ kept: list[str] = []+ for rel in sorted(paths, key=lambda value: len(Path(value).parts)):+ parts = Path(rel).parts+ if any(parts[: len(Path(parent).parts)] == Path(parent).parts for parent in kept):+ continue+ kept.append(rel)+ return kept+++def send(+ case: Case,+ entities: list[dict[str, Any]],+ tombstones: list[dict[str, Any]],+) -> dict[str, Any]:+ """Journal a delete before changing files, indexes or graph rows."""+ with case.lock:+ group_id = _new_id("t")+ root = _group_dir(case, group_id)+ ids = {e["id"] for e in entities}+ links = collect_links(case, ids)+ files = _travelling_files(case, entities)+ target = entities[0]+ payload = {+ "entities": entities,+ "links": links,+ "files": files,+ "tombstones": tombstones,+ }+ group = case.add_trash_group(+ group_id,+ label=str(target.get("label") or target.get("id")),+ type_=str(target.get("type") or ""),+ item_count=len(entities),+ size_bytes=0,+ payload=payload,+ state="preparing",+ )+ try:+ for entity in entities:+ artifact_engine.unfile(case, entity)+ for rel in files:+ source = case.resolve_inside(rel)+ if source.exists():+ _move(source, root / rel)+ return case.update_trash_group(group_id, size_bytes=_dir_size(root))+ except Exception:+ _rollback_delete(case, group)+ raise+++def commit(case: Case, group_id: str) -> dict[str, Any]:+ """Publish a fully completed delete in the user-visible trash."""+ with case.lock:+ return case.update_trash_group(group_id, state="ready")+++def rollback(case: Case, group_id: str) -> None:+ """Undo a delete that did not reach its durable ready state."""+ with case.lock:+ group = case.get_trash_group(group_id)+ if group is not None:+ _rollback_delete(case, group)+++def restore(case: Case, group_id: str) -> dict[str, Any]:+ """Put one delete action back, all of it or none.++ In this order, because the order is the correctness:++ 1. every destination is checked free, then the files move back — a restore+ that would overwrite something refuses instead, naming the path, rather+ than renaming an artifact behind the analyst;+ 2. the entities come back with their original ids, since the delete freed+ them and every recorded path still points at them;+ 3. the links come back where both ends survived; the rest are counted and+ reported, not hidden;+ 4. the tombstones this delete wrote on survivors are lifted;+ 5. restored media are filed in the browse index again and their thumbnails+ re-queued, because a thumbnail was dropped rather than moved.+ """+ with case.lock:+ group = case.get_trash_group(group_id)+ if group is None or group.get("state") != "ready":+ 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()+ ]+ if occupied:+ raise CaseError(+ f"'{occupied[0]}' is back in the case; rename or delete it before restoring"+ )+ group = case.update_trash_group(group_id, state="restoring")+ return _finish_restore(case, group)+++def purge(case: Case, group_id: str) -> None:+ """Drop one group for good. The entity left the graph when it was deleted,+ so this is a directory and a row, never a second trip through the delete+ chokepoint."""+ with case.lock:+ group = case.get_trash_group(group_id)+ if group is None or group.get("state") != "ready":+ raise CaseError(f"trash group '{group_id}' not found")+ _drop_dir(case, group_id)+ case.remove_trash_group(group_id)+++def empty(case: Case) -> int:+ """Purge every group. Returns how many were dropped."""+ with case.lock:+ ids = [group["id"] for group in case.list_trash()]+ for group_id in ids:+ purge(case, group_id)+ return len(ids)+++def recover(case: Case) -> None:+ """Resolve interrupted filesystem operations whenever a case is opened."""+ with case.lock:+ for group in case.list_incomplete_trash():+ state = group.get("state")+ if state == "restoring":+ _finish_restore(case, group)+ continue+ if state != "preparing":+ raise CaseError(+ f"trash group '{group['id']}' has an unknown state '{state}'"+ )+ entities = list((group.get("payload") or {}).get("entities") or [])+ if any(case.get_entity(entity["id"]) is not None for entity in entities):+ _rollback_delete(case, group)+ else:+ case.update_trash_group(group["id"], state="ready")+++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+ destination = case.resolve_inside(rel)+ if source.exists():+ _move(source, destination)+ elif not destination.exists():+ raise CaseError(f"trash artifact '{rel}' is missing")+++def _restore_records(case: Case, group: dict[str, Any]) -> dict[str, int]:+ payload = group.get("payload") or {}+ entities: list[dict[str, Any]] = list(payload.get("entities") or [])+ result = case.reinsert(entities, list(payload.get("links") or []))+ for scar in payload.get("tombstones") or []:+ link_engine.remove_tombstone(case, scar["entity"], scar["path"])+ for entity in entities:+ refiled = artifact_engine.refile(case, entity)+ if refiled:+ thumbnail_engine.enqueue(case, refiled)+ return result+++def _finish_restore(case: Case, group: dict[str, Any]) -> dict[str, Any]:+ _restore_files(case, group)+ result = _restore_records(case, group)+ _drop_dir(case, group["id"])+ case.remove_trash_group(group["id"])+ return {"status": "restored", **result, "group": group["id"]}+++def _rollback_delete(case: Case, group: dict[str, Any]) -> None:+ _restore_files(case, group)+ _restore_records(case, group)+ _drop_dir(case, group["id"])+ case.remove_trash_group(group["id"])+++def _drop_dir(case: Case, group_id: str) -> None:+ """Remove one group's directory, and the trash root once it holds nothing —+ an emptied trash leaves a case exactly as it was born."""+ group = _group_dir(case, group_id)+ if group.exists():+ shutil.rmtree(group)+ root = case.trash_dir+ if root.is_dir() and not any(root.iterdir()):+ root.rmdir()diff --git a/src/azimut/engine/workqueue.py b/src/azimut/engine/workqueue.pyindex 43bf546..b4d92b3 100644--- a/src/azimut/engine/workqueue.py+++ b/src/azimut/engine/workqueue.py@@ -46,6 +46,10 @@ class JobFailed(Exception):"""The job failed this time and deserves another attempt."""+class JobRemoved(Exception):+ """The handler removed its owning case, so no row remains to settle."""++def register(kind: str, handler: Handler) -> None:HANDLERS[kind] = handler@@ -70,13 +74,16 @@ def has_queued(case: "CaseType") -> bool:return bool(case.list_jobs(state="queued"))-def _settle(case: "CaseType", job: dict[str, Any]) -> None:+def _settle(case: "CaseType", job: dict[str, Any]) -> bool:+ """Settle one job. ``True`` means the handler removed the owning case."""handler = HANDLERS.get(job["kind"])if handler is None:case.cancel_job(job["id"])- return+ return Falsetry:handler(case, job)+ except JobRemoved:+ return Trueexcept JobCancelled:case.cancel_job(job["id"])except JobFailed as exc:@@ -85,6 +92,7 @@ def _settle(case: "CaseType", job: dict[str, Any]) -> None:case.fail_job(job["id"], f"{type(exc).__name__}: {exc}")else:case.complete_job(job["id"])+ return Falsedef drain(case: "CaseType") -> int:@@ -96,8 +104,10 @@ def drain(case: "CaseType") -> int:job = case.claim_job()if job is None:return handled- _settle(case, job)+ removed = _settle(case, job)handled += 1+ if removed:+ return handled# -- the single background worker -----------------------------------------diff --git a/src/azimut/repository.py b/src/azimut/repository.pyindex dc828e7..fe7bde2 100644--- a/src/azimut/repository.py+++ b/src/azimut/repository.py@@ -223,6 +223,50 @@ class CaseRepository(Protocol):def remove_folder(self, name: str) -> list[str]:...+ # -- trash journal -----------------------------------------------------+ #+ # A delete keeps hard-deleting the graph rows and records the recipe to put+ # them back, one row per delete action. Nothing else in the app filters on a+ # "deleted" state, because nothing else has to know.++ def add_trash_group(+ self,+ group_id: str,+ *,+ label: str,+ type_: str,+ item_count: int,+ size_bytes: int,+ payload: dict[str, Any],+ ) -> dict[str, Any]:+ ...++ def list_trash(self) -> list[dict[str, Any]]:+ """Every group, newest first, without its payload."""+ ...++ def get_trash_group(self, group_id: str) -> dict[str, Any] | None:+ """One group with the payload needed to restore it, or None."""+ ...++ def remove_trash_group(self, group_id: str) -> None:+ ...++ def clear_trash(self) -> list[str]:+ """Drop every group, returning their ids."""+ ...++ def trash_summary(self) -> dict[str, int]:+ """``{"groups": n, "items": n, "size_bytes": n}`` in one query."""+ ...++ def reinsert(+ self, entities: list[dict[str, Any]], links: list[dict[str, Any]]+ ) -> dict[str, int]:+ """Re-insert deleted entities with their original ids, plus the links+ whose two endpoints still exist."""+ ...+# -- durable jobs ------------------------------------------------------## Local background work (thumbnails today; EXIF, OCR, transcripts later) that@@ -260,7 +304,7 @@ class CaseRepository(Protocol):) -> list[dict[str, Any]]:...- def count_jobs(self) -> dict[str, int]:+ def count_jobs(self, *, kind: str | None = None) -> dict[str, int]:...def recover_jobs(self) -> int:diff --git a/src/azimut/server.py b/src/azimut/server.pyindex b67f70e..a62a638 100644--- a/src/azimut/server.py+++ b/src/azimut/server.py@@ -99,6 +99,15 @@ def create_app() -> FastAPI:except OSError:pass+ # 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+# 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.diff --git a/src/azimut/sqlite_backend.py b/src/azimut/sqlite_backend.pyindex 52b2da4..773cc3b 100644--- a/src/azimut/sqlite_backend.py+++ b/src/azimut/sqlite_backend.py@@ -45,7 +45,10 @@ if TYPE_CHECKING:# `item_json` and need no column; presence does, because filtering "only the# files that carry a position" has to happen in SQL over the whole case rather# than in the page the client already holds.-SQLITE_SCHEMA = 5+# Schema 6 adds the `trash` journal: one row per delete action, holding the+# recipe to put it back. Schema 7 adds its recovery state so interrupted+# filesystem moves can be completed or rolled back on the next case open.+SQLITE_SCHEMA = 7_SCHEMA = """CREATE TABLE meta (@@ -93,6 +96,16 @@ CREATE TABLE jobs (created_at TEXT NOT NULL,updated_at TEXT NOT NULL);+CREATE TABLE trash (+ id TEXT PRIMARY KEY,+ deleted_at TEXT NOT NULL,+ label TEXT NOT NULL,+ type TEXT NOT NULL,+ item_count INTEGER NOT NULL DEFAULT 0,+ size_bytes INTEGER NOT NULL DEFAULT 0,+ state TEXT NOT NULL DEFAULT 'ready',+ payload_json TEXT NOT NULL DEFAULT '{}'+);CREATE TABLE media_items (path TEXT PRIMARY KEY,entity_id TEXT UNIQUE,@@ -124,6 +137,7 @@ CREATE INDEX idx_media_size ON media_items(size);CREATE INDEX idx_media_added ON media_items(added_at);CREATE INDEX idx_media_source ON media_items(source_type);CREATE INDEX idx_media_gps ON media_items(has_gps);+CREATE INDEX idx_trash_deleted ON trash(deleted_at);"""# Job lifecycle (doc "Job states"): a fresh job is `queued`; the worker claims it@@ -234,6 +248,30 @@ def _migrate_4_to_5(conn: sqlite3.Connection) -> None:conn.execute("CREATE INDEX idx_media_gps ON media_items(has_gps)")+def _migrate_5_to_6(conn: sqlite3.Connection) -> None:+ """Add the ``trash`` journal.++ One row per delete action, not per entity: deleting a video that carries+ three Inspect sessions writes a single group that comes back as a whole. The+ payload holds the recipe (entities, their incident links, the files moved+ aside, the tombstones the delete wrote); the head columns are what the+ sidebar node reads, so listing the trash never touches a payload.+ """+ conn.execute(+ "CREATE TABLE trash ("+ " id TEXT PRIMARY KEY, deleted_at TEXT NOT NULL, label TEXT NOT NULL,"+ " type TEXT NOT NULL, item_count INTEGER NOT NULL DEFAULT 0,"+ " size_bytes INTEGER NOT NULL DEFAULT 0,"+ " payload_json TEXT NOT NULL DEFAULT '{}')"+ )+ conn.execute("CREATE INDEX idx_trash_deleted ON trash(deleted_at)")+++def _migrate_6_to_7(conn: sqlite3.Connection) -> None:+ """Track interrupted delete and restore operations for crash recovery."""+ conn.execute("ALTER TABLE trash ADD COLUMN state TEXT NOT NULL DEFAULT 'ready'")++# from_version -> function(conn) applying the in-place upgrade to from_version + 1.# Runs inside one transaction per step in `SqliteCase._upgrade`, which stamps the# new schema_version and records the migration; the step only reshapes the db.@@ -242,6 +280,8 @@ _SQLITE_MIGRATIONS: dict[int, Callable[[sqlite3.Connection], None]] = {2: _migrate_2_to_3,3: _migrate_3_to_4,4: _migrate_4_to_5,+ 5: _migrate_5_to_6,+ 6: _migrate_6_to_7,}_MEDIA_CATEGORIES = (@@ -1291,6 +1331,213 @@ class SqliteCase:return self._write(op)+ # -- trash journal -----------------------------------------------------+ #+ # The live graph keeps hard-deleting: a deleted entity is gone from+ # `entities`, so no query anywhere needs a "not deleted" filter. What is kept+ # is the recipe to put it back, in one row per delete action.++ @staticmethod+ def _trash(row: sqlite3.Row, *, payload: bool = False) -> dict[str, Any]:+ group = {+ "id": row["id"],+ "deleted_at": row["deleted_at"],+ "label": row["label"],+ "type": row["type"],+ "item_count": row["item_count"],+ "size_bytes": row["size_bytes"],+ }+ if payload:+ group["state"] = row["state"]+ group["payload"] = json.loads(row["payload_json"])+ return group++ def add_trash_group(+ self,+ group_id: str,+ *,+ label: str,+ type_: str,+ item_count: int,+ size_bytes: int,+ payload: dict[str, Any],+ state: str = "ready",+ ) -> dict[str, Any]:+ """Record one delete action before its filesystem move begins."""+ now = _now()++ def op(conn: sqlite3.Connection) -> dict[str, Any]:+ conn.execute(+ "INSERT INTO trash"+ "(id, deleted_at, label, type, item_count, size_bytes, state, payload_json)"+ " VALUES(?, ?, ?, ?, ?, ?, ?, ?)",+ (+ group_id, now, label, type_, item_count, size_bytes,+ state,+ json.dumps(payload, ensure_ascii=False),+ ),+ )+ self._touch(conn)+ row = conn.execute("SELECT * FROM trash WHERE id = ?", (group_id,)).fetchone()+ return self._trash(row, payload=True)++ return self._write(op)++ def update_trash_group(+ self,+ group_id: str,+ *,+ state: str | None = None,+ size_bytes: int | None = None,+ payload: dict[str, Any] | None = None,+ ) -> dict[str, Any]:+ def op(conn: sqlite3.Connection) -> dict[str, Any]:+ row = conn.execute("SELECT * FROM trash WHERE id = ?", (group_id,)).fetchone()+ if row is None:+ raise CaseError(f"trash group '{group_id}' not found")+ conn.execute(+ "UPDATE trash SET state = ?, size_bytes = ?, payload_json = ? WHERE id = ?",+ (+ state if state is not None else row["state"],+ size_bytes if size_bytes is not None else row["size_bytes"],+ json.dumps(payload, ensure_ascii=False)+ if payload is not None+ else row["payload_json"],+ group_id,+ ),+ )+ self._touch(conn)+ updated = conn.execute("SELECT * FROM trash WHERE id = ?", (group_id,)).fetchone()+ return self._trash(updated, payload=True)++ return self._write(op)++ def list_trash(self) -> list[dict[str, Any]]:+ """Every group, newest first, without its payload — the sidebar node+ reads this and stays within the bounded-loading rule."""+ with self._connect() as conn:+ rows = conn.execute(+ "SELECT id, deleted_at, label, type, item_count, size_bytes"+ ", state FROM trash WHERE state = 'ready'"+ " ORDER BY deleted_at DESC, rowid DESC"+ ).fetchall()+ return [self._trash(r) for r in rows]++ def list_incomplete_trash(self) -> list[dict[str, Any]]:+ with self._connect() as conn:+ rows = conn.execute(+ "SELECT * FROM trash WHERE state != 'ready' ORDER BY deleted_at, rowid"+ ).fetchall()+ return [self._trash(row, payload=True) for row in rows]++ def get_trash_group(self, group_id: str) -> dict[str, Any] | None:+ """One group with its payload — read only when restoring or purging."""+ with self._connect() as conn:+ row = conn.execute("SELECT * FROM trash WHERE id = ?", (group_id,)).fetchone()+ return self._trash(row, payload=True) if row is not None else None++ def remove_trash_group(self, group_id: str) -> None:+ def op(conn: sqlite3.Connection) -> None:+ cur = conn.execute("DELETE FROM trash WHERE id = ?", (group_id,))+ if cur.rowcount == 0:+ raise CaseError(f"trash group '{group_id}' not found")+ self._touch(conn)++ self._write(op)++ def clear_trash(self) -> list[str]:+ """Drop every group, returning the ids so the caller can remove their+ directories."""++ def op(conn: sqlite3.Connection) -> list[str]:+ ids = [+ r["id"]+ for r in conn.execute("SELECT id FROM trash WHERE state = 'ready'")+ ]+ if ids:+ conn.execute("DELETE FROM trash WHERE state = 'ready'")+ self._touch(conn)+ return ids++ return self._write(op)++ def trash_summary(self) -> dict[str, int]:+ """Groups, items and bytes held — what the node shows, in one query."""+ with self._connect() as conn:+ row = conn.execute(+ "SELECT COUNT(*) AS groups, COALESCE(SUM(item_count), 0) AS items,"+ " COALESCE(SUM(size_bytes), 0) AS size"+ " FROM trash WHERE state = 'ready'"+ ).fetchone()+ return {+ "groups": int(row["groups"]),+ "items": int(row["items"]),+ "size_bytes": int(row["size"]),+ }++ def reinsert(+ self, entities: list[dict[str, Any]], links: list[dict[str, Any]]+ ) -> dict[str, int]:+ """Put deleted rows back with their original ids, in one transaction.++ The ids were freed by the delete, so they are taken again rather than+ minted — every path, spec and draft recorded elsewhere still points at+ them. A link is re-inserted only when both endpoints exist: foreign keys+ forbid the rest, and an endpoint deleted separately is a real loss, so it+ is counted and reported instead of hidden.+ """++ def op(conn: sqlite3.Connection) -> dict[str, int]:+ for entity in entities:+ attrs = entity.get("attrs") or {}+ prov = entity.get("provenance") or {}+ conn.execute(+ "INSERT OR REPLACE INTO entities"+ "(id, type, label, attrs_json, folder, search_text,"+ " prov_by, prov_at, prov_status, prov_source)"+ " VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",+ (+ entity["id"],+ entity["type"],+ entity["label"],+ json.dumps(attrs, ensure_ascii=False),+ _folder_of(attrs),+ _entity_search_text(entity["type"], entity["label"], attrs),+ prov.get("by", "user"),+ prov.get("at", _now()),+ prov.get("status", "confirmed"),+ prov.get("source"),+ ),+ )+ present = {+ r["id"]+ for r in conn.execute("SELECT id FROM entities")+ }+ kept = 0+ for link in links:+ if link["from"] not in present or link["to"] not in present:+ continue+ prov = link.get("provenance") or {}+ conn.execute(+ "INSERT OR REPLACE INTO links"+ "(id, from_id, to_id, type, prov_by, prov_at, prov_status, prov_source)"+ " VALUES(?, ?, ?, ?, ?, ?, ?, ?)",+ (+ link["id"], link["from"], link["to"], link["type"],+ prov.get("by", "user"), prov.get("at", _now()),+ prov.get("status", "confirmed"), prov.get("source"),+ ),+ )+ kept += 1+ self._touch(conn)+ return {+ "entities": len(entities),+ "links": kept,+ "links_lost": len(links) - kept,+ }++ return self._write(op)+# -- durable jobs (thumbnail and background-job model) -----------------def enqueue_job(@@ -1425,10 +1672,19 @@ class SqliteCase:rows = conn.execute(f"SELECT * FROM jobs{clause} ORDER BY rowid", params).fetchall()return [self._job(r) for r in rows]- def count_jobs(self) -> dict[str, int]:+ def count_jobs(self, *, kind: str | None = None) -> dict[str, int]:"""Per-state job counts — the queue's badge without listing every row."""with self._connect() as conn:- rows = conn.execute("SELECT state, COUNT(*) AS n FROM jobs GROUP BY state").fetchall()+ if kind is None:+ rows = conn.execute(+ "SELECT state, COUNT(*) AS n FROM jobs GROUP BY state"+ ).fetchall()+ else:+ rows = conn.execute(+ "SELECT state, COUNT(*) AS n FROM jobs"+ " WHERE kind = ? GROUP BY state",+ (kind,),+ ).fetchall()return {r["state"]: r["n"] for r in rows}def recover_jobs(self) -> int:diff --git a/src/azimut/workspace.py b/src/azimut/workspace.pyindex 7a70eaa..7ebb5c5 100644--- a/src/azimut/workspace.py+++ b/src/azimut/workspace.py@@ -4,11 +4,12 @@ A case is a plain directory (spec §4):<case>/├── case.json # case manifest- ├── case.db # entities, links, folders and jobs+ ├── 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+ ├── exports/ # post drafts, reports+ └── .trash/ # deleted artifacts, one directory per delete actionOne-shot mode uses the same layout under ``scratch/`` and can be promoted into``cases/`` (spec §3.3).@@ -36,6 +37,11 @@ if TYPE_CHECKING: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.#@@ -273,6 +279,9 @@ class Case:if (path / "case.json").exists():case = cls(path)case.migrate()+ from .engine import trash as trash_engine++ trash_engine.recover(case)return caseraise CaseError(f"case '{case_id}' not found")@@ -350,7 +359,13 @@ class Case:renames into place (``engine/media._write_sidecar``); a power cut in thatwindow strands one, and treating it as content would keep an otherwiseempty scratch case alive forever.++ The trash does count. What is in it was content a moment ago and can be+ brought back, so reaping the case around it would delete recoverable work+ without anyone asking."""+ if (path / TRASH_DIR).is_dir() and any((path / TRASH_DIR).iterdir()):+ return Truefor sub in CASE_SUBDIRS:directory = path / subif not directory.is_dir():@@ -816,6 +831,74 @@ class Case:def remove_folder(self, name: str) -> list[str]:return self._graph().remove_folder(name)+ # -- trash journal (engine/trash.py owns the files) ----------------------++ def add_trash_group(+ self,+ group_id: str,+ *,+ label: str,+ type_: str,+ item_count: int,+ size_bytes: int,+ payload: dict[str, Any],+ state: str = "ready",+ ) -> dict[str, Any]:+ return self._graph().add_trash_group(+ group_id,+ label=label,+ type_=type_,+ item_count=item_count,+ size_bytes=size_bytes,+ payload=payload,+ state=state,+ )++ def update_trash_group(+ self,+ group_id: str,+ *,+ state: str | None = None,+ size_bytes: int | None = None,+ payload: dict[str, Any] | None = None,+ ) -> dict[str, Any]:+ return self._graph().update_trash_group(+ group_id,+ state=state,+ size_bytes=size_bytes,+ payload=payload,+ )++ def list_trash(self) -> list[dict[str, Any]]:+ return self._graph().list_trash()++ def get_trash_group(self, group_id: str) -> dict[str, Any] | None:+ return self._graph().get_trash_group(group_id)++ def list_incomplete_trash(self) -> list[dict[str, Any]]:+ return self._graph().list_incomplete_trash()++ def remove_trash_group(self, group_id: str) -> None:+ self._graph().remove_trash_group(group_id)++ def clear_trash(self) -> list[str]:+ return self._graph().clear_trash()++ def trash_summary(self) -> dict[str, int]:+ return self._graph().trash_summary()++ def reinsert(+ self, entities: list[dict[str, Any]], links: list[dict[str, Any]]+ ) -> dict[str, int]:+ return self._graph().reinsert(entities, links)++ @property+ def trash_dir(self) -> Path:+ """Where deleted artifacts wait. Hidden, at the case root, and never a+ `CASE_SUBDIRS` member: nothing that walks a case's content should walk+ into it."""+ return self.path / TRASH_DIR+# -- durable jobs (thumbnail and background-job model) -------------------def enqueue_job(@@ -850,8 +933,8 @@ class Case:) -> list[dict[str, Any]]:return self._graph().list_jobs(kind=kind, state=state)- def count_jobs(self) -> dict[str, int]:- return self._graph().count_jobs()+ def count_jobs(self, *, kind: str | None = None) -> dict[str, int]:+ return self._graph().count_jobs(kind=kind)def recover_jobs(self) -> int:return self._graph().recover_jobs()diff --git a/tests/fullcase.py b/tests/fullcase.pynew file mode 100644index 0000000..7f30f8c--- /dev/null+++ b/tests/fullcase.py@@ -0,0 +1,200 @@+"""One case holding an artifact from every tool, built through the real API.++The gates that keep the trash and the bundle honest all need the same thing: a+case that actually contains what a case can contain. Building it once, through+the endpoints the app itself serves, is what makes those gates cheap — a new+tool adds its artifact here and the gates cover it for free.++Nothing is written by hand. If a tool changes where it files its work, this+fixture changes with it, and the gates read the result rather than a+hand-maintained list of paths.++Standard library plus Pillow, and it lives under ``tests/`` so hatchling never+packages it into the wheel or the frozen binaries.+"""++from __future__ import annotations++import base64+import hashlib+import io+from dataclasses import dataclass, field++from PIL import Image+++def _png(size: tuple[int, int] = (80, 60), color: tuple[int, int, int] = (120, 60, 30)) -> bytes:+ buf = io.BytesIO()+ Image.new("RGB", size, color).save(buf, "PNG")+ return buf.getvalue()+++@dataclass+class FullCase:+ """What was planted, so a gate can name it rather than rediscover it."""++ case_id: str+ photo: str = ""+ piece: str = ""+ collage: str = ""+ capture: str = ""+ session: str = ""+ proof: str = ""+ proof_asset: str = ""+ draft: str = ""+ note_id: str = ""+ place_id: str = ""+ grid: str = ""+ entity_types: set[str] = field(default_factory=set)+++def build_full_case(client, name: str = "Full case") -> FullCase:+ """Fill one case through every tool that files an artifact.++ Returns once the background queue is idle, so a caller can move or delete the+ case directory without racing an enrichment or a thumbnail write.+ """+ from azimut.engine import workqueue++ case_id = client.post("/api/cases", json={"name": name}).json()["id"]+ full = FullCase(case_id=case_id)++ # -- media: two uploads, and a collage composed from both ----------------+ def upload(filename: str, data: bytes) -> str:+ res = client.post(+ f"/api/cases/{case_id}/media/upload",+ files={"file": (filename, io.BytesIO(data), "image/png")},+ )+ assert res.status_code == 200, res.text+ return res.json()["item"]["path"]++ full.photo = upload("photo.png", _png(color=(10, 20, 30)))+ full.piece = upload("piece.png", _png(color=(200, 100, 50), size=(60, 60)))++ collage = client.post(+ f"/api/cases/{case_id}/inspect/compose",+ json={+ "width": 200,+ "height": 120,+ "nodes": [+ {"src": {"path": full.photo},+ "quad": [[5, 5], [95, 5], [95, 110], [5, 110]]},+ {"src": {"path": full.piece},+ "quad": [[105, 5], [195, 5], [195, 110], [105, 110]]},+ ],+ "label": "Collage",+ },+ )+ assert collage.status_code == 200, collage.text+ full.collage = collage.json()["item"]["path"]++ # -- capture: a screenshot, which needs no network ------------------------+ client.put("/api/settings/keys", json={"google_js": "AIza.js"})+ shot = client.post(+ f"/api/cases/{case_id}/satellite/screenshot",+ files={"image": ("shot.png", _png(color=(40, 80, 40)), "image/png")},+ data={"lat": "48.8584", "lon": "2.2945", "zoom": "18",+ "provider": "google-js", "bearing": "45"},+ )+ assert shot.status_code == 200, shot.text+ full.capture = client.get(f"/api/cases/{case_id}/satellite").json()[0]["path"]++ # -- inspect session: adjustments over the photo (depends-on) -------------+ session = client.post(+ f"/api/cases/{case_id}/inspect/sessions",+ json={+ "title": "Photo pass",+ "spec": {"source": {"path": full.photo}, "ops": [+ {"op": "brightness", "params": {"value": 1.2}}+ ]},+ },+ )+ assert session.status_code == 200, session.text+ full.session = f"inspect/{session.json()['name']}.json"++ # -- a place, and a relation to the photo ---------------------------------+ place = client.post(+ f"/api/cases/{case_id}/satellite/place",+ json={"lat": 48.8584, "lon": 2.2945, "zoom": 17, "title": "Tower"},+ )+ assert place.status_code == 200, place.text+ full.place_id = place.json()["id"]+ photo_entity = client.get(+ f"/api/cases/{case_id}/entities/lookup", params={"attr": "path", "value": full.photo}+ ).json()["entity"]+ related = client.post(+ f"/api/cases/{case_id}/links",+ json={"from_id": photo_entity["id"], "to_id": full.place_id, "type": "located-at"},+ )+ assert related.status_code == 200, related.text++ # -- proof: one panel from the case, one pasted image ---------------------+ pasted = _png(size=(40, 30), color=(220, 220, 40))+ asset_name = f"{hashlib.sha256(pasted).hexdigest()[:16]}.png"+ proof = client.post(+ f"/api/cases/{case_id}/proofs",+ json={+ "title": "Convoy proof",+ "png_base64": base64.b64encode(_png(size=(200, 120))).decode(),+ "spec": {+ "panels": [{"id": "p0", "src": full.photo, "natural": [80, 60]}],+ "shapes": [],+ "pastes": [{"id": "x0", "asset": asset_name, "natural": [40, 30],+ "x": 10, "y": 10, "scale": 1}],+ },+ "assets": [{"name": asset_name, "data": base64.b64encode(pasted).decode()}],+ },+ )+ assert proof.status_code == 200, proof.text+ full.proof = proof.json()["spec_path"]+ full.proof_asset = f"proofs/{proof.json()['name']}.assets/{asset_name}"++ # -- post: derived from the proof and the photo ---------------------------+ draft = client.post(+ f"/api/cases/{case_id}/drafts",+ json={+ "title": "Thread draft",+ "state": {"proofPng": proof.json()["png"], "mediaPaths": [full.photo]},+ },+ )+ assert draft.status_code == 200, draft.text+ full.draft = draft.json()["draft"]++ # -- a filed note, the free-form notes, a folder, and a saved grid --------+ client.post(f"/api/cases/{case_id}/folders", json={"name": "Sources/Telegram"})+ note = client.post(+ f"/api/cases/{case_id}/notes",+ json={"title": "Witness", "folder": "Sources/Telegram", "content": "# Witness\n"},+ )+ assert note.status_code == 200, note.text+ full.note_id = note.json()["id"]+ client.put(f"/api/cases/{case_id}/notes", json={"text": "# Full case\n\nRunning notes.\n"})++ grid = client.put(+ f"/api/cases/{case_id}/search-grids/north-sweep",+ json={+ "title": "North sweep",+ "spec": {+ "azimut_grid": 1,+ "cell_m": 500,+ "anchor": {"lat": 48.0, "lon": 2.0},+ "lat_step": 0.0045,+ "lon_step": 0.0067,+ "aoi": {"type": "rect",+ "bounds": {"south": 48.0, "west": 2.0, "north": 48.02, "east": 2.02}},+ "statuses": {"0:0": "cleared"},+ },+ },+ )+ assert grid.status_code == 200, grid.text+ full.grid = f"search/{grid.json()['name']}.json"++ # Enrichment and thumbnails were queued along the way; let them land, or the+ # caller's first delete races a background write into the same case.+ workqueue.wait_until_idle(timeout=20)++ entities = client.get(+ f"/api/cases/{case_id}/catalog/entities", params={"limit": 500}+ ).json()["items"]+ full.entity_types = {e["type"] for e in entities}+ return fulldiff --git a/tests/test_artifacts.py b/tests/test_artifacts.pynew file mode 100644index 0000000..3bbb766--- /dev/null+++ b/tests/test_artifacts.py@@ -0,0 +1,116 @@+"""The artifact registry, and the gates that keep it honest.++Two rules a later tool inherits without doing anything:++- whatever it files, deleting it leaves the case as it was born — no orphan+ beside a deleted proof, no folder nothing points at;+- whatever entity type it introduces has said what it owns on disk, or said it+ owns nothing and why.++Both read `tests/fullcase.py`, so a new tool is covered by adding its artifact+there.+"""++from pathlib import Path++import fullcase+from azimut.engine import artifacts+from azimut.workspace import Case++# The thumbnail cache is content-addressed, budgeted and regenerated on demand,+# and the bundle leaves it out for the same reason: it is not case content. The+# tree comparison below skips it rather than pretending it is.+CACHE = "media/.thumbs"+++def tree(root: Path) -> set[str]:+ """Every path under a case directory, as case-relative posix strings."""+ out = set()+ for path in root.rglob("*"):+ rel = path.relative_to(root).as_posix()+ if rel == CACHE or rel.startswith(CACHE + "/"):+ continue+ out.add(rel)+ return out+++def delete_everything(client, case_id: str) -> None:+ """Delete every entity through the chokepoint, cascades included."""+ for _ in range(50):+ entities = client.get(+ f"/api/cases/{case_id}/catalog/entities", params={"limit": 500}+ ).json()["items"]+ if not entities:+ return+ for entity in entities:+ # A cascade may already have taken it; a 404 is that, not a failure.+ client.delete(f"/api/cases/{case_id}/entities/{entity['id']}")+ raise AssertionError("entities kept coming back")+++def test_deleting_everything_returns_the_case_to_its_birth_state(client):+ """The gate. One artifact per tool goes in, everything is deleted, and what+ is left has to be a fresh case — byte-for-byte in shape, if not in content.++ This is what catches the file a later tool forgets to declare: an orphan is+ invisible in the UI and shows up here as one extra path.+ """+ full = fullcase.build_full_case(client)+ born = Case.open(client.post("/api/cases", json={"name": "Newborn"}).json()["id"])++ delete_everything(client, full.case_id)+ # Grids are not entities, so nothing deletes them for us (a gap the trash+ # work records rather than closes).+ client.delete(f"/api/cases/{full.case_id}/search-grids/north-sweep")+ # Deleting is reversible now, so the bytes are still in the trash: this is+ # the second half of the gate, and where they are actually reclaimed.+ client.delete(f"/api/cases/{full.case_id}/trash")++ emptied = Case.open(full.case_id)+ assert tree(emptied.path) == tree(born.path)+++def test_deleting_a_proof_takes_its_pasted_images(client):+ """The leak this registry closed: the sidebar delete knew the spec and the+ export, and left ``proofs/<name>.assets/`` behind with the pastes inside."""+ full = fullcase.build_full_case(client)+ case = Case.open(full.case_id)+ assets = case.resolve_inside(full.proof_asset).parent+ assert assets.is_dir()++ entity = client.get(+ f"/api/cases/{full.case_id}/entities/lookup",+ params={"attr": "spec", "value": full.proof},+ ).json()["entity"]+ client.delete(f"/api/cases/{full.case_id}/entities/{entity['id']}")++ assert not assets.exists()+ assert not case.resolve_inside(full.proof).exists()+++def test_every_type_in_a_full_case_declares_what_it_owns(client):+ """A type in neither table is not a decision, it is an oversight — the next+ tool declares its files in ``KINDS`` or declares it has none in ``NO_FILES``,+ with the reason beside it."""+ full = fullcase.build_full_case(client)++ undeclared = {t for t in full.entity_types if not artifacts.declares(t)}+ assert not undeclared, f"entity types that never say what they own: {sorted(undeclared)}"+ assert all(reason for reason in artifacts.NO_FILES.values())+++def test_the_registry_answers_for_one_media_and_its_companions(client):+ """What ``owned`` returns is what moves; what ``caches`` returns is what is+ dropped and regenerated. A media has all three."""+ full = fullcase.build_full_case(client)+ case = Case.open(full.case_id)+ entity = client.get(+ f"/api/cases/{full.case_id}/entities/lookup",+ params={"attr": "path", "value": full.photo},+ ).json()["entity"]++ owned = artifacts.owned(case, entity)+ assert owned[0] == full.photo+ assert full.photo + ".azimut.json" in owned+ assert 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_bulk_trash.py b/tests/test_bulk_trash.pynew file mode 100644index 0000000..a1fca66--- /dev/null+++ b/tests/test_bulk_trash.py@@ -0,0 +1,94 @@+"""A multi-selection is one delete action and one restore group."""++import shutil++import pytest++from azimut.api.cases import delete_entities_deep+from azimut.engine import trash+from azimut.workspace import Case+++def test_multi_delete_is_one_trash_group(tmp_workspace):+ case = Case.create("Bulk delete")+ first = case.create_note("First", "", "one")+ second = case.create_note("Second", "", "two")++ deleted = delete_entities_deep(case, [first["id"], second["id"]])++ assert set(deleted["deleted"]) == {first["id"], second["id"]}+ groups = case.list_trash()+ assert len(groups) == 1+ assert groups[0]["item_count"] == 2+ assert not case.resolve_inside(first["attrs"]["path"]).exists()+ assert not case.resolve_inside(second["attrs"]["path"]).exists()++ restored = trash.restore(case, deleted["trash"])+ assert restored["entities"] == 2+ assert case.resolve_inside(first["attrs"]["path"]).read_text(encoding="utf-8") == "one"+ assert case.resolve_inside(second["attrs"]["path"]).read_text(encoding="utf-8") == "two"+++def test_recovery_rolls_back_an_interrupted_delete(tmp_workspace):+ case = Case.create("Interrupted delete")+ note = case.create_note("Note", "", "kept")++ group = trash.send(case, [note], [])+ assert case.list_trash() == []+ assert not case.resolve_inside(note["attrs"]["path"]).exists()++ trash.recover(case)++ assert case.get_entity(note["id"]) is not None+ assert case.resolve_inside(note["attrs"]["path"]).read_text(encoding="utf-8") == "kept"+ assert case.get_trash_group(group["id"]) is None+++def test_recovery_publishes_a_delete_after_the_graph_rows_are_gone(tmp_workspace):+ case = Case.create("Interrupted commit")+ note = case.create_note("Note", "", "kept")++ group = trash.send(case, [note], [])+ case.remove_entity(note["id"])+ trash.recover(case)++ assert case.get_entity(note["id"]) is None+ assert case.list_trash()[0]["id"] == group["id"]+ assert not case.resolve_inside(note["attrs"]["path"]).exists()+++def test_recovery_finishes_a_partially_moved_restore(tmp_workspace):+ case = Case.create("Interrupted restore")+ note = case.create_note("Note", "", "kept")+ deleted = delete_entities_deep(case, [note["id"]])+ rel = note["attrs"]["path"]+ source = case.trash_dir / deleted["trash"] / rel+ destination = case.resolve_inside(rel)++ case.update_trash_group(deleted["trash"], state="restoring")+ destination.parent.mkdir(parents=True, exist_ok=True)+ shutil.move(source, destination)+ trash.recover(case)++ assert case.get_entity(note["id"]) is not None+ assert destination.read_text(encoding="utf-8") == "kept"+ assert case.get_trash_group(deleted["trash"]) is None+++def test_purge_keeps_the_journal_when_windows_refuses_the_delete(+ tmp_workspace, monkeypatch+):+ case = Case.create("Locked trash")+ note = case.create_note("Note", "", "kept")+ deleted = delete_entities_deep(case, [note["id"]])++ with monkeypatch.context() as patch:+ patch.setattr(+ trash.shutil,+ "rmtree",+ lambda _path, **_kwargs: (_ for _ in ()).throw(PermissionError("locked")),+ )+ with pytest.raises(PermissionError, match="locked"):+ trash.purge(case, deleted["trash"])++ assert case.list_trash()[0]["id"] == deleted["trash"]diff --git a/tests/test_bundles.py b/tests/test_bundles.pynew file mode 100644index 0000000..0121d8a--- /dev/null+++ b/tests/test_bundles.py@@ -0,0 +1,446 @@+"""Portable case bundles: contents, integrity, encryption and round trip."""++from __future__ import annotations++import json+import os+import sqlite3+import zipfile+from contextlib import closing+from io import BytesIO+from pathlib import Path+from types import SimpleNamespace++import pytest++from azimut import config+from azimut.engine import bundles, workqueue+from azimut.workspace import Case+++def bundle_case(tmp_workspace, monkeypatch) -> Case:+ monkeypatch.setattr(workqueue, "start_workers", False)+ case = Case.create("Source 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.add_trash_group(+ "old",+ label="Gone",+ type_="note",+ item_count=1,+ size_bytes=4,+ payload={},+ )+ case.enqueue_job("test-pending", payload={"machine": "local"})+ return case+++def test_clean_database_closes_every_sqlite_handle(monkeypatch, tmp_path):+ connections: list[SimpleNamespace] = []++ def connect(_path):+ connection = SimpleNamespace(closed=False)+ connection.backup = lambda _target: None+ connection.execute = lambda _sql: None+ connection.commit = lambda: None+ connection.close = lambda: setattr(connection, "closed", True)+ connections.append(connection)+ return connection++ monkeypatch.setattr(bundles.sqlite3, "connect", connect)++ bundles._clean_database(tmp_path / "source.db", tmp_path / "target.db")++ assert len(connections) == 3+ assert all(connection.closed for connection in connections)+++def test_plain_bundle_has_ordered_manifests_and_a_clean_database(bundle_case):+ exported = bundles.export_case(bundle_case)++ assert exported.parent == config.bundles_dir()+ assert exported.name.endswith(".azimut.zip")+ with zipfile.ZipFile(exported) as archive:+ names = archive.namelist()+ assert names[0] == bundles.HEADER_NAME+ assert 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)++ 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"))+ with closing(sqlite3.connect(extracted)) as conn:+ assert conn.execute("SELECT COUNT(*) FROM trash").fetchone()[0] == 0+ assert conn.execute(+ "SELECT COUNT(*) FROM jobs WHERE state IN ('queued', 'running')"+ ).fetchone()[0] == 0+++def test_sealed_bundle_hides_the_zip_and_rejects_a_wrong_password(bundle_case):+ exported = bundles.export_case(bundle_case, password="correct horse")++ assert exported.name.endswith(".azimut.enc")+ assert exported.read_bytes().startswith(bundles.MAGIC)+ assert not exported.read_bytes().startswith(b"PK")+ inspected = bundles.inspect_bundle(exported, password="correct horse")+ assert inspected["sealed"] is True+ assert inspected["case_name"] == "Source case"+ assert inspected["space_ok"] is True+ assert inspected["estimated_import_bytes"] >= inspected["total_size"]+ assert inspected["free_space_bytes"] > inspected["space_reserve_bytes"]+ with pytest.raises(bundles.BundleError, match="wrong password"):+ bundles.inspect_bundle(exported, password="wrong")++ hostile = config.bundles_dir() / "hostile-kdf.azimut.enc"+ data = bytearray(exported.read_bytes())+ data[16] = 31 # log2(n), authenticated only after key derivation+ hostile.write_bytes(data)+ with pytest.raises(bundles.BundleError, match="key parameters"):+ bundles.inspect_bundle(hostile, password="correct horse")+++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)+ exported = bundles.export_case(bundle_case, password="secret")+ truncated = config.bundles_dir() / "truncated.azimut.enc"+ truncated.write_bytes(exported.read_bytes()[:-1])+ destination = Case.create("Truncated import")++ with pytest.raises(bundles.BundleError, match="damaged|incomplete"):+ bundles.import_into(destination, truncated, password="secret")++ assert destination.path.exists()+ assert destination.list_entities() == []++[email protected]("password", [None, "bundle secret"])+def test_export_import_round_trip_creates_a_new_case(bundle_case, password):+ exported = bundles.export_case(bundle_case, password=password)+ destination = Case.create(bundles.imported_name("Source case"))++ result = bundles.import_into(destination, exported, password=password)+ imported = Case.open(result["case_id"])++ assert imported.id != bundle_case.id+ assert imported.read()["name"] == "Source case (imported)"+ 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:+ meta = dict(conn.execute("SELECT key, value FROM meta"))+ assert meta["origin_case_id"] == bundle_case.id+ assert meta["imported_at"]+++def test_export_import_round_trip_keeps_confirmed_relations(bundle_case):+ media = bundle_case.add_entity(+ "media",+ "GPS photo",+ {"path": "media/gps-photo.jpg"},+ by="user",+ )+ place = bundle_case.add_entity(+ "place",+ "Chosen place",+ {"lat": 48.858333, "lon": 2.350833},+ by="user",+ )+ relation = bundle_case.add_link(+ media["id"],+ place["id"],+ "located-at",+ by="user",+ status="confirmed",+ )++ exported = bundles.export_case(bundle_case)+ destination = Case.create(bundles.imported_name("Source case"))+ imported = Case.open(bundles.import_into(destination, exported)["case_id"])++ assert imported.get_link(relation["id"]) == relation+ assert imported.get_link(relation["id"])["provenance"]["status"] == "confirmed"+++def test_manifest_is_an_allowlist_not_a_hint(bundle_case):+ exported = bundles.export_case(bundle_case)+ tampered = config.bundles_dir() / "tampered.azimut.zip"+ with zipfile.ZipFile(exported) as source, zipfile.ZipFile(tampered, "w") as target:+ for info in source.infolist()[:-1]:+ target.writestr(info, source.read(info))+ target.writestr("stowaway.txt", b"not declared")+ target.writestr(source.infolist()[-1], source.read(source.infolist()[-1]))++ destination = Case.create("Tampered import")+ with pytest.raises(bundles.BundleError, match="undeclared|do not match"):+ bundles.import_into(destination, tampered)+++def test_manifest_sizes_are_checked_before_extraction(bundle_case):+ exported = bundles.export_case(bundle_case)+ tampered = config.bundles_dir() / "wrong-size.azimut.zip"+ 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")+ record["size"] += 1+ for info in infos[:-1]:+ target.writestr(info, source.read(info))+ target.writestr(infos[-1], json.dumps(manifest).encode())++ destination = Case.create("Wrong size import")+ with pytest.raises(bundles.BundleError, match="manifest member"):+ bundles.import_into(destination, tampered)++ assert destination.list_entities() == []+++def test_bundle_header_bounds_names_and_total_sizes():+ base = {+ "format_version": bundles.BUNDLE_FORMAT,+ "case_db_schema": bundles.SQLITE_SCHEMA,+ "case_name": "Case",+ "origin_case_id": "case",+ "total_size": 0,+ }+ with pytest.raises(bundles.BundleError, match="case name"):+ bundles._validate_header({**base, "case_name": "x" * (bundles.MAX_CASE_NAME + 1)})+ with pytest.raises(bundles.BundleError, match="total size"):+ bundles._validate_header({**base, "total_size": -1})+ with pytest.raises(bundles.BundleError, match="total size"):+ bundles._validate_header({**base, "total_size": bundles.MAX_DECLARED_SIZE + 1})+++ "names",+ [+ ["case.json", "media/../case.db"],+ ["case.json", "media/./photo.jpg"],+ ["case.json", "media/photo.jpg", "media//photo.jpg"],+ ["case.json", "media/CON.txt"],+ ["case.json", "media/photo:stream"],+ ["case.json", "media/photo. "],+ ],+)+def test_bundle_member_names_are_safe_on_every_supported_os(names):+ with pytest.raises(bundles.BundleError, match="not portable"):+ bundles._validate_member_names(names)+++def test_bundle_members_cannot_alias_on_case_insensitive_filesystems():+ with pytest.raises(bundles.BundleError, match="collide"):+ bundles._validate_member_names(["media/Photo.jpg", "media/photo.jpg"])+++def test_import_space_is_dynamic_instead_of_a_small_fixed_bundle_cap(+ bundle_case, monkeypatch+):+ exported = bundles.export_case(bundle_case)+ total = 40 * 1024 * 1024 * 1024+ free = 30 * 1024 * 1024 * 1024+ monkeypatch.setattr(+ bundles.shutil,+ "disk_usage",+ lambda _path: SimpleNamespace(total=total, used=total - free, free=free),+ )++ preview = bundles.inspect_bundle(exported)+ assert preview["large_bundle"] is False+ assert preview["space_ok"] is True++ free = preview["total_size"] + preview["space_reserve_bytes"] - 1+ monkeypatch.setattr(+ bundles.shutil,+ "disk_usage",+ lambda _path: SimpleNamespace(total=total, used=total - free, free=free),+ )+ preview = bundles.inspect_bundle(exported)+ assert preview["space_ok"] is False+ with pytest.raises(bundles.BundleError, match="not enough free space"):+ bundles.queue_import(exported)+++def test_staged_upload_stops_before_consuming_the_disk_reserve(+ tmp_workspace, monkeypatch+):+ total = 10 * 1024 * 1024 * 1024+ reserve = bundles._disk_reserve(total)+ monkeypatch.setattr(+ bundles.shutil,+ "disk_usage",+ lambda _path: SimpleNamespace(total=total, used=total - reserve - 3, free=reserve + 3),+ )++ with pytest.raises(bundles.BundleError, match="not enough free space"):+ bundles.stage_upload(BytesIO(b"four"))++ imports = config.bundles_dir() / ".imports"+ assert list(imports.glob("*")) == []+++def test_export_stops_before_consuming_the_disk_reserve(bundle_case, monkeypatch):+ total = 10 * 1024 * 1024 * 1024+ reserve = bundles._disk_reserve(total)+ monkeypatch.setattr(+ bundles.shutil,+ "disk_usage",+ lambda _path: SimpleNamespace(total=total, used=total - reserve, free=reserve),+ )++ with pytest.raises(bundles.BundleError, match="not enough free space"):+ bundles.export_case(bundle_case)++ assert not any(config.bundles_dir().glob("*.tmp"))+++def test_every_top_level_case_entry_has_a_bundle_decision(bundle_case):+ assert all(+ bundles.classify_case_entry(path.name) is not None+ for path in bundle_case.path.iterdir()+ )+++def test_export_cannot_escape_the_workspace_bundle_directory(bundle_case, tmp_path):+ with pytest.raises(bundles.BundleError, match="must stay"):+ bundles.export_case(bundle_case, output=tmp_path / "outside.azimut.zip")+++def test_passwords_never_enter_durable_job_payloads(bundle_case):+ export_job = bundles.queue_export(bundle_case, password="export secret")+ source = bundles.export_case(bundle_case, password="import secret")+ imported, import_job = bundles.queue_import(source, password="import secret")++ assert export_job["payload"]["sealed"] is True+ assert "password" not in export_job["payload"]+ assert import_job["payload"]["sealed"] is True+ assert "password" not in import_job["payload"]+ with closing(sqlite3.connect(bundle_case.path / "case.db")) 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:+ import_payload = conn.execute(+ "SELECT payload_json FROM jobs WHERE id = ?", (import_job["id"],)+ ).fetchone()[0]+ assert "export secret" not in export_payload+ assert "import secret" not in import_payload+++def test_durable_export_and_import_jobs_finish_on_the_case_queue(bundle_case):+ export_job = bundles.queue_export(bundle_case)+ assert workqueue.drain(bundle_case) >= 1+ exported = Path(export_job["payload"]["output"])+ assert exported.is_file()+ assert bundle_case.get_job(export_job["id"])["state"] == "ready"++ imported, import_job = bundles.queue_import(exported)+ assert workqueue.drain(imported) == 1+ restored = Case.open(imported.id)+ assert restored.get_job(import_job["id"])["state"] == "ready"+ assert [entity["label"] for entity in restored.list_entities()] == ["Witness"]+++def test_a_failed_import_removes_its_empty_case_shell(bundle_case):+ exported = bundles.export_case(bundle_case)+ tampered = config.bundles_dir() / "broken.azimut.zip"+ data = bytearray(exported.read_bytes())+ data[len(data) // 2] ^= 0xFF+ tampered.write_bytes(data)++ imported, job = bundles.queue_import(tampered)+ case_id = imported.id+ workqueue.drain(imported)++ assert not imported.path.exists()+ status = bundles.job_status(case_id, job["id"])+ assert status["state"] == "failed"+++def test_browser_upload_previews_then_imports_and_removes_staging(client, bundle_case):+ exported = bundles.export_case(bundle_case, password="secret")+ response = client.post(+ "/api/cases/bundles/inspect",+ files={"file": ("source.azimut.enc", BytesIO(exported.read_bytes()), "application/octet-stream")},+ data={"password": "secret"},+ )++ assert response.status_code == 200+ preview = response.json()+ assert preview["case_name"] == "Source case"+ assert "path" not in preview+ assert preview["space_ok"] is True+ assert preview["estimated_import_bytes"] >= preview["total_size"]+ staged = bundles.uploaded_bundle(preview["upload_id"])++ started = client.post(+ "/api/cases/bundles/import",+ json={"upload_id": preview["upload_id"], "password": "secret"},+ )+ assert started.status_code == 200+ body = started.json()+ imported = Case.open(body["case_id"])+ assert workqueue.drain(imported) == 1+ assert not staged.exists()+ assert Case.open(body["case_id"]).read()["name"] == "Source case (imported)"+++def test_browser_upload_can_be_discarded_and_invalid_content_is_removed(client, bundle_case):+ exported = bundles.export_case(bundle_case)+ preview = client.post(+ "/api/cases/bundles/inspect",+ files={"file": ("source.azimut.zip", exported.read_bytes(), "application/zip")},+ ).json()+ staged = bundles.uploaded_bundle(preview["upload_id"])++ discarded = client.delete(f"/api/cases/bundles/uploads/{preview['upload_id']}")+ assert discarded.status_code == 200+ assert not staged.exists()++ invalid = client.post(+ "/api/cases/bundles/inspect",+ files={"file": ("fake.zip", b"not a bundle", "application/zip")},+ )+ assert invalid.status_code == 400+ assert list((config.bundles_dir() / ".imports").glob("*.bundle")) == []+++def test_ready_export_downloads_as_an_attachment(client, bundle_case):+ started = client.post(+ f"/api/cases/{bundle_case.id}/bundle/export",+ json={"password": None},+ )+ assert started.status_code == 200+ job_id = started.json()["job_id"]+ assert "output" not in started.json()+ assert workqueue.drain(bundle_case) >= 1++ status = client.get(f"/api/cases/{bundle_case.id}/bundle/jobs/{job_id}")+ assert "payload" not in status.json()+ response = client.get(+ f"/api/cases/{bundle_case.id}/bundle/jobs/{job_id}/download"+ )+ assert response.status_code == 200+ assert response.content.startswith(b"PK")+ assert "attachment;" in response.headers["content-disposition"]+ assert ".azimut.zip" in response.headers["content-disposition"]+++def test_abandoned_browser_uploads_expire(bundle_case):+ upload_id, staged = bundles.stage_upload(BytesIO(b"old upload"))+ os.utime(staged, (0, 0))++ bundles.cleanup_uploads(now=bundles.UPLOAD_MAX_AGE + 1)++ assert not staged.exists()+ with pytest.raises(bundles.BundleError, match="not found"):+ bundles.uploaded_bundle(upload_id)diff --git a/tests/test_enrich.py b/tests/test_enrich.pyindex d7e996b..9bff139 100644--- a/tests/test_enrich.py+++ b/tests/test_enrich.py@@ -422,6 +422,53 @@ def test_media_from_an_older_release_still_gets_its_suggestions(tmp_workspace, massert [ln["type"] for ln in case.links_of(media["id"])] == [enrich.LOCATED_AT]+def test_backfill_keeps_an_imported_confirmed_gps_relation(+ tmp_workspace, monkeypatch, tmp_path+):+ """A bundle may bring old media that needs the current enrichment version+ together with an analyst's confirmed Relate-to choice. The facts may be+ refreshed, but that choice must not come back as another suggestion."""+ from azimut.engine import links as link_engine+ from azimut.engine import media as media_engine+ from azimut.engine import workqueue+ from azimut.workspace import Case++ monkeypatch.setattr(workqueue, "start_workers", False)+ case = Case.create("Imported relation")+ exif = _exif_with_gps((48, 51, 30.0), "N", (2, 21, 3.0), "E")+ rel = _import_image(case, "related.jpg", tmp_path, exif)+ workqueue.drain(case)++ media = case.find_entity(attr="path", value=rel)+ for link in case.links_of(media["id"]):+ case.remove_link(link["id"])+ place = case.add_entity(+ "place",+ "Chosen place",+ {"lat": 48.858333, "lon": 2.350833},+ by="user",+ )+ stated = link_engine.add_relation(+ case,+ media["id"],+ place["id"],+ enrich.LOCATED_AT,+ by="user",+ )++ sidecar = media_engine.read_item(case, rel)+ sidecar.pop("enrich_version", None)+ media_engine._write_sidecar(case.resolve_inside(rel), sidecar)+ enrich.on_register(case, rel, "image", media["id"])+ workqueue.drain(case)++ located = [+ link for link in case.links_of(media["id"]) if link["type"] == enrich.LOCATED_AT+ ]+ assert located == [stated]+ assert located[0]["provenance"]["status"] == "confirmed"++def test_a_probe_that_never_ran_is_left_for_the_backfill_to_retry(tmp_workspace, monkeypatch, tmp_path):"""A timed-out or crashed ffprobe is not an answer about the file. Stamping theenrichment version on it would take it out of the backfill's reach for good."""diff --git a/tests/test_media_api.py b/tests/test_media_api.pyindex 76eeb45..d910416 100644--- a/tests/test_media_api.py+++ b/tests/test_media_api.py@@ -331,6 +331,23 @@ def test_media_page_items_carry_thumb_state(client):assert page["items"][0]["thumb_state"] == "ready"+def test_media_page_reports_pending_thumbnails_beyond_the_loaded_page(client, monkeypatch):+ from azimut.engine import workqueue++ monkeypatch.setattr(workqueue, "start_workers", False)+ cid = client.post("/api/cases", json={"name": "Paged thumbnail jobs"}).json()["id"]+ for index, name in enumerate(("a.mp4", "b.mp4")):+ client.post(+ f"/api/cases/{cid}/media/upload",+ files={"file": (name, io.BytesIO(f"video {index}".encode()), "video/mp4")},+ )++ page = client.get(f"/api/cases/{cid}/media/page", params={"limit": 1}).json()++ assert len(page["items"]) == 1+ assert page["facets"]["thumbnail_pending"] == 2++def test_duplicate_detection(client):cid = client.post("/api/cases", json={"name": "Dup"}).json()["id"]data = _png_bytes(color=(1, 2, 3))diff --git a/tests/test_release_gate.py b/tests/test_release_gate.pyindex 2367313..620d326 100644--- a/tests/test_release_gate.py+++ b/tests/test_release_gate.py@@ -249,6 +249,7 @@ def test_intel_macos_package_support_floor_matches_the_lock():root = Path(__file__).resolve().parent.parentreadme = (root / "README.md").read_text(encoding="utf-8")lock = (root / "uv.lock").read_text(encoding="utf-8")+ dependencies = _pyproject()["project"]["dependencies"]opencv = lock.split('[[package]]\nname = "opencv-python-headless"',maxsplit=1,@@ -257,3 +258,19 @@ def test_intel_macos_package_support_floor_matches_the_lock():assert "macOS (Intel, 14+)" in readmeassert "macosx_14_0_x86_64.whl" in opencv++ crypto = [dependency for dependency in dependencies if dependency.startswith("cryptography")]+ assert len(crypto) == 2+ assert any(+ "<49" in dependency+ and "sys_platform == 'darwin'" in dependency+ and "platform_machine == 'x86_64'" in dependency+ for dependency in crypto+ )+ assert any(+ "<50" in dependency+ and "sys_platform != 'darwin' or platform_machine != 'x86_64'" in dependency+ for dependency in crypto+ )+ assert "cryptography-48.0.1-cp311-abi3-macosx_10_9_universal2.whl" in lock+ assert "cryptography-49.0.0-cp311-abi3-macosx_11_0_arm64.whl" in lockdiff --git a/tests/test_repository.py b/tests/test_repository.pyindex 0200746..2aea14f 100644--- a/tests/test_repository.py+++ b/tests/test_repository.py@@ -326,6 +326,10 @@ def test_enqueue_is_idempotent_on_key(repo):# a different key is a distinct jobrepo.enqueue_job("thumbnail", key="media/b.jpg")assert repo.count_jobs() == {"queued": 2}+ repo.enqueue_job("enrich", key="media/a.jpg")+ assert repo.count_jobs() == {"queued": 3}+ assert repo.count_jobs(kind="thumbnail") == {"queued": 2}+ assert repo.count_jobs(kind="enrich") == {"queued": 1}def test_claim_takes_one_queued_job_oldest_first(repo):diff --git a/tests/test_sqlite_backend.py b/tests/test_sqlite_backend.pyindex 97d25bc..1a12d97 100644--- a/tests/test_sqlite_backend.py+++ b/tests/test_sqlite_backend.py@@ -144,13 +144,14 @@ INSERT INTO entities(id, type, label, attrs_json, prov_by, prov_at)def test_open_upgrades_a_v1_db_through_every_migration(tmp_path):"""A schema-1 case.db is upgraded on open through the whole chain: the foldercolumn is added and backfilled (1->2), the jobs table is created (2->3),- search/media browse indexes arrive in schema 4 and the position flag in 5. A- second open applies nothing."""+ search/media browse indexes arrive in schema 4, the position flag in 5 and+ the trash journal in 6 and its recovery state in 7. A second open applies+ nothing."""db = tmp_path / "case.db"with sqlite3.connect(db) as conn:conn.executescript(_SCHEMA_V1)- store = SqliteCase.open(db) # runs 1 -> 2 -> 3 -> 4 -> 5 in place+ store = SqliteCase.open(db) # runs 1 -> 2 -> 3 -> 4 -> 5 -> 6 -> 7 in place# 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"]@@ -159,11 +160,11 @@ def test_open_upgrades_a_v1_db_through_every_migration(tmp_path):store.enqueue_job("thumbnail", key="media/x.jpg")assert store.count_jobs() == {"queued": 1}with sqlite3.connect(db) as conn:- assert conn.execute("SELECT value FROM meta WHERE key='schema_version'").fetchone()[0] == "5"+ assert conn.execute("SELECT value FROM meta WHERE key='schema_version'").fetchone()[0] == "7"applied = {r[0] for r in conn.execute("SELECT version FROM schema_migrations").fetchall()}- assert {2, 3, 4, 5} <= applied+ assert {2, 3, 4, 5, 6, 7} <= appliedcolumns = {row[1] for row in conn.execute("PRAGMA table_info(entities)").fetchall()}@@ -171,10 +172,17 @@ def test_open_upgrades_a_v1_db_through_every_migration(tmp_path):assert conn.execute("SELECT value FROM meta WHERE key='media_index_ready'").fetchone()[0] == "1"+ # 5 -> 6: the trash journal is there, and empty.+ assert store.trash_summary() == {"groups": 0, "items": 0, "size_bytes": 0}+ # 6 -> 7: interrupted moves have a durable recovery state.+ trash_columns = {+ row[1] for row in conn.execute("PRAGMA table_info(trash)").fetchall()+ }+ assert "state" in trash_columnsSqliteCase.open(db) # idempotent — the second open applies nothingwith sqlite3.connect(db) as conn:- for version in (2, 3, 4, 5):+ for version in (2, 3, 4, 5, 6, 7):assert conn.execute("SELECT COUNT(*) FROM schema_migrations WHERE version = ?", (version,)).fetchone()[0] == 1diff --git a/tests/test_trash.py b/tests/test_trash.pynew file mode 100644index 0000000..709eea3--- /dev/null+++ b/tests/test_trash.py@@ -0,0 +1,201 @@+"""The trash: a delete you can take back.++What is asserted here is the contract the rest of the app relies on — the graph+still hard-deletes, so nothing else has to filter deleted rows out, and the undo+puts back the entity, its files, its links and the scars its delete wrote.+"""++import fullcase+from azimut.engine import workqueue+from azimut.workspace import Case+++def entity_of(client, case_id: str, attr: str, value: str) -> dict:+ return client.get(+ f"/api/cases/{case_id}/entities/lookup", params={"attr": attr, "value": value}+ ).json()["entity"]+++def trash_of(client, case_id: str) -> dict:+ return client.get(f"/api/cases/{case_id}/trash").json()+++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")++ deleted = client.delete(f"/api/cases/{full.case_id}/entities/{note['id']}").json()++ # gone from the graph and from disk, exactly as before...+ assert entity_of(client, full.case_id, "path", note["attrs"]["path"]) is None+ assert not case.resolve_inside(note["attrs"]["path"]).exists()+ # ...but the file is aside, and the case says so+ listed = trash_of(client, full.case_id)+ assert listed["groups"][0]["id"] == deleted["trash"]+ assert listed["groups"][0]["label"] == note["label"]+ assert listed["items"] == 1+ assert listed["size_bytes"] > 0+ assert (case.trash_dir / deleted["trash"] / note["attrs"]["path"]).is_file()+++def test_undo_brings_back_the_entity_its_id_and_its_file(client):+ full = fullcase.build_full_case(client)+ case = Case.open(full.case_id)+ photo = entity_of(client, full.case_id, "path", full.photo)++ group = client.delete(f"/api/cases/{full.case_id}/entities/{photo['id']}").json()["trash"]+ restored = client.post(f"/api/cases/{full.case_id}/trash/{group}/restore")+ assert restored.status_code == 200, restored.text++ back = entity_of(client, full.case_id, "path", full.photo)+ # the same id: every spec, draft and link recorded elsewhere still points at it+ assert back["id"] == photo["id"]+ assert case.resolve_inside(full.photo).is_file()+ assert case.resolve_inside(full.photo + ".azimut.json").is_file()+ # and it is browsable again — the media index row came back with it+ listed = client.get(f"/api/cases/{full.case_id}/media").json()+ assert any(item["path"] == full.photo for item in listed)+ assert trash_of(client, full.case_id)["groups"] == []+++def test_a_cascade_comes_back_as_one_piece(client):+ """An Inspect session only depends on its subject, so deleting the photo+ takes the session too. Undo has to bring both, or the analyst gets half a+ case back."""+ full = fullcase.build_full_case(client)+ photo = entity_of(client, full.case_id, "path", full.photo)+ session = entity_of(client, full.case_id, "spec", full.session)++ deleted = client.delete(f"/api/cases/{full.case_id}/entities/{photo['id']}").json()+ assert session["id"] in deleted["deleted"]+ assert trash_of(client, full.case_id)["groups"][0]["item_count"] == len(deleted["deleted"])++ client.post(f"/api/cases/{full.case_id}/trash/{deleted['trash']}/restore")++ assert entity_of(client, full.case_id, "spec", full.session)["id"] == session["id"]+ # the depends-on edge is back too, so a second delete still cascades+ chain = client.get(f"/api/cases/{full.case_id}/entities/{photo['id']}/chain").json()+ assert any(d["entity"]["id"] == session["id"] for d in chain["dependents"])+++def test_undo_lifts_the_scar_that_delete_wrote(client):+ """A proof survives its panel's deletion, carrying a tombstone. Restoring the+ panel makes the proof whole again — the scar goes, the derivation returns."""+ full = fullcase.build_full_case(client)+ photo = entity_of(client, full.case_id, "path", full.photo)+ proof = entity_of(client, full.case_id, "spec", full.proof)++ group = client.delete(f"/api/cases/{full.case_id}/entities/{photo['id']}").json()["trash"]+ scarred = client.get(f"/api/cases/{full.case_id}/entities/{proof['id']}/chain").json()+ assert [lost["path"] for lost in scarred["lost"]] == [full.photo]++ client.post(f"/api/cases/{full.case_id}/trash/{group}/restore")++ healed = client.get(f"/api/cases/{full.case_id}/entities/{proof['id']}/chain").json()+ assert healed["lost"] == []+ assert any(s["entity"]["id"] == photo["id"] for s in healed["sources"])+++def test_a_relation_survives_the_round_trip(client):+ """Relations vanish untraced — no cascade, no tombstone — so the trash is the+ only thing that can bring one back."""+ full = fullcase.build_full_case(client)+ photo = entity_of(client, full.case_id, "path", full.photo)++ group = client.delete(f"/api/cases/{full.case_id}/entities/{photo['id']}").json()["trash"]+ client.post(f"/api/cases/{full.case_id}/trash/{group}/restore")++ chain = client.get(f"/api/cases/{full.case_id}/entities/{photo['id']}/chain").json()+ stated = [r for r in chain["relations"] if r["link"]["type"] == "located-at"]+ assert [r["entity"]["id"] for r in stated] == [full.place_id]+++def test_a_proof_takes_its_pasted_images_into_the_trash_and_back(client):+ full = fullcase.build_full_case(client)+ case = Case.open(full.case_id)+ 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()+ assert not case.resolve_inside(full.proof_asset).exists()++ client.post(f"/api/cases/{full.case_id}/trash/{group}/restore")+ assert case.resolve_inside(full.proof_asset).is_file()+++def test_restoring_onto_an_occupied_path_refuses_rather_than_renames(client):+ """Rewriting a restored artifact's path behind the analyst is worse than a+ 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")+ 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")++ refused = client.post(f"/api/cases/{full.case_id}/trash/{group}/restore")+ assert refused.status_code == 409+ assert rel in refused.json()["detail"]+ # nothing moved: the group is intact and can be restored once the path is free+ assert trash_of(client, full.case_id)["groups"][0]["id"] == group+ case.resolve_inside(rel).unlink()+ assert client.post(f"/api/cases/{full.case_id}/trash/{group}/restore").status_code == 200+++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")++ 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++ assert not (case.trash_dir / group).exists()+ assert trash_of(client, full.case_id)["groups"] == []+ # and it cannot be restored afterwards+ assert client.post(f"/api/cases/{full.case_id}/trash/{group}/restore").status_code == 404+++def test_emptying_the_trash_clears_every_group(client):+ full = fullcase.build_full_case(client)+ case = Case.open(full.case_id)+ for attr, value in (("spec", full.proof), ("draft", full.draft)):+ entity = entity_of(client, full.case_id, attr, value)+ client.delete(f"/api/cases/{full.case_id}/entities/{entity['id']}")+ assert len(trash_of(client, full.case_id)["groups"]) == 2++ assert client.delete(f"/api/cases/{full.case_id}/trash").json() == {"purged": 2}+ assert trash_of(client, full.case_id)["groups"] == []+ assert not case.trash_dir.exists()+++def test_a_restored_media_gets_its_thumbnail_back(client):+ """Thumbnails never travel — they are a shared cache — so the restore has to+ ask for a new one rather than expect the old file to be waiting."""+ full = fullcase.build_full_case(client)+ case = Case.open(full.case_id)+ photo = entity_of(client, full.case_id, "path", full.photo)+ thumb = client.get(f"/api/cases/{full.case_id}/media").json()+ thumb_rel = next(item["thumbnail"] for item in thumb if item["path"] == full.photo)++ group = client.delete(f"/api/cases/{full.case_id}/entities/{photo['id']}").json()["trash"]+ assert not (case.trash_dir / group / thumb_rel).exists()+ assert not case.resolve_inside(thumb_rel).exists()++ client.post(f"/api/cases/{full.case_id}/trash/{group}/restore")+ workqueue.wait_until_idle(timeout=20)+ assert case.resolve_inside(thumb_rel).is_file()+++def test_deleting_a_case_takes_its_trash_with_it(client):+ """Deleting a whole case stays immediate — the trash is inside the case, so+ 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")+ client.delete(f"/api/cases/{full.case_id}/entities/{note['id']}")++ assert client.delete(f"/api/cases/{full.case_id}").status_code == 200+ assert not case.path.exists()diff --git a/uv.lock b/uv.lockindex ff7740b..93dd068 100644--- a/uv.lock+++ b/uv.lock@@ -2,9 +2,12 @@ version = 1revision = 3requires-python = ">=3.11"resolution-markers = [- "python_full_version >= '3.15'",- "python_full_version >= '3.12' and python_full_version < '3.15'",- "python_full_version < '3.12'",+ "(python_full_version >= '3.15' and platform_machine != 'x86_64') or (python_full_version >= '3.15' and sys_platform != 'darwin')",+ "python_full_version >= '3.15' and platform_machine == 'x86_64' and sys_platform == 'darwin'",+ "(python_full_version >= '3.12' and python_full_version < '3.15' and platform_machine != 'x86_64') or (python_full_version >= '3.12' and python_full_version < '3.15' and sys_platform != 'darwin')",+ "python_full_version >= '3.12' and python_full_version < '3.15' and platform_machine == 'x86_64' and sys_platform == 'darwin'",+ "(python_full_version < '3.12' and platform_machine != 'x86_64') or (python_full_version < '3.12' and sys_platform != 'darwin')",+ "python_full_version < '3.12' and platform_machine == 'x86_64' and sys_platform == 'darwin'",][[package]]@@ -92,6 +95,8 @@ wheels = [name = "azimut"source = { editable = "." }dependencies = [+ { name = "cryptography", version = "48.0.1", source = { registry = "https://pypi.org/simple" }, marker = "platform_machine == 'x86_64' and sys_platform == 'darwin'" },+ { name = "cryptography", version = "49.0.0", source = { registry = "https://pypi.org/simple" }, marker = "platform_machine != 'x86_64' or sys_platform != 'darwin'" },{ name = "fastapi" },{ name = "gallery-dl" },{ name = "httpx" },@@ -126,6 +131,8 @@ release = [[package.metadata]requires-dist = [+ { name = "cryptography", marker = "platform_machine != 'x86_64' or sys_platform != 'darwin'", specifier = ">=45,<50" },+ { name = "cryptography", marker = "platform_machine == 'x86_64' and sys_platform == 'darwin'", specifier = ">=45,<49" },{ name = "fastapi", specifier = ">=0.111,<1.0" },{ name = "gallery-dl", specifier = ">=1.27" },{ name = "httpx", specifier = ">=0.27,<1.0" },@@ -159,7 +166,7 @@ name = "build"version = "1.5.0"source = { registry = "https://pypi.org/simple" }dependencies = [- { name = "colorama", marker = "os_name == 'nt'" },+ { name = "colorama", marker = "(os_name == 'nt' and platform_machine != 'x86_64') or (os_name == 'nt' and sys_platform != 'darwin')" },{ name = "packaging" },{ name = "pyproject-hooks" },]@@ -186,6 +193,8 @@ dependencies = []sdist = { url = "https://files.pythonhosted.org/packages/57/5f/ff100cae70ebe9d8df1c01a00e510e45d9adb5c1fdda84791b199141de97/cffi-2.1.0.tar.gz", hash = "sha256:efc1cdd798b1aaf39b4610bba7aad28c9bea9b910f25c784ccf9ec1fa719d1f9", size = 531036, upload-time = "2026-07-06T21:34:30.382Z" }wheels = [+ { url = "https://files.pythonhosted.org/packages/d3/67/85c89a59ba36a671e79638f44d466749f08179266a57e4f2ffdf92174072/cffi-2.1.0-cp311-cp311-macosx_10_15_x86_64.whl", hash = "sha256:02cb7ff33ded4f1532476731f89ede53e2e488a8e6205515a82144246ffa7dcc", size = 183845, upload-time = "2026-07-06T21:32:26.32Z" },+ { url = "https://files.pythonhosted.org/packages/ea/dd/e3b0baa2d3d6a857ac72b7efbf18e32e487c9cdafcc13049ad765495b15e/cffi-2.1.0-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:f5bce581e6b8c235e566a14768a943b172ada3ed73537bb0c0be1edee312d4e7", size = 184186, upload-time = "2026-07-06T21:32:28.025Z" },{ url = "https://files.pythonhosted.org/packages/65/68/9f3ef890cf3c6ab97bd531c5677f67613d302165d16f8142b2811782a614/cffi-2.1.0-cp311-cp311-manylinux1_i686.manylinux2014_i686.manylinux_2_17_i686.manylinux_2_5_i686.whl", hash = "sha256:30b65779d598c370374fefabf138d456fd6f3216bfa7bedfab1ba82025b0cd93", size = 211892, upload-time = "2026-07-06T21:32:29.565Z" },{ url = "https://files.pythonhosted.org/packages/22/d7/1a74539db16d8bfd839ff1515948948efbb162e574650fd3d846896eea95/cffi-2.1.0-cp311-cp311-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:88023dfe18799507b73f1dbb0d14326a17465de1bc9c9c7655c22845e9ddc3a2", size = 218793, upload-time = "2026-07-06T21:32:30.951Z" },{ url = "https://files.pythonhosted.org/packages/ec/d1/9a5b7169499e8e8d8e636de70b97ac7c9447104d2ff1a2cd94790cea5162/cffi-2.1.0-cp311-cp311-manylinux2014_ppc64le.manylinux_2_17_ppc64le.whl", hash = "sha256:0a96b74cda968eebbad56d973efe5098974f0a9fb323865bf99ea1fd24e3e64c", size = 205737, upload-time = "2026-07-06T21:32:32.216Z" },@@ -194,6 +203,11 @@ wheels = [{ url = "https://files.pythonhosted.org/packages/a2/a5/d4fe77b589e5e82d43ebc809bf2e6474afe8e48e32ea050b9357645b6471/cffi-2.1.0-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:9d8272c0e483b024e1b9ad029821470ed8ec65631dbd90217469da0e7cd89f1c", size = 221251, upload-time = "2026-07-06T21:32:36.527Z" },{ url = "https://files.pythonhosted.org/packages/22/f0/a2fc43084c0433caf7f461bccc013e28f848d04ee1c5ed7fce71423cf4d9/cffi-2.1.0-cp311-cp311-musllinux_1_2_i686.whl", hash = "sha256:7762faa47e8ff7eb80bd261d9a7d8eea2d8baa69de5e95b70c1f338bbe712f02", size = 214250, upload-time = "2026-07-06T21:32:37.852Z" },{ url = "https://files.pythonhosted.org/packages/04/8c/b925975448cf20634a9fbd5efceb807219db452653648d2897c0989cab2d/cffi-2.1.0-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:89095c1968b4ba8285840e131bf2891b09ae137fe2146905acae0354fbce1b5e", size = 219441, upload-time = "2026-07-06T21:32:39.146Z" },+ { url = "https://files.pythonhosted.org/packages/eb/da/5c4918a2d61d86fa927d716cb3d8e4626ef8dc8f605a599d32f33897f59a/cffi-2.1.0-cp311-cp311-win32.whl", hash = "sha256:64c753a0f87a256020004f37a1c8c02c480e725f910f0b2a0f3f07debd1b2479", size = 174496, upload-time = "2026-07-06T21:32:40.467Z" },+ { url = "https://files.pythonhosted.org/packages/f9/c8/6c2de1d55cf35ef8b92885d5ef280790f0fb9634d87ea1cc315176aecd61/cffi-2.1.0-cp311-cp311-win_amd64.whl", hash = "sha256:4f26194e3d95e06501b942642855aed4f953d55e95d7d01b7c4483db3ecff458", size = 185113, upload-time = "2026-07-06T21:32:41.761Z" },+ { url = "https://files.pythonhosted.org/packages/9e/4e/e8d7cb5783f1841a3c8fb3a7735838d7484d08ec08c9f984b14cac1ac0e9/cffi-2.1.0-cp311-cp311-win_arm64.whl", hash = "sha256:35aaea0c7ee0e58a5cd8c2fd1a48fdf7ece0d2699b7ecdda08194e9ce5dd9b3d", size = 179927, upload-time = "2026-07-06T21:32:42.961Z" },+ { url = "https://files.pythonhosted.org/packages/1e/85/990925db5df586ec90beb97529c853497e7f85ba0234830447faf41c3057/cffi-2.1.0-cp312-cp312-macosx_10_15_x86_64.whl", hash = "sha256:df2b82571a1b30f58a87bf4e5a9e78d2b1eff6c6ce8fd3aa3757221f93f0863f", size = 184829, upload-time = "2026-07-06T21:32:44.324Z" },+ { url = "https://files.pythonhosted.org/packages/4b/92/e7bb136ad6b5352603732cf907ef862ca103f20f2031c1735a46300c20c9/cffi-2.1.0-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:78474632761faa0fb96f30b1c928c84ebcf68713cbb80d15bab09dfe61640fde", size = 184728, upload-time = "2026-07-06T21:32:45.683Z" },{ url = "https://files.pythonhosted.org/packages/c3/c0/d1ec30ffb370f748f2fb54425972bfef9871e0132e82fb589c46b6676049/cffi-2.1.0-cp312-cp312-manylinux1_i686.manylinux2014_i686.manylinux_2_17_i686.manylinux_2_5_i686.whl", hash = "sha256:5972433ad71a9e46516584ef60a0fda12d9dc459938d1539c3ddecf9bdc1368d", size = 214815, upload-time = "2026-07-06T21:32:48.557Z" },{ url = "https://files.pythonhosted.org/packages/1b/dc/5620cf930688be01f2d673804291de757a934c90b946dbdc3d84130c2ea4/cffi-2.1.0-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:b6422532152adf4e59b110cb2808cee7a033800952f5c036b4af047ee43199e7", size = 222429, upload-time = "2026-07-06T21:32:49.848Z" },{ url = "https://files.pythonhosted.org/packages/4b/a4/77b53abbf7a1e0beb9637edbef2a94d15f9c822f591e85d439ffd91519a6/cffi-2.1.0-cp312-cp312-manylinux2014_ppc64le.manylinux_2_17_ppc64le.whl", hash = "sha256:46b1c8db8f6122420f32d02fffb924c2fe9bc772d228c7c711748fff56aabb2b", size = 210315, upload-time = "2026-07-06T21:32:51.221Z" },@@ -201,8 +215,13 @@ wheels = [{ url = "https://files.pythonhosted.org/packages/62/f2/c9522a81c32132799a1972c39f5c5f8b4c8b9f00488a23feaa6c06f07741/cffi-2.1.0-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:1e9f50d192a3e525b15a75ab5114e442d83d657b7ec29182a991bc9a88fd3a66", size = 221844, upload-time = "2026-07-06T21:32:53.704Z" },{ url = "https://files.pythonhosted.org/packages/6e/28/bd53988b9833e8f8ad539d26f4c07a6b3f6bcb1e9e02e7ca038250b3428d/cffi-2.1.0-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:98fff996e983a36d3aa2eca83af40c5821202e7e6f32d13ae94e3d2286f10cfe", size = 225287, upload-time = "2026-07-06T21:32:54.907Z" },{ url = "https://files.pythonhosted.org/packages/79/99/0d0fd37f055224085f42bbb2c022d002e17dde4a97972822327b07d84101/cffi-2.1.0-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:379de10ce1ba048b1448599d1b37b24caee16309d1ac98d3982fc997f768700b", size = 223681, upload-time = "2026-07-06T21:32:56.329Z" },+ { url = "https://files.pythonhosted.org/packages/b0/80/c138990aa2a70b1a269f6e06348729836d733d6f970867943f61d367f8cc/cffi-2.1.0-cp312-cp312-win32.whl", hash = "sha256:9b8f0f26ca4e7513c534d351eca551947d053fac438f2a04ac96d882909b0d3a", size = 175269, upload-time = "2026-07-06T21:32:57.777Z" },+ { url = "https://files.pythonhosted.org/packages/a8/eb/f636456ff21a83fc13c032b58cc5dde061691546ac79efa284b2989b7982/cffi-2.1.0-cp312-cp312-win_amd64.whl", hash = "sha256:c97f080ea627e2863524c5af3836e2270b5f5dfff1f104392b959f8df0c5d384", size = 185881, upload-time = "2026-07-06T21:32:59.253Z" },+ { url = "https://files.pythonhosted.org/packages/dd/2c/400ea43e721727dca8a65c4521390e9196757caba4a45643acb2b63271b8/cffi-2.1.0-cp312-cp312-win_arm64.whl", hash = "sha256:6d194185eabd279f1c05ebe3504265ddfc5ad2b58d0714f7db9f01da592e9eb6", size = 180088, upload-time = "2026-07-06T21:33:02.278Z" },{ url = "https://files.pythonhosted.org/packages/96/88/a996879e2eeccb815f6e3a5967b12a308257412acec882039d386bd2aa7b/cffi-2.1.0-cp313-cp313-ios_13_0_arm64_iphoneos.whl", hash = "sha256:10537b1df4967ca26d21e5072d7d54188354483b91dc75058968d3f0cf13fbda", size = 194331, upload-time = "2026-07-06T21:33:03.697Z" },{ url = "https://files.pythonhosted.org/packages/58/85/7ae00d5c8dd6266f4e944c3db630f3c5c9a98b61d469c714d848b1d8138a/cffi-2.1.0-cp313-cp313-ios_13_0_arm64_iphonesimulator.whl", hash = "sha256:a95b05f9baf29b91171b3a8bd2020b028835243e7b0ff6bb23e2a3c228518b1b", size = 196966, upload-time = "2026-07-06T21:33:05.353Z" },+ { url = "https://files.pythonhosted.org/packages/8c/e9/45c3a76ad8d43ad9261f4c95436da61128d3ca545d72b9612c0ab5be0b1c/cffi-2.1.0-cp313-cp313-macosx_10_15_x86_64.whl", hash = "sha256:15faec4adfff450819f3aee0e2e02c812de6edb88203aa58807955db2003472a", size = 184795, upload-time = "2026-07-06T21:33:06.699Z" },+ { url = "https://files.pythonhosted.org/packages/84/4c/82f132cb4418ee6d953d982b19191e87e2a6372c8a4ce36e50b69d6ade4a/cffi-2.1.0-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:716ff8ec22f20b4d988b12884086bcef0fc99737043e503f7a3935a6be99b1ea", size = 184746, upload-time = "2026-07-06T21:33:08.071Z" },{ url = "https://files.pythonhosted.org/packages/a0/1c/4ed5a0e5bdca6cbc275556de3328dd1b76fd0c11cc13c88fe66d1d8715f2/cffi-2.1.0-cp313-cp313-manylinux1_i686.manylinux2014_i686.manylinux_2_17_i686.manylinux_2_5_i686.whl", hash = "sha256:63960549e4f8dc41e31accb97b975abaecfc44c03e396c093a6436763c2ea7db", size = 214747, upload-time = "2026-07-06T21:33:09.671Z" },{ url = "https://files.pythonhosted.org/packages/3a/a6/e879bb68cc23a2bc9ba8f4b7d8019f0c2694bad2ab6c4a3701d429439f58/cffi-2.1.0-cp313-cp313-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:ff067a8d8d880e7809e4ac88eb009bb848870115317b306666502ccad30b147f", size = 222392, upload-time = "2026-07-06T21:33:10.896Z" },{ url = "https://files.pythonhosted.org/packages/88/f6/01890cfd63c08f8eb96a8319b0443690197d240a8bd6346048cf7bde9190/cffi-2.1.0-cp313-cp313-manylinux2014_ppc64le.manylinux_2_17_ppc64le.whl", hash = "sha256:3b926723c13eba9f81d2ef3820d63aeceec3b2d4639906047bf675cb8a7a500d", size = 210285, upload-time = "2026-07-06T21:33:12.251Z" },@@ -210,34 +229,57 @@ wheels = [{ url = "https://files.pythonhosted.org/packages/6f/08/f2e7d62c460faae0926f2d6e423694aa409ced3bc1fe2927a0a6e5f05416/cffi-2.1.0-cp313-cp313-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:799416bae98336e400981ff6e532d67d5c709cfb30afb79865a1315f94b0e224", size = 221808, upload-time = "2026-07-06T21:33:15.466Z" },{ url = "https://files.pythonhosted.org/packages/38/37/04f54b8e63a02f3d908332c9effbf8c366167c6f733ed8a3d4f79b7e2a1e/cffi-2.1.0-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:961be50688f7fba2fa65f63712d3b9b341a22311f5253460ce933f52f0de1c8c", size = 225241, upload-time = "2026-07-06T21:33:16.869Z" },{ url = "https://files.pythonhosted.org/packages/a9/d6/c72eecca433cd3e681c65ed313ab4835d9d4a379704d0f628a6a05f51c2e/cffi-2.1.0-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:bf5c6cf48238b0eb4c086978c492ad1cbc22373fc5b2d7353b3a598ce6db887a", size = 223588, upload-time = "2026-07-06T21:33:18.239Z" },+ { url = "https://files.pythonhosted.org/packages/c6/4b/e706f67279140f92939da3475ad610df18bfd52d50f14953a8e5fede71d5/cffi-2.1.0-cp313-cp313-win32.whl", hash = "sha256:db3eb7d46527159a878ec3460e9d40615bc25ba337d477db681aea6e4f05c5d2", size = 175248, upload-time = "2026-07-06T21:33:19.799Z" },+ { url = "https://files.pythonhosted.org/packages/5a/47/59eb7975cb0e4ef0afa764ea945b29a5bb4537a9f771cb7d6c8a5dd74c95/cffi-2.1.0-cp313-cp313-win_amd64.whl", hash = "sha256:8e74a6135550c4748af665b1b1118b6aab33b1fc6a16f9aff630af107c3b4512", size = 185717, upload-time = "2026-07-06T21:33:21.47Z" },+ { url = "https://files.pythonhosted.org/packages/5a/af/34fee85c48f8d94efc8597bc09470c9dd274c145f1c12e0fbc6ab6d38d74/cffi-2.1.0-cp313-cp313-win_arm64.whl", hash = "sha256:2282cd5e38aa8accd03e99d1256af8411c84cdbee6a89d841b563fdbd1f3e50f", size = 180114, upload-time = "2026-07-06T21:33:22.515Z" },{ url = "https://files.pythonhosted.org/packages/d8/f0/81478e482afa03f6d18dc8f2afb5edc45b3080853b634b5ed91961be0998/cffi-2.1.0-cp314-cp314-ios_13_0_arm64_iphoneos.whl", hash = "sha256:d2117334c3af3bdcb9a88522b844a2bdb5efdc4f71c6c822df55486ae1c3347a", size = 194142, upload-time = "2026-07-06T21:33:23.657Z" },{ url = "https://files.pythonhosted.org/packages/7d/95/8de304305cd9204974b0ca051b86d307cafca13aa575a0ef1b44d92c0d8c/cffi-2.1.0-cp314-cp314-ios_13_0_arm64_iphonesimulator.whl", hash = "sha256:702c436735fbe99d59ada02a1f65cfc0d31c0ee8b7290912f8fbc5cd1e4b16c3", size = 196819, upload-time = "2026-07-06T21:33:25.007Z" },+ { url = "https://files.pythonhosted.org/packages/20/71/7c8372d30e42415602ed9f268f7cfd66f1b855fed881ecd168bcb45dbc0b/cffi-2.1.0-cp314-cp314-macosx_10_15_x86_64.whl", hash = "sha256:1ff3456eab0d889592d1936d6125bbfbc7ae4d3354a700f8bd80450a66445d4d", size = 184965, upload-time = "2026-07-06T21:33:26.605Z" },+ { url = "https://files.pythonhosted.org/packages/d6/5c/584e626835f0375c928176c04137c96927165cb8733cdb3150ec04e5ee5e/cffi-2.1.0-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:c4165821e131d6d4ca444347c2b694e2311bcfa3fe5a861cc72968f28867beac", size = 184952, upload-time = "2026-07-06T21:33:27.823Z" },{ url = "https://files.pythonhosted.org/packages/2e/d2/065fcae1c73979fac8e054462478d0ff8a29c40cdc2ed7ea5676a061df53/cffi-2.1.0-cp314-cp314-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:276f20fffd7b396e12516ba8edf9509210ac248cbbc5acbc39cd512f9f59ebe6", size = 222353, upload-time = "2026-07-06T21:33:29.178Z" },{ url = "https://files.pythonhosted.org/packages/ed/a5/e8bbb1ce5b3ac2f53ad6a10bde44318a5a8d99d4f4a000d44a6e39aeb3e4/cffi-2.1.0-cp314-cp314-manylinux2014_ppc64le.manylinux_2_17_ppc64le.whl", hash = "sha256:7d5980a3433d4b71a5e120f9dd551403d7824e31e2e67124fe2769c404c06913", size = 210051, upload-time = "2026-07-06T21:33:30.534Z" },{ url = "https://files.pythonhosted.org/packages/28/ed/c127d3ac36e899c965e3361357c3befacd6578c03f40125183e41c3b219e/cffi-2.1.0-cp314-cp314-manylinux2014_s390x.manylinux_2_17_s390x.whl", hash = "sha256:6ca4919c6e4f89aa99c42510b42cf54596892c00b3f9077f6bdd1505e24b9c8d", size = 208630, upload-time = "2026-07-06T21:33:31.753Z" },{ url = "https://files.pythonhosted.org/packages/cc/d7/97d3136f81db489ec8d1d67748c110d6c994268fd7528014aa9f2b085e4e/cffi-2.1.0-cp314-cp314-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:d53d10f7da99ae46f7373b9150393e9c5eab9b224909982b43832668de4779f5", size = 221593, upload-time = "2026-07-06T21:33:33.044Z" },{ url = "https://files.pythonhosted.org/packages/d3/27/93195977168ee63aed233a1a0993a2178798654d1f4bddcdd321d6fd3b21/cffi-2.1.0-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:c351efb95e832a853a29361675f33a7ce53de1a109cd73fd47af0712213aa4ce", size = 225146, upload-time = "2026-07-06T21:33:34.224Z" },{ url = "https://files.pythonhosted.org/packages/b3/c1/6dbd291ee2ae5a50a034aa057207081f545923bbf15dad4511e985aafff5/cffi-2.1.0-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:dbf7c7a88e2bac086f06d14577332760bdeecc42bdec8ac4077f6260557d9326", size = 223240, upload-time = "2026-07-06T21:33:35.57Z" },+ { url = "https://files.pythonhosted.org/packages/0f/6f/ade5ce9863a57992a6ea3d0d10d7e29b8749fc127204b3d493d667b2815f/cffi-2.1.0-cp314-cp314-win32.whl", hash = "sha256:1854b724d00f6654c742097d5387569021be12d3a0f770eae1df8f8acfcc6acd", size = 177723, upload-time = "2026-07-06T21:33:51.626Z" },+ { url = "https://files.pythonhosted.org/packages/41/de/92b9eeed4ae4a21d6fd9b2a2c8505cbed573299902ea73981cc13f7ff62c/cffi-2.1.0-cp314-cp314-win_amd64.whl", hash = "sha256:1b96bfe2c4bd825681b7d311ad6d9b7280a091f43e8f63da5729638083cd3bfb", size = 187937, upload-time = "2026-07-06T21:33:53.403Z" },+ { url = "https://files.pythonhosted.org/packages/2e/1a/cc6ae6c2913a03aab8898eee57963cf1035b8df5872ed8b9115fcc7e2be8/cffi-2.1.0-cp314-cp314-win_arm64.whl", hash = "sha256:7d28dff1db6764108bc30788d85d61c876beff416d9a49cb9dd7c5a9f34f5804", size = 183001, upload-time = "2026-07-06T21:33:54.74Z" },+ { url = "https://files.pythonhosted.org/packages/14/f0/134c00ce0779ec86dea2aa1aac69339c2741a8045072676763512363a2ea/cffi-2.1.0-cp314-cp314t-macosx_10_15_x86_64.whl", hash = "sha256:7ea6b3e2c4250ff1de21c630fe72d0f63eb95c2c32ffbf64a358cf4a8836d714", size = 188538, upload-time = "2026-07-06T21:33:36.792Z" },+ { url = "https://files.pythonhosted.org/packages/50/d8/3b86aba791cb610d24e8a3e1b2cd529e71fa15096b04e4d4e360049d4a4c/cffi-2.1.0-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:6af371f3767faeffc6ac1ef57cdfd25844403e9d3f476c5537caee499de96376", size = 188230, upload-time = "2026-07-06T21:33:38.011Z" },{ url = "https://files.pythonhosted.org/packages/14/d0/117dcd9209255ad8571fbc8c92ef32593a1d294dcec91ddc4e4db50606f2/cffi-2.1.0-cp314-cp314t-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:eb4e8997a49aa2c08a3e43c9045d224448b8941d88e7ac163c7d383e560cbf98", size = 223899, upload-time = "2026-07-06T21:33:39.514Z" },{ url = "https://files.pythonhosted.org/packages/b6/3d/f20f8b886b254e3ad10e15cd4186d3aed49f3e6a35ab37aab9f8f25f7c03/cffi-2.1.0-cp314-cp314t-manylinux2014_ppc64le.manylinux_2_17_ppc64le.whl", hash = "sha256:bf01d8c84cbea96b944c73b22182e6c7c432b3475632b8111dbfdc95ddad6e13", size = 211652, upload-time = "2026-07-06T21:33:40.851Z" },{ url = "https://files.pythonhosted.org/packages/28/3b/fad54de07260b93ddeef4b96d0131d57ea900675df1d410ae1deee52d7a6/cffi-2.1.0-cp314-cp314t-manylinux2014_s390x.manylinux_2_17_s390x.whl", hash = "sha256:33eb1ad83ebe8f313e0df035c406227d55a79456704a863fad9842136af5ad7d", size = 210755, upload-time = "2026-07-06T21:33:42.183Z" },{ url = "https://files.pythonhosted.org/packages/cc/82/3d5c705acb7abbba9bbd7d79b8e62e0f25b6120eb7ae6ac49f1b721722fe/cffi-2.1.0-cp314-cp314t-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:ac0f1a2d0cfa7eea3f2aaf006ab6e70e8feeb16b75d65b7e5939982ca2f11056", size = 223933, upload-time = "2026-07-06T21:33:43.603Z" },{ url = "https://files.pythonhosted.org/packages/6c/d0/47e338384ab6b1004241002fa616301020cea4fc95f283506565d252f276/cffi-2.1.0-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:c16914df9fb7f500e440e6875fa23ff5e0b31db01fa9c06af98d59a91f0dc2e4", size = 226749, upload-time = "2026-07-06T21:33:45.046Z" },{ url = "https://files.pythonhosted.org/packages/70/25/65bd5b58ea4bfdfc15cde02cb5365f89ef8ab8b2adfb8fe5c4bd4233382f/cffi-2.1.0-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:5ecbd0499275d57506d397eebe1981cee87b47fcd9ef5c22cab7ed7644a39a94", size = 225703, upload-time = "2026-07-06T21:33:46.374Z" },+ { url = "https://files.pythonhosted.org/packages/dc/78/aa01ac599a8a4322533d45a1f9bc93b338276d2d59dabbe7c6d92a775c81/cffi-2.1.0-cp314-cp314t-win32.whl", hash = "sha256:7d034dcffa09e9a46c93fa3a3be402096cb5354ac6e41ab8e5cc9cd8b642ad76", size = 182857, upload-time = "2026-07-06T21:33:47.696Z" },+ { url = "https://files.pythonhosted.org/packages/b9/26/d00496b22de4d4228f32dde94ad996f350c8aad676d63bcca0743c8dea4d/cffi-2.1.0-cp314-cp314t-win_amd64.whl", hash = "sha256:0582a58f3051372229ca8e7f5f589f9e5632678208d8636fea3676711fdf7fe5", size = 194065, upload-time = "2026-07-06T21:33:48.953Z" },+ { url = "https://files.pythonhosted.org/packages/d5/dd/0c7dbf815a579ff005008a2d815a55d6bb047c349eef536d9dc53d3f0a8d/cffi-2.1.0-cp314-cp314t-win_arm64.whl", hash = "sha256:510aeeeac94811b138077451da1fb18b308a5feab47dd2b603af55804155e1c8", size = 186404, upload-time = "2026-07-06T21:33:50.309Z" },{ url = "https://files.pythonhosted.org/packages/55/c7/8c8c50cb11c6750051daf12164098a9a6f027ac4356967fd4d800a07f242/cffi-2.1.0-cp315-cp315-ios_13_0_arm64_iphoneos.whl", hash = "sha256:2e9dabb9abcb7ad15938c7196ad5c1718a4e6d33cc79b4c0209bdb64c4a54a5c", size = 194121, upload-time = "2026-07-06T21:33:56.109Z" },{ url = "https://files.pythonhosted.org/packages/99/e2/67680bf19a6b60d2bb7ff83baefa2a4c3d2d7dc0f3277034b802e1fc504c/cffi-2.1.0-cp315-cp315-ios_13_0_arm64_iphonesimulator.whl", hash = "sha256:37f525a7e7e50c017fdebe58b787be310ad59357ae43a053943a6e1a6c526001", size = 196820, upload-time = "2026-07-06T21:33:57.288Z" },+ { url = "https://files.pythonhosted.org/packages/ed/da/4bbe583a3b3a5c8c60892124fe17f3fa3656523faf0d3484eae90f091853/cffi-2.1.0-cp315-cp315-macosx_10_15_x86_64.whl", hash = "sha256:95f2954c2c9473d892eca6e0409f3568b37ab62a8eedb122461f73cc273476e3", size = 184936, upload-time = "2026-07-06T21:33:58.765Z" },+ { url = "https://files.pythonhosted.org/packages/e5/4b/1f4c36ab273980d7aa75bb126ea4f8971f24a96108acad3a0a084028c57b/cffi-2.1.0-cp315-cp315-macosx_11_0_arm64.whl", hash = "sha256:cdf2448aab5f661c9315308ec8b93f4e8a1a67a3c733f8631067a2b67d5913dc", size = 185045, upload-time = "2026-07-06T21:34:00.085Z" },{ url = "https://files.pythonhosted.org/packages/ef/c3/ad299dc38f3583f8d916b299f028af418a9ec98bc695fcbebeae7420691c/cffi-2.1.0-cp315-cp315-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:90bec57cf82089383bd06a605b3eb8daebf7e5a668520beaf6e327a83a947699", size = 222342, upload-time = "2026-07-06T21:34:01.814Z" },{ url = "https://files.pythonhosted.org/packages/eb/d8/df4543cc087245044ed02ef3ad8e0a26619d0075ac7a77a12dc81177851b/cffi-2.1.0-cp315-cp315-manylinux2014_ppc64le.manylinux_2_17_ppc64le.whl", hash = "sha256:6274dcb2d15cef48daa73ed1be5a40d501d74dccd0cd6db364776d12cb6ba022", size = 210073, upload-time = "2026-07-06T21:34:03.255Z" },{ url = "https://files.pythonhosted.org/packages/2c/0e/fac738d73728c6cea2a88a2883dca54892496cbba88a1dc1f2909cb8a6f5/cffi-2.1.0-cp315-cp315-manylinux2014_s390x.manylinux_2_17_s390x.whl", hash = "sha256:2b71d409cccee78310ab5dec549aed052aaea483346e282c7b02362596e01bb0", size = 208551, upload-time = "2026-07-06T21:34:04.433Z" },{ url = "https://files.pythonhosted.org/packages/e6/3f/0b04a700dd64f465c93020253a793a82c9b4dff9961f48facd0df945d9b8/cffi-2.1.0-cp315-cp315-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:7d3538f9c0e50670f4deb93dbb696576e60590369cae2faf7de681e597a8a1f1", size = 221649, upload-time = "2026-07-06T21:34:06.157Z" },{ url = "https://files.pythonhosted.org/packages/5d/7c/b7379a5704c79eda57ce075869ba70a0368d1c850f803b3c0d078d39dcaf/cffi-2.1.0-cp315-cp315-musllinux_1_2_aarch64.whl", hash = "sha256:8f9ec95b8a043d3dfbc74d9abc6f7baf524dd27a8dc160b0a32ff9cdab650c28", size = 225203, upload-time = "2026-07-06T21:34:07.489Z" },{ url = "https://files.pythonhosted.org/packages/5a/02/d5e6c43ea85c41bda2a184a3418f195fe7cf602967a8d2b94e085b83deef/cffi-2.1.0-cp315-cp315-musllinux_1_2_x86_64.whl", hash = "sha256:af5e2915d41fe6c961694d7bfdc8562942638200f3ce2765dfb8b745cf997629", size = 223263, upload-time = "2026-07-06T21:34:08.712Z" },+ { url = "https://files.pythonhosted.org/packages/2c/d8/772b8259bf75749adffb1c546828978381fb516f60cf701f6c83daf60c85/cffi-2.1.0-cp315-cp315-win32.whl", hash = "sha256:0a42c688d19fca6e095a53c6a6e2295a5b050a8b289f109adab02a9e61a25de6", size = 177696, upload-time = "2026-07-06T21:34:26.355Z" },+ { url = "https://files.pythonhosted.org/packages/2f/dd/afa2191fc6d57fedd26e5844a2fe2fcc0bbfa00961bbaa5a41e4921e7cca/cffi-2.1.0-cp315-cp315-win_amd64.whl", hash = "sha256:bccbbb5ee76a61f9d99b5bf3846a51d7fca4b6a732fe46f89295610edaf41853", size = 187914, upload-time = "2026-07-06T21:34:27.58Z" },+ { url = "https://files.pythonhosted.org/packages/05/ef/6cd4f8c671517162379dc79cfae5aea9106bc38abb89628d5c16adf6a838/cffi-2.1.0-cp315-cp315-win_arm64.whl", hash = "sha256:8d35c139744adb3e727cd51b1a18324bbe44b8bd41bf8322bca4d41289f48eda", size = 183004, upload-time = "2026-07-06T21:34:28.905Z" },+ { url = "https://files.pythonhosted.org/packages/11/b6/12fc55092817a5faa26fb8c40c7f9d662e11a46ee248c137aafc42517d92/cffi-2.1.0-cp315-cp315t-macosx_10_15_x86_64.whl", hash = "sha256:f9912624a0c0b834b7520d7769b3644453aabc0a7e1c839da7359f050750e9bc", size = 188378, upload-time = "2026-07-06T21:34:09.926Z" },+ { url = "https://files.pythonhosted.org/packages/8d/2e/cdac88979f295fde5daa69622c7d2111e56e7ceb94f211357fbe452339e4/cffi-2.1.0-cp315-cp315t-macosx_11_0_arm64.whl", hash = "sha256:df92f2aba50eb4d96718b68ef76f2e57a57b54f2fa62333496d16c6d585a85ca", size = 188319, upload-time = "2026-07-06T21:34:11.101Z" },{ url = "https://files.pythonhosted.org/packages/e0/27/1d0b408497e41a74795af122d7b603c418c5fed0171450f899afd04e594f/cffi-2.1.0-cp315-cp315t-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:0520e1f4c35f44e209cbbb421b67eec42e6a157f59444dfb6058874ff3610e5d", size = 223904, upload-time = "2026-07-06T21:34:12.606Z" },{ url = "https://files.pythonhosted.org/packages/8b/31/e115c985105dd7ffb32444505f18ceb874bb42d992af05d5dced7ecf1980/cffi-2.1.0-cp315-cp315t-manylinux2014_ppc64le.manylinux_2_17_ppc64le.whl", hash = "sha256:3681e031db29958a7502f5c0c9d6bbc4c36cb20f7b104086fa642d1799631ff8", size = 211554, upload-time = "2026-07-06T21:34:13.987Z" },{ url = "https://files.pythonhosted.org/packages/5a/67/9e6e09409336d9e515c58367e7cfcf4f89df06ad25252675595a58eb59d5/cffi-2.1.0-cp315-cp315t-manylinux2014_s390x.manylinux_2_17_s390x.whl", hash = "sha256:762f99479dcb369f60ab9017ad4ab97a36a1dd7c1ee5a3b15db0f4b8659120cd", size = 210795, upload-time = "2026-07-06T21:34:15.972Z" },{ url = "https://files.pythonhosted.org/packages/19/e5/d3cc82a4a0be7902af279c04181ad038449c096734464a5ae1de3e1401bd/cffi-2.1.0-cp315-cp315t-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:0611e7ebf90573a535ebdc33ae9da222d037853983e13359f580fab781ca017f", size = 223843, upload-time = "2026-07-06T21:34:17.509Z" },{ url = "https://files.pythonhosted.org/packages/b9/65/b434abc97ce7cecc2c640fde160507c0ecc7e21544b483ba3325d2e2ea17/cffi-2.1.0-cp315-cp315t-musllinux_1_2_aarch64.whl", hash = "sha256:86cf8755a791f72c85dc287128cc62d4f24d392e3f1e15837245623f4a33cccc", size = 226773, upload-time = "2026-07-06T21:34:19.05Z" },{ url = "https://files.pythonhosted.org/packages/b5/9f/d4dc66ca651eb1145a133314cda721abf13cfac3d28c4a0402263ae6ad75/cffi-2.1.0-cp315-cp315t-musllinux_1_2_x86_64.whl", hash = "sha256:ba00f661f8ba35d075c937174e27c2c421cec3942fd2e0ea3e66996757c0fdd9", size = 225719, upload-time = "2026-07-06T21:34:20.576Z" },+ { url = "https://files.pythonhosted.org/packages/68/5a/e536c528bc8057496c360c0978559a2dc45653f89dd6151078aa7d8fca1a/cffi-2.1.0-cp315-cp315t-win32.whl", hash = "sha256:cb96698e3c7413d906ce83f8ffd245ec1bd94707541f299d0ce4d6b0193e982b", size = 182760, upload-time = "2026-07-06T21:34:22.059Z" },+ { url = "https://files.pythonhosted.org/packages/d3/0b/0ffe8b82d3875bced5fa1e7986a7a46b748262a40ab7f60b475eb9fb1bb3/cffi-2.1.0-cp315-cp315t-win_amd64.whl", hash = "sha256:f146d154428a2523f9cc7936c02353c2459b8f6cf07d3cd1ee1c0a611109c5d5", size = 193769, upload-time = "2026-07-06T21:34:23.589Z" },+ { url = "https://files.pythonhosted.org/packages/a0/17/1073b53b68c9b5ca6914adf5f8bf55aacc2d3be102418c90700160ea8605/cffi-2.1.0-cp315-cp315t-win_arm64.whl", hash = "sha256:cbb7640ce37159548d2147b5b8c241f962143d4c71231431820783f4dc78f210", size = 186405, upload-time = "2026-07-06T21:34:24.857Z" },][[package]]@@ -335,15 +377,40 @@ wheels = [{ url = "https://files.pythonhosted.org/packages/d1/d6/3965ed04c63042e047cb6a3e6ed1a63a35087b6a609aa3a15ed8ac56c221/colorama-0.4.6-py2.py3-none-any.whl", hash = "sha256:4f1d9991f5acc0ca119f9d443620b77f9d6b33703e51011c16baf57afb285fc6", size = 25335, upload-time = "2022-10-25T02:36:20.889Z" },]+[[package]]+name = "cryptography"+version = "48.0.1"+source = { registry = "https://pypi.org/simple" }+resolution-markers = [+ "python_full_version >= '3.15' and platform_machine == 'x86_64' and sys_platform == 'darwin'",+ "python_full_version >= '3.12' and python_full_version < '3.15' and platform_machine == 'x86_64' and sys_platform == 'darwin'",+ "python_full_version < '3.12' and platform_machine == 'x86_64' and sys_platform == 'darwin'",+]+dependencies = [+ { name = "cffi", marker = "platform_python_implementation != 'PyPy'" },+]+sdist = { url = "https://files.pythonhosted.org/packages/12/45/870e7f4bef50e5f53b9f51d4428aee5290eedf58ba443f16b1ebb7ab8e66/cryptography-48.0.1.tar.gz", hash = "sha256:266f4ee051abb2f725b74ef8072b521ce1feacf685a3364fa6a6b45548db791a", size = 832989, upload-time = "2026-06-09T22:32:31.8Z" }+wheels = [+ { url = "https://files.pythonhosted.org/packages/1b/bc/ee4137cbbe105652c0ee4252792b78fc8e7afa4b8e61d9d5dc05a7f45731/cryptography-48.0.1-cp311-abi3-macosx_10_9_universal2.whl", hash = "sha256:3e4a1a3232eef2e6c732827d5722db29a0cc8b27af2a4d865b094cf954be9ca1", size = 8008324, upload-time = "2026-06-09T22:31:00.702Z" },+ { url = "https://files.pythonhosted.org/packages/42/06/3e768b4c3bc78201583fa35a0e18f640dd782ff41afba88f8545481a8874/cryptography-48.0.1-cp314-cp314t-macosx_10_9_universal2.whl", hash = "sha256:f817adc181390bd54f2f700107a7419040fb7c1bdf2fc26f36551a06a68c3345", size = 7989830, upload-time = "2026-06-09T22:31:07.8Z" },+ { url = "https://files.pythonhosted.org/packages/ca/6c/00fa2a95997164c8b2072ce327c23d4ab20809ccc323ea5fab91e53a4bba/cryptography-48.0.1-cp39-abi3-macosx_10_9_universal2.whl", hash = "sha256:4fdc69f8e4316bcf0c8c8ec1f26f285d12e8142d88d96c876a59a03be3f6ae67", size = 7987408, upload-time = "2026-06-09T22:32:20.777Z" },+]+[[package]]name = "cryptography"version = "49.0.0"source = { registry = "https://pypi.org/simple" }+resolution-markers = [+ "(python_full_version >= '3.15' and platform_machine != 'x86_64') or (python_full_version >= '3.15' and sys_platform != 'darwin')",+ "(python_full_version >= '3.12' and python_full_version < '3.15' and platform_machine != 'x86_64') or (python_full_version >= '3.12' and python_full_version < '3.15' and sys_platform != 'darwin')",+ "(python_full_version < '3.12' and platform_machine != 'x86_64') or (python_full_version < '3.12' and sys_platform != 'darwin')",+]dependencies = [{ name = "cffi", marker = "platform_python_implementation != 'PyPy'" },]sdist = { url = "https://files.pythonhosted.org/packages/1f/99/d1c90d6041656cc6ee229dc99cd67fd0cd5aec3c5f7d72fffc27cc750054/cryptography-49.0.0.tar.gz", hash = "sha256:f89660a348f4f78a92366240a61404e337586ef7f5909a2fef59ca88ef505493", size = 854345, upload-time = "2026-06-12T20:02:30.512Z" }wheels = [+ { url = "https://files.pythonhosted.org/packages/9b/22/adf66990e63584a68dfb50c24f48a125c07b1699899381c8151e63ed458c/cryptography-49.0.0-cp311-abi3-macosx_11_0_arm64.whl", hash = "sha256:966fe0e9c67490071f14c0d2b1cb2dfb3023c5ce39457343931415f08382f2db", size = 4032100, upload-time = "2026-06-12T20:02:32.143Z" },{ url = "https://files.pythonhosted.org/packages/09/41/3797cfaf69cae04a13ee78ebd83f0678d9c02b4779d21ce24445326f1a69/cryptography-49.0.0-cp311-abi3-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:36d1709f992593689b45bda411498d62c6e365f2ca00b84657d4dadd24de16db", size = 4692978, upload-time = "2026-06-12T20:01:21.305Z" },{ url = "https://files.pythonhosted.org/packages/e6/8b/43011f7ebe515a8aa20d61f290a326cd890c2e738e16e59eaff8d9c3a412/cryptography-49.0.0-cp311-abi3-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:0e959b578856a3924bc0cbb710fc12c387b9412a951389f3ca61704a9e25f325", size = 4716422, upload-time = "2026-06-12T20:01:48.566Z" },{ url = "https://files.pythonhosted.org/packages/4a/91/01ce7303a4579e6d3a6abef01bd322848e9ea7a219adcabc5048b9033571/cryptography-49.0.0-cp311-abi3-manylinux_2_28_aarch64.whl", hash = "sha256:53ecee2e23f7169b6117e99fc8a944e5e50f79e69758a83b52a00cb98ab2b2d2", size = 4700503, upload-time = "2026-06-12T20:02:47.091Z" },@@ -355,6 +422,8 @@ wheels = [{ url = "https://files.pythonhosted.org/packages/a9/3c/f3ad17eecc1a57b0ba236dc01f90e783c51f4a2f35f64777cc4f47a184b2/cryptography-49.0.0-cp311-abi3-manylinux_2_34_x86_64.whl", hash = "sha256:cbc77da8c523d5abd028635ba850a6966fcee2c82e2bf65a41d1d8afe0f98be9", size = 4749290, upload-time = "2026-06-12T20:01:30.848Z" },{ url = "https://files.pythonhosted.org/packages/4f/01/339573cf1023163a400b0b5d16f6d507de413b9f60be6fd1b77feeaf6737/cryptography-49.0.0-cp311-abi3-musllinux_1_2_aarch64.whl", hash = "sha256:b87e65d263b3e5d3bb92a57e2a6638e2f31110fa7aa890c7b2dbba42248d0a3f", size = 4834612, upload-time = "2026-06-12T20:01:29.246Z" },{ url = "https://files.pythonhosted.org/packages/71/fd/577302e213a1be9468f92d1afef66fcf1ef83d516819d9992ca547f592bd/cryptography-49.0.0-cp311-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:66ec79c3904820572d7e987abdf304281f141d37ad9a489b8e97066e7b9b6459", size = 4980804, upload-time = "2026-06-12T20:01:42.853Z" },+ { url = "https://files.pythonhosted.org/packages/1f/09/f42b1d190c5ba75f72062a387f8030d1d75f6ab035788f1d9c4b01de6525/cryptography-49.0.0-cp311-abi3-win_amd64.whl", hash = "sha256:e5dfc1e64de5677cec922ffa8da89c546d0415bf6efdf081842e5d44c84e1f0e", size = 3810026, upload-time = "2026-06-12T20:02:39.262Z" },+ { url = "https://files.pythonhosted.org/packages/ec/9e/db72b3ae7fc9cfad53e630e56c6ae83b9b6ff0bf3718ffb8012d20b3aabf/cryptography-49.0.0-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:73a205dce83953d131a4aa1e0fd917a2fd1c5b1eef251e9d7152efefcbf5caf7", size = 4013892, upload-time = "2026-06-12T20:02:10.735Z" },{ url = "https://files.pythonhosted.org/packages/86/12/c48a424f38db03027be9f7ed5c7dc5de9933dbee992865f98b13727a009d/cryptography-49.0.0-cp314-cp314t-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:196ecd6a36e4e9aa10270393bb98d8df88fccee0bf1e5128b91ae4eb4375896d", size = 4678835, upload-time = "2026-06-12T20:02:48.743Z" },{ url = "https://files.pythonhosted.org/packages/68/28/8a3ad4653662c93fc44dc4e5d8fd374c25c42e07b34bbfbadf49cf57a5a8/cryptography-49.0.0-cp314-cp314t-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:7abcee80084cda3f7691f3eb1ce480d8df49cec637b429aa35986c1de71738aa", size = 4697239, upload-time = "2026-06-12T20:02:56.03Z" },{ url = "https://files.pythonhosted.org/packages/a8/b2/2193fc74f81aee4f9b62733133b73b5176718932ed8f2e4b03fa040480a6/cryptography-49.0.0-cp314-cp314t-manylinux_2_28_aarch64.whl", hash = "sha256:4ae387c9cb68ea569ca17e490d66d8142b81c3cc814bf179974b7d146e490bbb", size = 4685593, upload-time = "2026-06-12T20:02:50.666Z" },@@ -366,6 +435,8 @@ wheels = [{ url = "https://files.pythonhosted.org/packages/11/2d/5e1fb307cb5931881516b464c98774b3f2c36b5d4bb9a2830253cf553cad/cryptography-49.0.0-cp314-cp314t-manylinux_2_34_x86_64.whl", hash = "sha256:d8ecde755e2e91bf773fc94e8c9d730cd7f2007004cb492263a794ec3899a1c8", size = 4730441, upload-time = "2026-06-12T20:02:01.469Z" },{ url = "https://files.pythonhosted.org/packages/e4/c0/bff5a02ee731d207d6a1ed51732549d8c53d2bc8da1d10ec6f2844201d68/cryptography-49.0.0-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:e3fb64c420688e5319ae25113a354015abbd8dffbfbc41781a1ea66fc7622ac3", size = 4815869, upload-time = "2026-06-12T20:01:36.574Z" },{ url = "https://files.pythonhosted.org/packages/b9/26/814681d14248d95d73d5c3eea0c39a94eb8302df966f670a2c60de90974b/cryptography-49.0.0-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:32703d93296f5c1f4b53349ad3a250c2cae0fdecd3a3dd5d47e616d8d616af27", size = 4960948, upload-time = "2026-06-12T20:02:18.688Z" },+ { url = "https://files.pythonhosted.org/packages/4c/fe/93ecac273d3738939d023612ad12cca9a3740a5345d69fda04134c43fd96/cryptography-49.0.0-cp314-cp314t-win_amd64.whl", hash = "sha256:33cd0565932807baddb67b96dbee92f2c374b5c89dee09fd74079aeb8c8dba61", size = 3799153, upload-time = "2026-06-12T20:01:39.059Z" },+ { url = "https://files.pythonhosted.org/packages/19/2a/5bb823f5bedcf80718cea7fbc95ec5515cca3769633c4b01a32be7f30e7c/cryptography-49.0.0-cp39-abi3-macosx_11_0_arm64.whl", hash = "sha256:ec5e529fb80935c94fe7b729f9972b50e351a0e6b50aa294fd5cabb109fcc29a", size = 4025947, upload-time = "2026-06-12T20:01:25.745Z" },{ url = "https://files.pythonhosted.org/packages/3d/df/40577043ca124e17012f408ddddaeb213b856336ac82ddb3bc915f39e29f/cryptography-49.0.0-cp39-abi3-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:f78ff2c9ed8dc2d036b0f4d640e22522213d047c1b14e61205a7e55c80a494d4", size = 4692429, upload-time = "2026-06-12T20:01:53.628Z" },{ url = "https://files.pythonhosted.org/packages/2c/99/2d13299eb3dd27b02dcfaafcc91d6b5cb3329f7cbd6d8f51921acd566c1a/cryptography-49.0.0-cp39-abi3-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:35b151772baff2c74cba7fa290ceaff4c3b11c0c881eb93eb5dbc05a7cfbba18", size = 4700968, upload-time = "2026-06-12T20:02:45.383Z" },{ url = "https://files.pythonhosted.org/packages/a5/4d/9c0cd02f95e2602dd5e563da149ee0830abef3537be8b34dc56281ebe27a/cryptography-49.0.0-cp39-abi3-manylinux_2_28_aarch64.whl", hash = "sha256:0f21641cf4b30fca7aee061ced0ec7ad7b073518088b7c9969a297c0ae796c69", size = 4697758, upload-time = "2026-06-12T20:01:41.13Z" },@@ -377,10 +448,13 @@ wheels = [{ url = "https://files.pythonhosted.org/packages/a0/84/84fe36f19caf857d61cb7fc9c63035a47ffabd84ea12d1d393148efa3615/cryptography-49.0.0-cp39-abi3-manylinux_2_34_x86_64.whl", hash = "sha256:2400ef9c9e2299a25614eb1dea3db54a69b1349efd043bfac9c67630d136df36", size = 4735650, upload-time = "2026-06-12T20:02:41.389Z" },{ url = "https://files.pythonhosted.org/packages/6c/a0/db537264e234f7273a73ec020873d6d6b39dfd8a53db78b550ca8320440e/cryptography-49.0.0-cp39-abi3-musllinux_1_2_aarch64.whl", hash = "sha256:67e1d20ad9ef3a563c59ef22e7a8a0b8210bd26604369ea4a30a7c66aefe504e", size = 4834820, upload-time = "2026-06-12T20:01:51.847Z" },{ url = "https://files.pythonhosted.org/packages/93/77/8df9eb486495979bccecd1062e2eaf435250e84437040295b57d09048b0b/cryptography-49.0.0-cp39-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:42b0684e0e40cf26122427802486f6d93aea593612603a94fbf260c7eb1e9c1b", size = 4967968, upload-time = "2026-06-12T20:02:12.524Z" },+ { url = "https://files.pythonhosted.org/packages/c2/e6/f60198ea8d9dfa15fff9ed4ca02ce362f6eadd9ba757dcc50634c4257b63/cryptography-49.0.0-cp39-abi3-win_amd64.whl", hash = "sha256:026ac7423e6fa66872d3bf889be5974507da3944f866f704fa200eadacd00001", size = 3785547, upload-time = "2026-06-12T20:02:26.847Z" },+ { url = "https://files.pythonhosted.org/packages/63/d3/4a83af35d65e3fad632c926fad684c193ea4398569ccb0bbbc7fe8f5dc9a/cryptography-49.0.0-pp311-pypy311_pp73-macosx_11_0_arm64.whl", hash = "sha256:fc1e275c2f1d97b1a6450b8b0ea3ebfa6e087a611c2b26cb2404d48588abab7b", size = 3993685, upload-time = "2026-06-12T20:02:14.883Z" },{ url = "https://files.pythonhosted.org/packages/d6/a7/f9dac0ab7f80368c56993a7bf638ef9935f825c91902798481fac0898138/cryptography-49.0.0-pp311-pypy311_pp73-manylinux_2_28_aarch64.whl", hash = "sha256:c83782480a4a9da4d0feb51950131ba32e12e70813848b3343f6e18c28a66838", size = 4676239, upload-time = "2026-06-12T20:02:28.793Z" },{ url = "https://files.pythonhosted.org/packages/d7/70/2ba3769dd0ae167e2f33dfa9592d45db6ff9a61d62ca1a5b3d1bdd09068f/cryptography-49.0.0-pp311-pypy311_pp73-manylinux_2_28_x86_64.whl", hash = "sha256:b39efa323140595abd3ecca8529d321ae50f55f3aa3ba9cc81ea56a6011953d5", size = 4715584, upload-time = "2026-06-12T20:01:27.495Z" },{ url = "https://files.pythonhosted.org/packages/94/64/2923570ac1c0bd3a737aa366ac3abbbbde273042308b8cde95e2364a6e6a/cryptography-49.0.0-pp311-pypy311_pp73-manylinux_2_34_aarch64.whl", hash = "sha256:b47db11c2c3525083296069b98ac5221907455e989ae0c2e3008bde851921615", size = 4675885, upload-time = "2026-06-12T20:01:55.49Z" },{ url = "https://files.pythonhosted.org/packages/ab/f8/614dc7e051418cfe53d55173c1e24c6b0085e89996fe90508c2fdf769aef/cryptography-49.0.0-pp311-pypy311_pp73-manylinux_2_34_x86_64.whl", hash = "sha256:084ef1af862eb07ec46d25f68689f2102a9fc0e05ce7b80f14f5fe51e4eef0f6", size = 4715449, upload-time = "2026-06-12T20:02:05.469Z" },+ { url = "https://files.pythonhosted.org/packages/aa/50/a9caea39ad19c431c1a3f8a31114df65b260cdfe67786b6c7e7c040c4c44/cryptography-49.0.0-pp311-pypy311_pp73-win_amd64.whl", hash = "sha256:be9fcb48a55f023493482827d4f459bd263cc20efde64f204b97c123201850c6", size = 3783731, upload-time = "2026-06-12T20:02:43.319Z" },][[package]]@@ -715,7 +789,8 @@ name = "numpy"version = "2.4.6"source = { registry = "https://pypi.org/simple" }resolution-markers = [- "python_full_version < '3.12'",+ "(python_full_version < '3.12' and platform_machine != 'x86_64') or (python_full_version < '3.12' and sys_platform != 'darwin')",+ "python_full_version < '3.12' and platform_machine == 'x86_64' and sys_platform == 'darwin'",]sdist = { url = "https://files.pythonhosted.org/packages/d0/ad/fed0499ce6a338d2a03ebae59cd15093910c8875328855781952abf6c2fe/numpy-2.4.6.tar.gz", hash = "sha256:f3a3570c4a2a16746ac2c31a7c7c7b0c186b95ce902e33db6f28094ed7387dda", size = 20735807, upload-time = "2026-05-18T23:37:14.07Z" }wheels = [@@ -797,8 +872,10 @@ name = "numpy"version = "2.5.1"source = { registry = "https://pypi.org/simple" }resolution-markers = [- "python_full_version >= '3.15'",- "python_full_version >= '3.12' and python_full_version < '3.15'",+ "(python_full_version >= '3.15' and platform_machine != 'x86_64') or (python_full_version >= '3.15' and sys_platform != 'darwin')",+ "python_full_version >= '3.15' and platform_machine == 'x86_64' and sys_platform == 'darwin'",+ "(python_full_version >= '3.12' and python_full_version < '3.15' and platform_machine != 'x86_64') or (python_full_version >= '3.12' and python_full_version < '3.15' and sys_platform != 'darwin')",+ "python_full_version >= '3.12' and python_full_version < '3.15' and platform_machine == 'x86_64' and sys_platform == 'darwin'",]sdist = { url = "https://files.pythonhosted.org/packages/22/fd/89965aa4ac08c74998539fcbf24fa3540f3e15237fbeb6bcf9c908f4aade/numpy-2.5.1.tar.gz", hash = "sha256:a48a113e6afea91f5608793bafa7ef2ad481fefbda87ec5069f483de61cb9fa3", size = 20755553, upload-time = "2026-07-04T17:08:00.933Z" }wheels = [@@ -1327,7 +1404,7 @@ name = "secretstorage"version = "3.5.0"source = { registry = "https://pypi.org/simple" }dependencies = [- { name = "cryptography" },+ { name = "cryptography", version = "49.0.0", source = { registry = "https://pypi.org/simple" } },{ name = "jeepney" },]sdist = { url = "https://files.pythonhosted.org/packages/1c/03/e834bcd866f2f8a49a85eaff47340affa3bfa391ee9912a952a1faa68c7b/secretstorage-3.5.0.tar.gz", hash = "sha256:f04b8e4689cbce351744d5537bf6b1329c6fc68f91fa666f60a380edddcd11be", size = 19884, upload-time = "2025-11-23T19:02:53.191Z" }