> built 2026-12-05 20:24 UTC from 670e0d6 (main) · annals 0.0.82. Details: build_info.json

# index.html.md

<!-- generated by epythet -->

# annals

Annals for AI agents. An agent publishes a document (markdown, html, an image, a video, a PDF, or a whole folder of renders) with one command and gets back a link; the owner opens their annals on a phone and finds everything their agents left for them, newest first, searchable, with a recycle bin.

```bash
pip install annals
annals publish report.md --session my-agent
# https://apps.example.com/annals/d/20261003-203301-quarterly-report-3f9a
```

Beside what agents publish, the page can list other folders read in place, such as the sessions’ ledgers (`~/.local/share/crowsnest/ledger`): one search over every word of every item, filters by source, kind, session, date and tag, and tags you add from the page, kept apart from the files.

Documents are plain files in a directory. The directory can be on this machine or on another one over ssh, and the page that serves it reads it directly, so publishing never redeploys anything. No database, no build step, no API token.

## For agents

Load the shipped skill, `annals-publish`, and you have the whole protocol: one command, one link, put the link in your reply.

```bash
annals publish report.md                          # one document, prints its link
annals publish a.md b.md c.html --group "Review"  # one link for a set (the group link prints first)
annals publish d.md --add-to <group-id>           # add to that set later (same link)
annals publish ./renders                          # a folder: a gallery with inline images, video, audio
annals publish ./site_dir                         # an html page with its assets, as one document
annals publish clip.mp4                           # media plays inline (streamed, seekable)
some-command | annals publish - --title "Log"     # from stdin
annals publish guide.html --replace <link-or-id>  # a new version of a document: same link
annals publish page.md --upsert item=X --add-to <group>  # replace the document whose meta item is X, or create it (and group it)
annals publish page.html --artifact <claude.ai artifact link>  # plus a button to its interactive version
annals publish r.md --session <name>             # the page links the Claude Code session that made it (never in a share)
annals ls "search words"                          # what is there, newest first
annals trash <id>  /  annals restore <id>         # the recycle bin
annals rename <link-or-id> "New title"           # rename a document or group (kept by later versions)
```

Handed an annals link to read? It is private, so fetching it gets a login page. Read it through the same channel that publishes, on any machine where `annals publish` works; no share link is needed:

```bash
annals aggregate <link>   # the text of a document, or of every document in a group, as one markdown on stdout
annals show <link>        # its metadata, the groups it is in, and the annals links in its text
```

A link finds its own annals: its host is matched against every place the config knows (the default `base_url` and each named target’s), so a link to a second annals reads from there without `--to`.

What each kind looks like on the page:

| Published                                      | Shown as                                                                                                                 |
|------------------------------------------------|--------------------------------------------------------------------------------------------------------------------------|
| a `.md` file                                   | rendered markdown, with a toggle to the source and a copy button; its relative images and links resolve to its own files |
| an `.html` file, or a folder with `index.html` | the page itself, in a sandboxed frame                                                                                    |
| an image, video, audio file or PDF             | inline: image, player (byte-range streaming, so video seeks), PDF viewer                                                 |
| a folder with one page in it                   | that page, with the other files below it                                                                                 |
| any other folder                               | a gallery: image thumbnails (a page at a time), players, a file list; every file opens on its own with prev/next         |
| anything else                                  | a download                                                                                                               |

A folder skips hidden files and caches (`.*`, `__pycache__`, `*.pyc`); `--all-files` keeps them.

### Interactive version (`--artifact`)

`annals publish page.html --artifact https://claude.ai/...` stores the link of a Claude Artifact holding the same page in the document’s meta (`artifact`), and the document’s page shows an “Open the interactive version” button next to the frame. Comments, per-viewer and shared state and sharing then live on the artifact while annals stays the single in-tray. Only plain `https` links to `claude.ai` are accepted (`annals.store.ARTIFACT_HOSTS`; no port, credentials or odd characters), `--artifact` takes one path, and a `--replace` without `--artifact` keeps the current link.

### Links to what a document mentions

The owner reads on a phone and clicks through, so a document that mentions an issue or a message should link to it. `annals publish` reads markdown and text documents before publishing and warns on stderr about bare issue references (`#12`, `owner/repo#12`) and dated mentions of a message (“Karl asked on 10-29 in #tech-app-test”) that have no link (`annals.linkcheck`). It is a warning, not a gate: the document is published either way. `--no-link-check` turns it off.

### Every html page carries its own PDF button

A page is often read without the annals page around it: opened full page, its raw link mailed on, or shared. So `annals publish` puts a **Download this page as PDF** link inside the stored html itself (a line of its own at the end of the page, in its flow, so it never covers anything; hidden when printing, and taken out inside a frame, where annals offers the PDF in its own bar), pointing at `<stem>.pdf` beside it in the same document, printed at publish time by headless Chromium with the page’s print css (the `pdf` extra, then `playwright install chromium`). Printing runs in a child process killed after 60 seconds (`annals.pagepdf.DFLT_PRINT_TIMEOUT_S`); without Chromium, or when the page does not print in time, the button opens the browser’s print dialog instead, so it is never missing. The `server` extra leaves Playwright out on purpose (a server publishes only its own overview pages), so those get the print button. The document’s meta records the PDF as `pdf`. A share of the page includes the PDF, since the page links to it.

- A page that already has its PDF declares it, and nothing is printed: `<link rel="alternate" type="application/pdf" href="guide.pdf">` in its `<head>` (the button points there), or a `<stem>.pdf` published beside it.
- A page with its own download button marks it with `data-annals-pdf` (any element), and nothing is added.
- `data-annals-pdf="off"` on `<html>` or `<body>`, or `annals publish --no-pdf`, leaves the page as it is.
- `--replace` swaps the old button for a new one and prints the new version again.

In Python the printer is a seam: `DocStore.publish(..., pdf_renderer=fn)` takes any `fn(html_path) -> pdf bytes` (`None` never prints; the default is `annals.pagepdf.DFLT_PDF_RENDERER`, Chromium through pdfdol), and `pdf=False` turns it off. See `annals.pagepdf`.

### Living pages (`--replace`, `--upsert`)

`annals publish <path> --upsert key=value` is `--replace` for a document you find by its meta: it replaces the newest live document whose `source.<key>` equals the value, or creates one carrying that `key=value`, in one call. The reply adds `"created": true|false`, and `--group` / `--add-to` apply only when the document is new, so a repeated run changes nothing but the content (`--add-to` also heals a grouping that failed the first time). Upserts of one `key=value` are serialised by a lock beside the documents, so concurrent runs make one document. A document in the bin is not found: upserting after trashing it creates a new one. It needs a store it can read, so not an outbox or a room (use `--replace` with the id there).

`annals publish <path> --replace <link-or-id>` publishes a new version of an existing document: the id and the link stay, the page shows the new version marked “updated” and lists the earlier ones, each readable at `/d/<id>@<n>`. The previous files are kept under the document’s `.versions/<n>/`; nothing is deleted. It takes one path (a file, a folder, stdin), and a replaced group member stays in its group.

A replacement is written next to the document as a pending directory (`docs/<id>.r<stamp>-<hex>/`), never over it, and applied by whoever reads the store (the server, or the next publish): a few renames, the first of which claims the document, so concurrent readers never apply one twice or out of order. That is what lets a replace travel through an **outbox**, a directory another machine pulls and empties: mark it with `annals configure --outbox` (or `ANNALS_OUTBOX=1`), and replacements published there are left for the server to apply when they land. HTML pages without a doctype are served with `<!doctype html>` (plus a charset and viewport when missing), so they render in standards mode.

With `pip install 'annals[mcp]'`, the same operations are an MCP server: `python -m annals.mcp`.

## Where documents go

```bash
annals configure --target tw:/root/.local/share/annals --base-url https://apps.example.com/annals
```

That writes `~/.config/annals/config.toml`. `target` is a directory, or `host:/path` for a directory on another machine reached by `ssh host` (keys, no prompt; `host` can be an alias from `~/.ssh/config`). `ANNALS_TARGET` and `ANNALS_BASE_URL` override it per shell. With no configuration, documents go to `~/.local/share/annals` and the link points at a local `annals serve`.

### A second place (`--to`)

A config file can name more places: `annals configure --to team --target host:/path --base-url https://team.example.com/annals` saves a `[targets.team]` table and leaves the default alone. Then `annals publish r.md --to team` (also `ls`, `show`, `trash`, `restore`, `group`, `groups`) works on that place only, and `annals copy <link-or-id> --to team [--source other]` copies documents or whole groups there, keeping their ids. Nothing about the place is in the code: a name, a target and a base url.

### A room for an outside audience (`--room`)

A room is an annals for people outside (a client, a team): `annals configure --to client --target host:/path --base-url https://.../client_files --room`, then `annals copy <link> --to client` or `annals publish f.pdf --to client`, and nothing written there carries provenance (host, cwd, session, `--meta`). Serve it with `mk_api(data_dir=..., room=True)` behind the host’s login: read only, no bin, no ledgers, listening, overviews or shares, and only the meta fields a reader needs (no provenance) in any page or API answer, even for documents written by other means. Withdraw a document with `annals trash <id> --to client`.

## Hosting the page

**Inside an app platform** (the usual case). Mount the API under the platform’s prefix and let the platform’s login gate it:

```python
# server.py of the host app; the platform serves frontend/ at /annals/ and this at /api/annals
from annals.api import mk_api
app = mk_api(data_dir="/root/.local/share/annals")
```

and write the page shell once as the app’s frontend:

```bash
annals page-shell --api /api/annals --base /annals > frontend/index.html
```

The shell only names those two paths; the page’s script and style load from the API, so upgrading the package upgrades the page. Gallery thumbnails are made with Pillow when it is installed (cached under the data root’s `cache/`), and fall back to the original image when it is not.

**Standalone**, for a machine with no platform:

```bash
pip install 'annals[server]'
ANNALS_DATA_DIR=~/.local/share/annals annals serve --host 127.0.0.1 --port 8765
```

The page is at `http://127.0.0.1:8765/annals/`, its API under `/annals/api/`. Auth is chosen by environment variables:

| Situation                                                                 | Set                                                                                                   | Effect                                                                                                                                                                                   |
|---------------------------------------------------------------------------|-------------------------------------------------------------------------------------------------------|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| Behind an existing login that exposes a who-am-I endpoint                 | `ANNALS_WHOAMI_URL`, `ANNALS_ALLOWED_USERS=me@example.com`, optionally `ANNALS_LOGIN_URL=/auth/login` | the browser’s cookies are forwarded to that endpoint and the listed emails are allowed; anyone else is sent to the login page                                                            |
| No platform login                                                         | `ANNALS_BASIC_USER`, `ANNALS_BASIC_PASSWORD`                                                          | HTTP Basic                                                                                                                                                                               |
| Behind a gateway that names the reader in a header (a forward-auth proxy) | `ANNALS_USER_HEADER=X-Iq-User`, optionally `ANNALS_ALLOWED_USERS`                                     | the header names the reader, so each one’s listening is their own and overviews can be offered to some; bind to 127.0.0.1 behind the gateway, which must replace any copy a client sends |
| Localhost only                                                            | nothing                                                                                               | open                                                                                                                                                                                     |

## Acting on documents: pick, then choose what you want back

On a group’s page, tick the documents you want (with none ticked, all of them count); a bar at the bottom says what is picked and offers three buttons named after what they give, each opening one sheet (Back closes it):

- **Links**: **One link** for a person (expiry, optional password, and on a document “What’s included”) or **A link per document** for a notebook (one plain page each, no password). Your own agents need neither: the sheet’s first line copies the private address, which they read with `annals aggregate <link>`. Every link has its own copy button, plus **Copy all**.
- **One file**: the picked documents’ files (Markdown, html, text, PDFs, images) as one Markdown, PDF or web page file, to copy, download or open.
- **Listen**: a spoken review (when the host offers them, see below). For several documents, **One review of all** (their text is put in one document, tagged `combined` and added to the group, and that document gets an ordinary review; the same documents at the same versions reuse it) or **One each** (makes only the missing or out-of-date ones).

Under **⋯ More**, **Download originals (.zip)** streams the picked documents’ files exactly as published (audio and video too, which One file cannot hold): one folder per document, named after its title. The size is shown before the download starts; a pick of more than 100 documents or 512 MB (`annals.originals.MAX_DOCS`, `MAX_BYTES`) is refused with that limit named. `GET /originals/info?doc=<id>...` answers the size, `GET /originals.zip?doc=<id>...` the zip.

A document’s page has the same three buttons, acting on that document, and both pages keep the rest (copy the text, downloads, open raw, move to bin) under **⋯ More**. Every link, password and code block on the page has the same copy button: it copies inside the tap and answers on itself with a check and “Copied”.

## Spoken overviews

A document’s page can offer a Listen button: a few minutes of speech about the document, played with its script in sync. It is off unless the host turns it on, because making one spends money.

```python
app = mk_api(overviews=True)  # the button, and POST /docs/{id}/overview
```

Or only for some readers. The others see no Listen button, the overview routes answer them 404, and the documents overviews made are in none of their lists, searches, groups or Audio tab:

```python
app = mk_api(overviews={"me@example.com"})  # names as the login gives them
```

`annals serve --overviews '*'` turns it on without host code (or reader names separated by commas, as your login names them; with no login it is for this machine only, since anyone reaching the page could spend money); `annals serve` and the `annals.api:mk_app` factory also read the same choice from `ANNALS_OVERVIEWS`: unset for off, `*` for every reader, or names separated by commas. What the command may rely on and owes is written down in `misc/docs/design.md` (“The overview engine contract”).

A worker on the same machine fulfils the requests. It runs a command you choose, which takes a text file and writes one HTML page, and publishes that page as a document of its own:

```bash
export ANNALS_OVERVIEW_COMMAND='hailing overview {source} --minutes {minutes} --no-publish --player-to {out}'
annals listen-work                 # fulfils what is queued, one at a time
annals listen <doc-id> --minutes 3 # asks for one from the command line, as the button does
```

Run `annals listen-work` from a timer, not from a watcher on the folder: finished request files stay there, so a watcher would keep waking it. A current overview is not made again unless forced, and at most 20 are started in any 24 hours (`ANNALS_OVERVIEW_DAILY_LIMIT`). `annals.overview` has the details.

When the command cannot work until someone acts (an expired login, a voice account out of credit), the worker notices (the same failure, fast, from two documents in a row) and marks it down. The Audio tab and the Listen control then say why instead of offering a Try again, new requests wait, one is tried again every few hours, and the first success makes everything that waited. An agent that filed the fix can attach it, so the page links to it:

```bash
annals listen-down "the server's login expired" --link https://github.com/<owner>/<repo>/issues/<n>
annals listen-down            # shows the current state
annals listen-down --clear    # it works again: clears the mark and queues what waited
```

## Audio: what you still have to listen to

The **Audio** tab lists every spoken overview (documents tagged `overview`), newest first, with a search box and a filter by what you have heard: **Not started**, **In progress**, **Done**. Each row shows how much of it you heard and how many times you heard it to the end, and has a **Mark done** button for one you heard elsewhere.

An overview you asked for that is not made yet is listed above them, under **Not made yet**: being made (the tab looks again every few seconds and moves it into the list when it is ready), or failed, with when it was last tried, the document’s date, why (behind **Why**) and a **Try again** button. A command that answers in JSON (as `claude -p --output-format json` does) has its reason read out of it, so you see the reason rather than the envelope. A failure stays there for a week, so an overview you asked for never silently fails to appear.

Progress is kept on the server, per reader (the login’s email; `owner` with no login), so it follows you from the phone to the tablet: an overview you stopped halfway picks up where you stopped, on any device, with **Start over** beside it. What counts:

- **heard**: the distinct seconds played, so a replayed minute counts once; at 95% it is done;
- **listens**: each play that reaches the end of audio heard almost whole (dragging to the end is not a listen), counted once however often the page reports it;
- **your mark**: Mark done (or not done) wins over both; Reset forgets the document.

An overview plays inside a sandboxed frame, so the page cannot see its audio directly: every served html page that may play media gets a small relay script (`annals.media`) that posts what the player itself says it played to the page around it, so a locked screen, seeking or 2× speed are counted right (opt out with `data-annals-media="off"` on `<html>` or `<body>`; share links never carry it). Plain audio files are tracked from their own player. Records are one JSON file per reader under the data root (`listening/<reader>.json`); `mk_api(listening=...)` takes any other store, and `listening=None` keeps none. Progress is recorded on the annals page itself; a page opened on its own (“Open full page”) does not report.

## Highlights: keep a passage, find it again

On a document’s page, select some text and tap **Highlight**: the passage is kept, under the name `<title>-highlight-<n>`. A short note offers “Add a note or tags”; the name, the note (a comment), the tags and a colour are all optional and can be changed later. The page draws its highlights (a dotted line under the ones with a note), a tap on one shows its card, and removing one offers Undo.

**Highlights** in the navigation lists every passage you kept and filters as you type, over names, passages, notes, tags and document titles. A row opens its document on the passage: scrolled to it, in the middle of the screen, with its card open. The address is `…/d/<id>?h=<highlight>`, and Copy link on a card gives it.

To keep a whole document, highlight its title (select it, or “Highlight this page” under More → Highlights). It then sits in the same list, so the list is also your favourites, and it survives a rename.

More → Highlights is the page’s panel: its highlights, a switch to hide them, and two settings: the default colour (six of them, each legible in light and dark) and whether a page shows all of its highlights when it opens, or only the one you came for.

Highlights are each reader’s own, kept on the server (`highlights/<reader>.json` under the data root), so they follow you to every device behind the same login. There are none on a share link or in a room, where nobody is signed in. A markdown or text document is highlighted in its rendered view; an html page lives in a closed frame, so only its title can be kept.

For agents, the same collection:

```bash
annals highlights "rye water table"                  # search: every word, in name, passage, note, tags or title
annals highlights --doc <link or id> --tag later     # one document's, one tag's
annals highlight-add <link or id> "the passage, word for word" --comment "why" --tags "a, b"
annals highlight-add <link or id> "a passage" --file notes.md   # in one file of a folder document
annals highlight-add <link or id> "its title" --whole   # keep the document itself
annals highlight-edit <highlight id> --comment "..." --color green
annals highlight-remove <highlight id>
```

Reading works wherever the documents can be read. Changes are made on the machine that holds them (`ssh <host> annals highlight-add …`), because the server locks its files and a write from elsewhere would not; `--reader` (the address they sign in with) says whose: it can be left out once one reader, and only one, has highlights, and one reader’s are never listed with another’s. The page side is the [manicules](https://github.com/thorwhalen/manicules) widget, vendored under `annals/data/ui/vendor/manicules/` (`scripts/vendor-manicules.sh`); `annals.highlights` is the server side, and `mk_api(highlights=...)` the seam (any `(reader) -> ReaderHighlights` callable, or `None` to keep none).

## Read tokens: one group, for an agent that cannot reach the store

A cloud session with no ssh and no connector can read one group over HTTPS with a token:

```default
annals token new <group-id-or-link> --name cloud-agent          # 14 days; --expires 30d, at most 90d
annals tokens                                                   # live tokens (--all: revoked and expired too)
annals token-revoke <id>                                        # stops working at once
```

The token is printed once and only its hash is kept. It is sent as `Authorization: Bearer <token>` and reads (`GET`) the API of that group and nothing else: no other group, no publishing, no bin, no shares, no pages. A document tagged `private` or `noindex` is never reachable, and a combined document or overview is reachable only when every document it was made from is. A document dropped from the group, retagged or binned leaves the token’s reach within about two seconds. An agent is never offered `token new` or `token-revoke` (they are `credential` operations, not served by the MCP surface unless asked).

## Sharing one page

The annals is private; a **share link** lets someone without an account read ONE document (or one group) and nothing else. From the page, **Links › One link** on a document lists its files and the annals pages it links to under “What’s included”, so you choose what goes; from a shell:

```bash
annals share <id-or-link> --password -                       # 7 days by default; password from stdin
annals share <id> --expires 2026-11-30                       # or 12h, 30d, an ISO time, `never`
annals share <id> --include img/chart.png,img/map.png        # only these files (the page always goes)
annals shares                                                # live links (--all: revoked and expired too)
annals unshare <link-or-token>                               # off at once
```

The link is `<share_base_url>/<token>/`: 128 random bits, `noindex`, `no-referrer`. Every request is checked against the share’s record (`shares/<token>.json` under the data root), so a file you did not choose is a 404 even beside the shared page, a revoke or an expiry takes effect on the next request, and references to anything outside the share (an image you left out, a link to another annals page or to anything else on your annals’ host, an annals id in the text) are removed from every text file before it is sent (markdown, html, plain text, svg). A linked page you tick goes with the files it shows, not every file beside it. The password is a gate on the link, not an account: at least 8 characters, stored hashed (stdlib scrypt), with attempts limited per client and per link, and a correct one earns a cookie scoped to that link. Links are read-only and last 7 days unless you say otherwise.

**One link, readable by people and agents.** The page a link opens is the shared text itself, rendered on the server, with no script: markdown rendered, a group’s documents one after another, audio and video with the browser’s players. A document that is an html page is served as itself, sandboxed. So a person, NotebookLM, a link preview or `curl` all read the document, not only its title. The script viewer (galleries, downloads) is a link away (`<link>/?viewer`). The same link also answers as one file, under the same token, expiry, password and revocation:

| form     | address                                                                    | give it to                                                                     |
|----------|----------------------------------------------------------------------------|--------------------------------------------------------------------------------|
| page     | `<link>/` (a group: every document, in order); `<link>/d/<id>` one of them | a person, NotebookLM or any web reader                                         |
| Markdown | `<link>/share.md`; `<link>/d/<id>.md`                                      | an agent: the whole share as one text                                          |
| PDF      | `<link>/share.pdf`; `<link>/d/<id>.pdf`                                    | someone who wants the images in one file, or an upload (needs the `pdf` extra) |

The page names the other two in `<link rel="alternate">`, `annals share` prints all three, and the Share sheet offers them under “Same link as Markdown or PDF”.

Where the links are served:

- **Standalone** (`annals serve`): at `/annals/shared/<token>/`, outside the login, with nothing to configure.
- **Inside an app platform**: the share server must be reachable without the platform’s login, so run it as its own public app and tell annals where it is:

```python
# server.py of a second, PUBLIC app (the owner's app keeps its login)
from annals.share_api import mk_share_api
app = mk_share_api(data_dir="/root/.local/share/annals")
```

then set `ANNALS_SHARE_BASE_URL` (or `annals configure --share-base-url ...`, or `mk_api(share_base_url=...)` for the owner’s page) to that app’s public URL. Until it is set, shares are made but carry no link. `mk_share_api` takes `rate_limiter=` and `link_failure_limiter=` (anything with `allow(key) -> bool`, such as heed’s Redis limiter; the defaults count per process), `trusted_proxies=` (whose `X-Forwarded-For` names the client; loopback by default) and `private_hosts=`; the password `hasher` is a keyword of `annals.share.Shares` (argon2, or anything with `hash`/`verify`).

## Downloads

Every markdown page offers two downloads made by the server, under **One file** and under **⋯ More**: **Markdown (.md)** and a titled **PDF** with the images inside (audio, video and other files appear as a link to the resource). Both are named after the title (`quarterly-report-q3.pdf`) and are served under the same rules as the page: the owner’s login, or a share link’s scope (a recipient gets the filtered text and only the files the link includes). The PDF needs `pip install "annals[pdf]"` (WeasyPrint, which uses Pango; `annals[server]` includes it); without it the PDF action answers with that hint. Pages (`/d/<id>`) are drawn in the browser by `app.js`, so a page that gains an action gains it for every existing document.

A markdown page also opens **as a web page of its own** (**⋯ More → Open as web page**, `/api/annals/export/<id>?format=html`): the rendered text with its images inside, no script, no annals page around it, and the same **↓ PDF** button every annals-made html page carries, pointing at the PDF above. That is the link to open full page or send on; **Open raw** still gives the markdown itself.

## One file from many: Markdown, PDF or a web page

**One file** (on a group, a selection or one document) combines the picked documents’ files into a single file and lets you choose its format: **Markdown** (shown, with **Copy Markdown**, **Download .md** and **Open as text**), **PDF** (with a bookmark for each file) or a **Web page** (one self-contained `.html`). Audio and video cannot be part of a document; they are listed as left out, each with the reason, and so is a file that cannot be read (a damaged or password-protected PDF) while the others still go in. It is made on each request and never stored. A share link has the same button, built from the share’s filtered text and only the files it includes.

| input                                 | to Markdown                     | to web page / to PDF                                                                  |
|---------------------------------------|---------------------------------|---------------------------------------------------------------------------------------|
| markdown                              | as it is                        | rendered, the document’s images inside                                                |
| html                                  | converted (needs `markdownify`) | its structure and words; scripts, styles, frames, forms and remote images are dropped |
| text (`.txt`, `.json`, `.csv`, code…) | a code block                    | a preformatted block                                                                  |
| PDF                                   | its text (a scan has none)      | web page: its text; PDF: its pages, joined as they are                                |
| image                                 | not supported                   | a figure / a page of its own                                                          |

An image or a text file that sits in a document with pages (markdown, html, a PDF) belongs to that document, not a section of its own: a report and its figures combine as the report. Files are arranged with numbered names first, in numeric order, then the rest in the documents’ order.

```bash
annals aggregate <group-or-doc-id-or-link> > all.md                    # Markdown, from a shell
annals aggregate <id> --format pdf --output all.pdf                     # a PDF needs --output
annals aggregate <id> --format html --output all.html
annals aggregate <id> --order given --demote 0 --no-toc --keep-wraps   # Markdown options
```

The libraries behind each pair load only when it is used: PDF pages need WeasyPrint (which uses Pango), joining and reading PDFs need `pypdf` and `pdfdol`, html to Markdown needs `markdownify`. `pip install "annals[pdf]"` installs them all; a missing one stops the job before it starts, naming the library and the command. The API is `GET /groups/<gid>/aggregate?format=md|html|pdf` and `GET /aggregate?doc=<id>&doc=<id>` (`&download=1` to save, `&demote=`), `GET /<token>/aggregate` on the share server, and `GET /combine/formats` for what can be made; the response carries `X-Annals-Sections` (files that went in) and `X-Annals-Skipped` (percent-encoded JSON: which were left out and why).

A new pair (say docx to PDF) is one function in `annals/combine.py`, and every surface above learns it:

```python
from annals.combine import register

@register("docx", "pdf", requires=("some_module",))
def docx_to_pdf(item, ctx):          # item.text(), item.data(), item.rel; return the part for the format
    ...
```

```python
from annals.aggregate import aggregate_markdown        # the text mechanism, no documents involved
aggregate_markdown({"notes.md": "# Notes", "01-intro.md": "Hello"}, title="Bundle", demote=1)
```

`aggregate_markdown` takes `(path, text)` pairs and knows nothing of annals: `order=` (`numbered_first` by default, `None` for the order given, or any `paths -> paths` callable), `demote=`, `unwrap=`, `toc=`. The Markdown file has the title, a table of contents, and one `##` section per file named after its path (`Report/01-intro.md`); each file’s headings go one level down and hard-wrapped lines are joined. Footnotes are renamed per file so they do not collide, and a code block a file leaves open is closed at the end of its section. Relative links and images keep their paths, so they do not resolve inside the combined Markdown.

## A group’s documents as separate notebook sources

To take a group into a notebook (NotebookLM, now Gemini Notebook) with each document as its own source, open the group, tick the documents (none ticked means all), tap **Links**, choose **A link per document** and how long the links work (1 day by default), and tap **Make N links**. You get one link per page, each with its own copy button; tap **Copy all N links**, then in the notebook choose Add source → Website and paste: the notebook makes one source of each link, named after the document.

The links are an ordinary share of just those documents (no password, since the notebook cannot type one): unguessable, filtered like every shared text, and revocable with **Turn these links off** or under the **Links** tab. The notebook keeps its own copy once a link is added, so turning the links off afterwards does not remove the sources. Each link is a plain web page with no script (`<share link>/source/<doc id>/<file>`); markdown is rendered on the server, images, audio and PDFs get no link (a notebook takes those only as uploads). Why links and not a zip or a download: `misc/docs/notebook-sources.md`.

The API: `GET /shares/<token>/sources` (the owner’s) or `GET <share link>/sources` (the recipient’s) lists `{title, url}` per page; `GET /groups/<gid>/aggregate?doc=<id>&doc=<id>` combines only those documents.

## Other folders, search, filters and tags

Name extra folders when you mount the API, and they appear beside the published documents, each in its own section (`/annals/s/<name>`) and in `/annals/all`:

```python
app = mk_api(data_dir="~/.local/share/annals", sources={"ledgers": "~/.local/share/crowsnest/ledger"})
```

or, with no code, `ANNALS_SOURCES="ledgers=~/.local/share/crowsnest/ledger"` (several: comma-separated). A folder is read in place and never written: its files are listed newest first with their age, markdown renders, html is framed, the rest shows by its kind, and a sub-folder’s files count as written by the sub-folder’s name. Hidden files and caches are skipped.

**Per-machine mirrors.** `ANNALS_SOURCES="ledger-hosts=hosts:/srv/ledger-hosts"` (in Python, `sources={"ledger-hosts": annals.sources.HostMirrors(path, name="ledger-hosts")}`) lists each `<path>/<machine>/` folder as a source of its own, `ledger-hosts-<machine>`, titled “Ledger hosts: <machine>”: the folder name is the machine, so two machines holding a session of the same name stay two entries. A machine’s page says when it last pushed, read from the `_mirror.json` the pusher keeps in its folder (`{"machine", "pushed_at", "files"}`; the file is not listed as an item), so a ledger is never read as current on a machine that stopped pushing; the API’s rows and `/sources` carry `machine` and `pushed_at`. The folders are looked at again on every listing: a machine that starts pushing appears without a restart. A folder name that is not already lowercase letters, digits, `-` and `_` gets a short hash in its source name, so no two machines share one; renaming a machine’s folder makes it a new source (its tags stay with the old name). A push time that is not a valid ISO time, or is in the future, is not shown.

On every list:

- **Search** matches every word, case-insensitively, against titles, tags, sessions, excerpts and the full text of markdown and text files (on the server; the matching passage shows under the title).
- **Filters** are one button per family (source, kind, session, date, tag). Checked values within a family are alternatives (“any of”), families combine (“and”), the counts are what each choice would give now, and the active filters show as removable chips. The filters and the search are in the URL, so Back undoes a filter and a link reproduces the view.
- **Tags**: add or remove them on any item’s page; they save as you go. They are stored apart from the items, in one file under the data root (`tags/tags.json`), so a ledger is never touched; on a published document they replace the tags the publisher gave.

The API behind it: `GET /items?q=&source=&trash=` → `{data, total}`, `GET /items/<source>:<id>`, `PATCH /items/<source>:<id>` with `{"tags": [...]}`, `GET /tags`, `GET /sources`, and `GET /files/<source>/<path>` for a folder’s raw files. The page reaches items through [`@zodal/store-http`](https://www.npmjs.com/package/@zodal/store-http)’s provider (vendored; rebuild with `misc/vendor/build.sh`).

## Python API

```python
from annals import DocStore, publish
meta = DocStore("~/.local/share/annals").publish("report.md", tags=["q3"])
publish(["report.md"], tags="q3")["url"]          # same, through the configured target
```

`annals.api.mk_api(...)` is the mountable API; `annals.api.mk_app(data_dir=..., authorizer=...)` the standalone app. Both take `sources=` (name → folder path, or any `annals.sources.Source`) and `tags=` (any `MutableMapping` from item key to tag list; default `JsonTagStore`). `annals.catalog.Catalog` is the facade they stand on: every source’s rows as one list, searched, with the owner’s tags.

## Design notes

Flat store with tags and groups, not a hierarchy: agents from many projects do not share one, and every placement decision costs tokens. A document is `docs/<id>/meta.json` plus its files; the bin is `trash/<id>/`; a group is `groups/<gid>.json`. Ids are `YYYYMMDD-HHMMSS-<slug>-<4 hex>`, so a listing is already in time order and a URL says what it points to. The transport is a seam (`annals.target`): local directory, ssh, and later an http ingest endpoint. More in `misc/docs/design.md`.

## Skills

```bash
gh skill install thorwhalen/annals annals-publish
```

The skill also ships inside the package at `annals/data/skills/annals-publish/`.

<p class="epythet-aggregates">This documentation as a single file: <a href="annals.md">annals.md</a> (Markdown, for agents).</p>


# _autosummary/annals.aggregate.html.md

# annals.aggregate

Many markdown files as ONE markdown document: a title, a table of contents, a section per file.

The mechanism is text in, text out. [`aggregate_markdown()`](_autosummary/annals.aggregate.html.md#annals.aggregate.aggregate_markdown) takes `(path, text)` pairs
and knows nothing of documents, groups or shares; its choices are keyword arguments with
working defaults:

```default
>>> print(aggregate_markdown(
...     {"notes.md": "# Notes\nOne line\nwrapped.", "01-intro.md": "Hello."},
...     title="Bundle"), end="")
# Bundle

**Contents**

- [01-intro.md](#01-intromd)
- [notes.md](#notesmd)

## 01-intro.md

Hello.

## notes.md

## Notes
One line wrapped.
```

- `order`: how the files are arranged; [`numbered_first()`](_autosummary/annals.aggregate.html.md#annals.aggregate.numbered_first) by default (paths whose
  parts start with a number first, numerically, the rest in the order given), `None`
  keeps the order given, or any `paths -> paths` callable.
- `demote`: how many levels each file’s own headings go down (`1`: a file’s `#`
  becomes `##`); `0` leaves them.
- `unwrap`: join hard-wrapped lines of a paragraph or list item into one line
  ([`unwrap_lines()`](_autosummary/annals.aggregate.html.md#annals.aggregate.unwrap_lines)); code, tables, quotes and html are left as they are.
- `toc`: the table of contents, as links to the sections’ GitHub-style anchors.

[`doc_markdown_files()`](_autosummary/annals.aggregate.html.md#annals.aggregate.doc_markdown_files) is the bridge from annals documents: it yields the pairs for a
set of documents and the files of each a caller may read, through a `read` callable, so
the owner’s API, the share server (which reads filtered text) and the CLI share it.
Nothing is stored: the document is made per request.

### Functions

| [`aggregate_markdown`](_autosummary/annals.aggregate.html.md#annals.aggregate.aggregate_markdown)(files, \*[, title, order, ...])   | One markdown document of `files` (`{path: text}` or `(path, text)` pairs).              |
|-------------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------|
| [`demote_headings`](_autosummary/annals.aggregate.html.md#annals.aggregate.demote_headings)(text[, levels, max_level])           | `text` with every heading `levels` deeper (at most `max_level`); code untouched.        |
| [`doc_markdown_files`](_autosummary/annals.aggregate.html.md#annals.aggregate.doc_markdown_files)(docs, \*, read[, ...])            | `(path, text)` for every markdown file of `docs` (`(meta, files)` pairs).               |
| [`heading_anchor`](_autosummary/annals.aggregate.html.md#annals.aggregate.heading_anchor)(text[, seen])                         | The id GitHub (and most renderers) give a heading; `seen` numbers repeats.              |
| [`numbered_first`](_autosummary/annals.aggregate.html.md#annals.aggregate.numbered_first)(paths)                                | `paths` with numbered ones first, compared part by part, the rest in their given order. |
| [`strip_front_matter`](_autosummary/annals.aggregate.html.md#annals.aggregate.strip_front_matter)(text)                             | `text` without a leading YAML front-matter block (`---` .                               |
| [`unique_paths`](_autosummary/annals.aggregate.html.md#annals.aggregate.unique_paths)(pairs)                                  | The pairs with repeated paths told apart: `a.md`, `a.md (2)`.                           |
| [`unwrap_lines`](_autosummary/annals.aggregate.html.md#annals.aggregate.unwrap_lines)(text)                                   | `text` with hard-wrapped paragraphs and list items joined into one line each.           |

### Exceptions

| [`TooLarge`](_autosummary/annals.aggregate.html.md#annals.aggregate.TooLarge)   | The markdown to aggregate is over the size a caller allows.   |
|-------------------------------------------------------------|---------------------------------------------------------------|

### *exception* annals.aggregate.TooLarge

Bases: [`ValueError`](https://docs.python.org/3/builtins/exceptions.html#ValueError)

The markdown to aggregate is over the size a caller allows.

### annals.aggregate.aggregate_markdown(files, \*, title='', order=<function numbered_first>, demote=1, unwrap=True, toc=True, section_level=2)

One markdown document of `files` (`{path: text}` or `(path, text)` pairs).

A `# title`, a table of contents, then one section per file, headed by its path,
with the file’s text below (front matter dropped, headings `demote`-d, lines
unwrapped); see the module docstring for each choice.

* **Return type:**
  [`str`](https://docs.python.org/3/builtins/stdtypes.html#str)

### annals.aggregate.demote_headings(text, levels=1, , max_level=6)

`text` with every heading `levels` deeper (at most `max_level`); code untouched.

Setext headings (a line underlined with `===` or `---`) become `#` headings.

```pycon
>>> print(demote_headings("# A\nB\n---\n```\n# code\n```"))
## A
### B
```

```text
# code
```

* **Return type:**
  [`str`](https://docs.python.org/3/builtins/stdtypes.html#str)

### annals.aggregate.doc_markdown_files(docs, \*, read, max_bytes=None, skip=(<class 'KeyError'>, <class 'OSError'>, <class 'ValueError'>))

`(path, text)` for every markdown file of `docs` (`(meta, files)` pairs).

`files` are the files of that document the caller may read, and `read(doc_id,
rel)` reads one (the share server passes its filtered reader). A document whose one
markdown file is its page is named by that file; a folder, or a document with several
markdown files, by its title then the file (`Report/01-intro.md`). A file `read`
cannot read (one of `skip`) is left out; past `max_bytes` in all, [`TooLarge`](_autosummary/annals.aggregate.html.md#annals.aggregate.TooLarge).

* **Return type:**
  [`Iterator`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Iterator)[[`tuple`](https://docs.python.org/3/builtins/stdtypes.html#tuple)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`str`](https://docs.python.org/3/builtins/stdtypes.html#str)]]

### annals.aggregate.heading_anchor(text, seen=None)

The id GitHub (and most renderers) give a heading; `seen` numbers repeats.

```pycon
>>> seen = {}
>>> heading_anchor("01-intro.md", seen), heading_anchor("01-intro.md", seen)
('01-intromd', '01-intromd-1')
```

* **Return type:**
  [`str`](https://docs.python.org/3/builtins/stdtypes.html#str)

### annals.aggregate.numbered_first(paths)

`paths` with numbered ones first, compared part by part, the rest in their given order.

A part (a folder or file name) that starts with digits sorts by that number, before any
part that does not; parts without a number keep the order they first appeared in, so a
folder’s files stay together.

```pycon
>>> numbered_first(["b.md", "10-z.md", "a.md", "2-y.md", "r/02.md", "r/01.md"])
['2-y.md', '10-z.md', 'b.md', 'a.md', 'r/01.md', 'r/02.md']
```

* **Return type:**
  [`list`](https://docs.python.org/3/builtins/stdtypes.html#list)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str)]

### annals.aggregate.strip_front_matter(text)

`text` without a leading YAML front-matter block (`---` … `---`).

It must start with a `key:` line, so a page that opens with a horizontal rule
keeps it.

```pycon
>>> strip_front_matter("---\ntitle: x\n---\n# Body")
'# Body'
>>> strip_front_matter("---\nIntro\n---\nbody")
'---\nIntro\n---\nbody'
```

* **Return type:**
  [`str`](https://docs.python.org/3/builtins/stdtypes.html#str)

### annals.aggregate.unique_paths(pairs)

The pairs with repeated paths told apart: `a.md`, `a.md (2)`.

* **Return type:**
  [`list`](https://docs.python.org/3/builtins/stdtypes.html#list)[[`tuple`](https://docs.python.org/3/builtins/stdtypes.html#tuple)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`str`](https://docs.python.org/3/builtins/stdtypes.html#str)]]

### annals.aggregate.unwrap_lines(text)

`text` with hard-wrapped paragraphs and list items joined into one line each.

Only ordinary text lines are joined: headings, list markers, quotes, tables, html,
fenced or indented code, and a line ending in a hard break (two spaces or `\`)
keep their line breaks.

```pycon
>>> print(unwrap_lines("A long\nsentence.\n\n- item\n  goes on\n- next\n\n    code\n    more"))
A long sentence.

- item goes on
- next

    code
    more
```

* **Return type:**
  [`str`](https://docs.python.org/3/builtins/stdtypes.html#str)


# _autosummary/annals.auth.html.md

# annals.auth

The auth seam: who may read the annals.

A annals is private by construction, so the server asks every request who is calling. The
answer comes from one of four `Authorizer` callables, chosen by [`authorizer_from_env()`](_autosummary/annals.auth.html.md#annals.auth.authorizer_from_env)
(or passed to `annals.api.mk_app()`):

* [`no_auth()`](_autosummary/annals.auth.html.md#annals.auth.no_auth): everyone is the owner. Right for `annals serve` bound to `127.0.0.1`,
  wrong anywhere else.
* [`CookieWhoami`](_autosummary/annals.auth.html.md#annals.auth.CookieWhoami): forward the request’s cookies to an identity endpoint that answers
  `{"email": ...}` (enlace_auth’s `/auth/whoami`), and allow the listed emails. This is
  how a annals sits behind an existing login without owning passwords: the login page, the
  session cookie and the logout belong to the platform; the annals only checks the allowlist.
  Env: `ANNALS_WHOAMI_URL`, `ANNALS_ALLOWED_USERS` (comma separated), `ANNALS_LOGIN_URL`.
* [`BasicAuth`](_autosummary/annals.auth.html.md#annals.auth.BasicAuth): one username and password (HTTP Basic). For a annals with no platform
  login in front of it. Env: `ANNALS_BASIC_USER`, `ANNALS_BASIC_PASSWORD`.
* [`TrustedHeader`](_autosummary/annals.auth.html.md#annals.auth.TrustedHeader): a gateway in front (a forward-auth proxy) signs people in and names
  them in a request header it sets, replacing any copy a client sent. The annals reads that
  name, so it can tell readers apart (whose listening is whose, who is offered spoken
  overviews) without a login of its own. Only safe when nothing but the gateway can reach
  the server. Env: `ANNALS_USER_HEADER` (e.g. `X-Iq-User`), optionally
  `ANNALS_ALLOWED_USERS`.

An authorizer returns the caller’s identity (a string) or `None`. The API turns `None`
into a 303 to the login page for a browser GET, and a 401 for anything else, mirroring
what enlace_auth does so the two are indistinguishable from the phone.

### Functions

| [`authorizer_from_env`](_autosummary/annals.auth.html.md#annals.auth.authorizer_from_env)([env])   | Pick the authorizer the environment describes; see the module docstring.   |
|-------------------------------------------------------------------------------|----------------------------------------------------------------------------|
| [`no_auth`](_autosummary/annals.auth.html.md#annals.auth.no_auth)(request)             | Everyone is `owner`.                                                       |

### Classes

| [`BasicAuth`](_autosummary/annals.auth.html.md#annals.auth.BasicAuth)(username, password)                      | HTTP Basic with one username and password, compared in constant time.            |
|-----------------------------------------------------------------------------------------------------|----------------------------------------------------------------------------------|
| [`CookieWhoami`](_autosummary/annals.auth.html.md#annals.auth.CookieWhoami)(whoami_url, allowed_users, \*[, ...]) | Ask an identity endpoint who holds this request's cookies; allow listed emails.  |
| [`RequestLike`](_autosummary/annals.auth.html.md#annals.auth.RequestLike)(\*args, \*\*kwargs)                    | The two things an authorizer reads from a request.                               |
| [`TrustedHeader`](_autosummary/annals.auth.html.md#annals.auth.TrustedHeader)(header, \*[, allowed_users])         | The caller is whoever the gateway in front names in `header`; no header, nobody. |

### *class* annals.auth.BasicAuth(username, password)

Bases: [`object`](https://docs.python.org/3/builtins/functions.html#object)

HTTP Basic with one username and password, compared in constant time.

### *class* annals.auth.CookieWhoami(whoami_url, allowed_users, \*, login_url='/auth/login', cache_ttl_s=30.0, cache_max=256, clock=<built-in function monotonic>)

Bases: [`object`](https://docs.python.org/3/builtins/functions.html#object)

Ask an identity endpoint who holds this request’s cookies; allow listed emails.

### *class* annals.auth.RequestLike(\*args, \*\*kwargs)

Bases: [`Protocol`](https://docs.python.org/3/library/typing.html#typing.Protocol)

The two things an authorizer reads from a request.

### *class* annals.auth.TrustedHeader(header, , allowed_users=None)

Bases: [`object`](https://docs.python.org/3/builtins/functions.html#object)

The caller is whoever the gateway in front names in `header`; no header, nobody.

The gateway must set the header on every request it lets through and replace a copy a
client sent, and the server must be reachable through the gateway only (bound to
loopback behind it), or anyone could name themselves. `allowed_users`, when given,
narrows who may read to those names. Names are compared and returned in lower case.

### annals.auth.authorizer_from_env(env=None)

Pick the authorizer the environment describes; see the module docstring.

* **Return type:**
  [`Callable`](https://docs.python.org/3/library/typing.html#typing.Callable)[[[`RequestLike`](_autosummary/annals.auth.html.md#annals.auth.RequestLike)], [`Optional`](https://docs.python.org/3/library/typing.html#typing.Optional)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str)]]

### annals.auth.no_auth(request)

Everyone is `owner`. Only for a server that listens on localhost.

* **Return type:**
  [`Optional`](https://docs.python.org/3/library/typing.html#typing.Optional)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str)]


# _autosummary/annals.bulk.html.md

# annals.bulk

Bulk actions: one action over a selection of items, in one request.

Every single-item action on a document has a batch form here (anything done to one item can
be done to a selection), so the page sends one request per
action and gets one answer, never N requests and N toasts. Each function answers
`{"done": [...], "refused": [{"id" or "key", "why"}]}`: an item that cannot take the
action is refused with a reason and the rest go ahead, and `done` says what actually
changed, which is exactly what an Undo takes back.

- [`edit_tags()`](_autosummary/annals.bulk.html.md#annals.bulk.edit_tags): add and remove tags, per item, atomically (`ops` may differ per item,
  so an Undo can take back only what each item gained or lost).
- [`trash()`](_autosummary/annals.bulk.html.md#annals.bulk.trash) and [`restore()`](_autosummary/annals.bulk.html.md#annals.bulk.restore): move to and from the recycle bin (each the other’s Undo);
  one already where it was asked to go is listed in `already`, not `done`.
- [`purge()`](_autosummary/annals.bulk.html.md#annals.bulk.purge): delete forever, only what is already in the bin. Irreversible: the page asks
  first (with the count; typed above a threshold).

A selection larger than `max_items` is refused whole (`ValueError`): the page says so
rather than starting a request that could time out half way.

```pycon
>>> from annals.store import DocStore
>>> import tempfile
>>> store = DocStore(tempfile.mkdtemp())
>>> a = store.publish(text="# A", title="A", filename="a.md")["id"]
>>> trash(store, [a, "nope"])["refused"]
[{'id': 'nope', 'why': 'no such document'}]
>>> restore(store, [a])["done"] == [a]
True
```

### Functions

| [`edit_tags`](_autosummary/annals.bulk.html.md#annals.bulk.edit_tags)(catalog, ops, \*[, max_items])    | Apply `[{"key", "add": [...], "remove": [...]}, ...]`, each item on its own, in one write of the tag store.                                                        |
|----------------------------------------------------------------------------------------------|--------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| [`purge`](_autosummary/annals.bulk.html.md#annals.bulk.purge)(store, catalog, ids, \*[, max_items]) | Delete each document forever, only those in the bin (the ids the person confirmed, never "everything in the bin now": one binned since from another tab survives). |
| [`restore`](_autosummary/annals.bulk.html.md#annals.bulk.restore)(store, ids, \*[, max_items])        | Bring each document back from the recycle bin (already out counts as done).                                                                                        |
| [`trash`](_autosummary/annals.bulk.html.md#annals.bulk.trash)(store, ids, \*[, max_items])          | Move each document to the recycle bin (already there counts as done).                                                                                              |

### annals.bulk.edit_tags(catalog, ops, , max_items=500)

Apply `[{"key", "add": [...], "remove": [...]}, ...]`, each item on its own, in
one write of the tag store.

`done` lists `{"key", "added", "removed", "tags"}` for each item that changed or was
already as asked; `refused` names the rest (no such item, an invalid tag).

* **Return type:**
  [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)

### annals.bulk.purge(store, catalog, ids, , max_items=500)

Delete each document forever, only those in the bin (the ids the person confirmed,
never “everything in the bin now”: one binned since from another tab survives).

* **Return type:**
  [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)

### annals.bulk.restore(store, ids, , max_items=500)

Bring each document back from the recycle bin (already out counts as done).

* **Return type:**
  [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)

### annals.bulk.trash(store, ids, , max_items=500)

Move each document to the recycle bin (already there counts as done).

* **Return type:**
  [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)


# _autosummary/annals.catalog.html.md

# annals.catalog

The catalog: every source’s items as one list, with search and the owner’s tags.

[`Catalog`](_autosummary/annals.catalog.html.md#annals.catalog.Catalog) is the facade the HTTP API stands on. It combines named sources (see
[`annals.sources`](_autosummary/annals.sources.html.md#module-annals.sources)) and a tag store (see [`annals.tags`](_autosummary/annals.tags.html.md#module-annals.tags)):

* [`Catalog.rows()`](_autosummary/annals.catalog.html.md#annals.catalog.Catalog.rows) lists items newest first, across sources or within one, each row
  with the owner’s tags overlaid. With a query, the catalog’s search strategy (its
  `search` keyword; see [`annals.search`](_autosummary/annals.search.html.md#module-annals.search)) picks the matching rows, best first, each
  with a `snippet` of the text around the match and, when it ranks, a `score`.
* [`Catalog.item()`](_autosummary/annals.catalog.html.md#annals.catalog.Catalog.item) is one item, [`Catalog.set_tags()`](_autosummary/annals.catalog.html.md#annals.catalog.Catalog.set_tags) replaces its tags (in the tag
  store, never in the item), [`Catalog.tag_counts()`](_autosummary/annals.catalog.html.md#annals.catalog.Catalog.tag_counts) lists every tag in use.

Facets (kind, session, date, tag) are not computed here: the page counts them over the rows
it received, so every toggle is instant and the counts are always the ones the current
query would give.

### Functions

| [`default_tags`](_autosummary/annals.catalog.html.md#annals.catalog.default_tags)(store)                            | Where the owner's tags live by default: one JSON file under the data root (`tags/tags.json`), or a dict when the data root is not on this machine.   |
|-------------------------------------------------------------------------------------------------|------------------------------------------------------------------------------------------------------------------------------------------------------|
| [`mk_catalog`](_autosummary/annals.catalog.html.md#annals.catalog.mk_catalog)(store, \*[, sources, tags, search]) | The published documents first, then the extra sources; the owner's tags beside them.                                                                 |
| [`owner_tags`](_autosummary/annals.catalog.html.md#annals.catalog.owner_tags)(store)                              | The owner's tags (set by `annals tag` or the page), keyed by item key, as one snapshot.                                                              |
| [`purge_document`](_autosummary/annals.catalog.html.md#annals.catalog.purge_document)(store, catalog, doc_id)         | Delete a document that is in the bin for good: its files, its tags, its cached thumbnails.                                                           |
| [`with_owner_tags`](_autosummary/annals.catalog.html.md#annals.catalog.with_owner_tags)(metas, tags)                   | `metas` (documents' meta) with each one's tags replaced by the owner's, where the owner set them.                                                    |

### Classes

| [`Catalog`](_autosummary/annals.catalog.html.md#annals.catalog.Catalog)(sources, \*, tags[, search])   | Named sources plus the owner's tags, listed, searched and tagged as one collection.   |
|-----------------------------------------------------------------------------------------|---------------------------------------------------------------------------------------|

### *class* annals.catalog.Catalog(sources, \*, tags, search=<function scan_search>)

Bases: [`object`](https://docs.python.org/3/builtins/functions.html#object)

Named sources plus the owner’s tags, listed, searched and tagged as one collection.

#### edit_tags(key, , add=(), remove=())

Add and remove tags on one item; [`edit_tags_many()`](_autosummary/annals.catalog.html.md#annals.catalog.Catalog.edit_tags_many) with one op.

Raises what that op was refused for (`KeyError`: no such item; `ValueError`).

```pycon
>>> cat = Catalog({}, tags={})
>>> cat._source = lambda name: type("S", (), {"item": lambda self, i: {"key": "s:" + i, "tags": ["Old"]}})()
>>> out = cat.edit_tags("s:a", add=["new", "old"], remove=["missing"])
>>> out["added"], out["removed"], out["tags"]
(['new'], [], ['new', 'Old'])
>>> cat.edit_tags("s:a", remove=["new"])["tags"], "s:a" in cat.tags  # back to the publisher's: no entry
(['Old'], False)
```

* **Return type:**
  [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)

#### edit_tags_many(ops)

Add and remove tags on many items, in one atomic step on the tag store.

Unlike [`set_tags()`](_autosummary/annals.catalog.html.md#annals.catalog.Catalog.set_tags), it never writes a list the caller read earlier, so a tag
added meanwhile stays. Case is ignored when matching. Only `add` is validated:
an existing tag the publisher gave (which may break today’s rules) can always be
removed. When an item’s tags come back to the publisher’s, the owner’s entry is
dropped, so the item follows its publisher again (an Undo restores that too).
Answers, per op, `{"key", "added", "removed", "tags"}` or `{"key", "error"}`.

* **Return type:**
  [`list`](https://docs.python.org/3/builtins/stdtypes.html#list)[[`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)]

#### forget(key)

Drop an item’s tags, its search entry and any cached text (when the item itself
is gone for good).

* **Return type:**
  [`None`](https://docs.python.org/3/builtins/constants.html#None)

#### item(key)

One item, with what the page shows; `KeyError` if there is none.

* **Return type:**
  [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)

#### rows(q='', , source=None, trash=False)

Items from one source or all: newest first, or, with a query `q`, the ones
the search strategy matched, best first.

* **Return type:**
  [`list`](https://docs.python.org/3/builtins/stdtypes.html#list)[[`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)]

#### set_tags(key, tags)

Replace an item’s tags (in the tag store); the item’s row, with them.

* **Return type:**
  [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)

#### *property* sources *: [dict](https://docs.python.org/3/builtins/stdtypes.html#dict)[[str](https://docs.python.org/3/builtins/stdtypes.html#str), [Source](_autosummary/annals.sources.html.md#annals.sources.Source)]*

the fixed ones in the order given, then each group’s, by machine.

* **Type:**
  Every source now

#### sources_info()

Each source’s name and title, in the order given; a mirror also says its `machine`
and when it was last pushed (`pushed_at`).

* **Return type:**
  [`list`](https://docs.python.org/3/builtins/stdtypes.html#list)[[`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)]

#### tag_counts()

Every tag in use on a listed item, with how many items carry it.

* **Return type:**
  [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`int`](https://docs.python.org/3/builtins/functions.html#int)]

### annals.catalog.default_tags(store)

Where the owner’s tags live by default: one JSON file under the data root
(`tags/tags.json`), or a dict when the data root is not on this machine.

* **Return type:**
  [`MutableMapping`](https://docs.python.org/3/library/collections.abc.html#collections.abc.MutableMapping)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`list`](https://docs.python.org/3/builtins/stdtypes.html#list)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str)]]

### annals.catalog.mk_catalog(store, , sources=None, tags=None, search=None)

The published documents first, then the extra sources; the owner’s tags beside them.

`sources` maps a name to a folder path (read in place) or a `Source`; by
default the folders named in `ANNALS_SOURCES`. `tags` defaults to one JSON file
under the data root (`tags/tags.json`), or a dict when the data root is remote.
`search` answers queries (see [`annals.search`](_autosummary/annals.search.html.md#module-annals.search)); by default a full-text index
kept under the data root, or a plain scan when the data root is remote.
The API, and any CLI or agent tool that tags items, build their catalog here.

* **Return type:**
  [`Catalog`](_autosummary/annals.catalog.html.md#annals.catalog.Catalog)

### annals.catalog.owner_tags(store)

The owner’s tags (set by `annals tag` or the page), keyed by item key, as one snapshot.

* **Return type:**
  [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`list`](https://docs.python.org/3/builtins/stdtypes.html#list)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str)]]

### annals.catalog.purge_document(store, catalog, doc_id)

Delete a document that is in the bin for good: its files, its tags, its cached thumbnails.

`PermissionError` for one that is not in the bin. Every surface purges through here.

* **Return type:**
  [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)

### annals.catalog.with_owner_tags(metas, tags)

`metas` (documents’ meta) with each one’s tags replaced by the owner’s, where the owner set them.

```pycon
>>> with_owner_tags([{"id": "a", "tags": ["x"]}, {"id": "b", "tags": ["y"]}], {"published:a": ["z"]})
[{'id': 'a', 'tags': ['z']}, {'id': 'b', 'tags': ['y']}]
```

* **Return type:**
  [`list`](https://docs.python.org/3/builtins/stdtypes.html#list)[[`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)]


# _autosummary/annals.combine.html.md

# annals.combine

Many files of many kinds as ONE document: a Markdown, html or PDF file.

The mechanism is a registry. A *converter* turns one file of one kind into a *part* of the
output format (markdown text, an html fragment, a PDF); a *joiner* puts the parts of a
format together (a table of contents and a section each; bookmarks and pages). Which pairs
exist is the table [`REGISTRY`](_autosummary/annals.combine.html.md#annals.combine.REGISTRY), filled by [`register()`](_autosummary/annals.combine.html.md#annals.combine.register):

```default
@register("pdf", "md", requires=("pdfdol",))
def pdf_to_md(item, ctx): ...
```

so a new pair (docx to pdf, say) is one decorated function, and the web page, the API and
the CLI all learn it from [`supported()`](_autosummary/annals.combine.html.md#annals.combine.supported) without a change.

What goes in:

```default
=========  ===========  =======================================================
input      to md        to html / to pdf
=========  ===========  =======================================================
md         as it is     rendered (images of the document inside)
html       converted    its text and structure (scripts and styles dropped)
text       a code block a preformatted block
pdf        its text     html: its text; pdf: its pages, joined as they are
image      -            a figure (html) / a page of its own (pdf)
=========  ===========  =======================================================
```

Audio, video and other files have no place in a document: they are reported as left out,
each with the reason, never silently dropped. A file that cannot be read (a damaged or
password-protected PDF) is left out the same way, and the others still go in.

An image or a text file that sits in a document with pages (markdown, html, a PDF) is part
of that document, not a section of its own: a report and its figures combine as the report.

Heavy libraries load only when a pair needs them (WeasyPrint for PDF pages, pypdf and pdfdol
to join and read PDFs, markdownify for html to markdown); a missing one is a
[`annals.requirements.MissingDependency`](_autosummary/annals.requirements.html.md#annals.requirements.MissingDependency) that says what to install, raised before any
work starts. Nothing is stored: the document is made per call.

```pycon
>>> combined = combine([_demo_source({"b.md": "# B\ntext", "a.md": "hello"})], "md", title="T")
>>> combined.sections, combined.ext
(2, 'md')
>>> print(combined.data.decode().splitlines()[0])
# T
```

### Module Attributes

| [`PAGE_KINDS`](_autosummary/annals.combine.html.md#annals.combine.PAGE_KINDS)          | kinds whose file is a document in itself                                                                                                             |
|----------------------------------------------------------------------|------------------------------------------------------------------------------------------------------------------------------------------------------|
| [`COMPANION_KINDS`](_autosummary/annals.combine.html.md#annals.combine.COMPANION_KINDS)     | kinds that illustrate or accompany a document with pages, so are not sections of its own                                                             |
| [`MAX_SKIPPED_LISTED`](_autosummary/annals.combine.html.md#annals.combine.MAX_SKIPPED_LISTED)  | skipped files listed in a result (and its headers); the rest are counted                                                                             |
| [`MAX_TEXT_PAGES`](_autosummary/annals.combine.html.md#annals.combine.MAX_TEXT_PAGES)      | a PDF with more pages than this is not read for its text (about 0.2 s a page)                                                                        |
| [`MAX_RENDERED_FILES`](_autosummary/annals.combine.html.md#annals.combine.MAX_RENDERED_FILES)  | files made into PDF pages by rendering (about 0.4 s each) in one output                                                                              |
| [`MAX_TEXT_FILE_BYTES`](_autosummary/annals.combine.html.md#annals.combine.MAX_TEXT_FILE_BYTES) | a text or html file larger than this is left out, and the others still go in                                                                         |
| [`MAX_HTML_DEPTH`](_autosummary/annals.combine.html.md#annals.combine.MAX_HTML_DEPTH)      | html nested deeper than this is flattened (very deep trees overflow the converters)                                                                  |
| [`MAX_SPAN`](_autosummary/annals.combine.html.md#annals.combine.MAX_SPAN)            | a table cell may span this many columns or rows (a bigger number is a layout attack)                                                                 |
| [`HTML_DEMOTE`](_autosummary/annals.combine.html.md#annals.combine.HTML_DEMOTE)         | headings of an embedded markdown or html file go this far down, under the section's own                                                              |
| [`REGISTRY`](_autosummary/annals.combine.html.md#annals.combine.REGISTRY)            | (kind, format) -> [`Pair`](_autosummary/annals.combine.html.md#annals.combine.Pair); add a pair with [`register()`](_autosummary/annals.combine.html.md#annals.combine.register) |
| [`HTML_CSP`](_autosummary/annals.combine.html.md#annals.combine.HTML_CSP)            | show itself, with its own styles and embedded images                                                                                                 |

### Functions

| [`combine`](_autosummary/annals.combine.html.md#annals.combine.combine)(sources[, fmt, title, demote, toc, ...])   | Every usable file of `sources` as one `fmt` ("md", "html" or "pdf") file.              |
|-----------------------------------------------------------------------------------------------------|----------------------------------------------------------------------------------------|
| [`explain`](_autosummary/annals.combine.html.md#annals.combine.explain)(fmt)                                       | One sentence on what a `fmt` output is made of (the 'supported' part of a message).    |
| [`html_body`](_autosummary/annals.combine.html.md#annals.combine.html_body)(text, \*[, rewrite_src, ...])            | The content of an html page as a safe fragment: its structure and words, nothing live. |
| [`items_of`](_autosummary/annals.combine.html.md#annals.combine.items_of)(sources, fmt)                             | The files to try for a `fmt` output, in the documents' order.                          |
| [`kinds_for`](_autosummary/annals.combine.html.md#annals.combine.kinds_for)(fmt)                                     | The kinds of file that can be put in a `fmt` output, in a stable order.                |
| [`register`](_autosummary/annals.combine.html.md#annals.combine.register)(kind, fmt, \*[, requires])                | Decorator: the function turns a file of `kind` into a part of the `fmt` output.        |
| [`skipped_header`](_autosummary/annals.combine.html.md#annals.combine.skipped_header)(skipped)                            | The skipped files as compact JSON for a response header: few, short, ascii.            |
| [`supported`](_autosummary/annals.combine.html.md#annals.combine.supported)()                                        | What can be made: `{format: {"label", "ext", "kinds"}}`, for a page or a message.      |

### Classes

| [`Combined`](_autosummary/annals.combine.html.md#annals.combine.Combined)(data, fmt, media_type, ext, sections)    | The result: the file's bytes, what it is, how many files went in and which did not.     |
|----------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------|
| [`Context`](_autosummary/annals.combine.html.md#annals.combine.Context)(fmt[, embedder])                          | What a converter may use besides the item: where images go, and the output's own needs. |
| [`Format`](_autosummary/annals.combine.html.md#annals.combine.Format)(name, label, ext, media_type, join[, ...]) | An output format: how it is named, joined, and whether each file gets its own context.  |
| [`Item`](_autosummary/annals.combine.html.md#annals.combine.Item)(source, rel, kind, label, title)             | One file to put in the output: a section, or a run of pages.                            |
| [`Job`](_autosummary/annals.combine.html.md#annals.combine.Job)(title, demote, embedder[, toc, unwrap])       | What a joiner needs besides the parts.                                                  |
| [`Pair`](_autosummary/annals.combine.html.md#annals.combine.Pair)(kind, fmt, fn[, requires])                   | One (kind, format) cell of the registry.                                                |
| [`Skipped`](_autosummary/annals.combine.html.md#annals.combine.Skipped)(label, reason)                            | A file left out, and why.                                                               |
| [`Source`](_autosummary/annals.combine.html.md#annals.combine.Source)(meta, files, read_text, open_path[, ...])  | One document, as a caller lets it be read: its files and how to get at them.            |

### Exceptions

| [`ConversionError`](_autosummary/annals.combine.html.md#annals.combine.ConversionError)   | One file could not be converted (damaged, protected, too large); the rest go on.   |
|--------------------------------------------------------------------|------------------------------------------------------------------------------------|
| [`NothingToCombine`](_autosummary/annals.combine.html.md#annals.combine.NothingToCombine)  | No file could be put in the output (the message says which kinds could).           |

### annals.combine.COMPANION_KINDS *= frozenset({'image', 'text'})*

kinds that illustrate or accompany a document with pages, so are not sections of its own

### *class* annals.combine.Combined(data, fmt, media_type, ext, sections, skipped=())

Bases: [`object`](https://docs.python.org/3/builtins/functions.html#object)

The result: the file’s bytes, what it is, how many files went in and which did not.

### *class* annals.combine.Context(fmt, embedder=Embedder())

Bases: [`object`](https://docs.python.org/3/builtins/functions.html#object)

What a converter may use besides the item: where images go, and the output’s own needs.

### *exception* annals.combine.ConversionError

Bases: [`ValueError`](https://docs.python.org/3/builtins/exceptions.html#ValueError)

One file could not be converted (damaged, protected, too large); the rest go on.

### *class* annals.combine.Format(name, label, ext, media_type, join, requires=(), context_per_item=False)

Bases: [`object`](https://docs.python.org/3/builtins/functions.html#object)

An output format: how it is named, joined, and whether each file gets its own context.

#### context_per_item *: [bool](https://docs.python.org/3/builtins/functions.html#bool)* *= False*

one context (images, budget) per file rather than one for the whole output

### annals.combine.HTML_CSP *= "default-src 'none'; img-src data:; style-src 'unsafe-inline'"*

show itself, with its own styles and embedded images

* **Type:**
  what a combined html page may do

### annals.combine.HTML_DEMOTE *= 2*

headings of an embedded markdown or html file go this far down, under the section’s own

### *class* annals.combine.Item(source, rel, kind, label, title)

Bases: [`object`](https://docs.python.org/3/builtins/functions.html#object)

One file to put in the output: a section, or a run of pages.

### *class* annals.combine.Job(title, demote, embedder, toc=True, unwrap=True)

Bases: [`object`](https://docs.python.org/3/builtins/functions.html#object)

What a joiner needs besides the parts.

### annals.combine.MAX_HTML_DEPTH *= 100*

html nested deeper than this is flattened (very deep trees overflow the converters)

### annals.combine.MAX_RENDERED_FILES *= 60*

files made into PDF pages by rendering (about 0.4 s each) in one output

### annals.combine.MAX_SKIPPED_LISTED *= 4*

skipped files listed in a result (and its headers); the rest are counted

### annals.combine.MAX_SPAN *= 100*

a table cell may span this many columns or rows (a bigger number is a layout attack)

### annals.combine.MAX_TEXT_FILE_BYTES *= 2000000*

a text or html file larger than this is left out, and the others still go in

### annals.combine.MAX_TEXT_PAGES *= 300*

a PDF with more pages than this is not read for its text (about 0.2 s a page)

### *exception* annals.combine.NothingToCombine

Bases: [`ValueError`](https://docs.python.org/3/builtins/exceptions.html#ValueError)

No file could be put in the output (the message says which kinds could).

### annals.combine.PAGE_KINDS *= frozenset({'html', 'md', 'pdf'})*

kinds whose file is a document in itself

### *class* annals.combine.Pair(kind, fmt, fn, requires=())

Bases: [`object`](https://docs.python.org/3/builtins/functions.html#object)

One (kind, format) cell of the registry.

### annals.combine.REGISTRY *: [dict](https://docs.python.org/3/builtins/stdtypes.html#dict)[[tuple](https://docs.python.org/3/builtins/stdtypes.html#tuple)[[str](https://docs.python.org/3/builtins/stdtypes.html#str), [str](https://docs.python.org/3/builtins/stdtypes.html#str)], [Pair](_autosummary/annals.combine.html.md#annals.combine.Pair)]* *= {('html', 'html'): Pair(kind='html', fmt='html', fn=<function \_html_body_of>, requires=()), ('html', 'md'): Pair(kind='html', fmt='md', fn=<function \_html_to_md>, requires=('markdownify',)), ('html', 'pdf'): Pair(kind='html', fmt='pdf', fn=<function \_page_to_pdf.<locals>.convert>, requires=('weasyprint',)), ('image', 'html'): Pair(kind='image', fmt='html', fn=<function \_image_body>, requires=()), ('image', 'pdf'): Pair(kind='image', fmt='pdf', fn=<function \_page_to_pdf.<locals>.convert>, requires=('weasyprint',)), ('md', 'html'): Pair(kind='md', fmt='html', fn=<function \_md_body>, requires=('markdown_it',)), ('md', 'md'): Pair(kind='md', fmt='md', fn=<function \_md_to_md>, requires=()), ('md', 'pdf'): Pair(kind='md', fmt='pdf', fn=<function \_page_to_pdf.<locals>.convert>, requires=('markdown_it', 'weasyprint')), ('pdf', 'html'): Pair(kind='pdf', fmt='html', fn=<function \_pdf_body>, requires=('pdfdol', 'pypdf')), ('pdf', 'md'): Pair(kind='pdf', fmt='md', fn=<function \_pdf_to_md>, requires=('pdfdol', 'pypdf')), ('pdf', 'pdf'): Pair(kind='pdf', fmt='pdf', fn=<function \_pdf_to_pdf>, requires=('pypdf', 'pdfdol')), ('text', 'html'): Pair(kind='text', fmt='html', fn=<function \_text_body>, requires=()), ('text', 'md'): Pair(kind='text', fmt='md', fn=<function \_text_to_md>, requires=()), ('text', 'pdf'): Pair(kind='text', fmt='pdf', fn=<function \_page_to_pdf.<locals>.convert>, requires=('weasyprint',))}*

(kind, format) -> [`Pair`](_autosummary/annals.combine.html.md#annals.combine.Pair); add a pair with [`register()`](_autosummary/annals.combine.html.md#annals.combine.register)

### *class* annals.combine.Skipped(label, reason)

Bases: [`object`](https://docs.python.org/3/builtins/functions.html#object)

A file left out, and why.

### *class* annals.combine.Source(meta, files, read_text, open_path, file_url=<function Source.<lambda>>, read_bytes=None)

Bases: [`object`](https://docs.python.org/3/builtins/functions.html#object)

One document, as a caller lets it be read: its files and how to get at them.

`read_text(rel)` is the file’s text (a share gives the *filtered* text);
`open_path(rel)` its path on disk, for bytes. Either may raise `OSError` or
`KeyError` for a file that is gone, which leaves that file out.

#### read_bytes *: [Callable](https://docs.python.org/3/library/collections.abc.html#collections.abc.Callable)[[[str](https://docs.python.org/3/builtins/stdtypes.html#str)], [bytes](https://docs.python.org/3/builtins/stdtypes.html#bytes)] | [None](https://docs.python.org/3/builtins/constants.html#None)* *= None*

how bytes are read when not straight from `open_path` (a share filters svg text)

### annals.combine.combine(sources, fmt='md', \*, title='', demote=1, toc=True, unwrap=True, order=<function numbered_first>, max_text_bytes=8000000, max_input_bytes=120000000, registry=None)

Every usable file of `sources` as one `fmt` (“md”, “html” or “pdf”) file.

`sources` are the documents ([`Source`](_autosummary/annals.combine.html.md#annals.combine.Source)), in their order; files are arranged by
`order` ([`annals.aggregate.numbered_first()`](_autosummary/annals.aggregate.html.md#annals.aggregate.numbered_first): numbered names first, numerically;
`None` keeps the documents’ order). `demote` is how far an embedded markdown file’s
headings go down in a markdown output, which also takes `toc` (a table of contents)
and `unwrap` (join hard-wrapped lines). `max_text_bytes` caps all the text read
([`annals.aggregate.TooLarge`](_autosummary/annals.aggregate.html.md#annals.aggregate.TooLarge)), `max_input_bytes` all the files together.

A file with no converter, or that cannot be read, is left out and listed in
`Combined.skipped` with the reason. Raises [`NothingToCombine`](_autosummary/annals.combine.html.md#annals.combine.NothingToCombine) when nothing is
left, [`annals.requirements.MissingDependency`](_autosummary/annals.requirements.html.md#annals.requirements.MissingDependency) when a library the conversions need
is not installed (before any work), and `ValueError` for an unknown `fmt`.

* **Return type:**
  [`Combined`](_autosummary/annals.combine.html.md#annals.combine.Combined)

### annals.combine.explain(fmt)

One sentence on what a `fmt` output is made of (the ‘supported’ part of a message).

* **Return type:**
  [`str`](https://docs.python.org/3/builtins/stdtypes.html#str)

### annals.combine.html_body(text, \*, rewrite_src=<function <lambda>>, rewrite_href=None, demote=0)

The content of an html page as a safe fragment: its structure and words, nothing live.

Only a fixed set of tags survives, with a few plain attributes: no script, style, frame,
form, event handler, `class` or `id`; a link keeps only an `http(s)` or `mailto`
address, which `rewrite_href(href)`, when given, may change or refuse (`None`: the
link keeps its words, loses its address). `rewrite_src(src)` decides each image: the url to show it from, or `None`
for its alt text instead (an image is never loaded from where the page says). `demote`
pushes headings that many levels down. Unbalanced tags are closed, so a fragment can
never swallow what is joined after it.

```pycon
>>> html_body('<body><script>x()</script><h1 onclick="x()">Hi</h1><a href="javascript:x()">y</a></body>')
'<h1>Hi</h1><a>y</a>'
```

The Download PDF button annals put in the page ([`annals.pagepdf`](_autosummary/annals.pagepdf.html.md#module-annals.pagepdf)) is not content,
so it is left out too.

* **Return type:**
  [`str`](https://docs.python.org/3/builtins/stdtypes.html#str)

### annals.combine.items_of(sources, fmt)

The files to try for a `fmt` output, in the documents’ order.

A document with pages (markdown, html, PDF) contributes those; its images and text
files are its own parts. A document with none contributes whatever it holds, so what
cannot be used (a video) is reported and not silently missing. A folder, or a document
with several such files, names each by its title then the file (`Report/01-intro.md`).

* **Return type:**
  [`Iterator`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Iterator)[[`Item`](_autosummary/annals.combine.html.md#annals.combine.Item)]

### annals.combine.kinds_for(fmt)

The kinds of file that can be put in a `fmt` output, in a stable order.

* **Return type:**
  [`tuple`](https://docs.python.org/3/builtins/stdtypes.html#tuple)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`...`](https://docs.python.org/3/builtins/constants.html#Ellipsis)]

### annals.combine.register(kind, fmt, , requires=())

Decorator: the function turns a file of `kind` into a part of the `fmt` output.

`requires` are the (importable) modules it needs, checked before any work starts.

* **Return type:**
  [`Callable`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Callable)[[[`Callable`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Callable)[[[`Item`](_autosummary/annals.combine.html.md#annals.combine.Item), [`Context`](_autosummary/annals.combine.html.md#annals.combine.Context)], [`str`](https://docs.python.org/3/builtins/stdtypes.html#str) | [`bytes`](https://docs.python.org/3/builtins/stdtypes.html#bytes)]], [`Callable`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Callable)[[[`Item`](_autosummary/annals.combine.html.md#annals.combine.Item), [`Context`](_autosummary/annals.combine.html.md#annals.combine.Context)], [`str`](https://docs.python.org/3/builtins/stdtypes.html#str) | [`bytes`](https://docs.python.org/3/builtins/stdtypes.html#bytes)]]

### annals.combine.skipped_header(skipped)

The skipped files as compact JSON for a response header: few, short, ascii.

At most [`MAX_SKIPPED_LISTED`](_autosummary/annals.combine.html.md#annals.combine.MAX_SKIPPED_LISTED) are listed (the count says how many there were) and
names and reasons are cut, so the header stays far under what a proxy accepts.

* **Return type:**
  [`str`](https://docs.python.org/3/builtins/stdtypes.html#str)

### annals.combine.supported()

What can be made: `{format: {"label", "ext", "kinds"}}`, for a page or a message.

* **Return type:**
  [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)]


# _autosummary/annals.config.html.md

# annals.config

Settings: where documents are published and what link to print.

Two values matter to a publisher:

* `target`: where the documents go. A directory (`~/.local/share/annals`) or an ssh
  destination (`tw:/root/.local/share/annals`). This is the data root the annals server
  reads, locally or on another machine.
* `base_url`: the public root of the annals app, so a publish can print the link the owner
  opens (`https://apps.example.com/annals`).
* `share_base_url`: where the public share server answers, so `annals share` prints the
  link a recipient opens (`<share_base_url>/<token>/`). It defaults to
  `<base_url>/shared`, which is where `annals serve` mounts it; a platform that runs the
  share server as its own public app sets it (`ANNALS_SHARE_BASE_URL` or the config file).

Resolution order, highest first: explicit keyword arguments, environment variables
(`ANNALS_TARGET`, `ANNALS_BASE_URL`), the config file (`$ANNALS_CONFIG` or
`$XDG_CONFIG_HOME/annals/config.toml`, default `~/.config/annals/config.toml`), then the
local defaults (publish into the local data dir, link to a local `annals serve`).

Named targets (`--to NAME`): a second place to publish, opted into per command. The config
file holds them as `[targets.NAME]` tables with the same two keys; `annals configure --to
NAME --target ... --base-url ...` writes one. `to` picks it over the environment and the
file’s default, and explicit `target`/`base_url` arguments still win over `to`.

A third, `outbox`, is true for a target another machine pulls and empties (the server
fetches documents from it rather than being written to): a replacement published there
travels as it is and is applied where it lands (see [`annals.store`](_autosummary/annals.store.html.md#module-annals.store)). `ANNALS_OUTBOX`
overrides it.

A fourth, `room`, is true for a target an outside audience reads (a client’s room, served
with `mk_api(room=True)`): `publish` and `copy` to it write no provenance (the
publisher’s host, cwd, session and `--meta` keys), so it never reaches that disk.

A link names its own place. [`link_target()`](_autosummary/annals.config.html.md#annals.config.link_target) reads the instance out of a document’s or
group’s link by matching it against every configured `base_url` (the default’s and each
named target’s), so `annals aggregate <link>` reads the right annals without `--to`. The
config file stays the one list of the annals this machine can read. [`link_target()`](_autosummary/annals.config.html.md#annals.config.link_target)
itself refuses a link to any other host; the read commands then fall back to the default
annals (ids are unique across annals, so that read finds the document or says there is none).

The server side has two knobs of its own. `ANNALS_DATA_DIR` is the directory the API
reads. It defaults to `~/.local/share/annals`, which is also the default publish target,
so with no configuration at all `annals publish` and `annals serve` meet in the same
place. `ANNALS_SOURCES` names extra folders the page lists beside the published documents,
read in place (`ledgers=~/.local/share/crowsnest/ledger`; several, comma-separated).

### Module Attributes

| [`ENV_SHARE_BASE_URL`](_autosummary/annals.config.html.md#annals.config.ENV_SHARE_BASE_URL)   | where the public share server answers (a share link is `<this>/<token>/`)   |
|-----------------------------------------------------------------------|-----------------------------------------------------------------------------|
| [`ENV_SOURCES`](_autosummary/annals.config.html.md#annals.config.ENV_SOURCES)          | "name=path, name2=path2"                                                    |

### Functions

| [`default_config_path`](_autosummary/annals.config.html.md#annals.config.default_config_path)()                          | `$ANNALS_CONFIG`, else `$XDG_CONFIG_HOME/annals/config.toml`.                                        |
|-------------------------------------------------------------------------------------------------|------------------------------------------------------------------------------------------------------|
| [`default_data_dir`](_autosummary/annals.config.html.md#annals.config.default_data_dir)()                             | The local data root: `$ANNALS_DATA_DIR` or `~/.local/share/annals`.                                  |
| [`link_target`](_autosummary/annals.config.html.md#annals.config.link_target)(ref, \*[, config_path])            | The configured place a document's or group's link lives in: `None` (the default) or a target's name. |
| [`load_settings`](_autosummary/annals.config.html.md#annals.config.load_settings)(\*[, target, base_url, to, ...]) | Resolve settings: arguments, then `to`, env, the config file, then local defaults.                   |
| [`named_targets`](_autosummary/annals.config.html.md#annals.config.named_targets)(\*[, config_path])               | The `[targets.NAME]` tables of the config file: name -> {target, base_url}.                          |
| [`write_config`](_autosummary/annals.config.html.md#annals.config.write_config)(settings, \*[, to, config_path])  | Write the config file (string keys only; no TOML writer dependency needed).                          |

### Classes

| [`Settings`](_autosummary/annals.config.html.md#annals.config.Settings)(target, base_url[, configured, ...])   | Where to publish and what link to print.   |
|--------------------------------------------------------------------------------------------------|--------------------------------------------|

### annals.config.ENV_SHARE_BASE_URL *= 'ANNALS_SHARE_BASE_URL'*

where the public share server answers (a share link is `<this>/<token>/`)

### annals.config.ENV_SOURCES *= 'ANNALS_SOURCES'*

“name=path, name2=path2”

* **Type:**
  extra folders the page lists beside the published documents

### *class* annals.config.Settings(target, base_url, configured=True, outbox=False, share_base_url='', room=False)

Bases: [`object`](https://docs.python.org/3/builtins/functions.html#object)

Where to publish and what link to print. See the module docstring for precedence.

#### as_dict()

Plain dict, for the CLI and MCP surfaces.

* **Return type:**
  [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)

#### configured *: [bool](https://docs.python.org/3/builtins/functions.html#bool)* *= True*

publishing then lands
in the local data dir and the link points at a local server, which is rarely meant

* **Type:**
  False when nothing (argument, env, config file) named a target

#### outbox *: [bool](https://docs.python.org/3/builtins/functions.html#bool)* *= False*

the target is pulled and emptied by another machine; replacements apply there

#### room *: [bool](https://docs.python.org/3/builtins/functions.html#bool)* *= False*

what is written to it carries no provenance

* **Type:**
  an outside audience reads this target

#### share_base_url *: [str](https://docs.python.org/3/builtins/stdtypes.html#str)* *= ''*

where share links point (`<this>/<token>/`); `<base_url>/shared` by default

### annals.config.default_config_path()

`$ANNALS_CONFIG`, else `$XDG_CONFIG_HOME/annals/config.toml`.

* **Return type:**
  [`Path`](https://docs.python.org/3/library/pathlib.html#pathlib.Path)

### annals.config.default_data_dir()

The local data root: `$ANNALS_DATA_DIR` or `~/.local/share/annals`.

* **Return type:**
  [`Path`](https://docs.python.org/3/library/pathlib.html#pathlib.Path)

### annals.config.link_target(ref, , config_path=None)

The configured place a document’s or group’s link lives in: `None` (the default) or a target’s name.

`ref` that is not an http(s) link (a bare id) names no place, so the answer is
`None`: read the default. A link is matched against the default `base_url` and
every `[targets.NAME]` one; the longest matching `base_url` wins, and among equals
a readable target beats an outbox (an outbox is written to, never read). Hosts and
paths are compared as a browser reaches them (`_url_key()`). A link that matches
none raises `ValueError` naming the places this machine knows.

```pycon
>>> import tempfile, pathlib
>>> cfg = pathlib.Path(tempfile.mkdtemp()) / "config.toml"
>>> _ = cfg.write_text('''[annals]
... target = "/srv/annals"
... base_url = "https://apps.example.com/annals"
... [targets.team]
... target = "team:/var/lib/annals"
... base_url = "https://annals.team.example.org/annals"
... ''')
>>> link_target("https://annals.team.example.org/annals/d/20261119-075018-a-4a58", config_path=cfg)
'team'
>>> link_target("https://APPS.example.com/annals/g/20261119-075018-b?f=x", config_path=cfg) is None
True
>>> link_target("20261119-075018-a-4a58", config_path=cfg) is None
True
```

* **Return type:**
  [`str`](https://docs.python.org/3/builtins/stdtypes.html#str) | [`None`](https://docs.python.org/3/builtins/constants.html#None)

### annals.config.load_settings(, target=None, base_url=None, to=None, outbox=None, share_base_url=None, room=None, config_path=None)

Resolve settings: arguments, then `to`, env, the config file, then local defaults.

`to` names a `[targets.NAME]` table of the config file; it replaces the environment
and the file’s default target for this call (explicit arguments still win).

* **Return type:**
  [`Settings`](_autosummary/annals.config.html.md#annals.config.Settings)

### annals.config.named_targets(, config_path=None)

The `[targets.NAME]` tables of the config file: name -> {target, base_url}.

* **Return type:**
  [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`str`](https://docs.python.org/3/builtins/stdtypes.html#str)]]

### annals.config.write_config(settings, , to=None, config_path=None)

Write the config file (string keys only; no TOML writer dependency needed).

With `to`, `settings` is saved as the named target `[targets.<to>]` and the
default section is left as it was; without it the default section is replaced. Either
way the other tables are kept.

* **Return type:**
  [`Path`](https://docs.python.org/3/library/pathlib.html#pathlib.Path)


# _autosummary/annals.docfilter.html.md

# annals.docfilter

Exact filters over a document’s meta, for a caller that polls: since, session, tag, source.

One place for the rules, so the CLI (`annals ls`), MCP and the HTTP `/docs` route cannot
drift: `since` is an ISO date or time (local time unless it has an offset) or an age
(`6h`, `2d`); `session`, `tag` and each `source` key match whole values, never
substrings; all given filters must hold. They are pure: the caller lists the documents (and
puts the owner’s tags in, [`annals.catalog.with_owner_tags()`](_autosummary/annals.catalog.html.md#annals.catalog.with_owner_tags)) and this narrows them.

```pycon
>>> docs = [{"id": "a", "tags": ["x"], "created": "2026-11-12T10:00:00+00:00", "source": {"session": "s1"}},
...         {"id": "b", "tags": ["y"], "created": "2026-11-10T10:00:00+00:00", "source": {"session": "s2"}}]
>>> [d["id"] for d in DocFilter.of(since="2026-11-11T00:00:00+00:00").apply(docs)]
['a']
>>> [d["id"] for d in DocFilter.of(session="s2", tag="y").apply(docs)]
['b']
```

### Module Attributes

| [`RESERVED_META`](_autosummary/annals.docfilter.html.md#annals.docfilter.RESERVED_META)   | provenance annals fills in itself; `--meta` cannot overwrite it   |
|------------------------------------------------------------------|-------------------------------------------------------------------|

### Functions

| [`changed_at`](_autosummary/annals.docfilter.html.md#annals.docfilter.changed_at)(meta)                 | When a document last changed: a replaced one counts from its newest version.                       |
|-----------------------------------------------------------------------------------|----------------------------------------------------------------------------------------------------|
| [`parse_iso`](_autosummary/annals.docfilter.html.md#annals.docfilter.parse_iso)(text)                  | An ISO date or time as an aware datetime; one with no offset is local time.                        |
| [`parse_meta`](_autosummary/annals.docfilter.html.md#annals.docfilter.parse_meta)(meta, \*[, reserved]) | `["corpus=x", "issue=12"]` (or one such string) as `{"corpus": "x", "issue": "12"}`.               |
| [`parse_since`](_autosummary/annals.docfilter.html.md#annals.docfilter.parse_since)(since, \*[, now])    | A moment, as an aware datetime: an ISO date or time (local time when it has no offset), or an age. |

### Classes

| [`DocFilter`](_autosummary/annals.docfilter.html.md#annals.docfilter.DocFilter)([since, session, tag, source])   | What a caller wants of a listing: any of since, session, tag and source keys; empty means all.   |
|---------------------------------------------------------------------------------------------|--------------------------------------------------------------------------------------------------|

### *class* annals.docfilter.DocFilter(since=None, session=None, tag=None, source=dict())

Bases: [`object`](https://docs.python.org/3/builtins/functions.html#object)

What a caller wants of a listing: any of since, session, tag and source keys; empty means all.

#### apply(docs)

The documents that pass, in their order.

* **Return type:**
  [`list`](https://docs.python.org/3/builtins/stdtypes.html#list)[[`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)]

#### matches(doc)

Whether `doc` (a meta) passes every filter that was given.

* **Return type:**
  [`bool`](https://docs.python.org/3/builtins/functions.html#bool)

#### *classmethod* of(, since=None, session=None, tag=None, meta=None)

From the CLI’s spelling: `since` text, `meta` as `key=value` strings.

* **Return type:**
  [`DocFilter`](_autosummary/annals.docfilter.html.md#annals.docfilter.DocFilter)

### annals.docfilter.RESERVED_META *= frozenset({'cwd', 'host', 'session', 'session_url'})*

provenance annals fills in itself; `--meta` cannot overwrite it

### annals.docfilter.changed_at(meta)

When a document last changed: a replaced one counts from its newest version.

* **Return type:**
  [`datetime`](https://docs.python.org/3/library/datetime.html#datetime.datetime) | [`None`](https://docs.python.org/3/builtins/constants.html#None)

### annals.docfilter.parse_iso(text)

An ISO date or time as an aware datetime; one with no offset is local time.

* **Return type:**
  [`datetime`](https://docs.python.org/3/library/datetime.html#datetime.datetime)

### annals.docfilter.parse_meta(meta, , reserved=frozenset({'cwd', 'host', 'session', 'session_url'}))

`["corpus=x", "issue=12"]` (or one such string) as `{"corpus": "x", "issue": "12"}`.

A key in `reserved` (what annals records itself) is refused: writing it would forge
provenance. A filter reads any key, so it passes `reserved=frozenset()`.

```pycon
>>> parse_meta(["corpus=annals", "issue=64"])
{'corpus': 'annals', 'issue': '64'}
>>> parse_meta(None)
{}
>>> parse_meta("oops")
Traceback (most recent call last):
...
ValueError: --meta takes key=value (for example corpus=annals), got 'oops'
>>> parse_meta(["host=h"])
Traceback (most recent call last):
...
ValueError: --meta cannot set 'host': annals records it (use --session for the session)
```

* **Return type:**
  [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`str`](https://docs.python.org/3/builtins/stdtypes.html#str)]

### annals.docfilter.parse_since(since, , now=None)

A moment, as an aware datetime: an ISO date or time (local time when it has no offset), or an age.

```pycon
>>> parse_since("2026-11-12T09:00+00:00").isoformat()
'2026-11-12T09:00:00+00:00'
>>> parse_since("2d", now=datetime(2026, 11, 14, tzinfo=timezone.utc)).date().isoformat()
'2026-11-12'
```

* **Return type:**
  [`datetime`](https://docs.python.org/3/library/datetime.html#datetime.datetime)


# _autosummary/annals.highlights.html.md

# annals.highlights

Each reader’s highlights: passages of documents kept with a name, tags and a note.

A reader selects text on a document’s page and keeps it. The page side is the
[manicules](https://github.com/thorwhalen/manicules) widget (vendored under
`ui/vendor/manicules/`); this module is the server side it talks to: what a highlight is
allowed to be, where each reader’s are kept, and how they are searched. A highlight of a
document’s whole title keeps the document itself, which is how a reader marks a favourite.

A highlight, as stored (the shape of manicules’ `highlight.schema.json`):

```default
{"id": "hmf3k2x9a1b2c3", "name": "Bread notes-highlight-1",
 "target": {"source": {"id": "<doc id>", "title": "Bread notes", "url": "d/<doc id>"},
            "part": "body",
            "quote": {"exact": "85 percent water", "prefix": "A rye loaf takes ", "suffix": ", and"},
            "position": {"start": 310, "end": 327}},
 "comment": "the number I keep forgetting", "tags": ["rye"], "color": "green",
 "created": "2026-11-27T10:00:00+00:00"}
```

The target is two W3C Web Annotation selectors (the quote with its context, and where it
was): the page finds the passage again from them after the document changed. `whole` in a
target means the entire part, whatever it says now. The server never interprets a target;
it bounds its size and keeps it.

Records live under the data root, one JSON file per reader
(`highlights/<reader>.json`, `{id: highlight}`, the layout manicules’ own file store and
CLI use), through [`annals.jsonstore.JsonFileStore`](_autosummary/annals.jsonstore.html.md#annals.jsonstore.JsonFileStore); each reader’s two settings (the
default colour, and whether a page shows all its highlights when it opens) are beside them
(`highlight-settings/<reader>.json`). [`for_reader()`](_autosummary/annals.highlights.html.md#annals.highlights.for_reader) is the seam: any
`(reader) -> ReaderHighlights` callable can replace it (`mk_api(highlights=...)`), its
records being anything with the three calls of [`Records`](_autosummary/annals.highlights.html.md#annals.highlights.Records). The routes the widget
talks to are `annals.highlights_api.mk_router()`.

```pycon
>>> rec = clean({"target": {"source": {"id": "d1", "title": "Notes"}, "quote": {"exact": "three sites"}}},
...             names=["Notes-highlight-1"], now="2026-11-27T10:00:00+00:00", new_id=lambda: "h1")
>>> rec["name"], rec["target"]["part"], rec["tags"], rec["comment"]
('Notes-highlight-2', 'body', [], '')
>>> [h["id"] for h in search({"h1": rec}, "SITES notes")]
['h1']
>>> search({"h1": rec}, "sites absent")
[]
>>> clean_patch({"comment": "why", "color": None, "tags": ["b", "A", "a"]})
{'comment': 'why', 'color': None, 'tags': ['A', 'b']}
```

### Module Attributes

| [`ENV_READER`](_autosummary/annals.highlights.html.md#annals.highlights.ENV_READER)       | the reader an agent surface (the CLI, the MCP server) answers for when none is named     |
|-------------------------------------------------------------------|------------------------------------------------------------------------------------------|
| [`PALETTE`](_autosummary/annals.highlights.html.md#annals.highlights.PALETTE)          | the colours a highlight may have (manicules' palette; each is legible in light and dark) |
| [`DEFAULT_SETTINGS`](_autosummary/annals.highlights.html.md#annals.highlights.DEFAULT_SETTINGS) | what a reader gets before choosing anything                                              |
| [`MAX_HIGHLIGHTS`](_autosummary/annals.highlights.html.md#annals.highlights.MAX_HIGHLIGHTS)   | the file is read whole on every page                                                     |
| [`MAX_STORE_BYTES`](_autosummary/annals.highlights.html.md#annals.highlights.MAX_STORE_BYTES)  | every list, search and page view reads it whole                                          |
| [`RESERVED_IDS`](_autosummary/annals.highlights.html.md#annals.highlights.RESERVED_IDS)     | ids the API's own routes use (`/highlights/settings`)                                    |
| [`PATCHABLE`](_autosummary/annals.highlights.html.md#annals.highlights.PATCHABLE)        | the fields a reader may change afterwards; the target never changes                      |

### Functions

| [`add`](_autosummary/annals.highlights.html.md#annals.highlights.add)(records, data)                    | Keep a new highlight.                                                                                                       |
|----------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------------------------------------|
| [`apply_patch`](_autosummary/annals.highlights.html.md#annals.highlights.apply_patch)(record, patch, \*[, now]) | `record` with a cleaned patch applied; a `None` colour goes back to the default.                                            |
| [`clean`](_autosummary/annals.highlights.html.md#annals.highlights.clean)(data, \*[, names, now, new_id]) | A complete highlight from what a caller sent, validated and bounded.                                                        |
| [`clean_patch`](_autosummary/annals.highlights.html.md#annals.highlights.clean_patch)(patch)                    | What a reader may change ([`PATCHABLE`](_autosummary/annals.highlights.html.md#annals.highlights.PATCHABLE)), validated; anything else is refused. |
| [`clean_settings`](_autosummary/annals.highlights.html.md#annals.highlights.clean_settings)(patch)                 | The settings a reader may set, validated: `color` and `showOthers`.                                                         |
| [`clean_target`](_autosummary/annals.highlights.html.md#annals.highlights.clean_target)(target)                  | A target as stored: its source, its part, and the selectors, each bounded.                                                  |
| [`default_name`](_autosummary/annals.highlights.html.md#annals.highlights.default_name)(title[, names])          | `<title>-highlight-<n>`, `n` the first number no highlight of that page uses.                                               |
| [`edit`](_autosummary/annals.highlights.html.md#annals.highlights.edit)(records, hid, patch)             | Change a highlight's name, note, tags or colour.                                                                            |
| [`for_reader`](_autosummary/annals.highlights.html.md#annals.highlights.for_reader)(root)                      | The default seam: `<root>/highlights/<reader>.json` and `highlight-settings/`.                                              |
| [`href`](_autosummary/annals.highlights.html.md#annals.highlights.href)(record)                          | A highlight's page, opened on it, relative to the page's base (`""` when it names none).                                    |
| [`new_id`](_autosummary/annals.highlights.html.md#annals.highlights.new_id)()                              | A new id: sortable by creation time, unique enough for one reader's collection.                                             |
| [`read_records`](_autosummary/annals.highlights.html.md#annals.highlights.read_records)(target, reader)          | One reader's highlights by id, read through a `Target` (a local folder, or over ssh): for a caller that only reads.         |
| [`readers`](_autosummary/annals.highlights.html.md#annals.highlights.readers)(target)                       | Who has highlights under a data root, read through its `Target` (so over ssh too).                                          |
| [`remove`](_autosummary/annals.highlights.html.md#annals.highlights.remove)(records, hid)                  | Delete a highlight and return it.                                                                                           |
| [`search`](_autosummary/annals.highlights.html.md#annals.highlights.search)(records[, q, source, tag])     | The highlights matching every word of `q` (case ignored), newest first.                                                     |
| [`search_text`](_autosummary/annals.highlights.html.md#annals.highlights.search_text)(record)                   | What a highlight is found by: its name, passage, note, tags and its page's title.                                           |
| [`settings_of`](_autosummary/annals.highlights.html.md#annals.highlights.settings_of)(store)                    | A reader's settings over the defaults (a stored value of the wrong kind is ignored).                                        |

### Classes

| [`HighlightStore`](_autosummary/annals.highlights.html.md#annals.highlights.HighlightStore)(path)                | One reader's highlights: `{id: highlight}` in one JSON file.                                                                                                                                        |
|--------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| [`ReaderHighlights`](_autosummary/annals.highlights.html.md#annals.highlights.ReaderHighlights)(records, settings) | What the API keeps for one reader: the highlights ([`Records`](_autosummary/annals.highlights.html.md#annals.highlights.Records)), and the settings beside them (a mapping of setting name to value, with `snapshot()`). |
| [`Records`](_autosummary/annals.highlights.html.md#annals.highlights.Records)(\*args, \*\*kwargs)         | One reader's highlights, as this module and the API use them: any store with these three calls can stand behind the seam (a table in a database as well as a file).                                 |
| [`SettingsStore`](_autosummary/annals.highlights.html.md#annals.highlights.SettingsStore)(path)                 | One reader's settings: `{setting: value}` in one JSON file.                                                                                                                                         |

### annals.highlights.DEFAULT_SETTINGS *= {'color': 'yellow', 'showOthers': True}*

what a reader gets before choosing anything

### annals.highlights.ENV_READER *= 'ANNALS_HIGHLIGHTS_READER'*

the reader an agent surface (the CLI, the MCP server) answers for when none is named

### *class* annals.highlights.HighlightStore(path)

Bases: [`JsonFileStore`](_autosummary/annals.jsonstore.html.md#annals.jsonstore.JsonFileStore)

One reader’s highlights: `{id: highlight}` in one JSON file.

#### has_room()

Whether another highlight may be added: the file is read whole on every page,
so it is bounded in bytes ([`MAX_STORE_BYTES`](_autosummary/annals.highlights.html.md#annals.highlights.MAX_STORE_BYTES)) as well as in number.

* **Return type:**
  [`bool`](https://docs.python.org/3/builtins/functions.html#bool)

#### valid(value)

Whether a value read from the file is kept (an invalid one is logged and skipped).

* **Return type:**
  [`bool`](https://docs.python.org/3/builtins/functions.html#bool)

### annals.highlights.MAX_HIGHLIGHTS *= 5000*

the file is read whole on every page

* **Type:**
  at most this many highlights per reader

### annals.highlights.MAX_STORE_BYTES *= 20000000*

every list, search and page view reads it whole

* **Type:**
  and their file at most this big

### annals.highlights.PALETTE *= ('yellow', 'green', 'blue', 'pink', 'orange', 'purple')*

the colours a highlight may have (manicules’ palette; each is legible in light and dark)

### annals.highlights.PATCHABLE *= ('name', 'comment', 'tags', 'color')*

the fields a reader may change afterwards; the target never changes

### annals.highlights.RESERVED_IDS *= frozenset({'settings'})*

ids the API’s own routes use (`/highlights/settings`)

### *class* annals.highlights.ReaderHighlights(records, settings)

Bases: [`object`](https://docs.python.org/3/builtins/functions.html#object)

What the API keeps for one reader: the highlights ([`Records`](_autosummary/annals.highlights.html.md#annals.highlights.Records)), and the
settings beside them (a mapping of setting name to value, with `snapshot()`).

### *class* annals.highlights.Records(\*args, \*\*kwargs)

Bases: [`Protocol`](https://docs.python.org/3/library/typing.html#typing.Protocol)

One reader’s highlights, as this module and the API use them: any store with these
three calls can stand behind the seam (a table in a database as well as a file).

#### modify(key, change)

Set `key` to `change(current or None)` atomically (`None` deletes it).

* **Return type:**
  [`Any`](https://docs.python.org/3/library/typing.html#typing.Any)

### *class* annals.highlights.SettingsStore(path)

Bases: [`JsonFileStore`](_autosummary/annals.jsonstore.html.md#annals.jsonstore.JsonFileStore)

One reader’s settings: `{setting: value}` in one JSON file.

#### valid(value)

Whether a value read from the file is kept (an invalid one is logged and skipped).

* **Return type:**
  [`bool`](https://docs.python.org/3/builtins/functions.html#bool)

### annals.highlights.add(records, data)

Keep a new highlight. Raises `ValueError` when it is invalid, when its id is taken,
or when the reader already has [`MAX_HIGHLIGHTS`](_autosummary/annals.highlights.html.md#annals.highlights.MAX_HIGHLIGHTS).

* **Return type:**
  [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)

### annals.highlights.apply_patch(record, patch, , now=None)

`record` with a cleaned patch applied; a `None` colour goes back to the default.

* **Return type:**
  [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)

### annals.highlights.clean(data, \*, names=(), now=None, new_id=<function new_id>)

A complete highlight from what a caller sent, validated and bounded.

`names` are the names of the page’s other highlights, for the default name. An `id`
or `created` the caller sent is kept when well formed (the page makes the id, so an
undo puts back the very same highlight); unknown fields are dropped.

* **Return type:**
  [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)

### annals.highlights.clean_patch(patch)

What a reader may change ([`PATCHABLE`](_autosummary/annals.highlights.html.md#annals.highlights.PATCHABLE)), validated; anything else is refused.

* **Return type:**
  [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)

### annals.highlights.clean_settings(patch)

The settings a reader may set, validated: `color` and `showOthers`.

* **Return type:**
  [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)

### annals.highlights.clean_target(target)

A target as stored: its source, its part, and the selectors, each bounded.

Raises `ValueError` for a target with no source id, with neither a quote nor
`whole`, or with a field of the wrong kind or size.

* **Return type:**
  [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)

### annals.highlights.default_name(title, names=())

`<title>-highlight-<n>`, `n` the first number no highlight of that page uses.

```pycon
>>> default_name("Notes", ["a", "Notes-highlight-3"])
'Notes-highlight-4'
>>> default_name("  ")
'page-highlight-1'
```

* **Return type:**
  [`str`](https://docs.python.org/3/builtins/stdtypes.html#str)

### annals.highlights.edit(records, hid, patch)

Change a highlight’s name, note, tags or colour. `KeyError` when there is none.

* **Return type:**
  [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)

### annals.highlights.for_reader(root)

The default seam: `<root>/highlights/<reader>.json` and `highlight-settings/`.

* **Return type:**
  [`Callable`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Callable)[[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str)], [`ReaderHighlights`](_autosummary/annals.highlights.html.md#annals.highlights.ReaderHighlights)]

### annals.highlights.href(record)

A highlight’s page, opened on it, relative to the page’s base (`""` when it names none).

The one place that address is built: the API’s `href`, the CLI’s `url` and the page
all come from here.

```pycon
>>> href({"id": "h1", "target": {"source": {"id": "d1", "url": "d/d1?f=a.md"}}})
'd/d1?f=a.md&h=h1'
```

* **Return type:**
  [`str`](https://docs.python.org/3/builtins/stdtypes.html#str)

### annals.highlights.new_id()

A new id: sortable by creation time, unique enough for one reader’s collection.

* **Return type:**
  [`str`](https://docs.python.org/3/builtins/stdtypes.html#str)

### annals.highlights.read_records(target, reader)

One reader’s highlights by id, read through a `Target` (a local folder, or over
ssh): for a caller that only reads. The one other place that knows the file layout is
[`for_reader()`](_autosummary/annals.highlights.html.md#annals.highlights.for_reader).

* **Return type:**
  [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)]

### annals.highlights.readers(target)

Who has highlights under a data root, read through its `Target` (so over ssh too).

* **Return type:**
  [`list`](https://docs.python.org/3/builtins/stdtypes.html#list)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str)]

### annals.highlights.remove(records, hid)

Delete a highlight and return it. `KeyError` when there is none.

* **Return type:**
  [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)

### annals.highlights.search(records, q='', , source=None, tag=None)

The highlights matching every word of `q` (case ignored), newest first.

`source` keeps one page’s (its source id), `tag` the ones carrying a tag. This is
the function a wider search calls to list a reader’s highlights beside documents.

* **Return type:**
  [`list`](https://docs.python.org/3/builtins/stdtypes.html#list)[[`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)]

### annals.highlights.search_text(record)

What a highlight is found by: its name, passage, note, tags and its page’s title.

* **Return type:**
  [`str`](https://docs.python.org/3/builtins/stdtypes.html#str)

### annals.highlights.settings_of(store)

A reader’s settings over the defaults (a stored value of the wrong kind is ignored).

* **Return type:**
  [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)


# _autosummary/annals.html.md

# annals

annals: an in-tray for AI agents. Publish documents and media to a private page; get a link.

Agents call [`annals.tools.publish()`](_autosummary/annals.tools.html.md#annals.tools.publish) (or `annals publish file.md` from a shell) and hand
the printed URL to their human, who opens it on a phone. The documents are plain files in a
directory, local or on another machine over ssh; `annals.api.mk_app()` serves that
directory as a private page with search, sort, groups and a recycle bin.

### Functions

| [`configure`](_autosummary/annals.html.md#annals.configure)(\*[, target, base_url, to, outbox, ...])   | Write the publisher config (where to publish, what link to print) and show it.                                                                                    |
|-------------------------------------------------------------------------------------------------------|-------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| [`group`](_autosummary/annals.html.md#annals.group)(title, doc_ids, \*[, add_to, target, ...])     | Make a group (one URL for a set of documents) from existing document ids.                                                                                         |
| [`groups`](_autosummary/annals.html.md#annals.groups)(\*[, target, base_url, to])                   | List groups, newest first.                                                                                                                                        |
| [`load_settings`](_autosummary/annals.html.md#annals.load_settings)(\*[, target, base_url, to, ...])       | Resolve settings: arguments, then `to`, env, the config file, then local defaults.                                                                                |
| [`ls`](_autosummary/annals.html.md#annals.ls)([q, trash, limit, target, base_url, to, ...])     | List documents (newest first), optionally filtered by words or showing the bin.                                                                                   |
| [`parse_target`](_autosummary/annals.html.md#annals.parse_target)(spec)                                   | `host:/path` becomes an [`SshTarget`](_autosummary/annals.html.md#annals.SshTarget); anything else a [`LocalTarget`](_autosummary/annals.html.md#annals.LocalTarget). |
| [`publish`](_autosummary/annals.html.md#annals.publish)(paths, \*[, title, tags, group, ...])        | Publish one document and print its link; several paths become several documents.                                                                                  |
| [`restore`](_autosummary/annals.html.md#annals.restore)(doc_ids, \*[, target, to])                   | Bring documents back from the recycle bin.                                                                                                                        |
| [`show`](_autosummary/annals.html.md#annals.show)(doc_id, \*[, target, base_url, to])             | A document's metadata, link, the groups it is in, and the annals links in its text.                                                                               |
| [`trash`](_autosummary/annals.html.md#annals.trash)(doc_ids, \*[, target, to])                     | Move documents to the recycle bin (restorable).                                                                                                                   |

### Classes

| [`DocStore`](_autosummary/annals.html.md#annals.DocStore)(target, \*[, settle])                | Publish, list, read, trash, restore and group documents on a `Target`.      |
|------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------|
| [`LocalTarget`](_autosummary/annals.html.md#annals.LocalTarget)(root)                             | A directory on this machine.                                                |
| [`Settings`](_autosummary/annals.html.md#annals.Settings)(target, base_url[, configured, ...]) | Where to publish and what link to print.                                    |
| [`SshTarget`](_autosummary/annals.html.md#annals.SshTarget)(host, root)                         | `host:path` on another machine, via the system ssh and rsync in batch mode. |

### *class* annals.DocStore(target, , settle=True)

Bases: [`object`](https://docs.python.org/3/builtins/functions.html#object)

Publish, list, read, trash, restore and group documents on a `Target`.

#### add_to_group(gid, doc_ids)

Append documents to an existing group, keeping order and skipping ones it has.

Each document must exist and not be in the bin; `KeyError` for a group that is not
there.

* **Return type:**
  [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)

#### doc_rel(doc_id)

The directory of a document (or of a version, `<id>@<n>`) under the data root.

* **Return type:**
  [`str`](https://docs.python.org/3/builtins/stdtypes.html#str)

#### group(gid)

One group, by id.

* **Return type:**
  [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)

#### group_docs(gid)

A group and the meta of each of its documents, in its order (missing or binned ones left out).

* **Return type:**
  [`tuple`](https://docs.python.org/3/builtins/stdtypes.html#tuple)[[`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict), [`list`](_autosummary/annals.html.md#annals.DocStore.list)[[`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)]]

#### groups_of(doc_id)

The groups a document is in, newest first, each as `{"id", "title", "n"}`.

* **Return type:**
  [`list`](_autosummary/annals.html.md#annals.DocStore.list)[[`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)]

#### holds(ref_id)

Whether a document (or a version of one) or a group with this id is here, in the bin or not.

* **Return type:**
  [`bool`](https://docs.python.org/3/builtins/functions.html#bool)

#### list(, trash=False)

Every document’s meta, last changed first (`updated`, else `created`).

Pending replacements are applied first (when this store settles). One whose
document is not here is listed under its own id, so it is never out of sight.

* **Return type:**
  [`list`](_autosummary/annals.html.md#annals.DocStore.list)[[`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)]

#### list_groups()

Every group, newest first.

* **Return type:**
  [`list`](_autosummary/annals.html.md#annals.DocStore.list)[[`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)]

#### make_group(title, doc_ids, , gid=None, live_only=True)

Create (or overwrite) a group: a titled, ordered list of documents.

The title is cleaned (control characters dropped, whitespace collapsed, at most
`MAX_GROUP_TITLE` long, not blank); repeats are dropped, keeping the first; each
document must exist and not be in the bin unless `live_only=False` (a bundle that
keeps a document later binned). `ValueError` says which rule failed. An explicit
`gid` rewrites that group, under its lock.

* **Return type:**
  [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)

#### meta(doc_id, , settle=True)

One document’s meta; `in_trash` says which side of the bin it is on.

`<id>@<n>` is version `n`: its own meta, with `version_of` naming the document.
A pending replacement, read by its own id, says `pending`. `settle=False`
skips applying pending replacements (for a hot path such as a raw file).

* **Return type:**
  [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)

#### pending(doc_id=None, , names=None)

Pending replacements (directory names), oldest first; of one document if given.

`names`: the listing of `docs/` when the caller already has it.

* **Return type:**
  [`list`](_autosummary/annals.html.md#annals.DocStore.list)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str)]

#### publish(\*sources, title=None, tags=(), source=None, text=None, filename='document.md', exclude=('.\*', '_\_pycache_\_', '\*.pyc', '\*.pyo'), replace=None, artifact=None, pdf=True, pdf_renderer='default')

Publish files (or a directory, or `text`) as ONE document; return its meta.

One markdown or html file is the common case. A directory is published whole, with
`index.html` (or the first renderable file) as the page shown. `text` publishes a
string as `filename` instead of reading sources. `exclude` lists glob patterns
skipped inside a directory (hidden files and caches by default; `()` keeps all).

`replace` (a document id) publishes a new version of that document instead of a
new document: same id, same link, the current files kept as a version. It is
written as a pending replacement and applied at once when this store settles
(otherwise where the store is read). The returned meta says `pending` until then.

`artifact` (a claude.ai artifact link, see `check_artifact_url()`) is the
interactive version of the page: the document’s page links out to it. A
replacement that names none keeps the document’s current one.

An html page gets its own Download PDF button, and `<stem>.pdf` printed beside
it by `pdf_renderer` unless it has one ([`annals.pagepdf`](_autosummary/annals.pagepdf.html.md#module-annals.pagepdf), which says how a
page declares or opts out). `pdf=False` leaves the page as it is.

* **Return type:**
  [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)

#### purge(doc_id)

Delete a document that is in the bin. Refuses one that is not.

* **Return type:**
  [`None`](https://docs.python.org/3/builtins/constants.html#None)

#### read_text(doc_id, rel=None)

A document’s main file (or one of its files) as text.

* **Return type:**
  [`str`](https://docs.python.org/3/builtins/stdtypes.html#str)

#### rename(doc_id, title)

Give a document a title of the owner’s choosing; a later version keeps it.

The title is cleaned as a group’s is (`clean_title()`). A version or a pending
replacement is refused (rename the document). Works in the bin too. Only `title`
and `renamed` change in the stored meta, which is read again under the document’s
lock: a document that moved meanwhile (trashed, restored, purged) is a
`RuntimeError`, never a meta written where its files are not. Returns its meta.

* **Return type:**
  [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)

#### rename_group(gid, title)

Give a group a new title (cleaned as at creation); its documents stay as they are.

* **Return type:**
  [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)

#### restore(doc_id)

Move a document out of the bin (idempotent).

* **Return type:**
  [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)

#### search(query, , trash=False)

Case-insensitive match of every query word against title, tags, excerpt, source.

* **Return type:**
  [`list`](_autosummary/annals.html.md#annals.DocStore.list)[[`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)]

#### settle(doc_id=None)

Apply pending replacements (of one document, or all); return the ids replaced.

A replacement whose document is not here yet (it is still on its way, or the
document was purged) stays pending and is listed under its own id.

* **Return type:**
  [`list`](_autosummary/annals.html.md#annals.DocStore.list)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str)]

#### trash(doc_id)

Move a document into the bin (idempotent).

* **Return type:**
  [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)

#### versions(doc_id)

Every version of a document, oldest first, the current one last.

* **Return type:**
  [`list`](_autosummary/annals.html.md#annals.DocStore.list)[[`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)]

### *class* annals.LocalTarget(root)

Bases: [`object`](https://docs.python.org/3/builtins/functions.html#object)

A directory on this machine.

`read_metas()` keeps each meta it parsed, keyed by its file’s inode, mtime, ctime
and size (every write replaces the file, so a new inode), and resolves the root once
per listing, not twice per file: listing a thousand documents costs a `stat` per
document, not a parse. It hands back copies, so a caller may change what it gets.

#### local_path(rel)

`rel` under the root, resolved; `None` if it escapes the root (a symlink).

* **Return type:**
  [`Path`](https://docs.python.org/3/library/pathlib.html#pathlib.Path) | [`None`](https://docs.python.org/3/builtins/constants.html#None)

### *class* annals.Settings(target, base_url, configured=True, outbox=False, share_base_url='', room=False)

Bases: [`object`](https://docs.python.org/3/builtins/functions.html#object)

Where to publish and what link to print. See the module docstring for precedence.

#### as_dict()

Plain dict, for the CLI and MCP surfaces.

* **Return type:**
  [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)

#### configured *: [bool](https://docs.python.org/3/builtins/functions.html#bool)* *= True*

publishing then lands
in the local data dir and the link points at a local server, which is rarely meant

* **Type:**
  False when nothing (argument, env, config file) named a target

#### outbox *: [bool](https://docs.python.org/3/builtins/functions.html#bool)* *= False*

the target is pulled and emptied by another machine; replacements apply there

#### room *: [bool](https://docs.python.org/3/builtins/functions.html#bool)* *= False*

what is written to it carries no provenance

* **Type:**
  an outside audience reads this target

#### share_base_url *: [str](https://docs.python.org/3/builtins/stdtypes.html#str)* *= ''*

where share links point (`<this>/<token>/`); `<base_url>/shared` by default

### *class* annals.SshTarget(host, root)

Bases: [`object`](https://docs.python.org/3/builtins/functions.html#object)

`host:path` on another machine, via the system ssh and rsync in batch mode.

### annals.configure(, target=None, base_url=None, to=None, outbox=False, share_base_url=None, room=False)

Write the publisher config (where to publish, what link to print) and show it.

### Example

`annals configure --target tw:/root/.local/share/annals --base-url https://apps.example.com/annals`.
`--to NAME` saves the target and base url as a named target (`annals publish --to NAME`)
and leaves the default alone. `--outbox` marks the target as an outbox: a directory
the server pulls and empties (it cannot be written to from here), so replacements are
left for the server to apply; it is kept by later changes (`ANNALS_OUTBOX=0` or an
edit of the file turns it off). `--share-base-url` is where share links point when
the share server is not at `<base-url>/shared` (a platform running it as its own
public app). `--room` marks a target an outside audience reads (a client’s room): what
is published or copied to it carries no provenance; kept by later changes, like
`--outbox`. With no arguments, shows the resolved settings without writing.

* **Return type:**
  [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)

### annals.group(title, doc_ids, , add_to=None, target=None, base_url=None, to=None)

Make a group (one URL for a set of documents) from existing document ids.

With `add_to` (a group id) the documents are added to that group instead, and `title`
is ignored. The documents must exist and not be in the bin; the title is cleaned (see
[`annals.store.clean_title()`](_autosummary/annals.store.html.md#annals.store.clean_title)).

* **Return type:**
  [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)

### annals.groups(, target=None, base_url=None, to=None)

List groups, newest first.

* **Return type:**
  [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)

### annals.load_settings(, target=None, base_url=None, to=None, outbox=None, share_base_url=None, room=None, config_path=None)

Resolve settings: arguments, then `to`, env, the config file, then local defaults.

`to` names a `[targets.NAME]` table of the config file; it replaces the environment
and the file’s default target for this call (explicit arguments still win).

* **Return type:**
  [`Settings`](_autosummary/annals.config.html.md#annals.config.Settings)

### annals.ls(q='', , trash=False, limit=50, target=None, base_url=None, to=None, since=None, session=None, tag=None, meta=None)

List documents (newest first), optionally filtered by words or showing the bin.

`to` lists a named target instead of the default one. The rest are exact filters,
all of which must hold, for tools that poll: `since` (an ISO date or time, or an age
like `6h` or `2d`: published or replaced at or after it), `session` (the publishing session’s
name, whole, case-sensitive), `tag` (one tag, whole: the owner’s own tags, set by `annals tag`, win over the publisher’s) and `meta` (`key=value`,
several allowed, against the document’s `source`: `corpus=annals`). A row is
`{id, title, kind, tags, created, updated, source, url}`; with `--json` that is the contract
(`misc/docs/design.md`), and `total` counts the matches before `limit`.

* **Return type:**
  [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)

### annals.parse_target(spec)

`host:/path` becomes an [`SshTarget`](_autosummary/annals.html.md#annals.SshTarget); anything else a [`LocalTarget`](_autosummary/annals.html.md#annals.LocalTarget).

* **Return type:**
  [`Target`](_autosummary/annals.target.html.md#annals.target.Target)

### annals.publish(paths, , title=None, tags='', group=None, add_to=None, session=None, session_url=None, all_files=False, target=None, base_url=None, to=None, replace=None, artifact=None, no_link_check=False, no_pdf=False, meta=None, upsert=None)

Publish one document and print its link; several paths become several documents.

An audio or video file takes its timed text along as one document: `talk.mp3
talk.vtt talk.chapters.vtt` (or `talk.cues.json`) is one audio document whose page
shows the transcript and chapters (`annals.store.SIDECAR_SUFFIXES`).

`paths`: files of any kind (markdown, html, images, video, audio, pdf, text), a
directory (one document: an `index.html` or single page with its assets, else a
gallery of everything in it), or `-` for stdin (markdown). `tags` is comma separated. `group`
names a group to create from the published documents; the reply then carries
`group_url` too. `add_to` appends them to an existing group instead (its id, as
printed in a group link), so a second batch lands under the link the owner already has. `session` records who published (the source shown on the page), and `session_url`
the claude.ai link that opens that session; by default the link of the Claude Code session
this runs in (`CLAUDE_CODE_BRIDGE_SESSION_ID`), `none` for no link. The document’s page
shows each session that made it, linked, under its title; a share or a room never does
([`annals.sessions`](_autosummary/annals.sessions.html.md#module-annals.sessions)). A directory skips
hidden files and caches (`.*`, `__pycache__`, `*.pyc`) unless `all_files`.
`to` publishes to a named target of the config file (`[targets.NAME]`, see
`annals configure --to`) instead of the default one. `replace` (a document’s link or
id) publishes ONE path as a new version of that document: the link stays the same, the
page shows the new version and offers the earlier ones. That is how a living page (a
guide, a status page) keeps one link. `artifact` (a claude.ai artifact link) is the
interactive version of the page: the document’s page shows an “Open the interactive
version” button. Publish the Artifact first, then the same page here with its link.
A markdown or text document that mentions an issue or a Slack/email/chat message
without linking to it gets a warning on stderr ([`annals.linkcheck`](_autosummary/annals.linkcheck.html.md#module-annals.linkcheck)); it is
published either way. `no_link_check` turns that check off.

An html page gets its own Download PDF button, inside the page, so it survives “open
full page”, raw links and shares, and `<stem>.pdf` printed beside it (headless
Chromium, the `pdf` extra; without it the button opens the print dialog). A page that
already has its PDF says so with `<link rel="alternate" type="application/pdf"
href="...">`; one with its own button marks it `data-annals-pdf`; `no_pdf` (or
`data-annals-pdf="off"` on `<html>`/`<body>`) leaves the page as it is
([`annals.pagepdf`](_autosummary/annals.pagepdf.html.md#module-annals.pagepdf)).

`meta` (`--meta key=value`, one flag per pair: `--meta corpus=x --meta issue=3`) records what the document belongs to, next
to `host`, `cwd` and `session` in its `source`: by convention `corpus` (the
repository or body of work), `repo`, `issue` (the issue it answers), `item` (a
desk item) and `kind` (report, brief, overview, render); other keys are kept as given.
`ls --session/--meta` finds them again. The CLI’s `--json` prints the result below
(`id`, `title`, `url`, and with a group `group_id` and `group_url`; several
paths give `docs`) as JSON and nothing else on stdout; that shape is a contract
(`misc/docs/design.md`).

`upsert` (`--upsert key=value`) makes the call idempotent for a living document
keyed by a meta value: it publishes ONE path as a new version of the newest live
document whose `source.<key>` equals the value (as `replace` would), or creates
one with that `key=value` in its `source` when there is none. The reply then says
`"created": true` or `false`, and `group` / `add_to` apply only when the
document is new. It takes the place of `replace`; not together.

* **Return type:**
  [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)

### annals.restore(doc_ids, , target=None, to=None)

Bring documents back from the recycle bin.

* **Return type:**
  [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)

### annals.show(doc_id, , target=None, base_url=None, to=None)

A document’s metadata, link, the groups it is in, and the annals links in its text.

`doc_id` may be the document’s link, on any annals this machine is configured for: the
link finds its own place (`to` names one explicitly). A group’s link gives the group
and its documents’ links. `links` are the links to other annals documents and groups
found in the document’s text files, on any annals this machine can read: follow them
with `annals show` or `annals aggregate`. To read the text, use `annals aggregate <link>`.

* **Return type:**
  [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)

### annals.trash(doc_ids, , target=None, to=None)

Move documents to the recycle bin (restorable).

* **Return type:**
  [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)

### Modules

| [`aggregate`](_autosummary/annals.aggregate.html.md#module-annals.aggregate)       | Many markdown files as ONE markdown document: a title, a table of contents, a section per file.                                                    |
|------------------------------------------------------------------------------------------|----------------------------------------------------------------------------------------------------------------------------------------------------|
| [`auth`](_autosummary/annals.auth.html.md#module-annals.auth)                 | The auth seam: who may read the annals.                                                                                                            |
| [`bulk`](_autosummary/annals.bulk.html.md#module-annals.bulk)                 | Bulk actions: one action over a selection of items, in one request.                                                                                |
| [`catalog`](_autosummary/annals.catalog.html.md#module-annals.catalog)           | The catalog: every source's items as one list, with search and the owner's tags.                                                                   |
| [`combine`](_autosummary/annals.combine.html.md#module-annals.combine)           | Many files of many kinds as ONE document: a Markdown, html or PDF file.                                                                            |
| [`config`](_autosummary/annals.config.html.md#module-annals.config)             | Settings: where documents are published and what link to print.                                                                                    |
| [`docfilter`](_autosummary/annals.docfilter.html.md#module-annals.docfilter)       | Exact filters over a document's meta, for a caller that polls: since, session, tag, source.                                                        |
| [`highlights`](_autosummary/annals.highlights.html.md#module-annals.highlights)     | Each reader's highlights: passages of documents kept with a name, tags and a note.                                                                 |
| [`jsonstore`](_autosummary/annals.jsonstore.html.md#module-annals.jsonstore)       | A `MutableMapping` kept in one JSON file, safe with several server processes.                                                                      |
| [`linkcheck`](_autosummary/annals.linkcheck.html.md#module-annals.linkcheck)       | Find what a document mentions without linking to it: the owner reads on a phone and clicks through.                                                |
| [`listening`](_autosummary/annals.listening.html.md#module-annals.listening)       | What each reader has heard of each audio document: percent heard, listens, where they stopped.                                                     |
| [`mcp`](_autosummary/annals.mcp.html.md#module-annals.mcp)                   | MCP surface: the same operations as the CLI, from [`annals.tools`](_autosummary/annals.tools.html.md#module-annals.tools), via `py2mcp`. |
| [`media`](_autosummary/annals.media.html.md#module-annals.media)               | The media relay for published html pages: what a framed page plays, told to the page around it.                                                    |
| [`notebook`](_autosummary/annals.notebook.html.md#module-annals.notebook)         | A share's documents as separate notebook sources: one plain web page per text file.                                                                |
| [`originals`](_autosummary/annals.originals.html.md#module-annals.originals)       | Originals: a pick's files, exactly as published, as one streamed `.zip`.                                                                           |
| [`overview`](_autosummary/annals.overview.html.md#module-annals.overview)         | Spoken overviews of a document: the request a page makes, and the worker that fulfils it.                                                          |
| [`pagepdf`](_autosummary/annals.pagepdf.html.md#module-annals.pagepdf)           | Every published html page carries its own Download PDF button, and the PDF beside it.                                                              |
| [`prefs`](_autosummary/annals.prefs.html.md#module-annals.prefs)               | Each reader's page preferences: a few named sections of JSON, kept on the server.                                                                  |
| [`records`](_autosummary/annals.records.html.md#module-annals.records)           | The published documents as records for a retrieval index, so an agent can find one by meaning.                                                     |
| [`references`](_autosummary/annals.references.html.md#module-annals.references)     | The references of documents, extracted and combined, in three forms.                                                                               |
| [`render`](_autosummary/annals.render.html.md#module-annals.render)             | Render markdown (and other page-like files) to html and PDF, with their images inside.                                                             |
| [`requirements`](_autosummary/annals.requirements.html.md#module-annals.requirements) | Optional dependencies, checked where they are needed and explained when they are missing.                                                          |
| [`search`](_autosummary/annals.search.html.md#module-annals.search)             | How the catalog answers a query: the search strategies.                                                                                            |
| [`sessions`](_autosummary/annals.sessions.html.md#module-annals.sessions)         | The sessions that made a document: each one's name and the link that opens it.                                                                     |
| [`share`](_autosummary/annals.share.html.md#module-annals.share)               | Share links: one document (or a group) behind a public, unguessable, revocable link.                                                               |
| [`share_page`](_autosummary/annals.share_page.html.md#module-annals.share_page)     | A share link's page with its text in it, and no script, so every reader can read it.                                                               |
| [`sources`](_autosummary/annals.sources.html.md#module-annals.sources)           | Item sources: everything the page lists, wherever it lives, as rows of one shape.                                                                  |
| [`store`](_autosummary/annals.store.html.md#module-annals.store)               | The document store: a flat set of documents, tags, groups and a recycle bin, as plain files.                                                       |
| [`tables`](_autosummary/annals.tables.html.md#module-annals.tables)             | Scrolling, zooming tables for published html pages.                                                                                                |
| [`tags`](_autosummary/annals.tags.html.md#module-annals.tags)                 | The owner's tags: a `MutableMapping` from item key to tag list, kept apart from the items.                                                         |
| [`target`](_autosummary/annals.target.html.md#module-annals.target)             | The transport seam: a document tree lands in a directory, here or on another machine.                                                              |
| [`titles`](_autosummary/annals.titles.html.md#module-annals.titles)             | A title for a file whose name says nothing: `overview.mp3`, `output.html`, `index.md`.                                                             |
| [`tokens`](_autosummary/annals.tokens.html.md#module-annals.tokens)             | Read tokens: a credential for an agent that cannot reach the store (a cloud session).                                                              |
| [`tools`](_autosummary/annals.tools.html.md#module-annals.tools)               | The operations, as plain functions: JSON-able arguments in, JSON-able dicts out.                                                                   |


# _autosummary/annals.jsonstore.html.md

# annals.jsonstore

A `MutableMapping` kept in one JSON file, safe with several server processes.

The owner’s tags ([`annals.tags`](_autosummary/annals.tags.html.md#module-annals.tags)) and each reader’s listening progress
([`annals.listening`](_autosummary/annals.listening.html.md#module-annals.listening)) are small, server-side records that the page changes one entry at
a time. [`JsonFileStore`](_autosummary/annals.jsonstore.html.md#annals.jsonstore.JsonFileStore) is that one mechanism: a JSON object in a file, written
atomically under an exclusive `flock`, re-read whenever another process changed it, and
never broken by a damaged file (it reads as empty and is kept aside at the next write).

A subclass says what a valid value is ([`JsonFileStore.valid()`](_autosummary/annals.jsonstore.html.md#annals.jsonstore.JsonFileStore.valid)) and how a value is
cleaned before it is stored ([`JsonFileStore.clean()`](_autosummary/annals.jsonstore.html.md#annals.jsonstore.JsonFileStore.clean)). [`JsonFileStore.modify()`](_autosummary/annals.jsonstore.html.md#annals.jsonstore.JsonFileStore.modify)
changes one entry from its current value under the lock, so two devices reporting at once
never lose each other’s change.

```pycon
>>> import tempfile, pathlib
>>> s = JsonFileStore(pathlib.Path(tempfile.mkdtemp()) / "x.json")
>>> s["a"] = {"n": 1}
>>> s.modify("a", lambda v: {"n": (v or {}).get("n", 0) + 1})
{'n': 2}
>>> dict(s)
{'a': {'n': 2}}
```

### Module Attributes

| [`DAMAGED_SUFFIX`](_autosummary/annals.jsonstore.html.md#annals.jsonstore.DAMAGED_SUFFIX)   | the suffix a damaged file is kept under, so a hand edit gone wrong can be recovered   |
|-------------------------------------------------------------------|---------------------------------------------------------------------------------------|

### Classes

| [`JsonFileStore`](_autosummary/annals.jsonstore.html.md#annals.jsonstore.JsonFileStore)(path)   | `{key: value}` in one JSON file, re-read when another process changed it.   |
|------------------------------------------------------------------------|-----------------------------------------------------------------------------|

### annals.jsonstore.DAMAGED_SUFFIX *= '.damaged'*

the suffix a damaged file is kept under, so a hand edit gone wrong can be recovered

### *class* annals.jsonstore.JsonFileStore(path)

Bases: [`MutableMapping`](https://docs.python.org/3/library/collections.abc.html#collections.abc.MutableMapping)

`{key: value}` in one JSON file, re-read when another process changed it.

A write takes an exclusive `flock` on `<file>.lock`, re-reads the file, changes it
and replaces it atomically. A read re-reads the file whenever its inode, size or mtime
changed (every write makes a new inode). `label` names the store in log messages.

#### clean(value)

The value as stored; raise `ValueError` to refuse it.

* **Return type:**
  [`Any`](https://docs.python.org/3/library/typing.html#typing.Any)

#### modify(key, change)

Set `key` to `change(current value or None)`, atomically; returns the stored value.

`change` returning `None` deletes the entry (and returns `None`).

* **Return type:**
  [`Any`](https://docs.python.org/3/library/typing.html#typing.Any)

#### modify_many(changes)

[`modify()`](_autosummary/annals.jsonstore.html.md#annals.jsonstore.JsonFileStore.modify) for several keys under one lock, one read and one write.

A change that raises leaves its key as it was (the error is its answer, under that
key); the others still apply. Answers `{key: stored value, None or the exception}`.
A batch of N edits costs one rewrite of the file, not N.

* **Return type:**
  [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`Any`](https://docs.python.org/3/library/typing.html#typing.Any)]

#### snapshot()

Every entry at once, under one read (what a listing overlays).

* **Return type:**
  [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`Any`](https://docs.python.org/3/library/typing.html#typing.Any)]

#### valid(value)

Whether a value read from the file is kept (an invalid one is logged and skipped).

* **Return type:**
  [`bool`](https://docs.python.org/3/builtins/functions.html#bool)


# _autosummary/annals.linkcheck.html.md

# annals.linkcheck

Find what a document mentions without linking to it: the owner reads on a phone and clicks through.

A published report says “Karl asked on 10-29 in #tech-app-test” or “see owner/repo#12”.
Without a link the reader has to go and find the message or the issue, often on a phone.
This module finds such mentions so `annals publish` can warn the author. It only warns
and never blocks: the author decides.

Two kinds, both in markdown or plain text (code spans and fenced blocks are ignored):

- `issue`: a GitHub-style reference, `owner/repo#12` or a bare `#12`, outside a link;
- `message`: a line that points at one message (a message, a thread, a DM, a reply, a
  post, someone who asked, said or wrote, or a `#channel`) tied to a date,
  and has no web address at all. A dated pointer to a conversation names one message, so it should be
  its permalink. Headings and date ranges (“2026-10-04 → 2026-11-07”) are periods, not
  messages, and are skipped.

```pycon
>>> doc = '''# Catch-up
... - Karl asked on 2026-10-29 in #tech-app-test what was missing.
... - Karl asked on [2026-10-29](https://x.slack.com/archives/C1/p1) in #tech-app-test.
... - Tracked in inoocq/meta#7 and #12.
... - Tracked in [inoocq/meta#7](https://github.com/inoocq/meta/issues/7).
... - Run `git log #3` here.
... ## Slack, 2026-10-04 → 2026-11-07
... - 574 messages from 2026-10-04 to 2026-11-07, Slack read by hand until 10-04.
... '''
>>> [(m.line, m.kind, m.ref) for m in unlinked_mentions(doc)]
[(2, 'message', 'Slack/chat message of 2026-10-29'), (4, 'issue', 'inoocq/meta#7'), (4, 'issue', '#12')]
```

Ordinary prose is not flagged: a colour, a date that is not tied to the conversation word, a
table row.

```pycon
>>> prose = '''A base surface of #121212 and #0b0b12.
... The composition review of 2026-11-12 [19] found that the owner's reply reaches an agent.
... | library | archived, last push 2026-09-18 | can post to a URL |
... Released 2026-05-01; its documentation said nothing about this.
... '''
>>> unlinked_mentions(prose)
[]
```

### Module Attributes

| [`URL`](_autosummary/annals.linkcheck.html.md#annals.linkcheck.URL)          | a web address anywhere on a line                                        |
|---------------------------------------------------------------|-------------------------------------------------------------------------|
| [`MD_LINK`](_autosummary/annals.linkcheck.html.md#annals.linkcheck.MD_LINK)      | a markdown link or image `[text](url)`, or an autolink `<url>`          |
| [`CODE_SPAN`](_autosummary/annals.linkcheck.html.md#annals.linkcheck.CODE_SPAN)    | an inline code span                                                     |
| [`ISSUE_REF`](_autosummary/annals.linkcheck.html.md#annals.linkcheck.ISSUE_REF)    | a GitHub-style issue or PR reference, qualified or bare.                |
| [`CONVERSATION`](_autosummary/annals.linkcheck.html.md#annals.linkcheck.CONVERSATION) | words that point at one message, and a #channel (letters, not a number) |
| [`DATE_RANGE`](_autosummary/annals.linkcheck.html.md#annals.linkcheck.DATE_RANGE)   | a period between two dates, which names no single message               |
| [`MAX_LISTED`](_autosummary/annals.linkcheck.html.md#annals.linkcheck.MAX_LISTED)   | how many mentions a warning lists before it says "and N more"           |

### Functions

| [`unlinked_mentions`](_autosummary/annals.linkcheck.html.md#annals.linkcheck.unlinked_mentions)(text)                  | Every issue reference and dated conversation mention in `text` that has no link.           |
|-------------------------------------------------------------------------------------------|--------------------------------------------------------------------------------------------|
| [`unlinked_warning`](_autosummary/annals.linkcheck.html.md#annals.linkcheck.unlinked_warning)(text, \*[, max_listed]) | A one-paragraph warning naming the unlinked mentions in `text`, or None if there are none. |

### Classes

| [`Mention`](_autosummary/annals.linkcheck.html.md#annals.linkcheck.Mention)(line, kind, ref)   | One unlinked mention: the 1-based `line`, its `kind` and the `ref` it names.   |
|-----------------------------------------------------------------------------|--------------------------------------------------------------------------------|

### annals.linkcheck.CODE_SPAN *= re.compile('\`[^\`]\*\`')*

an inline code span

### annals.linkcheck.CONVERSATION *= re.compile('\\\\b(?:message|thread|DM|e-?mail|reply|replied|post|posted|asked|said|wrote)\\\\b|(?<![\\\\w&/])#[a-z][\\\\w-]\*[a-z]\\\\b', re.IGNORECASE)*

words that point at one message, and a #channel (letters, not a number)

### annals.linkcheck.DATE_RANGE *= re.compile('(?<![\\\\d-])\\\\b(?:\\\\d{4}-)?(?:0[1-9]|1[0-2])-(?:0[1-9]|[12]\\\\d|3[01])\\\\b\\\\s\*(?:→|->|–|—|to|-)\\\\s\*(?<![\\\\d-])\\\\b(?:\\\\d{4}-)?(?:0[1-9]|1[0-2])-(?:0[1-9]|[12]\\\\d|3[01])\\\\b')*

a period between two dates, which names no single message

### annals.linkcheck.ISSUE_REF *= re.compile('(?<![\\\\w/&#])(?:[A-Za-z0-9][\\\\w.-]\*/[\\\\w.-]+#\\\\d+|#(?!\\\\d{6}\\\\b|\\\\d{8}\\\\b)\\\\d+)\\\\b')*

a GitHub-style issue or PR reference, qualified or bare. A bare `#` and six or eight
digits (`#121212`, `#12121280`) is a colour far more often than an issue

### annals.linkcheck.MAX_LISTED *= 5*

how many mentions a warning lists before it says “and N more”

### annals.linkcheck.MD_LINK *= re.compile('!?\\\\[[^\\\\]]\*\\\\]\\\\([^)]\*\\\\)|<https?://[^>]+>')*

a markdown link or image `[text](url)`, or an autolink `<url>`

### *class* annals.linkcheck.Mention(line, kind, ref)

Bases: [`object`](https://docs.python.org/3/builtins/functions.html#object)

One unlinked mention: the 1-based `line`, its `kind` and the `ref` it names.

### annals.linkcheck.URL *= re.compile('https?://\\\\S+')*

a web address anywhere on a line

### annals.linkcheck.unlinked_mentions(text)

Every issue reference and dated conversation mention in `text` that has no link.

* **Return type:**
  [`list`](https://docs.python.org/3/builtins/stdtypes.html#list)[[`Mention`](_autosummary/annals.linkcheck.html.md#annals.linkcheck.Mention)]

### annals.linkcheck.unlinked_warning(text, , max_listed=5)

A one-paragraph warning naming the unlinked mentions in `text`, or None if there are none.

```pycon
>>> print(unlinked_warning("Fixed in #4."))
1 mention without a link (the reader clicks through from a phone): line 1 #4. Link each one: an issue or PR to its GitHub URL, a Slack/email/chat message to its permalink.
>>> unlinked_warning("All linked: [#4](https://github.com/o/r/issues/4).") is None
True
```

* **Return type:**
  [`str`](https://docs.python.org/3/builtins/stdtypes.html#str) | [`None`](https://docs.python.org/3/builtins/constants.html#None)


# _autosummary/annals.listening.html.md

# annals.listening

What each reader has heard of each audio document: percent heard, listens, where they stopped.

The page reports what was played, a few seconds at a time, as spans of the audio’s own
timeline (`[[start, end], ...]` in seconds). The server keeps the **union** of those spans
per reader and document, so the percent heard counts each second once, however often it was
replayed or skipped back to, and two devices reporting the same minute add nothing twice.
A listen is counted when playback reaches the end of audio that has been heard almost
whole ([`DONE_SHARE`](_autosummary/annals.listening.html.md#annals.listening.DONE_SHARE)), so dragging to the end is not a listen; a report carries the
id of the play it belongs to, so a report sent twice (a retry, a page closing) counts one.

A record, per reader and document:

```default
{"heard": [[0.0, 61.5], [90.0, 120.0]], "duration": 300.0, "position": 120.0,
 "listens": 1, "done": true, "updated": "2026-11-09T10:00:00+00:00"}
```

`done` is the reader’s own mark (“I have heard this”), set or cleared from the page; it
is absent until they set it. [`status()`](_autosummary/annals.listening.html.md#annals.listening.status) reads a record as one of [`STATUSES`](_autosummary/annals.listening.html.md#annals.listening.STATUSES).

Records live under the data root, one JSON file per reader (`listening/<reader>.json`),
through [`annals.jsonstore.JsonFileStore`](_autosummary/annals.jsonstore.html.md#annals.jsonstore.JsonFileStore). [`for_reader()`](_autosummary/annals.listening.html.md#annals.listening.for_reader) is the seam: any
`(reader) -> store` callable whose stores are [`Records`](_autosummary/annals.listening.html.md#annals.listening.Records) can replace it
(`mk_api(listening=...)`).

```pycon
>>> merge_spans([[5, 10], [0, 3], [2, 6], [20, 20]])
[[0.0, 10.0]]
>>> rec = apply_report(None, {"spans": [[0, 30]], "duration": 100, "position": 30})
>>> percent(rec), status(rec)
(30, 'started')
>>> apply_report(None, {"spans": [[95, 100]], "duration": 100, "ended": "p0"})["listens"]  # dragged to the end
0
>>> rec = apply_report(rec, {"spans": [[30, 100]], "duration": 100, "position": 100, "ended": "p1"})
>>> rec = apply_report(rec, {"spans": [], "duration": 100, "position": 100, "ended": "p1"})
>>> percent(rec), rec["listens"], status(rec)
(100, 1, 'done')
```

### Module Attributes

| [`STATUSES`](_autosummary/annals.listening.html.md#annals.listening.STATUSES)         | what a record reads as, in the order the page offers them as filters               |
|-------------------------------------------------------------------|------------------------------------------------------------------------------------|
| [`DONE_SHARE`](_autosummary/annals.listening.html.md#annals.listening.DONE_SHARE)       | heard at least this share of the audio counts as done, without a listen to the end |
| [`MIN_STARTED_S`](_autosummary/annals.listening.html.md#annals.listening.MIN_STARTED_S)    | heard less than this many seconds is not started (a stray tap on play)             |
| [`MAX_SPANS`](_autosummary/annals.listening.html.md#annals.listening.MAX_SPANS)        | at most this many separate spans are kept; past it the closest ones are joined     |
| [`MAX_REPORT_SPANS`](_autosummary/annals.listening.html.md#annals.listening.MAX_REPORT_SPANS) | a report holds at most this many spans                                             |
| [`MAX_DURATION_S`](_autosummary/annals.listening.html.md#annals.listening.MAX_DURATION_S)   | longest audio a report may claim, in seconds (a sanity bound, not a feature limit) |
| [`RECENT_PLAYS`](_autosummary/annals.listening.html.md#annals.listening.RECENT_PLAYS)     | the plays that reached the end, remembered so a retried report counts none twice   |

### Functions

| [`apply_mark`](_autosummary/annals.listening.html.md#annals.listening.apply_mark)(record, done)            | `record` with the reader's own mark set (`True`/`False`) or cleared (`None`).       |
|--------------------------------------------------------------------------------------|-------------------------------------------------------------------------------------|
| [`apply_report`](_autosummary/annals.listening.html.md#annals.listening.apply_report)(record, report)        | `record` with a report from the page folded in.                                     |
| [`for_reader`](_autosummary/annals.listening.html.md#annals.listening.for_reader)(root)                    | The default seam: each reader's records in `<root>/listening/<reader>.json`.        |
| [`heard_seconds`](_autosummary/annals.listening.html.md#annals.listening.heard_seconds)(record)               | How many distinct seconds of the audio were heard.                                  |
| [`merge_spans`](_autosummary/annals.listening.html.md#annals.listening.merge_spans)(spans, \*[, max_spans]) | The union of `spans` as sorted, disjoint `[start, end]` pairs; empty spans dropped. |
| [`percent`](_autosummary/annals.listening.html.md#annals.listening.percent)(record)                     | The share of the audio heard, 0 to 100 (0 while the duration is unknown).           |
| [`reader_file`](_autosummary/annals.listening.html.md#annals.listening.reader_file)(reader)                 | The file name a reader's records are kept under: their identity, percent-encoded.   |
| [`status`](_autosummary/annals.listening.html.md#annals.listening.status)(record)                      | `done`, `started` or `not_started`; the reader's own mark wins when set.            |
| [`summary`](_autosummary/annals.listening.html.md#annals.listening.summary)(record)                     | A record as the page shows it: the record plus `percent` and `status`.              |

### Classes

| [`ListeningStore`](_autosummary/annals.listening.html.md#annals.listening.ListeningStore)(path)        | One reader's records: `{doc id: record}` in one JSON file.   |
|------------------------------------------------------------------------------|--------------------------------------------------------------|
| [`Records`](_autosummary/annals.listening.html.md#annals.listening.Records)(\*args, \*\*kwargs) | One reader's records, as the API uses them.                  |

### annals.listening.DONE_SHARE *= 0.95*

heard at least this share of the audio counts as done, without a listen to the end

### *class* annals.listening.ListeningStore(path)

Bases: [`JsonFileStore`](_autosummary/annals.jsonstore.html.md#annals.jsonstore.JsonFileStore)

One reader’s records: `{doc id: record}` in one JSON file.

#### valid(value)

Whether a value read from the file is kept (an invalid one is logged and skipped).

* **Return type:**
  [`bool`](https://docs.python.org/3/builtins/functions.html#bool)

### annals.listening.MAX_DURATION_S *= 86400*

longest audio a report may claim, in seconds (a sanity bound, not a feature limit)

### annals.listening.MAX_REPORT_SPANS *= 500*

a report holds at most this many spans

### annals.listening.MAX_SPANS *= 200*

at most this many separate spans are kept; past it the closest ones are joined

### annals.listening.MIN_STARTED_S *= 3.0*

heard less than this many seconds is not started (a stray tap on play)

### annals.listening.RECENT_PLAYS *= 20*

the plays that reached the end, remembered so a retried report counts none twice

### *class* annals.listening.Records(\*args, \*\*kwargs)

Bases: [`Protocol`](https://docs.python.org/3/library/typing.html#typing.Protocol)

One reader’s records, as the API uses them.

#### modify(key, change)

Set `key` to `change(current or None)` atomically (`None` deletes it).

* **Return type:**
  [`Any`](https://docs.python.org/3/library/typing.html#typing.Any)

### annals.listening.STATUSES *= ('not_started', 'started', 'done')*

what a record reads as, in the order the page offers them as filters

### annals.listening.apply_mark(record, done)

`record` with the reader’s own mark set (`True`/`False`) or cleared (`None`).

* **Return type:**
  [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict) | [`None`](https://docs.python.org/3/builtins/constants.html#None)

### annals.listening.apply_report(record, report)

`record` with a report from the page folded in. Raises `ValueError` on a bad report.

A report: `{"spans": [[a, b], ...], "duration": s, "position": s, "ended"?: play_id}`.
`ended` names the play that reached the end; each play id counts one listen.

* **Return type:**
  [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)

### annals.listening.for_reader(root)

The default seam: each reader’s records in `<root>/listening/<reader>.json`.

* **Return type:**
  [`Callable`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Callable)[[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str)], [`Records`](_autosummary/annals.listening.html.md#annals.listening.Records)]

### annals.listening.heard_seconds(record)

How many distinct seconds of the audio were heard.

* **Return type:**
  [`float`](https://docs.python.org/3/builtins/functions.html#float)

### annals.listening.merge_spans(spans, , max_spans=200)

The union of `spans` as sorted, disjoint `[start, end]` pairs; empty spans dropped.

Past `max_spans` pairs, the ones with the smallest gap between them are joined, so a
record stays small whatever a reader does (the percent heard can only grow by that).

* **Return type:**
  [`list`](https://docs.python.org/3/builtins/stdtypes.html#list)[[`list`](https://docs.python.org/3/builtins/stdtypes.html#list)[[`float`](https://docs.python.org/3/builtins/functions.html#float)]]

### annals.listening.percent(record)

The share of the audio heard, 0 to 100 (0 while the duration is unknown).

* **Return type:**
  [`int`](https://docs.python.org/3/builtins/functions.html#int)

### annals.listening.reader_file(reader)

The file name a reader’s records are kept under: their identity, percent-encoded.

The encoding is one-to-one, so two readers never share a file, and never a path.

* **Return type:**
  [`str`](https://docs.python.org/3/builtins/stdtypes.html#str)

### annals.listening.status(record)

`done`, `started` or `not_started`; the reader’s own mark wins when set.

* **Return type:**
  [`str`](https://docs.python.org/3/builtins/stdtypes.html#str)

### annals.listening.summary(record)

A record as the page shows it: the record plus `percent` and `status`.

* **Return type:**
  [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)


# _autosummary/annals.mcp.html.md

# annals.mcp

MCP surface: the same operations as the CLI, from [`annals.tools`](_autosummary/annals.tools.html.md#module-annals.tools), via `py2mcp`.

Run with `python -m annals.mcp` (needs `pip install 'annals[mcp]'`). String refs keep the
core free of any MCP import; the function list is the CLI’s (`annals.tools.EFFECTS` classifies
each operation), narrowed to the effects the host allows: by default read and write, not the
destructive `purge` or `listen`, which spends money.

### Module Attributes

| [`ENV_EFFECTS`](_autosummary/annals.mcp.html.md#annals.mcp.ENV_EFFECTS)   | the environment variable that widens (or narrows) what the server offers   |
|----------------------------------------------------------------|----------------------------------------------------------------------------|

### Functions

| [`mk_server`](_autosummary/annals.mcp.html.md#annals.mcp.mk_server)(\*[, effects])   | Build the MCP server over [`annals.tools`](_autosummary/annals.tools.html.md#module-annals.tools).   |
|-----------------------------------------------------------------------------|----------------------------------------------------------------------------------------------------------------|

### annals.mcp.ENV_EFFECTS *= 'ANNALS_MCP_EFFECTS'*

the environment variable that widens (or narrows) what the server offers

### annals.mcp.mk_server(, effects=None)

Build the MCP server over [`annals.tools`](_autosummary/annals.tools.html.md#module-annals.tools).

`effects` (default `read` and `write`, or the comma separated `ANNALS_MCP_EFFECTS`)
says which operations to serve; `destructive` adds `purge`, `spend` adds `listen`
(it costs money), `file` adds `aggregate --output`.


# _autosummary/annals.media.html.md

# annals.media

The media relay for published html pages: what a framed page plays, told to the page around it.

A spoken overview is an html page shown in a sandboxed frame, so the annals page cannot see
its audio. This adds one inlined script (the page’s own `ui/media-progress.js`) to any
html page that may play audio or video; the script posts what is played to the parent
page, which records what the reader heard ([`annals.listening`](_autosummary/annals.listening.html.md#module-annals.listening)), and takes a “start at”
from it. Opened on its own (no parent), the relay does nothing. Ahead of it goes the seek
guard (`ui/media-seek.js`, also loaded by the annals page itself): on an iPhone, a seek on a
paused element that has no data yet never lands and wedges every later seek, so the guard
holds such a seek until the element plays or its data arrives.

### Module Attributes

| [`SEEK_JS`](_autosummary/annals.media.html.md#annals.media.SEEK_JS)   | the seek guard, inlined first (shared pages too) so the relay's own seek and play go through it   |
|------------------------------------------------------------|---------------------------------------------------------------------------------------------------|

### Functions

| [`add_media_relay`](_autosummary/annals.media.html.md#annals.media.add_media_relay)(html, \*[, relay])   | `html` with the seek guard and the media relay injected, unless it plays nothing or opts out.                       |
|---------------------------------------------------------------------------------------|---------------------------------------------------------------------------------------------------------------------|
| [`media_version`](_autosummary/annals.media.html.md#annals.media.media_version)()                      | A short hash of what [`add_media_relay()`](_autosummary/annals.media.html.md#annals.media.add_media_relay) injects, for a page's ETag. |

### annals.media.SEEK_JS *= PosixPath('/home/runner/work/annals/annals/annals/data/ui/media-seek.js')*

the seek guard, inlined first (shared pages too) so the relay’s own seek and play go through it

### annals.media.add_media_relay(html, , relay=True)

`html` with the seek guard and the media relay injected, unless it plays nothing or
opts out. `relay=False` (a page nobody records, a share’s) injects the guard alone.

```pycon
>>> add_media_relay(b"<p>no media</p>") == b"<p>no media</p>"
True
>>> page = add_media_relay(b"<body><audio src=a.mp3></audio></body>")
>>> b'data-annals-media="seek"' in page and b'data-annals-media="1"' in page
True
>>> shared = add_media_relay(b"<body><audio src=a.mp3></audio></body>", relay=False)
>>> b'data-annals-media="seek"' in shared and b'data-annals-media="1"' not in shared
True
>>> add_media_relay(b"<p>an audio overview</p>") == b"<p>an audio overview</p>"
True
```

* **Return type:**
  [`bytes`](https://docs.python.org/3/builtins/stdtypes.html#bytes)

### annals.media.media_version()

A short hash of what [`add_media_relay()`](_autosummary/annals.media.html.md#annals.media.add_media_relay) injects, for a page’s ETag.

* **Return type:**
  [`str`](https://docs.python.org/3/builtins/stdtypes.html#str)


# _autosummary/annals.notebook.html.md

# annals.notebook

A share’s documents as separate notebook sources: one plain web page per text file.

A notebook product (NotebookLM, and Gemini’s notebooks, which share its sources) takes a
web page by its link, one source per link, and several links pasted at once; it reads
the page’s text and keeps its own copy. It does not unpack a zip, and its upload picker
needs the files on the device first. So the fewest taps from an iPad is: tick the
documents, copy one list of links, paste it into the notebook (see
`misc/docs/notebook-sources.md` for the research behind this).

The links are a share’s ([`annals.share`](_autosummary/annals.share.html.md#module-annals.share)): unguessable, scoped to the documents
ticked, expiring, revocable, and filtered like every shared text. This module only
decides what becomes a source and how one looks:

```default
GET <share link>/source/<doc id>/<file>   a script-free html page: <title>, the text
```

- [`source_files()`](_autosummary/annals.notebook.html.md#annals.notebook.source_files): which files of a document are sources (markdown and html pages,
  numbered files first, as [`annals.aggregate.numbered_first()`](_autosummary/annals.aggregate.html.md#annals.aggregate.numbered_first) orders them).
- [`notebook_sources()`](_autosummary/annals.notebook.html.md#annals.notebook.notebook_sources): the `{doc, file, title, url}` rows of a share, in its order.
- [`source_scope()`](_autosummary/annals.notebook.html.md#annals.notebook.source_scope): what a notebook share includes of a document: its source pages
  and the files they show, never the rest of a folder.
- [`render_source()`](_autosummary/annals.notebook.html.md#annals.notebook.render_source): one markdown file as its source page ([`render_source_body()`](_autosummary/annals.notebook.html.md#annals.notebook.render_source_body)
  is the page’s body alone, which the share page embeds), shared-text rules applied
  twice: to the text ([`annals.share.filter_refs()`](_autosummary/annals.share.html.md#annals.share.filter_refs)), then to every link and image of
  the rendered page ([`annals.share.ref_decider()`](_autosummary/annals.share.html.md#annals.share.ref_decider) over markdown-it’s tokens), and
  any annals id left in it removed. Cached, and rendered only up to
  [`RENDER_MAX_BYTES`](_autosummary/annals.notebook.html.md#annals.notebook.RENDER_MAX_BYTES) (a larger file is sent as escaped text): it is a public route.
- [`source_page()`](_autosummary/annals.notebook.html.md#annals.notebook.source_page): the page a notebook reads. Its `<title>` is the document’s title,
  which the notebook shows as the source’s name, so the sources can be told apart.
- [`markdown_html()`](_autosummary/annals.notebook.html.md#annals.notebook.markdown_html): markdown to html; `markdown-it-py` when installed (the
  `pdf` extra), else the text escaped in a `<pre>`, which a notebook reads as well.

### Module Attributes

| [`SOURCE_KINDS`](_autosummary/annals.notebook.html.md#annals.notebook.SOURCE_KINDS)      | the kinds of file a notebook can take from a link (images, audio, video and pdf it takes only as uploads)         |
|--------------------------------------------------------------------|-------------------------------------------------------------------------------------------------------------------|
| [`SOURCE_SEGMENT`](_autosummary/annals.notebook.html.md#annals.notebook.SOURCE_SEGMENT)    | the path segment of a source page under a share link                                                              |
| [`SOURCE_CSS`](_autosummary/annals.notebook.html.md#annals.notebook.SOURCE_CSS)        | plain, readable, light or dark, no script and nothing loaded from elsewhere                                       |
| [`SOURCE_CSP`](_autosummary/annals.notebook.html.md#annals.notebook.SOURCE_CSP)        | ones), nothing else; a sandbox (no origin, no script, no form) even so, since it is served beside the owner's app |
| [`HTML_SOURCE_CSP`](_autosummary/annals.notebook.html.md#annals.notebook.HTML_SOURCE_CSP)   | its own styles and images, no script, no request elsewhere                                                        |
| [`RENDER_MAX_BYTES`](_autosummary/annals.notebook.html.md#annals.notebook.RENDER_MAX_BYTES)  | rendering is superlinear on hostile input, and the route is public                                                |
| [`SOURCE_CACHE_SIZE`](_autosummary/annals.notebook.html.md#annals.notebook.SOURCE_CACHE_SIZE) | rendered source pages kept in memory (each at most a few times RENDER_MAX_BYTES)                                  |

### Functions

| [`markdown_html`](_autosummary/annals.notebook.html.md#annals.notebook.markdown_html)(text, \*[, rewrite_url, render])   | `text` (markdown) as html; every link and image through `rewrite_url`.                    |
|---------------------------------------------------------------------------------------------------|-------------------------------------------------------------------------------------------|
| [`notebook_sources`](_autosummary/annals.notebook.html.md#annals.notebook.notebook_sources)(scope, \*, link)                | One row per source file of `scope` (`(meta, files)` pairs, in the share's order).         |
| [`render_source`](_autosummary/annals.notebook.html.md#annals.notebook.render_source)(text, \*, title, \*\*scope)        | One markdown file of a share as its source page (see the module docstring).               |
| [`render_source_body`](_autosummary/annals.notebook.html.md#annals.notebook.render_source_body)(text, \*, link, doc_id, ...)  | One markdown file of a share as safe html, links and images made absolute.                |
| [`source_files`](_autosummary/annals.notebook.html.md#annals.notebook.source_files)(meta, files)                        | The files of a document (`files`: those a caller may serve) that are sources.             |
| [`source_link_rewriter`](_autosummary/annals.notebook.html.md#annals.notebook.source_link_rewriter)(decide, \*, link, ...)      | `url -> url | None` for a source page, which has no `<base>`.                             |
| [`source_page`](_autosummary/annals.notebook.html.md#annals.notebook.source_page)(title, body_html)                    | The page a notebook reads: a `<title>`, the body, plain style, no script.                 |
| [`source_scope`](_autosummary/annals.notebook.html.md#annals.notebook.source_scope)(read_text)                          | `meta -> files`: a document's source pages and the files they show, for a share.          |
| [`source_title`](_autosummary/annals.notebook.html.md#annals.notebook.source_title)(meta, rel, \*, several)             | The source's name in the notebook: the document's title, plus the file if it has several. |
| [`source_url`](_autosummary/annals.notebook.html.md#annals.notebook.source_url)(link, doc_id, rel)                    | `<link>/source/<doc id>/<file>` (`link`: the share's, with or without a slash).           |

### annals.notebook.HTML_SOURCE_CSP *= "sandbox; default-src 'none'; img-src 'self' data:; style-src 'self' 'unsafe-inline'; base-uri 'none'; form-action 'none'; frame-ancestors 'none'"*

its own styles and images, no script, no request elsewhere

* **Type:**
  an html source

### annals.notebook.RENDER_MAX_BYTES *= 300000*

rendering is
superlinear on hostile input, and the route is public

* **Type:**
  markdown past this size is sent as escaped text, not rendered

### annals.notebook.SOURCE_CACHE_SIZE *= 32*

rendered source pages kept in memory (each at most a few times RENDER_MAX_BYTES)

### annals.notebook.SOURCE_CSP *= "sandbox; default-src 'none'; img-src 'self' data:; style-src 'unsafe-inline'; base-uri 'none'; form-action 'none'; frame-ancestors 'none'"*

ones), nothing else; a
sandbox (no origin, no script, no form) even so, since it is served beside the owner’s app

* **Type:**
  what a source page may do
* **Type:**
  show its own images (and data

### annals.notebook.SOURCE_CSS *= ":root{color-scheme:light dark}body{font:17px/1.6 system-ui,-apple-system,'Segoe UI',sans-serif;max-width:46rem;margin:0 auto;padding:1.5rem 1rem 4rem}pre,code{font-family:ui-monospace,Menlo,monospace;font-size:.9em}pre{white-space:pre-wrap;overflow-wrap:anywhere}table{border-collapse:collapse}th,td{border:1px solid #8884;padding:.3em .6em}img{max-width:100%;height:auto}"*

plain, readable,
light or dark, no script and nothing loaded from elsewhere

* **Type:**
  a source page is read by a fetcher and, now and then, by a person

### annals.notebook.SOURCE_KINDS *= ('md', 'html')*

the kinds of file a notebook can take from a link (images, audio, video and pdf it
takes only as uploads)

### annals.notebook.SOURCE_SEGMENT *= 'source'*

the path segment of a source page under a share link

### annals.notebook.markdown_html(text, , rewrite_url=None, render=None)

`text` (markdown) as html; every link and image through `rewrite_url`.

`render(text, rewrite_url)` overrides the default renderer. Without one (no
`markdown-it-py`) the text is escaped in a `<pre>`: no markup, so no link.

* **Return type:**
  [`str`](https://docs.python.org/3/builtins/stdtypes.html#str)

### annals.notebook.notebook_sources(scope, , link)

One row per source file of `scope` (`(meta, files)` pairs, in the share’s order).

`{"sources": [{"doc", "file", "title", "url"}], "skipped": [{"doc", "title",
"kinds"}]}`; `skipped` names the documents with nothing a notebook can take from a
link (only images, audio, pdf…), so the page can say why they are missing.

* **Return type:**
  [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)

### annals.notebook.render_source(text, , title, \*\*scope)

One markdown file of a share as its source page (see the module docstring).

`scope` is [`render_source_body()`](_autosummary/annals.notebook.html.md#annals.notebook.render_source_body)’s; the page adds the `<title>`.

* **Return type:**
  [`str`](https://docs.python.org/3/builtins/stdtypes.html#str)

### annals.notebook.render_source_body(text, , link, doc_id, rel, files, sources, shared_ids, root_id='', private_hosts=())

One markdown file of a share as safe html, links and images made absolute.

Every argument is hashable, so a body is rendered once per text and scope.
`shared_ids` are the annals ids the share includes (opened at `<link>/d/<id>`),
`root_id` the shared group’s (opened at `<link>/`).

* **Return type:**
  [`str`](https://docs.python.org/3/builtins/stdtypes.html#str)

### annals.notebook.source_files(meta, files)

The files of a document (`files`: those a caller may serve) that are sources.

* **Return type:**
  [`list`](https://docs.python.org/3/builtins/stdtypes.html#list)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str)]

### annals.notebook.source_link_rewriter(decide, , link, doc_id, from_dir, sources)

`url -> url | None` for a source page, which has no `<base>`.

`decide` ([`annals.share.ref_decider()`](_autosummary/annals.share.html.md#annals.share.ref_decider)) says what may stay; a relative file it
keeps becomes absolute here: another source page of the document links to that
page, any other file to the share’s raw file. Anchors and web links stay as they are.

* **Return type:**
  [`Callable`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Callable)[[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str)], [`str`](https://docs.python.org/3/builtins/stdtypes.html#str) | [`None`](https://docs.python.org/3/builtins/constants.html#None)]

### annals.notebook.source_page(title, body_html)

The page a notebook reads: a `<title>`, the body, plain style, no script.

* **Return type:**
  [`str`](https://docs.python.org/3/builtins/stdtypes.html#str)

### annals.notebook.source_scope(read_text)

`meta -> files`: a document’s source pages and the files they show, for a share.

`read_text(doc_id, rel)` reads one file. A notebook share made with this (the
`files_of` of [`annals.share.Shares.create()`](_autosummary/annals.share.html.md#annals.share.Shares.create)) reaches nothing else of a folder.

* **Return type:**
  [`Callable`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Callable)[[[`Mapping`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Mapping)], [`list`](https://docs.python.org/3/builtins/stdtypes.html#list)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str)]]

### annals.notebook.source_title(meta, rel, , several)

The source’s name in the notebook: the document’s title, plus the file if it has several.

* **Return type:**
  [`str`](https://docs.python.org/3/builtins/stdtypes.html#str)

### annals.notebook.source_url(link, doc_id, rel)

`<link>/source/<doc id>/<file>` (`link`: the share’s, with or without a slash).

* **Return type:**
  [`str`](https://docs.python.org/3/builtins/stdtypes.html#str)


# _autosummary/annals.originals.html.md

# annals.originals

Originals: a pick’s files, exactly as published, as one streamed `.zip`.

One file ([`annals.combine`](_autosummary/annals.combine.html.md#module-annals.combine)) cannot hold audio or video, so a pick of originals has its
own form: one folder per document, named after its title, holding the document’s files with
their published names. The zip is **streamed** (members are stored, since audio, video, PDFs
and images are already compressed), so the server never holds it whole; the size is known
before it starts ([`plan()`](_autosummary/annals.originals.html.md#annals.originals.plan)), and a pick over the cap is refused with the cap in the
message ([`TooBig`](_autosummary/annals.originals.html.md#annals.originals.TooBig)), never started and abandoned half way.

```pycon
>>> import io, zipfile
>>> from pathlib import Path
>>> import tempfile
>>> d = Path(tempfile.mkdtemp()); (d / "a.txt").write_text("hi")
2
>>> docs = [{"id": "x", "title": "My / doc", "files": ["a.txt"]}]
>>> p = plan(docs, path_of=lambda i, rel: d / rel)
>>> [e.arcname for e in p.entries], p.bytes
(['My doc/a.txt'], 2)
>>> zipfile.ZipFile(io.BytesIO(b"".join(stream(p)))).read("My doc/a.txt")
b'hi'
```

### Functions

| [`folder_name`](_autosummary/annals.originals.html.md#annals.originals.folder_name)(title, fallback)                   | A title as a folder name: no separators or control characters, no leading dots, bounded.   |
|-------------------------------------------------------------------------------------------------|--------------------------------------------------------------------------------------------|
| [`plan`](_autosummary/annals.originals.html.md#annals.originals.plan)(docs, \*, path_of[, max_bytes, max_docs]) | The files of `docs` (metas with `id`, `title`, `files`) and their total size.              |
| [`size_text`](_autosummary/annals.originals.html.md#annals.originals.size_text)(n)                                   | Bytes as the page says them.                                                               |
| [`stream`](_autosummary/annals.originals.html.md#annals.originals.stream)(the_plan, \*[, chunk])                  | The zip of `the_plan`, in pieces, a file at a time (nothing is held whole).                |

### Classes

| [`Entry`](_autosummary/annals.originals.html.md#annals.originals.Entry)(path, arcname, size, mtime)   | One file: where it is, its name in the zip, its size and modification time.            |
|--------------------------------------------------------------------------------------|----------------------------------------------------------------------------------------|
| [`Plan`](_autosummary/annals.originals.html.md#annals.originals.Plan)(entries, bytes, docs)          | What a zip will hold: the entries, their total size, and the documents they came from. |

### Exceptions

| [`TooBig`](_autosummary/annals.originals.html.md#annals.originals.TooBig)   | The pick is over a cap; the message names the cap.   |
|-----------------------------------------------------------|------------------------------------------------------|

### *class* annals.originals.Entry(path, arcname, size, mtime)

Bases: [`object`](https://docs.python.org/3/builtins/functions.html#object)

One file: where it is, its name in the zip, its size and modification time.

### *class* annals.originals.Plan(entries, bytes, docs)

Bases: [`object`](https://docs.python.org/3/builtins/functions.html#object)

What a zip will hold: the entries, their total size, and the documents they came from.

### *exception* annals.originals.TooBig

Bases: [`ValueError`](https://docs.python.org/3/builtins/exceptions.html#ValueError)

The pick is over a cap; the message names the cap.

### annals.originals.folder_name(title, fallback)

A title as a folder name: no separators or control characters, no leading dots, bounded.

```pycon
>>> folder_name("Q3: plans / draft", "id1")
'Q3 plans draft'
>>> folder_name("  ..  ", "id1")
'id1'
>>> folder_name("con", "id1")
'con_'
```

* **Return type:**
  [`str`](https://docs.python.org/3/builtins/stdtypes.html#str)

### annals.originals.plan(docs, , path_of, max_bytes=None, max_docs=None)

The files of `docs` (metas with `id`, `title`, `files`) and their total size.

`path_of(doc_id, rel)` finds a file on disk (and refuses one that is not the
document’s). Two documents with one title get `title`, `title (2)`… A file that is
gone from disk is skipped. Over `max_docs` documents or `max_bytes` bytes: [`TooBig`](_autosummary/annals.originals.html.md#annals.originals.TooBig).

* **Return type:**
  [`Plan`](_autosummary/annals.originals.html.md#annals.originals.Plan)

### annals.originals.size_text(n)

Bytes as the page says them.

```pycon
>>> size_text(512 * 2**20), size_text(1536)
('512 MB', '1.5 KB')
```

* **Return type:**
  [`str`](https://docs.python.org/3/builtins/stdtypes.html#str)

### annals.originals.stream(the_plan, , chunk=262144)

The zip of `the_plan`, in pieces, a file at a time (nothing is held whole).

* **Return type:**
  [`Iterator`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Iterator)[[`bytes`](https://docs.python.org/3/builtins/stdtypes.html#bytes)]


# _autosummary/annals.overview.html.md

# annals.overview

Spoken overviews of a document: the request a page makes, and the worker that fulfils it.

A reader asks for an overview from a document’s page. That writes one small JSON file under
the data root (`overviews/<doc id>.json`). A worker on the same machine reads the document
from the store, runs a command that makes the overview, and publishes the result as a
document of its own. The page polls the request’s state.

annals does not know how an overview is made. The command is the seam: any program that
takes a text file and writes one HTML page, named in `ANNALS_OVERVIEW_COMMAND` or passed to
[`work()`](_autosummary/annals.overview.html.md#annals.overview.work), with `{source}`, `{minutes}` and `{out}` filled in, and `{url}`, the source document’s
page, so the overview can link to what it was based on:

```default
my-overview {source} --minutes {minutes} --player-to {out} --source-url {url}
```

The feature is off unless the host turns it on (`mk_api(overviews=True)`), because making
an overview spends money. A host can also offer it to some readers only
(`mk_api(overviews={"me@example.com"})`, or `ANNALS_OVERVIEWS` for `annals.api.mk_app()`;
see [`readers_offered()`](_autosummary/annals.overview.html.md#annals.overview.readers_offered)): the others get no Listen button, and the documents the feature
makes ([`made_here()`](_autosummary/annals.overview.html.md#annals.overview.made_here)) are hidden from them. For the same reason, a current overview is not made again unless
forced, a crash after publishing does not pay twice, `work` stops at a daily limit, and a
request nobody fulfilled expires rather than spending money whenever a worker next wakes.

Run the worker on a timer. Finished request files stay in the folder and the worker writes
there, so a watcher on the folder would keep waking it.

When the command cannot work until someone acts (an expired login, a voice account out of
credit), pressing again only spends the daily limit. So the worker notices it: the same
failure, fast, from two documents in a row, marks the maker *down* with that reason (a
document failing twice is that document). An agent can mark it too, with a link to where it
is being fixed (`annals listen-down "why" --link URL`). While it is down, nothing fails or
is dropped: requests *wait* (past the daily limit too), the page says why and what to do
instead of offering a Try again, and the worker tries one of them again every few hours. The
first success, or `annals listen-down --clear`, clears the mark and queues everything that
waited.

```pycon
>>> html_to_text("<title>x</title><p>One &amp; two</p><script>no()</script><p>Three</p>")
'One & two\n\nThree'
>>> [c["characters"] for c in choices()]
[2700, 4500, 6300]
```

### Module Attributes

| [`ENV_OVERVIEWS`](_autosummary/annals.overview.html.md#annals.overview.ENV_OVERVIEWS)           | see [`readers_offered()`](_autosummary/annals.overview.html.md#annals.overview.readers_offered)                                                                                            |
|--------------------------------------------------------------------------|-------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| [`READERS_SEP`](_autosummary/annals.overview.html.md#annals.overview.READERS_SEP)             | in `ANNALS_OVERVIEWS`, the readers are separated by this; `*` alone means every reader                                                                            |
| [`EVERY_READER`](_autosummary/annals.overview.html.md#annals.overview.EVERY_READER)            | in `ANNALS_OVERVIEWS`, the readers are separated by this; `*` alone means every reader                                                                            |
| [`REQUEST_FILE_MODE`](_autosummary/annals.overview.html.md#annals.overview.REQUEST_FILE_MODE)       | read by the server and the worker, which may be different users                                                                                                   |
| [`DFLT_DAILY_LIMIT`](_autosummary/annals.overview.html.md#annals.overview.DFLT_DAILY_LIMIT)        | at most this many overviews are started in any 24 hours, whoever asks                                                                                             |
| [`QUEUED_EXPIRY_S`](_autosummary/annals.overview.html.md#annals.overview.QUEUED_EXPIRY_S)         | nobody is waiting for it now                                                                                                                                      |
| [`RUNNING_MARGIN_S`](_autosummary/annals.overview.html.md#annals.overview.RUNNING_MARGIN_S)        | a request still running after this long has lost its worker                                                                                                       |
| [`DOWN_FILE`](_autosummary/annals.overview.html.md#annals.overview.DOWN_FILE)               | the file marking the maker down; not `.json`, because every `.json` here is a request                                                                             |
| [`DOWN_AFTER`](_autosummary/annals.overview.html.md#annals.overview.DOWN_AFTER)              | the same fast failure from this many documents in a row means the maker is down                                                                                   |
| [`FAST_FAILURE_S`](_autosummary/annals.overview.html.md#annals.overview.FAST_FAILURE_S)          | the maker could not start                                                                                                                                         |
| [`PROBE_EVERY_S`](_autosummary/annals.overview.html.md#annals.overview.PROBE_EVERY_S)           | while the maker is down, one waiting request is tried this often, to notice it works again                                                                        |
| [`MINUTES`](_autosummary/annals.overview.html.md#annals.overview.MINUTES)                 | the lengths a reader can pick, in minutes; each costs voice characters, so the set is closed                                                                      |
| [`CHARS_PER_MINUTE`](_autosummary/annals.overview.html.md#annals.overview.CHARS_PER_MINUTE)        | spoken English at about 150 words a minute and 6 characters a word; shown as an estimate                                                                          |
| [`TAG`](_autosummary/annals.overview.html.md#annals.overview.TAG)                     | marks a document that is itself an overview, so nobody makes an overview of an overview                                                                           |
| [`WAITING`](_autosummary/annals.overview.html.md#annals.overview.WAITING)                 | made once it works again, never spent on before                                                                                                                   |
| [`FAILED_SHOWN_S`](_autosummary/annals.overview.html.md#annals.overview.FAILED_SHOWN_S)          | a failed request is still listed as unmade for this long, so a retry is offered where the reader looks for the overview (the Audio tab), not only on the document |
| [`COMBINED_TAG`](_autosummary/annals.overview.html.md#annals.overview.COMBINED_TAG)            | marks a document made by putting several documents' text in one, for one review of them all                                                                       |
| [`COMBINED_REQUEST_PREFIX`](_autosummary/annals.overview.html.md#annals.overview.COMBINED_REQUEST_PREFIX) | a queued combination is filed under this plus its [`combined_key()`](_autosummary/annals.overview.html.md#annals.overview.combined_key), until it has a document                        |
| [`COMBINE_KIND`](_autosummary/annals.overview.html.md#annals.overview.COMBINE_KIND)            | the `kind` of a request record for a combination (the only marker; the id is a file name)                                                                         |

### Functions

| [`choices`](_autosummary/annals.overview.html.md#annals.overview.choices)()                                          | Each length on offer and what it would cost in voice characters.                                                               |
|-----------------------------------------------------------------------------------------------------|--------------------------------------------------------------------------------------------------------------------------------|
| [`combined_document`](_autosummary/annals.overview.html.md#annals.overview.combined_document)(store, docs, \*, title[, ...])   | One document holding the text of `docs`, so a review of it covers them all.                                                    |
| [`combined_key`](_autosummary/annals.overview.html.md#annals.overview.combined_key)(docs)                                 | Names a set of documents at their current versions, in any order.                                                              |
| [`combined_request_id`](_autosummary/annals.overview.html.md#annals.overview.combined_request_id)(key)                           | The id a queued combination is filed under, before its document exists.                                                        |
| [`eligible`](_autosummary/annals.overview.html.md#annals.overview.eligible)(meta)                                     | Whether a document can be spoken: readable text, current, and not itself an overview.                                          |
| [`find_combined`](_autosummary/annals.overview.html.md#annals.overview.find_combined)(store, key)                          | The combined document made for `key` ([`combined_key()`](_autosummary/annals.overview.html.md#annals.overview.combined_key)), if there is one.       |
| [`html_to_text`](_autosummary/annals.overview.html.md#annals.overview.html_to_text)(html)                                 | The readable text of a page: no markup, scripts or styles (nor its PDF button).                                                |
| [`made_here`](_autosummary/annals.overview.html.md#annals.overview.made_here)(meta)                                    | Whether the overview feature made this document: a spoken overview, or the text it combined to speak several documents as one. |
| [`maker_down`](_autosummary/annals.overview.html.md#annals.overview.maker_down)(requests)                               | Why no overview can be made until someone acts, or `None` while the maker works.                                               |
| [`mark_down`](_autosummary/annals.overview.html.md#annals.overview.mark_down)(requests[, reason, link])                | Say the maker is down, why, and where it is being fixed; keep what is not given.                                               |
| [`mark_up`](_autosummary/annals.overview.html.md#annals.overview.mark_up)(requests)                                  | The maker works (again): clear the mark and queue what waited; return those ids.                                               |
| [`readers_offered`](_autosummary/annals.overview.html.md#annals.overview.readers_offered)(spec)                              | Who may ask for and hear overviews: `False` (nobody), `True` (every reader), or a test.                                        |
| [`request`](_autosummary/annals.overview.html.md#annals.overview.request)(store, requests, doc_id, \*[, ...])        | Ask for an overview of a document.                                                                                             |
| [`request_combined`](_autosummary/annals.overview.html.md#annals.overview.request_combined)(store, requests, docs, \*, title) | Ask for ONE overview of several documents: of the document combining their text.                                               |
| [`state_of`](_autosummary/annals.overview.html.md#annals.overview.state_of)(store, requests, meta)                    | What a page shows for a document: its request's state and what it can start.                                                   |
| [`unmade`](_autosummary/annals.overview.html.md#annals.overview.unmade)(store, requests)                            | The overviews asked for and not (yet) made: being made, waiting, or failed recently.                                           |
| [`valid_minutes`](_autosummary/annals.overview.html.md#annals.overview.valid_minutes)(minutes)                             | Whether this is a length on offer.                                                                                             |
| [`work`](_autosummary/annals.overview.html.md#annals.overview.work)(store, requests, \*[, command, timeout, ...]) | Fulfil every queued request, one at a time, until none is left; return what happened.                                          |

### Classes

| [`Requests`](_autosummary/annals.overview.html.md#annals.overview.Requests)(data_dir)   | The request files: one per document, each replaced whole so a reader never sees half.   |
|-----------------------------------------------------------------------|-----------------------------------------------------------------------------------------|

### Exceptions

| [`MakerFailed`](_autosummary/annals.overview.html.md#annals.overview.MakerFailed)   | The overview command ran and failed: the maker's fault, not the document's.   |
|----------------------------------------------------------------|-------------------------------------------------------------------------------|

### annals.overview.CHARS_PER_MINUTE *= 900*

spoken English at about 150 words a minute and 6 characters a word; shown as an estimate

### annals.overview.COMBINED_REQUEST_PREFIX *= 'combined-'*

a queued combination is filed under this plus its [`combined_key()`](_autosummary/annals.overview.html.md#annals.overview.combined_key), until it has a document

### annals.overview.COMBINED_TAG *= 'combined'*

marks a document made by putting several documents’ text in one, for one review of them all

### annals.overview.COMBINE_KIND *= 'combine'*

the `kind` of a request record for a combination (the only marker; the id is a file name)

### annals.overview.DFLT_DAILY_LIMIT *= 20*

at most this many overviews are started in any 24 hours, whoever asks

### annals.overview.DOWN_AFTER *= 2*

the same fast failure from this many documents in a row means the maker is down

### annals.overview.DOWN_FILE *= 'maker-down'*

the file marking the maker down; not `.json`, because every `.json` here is a request

### annals.overview.ENV_OVERVIEWS *= 'ANNALS_OVERVIEWS'*

see [`readers_offered()`](_autosummary/annals.overview.html.md#annals.overview.readers_offered)

* **Type:**
  who is offered overviews, for a host built from the environment

### annals.overview.EVERY_READER *= '\*'*

in `ANNALS_OVERVIEWS`, the readers are separated by this; `*` alone means every reader

### annals.overview.FAILED_SHOWN_S *= 604800*

a failed request is still listed as unmade for this long, so a retry is offered where
the reader looks for the overview (the Audio tab), not only on the document

### annals.overview.FAST_FAILURE_S *= 120*

the maker could not start

* **Type:**
  a failure this quick never reached the work

### annals.overview.MINUTES *= (3, 5, 7)*

the lengths a reader can pick, in minutes; each costs voice characters, so the set is closed

### *exception* annals.overview.MakerFailed

Bases: [`RuntimeError`](https://docs.python.org/3/builtins/exceptions.html#RuntimeError)

The overview command ran and failed: the maker’s fault, not the document’s.

### annals.overview.PROBE_EVERY_S *= 10800*

while the maker is down, one waiting request is tried this often, to notice it works again

### annals.overview.QUEUED_EXPIRY_S *= 3600*

nobody is waiting for it now

* **Type:**
  a request still queued after this long is dropped

### annals.overview.READERS_SEP *= ','*

in `ANNALS_OVERVIEWS`, the readers are separated by this; `*` alone means every reader

### annals.overview.REQUEST_FILE_MODE *= 420*

read by the server and the worker, which may be different users

* **Type:**
  request files and the down mark

### annals.overview.RUNNING_MARGIN_S *= 600*

a request still running after this long has lost its worker

### *class* annals.overview.Requests(data_dir)

Bases: [`object`](https://docs.python.org/3/builtins/functions.html#object)

The request files: one per document, each replaced whole so a reader never sees half.

#### delete(doc_id)

Remove a request, if there is one.

* **Return type:**
  [`None`](https://docs.python.org/3/builtins/constants.html#None)

#### ids()

Documents with a request, oldest request first.

* **Return type:**
  [`list`](https://docs.python.org/3/builtins/stdtypes.html#list)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str)]

#### mark()

What the worker knows of the maker’s recent failures (see [`maker_down()`](_autosummary/annals.overview.html.md#annals.overview.maker_down)).

* **Return type:**
  [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)

#### note_start(doc_id)

Logged before the money is spent, so a crash still counts against the limit.

* **Return type:**
  [`None`](https://docs.python.org/3/builtins/constants.html#None)

#### put_mark(mark)

Replace the mark, or remove it (`None`).

* **Return type:**
  [`None`](https://docs.python.org/3/builtins/constants.html#None)

#### started_today()

How many overviews were started in the last 24 hours.

* **Return type:**
  [`int`](https://docs.python.org/3/builtins/functions.html#int)

### annals.overview.TAG *= 'overview'*

marks a document that is itself an overview, so nobody makes an overview of an overview

### annals.overview.WAITING *= 'waiting'*

made once it works again, never spent on before

* **Type:**
  asked for while the maker is down

### annals.overview.choices()

Each length on offer and what it would cost in voice characters.

* **Return type:**
  [`list`](https://docs.python.org/3/builtins/stdtypes.html#list)[[`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)]

### annals.overview.combined_document(store, docs, , title, group=None, max_bytes=None)

One document holding the text of `docs`, so a review of it covers them all.

A combined document among `docs` counts as the documents it combines. The same
documents at the same versions give the same document back, so asking twice makes one.
A new one is added to `group` when given. Raises `ValueError` when none of `docs`
has text to speak, or past `max_bytes` of text.

* **Return type:**
  [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)

### annals.overview.combined_key(docs)

Names a set of documents at their current versions, in any order.

```pycon
>>> combined_key([{"id": "b", "version": 2}, {"id": "a"}]) == combined_key([{"id": "a"}, {"id": "b", "version": 2}])
True
```

* **Return type:**
  [`str`](https://docs.python.org/3/builtins/stdtypes.html#str)

### annals.overview.combined_request_id(key)

The id a queued combination is filed under, before its document exists.

* **Return type:**
  [`str`](https://docs.python.org/3/builtins/stdtypes.html#str)

### annals.overview.eligible(meta)

Whether a document can be spoken: readable text, current, and not itself an overview.

* **Return type:**
  [`bool`](https://docs.python.org/3/builtins/functions.html#bool)

### annals.overview.find_combined(store, key)

The combined document made for `key` ([`combined_key()`](_autosummary/annals.overview.html.md#annals.overview.combined_key)), if there is one.

* **Return type:**
  [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict) | [`None`](https://docs.python.org/3/builtins/constants.html#None)

### annals.overview.html_to_text(html)

The readable text of a page: no markup, scripts or styles (nor its PDF button).

* **Return type:**
  [`str`](https://docs.python.org/3/builtins/stdtypes.html#str)

### annals.overview.made_here(meta)

Whether the overview feature made this document: a spoken overview, or the text it
combined to speak several documents as one. These are what a reader who is not offered
overviews never sees.

* **Return type:**
  [`bool`](https://docs.python.org/3/builtins/functions.html#bool)

### annals.overview.maker_down(requests)

Why no overview can be made until someone acts, or `None` while the maker works.

`{"reason", "since", "link"}`: in words, from when, and where it is being fixed (or
`None`). Set by the worker once the same fast failure came from [`DOWN_AFTER`](_autosummary/annals.overview.html.md#annals.overview.DOWN_AFTER)
documents in a row, or by hand with [`mark_down()`](_autosummary/annals.overview.html.md#annals.overview.mark_down); cleared by the next success or
[`mark_up()`](_autosummary/annals.overview.html.md#annals.overview.mark_up).

* **Return type:**
  [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict) | [`None`](https://docs.python.org/3/builtins/constants.html#None)

### annals.overview.mark_down(requests, reason='', , link=None)

Say the maker is down, why, and where it is being fixed; keep what is not given.

For an agent that filed the task that would fix it: the page then links to it. A link
alone only adds to a mark that is already there. Raises `ValueError` otherwise, or for a
link that is not a web address.

* **Return type:**
  [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)

### annals.overview.mark_up(requests)

The maker works (again): clear the mark and queue what waited; return those ids.

* **Return type:**
  [`list`](https://docs.python.org/3/builtins/stdtypes.html#list)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str)]

### annals.overview.readers_offered(spec)

Who may ask for and hear overviews: `False` (nobody), `True` (every reader), or a test.

`spec` is what a host passes as `overviews`: a bool, a predicate on the reader’s name
(an email, as `annals.api.reader_of()` gives it), a collection of names, or a string as
`ANNALS_OVERVIEWS` holds it (names separated by commas, `*` for every reader, empty for
nobody; `true`/`1`/`yes` and `false`/`0`/`no` mean the same as `*` and empty,
never a reader so named). Names are compared without case.

```pycon
>>> readers_offered("*"), readers_offered(""), readers_offered(None)
(True, False, False)
>>> readers_offered("true"), readers_offered(" No "), readers_offered(["*"])
(True, False, True)
>>> may = readers_offered(" Me@Example.com, ")
>>> may("me@example.com"), may("someone@example.com")
(True, False)
```

* **Return type:**
  [`Union`](https://docs.python.org/3/library/typing.html#typing.Union)[[`Callable`](https://docs.python.org/3/library/typing.html#typing.Callable)[[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str)], [`bool`](https://docs.python.org/3/builtins/functions.html#bool)], [`bool`](https://docs.python.org/3/builtins/functions.html#bool)]

### annals.overview.request(store, requests, doc_id, , minutes=5, force=False)

Ask for an overview of a document. Raises `ValueError` if it cannot be asked for.

Asking again while one is being made changes nothing, and neither does asking for one
that exists and is current unless `force`, so a repeat costs nothing. While the maker
is down ([`maker_down()`](_autosummary/annals.overview.html.md#annals.overview.maker_down)), the request waits for it rather than failing.

* **Return type:**
  [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)

### annals.overview.request_combined(store, requests, docs, , title, group=None, minutes=5, max_bytes=None)

Ask for ONE overview of several documents: of the document combining their text.

Nothing is published here. When the documents were combined before, that document gets
an ordinary request. Otherwise the request is queued, with the document ids, under
[`combined_request_id()`](_autosummary/annals.overview.html.md#annals.overview.combined_request_id) (a record marked `kind: "combine"`), and the worker makes
the combined document (see [`combined_document()`](_autosummary/annals.overview.html.md#annals.overview.combined_document)) when it starts the job, so a
request nobody works leaves no document behind. Returns `{"doc": <combined document
id, or None until the worker has made it>, "listen": <the overview's state>}`. Raises
`ValueError` as [`request()`](_autosummary/annals.overview.html.md#annals.overview.request) does, or when there is nothing to speak or too much
of it: refused now, not after the request has waited for a worker.

The key names the documents at their versions *now*. A retry after one of them changed
is a different key, so a new request: the old failed one stays listed until it expires.

* **Return type:**
  [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)

### annals.overview.state_of(store, requests, meta)

What a page shows for a document: its request’s state and what it can start.

* **Return type:**
  [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)

### annals.overview.unmade(store, requests)

The overviews asked for and not (yet) made: being made, waiting, or failed recently.

Each is `state_of` its document plus `doc`, `title`, `created` (the document’s),
`requested` and `finished` (the last try’s). A queued combination of several documents
has no document yet: `doc` is `None` and `combine` has the `docs` and `group`
to ask again with (`POST /overviews`). A request whose document is gone, binned
or no longer speakable is left out: nothing can be retried. Newest first.

* **Return type:**
  [`list`](https://docs.python.org/3/builtins/stdtypes.html#list)[[`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)]

### annals.overview.valid_minutes(minutes)

Whether this is a length on offer. Exactly an int: not `True`, and not `3.0`.

* **Return type:**
  [`bool`](https://docs.python.org/3/builtins/functions.html#bool)

### annals.overview.work(store, requests, \*, command=None, timeout=1800, daily_limit=None, doc_url=<class 'str'>)

Fulfil every queued request, one at a time, until none is left; return what happened.

A failure is recorded on its request, for the page to show, and the next one still runs.
A request made while this runs is picked up before it exits. `doc_url` turns a document
id into its page, for `{url}`. While the maker is down, requests wait, and one of them
is tried every [`PROBE_EVERY_S`](_autosummary/annals.overview.html.md#annals.overview.PROBE_EVERY_S); once one works, those waiting run too.

* **Return type:**
  [`list`](https://docs.python.org/3/builtins/stdtypes.html#list)[[`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)]


# _autosummary/annals.pagepdf.html.md

# annals.pagepdf

Every published html page carries its own Download PDF button, and the PDF beside it.

A page is often read without the annals page around it: opened full page, its raw url
mailed on, or shared. So at publish time the stored html itself gets a “Download this page
as PDF” link, pointing at `<stem>.pdf` in the same document. It is a line of its own at
the end of the page, in the page’s flow, so it never covers anything (it floated at the top
right until 2026-12-03, over the page’s title and an audio player’s controls). It is hidden
when printing, and it takes itself out inside a frame: in annals the page sits in one, and
annals offers the PDF in its own More menu. Serving a page runs [`refresh_button()`](_autosummary/annals.pagepdf.html.md#annals.pagepdf.refresh_button), so a
page stored with an older button gets this one. What is added:

1. **The page opts out** (`data-annals-pdf="off"` on `<html>` or `<body>`, or
   `annals publish --no-pdf`): nothing is added.
2. **The page has its own button** (any element with `data-annals-pdf`): nothing is
   added; it already says where its PDF is.
3. **The page declares its PDF** (`<link rel="alternate" type="application/pdf"
   href="...">`): the button points there, and nothing is printed.
4. **The document already holds** `<stem>.pdf` beside the page: the button points at it.
5. **Otherwise the page is printed** to `<stem>.pdf` by `pdf_renderer` (default
   [`print_with_chromium()`](_autosummary/annals.pagepdf.html.md#annals.pagepdf.print_with_chromium), pdfdol’s headless Chromium, in the `pdf` extra). When it
   > cannot print (no Chromium, a page that will not load in time), the button calls the
   > browser’s own print dialog instead, so it is never missing.

What this adds is one block wrapped in `<!--annals-pdf-->` markers (pure ASCII, so it
suits a page in any charset), so publishing a page that already went through here (a new
version through `--replace`) swaps the old button for a new one and prints the new page
again. The page’s bytes are otherwise kept as they were, whatever their encoding.

### Module Attributes

| [`PdfRenderer`](_autosummary/annals.pagepdf.html.md#annals.pagepdf.PdfRenderer)                            | `path of a staged html page -> PDF bytes`; raises when it cannot print                                                                                          |
|-----------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------------------------------------------------------------------------|
| [`DFLT_PRINT_TIMEOUT_S`](_autosummary/annals.pagepdf.html.md#annals.pagepdf.DFLT_PRINT_TIMEOUT_S)                   | the longest a page may take to print, in seconds, before the button prints instead                                                                              |
| [`DFLT_PDF_RENDERER`](_autosummary/annals.pagepdf.html.md#annals.pagepdf.DFLT_PDF_RENDERER)(page, \*[, timeout]) | what [`attach_pdf()`](_autosummary/annals.pagepdf.html.md#annals.pagepdf.attach_pdf) prints with when not told; read at call time, so a test or an embedding app can swap it once |
| [`DFLT`](_autosummary/annals.pagepdf.html.md#annals.pagepdf.DFLT)                                   | "the default renderer", told apart from `None` (never print)                                                                                                    |

### Functions

| [`DFLT_PDF_RENDERER`](_autosummary/annals.pagepdf.html.md#annals.pagepdf.DFLT_PDF_RENDERER)(page, \*[, timeout])            | what [`attach_pdf()`](_autosummary/annals.pagepdf.html.md#annals.pagepdf.attach_pdf) prints with when not told; read at call time, so a test or an embedding app can swap it once   |
|----------------------------------------------------------------------------------------------------|-------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| [`add_button`](_autosummary/annals.pagepdf.html.md#annals.pagepdf.add_button)(page, href)                            | `page` with a Download PDF link to `href` (or a print button when `None`).                                                                                        |
| [`attach_pdf`](_autosummary/annals.pagepdf.html.md#annals.pagepdf.attach_pdf)(root, main, files, \*[, pdf_renderer]) | Give the staged html page `root/main` its PDF button (and its PDF).                                                                                               |
| [`button_href`](_autosummary/annals.pagepdf.html.md#annals.pagepdf.button_href)(page)                                 | Where the button annals put in `page` points (`None`: none, or a print button).                                                                                   |
| [`declared_pdf`](_autosummary/annals.pagepdf.html.md#annals.pagepdf.declared_pdf)(page)                                | The href of the page's own `<link rel="alternate" type="application/pdf">`.                                                                                       |
| [`print_with_chromium`](_autosummary/annals.pagepdf.html.md#annals.pagepdf.print_with_chromium)(page, \*[, timeout])          | Print an html file to PDF with headless Chromium (pdfdol), with its print css.                                                                                    |
| [`refresh_button`](_autosummary/annals.pagepdf.html.md#annals.pagepdf.refresh_button)(page)                              | `page` with the button annals added (if any) as [`add_button()`](_autosummary/annals.pagepdf.html.md#annals.pagepdf.add_button) makes it now.                                       |
| [`strip_button`](_autosummary/annals.pagepdf.html.md#annals.pagepdf.strip_button)(page)                                | `page` without what [`add_button()`](_autosummary/annals.pagepdf.html.md#annals.pagepdf.add_button) put in it.                                                                      |
| [`wants_button`](_autosummary/annals.pagepdf.html.md#annals.pagepdf.wants_button)(page)                                | False when the page opts out, or already has a PDF button of its own.                                                                                             |

### annals.pagepdf.DFLT *= 'default'*

“the default renderer”, told apart from `None` (never print)

### annals.pagepdf.DFLT_PDF_RENDERER(page, , timeout=60)

what [`attach_pdf()`](_autosummary/annals.pagepdf.html.md#annals.pagepdf.attach_pdf) prints with when not told; read at call time, so a test or an
embedding app can swap it once

* **Return type:**
  [`bytes`](https://docs.python.org/3/builtins/stdtypes.html#bytes)

### annals.pagepdf.DFLT_PRINT_TIMEOUT_S *= 60*

the longest a page may take to print, in seconds, before the button prints instead

### annals.pagepdf.PdfRenderer

`path of a staged html page -> PDF bytes`; raises when it cannot print

alias of [`Callable`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Callable)[[[`Path`](https://docs.python.org/3/library/pathlib.html#pathlib.Path)], [`bytes`](https://docs.python.org/3/builtins/stdtypes.html#bytes)]

### annals.pagepdf.add_button(page, href)

`page` with a Download PDF link to `href` (or a print button when `None`).

One block goes at the end of the body (right before `</body>`, else `</html>`,
else the end of the page): a `<link rel="alternate">` declaring the PDF, so readers
and agents find it, its style, the footer holding the link, and the line that takes
the footer out inside a frame. Any button added earlier is replaced. `href` is used
as given (quote a file name first: [`attach_pdf()`](_autosummary/annals.pagepdf.html.md#annals.pagepdf.attach_pdf) does).

```pycon
>>> page = "<!doctype html><html><head></head><body><p>x</p></body></html>"
>>> out = add_button(page, "x.pdf")
>>> 'href="x.pdf"' in out and 'type="application/pdf"' in out
True
>>> out.startswith("<!doctype html>") and out.endswith("</body></html>")
True
>>> "window.print()" in add_button("<p>x</p>", None)
True
```

* **Return type:**
  [`str`](https://docs.python.org/3/builtins/stdtypes.html#str)

### annals.pagepdf.attach_pdf(root, main, files, , pdf_renderer='default')

Give the staged html page `root/main` its PDF button (and its PDF).

Returns `(files, pdf)`: `files` (relative to `root`) gains `<stem>.pdf` when it
is printed here, and `pdf` is where the page’s PDF is (a file of the document, or
the url the page declared), `None` when there is none. `pdf_renderer` defaults to
[`DFLT_PDF_RENDERER`](_autosummary/annals.pagepdf.html.md#annals.pagepdf.DFLT_PDF_RENDERER); `None` never prints: the button links to a PDF the
document or the page already has, else opens the print dialog. A renderer that fails
is logged and treated the same way; publishing never fails for want of a PDF.

* **Return type:**
  [`tuple`](https://docs.python.org/3/builtins/stdtypes.html#tuple)[[`list`](https://docs.python.org/3/builtins/stdtypes.html#list)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str)], [`str`](https://docs.python.org/3/builtins/stdtypes.html#str) | [`None`](https://docs.python.org/3/builtins/constants.html#None)]

### annals.pagepdf.button_href(page)

Where the button annals put in `page` points (`None`: none, or a print button).

```pycon
>>> button_href(add_button("<p>x</p>", "x.pdf"))
'x.pdf'
```

* **Return type:**
  [`str`](https://docs.python.org/3/builtins/stdtypes.html#str) | [`None`](https://docs.python.org/3/builtins/constants.html#None)

### annals.pagepdf.declared_pdf(page)

The href of the page’s own `<link rel="alternate" type="application/pdf">`.

A link annals added itself does not count: that is not the page declaring one.

```pycon
>>> declared_pdf('<link rel="alternate" type="application/pdf" href="guide.pdf">')
'guide.pdf'
>>> declared_pdf('<link rel="stylesheet" href="a.css">') is None
True
```

* **Return type:**
  [`str`](https://docs.python.org/3/builtins/stdtypes.html#str) | [`None`](https://docs.python.org/3/builtins/constants.html#None)

### annals.pagepdf.print_with_chromium(page, , timeout=60)

Print an html file to PDF with headless Chromium (pdfdol), with its print css.

Needs the `pdf` extra and `playwright install chromium`. It runs in a child
process, killed (with its browser) after `timeout` seconds. Images marked
`loading="lazy"` would print blank, so the page is printed from a copy without
that attribute, beside it so its relative files still load.

* **Return type:**
  [`bytes`](https://docs.python.org/3/builtins/stdtypes.html#bytes)

### annals.pagepdf.refresh_button(page)

`page` with the button annals added (if any) as [`add_button()`](_autosummary/annals.pagepdf.html.md#annals.pagepdf.add_button) makes it now.

Pages keep the button they were published with, so serving them runs this: a page
stored with an older button (one floating over the content) is served with today’s.

```pycon
>>> old = '<body><!--annals-pdf--><a id="annals-pdf" href="g.pdf">PDF</a><!--/annals-pdf--><p>x</p></body>'
>>> new = refresh_button(old)
>>> new.startswith("<body><p>x</p><!--annals-pdf-->") and button_href(new)
'g.pdf'
>>> refresh_button(new) == new and refresh_button("<p>none</p>") == "<p>none</p>"
True
```

* **Return type:**
  [`str`](https://docs.python.org/3/builtins/stdtypes.html#str)

### annals.pagepdf.strip_button(page)

`page` without what [`add_button()`](_autosummary/annals.pagepdf.html.md#annals.pagepdf.add_button) put in it.

```pycon
>>> strip_button(add_button("<body><p>x</p></body>", "x.pdf"))
'<body><p>x</p></body>'
```

* **Return type:**
  [`str`](https://docs.python.org/3/builtins/stdtypes.html#str)

### annals.pagepdf.wants_button(page)

False when the page opts out, or already has a PDF button of its own.

```pycon
>>> wants_button("<p>plain</p>")
True
>>> wants_button('<body data-annals-pdf="off"><p>x</p></body>')
False
>>> wants_button('<a href="g.pdf" data-annals-pdf>PDF</a>')
False
>>> wants_button('<script>"<a data-annals-pdf>"</script><p data-annals-pdf-note=1>')
True
```

* **Return type:**
  [`bool`](https://docs.python.org/3/builtins/functions.html#bool)


# _autosummary/annals.prefs.html.md

# annals.prefs

Each reader’s page preferences: a few named sections of JSON, kept on the server.

The page’s settings (the order of a document’s actions, first) follow the reader from the
phone to the tablet to the desktop, and from Safari to the home-screen app, which on an
iPhone keep separate browser storage. So they live here, one JSON file per reader beside the
listening records (`<root>/prefs/<reader>.json`), and the page keeps a copy in the browser
only to draw its first screen.

The page owns what a section means: its schema, defaults and the merge of a saved value with
a newer default are in `app.js` (`SETTINGS`). The server keeps each section as the
reader left it, refusing only what no section could be: a name that is not a short slug, a
value that is not a JSON object, a section over `MAX_SECTION_BYTES`, or more than
`MAX_SECTIONS` sections. That keeps a new setting a page-only change.

```pycon
>>> clean_section("bar", {"order": ["links", "listen"]})
{'order': ['links', 'listen']}
>>> clean_section("Bar!", {})
Traceback (most recent call last):
...
ValueError: a section name is a lower-case slug of at most 32 characters
```

### Functions

| [`clean_section`](_autosummary/annals.prefs.html.md#annals.prefs.clean_section)(name, value)        | `value` as kept under `name`, or `ValueError` saying why it cannot be.       |
|------------------------------------------------------------------------------------|------------------------------------------------------------------------------|
| [`for_reader`](_autosummary/annals.prefs.html.md#annals.prefs.for_reader)(root)                  | The default seam: each reader's preferences in `<root>/prefs/<reader>.json`. |
| [`put_section`](_autosummary/annals.prefs.html.md#annals.prefs.put_section)(records, name, value) | Keep `value` as the reader's `name` section; the sections as they now stand. |

### Classes

| [`PrefsStore`](_autosummary/annals.prefs.html.md#annals.prefs.PrefsStore)(path)   | One reader's preferences: `{section: object}` in one JSON file.   |
|---------------------------------------------------------------------|-------------------------------------------------------------------|

### *class* annals.prefs.PrefsStore(path)

Bases: [`JsonFileStore`](_autosummary/annals.jsonstore.html.md#annals.jsonstore.JsonFileStore)

One reader’s preferences: `{section: object}` in one JSON file.

#### valid(value)

Whether a value read from the file is kept (an invalid one is logged and skipped).

* **Return type:**
  [`bool`](https://docs.python.org/3/builtins/functions.html#bool)

### annals.prefs.clean_section(name, value)

`value` as kept under `name`, or `ValueError` saying why it cannot be.

* **Return type:**
  [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)

### annals.prefs.for_reader(root)

The default seam: each reader’s preferences in `<root>/prefs/<reader>.json`.

* **Return type:**
  [`Callable`](https://docs.python.org/3/library/typing.html#typing.Callable)[[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str)], [`Records`](_autosummary/annals.listening.html.md#annals.listening.Records)]

### annals.prefs.put_section(records, name, value)

Keep `value` as the reader’s `name` section; the sections as they now stand.

* **Return type:**
  [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)


# _autosummary/annals.records.html.md

# annals.records

The published documents as records for a retrieval index, so an agent can find one by meaning.

annals keeps its own full-text index for the page’s search box ([`annals.search`](_autosummary/annals.search.html.md#module-annals.search)).
Searching by meaning (“the report comparing local TTS engines”) is `ir`’s job, and `ir`
takes any package’s records through a named callable: register this one once (from Python;
`ir register` on the command line has no records option) and `ir` rebuilds from it:

```default
import ir, annals.records
ir.register("annals", "records", fetcher="annals.records:records",
            metadata_keys=list(annals.records.METADATA_KEYS))
ir.build_corpus("annals")       # then: ir discover annals "the report comparing local TTS engines"
```

One record per current document (the bin and earlier versions are not indexed). A markdown,
text or html document brings its text (html without its markup); a folder or a document of
several markdown files brings them as one text, as `annals aggregate` makes it; any other
kind (an image, a PDF) brings its title and excerpt, so it can still be found. Overviews and
combined documents duplicate their sources, so they are left out unless asked for. A document
the owner or the publisher tagged `noindex` or `private` (any case) is never yielded.

Run it where the documents are: it refuses an outbox and a remote target, because the
owner’s tags (the privacy gate) live beside the documents, and an index built from a partial
view would drop the rest. Two things belong to the index, not to this function: `ir` decides
a record changed by hashing its `text`, so a retag or retitle reaches the index’s filters
only on a rebuild that is `full` (which also prunes a document trashed, purged or newly
tagged `noindex`; register with full builds). `url` uses this machine’s `base_url`.

```pycon
>>> import tempfile, pathlib
>>> from annals.store import DocStore
>>> root = pathlib.Path(tempfile.mkdtemp())
>>> store = DocStore(root)
>>> _ = store.publish(text="# Local TTS engines\n\nPiper and Kokoro compared.", title="TTS", tags=["research"])
>>> _ = store.publish(text="# Secret\n\nnot for an index", title="S", tags=["noindex"])
>>> [(r["title"], r["tags"], "Kokoro" in r["text"]) for r in records(target=str(root))]
[('TTS', 'research', True)]
```

### Module Attributes

| [`DFLT_SKIP_TAGS`](_autosummary/annals.records.html.md#annals.records.DFLT_SKIP_TAGS)   | a document with one of these tags (any case) is never indexed                     |
|-------------------------------------------------------------------|-----------------------------------------------------------------------------------|
| [`DERIVED_TAGS`](_autosummary/annals.records.html.md#annals.records.DERIVED_TAGS)     | overviews and combined files                                                      |
| [`METADATA_KEYS`](_autosummary/annals.records.html.md#annals.records.METADATA_KEYS)    | the record fields that are filters in the index (`ir`'s `metadata_keys`)          |
| [`MAX_TEXT_CHARS`](_autosummary/annals.records.html.md#annals.records.MAX_TEXT_CHARS)   | a text is cut to this many characters, so one huge document cannot swamp an index |

### Functions

| [`is_withheld`](_autosummary/annals.records.html.md#annals.records.is_withheld)(meta, owner[, skip])          | Whether a document keeps out of an index or a token's reach: tagged with one of `skip` (any case) by the owner or, still, by the publisher.   |
|--------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------------------------------------------------------|
| [`records`](_autosummary/annals.records.html.md#annals.records.records)(\*[, target, to, skip_tags, ...]) | One dict per indexable document: `id`, `text` and the [`METADATA_KEYS`](_autosummary/annals.records.html.md#annals.records.METADATA_KEYS).                         |

### annals.records.DERIVED_TAGS *= frozenset({'combined', 'overview'})*

overviews and combined files

* **Type:**
  the tags of documents made from other documents

### annals.records.DFLT_SKIP_TAGS *= frozenset({'noindex', 'private'})*

a document with one of these tags (any case) is never indexed

### annals.records.MAX_TEXT_CHARS *= 2000000*

a text is cut to this many characters, so one huge document cannot swamp an index

### annals.records.METADATA_KEYS *= ('title', 'url', 'kind', 'session', 'tags', 'created', 'updated')*

the record fields that are filters in the index (`ir`’s `metadata_keys`)

### annals.records.is_withheld(meta, owner, skip=frozenset({'noindex', 'private'}))

Whether a document keeps out of an index or a token’s reach: tagged with one of `skip`
(any case) by the owner or, still, by the publisher. `owner` is the owner’s tag store.

* **Return type:**
  [`bool`](https://docs.python.org/3/builtins/functions.html#bool)

### annals.records.records(, target=None, to=None, skip_tags=frozenset({'noindex', 'private'}), include_derived=False)

One dict per indexable document: `id`, `text` and the [`METADATA_KEYS`](_autosummary/annals.records.html.md#annals.records.METADATA_KEYS).

`target` / `to` choose the store as `annals ls` does (default: the configured one).
`tags` is one comma-separated string, since an index filters on scalars.

* **Return type:**
  [`Iterator`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Iterator)[[`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)]


# _autosummary/annals.references.html.md

# annals.references

The references of documents, extracted and combined, in three forms.

A document’s references are the body of its references section: a markdown heading named
“References”, “Sources”, “Bibliography”, “Works cited” or “Citations” (any level, any case),
down to the next heading of the same or a higher level. Three forms, each text in, text out:

- `grouped` (the default): one `###` section per document holding its references as
  they are, under `## References for <title>`;
- `deduped`: every entry once, its citation number removed, as one bulleted list;
- `urls`: every web address once, one per line and nothing else, the form a notebook
  (Gemini Notebook, formerly NotebookLM) accepts as pasted website sources.

```pycon
>>> doc = '''# Bees
... Text [1].
... ## REFERENCES
... 1. [Hive life](https://bees.org/hive). 2024.
... [2] Smith J. Pollen, <https://pollen.net/a>
... ## Appendix
... not a reference https://no.org
... '''
>>> reference_sections(doc)
['1. [Hive life](https://bees.org/hive). 2024.\n[2] Smith J. Pollen, <https://pollen.net/a>']
>>> [strip_citation_number(e) for e in reference_entries(reference_sections(doc)[0])]
['[Hive life](https://bees.org/hive). 2024.', 'Smith J. Pollen, <https://pollen.net/a>']
>>> print(combine_references([("Bees", [doc]), ("Wasps", ["no references here"])],
...                          title="Insects", form="urls"), end="")
https://bees.org/hive
https://pollen.net/a
```

The mechanism knows nothing of the store: [`doc_reference_texts()`](_autosummary/annals.references.html.md#annals.references.doc_reference_texts) is the bridge that
reads a set of documents through a `read(doc_id, rel)` callable, so the owner’s API and,
later, a share can use it alike.

### Module Attributes

| [`REFERENCE_HEADINGS`](_autosummary/annals.references.html.md#annals.references.REFERENCE_HEADINGS)   | section names that hold references (a heading's text starts with one of them)   |
|-----------------------------------------------------------------------|---------------------------------------------------------------------------------|

### Functions

| [`collect`](_autosummary/annals.references.html.md#annals.references.collect)(docs, \*, read, title[, form])       | The references of `docs` (their meta) in `form`, with the counts the page shows.             |
|-----------------------------------------------------------------------------------------------|----------------------------------------------------------------------------------------------|
| [`combine_references`](_autosummary/annals.references.html.md#annals.references.combine_references)(items, \*, title[, form]) | `items` (a title and the texts of its pages) as their references in `form`.                  |
| [`doc_reference_texts`](_autosummary/annals.references.html.md#annals.references.doc_reference_texts)(docs, \*, read[, skip])  | `(title, texts)` for each of `docs` (`(meta, files)` pairs): its markdown pages' text.       |
| [`reference_entries`](_autosummary/annals.references.html.md#annals.references.reference_entries)(section)                   | The entries of a references section: each numbered or bulleted item, with its wrapped lines. |
| [`reference_sections`](_autosummary/annals.references.html.md#annals.references.reference_sections)(text)                     | The body of each references section of a markdown text, as written (blank edges trimmed).    |
| [`strip_citation_number`](_autosummary/annals.references.html.md#annals.references.strip_citation_number)(entry)                 | `entry` without its leading number or bullet (`1.`, `[1]`, `-`).                             |
| [`url_key`](_autosummary/annals.references.html.md#annals.references.url_key)(url)                                 | What makes two addresses the same page: no fragment, no trailing slash, host in lowercase.   |
| [`urls_of`](_autosummary/annals.references.html.md#annals.references.urls_of)(text)                                | The web addresses in `text`, in order of appearance, each once as written.                   |

### annals.references.REFERENCE_HEADINGS *= ('references', 'sources', 'bibliography', 'works cited', 'citations')*

section names that hold references (a heading’s text starts with one of them)

### annals.references.collect(docs, , read, title, form='grouped')

The references of `docs` (their meta) in `form`, with the counts the page shows.

`{text, items, without, count}`: `items` documents had references, `without` had none,
`count` lines of references (`grouped`: entries; the others: output lines or addresses).
`text` is empty when none had any. Every surface (the HTTP route, `annals references`,
MCP) reads references through here.

* **Return type:**
  [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)

### annals.references.combine_references(items, , title, form='grouped')

`items` (a title and the texts of its pages) as their references in `form`.

Items with no references section are left out. An empty string means none had any.

* **Return type:**
  [`str`](https://docs.python.org/3/builtins/stdtypes.html#str)

### annals.references.doc_reference_texts(docs, \*, read, skip=(<class 'KeyError'>, <class 'OSError'>, <class 'ValueError'>))

`(title, texts)` for each of `docs` (`(meta, files)` pairs): its markdown pages’ text.

Pages come in [`numbered_first()`](_autosummary/annals.aggregate.html.md#annals.aggregate.numbered_first) order; a page `read` cannot read
(one of `skip`) is left out.

* **Return type:**
  [`Iterator`](https://docs.python.org/3/library/typing.html#typing.Iterator)[[`tuple`](https://docs.python.org/3/builtins/stdtypes.html#tuple)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`list`](https://docs.python.org/3/builtins/stdtypes.html#list)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str)]]]

### annals.references.reference_entries(section)

The entries of a references section: each numbered or bulleted item, with its wrapped lines.

Prose that is not an item (an “Accessed on …” note) is not an entry. A section with no
list markers at all is one entry per non-blank line.

* **Return type:**
  [`list`](https://docs.python.org/3/builtins/stdtypes.html#list)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str)]

### annals.references.reference_sections(text)

The body of each references section of a markdown text, as written (blank edges trimmed).

* **Return type:**
  [`list`](https://docs.python.org/3/builtins/stdtypes.html#list)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str)]

### annals.references.strip_citation_number(entry)

`entry` without its leading number or bullet (`1.`, `[1]`, `-`).

* **Return type:**
  [`str`](https://docs.python.org/3/builtins/stdtypes.html#str)

### annals.references.url_key(url)

What makes two addresses the same page: no fragment, no trailing slash, host in lowercase.

* **Return type:**
  [`str`](https://docs.python.org/3/builtins/stdtypes.html#str)

### annals.references.urls_of(text)

The web addresses in `text`, in order of appearance, each once as written.

* **Return type:**
  [`list`](https://docs.python.org/3/builtins/stdtypes.html#list)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str)]


# _autosummary/annals.render.html.md

# annals.render

Render markdown (and other page-like files) to html and PDF, with their images inside.

No web framework in here, so the CLI can use it as the server does. The PDF is made by
WeasyPrint from markdown-it’s HTML (raw html in the markdown is shown as text, never
interpreted). Images are embedded; audio, video, other PDFs and files become a visible link
to the resource, so the reader can open or play it. WeasyPrint is imported on first use; a
missing one is a [`annals.requirements.MissingDependency`](_autosummary/annals.requirements.html.md#annals.requirements.MissingDependency) with the install hint.

Nothing is fetched from the network: an image outside the document is a link, never loaded.
Everything WeasyPrint is allowed to load is a placeholder url (`annals-file:N`) for bytes
this module already holds (`Embedded`).

### Module Attributes

| [`PDF_IMAGE_MAX_PX`](_autosummary/annals.render.html.md#annals.render.PDF_IMAGE_MAX_PX)       | longest side of an embedded image; a 6000 px render is shrunk, a phone screenshot is not              |
|-------------------------------------------------------------------------|-------------------------------------------------------------------------------------------------------|
| [`PDF_IMAGE_MAX_BYTES`](_autosummary/annals.render.html.md#annals.render.PDF_IMAGE_MAX_BYTES)    | an image larger than this on disk is linked, not embedded                                             |
| [`PDF_IMAGE_MAX_PIXELS`](_autosummary/annals.render.html.md#annals.render.PDF_IMAGE_MAX_PIXELS)   | an image with more pixels than this is not decoded to be shrunk (a small box would run out of memory) |
| [`PDF_IMAGES_TOTAL_BYTES`](_autosummary/annals.render.html.md#annals.render.PDF_IMAGES_TOTAL_BYTES) | all embedded images of one PDF together                                                               |
| [`PDF_MAX_TEXT_BYTES`](_autosummary/annals.render.html.md#annals.render.PDF_MAX_TEXT_BYTES)     | markdown larger than this is not made into a PDF (rendering cost grows faster than size)              |

### Functions

| [`html_to_pdf`](_autosummary/annals.render.html.md#annals.render.html_to_pdf)(doc, embedder)                         | A4 PDF of the html page `doc`; the only things it may load are `embedder`'s.        |
|-----------------------------------------------------------------------------------------------------|-------------------------------------------------------------------------------------|
| [`inline_embedded`](_autosummary/annals.render.html.md#annals.render.inline_embedded)(body, embedder)                    | `body` with each placeholder url replaced by a `data:` url of its bytes.            |
| `kind_of_mime`(rel)                                                                                 |                                                                                     |
| [`markdown_to_html`](_autosummary/annals.render.html.md#annals.render.markdown_to_html)(text, \*, rel, files, ...[, ...]) | The html body of the markdown `text` (the file `rel` of a document) and its images. |
| [`markdown_to_pdf`](_autosummary/annals.render.html.md#annals.render.markdown_to_pdf)(text, \*, title, rel, files, ...)  | A titled A4 PDF of the markdown `text` with its images inside (see the module doc). |
| [`page_html`](_autosummary/annals.render.html.md#annals.render.page_html)(title, body, \*[, created, css, ...])    | A standalone html page: the `title` as the document title, then `body`.             |
| [`resolve_ref`](_autosummary/annals.render.html.md#annals.render.resolve_ref)(href, \*, rel, files)                  | The document file a relative `href` of the markdown file `rel` names, or `None`.    |

### Classes

| [`Embedder`](_autosummary/annals.render.html.md#annals.render.Embedder)(\*[, max_total])   | The bytes a page may show, under placeholder urls, within a size budget.   |
|------------------------------------------------------------------------------|----------------------------------------------------------------------------|

### *class* annals.render.Embedder(, max_total=80000000)

Bases: [`object`](https://docs.python.org/3/builtins/functions.html#object)

The bytes a page may show, under placeholder urls, within a size budget.

WeasyPrint is only ever allowed to load these ([`html_to_pdf()`](_autosummary/annals.render.html.md#annals.render.html_to_pdf)), and an html output
gets them as `data:` urls ([`inline_embedded()`](_autosummary/annals.render.html.md#annals.render.inline_embedded)), so no render reaches the network
or the disk on its own.

#### add_image(read, rel, size)

A placeholder url for an image (shrunk), or `None` when it is too big to embed.

* **Return type:**
  [`str`](https://docs.python.org/3/builtins/stdtypes.html#str) | [`None`](https://docs.python.org/3/builtins/constants.html#None)

### annals.render.PDF_IMAGES_TOTAL_BYTES *= 80000000*

all embedded images of one PDF together

### annals.render.PDF_IMAGE_MAX_BYTES *= 25000000*

an image larger than this on disk is linked, not embedded

### annals.render.PDF_IMAGE_MAX_PIXELS *= 40000000*

an image with more pixels than this is not decoded to be shrunk (a small box would run out of memory)

### annals.render.PDF_IMAGE_MAX_PX *= 1800*

longest side of an embedded image; a 6000 px render is shrunk, a phone screenshot is not

### annals.render.PDF_MAX_TEXT_BYTES *= 400000*

markdown larger than this is not made into a PDF (rendering cost grows faster than size)

### annals.render.html_to_pdf(doc, embedder)

A4 PDF of the html page `doc`; the only things it may load are `embedder`’s.

* **Return type:**
  [`bytes`](https://docs.python.org/3/builtins/stdtypes.html#bytes)

### annals.render.inline_embedded(body, embedder)

`body` with each placeholder url replaced by a `data:` url of its bytes.

* **Return type:**
  [`str`](https://docs.python.org/3/builtins/stdtypes.html#str)

### annals.render.markdown_to_html(text, , rel, files, open_file, file_url, embedder=None, read_bytes=None, list_unreferenced=True)

The html body of the markdown `text` (the file `rel` of a document) and its images.

Images the document holds are embedded (placeholder urls in the returned
[`Embedder`](_autosummary/annals.render.html.md#annals.render.Embedder)); other files become links, shown as media rows; external images are
never fetched. Raw html in the markdown is text, not markup. `read_bytes(rel)` reads
an image the way the caller allows (a share filters svg text); `list_unreferenced=False`
leaves out the “More in this document” rows (when the document’s other files are
sections of a combined output of their own).

* **Return type:**
  [`tuple`](https://docs.python.org/3/builtins/stdtypes.html#tuple)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`Embedder`](_autosummary/annals.render.html.md#annals.render.Embedder)]

### annals.render.markdown_to_pdf(text, , title, rel, files, open_file, file_url, created='')

A titled A4 PDF of the markdown `text` with its images inside (see the module doc).

* **Return type:**
  [`bytes`](https://docs.python.org/3/builtins/stdtypes.html#bytes)

### annals.render.page_html(title, body, , created='', css='', heading=True)

A standalone html page: the `title` as the document title, then `body`.

`css` styles it on screen (a PDF brings its own); with it the page also gets a
viewport, so a phone shows it at its own width. `heading=False` leaves the title out
of the body (the text starts with its own).

* **Return type:**
  [`str`](https://docs.python.org/3/builtins/stdtypes.html#str)

### annals.render.resolve_ref(href, , rel, files)

The document file a relative `href` of the markdown file `rel` names, or `None`.

Absolute urls, paths that leave the document and files not in `files` are `None`.

* **Return type:**
  [`str`](https://docs.python.org/3/builtins/stdtypes.html#str) | [`None`](https://docs.python.org/3/builtins/constants.html#None)


# _autosummary/annals.requirements.html.md

# annals.requirements

Optional dependencies, checked where they are needed and explained when they are missing.

annals installs light: a heavy library (WeasyPrint for PDFs, pypdf for joining them,
markdownify for html to markdown) is imported only when the conversion that needs it runs,
and a missing one is a [`MissingDependency`](_autosummary/annals.requirements.html.md#annals.requirements.MissingDependency) that says which conversion needed it and
the exact command that fixes it, never a bare `ImportError` from deep inside a library.

```pycon
>>> check_requirements("json", what="anything")        # present: returns quietly
>>> try:
...     check_requirements("no_such_module_xyz", what="Combining into PDF")
... except MissingDependency as e:
...     print(str(e).splitlines()[0])
Combining into PDF needs no_such_module_xyz, which is not installed.
```

The pip name and the hint for a module are in [`PACKAGES`](_autosummary/annals.requirements.html.md#annals.requirements.PACKAGES), so a new optional library is
one entry there.

### Module Attributes

| [`DFLT_EXTRA`](_autosummary/annals.requirements.html.md#annals.requirements.DFLT_EXTRA)   | the extra of annals that installs everything a conversion may need   |
|---------------------------------------------------------------|----------------------------------------------------------------------|
| [`PACKAGES`](_autosummary/annals.requirements.html.md#annals.requirements.PACKAGES)     | module name -> (pip name, system hint or `""`)                       |

### Functions

| [`check_requirements`](_autosummary/annals.requirements.html.md#annals.requirements.check_requirements)(\*modules, what[, extra])   | Raise [`MissingDependency`](_autosummary/annals.requirements.html.md#annals.requirements.MissingDependency) unless every one of `modules` is installed.             |
|-------------------------------------------------------------------------------------------------|----------------------------------------------------------------------------------------------------------------------------------|
| [`import_lazily`](_autosummary/annals.requirements.html.md#annals.requirements.import_lazily)(name, \*, what[, extra])         | The module `name`, imported now; a failure to import it is a [`MissingDependency`](_autosummary/annals.requirements.html.md#annals.requirements.MissingDependency). |
| [`missing_modules`](_autosummary/annals.requirements.html.md#annals.requirements.missing_modules)(modules)                       | The `modules` that cannot be imported, found without importing them.                                                             |

### Exceptions

| [`MissingDependency`](_autosummary/annals.requirements.html.md#annals.requirements.MissingDependency)(modules, \*, what[, extra])   | A library an operation needs is not installed (the message says how to install it).   |
|--------------------------------------------------------------------------------------------------|---------------------------------------------------------------------------------------|

### annals.requirements.DFLT_EXTRA *= 'pdf'*

the extra of annals that installs everything a conversion may need

### *exception* annals.requirements.MissingDependency(modules, , what, extra='pdf')

Bases: [`RuntimeError`](https://docs.python.org/3/builtins/exceptions.html#RuntimeError)

A library an operation needs is not installed (the message says how to install it).

### annals.requirements.PACKAGES *: [dict](https://docs.python.org/3/builtins/stdtypes.html#dict)[[str](https://docs.python.org/3/builtins/stdtypes.html#str), [tuple](https://docs.python.org/3/builtins/stdtypes.html#tuple)[[str](https://docs.python.org/3/builtins/stdtypes.html#str), [str](https://docs.python.org/3/builtins/stdtypes.html#str)]]* *= {'PIL': ('pillow', ''), 'markdown_it': ('markdown-it-py', ''), 'markdownify': ('markdownify', ''), 'pdfdol': ('pdfdol', ''), 'playwright': ('playwright', 'Then fetch its browser: playwright install chromium'), 'pypdf': ('pypdf', ''), 'weasyprint': ('weasyprint', 'It also needs the Pango library (Debian/Ubuntu: apt install libpango-1.0-0).')}*

module name -> (pip name, system hint or `""`)

### annals.requirements.check_requirements(\*modules, what, extra='pdf')

Raise [`MissingDependency`](_autosummary/annals.requirements.html.md#annals.requirements.MissingDependency) unless every one of `modules` is installed.

Cheap (nothing is imported), so a caller checks everything a job will use *before* it
starts, and fails at once instead of half way.

* **Return type:**
  [`None`](https://docs.python.org/3/builtins/constants.html#None)

### annals.requirements.import_lazily(name, , what, extra='pdf')

The module `name`, imported now; a failure to import it is a [`MissingDependency`](_autosummary/annals.requirements.html.md#annals.requirements.MissingDependency).

A library that is installed but cannot load (WeasyPrint without Pango raises
`OSError`) is reported the same way.

### annals.requirements.missing_modules(modules)

The `modules` that cannot be imported, found without importing them.

* **Return type:**
  [`list`](https://docs.python.org/3/builtins/stdtypes.html#list)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str)]


# _autosummary/annals.search.html.md

# annals.search

How the catalog answers a query: the search strategies.

A strategy is a callable `(query, rows, text_of) -> rows`: given every listed row (the
catalog has already listed them and overlaid the owner’s tags) and a way to get an item’s
full text, it returns the rows that match, best first, each with a `snippet` of the
text around the match and, when it ranks, a `score` (higher is better). The catalog
takes one as its `search` keyword ([`annals.catalog.Catalog`](_autosummary/annals.catalog.html.md#annals.catalog.Catalog)), so a smarter one
(semantic, hybrid, an agent that rewrites the query) plugs in at the same place.

Two ship here:

* [`IndexedSearch`](_autosummary/annals.search.html.md#annals.search.IndexedSearch), the default when the data root is on this machine: a SQLite
  FTS5 index kept on disk (`cache/search/index.sqlite` under the data root). Each query
  brings it up to date first, re-reading only items whose stamp changed (their listed
  fields, and the `stamp` a source gives, else their time and size),
  so the first query after a restart costs one pass over the texts and every later one a
  few milliseconds. Matching is by word prefix with English stemming (`rate` finds
  “rates” and “rated”, not “separate”), every word required, ranked by BM25 with the
  title weighted most.
* [`scan_search()`](_autosummary/annals.search.html.md#annals.search.scan_search), the index-free fallback (a remote data root, tests): every word
  must appear as a substring of the title, tags, session, excerpt, id or full text;
  newest first, as listed.

### Module Attributes

| [`SNIPPET_CHARS`](_autosummary/annals.search.html.md#annals.search.SNIPPET_CHARS)   | characters of context on each side of the first match, in a snippet                  |
|------------------------------------------------------------------|--------------------------------------------------------------------------------------|
| [`SNIPPET_TOKENS`](_autosummary/annals.search.html.md#annals.search.SNIPPET_TOKENS)  | tokens in an index snippet (FTS5's own window)                                       |
| [`SNIPPET_ROWS`](_autosummary/annals.search.html.md#annals.search.SNIPPET_ROWS)    | the best rows that get a snippet (each costs ~5 ms); the rest show their excerpt.    |
| [`MAX_RESULTS`](_autosummary/annals.search.html.md#annals.search.MAX_RESULTS)     | the most rows a ranked query returns; the page shows a few dozen at a time           |
| [`DFLT_WEIGHTS`](_autosummary/annals.search.html.md#annals.search.DFLT_WEIGHTS)    | column weights for BM25, in the order of `_COLUMNS` (the title matters most)         |
| [`INDEX_DIR`](_autosummary/annals.search.html.md#annals.search.INDEX_DIR)       | where index files live, under the data root (`<name>.sqlite`)                        |
| [`SCHEMA_VERSION`](_autosummary/annals.search.html.md#annals.search.SCHEMA_VERSION)  | an old index is rebuilt                                                              |
| [`WINDOW_CHARS`](_autosummary/annals.search.html.md#annals.search.WINDOW_CHARS)    | characters of the body kept around the match for rows past `snippet_rows`            |
| [`SYNC_BATCH`](_autosummary/annals.search.html.md#annals.search.SYNC_BATCH)      | rows indexed per write transaction, so a first build never holds the lock for long   |
| [`SQL_VARS`](_autosummary/annals.search.html.md#annals.search.SQL_VARS)        | bound variables per statement (SQLite's default limit is far above; this stays safe) |

### Functions

| [`default_search`](_autosummary/annals.search.html.md#annals.search.default_search)(data_root, \*[, name])    | The index `<data root>/cache/search/<name>.sqlite` when the data root is on this machine, else the scan.   |
|-------------------------------------------------------------------------------------------|------------------------------------------------------------------------------------------------------------|
| [`fts_query`](_autosummary/annals.search.html.md#annals.search.fts_query)(q)                             | A user's words as an FTS5 query: every word required, each a prefix.                                       |
| [`query_words`](_autosummary/annals.search.html.md#annals.search.query_words)(q)                           | The words of a query, lowercased: `"Data  Rates"` -> `["data", "rates"]`.                                  |
| [`scan_search`](_autosummary/annals.search.html.md#annals.search.scan_search)(query, rows, text_of)        | Every word a substring of the row's fields or full text; rows kept in their order.                         |
| [`snippet_around`](_autosummary/annals.search.html.md#annals.search.snippet_around)(text, words, \*[, width]) | The text around the first occurrence of any of `words`, on one line.                                       |

### Classes

| [`IndexedSearch`](_autosummary/annals.search.html.md#annals.search.IndexedSearch)([path, weights, max_results, ...])   | A SQLite FTS5 index of every row's fields and text, synced per query by stamp.   |
|-----------------------------------------------------------------------------------------------------|----------------------------------------------------------------------------------|
| [`SearchStrategy`](_autosummary/annals.search.html.md#annals.search.SearchStrategy)(\*args, \*\*kwargs)                 | `(query, rows, text_of) -> matching rows, best first`.                           |

### annals.search.DFLT_WEIGHTS *= (10.0, 5.0, 2.0, 1.0, 1.0)*

column weights for BM25, in the order of `_COLUMNS` (the title matters most)

### annals.search.INDEX_DIR *= 'cache/search'*

where index files live, under the data root (`<name>.sqlite`)

### *class* annals.search.IndexedSearch(path=':memory:', , weights=(10.0, 5.0, 2.0, 1.0, 1.0), max_results=500, snippet_tokens=24, snippet_rows=60)

Bases: [`object`](https://docs.python.org/3/builtins/functions.html#object)

A SQLite FTS5 index of every row’s fields and text, synced per query by stamp.

`path` is the index file (made on first use; `":memory:"` keeps it in memory).
`weights` are BM25’s per-column weights (title, tags, session/id/source, excerpt,
text). `max_results` caps a ranked answer; the best `snippet_rows` carry FTS5’s
snippet, the rest a cheaper window of text around the query’s longest word. Safe
across threads (one sync at a time: queries that arrive during a sync wait for it
rather than redo it) and across processes sharing the file (two web workers): every
write is one short `BEGIN IMMEDIATE` transaction. If the index fails (a locked or
damaged file), a query falls back to [`scan_search()`](_autosummary/annals.search.html.md#annals.search.scan_search) rather than fail.

#### forget(key)

Drop an item from the index (it is gone for good).

* **Return type:**
  [`None`](https://docs.python.org/3/builtins/constants.html#None)

#### sync(rows, text_of)

(Re)index the rows whose stamp changed; returns how many.

Nothing is dropped here: a query only ever answers with the rows it was given, so
an item listed elsewhere (in the bin, behind a hiding store, or gone) simply does
not come back. [`forget()`](_autosummary/annals.search.html.md#annals.search.IndexedSearch.forget) drops an item for good.

* **Return type:**
  [`int`](https://docs.python.org/3/builtins/functions.html#int)

### annals.search.MAX_RESULTS *= 500*

the most rows a ranked query returns; the page shows a few dozen at a time

### annals.search.SCHEMA_VERSION *= '3'*

an old index is rebuilt

* **Type:**
  bumped when the schema or what is indexed changes

### annals.search.SNIPPET_CHARS *= 90*

characters of context on each side of the first match, in a snippet

### annals.search.SNIPPET_ROWS *= 60*

the best rows that get a snippet (each costs ~5 ms); the rest show their excerpt.
One page of the list (the page’s `LIST_PAGE`).

### annals.search.SNIPPET_TOKENS *= 24*

tokens in an index snippet (FTS5’s own window)

### annals.search.SQL_VARS *= 500*

bound variables per statement (SQLite’s default limit is far above; this stays safe)

### annals.search.SYNC_BATCH *= 200*

rows indexed per write transaction, so a first build never holds the lock for long

### *class* annals.search.SearchStrategy(\*args, \*\*kwargs)

Bases: [`Protocol`](https://docs.python.org/3/library/typing.html#typing.Protocol)

`(query, rows, text_of) -> matching rows, best first`.

`rows` are what the reader may see (a strategy never answers with anything else);
`text_of(row)` reads an item’s full text. A strategy that keeps state about items
may also have `forget(key)`, which the catalog calls when an item is gone for good.

### annals.search.WINDOW_CHARS *= 90*

characters of the body kept around the match for rows past `snippet_rows`

### annals.search.default_search(data_root, , name='index')

The index `<data root>/cache/search/<name>.sqlite` when the data root is on this
machine, else the scan.

* **Return type:**
  [`SearchStrategy`](_autosummary/annals.search.html.md#annals.search.SearchStrategy)

### annals.search.fts_query(q)

A user’s words as an FTS5 query: every word required, each a prefix.

Each word is quoted, so FTS5 syntax typed by the user (`AND`, `-`, `:`, quotes)
is searched for as text, never run as an operator. Control characters are dropped,
and so is a word with no letter or digit (the tokenizer would drop it anyway, and an
empty phrase matches nothing), so a query of only punctuation is no query.

```pycon
>>> fts_query('data rates')
'"data"* "rates"*'
>>> fts_query('a"b NOT')
'"a""b"* "not"*'
>>> fts_query('  ... - *')
''
```

* **Return type:**
  [`str`](https://docs.python.org/3/builtins/stdtypes.html#str)

### annals.search.query_words(q)

The words of a query, lowercased: `"Data  Rates"` -> `["data", "rates"]`.

* **Return type:**
  [`list`](https://docs.python.org/3/builtins/stdtypes.html#list)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str)]

### annals.search.scan_search(query, rows, text_of)

Every word a substring of the row’s fields or full text; rows kept in their order.

The full text is read only for rows whose fields lack a word.

* **Return type:**
  [`list`](https://docs.python.org/3/builtins/stdtypes.html#list)[[`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)]

### annals.search.snippet_around(text, words, , width=90)

The text around the first occurrence of any of `words`, on one line.

```pycon
>>> snippet_around("alpha beta gamma", ["beta"], width=6)
'alpha beta g…'
```

* **Return type:**
  [`str`](https://docs.python.org/3/builtins/stdtypes.html#str)


# _autosummary/annals.sessions.html.md

# annals.sessions

The sessions that made a document: each one’s name and the link that opens it.

A document’s meta carries them as `sessions`, a list of `{"name": ..., "url": ...}`
in the order they first worked on it: the session that published it, then each session
that published a new version (`annals publish --replace`). A group shows the sessions of
its documents. The link is a claude.ai link (`https://claude.ai/code/<bridge session id>`),
which only the owner can open; it is provenance, like `source` and `artifact`, so it is
never part of the document’s own content and leaves with the meta: a share or a room shows
an allowlist of meta fields that does not name it.

```pycon
>>> sessions_of({"source": {"session": "b2", "session_url": "https://claude.ai/code/session_01X"}})
[{'name': 'b2', 'url': 'https://claude.ai/code/session_01X'}]
>>> merged_sessions([{"name": "a", "url": ""}], [{"name": "a", "url": "https://claude.ai/code/s"}, {"name": "b", "url": ""}])
[{'name': 'a', 'url': 'https://claude.ai/code/s'}, {'name': 'b', 'url': ''}]
```

### Module Attributes

| [`SESSION_URL_TEMPLATE`](_autosummary/annals.sessions.html.md#annals.sessions.SESSION_URL_TEMPLATE)   | the claude.ai link of a session, from its Remote Control (bridge) session id                                           |
|-------------------------------------------------------------------------|------------------------------------------------------------------------------------------------------------------------|
| [`BRIDGE_ENV_VAR`](_autosummary/annals.sessions.html.md#annals.sessions.BRIDGE_ENV_VAR)         | its Remote Control session id                                                                                          |
| [`MAX_SESSIONS`](_autosummary/annals.sessions.html.md#annals.sessions.MAX_SESSIONS)           | the first, and the latest ones (a living page republished by a new session every day would otherwise grow without end) |
| [`MAX_READ`](_autosummary/annals.sessions.html.md#annals.sessions.MAX_READ)               | the most entries read from a meta written elsewhere, before merging                                                    |

### Functions

| [`checked_sessions`](_autosummary/annals.sessions.html.md#annals.sessions.checked_sessions)(sessions, check_url)      | `sessions` with each link `check_url` refuses (it raises `ValueError`) emptied: a meta written by another publisher is checked again before a page shows its links.   |
|---------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| [`merged_sessions`](_autosummary/annals.sessions.html.md#annals.sessions.merged_sessions)(\*lists[, limit])          | The sessions of `lists` in order, one entry each: the same link, or the same name when one of the two has no link, is the same session (the link is kept).            |
| [`session_names`](_autosummary/annals.sessions.html.md#annals.sessions.session_names)(meta)                        | The names of the sessions that made `meta`'s document (for `ls --session`).                                                                                           |
| [`session_url_from_env`](_autosummary/annals.sessions.html.md#annals.sessions.session_url_from_env)([env, var, template]) | The claude.ai link of the Claude Code session this process runs in, or `""`.                                                                                          |
| [`sessions_of`](_autosummary/annals.sessions.html.md#annals.sessions.sessions_of)(meta)                          | The sessions that made the document `meta` describes (see the module doc).                                                                                            |

### annals.sessions.BRIDGE_ENV_VAR *= 'CLAUDE_CODE_BRIDGE_SESSION_ID'*

its Remote Control session id

* **Type:**
  the variable Claude Code sets in a session’s shell

### annals.sessions.MAX_READ *= 200*

the most entries read from a meta written elsewhere, before merging

### annals.sessions.MAX_SESSIONS *= 12*

the first, and the latest ones (a living page
republished by a new session every day would otherwise grow without end)

* **Type:**
  the most sessions a document keeps

### annals.sessions.SESSION_URL_TEMPLATE *= 'https://claude.ai/code/{bridge_id}'*

the claude.ai link of a session, from its Remote Control (bridge) session id

### annals.sessions.checked_sessions(sessions, check_url)

`sessions` with each link `check_url` refuses (it raises `ValueError`) emptied:
a meta written by another publisher is checked again before a page shows its links.

* **Return type:**
  [`list`](https://docs.python.org/3/builtins/stdtypes.html#list)[[`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)]

### annals.sessions.merged_sessions(\*lists, limit=12)

The sessions of `lists` in order, one entry each: the same link, or the same name
when one of the two has no link, is the same session (the link is kept). At most
`limit`: the first session and the latest ones.

```pycon
>>> [s["name"] for s in merged_sessions([{"name": str(i), "url": ""} for i in range(20)], limit=4)]
['0', '17', '18', '19']
```

* **Return type:**
  [`list`](https://docs.python.org/3/builtins/stdtypes.html#list)[[`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)]

### annals.sessions.session_names(meta)

The names of the sessions that made `meta`’s document (for `ls --session`).

* **Return type:**
  [`set`](https://docs.python.org/3/builtins/stdtypes.html#set)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str)]

### annals.sessions.session_url_from_env(env=None, , var='CLAUDE_CODE_BRIDGE_SESSION_ID', template='https://claude.ai/code/{bridge_id}')

The claude.ai link of the Claude Code session this process runs in, or `""`.

```pycon
>>> session_url_from_env({"CLAUDE_CODE_BRIDGE_SESSION_ID": "session_01X"})
'https://claude.ai/code/session_01X'
>>> session_url_from_env({})
''
```

* **Return type:**
  [`str`](https://docs.python.org/3/builtins/stdtypes.html#str)

### annals.sessions.sessions_of(meta)

The sessions that made the document `meta` describes (see the module doc).

A meta written before `sessions` existed names its one session in `source`.

* **Return type:**
  [`list`](https://docs.python.org/3/builtins/stdtypes.html#list)[[`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)]


# _autosummary/annals.share.html.md

# annals.share

Share links: one document (or a group) behind a public, unguessable, revocable link.

A share is a record under the data root, `shares/<token>.json`, written through the
same [`annals.target.Target`](_autosummary/annals.target.html.md#annals.target.Target) as the documents, so `annals share` works over ssh
exactly like `annals publish`. The record is the whole contract; the owner’s API, the
page’s Share button, the CLI and the public share server (`annals.share_api`) are
surfaces over it:

```default
{
 "token": "<22 url-safe chars, 128 random bits>",
 "title": "...", "created": "<iso>",
 "root": {"kind": "doc" | "group", "id": "<id>"},
 "docs": {"<doc id>": ["<file>", ...], ...},   # what the link may reach, and only that
 "expires": "<iso>" | null,
 "password": "scrypt$..." | null,               # a hash; the password is never stored
 "revoked": "<iso>" | null                       # a tombstone: a revoked link is a 404
}
```

`docs` is the scope. Every request of the public server is checked against it, never
against what the link was made from: a file not listed is a 404 even when it sits beside
the shared page, and a page or a link of the shared text that points outside the scope is
removed before the text leaves the server ([`filter_refs()`](_autosummary/annals.share.html.md#annals.share.filter_refs)), so the recipient sees
neither private ids nor private paths.

The link itself (the token, the password gate, expiry, revocation) is a
`caplinks.CapabilityLinks` over these records; what is annals’ own is the scope
and the filtering. The password is a gate on the link, not an account: anyone who knows
both may read. It is hashed (stdlib `scrypt` by default, the `hasher` seam takes
argon2), and a correct one earns an HMAC cookie keyed by that hash, so changing the
password or revoking the link ends every open session.

### Module Attributes

| [`ANNALS_ID`](_autosummary/annals.share.html.md#annals.share.ANNALS_ID)   | an annals id (doc or group) as [`annals.store.mk_id()`](_autosummary/annals.store.html.md#annals.store.mk_id) makes them   |
|--------------------------------------------------------------|--------------------------------------------------------------------------------------------------------------------------------------|

### Functions

| [`annals_urls`](_autosummary/annals.share.html.md#annals.share.annals_urls)(text)                                 | The absolute links to annals document and group pages in `text`, once each, in order.                                                                                                                                  |
|----------------------------------------------------------------------------------------------------|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| [`dir_of`](_autosummary/annals.share.html.md#annals.share.dir_of)(rel)                                       | The directory part of a relative path, with its trailing slash (`""` at the top).                                                                                                                                      |
| [`filter_refs`](_autosummary/annals.share.html.md#annals.share.filter_refs)(text, kind, \*, files, shared[, ...]) | `text` with every reference outside the share removed (or rewritten).                                                                                                                                                  |
| [`ref_decider`](_autosummary/annals.share.html.md#annals.share.ref_decider)(\*, from_dir, files, shared[, ...])   | `url -> new url` (often the same) or `None` (remove it).                                                                                                                                                               |
| [`references`](_autosummary/annals.share.html.md#annals.share.references)(text, kind, \*[, from_dir])            | What a page points at: files of its document, and annals pages (by id).                                                                                                                                                |
| [`remove_unshared_ids`](_autosummary/annals.share.html.md#annals.share.remove_unshared_ids)(text, shared)                 | `text` with every annals id that `shared` does not map replaced by a marker.                                                                                                                                           |
| [`resolve_rel`](_autosummary/annals.share.html.md#annals.share.resolve_rel)(url[, from_dir])                      | A relative url as a file path inside the document, or `None` if it is not one.                                                                                                                                         |
| [`share_links`](_autosummary/annals.share.html.md#annals.share.share_links)(base, token)                          | The forms of one share link: `page` (people, and fetchers that run no script), `markdown` (agents: the whole share as one text) and `pdf` (images inside, or for an upload); empty when no share server is configured. |
| [`share_url`](_autosummary/annals.share.html.md#annals.share.share_url)(base, token)                            | The link a recipient opens, or `None` when no share server is configured.                                                                                                                                              |

### Classes

| [`Shares`](_autosummary/annals.share.html.md#annals.share.Shares)(store, \*[, hasher, clock])   | Create, read, list and revoke shares of a `DocStore`'s documents.   |
|---------------------------------------------------------------------------------------|---------------------------------------------------------------------|

### annals.share.ANNALS_ID *= '\\\\d{8}-\\\\d{6}-[a-z0-9]+(?:-[a-z0-9]+)\*'*

an annals id (doc or group) as [`annals.store.mk_id()`](_autosummary/annals.store.html.md#annals.store.mk_id) makes them

### *class* annals.share.Shares(store, \*, hasher=None, clock=<function now_utc>)

Bases: [`object`](https://docs.python.org/3/builtins/functions.html#object)

Create, read, list and revoke shares of a `DocStore`’s documents.

What a share reaches (its scope) is decided here; the link itself is `links`, a
`caplinks.CapabilityLinks` over the records under `shares/`. `hasher`
hashes link passwords (stdlib scrypt by default); `clock` returns the current UTC
`datetime` (tests pin it).

#### check_password(record, password)

Whether `password` opens `record`.

* **Return type:**
  [`bool`](https://docs.python.org/3/builtins/functions.html#bool)

#### create(ref, , include=None, exclude=(), password=None, expires='7d', title=None, files_of=None)

Share a document or a group (`ref` is its id); return the record (no hash).

A document is shared with all its files unless `include` names some (the page
itself always goes); `include` may also name annals pages the document links
to, which then open inside the share. A group is shared with all its documents
unless `include` names some. `exclude` removes files (or a group’s documents).
A linked page goes with the files it shows. `expires` is anything
`parse_expires()` reads, 7 days by default (`"never"` for none); `password`
gates the link (at least `caplinks.MIN_PASSWORD_LEN` characters).
`files_of(meta)` narrows which files of each of a group’s documents go (all of
them by default; [`annals.notebook.source_scope()`](_autosummary/annals.notebook.html.md#annals.notebook.source_scope) keeps only the pages and
what they show).

* **Return type:**
  [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)

#### included(record)

`(meta, files)` for each document of a share still there, in the share’s order.

`files` are the document’s files the share includes; a document deleted or in
the bin since the link was made is left out.

* **Return type:**
  [`list`](_autosummary/annals.share.html.md#annals.share.Shares.list)[[`tuple`](https://docs.python.org/3/builtins/stdtypes.html#tuple)[[`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict), [`list`](_autosummary/annals.share.html.md#annals.share.Shares.list)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str)]]]

#### list(, all=False)

Every share, newest first, without hashes; `all` adds revoked and expired.

* **Return type:**
  [`list`](_autosummary/annals.share.html.md#annals.share.Shares.list)[[`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)]

#### record(token)

The stored record (hash included), revoked or not; `None` if there is none.

* **Return type:**
  [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict) | [`None`](https://docs.python.org/3/builtins/constants.html#None)

#### resources(doc_id)

What the Share dialog offers for a document: its files, and the pages it links.

`{"main", "files": [{"rel", "kind", "size", "referenced"}], "pages": [{"id",
"title", "kind"}]}`. `referenced` marks the files the page itself shows or
links; `pages` are the other annals documents its text links to.

* **Return type:**
  [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)

#### revoke(token)

End a link now (idempotent). The record stays, as a tombstone, for the list.

* **Return type:**
  [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)

#### status(token)

`("ok" | "expired" | "missing", record)`; a revoked link is `missing`.

* **Return type:**
  [`tuple`](https://docs.python.org/3/builtins/stdtypes.html#tuple)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict) | [`None`](https://docs.python.org/3/builtins/constants.html#None)]

#### unlock_value(record)

The cookie value a correct password earns.

* **Return type:**
  [`str`](https://docs.python.org/3/builtins/stdtypes.html#str)

#### unlocked(record, value, , max_age_s)

Whether a cookie value is a live unlock of this record (no password: always).

* **Return type:**
  [`bool`](https://docs.python.org/3/builtins/functions.html#bool)

### annals.share.annals_urls(text)

The absolute links to annals document and group pages in `text`, once each, in order.

Any host: which annals a link belongs to is the reader’s config to decide
([`annals.config.link_target()`](_autosummary/annals.config.html.md#annals.config.link_target)). Relative links (`../d/<id>`) are not found:
a document’s own links to its annals are absolute, as `annals publish` prints them.

```pycon
>>> annals_urls("see **[map](https://a.example.io/annals/d/20261119-075018-the-map-4a58)**, "
...             "<https://b.example.com/annals/g/20261117-163049-set?f=x> and "
...             "https://a.example.io/annals/d/20261119-075018-the-map-4a58 again")
['https://a.example.io/annals/d/20261119-075018-the-map-4a58', 'https://b.example.com/annals/g/20261117-163049-set']
```

* **Return type:**
  [`list`](https://docs.python.org/3/builtins/stdtypes.html#list)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str)]

### annals.share.dir_of(rel)

The directory part of a relative path, with its trailing slash (`""` at the top).

* **Return type:**
  [`str`](https://docs.python.org/3/builtins/stdtypes.html#str)

### annals.share.filter_refs(text, kind, , files, shared, from_dir='', private_hosts=())

`text` with every reference outside the share removed (or rewritten).

`files` are the document’s files the share includes; `shared(id)` maps an annals
id to where the recipient opens it (in scope) or `None` (not shared). A markdown
image out of scope disappears, a link keeps its words; an html attribute goes; a bare
annals url becomes “(link not shared)” and a bare annals id “(not shared)”. The text
of the page itself is the owner’s: only references are touched. An absolute url on
one of `private_hosts` (the owner’s own) goes too, whatever its path. Every kind of
text is filtered (markdown, html, plain text, svg): only markdown syntax is markdown’s.
Best effort by design, and the second line of defence: the share server answers 404
for anything outside the share however the text names it.

* **Return type:**
  [`str`](https://docs.python.org/3/builtins/stdtypes.html#str)

### annals.share.ref_decider(, from_dir, files, shared, private_hosts=())

`url -> new url` (often the same) or `None` (remove it).

The one rule of what a shared text may point at; [`filter_refs()`](_autosummary/annals.share.html.md#annals.share.filter_refs) applies it to
the references it finds in text, [`annals.notebook`](_autosummary/annals.notebook.html.md#module-annals.notebook) to a rendered page’s links.

* **Return type:**
  [`Callable`](https://docs.python.org/3/library/typing.html#typing.Callable)[[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str)], [`str`](https://docs.python.org/3/builtins/stdtypes.html#str) | [`None`](https://docs.python.org/3/builtins/constants.html#None)]

### annals.share.references(text, kind, , from_dir='')

What a page points at: files of its document, and annals pages (by id).

`{"files": [rel, ...], "ids": [annals id, ...]}`, each in first-seen order; it
feeds the Share dialog, which offers them to the owner.

* **Return type:**
  [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)

### annals.share.remove_unshared_ids(text, shared)

`text` with every annals id that `shared` does not map replaced by a marker.

* **Return type:**
  [`str`](https://docs.python.org/3/builtins/stdtypes.html#str)

### annals.share.resolve_rel(url, from_dir='')

A relative url as a file path inside the document, or `None` if it is not one.

```pycon
>>> resolve_rel("img/a.png?x=1#y", "notes/")
'notes/img/a.png'
>>> resolve_rel("../../etc/passwd") is None, resolve_rel("https://x.org/a") is None
(True, True)
```

* **Return type:**
  [`str`](https://docs.python.org/3/builtins/stdtypes.html#str) | [`None`](https://docs.python.org/3/builtins/constants.html#None)

### annals.share.share_links(base, token)

The forms of one share link: `page` (people, and fetchers that run no script),
`markdown` (agents: the whole share as one text) and `pdf` (images inside, or for an
upload); empty when no share server is configured. [`annals.share_page`](_autosummary/annals.share_page.html.md#module-annals.share_page).

* **Return type:**
  [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`str`](https://docs.python.org/3/builtins/stdtypes.html#str)]

### annals.share.share_url(base, token)

The link a recipient opens, or `None` when no share server is configured.

* **Return type:**
  [`str`](https://docs.python.org/3/builtins/stdtypes.html#str) | [`None`](https://docs.python.org/3/builtins/constants.html#None)


# _autosummary/annals.share_page.html.md

# annals.share_page

A share link’s page with its text in it, and no script, so every reader can read it.

A share link used to answer with a shell: a `<title>` and an empty `<div>` that the
viewer’s script filled, with an html document inside a frame. NotebookLM made a
twenty-minute audio overview of such a link’s title. Its fetcher does run script, so it saw
the viewer’s buttons, but a group shows only titles there and a frame is not read. So the
page a link opens is now the shared text itself, rendered on the server under the rules
every shared text already follows, and nothing on it runs. The owner asked for exactly that:
a person only needs the document. The script viewer (galleries, players, downloads) is one
link away, `<link>/?viewer`.

The same share also answers as one Markdown file and one PDF, with the same token, expiry
and revocation (the routes are `annals.share_api`’s); the page names them in
`<link rel="alternate">` and in a line at its top:

```default
<link>/                 the page: every shared document's text (a group's, in order)
<link>/d/<id>           the page of one document of the share
<link>/share.md         the whole share as one Markdown file
<link>/share.pdf        the whole share as one PDF (images included)
<link>/d/<id>.md|.pdf   one document of it
<link>/?viewer          the script viewer, as before
```

What goes in the page, per document: its markdown and html files (the notebook sources of
[`annals.notebook`](_autosummary/annals.notebook.html.md#module-annals.notebook), numbered files first), markdown rendered with links and images
made safe by [`annals.notebook.render_source_body()`](_autosummary/annals.notebook.html.md#annals.notebook.render_source_body), html reduced to its structure and
words by [`annals.combine.html_body()`](_autosummary/annals.combine.html.md#annals.combine.html_body) with a link to the page as designed; for a
document with no text, its images; its audio and video with the browser’s own players;
then links to its other files. Past [`STATIC_MAX_BYTES`](_autosummary/annals.share_page.html.md#annals.share_page.STATIC_MAX_BYTES) of text or
[`STATIC_MAX_FILES`](_autosummary/annals.share_page.html.md#annals.share_page.STATIC_MAX_FILES) files, the remaining files and documents are links to their own pages, so a large group still answers quickly and every
document stays reachable. A document that *is* an html page ([`designed_page()`](_autosummary/annals.share_page.html.md#annals.share_page.designed_page)) is
served as itself at its own link, filtered and sandboxed as `/raw` serves it, with a
`<base>` ([`with_base()`](_autosummary/annals.share_page.html.md#annals.share_page.with_base)) so its images and styles load.

### Module Attributes

| [`STATIC_MAX_BYTES`](_autosummary/annals.share_page.html.md#annals.share_page.STATIC_MAX_BYTES)      | the page's text stops growing past this many bytes of html; later documents are links                                                         |
|------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------------------------------------------------------|
| [`STATIC_MAX_FILES`](_autosummary/annals.share_page.html.md#annals.share_page.STATIC_MAX_FILES)      | the text files rendered into one page at most; the rest are links (a page is made on every request, and anyone holding the link may make one) |
| [`STATIC_FILE_MAX_BYTES`](_autosummary/annals.share_page.html.md#annals.share_page.STATIC_FILE_MAX_BYTES) | a document's file larger than this is linked, not put in the page                                                                             |
| [`STATIC_MAX_IMAGES`](_autosummary/annals.share_page.html.md#annals.share_page.STATIC_MAX_IMAGES)     | images shown for a document without text (a gallery folder); the rest are listed                                                              |
| [`STATIC_MAX_PLAYERS`](_autosummary/annals.share_page.html.md#annals.share_page.STATIC_MAX_PLAYERS)    | audio and video players in one document's page; the rest are listed                                                                           |
| [`DESCRIPTION_CHARS`](_autosummary/annals.share_page.html.md#annals.share_page.DESCRIPTION_CHARS)     | the length of the page's `<meta name="description">`                                                                                          |
| [`ALTERNATES`](_autosummary/annals.share_page.html.md#annals.share_page.ALTERNATES)            | path suffix, media type, label                                                                                                                |
| [`SHARE_FILE`](_autosummary/annals.share_page.html.md#annals.share_page.SHARE_FILE)            | the share's whole text, at `<link>/<SHARE_FILE>.<ext>`                                                                                        |
| [`VIEWER_PARAM`](_autosummary/annals.share_page.html.md#annals.share_page.VIEWER_PARAM)          | `<link>/?viewer` opens the script viewer (galleries, players, downloads) instead                                                              |

### Functions

| [`alternate_links`](_autosummary/annals.share_page.html.md#annals.share_page.alternate_links)(link[, doc_id])              | The `<link rel="alternate">` tags of [`alternate_urls()`](_autosummary/annals.share_page.html.md#annals.share_page.alternate_urls), for the `<head>`.                              |
|-----------------------------------------------------------------------------------------------|--------------------------------------------------------------------------------------------------------------------------------------------------------|
| [`alternate_urls`](_autosummary/annals.share_page.html.md#annals.share_page.alternate_urls)(link[, doc_id])               | `(url, media type, label)` of the share (or of one document of it) as files.                                                                           |
| [`description_of`](_autosummary/annals.share_page.html.md#annals.share_page.description_of)(content, \*[, skip, n])       | The first `n` characters of the page's words (the title and alternates line left out).                                                                 |
| [`designed_page`](_autosummary/annals.share_page.html.md#annals.share_page.designed_page)(meta, files)                   | The html file a document's page *is*, when it is one, else `None`.                                                                                     |
| [`page_body`](_autosummary/annals.share_page.html.md#annals.share_page.page_body)(docs, \*, title, read_text, scope) | The page's content and its description: `(html, plain text of ~280 chars)`.                                                                            |
| [`with_base`](_autosummary/annals.share_page.html.md#annals.share_page.with_base)(page, href)                        | `page` with `<base href>` as its first element, so its relative references (images, styles, its other pages) resolve where the share serves its files. |

### Classes

| [`ShareScope`](_autosummary/annals.share_page.html.md#annals.share_page.ShareScope)(link, shared_ids[, root_id, ...])   | What a page of one share may show and link to.   |
|-------------------------------------------------------------------------------------------------|--------------------------------------------------|

### annals.share_page.ALTERNATES *= (('md', 'text/plain', 'Markdown'), ('pdf', 'application/pdf', 'PDF'))*

path suffix, media type, label

* **Type:**
  the alternate representations of a share

### annals.share_page.DESCRIPTION_CHARS *= 280*

the length of the page’s `<meta name="description">`

### annals.share_page.SHARE_FILE *= 'share'*

the share’s whole text, at `<link>/<SHARE_FILE>.<ext>`

### annals.share_page.STATIC_FILE_MAX_BYTES *= 2000000*

a document’s file larger than this is linked, not put in the page

### annals.share_page.STATIC_MAX_BYTES *= 1500000*

the page’s text stops growing past this many bytes of html; later documents are links

### annals.share_page.STATIC_MAX_FILES *= 40*

the text files rendered into one page at most; the rest are links (a page is made on
every request, and anyone holding the link may make one)

### annals.share_page.STATIC_MAX_IMAGES *= 60*

images shown for a document without text (a gallery folder); the rest are listed

### annals.share_page.STATIC_MAX_PLAYERS *= 20*

audio and video players in one document’s page; the rest are listed

### *class* annals.share_page.ShareScope(link, shared_ids, root_id='', private_hosts=())

Bases: [`object`](https://docs.python.org/3/builtins/functions.html#object)

What a page of one share may show and link to.

`link` is the share’s address (root-relative is fine: a fetcher resolves it against
the page), `shared_ids` the documents it includes, `root_id` its group (`""` for
a document share), `private_hosts` the owner’s hosts, never linked to.

#### shared(annals_id)

The share’s page for an annals id it includes, else `None`.

* **Return type:**
  [`str`](https://docs.python.org/3/builtins/stdtypes.html#str) | [`None`](https://docs.python.org/3/builtins/constants.html#None)

### annals.share_page.VIEWER_PARAM *= 'viewer'*

`<link>/?viewer` opens the script viewer (galleries, players, downloads) instead

### annals.share_page.alternate_links(link, doc_id=None)

The `<link rel="alternate">` tags of [`alternate_urls()`](_autosummary/annals.share_page.html.md#annals.share_page.alternate_urls), for the `<head>`.

* **Return type:**
  [`str`](https://docs.python.org/3/builtins/stdtypes.html#str)

### annals.share_page.alternate_urls(link, doc_id=None)

`(url, media type, label)` of the share (or of one document of it) as files.

* **Return type:**
  [`list`](https://docs.python.org/3/builtins/stdtypes.html#list)[[`tuple`](https://docs.python.org/3/builtins/stdtypes.html#tuple)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`str`](https://docs.python.org/3/builtins/stdtypes.html#str)]]

### annals.share_page.description_of(content, , skip='', n=280)

The first `n` characters of the page’s words (the title and alternates line left out).

* **Return type:**
  [`str`](https://docs.python.org/3/builtins/stdtypes.html#str)

### annals.share_page.designed_page(meta, files)

The html file a document’s page *is*, when it is one, else `None`.

Such a document is served as itself at its link (filtered and sandboxed, as `/raw`
serves it): a person sees it as designed, and a fetcher, even one that runs script,
reads it at the top level rather than inside a frame it does not open.

* **Return type:**
  [`str`](https://docs.python.org/3/builtins/stdtypes.html#str) | [`None`](https://docs.python.org/3/builtins/constants.html#None)

### annals.share_page.page_body(docs, , title, read_text, scope, doc_id=None, viewer_url=None, max_bytes=None)

The page’s content and its description: `(html, plain text of ~280 chars)`.

`docs` are the `(meta, files)` pairs to show, in order (one, for a document’s
page); `read_text(doc_id, rel)` reads a file as it is on disk (the shared-text
filters are applied here). `doc_id` names the document a `/d/<id>` page is for,
which picks the alternates the page offers; `viewer_url` is where the script viewer
opens it. `max_bytes`: [`STATIC_MAX_BYTES`](_autosummary/annals.share_page.html.md#annals.share_page.STATIC_MAX_BYTES).

* **Return type:**
  [`tuple`](https://docs.python.org/3/builtins/stdtypes.html#tuple)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`str`](https://docs.python.org/3/builtins/stdtypes.html#str)]

### annals.share_page.with_base(page, href)

`page` with `<base href>` as its first element, so its relative references
(images, styles, its other pages) resolve where the share serves its files.

The page’s own `<base>` and referrer `<meta>` go: either would send its requests,
or the link, elsewhere. The tag goes right after the doctype, where the parser puts it
in the head whatever comes later (a `<head>` written in a comment, say).

* **Return type:**
  [`bytes`](https://docs.python.org/3/builtins/stdtypes.html#bytes)


# _autosummary/annals.sources.html.md

# annals.sources

Item sources: everything the page lists, wherever it lives, as rows of one shape.

A *source* is a named, read-mostly collection of items. Two kinds exist:

* [`PublishedSource`](_autosummary/annals.sources.html.md#annals.sources.PublishedSource): the documents agents published (a [`annals.store.DocStore`](_autosummary/annals.store.html.md#annals.store.DocStore)).
* [`FolderSource`](_autosummary/annals.sources.html.md#annals.sources.FolderSource): a folder of files owned by someone else, read in place and never
  written (the crowsnest ledgers, and any other personal folder later). Its items are the
  folder’s files, keyed by their path relative to the folder.

Every source yields the same row shape, which the page lists, searches and filters:

`key`      `<source>:<id>`, unique across sources (the API’s item id)
`source`   the source’s name; `id` the item’s id within it
`title`, `kind` (see [`annals.store.kind_of()`](_autosummary/annals.store.html.md#annals.store.kind_of)), `session` (who wrote it)
`time`     ISO 8601, UTC: publication time, or a file’s last modification
`size`, `tags` (the item’s own; the catalog overlays the owner’s), `excerpt`

A *group of sources* is a source set that is not fixed: [`HostMirrors`](_autosummary/annals.sources.html.md#annals.sources.HostMirrors) turns each
`<root>/<machine>/` folder into a source of its own, found again on every listing, so a
machine that starts pushing appears without a restart.

Sources are plain objects with a few methods (the [`Source`](_autosummary/annals.sources.html.md#annals.sources.Source) protocol), so a new kind
of folder is a new class or a new keyword argument, never a change to the API.

### Module Attributes

| [`SOURCE_NAME_RE`](_autosummary/annals.sources.html.md#annals.sources.SOURCE_NAME_RE)        | a source name is a url segment and part of every item key                            |
|------------------------------------------------------------------------|--------------------------------------------------------------------------------------|
| [`RESERVED_SOURCE_NAMES`](_autosummary/annals.sources.html.md#annals.sources.RESERVED_SOURCE_NAMES) | names the page uses for its own routes (`/all`, `/trash`) or the published documents |
| [`HOSTS_PREFIX`](_autosummary/annals.sources.html.md#annals.sources.HOSTS_PREFIX)          | `ledger-hosts=hosts:/srv/ledger-hosts`                                               |

### Functions

| [`as_source`](_autosummary/annals.sources.html.md#annals.sources.as_source)(name, spec)    | A source from a source, or from a folder path (read in place as a [`FolderSource`](_autosummary/annals.sources.html.md#annals.sources.FolderSource)); `hosts:<path>` is a [`HostMirrors`](_autosummary/annals.sources.html.md#annals.sources.HostMirrors) (one source per machine folder in it).   |
|---------------------------------------------------------------------------|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| [`check_source_name`](_autosummary/annals.sources.html.md#annals.sources.check_source_name)(name)  | `name` if it can name an extra source; `ValueError` saying why not otherwise.                                                                                                                                                                               |
| [`file_stamp`](_autosummary/annals.sources.html.md#annals.sources.file_stamp)(st)           | What says a file changed: its inode, mtime and ctime (nanoseconds) and size.                                                                                                                                                                                |
| `iso_utc`(ts)                                                             |                                                                                                                                                                                                                                                             |
| [`list_meta`](_autosummary/annals.sources.html.md#annals.sources.list_meta)(meta)          | A listing row: the meta without its per-file tables (a folder can hold thousands).                                                                                                                                                                          |
| `mk_key`(source, item_id)                                                 |                                                                                                                                                                                                                                                             |
| [`parse_sources_spec`](_autosummary/annals.sources.html.md#annals.sources.parse_sources_spec)(spec) | `"ledgers=~/x, notes=/y"` -> `{"ledgers": "~/x", "notes": "/y"}` (the env form).                                                                                                                                                                            |
| [`split_key`](_autosummary/annals.sources.html.md#annals.sources.split_key)(key)           | `"ledgers:a/b.md"` -> `("ledgers", "a/b.md")`; `KeyError` when malformed.                                                                                                                                                                                   |
| [`top_level_name`](_autosummary/annals.sources.html.md#annals.sources.top_level_name)(rel)      | Who wrote a file in a folder of per-session files: `a.md` -> `a`, `b/c.md` -> `b`.                                                                                                                                                                          |
| [`with_thumb`](_autosummary/annals.sources.html.md#annals.sources.with_thumb)(meta)         | Add `thumb` (the first image, main file first) and fix pre-media kinds.                                                                                                                                                                                     |

### Classes

| [`FolderSource`](_autosummary/annals.sources.html.md#annals.sources.FolderSource)(root, \*, name[, title, ...])   | A folder of files, read in place and never written, as a `Mapping` of rows.          |
|-----------------------------------------------------------------------------------------------|--------------------------------------------------------------------------------------|
| [`HostMirrors`](_autosummary/annals.sources.html.md#annals.sources.HostMirrors)(root, \*, name[, title])         | A folder of per-machine mirrors (`ledger-hosts/<machine>/`) as one source each.      |
| [`MirrorSource`](_autosummary/annals.sources.html.md#annals.sources.MirrorSource)(root, \*, name, machine, ...)   | One machine's mirror of a folder (`<root>/<machine>/`), with who and when.           |
| [`PublishedSource`](_autosummary/annals.sources.html.md#annals.sources.PublishedSource)(store, \*[, title, ...])     | The documents agents published, as rows (a view over a `DocStore`).                  |
| [`Source`](_autosummary/annals.sources.html.md#annals.sources.Source)(\*args, \*\*kwargs)                   | What the catalog needs from a source of items.                                       |
| [`SourceGroup`](_autosummary/annals.sources.html.md#annals.sources.SourceGroup)()                                | A set of sources that is looked at again each time: `sources()` -> `{name: Source}`. |

### *class* annals.sources.FolderSource(root, \*, name, title=None, exclude=('.\*', '_\_pycache_\_', '\*.pyc', '\*.pyo'), session_of=<function top_level_name>)

Bases: [`Mapping`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Mapping)

A folder of files, read in place and never written, as a `Mapping` of rows.

Keys are paths relative to `root` (`"annals.md"`, `"cw-liaise/design.md"`), values
listing rows. The folder is walked on every listing (a stat per file, cheap for
hundreds), and a file is re-read only when its size or mtime changed. Hidden files and
caches are skipped (`exclude`, the same patterns a directory publish skips), and so
is anything that resolves outside `root`.

`session_of(rel)` names who wrote a file; the default suits a folder of per-session
files and sub-folders ([`top_level_name()`](_autosummary/annals.sources.html.md#annals.sources.top_level_name)).

#### file_path(rel)

The file on disk; `KeyError` if it is absent, hidden, or escapes the root.

Only the canonical spelling of a path is accepted (`a/b.md`, not `./a/b.md`,
`a//b.md` or `a/b.md/`), so one file has one key.

* **Return type:**
  [`Path`](https://docs.python.org/3/library/pathlib.html#pathlib.Path)

#### text(rel)

The file’s text (cached until it changes); `""` for binaries and huge files.

* **Return type:**
  [`str`](https://docs.python.org/3/builtins/stdtypes.html#str)

### annals.sources.HOSTS_PREFIX *= 'hosts:'*

`ledger-hosts=hosts:/srv/ledger-hosts`

* **Type:**
  the spelling of a group of host mirrors in `ANNALS_SOURCES`

### *class* annals.sources.HostMirrors(root, , name, title=None)

Bases: [`SourceGroup`](_autosummary/annals.sources.html.md#annals.sources.SourceGroup)

A folder of per-machine mirrors (`ledger-hosts/<machine>/`) as one source each.

`name` prefixes the source names (`<name>-<machine>`, the machine slugged); each
machine’s source is a [`MirrorSource`](_autosummary/annals.sources.html.md#annals.sources.MirrorSource), kept between listings so its caches last.
A hidden folder, a plain file, or a symlink out of `root` is not a machine.

#### sources()

`{source name: MirrorSource}` for each machine folder there now, by machine.

* **Return type:**
  [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`Source`](_autosummary/annals.sources.html.md#annals.sources.Source)]

### *class* annals.sources.MirrorSource(root, , name, machine, base_title, \*\*kw)

Bases: [`FolderSource`](_autosummary/annals.sources.html.md#annals.sources.FolderSource)

One machine’s mirror of a folder (`<root>/<machine>/`), with who and when.

The folder name is the machine. `_mirror.json` (`{"machine", "pushed_at", "files"}`,
written by whoever pushes) says when it was last pushed; each row carries `machine` and
`pushed_at` (read at every listing), so a ledger is never read as current on a machine
that stopped pushing. Items are keyed inside this source, so two machines holding the
same session name stay two items.

#### info()

What the page shows about the mirror: `{machine, pushed_at}`.

* **Return type:**
  [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)

#### pushed_at()

The mirror’s last push as `_mirror.json` says it (`""` when it does not, when
the file is not a small regular file, or when the time is not valid or is in the future).

* **Return type:**
  [`str`](https://docs.python.org/3/builtins/stdtypes.html#str)

### *class* annals.sources.PublishedSource(store, , title='Published', max_cached_texts=512)

Bases: [`object`](https://docs.python.org/3/builtins/functions.html#object)

The documents agents published, as rows (a view over a `DocStore`).

Always named `published`: the page links its items to `/d/<id>`.

#### forget(item_id)

Drop what is cached for a document that is gone for good (purged).

* **Return type:**
  [`None`](https://docs.python.org/3/builtins/constants.html#None)

### annals.sources.RESERVED_SOURCE_NAMES *= frozenset({'all', 'published', 'trash'})*

names the page uses for its own routes (`/all`, `/trash`) or the published documents

### annals.sources.SOURCE_NAME_RE *= re.compile('^[a-z0-9][a-z0-9_-]{0,63}$')*

a source name is a url segment and part of every item key

### *class* annals.sources.Source(\*args, \*\*kwargs)

Bases: [`Protocol`](https://docs.python.org/3/library/typing.html#typing.Protocol)

What the catalog needs from a source of items.

#### item(item_id)

One row plus what the page shows (`text` for text kinds). `KeyError` if absent.

* **Return type:**
  [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)

#### rows(, trash=False)

Listing rows, newest first.

* **Return type:**
  [`list`](https://docs.python.org/3/builtins/stdtypes.html#list)[[`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)]

#### text(item_id)

The item’s full text for search (`""` when it has none).

* **Return type:**
  [`str`](https://docs.python.org/3/builtins/stdtypes.html#str)

### *class* annals.sources.SourceGroup

Bases: [`object`](https://docs.python.org/3/builtins/functions.html#object)

A set of sources that is looked at again each time: `sources()` -> `{name: Source}`.

### annals.sources.as_source(name, spec)

A source from a source, or from a folder path (read in place as a [`FolderSource`](_autosummary/annals.sources.html.md#annals.sources.FolderSource));
`hosts:<path>` is a [`HostMirrors`](_autosummary/annals.sources.html.md#annals.sources.HostMirrors) (one source per machine folder in it).

* **Return type:**
  [`Source`](_autosummary/annals.sources.html.md#annals.sources.Source) | [`HostMirrors`](_autosummary/annals.sources.html.md#annals.sources.HostMirrors)

### annals.sources.check_source_name(name)

`name` if it can name an extra source; `ValueError` saying why not otherwise.

* **Return type:**
  [`str`](https://docs.python.org/3/builtins/stdtypes.html#str)

### annals.sources.file_stamp(st)

What says a file changed: its inode, mtime and ctime (nanoseconds) and size.

The mtime alone is not enough: a rewrite of the same size within one timestamp tick,
or a sync that keeps mtimes, would look unchanged.

* **Return type:**
  [`tuple`](https://docs.python.org/3/builtins/stdtypes.html#tuple)[[`int`](https://docs.python.org/3/builtins/functions.html#int), [`int`](https://docs.python.org/3/builtins/functions.html#int), [`int`](https://docs.python.org/3/builtins/functions.html#int), [`int`](https://docs.python.org/3/builtins/functions.html#int)]

### annals.sources.list_meta(meta)

A listing row: the meta without its per-file tables (a folder can hold thousands).

* **Return type:**
  [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)

### annals.sources.parse_sources_spec(spec)

`"ledgers=~/x, notes=/y"` -> `{"ledgers": "~/x", "notes": "/y"}` (the env form).

* **Return type:**
  [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`str`](https://docs.python.org/3/builtins/stdtypes.html#str)]

### annals.sources.split_key(key)

`"ledgers:a/b.md"` -> `("ledgers", "a/b.md")`; `KeyError` when malformed.

* **Return type:**
  [`tuple`](https://docs.python.org/3/builtins/stdtypes.html#tuple)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`str`](https://docs.python.org/3/builtins/stdtypes.html#str)]

### annals.sources.top_level_name(rel)

Who wrote a file in a folder of per-session files: `a.md` -> `a`, `b/c.md` -> `b`.

* **Return type:**
  [`str`](https://docs.python.org/3/builtins/stdtypes.html#str)

### annals.sources.with_thumb(meta)

Add `thumb` (the first image, main file first) and fix pre-media kinds.

Documents published before media kinds existed say `file` for an image or a video;
their kind is recomputed from the main file so they show inline too.

* **Return type:**
  [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)


# _autosummary/annals.store.html.md

# annals.store

The document store: a flat set of documents, tags, groups and a recycle bin, as plain files.

Layout under the data root (local or remote, see [`annals.target`](_autosummary/annals.target.html.md#module-annals.target)):

```default
docs/<id>/meta.json         one document: metadata
docs/<id>/<main file>       its content (index.html, report.md, ...), plus any assets
docs/<id>/.versions/<n>/    an earlier version, whole (its own meta.json and files)
docs/<id>.r<stamp>-<hex>/   a replacement not applied yet (``publish(replace=<id>)``)
trash/<id>/...              the same shape; the recycle bin is a move
groups/<gid>.json           a named, ordered list of document ids with its own URL
```

Flat on purpose: agents from many corpora do not share a hierarchy, and every placement
decision costs tokens. Tags and groups carry the structure. Ids are time-sortable and
readable (`20261003-203301-starwars-theme-report-3f9a`), so a listing is already in
publication order and a URL says what it points to.

Plain files, written whole, because the same tree is written by rsync from another machine
and read by the server; there is no index to keep consistent.

Living documents (one link that stays current) are a replace: the new files are written as
a *pending* replacement next to the document, never over it, and whoever reads the store
applies it ([`DocStore.settle()`](_autosummary/annals.store.html.md#annals.store.DocStore.settle)): the current files move under `.versions/<n>/` and
the replacement takes the id. Writing beside rather than over is what lets a replace travel
through an outbox (a directory another machine pulls and empties): the pending directory is
just another new directory to pull, and the store on the reading side applies it. Applying
is a sequence of renames, each claimed atomically, so two readers never apply the same
replacement twice and nothing is ever deleted.

### Module Attributes

| [`HEAD_CHARS`](_autosummary/annals.store.html.md#annals.store.HEAD_CHARS)         | how much of a file is read to find its title and excerpt                                                                                                                                                                                                                                |
|---------------------------------------------------------------------|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| [`DFLT_EXCLUDE`](_autosummary/annals.store.html.md#annals.store.DFLT_EXCLUDE)       | hidden files, caches, compiled python                                                                                                                                                                                                                                                   |
| [`VERSIONS`](_autosummary/annals.store.html.md#annals.store.VERSIONS)           | a published folder's own content skips hidden names, and a document that carries one anyway is refused)                                                                                                                                                                                 |
| [`VERSION_SEP`](_autosummary/annals.store.html.md#annals.store.VERSION_SEP)        | `<id>@<n>` names version `n` of a document; `@` is not an id character                                                                                                                                                                                                                  |
| [`PENDING_SEP`](_autosummary/annals.store.html.md#annals.store.PENDING_SEP)        | `<id>.r<stamp>-<hex>` is a pending replacement of `<id>`                                                                                                                                                                                                                                |
| [`LOCK_PREFIX`](_autosummary/annals.store.html.md#annals.store.LOCK_PREFIX)        | `<root>/.lock-<id>/` is held while a replacement of `<id>` is applied; it is also the working directory, holding `next` (the replacement) and `old` (the version being archived) between renames, and `lock.json` (what a recovery needs to know)                                       |
| [`LOCK_STALE_S`](_autosummary/annals.store.html.md#annals.store.LOCK_STALE_S)       | its work is finished or undone                                                                                                                                                                                                                                                          |
| [`GROUP_LOCK_WAIT_S`](_autosummary/annals.store.html.md#annals.store.GROUP_LOCK_WAIT_S)  | how long a group write waits for another writer of the same group, and how often it looks                                                                                                                                                                                               |
| [`GROUP_LOCK_STALE_S`](_autosummary/annals.store.html.md#annals.store.GROUP_LOCK_STALE_S) | a group lock is held for milliseconds, so one older than this is a dead holder's (the lock's note carries it, so recovery on another machine knows)                                                                                                                                     |
| [`MAX_GROUP_TITLE`](_autosummary/annals.store.html.md#annals.store.MAX_GROUP_TITLE)    | the longest title a group may have (a longer one is refused, not cut)                                                                                                                                                                                                                   |
| [`SWAP_WAIT_S`](_autosummary/annals.store.html.md#annals.store.SWAP_WAIT_S)        | a reader that misses a document being swapped waits for it this long, in steps                                                                                                                                                                                                          |
| [`SWAP_STEP_S`](_autosummary/annals.store.html.md#annals.store.SWAP_STEP_S)        | a reader that misses a document being swapped waits for it this long, in steps                                                                                                                                                                                                          |
| [`INCOMING_PREFIX`](_autosummary/annals.store.html.md#annals.store.INCOMING_PREFIX)    | a replacement is written under this hidden name, then renamed into place whole                                                                                                                                                                                                          |
| [`RESERVED`](_autosummary/annals.store.html.md#annals.store.RESERVED)           | the store's bookkeeping lives there                                                                                                                                                                                                                                                     |
| [`ARTIFACT_HOSTS`](_autosummary/annals.store.html.md#annals.store.ARTIFACT_HOSTS)     | the interactive version of a page lives there, and the document's page links out to it                                                                                                                                                                                                  |
| [`THUMB_CACHE`](_autosummary/annals.store.html.md#annals.store.THUMB_CACHE)        | where the page's thumbnails are cached, under the data root (beside the documents, never inside one)                                                                                                                                                                                    |
| [`SIDECAR_SUFFIXES`](_autosummary/annals.store.html.md#annals.store.SIDECAR_SUFFIXES)   | timed text published beside an audio file, named `<stem><suffix>` in the same folder (the suffix in any case): a transcript (`.cues.json`, `.vtt` or `.srt`) and chapters (`.chapters.vtt`).                                                                                            |
| [`PROVENANCE_KEYS`](_autosummary/annals.store.html.md#annals.store.PROVENANCE_KEYS)    | `source` (the publisher's host, cwd, session and `--meta` keys), `artifact` (a claude.ai link only the owner can open) and `sessions` (the sessions that made it, with their claude.ai links: [`annals.sessions`](_autosummary/annals.sessions.html.md#module-annals.sessions)). |
| [`ROOM_META_KEYS`](_autosummary/annals.store.html.md#annals.store.ROOM_META_KEYS)     | everything a reader's page needs, and nothing else, so a field added later stays out until named here                                                                                                                                                                                   |

### Functions

| [`check_artifact_url`](_autosummary/annals.store.html.md#annals.store.check_artifact_url)(url, \*[, hosts])   | `url` if it is an `https` link to one of `hosts` (or a subdomain), else raise.                                                                               |
|-----------------------------------------------------------------------------------------|--------------------------------------------------------------------------------------------------------------------------------------------------------------|
| [`check_id`](_autosummary/annals.store.html.md#annals.store.check_id)(doc_id)                       | Raise `ValueError` on an id that could not have come from [`mk_id()`](_autosummary/annals.store.html.md#annals.store.mk_id).                                          |
| [`clean_title`](_autosummary/annals.store.html.md#annals.store.clean_title)(title)                     | A title as the page shows it: control and invisible format characters dropped, whitespace collapsed.                                                         |
| [`is_sidecar_of`](_autosummary/annals.store.html.md#annals.store.is_sidecar_of)(path, media)             | True when `path` is timed text for `media`: `talk.vtt` or `talk.cues.json` for `talk.mp3`, in the same folder (paths compare whole), the suffix in any case. |
| [`kind_of`](_autosummary/annals.store.html.md#annals.store.kind_of)(filename)                      | The rendering kind of a file, from its extension.                                                                                                            |
| [`mk_id`](_autosummary/annals.store.html.md#annals.store.mk_id)(title, \*[, when])               | `YYYYMMDD-HHMMSS-<slug>-<4 hex>`: sortable by time, readable in a URL.                                                                                       |
| [`mk_pending_id`](_autosummary/annals.store.html.md#annals.store.mk_pending_id)(doc_id, \*[, when])      | `<id>.r<YYYYMMDDHHMMSSffffff>-<hex>`: sorts in publication order.                                                                                            |
| [`now_iso`](_autosummary/annals.store.html.md#annals.store.now_iso)()                              | UTC timestamp with second precision, the format every meta.json uses.                                                                                        |
| [`room_meta`](_autosummary/annals.store.html.md#annals.store.room_meta)(meta, \*[, keys])            | Only the fields of `meta` a room shows ([`ROOM_META_KEYS`](_autosummary/annals.store.html.md#annals.store.ROOM_META_KEYS)).                                                    |
| [`slugify`](_autosummary/annals.store.html.md#annals.store.slugify)(text, \*[, max_len])           | Lowercase ascii words joined by hyphens; empty input becomes `doc`.                                                                                          |
| [`split_version`](_autosummary/annals.store.html.md#annals.store.split_version)(doc_id)                  | `("<id>", n)` from `<id>@<n>` (version `n`), `("<id>", None)` from an id.                                                                                    |
| [`title_and_excerpt`](_autosummary/annals.store.html.md#annals.store.title_and_excerpt)(head, kind)          | A title (markdown `# h1` or html `<title>`) and a plain-text excerpt of `head`.                                                                              |
| [`without_provenance`](_autosummary/annals.store.html.md#annals.store.without_provenance)(meta, \*[, keys])   | `meta` without the keys that say where it came from.                                                                                                         |

### Classes

| [`DocStore`](_autosummary/annals.store.html.md#annals.store.DocStore)(target, \*[, settle])                    | Publish, list, read, trash, restore and group documents on a `Target`.              |
|----------------------------------------------------------------------------------------------------|-------------------------------------------------------------------------------------|
| [`GroupScopedStore`](_autosummary/annals.store.html.md#annals.store.GroupScopedStore)(store, gid, \*[, withheld, ...]) | What a read token for group `gid` may see: that group's documents, and no others.   |
| [`HidingStore`](_autosummary/annals.store.html.md#annals.store.HidingStore)(store, \*, hide)                      | The documents of `store` without those `hide(meta)` is true of, on the same target. |
| [`RoomStore`](_autosummary/annals.store.html.md#annals.store.RoomStore)(store, \*[, keys])                      | The documents of `store` as an outside audience reads them (a room).                |

### annals.store.ARTIFACT_HOSTS *= ('claude.ai',)*

the interactive
version of a page lives there, and the document’s page links out to it

* **Type:**
  hosts an artifact link (`publish(artifact=...)`) may point at

### annals.store.DFLT_EXCLUDE *= ('.\*', '_\_pycache_\_', '\*.pyc', '\*.pyo')*

hidden files, caches, compiled python

* **Type:**
  names never published from a directory

### *class* annals.store.DocStore(target, , settle=True)

Bases: [`object`](https://docs.python.org/3/builtins/functions.html#object)

Publish, list, read, trash, restore and group documents on a `Target`.

#### add_to_group(gid, doc_ids)

Append documents to an existing group, keeping order and skipping ones it has.

Each document must exist and not be in the bin; `KeyError` for a group that is not
there.

* **Return type:**
  [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)

#### doc_rel(doc_id)

The directory of a document (or of a version, `<id>@<n>`) under the data root.

* **Return type:**
  [`str`](https://docs.python.org/3/builtins/stdtypes.html#str)

#### group(gid)

One group, by id.

* **Return type:**
  [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)

#### group_docs(gid)

A group and the meta of each of its documents, in its order (missing or binned ones left out).

* **Return type:**
  [`tuple`](https://docs.python.org/3/builtins/stdtypes.html#tuple)[[`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict), [`list`](_autosummary/annals.store.html.md#annals.store.DocStore.list)[[`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)]]

#### groups_of(doc_id)

The groups a document is in, newest first, each as `{"id", "title", "n"}`.

* **Return type:**
  [`list`](_autosummary/annals.store.html.md#annals.store.DocStore.list)[[`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)]

#### holds(ref_id)

Whether a document (or a version of one) or a group with this id is here, in the bin or not.

* **Return type:**
  [`bool`](https://docs.python.org/3/builtins/functions.html#bool)

#### list(, trash=False)

Every document’s meta, last changed first (`updated`, else `created`).

Pending replacements are applied first (when this store settles). One whose
document is not here is listed under its own id, so it is never out of sight.

* **Return type:**
  [`list`](_autosummary/annals.store.html.md#annals.store.DocStore.list)[[`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)]

#### list_groups()

Every group, newest first.

* **Return type:**
  [`list`](_autosummary/annals.store.html.md#annals.store.DocStore.list)[[`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)]

#### make_group(title, doc_ids, , gid=None, live_only=True)

Create (or overwrite) a group: a titled, ordered list of documents.

The title is cleaned (control characters dropped, whitespace collapsed, at most
`MAX_GROUP_TITLE` long, not blank); repeats are dropped, keeping the first; each
document must exist and not be in the bin unless `live_only=False` (a bundle that
keeps a document later binned). `ValueError` says which rule failed. An explicit
`gid` rewrites that group, under its lock.

* **Return type:**
  [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)

#### meta(doc_id, , settle=True)

One document’s meta; `in_trash` says which side of the bin it is on.

`<id>@<n>` is version `n`: its own meta, with `version_of` naming the document.
A pending replacement, read by its own id, says `pending`. `settle=False`
skips applying pending replacements (for a hot path such as a raw file).

* **Return type:**
  [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)

#### pending(doc_id=None, , names=None)

Pending replacements (directory names), oldest first; of one document if given.

`names`: the listing of `docs/` when the caller already has it.

* **Return type:**
  [`list`](_autosummary/annals.store.html.md#annals.store.DocStore.list)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str)]

#### publish(\*sources, title=None, tags=(), source=None, text=None, filename='document.md', exclude=('.\*', '_\_pycache_\_', '\*.pyc', '\*.pyo'), replace=None, artifact=None, pdf=True, pdf_renderer='default')

Publish files (or a directory, or `text`) as ONE document; return its meta.

One markdown or html file is the common case. A directory is published whole, with
`index.html` (or the first renderable file) as the page shown. `text` publishes a
string as `filename` instead of reading sources. `exclude` lists glob patterns
skipped inside a directory (hidden files and caches by default; `()` keeps all).

`replace` (a document id) publishes a new version of that document instead of a
new document: same id, same link, the current files kept as a version. It is
written as a pending replacement and applied at once when this store settles
(otherwise where the store is read). The returned meta says `pending` until then.

`artifact` (a claude.ai artifact link, see [`check_artifact_url()`](_autosummary/annals.store.html.md#annals.store.check_artifact_url)) is the
interactive version of the page: the document’s page links out to it. A
replacement that names none keeps the document’s current one.

An html page gets its own Download PDF button, and `<stem>.pdf` printed beside
it by `pdf_renderer` unless it has one ([`annals.pagepdf`](_autosummary/annals.pagepdf.html.md#module-annals.pagepdf), which says how a
page declares or opts out). `pdf=False` leaves the page as it is.

* **Return type:**
  [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)

#### purge(doc_id)

Delete a document that is in the bin. Refuses one that is not.

* **Return type:**
  [`None`](https://docs.python.org/3/builtins/constants.html#None)

#### read_text(doc_id, rel=None)

A document’s main file (or one of its files) as text.

* **Return type:**
  [`str`](https://docs.python.org/3/builtins/stdtypes.html#str)

#### rename(doc_id, title)

Give a document a title of the owner’s choosing; a later version keeps it.

The title is cleaned as a group’s is ([`clean_title()`](_autosummary/annals.store.html.md#annals.store.clean_title)). A version or a pending
replacement is refused (rename the document). Works in the bin too. Only `title`
and `renamed` change in the stored meta, which is read again under the document’s
lock: a document that moved meanwhile (trashed, restored, purged) is a
`RuntimeError`, never a meta written where its files are not. Returns its meta.

* **Return type:**
  [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)

#### rename_group(gid, title)

Give a group a new title (cleaned as at creation); its documents stay as they are.

* **Return type:**
  [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)

#### restore(doc_id)

Move a document out of the bin (idempotent).

* **Return type:**
  [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)

#### search(query, , trash=False)

Case-insensitive match of every query word against title, tags, excerpt, source.

* **Return type:**
  [`list`](_autosummary/annals.store.html.md#annals.store.DocStore.list)[[`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)]

#### settle(doc_id=None)

Apply pending replacements (of one document, or all); return the ids replaced.

A replacement whose document is not here yet (it is still on its way, or the
document was purged) stays pending and is listed under its own id.

* **Return type:**
  [`list`](_autosummary/annals.store.html.md#annals.store.DocStore.list)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str)]

#### trash(doc_id)

Move a document into the bin (idempotent).

* **Return type:**
  [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)

#### versions(doc_id)

Every version of a document, oldest first, the current one last.

* **Return type:**
  [`list`](_autosummary/annals.store.html.md#annals.store.DocStore.list)[[`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)]

### annals.store.GROUP_LOCK_STALE_S *= 30*

a group lock is held for milliseconds, so one older than this is a dead holder’s (the
lock’s note carries it, so recovery on another machine knows)

### annals.store.GROUP_LOCK_WAIT_S *= 10*

how long a group write waits for another writer of the same group, and how often it looks

### *class* annals.store.GroupScopedStore(store, gid, \*, withheld=<function GroupScopedStore.<lambda>>, ttl_s=2.0, clock=None)

Bases: [`RoomStore`](_autosummary/annals.store.html.md#annals.store.RoomStore)

What a read token for group `gid` may see: that group’s documents, and no others.

A room’s view (nothing in the bin, no provenance) narrowed to the members of one group,
minus whatever `withheld(meta)` is true of (documents tagged `private` or
`noindex`). Every other group is absent, its title included; so is a document that
is not a member, whichever route asks. Membership is read from the group itself, at
most once per `ttl_s` seconds, so a document added to or dropped from the group
changes what the token reaches within that time.

#### group(gid)

One group, by id.

* **Return type:**
  [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)

#### list_groups()

Every group, newest first.

* **Return type:**
  [`list`](https://docs.python.org/3/builtins/stdtypes.html#list)[[`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)]

### annals.store.HEAD_CHARS *= 4000*

how much of a file is read to find its title and excerpt

### *class* annals.store.HidingStore(store, , hide)

Bases: [`DocStore`](_autosummary/annals.store.html.md#annals.store.DocStore)

The documents of `store` without those `hide(meta)` is true of, on the same target.

A hidden document is absent, not refused: it is not listed or found, [`meta()`](_autosummary/annals.store.html.md#annals.store.HidingStore.meta) raises
`KeyError` for it, its versions and its pending replacements (so whatever reads a
document through the store, its page, files, versions or a share, answers as for a
missing one), and groups read through this store leave it out. An API built over this
store therefore cannot show it anywhere, whichever route asks; [`hides()`](_autosummary/annals.store.html.md#annals.store.HidingStore.hides) lets what
keeps records of its own about documents (shares) hide those records too. Reads go
through `store`, so a subclass’s reading still applies; writes reach the same target,
and a group is always rewritten from its whole list, so hiding never deletes anything.

#### add_to_group(gid, doc_ids)

Append to the group’s whole list (the hidden ids stay in it); a hidden document
is refused as a missing one.

* **Return type:**
  [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)

#### group(gid)

One group, by id.

* **Return type:**
  [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)

#### hides(doc_id)

Whether `doc_id` is a document of the whole store that this one hides.

* **Return type:**
  [`bool`](https://docs.python.org/3/builtins/functions.html#bool)

#### list(, trash=False)

Every document’s meta, last changed first (`updated`, else `created`).

Pending replacements are applied first (when this store settles). One whose
document is not here is listed under its own id, so it is never out of sight.

* **Return type:**
  [`list`](_autosummary/annals.store.html.md#annals.store.HidingStore.list)[[`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)]

#### list_groups()

Every group, newest first.

* **Return type:**
  [`list`](_autosummary/annals.store.html.md#annals.store.HidingStore.list)[[`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)]

#### meta(doc_id, , settle=True)

One document’s meta; `in_trash` says which side of the bin it is on.

`<id>@<n>` is version `n`: its own meta, with `version_of` naming the document.
A pending replacement, read by its own id, says `pending`. `settle=False`
skips applying pending replacements (for a hot path such as a raw file).

* **Return type:**
  [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)

### annals.store.INCOMING_PREFIX *= '.incoming-'*

a replacement is written under this hidden name, then renamed into place whole

### annals.store.LOCK_PREFIX *= '.lock-'*

`<root>/.lock-<id>/` is held while a replacement of `<id>` is applied; it is also
the working directory, holding `next` (the replacement) and `old` (the version
being archived) between renames, and `lock.json` (what a recovery needs to know)

### annals.store.LOCK_STALE_S *= 600*

its work is finished or undone

* **Type:**
  a lock older than this was left by a crash

### annals.store.MAX_GROUP_TITLE *= 200*

the longest title a group may have (a longer one is refused, not cut)

### annals.store.PENDING_SEP *= '.r'*

`<id>.r<stamp>-<hex>` is a pending replacement of `<id>`

### annals.store.PROVENANCE_KEYS *= ('source', 'artifact', 'sessions')*

`source` (the publisher’s host,
cwd, session and `--meta` keys), `artifact` (a claude.ai link only the owner can
open) and `sessions` (the sessions that made it, with their claude.ai links:
[`annals.sessions`](_autosummary/annals.sessions.html.md#module-annals.sessions)). `copy` to a room drops them from what it writes.

* **Type:**
  what a document’s meta says about where it came from

### annals.store.RESERVED *= ('.versions',)*

the store’s bookkeeping lives there

* **Type:**
  names a document’s own files may not use

### annals.store.ROOM_META_KEYS *= frozenset({'created', 'excerpt', 'files', 'id', 'in_trash', 'kind', 'main', 'pdf', 'size', 'sizes', 'tags', 'title', 'updated', 'version', 'version_of', 'versions'})*

everything a
reader’s page needs, and nothing else, so a field added later stays out until named here

* **Type:**
  the fields of a document’s meta an outside audience may see (a room)

### *class* annals.store.RoomStore(store, , keys=frozenset({'created', 'excerpt', 'files', 'id', 'in_trash', 'kind', 'main', 'pdf', 'size', 'sizes', 'tags', 'title', 'updated', 'version', 'version_of', 'versions'}))

Bases: [`HidingStore`](_autosummary/annals.store.html.md#annals.store.HidingStore)

The documents of `store` as an outside audience reads them (a room).

Nothing in the bin: a binned document is absent, as in [`HidingStore`](_autosummary/annals.store.html.md#annals.store.HidingStore), so the
owner withdraws a document from a room by binning it; a group left with no document
to show is absent too (its title included). And only the fields in
[`ROOM_META_KEYS`](_autosummary/annals.store.html.md#annals.store.ROOM_META_KEYS): every meta read through this store (one, a listing, a search,
a group’s) comes without the rest, so whatever an API builds from it cannot show or
match them. Writes go to `store` unchanged. Reading may still settle a pending
replacement the publisher left, as the owner’s store does.

#### group(gid)

One group, by id.

* **Return type:**
  [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)

#### list(, trash=False)

Every document’s meta, last changed first (`updated`, else `created`).

Pending replacements are applied first (when this store settles). One whose
document is not here is listed under its own id, so it is never out of sight.

* **Return type:**
  [`list`](_autosummary/annals.store.html.md#annals.store.RoomStore.list)[[`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)]

#### list_groups()

Every group, newest first.

* **Return type:**
  [`list`](_autosummary/annals.store.html.md#annals.store.RoomStore.list)[[`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)]

#### meta(doc_id, , settle=True)

One document’s meta; `in_trash` says which side of the bin it is on.

`<id>@<n>` is version `n`: its own meta, with `version_of` naming the document.
A pending replacement, read by its own id, says `pending`. `settle=False`
skips applying pending replacements (for a hot path such as a raw file).

* **Return type:**
  [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)

### annals.store.SIDECAR_SUFFIXES *= ('.cues.json', '.chapters.vtt', '.vtt', '.srt')*

timed text published beside an audio file, named `<stem><suffix>` in the same folder
(the suffix in any case): a transcript (`.cues.json`, `.vtt` or `.srt`) and chapters
(`.chapters.vtt`). The page plays the audio with them (`app.js`’s `SIDECARS`); a
document of one audio file and its sidecars is an audio document, not a folder. (Video
is left out until its page shows them.)

### annals.store.SWAP_STEP_S *= 0.02*

a reader that misses a document being swapped waits for it this long, in steps

### annals.store.SWAP_WAIT_S *= 2.0*

a reader that misses a document being swapped waits for it this long, in steps

### annals.store.THUMB_CACHE *= 'cache/thumbs'*

where the page’s thumbnails are cached, under the data root (beside the documents, never inside one)

### annals.store.VERSIONS *= '.versions'*

a published folder’s own content
skips hidden names, and a document that carries one anyway is refused)

* **Type:**
  where a document keeps its earlier versions (hidden

### annals.store.VERSION_SEP *= '@'*

`<id>@<n>` names version `n` of a document; `@` is not an id character

### annals.store.check_artifact_url(url, , hosts=('claude.ai',))

`url` if it is an `https` link to one of `hosts` (or a subdomain), else raise.

The link is shown on the document’s page as a button, so only a plain https URL to a
known artifact host is accepted: no other scheme, no credentials, no port, a host of
dns labels only, printable ascii without quotes, angle brackets or backslashes.

* **Return type:**
  [`str`](https://docs.python.org/3/builtins/stdtypes.html#str)

### annals.store.check_id(doc_id)

Raise `ValueError` on an id that could not have come from [`mk_id()`](_autosummary/annals.store.html.md#annals.store.mk_id).

* **Return type:**
  [`str`](https://docs.python.org/3/builtins/stdtypes.html#str)

### annals.store.clean_title(title)

A title as the page shows it: control and invisible format characters dropped,
whitespace collapsed. `ValueError` when blank or longer than `MAX_GROUP_TITLE`.

* **Return type:**
  [`str`](https://docs.python.org/3/builtins/stdtypes.html#str)

### annals.store.is_sidecar_of(path, media)

True when `path` is timed text for `media`: `talk.vtt` or `talk.cues.json` for
`talk.mp3`, in the same folder (paths compare whole), the suffix in any case.

```pycon
>>> is_sidecar_of("a/talk.CHAPTERS.vtt", "a/talk.mp3"), is_sidecar_of("b/talk.vtt", "a/talk.mp3")
(True, False)
```

* **Return type:**
  [`bool`](https://docs.python.org/3/builtins/functions.html#bool)

### annals.store.kind_of(filename)

The rendering kind of a file, from its extension.

* **Return type:**
  [`str`](https://docs.python.org/3/builtins/stdtypes.html#str)

### annals.store.mk_id(title, , when=None)

`YYYYMMDD-HHMMSS-<slug>-<4 hex>`: sortable by time, readable in a URL.

* **Return type:**
  [`str`](https://docs.python.org/3/builtins/stdtypes.html#str)

### annals.store.mk_pending_id(doc_id, , when=None)

`<id>.r<YYYYMMDDHHMMSSffffff>-<hex>`: sorts in publication order.

* **Return type:**
  [`str`](https://docs.python.org/3/builtins/stdtypes.html#str)

### annals.store.now_iso()

UTC timestamp with second precision, the format every meta.json uses.

* **Return type:**
  [`str`](https://docs.python.org/3/builtins/stdtypes.html#str)

### annals.store.room_meta(meta, , keys=frozenset({'created', 'excerpt', 'files', 'id', 'in_trash', 'kind', 'main', 'pdf', 'size', 'sizes', 'tags', 'title', 'updated', 'version', 'version_of', 'versions'}))

Only the fields of `meta` a room shows ([`ROOM_META_KEYS`](_autosummary/annals.store.html.md#annals.store.ROOM_META_KEYS)).

```pycon
>>> room_meta({"id": "a", "source": {"host": "h"}, "from_pending": "p", "versions": [{"n": 1, "from_pending": "p"}]})
{'id': 'a', 'versions': [{'n': 1}]}
```

* **Return type:**
  [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)

### annals.store.slugify(text, , max_len=48)

Lowercase ascii words joined by hyphens; empty input becomes `doc`.

* **Return type:**
  [`str`](https://docs.python.org/3/builtins/stdtypes.html#str)

### annals.store.split_version(doc_id)

`("<id>", n)` from `<id>@<n>` (version `n`), `("<id>", None)` from an id.

* **Return type:**
  [`tuple`](https://docs.python.org/3/builtins/stdtypes.html#tuple)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`int`](https://docs.python.org/3/builtins/functions.html#int) | [`None`](https://docs.python.org/3/builtins/constants.html#None)]

### annals.store.title_and_excerpt(head, kind)

A title (markdown `# h1` or html `<title>`) and a plain-text excerpt of `head`.

* **Return type:**
  [`tuple`](https://docs.python.org/3/builtins/stdtypes.html#tuple)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str) | [`None`](https://docs.python.org/3/builtins/constants.html#None), [`str`](https://docs.python.org/3/builtins/stdtypes.html#str)]

### annals.store.without_provenance(meta, , keys=('source', 'artifact', 'sessions'))

`meta` without the keys that say where it came from.

```pycon
>>> without_provenance({"id": "a", "source": {"host": "h"}, "artifact": "x"})
{'id': 'a'}
```

* **Return type:**
  [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)


# _autosummary/annals.tables.html.md

# annals.tables

Scrolling, zooming tables for published html pages.

A published html page is served as written; this adds one inlined script (the page’s own
`ui/tables.js`) that wraps each data table in a horizontally scrollable, zoomable box,
and lifts a viewport meta that forbids pinch-zoom. Markdown documents get the same script
from the page itself, so both paths share one implementation.

### Functions

| [`add_table_tools`](_autosummary/annals.tables.html.md#annals.tables.add_table_tools)(html)   | `html` with the table script injected, unless it has no table or opts out.                                          |
|--------------------------------------------------------------------------|---------------------------------------------------------------------------------------------------------------------|
| [`allow_zoom`](_autosummary/annals.tables.html.md#annals.tables.allow_zoom)(html)        | `html` with pinch-zoom allowed: no `user-scalable=no` or scale limits in its viewport meta.                         |
| [`tables_version`](_autosummary/annals.tables.html.md#annals.tables.tables_version)()        | A short hash of what [`add_table_tools()`](_autosummary/annals.tables.html.md#annals.tables.add_table_tools) injects, for a page's ETag. |

### annals.tables.add_table_tools(html)

`html` with the table script injected, unless it has no table or opts out.

* **Return type:**
  [`bytes`](https://docs.python.org/3/builtins/stdtypes.html#bytes)

### annals.tables.allow_zoom(html)

`html` with pinch-zoom allowed: no `user-scalable=no` or scale limits in its viewport meta.

* **Return type:**
  [`bytes`](https://docs.python.org/3/builtins/stdtypes.html#bytes)

### annals.tables.tables_version()

A short hash of what [`add_table_tools()`](_autosummary/annals.tables.html.md#annals.tables.add_table_tools) injects, for a page’s ETag.

* **Return type:**
  [`str`](https://docs.python.org/3/builtins/stdtypes.html#str)


# _autosummary/annals.tags.html.md

# annals.tags

The owner’s tags: a `MutableMapping` from item key to tag list, kept apart from the items.

Tags the owner adds on the page are stored here, never in the items themselves: a folder
source belongs to whoever writes it (a crowsnest ledger belongs to its session), so annals
must not edit it, and a published document’s `meta.json` is the publisher’s record.
An entry, once present, is the item’s whole tag list (it replaces the item’s own tags, so
removing a tag the publisher set works too); deleting the entry falls back to them.

[`JsonTagStore`](_autosummary/annals.tags.html.md#annals.tags.JsonTagStore), the default, is one JSON file under the data root
(`<data root>/tags/tags.json`), written atomically. Any `MutableMapping[str, list[str]]`
can replace it (`mk_api(tags=...)`), e.g. a table in a database.

### Functions

| [`normalize_tags`](_autosummary/annals.tags.html.md#annals.tags.normalize_tags)(tags)   | Trimmed, single-spaced, de-duplicated (ignoring case), sorted; refuses junk.   |
|-------------------------------------------------------------------------|--------------------------------------------------------------------------------|

### Classes

| [`JsonTagStore`](_autosummary/annals.tags.html.md#annals.tags.JsonTagStore)(path)   | `{item key: [tags]}` in one JSON file (see [`annals.jsonstore.JsonFileStore`](_autosummary/annals.jsonstore.html.md#annals.jsonstore.JsonFileStore)).   |
|-----------------------------------------------------------------------|---------------------------------------------------------------------------------------------------------------------------------------------------------------|

### *class* annals.tags.JsonTagStore(path)

Bases: [`JsonFileStore`](_autosummary/annals.jsonstore.html.md#annals.jsonstore.JsonFileStore)

`{item key: [tags]}` in one JSON file (see [`annals.jsonstore.JsonFileStore`](_autosummary/annals.jsonstore.html.md#annals.jsonstore.JsonFileStore)).

Safe with several server processes on one machine; a damaged file reads as empty and is
kept aside (`tags.json.damaged`) at the next write.

#### clean(value)

The value as stored; raise `ValueError` to refuse it.

* **Return type:**
  [`list`](https://docs.python.org/3/builtins/stdtypes.html#list)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str)]

#### valid(value)

Whether a value read from the file is kept (an invalid one is logged and skipped).

* **Return type:**
  [`bool`](https://docs.python.org/3/builtins/functions.html#bool)

### annals.tags.normalize_tags(tags)

Trimmed, single-spaced, de-duplicated (ignoring case), sorted; refuses junk.

Raises `ValueError` for a tag that is not a string, is longer than `MAX_TAG_LEN`,
holds control characters, or for more than `MAX_TAGS_PER_ITEM` tags.

* **Return type:**
  [`list`](https://docs.python.org/3/builtins/stdtypes.html#list)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str)]


# _autosummary/annals.target.html.md

# annals.target

The transport seam: a document tree lands in a directory, here or on another machine.

A `Target` is the handful of filesystem verbs the store needs (put a directory, move,
remove, read and write a text file, list sub-directories, read every `meta.json` under a
directory). Two implementations:

* [`LocalTarget`](_autosummary/annals.target.html.md#annals.target.LocalTarget): a directory on this machine, plain `pathlib`/`shutil`.
* [`SshTarget`](_autosummary/annals.target.html.md#annals.target.SshTarget): `host:path` on another machine, through the system `ssh` and
  `rsync` in batch mode (no prompts, so an agent never hangs). The host is whatever the
  user’s `~/.ssh/config` resolves, so an alias such as `tw` works.

[`parse_target()`](_autosummary/annals.target.html.md#annals.target.parse_target) picks one from a string. An HTTP target (a bearer-token ingest
endpoint) is the declared replacement for the ssh one and is not built yet.

### Module Attributes

| [`RECORD_SEP`](_autosummary/annals.target.html.md#annals.target.RECORD_SEP)   | Separator between concatenated meta.json files when reading many at once over ssh.                                                  |
|---------------------------------------------------------------|-------------------------------------------------------------------------------------------------------------------------------------|
| [`META_GLOB`](_autosummary/annals.target.html.md#annals.target.META_GLOB)    | each document's meta.json                                                                                                           |
| [`LOCK_NOTE`](_autosummary/annals.target.html.md#annals.target.LOCK_NOTE)    | the note a lock directory is created with (see [`Target.make_lock()`](_autosummary/annals.target.html.md#annals.target.Target.make_lock))                 |
| [`SSH_SHARE_S`](_autosummary/annals.target.html.md#annals.target.SSH_SHARE_S)  | the several calls of one command (and the next command soon after) reuse it instead of paying a handshake each (~3 s to a far host) |

### Functions

| [`check_glob`](_autosummary/annals.target.html.md#annals.target.check_glob)(pattern)       | A glob safe to hand a remote shell unquoted: names, `*` and `/` only, no hidden part.                                                                             |
|----------------------------------------------------------------------------|-------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| [`check_rel`](_autosummary/annals.target.html.md#annals.target.check_rel)(rel)            | Refuse anything that could escape the root; the store only ever passes safe paths.                                                                                |
| [`parse_target`](_autosummary/annals.target.html.md#annals.target.parse_target)(spec)        | `host:/path` becomes an [`SshTarget`](_autosummary/annals.target.html.md#annals.target.SshTarget); anything else a [`LocalTarget`](_autosummary/annals.target.html.md#annals.target.LocalTarget). |
| [`ssh_opts`](_autosummary/annals.target.html.md#annals.target.ssh_opts)(\*[, share_dir]) | The ssh options: batch mode, and one connection shared by consecutive calls.                                                                                      |

### Classes

| [`LocalTarget`](_autosummary/annals.target.html.md#annals.target.LocalTarget)(root)          | A directory on this machine.                                                |
|-----------------------------------------------------------------------------|-----------------------------------------------------------------------------|
| [`SshTarget`](_autosummary/annals.target.html.md#annals.target.SshTarget)(host, root)      | `host:path` on another machine, via the system ssh and rsync in batch mode. |
| [`Target`](_autosummary/annals.target.html.md#annals.target.Target)(\*args, \*\*kwargs) | What the store needs from wherever the documents live.                      |

### annals.target.LOCK_NOTE *= 'lock.json'*

the note a lock directory is created with (see [`Target.make_lock()`](_autosummary/annals.target.html.md#annals.target.Target.make_lock))

### *class* annals.target.LocalTarget(root)

Bases: [`object`](https://docs.python.org/3/builtins/functions.html#object)

A directory on this machine.

`read_metas()` keeps each meta it parsed, keyed by its file’s inode, mtime, ctime
and size (every write replaces the file, so a new inode), and resolves the root once
per listing, not twice per file: listing a thousand documents costs a `stat` per
document, not a parse. It hands back copies, so a caller may change what it gets.

#### local_path(rel)

`rel` under the root, resolved; `None` if it escapes the root (a symlink).

* **Return type:**
  [`Path`](https://docs.python.org/3/library/pathlib.html#pathlib.Path) | [`None`](https://docs.python.org/3/builtins/constants.html#None)

### annals.target.META_GLOB *= '\*/meta.json'*

each document’s meta.json

* **Type:**
  what [`Target.read_metas()`](_autosummary/annals.target.html.md#annals.target.Target.read_metas) reads by default

### annals.target.RECORD_SEP *= '\\x1e'*

Separator between concatenated meta.json files when reading many at once over ssh.

### annals.target.SSH_SHARE_S *= 60*

the several calls of one command
(and the next command soon after) reuse it instead of paying a handshake each (~3 s to a far host)

* **Type:**
  how long the shared ssh connection outlives its last use

### *class* annals.target.SshTarget(host, root)

Bases: [`object`](https://docs.python.org/3/builtins/functions.html#object)

`host:path` on another machine, via the system ssh and rsync in batch mode.

### *class* annals.target.Target(\*args, \*\*kwargs)

Bases: [`Protocol`](https://docs.python.org/3/library/typing.html#typing.Protocol)

What the store needs from wherever the documents live.

#### file_sizes(rel, files)

The byte size of each of `files` under `rel` that is a regular file.

* **Return type:**
  [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`int`](https://docs.python.org/3/builtins/functions.html#int)]

#### local_path(rel)

The file on this machine’s disk, when the documents are local (to stream it).

* **Return type:**
  [`Path`](https://docs.python.org/3/library/pathlib.html#pathlib.Path) | [`None`](https://docs.python.org/3/builtins/constants.html#None)

#### make_lock(rel, note)

Create directory `rel` holding `lock.json` (`note`) as one step; fail if
it exists. An atomic test-and-set: a lock that is never seen without its note.

* **Return type:**
  [`None`](https://docs.python.org/3/builtins/constants.html#None)

#### move(rel_src, rel_dst)

Rename; fails when the source is gone or the destination already exists.

* **Return type:**
  [`None`](https://docs.python.org/3/builtins/constants.html#None)

#### read_metas(rel, , pattern='\*/meta.json')

Every JSON file under `rel` matching `pattern`, read in one go (hidden ones skipped).

* **Return type:**
  [`list`](https://docs.python.org/3/builtins/stdtypes.html#list)[[`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)]

### annals.target.check_glob(pattern)

A glob safe to hand a remote shell unquoted: names, `*` and `/` only, no hidden part.

* **Return type:**
  [`str`](https://docs.python.org/3/builtins/stdtypes.html#str)

### annals.target.check_rel(rel)

Refuse anything that could escape the root; the store only ever passes safe paths.

* **Return type:**
  [`str`](https://docs.python.org/3/builtins/stdtypes.html#str)

### annals.target.parse_target(spec)

`host:/path` becomes an [`SshTarget`](_autosummary/annals.target.html.md#annals.target.SshTarget); anything else a [`LocalTarget`](_autosummary/annals.target.html.md#annals.target.LocalTarget).

* **Return type:**
  [`Target`](_autosummary/annals.target.html.md#annals.target.Target)

### annals.target.ssh_opts(, share_dir=None)

The ssh options: batch mode, and one connection shared by consecutive calls.

The shared connection’s socket lives in `share_dir` (default `~/.ssh`); without that
directory every call opens its own connection, as plain `ssh` would.

* **Return type:**
  [`tuple`](https://docs.python.org/3/builtins/stdtypes.html#tuple)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`...`](https://docs.python.org/3/builtins/constants.html#Ellipsis)]


# _autosummary/annals.titles.html.md

# annals.titles

A title for a file whose name says nothing: `overview.mp3`, `output.html`, `index.md`.

A document is titled by what it says (a `# heading`, a `<title>`), else by its file
name. Tools that make media often name every output the same (podpatch and hailing both
write `<folder>/overview.mp3`), so seven audio overviews were all titled “overview”. When
the file name is one of [`GENERIC_STEMS`](_autosummary/annals.titles.html.md#annals.titles.GENERIC_STEMS), the title comes from beside the file
instead: the `title` of a JSON manifest in its folder ([`TITLE_FILES`](_autosummary/annals.titles.html.md#annals.titles.TITLE_FILES)), else the
folder’s own name without its date and hash, but only when the folder was made by a tool
(its name carries a date stamp or a short hash): a person’s folder (their home, a repo, a
client’s) never names a document, since a title shows wherever the document is shared.

```pycon
>>> is_generic("overview") and is_generic("Final_Output") and not is_generic("theremin")
True
>>> folder_title("20261119-223540-theremin-and-gesture-controlled-7d32")
'theremin and gesture controlled'
```

### Module Attributes

| [`GENERIC_STEMS`](_autosummary/annals.titles.html.md#annals.titles.GENERIC_STEMS)         | file names (without extension) that never title a document on their own       |
|------------------------------------------------------------------------|-------------------------------------------------------------------------------|
| [`TITLE_FILES`](_autosummary/annals.titles.html.md#annals.titles.TITLE_FILES)           | files a maker writes beside its output whose `title` names it, tried in order |
| [`MAX_TITLE`](_autosummary/annals.titles.html.md#annals.titles.MAX_TITLE)             | the longest title taken from a manifest (a rename allows as much)             |
| [`UNINFORMATIVE_FOLDERS`](_autosummary/annals.titles.html.md#annals.titles.UNINFORMATIVE_FOLDERS) | folder names that say nothing either (a title from one would be noise)        |

### Functions

| [`folder_title`](_autosummary/annals.titles.html.md#annals.titles.folder_title)(name)              | A tool's output folder's name as a title: date stamp and trailing hash dropped, separators spaced; `""` for a folder no tool made (no stamp and no hash), or one whose words are only digits and hex (a uuid, a temporary folder's name).   |
|----------------------------------------------------------------------------------|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| [`is_generic`](_autosummary/annals.titles.html.md#annals.titles.is_generic)(stem, \*[, generic]) | Whether a file name (without extension) says nothing about what it holds: one of `generic`, or two of them ("final output", "audio overview").                                                                                              |
| [`title_beside`](_autosummary/annals.titles.html.md#annals.titles.title_beside)(path)              | A title for the file `path` from what is beside it (see the module doc), or `None` when its folder says nothing either.                                                                                                                     |

### annals.titles.GENERIC_STEMS *= frozenset({'audio', 'document', 'export', 'file', 'final', 'index', 'main', 'narration', 'out', 'output', 'overview', 'page', 'player', 'recording', 'render', 'report', 'result', 'speech', 'summary', 'take', 'track', 'untitled', 'video', 'voice'})*

file names (without extension) that never title a document on their own

### annals.titles.MAX_TITLE *= 200*

the longest title taken from a manifest (a rename allows as much)

### annals.titles.TITLE_FILES *= ('manifest.json', 'meta.json', 'script.json', 'info.json')*

files a maker writes beside its output whose `title` names it, tried in order

### annals.titles.UNINFORMATIVE_FOLDERS *= frozenset({'desktop', 'documents', 'downloads', 'home', 'overviews', 'root', 'scratchpad', 'temp', 'tmp', 'work'})*

folder names that say nothing either (a title from one would be noise)

### annals.titles.folder_title(name)

A tool’s output folder’s name as a title: date stamp and trailing hash dropped,
separators spaced; `""` for a folder no tool made (no stamp and no hash), or one whose
words are only digits and hex (a uuid, a temporary folder’s name).

```pycon
>>> folder_title("2026-11-22-tables-and-session-links"), folder_title("thorwhalen")
('tables and session links', '')
```

* **Return type:**
  [`str`](https://docs.python.org/3/builtins/stdtypes.html#str)

### annals.titles.is_generic(stem, , generic=frozenset({'audio', 'desktop', 'document', 'documents', 'downloads', 'export', 'file', 'final', 'home', 'index', 'main', 'narration', 'out', 'output', 'overview', 'overviews', 'page', 'player', 'recording', 'render', 'report', 'result', 'root', 'scratchpad', 'speech', 'summary', 'take', 'temp', 'tmp', 'track', 'untitled', 'video', 'voice', 'work'}))

Whether a file name (without extension) says nothing about what it holds: one of
`generic`, or two of them (“final output”, “audio overview”).

* **Return type:**
  [`bool`](https://docs.python.org/3/builtins/functions.html#bool)

### annals.titles.title_beside(path)

A title for the file `path` from what is beside it (see the module doc), or `None`
when its folder says nothing either.

```pycon
>>> import tempfile, os
>>> d = Path(tempfile.mkdtemp()) / "20261119-223540-theremin-7d32"; d.mkdir()
>>> title_beside(d / "overview.mp3")
'theremin'
>>> _ = (d / "manifest.json").write_text('{"title": "The Theremin: Invention, Spies"}')
>>> title_beside(d / "overview.mp3")
'The Theremin: Invention, Spies'
```

* **Return type:**
  [`str`](https://docs.python.org/3/builtins/stdtypes.html#str) | [`None`](https://docs.python.org/3/builtins/constants.html#None)


# _autosummary/annals.tokens.html.md

# annals.tokens

Read tokens: a credential for an agent that cannot reach the store (a cloud session).

A token is scoped to ONE group, can only read (`GET`), is stored hashed, and expires (14
days unless told, 90 at most; there is no “never”). It never reaches a document tagged
`private` or `noindex` ([`annals.records.is_withheld()`](_autosummary/annals.records.html.md#annals.records.is_withheld)), however the group is edited
later. The server accepts it as `Authorization: Bearer <token>` on the API
(`annals.api.mk_app()`), where it is answered by a read-only room over the group
([`annals.store.GroupScopedStore`](_autosummary/annals.store.html.md#annals.store.GroupScopedStore)), so a route added later is out of reach until it is
named in `annals.api.TOKEN_ROUTES`.

The records are `tokens/<id>.json` under the data root (through the store’s target, so
`annals token new` works over ssh like `annals publish`):

```default
{"id": "...", "name": "cloud-agent", "group": "<gid>", "created": "<iso>",
 "expires": "<iso>", "hash": "<sha256 of the secret>", "revoked": "<iso>" | null}
```

The token itself, `annt_<id>.<secret>`, is shown once at creation and never stored. The
secret is 256 random bits, so a plain SHA-256 is enough (there is nothing to guess and
nothing to stretch); it is compared in constant time.

```pycon
>>> import tempfile
>>> from annals.store import DocStore
>>> store = DocStore(tempfile.mkdtemp())
>>> d = store.publish(text="# a", title="A")["id"]
>>> g = store.make_group("G", [d])["id"]
>>> tokens = ReadTokens(store)
>>> token, rec = tokens.create(g, name="agent")
>>> tokens.verify(token)["group"] == g, tokens.verify(token + "x")
(True, None)
>>> _ = tokens.revoke(rec["id"]); tokens.verify(token)
```

### Module Attributes

| [`MAX_DAYS`](_autosummary/annals.tokens.html.md#annals.tokens.MAX_DAYS)   | a long-lived credential is what the scope exists to avoid   |
|-------------------------------------------------------------|-------------------------------------------------------------|

### Functions

| [`bearer_of`](_autosummary/annals.tokens.html.md#annals.tokens.bearer_of)(header)   | The token in an `Authorization` header, or `None` when it carries none of ours.   |
|----------------------------------------------------------------------|-----------------------------------------------------------------------------------|

### Classes

| [`ReadTokens`](_autosummary/annals.tokens.html.md#annals.tokens.ReadTokens)(store, \*[, clock, max_days])   | Make, check, list and revoke the read tokens of a `DocStore`'s groups.   |
|---------------------------------------------------------------------------------------------|--------------------------------------------------------------------------|

### annals.tokens.MAX_DAYS *= 90*

a long-lived credential is what the scope exists to avoid

* **Type:**
  the longest a token may live

### *class* annals.tokens.ReadTokens(store, \*, clock=<function now_utc>, max_days=90)

Bases: [`object`](https://docs.python.org/3/builtins/functions.html#object)

Make, check, list and revoke the read tokens of a `DocStore`’s groups.

#### create(group, , name, expires='14d')

`(token, record)`: the token is shown once, only its hash is kept.

* **Return type:**
  [`tuple`](https://docs.python.org/3/builtins/stdtypes.html#tuple)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)]

#### list(, all=False)

The records without their hash, newest first (`all`: revoked and expired too).

* **Return type:**
  [`list`](_autosummary/annals.tokens.html.md#annals.tokens.ReadTokens.list)[[`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)]

#### revoke(ident)

Stop a token working at once (its id, or the token itself); the record stays.

* **Return type:**
  [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)

#### verify(token)

The record of a good token, else `None`: unknown, wrong secret, revoked, expired.

* **Return type:**
  [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict) | [`None`](https://docs.python.org/3/builtins/constants.html#None)

### annals.tokens.bearer_of(header)

The token in an `Authorization` header, or `None` when it carries none of ours.

```pycon
>>> bearer_of("Bearer annt_x.y"), bearer_of("Basic abc"), bearer_of(None)
('annt_x.y', None, None)
```

* **Return type:**
  [`str`](https://docs.python.org/3/builtins/stdtypes.html#str) | [`None`](https://docs.python.org/3/builtins/constants.html#None)


# _autosummary/annals.tools.html.md

# annals.tools

The operations, as plain functions: JSON-able arguments in, JSON-able dicts out.

This module is the single source of truth for what a annals can do. The CLI
(`annals.__main__`, via `cw`), the MCP server (`py2mcp` over string refs to these
names) and the shipped skill all describe the same functions, so there is nothing to keep
in parity. Nothing here prints or exits; the surfaces do that.

### Module Attributes

| [`LINK_CHECKED_SUFFIXES`](_autosummary/annals.tools.html.md#annals.tools.LINK_CHECKED_SUFFIXES)   | the suffixes whose text the link check reads (prose an author writes by hand)                                               |
|--------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------------------------------------|
| [`UPSERT_LOCK_TTL_S`](_autosummary/annals.tools.html.md#annals.tools.UPSERT_LOCK_TTL_S)       | how long a crashed upsert's lock is honoured before it is recovered                                                         |
| [`LINKS_READ_SUFFIXES`](_autosummary/annals.tools.html.md#annals.tools.LINKS_READ_SUFFIXES)     | the suffixes whose text [`show()`](_autosummary/annals.tools.html.md#annals.tools.show) reads for the annals links a document makes |
| [`LINKS_MAX_FILES`](_autosummary/annals.tools.html.md#annals.tools.LINKS_MAX_FILES)         | [`show()`](_autosummary/annals.tools.html.md#annals.tools.show) reads at most this many of a document's text files for links ...    |
| [`LINKS_MAX_FILE_BYTES`](_autosummary/annals.tools.html.md#annals.tools.LINKS_MAX_FILE_BYTES)    |                                                                                                                             |
| [`EFFECTS`](_autosummary/annals.tools.html.md#annals.tools.EFFECTS)                 | a surface serves the levels its caller allows.                                                                              |
| [`DFLT_EFFECTS`](_autosummary/annals.tools.html.md#annals.tools.DFLT_EFFECTS)            | what an agent or a tool is offered unless its host asks for more (MCP reads this)                                           |

### Functions

| [`aggregate`](_autosummary/annals.tools.html.md#annals.tools.aggregate)(group_id, \*[, format, output, ...])     | The files of a group (or one document) as ONE markdown, html or pdf file (nothing is stored).             |
|-----------------------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------------------|
| [`configure`](_autosummary/annals.tools.html.md#annals.tools.configure)(\*[, target, base_url, to, outbox, ...]) | Write the publisher config (where to publish, what link to print) and show it.                            |
| [`copy`](_autosummary/annals.tools.html.md#annals.tools.copy)(refs, \*, to[, source, target, base_url])     | Copy documents or groups to a named target, keeping their ids; print the new link.                        |
| [`export`](_autosummary/annals.tools.html.md#annals.tools.export)(doc_id, \*[, format, file, output, ...])    | One markdown file of a document as a `.md` or a titled `.pdf`, as the page's Export gives it.             |
| [`group`](_autosummary/annals.tools.html.md#annals.tools.group)(title, doc_ids, \*[, add_to, target, ...])   | Make a group (one URL for a set of documents) from existing document ids.                                 |
| [`groups`](_autosummary/annals.tools.html.md#annals.tools.groups)(\*[, target, base_url, to])                 | List groups, newest first.                                                                                |
| [`highlight_add`](_autosummary/annals.tools.html.md#annals.tools.highlight_add)(doc, exact, \*[, file, prefix, ...]) | Keep a passage of a document as a highlight, as selecting it on the page does.                            |
| [`highlight_edit`](_autosummary/annals.tools.html.md#annals.tools.highlight_edit)(highlight_id, \*[, name, ...])      | Change a highlight's name, note, tags or colour; its passage never changes.                               |
| [`highlight_remove`](_autosummary/annals.tools.html.md#annals.tools.highlight_remove)(highlight_id, \*[, reader, ...])  | Delete a highlight.                                                                                       |
| [`highlights`](_autosummary/annals.tools.html.md#annals.tools.highlights)([q, doc, tag, reader, limit, ...])      | List or search the highlights a reader kept on documents' pages, newest first.                            |
| [`listen`](_autosummary/annals.tools.html.md#annals.tools.listen)(doc_id, \*[, minutes, force, also, ...])    | Ask for a spoken overview of a document, as its page's Listen button does.                                |
| [`listen_down`](_autosummary/annals.tools.html.md#annals.tools.listen_down)([reason, link, clear, target, to])     | Say why spoken overviews cannot be made, and where that is being fixed; or clear it.                      |
| [`listen_work`](_autosummary/annals.tools.html.md#annals.tools.listen_work)(\*[, command, target, to])             | Fulfil the queued overview requests, one at a time (a timer runs this on the server).                     |
| [`ls`](_autosummary/annals.tools.html.md#annals.tools.ls)([q, trash, limit, target, base_url, to, ...])   | List documents (newest first), optionally filtered by words or showing the bin.                           |
| [`overview_state`](_autosummary/annals.tools.html.md#annals.tools.overview_state)(doc_id, \*[, target, to])           | Where a document's spoken overview stands (not asked for, queued, made, failed), without asking for one.  |
| [`page_shell`](_autosummary/annals.tools.html.md#annals.tools.page_shell)(\*[, api, base, title])                 | The page's html shell, for a host that serves the API under its own prefix.                               |
| [`publish`](_autosummary/annals.tools.html.md#annals.tools.publish)(paths, \*[, title, tags, group, ...])      | Publish one document and print its link; several paths become several documents.                          |
| [`purge`](_autosummary/annals.tools.html.md#annals.tools.purge)(doc_ids, \*[, target, to])                   | Delete documents that are in the bin for good (not restorable).                                           |
| [`references`](_autosummary/annals.tools.html.md#annals.tools.references)(ref, \*[, form, also, target, to])      | The references of a document or a group, as its page's References action gives them.                      |
| [`rename`](_autosummary/annals.tools.html.md#annals.tools.rename)(ref, title, \*[, target, to])               | Rename a document or a group (its link or id), as the page's Rename does.                                 |
| [`restore`](_autosummary/annals.tools.html.md#annals.tools.restore)(doc_ids, \*[, target, to])                 | Bring documents back from the recycle bin.                                                                |
| [`serve`](_autosummary/annals.tools.html.md#annals.tools.serve)(\*[, host, port, data_dir, base_path, ...])  | Serve the annals page and API (needs `pip install 'annals[server]'`).                                     |
| [`share`](_autosummary/annals.tools.html.md#annals.tools.share)(ref, \*[, password, expires, include, ...])  | Make a public link to ONE document (or group) and print it; nothing else is reachable.                    |
| [`shareable`](_autosummary/annals.tools.html.md#annals.tools.shareable)(doc_id, \*[, target, to])                | What the Share dialog offers for a document: its files, and the other annals documents its text links to. |
| [`shares`](_autosummary/annals.tools.html.md#annals.tools.shares)(\*[, all, target, base_url, to])            | List share links, newest first (`all`: revoked and expired ones too).                                     |
| [`show`](_autosummary/annals.tools.html.md#annals.tools.show)(doc_id, \*[, target, base_url, to])           | A document's metadata, link, the groups it is in, and the annals links in its text.                       |
| [`tag`](_autosummary/annals.tools.html.md#annals.tools.tag)(doc_id, tags, \*[, target, to])                | Set a document's tags (comma separated; "" clears them), as the page's tag editor does.                   |
| [`token_new`](_autosummary/annals.tools.html.md#annals.tools.token_new)(group, \*, name[, expires, target, to])  | Make a read token for ONE group: for an agent that cannot reach the store.                                |
| [`token_revoke`](_autosummary/annals.tools.html.md#annals.tools.token_revoke)(ids, \*[, target, to])                | Revoke read tokens (their id from `annals tokens`, or the token): they stop working at once.              |
| [`tokens`](_autosummary/annals.tools.html.md#annals.tools.tokens)(\*[, all, target, to])                      | List read tokens, newest first (`all`: revoked and expired ones too); never the token.                    |
| [`tools_with`](_autosummary/annals.tools.html.md#annals.tools.tools_with)([effects])                              | The operations whose effect is in `effects`, in the CLI's order: the list a caller-facing surface serves. |
| [`trash`](_autosummary/annals.tools.html.md#annals.tools.trash)(doc_ids, \*[, target, to])                   | Move documents to the recycle bin (restorable).                                                           |
| [`unshare`](_autosummary/annals.tools.html.md#annals.tools.unshare)(links, \*[, target, to])                   | Revoke share links (their token or full link): they stop working at once.                                 |

### annals.tools.DFLT_EFFECTS *= frozenset({'read', 'write'})*

what an agent or a tool is offered unless its host asks for more (MCP reads this)

### annals.tools.EFFECTS *= {'aggregate': 'file', 'configure': 'write', 'copy': 'write', 'export': 'file', 'group': 'write', 'groups': 'read', 'highlight_add': 'write', 'highlight_edit': 'write', 'highlight_remove': 'destructive', 'highlights': 'read', 'listen': 'spend', 'listen_down': 'spend', 'listen_work': 'server', 'ls': 'read', 'overview_state': 'read', 'page_shell': 'server', 'publish': 'write', 'purge': 'destructive', 'references': 'read', 'rename': 'write', 'restore': 'write', 'serve': 'server', 'share': 'write', 'shareable': 'read', 'shares': 'read', 'show': 'read', 'tag': 'write', 'token_new': 'credential', 'token_revoke': 'credential', 'tokens': 'read', 'trash': 'write', 'unshare': 'write'}*

a surface serves the levels its caller
allows. `read` changes nothing; `write` changes the store or a setting and can be undone
or repeated; `file` writes a path on the machine that runs it; `destructive` cannot be
undone; `spend` costs money or queues work that does; `server` is run by a server or a
timer, never by a caller; `credential` mints or revokes a credential, which a caller
(an agent) must not do for itself.

* **Type:**
  what a function does to the world, least to most

### annals.tools.LINKS_MAX_FILES *= 20*

[`show()`](_autosummary/annals.tools.html.md#annals.tools.show) reads at most this many of a document’s text files for links …

### annals.tools.LINKS_MAX_FILE_BYTES *= 1000000*

… and none larger than this (bytes, from the document’s meta)

### annals.tools.LINKS_READ_SUFFIXES *= frozenset({'.htm', '.html', '.markdown', '.md', '.txt'})*

the suffixes whose text [`show()`](_autosummary/annals.tools.html.md#annals.tools.show) reads for the annals links a document makes

### annals.tools.LINK_CHECKED_SUFFIXES *= frozenset({'.markdown', '.md', '.txt'})*

the suffixes whose text the link check reads (prose an author writes by hand)

### annals.tools.UPSERT_LOCK_TTL_S *= 120*

how long a crashed upsert’s lock is honoured before it is recovered

### annals.tools.aggregate(group_id, , format='md', output=None, demote=1, order='numbered', no_toc=False, keep_wraps=False, target=None, to=None)

The files of a group (or one document) as ONE markdown, html or pdf file (nothing is stored).

`group_id` is a group’s or a document’s id or link. `format`: `md` (printed, or
written to `output`), `html` (a web page, the same) or `pdf` (needs `output`).
Markdown, html, text, PDF and image files go in; what cannot (audio, video, other
files, a damaged PDF) is listed on stderr, with the reason, and left out. The markdown
has the group’s title, a table of contents, then one `##` section per file named after
its path (a folder document’s files under its title). `order`: `numbered` puts paths
that start with a number first, numerically, the rest in the group’s order; `given`
keeps the group’s order. `demote` pushes each file’s headings that many levels down
(`0`: as written). Hard-wrapped lines are joined unless `keep_wraps`; `no_toc`
leaves out the table of contents. Redirect to save text, or name the file:
`annals aggregate <id> --format pdf --output bundle.pdf`. A PDF or html needs
`pip install 'annals[pdf]'`; a missing library says so.

* **Return type:**
  [`str`](https://docs.python.org/3/builtins/stdtypes.html#str) | [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)

### annals.tools.configure(, target=None, base_url=None, to=None, outbox=False, share_base_url=None, room=False)

Write the publisher config (where to publish, what link to print) and show it.

### Example

`annals configure --target tw:/root/.local/share/annals --base-url https://apps.example.com/annals`.
`--to NAME` saves the target and base url as a named target (`annals publish --to NAME`)
and leaves the default alone. `--outbox` marks the target as an outbox: a directory
the server pulls and empties (it cannot be written to from here), so replacements are
left for the server to apply; it is kept by later changes (`ANNALS_OUTBOX=0` or an
edit of the file turns it off). `--share-base-url` is where share links point when
the share server is not at `<base-url>/shared` (a platform running it as its own
public app). `--room` marks a target an outside audience reads (a client’s room): what
is published or copied to it carries no provenance; kept by later changes, like
`--outbox`. With no arguments, shows the resolved settings without writing.

* **Return type:**
  [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)

### annals.tools.copy(refs, , to, source=None, target=None, base_url=None)

Copy documents or groups to a named target, keeping their ids; print the new link.

`refs` are links (`https://.../annals/d/<id>`, `.../g/<group-id>`) or bare ids; only
the id is used, so the link may point at any instance. They are read from the default
target (or the named target `source`) and written to the named target `to`. A group
is copied with its documents and keeps its id and title. Copying again refreshes the
copy. The source must be readable from this machine (a directory, or `host:/path`).
`target`/`base_url` override the DESTINATION’s location, as in `publish`.

* **Return type:**
  [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)

### annals.tools.export(doc_id, , format='pdf', file=None, output=None, target=None, to=None)

One markdown file of a document as a `.md` or a titled `.pdf`, as the page’s Export gives it.

`file` names another markdown file of a folder document (default: the main one). A PDF
(images inside; needs the `annals[pdf]` extra) is a binary file, so name it with
`--output FILE`; `md` prints the text or writes it to `output`. For several documents
as one file, with a table of contents, use `annals aggregate`.

* **Return type:**
  [`str`](https://docs.python.org/3/builtins/stdtypes.html#str) | [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)

### annals.tools.group(title, doc_ids, , add_to=None, target=None, base_url=None, to=None)

Make a group (one URL for a set of documents) from existing document ids.

With `add_to` (a group id) the documents are added to that group instead, and `title`
is ignored. The documents must exist and not be in the bin; the title is cleaned (see
[`annals.store.clean_title()`](_autosummary/annals.store.html.md#annals.store.clean_title)).

* **Return type:**
  [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)

### annals.tools.groups(, target=None, base_url=None, to=None)

List groups, newest first.

* **Return type:**
  [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)

### annals.tools.highlight_add(doc, exact, , file=None, prefix='', suffix='', name=None, comment='', tags='', color=None, whole=False, reader=None, target=None, to=None)

Keep a passage of a document as a highlight, as selecting it on the page does.

`doc` is the document’s id or link; `file` names one file of it (as its page’s
`?f=` does) when the passage is not in its main text. `exact` is the passage word for
word as the page shows it (rendered text, not markdown marks); `prefix` and `suffix`
(the text just before and after) tell two identical passages apart. `whole` keeps the
document itself by its title (`exact` is then the title, or anything). `name`
defaults to `<title>-highlight-<n>`; `tags` is comma separated; `color` is one of
yellow, green, blue, pink, orange, purple. Run where the documents are kept; `reader`
is whose (needed until one reader, and only one, has highlights). Returns
`{highlight}`, with its `url`.

* **Return type:**
  [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)

### annals.tools.highlight_edit(highlight_id, , name=None, comment=None, tags=None, color=None, reader=None, target=None, to=None)

Change a highlight’s name, note, tags or colour; its passage never changes.

Only what is given changes: `comment ""` clears the note, `tags ""` the tags,
`color default` goes back to the reader’s default colour. Run where the documents are
kept. Returns `{highlight}`.

* **Return type:**
  [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)

### annals.tools.highlight_remove(highlight_id, , reader=None, target=None, to=None)

Delete a highlight. Returns `{removed}`, the highlight as it was.

Run where the documents are kept. Nothing brings it back but adding it again.

* **Return type:**
  [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)

### annals.tools.highlights(q='', , doc=None, tag=None, reader=None, limit=50, target=None, base_url=None, to=None)

List or search the highlights a reader kept on documents’ pages, newest first.

A highlight is a passage of a document kept with a name, a note (`comment`) and tags;
one whose `target.whole` is true and `target.part` is `title` keeps the whole
document (a favourite). `q`: words that must all appear in the name, the passage, the
note, the tags or the document’s title. `doc` (an id or a link) keeps one document’s
(its files’ included), `tag` one tag’s. `reader` is whose (the address they sign in
with); it may be left out when one reader has highlights. Each row has `reader` and
`url`, the page opened on the passage. Returns `{highlights, total, reader}`;
`total` counts matches before `limit`.

* **Return type:**
  [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)

### annals.tools.listen(doc_id, , minutes=5, force=False, also=None, target=None, to=None)

Ask for a spoken overview of a document, as its page’s Listen button does. Spends money.

`also` (more document ids) asks for ONE overview of all of them together, as the page
does for a pick: their text is put in one document (made when the worker starts the job),
and the same documents at the same versions reuse it. `force` then does not apply.

* **Return type:**
  [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)

### annals.tools.listen_down(reason='', , link='', clear=False, target=None, to=None)

Say why spoken overviews cannot be made, and where that is being fixed; or clear it.

With nothing given, shows the current state. The Audio tab then shows the reason and the
link instead of a Try again that cannot work, e.g.
`annals listen-down "the server's login expired" --link <issue url>`. The worker finds
out by itself too, and clears it on the next success; `--clear` clears it now and
queues every request that waited.

* **Return type:**
  [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)

### annals.tools.listen_work(, command='', target=None, to=None)

Fulfil the queued overview requests, one at a time (a timer runs this on the server).

`command` makes one overview, with {source}, {minutes}, {out} and {url} filled in; by default,
`$ANNALS_OVERVIEW_COMMAND`.

* **Return type:**
  [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)

### annals.tools.ls(q='', , trash=False, limit=50, target=None, base_url=None, to=None, since=None, session=None, tag=None, meta=None)

List documents (newest first), optionally filtered by words or showing the bin.

`to` lists a named target instead of the default one. The rest are exact filters,
all of which must hold, for tools that poll: `since` (an ISO date or time, or an age
like `6h` or `2d`: published or replaced at or after it), `session` (the publishing session’s
name, whole, case-sensitive), `tag` (one tag, whole: the owner’s own tags, set by `annals tag`, win over the publisher’s) and `meta` (`key=value`,
several allowed, against the document’s `source`: `corpus=annals`). A row is
`{id, title, kind, tags, created, updated, source, url}`; with `--json` that is the contract
(`misc/docs/design.md`), and `total` counts the matches before `limit`.

* **Return type:**
  [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)

### annals.tools.overview_state(doc_id, , target=None, to=None)

Where a document’s spoken overview stands (not asked for, queued, made, failed), without asking for one.

Poll this after `annals listen`. For a combined overview (`listen --also`) give the
combined document’s id once the worker has made it; until then `listen` returns the state.

* **Return type:**
  [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)

### annals.tools.page_shell(, api='/api/annals', base='/annals', title='annals')

The page’s html shell, for a host that serves the API under its own prefix.

An enlace app writes it once as its frontend:
`annals page-shell --api /api/annals --base /annals > frontend/index.html`.
The shell only names the two paths; the page’s code loads from the API, so it upgrades
with the package.

* **Return type:**
  [`str`](https://docs.python.org/3/builtins/stdtypes.html#str)

### annals.tools.publish(paths, , title=None, tags='', group=None, add_to=None, session=None, session_url=None, all_files=False, target=None, base_url=None, to=None, replace=None, artifact=None, no_link_check=False, no_pdf=False, meta=None, upsert=None)

Publish one document and print its link; several paths become several documents.

An audio or video file takes its timed text along as one document: `talk.mp3
talk.vtt talk.chapters.vtt` (or `talk.cues.json`) is one audio document whose page
shows the transcript and chapters (`annals.store.SIDECAR_SUFFIXES`).

`paths`: files of any kind (markdown, html, images, video, audio, pdf, text), a
directory (one document: an `index.html` or single page with its assets, else a
gallery of everything in it), or `-` for stdin (markdown). `tags` is comma separated. `group`
names a group to create from the published documents; the reply then carries
`group_url` too. `add_to` appends them to an existing group instead (its id, as
printed in a group link), so a second batch lands under the link the owner already has. `session` records who published (the source shown on the page), and `session_url`
the claude.ai link that opens that session; by default the link of the Claude Code session
this runs in (`CLAUDE_CODE_BRIDGE_SESSION_ID`), `none` for no link. The document’s page
shows each session that made it, linked, under its title; a share or a room never does
([`annals.sessions`](_autosummary/annals.sessions.html.md#module-annals.sessions)). A directory skips
hidden files and caches (`.*`, `__pycache__`, `*.pyc`) unless `all_files`.
`to` publishes to a named target of the config file (`[targets.NAME]`, see
`annals configure --to`) instead of the default one. `replace` (a document’s link or
id) publishes ONE path as a new version of that document: the link stays the same, the
page shows the new version and offers the earlier ones. That is how a living page (a
guide, a status page) keeps one link. `artifact` (a claude.ai artifact link) is the
interactive version of the page: the document’s page shows an “Open the interactive
version” button. Publish the Artifact first, then the same page here with its link.
A markdown or text document that mentions an issue or a Slack/email/chat message
without linking to it gets a warning on stderr ([`annals.linkcheck`](_autosummary/annals.linkcheck.html.md#module-annals.linkcheck)); it is
published either way. `no_link_check` turns that check off.

An html page gets its own Download PDF button, inside the page, so it survives “open
full page”, raw links and shares, and `<stem>.pdf` printed beside it (headless
Chromium, the `pdf` extra; without it the button opens the print dialog). A page that
already has its PDF says so with `<link rel="alternate" type="application/pdf"
href="...">`; one with its own button marks it `data-annals-pdf`; `no_pdf` (or
`data-annals-pdf="off"` on `<html>`/`<body>`) leaves the page as it is
([`annals.pagepdf`](_autosummary/annals.pagepdf.html.md#module-annals.pagepdf)).

`meta` (`--meta key=value`, one flag per pair: `--meta corpus=x --meta issue=3`) records what the document belongs to, next
to `host`, `cwd` and `session` in its `source`: by convention `corpus` (the
repository or body of work), `repo`, `issue` (the issue it answers), `item` (a
desk item) and `kind` (report, brief, overview, render); other keys are kept as given.
`ls --session/--meta` finds them again. The CLI’s `--json` prints the result below
(`id`, `title`, `url`, and with a group `group_id` and `group_url`; several
paths give `docs`) as JSON and nothing else on stdout; that shape is a contract
(`misc/docs/design.md`).

`upsert` (`--upsert key=value`) makes the call idempotent for a living document
keyed by a meta value: it publishes ONE path as a new version of the newest live
document whose `source.<key>` equals the value (as `replace` would), or creates
one with that `key=value` in its `source` when there is none. The reply then says
`"created": true` or `false`, and `group` / `add_to` apply only when the
document is new. It takes the place of `replace`; not together.

* **Return type:**
  [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)

### annals.tools.purge(doc_ids, , target=None, to=None)

Delete documents that are in the bin for good (not restorable). One that is not in the bin is refused.

* **Return type:**
  [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)

### annals.tools.references(ref, , form='grouped', also=None, target=None, to=None)

The references of a document or a group, as its page’s References action gives them.

`ref` is a group’s or a document’s id or link. `form`: `grouped` (each document’s
references section as it is), `deduped` (every entry once, numbers removed) or `urls`
(one address per line, nothing else: what a notebook takes as pasted sources). Documents
with no references section are left out; none at all is an error. `also` (more document
ids) takes the references of those documents together, as a pick on the page does.

* **Return type:**
  [`str`](https://docs.python.org/3/builtins/stdtypes.html#str)

### annals.tools.rename(ref, title, , target=None, to=None)

Rename a document or a group (its link or id), as the page’s Rename does.

The document keeps the owner’s title when a new version is published over it
(`publish --replace`). Returns `{id, title}`.

* **Return type:**
  [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)

### annals.tools.restore(doc_ids, , target=None, to=None)

Bring documents back from the recycle bin.

* **Return type:**
  [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)

### annals.tools.serve(, host='127.0.0.1', port=8765, data_dir=None, base_path='/annals', allow_open=False, overviews=None)

Serve the annals page and API (needs `pip install 'annals[server]'`).

Auth comes from the environment: `ANNALS_WHOAMI_URL` + `ANNALS_ALLOWED_USERS` to sit
behind an existing login, `ANNALS_BASIC_USER` + `ANNALS_BASIC_PASSWORD` for HTTP Basic,
nothing for an open server on localhost. A host reachable beyond this machine with no auth
configured is refused unless `allow_open` (`--allow-open`) says something else gates it.
`overviews` (`--overviews '*'`, or reader names separated by commas) offers the Listen
button to those the login lets in (unset: `ANNALS_OVERVIEWS` decides, and unset it is
off; `--overviews ''` forces it off). It spends money, needs `ANNALS_OVERVIEW_COMMAND`
and a worker (`annals listen-work` on a timer), and a server with no login serves it
only on this machine.

* **Return type:**
  [`None`](https://docs.python.org/3/builtins/constants.html#None)

### annals.tools.share(ref, , password=None, expires='7d', include=None, exclude=None, title=None, target=None, base_url=None, to=None)

Make a public link to ONE document (or group) and print it; nothing else is reachable.

Returns three forms of the one link (the CLI prints the first on stdout, the others
on stderr): `url`, the page, whose text is in the html (a
person, NotebookLM or any fetcher reads it without running script); `markdown`, the
whole share as one text, for an agent; `pdf`, the same with its images. All three end
with the link’s expiry or revocation.

`ref` is a document or group id, or its link. The link opens without a login, shows
only that page and the files chosen, and can be revoked (`annals unshare`).
`include`: comma separated files of the document to share (the page itself always
is), or ids of other annals pages it links to; by default every file of the document
(for a group: every document; `include` then picks documents). `exclude` drops
files. `expires` (7 days unless told): `12h`, `30d`, `2w`, a date (`2026-11-01`,
through that day, UTC), an ISO time, or `never`. `password` gates the link (stored hashed; `-` reads it from
stdin, so it stays out of the shell history).

* **Return type:**
  [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)

### annals.tools.shareable(doc_id, , target=None, to=None)

What the Share dialog offers for a document: its files, and the other annals documents its text links to.

`{main, files: [{rel, kind, size, referenced}], pages: [{id, title, kind}]}`: the
choices `annals share` takes for what a link may show.

* **Return type:**
  [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)

### annals.tools.shares(, all=False, target=None, base_url=None, to=None)

List share links, newest first (`all`: revoked and expired ones too).

* **Return type:**
  [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)

### annals.tools.show(doc_id, , target=None, base_url=None, to=None)

A document’s metadata, link, the groups it is in, and the annals links in its text.

`doc_id` may be the document’s link, on any annals this machine is configured for: the
link finds its own place (`to` names one explicitly). A group’s link gives the group
and its documents’ links. `links` are the links to other annals documents and groups
found in the document’s text files, on any annals this machine can read: follow them
with `annals show` or `annals aggregate`. To read the text, use `annals aggregate <link>`.

* **Return type:**
  [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)

### annals.tools.tag(doc_id, tags, , target=None, to=None)

Set a document’s tags (comma separated; “” clears them), as the page’s tag editor does.

The tags are the owner’s overlay, kept apart from the document and shown by `ls` and
`show` in place of the publisher’s. They live where the documents do, so this refuses an
outbox or a remote target. `doc_id` may be the document’s link. Returns `{id, tags}`.

* **Return type:**
  [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)

### annals.tools.token_new(group, , name, expires='14d', target=None, to=None)

Make a read token for ONE group: for an agent that cannot reach the store.

The token reads (`GET`) that group’s documents over the API as
`Authorization: Bearer <token>`, and nothing else: no other group, no publishing, no
bin, no shares, and never a document tagged `private` or `noindex`. It is printed
once (`token`) and only its hash is kept. `name` says who holds it. `expires`
is 14 days unless told, 90 at most: `7d`, `12h`, a date.

* **Return type:**
  [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)

### annals.tools.token_revoke(ids, , target=None, to=None)

Revoke read tokens (their id from `annals tokens`, or the token): they stop working at once.

* **Return type:**
  [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)

### annals.tools.tokens(, all=False, target=None, to=None)

List read tokens, newest first (`all`: revoked and expired ones too); never the token.

* **Return type:**
  [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)

### annals.tools.tools_with(effects=frozenset({'read', 'write'}))

The operations whose effect is in `effects`, in the CLI’s order: the list a caller-facing surface serves.

```pycon
>>> [f.__name__ for f in tools_with({"read"})]
['ls', 'show', 'groups', 'references', 'shareable', 'shares', 'tokens', 'overview_state', 'highlights']
```

* **Return type:**
  [`list`](https://docs.python.org/3/builtins/stdtypes.html#list)

### annals.tools.trash(doc_ids, , target=None, to=None)

Move documents to the recycle bin (restorable).

* **Return type:**
  [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)

### annals.tools.unshare(links, , target=None, to=None)

Revoke share links (their token or full link): they stop working at once.

* **Return type:**
  [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)


# about-this-build.html.md

<!-- generated by epythet -->

# About this build

This documentation was built on **2026-12-05 20:24 UTC** from commit <a href="https://github.com/addaix/annals/commit/670e0d6de63eb0ec47d635601be970d663683871"><code>670e0d6</code></a> on branch <code>main</code>, for **annals 0.0.82** (from <code>pyproject.toml</code>).

#### WARNING
The documentation and the package may be misaligned:

- The documented version (0.0.82) is behind the latest release on PyPI (0.0.83): `pip install annals` gives newer code than these docs describe.

## Source

|                     |                                                                                                                                                      |
|---------------------|------------------------------------------------------------------------------------------------------------------------------------------------------|
| Commit              | <a href="https://github.com/addaix/annals/commit/670e0d6de63eb0ec47d635601be970d663683871"><code>670e0d6de63eb0ec47d635601be970d663683871</code></a> |
| Branch              | <code>main</code>                                                                                                                                    |
| Tags at this commit | none                                                                                                                                                 |
| Working tree        | clean                                                                                                                                                |
| Remote              | <code>https://github.com/addaix/annals</code>                                                                                                        |

## Continuous integration

|              |                                                                                            |
|--------------|--------------------------------------------------------------------------------------------|
| Repository   | <code>addaix/annals</code>                                                                 |
| Run          | <a href="https://github.com/addaix/annals/actions/runs/47564405756">47564405756</a>        |
| Ref          | <code>refs/heads/main</code>                                                               |
| Event commit | <code>670e0d6de63eb0ec47d635601be970d663683871</code> (in the history of the built commit) |

## Tools

|          |         |
|----------|---------|
| epythet  | 0.2.26  |
| Sphinx   | 9.1.1   |
| docutils | 0.22.4  |
| Python   | 3.12.16 |

## Configuration as resolved

|               |                                                                  |
|---------------|------------------------------------------------------------------|
| theme         | <code>auto</code> (Sphinx theme <code>shibuya</code>)            |
| accent        | <code>#624496</code>                                             |
| api_generator | <code>autosummary</code>                                         |
| ignore        | <code>tests/</code>, <code>scrap/</code>, <code>examples/</code> |
| agent_outputs | <code>true</code>                                                |
| aggregates    | <code>md</code>                                                  |
| ai_artifacts  | <code>true</code>                                                |

## Package on PyPI

Latest release: <a href="https://pypi.org/project/annals/0.0.83/">0.0.83</a>, newer than the documented version (0.0.82).

## Reproduce

```bash
git clone https://github.com/addaix/annals && cd annals
git checkout 670e0d6de63eb0ec47d635601be970d663683871
pip install "epythet==0.2.26"
epythet quickstart . --ignore tests/ scrap/ examples/
```

The same data, for machines: <a href="build_info.json"><code>build_info.json</code></a> (schema version 1).


# ai-agents.html.md

<!-- generated by epythet -->

# For AI agents

`annals` ships artifacts for coding agents alongside its code. This page lists
them, says where each lives in the repository, and points at the
machine-readable copies of this documentation.

## Skills

Skills are folders holding a `SKILL.md` (the [Agent Skills](https://agentskills.io) format): a description that tells an agent when to use it and a body with the procedure. Install one into your agent with `gh skill` (any host: `--agent claude-code`, `copilot`, `cursor`, `codex`, `gemini`), or use the copy bundled in the wheel.

### `annals-publish`

Publish a document or media (a markdown report, an html page, images, video, audio, a PDF, or a whole folder of renders) to the owner’s private annals and hand back the link, so they can read it on a phone or tablet away from the terminal. Use whenever the user asks to “publish this”, “post it to my annals”, “put it where I can read it on my phone”, “give me a link to that report”, “show me the images”, “where can I see the renders”, “share the page with me”, or whenever you have produced a document longer than a few lines that the user will want to read later or elsewhere. Also covers living pages (one link that stays current: `--replace`), grouping several documents under one link, listing what is in the annals, and moving a document to the recycle bin. Also use whenever you are handed an annals link (`.../annals/d/<id>` or `.../annals/g/<id>`) to read: the page is private, so read it with `annals aggregate <link>`, never by fetching the URL and never by asking for a share link.

```bash
gh skill install addaix/annals annals-publish --agent claude-code
```

Source: [`annals/data/skills/annals-publish`](https://github.com/addaix/annals/tree/HEAD/annals/data/skills/annals-publish) (bundled with the pip package).

The bundled skills are also on disk after `pip install annals`, under the package’s `data/skills/` directory; link them into an agent without network access with `skill link-skills <that directory>`.

## Machine-readable documentation

This site publishes the same documentation in forms that fit an agent’s context window:

- [`llms.txt`](https://addaix.github.io/annals/llms.txt): an index of every page with a one-line description ([llms.txt](https://llmstxt.org) format)
- [`annals.md`](https://addaix.github.io/annals/annals.md): the whole documentation as one Markdown file
- `<page>.html.md`: a rendered Markdown twin of every page, advertised from each page’s `<head>` with `<link rel="alternate" type="text/markdown">`
- [`objects.inv`](https://addaix.github.io/annals/objects.inv): the Sphinx inventory: a symbol-to-URL index (`sphobjinv convert plain objects.inv -`)


# api.html.md

# API reference

| [`annals`](_autosummary/annals.html.md#module-annals)   | annals: an in-tray for AI agents.   |
|-------------------------------------------------------------------------|-------------------------------------|


