8000 GitHub - AngelsalamancaCar/dominio · GitHub
[go: up one dir, main page]

Skip to content
AngelsalamancaCarPublic

About

No description, website, or topics provided.

Resources

Stars

1 star

Watchers

0 watching

Forks

Repository files navigation

Dominio — Documentation Package Tool

🇺🇸 English  •  🇪🇸 Español

Quality-control service for Google Docs/Sheets/Forms review packages — state machine, automated Drive permission provisioning, notifications, append-only audit trail.

phases gate design doc


🇺🇸 English

Table of contents

Architecture

Component Language Role Trigger
api Go Public HTTPS API: OAuth2 login, package/document/workflow CRUD, state-machine engine, Drive permission provisioning, audit log writes HTTP (Cloud Run service)
notify-worker Python Consumes package events, sends templated email via Gmail API Pub/Sub push (Cloud Run service)
sweep-job Python Scheduled job: due-date reminders, staleness detection, stuck-notification reconciliation Cloud Scheduler → Cloud Run Job
web SPA (vanilla ES modules, no build step) Portfolio, package detail, wizard, workflow editor, admin console Served by api (WEB_DIR) or any static host

Backed by Cloud SQL for PostgreSQL. Google Workspace access is per-user OAuth2 (no domain-wide delegation) — every Drive/Gmail call carries a specific user's identity. Full design spec: dominio-plan.md; implementation phases and design-review decisions: dominio-agent-plan.md; consulting-style architecture write-up: dominiodesign.md; Claude Code project instructions: CLAUDE.md.

Repo layout

Expand full tree
/api            Go module — cmd/: api, migrate, drain (scheduled permission-task retry),
                adminctl (operator tool that seeds the first admin of an environment).
                internal/: engine, permissions (reconciler), repo, oauth, session,
                httpapi, cipher (local + KMS), googleclient (Fake + real.go),
                tokenvend (per-user access-token vend), gcpauth (the service's own
                identity), bootstrap (fake-vs-real selection), obs (correlation ids
                + metrics). Dockerfile builds from the repo root.
/worker         Python package — notify_worker, sweep_job, google_client, repo;
                Dockerfile with both entrypoints (also built from the repo root)
/web            Frontend SPA — index.html + app.css + js/ (ES modules, no npm);
                picker.html is a throwaway P4 dev stub
/migrations     Shared SQL migrations — single source of schema truth
                (testdata/ = golden fixtures pinning Go + Python data layers;
                seed/ = dev fixtures, not migrations)
/infra          Terraform for Cloud Run, Cloud SQL, Pub/Sub, Scheduler, Secret
                Manager, KMS + monitoring; README.md is the deployment runbook
/docs           Documentation (phase status, per-phase plans p<N>-plan.md,
                test-checklist.md, user-guide.md)
/scripts        Dev/CI scripts (verify.sh — the phase gate; seed.sh, reset-db.sh)

🚦 Build status

All build phases are complete:

Phase Scope Status
P0 Walking skeleton + verification harness ✅
P1 Schema + data-access + contract tests ✅
P2 State engine + reconciler (against fakes) ✅
P3 Auth & token custody ✅ (one [integration] item pends a dev OAuth client)
P4 Real Google client behind the interface ✅ (live integration run pends a test Workspace)
P5 Notifications, outbox, sweep ✅
P6 Frontend ✅
P7 Templates, versioning, hardening ✅
P8 Full IaC + production cutover ✅ code/Terraform — real terraform apply pending a billed GCP project
P9 Admin-role governance ✅

Live status detail: docs/README.md. The only step outstanding across the whole program is operational — running terraform apply against a provisioned, billed GCP project (runbook: infra/README.md).

Prerequisites

  • Go 1.26+
  • Python 3.12+
  • Docker (with Compose)
  • Bash + curl (for scripts/verify.sh; on Windows use Git Bash)

Local development

Local stack runs Postgres in Docker on host port 5433 (avoids collision with any local Postgres on 5432):

docker compose up -d --wait postgres

Default connection string (schema owner, used by migrations):

postgres://dominio:dominio@localhost:5433/dominio?sslmode=disable

Services and tests use per-component roles created by migration 0003 (dev password equals the role name): dominio_api (Go, full write except audit_log update/delete) and dominio_sweep (Python, read-all + the sweep write set). The audit_log append-only rule is a DB grant — both roles get INSERT, SELECT only. Override DSNs via DATABASE_URL_API / DATABASE_URL_SWEEP.

