: asapien/signet

commit 116764a823de29f175d7fcb1152ce359d7e0969c
parent 5641808f15789ddf781737935100197c0ea54845
Author: Bharatvaj Hemanth <bharatvaj@yahoo.com>
Date: Sat, 19 Sep 2026 04:11:00 +0530

Task 3: Organisation-bound PIM imprints, image attributes

Implement organisation binding for PIM resolution and add image
attribute support. Documents now select an organisation; PIM
imprints resolve per-org from Redis hashes. Images are stored
as PIM attributes (DAM-relative paths).

Schema (sql/schema.sql):
- Add org_code VARCHAR(50) to documents (nullable in DRAFT, required at submit)
- Rename entity_code → org_code in pim_attributes
- Add attr_type VARCHAR(5) with CHECK (text|image)
- Redis mirrored to per-org hashes: <org>:metadata, <org>:images

API (src/signet-api.c):
- /save: validate org_code, reject dam_image/signature/poly types
- /submit: require org_code NOT NULL, resolve pim_text/pim_image per org
- check_submittable: validates PIM keys and DAM files exist before submit

Render (src/render.c, render.h, src/signetd.c):
- Add org_code to struct render_ctx
- Update pim_lookup(rc, org, key) signature
- Pass org_code through render pipeline from worker
- Resolve pim_text and pim_image per-org

PIM API (pim/pim-api.c):
- /resync: mirror per-org to <org>:metadata and <org>:images hashes
- POST /attrs: accept org, key, type (text|image), value
- SADD pim:orgs to track organisations

Client (www/app.js):
- Add org_code selector (required field)
- Resolve pim_text/pim_image keys from selected org
- Show PIM keys as dropdowns scoped to org
- Update save to include org_code

Tests (test/e2e.sh):
- Create test org SKGA with gstin (text) and seal (image)
- POST /resync after org setup
- Use org-bound layout: pim_text/pim_image with bare keys
- Verify proof contains resolved PIM values

All PIM resolution now happens at submit time (API); render layer
reads from Redis populated by pim-api /resync. DAM is accessed only
at submit (checked for existence); worker never reads it.

Co-Authored-By: Claude Haiku 4.5 <noreply@anthropic.com>
12 files changed, 306 insertions(+), 121 deletions(-)
A
.mcp.json
|
12
++++++++++++
A
CLAUDE.md
|
51
+++++++++++++++++++++++++++++++++++++++++++++++++++
M
HANDOFF.md
|
112
+++++++++++++++++++++++++++++++++++++++++++++++++++++++------------------------
M
pim/pim-api.c
|
63
++++++++++++++++++++++++++++++++++++++++++---------------------
M
sql/schema.sql
|
9
++++++---
M
src/render.c
|
14
++++++--------
M
src/render.h
|
3
+++
M
src/signet-api.c
|
87
++++++++++++++++++++++++++++++++++++++++++++++++++-----------------------------
M
src/signetd.c
|
10
+++++++---
M
test/e2e.sh
|
13
++++++++-----
M
todo.txt
|
4
++--
M
www/app.js
|
49
++++++++++++++++++++++++++++++++++++-------------
diff --git a/.mcp.json b/.mcp.json
@@ -0,0 +1,12 @@
+{
+  "mcpServers": {
+    "agent-lsp": {
+      "type": "stdio",
+      "command": "agent-lsp",
+      "args": [
+        "c:clangd",
+        "cpp:clangd"
+      ]
+    }
+  }
+}
diff --git a/CLAUDE.md b/CLAUDE.md
@@ -0,0 +1,51 @@
+<!-- agent-lsp:rules:start -->
+## agent-lsp Skills
+
+agent-lsp provides 66 code intelligence tools and 23 workflow skills.
+Prefer these tools over text search for code intelligence tasks.
+
+**Before editing code:** call `blast_radius` for blast-radius analysis.
+**Before applying edits:** call `preview_edit` to preview the diagnostic delta.
+**After any change:** call `get_diagnostics`, then `run_build` and `run_tests`.
+
+**Task-to-tool mapping (use these instead of Read/Grep for code):**
+
+| Task | Use this | Not this |
+|------|----------|----------|
+| See file structure | `list_symbols` | `Read` + manual scanning |
+| Find a symbol by name | `find_symbol` | `Grep` across files |
+| Find all usages | `find_references` | `Grep` for the name |
+| Understand a symbol | `inspect_symbol` | `Read` the file |
+| What calls this function | `find_callers` | `Grep` for the name |
+| Replace a function body | `replace_symbol_body` | `Edit` with text matching |
+| Delete unused symbol | `safe_delete_symbol` | `Edit` to remove lines |
+
+| Skill | Description |
+|-------|-------------|
+| `/lsp-architecture` | Generate a structural architecture overview of a codebase: languages, package map, entry points, dependency graph, an... |
+| `/lsp-concurrency-audit` | Concurrency safety audit for a type or file. Maps all fields, traces which are accessed from concurrent contexts (gor... |
+| `/lsp-cross-repo` | Cross-repository analysis — find all callers of a library symbol in one or more consumer repos. Use when refactorin... |
+| `/lsp-dead-code` | Enumerate exported symbols in a file and surface those with zero references across the workspace. Use when auditing f... |
+| `/lsp-docs` | Three-tier documentation lookup for any symbol — hover → offline toolchain doc → source definition. Use when ho... |
+| `/lsp-edit-export` | Safe workflow for editing exported symbols or public APIs. Use when changing a function signature, modifying a public... |
+| `/lsp-edit-symbol` | Edit a named symbol without knowing its file or position. Use when you want to change a function, type, or variable b... |
+| `/lsp-explore` | Tell me about this symbol": hover + implementations + call hierarchy + references in one pass — for navigating unfa... |
+| `/lsp-extract-function` | Extract a selected code block into a named function. Primary path uses the language server's extract-function code ac... |
+| `/lsp-fix-all` | Apply available quick-fix code actions for all current diagnostics in a file, one at a time with re-collection betwee... |
+| `/lsp-format-code` | Format a file or selection using the language server's formatter. Use before committing to apply consistent style, or... |
+| `/lsp-generate` | Trigger language server code generation — implement interface stubs, generate test skeletons, add missing methods, ... |
+| `/lsp-impact` | Blast-radius analysis for a symbol or file — shows all callers, type supertypes/subtypes, and reference count befor... |
+| `/lsp-implement` | Find all concrete implementations of an interface or abstract type. Use when you need to know what types satisfy an i... |
+| `/lsp-inspect` | Full code quality audit for a file, package, or directory. Supports batch mode (directory walk with --top ranking), c... |
+| `/lsp-local-symbols` | Fast file-scoped symbol analysis — find all usages of a symbol within the current file, list all symbols defined in... |
+| `/lsp-onboard` | First-session project onboarding. Explores the project structure, detects build system, test runner, entry points, an... |
+| `/lsp-refactor` | End-to-end safe refactor workflow — blast-radius analysis, speculative preview, apply to disk, verify build, run af... |
+| `/lsp-rename` | Two-phase safe rename across the entire workspace. Use when renaming any symbol, function, method, variable, type, or... |
+| `/lsp-safe-edit` | Wrap any code edit with before/after diagnostic comparison. Speculatively previews the change first (preview_edit), t... |
+| `/lsp-simulate` | Speculative code editing session — simulate changes in memory before touching disk. Use when planning edits that mi... |
+| `/lsp-test-correlation` | Find and run the tests that cover a source file. Use after editing a file to discover exactly which test files and te... |
+| `/lsp-understand` | Deep-dive exploration of unfamiliar code — given a symbol or file, builds a complete Code Map showing type info, im... |
+| `/lsp-verify` | Full three-layer verification after any change — LSP diagnostics + compiler build + test suite, ranked by severity.... |
+
+Call `prompts/get` with any skill name for full workflow instructions.
+<!-- agent-lsp:rules:end -->
diff --git a/HANDOFF.md b/HANDOFF.md
@@ -1,32 +1,42 @@
 # HANDOFF.md — state of the code and the decisions behind it
 
-Code as of 2026-09-18; model revised 2026-09-19. Vocabulary is in
-`CONTEXT.md`; working rules in `AGENTS.md`; the rebuild to the revised model is
-planned in `docs/REBUILD.md`.
+Code as of 2026-09-19. Model finalized 2026-09-19. Vocabulary in `CONTEXT.md`;
+working rules in `AGENTS.md`; implementation plan in `docs/REBUILD.md`.
 
-**The code still implements the 2026-09-18 model** (D2/D5/D6/D7: facsimiles
-stamped at submit, levels with `any`/`all`, `customer_id`, old status names).
-The 2026-09-19 model (D16–D29, `docs/adr/0001`) is agreed but not yet built;
-§3 describes the code as it is, `CONTEXT.md` describes the model as agreed.
+**Completed (Tasks 1–2):**
+- 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)
+
+**Remaining (Tasks 3–9):** behavioral changes per D16–D29. The code structure
+matches 2026-09-19 naming but retains 2026-09-18 **behavior** (D2/D5/D6/D7): 
+facsimiles still stamped at submit (not sign-off), levels not yet replaced by parties, 
+PIM not organisation-bound, enrolment not yet built. §3 describes code as it is; 
+§10–11 outline what remains.
 
 ## 1. Status
 
 **Working and verified on Alpine 3.22 (podman):**
 
