Compare commits

...
5 Commits
Author SHA1 Message Date
kiskaadee f4ac890432 fix(deps): bump certifi to 2026.10.23 (CVE-2026-115557)
Remediate eMudhra/emSign intermediate CA private key compromise by updating certifi to 2026.10.23.
2026-10-29 13:31:14 -05:00
kiskaadee 56656be597 feat(api): implement authentication and user profile routers
- Add get_current_user JWT dependency with HTTPBearer in routers/deps.py

- Add POST /auth/login and POST /auth/dev-token endpoints with user auto-provisioning

- Add GET /users/me and GET /users/me/collection endpoints with capture count aggregation

- Add integration tests for authentication lifecycle and collection tracking (36 passing tests)

- Synchronize todo.txt milestone deliverables
2026-10-15 07:13:26 -05:00
kiskaadee 285add0b98 feat(api): implement sculptures read router with spatial coordinate serialization
- Add GET /sculptures and GET /sculptures/{id} endpoints

- Implement EWKB/WKT coordinate extractor for PostGIS geometry

- Register router in FastAPI application

- Configure NullPool test database fixture to prevent connection pool clashes

- Add comprehensive integration and unit test suite (31 tests passing)

- Update todo.txt milestone tracking
2026-10-13 08:09:08 -05:00
kiskaadee 454e14b9fb docs(agents): adopt todo.txt milestone tracking and agent sync rules
- Add root todo.txt tracking foundational and Phase 3 deliverables
- Codify live task tracking and synchronization rule in AGENTS.md
2026-10-13 07:53:08 -05:00
kiskaadee 0329d5f588 docs(architecture): define Jev-powered Cascade Triage for crowdsourced reports
- Add Cascade Triage flow to Crowdsourcing & Ticket Service in docs/02_architecture.md.
- Codify ADR for non-autoregressive decision model (Jev) via pluggable TriageProvider.
- Update ADR-004 in docs/04_image_recognition_pipeline.md for fast-path device fallback triage.
2026-10-13 07:34:49 -05:00
18 changed files with 674 additions and 47 deletions

No files matched your search