Python dependencies (first needed in P1): pip install "psycopg[binary]>=3.2" pytest (or pip install -e worker[dev]).

Apply migrations:

cd api && go run ./cmd/migrate -dir ../migrations
Migrations are roll-forward only — details

Migrations are roll-forward only (spec §8.2): there are no down-migrations, and a correction is a new numbered file. The way to undo a local experiment is to rebuild the database:

./scripts/reset-db.sh      # drop schema + re-migrate + seed (dev only)
./scripts/seed.sh          # just the fixtures; idempotent, safe to re-run

Both refuse to run against anything but a local host, so neither can be aimed at a deployed environment. The seed puts one admin (qa-admin@example.com), one template and one package mid-review into the database; it is deliberately invisible to the sweep's global scans, so verify.sh stays green on a seeded database (see the invariant at the top of migrations/seed/seed.sql).

Verification gate

./scripts/verify.sh is the universal phase gate — every phase must keep it green. It:

  1. Brings up Postgres via docker compose
  2. Applies migrations
  3. Runs go vet + go test ./... (api) — includes the golden-fixture contract tests
  4. Runs the Google SDK boundary guard — fails if google.golang.org/api/ is imported outside internal/googleclient/real*.go
  5. Runs terraform fmt/validate (skipped if terraform is absent)
  6. Runs pytest (worker) — same contract fixtures through the Python layer, plus the outbox/claim tests
  7. Builds the API binary and checks /healthz responds
./scripts/verify.sh

Ends with VERIFY OK on success.

Testing individual services

# Go
cd api && go test ./...

# Python
cd worker && python -m pytest -q

Go and Python tests are DB-gated: they skip when DATABASE_URL is unset, so run them through verify.sh (which brings up Postgres) or export the DSN yourself.

Integration tier (real Google/GCP, on demand)

Excluded from the default gate; behind the integration build tag and skips cleanly without its env vars:

go test -tags integration ./internal/oauth/...        # live OAuth refresh
go test -tags integration ./internal/googleclient/... # real Drive/Gmail against a test Workspace

The Drive/Gmail client selection is by GOOGLE_MODE (fake default — the in-memory client that keeps the gate credential-free; real uses the live SDK).

Running the app locally

The api serves the SPA itself when WEB_DIR points at /web, so the session cookie is same-origin:

cd api
export GOOGLE_OAUTH_CLIENT_ID=… GOOGLE_OAUTH_CLIENT_SECRET=…
export OAUTH_REDIRECT_URL=http://localhost:8080/auth/google/callback
export DATABASE_URL=postgres://dominio_api:dominio_api@localhost:5433/dominio?sslmode=disable
export CIPHER_KEY=<32 bytes> SESSION_SIGNING_KEY=<32 bytes>
export WEB_DIR=../web            # serve the SPA from the api (same origin)
go run ./cmd/api

Then open http://localhost:8080/ — unauthenticated calls bounce through /auth/google/login. Without WEB_DIR the binary is API-only; without GOOGLE_OAUTH_CLIENT_ID it degrades to the healthz-only skeleton (that is how the gate runs it).

Observability

Every request carries a correlation id (X-Correlation-Id, minted if absent) that lands on every JSON log line of that request and rides the Pub/Sub message into the workers, so one review action is traceable api → event → email. GET /metrics serves aggregate counters in Prometheus text format — transitions by action and outcome (a rejection counts as rejected, never error), notifications queued, permission-task outcomes and internal token vends. Alert policies live in infra/monitoring.tf; they match Cloud Run services and jobs by name, so renaming one in infra/run.tf silently disables its alert.

Deployment

infra/ is the whole environment: Cloud Run (api + notify-worker services; sweep, drain and migrate jobs), Cloud SQL on a private IP, Pub/Sub, Scheduler, Secret Manager, KMS, Artifact Registry and one service account per component. infra/README.md is the runbook (first apply, OAuth secret, images, migrations, rollback, rotations). CI/CD is .github/workflows/deploy.yml — manual dispatch, keyless via Workload Identity Federation, and it runs the same verify.sh gate before it builds anything.

docker build -f api/Dockerfile    -t dominio-api    .   # from the repo root
docker build -f worker/Dockerfile -t dominio-worker .

