feat(db): implement database configuration, migrations, and CLI commands#2
Merged
raychrisgdp merged 19 commits intomainfrom Dec 31, 2025
Merged
feat(db): implement database configuration, migrations, and CLI commands#2raychrisgdp merged 19 commits intomainfrom
raychrisgdp merged 19 commits intomainfrom
Conversation
- Update `.gitignore` to include coverage and pytest cache files for cleaner version control. - Modify `.pre-commit-config.yaml` to set a maximum file size for large files and exclude specific files from checks. - Introduce `AGENTS.md` as a concise guide for AI agents, detailing project structure and quickstart commands. - Expand `Makefile` with new targets for testing coverage and specific PR dependencies. - Update `README.md` to reference the new `AGENTS.md` for developers and agents. - Add CI workflow configuration for automated linting and testing on pull requests. These changes improve the development experience and provide clearer guidance for contributors.
- Update `.gitignore` to retain `.cursor/commands/` while excluding other cursor files for better version control. - Add new command documentation for `post-review`, `pr-desc`, `review`, and `test-ac` to improve developer guidance and testing processes. - Introduce new test results documentation structure to validate acceptance criteria for PR specifications. - Implement automatic database migration execution on FastAPI startup to ensure compliance with project specifications. These changes improve the development workflow, enhance documentation clarity, and ensure better adherence to project requirements.
- Remove unnecessary import statements from test files to improve clarity and maintainability. - Introduce new tests for migration scenarios, including cases for when the alembic_version table exists and when it does not. - Enhance exception handling tests to ensure proper behavior during database migration checks. These changes streamline the test code and improve coverage for migration-related functionality.
- Add automated test for AC1: test_fastapi_lifespan_creates_db_and_runs_migrations Verifies FastAPI startup creates DB and runs migrations automatically Tests that all required tables exist: tasks, attachments, notifications, chat_history, config, alembic_version - Update .env.example to only include PR-001 relevant environment variables Removed LLM, Gmail, GitHub, and Notifications env vars Those belong to their respective PRs (PR-003, PR-006, PR-007, PR-011) - Remove .cursor/commands directory (development tooling outside spec scope) - Add .env.example update checklist items to relevant PR specs PR-002: Verify existing env vars (no new ones) PR-003-1: Add LLM_API_KEY, LLM_BASE_URL, LLM_MODEL PR-006: Add GMAIL_ENABLED, GMAIL_CREDENTIALS_PATH PR-007: Add GITHUB_TOKEN, GITHUB_USERNAME PR-011: Add NOTIFICATIONS_ENABLED, NOTIFICATION_SCHEDULE
Remove exception for .cursor/commands/ since .cursor files are development tooling outside PR scope and should not be tracked
Remove temporary PR spec files that were created to document .env.example requirements: - SKILL_ENRICHMENT_SUMMARY.md - PR-003-1 (llm-provider) - PR-003-2 (streaming-chat-api) - PR-003-3 (tui-chat-integration) - PR-005-1 (chromadb-embeddings) - PR-005-2 (semantic-search-rag) These files were exploratory and will be created properly in their respective PR implementations.
Revert changes to existing PR specs that were made during .env.example update. The .env.example checklist items should be added in their respective implementation PRs (PR-003-1, PR-006, PR-007, PR-011). Affected files: - PR-PLANS.md - PR-specs/INDEX.md - PR-002 through PR-012 (13 files total)
PR-PLANS.md had merge markers after restoration. Committing as-is to mark that these will be resolved when future PRs add their .env.example checklist items.
Restoring PR-PLANS.md to original version from before .env.example modifications. This file should only receive .env.example updates in its respective implementation PRs.
Resolve merge conflict by keeping approved version (0 findings). Remove git conflict markers from reviews/REVIEW_c-pr-001-db-config.md.
- Refactor `.gitignore` to streamline local artifact exclusions, specifically retaining `.opencode/skill`, `.uv-cache/`, and `.tmp/`. - Enhance `AGENTS.md` with detailed precommit workflow instructions and coding conventions, including common pitfalls and fixes. - Update `Makefile` to utilize `uv` for running commands, ensuring consistency in the development environment. - Add new testing guidelines in `TESTING_GUIDE.md` to address common issues and improve test organization. - Introduce a new command in `.cursor/commands` for fixing unit tests, providing a structured approach to achieving target coverage. - Update CI workflow to install `uv` as a dependency for better compatibility. These changes aim to improve the development process, enhance documentation clarity, and ensure better adherence to coding standards.
…flow - Refactor Makefile to consolidate dependency installation commands, enhancing clarity and efficiency. - Update `pyproject.toml` to include `pytest-xdist` for parallel test execution and `httpx` for FastAPI testing. - Modify database migration functions to ensure synchronous execution with appropriate error handling based on the environment. - Add tests to verify migration behavior and ensure timely completion, addressing potential issues with database initialization. These changes aim to streamline the development process, improve testing capabilities, and enhance error handling during migrations.
- Refactor Makefile to streamline the development environment setup by removing specific PR dependencies, focusing on core development dependencies. - Update `pyproject.toml` to clarify optional dependencies and enhance documentation regarding FastAPI and testing requirements. - Modify CI workflow to install dependencies using `uv`, ensuring a consistent installation process. - Revise setup documentation to reflect changes in dependency installation and provide clearer instructions for new developers. These updates aim to improve the development workflow, enhance clarity in dependency management, and ensure a smoother onboarding experience for contributors.
- Introduce asynchronous database initialization with `init_db_async()` to prevent blocking the event loop in async contexts. - Update CLI commands to ensure migrations run synchronously by converting async database URLs to sync URLs, avoiding potential asyncio conflicts. - Revise migration documentation to clarify the rationale for using sync URLs and the implementation details for both CLI and application startup. - Add tests to validate the async migration path and ensure timely completion of database upgrades. These changes aim to improve the reliability of database operations and enhance the overall development experience.
- Add a step to create a virtual environment using `uv venv` for better isolation of dependencies. - Modify linting commands to run through `uv`, ensuring consistency in the execution environment. These changes aim to improve the reliability of the CI process and streamline the development workflow.
- Update `.pre-commit-config.yaml` to include checks for both `backend` and `tests` directories. - Modify `Makefile` to streamline linting commands, ensuring both checking and formatting are applied to the specified directories. - Refactor CI workflow to utilize the updated `Makefile` for linting, improving consistency in the CI process. - Simplify database URL handling in `config.py` to strip query parameters more efficiently. - Add new tests to validate configuration precedence and database path handling, ensuring robustness in settings management. These changes aim to improve code quality, streamline development processes, and enhance the reliability of configuration handling.
- Update `AGENTS.md` to clarify the use of `init_db_async()` in FastAPI lifespan to prevent event loop blocking. - Modify `AGENT_GUIDE.md` to include detailed explanations on stripping query parameters from SQLite URLs in the `database_path` property. - Ensure migration URLs are converted to sync format to avoid asyncio conflicts, with documentation updates reflecting these changes. These updates aim to improve database initialization practices and enhance clarity in the documentation for better developer understanding.
- Remove caching configuration for pip in the CI workflow to streamline the dependency installation process. - Ensure the workflow continues to utilize `uv` for setting up the environment and installing necessary packages. These changes aim to simplify the CI process and improve the reliability of dependency management.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
Issues & Goals
.env→~/.taskgenie/config.toml→ defaults) for consistent app behavior across environmentstgenie db upgrade,downgrade,dump,restore)Implementation Highlights
backend/config.py): env vars →.envfile →~/.taskgenie/config.toml→ built-in defaults, with TOML config file support and automatic app directory creationbackend/database.py) with automatic migration execution on startup, foreign key enforcement for SQLite, and proper session management with dependency injection supportbackend/migrations/) with SQLite-specific setup, initial schema migration (001_initial_schema.py) creating tables fortasks,attachments,notifications,chat_history,config, andalembic_versiontgenie dbsubcommands (backend/cli/db.py):upgrade,downgrade,revision(with autogenerate),dump, andrestorewith confirmation prompts for destructive operationsbackend/models/) forTask,Attachment,Notification,ChatHistory, andConfigwith proper relationships, JSON fields, and timestamp managementbackend/main.pywith lifespan management to initialize database on startup and close connections on shutdowntests/) including configuration tests, database initialization tests, migration tests, CLI command tests, and model validation testsdocs/02-implementation/MIGRATIONS.md), agent guide (docs/02-implementation/AGENT_GUIDE.md), and updated PR specificationsKey Files Modified:
backend/config.py: Complete rewrite with Pydantic Settings, TOML config support, and multi-source precedence (250 lines added)backend/database.py: Database initialization with async SQLAlchemy, automatic migrations, and session management (175 lines added)backend/cli/db.py: New CLI module for database management commands (174 lines)backend/migrations/: Alembic configuration and initial schema migration (new directory)backend/models/: SQLAlchemy models for Task, Attachment, Notification, ChatHistory, Config (new files)backend/main.py: Added lifespan management for database initialization (30 lines modified)tests/: Comprehensive test suite covering config, database, migrations, CLI, and models (1622+ lines added)docs/02-implementation/MIGRATIONS.md: Migration guide with examples (219 lines)docs/02-implementation/AGENT_GUIDE.md: Agent workflow guide (811 lines)pyproject.toml: Added dependencies (alembic, pydantic-settings, tomllib) and test configuration (71 lines modified)How to Test
Database Configuration Testing
Configuration Precedence Verification:
Test environment variable override:
Test
.envfile:Test config.toml file:
Test default behavior:
Database Initialization Testing
Fresh Install Test (AC1):
Clean start:
Verify database creation:
Test health endpoint:
curl http://localhost:8000/health # Expected: {"status":"ok","version":"..."}CLI Database Commands Testing
Migration Commands:
Upgrade database:
uv run tgenie db upgrade # Expected: "✓ Database upgraded to head"Check current revision:
Create new migration (if schema changes):
Apply new migration:
uv run tgenie db upgrade head # Expected: "✓ Database upgraded to head"Test downgrade:
uv run tgenie db downgrade -1 # Expected: "✓ Database downgraded to -1"Backup/Restore Commands:
Create test data:
Dump database:
Restore database:
Data Model Testing
Model Validation:
Test Task model:
Test relationships:
Integration Testing
End-to-End Workflow:
Complete setup flow:
CLI-to-API integration:
Automated Testing
Run test suite:
Expected Test Coverage:
tests/test_config.py)tests/test_database.py)tests/cli/test_db.py)tests/models/)tests/test_migrations_env.py)Expected Behavior
~/.taskgenie/data/taskgenie.db(or configured path)alembic_versiontable is missingtgenie dbcommands execute successfully with proper error handling and user feedbackRelated Issues
docs/02-implementation/pr-specs/PR-001-db-config.md)Author Checklist
mainbranchAdditional Notes
Key Implementation Areas for Review
Configuration System (
backend/config.py):.env→~/.taskgenie/config.toml→ defaultsTaskGenieTomlSettingsSourcefor loading and flattening TOML configuration filesensure_app_dirs()method creates required directories (data/,cache/,logs/,vector_store/) with proper permissionsdatabase_url_resolvedproperty handles SQLite path resolution and async driver configurationDatabase Initialization (
backend/database.py):_run_migrations_if_needed()checks for database existence andalembic_versiontable, runs migrations automatically on startupPRAGMA foreign_keys=ONexecuted on every session to ensure referential integrityget_db()dependency injection generator with proper commit/rollback/close handlingAlembic Migrations (
backend/migrations/):001_initial_schema.pycreates tables fortasks,attachments,notifications,chat_history,config, andalembic_versionenv.pyconfigured for async SQLAlchemy with SQLite, handlesPRAGMA foreign_keys=ONsqlite+aiosqlite://) to sync URLs (sqlite://) to avoid asyncio conflicts during migrationsCLI Database Commands (
backend/cli/db.py):--autogenerateflag for automatic migration generation from model changes.dumpworkflow with confirmation prompts for destructive operationsget_alembic_cfg()resolves Alembic config from project structure and settings, converts async URLs to sync URLs for migrationsData Models (
backend/models/):FastAPI Integration (
backend/main.py):lifespan()context manager initializes database on startup and closes connections on shutdowninit_db()which automatically runs migrations if neededTesting (
tests/):Testing Notes
~/.taskgenie/data/taskgenie.db. Can be overridden viaTASKGENIE_DATA_DIRenv var ordatabase.urlin config.toml.alembic_versiontable is missing. This satisfies AC1 requirement for fresh install.PRAGMA foreign_keys=ON. Reviewers should verify this works correctly.sqlite+aiosqlite://) to sync URLs (sqlite://) before passing them to Alembic to avoid asyncio conflicts. This ensures migrations run synchronously.Settingsclass should be updated to reflect this accurately (noted in review feedback).from __future__ import annotationsfor consistency (noted in review feedback). This should be addressed but doesn't affect functionality.Manual Verification Checklist
make testand verify all tests pass~/.taskgenie/data/taskgenie.dband start API, verify database is created automaticallytasks,attachments,notifications,chat_history,config,alembic_versionuv run tgenie db upgradecommanduv run tgenie db downgrade -1commanduv run tgenie db dump --out backup.sql, verify backup file is createduv run tgenie db restore --in backup.sql, verify data is restoredcurl http://localhost:8000/healthbackend/migrations/versions/001_initial_schema.pyfor correctness~/.taskgenie/data/,cache/,logs/,vector_store/are created