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.
This commit is contained in:
1 parent
74451c1cdb
commit
4c856b1b3e
4 files changed
+175
-19
No files matched your search
@@ -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 <file>`, `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.
|
||||||
+29
-8
@@ -25,25 +25,46 @@
|
|||||||
|
|
||||||
## Logical Services
|
## Logical Services
|
||||||
|
|
||||||
### 1. Identity & Profile Service
|
### 1. Identity & Profile Service (SSO Adapter Architecture)
|
||||||
Manages user lifecycle, SSO, and the `trust_score` used by the reputation engine.
|
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
|
### 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
|
### 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
|
### 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
|
### 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)
|
### 6. Location Tracker Service (The Oracle) & Hybrid Consensus Engine
|
||||||
The final consumer of corroborated reports. Updates the "Single Source of Truth" (SSOT) for sculpture locations using a **Weighted Voting Algorithm**.
|
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)
|
## 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.
|
* **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.
|
* **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.
|
* **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.
|
||||||
|
|
||||||
@@ -63,39 +63,73 @@ graph TD
|
|||||||
## 3. Data Schemas & API Contracts
|
## 3. Data Schemas & API Contracts
|
||||||
|
|
||||||
### Database Schema (SQL)
|
### 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
|
```sql
|
||||||
-- Ensure extensions are loaded
|
-- Ensure extensions are loaded
|
||||||
CREATE EXTENSION IF NOT EXISTS postgis;
|
CREATE EXTENSION IF NOT EXISTS postgis;
|
||||||
CREATE EXTENSION IF NOT EXISTS vector;
|
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 (
|
CREATE TABLE sculptures (
|
||||||
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||||
name VARCHAR(255) NOT NULL,
|
name VARCHAR(255) NOT NULL,
|
||||||
|
artist VARCHAR(255) NOT NULL,
|
||||||
|
year INTEGER NOT NULL CHECK (year >= 1900),
|
||||||
description TEXT,
|
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
|
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)
|
-- Check-in Records table (Explorer's Gallery)
|
||||||
CREATE TABLE check_ins (
|
CREATE TABLE check_ins (
|
||||||
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||||
user_id UUID NOT NULL,
|
user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
||||||
sculpture_id UUID REFERENCES sculptures(id),
|
sculpture_id UUID NOT NULL REFERENCES sculptures(id) ON DELETE CASCADE,
|
||||||
captured_at TIMESTAMP WITH TIME ZONE NOT NULL,
|
captured_at TIMESTAMP WITH TIME ZONE NOT NULL,
|
||||||
photo_url VARCHAR(512) NOT NULL, -- URL pointing to the compressed 80KB photo
|
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
|
similarity_score FLOAT NOT NULL CHECK (similarity_score >= 0.0 AND similarity_score <= 1.0),
|
||||||
created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP
|
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
|
-- Crowdsourced Tickets / Reports table
|
||||||
CREATE INDEX idx_sculptures_location ON sculptures USING GIST (location);
|
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_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)
|
### API Endpoint (OpenAPI Fragment)
|
||||||
|
|||||||
@@ -53,6 +53,51 @@ paths:
|
|||||||
'401':
|
'401':
|
||||||
description: Invalid token provided.
|
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:
|
/users/me:
|
||||||
get:
|
get:
|
||||||
summary: Retrieve Current User Profile
|
summary: Retrieve Current User Profile
|
||||||
|
|||||||
Reference in new issue
Block a user