Key design principles

  1. Explicit actions only advance the workflow — opening/commenting on a doc never counts as approval.
  2. Audit log is append-only, enforced at both app layer and DB grant level (INSERT, SELECT only).
  3. Approvals capture evidence (head revision ID of each active document).
  4. Staleness is detected, not prevented — approvals against changed revisions get flagged STALE.
  5. Permissions are provisioned as a desired-state reconciler from committed workflow state; all permission operations are idempotent.
  6. Every state transition acquires a row lock on its package (SELECT … FOR UPDATE) — the package row is the concurrency boundary.
  7. Mutating API endpoints are idempotent by Idempotency-Key.

See dominio-plan.md §1.5 for the full list.

Documentation index

Document Purpose
dominio-plan.md Full original design specification (§1–§10)
dominio-agent-plan.md Design review (G1–G5, R1–R3, C1–C7, O1–O8) + phased build plan
dominiodesign.md Consulting-style architecture & design deliverable
CLAUDE.md Claude Code project instructions — invariants, contracts, working rules
docs/README.md Live phase status (Spanish)
docs/user-guide.md End-user guide (Spanish)
docs/test-checklist.md Maps every workflow transition + design decision to its covering test
infra/README.md Deployment runbook

↑ back to top


🇪🇸 Español

Índice

Arquitectura

Componente Lenguaje Rol Disparador
api Go API HTTPS pública: login OAuth2, CRUD de paquetes/documentos/workflow, motor de máquina de estados, aprovisionamiento de permisos en Drive, escritura del audit log HTTP (servicio en Cloud Run)
notify-worker Python Consume eventos de paquete, envía correo con plantilla vía Gmail API Push de Pub/Sub (servicio en Cloud Run)
sweep-job Python Job programado: recordatorios de fecha límite, detección de obsolescencia (staleness), reconciliación de notificaciones atascadas Cloud Scheduler → Cloud Run Job
web SPA (módulos ES nativos, sin build) Portafolio, detalle de paquete, wizard, editor de workflow, consola de administración Servida por api (WEB_DIR) o cualquier hosting estático

Respaldado por Cloud SQL para PostgreSQL. El acceso a Google Workspace es OAuth2 por usuario (sin delegación de dominio completo) — cada llamada a Drive/Gmail lleva la identidad de un usuario específico. Especificación de diseño completa: dominio-plan.md; fases de implementación y decisiones de la revisión de diseño: dominio-agent-plan.md; documento de arquitectura estilo consultoría: dominiodesign.md; instrucciones del proyecto para Claude Code: CLAUDE.md.

Estructura del repositorio

Ver árbol completo
/api            Módulo Go — cmd/: api, migrate, drain (reintento programado de tareas
                de permisos), adminctl (herramienta de operador que siembra el primer
                admin de un entorno).
                internal/: engine, permissions (reconciliador), repo, oauth, session,
                httpapi, cipher (local + KMS), googleclient (Fake + real.go),
                tokenvend (vendido de access-token por usuario), gcpauth (identidad
                propia del servicio), bootstrap (selección fake-vs-real), obs
                (correlation ids + métricas). El Dockerfile compila desde la raíz.
/worker         Paquete Python — notify_worker, sweep_job, google_client, repo;
                Dockerfile con ambos entrypoints (también compila desde la raíz)
/web            SPA de frontend — index.html + app.css + js/ (módulos ES, sin npm);
                picker.html es un stub descartable de desarrollo de P4
/migrations     Migraciones SQL compartidas — fuente única de verdad del esquema
                (testdata/ = fixtures de referencia que fijan las capas de datos
                Go + Python; seed/ = fixtures de desarrollo, no migraciones)
/infra          Terraform para Cloud Run, Cloud SQL, Pub/Sub, Scheduler, Secret
                Manager, KMS + monitoreo; README.md es el runbook de despliegue
/docs           Documentación (estado de fases, planes por fase p<N>-plan.md,
                test-checklist.md, user-guide.md)
/scripts        Scripts de desarrollo/CI (verify.sh — el gate de fase; seed.sh, reset-db.sh)

🚦 Estado del build

Todas las fases de construcción están completas:

