# sarracenia

# sarracenia

A Rust CLI that scans a repo's documentation and pushes it to Storefront. See `docs/ROADMAP.md` for where this is going.

## Building

```
just build
```

Requires the `common` git submodule: `git submodule update --init`.

## Configuration

`sarracenia` reads `./sarracenia.toml` by default, or the path given with `--config`:

```toml
source = "docs-pipeline"
base_path = "/"
title = "My Product"
prune_guard_min_ratio = 0.5
include = ["**/*.md"]
exclude = []

[storefront]
url = "https://example.com"
site = "docs"

[diagrams]
format = "svg"

[rust]
include_private = false
```

`title` is optional: it names the synthetic page created for the walk root when the root has no `README.md` or `index.md`, and is used as that page's title and sidebar label. Without it, the page is titled after the directory the command runs in. A real root `README.md` or `index.md` always wins, and `title` never applies to nested synthetic directory pages. An empty or blank `title` is an error. `scan` prints the resolved title.

`[titles]` is an optional table mapping a repo-relative directory to the title of its synthetic page (`[titles]` then `"src" = "Module reference"`). It applies only to directories that have no `README.md` or `index.md`; a key naming any other directory, or an empty value, is an error naming the key. Without an entry a synthetic page is titled with its humanized directory name (`reserved_paths` becomes `Reserved paths`).

Unknown keys and a missing `source` are hard errors naming the key. The Storefront token is never read from this file: set `SARRACENIA_TOKEN` in the environment. `[storefront] site` must name the site `SARRACENIA_TOKEN` is bound to: `check` and `push` fetch the token's site (`GET /api/auth/me`) and fail before any write if it differs from this key, naming both sites.

## Commands

```
sarracenia scan [--strict] [--diagram-format svg|png]                           # print the page tree, no network call
sarracenia push [--dry-run] [--strict] [--no-media] [--allow-mass-prune] [--diagram-format svg|png]  # push the page tree, or print the payload summary
sarracenia check                                                                # validate config, token and site reachability
```

`scan` and `push` walk the repo rooted at the current directory for `*.md` files, honoring `.gitignore` and the config's `include`/`exclude` globs, and always skipping `.git`, `target` and `node_modules`. Each Markdown file becomes a page; a directory's `README.md` (preferred) or `index.md` becomes that directory's own page, and a directory with neither gets a synthetic page so its children still have a parent. Page order (`sort_order`) is deterministic: a sibling literally named `index` sorts first, the rest alphabetically by slug. A Markdown page's title is the `title:` of its leading `---` front matter (the block is not published), else its first `#` heading, else the humanized file stem (separators become spaces, first letter capitalized); a synthetic page is titled by its `[titles]` entry, else its humanized directory name, or the config `title` for the root. `--strict` fails when a page's title is only its raw file or directory name. Path collisions and reserved paths (routes Storefront already owns, e.g. `/search`, `/media/*`, `/*.md`) are checked before any network call and name every file involved. `push` always sends `prune: true` so pages removed from the repo are retracted on the far side; `--dry-run` builds the same payload and prints a summary instead of sending it.

`prune_guard_min_ratio` (optional, 0.0 to 1.0, default `0.5`) guards that prune: before writing anything, `push` asks Storefront how many pages the source owns today (`GET /api/pages?source=<source>`) and refuses, naming both counts, when the scan found zero pages or fewer than that fraction of them (a wrong working directory or `include` glob would otherwise delete the docs section). `--allow-mass-prune` skips the check for an intentional cut-down. `--dry-run` makes no network call, so with zero pages it only warns.

Every relative Markdown link between repo files (`[x](../other.md)`, reference-style, with an anchor, in a table) is rewritten to the target page's absolute Storefront path before the push, resolved against the source file's position in the repo rather than its rendered page, so it is correct independently of how an index page's own links resolve in the browser. Links inside code spans/blocks and external URLs (`http:`, `https:`, `mailto:`) are left untouched. A link to a `*.md` file that cannot be resolved is printed as a warning naming the file and line; `--strict` turns that into a non-zero exit.

