Prepared for: Repository stakeholders / engineering leadership
Prepared by: Engineering consulting review
Document type: Architecture & Design Deliverable
Status: Reflects repository state as of the P9 milestone (all phases P0–P9 complete; production terraform apply pending)
Dominio is a quality-control system for documentation packages — bundles of Google Docs, Sheets, and Forms that must move through a defined review workflow (draft → review → validation → archive) with reviewer access provisioned automatically, notifications sent reliably, and every state change captured in an immutable audit trail.
The system is built as four deployable units sharing one Postgres schema:
| Component | Language | Responsibility | Trigger |
|---|---|---|---|
api |
Go | Public HTTPS surface: OAuth2 login, package/document/workflow CRUD, the state-machine engine, Drive permission reconciliation, audit writes | Cloud Run service |
notify-worker |
Python | Consumes package events, renders and sends templated email via Gmail API | Pub/Sub push (Cloud Run service) |
sweep-job |
Python | Scheduled sweep: due-date reminders, staleness detection, stuck-notification recovery | Cloud Scheduler → Cloud Run Job |
web |
Vanilla JS SPA | Portfolio, package detail, creation wizard, workflow editor, admin console | Served by api (same-origin) or any static host |
The design is deliberately dependency-light: no ORM, no JWT library, no Google API client outside one isolated package, no bundler for the frontend. This is a considered engineering position, not an oversight — it keeps the attack surface and the onboarding cost small, and it is enforced mechanically by a CI gate rather than left to code review discipline.
The codebase has progressed through nine build phases (P0–P9), each gated by a single verification script (scripts/verify.sh) that must stay green before the next phase begins. All phases are functionally complete, including infrastructure-as-code; the only remaining step before production traffic is the operational act of running terraform apply against a billed GCP project.
This document describes the system's architecture, data model, state machine, cross-cutting contracts, and deployment topology, and calls out the design decisions that most affect long-term maintainability.
┌─────────────────────────────────────────┐
│ Google Workspace │
│ Drive (files, permissions) · Gmail │
│ (per-user OAuth2 delegation) │
└──────────────▲──────────────▲─────────────┘
│ │
┌─────────────┴───┐ ┌──────┴───────────┐
│ api │ │ notify-worker │
│ (Go, Cloud Run) │ │ (Python, Cloud │
│ public HTTPS │ │ Run, private) │
└────────▲─────────┘ └────────▲─────────┘
│ │
browsers (web SPA) Pub/Sub push
│
┌──────────────────┐ ┌────────┴────────┐
│ sweep-job │ │ Cloud Scheduler │
│ (Python, Cloud │◄─────┤ (daily + hourly │
│ Run Job) │ │ triggers) │
└────────▲──────────┘ └─────────────────┘
│
┌─────────┴──────────┐
│ Cloud SQL / Postgres │
│ (single shared schema) │
└────────────────────────┘
Two Go binaries beyond api complete the compute topology: migrate (roll-forward schema migrations) and drain (an hourly Cloud Run Job that retries failed permission-reconciliation tasks so a Drive ACL failure does not block reviewers until the next daily sweep). A fourth Go binary, adminctl, is an operator tool for seeding the first admin identity of a freshly deployed environment.
The system's behavior is governed by seven principles stated in the project README, and enforced structurally rather than by convention:
- Explicit actions only advance the workflow. Opening or commenting on a document is never interpreted as approval — only an explicit engine transition does.
- The audit log is append-only, enforced at the database grant level (
INSERT, SELECTonly), not merely by application logic. - Approvals capture evidence — the head Drive revision ID of every active document at the moment of approval.
- Staleness is detected, never prevented. An approval against a document that has since changed is flagged
STALErather than blocked; the workflow does not fight the user's editing process. - Permissions are a desired-state reconciler, derived from committed workflow state after the fact, never granted inline during a transition.
- Every state transition takes a row lock on its package (
SELECT … FOR UPDATE) — the package row is the single concurrency boundary for the whole system. - Mutating API endpoints are idempotent by client-supplied
Idempotency-Key.
These are not aspirational guidelines; each is backed by a specific mechanism described in Sections 3–5.
The project takes an explicit anti-framework stance:
- No JWT library — sessions are stdlib HS256 (
api/internal/session). - No
golang.org/x/oauth2— OAuth2 token exchange/refresh is hand-rolled over stdlibnet/http(api/internal/oauth/real.go). - No Google Cloud SDK for Pub/Sub, KMS, or metadata calls — all done via stdlib
net/httpagainst the REST APIs, enforced by a CI grep guard with no exception list. - No
google-api-python-clientin the Python workers — Gmail/Drive calls go over stdliburllib. - No frontend bundler or framework — the SPA is vanilla ES modules plus one stylesheet.
The single sanctioned exception is the official Google Go SDK, and it is confined to one file pair (api/internal/googleclient/real*.go), behind an interface every other package depends on. This boundary is not aspirational either — verify.sh fails the build if google.golang.org/api/ is imported anywhere else.
/api Go module
/cmd/api HTTP service entrypoint
/cmd/migrate Roll-forward schema migration runner
/cmd/drain Scheduled retry of failed permission-reconciliation tasks
/cmd/adminctl Operator CLI — seeds the first admin of an environment
/internal
engine/ State-machine transitions, template application, admin governance
permissions/ Desired-state Drive ACL reconciler
repo/ Go data-access layer (contract-pinned against Python)
oauth/ Token exchange/refresh (user-delegated identity)
tokenvend/ Shared access-token cache + refresh, used by both googleclient and the internal endpoint
session/ Stdlib HS256 session cookies
httpapi/ Thin HTTP adapters — auth, packages, transitions, portfolio, admins
cipher/ KMS envelope encryption for stored refresh tokens
googleclient/ Fake (in-memory) + Real (Google SDK) Drive/Gmail client, one interface
gcpauth/ The service's own identity (metadata server), for KMS/Pub/Sub calls
bootstrap/ Fake-vs-real selection by environment variable, for all four swappable subsystems
obs/ Correlation-ID propagation + hand-rolled Prometheus metrics
/worker Python package
notify_worker/ Notification delivery (push handler + shared deliver() path)
sweep_job/ Scheduled sweep entrypoint
google_client/ Python mirror of the Go Drive/Gmail Fake/Real split
repo/ Python data-access layer (contract-pinned against Go)
/web Vanilla-JS SPA — index.html, app.css, js/ (api.js, app.js, ui.js, views/)
/migrations Shared SQL migrations — single source of schema truth
/testdata Golden fixtures loaded by both the Go and Python contract tests
/seed Dev-only fixtures (kept out of the migration runner's glob path)
/infra Terraform — Cloud Run, Cloud SQL, Pub/Sub, Scheduler, Secret Manager, KMS, monitoring
/docs Phase status, per-phase plans, test checklist, user guide
/scripts verify.sh (the phase gate), seed.sh, reset-db.sh
Each directory boundary corresponds to an explicit architectural decision recorded in dominio-agent-plan.md, not an incidental grouping — several are discussed below because they resolve a specific design risk.
The schema (migrations/0002_core_schema.sql onward) is intentionally flat and normalized around one aggregate root, packages. Primary keys are application-generated UUIDs (not DB defaults), so the Go and Python data layers construct identical identifiers without a round trip. Enum-shaped columns are text + CHECK, never native Postgres ENUM types — this keeps the migration path for adding a new state a pure ALTER TABLE ... DROP CONSTRAINT / ADD CONSTRAINT, and keeps the constraint visible in a \d inspection rather than hidden in pg_enum.
| Table | Purpose | Notable constraints |
|---|---|---|
packages |
The workflow aggregate root | state CHECK against 5 values; template_id, supersedes_package_id self/foreign references for versioning |
documents |
Google Docs/Sheets/Forms attached to a package | last_known_revision_id backs staleness detection; status ACTIVE/REMOVED (soft delete) |
workflow_stages |
Ordered review stages within a package | completion_rule ALL/ANY/QUORUM, with a CHECK tying QUORUM to a required quorum_n |
participants |
A reviewer/editor/validator assigned to a stage | status is workflow-owned only; engagement (last_notified_at, last_opened_at) is tracked separately so a UI "seen" event can never be conflated with an approval |
audit_log |
Append-only history of every transition | DB-level grant restricts both service roles to INSERT, SELECT |
notifications |
Outbox + delivery log | status PENDING/SENDING/SENT/FAILED; claimed_at/attempts back the single-sender claim |
user_tokens |
Encrypted per-user Google refresh/access tokens | Owned exclusively by the Go api |
permission_tasks |
Durable reconciler work items after an ACL failure | reason enumerates the workflow event that triggered it |
idempotency_keys |
Cached response per (key), scoped to a package + endpoint |
TTL-pruned by the sweep |
templates |
Reusable package presets | default_workflow frozen as jsonb |
admins |
The admin role, as data | Grant/revoke is itself an audited engine transition |
- No
SKIPPEDstage state. An early design review (decision G5) identified this as a dead/unreachable value and removed it before it could accumulate dead code paths in the engine. audit_log.sourcedistinguishesAPIfromSWEEP(and, after migration0006,CLI) so an audit trail entry always tells you which execution context produced it — a Postgres-level change made viaadminctlis never confused with one made from a browser session.package_idis nullable on bothaudit_logandnotifications, deliberately — some audit actions (e.g.,TOKEN_VENDED) and some notifications (ADMIN_ALERT) are not scoped to a single package.- Column order is a contract, not a style choice. Because two independent data-access layers (Go and Python) both read the same tables, a schema change must fan out to four places in lockstep: the migration, the Go struct, the Python dataclass (field order matching schema order), and the golden JSON fixture in
migrations/testdata/. Contract tests in both languages load and round-trip the same fixtures — this is the mechanism that catches a missed update, not a documentation reminder.
Packages move through five states: DRAFT → IN_REVIEW → CHANGES_REQUESTED → VALIDATED → ARCHIVED, with IN_REVIEW/CHANGES_REQUESTED cycling as stages complete or reviewers request changes. Every transition is handled by exactly one component, api/internal/engine, and never by raw SQL in an HTTP handler. A transition does four things inside one Postgres transaction:
SELECT … FOR UPDATEon the package row — this row lock is the concurrency boundary for the entire system (decision G1), replacing what would otherwise be an unspecified lost-update race on stage completion.- Re-validates authorization and transition legality server-side, regardless of what the UI already checked.
- Writes the
audit_logrow in the same transaction as the state change. - Honors the
Idempotency-Keyheader (decision R3) — a retried mutating request returns the cached first response rather than re-executing.
An illegal transition is rejected with no audit row written — the audit log records what happened, not what was attempted and refused.
An approval records the head Drive revision ID of every active document at the moment of approval. If a document changes after an approval was recorded, the participant's status is flagged STALE rather than the change being blocked — the system chooses to surface a signal over obstructing a reviewer's editing workflow. This is the practical expression of design principle #4.
The set of buttons a user may click is computed server-side by engine.AvailableActions and returned in the package detail payload; the SPA renders exactly that set and does not derive it independently. Each transition endpoint re-validates authorization and legality on its own regardless of what the client displayed — the server-computed action list is a UX convenience, never a security boundary in itself.
Several invariants span multiple files and are easy to violate without having read them explicitly. Each is backed by a specific enforcement mechanism, not left to reviewer memory.
Every Drive/Gmail interaction, in both languages, goes through a single interface (googleclient.GoogleClient in Go; its Python mirror in worker/google_client). The engine, the permission reconciler, and the workers see only that interface. verify.sh runs a grep guard that fails the build on any direct Google SDK import outside the one Real implementation file. Every call carries an explicit actorEmail, because Google access is per-user OAuth2 with no domain-wide delegation — the system never acts as an omnipotent service account against a user's Drive content.
oauth.Provider (token exchange/refresh) is kept as a separate interface from GoogleClient (Drive/Gmail data calls) — conflating "how do I get a token" with "what do I do with Drive" was identified as a coupling risk early and deliberately avoided.
Both the RealGoogleClient (needing a live per-actor access token for each Drive/Gmail call) and the internal HTTP token-vend endpoint need the same operation: "give me a valid access token for this user, cached if fresh, refreshed and re-cached if not." That logic exists exactly once, in tokenvend.Vendor; tokenvend.Source adapts it for googleclient.TokenSource. This was a conscious decision to prevent the refresh/cache logic from drifting into two slightly different implementations over time.
There are two distinct notions of "who is acting":
- The user's delegated identity (
oauth+tokenvend) — used for every Drive/Gmail call, since access is per-user, not domain-wide. - The service's own identity (
gcpauth, resolved from the Cloud Run metadata server) — used only for calls the service makes as itself: KMS wrap/unwrap, Pub/Sub publish.
Keeping these in separate packages makes "per-user OAuth, no domain-wide delegation" a property that can be checked by inspection (nothing in gcpauth touches Drive), rather than a claim that erodes silently if a future contributor reaches for the more convenient identity.
Refresh tokens are never handed to KMS directly. cipher.KMS generates a per-secret data-encryption key (DEK), seals the plaintext locally with AES-256-GCM, and asks KMS only to wrap that DEK. The stored blob format is version || len(wrappedDEK) || wrappedDEK || nonce+sealed. A dedicated test asserts the refresh token itself never crosses the KMS network boundary — KMS only ever sees an already-random DEK.
The notifications table is the source of truth for delivery, not the Pub/Sub message. The engine only enqueues PENDING rows inside its transaction; the Python notify_worker.deliver function is the single send path, shared by the Pub/Sub push handler and the sweep job. A published event is package-scoped ({package_id, event_type, correlation_id}) — never a specific notification ID — so a push handler that receives it re-scans for PENDING rows on that package rather than acting on a stale row reference; a lost message therefore loses nothing, since the sweep re-scans PENDING globally and calls the identical deliver function.
The concurrency primitive here (decision G4) is a single UPDATE … SET status='SENDING' … WHERE status='PENDING' RETURNING — a sender proceeds only if that UPDATE actually returned a row. This makes the row itself the mutex between a racing push delivery and a racing sweep delivery, without introducing a distributed lock.
api/internal/permissions/reconciler.go derives the desired Drive ACL purely from already-committed package/stage/participant state, diffs it against the actual ACL, and applies the delta idempotently. On failure, it writes a durable permission_tasks row and, after a configured retry ceiling, an ADMIN_ALERT notification — it never rolls back the state transition that already committed (decisions G2/G3). This is a deliberate acceptance that a workflow transition and its Drive side-effect are not atomic, in exchange for never leaving the package's logical state hostage to a Drive API outage.
Two independent drain paths exist by design: Reconciler.DrainPending (Go, hourly via cmd/drain) handles the fast retry, because a package whose ACL failed blocks its reviewers now; the Python sweep deliberately does not touch permission_tasks — duplicating the reconciler logic in a second language would violate the one-interface rule in Section 5.1.
Migration 0003 grants both service roles (dominio_api, dominio_sweep) only INSERT, SELECT on audit_log. Any UPDATE/DELETE attempt fails with a Postgres permission error, independent of application code — a contract test in both languages asserts this directly against the database. This closes the gap between "our code doesn't update this table" and "this table cannot be updated," which matters for audit integrity under a future bug or a compromised application credential.
SaveAsTemplate copies a package's active documents into a new template folder and freezes its stages and participants as a default_workflow JSON blob. Applying a template inserts a fresh copy into the new package's own folder. No package ever shares a Drive file_id with its template or with another package — this guarantees that revoking permissions on one package's documents can never inadvertently affect another package or its template source.
The admin set is not a hardcoded list; granting or revoking it is itself an audited engine transition (engine/admins.go), governed by two rules that live in exactly one place so the HTTP API and the operator CLI cannot diverge:
- Only an existing admin can grant the role over HTTP — there is deliberately no public bootstrap endpoint, because a service that behaves differently when its admin table happens to be empty is a self-service privilege escalation path.
- The last admin can never be revoked over HTTP — an empty admin set disables template management, the operational attention strip, and package owner reassignment, with no way back through the API.
The admin set itself is the concurrency boundary for this subsystem (repo.LockAdmins takes SELECT … FOR UPDATE over the whole table) — the same pattern as the per-package lock in Section 4.1, applied to the one set of rows this transition touches. Seeding the very first admin of a new environment is handled outside the HTTP surface entirely, by the adminctl CLI (run as a Cloud Run Job): permitted without being an admin only while the table is empty, and gated by -force afterward.
Every request is stamped with a correlation ID (minted if the caller didn't supply X-Correlation-Id), which then appears on every log line for that request and rides the Pub/Sub message into the workers — one review action is traceable end-to-end from api through the event to the delivered email without a distributed tracing system. Metrics are a hand-rolled Prometheus-text counter registry exposed at /metrics, deliberately without a metrics SDK. A rejected request (403/409/422) is counted as rejected, never error — a design choice that keeps alerting focused on genuine failures rather than paging on-call for normal product behavior like a user clicking a button they weren't authorized for.
The SPA (/web) has no build step: vanilla ES modules plus one stylesheet, served by the api binary itself when WEB_DIR is set (keeping the session cookie same-origin). Its structure mirrors the product surface directly — views/portfolio.js, detail.js, wizard.js, workflow.js, templates.js, admins.js — with no framework-level abstraction between a view and the DOM. There is no dedicated frontend test suite; anything worth asserting is instead covered by the Go handler tests that produce the JSON the frontend consumes, on the reasoning that the contract at the HTTP boundary is what needs pinning, not the rendering code itself.
Cloud Run (services): api, notify-worker
Cloud Run (jobs): sweep-job, drain, migrate, adminctl (dominio-admin-job)
Cloud Scheduler: triggers sweep-job (daily) and drain (hourly)
Cloud SQL: Postgres, private IP
Pub/Sub: package-lifecycle events, api → notify-worker push
Secret Manager: OAuth client secret, signing/cipher keys
Cloud KMS: wraps the DEK used to encrypt stored refresh tokens
Artifact Registry: two images — dominio-api, dominio-worker
Both container images are built from the repository root, each bundling every binary for its language in one image (api ships api, migrate, drain, adminctl, /migrations, /web; worker ships both Python entrypoints). This is intentional: it makes it structurally impossible for one commit's api binary to run against another commit's migrations, because they are always the same image.
Two authentication postures apply to the two public-facing surfaces:
apiis public (browsers must reach/authand/api), so a Cloud Run invoker IAM binding cannot gate it. Its/internal/*routes instead verify the caller's Google-signed OIDC ID token in application code (RS256, cached JWKS, audience pinned to the api's own URL, issuer allow-listed to exactly the notify-worker and sweep-job service accounts).notify-workeris deployed private, withrun.invokergranted only to the Pub/Sub push service account — its handler therefore verifies nothing itself and must never be reachable by anything else.
Terraform (/infra) is authored in-repo and applied by hand; the CI gate runs only terraform fmt/validate (skipped entirely if Terraform isn't installed), leaving the actual apply a deliberate human action rather than an automated one. Two details in the Terraform are load-bearing beyond the obvious: the monitoring alert policies match Cloud Run services/jobs by name, so a rename in run.tf silently disables an alert; and the api's own public URL is computed locally rather than read back from the resource, because the api needs that URL for its OAuth redirect and its own OIDC audience before the resource can reference itself.
The project was built in ten phases (P0–P9), each required to leave a single script green before the next could start:
./scripts/verify.shThis script: brings up Postgres via Docker Compose → applies migrations → runs go vet + go test ./... (including the golden-fixture contract tests) → runs the Google-SDK-boundary grep guard → runs pytest for the Python workers → builds the API binary and checks /healthz. It ends with VERIFY OK on success and is credential-free by construction — every fake-vs-real subsystem (Google client, cipher, event publisher) defaults to its in-memory fake unless a specific environment variable selects the real implementation, so the hermetic gate always exercises the real production binaries, just wired to fakes.
A separate, explicitly-excluded integration tier (Go build tag integration) exercises live OAuth refresh and real Drive/Gmail calls against a test Workspace; it is run on demand, never as part of the default gate.
| Phase | Scope | Status |
|---|---|---|
| P0 | Walking skeleton + verification harness | Complete |
| P1 | Schema + data-access + contract tests | Complete |
| P2 | State engine + reconciler (against fakes) | Complete |
| P3 | Auth & token custody | Complete (hermetic gate green; one integration item pending a dev OAuth client) |
| P4 | Real Google client behind the interface | Complete (hermetic gate + SDK boundary guard green; live integration run pending test Workspace) |
| P5 | Notifications, outbox, sweep | Complete |
| P6 | Frontend | Complete |
| P7 | Templates, versioning, hardening | Complete |
| P8 | Full IaC + production cutover | Code and Terraform complete; real terraform apply pending a billed GCP project |
| P9 | Admin-role governance | Complete |
The only outstanding step across the entire program is operational: running terraform apply against a provisioned GCP project with billing and a production OAuth client — the runbook for that step lives in infra/README.md.
A few decisions are worth calling out explicitly, since they represent trade-offs rather than defaults:
- Duplicating the data-access layer in two languages (Go and Python) rather than running both workers through the API or a shared RPC layer. This was accepted as a maintenance cost in exchange for keeping the Python workers simple stdlib consumers of Postgres, with the drift risk closed by shared golden fixtures and contract tests in both languages rather than by discipline alone.
- Accepting non-atomicity between a workflow transition and its Drive permission side-effect, in favor of a durable-retry reconciler. The alternative (holding the transaction open across a Drive API call) was rejected as it would make the package lock in Section 4.1 span a slow external network call.
- No native Postgres ENUM types, favoring
text+CHECK, to keep the migration path for adding new states simple: adding a state isDROP CONSTRAINT/ADD CONSTRAINT, not a Postgres enum-alteration migration with its own transactional restrictions. - The seed dataset is deliberately invisible to the sweep's global scans — no seeded participant is
APPROVEDwith recorded revisions, and every seeded due date sits far in the future — because the sweep's own Python tests assert whole-run counts against the same databaseverify.shuses. This is a subtle but load-bearing constraint on any future seed-data change.
| Document | Purpose |
|---|---|
README.md |
Repo layout, prerequisites, local dev setup — bilingual (EN/ES) |
CLAUDE.md |
Claude Code project instructions — the same invariants and contracts summarized in this document, in directive form |
dominio-plan.md |
Full original design specification (§1–§10) |
dominio-agent-plan.md |
Design review (decisions G1–G5, R1–R3, C1–C7, O1–O8) and the phased build plan |
docs/README.md |
Live phase status |
docs/p<N>-plan.md |
Per-phase implementation plan |
docs/test-checklist.md |
Maps every workflow transition and design-review decision to its covering test |
docs/user-guide.md |
End-user documentation |
infra/README.md |
Deployment runbook |