# HANDOFF.md — state of the code and the decisions behind it

## Canonical checkout —2026-11-23

Use **`/Users/saikrupa/Projects/signet` on `main`** as the single working tree.
Earlier linked worktree paths below are historical checkpoints, not active source.
The old root's complete non-Git contents were privately archived, extracted and
regular-file SHA-256 verified before consolidation; the recovery directory is
referenced by `~/.local/var/signet-work/current-canonical-root`. Superseded prototype
source/configuration and old build outputs are kept there rather than mixed into
the tested application. Intentional cancelled-skill deletions are retained; local
agent settings/tasks and Finder metadata stay outside tracked product source.
At consolidation, application/runtime tests remained byte-identical to cc9e4cf;
subsequent native role/build fixes are recorded below. Origin is now
`git@nply.org:asapien/signet.git`; the owner authorizes push and treating secondary
GitHub mirror errors separately. Verify the primary remote SHA, not mirror output.
Consolidation commit fada598 was pushed and primary origin/main independently
verified equal; secondary mirror errors were ignored as instructed. Current HEAD
may include later documentation-only commits: Git is the source of truth. One
registered working tree remains; local task/settings metadata is preserved and
ignored. This consolidation is not a production deployment or Minci CI acceptance.

**Shared account/logout update —2026-11-30:** owner requested following
Movements, then explicitly approved commit/deploy. Source
`7eebccdbe852ed25a418d3ee942bf893cb0c3695` is published on primary main and
activated by native Minci **pipeline284**, project20, deployment record4
(success/succeeded; target acknowledgement yes). Non-loopback Signet now imports
the existing same-origin `/js/auth-ui.js` and uses its `sso-user-button` with the
API-validated username. The installed shared module sends Sign Out to
`https://sso.saikrupagas.com/logout`; no SDK copy, shared auth config change,
new backend or service restart. Loopback test-identity clearing stays unchanged.
Run: `/var/lib/signet-ci/.local/cache/minci/work/signet/runs/run.XXDpnloG`;
current release: `minci-9d87ea9f007cca44c94c07bd0e3a948b416a0caed88c5cd645a36484ec82132b`.
Installed app.js SHA256 matches source
`623900b92d7a733fcb012a828dd51802269b58b0c64e3d5fe798cded107cacee`.
JS/shared-module syntax, native build/check/package/activation and backend config
pass; all four OpenRC services remain started, API binary is byte-identical to
the prior release. Public app/assets/API/PIM anonymous requests redirect302 to
SSO; spoofed Remote-User returns403. **Authenticated browser menu/logout/session
invalidation has not been tested.** Human browser/signing/resource gates below
remain open; this is not a claim of full authentication acceptance.

**Live native beta —2026-11-24:** `https://sign.saikrupagas.com/` now redirects
to real HTTPS SSO; TLS and application routing are installed, no longer closed403.
Owner approved provisioning and server-side group lookup. Exact source
**df5fafaf964008950dc0313e4a37e8c49a5fd017** passed native **Minci pipeline281**
(project20), was activated and its real deployment record/target acknowledgement
verified. Published Minci80f778d was already on cdg-1; a separate pinned native
Alpine runner/receiver handles this target without replacing shared runners.
OpenRC API/PIM/worker/isolated AOF Redis are running and autostart; private paths,
role boundaries, lifecycle/initial empty restore and spoof/write denials pass.
Fixed multiword LDAP matching and kcgi ABI pairing; full disposable E2E and
byte-identical native synthetic-authorizer checks pass. **Real human browser
login/signing, native signing smoke and resource20 remain unverified/open.**
No live facsimiles/documents were seeded. DAM stays read-only; TSA stays disabled.
See `.scratch/beta-release/native-20261124.md` for exact receipts, recovery,
credential expiry/source-origin bootstrap and the unrelated failed APK Python
package attempt (no Python execution/forced repair). Earlier permission/domain/
Minci-capability blockers below are historical; do not ask those questions again.

**Earlier TLS-only checkpoint —2026-11-24 (superseded above):** owner confirmed
`https://sign.saikrupagas.com/` and requested fixing it first over SSH.
Fresh maa-1 inspection found no Signet installation/vhost and an incomplete
certificate request. Issued/installed TLS using existing ACME and reserved an
exact-match, deny-all proxy vhost: valid HTTPS now returns403 on every route.
**At that checkpoint this was not an application deployment.** Existing SSO/Ops/Regi smoke checks
pass; no packages/accounts/auth/application data changed. Current installed
Minci lacks the current namespace/remote helpers; Signet enrollment, native
provisioning and actual role mapping remain unresolved. See
`.scratch/beta-release/endpoint-20261124.md` for fresh evidence, recovery and
narrow approvals. Domain is no longer an open question; keep rollout29 open.

**Previous checkpoint:** the owner ended the session at a clean source-review checkpoint.
Read CONTEXT.md, this handoff, ADRs and `.scratch/beta-release/README.md`. Continue
rollout29 only when requested; verify current Minci capabilities/configuration
before treating the older inventory below as a live blocker. Public Signet domain,
per-app auth/role/write policies and actual source-bound CI/activation evidence
still need resolution. Keep14/20 and24–29 open; TSA remains optional/disabled.

