From 4c856b1b3e26f65ab7373ab8c60ed791ed3ad70a Mon Sep 17 00:00:00 2001 From: kiskaadee Date: Tue, 13 Oct 2026 06:27:49 -0500 Subject: [PATCH] docs: codify agent operating rules and consolidate architectural specifications - Add AGENTS.md specifying pre-commit verification gates, branch protection, and operating rules. - Reconcile relational SQL DDL across sculptures, users, check_ins, and tickets in docs/04_image_recognition_pipeline.md. - Specify SSO Identity Provider adapter pattern, Velocity Check math, and Hybrid Consensus thresholds in docs/02_architecture.md. - Add /auth/dev-token endpoint to docs/openapi_unified.yaml for offline development and automated testing. --- AGENTS.md | 56 +++++++++++++++++++++++++++ docs/02_architecture.md | 37 ++++++++++++++---- docs/04_image_recognition_pipeline.md | 56 +++++++++++++++++++++------ docs/openapi_unified.yaml | 45 +++++++++++++++++++++ 4 files changed, 175 insertions(+), 19 deletions(-) create mode 100644 AGENTS.md diff --git a/AGENTS.md b/AGENTS.md new file mode 100644 index 0000000..5fdec96 --- /dev/null +++ b/AGENTS.md @@ -0,0 +1,56 @@ +# Novias del Gato - Agent Guidelines & Workflow Rules + +This document specifies the mandatory workflows, constraints, and quality gates for AI agents operating in this repository. + +--- + +## 1. Core Operating Constraints + +- **No Direct Commits to `main`**: Agents must never commit directly to the `main` or `master` branches. All changes must be developed on descriptive feature, bugfix, or documentation branches (`feat/*`, `fix/*`, `docs/*`). +- **No Destructive Git Actions**: Commands such as `git reset --hard`, `git restore `, `git clean -fd`, and force-pushes (`git push --force`) are strictly prohibited without the user's explicit written approval. +- **Secret Redaction**: Never print, commit, or log sensitive information (tokens, secrets, private keys, database passwords, API credentials). Use environment variables and `.env` files (which must be ignored in `.gitignore`). +- **Session Modes**: + - `learning`: The user drives and writes the reasoning, the agent asks guiding questions. + - `delivery`: The agent may draft code and plans, presenting rationale and trade-offs. + +--- + +## 2. Verification Gates (Pre-Commit Checklist) + +Before any commit is proposed or executed, agents must execute and verify the following commands from the repository or `api/` directory: + +1. **Ruff Formatting**: + ```bash + uv run ruff format --check . + ``` +2. **Ruff Linting**: + ```bash + uv run ruff check . + ``` +3. **Static Type Checking (Pyright)**: + ```bash + uv run pyright + ``` +4. **Automated Test Suite (Pytest)**: + ```bash + uv run pytest + ``` + +No commit may be generated if any of these checks fail or report unhandled errors. + +--- + +## 3. Architecture & Domain Directives + +- **API-First Architecture**: Endpoints and schemas in `api/` must stay aligned with `docs/openapi_unified.yaml`. +- **SSO Identity Provider Pattern**: Authentication logic must be decoupled behind the `IdentityProvider` interface/adapter protocol. Do not hardcode vendor-specific auth checks in core routes. +- **Edge Inference Model Invariant**: Vector embeddings (1280 floats via MobileNetV2) are generated on client devices (WebAssembly/WebGL via ONNX Runtime Web). The backend never runs heavy deep learning inference on check-ins; it performs spatial proximity checks (PostGIS) and cosine similarity queries (`pgvector`). +- **Spatial & Vector Integrity**: Coordinates must use EPSG:4326 (WGS84). Embeddings must be 1280-dimension L2-normalized float vectors. + +--- + +## 4. Agent Directory & Delegation + +When working on specialized sub-domains: +- **Anne Droid** (`profile/agents/anne-droid.md`): Consult for UX flow, client accessibility, or backend API contract changes that impact the UI. Delegate to Anne for frontend component styling, PWA camera/canvas interaction, or client-side tests on `feat/anne/*` branches. +- Do not invoke Anne Droid for backend-only logic, database migrations, or Docker infrastructure. diff --git a/docs/02_architecture.md b/docs/02_architecture.md index 3b26ef6..4057b76 100644 --- a/docs/02_architecture.md +++ b/docs/02_architecture.md @@ -25,25 +25,46 @@ ## Logical Services -### 1. Identity & Profile Service -Manages user lifecycle, SSO, and the `trust_score` used by the reputation engine. +### 1. Identity & Profile Service (SSO Adapter Architecture) +Manages user lifecycle and authentication via a pluggable Identity Provider adapter (`IdentityProvider` protocol). +- **Core Interface**: Decoupled from specific OAuth vendors via `verify_token(token: str) -> AuthUserIdentity`. +- **Implementations**: + - `GoogleOAuthAdapter`: Production token verification using Google API certs. + - `MockDevAdapter`: Local development and automated testing adapter issuing valid test sessions without external network dependencies. + - Future-ready for Authelia / OIDC providers without modifying core routes. +- Maintains user profile attributes including `trust_score` (ranging from 0.0 to 1.0) and unlocked collection counts. ### 2. Integrity & Reputation Engine -Filters malicious traffic and spoofing. Performs **Velocity Checks** (time/distance deltas) and calculates user voting weight. +Guards against malicious data pollution, spoofing, and bot abuse. +- **Velocity Checks**: Analyzes spatio-temporal deltas between consecutive user submissions (check-ins and tickets): + $$v = \frac{d(p_1, p_2)}{\Delta t}$$ + If calculated speed $v > 120\text{ km/h}$ (maximum plausible urban velocity) and $\Delta t < 300\text{ s}$, the submission is rejected or tagged as suspicious. +- **Trust Score Adjustment**: Users start at baseline $0.5$. Successful verified crowdsourced reports increment `trust_score` by $+0.05$ (max $1.0$). Submissions caught spoofing or repeatedly rejected penalize trust by $-0.15$ (min $0.0$). ### 3. Hybrid Recognition Service -Validates "Check-ins" by comparing image vectors and GPS proximity using a `similarity_threshold`. +Validates "Check-ins" using client-side edge embeddings (MobileNetV2 1280-dimension float vector) and server-side spatial proximity: +- Coordinate proximity within 15 meters using PostGIS `ST_DWithin`. +- Cosine similarity threshold: $\text{similarity} = 1.0 - (\text{embedding} \Leftrightarrow \mathbf{v}_{\text{query}}) \ge 0.65$. ### 4. Interaction & Collection Service -Manages the many-to-many relationship between users and sculptures (unlocked achievements). +Manages the many-to-many relationship between users and sculptures (unlocked achievements, captured photo galleries, and cultural audio/insights). ### 5. Crowdsourcing & Ticket Service -Manages asynchronous reports (Tickets) for moved or missing sculptures. +Manages citizen reports for moved, missing, or altered sculptures: +- Accepts coordinates, observed status, verification photo, and optional commentary. +- Groups overlapping submissions into spatial clusters ($\le 20\text{ m}$ radius) over a 48-hour window. -### 6. Location Tracker Service (The Oracle) -The final consumer of corroborated reports. Updates the "Single Source of Truth" (SSOT) for sculpture locations using a **Weighted Voting Algorithm**. +### 6. Location Tracker Service (The Oracle) & Hybrid Consensus Engine +Computes the single source of truth (SSOT) location and status of each sculpture: +- **Cluster Confidence Metric**: + $$C_{\text{cluster}} = \sum_{i=1}^{N} \text{trust\_score}_i$$ +- **Automatic State Transition**: If $C_{\text{cluster}} \ge 3.0$ with $N \ge 3$ distinct submitters and variance $\sigma_{\text{dist}} \le 20\text{ m}$, the Oracle automatically promotes the reported coordinates/status to the official sculpture record. +- **Moderator Escalation**: If $1.5 \le C_{\text{cluster}} < 3.0$ or reports have conflicting statuses, the cluster is held in `pending` state for manual moderator review via `/reports/{id}/verify`. ## Architecture Decision Records (ADR) * **Separation of Check-in vs. Ticket:** Allows the system to be usable even with incorrect location data, fostering community correction without blocking the fun. * **Single Database (pgvector + PostGIS):** Reduces network latency and synchronization complexity between spatial and vector data. * **PWA Priority:** Chosen for immediate access (QR/URL) over the friction of app store downloads, especially for tourists. +* **SSO Adapter Pattern:** Isolates authentication provider logic behind a clean contract, allowing local offline testing and easy migration to alternative auth providers (e.g. Authelia) without touching business logic. +* **Hybrid Consensus Threshold:** Combines automated confidence scoring ($\ge 3.0$) with human-in-the-loop moderator verification for ambiguous edge cases, balancing real-time responsiveness with catalog integrity. + diff --git a/docs/04_image_recognition_pipeline.md b/docs/04_image_recognition_pipeline.md index 8e886f9..98e5164 100644 --- a/docs/04_image_recognition_pipeline.md +++ b/docs/04_image_recognition_pipeline.md @@ -63,39 +63,73 @@ graph TD ## 3. Data Schemas & API Contracts ### Database Schema (SQL) -We store the reference vectors using the `pgvector` extension and the physical locations using the `postgis` extension. +We store reference vectors using the `pgvector` extension and physical locations using the `postgis` extension. ```sql -- Ensure extensions are loaded CREATE EXTENSION IF NOT EXISTS postgis; CREATE EXTENSION IF NOT EXISTS vector; --- Sculptures table storing baseline vectors +-- Users table +CREATE TABLE users ( + id UUID PRIMARY KEY DEFAULT gen_random_uuid(), + name VARCHAR(100) NOT NULL, + email VARCHAR(255) UNIQUE NOT NULL, + trust_score FLOAT NOT NULL DEFAULT 0.5 CHECK (trust_score >= 0.0 AND trust_score <= 1.0), + created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP, + updated_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP +); + +-- Sculptures table storing baseline vectors and spatial locations (SRID 4326) CREATE TABLE sculptures ( id UUID PRIMARY KEY DEFAULT gen_random_uuid(), name VARCHAR(255) NOT NULL, + artist VARCHAR(255) NOT NULL, + year INTEGER NOT NULL CHECK (year >= 1900), description TEXT, - location GEOGRAPHY(Point, 4326) NOT NULL, -- Spatial coordinates (SRID 4326) + audio_url VARCHAR(512), + unlocked_content TEXT, + status VARCHAR(50) NOT NULL DEFAULT 'on-site' CHECK (status IN ('on-site', 'moved', 'missing')), + location GEOGRAPHY(Point, 4326) NOT NULL, embedding vector(1280) NOT NULL, -- L2-Normalized MobileNetV2 embedding vector - created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP + created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP, + updated_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP ); -- Check-in Records table (Explorer's Gallery) CREATE TABLE check_ins ( id UUID PRIMARY KEY DEFAULT gen_random_uuid(), - user_id UUID NOT NULL, - sculpture_id UUID REFERENCES sculptures(id), + user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE, + sculpture_id UUID NOT NULL REFERENCES sculptures(id) ON DELETE CASCADE, captured_at TIMESTAMP WITH TIME ZONE NOT NULL, photo_url VARCHAR(512) NOT NULL, -- URL pointing to the compressed 80KB photo - similarity_score FLOAT NOT NULL, -- The cosine distance calculated at check-in - created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP + similarity_score FLOAT NOT NULL CHECK (similarity_score >= 0.0 AND similarity_score <= 1.0), + created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT uq_user_sculpture UNIQUE (user_id, sculpture_id) ); --- Create a spatial index for fast proximity queries -CREATE INDEX idx_sculptures_location ON sculptures USING GIST (location); +-- Crowdsourced Tickets / Reports table +CREATE TABLE tickets ( + id UUID PRIMARY KEY DEFAULT gen_random_uuid(), + reporter_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE, + sculpture_id UUID NOT NULL REFERENCES sculptures(id) ON DELETE CASCADE, + reported_status VARCHAR(50) NOT NULL CHECK (reported_status IN ('on-site', 'moved', 'missing')), + location GEOGRAPHY(Point, 4326) NOT NULL, + photo_url VARCHAR(512), + description VARCHAR(500), + status VARCHAR(50) NOT NULL DEFAULT 'pending' CHECK (status IN ('pending', 'approved', 'rejected')), + reporter_trust_score FLOAT NOT NULL CHECK (reporter_trust_score >= 0.0 AND reporter_trust_score <= 1.0), + notes VARCHAR(300), + created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP, + resolved_at TIMESTAMP WITH TIME ZONE +); --- Create an HNSW index for fast vector cosine similarity search +-- Spatial and Vector Indexes +CREATE INDEX idx_sculptures_location ON sculptures USING GIST (location); CREATE INDEX idx_sculptures_embedding ON sculptures USING hnsw (embedding vector_cosine_ops); +CREATE INDEX idx_tickets_location ON tickets USING GIST (location); +CREATE INDEX idx_tickets_sculpture_status ON tickets (sculpture_id, status); +CREATE INDEX idx_check_ins_user ON check_ins (user_id); ``` ### API Endpoint (OpenAPI Fragment) diff --git a/docs/openapi_unified.yaml b/docs/openapi_unified.yaml index 4eeb7ee..20141ed 100644 --- a/docs/openapi_unified.yaml +++ b/docs/openapi_unified.yaml @@ -53,6 +53,51 @@ paths: '401': description: Invalid token provided. + /auth/dev-token: + post: + summary: Development SSO Bypass Token Generation + description: | + Generates a valid signed JWT for a specified email without contacting external identity providers. + Available only when server environment is configured for development or testing (ENV != 'production'). + operationId: getDevToken + requestBody: + required: true + content: + application/json: + schema: + type: object + required: + - email + properties: + email: + type: string + format: email + example: explorer@example.com + name: + type: string + example: Local Explorer + responses: + '200': + description: Test token issued + content: + application/json: + schema: + type: object + required: + - access_token + - token_type + - expires_in + properties: + access_token: + type: string + token_type: + type: string + example: Bearer + expires_in: + type: integer + '403': + description: Endpoint disabled in production mode. + /users/me: get: summary: Retrieve Current User Profile