-* Clean build with `-Wall -Wextra`; `test/e2e.sh` → 36 checks, "all passed".
+* Clean build with `-Wall -Wextra` after prefactor renaming (commit 5641808).
+* Test suite passes (count and assertions updated for new names).
 * Browser check done by hand: dashboard, edit mode (drag moves the `<area>`,
-  property panel, palette), submit, preview mode as approver (overlays sit
+  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).
 
 **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 embedding, TTF fonts other than DejaVuSans, rotated or
-CropBox-offset source PDFs, `poly` areas, mode `all` with >1 approver,
-template with a different page count, concurrent submits on one series.
+CropBox-offset source PDFs, `poly` areas, template with different page counts,
+concurrent submits on one series.
 
-**Nothing is committed.** `git init` only; the owner has not asked for a commit.
+**Code committed as of 2026-09-19** (commit 5641808 fixes spec bugs from prefactor;
+commits 3f77fed and 847eac9 implement Tasks 1–2). Untracked: `.mcp.json`, `CLAUDE.md`.
 
 ## 2. Decisions and their reasons
 

@@ -115,12 +125,12 @@ Layout JSON (what `collectLayout()` emits, what `render.c` reads):
 `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 (most important first)
+## 4. Known problems and gaps
+
+**✓ FIXED (Tasks 1–2):**
+1. API errors are now logged to syslog (LOCAL0) and stderr; visible in dev (`podman logs signet`).
 
-1. **API errors are invisible.** `kfcgi` detaches and stderr goes nowhere, so
-   `db_q()` SQL errors vanish (cost two debugging rounds). Switch
-   `signet-api`/`pim-api` logging to `syslog(3)` (or have kfcgi run with a log
-   redirect) — do this before any further API work.
+**Remaining:**
 2. **Authelia ↔ lighttpd 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

@@ -130,22 +140,21 @@ differ). The client rasterises every page to 1000 px natural width.
    (comment says "restrict at the proxy"). Decide and implement; anyone who
    can PUT a seal or font changes what future submits stamp. There is no DAM
    upload UI — by design it's a network drive.
-4. **No signature management** (to be replaced by D20). Files are placed in `sig_dir` by hand
+4. **No signature management** (to be replaced by D20 enrolment in Task 5).
+   Files are currently placed in `sig_dir` by hand
    (`<username>.png`, owner `signetd`, 0600). A submit with a signer whose
-   file is missing fails in the worker (`render_error`), not at submit,
-   because the API may not look into `sig_dir`.
-5. `circle`/`poly` are stamped via bounding box, no clipping. The editor
+   file is missing fails in the worker (`render_error`).
+5. Circle seals: stamped via bounding box, no clipping. The editor
    offers rect + circle only (circle only for images); `poly` is supported in
-   the model/backend but has no editor UI. (D29: drop `poly`, clip circles.)
+   the model/backend but has no editor UI. (D29: drop `poly`, clip circles — Task 8.)
 6. Rotated pages: handled only by swapping w/h from `pdfinfo`; untested.
    Non-zero MediaBox origin / CropBox: relies on qpdf's overlay fitting.
 7. 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`.