Documentation reconciled against source and Git history on 2026-11-10;
workflow implementation and verification updated 2026-11-12;
optional detached timestamp source checkpoint verified 2026-11-19;
owner-requested beta preparation updated2026-11-22.
Model finalized 2026-09-19. Vocabulary in `CONTEXT.md`; working rules in
`AGENTS.md`; historical implementation plan in `docs/REBUILD.md`.
The original completed-task records below are historical reports, not fresh
verification. Source inspection found material gaps against the agreed model;
see §4. Fresh verification is recorded separately in
`.scratch/roadmap/ticket-{10,11,12,13}.md`. Integration was merged locally to main
at64e43d2265b96fad8e1bfaa8a9f1c21d860c6e36; the original dirty checkout remains
preserved in the private recovery snapshot. Beta changes were committed and
merged as cc9e4cf; canonical consolidation followed as fada598. Check actual Git
refs/status in the active worktree:
`/Users/saikrupa/Projects/signet`.

**Earlier beta request (2026-11-22):** deploy a controlled beta despite unfinished sections,
add BETA beside the logo and remove username/groups browser prompts. Frontend
preparation and next-session tickets24–29 are recorded in
[the beta queue](.scratch/beta-release/README.md); existing14/20 remain open.
Warning-clean isolated build/full E2E and native-Chrome logged-out bootstrap
checks passed. No default identity or real SSO was introduced; production login
must provide trusted identity. Owner confirmed **maa-1**, using Minci's
commit → CI run → deploy workflow. Read-only inventory confirmed Alpine/OpenRC
and existing Authelia/authz services, but no Signet installation. That inventory
was on2026-11-22: Minci fc0ea0f then provided local delivery, while remote helpers
were separate uninstalled work. This is historical evidence, not a claim about
Minci's current state; another agent may have advanced it. Origin is now supplied
and main pushed. Signet CI enrollment/target capabilities and public domain still
need fresh verification/configuration. **No production deployment or actual CI
run was performed in this session**; use selected-project Minci, not an app-owned
SSH deploy or the unselected all-project `minci-submit` wrapper. See ticket29. This request supersedes historical
no-deployment intent, not the resource failure, security/data safeguards or
native-only production policy. Owned r5 local preview18095 has only three beta
static-asset overlays; its released synthetic PDF/metadata are byte-identical.
Preserved8080/18087/18090 stacks remain unchanged. Read the beta queue before
using older source/runtime pointers below.

**Historically reported complete (Tasks 1–9; qualifications in §4):**
- Syslog logging in both FastCGI APIs (visible errors, debuggable failures)
- Prefactor renaming: schema, roles, and decision names aligned with CONTEXT.md glossary
  (PENDING_APPROVAL→PENDING, APPROVED→RELEASED, maker→drafter, approver→signer, 
   customer_id removed, render_seq/rendered_seq system added)
- Organisation-bound PIM: documents select org, imprints resolve per-org from Redis,
  image attributes stored as PIM values. The API validates PIM references at
  submit; the worker resolves them and reads DAM files at render time. This
  does not yet provide the submit-time snapshot required by D18.
- **Party-based sequential signing** (D18): templates name parties; drafter assigns
  one signer per party at submit; parties sign strictly one after another; imprints
  intended to be flattened once at submit. Current snapshot/queue/release
  gaps are listed in §4.
- **Facsimile enrolment** (D20): signers without an enrolled facsimile draw/upload
  in the browser at first signing; image kept and reused. Admin may also place one.
- **Template and series lifecycle** (D28): templates may be retired and deleted only
  after unlinking all documents; series are retired, never deleted. Retired items
  rejected at submit with 409 error.
- **Circular seal clipping** (D29): circles are clipped using 4-Bezier approximation
  (k=0.5522847498) instead of bounding-box stamping.
- **Acceptance sweep**: docs refreshed for the party/enrolment/PIM model;
  event history is visible in the document UI and printed on the audit page;
  e2e acceptance was recorded in Task 9 (`todo.txt`, commit c0b1262).

## 1. Status

**Historical Alpine 3.22 (Podman) verification reports — not rerun in this reconciliation:**

* Clean build with `-Wall -Wextra` after the rebuild acceptance sweep.
* Test suite pass recorded for Task 9 (`todo.txt`, commit c0b1262).
* Browser check done by hand: dashboard, edit mode (drag moves the `<area>`,
  property panel, palette), submit, preview mode as signer (overlays sit
  exactly on the stamped text; seal alpha correct; signature under red box).
* RSS: signet-api ≈ 2.8 MB ×2 (+ ~1 MB kcgi parser children), signetd 2.8 MB,
  pim-api 2.4 MB, kfcgi 0.5 MB ×2 → ~17 MB of the 60 MB budget.
* Error logging: all API errors visible in `podman logs signet` (both syslog and 
  stderr, allowing debugging without external syslog setup in dev).

**Fresh isolated-development verification (2026-11-12, ticket 11):** clean
Alpine build with no warnings, full `test/e2e.sh` and `render-contract` pass;
real browser signing/enrolment/release and progress regressions pass. Both-page
edit/proof/stamped/final comparisons and audit-page inspection completed using
synthetic fixtures. See `.scratch/roadmap/ticket-11.md` for logs, scope and limits.
Tickets12/13 now add frozen revision content and fail-closed identity tests;
see their notes. This is not native production acceptance: proxy/resource/native
verification below remains mandatory.

