Metadata-Version: 2.4
Name: curu-catalog
Version: 0.6.2
Summary: Catalogues a media estate in place by content and answers search queries over it.
Keywords: media,catalogue,search,embeddings,near-duplicates,postgresql,mcp
Author: James Veitch
License-Expression: MIT
License-File: LICENSE
Classifier: Development Status :: 4 - Beta
Classifier: Environment :: Console
Classifier: Intended Audience :: End Users/Desktop
Classifier: Operating System :: MacOS
Classifier: Operating System :: POSIX :: Linux
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3 :: Only
Classifier: Programming Language :: Python :: 3.12
Classifier: Topic :: Multimedia
Classifier: Topic :: Database
Requires-Dist: blake3>=1.0
Requires-Dist: pgvector>=0.4
Requires-Dist: psycopg[binary,pool]>=3.2
Requires-Dist: pydantic>=2.9
Requires-Dist: mcp>=2.3
Requires-Dist: curu-vision>=0.50.0,<0.51
Requires-Dist: numpy>=2.5.4
Requires-Dist: boto3>=1.40 ; extra == 's3'
Requires-Python: >=3.12, <3.13
Project-URL: Repository, https://github.com/darth-veitcher/curu-catalog
Project-URL: Documentation, https://github.com/darth-veitcher/curu-catalog/tree/main#readme
Project-URL: Changelog, https://github.com/darth-veitcher/curu-catalog/blob/main/CHANGELOG.md
Project-URL: Issues, https://github.com/darth-veitcher/curu-catalog/issues
Provides-Extra: s3
Description-Content-Type: text/markdown

# curu-catalog

## What is this

curu-catalog makes a catalogue of a media estate, searches it with text and finds the near
duplicates of a picture. A media estate is a large collection of pictures and videos on disks,
network shares and S3 buckets. The catalogue identifies each file by its content, not by its path, and
it never changes your files. It is for the owner of the estate and for the AI
agents that work for the owner. The catalogue is a PostgreSQL database for an estate of tens
of terabytes, such as the owner's estate of about 40 TB. Workers on other computers can share
the work.

## What you can do