`push` uploads every local non-Markdown file a page references (`![x](img/a.png)`, `[spec](file.pdf)`) to Storefront's media library (`POST /api/media`) and rewrites the reference to the returned public URL; `scan` never touches the network, so it leaves those references as-is. A file's content is hashed (SHA-256) so the same bytes referenced under two different paths upload once per run; the hash-to-URL map lives only in memory for that run, so re-pushing an unchanged file uploads it again; Storefront gives no dedupe signal on this route today. A referenced file that is missing, outside the repo, over the 100 MiB limit, or with an extension outside the allow-list (`jpg`, `jpeg`, `png`, `webp`, `gif`, `svg`, `mp4`, `m4v`, `webm`, `mov`, `pdf`, `doc`, `docx`, `txt`, `csv`, `xls`, `xlsx`) fails the push naming the file and the line that references it. A token without the scope the upload needs fails the same way, naming the file and the response Storefront gave; uploads are never skipped silently. `--no-media` pushes the page tree without uploading anything, leaving every local file reference as-is and logging that it was skipped. Uploads go into a media library folder derived from `base_path`, so assets pushed from different sources do not collide.

`push` renders every fenced ` ```mermaid ` / ` ```d2 ` block in a page, and every standalone `*.mmd` / `*.d2` file a page references, to an image and uploads it the same way as ordinary media; the fence or reference is replaced by the uploaded URL. Rendering is pure Rust (`mermaid-rs-renderer` for Mermaid, `d2-little` for D2): no browser, Node or external CLI is required. The output format is SVG by default, or PNG with `[diagrams] format = "png"` / `--diagram-format png`; PNG conversion (`resvg`/`usvg`) embeds one font (DejaVu Sans, `src/fonts/DejaVuSans.ttf`, Bitstream Vera license) rather than using the host's installed fonts, so the same diagram source renders to identical bytes on every machine and CI runner. A diagram that fails to render (a syntax error in the source) fails the push naming the Markdown file and the line the fenced block opened on, or the file referenced.

`*.rs` files are scanned alongside Markdown for Rust doc comments (`//!` module docs, `///` / `#[doc = "..."]` item docs on `fn`, `struct`, `enum`, `trait`, `impl` items, `const`, `type` and `mod`). A file with at least one doc comment becomes a page at its mirrored path (`src/foo/bar.rs` -> `<base_path>/src/foo/bar`); a file with none gets no page. The page's H1 is the module docs' first heading, or the humanized file name; each item gets its own section with a signature code block (declaration without body) and its docs, in source order. Private items (anything short of `pub`, including `pub(crate)`) are excluded unless `[rust] include_private = true`. A file that fails to parse fails the run naming the file.

`-v` (repeatable) and `RUST_LOG` control log verbosity.

## Provenance

`push` sends the `provenance` object Storefront keeps in its push history, so the Docs sync screen can say which repo, commit and CI run produced a push. Values come from the Forgejo/Gitea Actions environment (`GITHUB_SERVER_URL` and `GITHUB_REPOSITORY` for `repo_url`, `GITHUB_SHA` for `commit`, `GITHUB_REF_NAME` for `ref_name`, `GITHUB_RUN_ID` for `run_url`, built as `<repo_url>/actions/runs/<id>`), falling back to `git rev-parse` for the commit and ref, and to `git log -1` in the current directory for the commit subject, author name and author email. Provenance is best-effort metadata: git being absent leaves those fields out, and a value Storefront would reject (a non-https URL, a commit that is not 7 to 64 hex characters, an invalid email) is dropped with a warning rather than failing the push. `--dry-run` prints what would be sent. Storefront does not accept per-page source paths or edit links today, so none are sent.

## Adopting sarracenia in another repo's CI

Every published Forgejo release (`vX.Y.Z`) and every push to this repo's `main` (as `latest`) publishes a musl-static Linux x86_64 binary to the organization's Forgejo Generic Packages registry at `<host>/api/packages/<org>/generic/sarracenia/<tag>/sarracenia-linux-x86_64`, where `<host>` is your Forgejo server and `<org>` the organization that owns the repo. A release run publishes only its `vX.Y.Z` files and never touches `latest`; the main-push run publishes only `latest`. Each `vX.Y.Z` also carries `sarracenia-linux-x86_64.sha256` (`<sha256>  sarracenia-linux-x86_64`), and the release run downloads both files and checks them before it passes. Pin an exact `vX.Y.Z` tag in a consuming repo; `latest` tracks `main` and is meant for this repo's own dogfooding, not for a pinned dependency. The registry's `files` API (`<host>/api/v1/packages/<org>/generic/sarracenia/<tag>/files`) returns the `sha256` of the published blob; verify against that field or against the `.sha256` file. The snippets below read the first entry of the `files` listing, which now holds two files for a release; that ordering is not guaranteed yet.