**Detached timestamp checkpoint (2026-11-19, source/test only):** optional
libcurl/libcrypto RFC3161 evidence over unchanged `final.pdf`, with separate
server sign-off/release and validated TSA time; four total release-anchored
attempts within one hour, never gating release. Disabled without explicit HTTPS
endpoint/trust and operator-installed system-cron scheduling. Final disposable
r5 warning-clean build, full E2E (including local HTTPS negatives, actual crash,
concurrent-runner exclusion, real cron, independent release, migration/access/
hash checks), incremental/staged install and101 source hashes passed. Timestamp
fixture sampled39784KiB; subsequent32-document A5-only probe33660KiB. These are
representative samples, not native/global resource acceptance. No live TSA,
browser acceptance, preview upgrade or deployment; the optional existing browser
cache is missing, and no dependency was reinstalled. See
`.scratch/detached-timestamps.md` and `docs/timestamps.md`. Ticket20 remains OPEN;
timestamp product edits are later than its restored final22 baseline.

**Not verified / never run:** OpenRC scripts, `etc/lighttpd-signet.conf`
(production config incl. WebDAV + CSP), real Authelia in front, `make install`
on a real host, JPEG variants beyond the RGB fixture, TTF fonts other than DejaVuSans, rotated or
CropBox-offset source PDFs, template with different page counts, concurrent
submits on one series.

**Git history inspected on 2026-11-10:** rebuild tasks are committed through
c0b1262; later commits on `main` add Authelia/test-container work through
68ed63b. At that historical inspection the original root had uncommitted
Authelia/dev-stack edits and local skill removals. The source/configuration delta
is now privately archived; intentional metadata removals are committed. This is
not the live inventory: use the canonical-checkout section and `git status`.

## 2. Decisions and their reasons