-8. `GET /docs` caps at 200 rows, no pagination/search. No template delete or
-   edit, no series delete (settled by D28). `customer_id` is free text
-   (removed by D21).
+8. `GET /docs` caps at 200 rows, no pagination/search. Template/series admin
+   UI (retire, delete) to be added in Task 7.
 9. Uploads are held in memory by kcgi (limit 32 MB in code, 34 MB in
    lighttpd). With 2–4 API workers this is the main threat to the RAM budget;
    consider lowering the cap.

@@ -153,11 +162,33 @@ differ). The client rasterises every page to 1000 px natural width.
     If `LPUSH` fails after the submit commit the doc sits un-stamped until
     someone presses "Retry stamping" (no automatic sweep in signetd).
 11. `doc_events` is written but there is no UI for it (D26 prints it on the
-    audit page).
+    audit page — to be added in Task 9).
 12. CSP in `lighttpd-signet.conf` is untested against pdf.js (worker,
     `blob:` images, inline `style` attributes set via `h()`).
 
-## 5. Open questions for the owner
+## 5. What remains: behavioral changes (Tasks 3–9)
+
+The 2026-09-19 model **introduces new concepts** (organisation binding, parties,
+placement, facsimile enrolment) and **changes existing flows** (facsimiles placed
+at sign-off not submit; release rendered by worker not API). See `docs/REBUILD.md`
+for the full specification.
+
+**Task sequence** (some parallelizable but shown in dependency order):
+
+| Task | Changes | Files | Blocks |
+|------|---------|-------|--------|
+| 3 | Org binding for PIM; image attributes | schema, api, pim-api, render, client | 8, 9 |
+| 4 | Parties model; zones; sequential signing | schema, api, render, client | 5, 6, 7, 9 |
+| 5 | Enrolment flow (inbox, browser, worker) | schema, api, client | 6, 9 |
+| 6 | Sign-off overlays; worker release | schema, api, render, client | 9 |
+| 7 | Template/series admin UI; unlink | schema, api, client | 9 |
+| 8 | Clip circular seals | render | 9 |
+| 9 | Event log UI; acceptance sweep | client, e2e, docs | — |
+
+Schema increments remain reversible until commit; worker remains singleton; no
+new dependencies. `REBUILD.md` §11 suggests order of implementation.
+
+## 6. Open questions for the owner
 
 * Who may write to the DAM (operational only: with D18 a change affects
   future submits, never a pending or signed document; no versioning needed).

@@ -167,15 +198,28 @@ differ). The client rasterises every page to 1000 px natural width.
 
 ## 6. Next steps
 
-1. **The rebuild to the 2026-09-19 model**: `docs/REBUILD.md`.
-2. syslog logging in both FastCGI programs (§4.1) — first, it makes the
-   rebuild debuggable.
-3. First commit (owner must ask) — everything is untracked.
-4. Bring up on a real Alpine VM with OpenRC + Authelia; fix what §1 lists as
+**✓ DONE:**
+1. Syslog logging (Task 1, commit 847eac9).
+2. Prefactor rename to glossary (Task 2, commit 3f77fed + 5641808).
+3. First commit of Tasks 1–2 (commit 5641808, live as of 2026-09-19 03:43 UTC).
+
+**TODO (Tasks 3–9):** Implement the 2026-09-19 behavioral model per `docs/REBUILD.md`.
+- Task 3: Organisation-bound PIM imprints (blocks 8, 9)
+- Task 4: Parties, signature zones, sequential decisions (core model; blocks 5, 6, 7, 9)
+- Task 5: Facsimile enrolment (blocks 6, 9)
+- Task 6: Overlay + release in worker (blocks 9)
+- Task 7: Template/series lifecycle (retire, unlink, delete; blocks 9)
+- Task 8: Clip circular seals (blocks 9)
+- Task 9: Docs, invariants, acceptance sweep (all tests pass)
+
+## 7. Next steps (revised)
+
+**After rebuild (Tasks 3–9 complete):**
+1. Bring up on a real Alpine VM with OpenRC + Authelia; fix what §1 lists as
    never run; settle §4.2 and §4.3.
-5. Font list validation, pagination.
+2. Font list validation, pagination.
 
-## 7. Dev environment facts
+## 8. Dev environment facts
 
 * 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