+11
View File
@@ -12,6 +12,7 @@ This document specifies the mandatory workflows, constraints, and quality gates
- **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.
- **Live Task Tracking (`todo.txt`)**: Keep `todo.txt` synchronized with code reality. When a deliverable or milestone is implemented and verified, mark it as completed (`x YYYY-MM-DD ...`) immediately. Never leave verified work marked as pending or untracked.
---
@@ -54,3 +55,13 @@ No commit may be generated if any of these checks fail or report unhandled error
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.
---
## 5. Live Task Tracking (`todo.txt`)
For multi-step engineering milestones and deliverables:
- Maintain a standard, comment-free `todo.txt` in the repository root formatted for `tuxedo` / `todo.sh`.
- Prioritize deliverables using standard priorities (`(A)`, `(B)`, `(C)`), projects (`+<component>`), and contexts (`@<area>`).
- Keep `todo.txt` synchronized with code reality: when a deliverable is implemented and verified, mark it completed (`x YYYY-MM-DD ...`) immediately. Never leave verified work marked as pending or untracked.
+1 -1
View File
@@ -47,7 +47,7 @@ exclude = ["**/__pycache__", ".venv"]
asyncio_mode = "auto"
asyncio_default_fixture_loop_scope = "function"
testpaths = ["tests"]
pythonpath = ["src"]
pythonpath = ["src", "."]
[build-system]
requires = ["hatchling"]
+6 -33
View File
@@ -1,9 +1,8 @@
from fastapi import FastAPI, HTTPException, status
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from api.core.config import settings
from api.models.auth import DevTokenRequest, LoginResponse
from api.services.auth.service import AuthService
from api.routers import auth, sculptures, users
app = FastAPI(
title=settings.PROJECT_NAME,
@@ -20,7 +19,10 @@ app.add_middleware(
allow_headers=["*"],
)
auth_service = AuthService()
# Register routers
app.include_router(auth.router)
app.include_router(users.router)
app.include_router(sculptures.router)
@app.get("/health", tags=["System"])
@@ -34,32 +36,3 @@ async def health_check() -> dict[str, str]:
"version": settings.VERSION,
"env": settings.ENV,
}
@app.post(
"/auth/dev-token",
response_model=LoginResponse,
tags=["Authentication"],
summary="Development SSO Bypass Token Generation",
)
async def generate_dev_token(payload: DevTokenRequest) -> LoginResponse:
"""
Generate signed JWT for testing without contacting external OAuth providers.
Available only when ENV is not 'production'.
"""
if settings.ENV == "production":
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail="Development token generation disabled in production environment.",
)
# Use deterministic mock ID based on email
import hashlib
import uuid
deterministic_uuid = uuid.UUID(hashlib.md5(payload.email.encode("utf-8")).hexdigest())
return auth_service.create_access_token(
user_id=str(deterministic_uuid),
email=payload.email,
)
+8 -4
View File
@@ -47,10 +47,14 @@ class SculptureDetails(Sculpture):
Extended sculpture model containing cultural details, unlocked content, and audio resources.
"""
description: str = Field(..., description="Public cultural description of the sculpture.")
audio_url: HttpUrl = Field(..., description="Direct link to the audio guide resource.")
unlocked_content: str = Field(
..., description="Extended history/curation unlocked upon checking in."
description: str | None = Field(
default=None, description="Public cultural description of the sculpture."
)
audio_url: HttpUrl | None = Field(
default=None, description="Direct link to the audio guide resource."
)
unlocked_content: str | None = Field(
default=None, description="Extended history/curation unlocked upon checking in."
)
model_config = {
+3
View File
@@ -0,0 +1,3 @@
"""
API routers module.
"""
+95
View File
@@ -0,0 +1,95 @@
import hashlib
import uuid
from typing import Annotated
from fastapi import APIRouter, Depends, HTTPException, status
from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession
from api.core.config import settings
from api.database.session import get_db_session
from api.db_models.user import UserDB
from api.models.auth import DevTokenRequest, LoginRequest, LoginResponse
from api.routers.deps import auth_service
router = APIRouter(prefix="/auth", tags=["Authentication"])
@router.post(
"/login",
response_model=LoginResponse,
summary="Google SSO Authentication",
description="Exchange a Google OAuth ID token for a system-issued JWT access token.",
)
async def login_user(
payload: LoginRequest,
db: Annotated[AsyncSession, Depends(get_db_session)],
) -> LoginResponse:
try:
identity = await auth_service.authenticate_sso(payload.id_token)
except ValueError as err:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail=f"Invalid token provided: {err}",
) from err
# Provision or retrieve user
result = await db.execute(select(UserDB).where(UserDB.email == identity.email))
user = result.scalars().first()
if not user:
user_uuid = uuid.UUID(hashlib.md5(identity.email.encode("utf-8")).hexdigest())
user = UserDB(
id=user_uuid,
name=identity.name,
email=identity.email,
trust_score=0.5,
)
db.add(user)
await db.commit()
await db.refresh(user)
return auth_service.create_access_token(
user_id=str(user.id),
email=user.email,
)
@router.post(
"/dev-token",
response_model=LoginResponse,
summary="Development SSO Bypass Token Generation",
description="Generate signed JWT for testing without contacting external OAuth providers.",
)
async def generate_dev_token(
payload: DevTokenRequest,
db: Annotated[AsyncSession, Depends(get_db_session)],
) -> LoginResponse:
if settings.ENV == "production":
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail="Development token generation disabled in production environment.",
)
# Deterministic UUID based on email
user_uuid = uuid.UUID(hashlib.md5(payload.email.encode("utf-8")).hexdigest())
# Ensure user exists in database
result = await db.execute(select(UserDB).where(UserDB.email == payload.email))
user = result.scalars().first()
if not user:
user = UserDB(
id=user_uuid,
name=payload.name,
email=payload.email,
trust_score=0.5,
)
db.add(user)
await db.commit()
await db.refresh(user)
return auth_service.create_access_token(
user_id=str(user.id),
email=user.email,
)
+66
View File
@@ -0,0 +1,66 @@
import uuid
from typing import Annotated
import jwt
from fastapi import Depends, HTTPException, status
from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer
from sqlalchemy.ext.asyncio import AsyncSession
from api.database.session import get_db_session
from api.db_models.user import UserDB
from api.services.auth.service import AuthService
security = HTTPBearer(auto_error=False)
auth_service = AuthService()
async def get_current_user(
credentials: Annotated[HTTPAuthorizationCredentials | None, Depends(security)],
db: Annotated[AsyncSession, Depends(get_db_session)],
) -> UserDB:
"""
FastAPI dependency validating Bearer JWT token and returning authenticated UserDB entity.
"""
if credentials is None:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Authentication token missing or expired.",
headers={"WWW-Authenticate": "Bearer"},
)
token = credentials.credentials
try:
payload = auth_service.decode_access_token(token)
except jwt.PyJWTError as err:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Authentication token missing or expired.",
headers={"WWW-Authenticate": "Bearer"},
) from err
user_id_str = payload.get("sub")
if not user_id_str:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Invalid token payload: missing subject.",
headers={"WWW-Authenticate": "Bearer"},
)
try:
user_uuid = uuid.UUID(user_id_str)
except ValueError as err:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Invalid user ID format in token.",
headers={"WWW-Authenticate": "Bearer"},
) from err
user = await db.get(UserDB, user_uuid)
if not user:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="User associated with token not found.",
headers={"WWW-Authenticate": "Bearer"},
)
return user
+100
View File
@@ -0,0 +1,100 @@
import struct
from typing import Annotated
from uuid import UUID
from fastapi import APIRouter, Depends, HTTPException, status
from geoalchemy2.elements import WKBElement, WKTElement
from pydantic import HttpUrl, TypeAdapter
from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession
from api.database.session import get_db_session
from api.db_models.sculpture import SculptureDB
from api.models.sculpture import Sculpture, SculptureDetails, SculptureStatus
router = APIRouter(prefix="/sculptures", tags=["Sculptures"])
http_url_adapter = TypeAdapter(HttpUrl)
def extract_coordinates(location: object) -> tuple[float, float]:
"""
Extract (longitude, latitude) from PostGIS WKBElement, WKTElement, or string representation.
"""
if isinstance(location, WKTElement) or (isinstance(location, str) and "POINT" in location):
raw_str = str(location).strip()
coords_str = raw_str[raw_str.find("(") + 1 : raw_str.find(")")]
lon, lat = map(float, coords_str.split())
return lon, lat
if isinstance(location, WKBElement):
raw = location.data
b = bytes.fromhex(raw) if isinstance(raw, str) else raw
byteorder = "<" if b[0] == 1 else ">"
geom_type = struct.unpack(byteorder + "I", b[1:5])[0]
# Check for SRID flag (EWKB: 0x20000000)
offset = 9 if (geom_type & 0x20000000) else 5
lon, lat = struct.unpack(byteorder + "dd", b[offset : offset + 16])
return lon, lat
raise ValueError(f"Unsupported location geometry format: {type(location)}")
def to_sculpture_read(db_item: SculptureDB) -> Sculpture:
lon, lat = extract_coordinates(db_item.location)
return Sculpture(
id=db_item.id,
name=db_item.name,
artist=db_item.artist,
year=db_item.year,
latitude=lat,
longitude=lon,
status=SculptureStatus(db_item.status),
)
def to_sculpture_details(db_item: SculptureDB) -> SculptureDetails:
lon, lat = extract_coordinates(db_item.location)
audio_url = http_url_adapter.validate_python(db_item.audio_url) if db_item.audio_url else None
return SculptureDetails(
id=db_item.id,
name=db_item.name,
artist=db_item.artist,
year=db_item.year,
latitude=lat,
longitude=lon,
status=SculptureStatus(db_item.status),
description=db_item.description,
audio_url=audio_url,
unlocked_content=db_item.unlocked_content,
)
@router.get("", response_model=list[Sculpture], summary="List All Cat Sculptures")
async def list_sculptures(
db: Annotated[AsyncSession, Depends(get_db_session)],
) -> list[Sculpture]:
"""
Returns list of all sculptures with names, locations, and current status (Single Source of Truth).
"""
query = select(SculptureDB).order_by(SculptureDB.name)
result = await db.execute(query)
sculptures_db = result.scalars().all()
return [to_sculpture_read(item) for item in sculptures_db]
@router.get("/{id}", response_model=SculptureDetails, summary="Get Sculpture Details")
async def get_sculpture_by_id(
id: UUID,
db: Annotated[AsyncSession, Depends(get_db_session)],
) -> SculptureDetails:
"""
Detailed information about a sculpture, historical context, artist, and unlockable audio guides.
"""
sculpture = await db.get(SculptureDB, id)
if not sculpture:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail="Sculpture not found.",
)
return to_sculpture_details(sculpture)
+73
View File
@@ -0,0 +1,73 @@
from typing import Annotated
from fastapi import APIRouter, Depends
from pydantic import EmailStr, HttpUrl, TypeAdapter
from sqlalchemy import func, select
from sqlalchemy.ext.asyncio import AsyncSession
from api.database.session import get_db_session
from api.db_models.checkin import CheckInDB
from api.db_models.user import UserDB
from api.models.checkin import CheckInRecord
from api.models.user import User
from api.routers.deps import get_current_user
router = APIRouter(prefix="/users", tags=["Users"])
email_adapter = TypeAdapter(EmailStr)
http_url_adapter = TypeAdapter(HttpUrl)
@router.get(
"/me",
response_model=User,
summary="Retrieve Current User Profile",
description="Get details about the authenticated user, including their community trust score.",
)
async def get_my_profile(
current_user: Annotated[UserDB, Depends(get_current_user)],
db: Annotated[AsyncSession, Depends(get_db_session)],
) -> User:
# Calculate count of unique verified captures
count_stmt = select(func.count(CheckInDB.id)).where(CheckInDB.user_id == current_user.id)
result = await db.execute(count_stmt)
captured_count = result.scalar() or 0
return User(
id=current_user.id,
name=current_user.name,
email=email_adapter.validate_python(current_user.email),
trust_score=current_user.trust_score,
captured_count=captured_count,
)
@router.get(
"/me/collection",
response_model=list[CheckInRecord],
summary="Get User's Unlocked Sculptures",
description="Returns the user's progress tracking which cat sculptures they have successfully captured.",
)
async def get_my_collection(
current_user: Annotated[UserDB, Depends(get_current_user)],
db: Annotated[AsyncSession, Depends(get_db_session)],
) -> list[CheckInRecord]:
stmt = (
select(CheckInDB)
.where(CheckInDB.user_id == current_user.id)
.order_by(CheckInDB.captured_at.desc())
)
result = await db.execute(stmt)
check_ins = result.scalars().all()
return [
CheckInRecord(
sculpture_id=item.sculpture_id,
unlocked_at=item.captured_at,
checkin_photo_url=(
http_url_adapter.validate_python(item.photo_url) if item.photo_url else None
),
similarity_score=item.similarity_score,
)
for item in check_ins
]
+30
View File
@@ -2,9 +2,39 @@ from collections.abc import AsyncGenerator
import pytest
from httpx import ASGITransport, AsyncClient
from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker, create_async_engine
from sqlalchemy.pool import NullPool
from api.core.config import settings
from api.database.session import get_db_session
from api.main import app
# Engine with NullPool prevents cross-loop asyncpg connection clashes in pytest
test_engine = create_async_engine(
settings.DATABASE_URL,
poolclass=NullPool,
echo=False,
)
TestAsyncSessionLocal = async_sessionmaker(
bind=test_engine,
class_=AsyncSession,
expire_on_commit=False,
autocommit=False,
autoflush=False,
)
async def override_get_db_session() -> AsyncGenerator[AsyncSession, None]:
async with TestAsyncSessionLocal() as session:
try:
yield session
finally:
await session.close()
app.dependency_overrides[get_db_session] = override_get_db_session
@pytest.fixture
async def async_client() -> AsyncGenerator[AsyncClient, None]:
@@ -0,0 +1,104 @@
import uuid
import pytest
from httpx import AsyncClient
from api.core.config import settings
from api.database.seed import INITIAL_SCULPTURES
from api.db_models.checkin import CheckInDB
from tests.conftest import TestAsyncSessionLocal
@pytest.mark.asyncio
async def test_auth_login_success(async_client: AsyncClient):
payload = {"id_token": "valid-mock-token"}
response = await async_client.post("/auth/login", json=payload)
assert response.status_code == 200
data = response.json()
assert "access_token" in data
assert data["token_type"] == "Bearer"
assert data["expires_in"] > 0
@pytest.mark.asyncio
async def test_auth_login_invalid_token(async_client: AsyncClient):
payload = {"id_token": "invalid-token"}
response = await async_client.post("/auth/login", json=payload)
assert response.status_code == 401
assert "Invalid token provided" in response.json()["detail"]
@pytest.mark.asyncio
async def test_dev_token_production_disabled(async_client: AsyncClient):
original_env = settings.ENV
try:
settings.ENV = "production"
payload = {"email": "blocked@cali.gov.co", "name": "Blocked"}
response = await async_client.post("/auth/dev-token", json=payload)
assert response.status_code == 403
assert "disabled in production" in response.json()["detail"]
finally:
settings.ENV = original_env
@pytest.mark.asyncio
async def test_users_me_unauthorized(async_client: AsyncClient):
# Missing header
res1 = await async_client.get("/users/me")
assert res1.status_code == 401
# Invalid token
res2 = await async_client.get("/users/me", headers={"Authorization": "Bearer bad.token.here"})
assert res2.status_code == 401
@pytest.mark.asyncio
async def test_users_me_and_collection_flow(async_client: AsyncClient):
test_email = f"explorer.{uuid.uuid4().hex[:8]}@example.com"
token_resp = await async_client.post(
"/auth/dev-token", json={"email": test_email, "name": "Collection Explorer"}
)
assert token_resp.status_code == 200
token = token_resp.json()["access_token"]
headers = {"Authorization": f"Bearer {token}"}
# 1. Profile initially has 0 captures
profile_resp = await async_client.get("/users/me", headers=headers)
assert profile_resp.status_code == 200
profile_data = profile_resp.json()
assert profile_data["email"] == test_email
assert profile_data["name"] == "Collection Explorer"
assert profile_data["captured_count"] == 0
user_id = uuid.UUID(profile_data["id"])
# 2. Collection initially empty
col_resp = await async_client.get("/users/me/collection", headers=headers)
assert col_resp.status_code == 200
assert col_resp.json() == []
# 3. Add a check-in record directly via DB session
sculpture_id = INITIAL_SCULPTURES[0]["id"]
async with TestAsyncSessionLocal() as session:
check_in = CheckInDB(
user_id=user_id,
sculpture_id=sculpture_id,
photo_url="https://cdn.gatos.cali.gov.co/uploads/test.jpg",
similarity_score=0.92,
)
session.add(check_in)
await session.commit()
# 4. Collection now has 1 capture
col_resp2 = await async_client.get("/users/me/collection", headers=headers)
assert col_resp2.status_code == 200
items = col_resp2.json()
assert len(items) == 1
assert items[0]["sculpture_id"] == str(sculpture_id)
assert items[0]["similarity_score"] == 0.92
assert items[0]["checkin_photo_url"] == "https://cdn.gatos.cali.gov.co/uploads/test.jpg"
# 5. Profile captured_count reflects the new capture
profile_resp2 = await async_client.get("/users/me", headers=headers)
assert profile_resp2.status_code == 200
assert profile_resp2.json()["captured_count"] == 1
@@ -1,7 +1,7 @@
import pytest
from httpx import AsyncClient
from api.main import auth_service
from api.routers.deps import auth_service
@pytest.mark.asyncio
@@ -0,0 +1,66 @@
import uuid
import pytest
from httpx import AsyncClient
from api.database.seed import INITIAL_SCULPTURES
@pytest.mark.asyncio
async def test_list_sculptures_endpoint(async_client: AsyncClient):
response = await async_client.get("/sculptures")
assert response.status_code == 200
data = response.json()
assert isinstance(data, list)
assert len(data) >= 3
# Check that our seeded sculptures are present
names = {item["name"] for item in data}
for seeded in INITIAL_SCULPTURES:
assert seeded["name"] in names
# Verify schema fields and coordinates on each sculpture
for item in data:
assert "id" in item
assert "name" in item
assert "artist" in item
assert "year" in item
assert "latitude" in item
assert "longitude" in item
assert "status" in item
# Cali bounding box check
assert 3.30 <= item["latitude"] <= 3.60
assert -76.60 <= item["longitude"] <= -76.40
assert item["status"] in ("on-site", "moved", "missing")
@pytest.mark.asyncio
async def test_get_sculpture_by_id_success(async_client: AsyncClient):
target_id = str(INITIAL_SCULPTURES[0]["id"])
response = await async_client.get(f"/sculptures/{target_id}")
assert response.status_code == 200
data = response.json()
assert data["id"] == target_id
assert data["name"] == INITIAL_SCULPTURES[0]["name"]
assert data["artist"] == INITIAL_SCULPTURES[0]["artist"]
assert data["year"] == INITIAL_SCULPTURES[0]["year"]
assert data["description"] == INITIAL_SCULPTURES[0]["description"]
assert data["audio_url"] == INITIAL_SCULPTURES[0]["audio_url"]
assert data["unlocked_content"] == INITIAL_SCULPTURES[0]["unlocked_content"]
@pytest.mark.asyncio
async def test_get_sculpture_by_id_not_found(async_client: AsyncClient):
non_existent_id = uuid.uuid4()
response = await async_client.get(f"/sculptures/{non_existent_id}")
assert response.status_code == 404
data = response.json()
assert data["detail"] == "Sculpture not found."
@pytest.mark.asyncio
async def test_get_sculpture_by_id_invalid_uuid(async_client: AsyncClient):
response = await async_client.get("/sculptures/invalid-uuid-1234")
assert response.status_code == 422
+77
View File
@@ -0,0 +1,77 @@
import struct
import uuid
import pytest
from geoalchemy2.elements import WKBElement, WKTElement
from api.db_models.sculpture import SculptureDB
from api.routers.sculptures import (
extract_coordinates,
to_sculpture_details,
to_sculpture_read,
)
def test_extract_coordinates_from_wkt():
wkt = WKTElement("POINT(-76.533282 3.450143)", srid=4326)
lon, lat = extract_coordinates(wkt)
assert abs(lon - (-76.533282)) < 1e-6
assert abs(lat - 3.450143) < 1e-6
def test_extract_coordinates_from_wkb_ewkb():
# Build standard EWKB for POINT(-76.533282 3.450143) SRID 4326
# byteorder: 1 (little-endian), type: 0x20000001 (Point + EWKB), srid: 4326
packed = struct.pack("<bIIdd", 1, 0x20000001, 4326, -76.533282, 3.450143)
wkb = WKBElement(packed)
lon, lat = extract_coordinates(wkb)
assert abs(lon - (-76.533282)) < 1e-6
assert abs(lat - 3.450143) < 1e-6
def test_extract_coordinates_unsupported_type():
with pytest.raises(ValueError, match="Unsupported location geometry format"):
extract_coordinates(12345) # type: ignore[arg-type]
def test_to_sculpture_read_mapping():
point = WKTElement("POINT(-76.5329 3.4508)", srid=4326)
db_item = SculptureDB(
id=uuid.uuid4(),
name="La Gata Ilustrada",
artist="Lucy Tejada",
year=2006,
description="A wonderful sculpture",
audio_url="https://cdn.gatos.cali.gov.co/audio/test.mp3",
unlocked_content="Secret lore",
status="on-site",
location=point,
embedding=[0.0] * 1280,
)
read_model = to_sculpture_read(db_item)
assert read_model.name == "La Gata Ilustrada"
assert read_model.year == 2006
assert abs(read_model.longitude - (-76.5329)) < 1e-6
assert abs(read_model.latitude - 3.4508) < 1e-6
def test_to_sculpture_details_mapping():
point = WKTElement("POINT(-76.5326 3.4516)", srid=4326)
db_item = SculptureDB(
id=uuid.uuid4(),
name="La Gata Ceremonial",
artist="José Horacio Martínez",
year=2006,
description="Pre-Columbian motifs",
audio_url="https://cdn.gatos.cali.gov.co/audio/ceremonial.mp3",
unlocked_content="Gold lore",
status="moved",
location=point,
embedding=[0.0] * 1280,
)
details_model = to_sculpture_details(db_item)
assert details_model.name == "La Gata Ceremonial"
assert details_model.status.value == "moved"
assert details_model.description == "Pre-Columbian motifs"
assert str(details_model.audio_url) == "https://cdn.gatos.cali.gov.co/audio/ceremonial.mp3"
assert details_model.unlocked_content == "Gold lore"
Generated
+3 -3
View File
@@ -92,11 +92,11 @@ wheels = [
[[package]]
name = "certifi"
version = "2026.7.22"
version = "2026.10.23"
source = { registry = "https://pypi.org/simple" }
sdist = { url = "https://files.pythonhosted.org/packages/a3/c2/24167ea9858356b47a87a50d39908bfdb72ceeefe0041586e704e5376b3a/certifi-2026.7.22.tar.gz", hash = "sha256:741e2c3b351ddf169a738da9f2c048608ff7f2c5cc02f1ebc6b118bb090d5d55", size = 138112, upload-time = "2026-07-22T03:35:12.644Z" }
sdist = { url = "https://files.pythonhosted.org/packages/fd/11/b524cbd9bbdaca58608e4cf4053fd463417549e1959fa8d3aa18319f9555/certifi-2026.10.23.tar.gz", hash = "sha256:a9895e6e2758b371e0545e321a3a8fd1fcfd9829ada8824a936dfb16aaaf36cd", size = 136225, upload-time = "2026-10-23T11:36:16.478Z" }
wheels = [
{ url = "https://files.pythonhosted.org/packages/0b/a7/71ac2cff56fec219ed242bb11b8efb69fcc4bec75db06fb7bfe35de520e6/certifi-2026.7.22-py3-none-any.whl", hash = "sha256:62f22742b58a1a33014a2b6b706588a8d7e2a88ae7bd1a6ebe8c992928483775", size = 136983, upload-time = "2026-07-22T03:35:11.276Z" },
{ url = "https://files.pythonhosted.org/packages/32/d1/a3652fe2c19134d0d15922177821d863cbd7e842d53a21bbe7e8e3a1b5ac/certifi-2026.10.23-py3-none-any.whl", hash = "sha256:e9b54de76e530bb6cf0ccd036787103acb58fd42ba930ea8bf948ddbaa2f61d1", size = 135082, upload-time = "2026-10-23T11:36:14.763Z" },
]
[[package]]
+11 -3
View File
@@ -49,10 +49,16 @@ Validates "Check-ins" using client-side edge embeddings (MobileNetV2 1280-dimens
### 4. Interaction & Collection Service
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 (Cascade Triage)
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.
- Accepts coordinates, observed status, verification photo, and optional free-form commentary.
- **Cascade Triage Architecture**:
1. **Tier 1 (Deterministic Math)**: Rejects physical impossibilities via spatio-temporal velocity checks ($v \le 120\text{ km/h}$).
2. **Tier 2 (System One Decision Engine - Jev)**: Free-form commentary and report metadata are processed via a pluggable `TriageProvider` adapter (backed by TypeSafe AI's non-autoregressive **Jev** model):
- `is_spam` (`noul`): Fast boolean probability filter to eliminate noise before human review.
- `category` (`choice`): Categorizes reports into municipal work, temporary festival relocation, vandalism, theft, or empty pedestal.
- `credibility` (`score`): Calibrated plausibility scoring used to scale reporter vote weight.
3. **Tier 3 (Spatial Clustering & Consensus)**: Groups verified submissions into spatial clusters ($\le 20\text{ m}$ radius) over a 48-hour window.
### 6. Location Tracker Service (The Oracle) & Hybrid Consensus Engine
Computes the single source of truth (SSOT) location and status of each sculpture:
@@ -67,4 +73,6 @@ Computes the single source of truth (SSOT) location and status of each sculpture
* **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.
* **Cascade Triage & Non-Autoregressive Decision Engine (Jev):** Free-form crowdsourced reports and device fallback queues are pre-triaged using TypeSafe AI's Jev model via a pluggable `TriageProvider` adapter. By choosing a non-autoregressive decision model over generative LLMs, the system achieves sub-200ms latency, calibrated probabilities, and guaranteed typed responses without heavy server-side GPU/RAM requirements. Code-level velocity math and client-side MobileNetV2 feature embeddings remain untouched.
+2 -2
View File
@@ -45,8 +45,8 @@ graph TD
### ADR-004: Asynchronous Moderation Queue for Device Failures
* **Context:** Some older or budget smartphones may throw exceptions when attempting WebAssembly compilation or WebGL initialization, preventing local vector generation.
* **Decision:** If the PWA catches an ONNX initialization error, it degrades gracefully by falling back to an **Asynchronous Moderation Queue**. It uploads the raw GPS coordinates and the compressed photo to the `/reports` endpoint. The check-in is set to "Pending" until an admin manually approves it.
* **Rationale:** Protects the server from loading resource-heavy inference engines (like PyTorch or full onnxruntime) on the backend, maintaining strict memory limits while still ensuring all users can complete check-ins.
* **Decision:** If the PWA catches an ONNX initialization error, it degrades gracefully by falling back to an **Asynchronous Moderation Queue**. It uploads the raw GPS coordinates and the compressed photo to the `/reports` endpoint. The check-in is set to "Pending" until an admin manually approves it or the pluggable Jev triage engine verifies the report's credibility.
* **Rationale:** Protects the server from loading resource-heavy inference engines (like PyTorch or full onnxruntime) on the backend, maintaining strict memory limits while still ensuring all users can complete check-ins. Combined with non-autoregressive decision models (Jev), fallback tickets can be pre-scored for credibility without human bottlenecking.
### ADR-005: Progressive Dataset Rollout via Admin Seeding Tool
* **Context:** Collecting, photographing, and seeding reference vectors for all 38 cats on day one is a bottleneck that delays MVP deployment.
+17
View File
@@ -0,0 +1,17 @@
x 2026-10-13 (A) Containerize PostGIS 17 + pgvector in docker-compose.yml with healthcheck +infra @db
x 2026-10-13 (A) Implement async SQLAlchemy 2.0 engine and session factory in api/database.py +api @db
x 2026-10-13 (A) Define Sculpture, CheckIn, and User ORM models with GeoAlchemy2 and pgvector in api/models.py +api @db
x 2026-10-13 (A) Initialize Alembic and create initial schema migration in api/alembic/ +api @db
x 2026-10-13 (A) Create seed script and populate 3 historical cat sculptures in api/scripts/seed_sculptures.py +api @db
x 2026-10-13 (A) Establish automated test suite with pytest-asyncio and SQLite/Postgres harness in api/tests/ +test @api
x 2026-10-13 (A) Draft Architectural Decision Record for Jev Cascade Triage in docs/adr/001-jev-cascade-triage.md +docs @arch
x 2026-10-15 (A) Implement Pydantic v2 domain schemas matching openapi_unified.yaml in api/models/ +api @backend
x 2026-10-15 (A) Implement IdentityProvider protocol, auth router, and users profile router in api/routers/ +api @auth
x 2026-10-13 (A) Implement Sculptures read router with spatial coordinate serialization in api/routers/sculptures.py +api @backend
(B) Implement Check-In verification engine with spatial distance threshold and cosine similarity threshold in api/services/checkin.py +api @backend
(B) Implement Check-In router with idempotency and streak tracking in api/routers/checkins.py +api @backend
(B) Implement Jev lightweight triage adapter protocol and mock fallback in api/services/triage.py +api @ai
(C) Implement consensus engine for multi-user spatial cluster voting in api/services/consensus.py +api @backend
(C) Implement public catalog and leaderboard endpoints in api/routers/catalog.py +api @backend
(C) Write comprehensive integration tests for Check-In flow, edge cases, and spatial rejection in api/tests/test_checkins.py +test @api
(D) Consult Anne Droid to review OpenAPI schemas against PWA client camera and canvas contract +pwa @frontend