| # | Decision | Why |
| :-- | :-- | :-- |
| D1 | **No groff.** Overlay PDF is written by `src/pdfw.c`; `qpdf --overlay` merges | `groff -Tpdf` = `gropdf` = Perl; `.PDFPIC` only embeds PDFs (PNG would need ImageMagick, alpha doubtful); spec's sample used `.h` which is not a request. Owner accepted ("others use recommended"). Owner's motive for troff was dynamic content → covered by `serial`/`date` imprints + series + templates |
| D2 | *Superseded by D18.* Stamping at submit; approval = sign-off | Owner, mid-build: "stamping is done immediately… checkers only then send a signal that the stamped document is okay, that is essentially the signing". Hence two files: `proof.pdf` (no signatures → maker) and `stamped.pdf` (with signatures → checkers) |
| D3 | **No `STAMPING`/`FAILED` status** | Owner rejected it. Async gap was originally `rendered_revision < revision`; the agreed render gate is now `rendered_seq < render_seq` (§4 records implementation gaps); failure by `render_error` + "Retry stamping" (`POST …/rerender`) |
| D4 | *Superseded by D27.* Statuses `DRAFT, PENDING_APPROVAL, CORRECTION_REQUIRED, CORRECTED, DISAPPROVED, APPROVED` | Owner prefers these over an umbrella REJECTED. `CORRECTED` behaves exactly like `PENDING_APPROVAL` (both in `PENDING` macro); it only flags a resubmission. Correction resets `current_level` to 1 and bumps `revision` |
| D5 | *Superseded by D18.* Multi-level routes: `{"levels":[{"approvers":[…],"mode":"any"|"all"}]}` per document | Owner: many approvers, same level or through levels, several per level |
| D6 | *Superseded by D18.* Signature ref = explicit username that must appear in the route; `level:N` refs dropped | With D2 the image is stamped before anyone approves, so "whoever approves level N" is unknowable |
| D7 | *Superseded by D18.* Release (audit page + hash) runs synchronously in signet-api at the last sign-off | Needs no secrets (stamped copy already exists), keeps APPROVED atomic with `final_sha256`. `stamped.pdf` is deleted on release, correction and disapproval |
| D8 | Fonts are DAM assets (`/dam/fonts/*.ttf`), used by browser (`FontFace`) and worker (embedded, Identity-H + ToUnicode) | Owner: "don't hardcode the font, both frontend and backend use the same font via the WebDAV path" |
| D9 | Series pattern `{date:<strftime>}` / `{seq:<width>}`, counter per (series, day), serial and **document date** fixed at **first submit**; a disapproved document keeps its number (gap in the register); a resubmit keeps serial and date | Owner's example `SKGA/SCNREPLY/20260909/01`. Drafts never burn numbers. Confirmed by owner 2026-09-19 |
| D10 | No drafter free-text imprint | Owner: "don't want [that] feature for now" |
| D11 | Server never rasterises; preview = pdf.js rendering of the server-flattened PDF | ImageMagick needs Ghostscript for PDF (prohibited); gives maximal edit/preview code sharing |
| D12 | `imageMapResizer` replaced by `scaleArea()` + `ResizeObserver` (~10 lines) | Owner asked for a jQuery-less alternative; the overlay needs the resize hook anyway |
| D13 | Identity from request **headers** `Remote-User`/`Remote-Groups` (names configurable) | kcgi exposes `HTTP_*` headers via `r->reqs` but not arbitrary CGI vars like `REMOTE_USER` |
| D14 | Two OS users: `signet` (API, PIM) and `signetd` (worker, sole reader of `sig_dir`), shared group `signet`, `data_dir` mode 2770 | Privilege separation is the actual reason a worker still exists after D7 |
| D15 | yyjson 0.10.0 vendored; name "Signet" | Owner's choices |
| D16 | **No separation of duties**: the drafter may be a signer on their own document | Owner (2026-09-19): self-service is common — an authorized signatory builds a template, submits and signs it themselves to get a printable copy. Drafter/signer are roles, not people |
| D17 | A correction request voids **all** sign-offs of that revision; after resubmit every party signs again from the first | A sign-off attests one specific stamped copy; the copy changed. Owner confirmed 2026-09-19 |
| D18 | **Party model, DocuSeal-style** (`docs/adr/0001`): a template names parties; the drafter assigns one signer per party at submit; parties sign strictly one after another; the drafter reserves a signature zone, the signer fills it at sign-off with their own facsimile; release is rendered by the worker after the last sign-off. **Imprints are flattened once, at submit**; each sign-off overlays the facsimile onto the previous stamped copy, so the DAM is read only at submit and a mid-route seal/font change cannot reach a pending document | Owner 2026-09-19: "a document requires a signature of a signatory. Anyone [holding the post] can sign that box"; then "compare with DocuSeal and copy them". Replaces D2/D5/D6/D7. `any`/`all` and multi-approver levels are gone; "any partner" = the drafter picks which partner |
| D19 | At most **one zone per party**; check-only parties (no zone) exist; per-page names or initials are ordinary text imprints, not signatures | Owner 2026-09-19: initials-on-every-page is not an obvious case; "put [the] name … or place a partner text there" |
| D20 | **Enrolment at first signing**: a signer without an enrolled facsimile signs in the browser (draw/upload, as DocuSeal); the image is kept and reused; an admin may also place one | Owner 2026-09-19. Replaces the original hand-copied `sig_dir` workflow; the worker remains the sole reader of stored facsimiles (D14) |
| D21 | **No "customer" concept.** `customer_id` (free text on documents, a dashboard column, a side-panel field) is to be removed in the rebuild | Owner 2026-09-19: "I don't know how a customer got here, delete it" |
| D22 | **Title is mandatory**; the drafter must set it before submit. Replaces today's "blank → serial" default | Owner 2026-09-19 |
| D23 | **PIM is a deliberately reduced, local key/value mirror** (Redis) of the organisation's full PIM, which is too heavy to run beside Signet. **A document is bound to one organisation**, chosen by the drafter; PIM imprints reference an attribute *key* and resolve against that organisation at submit. Replaces today's literal `org:key` refs baked into the template | Owner 2026-09-19: "select an org and fetch all the gstin and bank account in the right places automatically" |
| D24 | **PIM is readable by everyone in the organisation.** No per-user redaction | Owner 2026-09-19. A redaction blacklist was considered and dropped the same day: it would have to reach the proof and the release, and "brings more problems than it solves" |
| D25 | **PIM attributes have a type: text or image.** An image attribute's value is a path on the DAM (the network drive stays the file store); the organisation's seal is its `seal` image attribute. Every image on a document comes through a PIM key, so templates stay organisation-independent | Owner 2026-09-19: "implement images feature in PIM now, not later". Replaces the drafter picking a DAM file by hand |
| D26 | **The audit page carries the whole event log**: creation, every submit, every correction request and disapproval with its reason, every sign-off, across all revisions | Owner 2026-09-19: the printed body is "squeaky clean", so the audit page is the only place the history shows |
| D27 | Statuses renamed to match the vocabulary: `DRAFT, PENDING, CORRECTION_REQUIRED, DISAPPROVED, RELEASED`. `CORRECTED` becomes a `RESUBMITTED` event, not a status | Owner 2026-09-19, on recommendation. Replaces D4 |
| D28 | **Templates are edited and retired, never silently deleted**; an admin may delete a template only after every document has been **unlinked** from it. **Series are retired, never deleted or re-patterned** once a serial has been issued | Owner 2026-09-19. Documents are self-contained copies, so unlinking loses nothing but the back-reference |
| D29 | **Latin script only** for now (no shaping). Imprint shapes: **rectangle and circle** (circle clips a round seal); `poly` dropped | Owner 2026-09-19 |
| D30 | **Private signature collections** (`docs/adr/0002`): labelled immutable facsimiles per user, one ready default, signer chooses at sign-off; the decision pins its exact owned/enrolled ID. Organisation seals remain PIM/DAM assets. Legacy files and NULL-reference decisions retain their meaning | Owner requested multiple signatures per user and organisation-owned stamps/assets, 2026-11-13; extends D20, avoids mutable-default/replacement races |
| D31 | **Detached external timestamps** (`docs/adr/0003`): optional validated RFC3161 evidence over the unchanged released PDF, separate TSA time, four total attempts within one release-anchored hour; failures never control release. libcurl + OpenSSL libcrypto, short-lived system-cron runner; explicit TSA trust, no PDF signing/key custody | Owner approved timestamp-only cushion and both libraries, 2026-11-19; not PAdES B-T, independently verified sign-off time, identity or legal qualification. Existing D18/D20/D26 behavior unchanged |

## 3. Map of the code (2026-09-19 model)