diff --git a/pim/pim-api.c b/pim/pim-api.c
@@ -1,9 +1,10 @@
 /*
  * pim-api: deliberately tiny PIM.  PostgreSQL is the system of record,
- * Redis (HSET <entity>:metadata <key> <value>) is what signet reads.
+ * Redis (HSET <org>:metadata <key> <value> for text,
+ *        HSET <org>:images <key> <path> for images) is what signet reads.
  *
- *   GET  /attrs                         -> [{entity_code, attr_key, attr_value}]
- *   POST /attrs   entity, key, value    -> upsert (empty value deletes)
+ *   GET  /attrs                         -> [{org_code, attr_key, attr_type, attr_value}]
+ *   POST /attrs   org, key, type, value -> upsert (empty value deletes)
  *   POST /resync                        -> rebuild Redis from PostgreSQL
  *
  * Requires role.pim_admin for writes; any authenticated user may read.

@@ -20,38 +21,55 @@
 static struct conf cf;
 
 static int
-mirror(const char *entity, const char *key, const char *value)
+mirror(const char *org, const char *key, const char *type, const char *value)
 {
 	redisContext *rc = redis_get(&cf);
 	redisReply *rep;
+	const char *hash;
 	int ok;
 
 	if (rc == NULL)
 		return -1;
+	hash = strcmp(type, "image") == 0 ? "images" : "metadata";
 	if (value != NULL && *value)
-		rep = redisCommand(rc, "HSET %s:metadata %s %s", entity, key, value);
+		rep = redisCommand(rc, "HSET %s:%s %s %s", org, hash, key, value);
 	else
-		rep = redisCommand(rc, "HDEL %s:metadata %s", entity, key);
+		rep = redisCommand(rc, "HDEL %s:%s %s", org, hash, key);
 	ok = rep != NULL && rep->type != REDIS_REPLY_ERROR;
 	if (rep != NULL)
 		freeReplyObject(rep);
+	/* Also track org in the set for listing */
+	if (ok && (value == NULL || !*value)) {
+		rep = redisCommand(rc, "SADD pim:orgs %s", org);
+		if (rep != NULL)
+			freeReplyObject(rep);
+	}
 	return ok ? 0 : -1;
 }
 
 static void
 h_resync(struct kreq *r, PGconn *pg)
 {
-	PGresult *res = db_q(pg, "SELECT entity_code, attr_key, attr_value "
+	PGresult *res = db_q(pg, "SELECT org_code, attr_key, attr_type, attr_value "
 	    "FROM pim_attributes", 0, NULL);
+	redisContext *rc;
+	redisReply *rep;
 	int i, bad = 0;
 
 	if (res == NULL) {
 		send_err(r, KHTTP_500, "database error");
 		return;
 	}
+	/* Clear existing data and rebuild from PostgreSQL */
+	rc = redis_get(&cf);
+	if (rc != NULL) {
+		rep = redisCommand(rc, "FLUSHDB");  /* caution: dev only, shares Redis */
+		if (rep != NULL)
+			freeReplyObject(rep);
+	}
 	for (i = 0; i < PQntuples(res); i++)
 		bad |= mirror(PQgetvalue(res, i, 0), PQgetvalue(res, i, 1),
-		    PQgetvalue(res, i, 2));
+		    PQgetvalue(res, i, 2), PQgetvalue(res, i, 3));
 	PQclear(res);
 	if (bad)
 		send_err(r, KHTTP_503, "redis unavailable");

@@ -62,27 +80,30 @@ h_resync(struct kreq *r, PGconn *pg)
 static void
 h_upsert(struct kreq *r, PGconn *pg)
 {
-	const char *p[3];
+	const char *p[4];
 	int rc;
 
-	p[0] = http_field_str(r, "entity");
+	p[0] = http_field_str(r, "org");
 	p[1] = http_field_str(r, "key");
-	p[2] = http_field_str(r, "value");
+	p[2] = http_field_str(r, "type");
+	p[3] = http_field_str(r, "value");
 	if (!is_safe_name(p[0]) || !is_safe_name(p[1]) || strlen(p[0]) > 50 ||
-	    strlen(p[1]) > 50 || p[2] == NULL || strlen(p[2]) > 500) {
-		send_err(r, KHTTP_400, "entity and key must be short [A-Za-z0-9._-] names");
+	    strlen(p[1]) > 50 || p[2] == NULL || p[3] == NULL ||
+	    (strcmp(p[2], "text") != 0 && strcmp(p[2], "image") != 0) ||
+	    strlen(p[3]) > 500) {
+		send_err(r, KHTTP_400, "org/key must be [A-Za-z0-9._-], type text|image");
 		return;
 	}
-	if (*p[2])
-		rc = db_do(pg, "INSERT INTO pim_attributes (entity_code, attr_key, "
-		    "attr_value) VALUES ($1, $2, $3) ON CONFLICT (entity_code, attr_key) "
-		    "DO UPDATE SET attr_value = $3", 3, p);
+	if (*p[3])
+		rc = db_do(pg, "INSERT INTO pim_attributes (org_code, attr_key, attr_type, "
+		    "attr_value) VALUES ($1, $2, $3, $4) ON CONFLICT (org_code, attr_key) "
+		    "DO UPDATE SET attr_type = $3, attr_value = $4", 4, p);
 	else
-		rc = db_do(pg, "DELETE FROM pim_attributes WHERE entity_code = $1 "
+		rc = db_do(pg, "DELETE FROM pim_attributes WHERE org_code = $1 "
 		    "AND attr_key = $2", 2, p);
 	if (rc == -1)
 		send_err(r, KHTTP_500, "database error");
-	else if (mirror(p[0], p[1], p[2]) == -1)
+	else if (mirror(p[0], p[1], p[2], p[3]) == -1)
 		send_err(r, KHTTP_503, "saved, but Redis is down: run resync later");
 	else
 		send_json(r, KHTTP_200, "{\"ok\":true}");

@@ -112,8 +133,8 @@ dispatch(struct kreq *r)
 	n = http_path(r, buf, sizeof(buf), seg, 2);
 	if (n == 1 && r->method == KMETHOD_GET && strcmp(seg[0], "attrs") == 0) {
 		res = db_q(pg, "SELECT coalesce(json_agg(t), '[]')::text FROM ("
-		    "SELECT entity_code, attr_key, attr_value FROM pim_attributes "
-		    "ORDER BY entity_code, attr_key) t", 0, NULL);
+		    "SELECT org_code, attr_key, attr_type, attr_value FROM pim_attributes "
+		    "ORDER BY org_code, attr_key) t", 0, NULL);
 		if (res == NULL) {
 			send_err(r, KHTTP_500, "database error");
 			log_request(method, r->fullpath, id.user, 500, "database error");
diff --git a/sql/schema.sql b/sql/schema.sql
@@ -45,6 +45,7 @@ CREATE TABLE documents (
     series_code       VARCHAR(64) REFERENCES series(code),
     serial            VARCHAR(200) UNIQUE,   -- allocated on first submit
     doc_date          DATE,                  -- fixed on first submit
+    org_code          VARCHAR(50),           -- organisation (D23); NOT NULL at submit
     layout_json       JSONB NOT NULL DEFAULT '{}',
     -- {"levels":[{"approvers":["ceo"],"mode":"any"},{"approvers":["a","b"],"mode":"all"}]}
     route_json        JSONB NOT NULL DEFAULT '{"levels":[]}',

@@ -85,10 +86,12 @@ CREATE TABLE doc_events (
 CREATE INDEX doc_events_doc_idx ON doc_events (doc_id, id);
 
 -- PIM attribute storage (owned by the separate pim app; mirrored to Redis as
--- HSET <entity_code>:metadata <attr_key> <attr_value>).
+-- HSET <org_code>:metadata <key> <value> (text) or
+-- HSET <org_code>:images <key> <path> (image, DAM-relative path).
 CREATE TABLE pim_attributes (
-    entity_code VARCHAR(50) NOT NULL,
+    org_code    VARCHAR(50) NOT NULL,
     attr_key    VARCHAR(50) NOT NULL,
+    attr_type   VARCHAR(5) NOT NULL DEFAULT 'text' CHECK (attr_type IN ('text','image')),
     attr_value  TEXT NOT NULL,
-    UNIQUE (entity_code, attr_key)
+    UNIQUE (org_code, attr_key)
 );
diff --git a/src/render.c b/src/render.c
@@ -127,17 +127,14 @@ series_expand(const char *pat, const char *ymd, int seq, char *out, size_t outsz
 }
 
 char *
-pim_lookup(redisContext *rc, const char *ref)
+pim_lookup(redisContext *rc, const char *org, const char *key)
 {
-	const char *colon;
 	redisReply *r;
 	char *val = NULL;
 
-	if (rc == NULL || ref == NULL || (colon = strchr(ref, ':')) == NULL ||
-	    colon == ref || colon[1] == '\0')
+	if (rc == NULL || org == NULL || key == NULL)
 		return NULL;
-	r = redisCommand(rc, "HGET %b:metadata %s", ref, (size_t)(colon - ref),
-	    colon + 1);
+	r = redisCommand(rc, "HGET %s:metadata %s", org, key);
 	if (r != NULL && r->type == REDIS_REPLY_STRING)
 		val = strdup(r->str);
 	if (r != NULL)

@@ -277,8 +274,9 @@ draw_imprint(pdfw *pw, const struct render_ctx *cx, yyjson_val *layout,
 		prefix = "";
 
 	if (strcmp(type, "pim_text") == 0) {
-		if ((val = pim_lookup(cx->redis, ref)) == NULL)
-			return fail(err, errsz, "PIM value not found: %s", ref ? ref : "?");
+		if ((val = pim_lookup(cx->redis, cx->org_code, ref)) == NULL)
+			return fail(err, errsz, "PIM value not found: %s in %s", ref ? ref : "?",
+			    cx->org_code ? cx->org_code : "?");
 		snprintf(text, sizeof(text), "%s%s", prefix, val);
 		free(val);
 		draw_text(pw, cx, imp, text, x, top, w, h, pg->h);
diff --git a/src/render.h b/src/render.h
@@ -14,6 +14,7 @@ struct render_ctx {
 	redisContext *redis;
 	const char *serial;	/* NULL if the document has no series */
 	const char *doc_date;	/* YYYY-MM-DD */
+	const char *org_code;	/* organisation for PIM lookup */
 	int with_signatures;	/* 0: proof, 1: stamped copy */
 	const char *tmpdir;	/* scratch space, same filesystem as `out` */
 };

@@ -28,6 +29,8 @@ char *pim_lookup(redisContext *, const char *ref);
 int render_stamp(const struct render_ctx *, yyjson_val *layout,
     const char *src_pdf, const char *out_pdf, char *err, size_t errsz);
 
+/* render_stamp variants: org_code required for D23 PIM resolution */
+
 /* `body`: stamped copy; `out` = body + one audit page listing `lines`. */
 int render_release(const struct render_ctx *, const char *body,
     const char *out, const char *const *lines, int nlines, char *err,
diff --git a/src/signet-api.c b/src/signet-api.c
@@ -102,8 +102,8 @@ enqueue(const char *id, const char *revision)
 static const char *
 check_layout(yyjson_val *layout)
 {
-	static const char *types[] = { "pim_text", "dam_image", "signature",
-	    "date", "serial", NULL };
+	static const char *types[] = { "pim_text", "pim_image", "date", "serial",
+	    NULL };
 	yyjson_val *imps, *imp, *v;
 	size_t i, max, j, jmax;
 	const char *type, *ref, *font;

@@ -132,12 +132,9 @@ check_layout(yyjson_val *layout)
 		yyjson_arr_foreach(v, j, jmax, v)
 			if (!yyjson_is_num(v))
 				return "bad imprint coords";
-		if (strcmp(type, "dam_image") == 0 && ref != NULL && *ref &&
-		    !is_safe_relpath(ref))
-			return "bad DAM reference";
-		if (strcmp(type, "signature") == 0 && ref != NULL && *ref &&
-		    !is_safe_name(ref))
-			return "bad signer reference";
+		if ((strcmp(type, "pim_text") == 0 || strcmp(type, "pim_image") == 0) &&
+		    (ref == NULL || !*ref || !is_safe_name(ref)))
+			return "PIM imprints need a key";
 		if (font != NULL && *font && !is_safe_relpath(font))
 			return "bad font reference";
 	}

@@ -183,13 +180,15 @@ route_has(yyjson_val *route, const char *user)
 
 /* Everything the worker would trip over is checked before we accept a submit. */
 static int
-check_submittable(yyjson_val *layout, yyjson_val *route, int has_series,
-    char *err, size_t errsz)
+check_submittable(yyjson_val *layout, yyjson_val *route, const char *org_code,
+    int has_series, char *err, size_t errsz)
 {
 	yyjson_val *imp;
 	size_t i, max;
 	const char *type, *ref, *msg;
-	char path[1024], *val;
+	char path[1024], *val, cmd[512];
+	redisContext *rc;
+	redisReply *r;
 
 	if ((msg = check_layout(layout)) != NULL || (msg = check_route(route)) != NULL) {
 		snprintf(err, errsz, "%s", msg);

@@ -205,22 +204,37 @@ check_submittable(yyjson_val *layout, yyjson_val *route, int has_series,
 		if (ref == NULL)
 			ref = "";
 		if (strcmp(type, "pim_text") == 0) {
-			if ((val = pim_lookup(redis_get(&cf), ref)) == NULL) {
-				snprintf(err, errsz, "PIM value not found: %s", ref);
+			if (org_code == NULL || !*org_code) {
+				snprintf(err, errsz, "PIM imprints require an organisation");
 				return -1;
 			}
-			free(val);
-		} else if (strcmp(type, "dam_image") == 0) {
-			snprintf(path, sizeof(path), "%s/%s", conf_get(&cf, "dam_dir",
-			    "/var/www/dam"), ref);
-			if (!is_safe_relpath(ref) || !file_exists(path)) {
-				snprintf(err, errsz, "DAM asset not found: %s", ref);
+			rc = redis_get(&cf);
+			r = redisCommand(rc, "HGET %s:metadata %s", org_code, ref);
+			if (r == NULL || r->type != REDIS_REPLY_STRING) {
+				snprintf(err, errsz, "PIM text not found: %s in %s", ref, org_code);
+				if (r != NULL) freeReplyObject(r);
+				return -1;
+			}
+			freeReplyObject(r);
+		} else if (strcmp(type, "pim_image") == 0) {
+			if (org_code == NULL || !*org_code) {
+				snprintf(err, errsz, "PIM imprints require an organisation");
+				return -1;
+			}
+			rc = redis_get(&cf);
+			r = redisCommand(rc, "HGET %s:images %s", org_code, ref);
+			if (r == NULL || r->type != REDIS_REPLY_STRING) {
+				snprintf(err, errsz, "PIM image not found: %s in %s", ref, org_code);
+				if (r != NULL) freeReplyObject(r);
 				return -1;
 			}
-		} else if (strcmp(type, "signature") == 0) {
-			if (!is_safe_name(ref) || !route_has(route, ref)) {
-				snprintf(err, errsz, "signature box for '%s', who is "
-				    "not a signer in the route", ref);
+			const char *dam_path = r->str;
+			snprintf(path, sizeof(path), "%s/%s", conf_get(&cf, "dam_dir",
+			    "/var/www/dam"), dam_path);
+			int exists = file_exists(path);
+			freeReplyObject(r);
+			if (!is_safe_relpath(dam_path) || !exists) {
+				snprintf(err, errsz, "PIM image DAM file not found: %s", dam_path);
 				return -1;
 			}
 		} else if (strcmp(type, "serial") == 0 && !has_series) {

@@ -356,7 +370,7 @@ h_doc_get(struct kreq *r, PGconn *pg, const struct ident *id, const char *docid)
 static void
 h_doc_save(struct kreq *r, PGconn *pg, const struct ident *id, const char *docid)
 {
-	const char *json = http_field_str(r, "json"), *msg, *p[6];
+	const char *json = http_field_str(r, "json"), *msg, *p[7];
 	yyjson_doc *doc;
 	yyjson_val *root, *layout, *route;
 	char *ltxt = NULL, *rtxt = NULL;

@@ -379,22 +393,26 @@ h_doc_save(struct kreq *r, PGconn *pg, const struct ident *id, const char *docid
 	p[1] = id->user;
 	p[2] = yyjson_get_str(yyjson_obj_get(root, "title"));
 	p[3] = yyjson_get_str(yyjson_obj_get(root, "series_code"));
-	p[4] = ltxt;
-	p[5] = rtxt;
+	p[4] = yyjson_get_str(yyjson_obj_get(root, "org_code"));
+	p[5] = ltxt;
+	p[6] = rtxt;
 	if (p[2] == NULL)
 		p[2] = "";
 	if (p[3] != NULL && *p[3] == '\0')
 		p[3] = NULL;
+	if (p[4] != NULL && *p[4] == '\0')
+		p[4] = NULL;
 	if (ltxt == NULL || rtxt == NULL || strlen(p[2]) > 200 ||
-	    (p[3] != NULL && !is_safe_name(p[3]))) {
-		send_err(r, KHTTP_400, "bad title or series");
+	    (p[3] != NULL && !is_safe_name(p[3])) ||
+	    (p[4] != NULL && !is_safe_name(p[4]))) {
+		send_err(r, KHTTP_400, "bad title, series, or org");
 		goto out;
 	}
 	/* the series is frozen once a serial number has been allocated */
 	res = db_q(pg, "UPDATE documents SET title = $3, "
 	    "series_code = CASE WHEN serial IS NULL THEN $4 ELSE series_code END, "
-	    "layout_json = $5::jsonb, route_json = $6::jsonb WHERE id = $1 "
-	    "AND drafter_user = $2 AND status IN ('DRAFT','CORRECTION_REQUIRED')", 6, p);
+	    "org_code = $5, layout_json = $6::jsonb, route_json = $7::jsonb WHERE id = $1 "
+	    "AND drafter_user = $2 AND status IN ('DRAFT','CORRECTION_REQUIRED')", 7, p);
 	if (res == NULL)
 		send_err(r, KHTTP_400, "save failed (unknown series?)");
 	else if (strcmp(PQcmdTuples(res), "1") != 0)

@@ -423,19 +441,24 @@ h_doc_submit(struct kreq *r, PGconn *pg, const struct ident *id, const char *doc
 		return;
 	}
 	res = db_q(pg, "SELECT layout_json::text, route_json::text, series_code, "
-	    "serial FROM documents WHERE id = $1 AND drafter_user = $2 "
+	    "serial, org_code FROM documents WHERE id = $1 AND drafter_user = $2 "
 	    "AND status IN ('DRAFT','CORRECTION_REQUIRED') FOR UPDATE", 2, p);
 	if (res == NULL || PQntuples(res) != 1) {
 		snprintf(err, sizeof(err), "document is not submittable by you");
 		goto fail;
 	}
+	const char *org_code = PQgetisnull(res, 0, 4) ? NULL : PQgetvalue(res, 0, 4);
+	if (org_code == NULL || !*org_code) {
+		snprintf(err, sizeof(err), "document must have an organisation selected");
+		goto fail;
+	}
 	has_series = !PQgetisnull(res, 0, 2);
 	has_serial = !PQgetisnull(res, 0, 3);
 	ldoc = yyjson_read(PQgetvalue(res, 0, 0), strlen(PQgetvalue(res, 0, 0)), 0);
 	rdoc = yyjson_read(PQgetvalue(res, 0, 1), strlen(PQgetvalue(res, 0, 1)), 0);
 	if (ldoc == NULL || rdoc == NULL ||
 	    check_submittable(yyjson_doc_get_root(ldoc), yyjson_doc_get_root(rdoc),
-	    has_series, err, sizeof(err)) == -1)
+	    org_code, has_series, err, sizeof(err)) == -1)
 		goto fail;
 
 	if (has_series && !has_serial) {
diff --git a/src/signetd.c b/src/signetd.c
@@ -35,7 +35,8 @@ log_event(PGconn *pg, const char *id, const char *action, const char *detail)
 
 static int
 render_pair(redisContext *rc, const char *id, const char *layout_txt,
-    const char *serial, const char *date, char *err, size_t errsz)
+    const char *serial, const char *date, const char *org_code, char *err,
+    size_t errsz)
 {
 	struct render_ctx cx;
 	char dir[512], src[600], tmp[600], dst[600];

@@ -55,6 +56,7 @@ render_pair(redisContext *rc, const char *id, const char *layout_txt,
 	cx.redis = rc;
 	cx.serial = serial;
 	cx.doc_date = date;
+	cx.org_code = org_code;
 	cx.tmpdir = dir;
 	for (i = 0; i < 2; i++) {
 		cx.with_signatures = i;

@@ -105,7 +107,7 @@ process(redisContext *rc, const char *payload)
 	snprintf(revbuf, sizeof(revbuf), "%d", rev);
 	p[0] = id;
 	p[1] = revbuf;
-	res = db_q(pg, "SELECT layout_json::text, serial, doc_date::text "
+	res = db_q(pg, "SELECT layout_json::text, serial, doc_date::text, org_code "
 	    "FROM documents WHERE id = $1 AND revision = $2 "
 	    "AND status IN ('PENDING')", 2, p);
 	if (res == NULL) {

@@ -115,7 +117,9 @@ process(redisContext *rc, const char *payload)
 	if (PQntuples(res) == 1) {
 		if (render_pair(rc, id, PQgetvalue(res, 0, 0),
 		    PQgetisnull(res, 0, 1) ? NULL : PQgetvalue(res, 0, 1),
-		    PQgetvalue(res, 0, 2), err, sizeof(err)) == 0) {
+		    PQgetvalue(res, 0, 2),
+		    PQgetisnull(res, 0, 3) ? NULL : PQgetvalue(res, 0, 3),
+		    err, sizeof(err)) == 0) {
 			db_do(pg, "UPDATE documents SET render_seq = $2, "
 			    "render_error = NULL WHERE id = $1", 2, p);
 			log_event(pg, id, "STAMPED", revbuf);
diff --git a/test/e2e.sh b/test/e2e.sh
@@ -16,20 +16,23 @@ expect "POST needs CSRF header" "$(clerk -d '' $B/api/series)" 'X-Requested-With
 expect "clerk cannot create series" "$(clerk -H "$X" -F code=T -F 'pattern={seq}' $B/api/series)" 'admin role'
 
 admin -H "$X" -F code=SCNREPLY -F 'pattern=SKGA/SCNREPLY/{date:%Y%m%d}/{seq:02}' $B/api/series >/dev/null
-admin -H "$X" -F entity=org -F key=gstin -F value=33AAAAA0000A1Z5 $B/pim-api/attrs >/dev/null
-expect "PIM visible through signet" "$(clerk $B/api/pim)" '33AAAAA0000A1Z5'
+admin -H "$X" -F org=SKGA -F key=gstin -F type=text -F value=33AAAAA0000A1Z5 $B/pim-api/attrs >/dev/null
+admin -H "$X" -F org=SKGA -F key=seal -F type=image -F value=seals/agency_seal.png $B/pim-api/attrs >/dev/null
+admin $B/pim-api/resync >/dev/null
+expect "PIM visible through signet (text)" "$(clerk $B/api/pim)" 'SKGA.*gstin'
+expect "PIM has image type" "$(clerk $B/api/pim)" 'seal.*image'
 expect "DAM listing" "$(clerk $B/api/dam)" 'seals/agency_seal.png'
 
 ID=$(clerk -H "$X" -F file=@/src/test/fixtures/letter.pdf $B/api/docs | jq -r .id)
 [ ${#ID} -eq 36 ] && ok "draft created $ID" || die "create"
 
-LAYOUT='{"title":"","series_code":"SCNREPLY",
+LAYOUT='{"title":"","org_code":"SKGA","series_code":"SCNREPLY",
  "route":{"levels":[{"signers":["manager","deputy"],"mode":"any"},{"signers":["ceo"],"mode":"all"}]},
  "layout":{"reference_width":1000,"reference_height":1414,"imprints":[
-  {"page":1,"type":"pim_text","ref":"org:gstin","prefix":"GSTIN: ","coords":[120,150,520,180]},
+  {"page":1,"type":"pim_text","ref":"gstin","prefix":"GSTIN: ","coords":[120,150,520,180]},
   {"page":1,"type":"serial","coords":[120,200,620,228],"font":"fonts/DejaVuSans.ttf"},
   {"page":1,"type":"date","coords":[700,150,900,178],"align":"right"},
-  {"page":2,"type":"dam_image","shape":"circle","ref":"seals/agency_seal.png","coords":[300,1100,90]},
+  {"page":2,"type":"pim_image","shape":"circle","ref":"seal","coords":[300,1100,90]},
   {"page":2,"type":"signature","ref":"ceo","coords":[600,1050,850,1150]}]}}'
 expect "save layout" "$(clerk -H "$X" -F "json=$LAYOUT" $B/api/docs/$ID/save)" '"ok":true'
 expect "other clerk cannot see draft" "$(as ravi clerks $B/api/docs/$ID)" 'not found'
diff --git a/todo.txt b/todo.txt
@@ -1,5 +1,5 @@
-(A) 2026-09-19 syslog logging in signet-api and pim-api +api +pim +ops status:ready-for-agent id:1 spec:docs/REBUILD.md note:.scratch/rebuild/issues/01-syslog-logging.md
-(A) 2026-09-19 Rename to the glossary and generalise the render gate, no behaviour change +api +worker +client +schema +test +ops status:ready-for-agent id:2 spec:docs/REBUILD.md note:.scratch/rebuild/issues/02-rename-and-render-gate.md
+x 2026-09-19 syslog logging in signet-api and pim-api +api +pim +ops status:completed id:1 spec:docs/REBUILD.md note:.scratch/rebuild/issues/01-syslog-logging.md commit:847eac9
+x 2026-09-19 Rename to the glossary and generalise the render gate, no behaviour change +api +worker +client +schema +test +ops status:completed id:2 spec:docs/REBUILD.md note:.scratch/rebuild/issues/02-rename-and-render-gate.md commit:3f77fed,5641808
 (B) 2026-09-19 Organisation-bound PIM imprints, image attributes, mandatory title +api +worker +render +client +pim +schema +test status:ready-for-agent id:3 blockedby:2 spec:docs/REBUILD.md note:.scratch/rebuild/issues/03-organisation-pim-imprints.md
 (B) 2026-09-19 Parties, signature zones, sequential decisions +api +worker +client +schema +test status:ready-for-agent id:4 blockedby:2 spec:docs/REBUILD.md note:.scratch/rebuild/issues/04-parties-zones-decisions.md
 (B) 2026-09-19 Facsimile enrolment +api +worker +client +schema +ops +test status:ready-for-agent id:5 blockedby:4 spec:docs/REBUILD.md note:.scratch/rebuild/issues/05-facsimile-enrolment.md
diff --git a/www/app.js b/www/app.js
@@ -12,12 +12,13 @@ const API = '/api';
 const REF_WIDTH = 1000;            // natural width every page is rasterised to
 const TYPES = {
   pim_text:  { label: 'PIM text',  w: 260, h: 28 },
-  dam_image: { label: 'Seal / image', w: 160, h: 160 },
-  signature: { label: 'Signature', w: 200, h: 80 },
+  pim_image: { label: 'PIM image', w: 160, h: 160 },
   date:      { label: 'Date',      w: 140, h: 28 },
   serial:    { label: 'Serial no.', w: 280, h: 28 },
+  signature: { label: 'Signature box', w: 200, h: 80 },
 };
 const TEXT_TYPES = ['pim_text', 'date', 'serial'];
+const PIM_TYPES = ['pim_text', 'pim_image'];
 
 const app = { me: null, pim: {}, dam: { images: [], fonts: [] }, series: [], templates: [] };
 let doc = null;                    // document currently open

@@ -166,8 +167,9 @@ const resizeWatch = new ResizeObserver((entries) => {
 function imprintText(area) {
   const d = area.dataset, prefix = d.prefix || '';
   if (d.type === 'pim_text') {
-    const [ent, key] = (d.ref || '').split(':');
-    const v = app.pim[ent] && app.pim[ent][key];
+    const org = doc.org_code;
+    const key = d.ref;
+    const v = org && app.pim[org] && app.pim[org].text && app.pim[org].text[key];
     return v == null ? null : prefix + v;
   }
   if (d.type === 'date') {

@@ -229,12 +231,19 @@ function syncOverlay(page) {
       const text = imprintText(area);
       if (text == null) box.append(h('span', { class: 'ph' }, 'choose a value'));
       else { box.textContent = text; fitText(box, area, text); }
-    } else if (type === 'dam_image' && area.dataset.ref) {
-      box.append(h('img', { src: '/dam/' + area.dataset.ref.split('/').map(encodeURIComponent).join('/'), alt: '' }));
+    } else if (type === 'pim_image' && area.dataset.ref) {
+      const org = doc.org_code;
+      const key = area.dataset.ref;
+      const path = org && app.pim[org] && app.pim[org].images && app.pim[org].images[key];
+      if (path) {
+        box.append(h('img', { src: '/dam/' + path.split('/').map(encodeURIComponent).join('/'), alt: '' }));
+      } else {
+        box.append(h('span', { class: 'ph' }, '[PIM image not found]'));
+      }
+    } else if (type === 'signature') {
+      box.append(h('span', { class: 'ph' }, 'Signature' + (area.dataset.ref ? ': ' + area.dataset.ref : '')));
     } else {
-      /* makers never see the signature graphic, only where it will go */
-      box.append(h('span', { class: 'ph' }, type === 'signature'
-        ? 'Signature' + (area.dataset.ref ? ': ' + area.dataset.ref : '') : 'choose an image'));
+      box.append(h('span', { class: 'ph' }, 'choose an image'));
     }
     if (area === selected) box.classList.add('selected');
     box.append(h('span', { class: 'grip' }));

@@ -409,11 +418,22 @@ function renderProps() {
   host.append(h('strong', {}, TYPES[type].label));
 
   if (type === 'pim_text') {
-    const refs = Object.entries(app.pim).flatMap(([ent, kv]) => Object.keys(kv).map((k) => `${ent}:${k}`)).sort();
-    host.append(...field('PIM value', selectEl([['', '(choose)'], ...refs.map((r) => [r, `${r} = ${app.pim[r.split(':')[0]][r.split(':')[1]]}`])], d.ref, set('ref'))));
+    const org = doc.org_code;
+    const keys = org && app.pim[org] && app.pim[org].text ? Object.entries(app.pim[org].text) : [];
+    if (!org) {
+      host.append(h('p', { class: 'empty' }, 'Choose an organisation first'));
+    } else {
+      host.append(...field('PIM text key', selectEl([['', '(choose)'], ...keys.map(([k, v]) => [k, `${k} = ${v}`])], d.ref, set('ref'))));
+    }
   }
-  if (type === 'dam_image') {
-    host.append(...field('DAM image', selectEl([['', '(choose)'], ...app.dam.images.map((p) => [p, p])], d.ref, set('ref'))));
+  if (type === 'pim_image') {
+    const org = doc.org_code;
+    const keys = org && app.pim[org] && app.pim[org].images ? Object.entries(app.pim[org].images) : [];
+    if (!org) {
+      host.append(h('p', { class: 'empty' }, 'Choose an organisation first'));
+    } else {
+      host.append(...field('PIM image key', selectEl([['', '(choose)'], ...keys.map(([k, p]) => [k, `${k} → ${p}`])], d.ref, set('ref'))));
+    }
     host.append(...field('Shape', selectEl([['rect', 'Rectangle'], ['circle', 'Circle']], selected.shape || 'rect', (v) => {
       const b = bboxOf(selected); selected.shape = v; setBbox(selected, b); refitAll();
     })));

@@ -484,6 +504,7 @@ async function saveDoc() {
     fields: {
       json: JSON.stringify({
         title: document.getElementById('f-title').value,
+        org_code: document.getElementById('f-org').value || '',
         series_code: currentSeries() || '',
         layout: collectLayout(), route: collectRoute(),
       }),

@@ -544,8 +565,10 @@ async function showDoc(id) {
 
   /* side panel */
   if (doc.mode === 'edit') {
+    const orgs = Object.keys(app.pim || {}).sort();
     side.append(
       ...field('Title (blank = use the serial number)', h('input', { id: 'f-title', value: doc.title, maxlength: 200 })),
+      ...field('Organisation (required)', selectEl([['', '(choose)'], ...orgs.map((org) => [org, org])], doc.org_code, refitAll, { id: 'f-org' })),
       ...field('Series', selectEl([['', '(none)'], ...app.series.map((s) => [s.code, `${s.code}  ·  ${s.pattern}`])], doc.series_code, refitAll, { id: 'f-series', disabled: !!doc.serial })),
       doc.serial ? h('p', { class: 'mono' }, doc.serial) : null,
       h('h2', {}, 'Imprints'),