# Chronos — Build Brief for Claude Code > This document is the complete specification and standing instruction set for building the > Chronos time-lapse ecosystem from scratch. It is written to be read by Claude Code at the > start of every session (via `CLAUDE.md`, see Appendix A) and to be the single source of > truth for scope, architecture, constraints and delivery order. > > Working name: **Chronos**. Three shipped programs — **Chronos** (Windows desktop client), > **Chronos Server** (Linux/Docker and Windows), **Chronos Uploader** (Windows) — sharing one > engine. Target audience: photographers, astro/landscape shooters, construction and > weather-cam operators, hobbyists worldwide. --- ## 0. How to work on this project (operating rules for Claude Code) ### 0.1 Kickoff message Paste this as the first message in Claude Code, from an empty repository that contains only this file at `docs/BRIEF.md` and the prototype dump at `docs/reference/chronos-prototype.md`: ``` Read docs/BRIEF.md completely before doing anything. It is the full specification for this repository and it overrides your defaults. Then: 1. Create CLAUDE.md from Appendix A of the brief, and docs/DECISIONS.md, docs/CHANGELOG.md. 2. Execute Phase 0 exactly as described in §22, stopping at its phase gate. At every phase gate, report: what was built, how to run it, test results on Windows and Linux, open decisions. Do not ask questions before the gate unless a decision is irreversible; otherwise decide, record it in docs/DECISIONS.md, and continue. ``` ### 0.2 Standing rules 1. **Zero third-party packages, everywhere.** No `` in any `.csproj`, including tests, tools and build scripts. Anything that is not the .NET BCL, a Microsoft shared framework that ships with the .NET SDK/runtime (`Microsoft.NETCore.App`, `Microsoft.AspNetCore.App`, `Microsoft.WindowsDesktop.App`, the Windows SDK targeting pack), or an operating-system API reached by P/Invoke or COM interop, is implemented in-house. CI fails the build if a `PackageReference` appears (§19.2). The prototype in `docs/reference/chronos-prototype.md` proves this is workable: it decodes images with WIC, encodes video with Media Foundation, parses EXIF/TIFF/XMP with its own parsers, and writes its own MP4 container. 2. **No external processes.** No FFmpeg, no ExifTool, no ImageMagick, no PowerShell scripts at runtime. The only OS executables/dialogs the product may invoke are listed in §8.6 (format-volume dialog, shell "open with", browser launch for links). 3. **Cross-platform core, Windows-only presentation.** `Chronos.Core`, `Chronos.Data`, `Chronos.Protocol` and `Chronos.Server` target `net10.0` and must build and pass tests on Linux. Windows-only code lives in `*.Windows` projects or the desktop apps. 4. **English everywhere in the codebase**: identifiers, comments, commit messages, docs. The prototype is written in Italian; port the algorithms, not the language. 5. **Every user-visible string is a resource.** No literal UI text in code or XAML. English is the source language; Italian is the first translation; all other languages follow in Phase 8 (§16). 6. **UI copy rules (mandatory):** labels ≤ 3 words when possible; no helper text or paragraphs anywhere in the UI; explanations live only in tooltips (≤ 2 sentences); every actionable control has a tooltip; empty states are one sentence plus one button; errors are one sentence saying what happened plus one action. 7. **Decide, record, continue.** When the brief is silent, choose the option that is simplest, safest for user data, and consistent with the constraints; write one line in `docs/DECISIONS.md` (date, decision, alternative, reason). Ask the human only at phase gates, or before any irreversible or data-destroying design choice. 8. **User data is sacred.** Never delete, move or format anything without (a) a verified hash match of every copied file and (b) an explicit user action. Every destructive operation is dry-run-able and shows its plan first. 9. **Definition of Done for every phase:** CI green on Gitea Actions (§19.1: the Linux jobs; the `windows` job once a Windows runner is registered, until then the Windows-only tests run on a Windows PC; amended 2026-10-23, R3); all tests green; no new warnings; `docs/DECISIONS.md` and `docs/CHANGELOG.md` updated; a short "how to try it" note in the phase report; localization completeness check passes for `en` and `it`. 10. **Commit style:** Conventional Commits (`feat(core): …`, `fix(server): …`), small commits, one concern each. Never commit generated binaries, fixtures downloaded by scripts, or secrets. 11. **Reference prototype:** `docs/reference/chronos-prototype.md` is a Repomix dump of the previous single-program prototype (C#/.NET 10, WinForms, zero packages). Its engine (metadata parsing, deflicker, holy-grail transitions, optical flow, motion blur, stabilization, virtual camera, time remap, stacking, Media Foundation encoding, MP4 muxing, self-tests) was validated on real material. Port those algorithms faithfully into the new structure, with English names and unit tests; do not copy its UI (WinForms) or its file layout. Search it with grep; do not try to read it whole. --- ## 1. Product vision Chronos turns folders of photos (RAW, JPEG, HEIC…) into finished time-lapse videos and keeps a lifetime archive of shoots organised, verified and searchable — on one PC or on a shared server. - **Import** memory cards with per-card rules, session detection, renaming and hash verification; import directly into a local archive or straight to a server. - **Analyse** every sequence deeply (metadata + pixels) and let the advisor set frame timing, motion blur, deflicker, transitions and export presets — with a reason for every choice, visible in a tooltip. - **Render** with the in-house engine and GPU encoders (H.264/HEVC/AV1 via Media Foundation) to purpose-built presets, from 720p previews to 8K 10-bit archives. - **Archive** hundreds of thousands of photos across years and cameras, on local or network drives, with an index that can always be rebuilt from the files themselves. - **Share** through Chronos Server: central archive, users with logins, uploads from the tiny Uploader, sync of projects, server-side jobs, render delegation to GPU-equipped clients, and a web admin panel — deployable as a Docker container (Unraid template included) or on Windows. ### 1.1 Goals (measurable) - A first-time user imports a card, gets a recommended preset, and renders a 1080p preview in under five interactions from launch. - A library of 500,000 photos in 2,000 sequences: Library screen opens in < 1 s, scrolls at 60 fps, filters respond in < 200 ms, full index rebuild from sidecars in < 10 min. - Rendering quality equals or exceeds the prototype's measured results (§20.4 regression thresholds), with hardware encoding used whenever a hardware MFT exists. - Every feature reachable without reading any documentation; every control explained by its tooltip; UI available in ≥ 30 languages with RTL support. - Server: 10 concurrent clients uploading at line speed; resumable uploads; zero data loss on crash (append-only ingest + manifest commit). ### 1.2 Non-goals (v1) - Audio tracks (P2: mux an external AAC file), HDR/PQ output, colour-managed display. - macOS/Linux desktop clients (server only), mobile apps, browser-based editing. - Cloud object storage backends (S3 etc.), multi-server federation. - General RAW *development* beyond what the render pipeline needs (no Lightroom clone). - GPU compute for image processing (CPU SIMD only in v1; keep interfaces open). - Real-time tethered capture, camera control. - Plugin system. --- ## 2. Hard constraints and allowed native surface ### 2.1 Language and platform decision **C# on .NET 10 LTS** for every component. Reasons: one toolchain for a cross-platform server and a first-class Windows desktop; WPF and ASP.NET Core ship with the SDK (no packages); mature BCL for crypto, HTTP/2, WebSockets, JSON, compression and SIMD (`System.Numerics.Vector`, `Vector256`); direct P/Invoke/COM interop to WIC, Media Foundation and `winsqlite3.dll`; the validated engine is already C#. Alternatives were rejected: Python (stdlib GUI is dated, no GPU encode, no PostgreSQL driver), C++ (UI and server cost), Rust/Go (no standard GUI, no SQLite/PostgreSQL in std), Java (JavaFX is external). Desktop UI: **WPF** with the built-in Fluent theme (`Application.ThemeMode`, available in WPF since .NET 9, refined in .NET 10) for a Windows 11 look with dark/light/system modes and system accent colour, plus in-house custom `FrameworkElement`s for charts, filmstrip, curve editors and the virtualized photo grid. If the Fluent theme proves inadequate for any control, restyle it with an in-house `ResourceDictionary` — never a package. Window chrome: `WindowChrome` + `DwmSetWindowAttribute` (dark title bar, Mica/backdrop where available). ### 2.2 Allowed native/OS surface (Windows) | Need | API (all OS components, no packages) | |---|---| | Image decoding incl. RAW/HEIC/WebP/AVIF when codecs installed | WIC (`IWICImagingFactory`… via COM interop) | | Video encoding, hardware MFTs (NVENC/QSV/AMF) | Media Foundation (`MFStartup`, `MFTEnumEx`, `IMFTransform`, `ICodecAPI`) | | Local database | `winsqlite3.dll` (ships with Windows 10 1709+ / Windows 11) via P/Invoke | | Volume identity, device arrival | `GetVolumeInformationW`, `GetDriveTypeW`, `WM_DEVICECHANGE`, `SetupAPI` if needed | | Format a card | `SHFormatDrive` (OS format dialog) | | GPU name/VRAM for encoder capability display | DXGI (`CreateDXGIFactory1`, `IDXGIAdapter::GetDesc`) | | Taskbar progress, toasts | `ITaskbarList3`; toasts via Windows SDK projection (`net10.0-windows10.0.19041.0` targeting pack) or in-house tray balloon | | MTP cameras (P2) | Windows Portable Devices (COM) | | Window chrome | `dwmapi.dll` | Linux (server): BCL only. No `libsqlite3`, no `libva`, no FFmpeg. PostgreSQL is reached through the in-house wire-protocol client (§6.3). ### 2.3 What this implies (and how the brief resolves it) - **RAW decoding** without libraw is tiered (§8.2): full in-house decode for DNG/TIFF/ JPEG/PNG and a growing set of native RAW formats; embedded full-size JPEG previews as a universal fallback (every major RAW format embeds one); on Windows, WIC with the free Microsoft "Raw Image Extension" gives full decode of everything else. - **Video encoding** on Linux has no OS encoder API; the server produces pure-managed outputs (MJPEG-AVI, image sequences, GIF, APNG) itself and delegates MP4/H.264/HEVC/AV1 jobs to **render nodes** — Chronos clients that volunteer their GPU (§14.7). An in-house intra-only H.264 encoder is a P2 universal fallback (§11.6). - **Testing** uses an in-house runner (`Chronos.Testing`, §20.1), not xUnit/NUnit. - **HEIC/HEIF** cannot be decoded in-house (HEVC intra decoder is out of scope): Windows clients decode via WIC (HEIF + HEVC extensions); the server stores originals and relies on proxies produced by a Windows client or render node. --- ## 3. Repository layout ``` chronos/ (Gitea repository BalboSoft/Chronos; amended 2026-10-23, R2) ├── CLAUDE.md operating rules (Appendix A) ├── Directory.Build.props version, LangVersion, nullable, warnings-as-errors, analyzers ├── Directory.Build.targets zero-package guard, resource generation hooks ├── Chronos.slnx ├── global.json pins .NET 10 SDK ├── src/ │ ├── Chronos.Core/ net10.0 — engine: Metadata, Imaging, Codecs, Analysis, Motion, Video (container/muxers), Archive model, Naming, Localization runtime │ ├── Chronos.Core.Windows/ net10.0-windows — WIC decoder, Media Foundation encoder, DXGI, device APIs, winsqlite3 binding │ ├── Chronos.Data/ net10.0 — IDatabase abstraction, SQL dialects, migrations, repositories, Postgres wire client (Chronos.Data.Postgres), SQLite driver surface (implemented by Core.Windows binding) │ ├── Chronos.Protocol/ net10.0 — API DTOs, JSON contexts (source-generated), chunked upload protocol, sync manifests, WebSocket event schema, version negotiation │ ├── Chronos.Server/ net10.0 — ASP.NET Core minimal API, auth, job engine, storage service, admin web UI (embedded static files), Docker entrypoint │ ├── Chronos.App/ net10.0-windows — WPF desktop client │ ├── Chronos.Uploader/ net10.0-windows — WPF uploader (tray-capable) │ ├── Chronos.Setup/ net10.0-windows — in-house installer/uninstaller (self-extracting, Add/Remove Programs, shortcuts, file associations) │ └── Chronos.Tools/ net10.0 — CLI: selftest, diagnose, make-icon, i18n export/check, fixtures fetch, changelog ├── tests/ │ ├── Chronos.Testing/ in-house test framework + runner (attributes, asserts, fixtures, JUnit XML) │ ├── Chronos.Core.Tests/ │ ├── Chronos.Data.Tests/ includes PostgreSQL integration tests (skipped without CHRONOS_TEST_PG) │ ├── Chronos.Server.Tests/ in-process Kestrel on a random port │ ├── Chronos.App.Tests/ view-model tests + XAML lint (tooltip/resource rules) + screenshot smoke (`--capture`) │ └── fixtures/ tiny checked-in samples; larger CC0 RAW samples fetched by `Chronos.Tools fixtures` ├── branding/ icon sources (SVG), generated ICO/PNG sets ├── i18n/ .resx sources (en) + translations, glossary, machine-translation notes ├── deploy/ │ ├── docker/Dockerfile, docker-compose.yml, entrypoint │ └── unraid/chronos.xml ├── .gitea/workflows/ ci.yml, release.yml, docker.yml, perf.yml (amended 2026-10-23, R2) └── docs/ BRIEF.md (this), DECISIONS.md, CHANGELOG.md, ARCHITECTURE.md (generated per phase), reference/chronos-prototype.md ``` Project references: `App` → `Core`, `Core.Windows`, `Data`, `Protocol`. `Server` → `Core`, `Data`, `Protocol`. `Uploader` → `Core` (hashing, metadata light), `Protocol`. `Core` and `Data` never reference anything Windows-specific; CI builds them on Linux. --- ## 4. Architecture ### 4.1 Component diagram ``` ┌────────────────────────────────────────────────────────────────┐ │ Chronos (WPF client) │ │ Library · Edit · Import · Archive manager · Jobs │ │ Local mode: SQLite + local/network archive │ │ Server mode: REST/WS client, proxies cache, render node │ └───────┬───────────────────────────────────────┬────────────────┘ │ HTTPS REST + WebSocket │ Memory cards (USB/SD) ▼ ▼ ┌───────────────────────────────────┐ ┌──────────────────────────┐ │ Chronos Server │ │ Chronos Uploader (WPF) │ │ Kestrel · API v1 · Auth · Jobs │◄───────────│ queue · watch folders │ │ Storage service · Admin web panel │ HTTPS │ resumable chunk upload │ │ Pure-managed encoders │ └──────────────────────────┘ └──────┬──────────────────┬─────────┘ │ │ ▼ ▼ PostgreSQL (Docker) Archive volume (/archive: originals, sidecars, proxies, renders) or SQLite (Windows) ``` ### 4.2 Shared engine `Chronos.Core` is the same assembly on client and server: metadata parsing, image codecs, analysis advisor, render pipeline, container writers. Only the *decoder/encoder providers* differ per platform, behind two interfaces: ```csharp public interface IImageDecoderProvider { bool CanDecode(ImageFormatInfo f); DecodedImage Decode(DecodeRequest r); } public interface IVideoEncoderProvider { IReadOnlyList Capabilities { get; } IVideoEncoderSession Open(EncodeSettings s); } ``` Registered providers, in priority order: client → `WicDecoderProvider`, then `ManagedDecoderProvider`; server → `ManagedDecoderProvider` only. Encoders: client → `MediaFoundationEncoderProvider` (hardware first, software H.264 fallback), then `ManagedEncoderProvider` (MJPEG/AVI, sequences, GIF, APNG); server → managed only, plus delegation to render nodes. ### 4.3 Data flow: card → archive → render ``` Card ──scan(light metadata)──► Import plan (sessions, names) ──copy+hash──► originals/ ──light analysis──► sequence.json sidecar + DB rows ──queue──► deep analysis job ──► proxies + thumbs ──► advisor recommendations + suggested presets User opens sequence ──► settings (project JSON) ──render──► exports/ + DB render row ``` Frames are streamed to the server by the client or uploader through chunked, resumable, hash-verified uploads; the server commits the frame into the archive layout and updates the sequence manifest atomically (write temp → fsync → rename). ### 4.4 Modes of the client | Mode | Storage | Index | Who renders | |---|---|---|---| | Local | local or network drive archive | SQLite | this PC | | Server-connected | server archive; local proxies/thumbs cache | server DB via API; local SQLite caches only | server (managed formats), render nodes (MP4), or this PC after downloading originals | | Mixed | both; each sequence has an `origin` and a `sync state` | both | as above | Workspace and projects (amended 2026-10-26, R8). The desktop edits in a **workspace**, a folder on a fast disk outside every library (default `%LOCALAPPDATA%\Chronos\workspace`, or `.\data\workspace` for a portable copy), never inside the library. A sequence's **home** is where it lives: this PC's archive (phase 5a) or a server (phase 5b). The home keeps the sequence's **projects**: Main, which is the sequence's own settings, and other named sets of edits ("4K landscape", "Vertical social"), each with a linear history of versions pushed and pulled like git, with no branches. The workspace holds a working copy of a project: its working state, its versions, the sequence's proxies and, when chosen, its originals. Final renders run where the originals are: at the home, or on this PC for a project whose originals the workspace holds, each such render then sent home with the project and the version it shows. A local-only library works the same way, its archive being the home. Workspace upkeep (amended 2026-10-26, R8). The workspace removes the media of projects in step with their home that were not opened for a while or exceed its size limit, keeps in its own trash what it cannot prove the home holds, and moves to another folder with its projects only after a plan (§12.3, §12.8). Nothing it removes is the only copy: versions, unsent work and local renders not sent stay. Server home (amended 2026-10-26, R8). A Chronos Server whose `server/info` lists the `projects` capability is the home of its sequences, with the same rules as this PC's archive (§7, §14.3, §14.5). A server sequence opens in the workspace like a sequence of this PC: its proxies are downloaded into the workspace, its versions are pushed to and pulled from the server, and its renders and analyses run on the server. The server is reached only through this PC's sign-in on the Server screen: a project of a server this PC is not signed in to still opens from the workspace and reads Offline. An older server's sequences open with proxies as before (§14.5). --- ## 5. Domain model Primary entities (identical concepts in SQLite and PostgreSQL; ids are UUIDv7 stored as `TEXT`/`uuid`; timestamps UTC ISO-8601/`timestamptz`): - **Archive** — id, name, root path, layout templates, schema version, created, proxy policy. - **Sequence** — id, archive id, title, folder (relative), camera make/model/serial, lens, first/last capture, frame count, median interval, total bytes, status flags (`analyzed_light`, `analyzed_deep`, `proxies_built`, `thumbs_built`, `rendered_count`, `verified_at`), hero frame id, tags, rating, notes (short), settings JSON (project), analysis report JSON (compact) + path to full report, origin (local/server), sync state, version counters (`settings_version`, `frames_version`), owner user id (server). - **Frame** — id, sequence id, index, relative path, file name, size, sha256, captured at (with sub-second and source: EXIF/XMP/filesystem), exposure time, f-number, ISO, focal length, exposure bias, white balance, orientation, width, height, format, embedded preview info (offset/length), light stats (mean log-luminance, clip fractions) once analysed, flags (missing, corrupt, duplicate, excluded). - **Render** — id, sequence id, preset name, settings JSON, output relative path, codec, width, height, fps, duration, bytes, created, produced by (client id / server / node), project id and project version id (the project and version rendered, the version only when the home holds it with the settings rendered; amended 2026-10-26, R8), sha256 and kind (amended 2026-11-05, owner review 1 R3/R8/R9: the SHA-256 of a single-file render, taken when it is recorded, null for an image sequence's folder, verified file by file when copied, and for a render recorded before migration 0010, hashed the first time it is copied, deleted or restored; kind null for a video or an image sequence, told apart by the codec, or `still` for one frame saved as an image, with fps 0 and duration 0). - **RenderCopy** (amended 2026-11-05, owner review 1 R3/R8/R9) — id, render id, path, sha256, bytes, copied at, copied by: one hash-verified copy of a render in a videos folder (§12.10). No foreign key to the render, so the copy of a server render downloaded to a PC is recorded too and a copy outlives its render; Chronos never deletes a copy. - **Project** (amended 2026-10-26, R8) — id, sequence id, name (1–60 characters, unique among the sequence's live projects), is main (one live Main per sequence), head version id and number, mirrored version id and mirrored settings version (Main: the version and the settings version of its last mirror into the sequence's settings), created by, created, updated, deleted. Derived from the project's sidecars (§7) and rebuilt from them. - **ProjectVersion** (amended 2026-10-26, R8) — id (UUIDv7 made by the client), project id, parent id, number (1…, unique per project), kind (commit, merge, restore, imported, external), author, client name, note, settings JSON in the portable form (every frame position parked by photo, canonical text, stored as text and never re-encoded), content hash (SHA-256 of that text's UTF-8 bytes), settings format, frames version, restored from, created, stored (when the home took it; none while only a workspace has it). Immutable once stored. - **Workspace** (amended 2026-10-26, R8) — no table: a folder that describes itself (`workspace.json` and one folder per project, §12.3). - **Job** — id, kind (scan, rebuild, verify, light-analyse, deep-analyse, proxies, thumbs, render, import, upload-commit, maintenance; backup, cleanup, and the read-only duplicates and orphans reports; empty-trash, stored as 18, which erases exactly the trash entries of a confirmed plan, erases nothing when the trash changed since, and is never scheduled: amended 2026-10-26, R6; move, stored as 14, a Reorganize that applies exactly a confirmed plan of new folders, titles and file names to sequences of the archive, its target, and holds the rest of it when paused, cancelled or failed: amended 2026-10-26, R7; convert, stored as 19, a conversion of exactly the photos a confirmed plan lists, its targets the sequences, each converted all or nothing into its own frames or a new sequence: amended 2026-10-26, R7; workspace-copy, stored as 20, the copy of a sequence's proxies (and originals, when chosen) and deep report into a workspace project's media, run by the desktop only: amended 2026-10-26, R8; workspace-render, stored as 21, a render on this PC from the originals a workspace project holds; workspace-send, stored as 22, those renders sent home with their project and version; workspace-move, stored as 23, the workspace folder moved with its projects; all three run by the desktop only: amended 2026-10-26, R8; video-copy, stored as 24, renders copied hash-verified into a videos folder, desktop and server: amended 2026-11-05, owner review 1 R3/R8/R9), target ids, state (queued, running, paused, done, failed, cancelled), progress (done/total, fps, eta), log tail, created by, node id, attempts, error, schedule id (the schedule that queued it; amended 2026-10-26, R10). - **Schedule** (amended 2026-10-26, R10) — id, system key (set, and unique, on a host's system schedules, §14.6), name, action (scan, verify, thumbnails, proxies, analysis, maintenance, backup, cleanup, duplicates, orphans), target (`current`: the host's archive), parameters JSON, recurrence (text, no cron: `every:m|h|d` from 5 minutes to a day, 1–168 hours or 1–366 days; `daily:HH:MM`; `weekly:mon,thu@HH:MM`; `monthly:<1–28>@HH:MM`; wall-clock times of the host's zone), catch-up, priority of its jobs, enabled, next run (none while disabled), last run, last job id, last outcome (queued, skipped-pending, skipped-offline, skipped-nothing, unavailable, failed:), created by, created, updated. - **FrameRemoval** (amended 2026-10-26, R6) — the tombstone of a photo removed from a sequence: sequence id, sha256, replacement sha256 (the converted file that replaced it, R7), reason (deleted, replaced), removed at. Written from the sidecar's `removed` list (§7) at every index sync, so a rebuild keeps it, leaving out content a frame of the sequence holds again; it goes with its sequence row and outlives the trash entry. - **MediaCard** (client) — id, volume serial, filesystem label, capacity, nickname, camera identity (Make/Model/BodySerial from first file), profile JSON, first/last seen, import history (job ids). - **User** (server) — id, username, display name, password hash (PBKDF2), role (admin, editor, uploader, viewer), permissions bitmask, quota bytes, used bytes, disabled, must-change-password, created, last login. - **Session/Token** (server) — token hash, user id, client name, created, expires, last used, revoked. - **RenderNode** (server) — id, user id, client name, capabilities JSON (codecs, hardware encoder names, max resolution), last heartbeat, state. - **Setting** — key/value (typed JSON), scope (app, archive, user). - **Tag**, **SequenceTag** — normalised for filtering. - **AuditLog** (server) — who did what to which sequence/user, when. Indexes: `frame(sequence_id, index)`, `frame(sha256)`, `frame(captured_at)`, `sequence(archive_id, first_capture)`, `sequence(camera_model)`, tags, jobs by state and by schedule, `schedules(enabled, next_run)` (amended 2026-10-26, R10), `frame_removals(sequence_id, sha256)` (the key) and `frame_removals(sha256)` (migration 0008; amended 2026-10-26, R6), `projects(sequence_id, name)` and `projects(sequence_id)` where Main, both on live rows only, `project_versions(project_id, number)` (migration 0009, with `renders.project_id` and `renders.project_version_id`; amended 2026-10-26, R8), `renders(created)` and `render_copies(render_id)` (migration 0010, with `renders.sha256`, `renders.kind` and the table `render_copies`, no backfill; amended 2026-11-05, owner review 1 R3/R8/R9). Paging everywhere (keyset pagination on `(first_capture, id)`). --- ## 6. Data layer ### 6.1 `Chronos.Data` abstraction ```csharp public interface IDatabase : IAsyncDisposable { Dialect Dialect { get; } // Sqlite | Postgres Task OpenAsync(CancellationToken ct); // connection from pool } public interface IDbSession : IAsyncDisposable { Task ExecuteAsync(string sql, params DbParam[] p); IAsyncEnumerable QueryAsync(string sql, params DbParam[] p); Task BeginAsync(); Task BulkInsertAsync(string table, IReadOnlyList columns, IAsyncEnumerable rows); // COPY on PG, multi-row INSERT on SQLite } ``` Hand-written SQL in repositories (`SequenceRepository`, `FrameRepository`, …); no ORM. Migrations: numbered `.sql` files per dialect in `Chronos.Data/Migrations/{sqlite,postgres}/`, applied at startup inside a transaction, recorded in `schema_migrations`. Dialect differences (types, `RETURNING`, upserts) are confined to SQL files and a small `SqlDialect` helper. ### 6.2 SQLite (client, and Windows standalone server) - Binding: `Chronos.Core.Windows/Sqlite/WinSqlite3.cs` P/Invoke to `winsqlite3.dll` (`sqlite3_open_v2`, `prepare_v2`, `step`, `reset`, `finalize`, `bind_*`, `column_*`, `exec`, `errmsg`, `last_insert_rowid`, `changes`, `busy_timeout`, `libversion`, `extended_result_codes`). UTF-8 marshalling by hand. Check `sqlite3_libversion() ≥ 3.31` at startup; probe `PRAGMA compile_options` and never depend on FTS/JSON extensions. - Pragmas: `journal_mode=WAL`, `synchronous=NORMAL`, `foreign_keys=ON`, `temp_store=MEMORY`, `cache_size=-65536`, `mmap_size=268435456`. - Location: `%LOCALAPPDATA%\Chronos\chronos.db` (never Documents/OneDrive-synced folders — SQLite in a synced folder corrupts). Portable mode: `portable.txt` next to the exe puts everything under `.\data\`. - Backups: `VACUUM INTO` copies into `backups` next to the index, made by the Backup jobs of the `index-backup` system schedule (§14.6: every day on the desktop, daily at 03:00 on a server, both with catch-up; the first start after an upgrade copies at once when the newest copy is a day old), by *Back up now* (Settings › Advanced) and *Back up database* (Archive › Maintenance), and of the index a restore replaces. Every copy prunes the folder to the largest *Copies kept* of the backup schedules (3 by default), so no schedule deletes copies another one keeps. Restore from Settings › Advanced. (Amended 2026-10-26, R10.) ### 6.3 PostgreSQL client (`Chronos.Data.Postgres`) — in-house wire protocol v3 - TCP + optional TLS via `SslStream` after `SSLRequest`; `sslmode` = disable | prefer | require | verify-full. - Startup (`user`, `database`, `application_name=chronos-server`, `client_encoding=UTF8`, `TimeZone=UTC`); authentication: SCRAM-SHA-256 (`Rfc2898DeriveBytes.Pbkdf2`, HMAC-SHA256, channel binding not required), MD5, cleartext, trust. - Simple query, extended query (Parse/Bind/Describe/Execute/Sync) with parameters in text format except `bytea` (binary), prepared-statement cache per connection, transactions, `COPY … FROM STDIN` for bulk inserts, `LISTEN/NOTIFY` (used for multi-instance job wake-ups, optional), cancellation via `CancelRequest`. - Type mapping: `text, varchar, int4, int8, float8, bool, bytea, timestamptz, uuid, jsonb, numeric(as string)`; arrays not needed. - Connection pool (min/max, health check `SELECT 1`, idle eviction), typed `PostgresException` carrying SQLSTATE, retry on transient errors (57P01, 08xxx). - Test suite runs against PostgreSQL 16 and 17 service containers in CI (§19). --- ## 7. Archive format on disk The archive is the source of truth; the database is an index that can be rebuilt from it. ``` / ├── .chronos/ │ ├── archive.json { id, name, schemaVersion, created, layoutTemplates, proxyPolicy } │ ├── index-snapshot.bin optional accelerator for rebuild (all sidecars concatenated + hash); ignored if stale │ ├── locks/ lease files for concurrent writers (server + client on same share) │ ├── journal/ rename-.json: a mass rename or Reorganize being applied; convert-.json, .staged, .pins, .photos: a conversion (below; amended 2026-10-26, R7) │ ├── staging/ copies an import is filing; convert-//: the files a conversion made, until they take their place (below; amended 2026-10-26, R7) │ └── trash/ deleted sequences and photos, and originals a conversion replaced, kept until Empty; .erased/: what Empty erased that a replaced entry needs; videos/: deleted renders (below; amended 2026-10-26, R6, R7; amended 2026-11-05, owner review 1 R3/R8/R9) ├── 2026/ │ └── 2026-09-28 Canon EOS R5 - Harbour sunset/ folder = expanded FolderTemplate │ ├── originals/ IMG_0001.CR2 … names = expanded FileTemplate │ ├── proxies/ 0001.jpg … (JPEG, long edge per policy; optional, regenerable) │ ├── exports/ 2026-09-28 Harbour sunset - 4K HEVC.mp4 … │ └── .chronos/ │ ├── sequence.json sidecar manifest (below) │ ├── analysis.json full deep-analysis report │ ├── project.json render settings (the "project"; Main's head, below) │ ├── projects/ /project.json + versions/000001-.json …; .trash/: deleted projects (below; amended 2026-10-26, R8) │ ├── thumbs.pack packed thumbnails (one file per sequence, indexed; avoids 100k tiny files on SMB) │ ├── rename-files.json the file renames of a Reorganize a crash interrupted (below; amended 2026-10-26, R7) │ └── *.pending.json journals of an ingest, a photo deletion, a frame replacement (replace.pending.json, a conversion or its undo; amended 2026-10-26, R7) or a restore a crash interrupted (below) ``` The root-level folders above (`.chronos/` with `locks/`, `journal/`, `staging/`, `trash/`, `trash/photos/` and `trash/videos/`) exist from the start (amended 2026-11-06, owner review 4 R3): whatever path is chosen as the archive root, on the desktop or the server (Docker or Windows), gets them when the archive is created, adopted or opened, and only the missing ones are made; nothing existing is touched. The root itself is created only for a new archive. A create whose folders cannot be made fails with the reason (drive or share unavailable, permission denied, read-only, a file in the way); an open never fails for it: the problem is logged and shown (§14.8 dashboard, `/health`). Per-sequence folders and the trash's `.erasing`/`.erased` are still made when needed. `sequence.json` (canonical, versioned, written atomically): `{ id, title, camera, lens, frames: [{ i, file, size, sha256, capturedAt, exposure, fNumber, iso, focal, bias, wb, orientation, w, h, format, previewOffset, previewLength, flags, source? }], tags, rating, notes, status, versions, createdBy, updatedAt, removed? }`. Amended 2026-10-26, R6: `removed: [{ sha256, replacement?, reason: Deleted | Replaced, at }]` holds the tombstones of the photos removed from the sequence (§5 FrameRemoval), left out when there are none; `frames[].source: { sha256, format, file, size }` names the file a converted frame was made from: a conversion's Replace writes it, and its undo and a conversion job that resumes read it (amended 2026-10-26, R7). A build that does not know either field keeps it and writes it back unchanged. Trash (amended 2026-10-26, R6). Nothing in it is erased except by *Empty* (§12.5, §14.8): - `trash/[-