```
src/conf.[ch]      key = value config, inline "# comments", group-list helpers
src/util.[ch]      run_cmd (30s deadline, process-group cleanup, strict exit),
                   Linux direct-child parent-death safeguard, SHA-256, files,
                   is_uuid / is_safe_name / is_safe_relpath, utf8_next
src/db.[ch]        lazy PG + Redis connections, db_q / db_do
src/ttf.[ch]       bounds-checked TrueType reader: cmap 4/12, hmtx, metrics
src/pdfw.[ch]      PDF writer: pages, Helvetica fallback, embedded TTF
                   (CIDFontType2, W array, ToUnicode), PNG→RGB+SMask (libpng
                   simplified API, ≤4 MP), JPEG passthrough
src/render.[ch]    pdfinfo page sizes (+rot swap), bbox per shape, px→pt,
                   draw_text/draw_image, render_stamp (overlay + qpdf),
                   render_release (audit page + qpdf --pages), series_expand
src/snapshot.[ch]  bounded atomic PIM resolution, streamed/symlink-safe DAM
                   snapshots, per-revision manifests/hashes and rollback cleanup
src/http.[ch]      kcgi helpers: identity/roles, fields, CSRF check, path
                   split, send_json/err/file
src/signet-api.c   endpoints, placement/party visibility validation,
                   submit / decide transactions and typed-job dispatch
src/signetd.c      BRPOPLPUSH loop; stamp/sign/enrol/release branches;
                   full audit, body/final hashes, replay-safe release/cleanup
pim/pim-api.c      GET/POST /attrs, POST /resync (PG → Redis mirror)
pim/www/index.html one-page PIM editor
www/app.js         whole client; sections: helpers, fonts, geometry, imprint
                   values, overlay, layout⇄DOM, renderPdf, side panel, doc
                   view, dashboard, series, boot
sql/schema.sql     series, series_counters, templates, documents,
                   doc_decisions, doc_events, pim_attributes
etc/               signet.conf.example, lighttpd-signet.conf, init.d/*
test/              dev-up.sh (container entrypoint), lighttpd-dev.conf,
                   e2e.sh, make-fixtures.py, fixtures/
```

Disk layout: `<data_dir>/docs/<uuid>/{source,proof,stamped,final}.pdf` plus
immutable `render-<seq>.pdf` inputs, `proof-<snapshot UUID>.pdf` caches and
`snapshot-<UUID>/` assets/manifests; `<data_dir>/templates/<uuid>.pdf`,
`<dam_dir>/…`, `<sig_dir>/<user>.png`.

Current submit flow: `save` stores reference-only layout/route JSONB → `submit`
locks the document, resolves referenced organisation attributes atomically and
freezes DAM bytes into private hashed revision inputs, allocates the first
serial/date, updates status/revision/render sequence and commits →
`LPUSH {"doc_id","revision","seq","kind":"stamp"}` → worker locks the matching
pending document and renders one cached proof from frozen inputs; public proof
and initial stamped body are byte-identical. It commits `rendered_seq` and the
outcome event before acknowledging. A successful flatten survives DB failure.
The API exposes `rendering`, `rendered_seq`, `render_kind` and `can_retry`;
the client polls outstanding work and stops on error. Immutable per-sequence
render inputs prevent signature replay from overlaying a facsimile twice.
Zone sign-offs queue `sign` for the just-signed party; check-only parties advance
without rendering. Last sign-off queues `release`, which applies its optional
facsimile and appends the full cross-revision event log with body hash. Only
after final publication does the worker commit `RELEASED`/`final_sha256`, clean
stamped inputs and acknowledge. Snapshot/retry/mutation evidence is in ticket12.

Layout JSON (what `collectLayout()` emits, what `render.c` reads):

```json
{"reference_width":1000,"reference_height":1414,"imprints":[
 {"page":1,"shape":"rect","type":"pim_text","ref":"gstin","prefix":"GSTIN: ",
  "coords":[120,150,520,180],"ref_w":1000,"ref_h":1414,"font":"fonts/X.ttf","align":"left"},
 {"page":1,"shape":"rect","type":"signature_zone","party":"Manager","min_w":120,"min_h":45,
  "coords":[120,650,340,740],"ref_w":1000,"ref_h":1414}]}
```

`ref_w/ref_h` per imprint override the top-level reference size (pages can
differ). The client rasterises every page to 1000 px natural width.

## 4. Known problems and gaps

**Historically reported fixes (Tasks 1–9; see source-verified qualifications below):**
1. API errors are now logged to syslog (LOCAL0) and stderr; visible in dev (`podman logs signet`).
2. Facsimile management: signers now enrol at first signing (draw/upload browser UI);
   enrollment data stored in facsimiles table with dimensions and timestamp.
3. Party-based signing: templates define parties; drafter assigns one signer per party;
   parties sign strictly one after another (sequential). Levels/approver lists replaced.
4. Circular seal clipping: circles now clipped using 4-Bezier PDF path approximation
   instead of bounding-box stamping.
5. Template and series lifecycle: templates may be retired and deleted only after
   unlinking all documents; series are retired, never deleted. Retired items rejected
   at submit with 409 error.

**Source-verified gaps/repairs (2026-11-10 review; updated 2026-11-12):**

- **Fail-closed identity verified in ticket 13 on the integration branch.**
  Both APIs reject absent/invalid user headers; absent/unknown groups grant no
  roles. Configurable group/role and header remapping plus environment-backdoor
  regressions pass. The original checkout's unrelated uncommitted admin fallback
  was not included; do not deploy that dirty checkout. The trusted production
  proxy boundary remains unverified (ticket 14). See ticket-13 evidence.