| Task | Command | Section |
|---|---|---|
| Index a folder of pictures and videos | `curu-catalog index photos` | [Index a folder](#index-a-folder) |
| Index a network share (SMB or NFS) | `CURU_MOUNTS="estate://datasets=/Volumes/Datasets" curu-catalog index /Volumes/Datasets` | [Index a network share](#index-a-network-share) |
| Index the pictures and videos in an S3 bucket | `curu-catalog index s3://media/2026/` | [Index a bucket](#index-a-bucket) |
| Serve the pictures and videos to a page or a program by content hash | `curu-catalog media-serve --port 8120` | [Serve the media to a page or a program](#serve-the-media-to-a-page-or-a-program) |
| Put new pictures and videos into the content store, and give a program a link to one | `curu-catalog ingest new-photos` | [Keep new media in the content store](#keep-new-media-in-the-content-store) |
| Make the thumbnails of each picture and each shot | `curu-catalog thumbs-make` | [Make the thumbnails](#make-the-thumbnails) |
| Find the faces in your pictures | `curu-catalog faces-make` | [Find the faces in your pictures](#find-the-faces-in-your-pictures) |
| See the faces of a picture, or count the pictures in each face state | `curu-catalog faces photos/red-1.jpg` | [See the faces of a picture](#see-the-faces-of-a-picture) |
| Name the people in your pictures | `curu-catalog identity-make "Ada"` | [Name the people in your pictures](#name-the-people-in-your-pictures) |
| Record the people and characters that you know, with a key that never changes | `curu-catalog entity-make --kind character --name "Edmund Blackadder" --public-id wikidata:Q1756491` | [Record the people and characters that you know](#record-the-people-and-characters-that-you-know) |
| Let a program read the known entities that its caller can see | `curu-catalog known-entities --identity "https://id.example#owner"` | [Let a program read the known entities](#let-a-program-read-the-known-entities) |
| Export all identity data to a new file | `curu-catalog identity-export faces.jsonl` | [Export the identity data](#export-the-identity-data) |
| Remove the faces of one picture, of all pictures or of one person | `curu-catalog identity-remove --all` | [Remove the identity data](#remove-the-identity-data) |
| Show the captions of a picture or a video | `curu-catalog caption photos/red-1.jpg` | [Read the captions of a picture or a video](#read-the-captions-of-a-picture-or-a-video) |
| Read a thumbnail or the file of an asset | `curu-catalog thumb "$hash" --output red-thumb.jpg` | [Read a thumbnail or a file](#read-a-thumbnail-or-a-file) |
| Keep the catalogue correct after files change | `curu-catalog index photos --full` | [Keep the catalogue correct after files change](#keep-the-catalogue-correct-after-files-change) |
| Try again the files that did not decode | `curu-catalog index photos --retry-undecodable` | [Handle files that do not decode](#handle-files-that-do-not-decode) |
| Search pictures and videos with text | `curu-catalog search "a red car at dusk" -n 5` | [Search with text](#search-with-text) |
| Find the shots of a video in a time window | `curu-catalog timeline "$hash" --from 1 --to 3` | [Find the shots of a video in a time window](#find-the-shots-of-a-video-in-a-time-window) |
| See the earlier shot lists of a video | `curu-catalog timeline "$hash" --versions` | [See the earlier shot lists of a video](#see-the-earlier-shot-lists-of-a-video) |
| See the hashes and quality measurements of a picture | `curu-catalog signals photos/red-1.jpg` | [See the hashes and quality measurements of a picture](#see-the-hashes-and-quality-measurements-of-a-picture) |
| Find the near duplicates of a picture | `curu-catalog near photos/red-1.jpg` | [Find the near duplicates of a picture](#find-the-near-duplicates-of-a-picture) |
| Keep one text search saved | `curu-catalog query-save winter "a red car in snow" -n 5` | [Keep one text search saved](#keep-one-text-search-saved) |
| Read a gallery | `curu-catalog gallery-run keeps` | [Read a gallery](#read-a-gallery) |
| Delete pictures and videos in bulk | `curu-catalog bulk-delete "$hash1" "$hash2"` | [Delete in bulk](#delete-in-bulk) |
| Move subjects inside one share | `curu-catalog bulk-move "$hash1" curated` | [Move in bulk](#move-in-bulk) |
| Tag pictures in bulk | `curu-catalog bulk-tag "$hash1" --tag indoors` | [Tag in bulk](#tag-in-bulk) |
| Return the trashed files | `curu-catalog bulk-restore "<audit-id>"` | [Return the trashed files](#return-the-trashed-files) |
| Read the bulk ledger | `curu-catalog bulk-audit` | [Read the bulk ledger](#read-the-bulk-ledger) |
| Review from an agent | `curu-catalog tools` | [Review from an agent](#review-from-an-agent) |
| Measure one decision's threshold | `curu-catalog judge-report near` | [Measure a decision's threshold](#measure-a-decisions-threshold) |
| See the tags of a picture | `curu-catalog tags photos/red-1.jpg` | [See the tags of a picture](#see-the-tags-of-a-picture) |
| Record one run's outputs with `curu-catalog link-run` | `curu-catalog link-run "$run" v2 --output "$hash" --role final --intent "a red car at dusk"` | [Record one run's outputs](#record-one-runs-outputs) |
| Note one verdict with `curu-catalog judge-note` | `curu-catalog judge-note "$verdict-id" "the pose drifts"` | [Note one verdict](#note-one-verdict) |
| Serve the review page with `curu-catalog review-serve` | `curu-catalog review-serve --port 8110` | [Serve the review page](#serve-the-review-page) |
| Use the catalogue from another Python program | `from curu_catalog import gallery_run, thumbnail, read_bytes` | [Use the catalogue from another program](#use-the-catalogue-from-another-program) |
| Test a capability with the in-memory store | `from curu_catalog import MemoryStore` | [Test a capability with the in-memory store](#test-a-capability-with-the-in-memory-store) |
| Search pictures by one tag name | `curu-catalog tag-search indoors --page 2` | [Search pictures by one tag name](#search-pictures-by-one-tag-name) |
| Share the work between computers | `curu-catalog worker --identity nas-1 --daemon` | [Share the work between computers](#share-the-work-between-computers) |
| Run a worker from the Docker image | `docker pull darthveitcher/curu-worker:latest` | [Run a worker from the Docker image](#run-a-worker-from-the-docker-image) |
| Choose the hardware for the embeddings | `curu-catalog index photos --providers cpu` | [Choose the hardware for the embeddings](#choose-the-hardware-for-the-embeddings) |
| Use the model service for the embeddings and the tags | `CURU_VISION_URL=http://gpu-host:8765 curu-catalog worker --identity mini-1 --kinds embed.asset,tags.asset` | [Use the model service](#use-the-model-service) |
| Use the results in a program | `curu-catalog search "a red car" --json` | [Use the results in a program](#use-the-results-in-a-program) |
| Record one output without a model | `from curu_catalog import record_output` | [Record one output without a model](#record-one-output-without-a-model) |
| Handle errors | `curu-catalog index no-such-folder \|\| echo "exit code $?"` | [Handle errors](#handle-errors) |

## Install

You need these:

- Python 3.12 and [uv](https://docs.astral.sh/uv/).
- A C compiler and a Rust toolchain ([rustup](https://rustup.rs)). The install builds the
  Rust extension of curu-vision.
- PostgreSQL 18 with the pgvector extension 0.8.0 or later. The steps below start it in
  Docker. The image `pgvector/pgvector:pg18` had pgvector 0.8.7 on 2026-10-29.
- ffmpeg and ffprobe 6.0 or later on the path, and 8.1 or later on arm64. Only video work
  needs them.
- jq, to use the examples that read the JSON output.
- Read access to the GitHub repositories `darth-veitcher/curu-catalog` and
  `darth-veitcher/curu-vision`, which are private.

1. Install the `curu-catalog` command from this repository:

   ```bash
   uv tool install git+https://github.com/darth-veitcher/curu-catalog
   ```

2. Start PostgreSQL with pgvector, and make the database `curu` with the `vector` extension:

   ```bash
   docker run -d --rm --name curu-pg -p 127.0.0.1:5432:5432 \
     -e POSTGRES_PASSWORD=local-only -e POSTGRES_DB=curu pgvector/pgvector:pg18
   docker exec curu-pg psql -U postgres -d curu -c "CREATE EXTENSION IF NOT EXISTS vector;"
   ```

3. Download the weights of the embedding model one time, about 3 GB. Use the curu-vision
   tag that curu-catalog uses. The download can need a Hugging Face token in `HF_TOKEN`.
   After this step, curu-catalog uses no network:

   ```bash
   uvx --from git+https://github.com/darth-veitcher/curu-vision@v0.50.0 \
     python -m curu_vision fetch embeddinggemma-2
   ```

4. Tell curu-catalog where the catalogue is. Set the DSN (the connection string of the
   database) in the environment, and never in a file in the repository:

   ```bash
   export CURU_CATALOG_DSN="postgresql://postgres:local-only@127.0.0.1:5432/curu"
   ```

The container in step 2 has `--rm`, so Docker deletes it, and the catalogue, when it stops.
For a catalogue that you keep, see
[Deployment and operations](docs/reference/deployment.md).

## Quickstart

Put some pictures and a short video in a folder `photos`. Then index the folder and search
it:

```bash
curu-catalog index photos
curu-catalog search "a red picture" -n 3
```

The first command reads each file, identifies it by its content and stores a vector of
its meaning (an [embedding](#glossary)). It also records the [signals](#glossary) of each
picture and of each video shot. It does not change the files. Its report ends like this:

```text
signals recorded 8, recomputed 0, failed 0
files examined 7, assets created 7, locations added 7
rehashed 0, changed 0, missing 0, relinked 0, assets unlocated 0
```

The second command gives the three best matches, best first:

```text
1. score 0.7312 visual file:///home/me/photos/red-3.jpg
2. score 0.7309 visual file:///home/me/photos/clip.mp4 clip 0.000–2.000s
3. score 0.7299 visual file:///home/me/photos/red-1.jpg
not indexed: 0
```

A score near 0.7 is a good match, and a score near 0.5 is a weak match (measured: see
[Search with text](#search-with-text)). A video gives a match for each shot, with the time of
the shot. "not indexed" counts the assets that have no vector and no shots, so search cannot
find them.

## Index a folder

```bash
curu-catalog index photos
```

`index` reads each file under the folder and its subfolders, and makes a hash of its content.
Each different content is one asset. Two copies of one picture are one asset with two
locations. A new picture gets an embedding. Each video gets its shots, and each shot gets an
embedding. Each picture and each shot also gets its [signals](#glossary): see
[See the hashes and quality measurements of a picture](#see-the-hashes-and-quality-measurements-of-a-picture).

A second run does not hash again a file that has the same size and complete recorded work.
A picture is complete when it has a vector. A video is complete when the catalogue has its
shot facts. A file that did not decode is complete too: see
[Handle files that do not decode](#handle-files-that-do-not-decode). When a video misses shot vectors, the run embeds only those shots. When a picture
or a shot misses its signals, or they have an old [stamp](#glossary), the run adds only those
signals jobs.

The report gives one line for each file, then the totals:

| Value | What it means |
|---|---|
| `indexed` | Files that this run read and recorded. |
| `unchanged` | Files that this run did not hash again: the size is the same and the recorded work is complete. A signals job can still read the file. |
| `failed` | Files that this run could not use. Each one has its own line, with the reason. A line that ends with `(cannot decode)` is a file that did not decode. |
| `pending` | Files whose job another worker holds or has on the queue when this run ends. Each one has its own indented line with its job kind, its state and, when a worker holds it, that holder. The line is not shown when the number is 0. |
| `signals recorded` | Pictures and shots that got signals for the first time in this run. A second run of the same files gives 0. |
| `recomputed` (on the `signals` line) | Pictures and shots whose signals this run made again, because their stamp is old. |
| `failed` (on the `signals` line) | Pictures and shots that got no signals, for example a file that does not decode. `--json` gives each one with its reason. |
| `files examined` | All the files of this run. In the usual run, it is `indexed` + `unchanged` + `failed`, plus `pending` when another worker holds files at the end. |
| `assets created` | New contents. A copy of a known content adds a location, not an asset. |
| `locations added` | New locations (paths). |
| `cannot decode (known)` | Files that the run skipped, because they did not decode in an earlier run. One indented line for each file gives its reason. In the usual run, a file at a known path is also in `unchanged`. A copy at a new path is also a `failed` line. With `--full`, a file at a known path is in `rehashed`. With `--workers`, these files are on no other line. The line is not shown when the number is 0. |
| `symlinks skipped` | The [symlinks](#glossary) under the folder that the run did not follow. The line is not shown when the number is 0. |
| `not media skipped` | The files under the folder whose suffix is not that of a picture or a video, for example `.DS_Store` or `manifest.jsonl`. A `.txt` file with no media file of its name is in this number too. The run did not read them. The `@eaDir` folders, the `._` files and the symlinks are not in this number. The line is not shown when the number is 0. |

A failed file does not stop the run.

curu-catalog indexes only the files whose suffix is that of a picture or a video. The case of
the suffix has no effect:

- Pictures: `.jpg`, `.jpeg`, `.jpe`, `.jfif`, `.png`, `.apng`, `.gif`, `.webp`, `.bmp`,
  `.tif`, `.tiff`, `.heic`, `.heif` and `.avif`.
- Videos: `.mp4`, `.mov`, `.m4v`, `.webm`, `.mkv`, `.avi` and `.mts`.

It does not read the other files, such as `.DS_Store` or a `.json` file. It counts them on
the `not media skipped` line. A `.txt` file beside a media file of its name is a caption:
see [Read the captions of a picture or a video](#read-the-captions-of-a-picture-or-a-video). A file with one of these suffixes that does not
decode fails as `input`.

An index run may end while another worker still holds its jobs. The `index` command waits
up to 60 seconds at its end for the shared queue to settle. A still-busy queue reports its
held files as `pending`, and the run exits 0. The cap is the `CURU_INDEX_FLEET_WAIT`
environment value, 60 if you do not set it. Set it to 0 to end the run at once; the held
files still read as `pending`.

curu-catalog ignores the `@eaDir` folders and the `._` files that a
Synology NAS or a Mac puts beside your files.

curu-catalog does not follow a symlink, to a file or to a folder, under the folder that you
index. So it never reads a file outside that folder, and each computer finds the same files.
When the target of a link is in the folder, curu-catalog indexes the target at its own path.
The folder that you give can itself be a link.

## Index a network share

Mount the SMB or NFS share on the computer, then index the mount point. Give the share a
fixed name with `CURU_MOUNTS`:

```bash
export CURU_MOUNTS="estate://datasets=/Volumes/Datasets"
curu-catalog index /Volumes/Datasets/stills
```

`CURU_MOUNTS` holds `name=local path` pairs, separated by commas. The catalogue then records
`estate://datasets/stills/...`, and not the local path. Each computer sets its own local path
for the same name, for example `estate://datasets=/srv/estate` on the NAS. If a file is
under two local paths, the longer local path gives the name. If a location matches two
names, the worker uses the longer name to find the local path.

## Index a bucket

Give the catalogue the URL of the S3 server and the keys of a user that can only read.
Then index an `s3://bucket/prefix/` location, that is, a bucket and a folder in it:

```bash
export CURU_S3_ENDPOINT=http://nas:9000
export CURU_S3_ACCESS_KEY_ID=curu-reader CURU_S3_SECRET_ACCESS_KEY="$READER_SECRET"
curu-catalog index s3://media/2026/
```

The catalogue records each object as `s3://media/2026/...`. A picture in a bucket and the
same picture in a folder are one asset with two locations, because the content hash
identifies the picture. Search gives the `s3://` location of each result.

| Variable | What it does | Default |
|---|---|---|
| `CURU_S3_ENDPOINT` | The `http://` or `https://` URL of the S3 server, for example the RustFS server on the NAS | None. It is necessary |
| `CURU_S3_ACCESS_KEY_ID`, `CURU_S3_SECRET_ACCESS_KEY` | The keys of a user that can only read | None. They are necessary |
| `CURU_S3_REGION` | The region of the request signature | `us-east-1` |
| `CURU_S3_VIDEO_MODE` | How a video decodes: `stream` reads a link that expires, and `file` copies the video to a temporary file first | `stream` |
| `CURU_S3_URL_TTL` | How long a video link is valid, in seconds, from 60 to 604,800. A link that expires before ffmpeg finishes gives a `transient` failure. A longer link stays valid for longer if someone copies it | `3600` |
| `CURU_S3_FILE_LIMIT` | The largest video that the `file` mode copies, in bytes. The minimum is 1 | 8 GiB (8,589,934,592) |
| `CURU_S3_TMPDIR` | A folder that exists, for the temporary files of the `file` mode | The system temporary folder |

- Give the catalogue a user that can only read. The catalogue never writes, changes or
  deletes an object, and it never copies an object on the server. The bulk commands
  refuse an `s3://` location.
- A missing or wrong `CURU_S3_*` variable stops `index` with exit code 2, before it
  connects. The message names the variable and never shows a key.
- As for a folder, a second run reads no object that has the same size and complete
  recorded work. To read each object again, add `--full`.
- Each worker that takes jobs of a bucket needs the same `CURU_S3_*` variables.

## Keep new media in the content store

The content store keeps new pictures and videos in one S3 bucket. The key of each object
is made from its content hash, so no host needs a mount of a share to read it. Put a folder of new
media into the store, then let the workers index it:

```bash
export CURU_CAS_URL=s3://curu-cas/ CURU_CAS_S3_ENDPOINT=http://nas:9000
export CURU_CAS_S3_ACCESS_KEY_ID=curu-cas-reader CURU_CAS_S3_SECRET_ACCESS_KEY="$READ_SECRET"
export CURU_CAS_S3_WRITE_ACCESS_KEY_ID=curu-cas-writer
export CURU_CAS_S3_WRITE_SECRET_ACCESS_KEY="$WRITE_SECRET"
curu-catalog ingest new-photos
```

```text
files examined 6, put 6, bytes put 1,234,567, already stored 0, failed 0
not media skipped 1
queued 6
```

- `ingest` reads each media file of the folder and puts it into the store one time. It
  never changes, moves or deletes a file of the folder.
- `ingest` also puts the `.txt` caption file of each media file into the store, under
  the key of its own content hash. The caption becomes a fact of the media file. A `.txt`
  file with no media file of the same name stays out of the store, and it is not an asset.
- The catalogue records each object as `cas://blake3/v1/<hex><suffix>`. `<hex>` is the
  64 hexadecimal digits of the content hash. `<suffix>` is the lower-case suffix of its
  file, for example `.jpg`. That location names no bucket and no host, so a move of the
  store changes no catalogue row.
- `ingest` records the `cas://` location when it puts the object. So `media-serve` and
  `media-url` can give the object before a worker indexes it.
- The catalogue also records the origin of each file: the place that its bytes came from.
  No job reads an origin.
- `queued` counts the index jobs for the new objects. A worker with the
  [read key](#glossary) indexes them. It needs no `CURU_MOUNTS` entry for them. An object
  whose index job failed gets a new job at the next `ingest`.
- A second `ingest` of the folder does not read a media file again when the catalogue
  has its path, its size and its `cas://` location. It reads each caption file again.
  `--full` reads and hashes each file again, and it still puts no object twice.
- A file that changes during the ingest fails as `transient`, and the store does not
  take its new bytes. Run `ingest` again.
- The store refuses a second object with the same key. So `ingest` cannot change an object
  that the store holds.
- The store takes a file of 5 GiB or less. A larger file fails as `input`.
- `ingest` does not follow a symlink. A `symlinks skipped` line counts each one.
- `ingest` exits with code 1 when a file failed, and it names each failed file.

To give a program a picture or a video of the store, give it a
[link that expires](#glossary). The program reads the bytes from the link with no key,
until the link expires:

```bash
curu-catalog media-url "$hash"
curu-catalog media-url "$hash" --json
```

- The link is valid for `CURU_CAS_URL_TTL` seconds, 15 minutes by default. `--json`
  gives the time at which it expires, so the program can ask for a new link in time.
- The link is a secret until it expires. Give it only to the program that reads it.
- A shot gives the link of its video.
- An asset with no `cas://` location is not in the store: the command stops with exit
  code 2.
- `media-url` needs only the read key.

A Python program, such as curu, calls the same two functions from the package root. It
gives the store and the queue of its own catalogue connection:

```python
from curu_catalog import PgBackend, ingest, media_url

with PgBackend() as backend:
    report = ingest(backend.store, "new-photos", queue=backend.queue)
    link = media_url(backend.store, "blake3:v1:...")
    print(report.put, link.url, link.expires_at)
```

A program that makes one file at a time, such as curu, calls `ingest_file` for each
file. It gives one result, or a typed error for that file:

```python
from curu_catalog import PgBackend, TransientError, content_store, ingest_file

settings = {"CURU_CAS_URL": "s3://curu-cas/"}  # and the other CURU_CAS_* names
cas = content_store(settings)
with PgBackend() as backend:
    try:
        result = ingest_file(
            backend.store, "out/frame-1.png", queue=backend.queue, cas=cas
        )
    except TransientError:
        ...  # try the same file again later
    else:
        print(result.content_hash, result.location, result.new)
```

- `result.content_hash` is the content hash of the file, and `result.location` is its
  `cas://` location. The catalogue holds that location when the call returns.
  `result.new` is false when the store already held the bytes.
- `result.origin` is the URI of the path. `result.size` is the size of the file in bytes.
  `result.media_type` comes from the suffix, for example `image/png`.
- The path is the origin of the file, not a location. So no worker tries to read a path
  that is only on the computer of the program.
- `InputError` means that the file is not acceptable, for example a folder or a file that
  is not media. Do not try it again.
- `TransientError` means that the same call can be successful later, for example when
  the store does not answer. It is safe to call again with the same file.
- `InfrastructureError` means that a setting is missing or that the store refuses the
  key. Correct the settings first.
- `content_store` reads the settings from the mapping, not from the environment. Without
  `cas`, `ingest_file` reads them from the environment.
- `ingest_file` always reads `CURU_DERIVED_URL`, to refuse a path in the derived store.
  Without `reader`, it also reads `CURU_MOUNTS`.
- For the tests of a program, `MemoryContentStore` keeps the objects in memory, with
  `MemoryStore` and `MemoryJobQueue`. It needs no network.

| Variable | What it does | Default |
|---|---|---|
| `CURU_CAS_URL` | The bucket and the folder of the store, for example `s3://curu-cas/` | None. It is necessary |
| `CURU_CAS_S3_ENDPOINT` | The `http://` or `https://` URL of the S3 server | None. It is necessary |
| `CURU_CAS_S3_ACCESS_KEY_ID`, `CURU_CAS_S3_SECRET_ACCESS_KEY` | The read key: the key of a user that can only read the store. Each worker, `ingest`, `ingest_file` and `media-url` need it | None. They are necessary |
| `CURU_CAS_S3_WRITE_ACCESS_KEY_ID`, `CURU_CAS_S3_WRITE_SECRET_ACCESS_KEY` | The write key: the key of a user that can put and read, and cannot delete. Only `ingest` and `ingest_file` need it | None. Without it, `ingest` stops with exit code 1 at the first file that it must put, and `ingest_file` raises `InfrastructureError` |
| `CURU_CAS_S3_REGION` | The region of the request signature | `us-east-1` |
| `CURU_CAS_URL_TTL` | How long a link to an object of the store is valid, in seconds, from 60 to 604,800 | `900` |

## Serve the media to a page or a program

A page or a program can show a picture or play a video of the catalogue by its URL. The
[media service](#glossary) gives each content hash one URL that does not change and does
not expire. Start the service:

```bash
export CURU_CATALOG_SERVER_TOKEN="$MEDIA_TOKEN"
curu-catalog media-serve --host 0.0.0.0 --port 8120
```

In a second terminal, read a picture:

```bash
curl -H "Authorization: Bearer $MEDIA_TOKEN" -o red.jpg "http://media-host:8120/media/$hash"
```

| Route | What it gives |
|---|---|
| `GET /media/<hash>` | The file of the content hash. A `Range` header gives one part of it, for a video player |
| `GET /media/<hash>/thumb` | The thumbnail from the [derived store](#glossary). "Not found" when it is not made yet, or when `CURU_DERIVED_URL` is not set |

`<hash>` is the content hash `blake3:v1:<hex>`, or only its 64 hexadecimal digits.

| Answer | What it means |
|---|---|
| 200 | The bytes of the file or the thumbnail |
| 206 | The bytes of the one range of a `Range` header |
| 302 | The `redirect` mode: a link that expires to an object of the content store |
| 400 | The text is not a content hash, or the query string holds `token`, `access_token`, `X-Amz-Signature` or `X-Amz-Credential` |
| 401 | The bearer token is missing or wrong |
| 404 | The hash has no present location, the source refuses the read of the file, or the thumbnail is not there |
| 416 | The range is outside the file, or the header asks for more than one range |
| 503 | The catalogue, the store or the source does not answer. Try again later |

- The service only reads. It reads the file from the content store, a bucket or a folder.
- Put [TLS](#glossary) in front of the service, for example a reverse proxy: a server
  that takes the requests first and sends them on. The service uses HTTP only.
- Set the bind host with `--host`, or with `CURU_MEDIA_HOST` in a container.
- On [loopback](#glossary), the service starts with no access control. When you set a
  token, each request must carry it, on loopback too. On any other host, the service does
  not start until you set one of these:
  - `CURU_CATALOG_SERVER_TOKEN`: each request then carries `Authorization: Bearer <token>`.
  - `CURU_MEDIA_BEHIND_CONTROL=1`: a control in front of the service checks each request.
    It can be an [OIDC](#glossary) login, or the signed links of a CDN (a network of
    caches).
    With this setting, the service asks for no token, also when you set one.
- The service refuses a token in the query string of a URL, so the token never goes into
  the log of a proxy. It keeps no access log of its own.
- `CURU_MEDIA_MODE` chooses how a stored object goes to the client:
  - `proxy`, the default: the service sends the bytes. The client needs no route to the
    store.
  - `redirect`: the service answers with a redirect to a link that expires. The client
    then reads the bytes from the store. A page on `https` needs a store on `https` too.
- A file in a folder or in a bucket has no link of the content store, so the service
  always sends its bytes.

## Make the thumbnails

A gallery shows many pictures at a time. A program, such as the gallery of curu, reads a
small [thumbnail](#glossary) of each picture from the [derived store](#glossary). Set the
derived store before you index:

```bash
export CURU_DERIVED_URL=file:///srv/curu-derived/
curu-catalog index photos
```

Then `index` makes a thumbnail of each new picture, and of each shot of a new shot list. A
thumbnail is a JPEG that fits a square of 320 pixels. Its key in the store is
`thumb-1/320/<content hash>.jpg`, or `thumb-1/320/<shot key>.jpg` for a
[shot key](#glossary). Two copies of one picture share one thumbnail. The catalogue never
writes a thumbnail next to your files.

To make the thumbnails of a catalogue that exists, queue them, then run a worker that takes
the two thumbnail kinds:

```bash
curu-catalog thumbs-make
curu-catalog worker --identity thumbs-1 --kinds thumbs.asset,thumbs.shot
```

`thumbs-make` prints `queued <N> thumbs.asset and <M> thumbs.shot jobs`. With `--json`,
`pictures` and `shots` give the two counts. A count of 0 means that each subject already has
a thumbnail job on the queue, or that no subject has a present location.

| Variable | What it does | Default |
|---|---|---|
| `CURU_DERIVED_URL` | The derived store: `file:///folder/` (a folder that exists) or `s3://bucket/prefix/` | None. The catalogue makes no thumbnails |
| `CURU_DERIVED_S3_ENDPOINT` | The `http://` or `https://` URL of the S3 server of an `s3://` store | `CURU_S3_ENDPOINT` |
| `CURU_DERIVED_S3_ACCESS_KEY_ID`, `CURU_DERIVED_S3_SECRET_ACCESS_KEY` | The keys of a user that can write to the derived bucket | None. They are necessary for an `s3://` store |

- An `s3://` store uses `CURU_S3_REGION`, as the S3 source does.
- `thumbs-make` needs `CURU_DERIVED_URL`. For an `s3://` store, it also needs the two
  `CURU_DERIVED_S3_*` keys, and `CURU_DERIVED_S3_ENDPOINT` or `CURU_S3_ENDPOINT`. Without
  them, it stops with exit code 2 and names the variable.
- Give the workers of a fleet one store in a bucket, so that each computer can read each
  thumbnail.
- Use keys for the derived store that can write only to the derived bucket. The keys of
  the sources stay keys that can only read.
- `index` refuses the derived store, and each folder or bucket prefix that holds it or is in
  it, so a thumbnail never becomes an asset.
- A worker takes the thumbnail jobs only when its `--kinds` names them. A worker with these
  kinds and no `CURU_DERIVED_URL` stops at its first thumbnail job, with exit code 1. The
  message names the variable.
- A program that reads the store gets no thumbnail for an item that is not made yet. Run
  `thumbs-make`, then a thumbnail worker, to make it.

## Find the faces in your pictures

The catalogue can find each face in each picture, and keep its box and its face vector. A
[face vector](#glossary) is 128 numbers that describe one face. Two vectors of one
person are near each other. The faces are [identity data](#glossary), so the catalogue
keeps them apart from the other facts.

The index does not find the faces. Queue the face jobs, then run a worker that takes the
face kind:

```bash
curu-catalog faces-make
curu-catalog worker --identity faces-1 --kinds faces.asset
```

`faces-make` prints `queued <N> faces.asset jobs`. With `--json`, `queued` gives the jobs
that it queued. `current` gives the pictures that have a current
[face state](#glossary): `faces`, `no_faces` or `failed`. `removed` gives the pictures
whose faces you removed.

- The face models are YuNet and SFace, from curu-vision. They run on the CPU of the
  worker. No face vector goes to the model service. In a face run, a face vector goes
  only from the worker to the catalogue database.
- The worker loads the models on its first face job, from the model cache. A worker with
  no models in its cache tries the job again later. It never records `no_faces` for it.
- A picture with no face gets the state `no_faces`. A picture that no face worker has
  read is `not_indexed`.
- A picture that does not decode gets the state `failed`, with the reason.
- Two copies of one picture get one face job, because the faces belong to the content.
- When curu-vision changes a face model, the old faces become `stale`. Run `faces-make`
  again, and a worker finds the faces again.

## See the faces of a picture

To see the faces of one picture, give its content hash or a location. To count the
pictures in each face state, give `--summary`:

```bash
curu-catalog faces photos/red-1.jpg
curu-catalog faces --summary
```

The answer of one picture gives its state and the box and score of each face. A box is
in pixels of the picture: left, top, right and bottom. The score is the detection score
of the face model. It is more than 0.5 and at most 1. A higher score means that the model
is more sure that the box holds a face. The answer never gives a face vector, also with
`--json`.

| State | What it means |
|---|---|
| `faces` | The picture has one or more faces |
| `no_faces` | The face models found no face |
| `failed` | The picture did not decode. `detail` gives the reason |
| `stale` | The faces are from an older face model. Run `faces-make` again |
| `removed` | You removed the faces of the picture |
| `not_indexed` | No face worker has read the picture |

The summary prints one line, for example:

```text
faces 6, no faces 1, failed 0, stale 0, removed 0, not indexed 0; 36 faces in all
```

Each number before the semicolon is a count of pictures with a present location.
`faces in all` is the count of faces under the current face models.

## Name the people in your pictures

An [identity](#glossary) is one person, with the name that you give it. You assign the
faces of that person to the identity. The catalogue never names a person and never
assigns a face by itself.

First, see the positions of the faces of a picture with `faces`. Then make an identity,
and assign faces to it. A face is `SUBJECT@POSITION`: a content hash or a location, then
`@` and the position of the face:

```bash
curu-catalog identity-make "Ada"
curu-catalog identity-assign idn-0123456789ab --face photos/red-1.jpg@0 --face photos/red-2.jpg@1
```

`identity-make` prints the id of the new identity, such as `idn-0123456789ab`. The id never
changes. Two identities can have the same name, and the id tells them apart.

To correct an identity:

```bash
curu-catalog identity-rename idn-0123456789ab "Ada L."
curu-catalog identity-merge idn-ba98765432fe idn-0123456789ab
curu-catalog identity-split idn-0123456789ab "Cy" --face photos/red-2.jpg@1
curu-catalog identity-unassign --face photos/red-1.jpg@0
```

- `identity-rename` keeps the id and the faces.
- `identity-merge SOURCE TARGET` moves each face of SOURCE to TARGET. SOURCE keeps its id,
  and `identity-show SOURCE` names TARGET. The answer of `identity-merge` is the row of
  TARGET.
- `identity-split` makes a new identity and moves the named faces to it. It cannot move
  all the faces of the identity: rename the identity instead.
- `identity-unassign` removes the identity of a face. The face stays.
- A face has one identity at most. `identity-assign` refuses a face that has another
  identity. The message names that identity.
- `worker --identity` and `judge-record --identity` name a worker or a judge, not an
  identity.
- The bulk ledger records each change, with who and when. It holds ids and counts, never a
  name. Read it with `bulk-audit`.

To see the identities, list them, or show one with its faces:

```bash
curu-catalog identity-list
curu-catalog identity-show idn-0123456789ab
```

Each row gives the id, the name, and the counts of faces, pictures and stale faces. A face
is stale when a new face model replaced the faces of its picture. The catalogue keeps
your assignment, and `identity-show` gives it with no box. The answers never give a face
vector. A merged identity is not in the list, but `identity-show` still answers for it.

## Record the people and characters that you know

A [known entity](#glossary) is a person, a character or another thing that you know by
name. The catalogue gives each known entity a key that never changes. Other curu programs
use the key to name the entity in their documents.

A known entity is public or private. A public entity has one public id or more, such as
a Wikidata or an IMDb id. A private entity, such as a friend, has no public id. Its name,
role and description stay in the identity data, with the faces.

```bash
curu-catalog entity-make --kind character --name "Edmund Blackadder" --public-id wikidata:Q1756491
curu-catalog entity-make --kind person --name "Bob" --private --role brother
```

- `entity-make` prints the new entity: its key, kind, access, name and public ids. An
  example is `0193b1a2-7c4e-7d10-8a3b-5f2e9c1d4a77 character public Edmund Blackadder
  wikidata:Q1756491`. With `--json`, read the key from `key`.
- `--kind` and `--name` are necessary. The kinds are `person`, `character`, `animal`,
  `vehicle`, `structure`, `object` and `group`.
- `--role` and `--description` are optional. A description has 500 characters or fewer.
- A public id is `wikidata:Q<digits>`, `imdb:nm<digits>`, `imdb:tt<digits>` or
  `tmdb:<digits>`. Two entities cannot have the same public id. The message names the
  entity that has it.
- Only a person records or changes an entity. The bulk ledger records each change, with
  keys and counts, never a name.

To change an entity, or to show it:

```bash
curu-catalog entity-edit 0193b1a2-7c4e-7d10-8a3b-5f2e9c1d4a77 --name "The Black Adder" --add-public-id imdb:tt0084988
curu-catalog entity-show 0193b1a2-7c4e-7d10-8a3b-5f2e9c1d4a77
```

`entity-edit` keeps the key. A public entity must keep one public id or more.

When two entities are the same, merge them. To remove an entity, run a dry run first:

```bash
curu-catalog entity-merge 0193b1a2-0000-7000-8000-00000000aaaa 0193b1a2-7c4e-7d10-8a3b-5f2e9c1d4a77
curu-catalog entity-remove 0193b1a2-7c4e-7d10-8a3b-5f2e9c1d4a77
curu-catalog entity-remove 0193b1a2-7c4e-7d10-8a3b-5f2e9c1d4a77 --confirm
```

- `entity-merge SOURCE TARGET` keeps the key of TARGET. A read of SOURCE gives TARGET, so
  no old key breaks. The public ids and the links of SOURCE move to TARGET.
- A private and a public entity cannot merge.
- `entity-remove` without `--confirm` gives the count of the links and removes nothing.
  With `--confirm`, it removes the entity, its public ids, its links and its private name.

To link an identity, made with `identity-make`, to a known entity, run `identity-link`:

```bash
curu-catalog identity-link idn-0123456789ab 0193b1a2-7c4e-7d10-8a3b-5f2e9c1d4a77
curu-catalog identity-unlink idn-0123456789ab 0193b1a2-7c4e-7d10-8a3b-5f2e9c1d4a77
```

- A link holds the two ids, who made it and when. It holds no name.
- `identity-merge` moves the links of the source to the target. `identity-split` leaves
  them on the original identity.
- `identity-remove --identity` removes the links of the identity. It also removes each
  private entity that links to that identity only. The dry run gives both counts.
- Only a person links or unlinks.

## Let a program read the known entities

A program, such as curu, reads only the known entities that its caller can see. Set the
[owner identity](#glossary) in `CURU_CATALOG_OWNER_IDENTITY`. Its form is
`<issuer>#<subject>`: the URL of the login service, `#`, then the id that the login
service gives the person. The owner sees each entity. Each other caller sees the public
entities only.

```bash
export CURU_CATALOG_OWNER_IDENTITY="https://id.example#owner"
curu-catalog known-entities --identity "https://id.example#owner"
curu-catalog entity-assets 0193b1a2-7c4e-7d10-8a3b-5f2e9c1d4a77 --identity "https://id.example#owner"
curu-catalog entity-visible 0193b1a2-7c4e-7d10-8a3b-5f2e9c1d4a77 --identity "https://id.example#guest"
```

- `known-entities` lists each entity that the caller can see. Each has its key, kind,
  name, access (public or private), role, description, public ids and change time.
- `entity-assets` gives the content hashes of the pictures with the faces of each linked
  identity.
- `entity-visible` prints `<key> visible` or `<key> not visible`. With `--json`,
  `visible` is true or false. A key with no entity gives false.
- `--identity` of these three commands names the caller. It is not an identity that you
  made with `identity-make`.
- Without `--identity`, or with no owner identity set, the caller sees the public entities
  only.
- A caller that cannot see a private entity gets the same answer as for a key with no
  entity.
- The tools `known_entities`, `entity_assets` and `entity_visible` give the same answers.
  No tool writes an entity or a link.

## Export the identity data

To keep a copy of all identity data, export it to a new file. The file holds the faces,
the identities, the assignments, the face sample, the face answers, the private entities
and the links to the known entities:

```bash
curu-catalog identity-export faces.jsonl
```

To export one identity, add `--identity`. The file then holds the name of the identity
and each of its faces, with the vector of each current face. It also holds the pairs of
the face sample and the face answers that name one of its faces. It also holds the links
of the identity and the private entities that it links to:

```bash
curu-catalog identity-export ada.jsonl --identity idn-0123456789ab
```

The file is [JSON Lines](#glossary). The first line gives the format, its version and the
stamps of the face models, one for each [params hash](#glossary). In the export of all
data, each next line has a `kind`:

- A `face` line holds the content hash, the params hash and the position (the number of
  the face in the picture). It also holds the box, the score and the face vector.
- An `identity` line holds the id, the name, who made it and the identity that it merged
  into.
- An `assignment` line holds the identity id, the face, who assigned it and when.
- A `face_sample` line holds one pair of the stored face sample: its sample id, its two
  faces (`a` and `b`), its similarity and its band.
- A `face_answer` line holds one face answer: its two faces, `same` or `not-same`, who
  answered and when.

With `--identity`, the first line also gives the identity. Each next line gives one of its
faces, with who assigned it and when. A stale face has no box, no score and no vector.

Only your user can read the file. The command never writes over a file that exists, and
its answer gives only the counts.

## Remove the identity data

To remove identity data, name one picture or all pictures. The command is a dry run until
you add `--confirm`:

```bash
curu-catalog identity-remove --all                     # the counts only
curu-catalog identity-remove --all --confirm
curu-catalog identity-remove --subject photos/red-1.jpg --confirm
```

- A removal deletes the faces and their vectors. Then it cleans the old
  [row versions](#glossary) from the database files, so no table and no index keeps a
  row of a removed vector.
- A removal never changes a picture. It changes only the catalogue.
- Each removed picture keeps a [removed mark](#glossary) with no face data in it. The mark
  stops a later face run from reading the picture again.
- A removal marks each picture that has a face state: `faces`, `no_faces`, `failed` or
  `stale`. A picture that no face worker has read gets no mark, so a later `faces-make`
  queues it.
- The bulk ledger records each removal: who, when and the counts. Read it with
  `bulk-audit`.
- The nightly backups of a fleet keep identity data. A removed vector stays in the older
  backups until the retention deletes them. With one backup each night, the oldest backup
  is 6 to 7 weeks old. A week with no backup keeps an older backup longer.

To remove one person completely, name the identity. The faces of other people in the same
pictures stay:

```bash
curu-catalog identity-remove --identity idn-0123456789ab            # the counts only
curu-catalog identity-remove --identity idn-0123456789ab --confirm
```

- It removes the name of the identity, its assignments, and the face and the vector of
  each of its faces. It also removes each identity that was merged into it.
- Each removed face keeps a [removed face](#glossary) mark with no face data. A face run
  with the same face models does not find that face again. After a change of the face
  models, the face run can find the face again, as a new face with no identity.
- `--subject` also removes the assignments and the removed faces of that picture. The
  identities stay. `--all` also removes each identity, each assignment, each removed
  face, each link to a known entity and each private entity. The public entities stay.
- `identity-allow` does not clear a removed face. A face that you removed with its
  identity comes back after a change of the face models. It also comes back after a
  removal of its picture with `--subject` or `--all`, then `identity-allow`.

Each removal also deletes the pairs of the stored face sample and the face answers that
name a removed face. When the removal deletes some, the dry run gives their counts. A removal does
not delete the contact sheets in your folder. Delete them yourself.

To let a face run read the removed pictures again, clear their marks. Then run
`faces-make`:

```bash
curu-catalog identity-allow --all --confirm
```

## Read a thumbnail or a file

Write the thumbnail of a picture or a shot, or copy the file of an asset, to a new file:

```bash
hash=$(curu-catalog search "a red picture" --json | jq -r 'first(.results[] | select(.clip | not)).content_hash')
curu-catalog thumb "$hash" --output red-thumb.jpg --json
curu-catalog media-get "$hash" --output red.jpg --json
```

The subject is a content hash, a location or, for `thumb`, a [shot key](#glossary). A shot
key must be a shot of the current shot list.

The `--json` answer gives the subject, the byte count, the
[content type](#glossary), `sha256` and `output`, the path of the new file. `sha256` is the
SHA-256 of the bytes. It is not the content hash. `thumb` also gives `key`, the key in the
derived store, and `made`. `media-get` also gives the location that it read. When `made`
is false, the answer has no byte count, no `sha256` and no `output`.

- `thumb` needs `CURU_DERIVED_URL`. A thumbnail that is not made yet writes no file.
- `media-get` reads the first present location in sorted order: a folder, a share or a
  bucket. A shot has no file of its own, so use `thumb` for a shot.
- Both commands refuse an output path that exists, with exit code 2. They never write over
  a file.
- The `thumbnail` and `picture` tools give the same answers to an agent. They send the
  picture as image content: an MCP block that the client of the agent shows as a picture
  (see [the tools](docs/reference/tools.md)).

## Read the captions of a picture or a video

`index` keeps the caption of each picture and each video. It reads two sources:

- A `.txt` file beside the media file, with the same name: `frame.txt` beside `frame.png`.
  One `.txt` file gives the caption of each media file of its name, such as `a.png` and
  `a.jpg`. curu-caption and AI-Toolkit write captions this way.
- The caption inside a PNG file: the [iTXt chunk](#glossary) with the key `curu_caption:caption`, which
  curu-caption writes. The index reads it while it hashes the PNG, with no second read.

Show the captions of a picture or a video:

```bash
curu-catalog caption photos/red-1.jpg
curu-catalog caption photos/red-1.jpg --json
```

The text answer gives one line for each caption. The line gives the source, the location
of the media file and the first line of the text. A PNG caption shows `inside the file`
for its location. A location that is gone shows `(not present)`. With no caption, it says
`no caption`.

The `--json` answer gives `subject`, the content hash, also when you give a location. It gives `total`, the number
of captions, and `captions`. Each caption has these values:

| Value | Meaning |
|---|---|
| `source` | `txt` for a `.txt` file, or `png-itxt` for the caption inside a PNG file |
| `media_location` | The location of the media file of a `.txt` caption. A `png-itxt` caption has none |
| `caption_location` | The location of the `.txt` file. A `png-itxt` caption has none |
| `size` | The size of the `.txt` file in bytes, or of the text inside the PNG. The index compares it with the listed size to find a changed file |
| `caption_hash` | The [content hash](#glossary) of the caption file, or of the text inside the PNG |
| `text` | The text, with no white space at its ends |
| `present` | False when the media location is not present any more. For a `png-itxt` caption, false when the content has no present location |

- The `.txt` captions come first, in the order of their media locations. A content with
  two copies and two `.txt` files has two captions. The answer gives both.
- A changed `.txt` file gets its new text in the next `index`, also when the media file did
  not change. The index finds the change by the size of the file. A change of the same size
  needs `index --full`.
- A deleted `.txt` file loses its caption in the next `index`.
- An empty `.txt` file gives no caption. A `.txt` file of more than 1 MiB is not a
  caption. Its job fails as `input`, and the catalogue keeps the earlier caption of the
  file, if there is one. A read fault fails the job as `transient` and keeps the earlier
  caption, and the next `index` tries again. The index report does not show these
  failures: see the queue in [Run workers](docs/workers.md).
- A PNG that the catalogue indexed before it read captions has no PNG caption yet. Run
  `index --full` one time to read it.
- A `.txt` file with no media file of its name is on the `not media skipped` line.
- The search does not use the captions yet.
- The `caption` tool gives the same answer to an agent (see
  [the tools](docs/reference/tools.md)).

## Keep the catalogue correct after files change

Files change, move and disappear. Run a full pass to make the catalogue agree with the
folder again:

```bash
curu-catalog index photos --full
```

The [usual run](#glossary) uses the recorded size of each file to find a change. So it does
not see new content of the same size. `--full` reads every file again and makes its hash from
its bytes. The full pass adds these values to the report:

| Value | What it means |
|---|---|
| `rehashed` | Files that `--full` read again and found with the same content. |
| `changed` | Paths that now hold new content. The path points to a new asset. The old asset keeps all its facts. |
| `missing` | Paths that the folder no longer has. The catalogue records them as missing and deletes nothing. |
| `relinked` | Paths that were missing and are back. |
| `assets unlocated` | Assets with no present path. Their facts stay in the catalogue. |

In a full pass, `files examined` is `indexed` + `rehashed` + `changed` + `missing` +
`failed`, plus `pending` when another worker holds files at the end.

A moved file is a new path for an asset that the catalogue knows. The usual run adds the new
path at no model cost, and the next full pass records the old path as missing.

A file that the run cannot read for a short time, for example on a lost network share, fails
as `transient`. The catalogue never records it as missing.

## Handle files that do not decode

A broken file, such as a JPEG that is not complete, an empty file or a program with a
picture's name, does not decode. The first run that reads it records a "cannot decode" fact on its content.
The fact gives the reason and the [decoder](#glossary) that refused the file:

```text
failed file:///home/me/photos/broken.jpg (input, retryable=False): cannot decode image: ... (cannot decode)
```

The next runs and workers do not decode the file again or queue its jobs. A `--full` run
still reads its bytes to make the content hash. The report counts the file on the
`cannot decode (known)` line instead:

```text
cannot decode (known) 1
  cannot decode file:///home/me/photos/broken.jpg: cannot decode image: ... (curu-vision/image-decode image_decode image-decode-1 pillow 13.0.0)
```

- The decoder of a picture is the curu-vision picture decoder (`curu-vision/image-decode`).
  Its version is the [method version](#glossary) of the picture decode and the Pillow
  release. One fact applies to the vector and to the signals of the picture.
- The decoder of a video and its shots is the curu-vision video decoder
  (`curu-vision/media`). Its version is the method versions of the probe and of the frame
  decode.
- After an update that changes one of these versions, the old fact is not current any more.
  The next run and the next worker start then try the file one more time. An update of
  curu-vision that keeps the versions keeps each fact current.
- The fact of a video also records the ffmpeg version of the computer that refused it. An
  update of ffmpeg alone does not make a run decode the file again.
- A copy of the same broken bytes at a new path fails with `(cannot decode)` and queues no
  job.
- A `transient` failure, for example a share that does not respond, never gives this fact.

To try the files again, for example after you repair them or update ffmpeg, give
`--retry-undecodable`:

```bash
curu-catalog index photos --retry-undecodable
```

A file that fails again gets no second fact. A file that now decodes gets its vector and its
signals.

## Search with text

```bash
curu-catalog search "a red car at dusk" -n 5
```

`search` gives the best `-n` matches (10 if you do not give `-n`), best first. Each line
gives the rank, the score, the [match signal](#glossary) and the first path. A video match
also gives the start and end of the matched shot, in seconds.

- The score is the [cosine similarity](#glossary) between the text and the picture or the
  shot, from -1 to 1. A higher score means a nearer meaning.
- Use the score to sort the matches for one search. It is not a probability, and
  curu-catalog removes no match because of a low score.
- A test on 2026-10-27 used the test samples of curu-vision: three photos (cats, a tiger, a
  football match) and a video of a sea turtle. A text and the content that it describes gave
  0.68 to 0.76. A text and a different content gave 0.49 to 0.59.
- A search for something that is not in the catalogue still gives matches. In the same test,
  the best match for "a red sports car" had a score of 0.56.
- `not indexed` is the number of assets that have no vector and no shots, for example a
  picture whose embedding failed. A video whose shots have no vectors is not in this count. Search cannot find them, and it shows them apart from "no match".
- Search compares only the vectors of the current [stamp](#glossary). A vector of an older
  model or an older preprocessing stays in the catalogue, but search does not show it. The
  next `index` run of its folder embeds the picture or the shot again.

A search gives only the paths that are present. An asset whose files all disappeared can
still match, with no path.

## Find the shots of a video in a time window

A shot is a continuous run of frames from one camera take. `timeline` gives the shots of a
video asset that overlap a time window, from the facts in the catalogue. Give the asset by
its content hash, for example from a search:

```bash
hash=$(curu-catalog search "a red picture" --json | jq -r 'first(.results[] | select(.clip)).content_hash')
curu-catalog timeline "$hash" --from 1 --to 3 --count 2
```

```text
shot 0: 0.000–2.000s (start, score 0.00)
shot 1: 2.000–4.000s (cut, score 2.00)
method shots-3
frame at 1.667s
frame at 2.333s
```

- `--from` and `--to` give the window in seconds from the start of the video.
- Each video has one current [shot list](#glossary). A shot's number is its place in that
  list, from 0.
- Each shot line gives its number, its start and end in seconds, how it starts and its
  boundary score. A shot starts with `start` (the first shot), `cut` (a sudden change) or
  `gradual` (a fade or a dissolve).
- The boundary score is the change of colours at the start of the shot, from 0 (the same
  colours) to 2 (no colours in common). It is not a probability. curu-vision 0.8.0
  ([shot method](#glossary) `shots-3`) marks a cut only at a score of 0.4 or more. The red-to-blue cut of the
  example gives 2.00.
- `--count` sets the number of frame times in the window, at equal intervals (1 if you do
  not give it). curu-catalog gives the times only. It does not decode the frames, and
  `--size` has no effect.
- For a picture, or a video that has no shots yet, the answer is "not indexed: no shot facts
  for this content yet".
- `method` names the [shot method](#glossary) of the current shot list. When the answer is
  "not indexed", there is no `method` line.
- A curu-vision update can change the shot method. If `method` is not the shot method of
  the pinned curu-vision, the shot list is stale. Then run `curu-catalog index` on the
  folder. That run finds the shots of each video again, and the new shot list replaces the
  old list as a whole. The next run decodes no video. A worker start does not find the shots
  again.
- A shot that keeps its first and last frame in the new list keeps its vector. Its signals
  and its "cannot decode" fact stay too, but the curu-vision update makes them stale. A shot
  with other frames gets new facts.

## See the earlier shot lists of a video

Each new [shot list](#glossary) of a video is a new version. The current version is the list that every
command uses. The earlier versions stay in the catalogue as history. `timeline --versions`
lists them:

```bash
hash=$(curu-catalog search "a red picture" --json | jq -r 'first(.results[] | select(.clip)).content_hash')
curu-catalog timeline "$hash" --versions
```

```text
version 1: shots-3, 2 shots, 4.000s decoded, 2026-10-29T12:00:00Z to current
```

- Each line gives the version number, its shot method, its number of shots and its decoded
  length. Then it gives when the version started, and when it ended or `current`.
- The decoded length is the end of the last shot, or the time where the decode stopped
  early. A value below the length of the video means that the decode stopped early.
- The times are UTC.
- A `shots.asset` job under a new shot method records a new version, but not when its
  decode stops early (see the next item). A `shots.asset` job under the same shot method
  that finds the same shots records no new version.
- A decode that stops early, for example on a file that is cut off, does not replace a
  version that covers more of the video.
- For a picture, or a video that has no shots yet, the answer is "no shot list for this
  content yet".
- Do not give `--from`, `--to`, `--count` or `--size` with `--versions`. If you give one of
  them, the command stops with exit code 2.

## See the hashes and quality measurements of a picture

Each index run records the [signals](#glossary) of each picture and of each video shot.
Signals are two [perceptual hashes](#glossary), a flat flag and eight quality measurements.
curu-catalog records the numbers only. It does not decide that a picture is blurred or a copy.

```bash
curu-catalog signals photos/red-1.jpg
curu-catalog signals photos/clip.mp4 --at 3
```

The first command prints this. The example shows only the first of the `provenance` lines:

```text
signals of blake3:v1:f2e803663c4a9074d85244e15d335e2942cb324edb5901382c563743da0e7b99
phash 88b36b86ed527a64
dhash 0000000000000000
flat no
measurement blur_direction 44.3751
measurement bright_clipped 0
measurement colourfulness 67.6906
measurement contrast_spread 2
measurement dark_clipped 0
measurement detail 4.15836
measurement directionality 0.253582
measurement noise 0.322785
stamp hash-2, measure-1, image-decode-1, analysis side 512
provenance analysis_size [96, 96]
...
```

- Give the picture by its path, its location URI or its content hash.
- A video has signals for each shot, from the middle frame of the shot. Give the shot by its
  number in the current shot list, from 0, with `--shot`. Or give a time in seconds with
  `--at`.
- Without `--shot` or `--at`, the command stops with exit code 2 and gives the number of
  shots of the video.
- `phash` and `dhash` are perceptual hashes: 64-bit numbers in 16 hex digits. They stay
  almost the same when a picture is resized or saved again as JPEG.
- `flat yes` means that the picture has no variation, for example one solid colour. Its
  hashes then tell you nothing about its content. Each shot of the example video is one
  solid colour, so the second command gives `flat yes`.
- `detail` is the variance of the Laplacian, a measure of fine edges. A higher value means
  more fine detail. Blur makes it lower. Compare it only between pictures of the same kind.
- `directionality` goes from 0 to 1. A value near 1 means that the edges go in one direction,
  as motion blur makes them. `blur_direction` gives that direction in degrees, from 0 to 180.
- `dark_clipped` and `bright_clipped` are the shares of pixels, from 0 to 1, that are almost
  black or almost white. A high value means lost shadows or highlights.
- `contrast_spread` is the range of the middle brightness values, from 0 to 255. A low value
  means a flat, grey picture.
- `noise` is the estimated noise, in levels of 255. A higher value means more grain.
- `colourfulness` is about 0 for a grey picture, and above 100 for strong colours. A higher
  value means stronger colours.
- A measurement that cannot be made is not shown. It is never shown as 0. `detail`,
  `directionality` and `noise` need a picture of 3 pixels a side or more. `blur_direction`
  is not shown when `directionality` is 0, for example on a flat picture.
- `stamp` names the versions that made the numbers. `analysis side` is the largest side, in
  pixels, at which curu-vision measures a picture. curu-catalog compares numbers only when
  their stamps are the same.
- The `provenance` lines give each detail of how curu-vision made the numbers.
  `provenance package_version` names the curu-vision release, which is not part of the
  stamp.
- A curu-vision update that changes a [method version](#glossary) of the stamp makes the old
  signals stale. An update that keeps each method version keeps the signals current.
- The next start of a worker that takes a [signals kind](#glossary) computes the stale
  signals again, for each picture and shot with a present path. An index run does this for
  the files of its folder. The old signals stay in the catalogue.
- `cannot decode: <reason> (<decoder>)` means that the picture, or the frame of the shot,
  did not decode. See [Handle files that do not decode](#handle-files-that-do-not-decode).
- `not hashed: no signal facts yet` means that the picture has no signals. Run
  `curu-catalog index` on its folder, or start a worker (see
  [Share the work between computers](#share-the-work-between-computers)).
- `not hashed: its signal facts are under an older stamp; refresh to recompute` means that
  the signals are stale. To refresh, start a worker, or run `curu-catalog index` on its
  folder again.

## Find the near duplicates of a picture

A near duplicate is the same picture with small changes, for example a smaller size or a new
JPEG save. It can also be a video shot that shows the picture. `near` compares the pHashes, so
it finds near duplicates, not pictures of a similar subject.

This example makes a test picture and a JPEG copy at half size. Then it indexes them and asks
for the near duplicates of the test picture:

```bash
mkdir -p copies
ffmpeg -y -loglevel error -f lavfi -i testsrc=size=640x480 -frames:v 1 copies/card.png
ffmpeg -y -loglevel error -i copies/card.png -vf scale=320:240 -q:v 8 copies/card-small.jpg
curu-catalog index copies
curu-catalog near copies/card.png
```

The last command prints:

```text
near duplicates of copies/card.png (distance ≤ 6): 1 match, showing 1–1
 1. d=2 (dhash 0)  file:///home/me/copies/card-small.jpg
```

- Give the picture by its path, its location URI or its content hash. For a video, give one
  shot with `--shot` or `--at`, as for `signals`.
- `d` is the [pHash distance](#glossary): the number of bits, from 0 to 64, that are
  different in the two pHashes. A lower value means a nearer duplicate.
- A distance of 0 means that the two pHashes are the same. Usually the picture is the same,
  in another file or another format.
- A distance of 6 or less is a near duplicate. A copy at half size, or saved again as JPEG,
  stays in this range when the picture is 32 pixels a side or more.
- A distance of 20 or more is a different picture. In this example, the six pictures in
  `photos` are at 26 to 32 from the test picture.
- `dhash` is the same distance for the dHash, the second perceptual hash. When two matches
  have the same `d`, the match with the lower `dhash` is first.
- The answer gives every match up to the distance, nearest first. The first line gives the
  total and the matches that it shows.
- `--distance` sets the largest distance, from 0 to 16. The default is 6. Above 16, a
  distance does not mean a near duplicate, so the command stops with exit code 2.
- `--page-size` sets the matches on each page, from 1 to 200. The default is 20. Use
  `--page 2` for the next page, and continue until you have the total.
- A shot match gives the location of its video, the shot number and the time range of the
  shot.
- `below near-copy limit` marks a picture under 32 pixels a side. For such a picture, a near
  duplicate can be at a distance of more than 6.
- The command compares only the signals that have the current stamp. It does not compare or
  count the pictures and shots whose signals have a different stamp. `near --json` gives the
  stamp that it used. After a curu-vision update that changes the stamp, start a worker that
  takes a signals kind. It makes the signals of each picture and shot with a present path
  current.
- "not hashed" means that the picture has no signals, or only stale signals, as for
  `signals`. "cannot decode" means that the picture did not decode, as for `signals`. "flat" means that the picture has no variation, so its pHash tells nothing and
  the command gives no matches.
- A query is fast at estate size. A test generated 500,000 sets of current signals and
  500,000 older sets. 95 % of its queries took 0.45 seconds or less, and the slowest took
  0.79 seconds (see [Technical notes](#technical-notes)).

## Measure a decision's threshold

The catalogue measures each threshold before it uses it. No threshold value
comes from a model or a guess. The judged sets come from the catalogue's
rows only: no media read builds them. The near set reads the `sddb` folder
alone; the cull set reads it and the junk folder, and its name says both:
`sddb-junk-cull`.
`judge-sheets` writes contact sheets of the sampled pairs into a folder you
name, outside the repository. The sample is even over the distances 0 to 16.

```bash
curu-catalog judge-sheets near ~/sheets-near
```

Each pair carries its sample id and its distance. Judge each pair, then
record its answer. The answer word is `same` or `not-same` for `near`,
`keep` or `junk` for `cull`. Every answer is a human fact, and `owner`
applies without `--identity`. A corrected answer supersedes the older one;
the catalogue deletes nothing.

```bash
curu-catalog judge-record near 1 same
```

`judge-report` states, for each distance, the precision, the recall, the
answer count and the confidence interval. No model runs and nothing decodes.

```bash
curu-catalog judge-report near
```

The meaning in practice: a precision of 0.93 says that 93 of 100 pairs the
distance calls the same picture really look like it. A recall
of 0.90 says it finds 90 of 100 of the judged true duplicates. The interval
says how far each figure moves with the sample size.

You pick the value from the report. An ADR records the value, the judged
set and the figures. `judge-apply` then projects the verdicts. The verdicts
sit beside the search answers; a different threshold re-projects the same
facts with no decode and no model. The verdicts never hide a search result.

```bash
curu-catalog judge-apply near 6 --adr adr-near-2
```

Delete the contact sheets after judging; the sheets are the only thing you
throw away. The judgments stay in the catalogue. [docs/judging.md](docs/judging.md) walks the whole five steps.

### Measure the face threshold

The `face` decision measures when two faces show one person. Run a face run first (see
[Find the faces in your pictures](#find-the-faces-in-your-pictures)). Then write the sheets
of a face sample into a new folder:

```bash
curu-catalog judge-sheets face ~/sheets-faces
```

- The command measures each pair of two faces in two pictures, with the face similarity of
  curu-vision. The similarity is from -1 to 1. A higher value means more alike.
- It takes up to 8 pairs from each band of 0.05 of similarity. `--per-band` changes the 8.
  The same faces give the same pairs with the same ids.
- Each tile shows the two face crops, the sample id and the similarity. The label holds no
  path and no name of a person.
- A new run replaces the stored sample and its ids. Record the ids of the newest sheets
  only. A folder that holds sheets needs `--new`.

Record `same` or `not-same` for each sample id. The catalogue keeps each answer with the
identity data, not with the facts. A later answer supersedes the earlier one, and both
stay:

```bash
curu-catalog judge-record face 1 same
```

`judge-report face` gives the precision and the recall of `same` at each cut. A cut calls
`same` each pair at or above it. The report names the measure and the face stamp, so the
ADR of the threshold can record both. The measure `cosine-1` is the cosine of the angle
between the two face vectors. An answer on a face of an older face stamp is stale: the
report counts it, and no figure uses it.

```bash
curu-catalog judge-report face
```

`judge-apply face` refuses. The catalogue does not use the face threshold yet.

## Keep one text search saved

Keep one text search saved under a name, and run it against the facts now. The
run is the search command's own answer: the same rank and the same scores. New
pictures change the answer, never the saved text.

```bash
curu-catalog query-save winter "a red car in snow" -n 5
curu-catalog query-run winter
curu-catalog query-list
curu-catalog query-remove winter
```

`-n` gives the page size of each run (10 if you do not give it).

The name is unique. A same-name save is refused with its reason; the first save
stands. `query-run` reads the facts the catalogue holds now: new pictures change
the answer, never the saved text. `query-list` names what you saved, each with
its text and page size. `query-remove` frees the name: a removed query's
[galleries](#glossary) state that the query is gone, and every other command
answers whole. After the remove, that name saves again, and that save's own
row is new.

## Read a gallery

A gallery is a named view: a saved query's fresh run, or the owner's own
hand-made list. A query member shows its saved query's fresh run; a hand member names
its own subject, with locations and no score.

```bash
curu-catalog gallery-make keeps
curu-catalog gallery-add keeps --query winter
curu-catalog gallery-add keeps "file:///volumes/datasets/photos/red-1.jpg" --added-by owner
curu-catalog gallery-run keeps
curu-catalog gallery-list
curu-catalog gallery-remove keeps
```

The command refuses a same-name make with its name, and the first one
stands. A query member shows its saved query's fresh run: the
member's own rows answer with the query's rank and total, and new facts
change them. A hand member is your own row: a human fact no machine fact
overwrites or outranks; nothing rewrites its subject or its place. A removed
query's query member states it in its own row, and every other member
answers whole. A gallery's remove drops its own member rows with it; the
honest replay answers already gone.

## Delete in bulk

Delete several subjects at once. The command plans first: every run without
`--confirm` is a dry run that changes nothing. A confirmed run records the
audit rows first. It then trashes each file into the run's own subfolder
under the share's trash. The catalogue's locations then read the new truth.
The audit never deletes; a restore returns the files later.

```bash
curu-catalog bulk-delete photos/red-1.jpg
```

```bash
curu-catalog bulk-delete photos/red-1.jpg --confirm --added-by owner
```

The dry answer names each subject and its location, states each refusal
named apart, and gives the run's audit id. The confirmed answer names each
row's result, then the counts. `--json` carries the same fields as the text.

## Move in bulk

Move several subjects into one target folder on their own share. The plan
names each file's source and target, and a dry run moves nothing. The
command refuses a target outside the share. A confirmed run records the
audit rows first. It then moves each file, and the locations then read the
moved truth.

```bash
curu-catalog bulk-move "$hash1" curated
```

```bash
curu-catalog bulk-move "$hash1" curated --confirm --added-by owner
```

The share check reads the host's mount table (`CURU_MOUNTS`); the staged
walk in the integration tier proves both runs. `--json` carries the same
fields as the text.

## Tag in bulk

Give tag names to several subjects at once. The command writes one machine
tag fact per subject, one score per name. The names validate through the
tags tier's own vocabulary. Your own verdict holds a name: the mass fact
skips it and states the skip, and your rows survive byte-identical.

```bash
curu-catalog bulk-tag "$hash1" --tag indoors
```

```bash
curu-catalog bulk-tag "$hash1" --tag indoors --confirm --added-by owner
```

A subject with no signals fact reports apart, and the confirm writes
nothing for it. `--json` carries the same fields as the text.

## Return the trashed files

Name the audit run's own id (or a range of runs). The dry run names each
trash path and its original folder. A confirmed run returns each file, and
the locations then read the returned truth. The undo writes its own audit
rows beside the originals; nothing deletes.

```bash
curu-catalog bulk-restore "<audit-id>"
```

```bash
curu-catalog bulk-restore "<audit-id>" --confirm --added-by owner
```

## Read the bulk ledger

```bash
curu-catalog bulk-audit
```

The read names each run, its action, its actor and its state, then the item
rows beneath it. The audit never deletes. `--json` carries the same fields
as the text.

## Record one run's outputs

`link-run` records the link between one generation run's attempt and its outputs.
The outputs' content hashes come from an index run first: a hash that no index run
has seen is a caller error. A later call with the same run and attempt supersedes
the earlier link as a whole.

The command is one surface of the review lane: the
[tools server](reference/tools.md) reads the same facts, and
[judge-record](#measure-a-decisions-threshold) records the verdicts on them.

## Note one verdict

`judge-note` records one note beside one verdict, named by the verdict id the
`judge-record` answer printed. A later note supersedes the earlier one, and the
history keeps both. The text is bounded at 500 characters.

## Serve the review page

`review-serve` serves the review page on the loopback machine, by default on port
8110. The page lists the linked runs and their outputs, plays each one, and records
the owner's keep or reject and each note. A non-loopback host refuses at the start.
Open the address it prints in a browser on the machine that reads the media.

## See the tags of a picture

A tag run gives each picture the names of the tag model above a floor, each with its
category and score. The score of one tag sits between 0 and 1. A higher score means more
evidence for the name. It is not a probability that a person checked.

```bash
curu-catalog tags photos/red-1.jpg
```

The command prints one line per tag, rank first, with the score, the name and the
category. It names the stamp and the floor of the answer. The stamp says what made
the tags: the model, its repository and revision, and the SHA-256 of the model file and
of the label file. It also names the preprocessing and decode versions and the
quantization. The line shows
the model and the preprocessing version, and `--json` gives the full stamp.

A picture with no tag facts answers `not tagged`. Its tag facts can sit under an
older stamp. The reply then asks you to start a tag worker to recompute. For a
shot, name it with `--shot` or `--at`, as for `signals`.

## Search pictures by one tag name

You can find every picture that holds one name of the tag model. The answer ranks
the subjects by score, highest first, and shows each score. No threshold applies:
the command ranks and hides nothing.

```bash
curu-catalog tag-search indoors --page 2
```

The name is a name of the tag model's own vocabulary, with underscores, for example
`indoors` or `blue_background`. Use `--page` and `--page-size` to read a long answer
in parts. You need a tag run first; before one, the command names this. The first tag
job of a run records the names of the tag model, so the next `tag-search` can answer.

## Review from an agent

An agent reaches the catalogue surface as a typed tool server over the same
functions the commands call. The lane covers the search side. One tool
answers for each of `search`, `near`, `signals`, `timeline`, the timeline
versions read, `tags`, `tag-search`, `gallery-run`, and the gallery and
saved-query management. Beside them ride the review lane's judge read, the
bulk read, one bulk staging and one judgment record. The answer of one tool
is the command's own `--json` answer, field for field. The staging tool
answers with the plan and stops. The owner confirms through the bulk
commands. The tools carry no confirm, apply or restore action: that is the
owner's audited bulk lane.

Start the server with the catalogue's DSN in the environment. An agent that you
trust connects to it:

```bash
export CURU_CATALOG_DSN="postgresql://postgres:<password>@<nas-host>:5434/curu"
```

```bash
curu-catalog tools
```

```bash
curu-catalog tools --transport http
```

The server binds `127.0.0.1` by default, on port 8000. In a container on an internal
network, set `CURU_TOOLS_HOST=0.0.0.0`. The server has no access control, so never bind it
to an address that a client outside the stack can reach. See
[The tools server](reference/tools.md) for the tool list and the transports.

## Share the work between computers

Each unit of work is a job on a shared queue in the catalogue database. A worker is one
process that takes jobs from that queue. Start workers on the computers that can read the
media, all with the same `CURU_CATALOG_DSN`:

```bash
curu-catalog worker --identity mini-1
```

The worker takes jobs until the queue is empty, then prints its report and stops. Add
`--daemon` to make it continue to wait for jobs.

Add `--json` to see two more values. `workers` gives the jobs that each worker took.
`reclaim_count` gives the jobs that a worker put back on the queue because their claim was
too old.

A worker that takes a signals kind (`signals.asset` or `signals.shot`) first looks for the
pictures and shots that have no current signals. Its first line on standard error gives what
it found:

```text
worker mini-1 queued signals jobs: pictures 0, shots 0
```

- `pictures` and `shots` are the numbers of signals jobs that the worker added to the queue.
  On a catalogue with current signals, both are 0.
- The worker adds a job for each picture and each video shot with a present path and no
  current signals. It adds no job for a picture or a shot that already has one on the queue.
- It adds no job for a picture or a shot that did not decode under the current versions (see
  [Handle files that do not decode](#handle-files-that-do-not-decode)).
- After a curu-vision update that changes a method version of the stamp, all the signals
  are stale. Then the first start of a worker adds a job for each picture and each shot
  with a present path. Those jobs read each picture again.

To share an index between the workers, start the workers with `--daemon`. Set `CURU_MOUNTS`
on the computer that runs `index` too, so that the jobs hold the shared names. Then run
`index` with `--workers 2` on a computer that can read the folder. Any value more than 1
gives the same result:

```bash
curu-catalog index /Volumes/Datasets/stills --workers 2
```

With `--workers` more than 1, `index` does no jobs itself. It adds the jobs, waits until the
workers complete them and prints the report. If the queue is not empty after 3600 seconds, `index`
stops with exit code 1, and the workers continue the jobs.

A worker with no `--kinds` takes every kind except the tag kinds. `--kinds` gives each worker part of the
work, for example `--kinds scan.location` on the NAS. A worker with `--kinds`
also waits for the jobs of the other kinds. So start a worker for each kind, also for
`caption.location`, `signals.asset` and `signals.shot`. If no worker takes a kind that has jobs, the queue never becomes empty.

A stopped worker loses no completed work. When a claimed job is older than
`CURU_RECLAIM_AFTER` seconds (600 if you do not set it), another worker takes it back. This
also occurs for a slow worker that is still alive. Set the value longer than the time of one
batch of jobs. See [Run workers](docs/workers.md) for the job kinds, the settings and how to see the
queue.

## Run a worker from the Docker image

The worker images are on Docker Hub:

```bash
docker pull darthveitcher/curu-worker:latest
```

The image is for amd64 and arm64. It holds curu-catalog and its packages, but no ffmpeg and
no model weights. Use it for the jobs that need neither ffmpeg nor weights. They are `scan.location`,
`signals.asset` (an image newer than `20261027-0719`) and `caption.location` (`20261117-1701`
or later). For `embed.asset` jobs,
attach a volume that holds the weights and set `CURU_VISION_CACHE_DIR` to it, for example
`-v curu-weights:/cache -e CURU_VISION_CACHE_DIR=/cache`. The worker does not
download the weights. To put them in a volume, run the download in the image:

```bash
docker run --rm -v curu-weights:/cache -e CURU_VISION_CACHE_DIR=/cache --entrypoint python \
  -e HF_TOKEN darthveitcher/curu-worker:latest -m curu_vision fetch embeddinggemma-2
```

The CUDA image for NVIDIA GPUs, `darthveitcher/curu-worker-cuda`, runs the same command. It
holds CUDA 13, cuDNN 9, the GPU package of ONNX Runtime and ffmpeg. The NVIDIA driver must
support CUDA 13. Run it with `--device nvidia.com/gpu=<N>`, where `<N>` is an idle GPU. On a
computer with SELinux (the Linux access control), such as the orange-box, also give
`--security-opt label=disable`. Without it, the container cannot open the GPU. Then the
first embedding job stops the command with exit code 1 and an error that names
`CUDAExecutionProvider`. On a computer whose driver supports only CUDA 12, use `curu-worker`. For the orange-box,
`deploy/orange-box/compose.yaml` holds these settings. See
`docs/reference/deployment.md` for the orange-box run.

Each push of the image has two tags: `latest` and a date tag, such as `20261027-0719`. Use a
date tag to go back to an earlier image. The image `curu-worker:20261027-0719` does not have
the two signals kinds. Use the CUDA image `20261027-2148` or later. It is the first image whose
embedding jobs compute on the GPU.

Give the container the same settings as a worker on the computer: `CURU_CATALOG_DSN`,
`CURU_MOUNTS` and the shares as read-only volumes. Then give the `worker` command and its
options as the container command. The
[deployment guide](docs/reference/deployment.md#run-the-worker-on-the-nas) shows a Docker
Compose service for the NAS, and how to build and push the images.

## Choose the hardware for the embeddings

```bash
curu-catalog index photos --providers cpu
```

`index`, `search` and `worker` make the embeddings with ONNX Runtime. A
[provider](#glossary) is the part of ONNX Runtime that computes on one type of hardware: `cpu`,
`cuda` (an NVIDIA GPU) or `coreml` (Apple). Give one or more providers, separated by commas, for example
`--providers cuda,cpu`.

Each command chooses its providers in this order:

1. The `--providers` option.
2. The environment variable `CURU_EMBED_PROVIDERS`, for example `CURU_EMBED_PROVIDERS=cuda,cpu`.
3. `cuda,cpu` when ONNX Runtime has CUDA, as in the CUDA image. Else `cpu`. This step never
   chooses `coreml`.

With `--workers` above 1, `index` makes no embeddings itself, so it does not use
`--providers`. It still checks the names. Give the providers to each worker.

- Put `cpu` after `cuda`, as the automatic choice does.
- If a provider that you give does not load, the command stops with exit code 1 and an
  error that names the provider. It does not change to the CPU without an error.
- A name that is not `cpu`, `cuda` or `coreml`, in `--providers` or in `CURU_EMBED_PROVIDERS`,
  stops the command with exit code 2.
- A worker that takes `embed.asset` or `embed.shot` prints
  `worker <identity> embeds with <providers>` on standard error when it starts.
- The provenance of each vector gives its providers. One catalogue can hold vectors from
  different providers. A test ran on the orange-box, with an RTX 3090 GPU, on 2026-10-27.
  The CPU and CUDA vectors of the same picture had a cosine similarity of 0.99999 or more.
- Two matches whose scores differ by less than 0.0005 can change places. In the test, the
  other search results kept the same order.
- In the same test, the GPU embedded 24 pictures in 2.6 to 3.7 s. The CPU of the same
  computer took 80 s.

## Use the model service

```bash
export CURU_VISION_URL=http://gpu-host:8765
export CURU_VISION_TOKEN="$(cat ~/.config/curu-vision/token)"
curu-catalog worker --identity mini-1 --kinds embed.asset,embed.shot,tags.asset --daemon
```

The [model service](#glossary) of curu-vision runs the models on one computer, for example
a computer with a GPU. A worker with `CURU_VISION_URL` sends its embeddings to that
service, and its tags when it takes a tag kind. `CURU_VISION_TOKEN` holds the token of the
service. Set it in the environment only.

- Without `CURU_VISION_URL`, the worker runs the models in its own process.
- The service gives the same vectors and tags as the local models, within the measured
  bound of curu-vision. Each fact gets the same [stamp](#glossary), so the catalogue can
  mix the two.
- The provenance of each fact names the [provider](#glossary) `remote` and the
  [engine](#glossary) of the service, for example `onnx-cuda`.
- If the service does not answer, or refuses the token, the job fails as `transient`, with
  the error of the service. The worker does not change to the local model. Start the
  service, and the job runs again later.
- A URL without `CURU_VISION_TOKEN` stops the worker, with an error that names the
  variable. A worker that takes a tag kind stops at its start. Another worker stops at its
  first embedding job.
- `index` and `search` read the same variables, so they can use the service too.

See [Workers](docs/workers.md#use-the-model-service) for the details.

## Test a capability with the in-memory store

The package's own in-memory adapters ride the family's tests. Build
`curu_catalog.MemoryStore` and compose it as the
lanes' reads. Two instances hold separate facts, and no database, weights
or files load.

## Use the catalogue from another program

A program of the curu family, such as curu, imports from the package root `curu_catalog`
only. The names in `curu_catalog.__all__` are the [public names](#glossary). Do not
import a module below the root, because a name there can move with no warning. The root
has no search, near-duplicate or index function yet. A program of the curu family uses
the tool server for these. Another program can use the modules in
[Use the results in a program](#use-the-results-in-a-program).

The gallery functions, `thumbnail`, `read_bytes` and `record_output` take the store
first. When you give no derived store or source reader, each function uses the same
environment as the commands: `CURU_DERIVED_URL`, `CURU_MOUNTS` and the `CURU_S3_*`
variables. A function whose name ends in `_of` takes no store. It opens the catalogue of
`CURU_CATALOG_DSN`.

```python
from curu_catalog import PgBackend, gallery_add, gallery_make, gallery_run
from curu_catalog import read_bytes, thumbnail

with PgBackend() as backend:  # CURU_CATALOG_DSN names the catalogue
    store = backend.store
    gallery_make(store, "picks")
    gallery_add(store, "picks", member="photos/red-1.jpg", added_by="curu")
    for row in gallery_run(store, "picks").members:
        thumb = thumbnail(store, row.subject)
        if thumb.data is None:
            print(row.subject, "the thumbnail is not made yet")
        original = read_bytes(store, row.subject)  # the first present file
```

- `gallery_add` needs `added_by`, the name of your program. The member then records your
  program as its author, not the owner.
- `gallery_run` on a gallery of hand members loads no model. A gallery with a
  saved-query member stops with an `InfrastructureError`, because the root has no
  search [port](#glossary) yet. Use the `gallery-run` command or the tool server for
  such a gallery.
- `thumbnail` and `read_bytes` give an answer with two fields. `answer` has the values of
  the `--json` answer of `thumb` or `media-get`, and `data` has the bytes. `data` is `None`
  when the thumbnail is not made yet.
- `thumbnail` stops with an `InputError` when you give no derived store and
  `CURU_DERIVED_URL` is not set.
- `read_bytes` reads the whole file into memory. Use `media-get` for a large video.
- Catch `CatalogueError` for each error of the catalogue. `InputError` means that you must
  change the input. `TransientError` means that you can try again later.
- `import curu_catalog` loads no database driver and no model. Each name loads on its first
  use.

A test fails when the list of public names changes without its contract. The contract is
in [Technical notes](#technical-notes).

## Record one output without a model

For one file, the library's `record_output` records the location and the
content hash through the scan's own bounded read. No model loads, and the
recorded asset reads "not indexed" by search. A later index run of the
folder adds the embeddings at no identity cost.

```python
from pathlib import Path

from curu_catalog import PgBackend, record_output

with PgBackend() as backend:
    content_hash = record_output(backend.store, Path("/out/my.png"))
print(content_hash)
```

The `[s3]` extra: an install that never reads a bucket resolves no boto3.
Install it with `pip install 'curu-catalog[s3]'` before an `index` of an
`s3://` folder, and without it that index stops with a message naming the
extra.

## Use the results in a program

Add `--json` to `index`, `search`, `timeline`, `signals` or `near` to get the answer as one
JSON object. A worker with `--json` prints one JSON line for each report. Or call the same
functions from Python:

```python
from pathlib import Path

from curu_catalog.application.indexer import index
from curu_catalog.application.searcher import query
from curu_catalog.application.signals import near_duplicates, signals_of

report = index(Path("photos"))  # IndexReport, the same values as the index report
refresh = index(Path("photos"), full=True)  # IndexReport of a full pass
facts = signals_of("photos/red-1.jpg")  # SignalsResponse
copies = near_duplicates("photos/red-1.jpg")  # NearDuplicatesResponse
answer = query("a red picture", top_n=3)  # SearchResponse
for hit in answer.results:
    print(f"{hit.score:.2f}", hit.content_hash, hit.locations, hit.clip)
print("not indexed:", answer.not_indexed_count)
```

A search result in JSON looks like this. These values are examples, and a real hash has 64
hexadecimal digits:

```json
{
  "results": [
    {
      "content_hash": "blake3:v1:9f2c8a41d6",
      "locations": [
        "file:///Volumes/Estate/stills/car-07.png",
        "file:///Volumes/Estate/backup/car-07.png"
      ],
      "score": 0.7456,
      "signals": {"visual": 0.7456},
      "fact": {
        "model": "embeddinggemma-2",
        "revision": "daa72c51243991dfcaf9f9137d2c573d8f7790c0",
        "preprocessing_version": "eg2-image-2"
      }
    }
  ],
  "not_indexed_count": 4,
  "signals_available": ["visual"]
}
```

- `content_hash` is the identity of the asset. One asset gives all its present `locations`.
- `signals` gives the score of each match signal. Today the only match signal is `visual`.
- `fact` gives the model, its revision and the preprocessing version that made the vector.
- A video match also has `clip`, the start and end of the shot in seconds. It also has
  `shot`, the number of the shot in the current shot list, and `shot_key`, the
  [shot key](#glossary).

`index --json` gives the values of the report table, and these values too:

- Each failed file has `error_type` (`input` or `transient`), `detail` (the reason) and
  `retryable`, which is true for a `transient` failure. `undecodable` is true for a file
  that did not decode.
- `undecodable_known` gives each file of the `cannot decode (known)` line, with `uri`,
  `content_hash`, `decoder`, `tier` (the job kind that found the fault) and `detail`. For a
  shot, `content_hash` is its [shot key](#glossary), for example
  `<hash>/shot/00000050-00000099`.
- `symlinks_skipped` is the number of the `symlinks skipped` line, also when it is 0.
- `not_media_skipped` is the number of the `not media skipped` line, also when it is 0.
- `shot_jobs_not_current` is the number of `embed.shot` and `signals.shot` jobs whose shot
  is in no current shot list. They complete with no work.
- `shots_derived` is the number of new shot facts that this run recorded, and
  `clips_embedded` is the number of new shot vectors. A second run of the same videos gives
  0 for both.
- `signals_recorded` and `signals_recomputed` are the two numbers of the `signals` line.
  The report of `index --workers` does not have them: see
  [Run workers](docs/workers.md#index-with-the-workers).
  `signal_failures` gives each picture or shot that got no signals, as a failed file.
- `workers`, `reclaim_count` and `throughput` are for workers: see
  [Run workers](docs/workers.md#see-what-the-workers-do).

`timeline --json` gives `asset`, `shots`, `frames`, `not_indexed` and `shot_method`. Each
shot has `index`, `key`, `start`, `end`, `boundary_kind` and `boundary_score`, and each
frame has `time`. `shot_method` has the same value as the `method` line. When `not_indexed` is true,
the answer has no `shot_method` key.

`timeline --versions --json` gives `asset` and `versions`. Each version has `version`,
`method`, `started_at`, `ended_at`, `current`, `shots`, `ffmpeg_version` and
`decoded_length`. `ended_at` is null for the current version. `ffmpeg_version` is the
`-version` line of the ffmpeg that found the list.

`signals --json` gives `phash`, `dhash`, `flat`, `measurements`, `stamp` and `provenance`.
A measurement that cannot be made has no key in `measurements`. `not_hashed` is true when
there are no current signals, and `stale` is true when there are only stale signals. For a
picture that did not decode, `not_hashed` is true and `undecodable` gives the `decoder`,
the `tier`, the `error_class` and the `detail`. `error_class` is `UndecodableImage` or
`EmptyInput` for a picture, and `NotAVideo`, `NoVideoStream` or `TruncatedSource` for a
video. A shot has `NoFrame` when its video ends before the middle of the shot. Else a shot
has one of the video classes.

`near --json` gives `subject`, `distance`, `stamp`, `total`, `page`, `page_size` and
`matches`. Each match has `content_hash`, `phash_distance`, `dhash_distance`, `locations` and
`below_near_copy_limit`, and a shot match has `shot`, `shot_key` and `clip`. For a shot,
`subject` also has `shot`, `shot_key` and `clip`. The answer also has
`not_hashed`, `stale`, `flat`, `below_near_copy_limit` and `undecodable`, as for `signals`.

## Handle errors

curu-catalog gives one of three exit codes:

```bash
curu-catalog index no-such-folder || echo "exit code $?"
```

| Exit code | What it means | What to do |
|---|---|---|
| 0 | The command completed. Some files can still be in `failed`. | Read the `failed` lines. |
| 1 | A part that the command needs is missing, for example the database, its `vector` extension or a provider that does not load. The message names it. | Correct that part and run the command again. |
| 1, from `ingest` | A file failed, a `CURU_CAS_*` variable is missing, or the server refused the key. The message names each failed file or the variable. | Correct the cause, then run `ingest` again. |
| 1, from `index --workers` | The queue is not empty after 3600 seconds. The jobs stay on the queue. | Make sure that the workers run. Then read the queue with `psql` (see [Run workers](docs/workers.md#see-what-the-workers-do)). |
| 1, at the start of a command | The database holds shot keys of an older form, from an older curu-catalog. | Make the database again: see [Make the catalogue database again](docs/reference/deployment.md#make-the-catalogue-database-again). |
| 1, when the S3 server does not answer | The listing of the bucket failed before any file started. The message names the location. | Make sure that the server answers. Then run the command again. |
| 1, from `index` of a bucket | The S3 server refused the keys, or the policy of the user does not allow the bucket. The message names `CURU_S3_ACCESS_KEY_ID` and `CURU_S3_SECRET_ACCESS_KEY`. | Correct the keys or the policy. |
| 1, from `search` | The shots of earlier shot lists fill the vector index, so search cannot find enough current results. | No command removes earlier shot lists. Make the database again. |
| 1, from `thumb` or `media-get` | The derived store or the source did not answer. | Run the command again later. |
| 2 | The command or its input is wrong. Examples are a folder or a bucket that does not exist, and a `near` distance above 16. Others are a subject that is not known, and an asset with no present location. | Correct the command. |

Each failed file has a type. `input` means that the file or its location is bad. A file that
does not decode is `input`: the next runs skip it (see
[Handle files that do not decode](#handle-files-that-do-not-decode)). A new run fails each
other `input` file again. A location that is a
symlink is `input` too, and curu-catalog does not read it. `transient` means that the read
failed for a short time, for example on a lost share: a new run can read it. curu-catalog
never records a `transient` failure as missing or as "no content".

## Limits

- curu-catalog reads local folders, mounted SMB or NFS shares, S3 buckets and the content
  store. It writes to a bucket only for the content store, where it adds only new objects,
  and for the derived store of the thumbnails. It never writes to a bucket that it
  indexes.
- `ingest` takes a file or a folder. It does not take an `s3://` prefix, and it refuses
  the folder of the derived store.
- It has no command to show the queue and the workers, and no command to back up the
  catalogue. Use PostgreSQL's tools: see [Run workers](docs/workers.md) and
  [Back up and restore the catalogue](docs/backup.md).
- Search takes text only. It cannot search with an example picture, and it finds no people,
  tags or captions yet. The catalogue keeps the captions, but the search does not use them.
- curu-catalog knows a picture or a video only by its suffix, from the lists in
  [Index a folder](#index-a-folder). It does not read a video with another suffix, such as
  `.wmv`, and counts it on the `not media skipped` line.
- The usual run cannot see new content of the same size. Use `--full` for that.
- `timeline` gives frame times, not frames.
- The face run reads pictures only, not the frames of a video. It does not group the faces
  into people, and it does not name a person. A drawn or animated character can have no
  face that the models find.
- The faces are not in the search. The agent tools read the identities, but no tool
  names a person.
- The catalogue does not propose an identity. You assign each face yourself.
- A sheet of the `face` decision is a picture of people. Keep it private, and delete it
  after judging. No removal deletes it.
- No agent tool records a face answer. Only you record one, with `judge-record face`.
- No command reads an export file back into a catalogue.
- `near` compares pHashes only. It finds a copy that is resized or saved again as JPEG. A
  cropped, turned or mirrored copy can be at a large distance, so `near` can miss it.
- A near duplicate stays at a distance of 6 or less only for picture content of 32 pixels a
  side or more. A small change to a gradient or to a field of noise can change many bits.
- `signals` and `near` take one picture or one shot. No command lists all the near
  duplicates in the catalogue.
- Each curu-vision update that changes a method version of the stamp makes all the signals
  stale. The next start of a worker that takes a signals kind then reads each picture
  again, and decodes one frame of each shot again.
- An update that changes the shot method makes the shot list of each video stale. The next
  index run of the folder then decodes each video one time, and records a new version.
- The catalogue keeps each earlier shot list, and the vectors and signals of its shots. They
  use disk space. Each search reads their vectors and does not include them in the answer.
  No command deletes them.
- A read from a network share that does not respond stops after `CURU_READ_TIMEOUT` seconds
  (300 by default). It is a transient failure, so the batch continues.
- Each search counts the assets that are not indexed, and this count reads all the assets.
  So a search becomes slower as the catalogue becomes larger.
- One catalogue is one database. You cannot search two databases together.
- curu-catalog does not follow symlinks. A file that you can reach only through a link is
  not in the catalogue.
- A picture or a video needs a suffix from the lists in [Index a folder](#index-a-folder).
  Without it, for example a JPEG file with no suffix, it is not in the catalogue. Give it its
  suffix, then index the folder again.
- A file that is not media, but that an earlier version of curu-catalog recorded, stays in
  the catalogue. Each search counts it as not indexed. A `--full` run records its path as
  missing, although the file is still in the folder. No command removes its record from the
  catalogue.
- An update of ffmpeg alone does not try the videos that did not decode again. Use
  `--retry-undecodable`.

## Technical notes

- **How it works.** [How curu-catalog works](docs/how-it-works.md) shows the parts, the jobs
  and one pass of an index.
- **Media service.** `media-serve` is a Starlette application with two read routes and an
  access gate ([ADR-029](project-management/ADRs/ADR-029-the-media-service-serves-each-deployment.md),
  [contract](specs/025-content-store-mcp-tools/contracts/media-service.md)).
- **Content hash.** A content hash is `blake3:v1:` and 64 hexadecimal digits: BLAKE3 over all the
  bytes of the file, read in blocks of 1 MiB
  ([ADR-008](project-management/ADRs/ADR-008-content-hash.md)).
- **Faces.** The faces, their states and the removed marks are in the schema `identity` of
  the catalogue database, apart from the fact table. A removal deletes the rows, then runs
  `VACUUM` on the face tables
  ([ADR-028](project-management/ADRs/ADR-028-the-identity-store-is-a-schema-of-its-own.md),
  [contract](specs/027-face-facts-on-pictures/contracts/faces.md)). The face stamp is the
  expected output identity of YuNet and of SFace, from curu-vision with no model run. The
  identities, the assignments and the removed faces are in the same schema. A removal
  runs `VACUUM` on each table that it deletes rows from
  ([contract](specs/028-identities/contracts/identities.md)). The
  [write-ahead log](#glossary) keeps a removed row until PostgreSQL uses that log file again.
- **Content store.** The key of each object is `<prefix>blake3/v1/<aa>/<bb>/<hex>`.
  `<aa>` and `<bb>` are the first four hexadecimal digits of the hash. `ingest` sends
  `If-None-Match: *` with each object, and the SHA-256 of the bytes that it read first
  ([ADR-027](project-management/ADRs/ADR-027-the-content-store-keeps-new-media.md),
  [contract](specs/023-content-store-ingest/contracts/ingest.md)).
- **Embedding.** Pictures, shots and search texts get vectors from EmbeddingGemma 2 through
  [curu-vision](https://github.com/darth-veitcher/curu-vision), in one space of 768
  dimensions. curu-catalog pins curu-vision to a release tag, now v0.50.0
  ([ADR-001](project-management/ADRs/ADR-001-embeddinggemma-2-as-embedding-model.md)).
- **Stamps.** `EmbeddingStamp`, `TagStamp` and `SignalStamp` in `domain/models.py` are the
  params of each fact. `current_embedding_stamp` and `current_tag_stamp` read them from
  `expected_output_identity` of curu-vision, with no model run
  ([ADR-021](project-management/ADRs/ADR-021-stamps-name-the-model-identity.md)).
- **Providers.** `embed_providers` in `adapters/vision_embedder.py` holds the order of
  choice for `index`, `search` and `worker`. curu-vision checks the providers of each ONNX
  Runtime session, so a provider that does not load is an error. ADR-015 gives the decision
  and the measurement of CPU and CUDA vectors
  ([ADR-015](project-management/ADRs/ADR-015-embedding-providers.md)).
- **Store.** PostgreSQL 18 with pgvector keeps the assets, locations, facts and jobs
  ([ADR-005](project-management/ADRs/ADR-005-catalogue-store.md)). An HNSW index serves each
  search ([ADR-006](project-management/ADRs/ADR-006-ann-index.md)). Workers take jobs with
  `SKIP LOCKED`, so no two workers take the same job
  ([ADR-007](project-management/ADRs/ADR-007-job-queue.md)).
- **Video.** curu-vision finds the shots with ffmpeg and ffprobe, which must be 6.0 or later,
  and 8.1 or later on arm64. Each shot gets one vector
  ([ADR-010](project-management/ADRs/ADR-010-shot-facts-persist-pixels-on-demand.md),
  [ADR-011](project-management/ADRs/ADR-011-shot-indexing-job-kind.md)). curu-catalog reads
  the current shot method from the pinned curu-vision, and keeps no copy of its version.
- **Shot lists.** Each `shots.asset` job records a whole shot list as one version, a `shot_list`
  fact on the video. One transaction, under a lock on the video's row, ends the old version
  and records the new one. A shot's key comes from its first and last frame, so its facts
  belong to its frames. The frame numbers are the same on each ffmpeg build of the fleet
  (measured 2026-10-29). Search does not include the shots of earlier versions. It removes them inside the
  HNSW scan, so the answer keeps its length
  ([ADR-018](project-management/ADRs/ADR-018-versioned-shot-lists.md)).
- **Versions of the hashes and shots.** curu-vision v0.8.0 names the hash method `hash-2`
  and the shot method `shots-3`. On x86-64 they give the same values as `hash-1` and
  `shots-2`. On a Mac, the older methods gave other values for some pictures and shots.
  The new names make curu-catalog compute each older value again.
- **Near duplicates.** Four btree indexes, one on each 16-bit part of the pHash, find the
  matches without a scan of all the facts. The search is exact: it finds every match up to
  the distance ([ADR-013](project-management/ADRs/ADR-013-signal-facts-and-near-duplicate-index.md)).
  The answer gives every match in pages, not only the best matches
  ([ADR-014](project-management/ADRs/ADR-014-near-duplicates-every-match-paged.md)). The
  locations and the shots of the matches also come from indexes.
- **Near-duplicate speed.** A test generated 450,000 pictures and 5,000 videos of 10 shots
  (2026-10-27, `tests/system/test_near_scale.py`). The database was 2.9 GB, with 1,000,000
  signals rows of real fact width: 500,000 under the current stamp and 500,000 under an older
  stamp.
  It ran 100 full `near` answers at distance 6: the subject, the search of the four pHash
  indexes, the locations and the shots. The median was 44 ms, and 95 % took 66 ms or less.
  The slowest took 623 ms: the first query after the load, with a cold cache. On 10
  queries, a full scan found no match that the indexes did not find.
- **Signals.** curu-vision makes the hashes and the measurements. A set of signals is one
  fact of kind `signals` for each picture or shot and each stamp. The hashes are in two
  `bigint` columns ([ADR-013](project-management/ADRs/ADR-013-signal-facts-and-near-duplicate-index.md)).
  In one process, `index` does the signals jobs before the embedding jobs, because they
  cost less. Workers take the jobs in queue order. A test on a Mac with an M-series chip used 24 generated pictures
  (2026-10-27). A signals job took 9.5 ms for each picture, and an embedding on the CPU 5.3 s.
  The search for stale signals at the start of a worker reads all the catalogue, one time
  for each start.
- **Files that do not decode.** A "cannot decode" fact has the kind `undecodable`. Its
  producer is the decoder, and its parameters are the decoder versions. Every computer can
  read those versions without the model or ffmpeg, so all the workers agree when a fact is
  current. Only a refusal by the decoder makes such a fact. A `transient` failure, a
  location failure or a format that the ffmpeg of the computer cannot read never makes one
  ([ADR-016](project-management/ADRs/ADR-016-content-verdicts.md)).
- **Symlinks.** One function, `refuse_links` in `adapters/source_paths.py`, checks the paths.
  For a share in `CURU_MOUNTS`, it checks each part of the path below the root of the share.
  For a `file://` path, it checks only the last part. The reader and the video decoder both
  use it. The reader also opens with `O_NOFOLLOW`. ffmpeg has no such option, so ffmpeg can
  still follow a link that someone makes in the share during a job
  ([ADR-016](project-management/ADRs/ADR-016-content-verdicts.md)).
- **Fleet.** The catalogue database is on the NAS, the hash jobs run near the media and the
  embedding jobs run where the model weights are
  ([ADR-009](project-management/ADRs/ADR-009-fleet-deployment-shape.md)).
- **Open problems.** A share read that the read deadline abandons keeps one thread
  and one file descriptor blocked until the worker process ends
  ([Workers](docs/workers.md#the-read-deadline)). The "not indexed" count of each
  search reads every asset
  ([issue #37](https://github.com/darth-veitcher/curu-catalog/issues/37)).
- **Contracts.** These give the exact rules: the
  [CLI contract](specs/001-index-and-search/contracts/cli.md), the
  [Python API contract](specs/001-index-and-search/contracts/python-api.md), the
  [refresh contract](specs/002-refresh/contracts/refresh.md), the
  [fleet contract](specs/003-distribution/contracts/distribution.md) and the
  [video contract](specs/004-video-clips/contracts/python-api.md). The
  [signals contract](specs/005-signal-facts/contracts/python-api.md) and the
  [content verdicts contract](specs/006-content-verdicts/contracts/python-api.md) do too, and
  so does the [shot lists contract](specs/012-versioned-shot-lists/contracts/python-api.md).
  The [public API contract](specs/019-public-python-api/contracts/python-api.md) lists each
  public name of the package root and its signature
  ([ADR-025](project-management/ADRs/ADR-025-siblings-import-only-the-package-root.md)).
- **Rules and decisions.** The rules for each change are in
  [the constitution](.specify/memory/constitution.md), the decisions are in
  [project-management/ADRs](project-management/ADRs/README.md), and the plan is in the
  [roadmap](ROADMAP.md).

## Develop

```bash
uv sync
uv run ruff check && uv run ruff format --check
uv run ty check
uv run pytest                                   # hermetic: no database, no weights
export CURU_CATALOG_TEST_DSN="postgresql://postgres:local-only@127.0.0.1:5432/curu_test"
uv run pytest -m integration                    # real PostgreSQL, ffmpeg and weights
CURU_GOLDEN_DSN="postgresql://..." uv run pytest -m system   # owner-approved media only
CURU_SCALE_DSN="postgresql://..." uv run pytest -m system tests/system/test_near_scale.py -s
CURU_S3_SCALE_DSN="postgresql://..." uv run pytest -m system tests/system/test_s3_scale.py -s
beacon docs check                               # the writing standard, docs/WRITING.md
beacon doctor --strict
```

The hermetic tier (the tests that need no database, no weights and no network) needs the
`beacon` command, which checks the documentation. Install it with
`uv tool install beacon-framework`.

The integration tier needs a test database with the `vector` extension, and jq. The S3
tests also need a RustFS test server: see `AGENTS.md`, "Set up". The suite
empties its tables before each test. The `system` tier runs a fixed set of search questions
on media that the owner approved, in a database that it can empty. The near-duplicate test
loads 1,000,000 generated signals rows, with their assets, locations and shot facts, into
the database in `CURU_SCALE_DSN`. It drops the tables after the run. Give it an empty database in the `curu-pg` container, with 4 GB free on its
disk. With less free space, the test skips.

Write `README.md`, `docs/` and `AGENTS.md` to the [writing standard](docs/WRITING.md).
`AGENTS.md` gives the rules for each change.

## Glossary

- **Assignment**: the link from one face to one identity. Only a person makes it. It
  records who made it and when.
- **Asset**: one content, different from all the other contents. Two copies of a file are
  one asset.
- **Audit run**: one confirmed bulk action's own record. Its audit id names the run's trash subfolder, and each subject's own row rides beneath it. The audit never deletes.
- **Bucket**: a named container of objects on an S3 server.
- **Caption file**: a `.txt` file beside a media file, with the same name. Its text is the
  caption of the media file.
- **Cannot decode**: a fact that says that a decoder refused the bytes of a file. The next
  runs skip the file until the decoder changes.
- **Confidence interval**: the range where the true figure sits, at this sample's size. A
  figure has its own meaning beside its interval.
- **Content hash**: the content address of an asset, made from all its bytes. The same bytes always
  give the same hash.
- **Content store**: the S3 bucket that keeps new media. The key of each object is made
  from its content hash.
- **Content type**: the media type of some bytes, for example `image/jpeg`. `media-get`
  takes it from the suffix of the location, else it gives `application/octet-stream`.
- **Cosine similarity**: a measure of how near two vectors are, from -1 to 1. Higher is
  nearer.
- **CUDA**: the NVIDIA software that lets a program compute on an NVIDIA GPU.
- **cuDNN**: the NVIDIA library for neural networks on a GPU. ONNX Runtime needs it to use
  CUDA.
- **Decoder**: the code that makes pictures from the bytes of a file. A picture has the
  curu-vision picture decoder (`curu-vision/image-decode`), and a video has the curu-vision
  video decoder (`curu-vision/media`).
- **dHash**: the second perceptual hash. It comes from the changes of brightness between
  pixels that are side by side.
- **Derived store**: the folder or bucket prefix of `CURU_DERIVED_URL`, where the catalogue
  keeps the thumbnails that it makes, beside its database.
- **DSN**: the connection string of a PostgreSQL database, in `CURU_CATALOG_DSN`.
- **Embedding**: a vector of 768 numbers that represents the meaning of a picture, a shot or
  a text. Contents with similar meanings have near vectors.
- **Engine**: the runtime and hardware that ran a model, for example `onnx-cpu` or
  `onnx-cuda`. It is in the provenance of a fact, not in its stamp.
- **Face vector**: 128 numbers that describe one face in one picture. The vectors of
  two faces of one person are near each other. A face vector is identity data.
- **Face state**: the result of the face run for one picture: `faces`, `no_faces`,
  `failed`, `stale`, `removed` or `not_indexed`.
- **Fact**: one recorded result about an asset or a shot, such as a vector, a shot or a set
  of signals. Each fact records what made it: the model or the method, its version and the
  settings.
- **Flat**: a picture with no variation, for example one solid colour. Its perceptual hashes
  tell nothing about its content.
- **Floor**: the score at which a tag run keeps a name. The run keeps the tag scores above
  the stamp's floor, and nothing else. A floor of 0.01 keeps almost everything the model
  gave.
- **Fleet**: the computers that run workers on one catalogue.
- **Full pass**: an index with `--full`, which reads every file again.
- **Gallery**: a named view of the estate (the spec calls it a virtual gallery). Its members show a saved query's fresh run, or hold the subjects of a hand-made list, in the owner's own order.
- **Golden set**: the labelled estate set for search tests. It stays out of every
  judged set.
- **Hamming distance**: the number of bits that are different in two numbers of the same
  length.
- **Hand-made list**: the members that a person or a program adds with `gallery-add` or `gallery_add`. Each row names who added it in `added_by`. No machine fact overwrites or outranks a row that a person added.
- **HNSW**: an index that finds the nearest vectors without a comparison with every vector.
- **Identity**: one person, with the name that you give it, and the faces that you assign
  to it. Its id is `idn-` and 12 hexadecimal digits.
- **Identity data**: the faces, their vectors, the identities and the assignments. It
  also holds the face sample, the face answers, the private entities and the entity links.
  The catalogue keeps them apart from the other facts. You can list, export and
  remove them.
- **iTXt chunk**: a block of text inside a PNG file, with a key and a value. The PNG format
  keeps it beside the picture data.
- **JSON Lines**: a text file with one JSON object on each line.
- **Job**: one unit of work on the queue, such as the hash of one file.
- **Job kind**: the type of a job, such as `scan.location`. The two signals kinds are
  `signals.asset` (a picture) and `signals.shot` (a video shot).
- **Judged set**: the sample one decision's threshold is measured on. It is the one
  non-golden estate folder, read from the catalogue's rows only.
- **Judgment**: one answer a person gave about one pair or one candidate, recorded as a
  human fact. A corrected answer supersedes it; the catalogue deletes nothing.
- **Known entity**: a person, a character or another thing that you know by name. It has a
  key that never changes, and it is public or private.
- **Link that expires**: a URL that lets a program read one object with no key, for
  `CURU_S3_URL_TTL` or `CURU_CAS_URL_TTL` seconds. ffmpeg reads a video in a bucket
  through one. It is a secret until it expires.
- **Location**: a path where an asset is present. It is a local path, or a name from the
  mount table with the path under it, such as `estate://datasets/stills/a.jpg`. It can
  also be an object in a bucket, such as `s3://media/2026/a.jpg`. The reports
  also call it a path. One asset can have many locations.
- **Loopback**: the address `127.0.0.1` or `::1`, which only the same computer can reach.
- **Match signal**: one type of evidence that can match a search. Today the only match
  signal is `visual`, the vector of a picture or a shot. The search JSON calls them
  `signals`, but they are not the signals of a picture.
- **Media estate**: all the pictures and videos that you keep, on all your disks and shares.
- **Member**: one entry of a gallery. A query member shows its saved query's fresh run. A hand member names a subject that a person or a program added.
- **Method version**: the name and version of one curu-vision method, for example `hash-2`
  or `eg2-image-2`. It changes when the method can change a result.
- **Model service**: one curu-vision process that loads the models one time. It answers the
  embedding and tag requests of other computers over HTTP, with a token.
- **Media base URL**: the address of the media service, which a page puts before
  `/media/<hash>`. The deployer chooses it.
- **Media service**: the HTTP service of `media-serve`. It gives the file and the
  thumbnail of a content hash, and it only reads.
- **Mount table**: the `CURU_MOUNTS` pairs that give a fixed name to a local path.
- **Near duplicate**: the same picture with small changes, for example a smaller size or a
  new JPEG save. Its pHash distance to the original is small.
- **OIDC**: OpenID Connect, a login standard that an identity provider uses.
- **Origin**: the place that the bytes of an asset came from, before the ingest. It is a
  record only: no job reads it.
- **Owner identity**: the caller identity in `CURU_CATALOG_OWNER_IDENTITY`. It sees each
  known entity, with the name of a private entity.
- **pgvector**: the PostgreSQL extension that stores vectors and finds the nearest vectors.
- **Object**: one file in a bucket. Its key is its name, for example `2026/a.jpg`.
- **Package root**: the module `curu_catalog` itself. Another program imports only from it.
- **Port**: the interface that a function uses for one service, such as the store, the
  derived store or the source reader.
- **Public id**: an id of a known entity in a public database: `wikidata:Q<digits>`,
  `imdb:nm<digits>`, `imdb:tt<digits>` or `tmdb:<digits>`.
- **Public name**: a name in `curu_catalog.__all__`. Each other name can move with no
  warning.
- **Parity**: the sameness of two answers to one question. Here: one tool's answer is
  the command's own `--json` answer, field for field.
- **Params hash**: the hash of the settings in a stamp. Facts with the same params hash
  came from the same models and settings.
- **Perceptual hash**: a 64-bit number made from what a picture shows, not from its bytes.
  A small change to the picture changes few bits.
- **Prefix**: the first part of the keys of the objects in a bucket. It acts as a folder.
- **Precision**: how right a threshold is: the share of the pairs the threshold calls
  right that a person also called right. Its [recall](#glossary) tells how much it finds.
- **pHash**: the perceptual hash that `near` compares. It comes from the large shapes and
  the brightness of the picture.
- **pHash distance**: the [Hamming distance](#glossary) of two pHashes, from 0 to 64. A
  lower distance means a nearer duplicate.
- **Preprocessing version**: the version of the steps that prepare a picture or a shot for
  the model.
- **Provider**: the part of ONNX Runtime, the program that runs the model, that computes on
  one type of hardware: `cpu`, `cuda` or `coreml`. A fact from the model service names the provider `remote`.
- **Queue**: the table of jobs in the catalogue database. All workers share it.
- **Read key**: the key of a user that can only read the content store,
  `CURU_CAS_S3_ACCESS_KEY_ID` and `CURU_CAS_S3_SECRET_ACCESS_KEY`.
- **Recall**: how much a threshold finds: the share of the pairs a person called right that the threshold also calls right. Its [precision](#glossary) tells how right it is.
- **Removed face**: the content hash, the params hash and the position of a face that you
  removed with its identity. It holds no face data. A face run with the same face models skips
  it.
- **Removed mark**: the content hash of a picture whose faces you removed. It holds no
  face data. It stops a later face run from reading the picture again.
- **Row version**: a copy of a table row that PostgreSQL keeps after a change or a delete,
  until `VACUUM` removes it.
- **RustFS**: the S3 server on the NAS.
- **S3**: the protocol of a server that keeps files as objects in buckets.
- **Saved query**: one text search kept under a unique name, with its page
  size. It runs again against the facts the catalogue holds now.
- **Shot**: a continuous run of frames from one camera take.
- **Shot key**: the identity of a shot's facts. It is the content hash of the video, then
  `/shot/`, then the numbers of the first and the last frame of the shot. Each number has 8
  digits, and a `-` is between them. curu-vision counts the frames from the start of the
  file.
- **Shot list**: all the shots that one `shots.asset` job finds in one video. Each new list
  is a new version, and the current version is the one that every command uses.
- **Shot method**: the curu-vision method that finds the shots of a video. Its name, for
  example `shots-3`, changes when the method changes. When a curu-vision update changes the
  shot method, the `CHANGELOG.md` entry of that update names the new method.
- **Signals**: the pHash, the dHash, the flat flag and the eight quality measurements of one
  picture or one shot, with their stamp. `curu-catalog signals` shows them.
- **Stale**: a fact with a stamp that is not the current stamp. A shot list from a shot
  method that is not the current method is stale too. curu-catalog does not compare stale signals, and
  search does not show stale vectors. The next start of a worker that takes a signals kind
  computes the signals again, and so does the next index run of their folder. The next
  index run of a folder embeds its stale vectors again, and finds the shots of a stale shot
  list again.
- **Stamp**: what made a fact, as far as it changes the result. For signals: the method
  versions of the hash, the measurements and the decoder, and the analysis side. The
  analysis side is the largest side, in pixels, at which curu-vision measures a picture.
- **Stamp of a vector or of tags**: the model, its repository and revision, and the SHA-256
  of its files. It also names the quantization and the preprocessing, prompt or decode
  versions. A vector
  stamp also holds the dimension and the precision, and a tag stamp the floor. The
  curu-vision release, the engine and the hardware are not part of a stamp.
- **Store key**: the key of an object in the content store, made from its content hash.
- **Symlink**: a file system entry that points to another file or folder. curu-catalog does
  not follow it.
- **TLS**: the encryption of `https`.
- **Undo row**: one subject's own restore row. It sits beside the original audit rows, and none of them delete.
- **Threshold verdict**: the verdict row that one picked value produced, with that value
  in its identity. A different value re-projects the same facts; nothing is deleted.
- **Tool server**: the `curu-catalog tools` process. It serves the typed tools to an
  agent over MCP stdio or HTTP, on the local machine only by default.
- **Typed tool**: one tool of the server. Its input and answer ride the models the
  command answers, so both surfaces read the same.
- **Trash folder**: the volume root's own `TRASH/` folder. Each confirmed audit run gets one dated subfolder, keyed by its own audit id, and the deleted files rest there with their names. The index walk prunes the name, so a trashed file never indexes again. `bulk-restore` returns the files from it.
- **Tag score**: the number between 0 and 1 that the tag model gave one name for one
  picture. A higher score means the model saw more evidence for the name. It is not a
  probability that a person checked. A tag run keeps the scores above the
  [floor](#glossary).
- **Subject**: the thing a command answers about: one asset or one shot.
- **Vocabulary**: all the names that the tag model can give, each with its category,
  under the digest of the model's names file. `curu-catalog tag-search` answers only
  names in the vocabulary.
- **Thumbnail**: a small JPEG of a picture or of the middle frame of a shot. It fits a square
  of 320 pixels.
- **Usual run**: an index without `--full`. It does not hash again a file that has the same
  size and complete recorded work. It adds only the jobs that such a file still misses: shot
  vectors, or signals that are missing or stale.
- **Worker**: one process that takes jobs from the queue and does them.

- **Write-ahead log**: the files where PostgreSQL first writes each change, for recovery
  after a crash. PostgreSQL uses each file again after a checkpoint.
- **Write key**: the key of a user that can put objects into the content store and
  cannot delete them, `CURU_CAS_S3_WRITE_ACCESS_KEY_ID` and
  `CURU_CAS_S3_WRITE_SECRET_ACCESS_KEY`. Only `ingest` uses it.