# AGENTS.md — working rules for this repository

Read `CONTEXT.md` first (the glossary — use its words), then `HANDOFF.md`
(current state, decisions and why, open work) and `docs/adr/`. `README.md` is
the user-facing description and install guide. The invariants below are the
required design, not a claim that the current code satisfies every one.
See `HANDOFF.md` §4 for source-verified gaps and `docs/REBUILD.md` for the
historical implementation plan. Resolve the active checkout from HANDOFF's
canonical-checkout section; older worktree paths are historical.

## Hard constraints (from the owner; do not relax without asking)

* Target: bare-metal Alpine Linux + OpenRC, 1 vCPU / 1 GB RAM. All Signet
  processes together must stay **under 60 MB RSS** (currently ~17 MB).
* **Prohibited in production:** Docker/containers, Node.js, Python, Ruby, Java,
  headless Chrome/Puppeteer, DOMPDF, Ghostscript, any PDF wrapper library.
  Podman is used **only** on the dev machine for testing.
* Allowed: native C, `qpdf`, `pdfinfo`/poppler-utils, `lighttpd`
  (+`mod_webdav`, `mod_fastcgi`), PostgreSQL 16+, Redis, `kcgi`/`kfcgi`,
  `hiredis`, `libpq`, `libpng`, `zlib`, **libcurl + OpenSSL libcrypto**
  (owner-approved for optional detached RFC3161 evidence, 2026-11-19;
  `docs/timestamps.md`). JSON is **yyjson** (vendored, owner's
  choice). `php-fpm`, `imagemagick`, `groff` are permitted by the original spec
  but deliberately unused — do not add them back without a reason.
* Frontend: vanilla HTML/JS, no framework, no jQuery, no build step. Only
  third-party JS is vendored `pdf.js` 3.11.174 (UMD build). No CDN at runtime.
* RBAC group names are **never hardcoded**; they come from
  `/etc/signet/signet.conf` (`role.<name> = group, group`).
* PIM and DAM are separate, simple components. The signing app is the product.

## Invariants — breaking these is a bug

1. **The DOM is the layout state.** Every imprint is an `<area>` in the page's
   `<map>`; `data-coords` holds natural-pixel coordinates, `coords` is the
   scaled copy. Overlay boxes are *derived* from areas (`syncOverlay`), never
   the other way round.
2. **Edit and preview share code.** Same page renderer, same area model, same
   overlay generator; the only difference is what a box does (draggable layer
   vs. translucent marker over the server-flattened PDF).
3. **Text fitting is duplicated on purpose and must stay identical:**
   `fitText()` in `www/app.js` ⇔ `draw_text()` in `src/render.c`
   (size = 70 % of box height, shrink to fit width, vertically centred on
   ascent/descent). Change one, change the other, then compare edit mode
   against the proof visually.
4. **Clients never supply values, only references.** PIM text is resolved
   server-side from Redis (`HGET <org>:metadata <key>`); DAM refs are
   validated relative paths; signer refs are validated usernames. Facsimile
   UUIDs must resolve to an enrolled variant owned by the deciding signer.
5. **Only `signetd` reads `sig_dir`.** `signet-api` must never open a
   signature file. Drafters receive `proof.pdf` and, after release, `final.pdf`;
   `stamped.pdf` requires signer access on that document or admin access.
6. **Party-based sequential signing.** A template defines parties; the drafter
   assigns one signer per party at submit. Parties sign strictly one after
   another. Each sign-off overlays the signer's enrolled facsimile onto the
   previous stamped copy. Release happens in the worker after the last sign-off.
7. **Facsimiles are private, immutable user-owned variants (D30).** A signer
   enrols before or at first signing and chooses an enrolled variant at sign-off.
   Record its ID in the decision; defaults affect future choices only. The
   worker alone reads originals (`sig_dir`); admin enrolment adds a variant
   rather than replacing one. Preserve legacy user-named files/history during
   migration. See `docs/adr/0002-private-signature-collections.md`.
8. **Stamping produces only one cached copy per revision.** At submit, imprints
   are flattened once and stored as JSONB placement data. Each sign-off reads
   this placement and overlays a facsimile. PIM is read only at submit; a
   mid-route change to PIM cannot reach a pending document.
9. **A job leaves `<queue>:processing` only after PostgreSQL is updated.**
   Keep `BRPOPLPUSH` + `LREM`; startup drains `:processing` back to the queue.
10. **Serial numbers are allocated once, inside the submit transaction**
    (rolled back if submit fails) and never change across corrections.
11. Every path component that came from a request goes through `is_uuid`,
    `is_safe_name` or `is_safe_relpath` (`src/util.c`) before touching the
    filesystem. All SQL is parameterised (`db_q`/`db_do`).