- **D18 snapshotting implemented in ticket12.** Submit persists resolved text,
  copied/hash-verified images and fonts (including audit), date format and a
  private per-revision manifest. One proof flatten/cache supplies identical
  initial stamped bytes. Retries/sign-offs/release never reread live PIM/DAM;
  correction creates a new snapshot, preserving serial/date. Both-page visual
  and real mutation/rollback/replay tests pass; see ticket12 evidence. Upgrade
  requires the additive migration and draining legacy pending revisions; never
  manufacture historical snapshots from current values.
- **Queue/render contract repaired in ticket 10.** Typed payloads, locked
  sequence/revision/kind matching, stale/duplicate rejection, database-checked
  acknowledgement, startup recovery and kind-aware retry have targeted tests.
  Ticket 11 adds real release output/failure/replay tests; the placeholder is
  gone. See both ticket notes for evidence and limits. Full native production
  acceptance is not yet established.
- **Worker release completed in ticket 11.** Last-party overlay, aspect-fitted
  placement validation, check-only routes, complete paginated cross-revision
  audit, body/final hashes and transactional release now have API/worker/browser
  coverage. Only the worker reads stored facsimiles. Release output failures
  stay pending/retryable; DB failures retain work without a release event.
- **Submit/correction semantics repaired in ticket 11.** Empty titles are
  rejected before serial allocation. Resubmit logs `RESUBMITTED`, preserves
  serial/date and restarts party one with no old facsimiles/active decisions.
- **Sequential visibility repaired in ticket 11.** List/detail/file access is
  party-order-aware; `final` requires `RELEASED`; drafter-only access never
  exposes the pending stamped copy. Self-service remains supported.
- **Acceptance prerequisites repaired in ticket 11.** Organisation PIM JSON is
  grouped correctly and image keys resolve through Redis before DAM access.
  Browser zone/minimum metadata survives save; pointer/keyboard placement,
  first enrolment refresh and repeated notifications pass real browser tests.

**Other remaining / unverified work:**
6. **The forwarded-identity trust boundary is unproven.** lighttpd has no native forward-auth;
   the assumption is a proxy in front that sets and *overwrites*
   `Remote-User`/`Remote-Groups`. If identity only arrives as CGI
   `REMOTE_USER`, kcgi cannot see it → needs a lighttpd `setenv`/mod_magnet
   shim or a patch. Header spoofing must be impossible in production.
7. **DAM WebDAV write access** is not restricted in `lighttpd-signet.conf`
   (comment says "restrict at the proxy"). Decide and implement; anyone who
   can PUT a seal or font changes future submits; pending revisions now retain
   their frozen bytes. There is no DAM upload UI — by design
   it is a network drive.
8. Rotated pages: handled only by swapping w/h from `pdfinfo`; untested.
   Non-zero MediaBox origin / CropBox: relies on qpdf's overlay fitting.
9. No complex-script shaping (Tamil etc.). Latin + symbols (₹ if the font has
   it). OTF/CFF fonts are rejected → Helvetica fallback with a log line; the
   *browser* would still show the OTF, so edit ≠ proof in that case. Consider
   filtering `/api/dam` fonts through `ttf_load`.
10. `GET /docs` caps at 200 rows, no pagination/search.
11. Source-only upload/parser repairs retain32MiB PDF capacity via256KiB
    application chunks. API/PIM bodies are capped before kcgi at16KiB except
    multipart/form-data at1100KiB. Two900000-byte dense-form requests had
    exceeded120MiB aggregate RSS despite404 responses; tracker23 repairs this
    pre-parser gap. Large logical fields use multipart. Three near-cap nested
    multipart requests plus dense query/cookies peak50052KiB in the fixture;
    this is NOT mixed renderer/native certification. Native writer compression
    now uses16KiB output chunks, reducing maxRGB+font fixture32728→16216KiB.
    The72240KiB retained-request counterexample is now repaired source-only:
    both APIs discard unused/repeated fields and recycle large libpq I/O caches
    at request end. Seven final mixed samples peak57020KiB with exact pixels/font
    bytes.20 remains OPEN for other overlaps/cardinality/native acceptance; this
    is not a whole-runtime certificate. See `.scratch/request-retention.md`,
    `.scratch/image-memory.md` and `.scratch/bounded-parsers.md`.
    New2026-11-17 test-only diagnostic reproduces60992–62716KiB with just one
    unpruned PIM request overlapping qpdf. This DIFFERENT budget blocker is NOT
    repaired; `.scratch/parser-window.md`. Product source remains final22;
    parent20 requires a pre-materialization/coordination repair, not lower caps.
    A2026-11-18 parent-only admission experiment was rejected/reverted: reverse
    worker-first order still failed59136/59296KiB with a buffered kcgi child.
    Product source remains final22. Read `.scratch/parser-coordination.md` before
    another gate; request-first success alone is insufficient.
    Owner-provided typical profile is small single-page A5 text PDFs. A synthetic
    32-document signing/release batch samples33528KiB (warm33952KiB), full E2E
    passes; `.scratch/a5-workload.md`. This is representative sequential evidence,
    not a waiver of the above failures or native acceptance.
