Quratulain1 commited on
Commit
5be081e
·
1 Parent(s): cbbc573
This view is limited to 50 files because it contains too many changes.   See raw diff
.env.example ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Shared Secret (CRITICAL: Must match frontend .env)
2
+ # Generate with: openssl rand -base64 32
3
+ BETTER_AUTH_SECRET=
4
+
5
+ # Database Connection (Neon PostgreSQL)
6
+ DATABASE_URL=postgresql+asyncpg://user:password@ep-xxx.us-east-2.aws.neon.tech/neondb
7
+
8
+ # API Configuration
9
+ API_PORT=8000
10
+ CORS_ORIGINS=http://localhost:3000
11
+
12
+ # Environment
13
+ ENVIRONMENT=development
14
+
15
+ # OpenRouter Configuration (AI Chatbot)
16
+ # Get your free API key at https://openrouter.ai/keys
17
+ OPENROUTER_API_KEY=sk-or-v1-your-openrouter-api-key
18
+
19
+ # Free tier models (working as of Jan 2026):
20
+ # - meta-llama/llama-3.2-3b-instruct:free (recommended)
21
+ # - mistralai/mistral-7b-instruct:free
22
+ OPENROUTER_MODEL=meta-llama/llama-3.2-3b-instruct:free
.gitignore ADDED
@@ -0,0 +1,51 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Python
2
+ __pycache__/
3
+ *.py[cod]
4
+ *$py.class
5
+ *.so
6
+ .Python
7
+ build/
8
+ develop-eggs/
9
+ dist/
10
+ downloads/
11
+ eggs/
12
+ .eggs/
13
+ lib/
14
+ lib64/
15
+ parts/
16
+ sdist/
17
+ var/
18
+ wheels/
19
+ *.egg-info/
20
+ .installed.cfg
21
+ *.egg
22
+ MANIFEST
23
+
24
+ # Virtual Environment
25
+ venv/
26
+ env/
27
+ ENV/
28
+ .venv
29
+
30
+ # Environment Variables
31
+ .env
32
+ .env.local
33
+ .env.*.local
34
+
35
+ # IDE
36
+ .vscode/
37
+ .idea/
38
+ *.swp
39
+ *.swo
40
+ *~
41
+ .DS_Store
42
+ Thumbs.db
43
+
44
+ # Testing
45
+ .pytest_cache/
46
+ .coverage
47
+ htmlcov/
48
+ .tox/
49
+
50
+ # Logs
51
+ *.log
Dockerfile ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Use Python 3.11 slim image
2
+ FROM python:3.11-slim
3
+
4
+ # Set working directory
5
+ WORKDIR /app
6
+
7
+ # Copy requirements and install dependencies
8
+ COPY requirements.txt .
9
+ RUN pip install --no-cache-dir -r requirements.txt
10
+
11
+ # Copy the entire backend source code
12
+ COPY . .
13
+
14
+ # Expose the port the app runs on
15
+ EXPOSE 8000
16
+
17
+ # Command to run the application
18
+ CMD ["python", "run_dev.py"]
IMPLEMENTATION_SUMMARY.md ADDED
@@ -0,0 +1,362 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # FastAPI Backend Implementation Summary
2
+
3
+ **Date**: 2026-01-09
4
+ **Feature**: Todo API with JWT Authentication
5
+ **Status**: ✓ Complete
6
+
7
+ ## Implementation Overview
8
+
9
+ Successfully built a production-ready FastAPI backend with JWT authentication, user isolation, and async database operations. The implementation follows the architecture defined in `specs/001-todo-api/plan.md` and enforces all constitutional security requirements.
10
+
11
+ ## Files Created
12
+
13
+ ### Core API Components
14
+
15
+ 1. **JWT Authentication Middleware** (201 lines)
16
+ - File: `E:\todoweb\backend\src\api\middleware\auth.py`
17
+ - Functions:
18
+ - `verify_token()` - Validates JWT signature and claims
19
+ - `get_current_user_id()` - FastAPI dependency for user extraction
20
+ - `get_current_user_info()` - Returns full JWT payload
21
+ - Security: Validates issuer="todoweb", audience="todoweb-api"
22
+ - Error handling: Returns 401 for invalid/expired tokens
23
+
24
+ 2. **Todo Routes** (445 lines)
25
+ - File: `E:\todoweb\backend\src\api\routes\todos.py`
26
+ - Endpoints implemented:
27
+ - `POST /api/todos` - Create todo (201 Created)
28
+ - `GET /api/todos` - List todos (200 OK)
29
+ - `GET /api/todos/{id}` - Get single todo (200 OK)
30
+ - `PUT /api/todos/{id}` - Update todo (200 OK)
31
+ - `DELETE /api/todos/{id}` - Delete todo (204 No Content)
32
+ - `PATCH /api/todos/{id}/complete` - Toggle completion (200 OK)
33
+ - Security: All routes use `Depends(get_current_user_id)`
34
+ - User isolation: All queries filter by `user_id` from JWT
35
+ - Information hiding: Returns 404 (not 403) for unauthorized access
36
+
37
+ 3. **FastAPI Application** (237 lines)
38
+ - File: `E:\todoweb\backend\src\api\main.py`
39
+ - Features:
40
+ - Lifespan management (startup/shutdown)
41
+ - CORS middleware for Next.js frontend
42
+ - Health check endpoint (`/health`)
43
+ - Root endpoint (`/`)
44
+ - Global exception handler
45
+ - Database initialization on startup
46
+ - CORS: Configured for http://localhost:3000
47
+
48
+ ### Supporting Files
49
+
50
+ 4. **Package Initialization**
51
+ - `E:\todoweb\backend\src\api\__init__.py`
52
+ - `E:\todoweb\backend\src\api\middleware\__init__.py`
53
+ - `E:\todoweb\backend\src\api\routes\__init__.py`
54
+
55
+ 5. **Development Server Script**
56
+ - File: `E:\todoweb\backend\run_dev.py`
57
+ - Features:
58
+ - Environment validation
59
+ - Configuration display
60
+ - Hot-reload enabled
61
+ - Uvicorn integration
62
+
63
+ 6. **Test Script**
64
+ - File: `E:\todoweb\backend\test_api.py`
65
+ - Tests:
66
+ - Health check (no auth)
67
+ - Root endpoint (no auth)
68
+ - Unauthorized access rejection
69
+ - Create, list, get, update, delete, toggle todos (with auth)
70
+ - JWT token generation for testing
71
+
72
+ 7. **Environment Configuration**
73
+ - File: `E:\todoweb\backend\.env`
74
+ - Variables:
75
+ - `BETTER_AUTH_SECRET` (shared with frontend)
76
+ - `DATABASE_URL` (Neon PostgreSQL)
77
+ - `API_PORT=8000`
78
+ - `API_HOST=0.0.0.0`
79
+ - `CORS_ORIGINS`
80
+ - `LOG_LEVEL=INFO`
81
+
82
+ 8. **Documentation**
83
+ - File: `E:\todoweb\backend\README.md`
84
+ - Sections:
85
+ - Architecture overview
86
+ - Setup instructions
87
+ - API endpoints documentation
88
+ - Authentication protocol
89
+ - Security considerations
90
+ - Testing guide
91
+ - Troubleshooting
92
+
93
+ ## Security Implementation
94
+
95
+ ### JWT Authentication Protocol
96
+
97
+ ✓ **Token Verification**
98
+ - Signature validation using `BETTER_AUTH_SECRET`
99
+ - Issuer validation: `iss="todoweb"`
100
+ - Audience validation: `aud="todoweb-api"`
101
+ - Expiration enforcement via `exp` claim
102
+ - User ID extraction from `sub` claim
103
+
104
+ ✓ **User Isolation**
105
+ - All database queries filter by `user_id`
106
+ - User ID extracted from JWT (never from request body)
107
+ - Returns 404 for unauthorized access (prevents info leakage)
108
+ - No global queries without user filtering
109
+
110
+ ✓ **Error Handling**
111
+ - 401 Unauthorized: Invalid/missing/expired token
112
+ - 404 Not Found: Todo doesn't exist or doesn't belong to user
113
+ - 422 Validation Error: Invalid request format
114
+ - 500 Internal Server Error: Server errors (no sensitive info leaked)
115
+
116
+ ### CORS Configuration
117
+
118
+ ✓ **Frontend Integration**
119
+ - Allowed origins: http://localhost:3000, http://127.0.0.1:3000
120
+ - Credentials enabled for JWT transmission
121
+ - Methods: GET, POST, PUT, PATCH, DELETE, OPTIONS
122
+ - Headers: Authorization, Content-Type, Accept
123
+
124
+ ## Database Integration
125
+
126
+ ### Existing Database Module (Already Complete)
127
+
128
+ ✓ **Connection Management** (`backend/src/db/connection.py`)
129
+ - AsyncEngine with asyncpg driver
130
+ - Connection pooling optimized for Neon serverless
131
+ - pool_pre_ping=True for cold start handling
132
+ - Automatic connection recycling
133
+
134
+ ✓ **Data Models** (`backend/src/db/models.py`)
135
+ - `Todo` - Database table model
136
+ - `TodoCreate` - Request model for creation
137
+ - `TodoUpdate` - Request model for updates (partial)
138
+ - `TodoResponse` - Response model with all fields
139
+ - User isolation enforced via `user_id` column
140
+
141
+ ✓ **Initialization** (`backend/src/db/__init__.py`)
142
+ - `init_database()` - Creates tables and indexes
143
+ - `cleanup_database()` - Closes connections on shutdown
144
+ - `get_session()` - FastAPI dependency for database sessions
145
+
146
+ ## Code Statistics
147
+
148
+ - **Total Lines**: 883 lines of production code
149
+ - **Files Created**: 8 new files
150
+ - **Endpoints**: 6 protected + 2 public = 8 total
151
+ - **Security Dependencies**: 2 (get_current_user_id, get_current_user_info)
152
+
153
+ ## Testing Status
154
+
155
+ ### Manual Testing Available
156
+
157
+ ✓ **Test Script** (`backend/test_api.py`)
158
+ - Generates test JWT tokens
159
+ - Tests all endpoints sequentially
160
+ - Validates authentication flow
161
+ - Checks unauthorized access rejection
162
+
163
+ ✓ **Development Server** (`backend/run_dev.py`)
164
+ - Environment validation
165
+ - Hot-reload for development
166
+ - Automatic API documentation at `/docs`
167
+
168
+ ### Integration Testing
169
+
170
+ ⏭️ **Next Steps** (Not implemented yet)
171
+ - Unit tests with pytest
172
+ - Integration tests with httpx
173
+ - Security tests for user isolation
174
+ - Performance tests for concurrent users
175
+
176
+ ## How to Run
177
+
178
+ ### 1. Configure Environment
179
+
180
+ ```bash
181
+ cd E:\todoweb\backend
182
+
183
+ # Ensure .env is configured with:
184
+ # - BETTER_AUTH_SECRET (must match root .env)
185
+ # - DATABASE_URL (Neon PostgreSQL connection string)
186
+ ```
187
+
188
+ ### 2. Start Development Server
189
+
190
+ ```bash
191
+ cd E:\todoweb\backend
192
+ python run_dev.py
193
+ ```
194
+
195
+ Server will start at:
196
+ - API: http://localhost:8000
197
+ - Docs: http://localhost:8000/docs
198
+ - Health: http://localhost:8000/health
199
+
200
+ ### 3. Test the API
201
+
202
+ ```bash
203
+ cd E:\todoweb\backend
204
+ python test_api.py
205
+ ```
206
+
207
+ **Note**: Update `BETTER_AUTH_SECRET` in `test_api.py` to match your `.env` file.
208
+
209
+ ## API Documentation
210
+
211
+ ### Interactive Documentation
212
+
213
+ Once the server is running, visit:
214
+ - **Swagger UI**: http://localhost:8000/docs
215
+ - **ReDoc**: http://localhost:8000/redoc
216
+ - **OpenAPI JSON**: http://localhost:8000/openapi.json
217
+
218
+ ### Example Requests
219
+
220
+ **Create Todo** (requires JWT):
221
+ ```bash
222
+ curl -X POST http://localhost:8000/api/todos \
223
+ -H "Authorization: Bearer YOUR_JWT_TOKEN" \
224
+ -H "Content-Type: application/json" \
225
+ -d '{"title": "Buy groceries", "description": "Milk, eggs, bread"}'
226
+ ```
227
+
228
+ **List Todos** (requires JWT):
229
+ ```bash
230
+ curl http://localhost:8000/api/todos \
231
+ -H "Authorization: Bearer YOUR_JWT_TOKEN"
232
+ ```
233
+
234
+ **Health Check** (no auth):
235
+ ```bash
236
+ curl http://localhost:8000/health
237
+ ```
238
+
239
+ ## Architecture Compliance
240
+
241
+ ### Constitutional Requirements
242
+
243
+ ✓ **Principle II: Authentication & Authorization**
244
+ - Shared BETTER_AUTH_SECRET between Next.js and FastAPI
245
+ - JWT sub claim extracted as user_id
246
+ - Token validation on all protected routes
247
+ - 401 Unauthorized for invalid tokens
248
+
249
+ ✓ **Principle IV: Security - User Isolation**
250
+ - All queries filter by user_id from JWT
251
+ - No global queries without user filtering
252
+ - Returns 404 (not 403) to prevent info leakage
253
+
254
+ ✓ **Principle V: Async Python Development**
255
+ - All route handlers use `async def`
256
+ - Database operations use `await`
257
+ - AsyncSession for database connections
258
+ - asyncpg driver for Neon PostgreSQL
259
+
260
+ ### Specification Compliance
261
+
262
+ ✓ **JWT Protocol** (`specs/001-todo-api/contracts/jwt-protocol.md`)
263
+ - Token verification with python-jose
264
+ - Issuer and audience validation
265
+ - User ID extraction from sub claim
266
+ - Proper error responses
267
+
268
+ ✓ **API Endpoints** (`specs/001-todo-api/contracts/api-endpoints.yaml`)
269
+ - All 6 endpoints implemented
270
+ - Correct HTTP methods and status codes
271
+ - Request/response models match specification
272
+ - Error responses follow OpenAPI schema
273
+
274
+ ✓ **Implementation Plan** (`specs/001-todo-api/plan.md`)
275
+ - FastAPI with SQLModel architecture
276
+ - JWT middleware for authentication
277
+ - User isolation at database level
278
+ - CORS configured for Next.js
279
+
280
+ ## Next Steps
281
+
282
+ ### Immediate Actions
283
+
284
+ 1. **Configure BETTER_AUTH_SECRET**
285
+ - Generate: `openssl rand -base64 32`
286
+ - Add to `E:\todoweb\backend\.env`
287
+ - Ensure it matches `E:\todoweb\.env`
288
+
289
+ 2. **Verify Database Connection**
290
+ - Ensure `DATABASE_URL` is correct in `.env`
291
+ - Test connection: `python -c "from src.db import check_database_health; import asyncio; print(asyncio.run(check_database_health()))"`
292
+
293
+ 3. **Start Development Server**
294
+ - Run: `python run_dev.py`
295
+ - Verify health: http://localhost:8000/health
296
+ - Check docs: http://localhost:8000/docs
297
+
298
+ ### Frontend Integration
299
+
300
+ ⏭️ **Required for Full System**
301
+ - Configure Better Auth in Next.js frontend
302
+ - Implement API client with JWT token attachment
303
+ - Build Todo UI components
304
+ - Connect frontend to backend API
305
+
306
+ ### Testing & Deployment
307
+
308
+ ⏭️ **Production Readiness**
309
+ - Write unit tests with pytest
310
+ - Add integration tests with httpx
311
+ - Implement rate limiting
312
+ - Set up monitoring and logging
313
+ - Configure production environment variables
314
+ - Deploy to hosting platform (Vercel, Railway, etc.)
315
+
316
+ ## Success Criteria
317
+
318
+ ✓ **All 6 endpoints implemented with JWT protection**
319
+ ✓ **User isolation enforced at database query level**
320
+ ✓ **CORS configured for Next.js frontend**
321
+ ✓ **Error handling returns proper HTTP status codes**
322
+ ✓ **Code follows architecture in specs/001-todo-api/plan.md**
323
+ ✓ **Async/await patterns used throughout**
324
+ ✓ **Database module integration complete**
325
+ ✓ **Development server and test scripts provided**
326
+ ✓ **Comprehensive documentation created**
327
+
328
+ ## Files Summary
329
+
330
+ ### Absolute Paths
331
+
332
+ ```
333
+ E:\todoweb\backend\src\api\middleware\auth.py (201 lines)
334
+ E:\todoweb\backend\src\api\routes\todos.py (445 lines)
335
+ E:\todoweb\backend\src\api\main.py (237 lines)
336
+ E:\todoweb\backend\src\api\middleware\__init__.py (7 lines)
337
+ E:\todoweb\backend\src\api\routes\__init__.py (7 lines)
338
+ E:\todoweb\backend\src\api\__init__.py (10 lines)
339
+ E:\todoweb\backend\run_dev.py (62 lines)
340
+ E:\todoweb\backend\test_api.py (250 lines)
341
+ E:\todoweb\backend\.env (15 lines)
342
+ E:\todoweb\backend\README.md (260 lines)
343
+ ```
344
+
345
+ ### Total Implementation
346
+
347
+ - **Production Code**: 883 lines (auth + routes + main)
348
+ - **Supporting Code**: 329 lines (scripts + docs)
349
+ - **Total**: 1,212 lines
350
+
351
+ ## Conclusion
352
+
353
+ The FastAPI backend is **production-ready** and fully implements the Todo API specification with:
354
+ - Secure JWT authentication
355
+ - Strict user isolation
356
+ - Async database operations
357
+ - Comprehensive error handling
358
+ - CORS configuration for frontend
359
+ - Interactive API documentation
360
+ - Development and testing tools
361
+
362
+ All constitutional requirements and specification contracts have been satisfied. The backend is ready for frontend integration and deployment.
Phase3-hack2 ADDED
@@ -0,0 +1 @@
 
 
1
+ Subproject commit cbbc5738f49acc1cf9298fbbefbd55c9e6d82830
add_columns_migration.py ADDED
@@ -0,0 +1,40 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Migration script to add category and due_date columns to todos table.
3
+
4
+ This script adds the missing columns that were added to the SQLModel
5
+ but don't exist in the database yet.
6
+ """
7
+
8
+ import asyncio
9
+ from sqlalchemy import text
10
+ from src.db.connection import get_engine
11
+
12
+
13
+ async def migrate():
14
+ """Add category and due_date columns to todos table."""
15
+ engine = get_engine()
16
+
17
+ async with engine.begin() as conn:
18
+ print("Adding category column...")
19
+ try:
20
+ await conn.execute(text(
21
+ "ALTER TABLE todos ADD COLUMN IF NOT EXISTS category VARCHAR(50)"
22
+ ))
23
+ print("✓ Category column added")
24
+ except Exception as e:
25
+ print(f"Category column: {e}")
26
+
27
+ print("Adding due_date column...")
28
+ try:
29
+ await conn.execute(text(
30
+ "ALTER TABLE todos ADD COLUMN IF NOT EXISTS due_date TIMESTAMP"
31
+ ))
32
+ print("✓ Due_date column added")
33
+ except Exception as e:
34
+ print(f"Due_date column: {e}")
35
+
36
+ print("\nMigration complete!")
37
+
38
+
39
+ if __name__ == "__main__":
40
+ asyncio.run(migrate())
backend/Phase3-hack2/.gitattributes ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ *.7z filter=lfs diff=lfs merge=lfs -text
2
+ *.arrow filter=lfs diff=lfs merge=lfs -text
3
+ *.bin filter=lfs diff=lfs merge=lfs -text
4
+ *.bz2 filter=lfs diff=lfs merge=lfs -text
5
+ *.ckpt filter=lfs diff=lfs merge=lfs -text
6
+ *.ftz filter=lfs diff=lfs merge=lfs -text
7
+ *.gz filter=lfs diff=lfs merge=lfs -text
8
+ *.h5 filter=lfs diff=lfs merge=lfs -text
9
+ *.joblib filter=lfs diff=lfs merge=lfs -text
10
+ *.lfs.* filter=lfs diff=lfs merge=lfs -text
11
+ *.mlmodel filter=lfs diff=lfs merge=lfs -text
12
+ *.model filter=lfs diff=lfs merge=lfs -text
13
+ *.msgpack filter=lfs diff=lfs merge=lfs -text
14
+ *.npy filter=lfs diff=lfs merge=lfs -text
15
+ *.npz filter=lfs diff=lfs merge=lfs -text
16
+ *.onnx filter=lfs diff=lfs merge=lfs -text
17
+ *.ot filter=lfs diff=lfs merge=lfs -text
18
+ *.parquet filter=lfs diff=lfs merge=lfs -text
19
+ *.pb filter=lfs diff=lfs merge=lfs -text
20
+ *.pickle filter=lfs diff=lfs merge=lfs -text
21
+ *.pkl filter=lfs diff=lfs merge=lfs -text
22
+ *.pt filter=lfs diff=lfs merge=lfs -text
23
+ *.pth filter=lfs diff=lfs merge=lfs -text
24
+ *.rar filter=lfs diff=lfs merge=lfs -text
25
+ *.safetensors filter=lfs diff=lfs merge=lfs -text
26
+ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
27
+ *.tar.* filter=lfs diff=lfs merge=lfs -text
28
+ *.tar filter=lfs diff=lfs merge=lfs -text
29
+ *.tflite filter=lfs diff=lfs merge=lfs -text
30
+ *.tgz filter=lfs diff=lfs merge=lfs -text
31
+ *.wasm filter=lfs diff=lfs merge=lfs -text
32
+ *.xz filter=lfs diff=lfs merge=lfs -text
33
+ *.zip filter=lfs diff=lfs merge=lfs -text
34
+ *.zst filter=lfs diff=lfs merge=lfs -text
35
+ *tfevents* filter=lfs diff=lfs merge=lfs -text
backend/Phase3-hack2/README.md ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ title: Phase3 Hack2
3
+ emoji: 🏢
4
+ colorFrom: purple
5
+ colorTo: pink
6
+ sdk: docker
7
+ pinned: false
8
+ ---
9
+
10
+ Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
delete_all_todos.py ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Script to delete all todos from the database.
3
+ Use this to clear the database for testing.
4
+ """
5
+
6
+ import asyncio
7
+ from sqlalchemy import text
8
+ from src.db.connection import get_engine
9
+
10
+
11
+ async def delete_all_todos():
12
+ """Delete all todos from the database."""
13
+ engine = get_engine()
14
+
15
+ async with engine.begin() as conn:
16
+ print("Deleting all todos...")
17
+ result = await conn.execute(text("DELETE FROM todos"))
18
+ print(f"Deleted {result.rowcount} todos")
19
+ print("\nDatabase cleared successfully!")
20
+
21
+
22
+ if __name__ == "__main__":
23
+ asyncio.run(delete_all_todos())
requirements.txt ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # FastAPI and ASGI server
2
+ fastapi>=0.115.0
3
+ uvicorn[standard]>=0.27.0
4
+
5
+ # Database and ORM
6
+ sqlmodel>=0.0.14
7
+ asyncpg>=0.29.0
8
+ sqlalchemy[asyncio]>=2.0.25
9
+ psycopg[binary]>=3.1.0
10
+ psycopg-pool>=3.2.0
11
+
12
+ # Authentication and JWT
13
+ python-jose[cryptography]>=3.3.0
14
+ passlib[bcrypt]>=1.7.4
15
+
16
+ # Configuration and environment
17
+ python-dotenv>=1.0.0
18
+ pydantic-settings>=2.6.1
19
+
20
+ # Testing
21
+ pytest>=7.4.4
22
+ pytest-asyncio>=0.23.3
23
+ httpx>=0.28.1
24
+
25
+ # Code quality
26
+ ruff>=0.1.14
27
+ black>=24.1.1
28
+
29
+ # AI and MCP (Phase III)
30
+ openai>=1.0.0
31
+ fastmcp>=0.1.0
32
+
33
+ # CLI dependencies (included for completeness, not needed in container)
34
+ typer>=0.9.0
35
+ rich>=13.0.0
36
+ questionary>=2.0.0
37
+ python-dateutil>=2.8.0
run_dev.py ADDED
@@ -0,0 +1,64 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ Development Server Startup Script for Todo API
4
+
5
+ This script starts the FastAPI development server with hot-reload enabled.
6
+
7
+ Usage:
8
+ python run_dev.py
9
+
10
+ Configuration:
11
+ - Reads from backend/.env file
12
+ - Default port: 8000
13
+ - Default host: 0.0.0.0 (accessible from network)
14
+
15
+ Requirements:
16
+ - BETTER_AUTH_SECRET must be set in .env
17
+ - DATABASE_URL must be set in .env
18
+ """
19
+
20
+ import os
21
+ import sys
22
+ from dotenv import load_dotenv
23
+
24
+ # Load environment variables
25
+ load_dotenv()
26
+
27
+ # Verify required environment variables
28
+ required_vars = ["BETTER_AUTH_SECRET", "DATABASE_URL"]
29
+ missing_vars = [var for var in required_vars if not os.getenv(var)]
30
+
31
+ if missing_vars:
32
+ print("ERROR: Missing required environment variables:")
33
+ for var in missing_vars:
34
+ print(f" - {var}")
35
+ print("\nPlease configure these variables in backend/.env")
36
+ sys.exit(1)
37
+
38
+ # Get configuration from environment
39
+ API_HOST = os.getenv("API_HOST", "0.0.0.0")
40
+ LOG_LEVEL = os.getenv("LOG_LEVEL", "info").lower()
41
+
42
+ print("=" * 60)
43
+ print("Starting Todo API Development Server")
44
+ print("=" * 60)
45
+ print(f"Host: {API_HOST}")
46
+ print(f"Log Level: {LOG_LEVEL}")
47
+ print(f"Reload: Enabled (development mode)")
48
+ print("=" * 60)
49
+ print(f"\nAPI Documentation: http://localhost:8000/docs")
50
+ print(f"Health Check: http://localhost:8000/health")
51
+ print("\nPress CTRL+C to stop the server")
52
+ print("=" * 60)
53
+
54
+ # Start uvicorn server
55
+ if __name__ == "__main__":
56
+ import uvicorn
57
+
58
+ uvicorn.run(
59
+ "src.api.main:app",
60
+ host=API_HOST,
61
+ reload=True,
62
+ log_level=LOG_LEVEL,
63
+ access_log=True
64
+ )
src/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ # src package
src/api/__init__.py ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ API Package Initialization
3
+
4
+ This package contains the FastAPI application and all API-related components:
5
+ - main.py: FastAPI application entry point
6
+ - middleware/: Authentication and other middleware
7
+ - routes/: API endpoint handlers
8
+ """
9
+
10
+ __all__ = []
src/api/main.py ADDED
@@ -0,0 +1,238 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ FastAPI Application Entry Point for Todo API
3
+
4
+ Owner: Backend API Engineer
5
+ Purpose: Main FastAPI application with CORS, authentication, and database lifecycle
6
+ Architecture: Async FastAPI with SQLModel, JWT auth, and Neon PostgreSQL
7
+
8
+ Constitutional Constraints:
9
+ - REQUIRED: CORS configured for Next.js frontend (http://localhost:3000)
10
+ - REQUIRED: Database initialization on startup
11
+ - REQUIRED: Database cleanup on shutdown
12
+ - REQUIRED: Health check endpoint for monitoring
13
+ - REQUIRED: All routes protected with JWT authentication
14
+
15
+ Application Lifecycle:
16
+ 1. Startup: Initialize database connection and create tables
17
+ 2. Runtime: Handle API requests with JWT authentication
18
+ 3. Shutdown: Close database connections gracefully
19
+
20
+ All endpoints enforce strict user isolation per constitution Principle IV.
21
+ """
22
+
23
+ import logging
24
+ from contextlib import asynccontextmanager
25
+ from fastapi import FastAPI, status
26
+ from fastapi.middleware.cors import CORSMiddleware
27
+ from fastapi.responses import JSONResponse
28
+
29
+ from src.db import init_database, cleanup_database, check_database_health
30
+ from src.api.routes import todos, chat
31
+
32
+ # Configure logging
33
+ logging.basicConfig(
34
+ level=logging.INFO,
35
+ format="%(asctime)s - %(name)s - %(levelname)s - %(message)s"
36
+ )
37
+ logger = logging.getLogger("api.main")
38
+
39
+
40
+ @asynccontextmanager
41
+ async def lifespan(app: FastAPI):
42
+ """
43
+ Application lifespan manager for startup and shutdown events.
44
+
45
+ Startup:
46
+ - Initialize database connection
47
+ - Create tables if they don't exist
48
+ - Verify database health
49
+
50
+ Shutdown:
51
+ - Close database connections
52
+ - Release connection pool resources
53
+
54
+ Args:
55
+ app: FastAPI application instance
56
+
57
+ Yields:
58
+ None (context manager for lifespan)
59
+ """
60
+ # Startup
61
+ logger.info("Starting Todo API application...")
62
+ try:
63
+ await init_database()
64
+ logger.info("✓ Database initialized successfully")
65
+ except Exception as e:
66
+ logger.error(f"Failed to initialize database: {e}")
67
+ raise
68
+
69
+ yield
70
+
71
+ # Shutdown
72
+ logger.info("Shutting down Todo API application...")
73
+ try:
74
+ await cleanup_database()
75
+ logger.info("✓ Database connections closed")
76
+ except Exception as e:
77
+ logger.error(f"Error during shutdown: {e}")
78
+
79
+
80
+ # Create FastAPI application
81
+ app = FastAPI(
82
+ title="Todo API",
83
+ description="Secure Todo API with JWT authentication and user isolation",
84
+ version="1.0.0",
85
+ lifespan=lifespan,
86
+ docs_url="/docs",
87
+ redoc_url="/redoc",
88
+ openapi_url="/openapi.json"
89
+ )
90
+
91
+
92
+ # Configure CORS - Allow all origins
93
+ # NOTE: allow_credentials=False when using wildcard origin
94
+ app.add_middleware(
95
+ CORSMiddleware,
96
+ allow_origins=["*"], # Allow all origins
97
+ allow_credentials=False, # Required to be False when using "*"
98
+ allow_methods=["GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"],
99
+ allow_headers=[
100
+ "Authorization", # JWT Bearer token
101
+ "Content-Type",
102
+ "Accept",
103
+ "Origin",
104
+ "X-Requested-With"
105
+ ],
106
+ expose_headers=["Content-Length", "Content-Type"],
107
+ max_age=3600 # Cache preflight requests for 1 hour
108
+ )
109
+
110
+
111
+ # Include routers
112
+ app.include_router(todos.router)
113
+ app.include_router(chat.router)
114
+
115
+ # Note: MCP tools are called directly from chat endpoint
116
+ # FastMCP server mounting removed - tools work without external MCP server
117
+
118
+
119
+ # Health check endpoint (no authentication required)
120
+ @app.get(
121
+ "/health",
122
+ status_code=status.HTTP_200_OK,
123
+ tags=["health"],
124
+ summary="Health check endpoint",
125
+ description="Check if the API and database are healthy. No authentication required.",
126
+ responses={
127
+ 200: {"description": "Service is healthy"},
128
+ 503: {"description": "Service is unhealthy"}
129
+ }
130
+ )
131
+ async def health_check():
132
+ """
133
+ Health check endpoint for monitoring and load balancers.
134
+
135
+ Checks:
136
+ - API is running
137
+ - Database connection is healthy
138
+
139
+ Returns:
140
+ dict: Health status with database connectivity
141
+
142
+ Status Codes:
143
+ 200: Service is healthy
144
+ 503: Service is unhealthy (database connection failed)
145
+ """
146
+ try:
147
+ # Check database connectivity
148
+ db_healthy = await check_database_health()
149
+
150
+ if not db_healthy:
151
+ logger.error("Health check failed: Database connection unhealthy")
152
+ return JSONResponse(
153
+ status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
154
+ content={
155
+ "status": "unhealthy",
156
+ "database": "disconnected",
157
+ "message": "Database connection failed"
158
+ }
159
+ )
160
+
161
+ return {
162
+ "status": "healthy",
163
+ "database": "connected",
164
+ "message": "Todo API is running"
165
+ }
166
+
167
+ except Exception as e:
168
+ logger.error(f"Health check failed: {e}")
169
+ return JSONResponse(
170
+ status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
171
+ content={
172
+ "status": "unhealthy",
173
+ "database": "error",
174
+ "message": str(e)
175
+ }
176
+ )
177
+
178
+
179
+ # Root endpoint (no authentication required)
180
+ @app.get(
181
+ "/",
182
+ tags=["root"],
183
+ summary="API root endpoint",
184
+ description="Returns basic API information. No authentication required."
185
+ )
186
+ async def root():
187
+ """
188
+ Root endpoint with API information.
189
+
190
+ Returns:
191
+ dict: API name, version, and documentation links
192
+ """
193
+ return {
194
+ "name": "Todo API",
195
+ "version": "1.0.0",
196
+ "description": "Secure Todo API with JWT authentication and user isolation",
197
+ "documentation": "/docs",
198
+ "health": "/health"
199
+ }
200
+
201
+
202
+ # Global exception handler for unhandled errors
203
+ @app.exception_handler(Exception)
204
+ async def global_exception_handler(request, exc):
205
+ """
206
+ Global exception handler for unhandled errors.
207
+
208
+ Logs the error and returns a generic 500 response.
209
+ Prevents leaking sensitive information in error messages.
210
+
211
+ Args:
212
+ request: FastAPI request object
213
+ exc: Exception that was raised
214
+
215
+ Returns:
216
+ JSONResponse: Generic error response
217
+ """
218
+ logger.error(f"Unhandled exception: {exc}", exc_info=True)
219
+ return JSONResponse(
220
+ status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
221
+ content={
222
+ "detail": "Internal server error"
223
+ }
224
+ )
225
+
226
+
227
+ if __name__ == "__main__":
228
+ import uvicorn
229
+
230
+ # Run with uvicorn for development
231
+ # Production: Use gunicorn with uvicorn workers
232
+ uvicorn.run(
233
+ "backend.src.api.main:app",
234
+ host="0.0.0.0",
235
+ port=8000,
236
+ reload=True, # Auto-reload on code changes (development only)
237
+ log_level="info"
238
+ )
src/api/middleware/__init__.py ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ """
2
+ Authentication Middleware Package
3
+
4
+ This package contains JWT authentication middleware for the Todo API.
5
+ """
6
+
7
+ __all__ = []
src/api/middleware/auth.py ADDED
@@ -0,0 +1,199 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ JWT Authentication Middleware for Todo API
3
+
4
+ Owner: Backend Security Engineer
5
+ Purpose: JWT token verification and user_id extraction
6
+ Architecture: FastAPI dependency injection with python-jose
7
+
8
+ Constitutional Constraints:
9
+ - REQUIRED: Verify JWT signature using BETTER_AUTH_SECRET
10
+ - REQUIRED: Validate issuer="todoweb" and audience="todoweb-api"
11
+ - REQUIRED: Extract user_id from "sub" claim
12
+ - REQUIRED: Return 401 for invalid/expired/missing tokens
13
+ - REQUIRED: Use HTTPBearer security scheme
14
+
15
+ Security Protocol:
16
+ 1. Extract token from Authorization: Bearer <token> header
17
+ 2. Verify signature with shared BETTER_AUTH_SECRET
18
+ 3. Validate token claims (exp, iss, aud)
19
+ 4. Extract user_id from sub claim
20
+ 5. Return user_id for use in route handlers
21
+
22
+ All protected routes MUST use Depends(get_current_user_id) to enforce authentication.
23
+ """
24
+
25
+ import os
26
+ import logging
27
+ from typing import Annotated, Optional
28
+ from fastapi import HTTPException, Security, status
29
+ from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
30
+ from jose import jwt, JWTError
31
+ from jose.exceptions import ExpiredSignatureError, JWTClaimsError
32
+ from dotenv import load_dotenv
33
+
34
+ # Configure logging
35
+ logger = logging.getLogger("api.auth")
36
+
37
+ # Load environment variables
38
+ load_dotenv()
39
+
40
+ # HTTPBearer security scheme for JWT tokens
41
+ security = HTTPBearer(
42
+ scheme_name="Bearer",
43
+ description="JWT token from Better Auth. Include in Authorization header as 'Bearer <token>'",
44
+ auto_error=False
45
+ )
46
+
47
+
48
+ def get_better_auth_secret() -> str:
49
+ """
50
+ Get BETTER_AUTH_SECRET from environment.
51
+
52
+ Returns:
53
+ BETTER_AUTH_SECRET string
54
+
55
+ Raises:
56
+ HTTPException(500): If BETTER_AUTH_SECRET is not configured
57
+ """
58
+ secret = os.getenv("BETTER_AUTH_SECRET")
59
+ if not secret:
60
+ logger.error("BETTER_AUTH_SECRET environment variable not set")
61
+ raise HTTPException(
62
+ status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
63
+ detail="Server configuration error: Authentication secret not configured"
64
+ )
65
+ return secret
66
+
67
+
68
+ def verify_token(credentials: HTTPAuthorizationCredentials) -> dict:
69
+ """
70
+ Verify JWT token and extract payload.
71
+
72
+ Validates:
73
+ - Token signature using BETTER_AUTH_SECRET
74
+ - Token expiration (exp claim)
75
+ - Issuer claim (iss="todoweb")
76
+ - Audience claim (aud="todoweb-api")
77
+
78
+ Args:
79
+ credentials: HTTPAuthorizationCredentials from HTTPBearer
80
+
81
+ Returns:
82
+ dict: Decoded JWT payload containing user_id in "sub" claim
83
+
84
+ Raises:
85
+ HTTPException(401): If token is invalid, expired, or has invalid claims
86
+ """
87
+ token = credentials.credentials
88
+ secret = get_better_auth_secret()
89
+
90
+ try:
91
+ # Decode and verify JWT token
92
+ payload = jwt.decode(
93
+ token,
94
+ secret,
95
+ algorithms=["HS256"],
96
+ issuer="todoweb",
97
+ audience="todoweb-api"
98
+ )
99
+
100
+ logger.debug(f"Token verified successfully for user: {payload.get('sub')}")
101
+ return payload
102
+
103
+ except ExpiredSignatureError:
104
+ logger.warning("Token verification failed: Token has expired")
105
+ raise HTTPException(
106
+ status_code=status.HTTP_401_UNAUTHORIZED,
107
+ detail="Token has expired",
108
+ headers={"WWW-Authenticate": "Bearer"}
109
+ )
110
+ except JWTClaimsError as e:
111
+ logger.warning(f"Token verification failed: Invalid token claims - {e}")
112
+ raise HTTPException(
113
+ status_code=status.HTTP_401_UNAUTHORIZED,
114
+ detail="Invalid token claims (issuer or audience mismatch)",
115
+ headers={"WWW-Authenticate": "Bearer"}
116
+ )
117
+ except JWTError as e:
118
+ logger.warning(f"Token verification failed: {e}")
119
+ raise HTTPException(
120
+ status_code=status.HTTP_401_UNAUTHORIZED,
121
+ detail="Invalid authentication token",
122
+ headers={"WWW-Authenticate": "Bearer"}
123
+ )
124
+
125
+
126
+ async def get_current_user_id(
127
+ credentials: Annotated[Optional[HTTPAuthorizationCredentials], Security(security)] = None
128
+ ) -> str:
129
+ """
130
+ FastAPI dependency to extract user_id from JWT token.
131
+
132
+ This is the primary authentication dependency for all protected routes.
133
+
134
+ Args:
135
+ credentials: Automatically extracted from Authorization header
136
+
137
+ Returns:
138
+ str: User ID from JWT "sub" claim
139
+
140
+ Raises:
141
+ HTTPException(401): If token is missing, invalid, or missing user_id
142
+ """
143
+ if not credentials:
144
+ raise HTTPException(
145
+ status_code=status.HTTP_401_UNAUTHORIZED,
146
+ detail="Authentication required",
147
+ headers={"WWW-Authenticate": "Bearer"}
148
+ )
149
+
150
+ # Verify token and extract payload
151
+ payload = verify_token(credentials)
152
+
153
+ # Extract user_id from "sub" claim
154
+ user_id = payload.get("sub")
155
+
156
+ if not user_id:
157
+ logger.error("Token verification succeeded but 'sub' claim is missing")
158
+ raise HTTPException(
159
+ status_code=status.HTTP_401_UNAUTHORIZED,
160
+ detail="Invalid token: missing user ID",
161
+ headers={"WWW-Authenticate": "Bearer"}
162
+ )
163
+
164
+ return user_id
165
+
166
+
167
+ # Optional: Additional dependency for extracting full user info
168
+ async def get_current_user_info(
169
+ credentials: Annotated[HTTPAuthorizationCredentials, Security(security)]
170
+ ) -> dict:
171
+ """
172
+ FastAPI dependency to extract full user information from JWT token.
173
+
174
+ Returns the complete JWT payload including:
175
+ - sub: User ID
176
+ - email: User email (if present)
177
+ - iat: Issued at timestamp
178
+ - exp: Expiration timestamp
179
+
180
+ Usage:
181
+ @router.get("/api/profile")
182
+ async def get_profile(
183
+ user_info: Annotated[dict, Depends(get_current_user_info)]
184
+ ):
185
+ return {
186
+ "user_id": user_info["sub"],
187
+ "email": user_info.get("email")
188
+ }
189
+
190
+ Args:
191
+ credentials: Automatically extracted from Authorization header
192
+
193
+ Returns:
194
+ dict: Complete JWT payload
195
+
196
+ Raises:
197
+ HTTPException(401): If token is invalid
198
+ """
199
+ return verify_token(credentials)
src/api/routes/__init__.py ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ API Routes Package
3
+
4
+ This package contains all API route handlers for the Todo API.
5
+ """
6
+
7
+ from . import todos
8
+ from . import chat
9
+
10
+ __all__ = ["todos", "chat"]
src/api/routes/chat.py ADDED
@@ -0,0 +1,442 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # backend/src/api/routes/chat.py
2
+ """
3
+ Chat API Routes for AI Chatbot
4
+
5
+ Owner: Backend API Engineer
6
+ Purpose: RESTful endpoints for AI chat operations with user isolation
7
+ Architecture: FastAPI async routes with stateless memory management
8
+
9
+ Constitutional Constraints:
10
+ - REQUIRED: All routes MUST use Depends(get_current_user_id) for authentication
11
+ - REQUIRED: All database queries MUST filter by user_id
12
+ - REQUIRED: Stateless processing - no local session storage (Principle VI)
13
+ - REQUIRED: All tool calls logged for audit trail (Principle VIII)
14
+ """
15
+
16
+ import json
17
+ import logging
18
+ from typing import Annotated
19
+ from fastapi import APIRouter, Depends, HTTPException, status
20
+ from sqlalchemy.ext.asyncio import AsyncSession
21
+ from sqlalchemy import select
22
+
23
+ from src.db import get_session
24
+ from src.db.connection import get_session_factory
25
+ from src.api.middleware.auth import get_current_user_id
26
+ from src.api.schemas.chat import (
27
+ ChatRequest,
28
+ ChatResponse,
29
+ ToolCallSchema,
30
+ ConversationSchema,
31
+ ConversationWithMessagesSchema,
32
+ MessageSchema
33
+ )
34
+ from src.services.chat_service import (
35
+ get_conversation_history,
36
+ save_chat_exchange,
37
+ create_conversation,
38
+ get_conversation_by_id,
39
+ get_user_conversations,
40
+ delete_conversation
41
+ )
42
+ from src.services.agent_service import get_agent_service
43
+ from src.mcp.tools.task_tools import add_task_impl, list_tasks_impl, complete_task_impl, update_task_impl, delete_task_impl
44
+ from src.models.message import Message
45
+
46
+ # Configure logging
47
+ logger = logging.getLogger("api.chat")
48
+
49
+ # Create router
50
+ router = APIRouter(
51
+ prefix="/api",
52
+ tags=["chat"],
53
+ responses={
54
+ 401: {"description": "Authentication failed - invalid or missing JWT token"},
55
+ 500: {"description": "Internal server error"}
56
+ }
57
+ )
58
+
59
+
60
+ async def execute_tool(tool_name: str, tool_args: str, user_id: str) -> str:
61
+ """
62
+ Execute an MCP tool with user_id injection.
63
+
64
+ Per Constitution Principle VII: Tools are the ONLY way AI accesses data.
65
+ The user_id is injected from JWT, never from AI arguments.
66
+
67
+ Args:
68
+ tool_name: Name of the tool to execute
69
+ tool_args: JSON string of tool arguments
70
+ user_id: Authenticated user's ID from JWT
71
+
72
+ Returns:
73
+ Tool result as string
74
+ """
75
+ try:
76
+ args = json.loads(tool_args)
77
+ except json.JSONDecodeError:
78
+ args = {}
79
+
80
+ logger.info(f"Executing tool {tool_name} for user {user_id}")
81
+
82
+ # Validate task_id for tools that require it
83
+ tools_requiring_id = {"complete_task", "update_task", "delete_task"}
84
+ if tool_name in tools_requiring_id:
85
+ task_id = args.get("task_id", "")
86
+ if not task_id or not str(task_id).strip():
87
+ return "Error: Task ID is required. Please use 'show my tasks' to see your tasks with their IDs, then specify which task to modify."
88
+
89
+ if tool_name == "add_task":
90
+ return await add_task_impl(
91
+ user_id=user_id,
92
+ title=args.get("title", ""),
93
+ description=args.get("description")
94
+ )
95
+ elif tool_name == "list_tasks":
96
+ return await list_tasks_impl(
97
+ user_id=user_id,
98
+ status=args.get("status", "all")
99
+ )
100
+ elif tool_name == "complete_task":
101
+ return await complete_task_impl(
102
+ user_id=user_id,
103
+ task_id=args.get("task_id", "")
104
+ )
105
+ elif tool_name == "update_task":
106
+ return await update_task_impl(
107
+ user_id=user_id,
108
+ task_id=args.get("task_id", ""),
109
+ title=args.get("title"),
110
+ description=args.get("description")
111
+ )
112
+ elif tool_name == "delete_task":
113
+ return await delete_task_impl(
114
+ user_id=user_id,
115
+ task_id=args.get("task_id", "")
116
+ )
117
+ else:
118
+ return f"Error: Unknown tool '{tool_name}'"
119
+
120
+
121
+ @router.post(
122
+ "/{user_id}/chat",
123
+ response_model=ChatResponse,
124
+ summary="Send a chat message to the AI assistant",
125
+ description="Processes a user message through the AI agent, which may invoke MCP tools to manage tasks.",
126
+ responses={
127
+ 200: {"description": "Successful response from AI"},
128
+ 400: {"description": "Invalid request (empty message)"},
129
+ 403: {"description": "User ID mismatch with JWT"},
130
+ 404: {"description": "Conversation not found or unauthorized"}
131
+ }
132
+ )
133
+ async def chat(
134
+ user_id: str,
135
+ request: ChatRequest,
136
+ auth_user_id: Annotated[str, Depends(get_current_user_id)]
137
+ ) -> ChatResponse:
138
+ """
139
+ Stateless chat endpoint per stateless-memory-management skill.
140
+
141
+ Flow:
142
+ 1. Validates user matches JWT
143
+ 2. Gets or creates conversation
144
+ 3. Fetches history from DB (stateless)
145
+ 4. Processes with AI agent
146
+ 5. Persists exchange to DB
147
+ 6. Returns response
148
+
149
+ Args:
150
+ user_id: User ID from path (must match JWT)
151
+ request: Chat request with message and optional conversation_id
152
+ auth_user_id: User ID from JWT token
153
+
154
+ Returns:
155
+ ChatResponse with conversation_id, response text, and tool calls
156
+ """
157
+ # Verify user matches JWT (security check)
158
+ if user_id != auth_user_id:
159
+ logger.warning(f"User mismatch: path={user_id}, jwt={auth_user_id}")
160
+ raise HTTPException(
161
+ status_code=status.HTTP_403_FORBIDDEN,
162
+ detail="User ID mismatch with authentication token"
163
+ )
164
+
165
+ try:
166
+ session_factory = get_session_factory()
167
+ logger.info(f"Got session factory for user {user_id}")
168
+
169
+ # Get or create conversation
170
+ conversation_id = request.conversation_id
171
+
172
+ if conversation_id:
173
+ # Verify conversation exists and belongs to user
174
+ async with session_factory() as session:
175
+ conversation = await get_conversation_by_id(
176
+ conversation_id=conversation_id,
177
+ user_id=user_id,
178
+ session=session
179
+ )
180
+ if not conversation:
181
+ raise HTTPException(
182
+ status_code=status.HTTP_404_NOT_FOUND,
183
+ detail="Conversation not found"
184
+ )
185
+ logger.info(f"Found existing conversation {conversation_id}")
186
+ else:
187
+ # Create new conversation
188
+ async with session_factory() as session:
189
+ conversation = await create_conversation(
190
+ user_id=user_id,
191
+ first_message=request.message,
192
+ session=session
193
+ )
194
+ conversation_id = conversation.id
195
+ logger.info(f"Created new conversation {conversation_id}")
196
+
197
+ # Step 1: Fetch history from DB (stateless - no local cache)
198
+ async with session_factory() as session:
199
+ history = await get_conversation_history(
200
+ conversation_id=conversation_id,
201
+ user_id=user_id,
202
+ session=session,
203
+ limit=10
204
+ )
205
+ logger.info(f"Fetched {len(history)} messages from history")
206
+
207
+ # Step 2-3: Process with AI agent
208
+ logger.info("Getting agent service...")
209
+ agent = get_agent_service()
210
+ logger.info(f"Processing message with agent model: {agent.model}")
211
+ result = await agent.process_message(
212
+ user_message=request.message,
213
+ conversation_history=history,
214
+ user_id=user_id,
215
+ tool_executor=execute_tool
216
+ )
217
+ logger.info(f"Agent returned response with {len(result.get('tool_calls') or [])} tool calls")
218
+
219
+ # Step 4: Persist to DB (stateless - no local storage)
220
+ async with session_factory() as session:
221
+ await save_chat_exchange(
222
+ conversation_id=conversation_id,
223
+ user_id=user_id,
224
+ user_message=request.message,
225
+ assistant_response=result["response"],
226
+ tool_calls=result["tool_calls"],
227
+ session=session
228
+ )
229
+
230
+ # Format tool calls for response
231
+ tool_calls_response = None
232
+ if result["tool_calls"]:
233
+ tool_calls_response = [
234
+ ToolCallSchema(
235
+ tool=tc["tool"],
236
+ arguments=tc["arguments"],
237
+ result=tc["result"]
238
+ )
239
+ for tc in result["tool_calls"]
240
+ ]
241
+
242
+ logger.info(f"Chat processed for user {user_id}, conversation {conversation_id}")
243
+
244
+ return ChatResponse(
245
+ conversation_id=conversation_id,
246
+ response=result["response"],
247
+ tool_calls=tool_calls_response
248
+ )
249
+
250
+ except HTTPException:
251
+ raise
252
+ except Exception as e:
253
+ import traceback
254
+ logger.error(f"Chat processing error for user {user_id}: {e}")
255
+ logger.error(f"Traceback: {traceback.format_exc()}")
256
+ raise HTTPException(
257
+ status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
258
+ detail="Failed to process chat message"
259
+ )
260
+
261
+
262
+ @router.get(
263
+ "/{user_id}/conversations",
264
+ response_model=list[ConversationSchema],
265
+ summary="List user's conversations",
266
+ description="Returns all conversations for the authenticated user, sorted by most recent first.",
267
+ responses={
268
+ 200: {"description": "List of conversations"},
269
+ 403: {"description": "User ID mismatch with JWT"}
270
+ }
271
+ )
272
+ async def list_conversations(
273
+ user_id: str,
274
+ auth_user_id: Annotated[str, Depends(get_current_user_id)]
275
+ ) -> list[ConversationSchema]:
276
+ """
277
+ List all conversations for the authenticated user.
278
+
279
+ Args:
280
+ user_id: User ID from path (must match JWT)
281
+ auth_user_id: User ID from JWT token
282
+
283
+ Returns:
284
+ List of ConversationSchema objects
285
+ """
286
+ if user_id != auth_user_id:
287
+ raise HTTPException(
288
+ status_code=status.HTTP_403_FORBIDDEN,
289
+ detail="User ID mismatch with authentication token"
290
+ )
291
+
292
+ try:
293
+ session_factory = get_session_factory()
294
+ async with session_factory() as session:
295
+ conversations = await get_user_conversations(
296
+ user_id=user_id,
297
+ session=session
298
+ )
299
+ return [ConversationSchema.model_validate(c) for c in conversations]
300
+
301
+ except Exception as e:
302
+ logger.error(f"Failed to list conversations for user {user_id}: {e}")
303
+ raise HTTPException(
304
+ status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
305
+ detail="Failed to retrieve conversations"
306
+ )
307
+
308
+
309
+ @router.get(
310
+ "/{user_id}/conversations/{conversation_id}",
311
+ response_model=ConversationWithMessagesSchema,
312
+ summary="Get conversation with messages",
313
+ description="Returns a conversation and its full message history.",
314
+ responses={
315
+ 200: {"description": "Conversation with messages"},
316
+ 403: {"description": "User ID mismatch with JWT"},
317
+ 404: {"description": "Conversation not found or unauthorized"}
318
+ }
319
+ )
320
+ async def get_conversation(
321
+ user_id: str,
322
+ conversation_id: int,
323
+ auth_user_id: Annotated[str, Depends(get_current_user_id)]
324
+ ) -> ConversationWithMessagesSchema:
325
+ """
326
+ Get a conversation with its full message history.
327
+
328
+ Args:
329
+ user_id: User ID from path (must match JWT)
330
+ conversation_id: Conversation ID
331
+ auth_user_id: User ID from JWT token
332
+
333
+ Returns:
334
+ ConversationWithMessagesSchema with messages
335
+ """
336
+ if user_id != auth_user_id:
337
+ raise HTTPException(
338
+ status_code=status.HTTP_403_FORBIDDEN,
339
+ detail="User ID mismatch with authentication token"
340
+ )
341
+
342
+ try:
343
+ session_factory = get_session_factory()
344
+ async with session_factory() as session:
345
+ conversation = await get_conversation_by_id(
346
+ conversation_id=conversation_id,
347
+ user_id=user_id,
348
+ session=session
349
+ )
350
+
351
+ if not conversation:
352
+ raise HTTPException(
353
+ status_code=status.HTTP_404_NOT_FOUND,
354
+ detail="Conversation not found"
355
+ )
356
+
357
+ # Get all messages
358
+ statement = (
359
+ select(Message)
360
+ .where(
361
+ Message.conversation_id == conversation_id,
362
+ Message.user_id == user_id
363
+ )
364
+ .order_by(Message.created_at.asc())
365
+ )
366
+ result = await session.execute(statement)
367
+ messages = result.scalars().all()
368
+
369
+ return ConversationWithMessagesSchema(
370
+ id=conversation.id,
371
+ title=conversation.title,
372
+ created_at=conversation.created_at,
373
+ updated_at=conversation.updated_at,
374
+ messages=[MessageSchema.model_validate(m) for m in messages]
375
+ )
376
+
377
+ except HTTPException:
378
+ raise
379
+ except Exception as e:
380
+ logger.error(f"Failed to get conversation {conversation_id} for user {user_id}: {e}")
381
+ raise HTTPException(
382
+ status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
383
+ detail="Failed to retrieve conversation"
384
+ )
385
+
386
+
387
+ @router.delete(
388
+ "/{user_id}/conversations/{conversation_id}",
389
+ status_code=status.HTTP_204_NO_CONTENT,
390
+ summary="Delete a conversation",
391
+ description="Deletes a conversation and all its messages.",
392
+ responses={
393
+ 204: {"description": "Conversation deleted successfully"},
394
+ 403: {"description": "User ID mismatch with JWT"},
395
+ 404: {"description": "Conversation not found or unauthorized"}
396
+ }
397
+ )
398
+ async def delete_conversation_endpoint(
399
+ user_id: str,
400
+ conversation_id: int,
401
+ auth_user_id: Annotated[str, Depends(get_current_user_id)]
402
+ ):
403
+ """
404
+ Delete a conversation and all its messages.
405
+
406
+ Args:
407
+ user_id: User ID from path (must match JWT)
408
+ conversation_id: Conversation ID to delete
409
+ auth_user_id: User ID from JWT token
410
+
411
+ Returns:
412
+ 204 No Content on success
413
+ """
414
+ if user_id != auth_user_id:
415
+ raise HTTPException(
416
+ status_code=status.HTTP_403_FORBIDDEN,
417
+ detail="User ID mismatch with authentication token"
418
+ )
419
+
420
+ try:
421
+ session_factory = get_session_factory()
422
+ async with session_factory() as session:
423
+ deleted = await delete_conversation(
424
+ conversation_id=conversation_id,
425
+ user_id=user_id,
426
+ session=session
427
+ )
428
+
429
+ if not deleted:
430
+ raise HTTPException(
431
+ status_code=status.HTTP_404_NOT_FOUND,
432
+ detail="Conversation not found"
433
+ )
434
+
435
+ except HTTPException:
436
+ raise
437
+ except Exception as e:
438
+ logger.error(f"Failed to delete conversation {conversation_id} for user {user_id}: {e}")
439
+ raise HTTPException(
440
+ status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
441
+ detail="Failed to delete conversation"
442
+ )
src/api/routes/todos.py ADDED
@@ -0,0 +1,465 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Todo API Routes for FastAPI
3
+
4
+ Owner: Backend API Engineer
5
+ Purpose: RESTful endpoints for todo CRUD operations with user isolation
6
+ Architecture: FastAPI async routes with SQLModel and JWT authentication
7
+
8
+ Constitutional Constraints:
9
+ - REQUIRED: All routes MUST use Depends(get_current_user_id) for authentication
10
+ - REQUIRED: All database queries MUST filter by user_id
11
+ - REQUIRED: Return 404 (not 403) when todo doesn't belong to user (prevent info leakage)
12
+ - REQUIRED: Async/await for all database operations
13
+ - REQUIRED: Proper HTTP status codes (201 for create, 204 for delete, etc.)
14
+
15
+ Security Protocol:
16
+ 1. Extract user_id from JWT via get_current_user_id dependency
17
+ 2. Filter all queries by user_id (never trust client input)
18
+ 3. Return 404 if todo not found OR doesn't belong to user
19
+ 4. Never expose existence of other users' todos
20
+
21
+ All endpoints enforce strict user isolation per constitution Principle IV.
22
+ """
23
+
24
+ import logging
25
+ from typing import Annotated, List
26
+ from uuid import UUID
27
+ from datetime import datetime
28
+ from fastapi import APIRouter, Depends, HTTPException, status
29
+ from sqlalchemy.ext.asyncio import AsyncSession
30
+ from sqlalchemy import select
31
+ from sqlmodel import col
32
+
33
+ from src.db import (
34
+ get_session,
35
+ Todo,
36
+ TodoCreate,
37
+ TodoUpdate,
38
+ TodoResponse
39
+ )
40
+ from src.api.middleware.auth import get_current_user_id
41
+
42
+ # Configure logging
43
+ logger = logging.getLogger("api.todos")
44
+
45
+ # Create router with prefix and tags
46
+ router = APIRouter(
47
+ prefix="/api/todos",
48
+ tags=["todos"],
49
+ responses={
50
+ 401: {"description": "Authentication failed - invalid or missing JWT token"},
51
+ 500: {"description": "Internal server error"}
52
+ }
53
+ )
54
+
55
+
56
+ @router.post(
57
+ "",
58
+ response_model=TodoResponse,
59
+ status_code=status.HTTP_201_CREATED,
60
+ summary="Create a new todo",
61
+ description="Creates a new todo item for the authenticated user. The user_id is automatically extracted from the JWT token.",
62
+ responses={
63
+ 201: {"description": "Todo created successfully"},
64
+ 400: {"description": "Invalid request format"},
65
+ 422: {"description": "Validation error"}
66
+ }
67
+ )
68
+ async def create_todo(
69
+ todo_data: TodoCreate,
70
+ user_id: Annotated[str, Depends(get_current_user_id)],
71
+ session: Annotated[AsyncSession, Depends(get_session)]
72
+ ) -> TodoResponse:
73
+ """
74
+ Create a new todo for the authenticated user.
75
+
76
+ Security:
77
+ - user_id is extracted from JWT (never from request body)
78
+ - Todo is automatically associated with authenticated user
79
+
80
+ Args:
81
+ todo_data: Todo creation data (title, description, is_completed)
82
+ user_id: Automatically extracted from JWT token
83
+ session: Database session
84
+
85
+ Returns:
86
+ TodoResponse: Created todo with all fields including id and timestamps
87
+ """
88
+ try:
89
+ # Debug: Log incoming request data
90
+ logger.info(f"Creating todo with data: title={todo_data.title}, category={todo_data.category}, due_date={todo_data.due_date}")
91
+
92
+ # Convert timezone-aware datetime to timezone-naive for PostgreSQL compatibility
93
+ due_date_naive = None
94
+ if todo_data.due_date:
95
+ if todo_data.due_date.tzinfo is not None:
96
+ # Remove timezone info to match created_at/updated_at
97
+ due_date_naive = todo_data.due_date.replace(tzinfo=None)
98
+ else:
99
+ due_date_naive = todo_data.due_date
100
+
101
+ # Create new todo with user_id from JWT
102
+ new_todo = Todo(
103
+ user_id=user_id,
104
+ title=todo_data.title,
105
+ description=todo_data.description,
106
+ category=todo_data.category,
107
+ due_date=due_date_naive,
108
+ is_completed=todo_data.is_completed,
109
+ created_at=datetime.utcnow(),
110
+ updated_at=datetime.utcnow()
111
+ )
112
+
113
+ session.add(new_todo)
114
+ await session.commit()
115
+ await session.refresh(new_todo)
116
+
117
+ logger.info(f"Todo created: {new_todo.id} (category={new_todo.category}) for user: {user_id}")
118
+ return TodoResponse.model_validate(new_todo)
119
+
120
+ except Exception as e:
121
+ await session.rollback()
122
+ logger.error(f"Failed to create todo for user {user_id}: {e}")
123
+ raise HTTPException(
124
+ status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
125
+ detail="Failed to create todo"
126
+ )
127
+
128
+
129
+ @router.get(
130
+ "",
131
+ response_model=List[TodoResponse],
132
+ summary="List all todos for authenticated user",
133
+ description="Retrieves all todo items belonging to the authenticated user, ordered by creation date (newest first)",
134
+ responses={
135
+ 200: {"description": "Successfully retrieved todo list"}
136
+ }
137
+ )
138
+ async def list_todos(
139
+ user_id: Annotated[str, Depends(get_current_user_id)],
140
+ session: Annotated[AsyncSession, Depends(get_session)]
141
+ ) -> List[TodoResponse]:
142
+ """
143
+ List all todos for the authenticated user.
144
+
145
+ Security:
146
+ - Only returns todos where user_id matches JWT sub claim
147
+ - Other users' todos are never visible
148
+
149
+ Args:
150
+ user_id: Automatically extracted from JWT token
151
+ session: Database session
152
+
153
+ Returns:
154
+ List[TodoResponse]: List of todos ordered by created_at (newest first)
155
+ """
156
+ try:
157
+ # Query todos filtered by user_id (CRITICAL: user isolation)
158
+ statement = (
159
+ select(Todo)
160
+ .where(col(Todo.user_id) == user_id)
161
+ .order_by(Todo.created_at.desc())
162
+ )
163
+
164
+ result = await session.execute(statement)
165
+ todos = result.scalars().all()
166
+
167
+ logger.debug(f"Retrieved {len(todos)} todos for user: {user_id}")
168
+ return [TodoResponse.model_validate(todo) for todo in todos]
169
+
170
+ except Exception as e:
171
+ logger.error(f"Failed to list todos for user {user_id}: {e}")
172
+ raise HTTPException(
173
+ status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
174
+ detail="Failed to retrieve todos"
175
+ )
176
+
177
+
178
+ @router.get(
179
+ "/{todo_id}",
180
+ response_model=TodoResponse,
181
+ summary="Get a specific todo",
182
+ description="Retrieves a single todo by ID. Returns 404 if todo doesn't exist or doesn't belong to authenticated user.",
183
+ responses={
184
+ 200: {"description": "Successfully retrieved todo"},
185
+ 404: {"description": "Todo not found or doesn't belong to user"}
186
+ }
187
+ )
188
+ async def get_todo(
189
+ todo_id: UUID,
190
+ user_id: Annotated[str, Depends(get_current_user_id)],
191
+ session: Annotated[AsyncSession, Depends(get_session)]
192
+ ) -> TodoResponse:
193
+ """
194
+ Get a specific todo by ID.
195
+
196
+ Security:
197
+ - Returns 404 if todo doesn't exist OR doesn't belong to user
198
+ - Never reveals whether todo exists for another user (prevents info leakage)
199
+
200
+ Args:
201
+ todo_id: UUID of the todo to retrieve
202
+ user_id: Automatically extracted from JWT token
203
+ session: Database session
204
+
205
+ Returns:
206
+ TodoResponse: Todo with all fields
207
+
208
+ Raises:
209
+ HTTPException(404): If todo not found or doesn't belong to user
210
+ """
211
+ try:
212
+ # Query todo with BOTH id and user_id filters (CRITICAL: user isolation)
213
+ statement = select(Todo).where(
214
+ col(Todo.id) == todo_id,
215
+ col(Todo.user_id) == user_id
216
+ )
217
+
218
+ result = await session.execute(statement)
219
+ todo = result.scalar_one_or_none()
220
+
221
+ if not todo:
222
+ # Return 404 regardless of whether todo exists for another user
223
+ # This prevents information leakage about other users' todos
224
+ logger.warning(f"Todo not found or access denied: {todo_id} for user: {user_id}")
225
+ raise HTTPException(
226
+ status_code=status.HTTP_404_NOT_FOUND,
227
+ detail="Todo not found"
228
+ )
229
+
230
+ logger.debug(f"Retrieved todo: {todo_id} for user: {user_id}")
231
+ return TodoResponse.model_validate(todo)
232
+
233
+ except HTTPException:
234
+ raise
235
+ except Exception as e:
236
+ logger.error(f"Failed to get todo {todo_id} for user {user_id}: {e}")
237
+ raise HTTPException(
238
+ status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
239
+ detail="Failed to retrieve todo"
240
+ )
241
+
242
+
243
+ @router.put(
244
+ "/{todo_id}",
245
+ response_model=TodoResponse,
246
+ summary="Update a todo",
247
+ description="Updates an existing todo. Only provided fields are updated. Returns 404 if todo doesn't exist or doesn't belong to authenticated user.",
248
+ responses={
249
+ 200: {"description": "Todo updated successfully"},
250
+ 404: {"description": "Todo not found or doesn't belong to user"},
251
+ 422: {"description": "Validation error"}
252
+ }
253
+ )
254
+ async def update_todo(
255
+ todo_id: UUID,
256
+ todo_data: TodoUpdate,
257
+ user_id: Annotated[str, Depends(get_current_user_id)],
258
+ session: Annotated[AsyncSession, Depends(get_session)]
259
+ ) -> TodoResponse:
260
+ """
261
+ Update an existing todo.
262
+
263
+ Security:
264
+ - Only updates todo if it belongs to authenticated user
265
+ - Returns 404 if todo doesn't exist or doesn't belong to user
266
+ - user_id cannot be changed (enforced by not accepting it in request)
267
+
268
+ Args:
269
+ todo_id: UUID of the todo to update
270
+ todo_data: Fields to update (all optional)
271
+ user_id: Automatically extracted from JWT token
272
+ session: Database session
273
+
274
+ Returns:
275
+ TodoResponse: Updated todo with all fields
276
+
277
+ Raises:
278
+ HTTPException(404): If todo not found or doesn't belong to user
279
+ """
280
+ try:
281
+ # Query todo with BOTH id and user_id filters (CRITICAL: user isolation)
282
+ statement = select(Todo).where(
283
+ col(Todo.id) == todo_id,
284
+ col(Todo.user_id) == user_id
285
+ )
286
+
287
+ result = await session.execute(statement)
288
+ todo = result.scalar_one_or_none()
289
+
290
+ if not todo:
291
+ logger.warning(f"Todo not found or access denied for update: {todo_id} for user: {user_id}")
292
+ raise HTTPException(
293
+ status_code=status.HTTP_404_NOT_FOUND,
294
+ detail="Todo not found"
295
+ )
296
+
297
+ # Update only provided fields (partial update)
298
+ update_data = todo_data.model_dump(exclude_unset=True)
299
+
300
+ # Convert timezone-aware datetime to timezone-naive for PostgreSQL compatibility
301
+ if 'due_date' in update_data and update_data['due_date'] is not None:
302
+ if update_data['due_date'].tzinfo is not None:
303
+ # Remove timezone info to match created_at/updated_at
304
+ update_data['due_date'] = update_data['due_date'].replace(tzinfo=None)
305
+
306
+ for field, value in update_data.items():
307
+ setattr(todo, field, value)
308
+
309
+ # Update timestamp
310
+ todo.updated_at = datetime.utcnow()
311
+
312
+ session.add(todo)
313
+ await session.commit()
314
+ await session.refresh(todo)
315
+
316
+ logger.info(f"Todo updated: {todo_id} for user: {user_id}")
317
+ return TodoResponse.model_validate(todo)
318
+
319
+ except HTTPException:
320
+ raise
321
+ except Exception as e:
322
+ await session.rollback()
323
+ logger.error(f"Failed to update todo {todo_id} for user {user_id}: {e}")
324
+ raise HTTPException(
325
+ status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
326
+ detail="Failed to update todo"
327
+ )
328
+
329
+
330
+ @router.delete(
331
+ "/{todo_id}",
332
+ status_code=status.HTTP_204_NO_CONTENT,
333
+ summary="Delete a todo",
334
+ description="Permanently deletes a todo. Returns 404 if todo doesn't exist or doesn't belong to authenticated user.",
335
+ responses={
336
+ 204: {"description": "Todo deleted successfully (no content)"},
337
+ 404: {"description": "Todo not found or doesn't belong to user"}
338
+ }
339
+ )
340
+ async def delete_todo(
341
+ todo_id: UUID,
342
+ user_id: Annotated[str, Depends(get_current_user_id)],
343
+ session: Annotated[AsyncSession, Depends(get_session)]
344
+ ) -> None:
345
+ """
346
+ Delete a todo permanently.
347
+
348
+ Security:
349
+ - Only deletes todo if it belongs to authenticated user
350
+ - Returns 404 if todo doesn't exist or doesn't belong to user
351
+
352
+ Args:
353
+ todo_id: UUID of the todo to delete
354
+ user_id: Automatically extracted from JWT token
355
+ session: Database session
356
+
357
+ Returns:
358
+ None (204 No Content)
359
+
360
+ Raises:
361
+ HTTPException(404): If todo not found or doesn't belong to user
362
+ """
363
+ try:
364
+ # Query todo with BOTH id and user_id filters (CRITICAL: user isolation)
365
+ statement = select(Todo).where(
366
+ col(Todo.id) == todo_id,
367
+ col(Todo.user_id) == user_id
368
+ )
369
+
370
+ result = await session.execute(statement)
371
+ todo = result.scalar_one_or_none()
372
+
373
+ if not todo:
374
+ logger.warning(f"Todo not found or access denied for deletion: {todo_id} for user: {user_id}")
375
+ raise HTTPException(
376
+ status_code=status.HTTP_404_NOT_FOUND,
377
+ detail="Todo not found"
378
+ )
379
+
380
+ await session.delete(todo)
381
+ await session.commit()
382
+
383
+ logger.info(f"Todo deleted: {todo_id} for user: {user_id}")
384
+
385
+ except HTTPException:
386
+ raise
387
+ except Exception as e:
388
+ await session.rollback()
389
+ logger.error(f"Failed to delete todo {todo_id} for user {user_id}: {e}")
390
+ raise HTTPException(
391
+ status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
392
+ detail="Failed to delete todo"
393
+ )
394
+
395
+
396
+ @router.patch(
397
+ "/{todo_id}/complete",
398
+ response_model=TodoResponse,
399
+ summary="Toggle todo completion status",
400
+ description="Toggles the completion status of a todo (complete ↔ incomplete). Returns 404 if todo doesn't exist or doesn't belong to authenticated user.",
401
+ responses={
402
+ 200: {"description": "Todo completion status toggled successfully"},
403
+ 404: {"description": "Todo not found or doesn't belong to user"}
404
+ }
405
+ )
406
+ async def toggle_todo_completion(
407
+ todo_id: UUID,
408
+ user_id: Annotated[str, Depends(get_current_user_id)],
409
+ session: Annotated[AsyncSession, Depends(get_session)]
410
+ ) -> TodoResponse:
411
+ """
412
+ Toggle the completion status of a todo.
413
+
414
+ Security:
415
+ - Only toggles todo if it belongs to authenticated user
416
+ - Returns 404 if todo doesn't exist or doesn't belong to user
417
+
418
+ Args:
419
+ todo_id: UUID of the todo to toggle
420
+ user_id: Automatically extracted from JWT token
421
+ session: Database session
422
+
423
+ Returns:
424
+ TodoResponse: Updated todo with toggled completion status
425
+
426
+ Raises:
427
+ HTTPException(404): If todo not found or doesn't belong to user
428
+ """
429
+ try:
430
+ # Query todo with BOTH id and user_id filters (CRITICAL: user isolation)
431
+ statement = select(Todo).where(
432
+ col(Todo.id) == todo_id,
433
+ col(Todo.user_id) == user_id
434
+ )
435
+
436
+ result = await session.execute(statement)
437
+ todo = result.scalar_one_or_none()
438
+
439
+ if not todo:
440
+ logger.warning(f"Todo not found or access denied for toggle: {todo_id} for user: {user_id}")
441
+ raise HTTPException(
442
+ status_code=status.HTTP_404_NOT_FOUND,
443
+ detail="Todo not found"
444
+ )
445
+
446
+ # Toggle completion status
447
+ todo.is_completed = not todo.is_completed
448
+ todo.updated_at = datetime.utcnow()
449
+
450
+ session.add(todo)
451
+ await session.commit()
452
+ await session.refresh(todo)
453
+
454
+ logger.info(f"Todo completion toggled: {todo_id} (now {todo.is_completed}) for user: {user_id}")
455
+ return TodoResponse.model_validate(todo)
456
+
457
+ except HTTPException:
458
+ raise
459
+ except Exception as e:
460
+ await session.rollback()
461
+ logger.error(f"Failed to toggle todo {todo_id} for user {user_id}: {e}")
462
+ raise HTTPException(
463
+ status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
464
+ detail="Failed to toggle todo completion"
465
+ )
src/api/schemas/__init__.py ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # backend/src/api/schemas/__init__.py
2
+ """API schemas package."""
3
+
4
+ from .chat import ChatRequest, ChatResponse, ToolCallSchema, ConversationSchema, MessageSchema
5
+
6
+ __all__ = [
7
+ "ChatRequest",
8
+ "ChatResponse",
9
+ "ToolCallSchema",
10
+ "ConversationSchema",
11
+ "MessageSchema"
12
+ ]
src/api/schemas/chat.py ADDED
@@ -0,0 +1,103 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # backend/src/api/schemas/chat.py
2
+ """
3
+ Chat API Schemas
4
+
5
+ Owner: Backend API Engineer
6
+ Purpose: Pydantic models for chat API request/response validation
7
+ Architecture: Per contracts/chat-api.yaml specification
8
+ """
9
+
10
+ from pydantic import BaseModel, Field
11
+ from typing import Optional, Any
12
+ from datetime import datetime
13
+
14
+
15
+ class ChatRequest(BaseModel):
16
+ """Request model for POST /api/{user_id}/chat"""
17
+ message: str = Field(
18
+ ...,
19
+ min_length=1,
20
+ max_length=4000,
21
+ description="The user's message to the AI assistant"
22
+ )
23
+ conversation_id: Optional[int] = Field(
24
+ default=None,
25
+ description="Optional conversation ID to continue. If omitted, creates new conversation."
26
+ )
27
+
28
+ class Config:
29
+ json_schema_extra = {
30
+ "example": {
31
+ "message": "Add a task to buy groceries",
32
+ "conversation_id": None
33
+ }
34
+ }
35
+
36
+
37
+ class ToolCallSchema(BaseModel):
38
+ """Schema for tool call information in responses"""
39
+ tool: str = Field(..., description="Name of the MCP tool called")
40
+ arguments: str = Field(..., description="JSON string of arguments passed to the tool")
41
+ result: str = Field(..., description="Result returned by the tool")
42
+
43
+ class Config:
44
+ json_schema_extra = {
45
+ "example": {
46
+ "tool": "add_task",
47
+ "arguments": '{"title": "Buy groceries"}',
48
+ "result": "Task 'Buy groceries' added with ID 15."
49
+ }
50
+ }
51
+
52
+
53
+ class ChatResponse(BaseModel):
54
+ """Response model for POST /api/{user_id}/chat"""
55
+ conversation_id: int = Field(..., description="The conversation ID (new or existing)")
56
+ response: str = Field(..., description="The AI assistant's response text")
57
+ tool_calls: Optional[list[ToolCallSchema]] = Field(
58
+ default=None,
59
+ description="List of tool calls made by the AI"
60
+ )
61
+
62
+ class Config:
63
+ json_schema_extra = {
64
+ "example": {
65
+ "conversation_id": 42,
66
+ "response": "I've added 'Buy groceries' to your task list.",
67
+ "tool_calls": [
68
+ {
69
+ "tool": "add_task",
70
+ "arguments": '{"title": "Buy groceries"}',
71
+ "result": "Task 'Buy groceries' added with ID 15."
72
+ }
73
+ ]
74
+ }
75
+ }
76
+
77
+
78
+ class MessageSchema(BaseModel):
79
+ """Schema for message in conversation history"""
80
+ id: int
81
+ role: str = Field(..., description="Message role: 'user' or 'assistant'")
82
+ content: str
83
+ tool_calls: Optional[list[ToolCallSchema]] = None
84
+ created_at: datetime
85
+
86
+ class Config:
87
+ from_attributes = True
88
+
89
+
90
+ class ConversationSchema(BaseModel):
91
+ """Schema for conversation metadata"""
92
+ id: int
93
+ title: str
94
+ created_at: datetime
95
+ updated_at: datetime
96
+
97
+ class Config:
98
+ from_attributes = True
99
+
100
+
101
+ class ConversationWithMessagesSchema(ConversationSchema):
102
+ """Schema for conversation with full message history"""
103
+ messages: list[MessageSchema] = []
src/cli.py ADDED
@@ -0,0 +1,502 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ CLI Layer for Interactive Todo Application (v2.0.0)
3
+
4
+ Owner: Menu/UX Agent
5
+ Purpose: Interactive terminal interface using Typer and Rich
6
+ Architecture: Command-driven CLI with async service orchestration
7
+
8
+ Constitutional Constraints:
9
+ - ALLOWED: Rich UI output, Typer commands, User input collection, Service layer orchestration
10
+ - FORBIDDEN: SQL queries, Direct database access, Business logic validation (delegates to services)
11
+ """
12
+
13
+ import asyncio
14
+ import typer
15
+ import questionary
16
+ from rich.console import Console
17
+ from rich.table import Table
18
+ from rich.panel import Panel
19
+ from rich.progress import Progress, SpinnerColumn, TextColumn
20
+ from rich import print as rprint
21
+ from datetime import datetime
22
+ from typing import Optional, List, Any
23
+ from enum import Enum
24
+
25
+ from src.models import Priority, TaskStatus, TaskCreate, TaskUpdate, RecurrenceInterval
26
+ from src import services
27
+
28
+ # Initialize Typer app and Rich console
29
+ app = typer.Typer(help="Interactive Todo Application CLI")
30
+ console = Console()
31
+
32
+ class SortOption(str, Enum):
33
+ DATE = "date"
34
+ ALPHA = "alpha"
35
+ PRIORITY = "priority"
36
+
37
+ def get_priority_color(priority: Any) -> str:
38
+ """Return color associated with priority level."""
39
+ # Handle both Enum and raw string
40
+ val = priority.value if hasattr(priority, 'value') else str(priority)
41
+ colors = {
42
+ "high": "red",
43
+ "medium": "yellow",
44
+ "low": "green"
45
+ }
46
+ return colors.get(val.lower(), "white")
47
+
48
+ def display_error(message: str):
49
+ """Display error message in a Rich panel."""
50
+ console.print(Panel(f"[bold red]Error:[/bold red] {message}", border_style="red"))
51
+
52
+ def display_success(message: str):
53
+ """Display success message."""
54
+ console.print(f"[bold green]✓[/bold green] {message}")
55
+
56
+ async def run_with_progress(coro, description: str):
57
+ """Run an async coroutine with a Rich progress spinner."""
58
+ with Progress(
59
+ SpinnerColumn(),
60
+ TextColumn("[progress.description]{task.description}"),
61
+ transient=True,
62
+ ) as progress:
63
+ progress.add_task(description=description, total=None)
64
+ return await coro
65
+
66
+ async def interactive_date_picker(prompt: str) -> Optional[datetime]:
67
+ """Helper to pick a date using natural language or interactive prompt."""
68
+ date_str = await asyncio.to_thread(questionary.text(f"{prompt} (e.g. 'tomorrow', 'next mon at 3pm')").ask)
69
+ if not date_str:
70
+ return None
71
+
72
+ parsed_date = services.parse_natural_date(date_str)
73
+ if not parsed_date:
74
+ console.print("[yellow]Could not parse date. Please use YYYY-MM-DD format or try again.[/yellow]")
75
+ # Fallback to manual entry
76
+ manual_str = await asyncio.to_thread(questionary.text("Due Date (YYYY-MM-DD HH:MM:SS)").ask)
77
+ if not manual_str: return None
78
+ try:
79
+ return datetime.fromisoformat(manual_str.replace(' ', 'T'))
80
+ except ValueError:
81
+ console.print("[red]Invalid date format.[/red]")
82
+ return None
83
+ return parsed_date
84
+
85
+ @app.command()
86
+ def add(
87
+ title: Optional[str] = typer.Argument(None, help="The title of the task"),
88
+ description: Optional[str] = typer.Option(None, "--desc", "-d", help="Task description"),
89
+ priority: Priority = typer.Option(Priority.MEDIUM, "--priority", "-p", help="Task priority"),
90
+ category: Optional[str] = typer.Option(None, "--category", "-c", help="Task category"),
91
+ due: Optional[str] = typer.Option(None, "--due", help="Due date (natural language)"),
92
+ recurrence: RecurrenceInterval = typer.Option(RecurrenceInterval.NONE, "--recurrence", "-r", help="Recurrence interval"),
93
+ interactive: bool = typer.Option(False, "--interactive", "-i", help="Use interactive wizard"),
94
+ ):
95
+ """Add a new task with optional metadata."""
96
+ async def _add():
97
+ nonlocal title, description, priority, category, due, recurrence
98
+
99
+ if interactive or not title:
100
+ # Use questionary for interactive form
101
+ title = await asyncio.to_thread(questionary.text("Task title:", validate=lambda text: len(text) > 0).ask)
102
+ description = await asyncio.to_thread(questionary.text("Description (optional):").ask)
103
+ choice = await asyncio.to_thread(questionary.select(
104
+ "Priority:",
105
+ choices=["low", "medium", "high"],
106
+ default=priority.value if priority else "medium"
107
+ ).ask)
108
+ priority = Priority(choice)
109
+ category = await asyncio.to_thread(questionary.text("Category (optional):").ask)
110
+
111
+ # Date picking
112
+ due_date = await interactive_date_picker("Due Date")
113
+
114
+ # Recurrence
115
+ choice = await asyncio.to_thread(questionary.select(
116
+ "Recurrence:",
117
+ choices=["none", "daily", "weekly", "monthly"],
118
+ default=recurrence.value if recurrence else "none"
119
+ ).ask)
120
+ recurrence = RecurrenceInterval(choice)
121
+ else:
122
+ # Command line mode
123
+ due_date = services.parse_natural_date(due) if due else None
124
+
125
+ task_data = TaskCreate(
126
+ title=title,
127
+ description=description,
128
+ priority=priority,
129
+ category=category,
130
+ due_date=due_date,
131
+ recurrence_interval=recurrence
132
+ )
133
+ result = await run_with_progress(services.create_task(task_data), "Creating task...")
134
+
135
+ if result["success"]:
136
+ display_success(result["message"])
137
+ else:
138
+ display_error(result["message"])
139
+
140
+ asyncio.run(_add())
141
+
142
+ async def async_add(title: str = "", description: Optional[str] = None, priority: Priority = Priority.MEDIUM,
143
+ category: Optional[str] = None, due: Optional[str] = None,
144
+ recurrence: RecurrenceInterval = RecurrenceInterval.NONE,
145
+ interactive: bool = False):
146
+ """Async version of add for interactive mode."""
147
+ if interactive or not title:
148
+ # Use questionary for interactive form
149
+ title = await asyncio.to_thread(questionary.text("Task title:", validate=lambda text: len(text) > 0).ask)
150
+ description = await asyncio.to_thread(questionary.text("Description (optional):").ask)
151
+ choice = await asyncio.to_thread(questionary.select(
152
+ "Priority:",
153
+ choices=["low", "medium", "high"],
154
+ default=priority.value if priority else "medium"
155
+ ).ask)
156
+ priority = Priority(choice)
157
+ category = await asyncio.to_thread(questionary.text("Category (optional):").ask)
158
+
159
+ # Date picking
160
+ due_date = await interactive_date_picker("Due Date")
161
+
162
+ # Recurrence
163
+ choice = await asyncio.to_thread(questionary.select(
164
+ "Recurrence:",
165
+ choices=["none", "daily", "weekly", "monthly"],
166
+ default=recurrence.value if recurrence else "none"
167
+ ).ask)
168
+ recurrence = RecurrenceInterval(choice)
169
+ else:
170
+ # Command line mode
171
+ due_date = services.parse_natural_date(due) if due else None
172
+
173
+ task_data = TaskCreate(
174
+ title=title,
175
+ description=description,
176
+ priority=priority,
177
+ category=category,
178
+ due_date=due_date,
179
+ recurrence_interval=recurrence
180
+ )
181
+ result = await run_with_progress(services.create_task(task_data), "Creating task...")
182
+
183
+ if result["success"]:
184
+ display_success(result["message"])
185
+ else:
186
+ display_error(result["message"])
187
+
188
+ async def async_list_tasks(status: Optional[TaskStatus] = None, category: Optional[str] = None,
189
+ priority: Optional[Priority] = None, sort: str = "date"):
190
+ """Async version of list_tasks for interactive mode."""
191
+ sort_enum = SortOption(sort) if sort in ["date", "alpha", "priority"] else SortOption.DATE
192
+
193
+ result = await run_with_progress(
194
+ services.get_tasks(status=status, category=category, priority=priority, sort_by=sort_enum.value),
195
+ "Fetching tasks..."
196
+ )
197
+
198
+ if not result["success"]:
199
+ display_error(result["message"])
200
+ return
201
+
202
+ tasks = result["data"]
203
+ if not tasks:
204
+ console.print("[yellow]No tasks found matching criteria.[/yellow]")
205
+ return
206
+
207
+ table = Table(title="Todo Tasks", header_style="bold cyan")
208
+ table.add_column("ID", justify="right", style="cyan", no_wrap=True)
209
+ table.add_column("Status", justify="center")
210
+ table.add_column("Priority", justify="center")
211
+ table.add_column("Title", style="white")
212
+ table.add_column("Category", style="blue")
213
+ table.add_column("Due Date", style="green")
214
+ table.add_column("Recur", style="yellow")
215
+
216
+ for task in tasks:
217
+ # Normalize status to icon
218
+ task_status = task.status.value if hasattr(task.status, 'value') else str(task.status)
219
+ status_icon = "[green]✓[/green]" if task_status == "completed" else "[yellow]○[/yellow]"
220
+
221
+ # Normalize priority and recurrence
222
+ p_val = task.priority.value if hasattr(task.priority, 'value') else str(task.priority)
223
+ r_val = task.recurrence_interval.value if hasattr(task.recurrence_interval, 'value') else str(task.recurrence_interval)
224
+
225
+ p_color = get_priority_color(p_val)
226
+ priority_str = f"[{p_color}]{p_val.upper()}[/{p_color}]"
227
+ due_str = task.due_date.strftime("%Y-%m-%d %H:%M") if task.due_date else "-"
228
+ recur_str = r_val if r_val != "none" else "-"
229
+
230
+ table.add_row(
231
+ str(task.id),
232
+ status_icon,
233
+ priority_str,
234
+ task.title,
235
+ task.category or "-",
236
+ due_str,
237
+ recur_str
238
+ )
239
+
240
+ console.print(table)
241
+ console.print(f"\n[italic]{result['message']}[/italic]")
242
+
243
+ async def async_search(query: str):
244
+ """Async version of search for interactive mode."""
245
+ result = await run_with_progress(services.search_tasks(query), f"Searching for '{query}'...")
246
+
247
+ if not result["success"]:
248
+ display_error(result["message"])
249
+ return
250
+
251
+ tasks = result["data"]
252
+ if not tasks:
253
+ console.print(f"[yellow]No tasks found matching '{query}'.[/yellow]")
254
+ return
255
+
256
+ table = Table(title=f"Search Results: {query}")
257
+ table.add_column("ID", justify="right", style="cyan")
258
+ table.add_column("Status", justify="center")
259
+ table.add_column("Title", style="magenta")
260
+
261
+ for task in tasks:
262
+ status_icon = "✓" if task.status == TaskStatus.COMPLETED else "○"
263
+ table.add_row(str(task.id), status_icon, task.title)
264
+
265
+ console.print(table)
266
+
267
+ async def async_update(task_id: int, title: Optional[str] = None, description: Optional[str] = None,
268
+ priority: Optional[Priority] = None, category: Optional[str] = None,
269
+ due: Optional[str] = None, status: Optional[TaskStatus] = None,
270
+ recurrence: Optional[RecurrenceInterval] = None,
271
+ interactive: bool = False):
272
+ """Async version of update for interactive mode."""
273
+ if interactive:
274
+ # Fetch existing task first
275
+ res = await services.get_tasks()
276
+ existing = None
277
+ for t in res["data"]:
278
+ if t.id == task_id:
279
+ existing = t
280
+ break
281
+
282
+ if existing:
283
+ title = await asyncio.to_thread(questionary.text("New title:", default=existing.title).ask)
284
+ choice = await asyncio.to_thread(questionary.select(
285
+ "New Priority:",
286
+ choices=["low", "medium", "high"],
287
+ default=existing.priority if existing.priority else "medium"
288
+ ).ask)
289
+ priority = Priority(choice)
290
+ due_date = await interactive_date_picker("New Due Date")
291
+ choice = await asyncio.to_thread(questionary.select(
292
+ "New Recurrence:",
293
+ choices=["none", "daily", "weekly", "monthly"],
294
+ default=existing.recurrence_interval if existing.recurrence_interval else "none"
295
+ ).ask)
296
+ recurrence = RecurrenceInterval(choice)
297
+ else:
298
+ display_error(f"Task {task_id} not found.")
299
+ return
300
+ else:
301
+ # Command line mode
302
+ due_date = services.parse_natural_date(due) if due else None
303
+
304
+ # Handle completion status specifically for boolean transition
305
+ is_completed = None
306
+ if status:
307
+ is_completed = (status == TaskStatus.COMPLETED)
308
+
309
+ update_data = TaskUpdate(
310
+ title=title,
311
+ description=description,
312
+ priority=priority,
313
+ category=category,
314
+ due_date=due_date,
315
+ is_completed=is_completed,
316
+ recurrence_interval=recurrence
317
+ )
318
+
319
+ result = await run_with_progress(services.update_task(task_id, update_data), f"Updating task {task_id}...")
320
+
321
+ if result["success"]:
322
+ display_success(result["message"])
323
+ else:
324
+ display_error(result["message"])
325
+
326
+ async def async_delete(task_id: int, force: bool = True):
327
+ """Async version of delete for interactive mode."""
328
+ result = await run_with_progress(services.delete_task(task_id), f"Deleting task {task_id}...")
329
+
330
+ if result["success"]:
331
+ display_success(result["message"])
332
+ else:
333
+ display_error(result["message"])
334
+
335
+ async def async_complete(task_id: int):
336
+ """Async version of complete for interactive mode."""
337
+ result = await run_with_progress(services.toggle_task_completion(task_id), f"Toggling status for task {task_id}...")
338
+
339
+ if result["success"]:
340
+ display_success(result["message"])
341
+ else:
342
+ display_error(result["message"])
343
+
344
+ async def async_history(root_task_id: int):
345
+ """Async version of history for interactive mode."""
346
+ result = await run_with_progress(services.get_task_history(root_task_id), f"Fetching history for {root_task_id}...")
347
+
348
+ if not result["success"]:
349
+ display_error(result["message"])
350
+ return
351
+
352
+ tasks = result["data"]
353
+ table = Table(title=f"Task History Series: {root_task_id}", header_style="bold cyan")
354
+ table.add_column("ID", justify="right")
355
+ table.add_column("Status")
356
+ table.add_column("Completed Date")
357
+ table.add_column("Due Date")
358
+
359
+ for task in tasks:
360
+ status_icon = "✓" if task.status == TaskStatus.COMPLETED else "○"
361
+ completed_str = task.updated_at.strftime("%Y-%m-%d %H:%M") if task.status == TaskStatus.COMPLETED else "-"
362
+ due_str = task.due_date.strftime("%Y-%m-%d %H:%M") if task.due_date else "-"
363
+ table.add_row(str(task.id), status_icon, completed_str, due_str)
364
+
365
+ console.print(table)
366
+
367
+ @app.command(name="list")
368
+ def list_tasks(
369
+ status: Optional[TaskStatus] = typer.Option(None, "--status", help="Filter by status"),
370
+ category: Optional[str] = typer.Option(None, "--category", help="Filter by category"),
371
+ priority: Optional[Priority] = typer.Option(None, "--priority", help="Filter by priority"),
372
+ sort: SortOption = typer.Option(SortOption.DATE, "--sort", help="Sort order"),
373
+ ):
374
+ """List tasks with optional filtering and sorting."""
375
+ async def _list():
376
+ await async_list_tasks(status=status, category=category, priority=priority, sort=sort.value)
377
+
378
+ asyncio.run(_list())
379
+
380
+ @app.command()
381
+ def search(
382
+ query: str = typer.Argument(..., help="Search keyword"),
383
+ ):
384
+ """Search for tasks by title or description."""
385
+ async def _search():
386
+ await async_search(query)
387
+
388
+ asyncio.run(_search())
389
+
390
+ @app.command()
391
+ def update(
392
+ task_id: int = typer.Argument(..., help="ID of the task to update"),
393
+ title: Optional[str] = typer.Option(None, "--title", help="New title"),
394
+ description: Optional[str] = typer.Option(None, "--desc", help="New description"),
395
+ priority: Optional[Priority] = typer.Option(None, "--priority", help="New priority"),
396
+ category: Optional[str] = typer.Option(None, "--category", help="New category"),
397
+ due: Optional[str] = typer.Option(None, "--due", help="New due date (natural language)"),
398
+ status: Optional[TaskStatus] = typer.Option(None, "--status", help="New status"),
399
+ recurrence: Optional[RecurrenceInterval] = typer.Option(None, "--recurrence", help="New recurrence interval"),
400
+ interactive: bool = typer.Option(False, "--interactive", "-i", help="Use interactive wizard"),
401
+ ):
402
+ """Update task metadata."""
403
+ async def _update():
404
+ nonlocal title, description, priority, category, due, status, recurrence
405
+
406
+ if interactive:
407
+ # Fetch existing task first
408
+ res = await services.get_tasks() # Inefficient but simple for now
409
+ existing = None
410
+ for t in res["data"]:
411
+ if t.id == task_id:
412
+ existing = t
413
+ break
414
+
415
+ if existing:
416
+ title = await asyncio.to_thread(questionary.text("New title:", default=existing.title).ask)
417
+ priority = Priority(await asyncio.to_thread(questionary.select("Priority:", choices=["low", "medium", "high"], default=existing.priority).ask))
418
+ due_date = await interactive_date_picker("New Due Date")
419
+ recurrence = RecurrenceInterval(await asyncio.to_thread(questionary.select("Recurrence:", choices=["none", "daily", "weekly", "monthly"], default=existing.recurrence_interval).ask))
420
+ else:
421
+ display_error(f"Task {task_id} not found.")
422
+ return
423
+ else:
424
+ due_date = services.parse_natural_date(due) if due else None
425
+
426
+ # Convert status to bool for repository
427
+ is_completed = None
428
+ if status:
429
+ is_completed = (status == TaskStatus.COMPLETED)
430
+
431
+ update_data = TaskUpdate(
432
+ title=title,
433
+ description=description,
434
+ priority=priority,
435
+ category=category,
436
+ due_date=due_date,
437
+ is_completed=is_completed,
438
+ recurrence_interval=recurrence
439
+ )
440
+
441
+ result = await run_with_progress(services.update_task(task_id, update_data), f"Updating task {task_id}...")
442
+
443
+ if result["success"]:
444
+ display_success(result["message"])
445
+ else:
446
+ display_error(result["message"])
447
+
448
+ asyncio.run(_update())
449
+
450
+ @app.command()
451
+ def delete(
452
+ task_id: int = typer.Argument(..., help="ID of the task to delete"),
453
+ force: bool = typer.Option(False, "--force", "-f", help="Skip confirmation"),
454
+ ):
455
+ """Delete a task."""
456
+ async def _delete():
457
+ await async_delete(task_id, force)
458
+
459
+ asyncio.run(_delete())
460
+
461
+ @app.command()
462
+ def complete(
463
+ task_id: int = typer.Argument(..., help="ID of the task to toggle completion"),
464
+ ):
465
+ """Toggle task completion status."""
466
+ async def _toggle():
467
+ await async_complete(task_id)
468
+
469
+ asyncio.run(_toggle())
470
+
471
+ @app.command()
472
+ def history(
473
+ root_task_id: int = typer.Argument(..., help="ID of the original task"),
474
+ ):
475
+ """View history of a recurring task series."""
476
+ async def _history():
477
+ result = await run_with_progress(services.get_task_history(root_task_id), f"Fetching history for {root_task_id}...")
478
+
479
+ if not result["success"]:
480
+ display_error(result["message"])
481
+ return
482
+
483
+ tasks = result["data"]
484
+ table = Table(title=f"Task History Series: {root_task_id}", header_style="bold cyan")
485
+ table.add_column("ID", justify="right")
486
+ table.add_column("Status")
487
+ table.add_column("Completed Date")
488
+ table.add_column("Due Date")
489
+
490
+ for task in tasks:
491
+ status_icon = "✓" if task.status == TaskStatus.COMPLETED else "○"
492
+ completed_str = task.updated_at.strftime("%Y-%m-%d %H:%M") if task.status == TaskStatus.COMPLETED else "-"
493
+ due_str = task.due_date.strftime("%Y-%m-%d %H:%M") if task.due_date else "-"
494
+ table.add_row(str(task.id), status_icon, completed_str, due_str)
495
+
496
+ console.print(table)
497
+
498
+ asyncio.run(_history())
499
+
500
+ if __name__ == "__main__":
501
+ app()
502
+
src/database.py ADDED
@@ -0,0 +1,248 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Database Layer for Interactive Todo Application (v2.0.0)
3
+
4
+ Owner: Database Agent
5
+ Purpose: Neon PostgreSQL connection management and schema initialization
6
+ Architecture: 100% async/await with connection pooling and retry logic
7
+
8
+ Constitutional Constraints:
9
+ - ALLOWED: Database connections, SQL queries, schema initialization, error handling
10
+ - FORBIDDEN: User input (input()), User output (print() for menus), Business logic, Service layer calls
11
+ - FORBIDDEN: CRUD functions (SELECT, INSERT, UPDATE, DELETE) - these belong in src/repository.py
12
+
13
+ All operations use parameterized queries to prevent SQL injection.
14
+ All connections are managed via an asynchronous pool with retry logic for Neon cold starts.
15
+ """
16
+
17
+ import os
18
+ import asyncio
19
+ import logging
20
+ from typing import Optional
21
+ import psycopg
22
+ from psycopg_pool import AsyncConnectionPool
23
+ from dotenv import load_dotenv
24
+
25
+ # Configure logging
26
+ logging.basicConfig(
27
+ filename=".app.log",
28
+ level=logging.INFO,
29
+ format="%(asctime)s - %(name)s - %(levelname)s - %(message)s"
30
+ )
31
+ logger = logging.getLogger("database")
32
+
33
+ # Load environment variables
34
+ load_dotenv()
35
+
36
+ class DatabaseManager:
37
+ """
38
+ Manages asynchronous database connections and schema initialization.
39
+
40
+ Includes retry logic for Neon cold starts and connection pooling.
41
+ """
42
+
43
+ _pool: Optional[AsyncConnectionPool] = None
44
+ _instance: Optional['DatabaseManager'] = None
45
+
46
+ def __new__(cls):
47
+ if cls._instance is None:
48
+ cls._instance = super(DatabaseManager, cls).__new__(cls)
49
+ return cls._instance
50
+
51
+ async def get_pool(self) -> AsyncConnectionPool:
52
+ """
53
+ Initialize and return the connection pool.
54
+
55
+ Returns:
56
+ AsyncConnectionPool instance
57
+
58
+ Raises:
59
+ ConnectionError: If DATABASE_URL is missing or connection fails
60
+ """
61
+ if self._pool is None:
62
+ database_url = os.getenv("DATABASE_URL")
63
+ if not database_url:
64
+ logger.error("DATABASE_URL environment variable is missing")
65
+ raise ConnectionError(
66
+ "DATABASE_URL environment variable is not set. "
67
+ "Please create a .env file with DATABASE_URL=<your-neon-connection-string>"
68
+ )
69
+
70
+ try:
71
+ # Connection string optimization for Neon (e.g., adding keepalives)
72
+ # pool_size can be adjusted based on requirements
73
+ self._pool = AsyncConnectionPool(
74
+ conninfo=database_url,
75
+ open=True,
76
+ min_size=1,
77
+ max_size=10,
78
+ timeout=30.0,
79
+ name="todo_pool"
80
+ )
81
+ logger.info("Database connection pool initialized")
82
+ except Exception as e:
83
+ logger.error(f"Failed to initialize database pool: {e}")
84
+ raise ConnectionError(f"Failed to initialize database pool: {e}")
85
+
86
+ return self._pool
87
+
88
+ async def close_pool(self) -> None:
89
+ """Close the connection pool and release resources."""
90
+ if self._pool:
91
+ await self._pool.close()
92
+ self._pool = None
93
+ logger.info("Database connection pool closed")
94
+
95
+ async def get_connection(self, max_retries: int = 5, initial_delay: float = 1.0):
96
+ """
97
+ Obtain a connection from the pool with retry logic for cold starts.
98
+
99
+ Args:
100
+ max_retries: Maximum number of attempts to connect
101
+ initial_delay: Initial delay between retries in seconds
102
+
103
+ Returns:
104
+ An asynchronous connection context manager
105
+
106
+ Raises:
107
+ ConnectionError: If connection cannot be established after retries
108
+ """
109
+ pool = await self.get_pool()
110
+
111
+ last_exception = None
112
+ delay = initial_delay
113
+
114
+ for attempt in range(1, max_retries + 1):
115
+ try:
116
+ # pool.connection() is an async context manager
117
+ async with pool.connection() as conn:
118
+ # Validate the connection with a simple query
119
+ await conn.execute("SELECT 1")
120
+ # If we get here, the connection is healthy
121
+ # Unfortunately we can't return the connection from within the context manager
122
+ # without it being returned to the pool.
123
+ # Users of this method should use the context manager directly.
124
+ pass
125
+
126
+ # If validation succeeded, return a context manager for the caller
127
+ return pool.connection()
128
+
129
+ except (psycopg.OperationalError, Exception) as e:
130
+ last_exception = e
131
+ logger.warning(f"Database connection attempt {attempt} failed: {e}. Retrying in {delay}s...")
132
+ await asyncio.sleep(delay)
133
+ delay *= 2 # Exponential backoff
134
+
135
+ logger.error(f"Failed to connect to database after {max_retries} attempts.")
136
+ raise ConnectionError(f"Could not connect to database: {last_exception}")
137
+
138
+ async def init_db() -> None:
139
+ """
140
+ Initialize the database schema for the Todo application.
141
+
142
+ Includes task table creation with new columns (priority, category, due_date)
143
+ and indexes for optimization.
144
+
145
+ Schema:
146
+ - id: SERIAL PRIMARY KEY
147
+ - title: TEXT NOT NULL
148
+ - description: TEXT
149
+ - priority: TEXT DEFAULT 'medium' (CHECK: low, medium, high)
150
+ - category: TEXT
151
+ - due_date: TIMESTAMP
152
+ - is_completed: BOOLEAN DEFAULT FALSE
153
+ - created_at: TIMESTAMP DEFAULT NOW()
154
+ - updated_at: TIMESTAMP DEFAULT NOW()
155
+
156
+ Constitutional Compliance:
157
+ ✅ Async/await pattern
158
+ ✅ Parameterized queries
159
+ ✅ No business logic
160
+ ✅ No user interaction
161
+ """
162
+ db = DatabaseManager()
163
+
164
+ try:
165
+ pool = await db.get_pool()
166
+
167
+ logger.info("Initializing database schema...")
168
+
169
+ # Create the tasks table with modern schema requirements - without constraint initially to avoid conflicts
170
+ async with pool.connection() as conn:
171
+ async with conn.cursor() as cur:
172
+ await cur.execute("""
173
+ CREATE TABLE IF NOT EXISTS tasks (
174
+ id SERIAL PRIMARY KEY,
175
+ title TEXT NOT NULL,
176
+ description TEXT,
177
+ priority TEXT DEFAULT 'medium',
178
+ category TEXT,
179
+ due_date TIMESTAMP,
180
+ is_completed BOOLEAN DEFAULT FALSE,
181
+ created_at TIMESTAMP DEFAULT NOW(),
182
+ updated_at TIMESTAMP DEFAULT NOW()
183
+ );
184
+ """)
185
+ await conn.commit()
186
+
187
+ # Migration: Ensure new columns exist for users upgrading from beginner version
188
+ async with pool.connection() as conn:
189
+ async with conn.cursor() as cur:
190
+ # Add recurrence_interval column (backward compatible)
191
+ await cur.execute("ALTER TABLE tasks ADD COLUMN IF NOT EXISTS recurrence_interval TEXT DEFAULT 'none';")
192
+ await conn.commit()
193
+
194
+ async with pool.connection() as conn:
195
+ async with conn.cursor() as cur:
196
+ # Add parent_task_id foreign key
197
+ await cur.execute("ALTER TABLE tasks ADD COLUMN IF NOT EXISTS parent_task_id INT;")
198
+ await conn.commit()
199
+
200
+ async with pool.connection() as conn:
201
+ async with conn.cursor() as cur:
202
+ # Add reminder_sent flag
203
+ await cur.execute("ALTER TABLE tasks ADD COLUMN IF NOT EXISTS reminder_sent BOOLEAN DEFAULT FALSE;")
204
+ await conn.commit()
205
+
206
+ # Add recurrence_interval check constraint (non-validating for existing data)
207
+ async with pool.connection() as conn:
208
+ async with conn.cursor() as cur:
209
+ # Drop existing constraint first to ensure it has correct values
210
+ await cur.execute("ALTER TABLE tasks DROP CONSTRAINT IF EXISTS recurrence_check;")
211
+ await cur.execute("ALTER TABLE tasks ADD CONSTRAINT recurrence_check CHECK (recurrence_interval IN ('daily', 'weekly', 'monthly', 'none')) NOT VALID;")
212
+ # Validate the constraint for existing rows
213
+ await cur.execute("ALTER TABLE tasks VALIDATE CONSTRAINT recurrence_check;")
214
+ await conn.commit()
215
+
216
+ # Create indexes for performance optimization
217
+ async with pool.connection() as conn:
218
+ async with conn.cursor() as cur:
219
+ await cur.execute("""
220
+ CREATE INDEX IF NOT EXISTS idx_tasks_priority ON tasks(priority);
221
+ """)
222
+ await cur.execute("""
223
+ CREATE INDEX IF NOT EXISTS idx_tasks_due_date ON tasks(due_date);
224
+ """)
225
+ # NEW: Index for parent-child queries (task history)
226
+ await cur.execute("""
227
+ CREATE INDEX IF NOT EXISTS idx_tasks_parent ON tasks(parent_task_id);
228
+ """)
229
+ # NEW: Index for reminder check (fast query of pending, unnotified due tasks)
230
+ await cur.execute("""
231
+ CREATE INDEX IF NOT EXISTS idx_tasks_reminder
232
+ ON tasks(due_date) WHERE is_completed = FALSE AND reminder_sent = FALSE;
233
+ """)
234
+ # NEW: Index for recurrence filtering (find all recurring tasks)
235
+ await cur.execute("""
236
+ CREATE INDEX IF NOT EXISTS idx_tasks_recurrence
237
+ ON tasks(recurrence_interval) WHERE recurrence_interval != 'none';
238
+ """)
239
+ await conn.commit()
240
+
241
+ logger.info("Database schema initialized successfully")
242
+
243
+ except Exception as e:
244
+ logger.error(f"Schema initialization failed: {e}")
245
+ raise
246
+
247
+ # Singleton instance for easy access
248
+ db_manager = DatabaseManager()
src/db.py.bak ADDED
@@ -0,0 +1,474 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Database Layer for Interactive Todo Application
3
+
4
+ Owner: Database Agent
5
+ Purpose: Neon PostgreSQL connection management and CRUD operations
6
+
7
+ Constitutional Constraints:
8
+ - ALLOWED: Database connections, SQL queries, schema initialization, error handling
9
+ - FORBIDDEN: User input (input()), User output (print() for menus), Business logic, Service layer calls
10
+
11
+ All functions use parameterized queries to prevent SQL injection.
12
+ All write operations include proper transaction management (commit/rollback).
13
+ """
14
+
15
+ import os
16
+ from typing import Optional
17
+ import psycopg2
18
+ import psycopg2.extensions
19
+ import psycopg2.extras
20
+ from dotenv import load_dotenv
21
+
22
+
23
+ # Load environment variables from .env file
24
+ load_dotenv()
25
+
26
+
27
+ def get_connection() -> psycopg2.extensions.connection:
28
+ """
29
+ Establish connection to Neon PostgreSQL using DATABASE_URL from environment.
30
+
31
+ Returns:
32
+ Active database connection with autocommit disabled for transaction control
33
+
34
+ Raises:
35
+ ConnectionError: If DATABASE_URL environment variable is missing
36
+ ConnectionError: If connection to database fails
37
+
38
+ Implementation Notes:
39
+ - Loads DATABASE_URL from environment using python-dotenv
40
+ - Uses psycopg2.connect() with connection string
41
+ - Sets autocommit=False for explicit transaction control
42
+ - Connection supports context manager usage (with statement)
43
+
44
+ Constitutional Compliance:
45
+ ✅ NO user interaction
46
+ ✅ NO business logic
47
+ ✅ Database-only concern
48
+ """
49
+ database_url = os.getenv("DATABASE_URL")
50
+
51
+ if not database_url:
52
+ raise ConnectionError(
53
+ "DATABASE_URL environment variable is not set. "
54
+ "Please create a .env file with DATABASE_URL=<your-neon-connection-string>"
55
+ )
56
+
57
+ try:
58
+ # Establish connection with autocommit disabled for transaction control
59
+ conn = psycopg2.connect(database_url)
60
+ conn.autocommit = False
61
+ return conn
62
+
63
+ except psycopg2.OperationalError as e:
64
+ raise ConnectionError(f"Failed to connect to database: {e}")
65
+
66
+ except Exception as e:
67
+ raise ConnectionError(f"Unexpected error during database connection: {e}")
68
+
69
+
70
+ def initialize_schema(conn: psycopg2.extensions.connection) -> None:
71
+ """
72
+ Create tasks table if it doesn't exist.
73
+
74
+ Args:
75
+ conn: Active database connection
76
+
77
+ Raises:
78
+ psycopg2.DatabaseError: If schema creation fails
79
+
80
+ Implementation Notes:
81
+ - Executes CREATE TABLE IF NOT EXISTS (idempotent operation)
82
+ - Creates indexes for performance optimization
83
+ - Commits transaction on success
84
+ - Rolls back transaction on failure
85
+ - Table definition matches data-model.md specification
86
+
87
+ Schema:
88
+ - id: SERIAL PRIMARY KEY (auto-increment)
89
+ - title: VARCHAR(200) NOT NULL
90
+ - description: TEXT (nullable)
91
+ - is_completed: BOOLEAN NOT NULL DEFAULT FALSE
92
+ - created_at: TIMESTAMP NOT NULL DEFAULT NOW()
93
+ - updated_at: TIMESTAMP NOT NULL DEFAULT NOW()
94
+
95
+ Constitutional Compliance:
96
+ ✅ NO user interaction
97
+ ✅ NO business logic
98
+ ✅ Database-only concern
99
+ """
100
+ cursor = conn.cursor()
101
+
102
+ try:
103
+ # Create tasks table with all required fields
104
+ cursor.execute("""
105
+ CREATE TABLE IF NOT EXISTS tasks (
106
+ id SERIAL PRIMARY KEY,
107
+ title VARCHAR(200) NOT NULL,
108
+ description TEXT,
109
+ is_completed BOOLEAN NOT NULL DEFAULT FALSE,
110
+ created_at TIMESTAMP NOT NULL DEFAULT NOW(),
111
+ updated_at TIMESTAMP NOT NULL DEFAULT NOW()
112
+ );
113
+ """)
114
+
115
+ # Create index on completion status for filtering (optional optimization)
116
+ cursor.execute("""
117
+ CREATE INDEX IF NOT EXISTS idx_tasks_completed
118
+ ON tasks(is_completed);
119
+ """)
120
+
121
+ # Create index on created_at for sorting (optional optimization)
122
+ cursor.execute("""
123
+ CREATE INDEX IF NOT EXISTS idx_tasks_created
124
+ ON tasks(created_at DESC);
125
+ """)
126
+
127
+ # ALWAYS renumber all tasks to start from 1 on app startup
128
+ # This ensures IDs are sequential without gaps regardless of deletions
129
+ cursor.execute("SELECT COUNT(*) FROM tasks;")
130
+ count = cursor.fetchone()[0]
131
+
132
+ if count > 0:
133
+ # Temporarily disable the primary key constraint to allow renumbering
134
+ # Create a temporary sequence for safe renumbering
135
+ cursor.execute("""
136
+ -- Create temporary column for new IDs
137
+ ALTER TABLE tasks ADD COLUMN IF NOT EXISTS temp_id INTEGER;
138
+
139
+ -- Assign new sequential IDs ordered by creation date
140
+ WITH numbered AS (
141
+ SELECT id, ROW_NUMBER() OVER (ORDER BY created_at) as row_num
142
+ FROM tasks
143
+ )
144
+ UPDATE tasks
145
+ SET temp_id = numbered.row_num
146
+ FROM numbered
147
+ WHERE tasks.id = numbered.id;
148
+
149
+ -- Update the actual IDs
150
+ UPDATE tasks SET id = temp_id;
151
+
152
+ -- Drop temporary column
153
+ ALTER TABLE tasks DROP COLUMN IF EXISTS temp_id;
154
+
155
+ -- Get max ID and reset sequence
156
+ SELECT setval('tasks_id_seq', (SELECT MAX(id) FROM tasks));
157
+ """)
158
+ else:
159
+ # Empty table - reset sequence to 1
160
+ cursor.execute("SELECT setval('tasks_id_seq', 1, false);")
161
+
162
+ conn.commit()
163
+
164
+ except psycopg2.DatabaseError as e:
165
+ conn.rollback()
166
+ raise psycopg2.DatabaseError(f"Failed to initialize schema: {e}")
167
+
168
+ finally:
169
+ cursor.close()
170
+
171
+
172
+ def create_task_db(
173
+ conn: psycopg2.extensions.connection,
174
+ title: str,
175
+ description: Optional[str]
176
+ ) -> int:
177
+ """
178
+ Insert new task into database.
179
+
180
+ Args:
181
+ conn: Active database connection
182
+ title: Task title (assumed pre-validated by service layer)
183
+ description: Task description (optional, can be None)
184
+
185
+ Returns:
186
+ ID of newly created task (SERIAL auto-generated)
187
+
188
+ Raises:
189
+ psycopg2.DatabaseError: If insertion fails
190
+
191
+ Implementation Notes:
192
+ - Uses parameterized query with %s placeholders
193
+ - NO validation performed (service layer responsibility)
194
+ - is_completed defaults to FALSE (database default)
195
+ - created_at and updated_at default to NOW() (database default)
196
+ - Returns auto-generated task ID using RETURNING clause
197
+ - Commits transaction on success
198
+ - Rolls back transaction on failure
199
+
200
+ Constitutional Compliance:
201
+ ✅ NO validation (service layer responsibility)
202
+ ✅ NO user interaction
203
+ ✅ Parameterized queries (SQL injection prevention)
204
+ """
205
+ cursor = conn.cursor()
206
+
207
+ try:
208
+ # Parameterized INSERT query with RETURNING clause to get new ID
209
+ cursor.execute(
210
+ """
211
+ INSERT INTO tasks (title, description)
212
+ VALUES (%s, %s)
213
+ RETURNING id;
214
+ """,
215
+ (title, description)
216
+ )
217
+
218
+ # Fetch the auto-generated task ID
219
+ task_id = cursor.fetchone()[0]
220
+
221
+ conn.commit()
222
+ return task_id
223
+
224
+ except psycopg2.IntegrityError as e:
225
+ conn.rollback()
226
+ raise psycopg2.DatabaseError(f"Data integrity error during task creation: {e}")
227
+
228
+ except psycopg2.DatabaseError as e:
229
+ conn.rollback()
230
+ raise psycopg2.DatabaseError(f"Failed to create task: {e}")
231
+
232
+ finally:
233
+ cursor.close()
234
+
235
+
236
+ def get_all_tasks_db(conn: psycopg2.extensions.connection) -> list[tuple]:
237
+ """
238
+ Retrieve all tasks from database ordered by creation date (newest first).
239
+
240
+ Args:
241
+ conn: Active database connection
242
+
243
+ Returns:
244
+ List of tuples, each tuple contains:
245
+ (id, title, description, is_completed, created_at, updated_at)
246
+
247
+ Returns empty list if no tasks exist
248
+
249
+ Raises:
250
+ psycopg2.DatabaseError: If query fails
251
+
252
+ Implementation Notes:
253
+ - Selects all 6 fields in consistent order
254
+ - Orders by created_at DESC (newest tasks first)
255
+ - Returns raw tuples (service layer converts to Task objects)
256
+ - No pagination (scope supports < 1000 tasks)
257
+ - Read-only operation (no commit needed)
258
+
259
+ Constitutional Compliance:
260
+ ✅ NO business logic (no filtering, no transformation)
261
+ ✅ Returns raw data for service layer processing
262
+ """
263
+ cursor = conn.cursor()
264
+
265
+ try:
266
+ # Select all tasks ordered by creation date (newest first)
267
+ cursor.execute("""
268
+ SELECT id, title, description, is_completed, created_at, updated_at
269
+ FROM tasks
270
+ ORDER BY created_at DESC;
271
+ """)
272
+
273
+ # Fetch all results as list of tuples
274
+ tasks = cursor.fetchall()
275
+ return tasks
276
+
277
+ except psycopg2.DatabaseError as e:
278
+ raise psycopg2.DatabaseError(f"Failed to retrieve tasks: {e}")
279
+
280
+ finally:
281
+ cursor.close()
282
+
283
+
284
+ def update_task_db(
285
+ conn: psycopg2.extensions.connection,
286
+ task_id: int,
287
+ title: Optional[str],
288
+ description: Optional[str]
289
+ ) -> bool:
290
+ """
291
+ Update task title and/or description.
292
+
293
+ Args:
294
+ conn: Active database connection
295
+ task_id: ID of task to update
296
+ title: New title (None = no change)
297
+ description: New description (None = no change)
298
+
299
+ Returns:
300
+ True if task was updated (task existed)
301
+ False if task was not found
302
+
303
+ Raises:
304
+ psycopg2.DatabaseError: If update fails
305
+
306
+ Implementation Notes:
307
+ - Builds dynamic UPDATE query based on which fields are not None
308
+ - Always sets updated_at = NOW()
309
+ - Uses parameterized query for all values
310
+ - Checks cursor.rowcount to determine if task was found
311
+ - Commits transaction on success
312
+ - Rolls back transaction on failure
313
+
314
+ Constitutional Compliance:
315
+ ✅ NO validation (service layer validates before calling)
316
+ ✅ Parameterized queries
317
+ ✅ NO business logic (no field value processing)
318
+ """
319
+ cursor = conn.cursor()
320
+
321
+ try:
322
+ # Build dynamic UPDATE query based on provided fields
323
+ update_fields = []
324
+ params = []
325
+
326
+ # Build query safely without f-strings - construct from safe string operations
327
+ set_clause_parts = []
328
+
329
+ if title is not None:
330
+ set_clause_parts.append("title = %s")
331
+ params.append(title)
332
+
333
+ if description is not None:
334
+ set_clause_parts.append("description = %s")
335
+ params.append(description)
336
+
337
+ # Always update the updated_at timestamp
338
+ set_clause_parts.append("updated_at = NOW()")
339
+
340
+ # Add task_id as final parameter for WHERE clause
341
+ params.append(task_id)
342
+
343
+ # Construct query safely using string concatenation (no f-strings)
344
+ query = "UPDATE tasks SET " + ", ".join(set_clause_parts) + " WHERE id = %s;"
345
+
346
+ cursor.execute(query, params)
347
+
348
+ # Check if any rows were affected (task existed)
349
+ rows_affected = cursor.rowcount
350
+
351
+ conn.commit()
352
+ return rows_affected > 0
353
+
354
+ except psycopg2.DatabaseError as e:
355
+ conn.rollback()
356
+ raise psycopg2.DatabaseError(f"Failed to update task: {e}")
357
+
358
+ finally:
359
+ cursor.close()
360
+
361
+
362
+ def toggle_task_status_db(
363
+ conn: psycopg2.extensions.connection,
364
+ task_id: int
365
+ ) -> bool:
366
+ """
367
+ Toggle task completion status (complete <-> incomplete).
368
+
369
+ Args:
370
+ conn: Active database connection
371
+ task_id: ID of task to toggle
372
+
373
+ Returns:
374
+ True if task was toggled (task existed)
375
+ False if task was not found
376
+
377
+ Raises:
378
+ psycopg2.DatabaseError: If toggle fails
379
+
380
+ Implementation Notes:
381
+ - Uses NOT operator to flip boolean value
382
+ - Updates updated_at timestamp automatically
383
+ - Uses parameterized query
384
+ - Checks cursor.rowcount to determine if task was found
385
+ - Commits transaction on success
386
+ - Rolls back transaction on failure
387
+
388
+ Constitutional Compliance:
389
+ ✅ Simple boolean toggle (no conditional logic)
390
+ ✅ Parameterized query
391
+ ✅ NO validation needed (toggle is idempotent)
392
+ """
393
+ cursor = conn.cursor()
394
+
395
+ try:
396
+ # Toggle is_completed and update timestamp
397
+ cursor.execute(
398
+ """
399
+ UPDATE tasks
400
+ SET is_completed = NOT is_completed, updated_at = NOW()
401
+ WHERE id = %s;
402
+ """,
403
+ (task_id,)
404
+ )
405
+
406
+ # Check if any rows were affected (task existed)
407
+ rows_affected = cursor.rowcount
408
+
409
+ conn.commit()
410
+ return rows_affected > 0
411
+
412
+ except psycopg2.DatabaseError as e:
413
+ conn.rollback()
414
+ raise psycopg2.DatabaseError(f"Failed to toggle task status: {e}")
415
+
416
+ finally:
417
+ cursor.close()
418
+
419
+
420
+ def delete_task_db(
421
+ conn: psycopg2.extensions.connection,
422
+ task_id: int
423
+ ) -> bool:
424
+ """
425
+ Permanently delete task from database.
426
+
427
+ Args:
428
+ conn: Active database connection
429
+ task_id: ID of task to delete
430
+
431
+ Returns:
432
+ True if task was deleted (task existed)
433
+ False if task was not found
434
+
435
+ Raises:
436
+ psycopg2.DatabaseError: If deletion fails
437
+
438
+ Implementation Notes:
439
+ - Simple DELETE operation with WHERE clause
440
+ - Uses parameterized query
441
+ - Checks cursor.rowcount to determine if task was found
442
+ - Commits transaction on success
443
+ - Rolls back transaction on failure
444
+ - No CASCADE needed (no foreign keys in schema)
445
+
446
+ Constitutional Compliance:
447
+ ✅ Simple DELETE operation
448
+ ✅ NO validation (service layer confirms intent)
449
+ ✅ Parameterized query
450
+ """
451
+ cursor = conn.cursor()
452
+
453
+ try:
454
+ # Delete task by ID
455
+ cursor.execute(
456
+ """
457
+ DELETE FROM tasks
458
+ WHERE id = %s;
459
+ """,
460
+ (task_id,)
461
+ )
462
+
463
+ # Check if any rows were affected (task existed)
464
+ rows_affected = cursor.rowcount
465
+
466
+ conn.commit()
467
+ return rows_affected > 0
468
+
469
+ except psycopg2.DatabaseError as e:
470
+ conn.rollback()
471
+ raise psycopg2.DatabaseError(f"Failed to delete task: {e}")
472
+
473
+ finally:
474
+ cursor.close()
src/db/README.md ADDED
@@ -0,0 +1,333 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Database Module - Todo API
2
+
3
+ ## Overview
4
+
5
+ This module provides Neon Serverless PostgreSQL integration for the Todo API with multi-tenant isolation and Better Auth compatibility.
6
+
7
+ ## Architecture
8
+
9
+ - **ORM**: SQLModel (Pydantic + SQLAlchemy)
10
+ - **Driver**: asyncpg (async PostgreSQL driver)
11
+ - **Database**: Neon Serverless PostgreSQL
12
+ - **Pattern**: Async/await throughout
13
+ - **Isolation**: Multi-tenant with user_id filtering
14
+
15
+ ## Key Features
16
+
17
+ ### 1. Serverless Optimization
18
+ - `pool_pre_ping=True`: Validates connections before use (handles cold starts)
19
+ - Small connection pool (5 connections): Optimized for serverless
20
+ - Connection recycling: Prevents stale connections
21
+ - Exponential backoff: Retry logic for connection failures
22
+
23
+ ### 2. Multi-Tenant Isolation
24
+ - Every table includes `user_id: str` column (REQUIRED)
25
+ - `user_id` is indexed for query performance
26
+ - All queries MUST filter by `user_id`
27
+ - User ID extracted from JWT sub claim (never from client input)
28
+
29
+ ### 3. Better Auth Compatibility
30
+ - No conflicts with Better Auth tables (user, session, account, verification)
31
+ - `user_id` references Better Auth's user table (managed externally)
32
+ - No foreign key constraints (Better Auth is source of truth)
33
+
34
+ ## Files
35
+
36
+ ```
37
+ backend/src/db/
38
+ ├── __init__.py # Package exports and initialization
39
+ ├── connection.py # Database connection and session management
40
+ ├── models.py # SQLModel schemas (Todo, TodoCreate, TodoUpdate, TodoResponse)
41
+ ├── verify.py # Verification script
42
+ └── README.md # This file
43
+ ```
44
+
45
+ ## Setup
46
+
47
+ ### 1. Environment Variables
48
+
49
+ Add to your `.env` file:
50
+
51
+ ```bash
52
+ DATABASE_URL=postgresql://user:password@ep-xxx.us-east-2.aws.neon.tech/neondb
53
+ ```
54
+
55
+ **Note**: The connection string will be automatically converted to `postgresql+asyncpg://` for async operations.
56
+
57
+ ### 2. Install Dependencies
58
+
59
+ ```bash
60
+ pip install -r backend/requirements.txt
61
+ ```
62
+
63
+ Required packages:
64
+ - `sqlmodel==0.0.14`
65
+ - `asyncpg==0.29.0`
66
+ - `sqlalchemy[asyncio]==2.0.25`
67
+
68
+ ### 3. Initialize Database
69
+
70
+ ```python
71
+ from backend.src.db import init_database
72
+
73
+ # Call during application startup
74
+ await init_database()
75
+ ```
76
+
77
+ ### 4. Verify Setup
78
+
79
+ ```bash
80
+ python -m backend.src.db.verify
81
+ ```
82
+
83
+ This will:
84
+ - Test database connectivity
85
+ - Create tables and indexes
86
+ - Verify schema matches SQLModel definitions
87
+ - Display detailed status of each check
88
+
89
+ ## Usage
90
+
91
+ ### In FastAPI Routes
92
+
93
+ ```python
94
+ from fastapi import Depends
95
+ from sqlalchemy.ext.asyncio import AsyncSession
96
+ from backend.src.db import get_session, Todo, TodoCreate
97
+
98
+ @app.post("/api/todos")
99
+ async def create_todo(
100
+ todo_data: TodoCreate,
101
+ user_id: str, # Extracted from JWT middleware
102
+ session: AsyncSession = Depends(get_session)
103
+ ):
104
+ # Create todo with user isolation
105
+ todo = Todo(
106
+ **todo_data.model_dump(),
107
+ user_id=user_id # REQUIRED for multi-tenant isolation
108
+ )
109
+ session.add(todo)
110
+ await session.commit()
111
+ await session.refresh(todo)
112
+ return todo
113
+ ```
114
+
115
+ ### Query with User Isolation
116
+
117
+ ```python
118
+ from sqlmodel import select
119
+ from backend.src.db import Todo
120
+
121
+ async def get_user_todos(user_id: str, session: AsyncSession):
122
+ # ALWAYS filter by user_id
123
+ statement = select(Todo).where(Todo.user_id == user_id)
124
+ result = await session.execute(statement)
125
+ return result.scalars().all()
126
+ ```
127
+
128
+ ### Application Lifecycle
129
+
130
+ ```python
131
+ from fastapi import FastAPI
132
+ from backend.src.db import init_database, cleanup_database
133
+
134
+ app = FastAPI()
135
+
136
+ @app.on_event("startup")
137
+ async def startup():
138
+ await init_database()
139
+
140
+ @app.on_event("shutdown")
141
+ async def shutdown():
142
+ await cleanup_database()
143
+ ```
144
+
145
+ ## Database Schema
146
+
147
+ ### Todos Table
148
+
149
+ ```sql
150
+ CREATE TABLE todos (
151
+ id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
152
+ user_id VARCHAR(255) NOT NULL,
153
+ title VARCHAR(200) NOT NULL,
154
+ description TEXT,
155
+ is_completed BOOLEAN NOT NULL DEFAULT FALSE,
156
+ created_at TIMESTAMP NOT NULL DEFAULT NOW(),
157
+ updated_at TIMESTAMP NOT NULL DEFAULT NOW()
158
+ );
159
+
160
+ -- Indexes
161
+ CREATE INDEX ix_todos_user_id ON todos(user_id);
162
+ CREATE INDEX idx_todos_user_completed ON todos(user_id, is_completed);
163
+ ```
164
+
165
+ ### Field Specifications
166
+
167
+ | Field | Type | Constraints | Description |
168
+ |-------|------|-------------|-------------|
169
+ | id | UUID | PRIMARY KEY | Unique identifier (auto-generated) |
170
+ | user_id | VARCHAR(255) | NOT NULL, INDEXED | Owner's user ID from JWT |
171
+ | title | VARCHAR(200) | NOT NULL, 1-200 chars | Todo title |
172
+ | description | TEXT | NULLABLE, max 2000 chars | Optional description |
173
+ | is_completed | BOOLEAN | NOT NULL, default FALSE | Completion status |
174
+ | created_at | TIMESTAMP | NOT NULL | Creation timestamp (UTC) |
175
+ | updated_at | TIMESTAMP | NOT NULL | Last modification timestamp (UTC) |
176
+
177
+ ## SQLModel Models
178
+
179
+ ### Todo (Database Model)
180
+ Full model with all fields including system-generated ones.
181
+
182
+ ### TodoCreate (Request Model)
183
+ For creating todos. Excludes id, user_id, and timestamps.
184
+
185
+ ### TodoUpdate (Request Model)
186
+ For updating todos. All fields optional (partial updates).
187
+
188
+ ### TodoResponse (Response Model)
189
+ For API responses. Includes all fields.
190
+
191
+ ## Security Considerations
192
+
193
+ ### Multi-Tenant Isolation (CRITICAL)
194
+
195
+ 1. **Every query MUST filter by user_id**
196
+ ```python
197
+ # ✓ CORRECT
198
+ select(Todo).where(Todo.user_id == user_id)
199
+
200
+ # ✗ WRONG - Security vulnerability!
201
+ select(Todo) # Returns all users' todos
202
+ ```
203
+
204
+ 2. **Never accept user_id from client input**
205
+ ```python
206
+ # ✓ CORRECT
207
+ user_id = extract_from_jwt(token)
208
+
209
+ # ✗ WRONG - Security vulnerability!
210
+ user_id = request.body.get("user_id")
211
+ ```
212
+
213
+ 3. **Use UUID primary keys**
214
+ - Prevents enumeration attacks
215
+ - UUIDs are globally unique and unpredictable
216
+
217
+ ### Input Validation
218
+
219
+ SQLModel automatically validates:
220
+ - Field types (string, boolean, datetime)
221
+ - String lengths (min/max)
222
+ - Required vs optional fields
223
+ - Data format (UUID, datetime)
224
+
225
+ ## Performance Optimization
226
+
227
+ ### Connection Pooling
228
+ - Pool size: 5 (optimized for serverless)
229
+ - Max overflow: 10 (additional connections when needed)
230
+ - Pool recycling: 3600 seconds (1 hour)
231
+
232
+ ### Indexes
233
+ - `user_id`: Critical for all queries (every query filters by user_id)
234
+ - `(user_id, is_completed)`: Optimizes "show my incomplete todos" queries
235
+
236
+ ### Query Patterns
237
+ - Use async/await for non-blocking I/O
238
+ - Select only needed columns when possible
239
+ - Consider pagination for large result sets
240
+
241
+ ## Error Handling
242
+
243
+ ### Connection Errors
244
+ ```python
245
+ try:
246
+ session = await get_session()
247
+ except ConnectionError as e:
248
+ # Handle connection failure
249
+ # Check DATABASE_URL is set
250
+ # Verify Neon database is accessible
251
+ ```
252
+
253
+ ### Query Errors
254
+ ```python
255
+ try:
256
+ await session.execute(statement)
257
+ await session.commit()
258
+ except Exception as e:
259
+ await session.rollback()
260
+ # Handle query error
261
+ ```
262
+
263
+ ## Testing
264
+
265
+ ### Unit Tests
266
+ Test query functions with mock data:
267
+ ```python
268
+ import pytest
269
+ from backend.src.db import Todo, TodoCreate
270
+
271
+ @pytest.mark.asyncio
272
+ async def test_create_todo(session):
273
+ todo_data = TodoCreate(title="Test", description="Test todo")
274
+ todo = Todo(**todo_data.model_dump(), user_id="test_user")
275
+ session.add(todo)
276
+ await session.commit()
277
+ assert todo.id is not None
278
+ ```
279
+
280
+ ### Integration Tests
281
+ Test with real Neon database (test database):
282
+ ```python
283
+ @pytest.mark.asyncio
284
+ async def test_user_isolation(session):
285
+ # Create todos for two different users
286
+ todo1 = Todo(title="User 1 Todo", user_id="user1")
287
+ todo2 = Todo(title="User 2 Todo", user_id="user2")
288
+
289
+ # Verify user1 cannot see user2's todos
290
+ result = await session.execute(
291
+ select(Todo).where(Todo.user_id == "user1")
292
+ )
293
+ todos = result.scalars().all()
294
+ assert len(todos) == 1
295
+ assert todos[0].user_id == "user1"
296
+ ```
297
+
298
+ ## Troubleshooting
299
+
300
+ ### "DATABASE_URL environment variable not set"
301
+ - Ensure `.env` file exists in project root
302
+ - Verify `DATABASE_URL` is set with your Neon connection string
303
+ - Format: `postgresql://user:password@host.neon.tech/database`
304
+
305
+ ### "Failed to connect to database"
306
+ - Check Neon database is running
307
+ - Verify connection string is correct
308
+ - Check network connectivity
309
+ - Review Neon dashboard for database status
310
+
311
+ ### "Table does not exist"
312
+ - Run `await init_database()` during startup
313
+ - Or run verification script: `python -m backend.src.db.verify`
314
+
315
+ ### "Connection pool exhausted"
316
+ - Increase `pool_size` in `connection.py` (default: 5)
317
+ - Check for connection leaks (ensure sessions are closed)
318
+ - Review query performance (slow queries hold connections)
319
+
320
+ ## Next Steps
321
+
322
+ 1. ✓ Database module created
323
+ 2. ⏭️ Create JWT middleware for user_id extraction
324
+ 3. ⏭️ Implement FastAPI routes with user isolation
325
+ 4. ⏭️ Add integration tests for multi-tenant scenarios
326
+ 5. ⏭️ Configure Better Auth for user management
327
+
328
+ ## References
329
+
330
+ - [SQLModel Documentation](https://sqlmodel.tiangolo.com/)
331
+ - [Neon PostgreSQL Documentation](https://neon.tech/docs)
332
+ - [FastAPI Database Guide](https://fastapi.tiangolo.com/tutorial/sql-databases/)
333
+ - [Better Auth Documentation](https://www.better-auth.com/)
src/db/SETUP_COMPLETE.md ADDED
@@ -0,0 +1,338 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Database Setup Complete - Todo API
2
+
3
+ ## Summary
4
+
5
+ The Neon PostgreSQL database module has been successfully initialized for the Todo API with full multi-tenant isolation and serverless optimization.
6
+
7
+ ## Created Files
8
+
9
+ ### Core Database Module
10
+ ```
11
+ backend/src/db/
12
+ ├── __init__.py # Package initialization and exports
13
+ ├── connection.py # Neon-optimized connection management
14
+ ├── models.py # SQLModel schemas with multi-tenant isolation
15
+ ├── verify.py # Database verification script
16
+ └── README.md # Comprehensive documentation
17
+ ```
18
+
19
+ ### File Details
20
+
21
+ #### 1. connection.py (Database Connection)
22
+ - **AsyncEngine** with asyncpg driver for Neon PostgreSQL
23
+ - **pool_pre_ping=True**: Critical for serverless cold start handling
24
+ - **Connection pooling**: Optimized for serverless (pool_size=5, max_overflow=10)
25
+ - **Retry logic**: Exponential backoff for connection failures
26
+ - **Session management**: FastAPI dependency injection support
27
+ - **Health checks**: Database connectivity monitoring
28
+
29
+ #### 2. models.py (SQLModel Schemas)
30
+ - **Todo**: Database model with all fields
31
+ - `id`: UUID primary key (auto-generated)
32
+ - `user_id`: String, indexed, REQUIRED for multi-tenant isolation
33
+ - `title`: String (1-200 chars, required)
34
+ - `description`: String (optional, max 2000 chars)
35
+ - `is_completed`: Boolean (default: False)
36
+ - `created_at`: DateTime (UTC, auto-generated)
37
+ - `updated_at`: DateTime (UTC, auto-updated)
38
+
39
+ - **TodoCreate**: Request model for creating todos
40
+ - **TodoUpdate**: Request model for updating todos (partial updates)
41
+ - **TodoResponse**: Response model with all fields
42
+
43
+ #### 3. __init__.py (Package Initialization)
44
+ - Exports all database utilities and models
45
+ - `init_database()`: Creates tables and indexes
46
+ - `cleanup_database()`: Graceful shutdown
47
+ - `get_session()`: FastAPI dependency for database sessions
48
+
49
+ #### 4. verify.py (Verification Script)
50
+ - Tests database connectivity
51
+ - Verifies table schema
52
+ - Checks indexes are created
53
+ - Provides detailed status output
54
+
55
+ #### 5. README.md (Documentation)
56
+ - Complete usage guide
57
+ - Security considerations
58
+ - Performance optimization tips
59
+ - Troubleshooting guide
60
+
61
+ ## Constitutional Compliance
62
+
63
+ ### ✓ Multi-Tenant Isolation (Principle IV)
64
+ - All tables include `user_id: str` column (REQUIRED)
65
+ - `user_id` is indexed for query performance
66
+ - All queries MUST filter by `user_id`
67
+ - User ID extracted from JWT sub claim (never from client input)
68
+
69
+ ### ✓ SQLModel Exclusive
70
+ - All models use SQLModel (Pydantic + SQLAlchemy)
71
+ - No raw SQLAlchemy models
72
+ - Type-safe database interactions
73
+
74
+ ### ✓ Neon Serverless Optimization
75
+ - `pool_pre_ping=True` for cold start handling
76
+ - Small connection pool (5 connections)
77
+ - Connection recycling (3600 seconds)
78
+ - Async/await throughout
79
+
80
+ ### ✓ Better Auth Compatibility
81
+ - No conflicts with Better Auth tables
82
+ - `user_id` references Better Auth's user table
83
+ - No foreign key constraints (Better Auth manages users)
84
+
85
+ ## Database Schema
86
+
87
+ ```sql
88
+ CREATE TABLE todos (
89
+ id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
90
+ user_id VARCHAR(255) NOT NULL,
91
+ title VARCHAR(200) NOT NULL,
92
+ description TEXT,
93
+ is_completed BOOLEAN NOT NULL DEFAULT FALSE,
94
+ created_at TIMESTAMP NOT NULL DEFAULT NOW(),
95
+ updated_at TIMESTAMP NOT NULL DEFAULT NOW()
96
+ );
97
+
98
+ -- Indexes for performance
99
+ CREATE INDEX ix_todos_user_id ON todos(user_id);
100
+ CREATE INDEX idx_todos_user_completed ON todos(user_id, is_completed);
101
+ ```
102
+
103
+ ## Next Steps
104
+
105
+ ### 1. Configure Environment Variables
106
+
107
+ Edit `E:\todoweb\.env` and fill in your Neon database connection string:
108
+
109
+ ```bash
110
+ # Replace with your actual Neon connection string
111
+ DATABASE_URL=postgresql://user:password@ep-xxx.us-east-2.aws.neon.tech/neondb
112
+ ```
113
+
114
+ **How to get your Neon connection string:**
115
+ 1. Go to [Neon Console](https://console.neon.tech/)
116
+ 2. Select your project
117
+ 3. Go to "Connection Details"
118
+ 4. Copy the connection string (format: `postgresql://...`)
119
+
120
+ ### 2. Install Dependencies
121
+
122
+ ```bash
123
+ cd E:\todoweb\backend
124
+ pip install -r requirements.txt
125
+ ```
126
+
127
+ Required packages (already in requirements.txt):
128
+ - sqlmodel==0.0.14
129
+ - asyncpg==0.29.0
130
+ - sqlalchemy[asyncio]==2.0.25
131
+
132
+ ### 3. Verify Database Setup
133
+
134
+ Run the verification script to test connectivity and create tables:
135
+
136
+ ```bash
137
+ cd E:\todoweb
138
+ python -m backend.src.db.verify
139
+ ```
140
+
141
+ Expected output:
142
+ ```
143
+ ============================================================
144
+ Database Verification Script
145
+ ============================================================
146
+
147
+ [1/5] Checking database connectivity...
148
+ ✓ Database connection successful
149
+
150
+ [2/5] Initializing database schema...
151
+ ✓ Database schema initialized
152
+
153
+ [3/5] Verifying todos table...
154
+ ✓ Todos table exists
155
+
156
+ [4/5] Verifying table schema...
157
+ ✓ Column 'id' (uuid)
158
+ ✓ Column 'user_id' (character varying)
159
+ ✓ Column 'title' (character varying)
160
+ ✓ Column 'description' (character varying)
161
+ ✓ Column 'is_completed' (boolean)
162
+ ✓ Column 'created_at' (timestamp without time zone)
163
+ ✓ Column 'updated_at' (timestamp without time zone)
164
+
165
+ [5/5] Verifying indexes...
166
+ ✓ Index 'todos_pkey' exists
167
+ ✓ Index 'ix_todos_user_id' exists
168
+ ✓ Index 'idx_todos_user_completed' exists
169
+
170
+ ============================================================
171
+ ✓ All verification checks passed!
172
+ ============================================================
173
+
174
+ Database is ready for use.
175
+ ```
176
+
177
+ ### 4. Integrate with FastAPI
178
+
179
+ In your FastAPI application (e.g., `backend/src/api/main.py`):
180
+
181
+ ```python
182
+ from fastapi import FastAPI
183
+ from backend.src.db import init_database, cleanup_database
184
+
185
+ app = FastAPI()
186
+
187
+ @app.on_event("startup")
188
+ async def startup():
189
+ """Initialize database on application startup"""
190
+ await init_database()
191
+
192
+ @app.on_event("shutdown")
193
+ async def shutdown():
194
+ """Cleanup database connections on shutdown"""
195
+ await cleanup_database()
196
+ ```
197
+
198
+ ### 5. Use in API Routes
199
+
200
+ Example route with user isolation:
201
+
202
+ ```python
203
+ from fastapi import Depends, HTTPException
204
+ from sqlalchemy.ext.asyncio import AsyncSession
205
+ from sqlmodel import select
206
+ from backend.src.db import get_session, Todo, TodoCreate, TodoResponse
207
+
208
+ @app.get("/api/todos", response_model=list[TodoResponse])
209
+ async def list_todos(
210
+ user_id: str, # Extracted from JWT middleware
211
+ session: AsyncSession = Depends(get_session)
212
+ ):
213
+ """List all todos for authenticated user"""
214
+ statement = select(Todo).where(Todo.user_id == user_id)
215
+ result = await session.execute(statement)
216
+ todos = result.scalars().all()
217
+ return todos
218
+
219
+ @app.post("/api/todos", response_model=TodoResponse)
220
+ async def create_todo(
221
+ todo_data: TodoCreate,
222
+ user_id: str, # Extracted from JWT middleware
223
+ session: AsyncSession = Depends(get_session)
224
+ ):
225
+ """Create a new todo for authenticated user"""
226
+ todo = Todo(
227
+ **todo_data.model_dump(),
228
+ user_id=user_id # REQUIRED for multi-tenant isolation
229
+ )
230
+ session.add(todo)
231
+ await session.commit()
232
+ await session.refresh(todo)
233
+ return todo
234
+ ```
235
+
236
+ ## Security Checklist
237
+
238
+ - [x] All tables include `user_id: str` column
239
+ - [x] `user_id` is indexed for performance
240
+ - [x] SQLModel used exclusively (no raw SQLAlchemy)
241
+ - [x] Connection includes `pool_pre_ping=True`
242
+ - [x] No naming conflicts with Better Auth tables
243
+ - [x] Environment variables used for DATABASE_URL
244
+ - [x] Error handling for connection failures
245
+ - [x] Type hints complete and correct
246
+ - [x] UUID primary keys (prevents enumeration attacks)
247
+ - [x] Input validation via SQLModel
248
+
249
+ ## Performance Features
250
+
251
+ - **Connection Pooling**: Reuses connections for better performance
252
+ - **Async Operations**: Non-blocking I/O for concurrent requests
253
+ - **Optimized Indexes**:
254
+ - `user_id` index for all queries
255
+ - Composite `(user_id, is_completed)` for filtered queries
256
+ - **Serverless Optimization**: Small pool size, connection recycling
257
+
258
+ ## Testing Strategy
259
+
260
+ ### Unit Tests
261
+ Test query functions with mock data:
262
+ ```python
263
+ @pytest.mark.asyncio
264
+ async def test_create_todo(session):
265
+ todo_data = TodoCreate(title="Test", description="Test todo")
266
+ todo = Todo(**todo_data.model_dump(), user_id="test_user")
267
+ session.add(todo)
268
+ await session.commit()
269
+ assert todo.id is not None
270
+ ```
271
+
272
+ ### Integration Tests
273
+ Test with real Neon database:
274
+ ```python
275
+ @pytest.mark.asyncio
276
+ async def test_user_isolation(session):
277
+ # Verify user1 cannot see user2's todos
278
+ result = await session.execute(
279
+ select(Todo).where(Todo.user_id == "user1")
280
+ )
281
+ todos = result.scalars().all()
282
+ assert all(t.user_id == "user1" for t in todos)
283
+ ```
284
+
285
+ ## Troubleshooting
286
+
287
+ ### Issue: "DATABASE_URL environment variable not set"
288
+ **Solution**:
289
+ 1. Ensure `.env` file exists at `E:\todoweb\.env`
290
+ 2. Add `DATABASE_URL=postgresql://...` with your Neon connection string
291
+
292
+ ### Issue: "Failed to connect to database"
293
+ **Solution**:
294
+ 1. Verify Neon database is running (check Neon Console)
295
+ 2. Check connection string format
296
+ 3. Ensure network connectivity
297
+ 4. Review Neon dashboard for database status
298
+
299
+ ### Issue: "Table does not exist"
300
+ **Solution**:
301
+ 1. Run `python -m backend.src.db.verify` to create tables
302
+ 2. Or call `await init_database()` in your FastAPI startup
303
+
304
+ ## Architecture Decisions
305
+
306
+ ### Why AsyncEngine with asyncpg?
307
+ - **Async/await**: Non-blocking I/O for better concurrency
308
+ - **asyncpg**: Fastest PostgreSQL driver for Python
309
+ - **Neon compatibility**: Optimized for serverless PostgreSQL
310
+
311
+ ### Why pool_pre_ping=True?
312
+ - **Serverless cold starts**: Validates connections before use
313
+ - **Stale connections**: Detects and replaces dead connections
314
+ - **Reliability**: Prevents "connection already closed" errors
315
+
316
+ ### Why small pool size (5)?
317
+ - **Serverless optimization**: Neon works better with fewer connections
318
+ - **Resource efficiency**: Reduces memory usage
319
+ - **Cost optimization**: Fewer connections = lower costs
320
+
321
+ ### Why UUID primary keys?
322
+ - **Security**: Prevents enumeration attacks
323
+ - **Global uniqueness**: No collisions across distributed systems
324
+ - **Unpredictability**: Cannot guess valid IDs
325
+
326
+ ## References
327
+
328
+ - **Data Model**: `E:\todoweb\specs\001-todo-api\data-model.md`
329
+ - **Architecture Plan**: `E:\todoweb\specs\001-todo-api\plan.md`
330
+ - **Database README**: `E:\todoweb\backend\src\db\README.md`
331
+ - **SQLModel Docs**: https://sqlmodel.tiangolo.com/
332
+ - **Neon Docs**: https://neon.tech/docs
333
+
334
+ ## Status
335
+
336
+ ✅ **Database module complete and ready for use**
337
+
338
+ Next phase: Implement JWT middleware and FastAPI routes with user isolation.
src/db/__init__.py ADDED
@@ -0,0 +1,149 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Database Package Initialization for Todo API
3
+
4
+ Owner: Database Reliability Engineer
5
+ Purpose: Central database module exports and initialization
6
+ Architecture: Async/await with SQLModel and Neon PostgreSQL
7
+
8
+ This module provides:
9
+ - Database connection management (get_session, get_engine)
10
+ - SQLModel models (Todo, TodoCreate, TodoUpdate, TodoResponse)
11
+ - Initialization utilities (create_tables, init_database)
12
+ - Health check functions
13
+
14
+ Usage:
15
+ from backend.src.db import get_session, Todo, TodoCreate
16
+ from backend.src.db import init_database
17
+
18
+ # Initialize database on startup
19
+ await init_database()
20
+
21
+ # Use in FastAPI routes
22
+ @app.get("/api/todos")
23
+ async def list_todos(session: AsyncSession = Depends(get_session)):
24
+ # Query todos with user isolation
25
+ pass
26
+ """
27
+
28
+ import logging
29
+ from sqlalchemy.ext.asyncio import AsyncSession, AsyncEngine
30
+ from sqlalchemy import text
31
+
32
+ # Import connection utilities
33
+ from .connection import (
34
+ get_engine,
35
+ get_session,
36
+ get_session_factory,
37
+ create_tables,
38
+ close_engine,
39
+ check_database_health,
40
+ )
41
+
42
+ # Import models
43
+ from .models import (
44
+ Todo,
45
+ TodoBase,
46
+ TodoCreate,
47
+ TodoUpdate,
48
+ TodoResponse,
49
+ )
50
+
51
+ # Import chat models (Phase III)
52
+ from ..models.conversation import Conversation
53
+ from ..models.message import Message
54
+
55
+ # Configure logging
56
+ logger = logging.getLogger("database")
57
+
58
+
59
+ async def init_database() -> None:
60
+ """
61
+ Initialize the database for the Todo API.
62
+
63
+ This function should be called once during application startup.
64
+
65
+ Steps:
66
+ 1. Create all SQLModel tables (todos table)
67
+ 2. Create composite index for query optimization
68
+ 3. Verify database connectivity
69
+
70
+ Note:
71
+ - Better Auth tables are managed separately (not created here)
72
+ - Only creates tables that don't exist (IF NOT EXISTS)
73
+ - Safe to call multiple times (idempotent)
74
+
75
+ Raises:
76
+ Exception: If database initialization fails
77
+ """
78
+ logger.info("Initializing database for Todo API...")
79
+
80
+ try:
81
+ # Step 1: Create all SQLModel tables
82
+ await create_tables()
83
+ logger.info("✓ Database tables created")
84
+
85
+ # Step 2: Create composite index for optimized queries
86
+ # Index: (user_id, is_completed) for "show my incomplete todos" queries
87
+ engine = get_engine()
88
+ async with engine.begin() as conn:
89
+ # Check if index exists before creating
90
+ await conn.execute(text("""
91
+ CREATE INDEX IF NOT EXISTS idx_todos_user_completed
92
+ ON todos(user_id, is_completed);
93
+ """))
94
+ logger.info("✓ Composite index created (user_id, is_completed)")
95
+
96
+ # Step 3: Verify database connectivity
97
+ is_healthy = await check_database_health()
98
+ if not is_healthy:
99
+ raise ConnectionError("Database health check failed")
100
+ logger.info("✓ Database health check passed")
101
+
102
+ logger.info("Database initialization complete")
103
+
104
+ except Exception as e:
105
+ logger.error(f"Database initialization failed: {e}")
106
+ raise
107
+
108
+
109
+ async def cleanup_database() -> None:
110
+ """
111
+ Cleanup database connections during application shutdown.
112
+
113
+ This function should be called during application shutdown to:
114
+ - Close all database connections
115
+ - Release connection pool resources
116
+ - Ensure graceful shutdown
117
+
118
+ Usage:
119
+ @app.on_event("shutdown")
120
+ async def shutdown():
121
+ await cleanup_database()
122
+ """
123
+ logger.info("Cleaning up database connections...")
124
+ await close_engine()
125
+ logger.info("Database cleanup complete")
126
+
127
+
128
+ # Export all public components
129
+ __all__ = [
130
+ # Connection utilities
131
+ "get_engine",
132
+ "get_session",
133
+ "get_session_factory",
134
+ "create_tables",
135
+ "close_engine",
136
+ "check_database_health",
137
+ # Models
138
+ "Todo",
139
+ "TodoBase",
140
+ "TodoCreate",
141
+ "TodoUpdate",
142
+ "TodoResponse",
143
+ # Chat models (Phase III)
144
+ "Conversation",
145
+ "Message",
146
+ # Initialization
147
+ "init_database",
148
+ "cleanup_database",
149
+ ]
src/db/connection.py ADDED
@@ -0,0 +1,241 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Database Connection Configuration for Todo API
3
+
4
+ Owner: Database Reliability Engineer
5
+ Purpose: Neon Serverless PostgreSQL connection with asyncpg driver
6
+ Architecture: Async/await with SQLModel ORM and connection pooling
7
+
8
+ Constitutional Constraints:
9
+ - REQUIRED: pool_pre_ping=True for serverless cold start handling
10
+ - REQUIRED: AsyncEngine with asyncpg driver
11
+ - REQUIRED: Environment variable for DATABASE_URL (never hardcode)
12
+ - REQUIRED: Connection pooling optimized for serverless (smaller pool sizes)
13
+
14
+ All operations use SQLModel for type-safe database interactions.
15
+ Connection includes retry logic and proper error handling for Neon serverless.
16
+ """
17
+
18
+ import os
19
+ import logging
20
+ from typing import AsyncGenerator
21
+ from sqlalchemy.ext.asyncio import create_async_engine, AsyncSession, AsyncEngine
22
+ from sqlalchemy.orm import sessionmaker
23
+ from sqlalchemy import text
24
+ from sqlmodel import SQLModel
25
+ from dotenv import load_dotenv
26
+
27
+ # Configure logging
28
+ logging.basicConfig(
29
+ level=logging.INFO,
30
+ format="%(asctime)s - %(name)s - %(levelname)s - %(message)s"
31
+ )
32
+ logger = logging.getLogger("database.connection")
33
+
34
+ # Load environment variables
35
+ load_dotenv()
36
+
37
+
38
+ class DatabaseConfig:
39
+ """
40
+ Database configuration for Neon Serverless PostgreSQL.
41
+
42
+ Optimized for serverless with:
43
+ - pool_pre_ping: Validates connections before use (handles cold starts)
44
+ - Small pool size: Serverless databases work better with fewer connections
45
+ - Pool recycling: Prevents stale connections
46
+ - Async operations: Non-blocking I/O for better concurrency
47
+ """
48
+
49
+ def __init__(self):
50
+ self.database_url = os.getenv("DATABASE_URL")
51
+ if not self.database_url:
52
+ raise ValueError(
53
+ "DATABASE_URL environment variable not set. "
54
+ "Please add DATABASE_URL to your .env file with your Neon connection string."
55
+ )
56
+
57
+ # Remove query parameters that asyncpg doesn't accept in URL
58
+ # (sslmode, channel_binding, etc. will be handled via connect_args)
59
+ if "?" in self.database_url:
60
+ self.database_url = self.database_url.split("?")[0]
61
+ logger.info("Removed query parameters from DATABASE_URL (will use connect_args for SSL)")
62
+
63
+ # Convert postgresql:// to postgresql+asyncpg:// for async driver
64
+ if self.database_url.startswith("postgresql://"):
65
+ self.database_url = self.database_url.replace(
66
+ "postgresql://", "postgresql+asyncpg://", 1
67
+ )
68
+ elif not self.database_url.startswith("postgresql+asyncpg://"):
69
+ raise ValueError(
70
+ "DATABASE_URL must start with 'postgresql://' or 'postgresql+asyncpg://'"
71
+ )
72
+
73
+ logger.info("Database configuration initialized")
74
+
75
+ def get_engine(self) -> AsyncEngine:
76
+ """
77
+ Create and return an async database engine.
78
+
79
+ Configuration optimized for Neon Serverless:
80
+ - pool_pre_ping=True: Critical for serverless cold starts
81
+ - pool_size=5: Smaller pool for serverless (vs 10-20 for traditional)
82
+ - max_overflow=10: Additional connections when pool exhausted
83
+ - pool_recycle=3600: Recycle connections after 1 hour
84
+ - echo=False: Disable SQL logging in production (set True for debugging)
85
+
86
+ Returns:
87
+ AsyncEngine configured for Neon PostgreSQL
88
+
89
+ Raises:
90
+ ValueError: If DATABASE_URL is not set or invalid
91
+ """
92
+ # SSL configuration for Neon (asyncpg requires ssl='require' as connect_arg)
93
+ import ssl as ssl_module
94
+
95
+ engine = create_async_engine(
96
+ self.database_url,
97
+ echo=False, # Set to True for SQL query logging during development
98
+ future=True,
99
+ pool_pre_ping=True, # CRITICAL: Validates connections before use
100
+ pool_size=5, # Smaller pool for serverless optimization
101
+ max_overflow=10, # Additional connections when needed
102
+ pool_recycle=3600, # Recycle connections after 1 hour (prevents stale connections)
103
+ connect_args={
104
+ "ssl": ssl_module.create_default_context(), # Enable SSL for Neon
105
+ "server_settings": {
106
+ "application_name": "todo-api"
107
+ }
108
+ }
109
+ )
110
+
111
+ logger.info("Database engine created with Neon-optimized settings")
112
+ return engine
113
+
114
+
115
+ # Global engine instance (singleton pattern)
116
+ _engine: AsyncEngine | None = None
117
+ _session_factory: sessionmaker | None = None
118
+
119
+
120
+ def get_engine() -> AsyncEngine:
121
+ """
122
+ Get or create the global database engine.
123
+
124
+ Returns:
125
+ AsyncEngine instance (singleton)
126
+ """
127
+ global _engine
128
+ if _engine is None:
129
+ config = DatabaseConfig()
130
+ _engine = config.get_engine()
131
+ return _engine
132
+
133
+
134
+ def get_session_factory() -> sessionmaker:
135
+ """
136
+ Get or create the global session factory.
137
+
138
+ Returns:
139
+ sessionmaker configured for async sessions
140
+ """
141
+ global _session_factory
142
+ if _session_factory is None:
143
+ engine = get_engine()
144
+ _session_factory = sessionmaker(
145
+ engine,
146
+ class_=AsyncSession,
147
+ expire_on_commit=False, # Prevent lazy loading issues after commit
148
+ autocommit=False,
149
+ autoflush=False,
150
+ )
151
+ return _session_factory
152
+
153
+
154
+ async def get_session() -> AsyncGenerator[AsyncSession, None]:
155
+ """
156
+ Dependency function to get database session for FastAPI routes.
157
+
158
+ Usage in FastAPI:
159
+ @app.get("/api/todos")
160
+ async def list_todos(session: AsyncSession = Depends(get_session)):
161
+ # Use session here
162
+ pass
163
+
164
+ Yields:
165
+ AsyncSession for database operations
166
+
167
+ Note:
168
+ This is an async generator that properly handles session lifecycle.
169
+ The session is automatically closed after the request completes.
170
+ """
171
+ session_factory = get_session_factory()
172
+ async with session_factory() as session:
173
+ try:
174
+ yield session
175
+ except Exception as e:
176
+ await session.rollback()
177
+ logger.error(f"Database session error: {e}")
178
+ raise
179
+ finally:
180
+ await session.close()
181
+
182
+
183
+ async def create_tables() -> None:
184
+ """
185
+ Create all database tables defined in SQLModel models.
186
+
187
+ This should be called once during application startup.
188
+ Uses SQLModel.metadata.create_all() to create tables.
189
+
190
+ Note:
191
+ - Only creates tables that don't exist (IF NOT EXISTS)
192
+ - Does not modify existing tables (use migrations for schema changes)
193
+ - Better Auth tables are managed separately (not created here)
194
+
195
+ Raises:
196
+ Exception: If table creation fails
197
+ """
198
+ engine = get_engine()
199
+ try:
200
+ async with engine.begin() as conn:
201
+ await conn.run_sync(SQLModel.metadata.create_all)
202
+ logger.info("Database tables created successfully")
203
+ except Exception as e:
204
+ logger.error(f"Failed to create database tables: {e}")
205
+ raise
206
+
207
+
208
+ async def close_engine() -> None:
209
+ """
210
+ Close the database engine and release all connections.
211
+
212
+ This should be called during application shutdown.
213
+ Ensures all connections are properly closed and resources released.
214
+ """
215
+ global _engine, _session_factory
216
+ if _engine:
217
+ await _engine.dispose()
218
+ _engine = None
219
+ _session_factory = None
220
+ logger.info("Database engine closed and connections released")
221
+
222
+
223
+ # Health check function for monitoring
224
+ async def check_database_health() -> bool:
225
+ """
226
+ Check if database connection is healthy.
227
+
228
+ Returns:
229
+ True if database is accessible, False otherwise
230
+
231
+ Usage:
232
+ Used by health check endpoints to verify database connectivity
233
+ """
234
+ try:
235
+ engine = get_engine()
236
+ async with engine.connect() as conn:
237
+ await conn.execute(text("SELECT 1"))
238
+ return True
239
+ except Exception as e:
240
+ logger.error(f"Database health check failed: {e}")
241
+ return False
src/db/models.py ADDED
@@ -0,0 +1,228 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ SQLModel Database Models for Todo API
3
+
4
+ Owner: Database Reliability Engineer
5
+ Purpose: Type-safe database models with multi-tenant isolation
6
+ Architecture: SQLModel (Pydantic + SQLAlchemy) with async support
7
+
8
+ Constitutional Constraints:
9
+ - REQUIRED: All tables MUST include user_id: str column (multi-tenant isolation)
10
+ - REQUIRED: user_id MUST be indexed for query performance
11
+ - REQUIRED: SQLModel exclusive (no raw SQLAlchemy models)
12
+ - REQUIRED: Better Auth compatibility (no conflicts with user table)
13
+
14
+ All models enforce user isolation per constitution Principle IV.
15
+ """
16
+
17
+ from sqlmodel import SQLModel, Field
18
+ from datetime import datetime
19
+ from uuid import UUID, uuid4
20
+ from typing import Optional
21
+
22
+
23
+ class TodoBase(SQLModel):
24
+ """
25
+ Base model with shared fields for requests/responses.
26
+
27
+ This model contains fields that are common across create/update/response models.
28
+ Does not include system-generated fields (id, user_id, timestamps).
29
+ """
30
+ title: str = Field(
31
+ min_length=1,
32
+ max_length=200,
33
+ description="Todo title (required, 1-200 characters)"
34
+ )
35
+ description: Optional[str] = Field(
36
+ default=None,
37
+ max_length=2000,
38
+ description="Optional detailed description (max 2000 characters)"
39
+ )
40
+ category: Optional[str] = Field(
41
+ default=None,
42
+ max_length=50,
43
+ description="Optional category for organizing todos (e.g., Work, Personal, Shopping)"
44
+ )
45
+ due_date: Optional[datetime] = Field(
46
+ default=None,
47
+ description="Optional due date for the todo"
48
+ )
49
+ is_completed: bool = Field(
50
+ default=False,
51
+ description="Completion status (default: false)"
52
+ )
53
+
54
+
55
+ class Todo(TodoBase, table=True):
56
+ """
57
+ Database model for todos table.
58
+
59
+ Includes all fields including system-generated ones (id, user_id, timestamps).
60
+
61
+ Multi-Tenant Isolation:
62
+ - user_id is REQUIRED and INDEXED
63
+ - All queries MUST filter by user_id
64
+ - user_id is extracted from JWT sub claim (never from client input)
65
+
66
+ Better Auth Compatibility:
67
+ - user_id references Better Auth's user table (managed externally)
68
+ - No foreign key constraint (Better Auth manages users separately)
69
+ - Todos remain if user deleted (business decision - can be changed)
70
+
71
+ Indexes:
72
+ - Primary: id (UUID) - Fast lookups by todo ID
73
+ - Secondary: user_id - Critical for user isolation queries
74
+ - Composite: (user_id, is_completed) - Optimizes filtered lists
75
+ """
76
+ __tablename__ = "todos"
77
+
78
+ id: UUID = Field(
79
+ default_factory=uuid4,
80
+ primary_key=True,
81
+ description="Unique identifier (UUID v4)"
82
+ )
83
+
84
+ user_id: str = Field(
85
+ index=True,
86
+ nullable=False,
87
+ description="Owner user ID from JWT sub claim (REQUIRED for multi-tenant isolation)"
88
+ )
89
+
90
+ created_at: datetime = Field(
91
+ default_factory=datetime.utcnow,
92
+ nullable=False,
93
+ description="Creation timestamp (UTC)"
94
+ )
95
+
96
+ updated_at: datetime = Field(
97
+ default_factory=datetime.utcnow,
98
+ nullable=False,
99
+ description="Last modification timestamp (UTC)"
100
+ )
101
+
102
+ class Config:
103
+ """SQLModel configuration"""
104
+ json_schema_extra = {
105
+ "example": {
106
+ "id": "550e8400-e29b-41d4-a716-446655440000",
107
+ "user_id": "user_123abc",
108
+ "title": "Buy groceries",
109
+ "description": "Milk, eggs, bread",
110
+ "category": "Shopping",
111
+ "due_date": "2026-01-15T18:00:00Z",
112
+ "is_completed": False,
113
+ "created_at": "2026-01-09T10:00:00Z",
114
+ "updated_at": "2026-01-09T10:00:00Z"
115
+ }
116
+ }
117
+
118
+
119
+ class TodoCreate(TodoBase):
120
+ """
121
+ Request model for creating a todo.
122
+
123
+ Excludes system-generated fields:
124
+ - id: Generated by database
125
+ - user_id: Extracted from JWT (security requirement)
126
+ - created_at: Set by database
127
+ - updated_at: Set by database
128
+
129
+ Validation:
130
+ - title: Required, 1-200 characters
131
+ - description: Optional, max 2000 characters
132
+ - is_completed: Optional, defaults to False
133
+ """
134
+ pass
135
+
136
+
137
+ class TodoUpdate(SQLModel):
138
+ """
139
+ Request model for updating a todo.
140
+
141
+ All fields are optional (partial updates supported).
142
+ Only provided fields will be updated.
143
+
144
+ Validation:
145
+ - title: If provided, must be 1-200 characters
146
+ - description: If provided, max 2000 characters
147
+ - category: If provided, max 50 characters
148
+ - due_date: If provided, must be valid datetime
149
+ - is_completed: If provided, must be boolean
150
+
151
+ Note:
152
+ - user_id cannot be changed (security requirement)
153
+ - id cannot be changed (immutable)
154
+ - timestamps are updated automatically
155
+ """
156
+ title: Optional[str] = Field(
157
+ default=None,
158
+ min_length=1,
159
+ max_length=200,
160
+ description="Todo title (optional for updates)"
161
+ )
162
+ description: Optional[str] = Field(
163
+ default=None,
164
+ max_length=2000,
165
+ description="Optional detailed description"
166
+ )
167
+ category: Optional[str] = Field(
168
+ default=None,
169
+ max_length=50,
170
+ description="Optional category"
171
+ )
172
+ due_date: Optional[datetime] = Field(
173
+ default=None,
174
+ description="Optional due date"
175
+ )
176
+ is_completed: Optional[bool] = Field(
177
+ default=None,
178
+ description="Completion status"
179
+ )
180
+
181
+
182
+ class TodoResponse(TodoBase):
183
+ """
184
+ Response model with all fields.
185
+
186
+ Includes all fields from the database model.
187
+ Used for API responses to ensure consistent structure.
188
+
189
+ Fields:
190
+ - id: UUID (system-generated)
191
+ - user_id: String (from JWT)
192
+ - title: String (required)
193
+ - description: String | None (optional)
194
+ - is_completed: Boolean (default: false)
195
+ - created_at: DateTime (UTC)
196
+ - updated_at: DateTime (UTC)
197
+ """
198
+ id: UUID
199
+ user_id: str
200
+ created_at: datetime
201
+ updated_at: datetime
202
+
203
+ class Config:
204
+ """SQLModel configuration"""
205
+ json_schema_extra = {
206
+ "example": {
207
+ "id": "550e8400-e29b-41d4-a716-446655440000",
208
+ "user_id": "user_123abc",
209
+ "title": "Buy groceries",
210
+ "description": "Milk, eggs, bread",
211
+ "category": "Shopping",
212
+ "due_date": "2026-01-15T18:00:00Z",
213
+ "is_completed": False,
214
+ "created_at": "2026-01-09T10:00:00Z",
215
+ "updated_at": "2026-01-09T10:00:00Z"
216
+ }
217
+ }
218
+
219
+
220
+ # Additional index configuration for composite index
221
+ # This will be created during table initialization
222
+ # CREATE INDEX idx_todos_user_completed ON todos(user_id, is_completed);
223
+ #
224
+ # Rationale:
225
+ # - Common query pattern: "show me my incomplete todos"
226
+ # - Composite index optimizes: WHERE user_id = ? AND is_completed = ?
227
+ # - Single user_id index covers: WHERE user_id = ?
228
+ # - Both indexes are beneficial for different query patterns
src/db/verify.py ADDED
@@ -0,0 +1,159 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Database Verification Script for Todo API
3
+
4
+ Purpose: Verify database connection and schema initialization
5
+ Usage: python -m backend.src.db.verify
6
+
7
+ This script:
8
+ 1. Tests database connection to Neon PostgreSQL
9
+ 2. Verifies all tables are created correctly
10
+ 3. Checks indexes are in place
11
+ 4. Validates schema matches SQLModel definitions
12
+
13
+ Run this after setting up your DATABASE_URL in .env file.
14
+ """
15
+
16
+ import asyncio
17
+ import sys
18
+ import logging
19
+ from sqlalchemy import text
20
+ from sqlalchemy.ext.asyncio import AsyncSession
21
+
22
+ # Configure logging
23
+ logging.basicConfig(
24
+ level=logging.INFO,
25
+ format="%(asctime)s - %(levelname)s - %(message)s"
26
+ )
27
+ logger = logging.getLogger("database.verify")
28
+
29
+
30
+ async def verify_database():
31
+ """
32
+ Verify database setup and connectivity.
33
+
34
+ Returns:
35
+ bool: True if all checks pass, False otherwise
36
+ """
37
+ try:
38
+ # Import after logging is configured
39
+ from backend.src.db import (
40
+ init_database,
41
+ get_session,
42
+ check_database_health,
43
+ get_engine
44
+ )
45
+
46
+ logger.info("=" * 60)
47
+ logger.info("Database Verification Script")
48
+ logger.info("=" * 60)
49
+
50
+ # Step 1: Check database health
51
+ logger.info("\n[1/5] Checking database connectivity...")
52
+ is_healthy = await check_database_health()
53
+ if not is_healthy:
54
+ logger.error("✗ Database connection failed")
55
+ return False
56
+ logger.info("✓ Database connection successful")
57
+
58
+ # Step 2: Initialize database (create tables and indexes)
59
+ logger.info("\n[2/5] Initializing database schema...")
60
+ await init_database()
61
+ logger.info("✓ Database schema initialized")
62
+
63
+ # Step 3: Verify todos table exists
64
+ logger.info("\n[3/5] Verifying todos table...")
65
+ engine = get_engine()
66
+ async with engine.begin() as conn:
67
+ result = await conn.execute(text("""
68
+ SELECT EXISTS (
69
+ SELECT FROM information_schema.tables
70
+ WHERE table_name = 'todos'
71
+ );
72
+ """))
73
+ table_exists = result.scalar()
74
+
75
+ if not table_exists:
76
+ logger.error("✗ Todos table not found")
77
+ return False
78
+ logger.info("✓ Todos table exists")
79
+
80
+ # Step 4: Verify table schema
81
+ logger.info("\n[4/5] Verifying table schema...")
82
+ async with engine.begin() as conn:
83
+ result = await conn.execute(text("""
84
+ SELECT column_name, data_type, is_nullable
85
+ FROM information_schema.columns
86
+ WHERE table_name = 'todos'
87
+ ORDER BY ordinal_position;
88
+ """))
89
+ columns = result.fetchall()
90
+
91
+ required_columns = {
92
+ 'id': 'uuid',
93
+ 'user_id': 'character varying',
94
+ 'title': 'character varying',
95
+ 'description': 'character varying',
96
+ 'is_completed': 'boolean',
97
+ 'created_at': 'timestamp without time zone',
98
+ 'updated_at': 'timestamp without time zone'
99
+ }
100
+
101
+ found_columns = {col[0]: col[1] for col in columns}
102
+
103
+ for col_name, col_type in required_columns.items():
104
+ if col_name not in found_columns:
105
+ logger.error(f"✗ Missing column: {col_name}")
106
+ return False
107
+ logger.info(f" ✓ Column '{col_name}' ({found_columns[col_name]})")
108
+
109
+ # Step 5: Verify indexes
110
+ logger.info("\n[5/5] Verifying indexes...")
111
+ async with engine.begin() as conn:
112
+ result = await conn.execute(text("""
113
+ SELECT indexname
114
+ FROM pg_indexes
115
+ WHERE tablename = 'todos';
116
+ """))
117
+ indexes = [row[0] for row in result.fetchall()]
118
+
119
+ required_indexes = ['todos_pkey', 'ix_todos_user_id', 'idx_todos_user_completed']
120
+
121
+ for index_name in required_indexes:
122
+ if index_name in indexes:
123
+ logger.info(f" ✓ Index '{index_name}' exists")
124
+ else:
125
+ logger.warning(f" ⚠ Index '{index_name}' not found (may be created with different name)")
126
+
127
+ logger.info("\n" + "=" * 60)
128
+ logger.info("✓ All verification checks passed!")
129
+ logger.info("=" * 60)
130
+ logger.info("\nDatabase is ready for use.")
131
+ logger.info("Next steps:")
132
+ logger.info(" 1. Start the FastAPI server: uvicorn backend.src.api.main:app --reload")
133
+ logger.info(" 2. Test the API endpoints with authentication")
134
+ logger.info(" 3. Verify user isolation in multi-tenant scenarios")
135
+
136
+ return True
137
+
138
+ except ValueError as e:
139
+ logger.error(f"\n✗ Configuration error: {e}")
140
+ logger.error("\nPlease ensure:")
141
+ logger.error(" 1. .env file exists in project root")
142
+ logger.error(" 2. DATABASE_URL is set with your Neon connection string")
143
+ logger.error(" 3. Format: postgresql://user:password@host.neon.tech/database")
144
+ return False
145
+
146
+ except Exception as e:
147
+ logger.error(f"\n✗ Verification failed: {e}")
148
+ logger.exception("Full error details:")
149
+ return False
150
+
151
+
152
+ async def main():
153
+ """Main entry point for verification script."""
154
+ success = await verify_database()
155
+ sys.exit(0 if success else 1)
156
+
157
+
158
+ if __name__ == "__main__":
159
+ asyncio.run(main())
src/main.py ADDED
@@ -0,0 +1,164 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Application Entry Point for Interactive Todo Application (v2.0.0)
3
+
4
+ Owner: Menu/UX Agent
5
+ Purpose: Entry point for the Typer-based CLI
6
+ Architecture: Delegates execution to src/cli.py
7
+
8
+ Constitutional Constraints:
9
+ - ALLOWED: CLI orchestration, startup/shutdown logic
10
+ - FORBIDDEN: SQL queries, Business logic, Direct database access
11
+ """
12
+
13
+ import sys
14
+ import asyncio
15
+ import selectors
16
+ from rich.console import Console
17
+ from rich.prompt import Prompt, IntPrompt
18
+ from rich.panel import Panel
19
+ from rich.table import Table
20
+ from datetime import datetime
21
+
22
+ # Set event loop policy for Windows if needed
23
+ if sys.platform == 'win32':
24
+ asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())
25
+
26
+ from src.cli import add, list_tasks, search, update, delete, complete, history, async_add, async_list_tasks, async_search, async_update, async_delete, async_complete, async_history
27
+ from src.models import Priority, TaskStatus, RecurrenceInterval
28
+ from src.database import init_db
29
+ from src.notification_manager import check_due_tasks_and_notify
30
+
31
+ console = Console()
32
+
33
+ def show_welcome():
34
+ """Display welcome message and instructions."""
35
+ console.print(Panel.fit(
36
+ "[bold cyan]Interactive Todo Application (v2.1.0)[/bold cyan]\n"
37
+ "Advanced Intelligent Task Management",
38
+ title="Welcome",
39
+ border_style="cyan"
40
+ ))
41
+
42
+ async def async_history(task_id: int):
43
+ """Placeholder or delegate to cli implementation."""
44
+ from src.cli import history
45
+ # The history command in cli.py is already async-wrapped
46
+ # But for simplicity, we call the logic directly if available
47
+ from src import services
48
+ from rich.table import Table
49
+
50
+ result = await services.get_task_history(task_id)
51
+ if not result["success"]:
52
+ console.print(f"[red]{result['message']}[/red]")
53
+ return
54
+
55
+ tasks = result["data"]
56
+ table = Table(title=f"Task History Series: {task_id}", header_style="bold cyan")
57
+ table.add_column("ID", justify="right")
58
+ table.add_column("Status")
59
+ table.add_column("Completed Date")
60
+ table.add_column("Due Date")
61
+
62
+ for task in tasks:
63
+ # Convert task to dict if it's a Pydantic model
64
+ t_dict = task.to_dict() if hasattr(task, 'to_dict') else task
65
+ status_icon = "[green]✓[/green]" if t_dict['status'] == TaskStatus.COMPLETED else "[yellow]○[/yellow]"
66
+ completed_str = t_dict['updated_at'].strftime("%Y-%m-%d %H:%M") if t_dict['status'] == TaskStatus.COMPLETED else "-"
67
+ due_str = t_dict['due_date'].strftime("%Y-%m-%d %H:%M") if t_dict['due_date'] else "-"
68
+ table.add_row(str(t_dict['id']), status_icon, completed_str, due_str)
69
+
70
+ console.print(table)
71
+
72
+ async def interactive_loop():
73
+ """Run the application in a highly interactive continuous loop."""
74
+ show_welcome()
75
+
76
+ while True:
77
+ console.print("\n[bold]Main Menu:[/bold]")
78
+ console.print("1. [green]Add[/green] a new task (Interactive Wizard)")
79
+ console.print("2. [blue]List[/blue] all tasks")
80
+ console.print("3. [yellow]Search[/yellow] tasks")
81
+ console.print("4. [magenta]Update[/magenta] a task")
82
+ console.print("5. [cyan]Complete/Toggle[/cyan] a task")
83
+ console.print("6. [white]View History[/white] of a recurring task")
84
+ console.print("7. [red]Delete[/red] a task")
85
+ console.print("0. [grey50]Exit[/grey50]")
86
+
87
+ choice = Prompt.ask("\nChoose an action", choices=["1", "2", "3", "4", "5", "6", "7", "0"], default="2")
88
+
89
+ try:
90
+ if choice == "1": # Add
91
+ await async_add(title="", interactive=True)
92
+
93
+ elif choice == "2": # List
94
+ status_raw = Prompt.ask("Filter by status", choices=["pending", "completed", "all"], default="all")
95
+ prio_raw = Prompt.ask("Filter by priority", choices=["low", "medium", "high", "all"], default="all")
96
+ sort = Prompt.ask("Sort by", choices=["date", "priority", "alpha"], default="date")
97
+
98
+ status_filter = None
99
+ if status_raw != "all":
100
+ status_filter = TaskStatus(status_raw)
101
+
102
+ prio_filter = None
103
+ if prio_raw != "all":
104
+ prio_filter = Priority(prio_raw)
105
+
106
+ await async_list_tasks(
107
+ status=status_filter,
108
+ priority=prio_filter,
109
+ sort=sort
110
+ )
111
+
112
+ elif choice == "3": # Search
113
+ query = Prompt.ask("Enter search keyword")
114
+ await async_search(query=query)
115
+
116
+ elif choice == "4": # Update
117
+ task_id = IntPrompt.ask("Enter Task ID to update")
118
+ await async_update(task_id=task_id, interactive=True)
119
+
120
+ elif choice == "5": # Complete
121
+ task_id = IntPrompt.ask("Enter Task ID to toggle")
122
+ await async_complete(task_id=task_id)
123
+
124
+ elif choice == "6": # History
125
+ task_id = IntPrompt.ask("Enter the original Task ID")
126
+ await async_history(task_id=task_id)
127
+
128
+ elif choice == "7": # Delete
129
+ task_id = IntPrompt.ask("Enter Task ID to delete")
130
+ await async_delete(task_id=task_id)
131
+
132
+ elif choice == "0": # Exit
133
+ console.print("[cyan]Goodbye![/cyan]")
134
+ break
135
+
136
+ except Exception as e:
137
+ console.print(f"[bold red]An error occurred:[/bold red] {e}")
138
+
139
+ async def main():
140
+ """Execute the application. Always enters the primary interactive loop."""
141
+ # Ensure database is initialized before any operations
142
+ try:
143
+ await init_db()
144
+ except Exception as e:
145
+ console.print(f"[bold red]Critical Error during database initialization:[/bold red] {e}")
146
+ sys.exit(1)
147
+
148
+ # Boot check: Notifications for due tasks
149
+ try:
150
+ notified_count = await check_due_tasks_and_notify()
151
+ if notified_count > 0:
152
+ console.print(f"[bold yellow]Reminder:[/bold yellow] You have {notified_count} tasks due soon! (Check OS notifications)")
153
+ except Exception as e:
154
+ # Catch silently as per constraints
155
+ pass
156
+
157
+ try:
158
+ await interactive_loop()
159
+ except KeyboardInterrupt:
160
+ console.print("\n\n[yellow]Application interrupted. Exiting...[/yellow]")
161
+ sys.exit(0)
162
+
163
+ if __name__ == "__main__":
164
+ asyncio.run(main())
src/mcp/__init__.py ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ # backend/src/mcp/__init__.py
2
+ """MCP (Model Context Protocol) package for AI chatbot tools."""
3
+
4
+ from .server import mcp_server
5
+
6
+ __all__ = ["mcp_server"]
src/mcp/server.py ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # backend/src/mcp/server.py
2
+ """
3
+ FastMCP Server for AI Chatbot Task Management
4
+
5
+ Owner: MCP Engineer
6
+ Purpose: MCP tool server for AI agent task operations
7
+ Architecture: FastMCP with FastAPI integration
8
+
9
+ Constitutional Constraints:
10
+ - REQUIRED: All tools enforce user_id isolation (Principle IV)
11
+ - REQUIRED: Tools are the ONLY way AI accesses data (Principle VII)
12
+ - REQUIRED: All tool calls logged for audit trail (Principle VIII)
13
+ """
14
+
15
+ import logging
16
+
17
+ logger = logging.getLogger("mcp.server")
18
+
19
+ # Import the mcp instance from task_tools (tools are registered there)
20
+ from .tools.task_tools import mcp, add_task, list_tasks, complete_task, update_task, delete_task
21
+
22
+ # Re-export as mcp_server for consistency
23
+ mcp_server = mcp
24
+
25
+ logger.info("FastMCP server 'task-tools' initialized with tools: add_task, list_tasks, complete_task, update_task, delete_task")
26
+
27
+ __all__ = ["mcp_server", "add_task", "list_tasks", "complete_task", "update_task", "delete_task"]
src/mcp/tools/__init__.py ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ # backend/src/mcp/tools/__init__.py
2
+ """MCP tools for task management."""
3
+
4
+ from .task_tools import mcp, add_task, list_tasks, complete_task, verify_task_ownership
5
+
6
+ __all__ = ["mcp", "add_task", "list_tasks", "complete_task", "verify_task_ownership"]
src/mcp/tools/task_tools.py ADDED
@@ -0,0 +1,360 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # backend/src/mcp/tools/task_tools.py
2
+ """
3
+ MCP Tools for AI Chatbot Task Management
4
+
5
+ Owner: MCP Engineer
6
+ Purpose: Tool definitions for AI agent task operations
7
+ Architecture: FastMCP tools with async database operations
8
+
9
+ Constitutional Constraints:
10
+ - REQUIRED: All tools enforce user_id isolation (Principle IV)
11
+ - REQUIRED: Tools are the ONLY way AI accesses data (Principle VII)
12
+ - REQUIRED: Ownership double-check before modifications (mcp-ownership-verification)
13
+
14
+ Note: Core functions are defined separately from MCP decorators to allow
15
+ direct calling from the chat endpoint while also exposing them via MCP.
16
+ """
17
+
18
+ import logging
19
+ from typing import Annotated, Optional
20
+ from uuid import UUID
21
+ from fastmcp import FastMCP
22
+ from sqlalchemy.ext.asyncio import AsyncSession
23
+ from sqlalchemy import select, text
24
+
25
+ from src.db.connection import get_session_factory
26
+ from src.db.models import Todo
27
+
28
+ logger = logging.getLogger("mcp.tools.task_tools")
29
+
30
+ # Initialize FastMCP server
31
+ mcp = FastMCP("task-tools")
32
+
33
+
34
+ async def find_task_by_short_id(
35
+ short_id: str,
36
+ user_id: str,
37
+ session: AsyncSession
38
+ ) -> Todo | None:
39
+ """
40
+ Find a task by short ID (first 8 chars of UUID).
41
+
42
+ Uses raw SQL since SQLAlchemy UUID cast doesn't work well.
43
+ """
44
+ # Use raw SQL for the LIKE query on UUID
45
+ query = text("""
46
+ SELECT id, user_id, title, description, is_completed, created_at, updated_at
47
+ FROM todo
48
+ WHERE user_id = :user_id AND CAST(id AS TEXT) LIKE :pattern
49
+ LIMIT 1
50
+ """)
51
+ result = await session.execute(query, {"user_id": user_id, "pattern": f"{short_id}%"})
52
+ row = result.fetchone()
53
+
54
+ if row:
55
+ # Fetch the actual ORM object
56
+ statement = select(Todo).where(Todo.id == row[0], Todo.user_id == user_id)
57
+ orm_result = await session.execute(statement)
58
+ return orm_result.scalar_one_or_none()
59
+ return None
60
+
61
+
62
+ async def verify_task_ownership(
63
+ task_id: str,
64
+ user_id: str,
65
+ session: AsyncSession
66
+ ) -> Todo | None:
67
+ """
68
+ Double-check ownership before modification.
69
+
70
+ Per mcp-ownership-verification skill:
71
+ - Always verify task.user_id matches the authenticated user_id
72
+ - Return None if task doesn't exist OR user doesn't own it
73
+ - Error message must not reveal whether task exists for other users
74
+
75
+ Args:
76
+ task_id: UUID string of the task
77
+ user_id: Authenticated user's ID from JWT sub claim
78
+ session: Active database session
79
+
80
+ Returns:
81
+ Todo if found and owned by user, None otherwise
82
+ """
83
+ try:
84
+ uuid_id = UUID(task_id)
85
+ except ValueError:
86
+ logger.warning(f"Invalid UUID format for task_id: {task_id}")
87
+ return None
88
+
89
+ statement = select(Todo).where(
90
+ Todo.id == uuid_id,
91
+ Todo.user_id == user_id
92
+ )
93
+ result = await session.execute(statement)
94
+ return result.scalar_one_or_none()
95
+
96
+
97
+ # ============================================================================
98
+ # Core tool functions (directly callable)
99
+ # ============================================================================
100
+
101
+ async def add_task_impl(
102
+ user_id: str,
103
+ title: str,
104
+ description: Optional[str] = None
105
+ ) -> str:
106
+ """Create a new task for the user."""
107
+ # Validate title
108
+ if not title or not title.strip():
109
+ return "Error: Title is required and cannot be empty."
110
+
111
+ if len(title) > 200:
112
+ return "Error: Title must be 200 characters or less."
113
+
114
+ session_factory = get_session_factory()
115
+ async with session_factory() as session:
116
+ try:
117
+ task = Todo(
118
+ user_id=user_id,
119
+ title=title.strip(),
120
+ description=description,
121
+ is_completed=False
122
+ )
123
+ session.add(task)
124
+ await session.commit()
125
+ await session.refresh(task)
126
+
127
+ logger.info(f"Task created: {task.id} for user {user_id}")
128
+ return f"Task '{task.title}' added with ID {task.id}."
129
+ except Exception as e:
130
+ await session.rollback()
131
+ logger.error(f"Failed to create task: {e}")
132
+ return "Error: Failed to create task. Please try again."
133
+
134
+
135
+ async def list_tasks_impl(
136
+ user_id: str,
137
+ status: str = "all"
138
+ ) -> str:
139
+ """List the user's tasks with optional status filter."""
140
+ # Validate status
141
+ valid_statuses = ["all", "pending", "completed"]
142
+ if status not in valid_statuses:
143
+ return f"Error: Invalid status '{status}'. Use 'all', 'pending', or 'completed'."
144
+
145
+ session_factory = get_session_factory()
146
+ async with session_factory() as session:
147
+ try:
148
+ statement = select(Todo).where(Todo.user_id == user_id)
149
+
150
+ if status == "pending":
151
+ statement = statement.where(Todo.is_completed == False)
152
+ elif status == "completed":
153
+ statement = statement.where(Todo.is_completed == True)
154
+
155
+ statement = statement.order_by(Todo.created_at.desc())
156
+ result = await session.execute(statement)
157
+ tasks = result.scalars().all()
158
+
159
+ if not tasks:
160
+ return "You have no tasks."
161
+
162
+ status_label = f"{status} " if status != "all" else ""
163
+ lines = [f"Your {status_label}tasks:"]
164
+ for task in tasks:
165
+ icon = "[x]" if task.is_completed else "[ ]"
166
+ # Show full UUID for clarity
167
+ lines.append(f"- ID: {task.id} {icon} {task.title}")
168
+
169
+ logger.info(f"Listed {len(tasks)} tasks for user {user_id}")
170
+ return "\n".join(lines)
171
+ except Exception as e:
172
+ logger.error(f"Failed to list tasks: {e}")
173
+ return "Error: Failed to retrieve tasks. Please try again."
174
+
175
+
176
+ async def complete_task_impl(
177
+ user_id: str,
178
+ task_id: str
179
+ ) -> str:
180
+ """Mark a task as complete. Verifies ownership before modification."""
181
+ # Validate task_id is provided
182
+ if not task_id or not task_id.strip():
183
+ return "Error: Task ID is required. Please use 'show my tasks' to see your tasks with their IDs."
184
+
185
+ task_id = task_id.strip()
186
+
187
+ session_factory = get_session_factory()
188
+ async with session_factory() as session:
189
+ try:
190
+ # Handle short ID (first 8 chars) or full UUID
191
+ if len(task_id) == 8:
192
+ logger.info(f"Using short ID search for task_id: {task_id}")
193
+ task = await find_task_by_short_id(task_id, user_id, session)
194
+ else:
195
+ logger.info(f"Using full UUID search for task_id: {task_id}")
196
+ task = await verify_task_ownership(task_id, user_id, session)
197
+
198
+ if not task:
199
+ return f"Error: Task with ID '{task_id}' not found. Please check the ID and try again."
200
+
201
+ if task.is_completed:
202
+ return f"Task '{task.title}' is already complete."
203
+
204
+ task.is_completed = True
205
+ await session.commit()
206
+
207
+ logger.info(f"Task completed: {task.id} for user {user_id}")
208
+ return f"Task '{task.title}' marked as complete."
209
+ except Exception as e:
210
+ await session.rollback()
211
+ logger.error(f"Failed to complete task: {e}")
212
+ return "Error: Failed to complete task. Please try again."
213
+
214
+
215
+ async def update_task_impl(
216
+ user_id: str,
217
+ task_id: str,
218
+ title: Optional[str] = None,
219
+ description: Optional[str] = None
220
+ ) -> str:
221
+ """Update a task's title or description. Verifies ownership before modification."""
222
+ logger.info(f"update_task_impl called: user_id={user_id}, task_id={task_id}, title={title}, description={description}")
223
+
224
+ # Validate task_id is provided
225
+ if not task_id or not task_id.strip():
226
+ return "Error: Task ID is required. Please use 'show my tasks' to see your tasks with their IDs."
227
+
228
+ task_id = task_id.strip()
229
+
230
+ if not title and description is None:
231
+ return "Error: Provide at least a new title or description to update."
232
+
233
+ session_factory = get_session_factory()
234
+ async with session_factory() as session:
235
+ try:
236
+ # Handle short ID (first 8 chars) or full UUID
237
+ if len(task_id) == 8:
238
+ logger.info(f"Using short ID search for task_id: {task_id}")
239
+ task = await find_task_by_short_id(task_id, user_id, session)
240
+ else:
241
+ logger.info(f"Using full UUID search for task_id: {task_id}")
242
+ task = await verify_task_ownership(task_id, user_id, session)
243
+
244
+ if not task:
245
+ logger.warning(f"Task not found or unauthorized: task_id={task_id}, user_id={user_id}")
246
+ return f"Error: Task with ID '{task_id}' not found. Please check the ID and try again."
247
+
248
+ old_title = task.title
249
+ if title:
250
+ if len(title) > 200:
251
+ return "Error: Title must be 200 characters or less."
252
+ task.title = title.strip()
253
+ if description is not None:
254
+ task.description = description
255
+
256
+ await session.commit()
257
+
258
+ logger.info(f"Task updated: {task.id} for user {user_id}")
259
+ return f"Task updated: '{old_title}' -> '{task.title}'"
260
+ except Exception as e:
261
+ await session.rollback()
262
+ logger.error(f"Failed to update task: {e}")
263
+ return "Error: Failed to update task. Please try again."
264
+
265
+
266
+ async def delete_task_impl(
267
+ user_id: str,
268
+ task_id: str
269
+ ) -> str:
270
+ """Delete a task. Verifies ownership before deletion."""
271
+ # Validate task_id is provided
272
+ if not task_id or not task_id.strip():
273
+ return "Error: Task ID is required. Please use 'show my tasks' to see your tasks with their IDs."
274
+
275
+ task_id = task_id.strip()
276
+
277
+ session_factory = get_session_factory()
278
+ async with session_factory() as session:
279
+ try:
280
+ # Handle short ID (first 8 chars) or full UUID
281
+ if len(task_id) == 8:
282
+ logger.info(f"Using short ID search for task_id: {task_id}")
283
+ task = await find_task_by_short_id(task_id, user_id, session)
284
+ else:
285
+ logger.info(f"Using full UUID search for task_id: {task_id}")
286
+ task = await verify_task_ownership(task_id, user_id, session)
287
+
288
+ if not task:
289
+ return f"Error: Task with ID '{task_id}' not found. Please check the ID and try again."
290
+
291
+ task_title = task.title
292
+ await session.delete(task)
293
+ await session.commit()
294
+
295
+ logger.info(f"Task deleted: {task_id} for user {user_id}")
296
+ return f"Task '{task_title}' has been deleted."
297
+ except Exception as e:
298
+ await session.rollback()
299
+ logger.error(f"Failed to delete task: {e}")
300
+ return "Error: Failed to delete task. Please try again."
301
+
302
+
303
+ # ============================================================================
304
+ # MCP-decorated wrappers (for MCP server exposure)
305
+ # ============================================================================
306
+
307
+ @mcp.tool()
308
+ async def add_task(
309
+ user_id: Annotated[str, "The authenticated user's ID from JWT sub claim"],
310
+ title: Annotated[str, "Title of the task (max 200 characters)"],
311
+ description: Annotated[Optional[str], "Optional description of the task"] = None
312
+ ) -> str:
313
+ """Create a new task for the user."""
314
+ return await add_task_impl(user_id, title, description)
315
+
316
+
317
+ @mcp.tool()
318
+ async def list_tasks(
319
+ user_id: Annotated[str, "The authenticated user's ID from JWT sub claim"],
320
+ status: Annotated[str, "Filter by status: 'all', 'pending', or 'completed'"] = "all"
321
+ ) -> str:
322
+ """List the user's tasks with optional status filter."""
323
+ return await list_tasks_impl(user_id, status)
324
+
325
+
326
+ @mcp.tool()
327
+ async def complete_task(
328
+ user_id: Annotated[str, "The authenticated user's ID from JWT sub claim"],
329
+ task_id: Annotated[str, "The ID (or first 8 characters) of the task to mark as complete"]
330
+ ) -> str:
331
+ """Mark a task as complete. Verifies ownership before modification."""
332
+ return await complete_task_impl(user_id, task_id)
333
+
334
+
335
+ @mcp.tool()
336
+ async def update_task(
337
+ user_id: Annotated[str, "The authenticated user's ID from JWT sub claim"],
338
+ task_id: Annotated[str, "The ID (or first 8 characters) of the task to update"],
339
+ title: Annotated[Optional[str], "New title for the task"] = None,
340
+ description: Annotated[Optional[str], "New description for the task"] = None
341
+ ) -> str:
342
+ """Update a task's title or description. Verifies ownership before modification."""
343
+ return await update_task_impl(user_id, task_id, title, description)
344
+
345
+
346
+ @mcp.tool()
347
+ async def delete_task(
348
+ user_id: Annotated[str, "The authenticated user's ID from JWT sub claim"],
349
+ task_id: Annotated[str, "The ID (or first 8 characters) of the task to delete"]
350
+ ) -> str:
351
+ """Delete a task. Verifies ownership before deletion."""
352
+ return await delete_task_impl(user_id, task_id)
353
+
354
+
355
+ __all__ = [
356
+ "mcp",
357
+ "add_task", "list_tasks", "complete_task", "update_task", "delete_task",
358
+ "add_task_impl", "list_tasks_impl", "complete_task_impl", "update_task_impl", "delete_task_impl",
359
+ "verify_task_ownership"
360
+ ]
src/menu.py ADDED
@@ -0,0 +1,345 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Menu/UX Layer for Interactive Todo Application
3
+
4
+ Owner: Menu/UX Agent
5
+ Purpose: Display menus, collect user input, render task lists
6
+
7
+ Constitutional Constraints:
8
+ - ALLOWED: Menu display (print()), User input (input()), Input validation, Service layer calls
9
+ - FORBIDDEN: SQL queries, Database connections, Business logic validation, Schema changes
10
+ """
11
+
12
+ from typing import Optional
13
+ from models import Task
14
+ import services
15
+
16
+
17
+ def display_menu() -> None:
18
+ """
19
+ Display main menu options to user.
20
+
21
+ Menu Options:
22
+ 1. Create New Task
23
+ 2. View All Tasks
24
+ 3. Update Task
25
+ 4. Toggle Task Completion
26
+ 5. Delete Task
27
+ 6. Exit
28
+
29
+ Constitutional Compliance:
30
+ ✅ Display only (no input collection)
31
+ ✅ NO SQL queries
32
+ ✅ NO business logic
33
+ """
34
+ print("\n" + "=" * 50)
35
+ print(" INTERACTIVE TODO APPLICATION")
36
+ print("=" * 50)
37
+ print("1. Create New Task")
38
+ print("2. View All Tasks")
39
+ print("3. Update Task")
40
+ print("4. Toggle Task Completion")
41
+ print("5. Delete Task")
42
+ print("6. Exit")
43
+ print("=" * 50)
44
+
45
+
46
+ def get_menu_choice() -> str:
47
+ """
48
+ Get and validate menu selection from user.
49
+
50
+ Returns:
51
+ User's menu choice as string ('1' through '6')
52
+
53
+ Implementation Notes:
54
+ - Prompts user for input
55
+ - Validates choice is in valid range (1-6)
56
+ - Loops until valid input received
57
+ - Returns validated choice as string
58
+
59
+ Constitutional Compliance:
60
+ ✅ Input validation (format only)
61
+ ✅ NO business logic validation
62
+ ✅ NO database operations
63
+ """
64
+ while True:
65
+ choice = input("\nEnter your choice (1-6): ").strip()
66
+
67
+ if choice in ['1', '2', '3', '4', '5', '6']:
68
+ return choice
69
+ else:
70
+ print("Invalid choice. Please enter a number between 1 and 6.")
71
+
72
+
73
+ def handle_create_task(conn) -> None:
74
+ """
75
+ Collect task details and create task via service layer.
76
+
77
+ Args:
78
+ conn: Active database connection to pass to service layer
79
+
80
+ Implementation Notes:
81
+ - Prompts for title (required)
82
+ - Prompts for description (optional)
83
+ - Validates input is non-empty for title
84
+ - Calls services.create_task() with connection
85
+ - Displays success or error message from service layer
86
+
87
+ Constitutional Compliance:
88
+ ✅ Input collection only
89
+ ✅ Calls service layer for business logic
90
+ ✅ NO SQL queries
91
+ ✅ NO business validation (delegates to service layer)
92
+ """
93
+ print("\n--- Create New Task ---")
94
+
95
+ # Collect title (required)
96
+ title = input("Enter task title: ").strip()
97
+
98
+ if not title:
99
+ print("Error: Title cannot be empty.")
100
+ return
101
+
102
+ # Collect description (optional)
103
+ description = input("Enter task description (optional, press Enter to skip): ").strip()
104
+
105
+ # If description is empty string, pass None
106
+ if not description:
107
+ description = None
108
+
109
+ # Call service layer to create task
110
+ result = services.create_task(conn, title, description)
111
+
112
+ # Display result from service layer
113
+ if result['success']:
114
+ print(f"\n✓ {result['message']}")
115
+ else:
116
+ print(f"\n✗ {result['message']}")
117
+
118
+
119
+ def format_task_display(task: Task) -> str:
120
+ """
121
+ Format task for terminal display.
122
+
123
+ Args:
124
+ task: Task object to format
125
+
126
+ Returns:
127
+ Formatted string with status icon, ID, title, and description
128
+
129
+ Format:
130
+ [✓] #123: Task title - Description preview...
131
+ [○] #456: Another task
132
+
133
+ Implementation Notes:
134
+ - Uses ✓ for completed tasks, ○ for incomplete tasks
135
+ - Shows task ID, title, and truncated description
136
+ - Leverages Task.__str__() method for consistent formatting
137
+
138
+ Constitutional Compliance:
139
+ ✅ Display formatting only
140
+ ✅ NO business logic
141
+ ✅ NO database operations
142
+ """
143
+ return str(task)
144
+
145
+
146
+ def handle_list_tasks(conn) -> None:
147
+ """
148
+ Display all tasks in readable format via service layer.
149
+
150
+ Args:
151
+ conn: Active database connection to pass to service layer
152
+
153
+ Implementation Notes:
154
+ - Calls services.list_tasks() with connection
155
+ - Formats and displays each task using format_task_display()
156
+ - Shows count of tasks
157
+ - Displays message if no tasks exist
158
+
159
+ Constitutional Compliance:
160
+ ✅ Display only
161
+ ✅ Calls service layer for data retrieval
162
+ ✅ NO SQL queries
163
+ ✅ NO business logic
164
+ """
165
+ print("\n--- All Tasks ---")
166
+
167
+ # Call service layer to retrieve tasks
168
+ result = services.list_tasks(conn)
169
+
170
+ if not result['success']:
171
+ print(f"\n✗ {result['message']}")
172
+ return
173
+
174
+ tasks = result['tasks']
175
+
176
+ if not tasks:
177
+ print("\nNo tasks found. Create your first task!")
178
+ return
179
+
180
+ print(f"\nTotal tasks: {len(tasks)}\n")
181
+
182
+ # Display each task
183
+ for task in tasks:
184
+ print(format_task_display(task))
185
+
186
+
187
+ def handle_update_task(conn) -> None:
188
+ """
189
+ Collect task ID and new details, update task via service layer.
190
+
191
+ Args:
192
+ conn: Active database connection to pass to service layer
193
+
194
+ Implementation Notes:
195
+ - Prompts for task ID
196
+ - Validates ID is a positive integer
197
+ - Prompts for new title (optional)
198
+ - Prompts for new description (optional)
199
+ - Ensures at least one field is provided
200
+ - Calls services.update_task() with connection
201
+ - Displays success or error message from service layer
202
+
203
+ Constitutional Compliance:
204
+ ✅ Input collection and format validation
205
+ ✅ Calls service layer for business logic
206
+ ✅ NO SQL queries
207
+ ✅ NO business validation (delegates to service layer)
208
+ """
209
+ print("\n--- Update Task ---")
210
+
211
+ # Collect task ID
212
+ task_id_input = input("Enter task ID to update: ").strip()
213
+
214
+ try:
215
+ task_id = int(task_id_input)
216
+ if task_id <= 0:
217
+ print("Error: Task ID must be a positive integer.")
218
+ return
219
+ except ValueError:
220
+ print("Error: Invalid task ID. Please enter a number.")
221
+ return
222
+
223
+ # Collect new title (optional)
224
+ print("\nLeave field empty to keep current value:")
225
+ new_title = input("Enter new title (or press Enter to skip): ").strip()
226
+
227
+ # If empty, set to None to indicate no change
228
+ if not new_title:
229
+ new_title = None
230
+
231
+ # Collect new description (optional)
232
+ new_description = input("Enter new description (or press Enter to skip): ").strip()
233
+
234
+ # If empty, set to None to indicate no change
235
+ if not new_description:
236
+ new_description = None
237
+
238
+ # Validate at least one field is provided
239
+ if new_title is None and new_description is None:
240
+ print("Error: Must provide at least one field to update (title or description).")
241
+ return
242
+
243
+ # Call service layer to update task
244
+ result = services.update_task(conn, task_id, new_title, new_description)
245
+
246
+ # Display result from service layer
247
+ if result['success']:
248
+ print(f"\n✓ {result['message']}")
249
+ else:
250
+ print(f"\n✗ {result['message']}")
251
+
252
+
253
+ def handle_toggle_task(conn) -> None:
254
+ """
255
+ Collect task ID and toggle completion via service layer.
256
+
257
+ Args:
258
+ conn: Active database connection to pass to service layer
259
+
260
+ Implementation Notes:
261
+ - Prompts for task ID
262
+ - Validates ID is a positive integer
263
+ - Calls services.toggle_task_completion() with connection
264
+ - Displays success or error message from service layer
265
+
266
+ Constitutional Compliance:
267
+ ✅ Input collection and format validation
268
+ ✅ Calls service layer for business logic
269
+ ✅ NO SQL queries
270
+ ✅ NO business logic
271
+ """
272
+ print("\n--- Toggle Task Completion ---")
273
+
274
+ # Collect task ID
275
+ task_id_input = input("Enter task ID to toggle: ").strip()
276
+
277
+ try:
278
+ task_id = int(task_id_input)
279
+ if task_id <= 0:
280
+ print("Error: Task ID must be a positive integer.")
281
+ return
282
+ except ValueError:
283
+ print("Error: Invalid task ID. Please enter a number.")
284
+ return
285
+
286
+ # Call service layer to toggle task completion
287
+ result = services.toggle_task_completion(conn, task_id)
288
+
289
+ # Display result from service layer
290
+ if result['success']:
291
+ print(f"\n✓ {result['message']}")
292
+ else:
293
+ print(f"\n✗ {result['message']}")
294
+
295
+
296
+ def handle_delete_task(conn) -> None:
297
+ """
298
+ Collect task ID and delete task via service layer.
299
+
300
+ Args:
301
+ conn: Active database connection to pass to service layer
302
+
303
+ Implementation Notes:
304
+ - Prompts for task ID
305
+ - Validates ID is a positive integer
306
+ - Prompts for confirmation (destructive action)
307
+ - Calls services.delete_task() with connection
308
+ - Displays success or error message from service layer
309
+
310
+ Constitutional Compliance:
311
+ ✅ Input collection and format validation
312
+ ✅ Confirmation prompt for destructive action
313
+ ✅ Calls service layer for business logic
314
+ ✅ NO SQL queries
315
+ ✅ NO business logic
316
+ """
317
+ print("\n--- Delete Task ---")
318
+
319
+ # Collect task ID
320
+ task_id_input = input("Enter task ID to delete: ").strip()
321
+
322
+ try:
323
+ task_id = int(task_id_input)
324
+ if task_id <= 0:
325
+ print("Error: Task ID must be a positive integer.")
326
+ return
327
+ except ValueError:
328
+ print("Error: Invalid task ID. Please enter a number.")
329
+ return
330
+
331
+ # Confirmation prompt for destructive action
332
+ confirmation = input(f"Are you sure you want to delete task #{task_id}? (yes/no): ").strip().lower()
333
+
334
+ if confirmation not in ['yes', 'y']:
335
+ print("Deletion cancelled.")
336
+ return
337
+
338
+ # Call service layer to delete task
339
+ result = services.delete_task(conn, task_id)
340
+
341
+ # Display result from service layer
342
+ if result['success']:
343
+ print(f"\n✓ {result['message']}")
344
+ else:
345
+ print(f"\n✗ {result['message']}")
src/models/__init__.py ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ # backend/src/models/__init__.py
2
+ """Database models package."""
3
+
4
+ from .conversation import Conversation
5
+ from .message import Message
6
+
7
+ __all__ = ["Conversation", "Message"]
src/models/conversation.py ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # backend/src/models/conversation.py
2
+ """Conversation model for AI chatbot feature."""
3
+
4
+ from sqlmodel import SQLModel, Field
5
+ from datetime import datetime
6
+ from typing import Optional
7
+
8
+
9
+ class Conversation(SQLModel, table=True):
10
+ """Represents a chat thread between a user and the AI assistant."""
11
+ __tablename__ = "conversations"
12
+
13
+ id: Optional[int] = Field(default=None, primary_key=True)
14
+ user_id: str = Field(index=True, nullable=False)
15
+ title: str = Field(max_length=100, nullable=False)
16
+ created_at: datetime = Field(default_factory=datetime.utcnow)
17
+ updated_at: datetime = Field(default_factory=datetime.utcnow)
src/models/message.py ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # backend/src/models/message.py
2
+ """Message model for AI chatbot feature."""
3
+
4
+ from sqlmodel import SQLModel, Field, Column
5
+ from sqlalchemy import JSON
6
+ from datetime import datetime
7
+ from typing import Optional, List, Any
8
+
9
+
10
+ class Message(SQLModel, table=True):
11
+ """Represents a single message within a conversation."""
12
+ __tablename__ = "messages"
13
+
14
+ id: Optional[int] = Field(default=None, primary_key=True)
15
+ conversation_id: int = Field(foreign_key="conversations.id", index=True, nullable=False)
16
+ user_id: str = Field(index=True, nullable=False)
17
+ role: str = Field(max_length=20, nullable=False) # "user" or "assistant"
18
+ content: str = Field(nullable=False)
19
+ tool_calls: Optional[List[Any]] = Field(default=None, sa_column=Column(JSON))
20
+ created_at: datetime = Field(default_factory=datetime.utcnow, index=True)
src/models_old.py ADDED
@@ -0,0 +1,147 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Task Data Model for Interactive Todo Application
3
+
4
+ Owner: Service Logic Agent
5
+ Purpose: Task entity definition, enums, and structured models for task management
6
+
7
+ Constitutional Constraints:
8
+ - ALLOWED: Data model definitions, conversion methods
9
+ - FORBIDDEN: User input (input()), User output (print()), Database connections, Business logic
10
+ """
11
+
12
+ from enum import Enum
13
+ from datetime import datetime
14
+ from typing import Optional
15
+ from pydantic import BaseModel, Field, ConfigDict
16
+
17
+
18
+ class Priority(str, Enum):
19
+ """Priority levels for tasks."""
20
+ LOW = 'low'
21
+ MEDIUM = 'medium'
22
+ HIGH = 'high'
23
+
24
+
25
+ class RecurrenceInterval(str, Enum):
26
+ """Recurrence interval for tasks."""
27
+ NONE = 'none'
28
+ DAILY = 'daily'
29
+ WEEKLY = 'weekly'
30
+ MONTHLY = 'monthly'
31
+
32
+
33
+ class TaskStatus(str, Enum):
34
+ """Completion status for tasks."""
35
+ PENDING = 'pending'
36
+ COMPLETED = 'completed'
37
+
38
+
39
+ class TaskCreate(BaseModel):
40
+ """Schema for creating a new task."""
41
+ title: str = Field(min_length=1, max_length=255)
42
+ description: Optional[str] = None
43
+ priority: Priority = Priority.MEDIUM
44
+ category: Optional[str] = None
45
+ due_date: Optional[datetime] = None
46
+ recurrence_interval: RecurrenceInterval = RecurrenceInterval.NONE
47
+
48
+ model_config = ConfigDict(use_enum_values=True)
49
+
50
+
51
+ class TaskUpdate(BaseModel):
52
+ """Schema for updating an existing task."""
53
+ title: Optional[str] = Field(default=None, min_length=1, max_length=255)
54
+ description: Optional[str] = None
55
+ priority: Optional[Priority] = None
56
+ category: Optional[str] = None
57
+ due_date: Optional[datetime] = None
58
+ status: Optional[TaskStatus] = None
59
+ recurrence_interval: Optional[RecurrenceInterval] = None
60
+
61
+ model_config = ConfigDict(use_enum_values=True)
62
+
63
+
64
+ class Task(BaseModel):
65
+ """
66
+ Task entity representing a todo item.
67
+
68
+ Attributes:
69
+ id: Unique task identifier
70
+ title: Task title (1-255 characters)
71
+ description: Optional detailed description
72
+ priority: Priority level (low, medium, high)
73
+ category: Optional category name
74
+ due_date: Optional due date timestamp
75
+ status: Task completion status (pending, completed)
76
+ recurrence_interval: Recurrence interval (daily, weekly, monthly, none)
77
+ parent_task_id: Reference to parent task (for recurring task instances)
78
+ reminder_sent: Whether notification sent
79
+ created_at: Creation timestamp
80
+ updated_at: Last modification timestamp
81
+
82
+ Constitutional Compliance:
83
+ ✅ Pure data model (no behavior)
84
+ ✅ NO user interaction
85
+ ✅ NO database access
86
+ """
87
+ id: int
88
+ title: str = Field(min_length=1, max_length=255)
89
+ description: Optional[str] = None
90
+ priority: Priority = Priority.MEDIUM
91
+ category: Optional[str] = None
92
+ due_date: Optional[datetime] = None
93
+ status: TaskStatus = TaskStatus.PENDING
94
+ recurrence_interval: RecurrenceInterval = RecurrenceInterval.NONE
95
+ parent_task_id: Optional[int] = None
96
+ reminder_sent: bool = False
97
+ created_at: datetime
98
+ updated_at: datetime
99
+
100
+ model_config = ConfigDict(use_enum_values=True, from_attributes=True)
101
+
102
+ def to_dict(self) -> dict:
103
+ """
104
+ Convert Task to dictionary representation.
105
+
106
+ Returns:
107
+ Dictionary with all task fields, timestamps in ISO format
108
+ """
109
+ return self.model_dump()
110
+
111
+ @classmethod
112
+ def from_db_row(cls, row: tuple) -> 'Task':
113
+ """
114
+ Create Task from database row tuple.
115
+
116
+ Args:
117
+ row: Database row as tuple.
118
+ Expects: (id, title, description, priority, category, due_date, is_completed, recurrence_interval, parent_task_id, reminder_sent, created_at, updated_at)
119
+
120
+ Returns:
121
+ Task instance populated from database row
122
+ """
123
+ # Convert boolean is_completed to TaskStatus enum
124
+ is_completed = row[6]
125
+ status = TaskStatus.COMPLETED if is_completed else TaskStatus.PENDING
126
+
127
+ return cls(
128
+ id=row[0],
129
+ title=row[1],
130
+ description=row[2],
131
+ priority=Priority(row[3]),
132
+ category=row[4],
133
+ due_date=row[5],
134
+ status=status,
135
+ recurrence_interval=RecurrenceInterval(row[7]),
136
+ parent_task_id=row[8],
137
+ reminder_sent=row[9],
138
+ created_at=row[10],
139
+ updated_at=row[11]
140
+ )
141
+
142
+ def __str__(self) -> str:
143
+ """String representation for display."""
144
+ icon = "✓" if self.status == TaskStatus.COMPLETED else "○"
145
+ priority_tag = f" [{self.priority.upper()}]"
146
+ due_tag = f" (Due: {self.due_date.strftime('%Y-%m-%d')})" if self.due_date else ""
147
+ return f"[{icon}]{priority_tag} #{self.id}: {self.title}{due_tag}"
src/notification_manager.py ADDED
@@ -0,0 +1,97 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Notification Manager for Interactive Todo Application
3
+
4
+ Owner: Service Logic Agent
5
+ Purpose: Handle cross-platform desktop notifications and boot checks for due tasks
6
+ Architecture: 100% async/await, graceful degradation if plyer unsupported
7
+
8
+ Constitutional Compliance:
9
+ - ✅ Service Logic Agent ownership
10
+ - ✅ NO database connections (must use repository layer)
11
+ - ✅ NO user interaction (input(), print())
12
+ - ✅ NO Rich UI (system notifications only)
13
+ - ✅ All functions async
14
+ - ✅ Graceful degradation if notifications unsupported
15
+ """
16
+
17
+ import logging
18
+ from datetime import datetime, timedelta
19
+ from plyer import notification
20
+ from src.repository import get_all_tasks, update_task
21
+
22
+ logger = logging.getLogger("notification_manager")
23
+
24
+ async def show_notification(title: str, message: str) -> bool:
25
+ """
26
+ Display cross-platform desktop notification.
27
+
28
+ Args:
29
+ title: Notification title
30
+ message: Notification message body
31
+
32
+ Returns:
33
+ True if successful, False otherwise
34
+ """
35
+ try:
36
+ # notification.notify is a synchronous call but usually very fast
37
+ #plyer handles platform-specific details internally
38
+ notification.notify(
39
+ title=title,
40
+ message=message,
41
+ app_name="Todo CLI",
42
+ timeout=10 # seconds
43
+ )
44
+ return True
45
+ except Exception as e:
46
+ # Catch silently as per constraints
47
+ logger.warning(f"OS notification failed: {e}")
48
+ return False
49
+
50
+ async def check_due_tasks_and_notify() -> int:
51
+ """
52
+ Find tasks due within 30 minutes and send notifications.
53
+
54
+ Returns:
55
+ Number of tasks notified
56
+ """
57
+ try:
58
+ now = datetime.now()
59
+ time_threshold = now + timedelta(minutes=30)
60
+
61
+ # Query all tasks (we'll filter in memory for precision)
62
+ tasks = await get_all_tasks(status='pending')
63
+
64
+ # Filter for tasks due within 30 minutes that haven't been notified
65
+ due_tasks = [
66
+ t for t in tasks
67
+ if t.due_date
68
+ and t.due_date >= now # Only upcoming ones
69
+ and t.due_date <= time_threshold
70
+ and not t.reminder_sent
71
+ ]
72
+
73
+ if not due_tasks:
74
+ return 0
75
+
76
+ # Send notification
77
+ if len(due_tasks) == 1:
78
+ task = due_tasks[0]
79
+ title = "Task Due Soon"
80
+ message = f"'{task.title}' is due at {task.due_date.strftime('%H:%M')}"
81
+ else:
82
+ title = f"{len(due_tasks)} Tasks Due Soon"
83
+ message = f"You have Multiple tasks due within 30 minutes."
84
+
85
+ # Show notification (silent failure if daemon missing)
86
+ await show_notification(title, message)
87
+
88
+ # Mark as notified in database
89
+ for task in due_tasks:
90
+ await update_task(task.id, reminder_sent=True)
91
+
92
+ logger.info(f"Notified about {len(due_tasks)} upcoming tasks.")
93
+ return len(due_tasks)
94
+
95
+ except Exception as e:
96
+ logger.error(f"Error during due task check: {e}")
97
+ return 0
src/recurrence_engine.py ADDED
@@ -0,0 +1,103 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Recurrence Engine for Interactive Todo Application
3
+
4
+ Owner: Service Logic Agent
5
+ Purpose: Calculate next due dates and manage recurring task instances
6
+ Architecture: 100% async/await, interval-based arithmetic
7
+
8
+ Constitutional Compliance:
9
+ - ✅ Service Logic Agent ownership
10
+ - ✅ NO database connections (must use repository layer)
11
+ - ✅ NO user interaction (input(), print())
12
+ - ✅ NO Rich UI (business logic only)
13
+ - ✅ All functions async
14
+ """
15
+
16
+ import logging
17
+ from datetime import datetime, timedelta
18
+ from typing import Optional
19
+ from dateutil.relativedelta import relativedelta
20
+ from src.models import TaskCreate, RecurrenceInterval
21
+ from src.repository import get_task_by_id, create_task, update_task
22
+
23
+ logger = logging.getLogger("recurrence_engine")
24
+
25
+ async def calculate_next_due_date(
26
+ current_due_date: datetime,
27
+ recurrence_interval: str
28
+ ) -> Optional[datetime]:
29
+ """
30
+ Calculate next occurrence based on recurrence interval.
31
+
32
+ Args:
33
+ current_due_date: Current task's due date
34
+ recurrence_interval: Interval string (daily, weekly, monthly, none)
35
+
36
+ Returns:
37
+ Next due date or None if interval is none
38
+ """
39
+ if recurrence_interval == RecurrenceInterval.DAILY:
40
+ return current_due_date + timedelta(days=1)
41
+ elif recurrence_interval == RecurrenceInterval.WEEKLY:
42
+ return current_due_date + relativedelta(weeks=1)
43
+ elif recurrence_interval == RecurrenceInterval.MONTHLY:
44
+ return current_due_date + relativedelta(months=1)
45
+ else: # "none" or invalid
46
+ return None
47
+
48
+ async def create_recurring_task_instance(
49
+ completed_task_id: int,
50
+ current_due_date: Optional[datetime],
51
+ recurrence_interval: str
52
+ ) -> Optional[int]:
53
+ """
54
+ Create new pending instance when recurring task completed.
55
+
56
+ Args:
57
+ completed_task_id: ID of the just-completed task
58
+ current_due_date: Due date of completed task
59
+ recurrence_interval: Recurrence interval string
60
+
61
+ Returns:
62
+ ID of newly created task or None
63
+ """
64
+ # Skip if no recurrence or invalid
65
+ if recurrence_interval == RecurrenceInterval.NONE or recurrence_interval is None:
66
+ return None
67
+
68
+ # Fetch completed task details
69
+ completed_task = await get_task_by_id(completed_task_id)
70
+ if not completed_task:
71
+ logger.warning(f"Failed to find completed task {completed_task_id} for recurrence")
72
+ return None
73
+
74
+ # Calculate next due date
75
+ next_due_date = None
76
+ if current_due_date:
77
+ next_due_date = await calculate_next_due_date(
78
+ current_due_date,
79
+ recurrence_interval
80
+ )
81
+
82
+ # Process creation logic
83
+ try:
84
+ # Create new pending instance with same attributes
85
+ created_task = await create_task(
86
+ title=completed_task.title,
87
+ description=completed_task.description,
88
+ priority=completed_task.priority.value,
89
+ category=completed_task.category,
90
+ due_date=next_due_date,
91
+ recurrence_interval=recurrence_interval,
92
+ parent_task_id=completed_task_id
93
+ )
94
+
95
+ if created_task:
96
+ logger.info(f"Created recurring task instance: {created_task.id} (parent: {completed_task_id})")
97
+ return created_task.id
98
+
99
+ except Exception as e:
100
+ logger.error(f"Failed to create recurring task instance: {e}")
101
+ return None
102
+
103
+ return None
src/repository.py ADDED
@@ -0,0 +1,281 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Repository Layer for Interactive Todo Application (v2.0.0)
3
+
4
+ Owner: Database Agent
5
+ Purpose: Data persistence and retrieval logic for tasks
6
+ Architecture: Async/Await with PostgreSQL using psycopg3
7
+
8
+ Constitutional Constraints:
9
+ - ALLOWED: CRUD operations, SQL queries, parameterized inputs, async implementation
10
+ - FORBIDDEN: User interaction (input/print), direct database connections (must use database.py),
11
+ business logic validation, UI formatting.
12
+
13
+ All functions use full column sets to remain consistent with Task.from_db_row.
14
+ """
15
+
16
+ import logging
17
+ from typing import List, Optional, Any
18
+ from datetime import datetime
19
+ from src.database import db_manager
20
+ from src.models import Task, Priority, TaskStatus
21
+
22
+ logger = logging.getLogger("repository")
23
+
24
+ # Full column set to ensure consistency across all SELECT queries
25
+ FULL_COLUMN_SET = (
26
+ "id, title, description, priority, category, due_date, "
27
+ "is_completed, recurrence_interval, parent_task_id, "
28
+ "reminder_sent, created_at, updated_at"
29
+ )
30
+
31
+ async def create_task(title: str, description: Optional[str] = None,
32
+ priority: str = 'medium', category: Optional[str] = None,
33
+ due_date: Optional[datetime] = None,
34
+ recurrence_interval: str = 'none',
35
+ parent_task_id: Optional[int] = None) -> Task:
36
+ """
37
+ Create a new task in the database.
38
+
39
+ Args:
40
+ title: Task title
41
+ description: Optional description
42
+ priority: Task priority (low, medium, high)
43
+ category: Optional category
44
+ due_date: Optional due date
45
+ recurrence_interval: Recurrence interval (daily, weekly, monthly, none)
46
+ parent_task_id: Optional parent task ID
47
+
48
+ Returns:
49
+ The newly created Task object
50
+ """
51
+ async with await db_manager.get_connection() as conn:
52
+ async with conn.cursor() as cur:
53
+ await cur.execute(
54
+ f"""
55
+ INSERT INTO tasks (title, description, priority, category, due_date,
56
+ recurrence_interval, parent_task_id)
57
+ VALUES (%s, %s, %s, %s, %s, %s, %s)
58
+ RETURNING {FULL_COLUMN_SET}
59
+ """,
60
+ (title, description, priority, category, due_date,
61
+ recurrence_interval, parent_task_id)
62
+ )
63
+ row = await cur.fetchone()
64
+ await conn.commit()
65
+
66
+ # row: (id, title, description, priority, category, due_date,
67
+ # is_completed, recurrence_interval, parent_task_id,
68
+ # reminder_sent, created_at, updated_at)
69
+ # models.Task.from_db_row expects this exact order and content
70
+ return Task.from_db_row(row)
71
+
72
+ async def get_all_tasks(status: Optional[str] = None,
73
+ category: Optional[str] = None,
74
+ priority: Optional[str] = None,
75
+ parent_task_id: Optional[int] = None,
76
+ recurrence_interval: Optional[str] = None,
77
+ due_before: Optional[datetime] = None,
78
+ due_after: Optional[datetime] = None,
79
+ sort_by: str = 'date') -> List[Task]:
80
+ """
81
+ Retrieve all tasks with optional filters and sorting.
82
+
83
+ Args:
84
+ status: Filter by completion status ('completed', 'pending')
85
+ category: Filter by category
86
+ priority: Filter by priority
87
+ parent_task_id: Filter by parent task (for task history)
88
+ recurrence_interval: Filter by recurrence interval
89
+ due_before: Filter by due date before this time
90
+ due_after: Filter by due date after this time
91
+ sort_by: Sorting method ('date', 'alpha', 'priority')
92
+
93
+ Returns:
94
+ List of Task objects
95
+ """
96
+ query = f"SELECT {FULL_COLUMN_SET} FROM tasks"
97
+ conditions = []
98
+ params = []
99
+
100
+ if status == 'completed':
101
+ conditions.append("is_completed = TRUE")
102
+ elif status == 'pending':
103
+ conditions.append("is_completed = FALSE")
104
+
105
+ if category:
106
+ conditions.append("category = %s")
107
+ params.append(category)
108
+
109
+ if priority:
110
+ conditions.append("priority = %s")
111
+ params.append(priority)
112
+
113
+ if parent_task_id:
114
+ conditions.append("parent_task_id = %s")
115
+ params.append(parent_task_id)
116
+
117
+ if recurrence_interval:
118
+ conditions.append("recurrence_interval = %s")
119
+ params.append(recurrence_interval)
120
+
121
+ if due_before:
122
+ conditions.append("due_date <= %s")
123
+ params.append(due_before)
124
+
125
+ if due_after:
126
+ conditions.append("due_date >= %s")
127
+ params.append(due_after)
128
+
129
+ if conditions:
130
+ query += " WHERE " + " AND ".join(conditions)
131
+
132
+ # Sorting logic
133
+ if sort_by == 'priority':
134
+ query += """ ORDER BY CASE
135
+ WHEN priority = 'high' THEN 1
136
+ WHEN priority = 'medium' THEN 2
137
+ WHEN priority = 'low' THEN 3
138
+ ELSE 4 END, created_at DESC"""
139
+ elif sort_by == 'alpha':
140
+ query += ' ORDER BY title COLLATE "C" ASC'
141
+ else: # default 'date'
142
+ query += " ORDER BY due_date ASC NULLS LAST, created_at DESC"
143
+
144
+ async with await db_manager.get_connection() as conn:
145
+ async with conn.cursor() as cur:
146
+ await cur.execute(query, params)
147
+ rows = await cur.fetchall()
148
+ return [Task.from_db_row(row) for row in rows]
149
+
150
+ async def update_task(task_id: int, **kwargs) -> Optional[Task]:
151
+ """
152
+ Update an existing task.
153
+
154
+ Args:
155
+ task_id: ID of the task to update
156
+ **kwargs: Fields to update (title, description, priority, category, due_date, is_completed, recurrence_interval, parent_task_id, reminder_sent)
157
+
158
+ Returns:
159
+ Updated Task object or None if not found
160
+ """
161
+ # handle reminder_sent reset on due_date change
162
+ if 'due_date' in kwargs and 'reminder_sent' not in kwargs:
163
+ kwargs['reminder_sent'] = False
164
+
165
+ # Filter out None values or handle specific field mapping if necessary
166
+ # is_completed might be passed instead of status based on previous implementation
167
+ if 'status' in kwargs and 'is_completed' not in kwargs:
168
+ kwargs['is_completed'] = (kwargs.pop('status') == TaskStatus.COMPLETED)
169
+
170
+ # Only keep non-None values to avoid updating with NULL where not allowed
171
+ kwargs = {k: v for k, v in kwargs.items() if v is not None}
172
+
173
+ if not kwargs:
174
+ return await get_task_by_id(task_id)
175
+
176
+ kwargs['updated_at'] = datetime.now()
177
+
178
+ # Use parameterized query for security
179
+ columns = []
180
+ params = []
181
+ for k, v in kwargs.items():
182
+ columns.append(f"{k} = %s")
183
+ params.append(v)
184
+
185
+ set_clause = ", ".join(columns)
186
+ params.append(task_id)
187
+
188
+ query = f"UPDATE tasks SET {set_clause} WHERE id = %s RETURNING {FULL_COLUMN_SET}"
189
+
190
+ async with await db_manager.get_connection() as conn:
191
+ async with conn.cursor() as cur:
192
+ await cur.execute(query, params)
193
+ row = await cur.fetchone()
194
+ await conn.commit()
195
+ if row:
196
+ return Task.from_db_row(row)
197
+ return None
198
+
199
+ async def delete_task(task_id: int) -> bool:
200
+ """
201
+ Delete a task from the database.
202
+
203
+ Args:
204
+ task_id: ID of the task to delete
205
+
206
+ Returns:
207
+ True if deleted, False otherwise
208
+ """
209
+ async with await db_manager.get_connection() as conn:
210
+ async with conn.cursor() as cur:
211
+ await cur.execute("DELETE FROM tasks WHERE id = %s", (task_id,))
212
+ result = cur.rowcount > 0
213
+ await conn.commit()
214
+ return result
215
+
216
+ async def search_tasks(query: str) -> List[Task]:
217
+ """
218
+ Search for tasks by title or description.
219
+
220
+ Args:
221
+ query: Search string
222
+
223
+ Returns:
224
+ List of matching Task objects
225
+ """
226
+ search_term = f"%{query}%"
227
+ sql = f"""
228
+ SELECT {FULL_COLUMN_SET}
229
+ FROM tasks
230
+ WHERE title ILIKE %s OR description ILIKE %s
231
+ ORDER BY created_at DESC
232
+ """
233
+ async with await db_manager.get_connection() as conn:
234
+ async with conn.cursor() as cur:
235
+ await cur.execute(sql, (search_term, search_term))
236
+ rows = await cur.fetchall()
237
+ return [Task.from_db_row(row) for row in rows]
238
+
239
+ async def get_task_by_id(task_id: int) -> Optional[Task]:
240
+ """
241
+ Retrieve a single task by ID.
242
+
243
+ Args:
244
+ task_id: Task ID
245
+
246
+ Returns:
247
+ Task object or None if not found
248
+ """
249
+ async with await db_manager.get_connection() as conn:
250
+ async with conn.cursor() as cur:
251
+ await cur.execute(
252
+ f"SELECT {FULL_COLUMN_SET} FROM tasks WHERE id = %s",
253
+ (task_id,)
254
+ )
255
+ row = await cur.fetchone()
256
+ if row:
257
+ return Task.from_db_row(row)
258
+ return None
259
+
260
+ async def get_task_history(root_task_id: int) -> List[Task]:
261
+ """
262
+ Get all instances of a recurring task series.
263
+
264
+ Args:
265
+ root_task_id: ID of the root task
266
+
267
+ Returns:
268
+ List of Task objects in the series
269
+ """
270
+ async with await db_manager.get_connection() as conn:
271
+ async with conn.cursor() as cur:
272
+ # Query: root task OR any task with parent_task_id = root_task_id
273
+ query = f"""
274
+ SELECT {FULL_COLUMN_SET}
275
+ FROM tasks
276
+ WHERE id = %s OR parent_task_id = %s
277
+ ORDER BY created_at ASC
278
+ """
279
+ await cur.execute(query, (root_task_id, root_task_id))
280
+ rows = await cur.fetchall()
281
+ return [Task.from_db_row(row) for row in rows]
src/services.py ADDED
@@ -0,0 +1,359 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Service Layer for Interactive Todo Application (v2.0.0)
3
+
4
+ Owner: Service Logic Agent
5
+ Purpose: Business logic orchestration, validation, and error translation
6
+ Architecture: Async/Await with Pydantic models
7
+
8
+ Constitutional Constraints:
9
+ - ALLOWED: Business rule validation, orchestration between CLI and Repository, error handling
10
+ - FORBIDDEN: Direct database connections (uses repository.py), User input (input()),
11
+ User output (print()), SQL queries, Rich UI output.
12
+
13
+ All service functions return dictionaries with consistent structure:
14
+ - {'success': bool, 'message': str, 'data': Any | None}
15
+ """
16
+
17
+ import logging
18
+ import dateparser
19
+ from datetime import datetime, timedelta
20
+ from typing import List, Optional, Dict, Any
21
+ from src.models import Task, TaskCreate, TaskUpdate, TaskStatus, RecurrenceInterval, Priority
22
+ import src.repository as repository
23
+ from src.recurrence_engine import create_recurring_task_instance
24
+
25
+ logger = logging.getLogger("services")
26
+
27
+ def parse_natural_date(date_str: str) -> Optional[datetime]:
28
+ """
29
+ Parse natural language date string into datetime object.
30
+
31
+ Args:
32
+ date_str: Human-readable date string
33
+
34
+ Returns:
35
+ Datetime object or None if parsing fails
36
+ """
37
+ if not date_str or not date_str.strip():
38
+ return None
39
+
40
+ # dateparser configuration
41
+ settings = {
42
+ 'RETURN_AS_TIMEZONE_AWARE': False, # Store as local/naive for now to match project simple datetime usage
43
+ 'PREFER_DATES_FROM': 'future',
44
+ 'PREFER_DAY_OF_MONTH': 'current'
45
+ }
46
+
47
+ try:
48
+ parsed_date = dateparser.parse(date_str, settings=settings)
49
+ return parsed_date
50
+ except Exception as e:
51
+ logger.warning(f"Failed to parse date string '{date_str}': {e}")
52
+ return None
53
+
54
+ async def create_task(task_data: TaskCreate) -> Dict[str, Any]:
55
+ """
56
+ Orchestrate task creation with validation.
57
+
58
+ Args:
59
+ task_data: Pydantic model containing task creation fields
60
+
61
+ Returns:
62
+ Dict with success status, message, and created task data
63
+ """
64
+ try:
65
+ # Pydantic already handled basic type validation and length constraints via TaskCreate
66
+ # Extract data and call repository
67
+ new_task = await repository.create_task(
68
+ title=task_data.title.strip(),
69
+ description=task_data.description.strip() if task_data.description else None,
70
+ priority=task_data.priority,
71
+ category=task_data.category.strip() if task_data.category else None,
72
+ due_date=task_data.due_date,
73
+ recurrence_interval=task_data.recurrence_interval
74
+ )
75
+
76
+ return {
77
+ "success": True,
78
+ "message": f"Task '{new_task.title}' created successfully.",
79
+ "data": new_task
80
+ }
81
+ except Exception as e:
82
+ logger.error(f"Error creating task: {e}")
83
+ return {
84
+ "success": False,
85
+ "message": f"Failed to create task: {str(e)}",
86
+ "data": None
87
+ }
88
+
89
+ async def get_tasks(
90
+ status: Optional[TaskStatus] = None,
91
+ category: Optional[str] = None,
92
+ priority: Optional[Priority] = None,
93
+ parent_task_id: Optional[int] = None,
94
+ recurrence_interval: Optional[str] = None,
95
+ due_before: Optional[datetime] = None,
96
+ due_after: Optional[datetime] = None,
97
+ sort_by: str = 'date'
98
+ ) -> Dict[str, Any]:
99
+ """
100
+ Retrieve tasks with filtering and sorting.
101
+
102
+ Args:
103
+ status: Filter by completion status
104
+ category: Filter by category name
105
+ priority: Filter by priority level
106
+ parent_task_id: Filter by parent task
107
+ recurrence_interval: Filter by recurrence interval
108
+ due_before: Filter by due date before
109
+ due_after: Filter by due date after
110
+ sort_by: Sorting criterion ('date', 'alpha', 'priority')
111
+
112
+ Returns:
113
+ Dict with success status, message, and list of tasks
114
+ """
115
+ try:
116
+ # Normalize status and priority to string values for repository
117
+ status_val = status
118
+ if status and hasattr(status, 'value'):
119
+ status_val = status.value
120
+ elif status:
121
+ status_val = str(status)
122
+
123
+ priority_val = priority
124
+ if priority and hasattr(priority, 'value'):
125
+ priority_val = priority.value
126
+ elif priority:
127
+ priority_val = str(priority)
128
+
129
+ tasks = await repository.get_all_tasks(
130
+ status=status_val,
131
+ category=category,
132
+ priority=priority_val,
133
+ parent_task_id=parent_task_id,
134
+ recurrence_interval=recurrence_interval,
135
+ due_before=due_before,
136
+ due_after=due_after,
137
+ sort_by=sort_by
138
+ )
139
+
140
+ return {
141
+ "success": True,
142
+ "message": f"Retrieved {len(tasks)} tasks.",
143
+ "data": tasks
144
+ }
145
+ except Exception as e:
146
+ logger.error(f"Error retrieving tasks: {e}")
147
+ return {
148
+ "success": False,
149
+ "message": f"Failed to retrieve tasks: {str(e)}",
150
+ "data": []
151
+ }
152
+
153
+ async def update_task(task_id: int, update_data: TaskUpdate) -> Dict[str, Any]:
154
+ """
155
+ Update an existing task with validation.
156
+
157
+ Args:
158
+ task_id: ID of the task to update
159
+ update_data: Pydantic model containing update fields
160
+
161
+ Returns:
162
+ Dict with success status, message, and updated task data
163
+ """
164
+ try:
165
+ # Business Validation: Ensure task exists
166
+ existing_task = await repository.get_task_by_id(task_id)
167
+ if not existing_task:
168
+ return {
169
+ "success": False,
170
+ "message": f"Task with ID {task_id} not found.",
171
+ "data": None
172
+ }
173
+
174
+ # Convert Pydantic model to dict, excluding unset fields
175
+ updates = update_data.model_dump(exclude_unset=True)
176
+ if not updates:
177
+ return {
178
+ "success": True,
179
+ "message": "No changes requested.",
180
+ "data": existing_task
181
+ }
182
+
183
+ # Handle string stripping for updates
184
+ if 'title' in updates and updates['title']:
185
+ updates['title'] = updates['title'].strip()
186
+ if 'description' in updates and updates['description']:
187
+ updates['description'] = updates['description'].strip()
188
+ if 'category' in updates and updates['category']:
189
+ updates['category'] = updates['category'].strip()
190
+
191
+ updated_task = await repository.update_task(task_id, **updates)
192
+
193
+ return {
194
+ "success": True,
195
+ "message": f"Task {task_id} updated successfully.",
196
+ "data": updated_task
197
+ }
198
+ except Exception as e:
199
+ logger.error(f"Error updating task {task_id}: {e}")
200
+ return {
201
+ "success": False,
202
+ "message": f"Failed to update task: {str(e)}",
203
+ "data": None
204
+ }
205
+
206
+ async def delete_task(task_id: int) -> Dict[str, Any]:
207
+ """
208
+ Delete a task.
209
+
210
+ Args:
211
+ task_id: ID of the task to delete
212
+
213
+ Returns:
214
+ Dict with success status and message
215
+ """
216
+ try:
217
+ # Business Validation: Ensure task exists
218
+ existing_task = await repository.get_task_by_id(task_id)
219
+ if not existing_task:
220
+ return {
221
+ "success": False,
222
+ "message": f"Task with ID {task_id} not found.",
223
+ "data": None
224
+ }
225
+
226
+ success = await repository.delete_task(task_id)
227
+ if success:
228
+ return {
229
+ "success": True,
230
+ "message": f"Task {task_id} deleted successfully.",
231
+ "data": None
232
+ }
233
+ else:
234
+ return {
235
+ "success": False,
236
+ "message": f"Failed to delete task {task_id}.",
237
+ "data": None
238
+ }
239
+ except Exception as e:
240
+ logger.error(f"Error deleting task {task_id}: {e}")
241
+ return {
242
+ "success": False,
243
+ "message": f"Error during deletion: {str(e)}",
244
+ "data": None
245
+ }
246
+
247
+ async def search_tasks(query: str) -> Dict[str, Any]:
248
+ """
249
+ Search for tasks by query string.
250
+
251
+ Args:
252
+ query: Search term
253
+
254
+ Returns:
255
+ Dict with success status, message, and matching tasks
256
+ """
257
+ if not query or not query.strip():
258
+ return {
259
+ "success": False,
260
+ "message": "Search query cannot be empty.",
261
+ "data": []
262
+ }
263
+
264
+ try:
265
+ tasks = await repository.search_tasks(query.strip())
266
+ return {
267
+ "success": True,
268
+ "message": f"Found {len(tasks)} tasks matching '{query}'.",
269
+ "data": tasks
270
+ }
271
+ except Exception as e:
272
+ logger.error(f"Error searching tasks for '{query}': {e}")
273
+ return {
274
+ "success": False,
275
+ "message": f"Search failed: {str(e)}",
276
+ "data": []
277
+ }
278
+
279
+ async def toggle_task_completion(task_id: int) -> Dict[str, Any]:
280
+ """
281
+ Toggle the completion status of a task.
282
+
283
+ Args:
284
+ task_id: ID of the task to toggle
285
+
286
+ Returns:
287
+ Dict with success status, message, and updated task data
288
+ """
289
+ try:
290
+ existing_task = await repository.get_task_by_id(task_id)
291
+ if not existing_task:
292
+ return {
293
+ "success": False,
294
+ "message": f"Task with ID {task_id} not found.",
295
+ "data": None
296
+ }
297
+
298
+ # Determine new status
299
+ is_completed = (existing_task.status == TaskStatus.PENDING)
300
+ new_status = TaskStatus.COMPLETED if is_completed else TaskStatus.PENDING
301
+
302
+ updated_task = await repository.update_task(task_id, status=new_status)
303
+
304
+ # Trigger recurrence logic if marking as completed
305
+ new_task_msg = ""
306
+ if is_completed and updated_task.recurrence_interval != RecurrenceInterval.NONE:
307
+ new_instance_id = await create_recurring_task_instance(
308
+ completed_task_id=task_id,
309
+ current_due_date=updated_task.due_date,
310
+ recurrence_interval=updated_task.recurrence_interval
311
+ )
312
+ if new_instance_id:
313
+ new_task_msg = f" New recurring instance created: {new_instance_id}."
314
+
315
+ status_str = "completed" if is_completed else "pending"
316
+ return {
317
+ "success": True,
318
+ "message": f"Task {task_id} marked as {status_str}.{new_task_msg}",
319
+ "data": updated_task
320
+ }
321
+ except Exception as e:
322
+ logger.error(f"Error toggling task {task_id}: {e}")
323
+ return {
324
+ "success": False,
325
+ "message": f"Failed to toggle status: {str(e)}",
326
+ "data": None
327
+ }
328
+
329
+ async def get_task_history(root_task_id: int) -> Dict[str, Any]:
330
+ """
331
+ Get all instances of a recurring task series.
332
+
333
+ Args:
334
+ root_task_id: ID of the root task
335
+
336
+ Returns:
337
+ Dict with success status, message, and list of tasks
338
+ """
339
+ try:
340
+ tasks = await repository.get_task_history(root_task_id)
341
+ if not tasks:
342
+ return {
343
+ "success": False,
344
+ "message": f"No history found for task {root_task_id}.",
345
+ "data": []
346
+ }
347
+
348
+ return {
349
+ "success": True,
350
+ "message": f"Found {len(tasks)} instances in series.",
351
+ "data": tasks
352
+ }
353
+ except Exception as e:
354
+ logger.error(f"Error retrieving task history for {root_task_id}: {e}")
355
+ return {
356
+ "success": False,
357
+ "message": f"Failed to retrieve history: {str(e)}",
358
+ "data": []
359
+ }
src/services/__init__.py ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # backend/src/services/__init__.py
2
+ """Services package for business logic."""
3
+
4
+ from .chat_service import (
5
+ get_conversation_history,
6
+ save_chat_exchange,
7
+ create_conversation,
8
+ get_conversation_by_id,
9
+ get_user_conversations
10
+ )
11
+ from .agent_service import AgentService, get_agent_service
12
+
13
+ __all__ = [
14
+ "get_conversation_history",
15
+ "save_chat_exchange",
16
+ "create_conversation",
17
+ "get_conversation_by_id",
18
+ "get_user_conversations",
19
+ "AgentService",
20
+ "get_agent_service"
21
+ ]
src/services/agent_service.py ADDED
@@ -0,0 +1,362 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # backend/src/services/agent_service.py
2
+ """
3
+ Agent Service for AI Chatbot
4
+
5
+ Owner: AI Orchestrator
6
+ Purpose: OpenRouter LLM integration for stateless AI processing
7
+ Architecture: Stateless with AsyncOpenAI client (OpenRouter-compatible)
8
+
9
+ Constitutional Constraints:
10
+ - REQUIRED: Stateless processing (Principle VI)
11
+ - REQUIRED: Tools are the ONLY way AI accesses data (Principle VII)
12
+ - REQUIRED: All tool calls captured for audit (Principle VIII)
13
+
14
+ Note: Free tier models on OpenRouter don't support function calling.
15
+ This implementation uses structured prompts to parse tool intents from text.
16
+ """
17
+
18
+ import os
19
+ import re
20
+ import json
21
+ import logging
22
+ from typing import Optional
23
+ from openai import AsyncOpenAI, RateLimitError, APIError
24
+
25
+ logger = logging.getLogger("services.agent_service")
26
+
27
+ # OpenRouter base URL (OpenAI-compatible API)
28
+ OPENROUTER_BASE_URL = "https://openrouter.ai/api/v1"
29
+
30
+ # System prompt for the AI agent (structured output for tool parsing)
31
+ SYSTEM_PROMPT = """You are a task management assistant. Help users manage their to-do list.
32
+
33
+ VALID ACTIONS: ADD_TASK, LIST_TASKS, COMPLETE_TASK, UPDATE_TASK, DELETE_TASK
34
+
35
+ RULES:
36
+ 1. Use ONLY these 5 actions. Never use other action names.
37
+ 2. Output ONE command block per response.
38
+ 3. COMPLETE_TASK, UPDATE_TASK, DELETE_TASK require a task_id from the user's message.
39
+ 4. Task IDs are UUIDs like "85fcb698-ab86-4255-80f7-d3a0aef307f6" - ONLY use IDs the user provides.
40
+ 5. If user wants to complete/update/delete but didn't provide an ID, DO NOT output a command. Ask them to say "show tasks" first.
41
+ 6. NEVER invent or guess task IDs. If no valid UUID is in the user's message, ask for it.
42
+
43
+ COMMAND FORMAT (copy exactly):
44
+ ```command
45
+ ACTION: ACTION_NAME
46
+ PARAMS: {"key": "value"}
47
+ ```
48
+
49
+ EXAMPLES:
50
+
51
+ User: "add buy milk"
52
+ ```command
53
+ ACTION: ADD_TASK
54
+ PARAMS: {"title": "buy milk"}
55
+ ```
56
+
57
+ User: "show tasks"
58
+ ```command
59
+ ACTION: LIST_TASKS
60
+ PARAMS: {"status": "all"}
61
+ ```
62
+
63
+ User: "complete 85fcb698-ab86-4255-80f7-d3a0aef307f6"
64
+ ```command
65
+ ACTION: COMPLETE_TASK
66
+ PARAMS: {"task_id": "85fcb698-ab86-4255-80f7-d3a0aef307f6"}
67
+ ```
68
+
69
+ User: "update 85fcb698-ab86-4255-80f7-d3a0aef307f6 to buy organic milk"
70
+ ```command
71
+ ACTION: UPDATE_TASK
72
+ PARAMS: {"task_id": "85fcb698-ab86-4255-80f7-d3a0aef307f6", "title": "buy organic milk"}
73
+ ```
74
+
75
+ User: "delete 85fcb698-ab86-4255-80f7-d3a0aef307f6"
76
+ ```command
77
+ ACTION: DELETE_TASK
78
+ PARAMS: {"task_id": "85fcb698-ab86-4255-80f7-d3a0aef307f6"}
79
+ ```
80
+
81
+ User: "delete my task" (no UUID provided)
82
+ I need the task ID. Say "show tasks" to see your tasks with their IDs, then tell me which to delete.
83
+
84
+ User: "update the milk task" (no UUID provided)
85
+ I need the task ID to update it. Say "show tasks" to see your tasks with their IDs.
86
+
87
+ User: "hello"
88
+ Hi! I can help manage your tasks. Say "add [task]" to create, "show tasks" to list, or provide a task ID to complete/update/delete."""
89
+
90
+
91
+ class AgentService:
92
+ """
93
+ Stateless AI agent service using OpenRouter API (OpenAI-compatible).
94
+
95
+ Per Constitution Principle VI: No local session state.
96
+ All context is passed in via conversation_history parameter.
97
+
98
+ Note: Free tier models don't support function calling, so we use
99
+ structured prompts and parse commands from text responses.
100
+ """
101
+
102
+ # Regex pattern to extract command blocks from AI response
103
+ # Handles both wrapped (```command...```) and unwrapped formats
104
+ COMMAND_PATTERN = re.compile(
105
+ r'(?:```command\s*\n)?' # Optional opening wrapper
106
+ r'ACTION:\s*(\w+)\s*\n'
107
+ r'PARAMS:\s*(\{.*?\})'
108
+ r'(?:\s*\n```)?', # Optional closing wrapper
109
+ re.IGNORECASE | re.DOTALL
110
+ )
111
+
112
+ # Map action names to tool names
113
+ ACTION_TO_TOOL = {
114
+ "ADD_TASK": "add_task",
115
+ "CREATE_TASK": "add_task", # Alias
116
+ "LIST_TASKS": "list_tasks",
117
+ "READ_TASK": "list_tasks", # Alias - LLM sometimes uses this
118
+ "READ_TASKS": "list_tasks", # Alias
119
+ "SHOW_TASKS": "list_tasks", # Alias
120
+ "GET_TASKS": "list_tasks", # Alias
121
+ "COMPLETE_TASK": "complete_task",
122
+ "MARK_COMPLETE": "complete_task", # Alias
123
+ "UPDATE_TASK": "update_task",
124
+ "EDIT_TASK": "update_task", # Alias
125
+ "DELETE_TASK": "delete_task",
126
+ "REMOVE_TASK": "delete_task", # Alias
127
+ }
128
+
129
+ # Actions that require a task_id (including aliases)
130
+ ACTIONS_REQUIRING_ID = {
131
+ "COMPLETE_TASK", "MARK_COMPLETE",
132
+ "UPDATE_TASK", "EDIT_TASK",
133
+ "DELETE_TASK", "REMOVE_TASK"
134
+ }
135
+
136
+ def __init__(self):
137
+ """Initialize the OpenRouter client."""
138
+ api_key = os.getenv("OPENROUTER_API_KEY")
139
+ if not api_key:
140
+ raise ValueError("OPENROUTER_API_KEY environment variable not set")
141
+
142
+ self.client = AsyncOpenAI(
143
+ api_key=api_key,
144
+ base_url=OPENROUTER_BASE_URL
145
+ )
146
+ # Default to Qwen 2.5 7B - better instruction following than Llama 3B
147
+ self.model = os.getenv("OPENROUTER_MODEL", "qwen/qwen-2.5-7b-instruct:free")
148
+ logger.info(f"AgentService initialized with OpenRouter model: {self.model}")
149
+
150
+ def _parse_commands(self, text: str) -> list[tuple[str, dict]]:
151
+ """
152
+ Parse command blocks from AI response text.
153
+ Only returns the FIRST valid command found to prevent multiple actions.
154
+
155
+ Returns:
156
+ List with at most one (action_name, params_dict) tuple
157
+ """
158
+ commands = []
159
+ match = self.COMMAND_PATTERN.search(text) # Only find first match
160
+ if match:
161
+ action = match.group(1).upper().strip()
162
+ # Skip empty or invalid actions
163
+ if not action or action not in self.ACTION_TO_TOOL:
164
+ logger.warning(f"Skipping invalid/empty action: '{action}'")
165
+ return commands
166
+ try:
167
+ params = json.loads(match.group(2))
168
+ except json.JSONDecodeError:
169
+ params = {}
170
+ commands.append((action, params))
171
+ return commands
172
+
173
+ def _validate_command(self, action: str, params: dict) -> tuple[bool, str]:
174
+ """
175
+ Validate that a command has all required parameters.
176
+
177
+ Args:
178
+ action: The action name (e.g., "COMPLETE_TASK")
179
+ params: The parameters dict
180
+
181
+ Returns:
182
+ Tuple of (is_valid, error_message)
183
+ """
184
+ if action in self.ACTIONS_REQUIRING_ID:
185
+ task_id = params.get("task_id", "")
186
+ if not task_id or not task_id.strip():
187
+ return False, f"I need a task ID to {action.lower().replace('_', ' ')}. Please say 'show my tasks' first to see your tasks with their IDs."
188
+ return True, ""
189
+
190
+ def _clean_response(self, text: str) -> str:
191
+ """Remove command blocks from response text for cleaner output."""
192
+ return self.COMMAND_PATTERN.sub('', text).strip()
193
+
194
+ def _clean_history(self, history: list[dict]) -> list[dict]:
195
+ """
196
+ Clean conversation history to prevent LLM confusion.
197
+
198
+ Removes command blocks from previous assistant messages and
199
+ limits history to prevent context overload.
200
+ """
201
+ cleaned = []
202
+ # Only keep last 4 messages to prevent confusion
203
+ recent_history = history[-4:] if len(history) > 4 else history
204
+
205
+ for msg in recent_history:
206
+ if msg["role"] == "assistant":
207
+ # Remove command blocks from previous assistant responses
208
+ clean_content = self._clean_response(msg["content"])
209
+ # Also remove "Tool results:" sections
210
+ if "Tool results:" in clean_content:
211
+ clean_content = clean_content.split("Tool results:")[0].strip()
212
+ if clean_content:
213
+ cleaned.append({"role": "assistant", "content": clean_content})
214
+ else:
215
+ cleaned.append(msg)
216
+
217
+ return cleaned
218
+
219
+ async def process_message(
220
+ self,
221
+ user_message: str,
222
+ conversation_history: list[dict],
223
+ user_id: str,
224
+ tool_executor: callable
225
+ ) -> dict:
226
+ """
227
+ Process a user message statelessly (no history used).
228
+
229
+ Args:
230
+ user_message: The new message from user
231
+ conversation_history: Ignored - each message is independent
232
+ user_id: For tool authorization (passed to tool executor)
233
+ tool_executor: Async function to execute tool calls
234
+
235
+ Returns:
236
+ dict with 'response' (str) and 'tool_calls' (list)
237
+ """
238
+ # Stateless: Only use system prompt + current message (no history)
239
+ messages = [
240
+ {"role": "system", "content": SYSTEM_PROMPT},
241
+ {"role": "user", "content": user_message}
242
+ ]
243
+
244
+ tool_calls_log = []
245
+
246
+ try:
247
+ # API call (no tools parameter - using text-based commands)
248
+ response = await self.client.chat.completions.create(
249
+ model=self.model,
250
+ messages=messages,
251
+ extra_headers={
252
+ "HTTP-Referer": "https://todozen.app",
253
+ "X-Title": "TodoZen AI Assistant"
254
+ }
255
+ )
256
+
257
+ assistant_content = response.choices[0].message.content or ""
258
+
259
+ # Debug: Log raw LLM response
260
+ logger.info(f"Raw LLM response: {assistant_content[:500]}")
261
+
262
+ # Parse commands from response
263
+ commands = self._parse_commands(assistant_content)
264
+ logger.info(f"Parsed commands: {commands}")
265
+
266
+ if commands:
267
+ # Execute each command (should be only one due to _parse_commands)
268
+ tool_results = []
269
+ for action, params in commands:
270
+ # Validate command has required parameters
271
+ is_valid, error_msg = self._validate_command(action, params)
272
+ if not is_valid:
273
+ logger.warning(f"Invalid command {action}: missing task_id")
274
+ # Return the error message without executing the tool
275
+ return {
276
+ "response": error_msg,
277
+ "tool_calls": None
278
+ }
279
+
280
+ tool_name = self.ACTION_TO_TOOL.get(action)
281
+ if not tool_name:
282
+ logger.warning(f"Unknown action: {action}")
283
+ continue
284
+
285
+ tool_args = json.dumps(params)
286
+ logger.info(f"Executing tool: {tool_name} with args: {tool_args}")
287
+
288
+ # Execute tool and get result
289
+ tool_result = await tool_executor(
290
+ tool_name=tool_name,
291
+ tool_args=tool_args,
292
+ user_id=user_id
293
+ )
294
+
295
+ # Log tool call for audit trail
296
+ tool_calls_log.append({
297
+ "tool": tool_name,
298
+ "arguments": tool_args,
299
+ "result": tool_result
300
+ })
301
+ tool_results.append(tool_result)
302
+
303
+ # Get follow-up response with tool results
304
+ messages.append({"role": "assistant", "content": assistant_content})
305
+ messages.append({
306
+ "role": "user",
307
+ "content": f"Tool results:\n" + "\n".join(tool_results) + "\n\nPlease provide a friendly summary of what was done."
308
+ })
309
+
310
+ follow_up = await self.client.chat.completions.create(
311
+ model=self.model,
312
+ messages=messages,
313
+ extra_headers={
314
+ "HTTP-Referer": "https://todozen.app",
315
+ "X-Title": "TodoZen AI Assistant"
316
+ }
317
+ )
318
+ final_response = follow_up.choices[0].message.content or ""
319
+ else:
320
+ # No commands - just return the response
321
+ final_response = assistant_content
322
+
323
+ # Clean any remaining command blocks from response
324
+ final_response = self._clean_response(final_response)
325
+
326
+ logger.info(f"Agent processed message with {len(tool_calls_log)} tool calls")
327
+
328
+ return {
329
+ "response": final_response,
330
+ "tool_calls": tool_calls_log if tool_calls_log else None
331
+ }
332
+
333
+ except RateLimitError as e:
334
+ logger.error(f"Rate limit exceeded: {e}")
335
+ return {
336
+ "response": "I'm currently experiencing high demand. Please wait a moment and try again.",
337
+ "tool_calls": None
338
+ }
339
+ except APIError as e:
340
+ logger.error(f"API error: {e}")
341
+ return {
342
+ "response": "I'm having trouble connecting to my AI service. Please try again in a moment.",
343
+ "tool_calls": None
344
+ }
345
+ except Exception as e:
346
+ logger.error(f"Agent processing error: {e}")
347
+ return {
348
+ "response": "I'm sorry, I encountered an error processing your request. Please try again.",
349
+ "tool_calls": None
350
+ }
351
+
352
+
353
+ # Singleton instance
354
+ _agent_service: Optional[AgentService] = None
355
+
356
+
357
+ def get_agent_service() -> AgentService:
358
+ """Get or create the singleton AgentService instance."""
359
+ global _agent_service
360
+ if _agent_service is None:
361
+ _agent_service = AgentService()
362
+ return _agent_service
src/services/chat_service.py ADDED
@@ -0,0 +1,258 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # backend/src/services/chat_service.py
2
+ """
3
+ Chat Service for AI Chatbot
4
+
5
+ Owner: AI Orchestrator
6
+ Purpose: Stateless conversation management per stateless-memory-management skill
7
+ Architecture: Database-backed memory with no local session state
8
+
9
+ Constitutional Constraints:
10
+ - REQUIRED: All queries filter by user_id (Principle IV)
11
+ - REQUIRED: No local session storage (Principle VI)
12
+ - REQUIRED: Messages persisted immediately after AI response (Principle VIII)
13
+ """
14
+
15
+ import logging
16
+ from datetime import datetime
17
+ from typing import Optional
18
+ from sqlalchemy import select
19
+ from sqlalchemy.ext.asyncio import AsyncSession
20
+
21
+ from src.db.models import Todo
22
+ from src.models.conversation import Conversation
23
+ from src.models.message import Message
24
+
25
+ logger = logging.getLogger("services.chat_service")
26
+
27
+
28
+ async def get_conversation_history(
29
+ conversation_id: int,
30
+ user_id: str,
31
+ session: AsyncSession,
32
+ limit: int = 10
33
+ ) -> list[dict]:
34
+ """
35
+ Fetch last N messages for conversation context.
36
+
37
+ Per stateless-memory-management skill:
38
+ - Fetches from database on every request (no caching)
39
+ - Filters by user_id for isolation
40
+ - Returns in chronological order for OpenAI
41
+
42
+ Args:
43
+ conversation_id: The conversation to fetch history for
44
+ user_id: The authenticated user (for isolation)
45
+ session: Database session
46
+ limit: Maximum messages to fetch (default 10)
47
+
48
+ Returns:
49
+ List of message dicts formatted for OpenAI: [{"role": "...", "content": "..."}]
50
+ """
51
+ statement = (
52
+ select(Message)
53
+ .where(
54
+ Message.conversation_id == conversation_id,
55
+ Message.user_id == user_id # REQUIRED: User isolation
56
+ )
57
+ .order_by(Message.created_at.desc())
58
+ .limit(limit)
59
+ )
60
+
61
+ result = await session.execute(statement)
62
+ messages = result.scalars().all()
63
+
64
+ # Reverse to chronological order and format for OpenAI
65
+ history = [
66
+ {"role": msg.role, "content": msg.content}
67
+ for msg in reversed(messages)
68
+ ]
69
+
70
+ logger.debug(f"Fetched {len(history)} messages for conversation {conversation_id}")
71
+ return history
72
+
73
+
74
+ async def save_chat_exchange(
75
+ conversation_id: int,
76
+ user_id: str,
77
+ user_message: str,
78
+ assistant_response: str,
79
+ tool_calls: Optional[list],
80
+ session: AsyncSession
81
+ ) -> tuple[Message, Message]:
82
+ """
83
+ Persist user message and AI response to database.
84
+
85
+ Per stateless-memory-management skill:
86
+ - MUST be called immediately after AI responds
87
+ - Saves both user and assistant messages
88
+ - Updates conversation timestamp
89
+ - Stores tool_calls for audit trail (Principle VIII)
90
+
91
+ Args:
92
+ conversation_id: The conversation ID
93
+ user_id: The authenticated user's ID
94
+ user_message: The user's input message
95
+ assistant_response: The AI's response text
96
+ tool_calls: List of tool calls made by AI (for audit)
97
+ session: Database session
98
+
99
+ Returns:
100
+ Tuple of (user_message, assistant_message) Message objects
101
+ """
102
+ now = datetime.utcnow()
103
+
104
+ # Save user message
105
+ user_msg = Message(
106
+ conversation_id=conversation_id,
107
+ user_id=user_id,
108
+ role="user",
109
+ content=user_message,
110
+ created_at=now
111
+ )
112
+ session.add(user_msg)
113
+
114
+ # Save assistant response with tool calls for audit
115
+ assistant_msg = Message(
116
+ conversation_id=conversation_id,
117
+ user_id=user_id,
118
+ role="assistant",
119
+ content=assistant_response,
120
+ tool_calls=tool_calls,
121
+ created_at=now
122
+ )
123
+ session.add(assistant_msg)
124
+
125
+ # Update conversation timestamp
126
+ conversation = await session.get(Conversation, conversation_id)
127
+ if conversation:
128
+ conversation.updated_at = now
129
+
130
+ await session.commit()
131
+
132
+ logger.info(f"Saved chat exchange for conversation {conversation_id}")
133
+ return user_msg, assistant_msg
134
+
135
+
136
+ async def create_conversation(
137
+ user_id: str,
138
+ first_message: str,
139
+ session: AsyncSession
140
+ ) -> Conversation:
141
+ """
142
+ Create a new conversation with auto-generated title.
143
+
144
+ Title is generated from the first message (truncated to 50 chars).
145
+
146
+ Args:
147
+ user_id: The authenticated user's ID
148
+ first_message: The first message (used for title generation)
149
+ session: Database session
150
+
151
+ Returns:
152
+ The created Conversation object
153
+ """
154
+ # Generate title from first message (truncate to 50 chars)
155
+ title = first_message[:50].strip()
156
+ if len(first_message) > 50:
157
+ title = title + "..."
158
+
159
+ conversation = Conversation(
160
+ user_id=user_id,
161
+ title=title,
162
+ created_at=datetime.utcnow(),
163
+ updated_at=datetime.utcnow()
164
+ )
165
+ session.add(conversation)
166
+ await session.commit()
167
+ await session.refresh(conversation)
168
+
169
+ logger.info(f"Created conversation {conversation.id} for user {user_id}")
170
+ return conversation
171
+
172
+
173
+ async def get_conversation_by_id(
174
+ conversation_id: int,
175
+ user_id: str,
176
+ session: AsyncSession
177
+ ) -> Optional[Conversation]:
178
+ """
179
+ Get a conversation by ID with user ownership verification.
180
+
181
+ Args:
182
+ conversation_id: The conversation ID
183
+ user_id: The authenticated user's ID (for ownership check)
184
+ session: Database session
185
+
186
+ Returns:
187
+ Conversation if found and owned by user, None otherwise
188
+ """
189
+ statement = select(Conversation).where(
190
+ Conversation.id == conversation_id,
191
+ Conversation.user_id == user_id # REQUIRED: User isolation
192
+ )
193
+ result = await session.execute(statement)
194
+ return result.scalar_one_or_none()
195
+
196
+
197
+ async def get_user_conversations(
198
+ user_id: str,
199
+ session: AsyncSession,
200
+ limit: int = 20
201
+ ) -> list[Conversation]:
202
+ """
203
+ Get all conversations for a user, ordered by most recent.
204
+
205
+ Args:
206
+ user_id: The authenticated user's ID
207
+ session: Database session
208
+ limit: Maximum conversations to return
209
+
210
+ Returns:
211
+ List of Conversation objects
212
+ """
213
+ statement = (
214
+ select(Conversation)
215
+ .where(Conversation.user_id == user_id)
216
+ .order_by(Conversation.updated_at.desc())
217
+ .limit(limit)
218
+ )
219
+ result = await session.execute(statement)
220
+ return list(result.scalars().all())
221
+
222
+
223
+ async def delete_conversation(
224
+ conversation_id: int,
225
+ user_id: str,
226
+ session: AsyncSession
227
+ ) -> bool:
228
+ """
229
+ Delete a conversation and all its messages.
230
+
231
+ Args:
232
+ conversation_id: The conversation ID to delete
233
+ user_id: The authenticated user's ID (for ownership check)
234
+ session: Database session
235
+
236
+ Returns:
237
+ True if deleted, False if not found or unauthorized
238
+ """
239
+ # First verify ownership
240
+ conversation = await get_conversation_by_id(conversation_id, user_id, session)
241
+ if not conversation:
242
+ return False
243
+
244
+ # Delete all messages in the conversation
245
+ from sqlalchemy import delete
246
+ await session.execute(
247
+ delete(Message).where(
248
+ Message.conversation_id == conversation_id,
249
+ Message.user_id == user_id
250
+ )
251
+ )
252
+
253
+ # Delete the conversation
254
+ await session.delete(conversation)
255
+ await session.commit()
256
+
257
+ logger.info(f"Deleted conversation {conversation_id} for user {user_id}")
258
+ return True
test_api.py ADDED
@@ -0,0 +1,227 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Simple Test Script for Todo API Endpoints
3
+
4
+ This script tests the basic functionality of the Todo API without authentication.
5
+ For full integration tests with JWT, see tests/ directory.
6
+
7
+ Usage:
8
+ python test_api.py
9
+
10
+ Requirements:
11
+ - API server must be running on http://localhost:8000
12
+ - httpx library must be installed
13
+ """
14
+
15
+ import asyncio
16
+ import sys
17
+ from datetime import datetime, timedelta
18
+ from jose import jwt
19
+ import httpx
20
+
21
+ # Test configuration
22
+ API_BASE_URL = "http://localhost:8000"
23
+ TEST_USER_ID = "test_user_123"
24
+ BETTER_AUTH_SECRET = "test-secret-for-development" # Replace with actual secret
25
+
26
+
27
+ def create_test_token(user_id: str, secret: str) -> str:
28
+ """
29
+ Create a test JWT token for authentication.
30
+
31
+ Args:
32
+ user_id: User ID to include in token
33
+ secret: BETTER_AUTH_SECRET for signing
34
+
35
+ Returns:
36
+ JWT token string
37
+ """
38
+ payload = {
39
+ "sub": user_id,
40
+ "email": f"{user_id}@example.com",
41
+ "iat": datetime.utcnow(),
42
+ "exp": datetime.utcnow() + timedelta(days=1),
43
+ "iss": "todoweb",
44
+ "aud": "todoweb-api"
45
+ }
46
+ return jwt.encode(payload, secret, algorithm="HS256")
47
+
48
+
49
+ async def test_health_check():
50
+ """Test the health check endpoint (no auth required)."""
51
+ print("\n[TEST] Health Check")
52
+ async with httpx.AsyncClient() as client:
53
+ response = await client.get(f"{API_BASE_URL}/health")
54
+ print(f"Status: {response.status_code}")
55
+ print(f"Response: {response.json()}")
56
+ assert response.status_code == 200, "Health check failed"
57
+ print("✓ Health check passed")
58
+
59
+
60
+ async def test_root_endpoint():
61
+ """Test the root endpoint (no auth required)."""
62
+ print("\n[TEST] Root Endpoint")
63
+ async with httpx.AsyncClient() as client:
64
+ response = await client.get(f"{API_BASE_URL}/")
65
+ print(f"Status: {response.status_code}")
66
+ print(f"Response: {response.json()}")
67
+ assert response.status_code == 200, "Root endpoint failed"
68
+ print("✓ Root endpoint passed")
69
+
70
+
71
+ async def test_create_todo(token: str):
72
+ """Test creating a todo."""
73
+ print("\n[TEST] Create Todo")
74
+ async with httpx.AsyncClient() as client:
75
+ response = await client.post(
76
+ f"{API_BASE_URL}/api/todos",
77
+ json={
78
+ "title": "Test Todo",
79
+ "description": "This is a test todo",
80
+ "is_completed": False
81
+ },
82
+ headers={"Authorization": f"Bearer {token}"}
83
+ )
84
+ print(f"Status: {response.status_code}")
85
+ print(f"Response: {response.json()}")
86
+ assert response.status_code == 201, "Create todo failed"
87
+ todo = response.json()
88
+ print(f"✓ Todo created with ID: {todo['id']}")
89
+ return todo["id"]
90
+
91
+
92
+ async def test_list_todos(token: str):
93
+ """Test listing todos."""
94
+ print("\n[TEST] List Todos")
95
+ async with httpx.AsyncClient() as client:
96
+ response = await client.get(
97
+ f"{API_BASE_URL}/api/todos",
98
+ headers={"Authorization": f"Bearer {token}"}
99
+ )
100
+ print(f"Status: {response.status_code}")
101
+ print(f"Response: {response.json()}")
102
+ assert response.status_code == 200, "List todos failed"
103
+ todos = response.json()
104
+ print(f"✓ Retrieved {len(todos)} todos")
105
+ return todos
106
+
107
+
108
+ async def test_get_todo(token: str, todo_id: str):
109
+ """Test getting a specific todo."""
110
+ print(f"\n[TEST] Get Todo {todo_id}")
111
+ async with httpx.AsyncClient() as client:
112
+ response = await client.get(
113
+ f"{API_BASE_URL}/api/todos/{todo_id}",
114
+ headers={"Authorization": f"Bearer {token}"}
115
+ )
116
+ print(f"Status: {response.status_code}")
117
+ print(f"Response: {response.json()}")
118
+ assert response.status_code == 200, "Get todo failed"
119
+ print("✓ Todo retrieved successfully")
120
+
121
+
122
+ async def test_update_todo(token: str, todo_id: str):
123
+ """Test updating a todo."""
124
+ print(f"\n[TEST] Update Todo {todo_id}")
125
+ async with httpx.AsyncClient() as client:
126
+ response = await client.put(
127
+ f"{API_BASE_URL}/api/todos/{todo_id}",
128
+ json={
129
+ "title": "Updated Test Todo",
130
+ "description": "This todo has been updated"
131
+ },
132
+ headers={"Authorization": f"Bearer {token}"}
133
+ )
134
+ print(f"Status: {response.status_code}")
135
+ print(f"Response: {response.json()}")
136
+ assert response.status_code == 200, "Update todo failed"
137
+ print("✓ Todo updated successfully")
138
+
139
+
140
+ async def test_toggle_completion(token: str, todo_id: str):
141
+ """Test toggling todo completion."""
142
+ print(f"\n[TEST] Toggle Todo Completion {todo_id}")
143
+ async with httpx.AsyncClient() as client:
144
+ response = await client.patch(
145
+ f"{API_BASE_URL}/api/todos/{todo_id}/complete",
146
+ headers={"Authorization": f"Bearer {token}"}
147
+ )
148
+ print(f"Status: {response.status_code}")
149
+ print(f"Response: {response.json()}")
150
+ assert response.status_code == 200, "Toggle completion failed"
151
+ todo = response.json()
152
+ print(f"✓ Todo completion toggled to: {todo['is_completed']}")
153
+
154
+
155
+ async def test_delete_todo(token: str, todo_id: str):
156
+ """Test deleting a todo."""
157
+ print(f"\n[TEST] Delete Todo {todo_id}")
158
+ async with httpx.AsyncClient() as client:
159
+ response = await client.delete(
160
+ f"{API_BASE_URL}/api/todos/{todo_id}",
161
+ headers={"Authorization": f"Bearer {token}"}
162
+ )
163
+ print(f"Status: {response.status_code}")
164
+ assert response.status_code == 204, "Delete todo failed"
165
+ print("✓ Todo deleted successfully")
166
+
167
+
168
+ async def test_unauthorized_access():
169
+ """Test that endpoints reject requests without authentication."""
170
+ print("\n[TEST] Unauthorized Access")
171
+ async with httpx.AsyncClient() as client:
172
+ response = await client.get(f"{API_BASE_URL}/api/todos")
173
+ print(f"Status: {response.status_code}")
174
+ assert response.status_code == 403, "Should reject unauthorized requests"
175
+ print("✓ Unauthorized access correctly rejected")
176
+
177
+
178
+ async def main():
179
+ """Run all tests."""
180
+ print("=" * 60)
181
+ print("Todo API Test Suite")
182
+ print("=" * 60)
183
+ print(f"API URL: {API_BASE_URL}")
184
+ print(f"Test User: {TEST_USER_ID}")
185
+ print("=" * 60)
186
+
187
+ try:
188
+ # Test public endpoints
189
+ await test_health_check()
190
+ await test_root_endpoint()
191
+
192
+ # Test unauthorized access
193
+ await test_unauthorized_access()
194
+
195
+ # Create test token
196
+ print("\n[SETUP] Creating test JWT token...")
197
+ token = create_test_token(TEST_USER_ID, BETTER_AUTH_SECRET)
198
+ print(f"Token created for user: {TEST_USER_ID}")
199
+
200
+ # Test authenticated endpoints
201
+ todo_id = await test_create_todo(token)
202
+ await test_list_todos(token)
203
+ await test_get_todo(token, todo_id)
204
+ await test_update_todo(token, todo_id)
205
+ await test_toggle_completion(token, todo_id)
206
+ await test_delete_todo(token, todo_id)
207
+
208
+ print("\n" + "=" * 60)
209
+ print("✓ All tests passed!")
210
+ print("=" * 60)
211
+
212
+ except AssertionError as e:
213
+ print(f"\n✗ Test failed: {e}")
214
+ sys.exit(1)
215
+ except httpx.ConnectError:
216
+ print("\n✗ Cannot connect to API server")
217
+ print(f"Make sure the server is running at {API_BASE_URL}")
218
+ sys.exit(1)
219
+ except Exception as e:
220
+ print(f"\n✗ Unexpected error: {e}")
221
+ import traceback
222
+ traceback.print_exc()
223
+ sys.exit(1)
224
+
225
+
226
+ if __name__ == "__main__":
227
+ asyncio.run(main())
tests/test_auth.py ADDED
@@ -0,0 +1,268 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ JWT Authentication Tests
3
+
4
+ Purpose: Validate JWT token verification and security
5
+ Tests: Valid token, expired token, invalid signature, missing sub claim
6
+
7
+ Constitutional Requirements:
8
+ - REQUIRED: Reject tokens with invalid signature
9
+ - REQUIRED: Reject expired tokens
10
+ - REQUIRED: Reject tokens missing sub claim
11
+ - REQUIRED: Accept valid tokens with correct signature
12
+ """
13
+
14
+ import pytest
15
+ from datetime import datetime, timedelta
16
+ from jose import jwt
17
+ import os
18
+
19
+ # Test secret (matches .env for testing)
20
+ TEST_SECRET = os.getenv("BETTER_AUTH_SECRET", "test-secret-for-testing-only")
21
+
22
+
23
+ def create_test_token(
24
+ user_id: str = "test_user_123",
25
+ expires_delta: timedelta = timedelta(days=1),
26
+ secret: str = TEST_SECRET,
27
+ include_sub: bool = True,
28
+ issuer: str = "todoweb",
29
+ audience: str = "todoweb-api"
30
+ ) -> str:
31
+ """
32
+ Create a test JWT token with configurable parameters
33
+
34
+ Args:
35
+ user_id: User ID to include in sub claim
36
+ expires_delta: Time until token expires
37
+ secret: Secret key for signing
38
+ include_sub: Whether to include sub claim
39
+ issuer: Token issuer
40
+ audience: Token audience
41
+
42
+ Returns:
43
+ Encoded JWT token string
44
+ """
45
+ payload = {
46
+ "iat": datetime.utcnow(),
47
+ "exp": datetime.utcnow() + expires_delta,
48
+ "iss": issuer,
49
+ "aud": audience
50
+ }
51
+
52
+ if include_sub:
53
+ payload["sub"] = user_id
54
+
55
+ return jwt.encode(payload, secret, algorithm="HS256")
56
+
57
+
58
+ class TestJWTValidation:
59
+ """Test JWT token validation logic"""
60
+
61
+ def test_valid_token(self):
62
+ """Test that valid token is accepted"""
63
+ token = create_test_token(user_id="user_123")
64
+
65
+ # Decode and verify
66
+ payload = jwt.decode(
67
+ token,
68
+ TEST_SECRET,
69
+ algorithms=["HS256"],
70
+ issuer="todoweb",
71
+ audience="todoweb-api"
72
+ )
73
+
74
+ assert payload["sub"] == "user_123"
75
+ assert payload["iss"] == "todoweb"
76
+ assert payload["aud"] == "todoweb-api"
77
+ assert "exp" in payload
78
+ assert "iat" in payload
79
+
80
+ def test_expired_token(self):
81
+ """Test that expired token is rejected"""
82
+ # Create token that expired 1 day ago
83
+ token = create_test_token(
84
+ user_id="user_123",
85
+ expires_delta=timedelta(days=-1)
86
+ )
87
+
88
+ # Should raise ExpiredSignatureError
89
+ with pytest.raises(jwt.ExpiredSignatureError):
90
+ jwt.decode(
91
+ token,
92
+ TEST_SECRET,
93
+ algorithms=["HS256"],
94
+ issuer="todoweb",
95
+ audience="todoweb-api"
96
+ )
97
+
98
+ def test_invalid_signature(self):
99
+ """Test that token with wrong signature is rejected"""
100
+ # Create token with different secret
101
+ token = create_test_token(
102
+ user_id="user_123",
103
+ secret="wrong-secret-key"
104
+ )
105
+
106
+ # Should raise JWTError when verifying with correct secret
107
+ with pytest.raises(jwt.JWTError):
108
+ jwt.decode(
109
+ token,
110
+ TEST_SECRET,
111
+ algorithms=["HS256"],
112
+ issuer="todoweb",
113
+ audience="todoweb-api"
114
+ )
115
+
116
+ def test_missing_sub_claim(self):
117
+ """Test that token without sub claim is rejected"""
118
+ # Create token without sub claim
119
+ token = create_test_token(
120
+ user_id="user_123",
121
+ include_sub=False
122
+ )
123
+
124
+ # Token should decode but sub claim should be missing
125
+ payload = jwt.decode(
126
+ token,
127
+ TEST_SECRET,
128
+ algorithms=["HS256"],
129
+ issuer="todoweb",
130
+ audience="todoweb-api"
131
+ )
132
+
133
+ assert "sub" not in payload
134
+
135
+ def test_invalid_issuer(self):
136
+ """Test that token with wrong issuer is rejected"""
137
+ token = create_test_token(
138
+ user_id="user_123",
139
+ issuer="wrong-issuer"
140
+ )
141
+
142
+ # Should raise JWTClaimsError
143
+ with pytest.raises(jwt.JWTClaimsError):
144
+ jwt.decode(
145
+ token,
146
+ TEST_SECRET,
147
+ algorithms=["HS256"],
148
+ issuer="todoweb",
149
+ audience="todoweb-api"
150
+ )
151
+
152
+ def test_invalid_audience(self):
153
+ """Test that token with wrong audience is rejected"""
154
+ token = create_test_token(
155
+ user_id="user_123",
156
+ audience="wrong-audience"
157
+ )
158
+
159
+ # Should raise JWTClaimsError
160
+ with pytest.raises(jwt.JWTClaimsError):
161
+ jwt.decode(
162
+ token,
163
+ TEST_SECRET,
164
+ algorithms=["HS256"],
165
+ issuer="todoweb",
166
+ audience="todoweb-api"
167
+ )
168
+
169
+ def test_malformed_token(self):
170
+ """Test that malformed token is rejected"""
171
+ malformed_token = "not.a.valid.jwt.token"
172
+
173
+ # Should raise JWTError
174
+ with pytest.raises(jwt.JWTError):
175
+ jwt.decode(
176
+ malformed_token,
177
+ TEST_SECRET,
178
+ algorithms=["HS256"],
179
+ issuer="todoweb",
180
+ audience="todoweb-api"
181
+ )
182
+
183
+ def test_token_with_extra_claims(self):
184
+ """Test that token with extra claims is accepted"""
185
+ payload = {
186
+ "sub": "user_123",
187
+ "email": "user@example.com",
188
+ "name": "Test User",
189
+ "iat": datetime.utcnow(),
190
+ "exp": datetime.utcnow() + timedelta(days=1),
191
+ "iss": "todoweb",
192
+ "aud": "todoweb-api"
193
+ }
194
+
195
+ token = jwt.encode(payload, TEST_SECRET, algorithm="HS256")
196
+
197
+ # Should decode successfully
198
+ decoded = jwt.decode(
199
+ token,
200
+ TEST_SECRET,
201
+ algorithms=["HS256"],
202
+ issuer="todoweb",
203
+ audience="todoweb-api"
204
+ )
205
+
206
+ assert decoded["sub"] == "user_123"
207
+ assert decoded["email"] == "user@example.com"
208
+ assert decoded["name"] == "Test User"
209
+
210
+
211
+ class TestTokenExpiration:
212
+ """Test token expiration edge cases"""
213
+
214
+ def test_token_expires_in_future(self):
215
+ """Test token that expires in 7 days (standard expiration)"""
216
+ token = create_test_token(
217
+ user_id="user_123",
218
+ expires_delta=timedelta(days=7)
219
+ )
220
+
221
+ payload = jwt.decode(
222
+ token,
223
+ TEST_SECRET,
224
+ algorithms=["HS256"],
225
+ issuer="todoweb",
226
+ audience="todoweb-api"
227
+ )
228
+
229
+ assert payload["sub"] == "user_123"
230
+
231
+ def test_token_expires_soon(self):
232
+ """Test token that expires in 1 second"""
233
+ token = create_test_token(
234
+ user_id="user_123",
235
+ expires_delta=timedelta(seconds=1)
236
+ )
237
+
238
+ # Should still be valid
239
+ payload = jwt.decode(
240
+ token,
241
+ TEST_SECRET,
242
+ algorithms=["HS256"],
243
+ issuer="todoweb",
244
+ audience="todoweb-api"
245
+ )
246
+
247
+ assert payload["sub"] == "user_123"
248
+
249
+ def test_token_just_expired(self):
250
+ """Test token that just expired"""
251
+ token = create_test_token(
252
+ user_id="user_123",
253
+ expires_delta=timedelta(seconds=-1)
254
+ )
255
+
256
+ # Should be rejected
257
+ with pytest.raises(jwt.ExpiredSignatureError):
258
+ jwt.decode(
259
+ token,
260
+ TEST_SECRET,
261
+ algorithms=["HS256"],
262
+ issuer="todoweb",
263
+ audience="todoweb-api"
264
+ )
265
+
266
+
267
+ if __name__ == "__main__":
268
+ pytest.main([__file__, "-v"])
tests/test_todos.py ADDED
@@ -0,0 +1,525 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Todo API Endpoint Tests
3
+
4
+ Purpose: Validate all 6 Todo API endpoints with authentication
5
+ Tests: Create, List, Get, Update, Delete, Toggle Completion
6
+
7
+ Constitutional Requirements:
8
+ - REQUIRED: All endpoints must enforce JWT authentication
9
+ - REQUIRED: All endpoints must enforce user isolation
10
+ - REQUIRED: Proper HTTP status codes (201, 200, 204, 404, 422)
11
+ - REQUIRED: Input validation using Pydantic models
12
+ """
13
+
14
+ import pytest
15
+ from httpx import AsyncClient
16
+ from datetime import datetime, timedelta
17
+ from jose import jwt
18
+ import os
19
+ from uuid import uuid4
20
+
21
+ # Test secret
22
+ TEST_SECRET = os.getenv("BETTER_AUTH_SECRET", "test-secret-for-testing-only")
23
+
24
+ # Base URL for API
25
+ BASE_URL = "http://localhost:8000"
26
+
27
+
28
+ def create_test_token(user_id: str) -> str:
29
+ """Create a test JWT token for a specific user"""
30
+ payload = {
31
+ "sub": user_id,
32
+ "iat": datetime.utcnow(),
33
+ "exp": datetime.utcnow() + timedelta(days=1),
34
+ "iss": "todoweb",
35
+ "aud": "todoweb-api"
36
+ }
37
+ return jwt.encode(payload, TEST_SECRET, algorithm="HS256")
38
+
39
+
40
+ class TestHealthEndpoint:
41
+ """Test health check endpoint"""
42
+
43
+ @pytest.mark.asyncio
44
+ async def test_health_check(self):
45
+ """Test that health endpoint returns 200"""
46
+ async with AsyncClient(base_url=BASE_URL, timeout=30.0) as client:
47
+ response = await client.get("/health")
48
+ assert response.status_code == 200
49
+ data = response.json()
50
+ assert data["status"] == "healthy"
51
+
52
+
53
+ class TestCreateTodoEndpoint:
54
+ """Test POST /api/todos endpoint"""
55
+
56
+ @pytest.mark.asyncio
57
+ async def test_create_todo_success(self):
58
+ """Test creating a todo with valid data"""
59
+ async with AsyncClient(base_url=BASE_URL, timeout=30.0) as client:
60
+ token = create_test_token("user_123")
61
+ response = await client.post(
62
+ "/api/todos",
63
+ json={
64
+ "title": "Buy groceries",
65
+ "description": "Milk, eggs, bread"
66
+ },
67
+ headers={"Authorization": f"Bearer {token}"}
68
+ )
69
+
70
+ assert response.status_code == 201
71
+ data = response.json()
72
+ assert data["title"] == "Buy groceries"
73
+ assert data["description"] == "Milk, eggs, bread"
74
+ assert data["is_completed"] is False
75
+ assert "id" in data
76
+ assert "created_at" in data
77
+ assert "updated_at" in data
78
+
79
+ @pytest.mark.asyncio
80
+ async def test_create_todo_without_description(self):
81
+ """Test creating a todo without description (optional field)"""
82
+ async with AsyncClient(base_url=BASE_URL, timeout=30.0) as client:
83
+ token = create_test_token("user_123")
84
+ response = await client.post(
85
+ "/api/todos",
86
+ json={"title": "Simple task"},
87
+ headers={"Authorization": f"Bearer {token}"}
88
+ )
89
+
90
+ assert response.status_code == 201
91
+ data = response.json()
92
+ assert data["title"] == "Simple task"
93
+ assert data["description"] is None or data["description"] == ""
94
+
95
+ @pytest.mark.asyncio
96
+ async def test_create_todo_empty_title(self):
97
+ """Test that empty title returns 422 validation error"""
98
+ async with AsyncClient(base_url=BASE_URL, timeout=30.0) as client:
99
+ token = create_test_token("user_123")
100
+ response = await client.post(
101
+ "/api/todos",
102
+ json={"title": "", "description": "Test"},
103
+ headers={"Authorization": f"Bearer {token}"}
104
+ )
105
+
106
+ assert response.status_code == 422
107
+
108
+ @pytest.mark.asyncio
109
+ async def test_create_todo_missing_title(self):
110
+ """Test that missing title returns 422 validation error"""
111
+ async with AsyncClient(base_url=BASE_URL, timeout=30.0) as client:
112
+ token = create_test_token("user_123")
113
+ response = await client.post(
114
+ "/api/todos",
115
+ json={"description": "Test"},
116
+ headers={"Authorization": f"Bearer {token}"}
117
+ )
118
+
119
+ assert response.status_code == 422
120
+
121
+ @pytest.mark.asyncio
122
+ async def test_create_todo_title_too_long(self):
123
+ """Test that title exceeding max length returns 422"""
124
+ async with AsyncClient(base_url=BASE_URL, timeout=30.0) as client:
125
+ token = create_test_token("user_123")
126
+ long_title = "x" * 201 # Exceeds 200 character limit
127
+ response = await client.post(
128
+ "/api/todos",
129
+ json={"title": long_title, "description": "Test"},
130
+ headers={"Authorization": f"Bearer {token}"}
131
+ )
132
+
133
+ assert response.status_code == 422
134
+
135
+ @pytest.mark.asyncio
136
+ async def test_create_todo_without_auth(self):
137
+ """Test that creating todo without auth returns 401"""
138
+ async with AsyncClient(base_url=BASE_URL, timeout=30.0) as client:
139
+ response = await client.post(
140
+ "/api/todos",
141
+ json={"title": "Test", "description": "Test"}
142
+ )
143
+
144
+ assert response.status_code == 401
145
+
146
+
147
+ class TestListTodosEndpoint:
148
+ """Test GET /api/todos endpoint"""
149
+
150
+ @pytest.mark.asyncio
151
+ async def test_list_todos_empty(self):
152
+ """Test listing todos when user has none"""
153
+ async with AsyncClient(base_url=BASE_URL, timeout=30.0) as client:
154
+ token = create_test_token(f"user_{uuid4()}")
155
+ response = await client.get(
156
+ "/api/todos",
157
+ headers={"Authorization": f"Bearer {token}"}
158
+ )
159
+
160
+ assert response.status_code == 200
161
+ data = response.json()
162
+ assert isinstance(data, list)
163
+ assert len(data) == 0
164
+
165
+ @pytest.mark.asyncio
166
+ async def test_list_todos_with_items(self):
167
+ """Test listing todos when user has multiple todos"""
168
+ async with AsyncClient(base_url=BASE_URL, timeout=30.0) as client:
169
+ user_id = f"user_{uuid4()}"
170
+ token = create_test_token(user_id)
171
+
172
+ # Create 3 todos
173
+ for i in range(3):
174
+ await client.post(
175
+ "/api/todos",
176
+ json={"title": f"Task {i}", "description": f"Description {i}"},
177
+ headers={"Authorization": f"Bearer {token}"}
178
+ )
179
+
180
+ # List todos
181
+ response = await client.get(
182
+ "/api/todos",
183
+ headers={"Authorization": f"Bearer {token}"}
184
+ )
185
+
186
+ assert response.status_code == 200
187
+ data = response.json()
188
+ assert len(data) == 3
189
+
190
+ @pytest.mark.asyncio
191
+ async def test_list_todos_without_auth(self):
192
+ """Test that listing todos without auth returns 401"""
193
+ async with AsyncClient(base_url=BASE_URL, timeout=30.0) as client:
194
+ response = await client.get("/api/todos")
195
+ assert response.status_code == 401
196
+
197
+
198
+ class TestGetTodoEndpoint:
199
+ """Test GET /api/todos/{id} endpoint"""
200
+
201
+ @pytest.mark.asyncio
202
+ async def test_get_todo_success(self):
203
+ """Test getting a specific todo by ID"""
204
+ async with AsyncClient(base_url=BASE_URL, timeout=30.0) as client:
205
+ token = create_test_token("user_123")
206
+
207
+ # Create a todo
208
+ create_response = await client.post(
209
+ "/api/todos",
210
+ json={"title": "Test todo", "description": "Test description"},
211
+ headers={"Authorization": f"Bearer {token}"}
212
+ )
213
+ todo_id = create_response.json()["id"]
214
+
215
+ # Get the todo
216
+ response = await client.get(
217
+ f"/api/todos/{todo_id}",
218
+ headers={"Authorization": f"Bearer {token}"}
219
+ )
220
+
221
+ assert response.status_code == 200
222
+ data = response.json()
223
+ assert data["id"] == todo_id
224
+ assert data["title"] == "Test todo"
225
+ assert data["description"] == "Test description"
226
+
227
+ @pytest.mark.asyncio
228
+ async def test_get_todo_not_found(self):
229
+ """Test getting a non-existent todo returns 404"""
230
+ async with AsyncClient(base_url=BASE_URL, timeout=30.0) as client:
231
+ token = create_test_token("user_123")
232
+ fake_id = str(uuid4())
233
+
234
+ response = await client.get(
235
+ f"/api/todos/{fake_id}",
236
+ headers={"Authorization": f"Bearer {token}"}
237
+ )
238
+
239
+ assert response.status_code == 404
240
+
241
+ @pytest.mark.asyncio
242
+ async def test_get_todo_invalid_uuid(self):
243
+ """Test getting a todo with invalid UUID format"""
244
+ async with AsyncClient(base_url=BASE_URL, timeout=30.0) as client:
245
+ token = create_test_token("user_123")
246
+
247
+ response = await client.get(
248
+ "/api/todos/not-a-valid-uuid",
249
+ headers={"Authorization": f"Bearer {token}"}
250
+ )
251
+
252
+ assert response.status_code == 422
253
+
254
+ @pytest.mark.asyncio
255
+ async def test_get_todo_without_auth(self):
256
+ """Test that getting todo without auth returns 401"""
257
+ async with AsyncClient(base_url=BASE_URL, timeout=30.0) as client:
258
+ response = await client.get(f"/api/todos/{uuid4()}")
259
+ assert response.status_code == 401
260
+
261
+
262
+ class TestUpdateTodoEndpoint:
263
+ """Test PUT /api/todos/{id} endpoint"""
264
+
265
+ @pytest.mark.asyncio
266
+ async def test_update_todo_success(self):
267
+ """Test updating a todo with valid data"""
268
+ async with AsyncClient(base_url=BASE_URL, timeout=30.0) as client:
269
+ token = create_test_token("user_123")
270
+
271
+ # Create a todo
272
+ create_response = await client.post(
273
+ "/api/todos",
274
+ json={"title": "Original title", "description": "Original description"},
275
+ headers={"Authorization": f"Bearer {token}"}
276
+ )
277
+ todo_id = create_response.json()["id"]
278
+
279
+ # Update the todo
280
+ response = await client.put(
281
+ f"/api/todos/{todo_id}",
282
+ json={"title": "Updated title", "description": "Updated description"},
283
+ headers={"Authorization": f"Bearer {token}"}
284
+ )
285
+
286
+ assert response.status_code == 200
287
+ data = response.json()
288
+ assert data["title"] == "Updated title"
289
+ assert data["description"] == "Updated description"
290
+
291
+ @pytest.mark.asyncio
292
+ async def test_update_todo_partial(self):
293
+ """Test partial update (only title or description)"""
294
+ async with AsyncClient(base_url=BASE_URL, timeout=30.0) as client:
295
+ token = create_test_token("user_123")
296
+
297
+ # Create a todo
298
+ create_response = await client.post(
299
+ "/api/todos",
300
+ json={"title": "Original", "description": "Original"},
301
+ headers={"Authorization": f"Bearer {token}"}
302
+ )
303
+ todo_id = create_response.json()["id"]
304
+
305
+ # Update only title
306
+ response = await client.put(
307
+ f"/api/todos/{todo_id}",
308
+ json={"title": "New title"},
309
+ headers={"Authorization": f"Bearer {token}"}
310
+ )
311
+
312
+ assert response.status_code == 200
313
+ data = response.json()
314
+ assert data["title"] == "New title"
315
+
316
+ @pytest.mark.asyncio
317
+ async def test_update_todo_not_found(self):
318
+ """Test updating non-existent todo returns 404"""
319
+ async with AsyncClient(base_url=BASE_URL, timeout=30.0) as client:
320
+ token = create_test_token("user_123")
321
+ fake_id = str(uuid4())
322
+
323
+ response = await client.put(
324
+ f"/api/todos/{fake_id}",
325
+ json={"title": "Updated", "description": "Updated"},
326
+ headers={"Authorization": f"Bearer {token}"}
327
+ )
328
+
329
+ assert response.status_code == 404
330
+
331
+ @pytest.mark.asyncio
332
+ async def test_update_todo_without_auth(self):
333
+ """Test that updating todo without auth returns 401"""
334
+ async with AsyncClient(base_url=BASE_URL, timeout=30.0) as client:
335
+ response = await client.put(
336
+ f"/api/todos/{uuid4()}",
337
+ json={"title": "Updated"}
338
+ )
339
+ assert response.status_code == 401
340
+
341
+
342
+ class TestDeleteTodoEndpoint:
343
+ """Test DELETE /api/todos/{id} endpoint"""
344
+
345
+ @pytest.mark.asyncio
346
+ async def test_delete_todo_success(self):
347
+ """Test deleting a todo"""
348
+ async with AsyncClient(base_url=BASE_URL, timeout=30.0) as client:
349
+ token = create_test_token("user_123")
350
+
351
+ # Create a todo
352
+ create_response = await client.post(
353
+ "/api/todos",
354
+ json={"title": "To be deleted", "description": "Delete me"},
355
+ headers={"Authorization": f"Bearer {token}"}
356
+ )
357
+ todo_id = create_response.json()["id"]
358
+
359
+ # Delete the todo
360
+ response = await client.delete(
361
+ f"/api/todos/{todo_id}",
362
+ headers={"Authorization": f"Bearer {token}"}
363
+ )
364
+
365
+ assert response.status_code == 204
366
+
367
+ # Verify todo is deleted
368
+ get_response = await client.get(
369
+ f"/api/todos/{todo_id}",
370
+ headers={"Authorization": f"Bearer {token}"}
371
+ )
372
+ assert get_response.status_code == 404
373
+
374
+ @pytest.mark.asyncio
375
+ async def test_delete_todo_not_found(self):
376
+ """Test deleting non-existent todo returns 404"""
377
+ async with AsyncClient(base_url=BASE_URL, timeout=30.0) as client:
378
+ token = create_test_token("user_123")
379
+ fake_id = str(uuid4())
380
+
381
+ response = await client.delete(
382
+ f"/api/todos/{fake_id}",
383
+ headers={"Authorization": f"Bearer {token}"}
384
+ )
385
+
386
+ assert response.status_code == 404
387
+
388
+ @pytest.mark.asyncio
389
+ async def test_delete_todo_without_auth(self):
390
+ """Test that deleting todo without auth returns 401"""
391
+ async with AsyncClient(base_url=BASE_URL, timeout=30.0) as client:
392
+ response = await client.delete(f"/api/todos/{uuid4()}")
393
+ assert response.status_code == 401
394
+
395
+
396
+ class TestToggleCompletionEndpoint:
397
+ """Test PATCH /api/todos/{id}/complete endpoint"""
398
+
399
+ @pytest.mark.asyncio
400
+ async def test_toggle_completion_to_complete(self):
401
+ """Test marking a todo as complete"""
402
+ async with AsyncClient(base_url=BASE_URL, timeout=30.0) as client:
403
+ token = create_test_token("user_123")
404
+
405
+ # Create a todo (default is incomplete)
406
+ create_response = await client.post(
407
+ "/api/todos",
408
+ json={"title": "Task to complete", "description": "Mark as done"},
409
+ headers={"Authorization": f"Bearer {token}"}
410
+ )
411
+ todo_id = create_response.json()["id"]
412
+ assert create_response.json()["is_completed"] is False
413
+
414
+ # Toggle to complete
415
+ response = await client.patch(
416
+ f"/api/todos/{todo_id}/complete",
417
+ headers={"Authorization": f"Bearer {token}"}
418
+ )
419
+
420
+ assert response.status_code == 200
421
+ data = response.json()
422
+ assert data["is_completed"] is True
423
+
424
+ @pytest.mark.asyncio
425
+ async def test_toggle_completion_to_incomplete(self):
426
+ """Test marking a completed todo as incomplete"""
427
+ async with AsyncClient(base_url=BASE_URL, timeout=30.0) as client:
428
+ token = create_test_token("user_123")
429
+
430
+ # Create and complete a todo
431
+ create_response = await client.post(
432
+ "/api/todos",
433
+ json={"title": "Completed task", "description": "Already done"},
434
+ headers={"Authorization": f"Bearer {token}"}
435
+ )
436
+ todo_id = create_response.json()["id"]
437
+
438
+ # Toggle to complete
439
+ await client.patch(
440
+ f"/api/todos/{todo_id}/complete",
441
+ headers={"Authorization": f"Bearer {token}"}
442
+ )
443
+
444
+ # Toggle back to incomplete
445
+ response = await client.patch(
446
+ f"/api/todos/{todo_id}/complete",
447
+ headers={"Authorization": f"Bearer {token}"}
448
+ )
449
+
450
+ assert response.status_code == 200
451
+ data = response.json()
452
+ assert data["is_completed"] is False
453
+
454
+ @pytest.mark.asyncio
455
+ async def test_toggle_completion_not_found(self):
456
+ """Test toggling completion of non-existent todo returns 404"""
457
+ async with AsyncClient(base_url=BASE_URL, timeout=30.0) as client:
458
+ token = create_test_token("user_123")
459
+ fake_id = str(uuid4())
460
+
461
+ response = await client.patch(
462
+ f"/api/todos/{fake_id}/complete",
463
+ headers={"Authorization": f"Bearer {token}"}
464
+ )
465
+
466
+ assert response.status_code == 404
467
+
468
+ @pytest.mark.asyncio
469
+ async def test_toggle_completion_without_auth(self):
470
+ """Test that toggling completion without auth returns 401"""
471
+ async with AsyncClient(base_url=BASE_URL, timeout=30.0) as client:
472
+ response = await client.patch(f"/api/todos/{uuid4()}/complete")
473
+ assert response.status_code == 401
474
+
475
+
476
+ class TestInputValidation:
477
+ """Test input validation across endpoints"""
478
+
479
+ @pytest.mark.asyncio
480
+ async def test_create_todo_with_extra_fields(self):
481
+ """Test that extra fields are ignored"""
482
+ async with AsyncClient(base_url=BASE_URL, timeout=30.0) as client:
483
+ token = create_test_token("user_123")
484
+ response = await client.post(
485
+ "/api/todos",
486
+ json={
487
+ "title": "Valid todo",
488
+ "description": "Valid description",
489
+ "extra_field": "Should be ignored",
490
+ "another_field": 123
491
+ },
492
+ headers={"Authorization": f"Bearer {token}"}
493
+ )
494
+
495
+ assert response.status_code == 201
496
+ data = response.json()
497
+ assert "extra_field" not in data
498
+ assert "another_field" not in data
499
+
500
+ @pytest.mark.asyncio
501
+ async def test_update_todo_with_invalid_data_type(self):
502
+ """Test that invalid data types return 422"""
503
+ async with AsyncClient(base_url=BASE_URL, timeout=30.0) as client:
504
+ token = create_test_token("user_123")
505
+
506
+ # Create a todo
507
+ create_response = await client.post(
508
+ "/api/todos",
509
+ json={"title": "Test", "description": "Test"},
510
+ headers={"Authorization": f"Bearer {token}"}
511
+ )
512
+ todo_id = create_response.json()["id"]
513
+
514
+ # Try to update with invalid data type
515
+ response = await client.put(
516
+ f"/api/todos/{todo_id}",
517
+ json={"title": 123}, # Should be string
518
+ headers={"Authorization": f"Bearer {token}"}
519
+ )
520
+
521
+ assert response.status_code == 422
522
+
523
+
524
+ if __name__ == "__main__":
525
+ pytest.main([__file__, "-v"])