12. External commands run only through `run_cmd()` (fork/execvp, exit status
    must be 0). No `system()`, no shell.

## Code style

* C99, OpenBSD KNF: tabs, return type on its own line, `snake_case`,
  `static` for file-local functions, sorted includes, no dynamic allocation
  where a bounded buffer does.
* Must compile clean with `-Wall -Wextra` (the Makefile sets this). yyjson is
  compiled separately without `-Wextra`.
* JSON responses are built by PostgreSQL (`row_to_json` / `json_agg`) and
  passed through; yyjson is for parsing input and the two small mutable
  documents in `/pim` and `/dam`.
* When a statement uses the same `$n` in a `SELECT` list and a `WHERE`, cast
  it (`$2::varchar`) — PostgreSQL otherwise fails with "inconsistent types
  deduced" Log failures through the existing stderr/syslog error helpers.
* JS: one file, `'use strict'`, DOM built with the `h()` helper and
  `textContent` only (no `innerHTML`). `parent.append()` does **not** filter
  `null` — only `h()` does.
* Comments explain *why*; match the density of the surrounding file.

## Build, run, test

Nothing builds natively on the owner's Mac (no kcgi/libpq/qpdf there); use the
Alpine container.

```sh
podman build -t signet-dev .
podman rm -f signet; podman run -d --name signet -p 8080:8080 signet-dev
sleep 6 && podman exec signet /src/test/e2e.sh        # must end with "all passed"
```

> On the owner's machine the host `podman` CLI currently fails with
> `knownhosts: ... line 47: missing key type pattern` (a malformed line in
> `~/.ssh/known_hosts`; do **not** edit that file without asking). Workaround:
> `podman machine ssh "cd /Users/saikrupa/Projects/signet && podman build -t signet-dev ."`
> and likewise for `run` / `exec` / `cp`. `/Users` is mounted in the VM.

* Fast loop for client-only changes:
  `podman cp www/app.js signet:/var/www/signet/app.js` (same for `style.css`).
  C changes need a rebuild of the image. A newly created container has fresh
  data; restarting an existing one preserves its initialized database.
* Browser testing: use the owned disposable preview from HANDOFF; never run
  destructive contracts against preserved previews or production. Missing/invalid
  identity fails closed in both APIs; missing groups grant no roles. There are no
  startup username/groups prompts. Deliberate `localStorage.signetDevIdentity`
  test headers are loopback-only; they are not login or proxy-auth evidence.
  Production must overwrite identity headers and prevent backend bypass. See
  `TESTING-AUTH.md` for the isolated test facility and configurable example groups.
* `curl` POSTs with no body get `411` from lighttpd — send `-d ''`.
* All state-changing requests need `X-Requested-With: signet`.
* Portable files can be syntax-checked on macOS:
  `cc -std=c99 -D_DARWIN_C_SOURCE -Isrc -fsyntax-only src/{conf,util,ttf}.c`,
  `node --check www/app.js`.
* **Error logging:** API-emitted 4xx/5xx use shared `send_err()`; its summary
  logs normalized route, validated actor, status and source site to stderr and
  LOCAL0 (warning for 4xx, error for 5xx). Keep private values/raw backend errors
  out of diagnostics; use SQLSTATE. Dev kfcgi must retain stderr (`-d`). For
  capture regressions/native logging boundaries, read `.scratch/api-logging.md`.
  Persistent native LOCAL0.warning capture/rotation remains an admin gate.

Extend `test/e2e.sh` with every API behaviour change; it is the regression
suite. After any change to `render.c`, `pdfw.c`, `ttf.c` or `fitText`, also do
the visual check (edit mode vs. proof vs. stamped copy, both pages).

## Repository conventions

* Git history exists (including rebuild and Authelia work). Commit only when
  the owner asks; branch first if on the default branch. Preserve unrelated
  working-tree changes.
* `vendor/` and `www/vendor/` are third-party, fetched verbatim — do not edit.
* Existing `test/fixtures/` contain synthetic data only. Their historical
  `test/make-fixtures.py` is not permission to execute Python; per-use approval
  is required by the owner's policy. Prefer existing native fixture facilities.
  Never commit real signature images.

## Agent skills

### Issue tracker

`todo.txt` at the repo root, one task per line, tagged by component
(`+api`, `+worker`, `+client`, …); completed lines go to `done.txt`; long-form
bodies under `.scratch/`. See `docs/agents/issue-tracker.md`.

### Triage labels

The five default roles, written as `status:<role>` tags on the todo line.
See `docs/agents/triage-labels.md`.

### Domain docs

Single-context: `CONTEXT.md` (glossary) + `docs/adr/`; state and the
decisions table live in `HANDOFF.md`. See `docs/agents/domain.md`.