12. Redis AOF must be enabled in production (`appendonly yes`); not enforced.
    If `LPUSH` fails after the submit commit the doc sits un-stamped until
    someone presses "Retry stamping" (no automatic sweep in signetd).
13. CSP in `lighttpd-signet.conf` is untested against pdf.js (worker,
    `blob:` images, inline `style` attributes set via `h()`).
14. PIM resync no longer uses `FLUSHDB` in integration source (tracker19).
    Scoped atomic reconciliation, canonical type/deletion mirroring, queue/
    foreign-key preservation, cache-error recovery and two-worker ordering pass
    disposable/full E2E/render tests. See `.scratch/pim-resync.md`. This fix is
    NOT installed on preserved :18087: do not invoke its old Resync action.
    Shared namespace allocation/native acceptance remain open.
15. PDF writer allocation failures repaired/dev-verified in tracker21:
    deterministic tests reproduced content/font leaks and persistent allocation
    retry in PDF open (not cprintf). Temporary realloc ownership, unpublished
    font cleanup, failed-open cleanup and failed-close finalisation guards now
    pass19-point transient/persistent injection, full E2E/render and both-page
    browser visual checks. Source-only; `.scratch/pdfw-allocation.md`.
16. Tracker22 repaired/dev-verified source-only2026-11-16: shared `send_err()`
    logs every API-emitted4xx/5xx with normalized route, validated actor, status
    and source site; backend diagnostics use SQLSTATE/operation, not raw values.
    Dev foreground kfcgi preserves stderr, including after pool/container restarts.
    Actual container capture and temporary LOCAL0/privacy regressions pass.
    `.scratch/api-logging.md`; pre-API errors and persistent native capture remain
    separate deployment gates. No preserved preview was upgraded.

## 5. Completed tasks (Tasks 1–9)

Tracker completion records are reproduced below. They do not establish that
all behavior in the 2026-09-19 model is implemented; §4 records contradictions
found in the current source.

| Task | Changes | Status |
|------|---------|--------|
| 1 | Syslog logging in FastCGI APIs | ✓ 2026-09-19 |
| 2 | Prefactor: vocabulary alignment + render gate | ✓ 2026-09-19 |
| 3 | Org binding for PIM; image attributes | ✓ 2026-09-19 |
| 4 | Parties model; zones; sequential signing | ✓ 2026-09-19 |
| 5 | Enrolment flow (browser, worker, schema) | ✓ 2026-09-19 |
| 6 | Sign-off overlays; worker release | ✓ 2026-09-19 |
| 7 | Template/series lifecycle; retire/delete/unlink | ✓ 2026-09-19 |
| 8 | Circular seal clipping with Bezier paths | ✓ 2026-09-19 |
| 9 | Docs, invariants and acceptance sweep | ✓ 2026-09-19 |

## 6. Open questions for the owner

* Who may write to the DAM? Snapshots protect pending revisions; writer policy
  still determines who may alter future submitted content.
* Which isolated native Alpine/OpenRC target and shared-service allocations may
  be used for ticket14? Upload/child/decoded-image peak resources, containment,
  backup/restore and coexistence need measurement before touching maa-1.
* Is a cryptographic PDF signature (PAdES) wanted later? Would need a new
  allowed dependency.
* Fix `~/.ssh/known_hosts` line 47 so host `podman` works? (Not touched.)

## 7. Next steps

Latest session resume/safety checklist: `.scratch/session-handoff.md` (2026-11-17).
The integration worktree was recovered from final22 into a durable directory;
use the path in that checklist, not the now-incomplete historical `/tmp` tree.
Owner reordered remaining work22 →20 →rest;22 is now source-only complete.
Continue20's remaining overlap/cardinality/native gates before production work.

**Feature-first priority (2026-11-10):** Signet supports trusted forwarded
identity (`Remote-User` plus the existing configured group/role mapping), not
an authentication-server implementation. The deployment administrator chooses
and manages the provider; Authelia-specific work is outside product scope.
Fail-closed identity handling and the forwarded-header trust boundary remain
production gates, not prerequisites for isolated feature development. Current
original-checkout missing-header admin experiment is unsafe and excluded from
the integration branch; ticket 13 now verifies the fail-closed implementation.

The implementation scopes and acceptance criteria are in
`.scratch/roadmap/spec.md`, indexed by tickets 10–14 in `todo.txt`/`done.txt`:

1. **Ticket 10:** render-job payloads, sequence gates, retry and database
   acknowledgement, including client progress handling, now have targeted
   implementation/tests; see `.scratch/roadmap/ticket-10.md`.
2. **Ticket 11 completed:** sequential facsimile overlays, worker-owned release,
   party/file visibility, correction/resubmit events and title validation pass
   targeted acceptance; see `.scratch/roadmap/ticket-11.md`.
3. **Ticket12 completed:** frozen PIM/DAM bytes and one immutable proof per
   revision; mutation, retry, correction and visual checks pass. See
   `.scratch/roadmap/ticket-12.md`.
4. **Ticket 13 completed:** fail-closed identity handling, config-only role/header
   mapping and both-API tests pass without an authentication-server dependency.
   See `.scratch/roadmap/ticket-13.md`. Proxy trust remains ticket 14.