Fase Alcance Estado
P0 Esqueleto funcional + arnés de verificación ✅
P1 Esquema + capa de acceso a datos + pruebas de contrato ✅
P2 Motor de estados + reconciliador (contra fakes) ✅
P3 Autenticación y custodia de tokens ✅ (un ítem [integration] pendiente de cliente OAuth de desarrollo)
P4 Cliente real de Google detrás de la interfaz ✅ (ejecución en vivo del tier de integración pendiente de un Workspace de prueba)
P5 Notificaciones, outbox, sweep ✅
P6 Frontend ✅
P7 Plantillas, versionado, hardening ✅
P8 IaC completo + corte a producción ✅ código/Terraform — falta el terraform apply real contra un proyecto GCP con facturación
P9 Gobierno del rol admin ✅

Detalle de estado en vivo: docs/README.md. El único paso pendiente en todo el programa es operativo — ejecutar terraform apply contra un proyecto GCP aprovisionado y con facturación (runbook: infra/README.md).

Prerrequisitos

  • Go 1.26+
  • Python 3.12+
  • Docker (con Compose)
  • Bash + curl (para scripts/verify.sh; en Windows usar Git Bash)

Desarrollo local

El stack local corre Postgres en Docker en el puerto de host 5433 (evita colisión con cualquier Postgres local en 5432):

docker compose up -d --wait postgres

Cadena de conexión por defecto (dueño del esquema, usada por las migraciones):

postgres://dominio:dominio@localhost:5433/dominio?sslmode=disable

Los servicios y las pruebas usan roles por componente creados por la migración 0003 (la contraseña de desarrollo es igual al nombre del rol): dominio_api (Go, escritura completa excepto update/delete de audit_log) y dominio_sweep (Python, lectura total + el conjunto de escritura del sweep). La regla de append-only de audit_log es un grant de la base de datos — ambos roles solo reciben INSERT, SELECT. Sobrescribe los DSN vía DATABASE_URL_API / DATABASE_URL_SWEEP.

Dependencias de Python (necesarias desde P1): pip install "psycopg[binary]>=3.2" pytest (o pip install -e worker[dev]).

Aplicar migraciones:

cd api && go run ./cmd/migrate -dir ../migrations
Las migraciones son solo hacia adelante — detalles

Las migraciones son solo hacia adelante (spec §8.2): no hay down-migrations, y una corrección es un archivo nuevo numerado. La forma de deshacer un experimento local es reconstruir la base de datos:

./scripts/reset-db.sh      # elimina el esquema + re-migra + siembra (solo dev)
./scripts/seed.sh          # solo los fixtures; idempotente, seguro de re-ejecutar

Ambos scripts se niegan a correr contra algo que no sea un host local, así que ninguno puede apuntarse a un entorno desplegado. El seed inserta un admin (qa-admin@example.com), una plantilla y un paquete a mitad de revisión; es deliberadamente invisible para los escaneos globales del sweep, de modo que verify.sh se mantiene verde sobre una base de datos sembrada (ver el invariante al inicio de migrations/seed/seed.sql).

Gate de verificación

./scripts/verify.sh es el gate universal de fase — cada fase debe mantenerlo en verde. El script:

  1. Levanta Postgres vía docker compose
  2. Aplica las migraciones
  3. Corre go vet + go test ./... (api) — incluye las pruebas de contrato con fixtures de referencia
  4. Corre el guard de frontera del SDK de Google — falla si se importa google.golang.org/api/ fuera de internal/googleclient/real*.go
  5. Corre terraform fmt/validate (se omite si terraform no está instalado)
  6. Corre pytest (worker) — los mismos fixtures de contrato a través de la capa Python, más las pruebas de outbox/claim
  7. Compila el binario de la API y verifica que /healthz responda
./scripts/verify.sh

Termina con VERIFY OK si todo pasa.

Pruebas de servicios individuales

# Go
cd api && go test ./...

# Python
cd worker && python -m pytest -q

Las pruebas de Go y Python están condicionadas a la base de datos: se omiten si DATABASE_URL no está definida, así que ejecútalas vía verify.sh (que levanta Postgres) o exporta el DSN tú mismo.

Tier de integración (Google/GCP real, bajo demanda)

Excluido del gate por defecto; está detrás del build tag integration y se omite limpiamente sin sus variables de entorno:

go test -tags integration ./internal/oauth/...        # refresh real de OAuth
go test -tags integration ./internal/googleclient/... # Drive/Gmail real contra un Workspace de prueba