Local use (Nushell):

```nu
let host = "https://<your Forgejo host>"
let org = "<your organization>"
let tag = "v1.2.3"  # pin an exact release tag
let file = "sarracenia-linux-x86_64"
let url = $"($host)/api/packages/($org)/generic/sarracenia/($tag)/($file)"

http get $url | save --force $file
let want = (http get $"($host)/api/v1/packages/($org)/generic/sarracenia/($tag)/files" | get 0.sha256)
let got = (open --raw $file | hash sha256)
if $got != $want {
    error make { msg: $"sarracenia checksum mismatch: got ($got), want ($want)" }
}
chmod +x $file
mv $file sarracenia
SARRACENIA_TOKEN=... ./sarracenia push
```

A Forgejo workflow step doing the same (mapping syntax):

```yaml
- name: Download sarracenia
  shell: nu {0}
  run: |
    let host = "${{ github.server_url }}"
    let org = "${{ github.repository_owner }}"
    let tag = "v1.2.3"
    let file = "sarracenia-linux-x86_64"
    let url = $"($host)/api/packages/($org)/generic/sarracenia/($tag)/($file)"
    http get $url | save --force $file
    let want = (http get $"($host)/api/v1/packages/($org)/generic/sarracenia/($tag)/files" | get 0.sha256)
    if (open --raw $file | hash sha256) != $want {
      error make { msg: "sarracenia checksum mismatch" }
    }
    chmod +x $file
    mv $file sarracenia

- name: Push docs to Storefront
  env:
    SARRACENIA_TOKEN: ${{ secrets.STOREFRONT_TOKEN }}
  run: ./sarracenia push
```

Check in a `sarracenia.toml` at the consuming repo's root; see [Configuration](#configuration) above for its shape. This repo's own `sarracenia.toml` is a worked example: it publishes this README and the `src` module docs (not the internal `docs/ROADMAP.md`) to the configured Storefront docs site under `/docs/sarracenia`.

### Token model

`SARRACENIA_TOKEN` is a Storefront `sfk_` token, never read from `sarracenia.toml`. A `content`-scoped token is enough for `push` runs that touch only Markdown pages (no local media, no Mermaid/D2 diagrams): page create/update/prune goes through the content API only. A run whose pages reference local media files, or whose Markdown contains fenced `mermaid`/`d2` blocks or `*.mmd`/`*.d2` file references, uploads through `POST /api/media`, which requires a full-scope admin token (`admin` or `super_admin` role) and answers `403` for a content-scoped token. `--no-media` lets a content-scoped token push pages without needing the wider scope. `check` validates the token and site reachability against whichever scope it is given, and both `check` and `push` fail if the token's site does not match `[storefront] site` (see Configuration above); a Storefront too old to report the token's site fails the same way, naming the missing `site_slug` field, rather than skipping the check.

### Exit codes

Requests to Storefront retry transient failures: connect errors, timeouts, and HTTP 429, 502, 503 and 504, up to 4 attempts in total with 1 s, 2 s and 4 s between them (a `Retry-After` header of up to 30 s replaces the wait). Other 4xx and 500 responses fail immediately. Each retry is logged at warn level. JSON requests time out after 30 s; a media upload times out after 60 s plus 1 s per 256 KiB of file (about 7 minutes for the 100 MiB limit).

Every command exits `0` on success. Any error (a config parse failure, an unresolved required field, a `--strict` link failure, a failed diagram render, a failed media upload, a token/scope rejection, an unreachable site) prints `Error: <cause>` to stderr and exits `1`; there is no distinct exit code per error class.

## Checks

```
just pre-push
just check-justfile
```

`just pre-push` mirrors `.forgejo/workflows/check.yml`: `cargo fmt --check`, `cargo clippy --all-targets --all-features -- --deny warnings`, `cargo build --all-targets`, `cargo test`. `just pre-commit` only runs `check-tree-ownership` and a fmt-only check; run `just install-hooks` after bumping `common` to get the `pre-push` git hook.

## Releasing

```
just create-release <major|minor|hotfix>
```

See `common/README.md` for the release flow.