5. **Ticket14 incomplete, before production:** verify trusted proxy identity,
   decide DAM writer policy and complete runtime/native Alpine/OpenRC acceptance.
   Local guards limit save/submit JSON before parse/clone and bound external
   commands to30s with group cleanup/Linux direct-child parent-death protection;
   unit, actual hang/retry, fixture suites and browser checks pass. HTTP buffering,
   decoded assets and aggregate/service-level resources remain unbounded by
   those guards and require further work. Follow-up18 now bounds decision
   placement and stored-layout parsing using the same1 MiB byte policy; exact
   limits, multibyte legacy rejection and correction recovery pass full E2E/
   render tests. This source-only change is NOT installed on preserved :18087.
   Resource audit and remaining technical blockers20/22:
   `.scratch/resource-audit.md`. Tracker21 allocation-failure repair now passes
   deterministic fault injection and renderer/browser acceptance in source;
   `.scratch/pdfw-allocation.md`. NOT installed on preserved previews. Follow-up19 also repairs global PIM Redis
   flushing and ordered mirror publication in source, with full regression
   evidence in `.scratch/pim-resync.md`. Neither fix is installed on :18087.
   Follow-up20 now repairs the concrete upload counterexample in source:32MiB
   PDF files use256KiB application chunks; all API/PIM prefixes have a pre-kcgi
   1100KiB request cap. Two max files plus near-cap ignored fields/hash checks
   give29,660KiB sampled peak versus182,624KiB before repair. Migration003,
   owner/readiness/retry/failed-commit recovery, full E2E/render and browser
   regressions pass. See `.scratch/bounded-uploads.md`. NOT installed :18087;
   API/browser/config/migration must move together on a separately approved
   upgrade. Tracker20 remains open for parser/image/font/render aggregation
   and native acceptance; this is not a whole-runtime RSS certificate.
   Tracker23 additionally repairs dense form amplification (122884KiB for two
   900000-byte requests): non-multipart bodies now have a16KiB pre-kcgi cap,
   multipart keeps1100KiB/1MiB logical fields. Three heavily populated multipart
   API/PIM requests with query/cookies peak50052KiB; both32MiB uploads, full
   E2E/render and real browser signing/upload tests still pass. Source-only,
   NOT installed :18087. `.scratch/bounded-parsers.md`; other20/22 work stays open.
   Native writer image/font compression now streams with exact decoded-byte,
   fault and two-page visual tests; fixture32728→16216KiB. Subsequent API request
   compaction and large libpq-cache recycling repair the retained-request mixed
   case (seven final samples <=57020KiB). The strip-rendering prototype was
   rejected/reverted.20 stays open for other overlaps/cardinality/native gates.
   Latest source/evidence: `.scratch/request-retention.md`; no preview install.
   Owner inputs, remaining work and evidence: `.scratch/roadmap/ticket-14.md`.
   Image-reader review also repaired opaque JPEG snapshots and matched image
   interpolation to the browser; RGB byte-preservation and both-page visual
   regressions pass. See the same ticket14 evidence, not a native certificate.
   Keep provider-specific auth experiments separate from application work.
6. Later: font-list validation and document-list pagination/search.

Add regression coverage and rerun acceptance for implementation changes; the
historical completed tickets do not substitute for fresh evidence.

## 8. Dev environment facts

* Preserve the user's `signet-jpeg-loopback` at `http://127.0.0.1:18087`
  (image `signet-jpeg-final`), its documents and the ticket11 :8080 stack.
  Earlier :8087 conflicted with an unrelated service; that service is untouched.
  Owner-approved in-place signature-collection upgrade completed 2026-11-14;
  original records/files/config/Redis preserved, backup/restore rehearsed.
  See `.scratch/preview-upgrade.md`. Do not run destructive contracts or
  reinitialise the user's preview.
* Signature collections (D30) are implemented/dev-verified and integrated,
  uncommitted in `feat/feature-first-roadmap` and `feat/signature-collections`. Clean synthetic preview:
  `signet-signatures-preview` at `http://127.0.0.1:18090`. Verification stack
  :18089 and early :18088 are stopped/retained. Full evidence, source/image
  hashes and scope: `.scratch/signature-collections.md`. No production/maa-1
  services or the original checkout changed; commits/publication are pending.
* Dev startup now keeps worker and lighttpd as siblings, not an exec'd web
  server inheriting the worker. Three graceful restarts and nonoverwriting
  seed/config persistence pass in disposable stacks. The fix is now installed
  in :18087 too; graceful and full-container restart/preservation checks pass.
  `--init` alone was insufficient.
  Fixture RSS samples do not certify native peak resource safety.
* Podman machine `podman-machine-default` (2 CPU / 2 GB / 20 GB) was created
  for this project; image `signet-dev`; a container named `signet` may still
  be running on :8080 with throw-away data. `test/dev-up.sh` initialises the DB
  only when absent; restarting an existing container does not reset it.
* Alpine 3.22 packages used: `kcgi-dev`, `hiredis-dev`, `libpq-dev`
  (headers in `/usr/include/postgresql`, found via `pkg-config`),
  `postgresql16`, `redis` 8, `lighttpd` 1.4.85 + `lighttpd-mod_webdav`,
  `qpdf` 12, `poppler-utils`, `font-dejavu` (test font).
* kfcgi flags: `-u` = socket owner (lighttpd), `-U` = process user (signet),
  `-p /` = no chroot (we exec qpdf and link libpq dynamically).