La selección del cliente de Drive/Gmail es por GOOGLE_MODE (fake por defecto — el cliente en memoria que mantiene el gate libre de credenciales; real usa el SDK en vivo).

Ejecutar la app en local

La api sirve la SPA directamente cuando WEB_DIR apunta a /web, de modo que la cookie de sesión sea same-origin:

cd api
export GOOGLE_OAUTH_CLIENT_ID=… GOOGLE_OAUTH_CLIENT_SECRET=…
export OAUTH_REDIRECT_URL=http://localhost:8080/auth/google/callback
export DATABASE_URL=postgres://dominio_api:dominio_api@localhost:5433/dominio?sslmode=disable
export CIPHER_KEY=<32 bytes> SESSION_SIGNING_KEY=<32 bytes>
export WEB_DIR=../web            # sirve la SPA desde la api (same origin)
go run ./cmd/api

Luego abre http://localhost:8080/ — las llamadas sin autenticar rebotan a /auth/google/login. Sin WEB_DIR el binario es solo API; sin GOOGLE_OAUTH_CLIENT_ID degrada al esqueleto healthz-only (así es como el gate lo ejecuta).

Observabilidad

Cada request lleva un correlation id (X-Correlation-Id, generado si no viene) que aparece en cada línea de log JSON de ese request y viaja en el mensaje de Pub/Sub hacia los workers, de modo que una acción de revisión es trazable api → evento → correo. GET /metrics expone contadores agregados en formato texto de Prometheus — transiciones por acción y resultado (un rechazo cuenta como rejected, nunca como error), notificaciones encoladas, resultados de tareas de permisos y vendidos de token internos. Las políticas de alerta viven en infra/monitoring.tf; hacen match con los servicios y jobs de Cloud Run por nombre, así que renombrar uno en infra/run.tf desactiva silenciosamente su alerta.

Despliegue

infra/ es el entorno completo: Cloud Run (servicios api + notify-worker; jobs sweep, drain y migrate), Cloud SQL con IP privada, Pub/Sub, Scheduler, Secret Manager, KMS, Artifact Registry y una cuenta de servicio por componente. infra/README.md es el runbook (primer apply, secreto OAuth, imágenes, migraciones, rollback, rotaciones). El CI/CD es .github/workflows/deploy.yml — dispatch manual, sin llaves vía Workload Identity Federation, y corre el mismo gate verify.sh antes de construir nada.

docker build -f api/Dockerfile    -t dominio-api    .   # desde la raíz del repo
docker build -f worker/Dockerfile -t dominio-worker .

Principios de diseño clave

  1. Solo las acciones explícitas avanzan el workflow — abrir o comentar un documento nunca cuenta como aprobación.
  2. El audit log es append-only, forzado tanto en la capa de aplicación como a nivel de grant de la base de datos (INSERT, SELECT únicamente).
  3. Las aprobaciones capturan evidencia (el ID de revisión de cabeza de cada documento activo).
  4. La obsolescencia (staleness) se detecta, no se previene — las aprobaciones contra revisiones cambiadas se marcan STALE.
  5. Los permisos se aprovisionan como un reconciliador de estado deseado a partir del estado de workflow ya confirmado; todas las operaciones de permisos son idempotentes.
  6. Cada transición de estado adquiere un row lock sobre su paquete (SELECT … FOR UPDATE) — la fila del paquete es el límite de concurrencia.
  7. Los endpoints mutables de la API son idempotentes vía Idempotency-Key.

Ver dominio-plan.md §1.5 para la lista completa.

Índice de documentación

Documento Propósito
dominio-plan.md Especificación de diseño original completa (§1–§10)
dominio-agent-plan.md Revisión de diseño (G1–G5, R1–R3, C1–C7, O1–O8) + plan de construcción por fases
dominiodesign.md Entregable de arquitectura estilo consultoría
CLAUDE.md Instrucciones del proyecto para Claude Code — invariantes, contratos, reglas de trabajo
docs/README.md Estado de fases en vivo (español)
docs/user-guide.md Guía de usuario final (español)
docs/test-checklist.md Mapea cada transición de workflow + decisión de diseño a la prueba que la cubre
infra/README.md Runbook de despliegue

↑ volver arriba

About

No description, website, or topics provided.

Resources

Stars

1 star

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages

0