### Install Project Dependencies Source: https://github.com/dennisrongo/spec-forge/blob/main/README.md Install all necessary project dependencies using pnpm. ```bash pnpm install ``` -------------------------------- ### Start Development Servers Source: https://github.com/dennisrongo/spec-forge/blob/main/README.md Start both the Next.js application and the Trigger.dev development server concurrently using pnpm. ```bash pnpm dev ``` -------------------------------- ### Start Development Server Source: https://github.com/dennisrongo/spec-forge/blob/main/tests/QUICKSTART.md Run this command in your terminal to start the development server, which is necessary before running tests or the application. ```bash pnpm dev:next ``` -------------------------------- ### Start Production Server Source: https://github.com/dennisrongo/spec-forge/blob/main/README.md Launches the production-ready server after the project has been built. ```bash pnpm start ``` -------------------------------- ### Start Development Server Source: https://github.com/dennisrongo/spec-forge/blob/main/tests/QUICKSTART.md Launch the Next.js development server in one terminal. ```bash # Terminal 1: Start Next.js pnpm dev:next ``` -------------------------------- ### Example Tech Stack Output Format Source: https://github.com/dennisrongo/spec-forge/blob/main/docs/VERSION_FETCHING.md An example of how the tech stack might be displayed in a markdown card, including technology names and their latest versions. ```markdown ## Tech Stack - Frontend: React 18.3.1, Next.js 15.1.0 - Backend: Express 4.19.2 - Database: PostgreSQL 16.2 ``` -------------------------------- ### Install Dependencies and Playwright Browsers Source: https://github.com/dennisrongo/spec-forge/blob/main/tests/README.md Installs project dependencies using pnpm and downloads the necessary Playwright browsers for testing. ```bash pnpm install npx playwright install chromium ``` -------------------------------- ### Copy Environment File Source: https://github.com/dennisrongo/spec-forge/blob/main/README.md Copy the example environment file to create a local configuration file. ```bash cp .env.example .env.local ``` -------------------------------- ### Install Playwright Dependencies Source: https://github.com/dennisrongo/spec-forge/blob/main/tests/QUICKSTART.md Install project dependencies and Playwright browsers. Ensure you have `pnpm` installed. ```bash pnpm install npx playwright install chromium ``` -------------------------------- ### User Creation and AI Provider Setup Source: https://github.com/dennisrongo/spec-forge/blob/main/tests/AI_PROVIDER_SETUP.md This code snippet demonstrates how a new user is created in the test environment, which automatically triggers the setup of the AI provider for that user. ```typescript const userId = await testData.createUser(name, email, password) // Automatically calls setupUserAIProvider(userId) which: // 1. Reads STRAICO_API_KEY from env // 2. Encrypts it // 3. Stores in user_preferences // 4. Sets model to 'openai/gpt-5-mini' ``` -------------------------------- ### Cleanup Logging Example Source: https://github.com/dennisrongo/spec-forge/blob/main/tests/CLEANUP_GUIDE.md Example log output showing the detailed steps and outcomes of the test data cleanup process, including user and project deletions. ```log [Test Fixture] Running cleanup... [Test Helper] Starting cleanup (1 users, 1 projects)... [Test Helper] Deleted user 123e4567-e89b-12d3-a456-426614174000 and all associated data [Test Helper] ✓ Cleaned up user 123e4567-e89b-12d3-a456-426614174000 [Test Helper] ✓ Cleanup complete - Removed 1 users and 1 projects [Test Fixture] Cleanup completed ``` -------------------------------- ### Quick Start: Set up Environment Variables and Run Tests Source: https://github.com/dennisrongo/spec-forge/blob/main/tests/API_KEY_SETUP_SUMMARY.md Use these bash commands to quickly set up your `.env.local` file with necessary API keys and then run the E2E tests. ```bash # 1. Add environment variables to .env.local echo "STRAICO_API_KEY=your_key" >> .env.local echo "ENCRYPTION_KEY=$(openssl rand -base64 32)" >> .env.local # 2. Install dependencies pnpm install npx playwright install chromium # 3. Run tests pnpm dev:next # Terminal 1 pnpm test # Terminal 2 ``` -------------------------------- ### Run Development Server and Tests Source: https://github.com/dennisrongo/spec-forge/blob/main/tests/README.md Starts the development server for the Next.js application in one terminal and runs the end-to-end tests in another. ```bash # Start development server pnpm dev:next # In another terminal, run tests pnpm test ``` -------------------------------- ### Basic Test Structure with Fixtures Source: https://github.com/dennisrongo/spec-forge/blob/main/tests/README.md Demonstrates a basic test case using imported fixtures for setup and assertions. Ensure 'auth.fixture' is correctly configured. ```typescript import { test, expect } from '../fixtures/auth.fixture' test.describe('My Feature', () => { test('should do something', async ({ projectPage, testData }) => { // Arrange const project = testData.generateTestProject() // Act await projectPage.createProject(project.title, project.description) // Assert await projectPage.expectProjectCreated() }) }) ``` -------------------------------- ### Context7 API JSON Response Example Source: https://github.com/dennisrongo/spec-forge/blob/main/docs/VERSION_FETCHING.md Example of the JSON structure returned by Context7's search API, containing version information for a library. ```json { "id": "/vercel/next.js", "title": "Next.js", "description": "Next.js enables you to create full-stack web applications...", "versions": [ "v14.3.0-canary.87", "v13.5.11", "v15.1.8", "v15.4.0-canary.82", "v12.3.7" ], "stars": 131745, "trustScore": 10 } ``` -------------------------------- ### Database Insertion of User Preferences Source: https://github.com/dennisrongo/spec-forge/blob/main/tests/AI_PROVIDER_SETUP.md Shows an example SQL INSERT statement for the `user_preferences` table, detailing the values for `user_id`, `active_ai_provider`, `straico_api_key_encrypted`, and `straico_model`. ```sql -- New user preferences are inserted INSERT INTO user_preferences ( user_id, active_ai_provider, straico_api_key_encrypted, straico_model ) VALUES ( '123e4567-e89b-12d3-a456-426614174000', 'straico', 'a1b2c3d4e5f6...', -- encrypted key 'openai/gpt-5-mini' ) ``` -------------------------------- ### Development Commands for Spec-Forge Source: https://github.com/dennisrongo/spec-forge/blob/main/CLAUDE.md Commands for installing dependencies, running development servers for Next.js and Trigger.dev, and managing database migrations. ```bash # Development pnpm install # Install dependencies pnpm dev # Run Next.js + Trigger.dev dev servers concurrently pnpm dev:next # Run only Next.js dev server (localhost:3000) pnpm dev:trigger # Run only Trigger.dev dev server # Database npx tsx scripts/run-all-migrations.ts # Run all migrations in order npx tsx scripts/run-migrations.ts # Run specific migration # Production pnpm build # Build for production pnpm start # Start production server pnpm lint # Run ESLint ``` -------------------------------- ### Access Application Source: https://github.com/dennisrongo/spec-forge/blob/main/README.md Access the running Spec-Forge application in your browser at http://localhost:3000. Follow the on-screen instructions to sign up and start creating project specifications. ```text http://localhost:3000 - Click **"Sign up"** to create your account - Enter your name, email, and password - Start creating AI-powered project specifications! ``` -------------------------------- ### Multiple Users Cleanup Scenario Source: https://github.com/dennisrongo/spec-forge/blob/main/tests/CLEANUP_GUIDE.md Example demonstrating how the cleanup process handles multiple users created within a single test, ensuring all are deleted. ```typescript test('user isolation', async ({ testData }) => { const user1 = await testData.createUser('User 1', 'user1@test.com', 'pass') const user2 = await testData.createUser('User 2', 'user2@test.com', 'pass') // Test logic // Cleanup deletes BOTH users }) ``` -------------------------------- ### Run Trigger.dev Development Server Source: https://github.com/dennisrongo/spec-forge/blob/main/README.md Starts only the Trigger.dev development server, which runs background task workers. ```bash pnpm dev:trigger ``` -------------------------------- ### Playwright Fixtures Example Source: https://github.com/dennisrongo/spec-forge/blob/main/tests/QUICKSTART.md Demonstrates the usage of various pre-configured fixtures available in Playwright tests for common actions like authentication, page navigation, and data generation. ```typescript test('example', async ({ authenticatedPage, // Already logged in authPage, // Login/signup actions projectPage, // Project creation featuresPage, // Feature selection clarifyPage, // Clarifying questions techStackPage, // Tech stack selection outputPage, // View specifications testData, // Database helpers testUser, // Generated test user }) => { // Your test code }) ``` -------------------------------- ### Example Query-Based Cache Entry Source: https://github.com/dennisrongo/spec-forge/blob/main/README.md This entry illustrates the format of cached version information used for queries. It includes details like library ID, name, query type, the query text, and the cached documentation version. This cache is reusable across projects. ```yaml library_id: /tanstack/query library_name: TanStack Query category: version query_type: latest_version query_text: What is the latest version of TanStack Query? documentation: v5_84_1 ``` -------------------------------- ### Successful Test Cleanup Scenario Source: https://github.com/dennisrongo/spec-forge/blob/main/tests/CLEANUP_GUIDE.md Example of a successful test case, showing the typical flow from user creation to project creation, followed by automatic cleanup. ```typescript test('create project', async ({ projectPage, testData, testUser }) => { // 1. User created in database // 2. User signs in // 3. Test actions await projectPage.createProject('Test', 'Description') // 4. Test completes // 5. Cleanup runs automatically // 6. All data deleted }) ``` -------------------------------- ### GET API Route for Project Retrieval Source: https://github.com/dennisrongo/spec-forge/blob/main/CLAUDE.md Handles GET requests to retrieve a specific project by ID. It includes authentication, parameter extraction, and user-specific data querying with error logging for not found projects. ```typescript import { auth } from "@/lib/auth" import { sql } from "@/lib/db" import { NextResponse } from "next/server" export async function GET(req: Request, { params }: { params: Promise<{ id: string }> }) { // 1. Authenticate const session = await auth() if (!session?.user?.id) return NextResponse.json({ error: "Unauthorized" }, { status: 401 }) // 2. Extract params (Next.js 16 async params) const { id } = await params // 3. Query with user isolation const [project] = await sql` SELECT * FROM projects WHERE id = ${id} AND user_id = ${session.user.id} ` // 4. Error logging with [SpecForge] prefix if (!project) { console.error(`[SpecForge] Project ${id} not found for user ${session.user.id}`) return NextResponse.json({ error: "Not found" }, { status: 404 }) } return NextResponse.json(project) } ``` -------------------------------- ### Automated Test User AI Provider Setup Source: https://github.com/dennisrongo/spec-forge/blob/main/tests/API_KEY_SETUP_SUMMARY.md This TypeScript code illustrates the automated process when a test user is created. It handles API key retrieval, encryption, storage, and AI provider activation. ```typescript // When you create a test user const userId = await testData.createUser('Test User', 'test@example.com', 'password') // Automatically: // ✅ Retrieves STRAICO_API_KEY from environment // ✅ Encrypts the key // ✅ Stores in user_preferences table // ✅ Sets model to 'openai/gpt-5-mini' // ✅ Activates Straico as the AI provider ``` -------------------------------- ### Console Logging Conventions Source: https://github.com/dennisrongo/spec-forge/blob/main/CLAUDE.md Standardizes console logging by prefixing all logs with '[SpecForge]'. This helps in identifying logs originating from this specific project, especially in shared environments. Includes examples for general and error logging. ```typescript console.log("[SpecForge] Starting spec generation for project:", projectId) console.error("[SpecForge] Context7 API error:", error) ``` -------------------------------- ### Complete User Journey Test Source: https://github.com/dennisrongo/spec-forge/blob/main/tests/QUICKSTART.md An example of a comprehensive end-to-end test that simulates a complete user journey, from project creation to verifying the final output. ```typescript test('complete user journey', async ({ projectPage, featuresPage, clarifyPage, techStackPage, outputPage, }) => { // Create project await projectPage.createProject('My App', 'Description') // Select features await featuresPage.selectMultipleFeatures(3) await featuresPage.continueToQuestions() // Answer questions await clarifyPage.answerQuestionsWithDefault(5) await clarifyPage.continueToTechStack() // Select tech await techStackPage.selectDefaultTechStack() await techStackPage.generateSpecifications() // Verify output await outputPage.expectGenerationComplete() await outputPage.expectPRDVisible() }) ``` -------------------------------- ### Defining Custom Test Fixtures Source: https://github.com/dennisrongo/spec-forge/blob/main/tests/README.md Illustrates how to create custom fixtures by extending the base test runner. This allows for reusable setup, usage, and cleanup logic for specific testing needs. ```typescript export const test = base.extend({ myFixture: async ({ page }, use) => { // Setup const fixture = new MyFixture(page) await fixture.setup() // Use in test await use(fixture) // Cleanup await fixture.cleanup() }, }) ``` -------------------------------- ### Independent Test Case Example Source: https://github.com/dennisrongo/spec-forge/blob/main/tests/README.md Demonstrates the best practice of creating independent test cases. Each test should set up its own data and state, avoiding dependencies on the execution order of other tests. ```typescript // ✅ Good: Each test is independent test('test 1', async ({ testData }) => { const user = testData.generateTestUser() await testData.createUser(user.name, user.email, user.password) // Test logic }) test('test 2', async ({ testData }) => { const user = testData.generateTestUser() await testData.createUser(user.name, user.email, user.password) // Different test logic }) ``` -------------------------------- ### Example Library Metadata Cache Entry Source: https://github.com/dennisrongo/spec-forge/blob/main/README.md This entry shows the structure of cached library metadata, including the library's name, ID, description, and latest version. This cache provides quick access to essential library details. ```yaml library_name: TanStack Query library_id: /tanstack/query description: Powerful asynchronous state management... latest_version: v5_84_1 ``` -------------------------------- ### Sync package-lock.json with npm install Source: https://github.com/dennisrongo/spec-forge/blob/main/README.md Use this command sequence to resolve GitHub Actions errors caused by an out-of-sync package-lock.json file after downgrading dependencies like NextAuth. This process removes the old lock file, generates a fresh one based on the current package.json, and then commits the changes. ```bash rm package-lock.json npm install git add package-lock.json package.json git commit -m "Sync package-lock.json after NextAuth v4 downgrade" git push ``` -------------------------------- ### Successful Test Cleanup Logs Source: https://github.com/dennisrongo/spec-forge/blob/main/tests/CLEANUP_GUIDE.md Log output corresponding to a successful test, detailing user creation, API key setup, project creation, and the subsequent cleanup process. ```log [Test Helper] Created user: test-123@specforge.test (uuid) [Test Helper] Set up Straico API key for user uuid [Test] Creating project... [Test Fixture] Running cleanup... [Test Helper] ✓ Cleaned up user uuid [Test Fixture] Cleanup completed ``` -------------------------------- ### Trigger.dev v4 Task Configuration Source: https://github.com/dennisrongo/spec-forge/blob/main/CLAUDE.md Example of configuring a Trigger.dev v4 task, including project ID, max duration, retry policy, and task directory. Ensure you use the v4 SDK. ```typescript import { task } from "@trigger.dev/sdk" // Configuration is typically done in trigger.config.ts // Project ID, Max duration: 3600s (1 hour), Retry policy: 3 attempts with exponential backoff, // Task directory: "./src/trigger" ``` -------------------------------- ### Using Authentication Fixture in Tests Source: https://github.com/dennisrongo/spec-forge/blob/main/tests/README.md Example of a test case utilizing the 'auth.fixture' which provides various pre-authenticated page objects and test data helpers. This fixture simplifies tests requiring authentication. ```typescript import { test, expect } from '../fixtures/auth.fixture' test('uses auth fixture', async ({ authenticatedPage, // Logged in page testUser, // User credentials with ID authPage, // Auth page object projectPage, // Project page object featuresPage, // Features page object clarifyPage, // Clarify page object techStackPage, // Tech stack page object outputPage, // Output page object testData, // Data helper }) => { // Test implementation }) ``` -------------------------------- ### Build Project for Production Source: https://github.com/dennisrongo/spec-forge/blob/main/README.md Compiles the project for production deployment. ```bash pnpm build ``` -------------------------------- ### Configure Trigger.dev Source: https://github.com/dennisrongo/spec-forge/blob/main/README.md Sign up for Trigger.dev, create a new project, and copy the development secret key to the TRIGGER_SECRET_KEY environment variable. ```bash # Sign up at https://trigger.dev # Create a new project # Copy the development secret key (tr_dev_...) to TRIGGER_SECRET_KEY ``` -------------------------------- ### Updating Playwright Dependencies Source: https://github.com/dennisrongo/spec-forge/blob/main/tests/README.md Update Playwright to the latest version using npm or pnpm, followed by installing the necessary browser binaries. ```bash pnpm add -D @playwright/test@latest npx playwright install ``` -------------------------------- ### Run Database Migration Script Source: https://github.com/dennisrongo/spec-forge/blob/main/docs/VERSION_FETCHING.md Command to execute the database migration script for creating the tech versions cache table. ```bash npm run tsx scripts/run-migration-035.ts ``` -------------------------------- ### Toast Notification Usage Source: https://github.com/dennisrongo/spec-forge/blob/main/CLAUDE.md Example of how to use the custom toast notification hook. Avoid using browser `alert` or `confirm` dialogs. ```typescript import { useToast } from "@/hooks/use-toast" const { toast } = useToast() toast({ variant: "destructive", title: "Error", description: "Message" }) ``` -------------------------------- ### Configure Environment Variables for Testing Source: https://github.com/dennisrongo/spec-forge/blob/main/tests/README.md Sets up essential environment variables in a .env.local file for database connection, authentication, AI provider API keys, and encryption. ```env # Database (Required) DATABASE_URL=postgresql://... # Authentication (Required) NEXTAUTH_SECRET=your-secret-key NEXTAUTH_URL=http://localhost:3000 # AI Provider (Required for E2E tests) # The test suite automatically configures Straico for test users STRAICO_API_KEY=your-straico-api-key # Encryption (Required for API key storage) ENCRYPTION_KEY=your-32-character-encryption-key-here # Context7 (Optional - gracefully degrades if not set) CONTEXT7_API_KEY=your-api-key # Trigger.dev (Required for spec generation tests) TRIGGER_SECRET_KEY=tr_dev_... ``` -------------------------------- ### Custom Feature Addition Test Source: https://github.com/dennisrongo/spec-forge/blob/main/tests/QUICKSTART.md An example test case for adding a custom feature to a project and verifying its presence in the list of features. ```typescript test('adds custom feature', async ({ projectPage, featuresPage }) => { await projectPage.createProject('Test', 'Description') await featuresPage.addCustomFeature( 'Custom Feature', 'Feature description', 'High', 'Medium' ) const features = await featuresPage.getFeatureNames() expect(features).toContain('Custom Feature') }) ``` -------------------------------- ### Environment-Specific API Keys Source: https://github.com/dennisrongo/spec-forge/blob/main/tests/AI_PROVIDER_SETUP.md Illustrates how to use different Straico API keys for development, CI/CD, and production environments to maintain security and isolation. ```bash # Development STRAICO_API_KEY=tr_dev_... # CI/CD STRAICO_API_KEY=tr_test_... # Production (app) STRAICO_API_KEY=tr_prod_... ``` -------------------------------- ### Create Trigger.dev Personal Access Token Source: https://github.com/dennisrongo/spec-forge/blob/main/README.md Generate a Personal Access Token in Trigger.dev cloud to authenticate with the CLI for deployment. This token starts with `tr_pat_`. ```bash # Go to https://cloud.trigger.dev/account/tokens # Click "Create new token" # Copy the token (starts with tr_pat_) ``` -------------------------------- ### Run Database Migrations Source: https://github.com/dennisrongo/spec-forge/blob/main/README.md Execute all database migrations using the provided TypeScript script. Ensure your Neon database is set up and the DATABASE_URL is configured in .env.local. ```bash npx tsx scripts/run-all-migrations.ts ``` -------------------------------- ### Basic Test Case Usage Source: https://github.com/dennisrongo/spec-forge/blob/main/tests/AI_PROVIDER_SETUP.md Demonstrates how to use the test fixtures in a test case. No additional AI provider configuration is needed as it's handled automatically. ```typescript import { test, expect } from '../fixtures/auth.fixture' test('should generate specifications', async ({ projectPage, featuresPage, clarifyPage, techStackPage, outputPage }) => { // AI provider is already configured // Create project, select features, answer questions, etc. // All AI features work automatically }) ``` -------------------------------- ### Verify Environment Variables and Run Single Test Source: https://github.com/dennisrongo/spec-forge/blob/main/tests/API_KEY_SETUP_SUMMARY.md These bash commands help verify that your environment variables are set correctly and allow you to run a single test file. Check logs for confirmation messages. ```bash # 1. Verify environment variables echo $STRAICO_API_KEY echo $ENCRYPTION_KEY # 2. Run a single test pnpm test example.spec.ts # 3. Check logs for confirmation # You should see: "[Test Helper] Set up Straico API key for user " ``` -------------------------------- ### AI IDE Integration Workflow Source: https://github.com/dennisrongo/spec-forge/blob/main/docs/index.html This snippet outlines the workflow for integrating SpecForge outputs with an AI IDE. It details the steps from generating specs to AI code generation. ```bash # 1. Generate your specs in SpecForge # 2. Copy the PRD output # 3. Paste into your AI IDE with: $ Build this project according to these specifications: [Paste your SpecForge PRD here] # AI generates your entire codebase ✓ Project scaffolded successfully ✓ 47 files generated ✓ All dependencies configured ✓ Ready to develop! ``` -------------------------------- ### Clone Spec-Forge Repository Source: https://github.com/dennisrongo/spec-forge/blob/main/README.md Clone the product-spec-generator repository from GitHub and navigate into the project directory. ```bash git clone https://github.com/yourusername/product-spec-generator.git cd product-spec-generator ``` -------------------------------- ### Failed Test Cleanup Scenario Source: https://github.com/dennisrongo/spec-forge/blob/main/tests/CLEANUP_GUIDE.md Example of a test case that fails due to validation errors, demonstrating that cleanup still occurs due to the 'finally' block in the fixture. ```typescript test('create project', async ({ projectPage }) => { // 1. User created // 2. Test actions await projectPage.createProject('', '') // Fails validation // 3. Test fails // 4. Cleanup STILL runs (finally block) // 5. All data deleted }) ``` -------------------------------- ### Update package-lock.json for CI/CD Source: https://github.com/dennisrongo/spec-forge/blob/main/README.md This script is used when your CI/CD pipeline requires `npm` but you develop locally with `pnpm`. It removes the `package-lock.json`, installs with `npm`, and stages the updated lock file. ```bash rm package-lock.json npm install git add package-lock.json git commit -m "Update package-lock.json for deployment" ``` -------------------------------- ### Backend: Read from Realtime Streams (v2) Source: https://github.com/dennisrongo/spec-forge/blob/main/CLAUDE.md Read data from a defined stream associated with a specific run. You can specify a timeout and a starting index to resume reading from a specific point. ```typescript // 3. Read from backend const stream = await aiStream.read(runId, { timeoutInSeconds: 300, startIndex: 0, // Resume from specific chunk }); for await (const chunk of stream) { console.log("Chunk:", chunk); // Fully typed } ``` -------------------------------- ### Import Fixtures for New Tests Source: https://github.com/dennisrongo/spec-forge/blob/main/tests/README.md Import necessary fixtures when creating new test files in the `tests/e2e/` directory. This sets up the testing environment. ```javascript import { test, expect } from '../fixtures/auth.fixture' ``` -------------------------------- ### Database Schema for User Preferences Source: https://github.com/dennisrongo/spec-forge/blob/main/tests/AI_PROVIDER_SETUP.md Illustrates the SQL schema for the `user_preferences` table, which stores AI provider configuration details such as the active provider, encrypted API key, and default model. ```sql CREATE TABLE user_preferences ( user_id UUID PRIMARY KEY, active_ai_provider TEXT DEFAULT 'openai', straico_api_key_encrypted TEXT, straico_model TEXT DEFAULT 'openai/gpt-5-mini', -- ... other fields ); ``` -------------------------------- ### Testing Database Connection with TypeScript Source: https://github.com/dennisrongo/spec-forge/blob/main/tests/README.md Verify your database connection by running migration scripts. Ensure the DATABASE_URL in your .env.local file is correctly configured. ```bash # Test connection npx tsx scripts/run-migrations.ts ``` -------------------------------- ### Verifying Authentication Environment Variables in Bash Source: https://github.com/dennisrongo/spec-forge/blob/main/tests/README.md Check your NextAuth configuration by echoing the relevant environment variables. Ensure NEXTAUTH_URL is set to the correct local development URL. ```bash # Verify environment variables echo $NEXTAUTH_SECRET echo $NEXTAUTH_URL # Should be http://localhost:3000 for local tests ``` -------------------------------- ### Manually Apply Database Migration SQL Source: https://github.com/dennisrongo/spec-forge/blob/main/docs/VERSION_FETCHING.md Alternative command to manually apply the SQL migration script using `psql`. ```bash psql $DATABASE_URL -f scripts/035_create_tech_versions_cache.sql ``` -------------------------------- ### Handling Existing Users in Test Helper Source: https://github.com/dennisrongo/spec-forge/blob/main/tests/AI_PROVIDER_SETUP.md Illustrates the logic within the `createUser` helper function to ensure that if a user already exists, their AI provider is configured before returning their ID. ```typescript async createUser(name: string, email: string, password: string): Promise { const existing = await this.sql`SELECT id FROM users WHERE email = ${email}` if (existing.length > 0) { const userId = existing[0].id as string // Ensure API key is configured for existing user await this.setupUserAIProvider(userId) return userId } // ... create new user } ``` -------------------------------- ### Configure STRAICO_API_KEY in .env.local Source: https://github.com/dennisrongo/spec-forge/blob/main/tests/AI_PROVIDER_SETUP.md Ensure the STRAICO_API_KEY is set in your .env.local file for tests to function correctly. This snippet shows how to check and add the key. ```bash # Check if the key is set echo $STRAICO_API_KEY # Add to .env.local if missing echo "STRAICO_API_KEY=your_key_here" >> .env.local ``` -------------------------------- ### Dependent Test Case Example (Bad Practice) Source: https://github.com/dennisrongo/spec-forge/blob/main/tests/README.md Illustrates a bad practice where tests depend on each other's execution order. This makes tests brittle and harder to debug. Avoid relying on shared state between tests. ```typescript // ❌ Bad: Tests depend on each other let sharedUserId: string test('test 1', async ({ testData }) => { sharedUserId = await testData.createUser(...) }) test('test 2', async () => { // Depends on test 1 running first await useUser(sharedUserId) }) ``` -------------------------------- ### Run All End-to-End Tests Source: https://github.com/dennisrongo/spec-forge/blob/main/tests/README.md Executes the entire suite of end-to-end tests. ```bash pnpm test ``` -------------------------------- ### Configure Environment Variables for E2E Tests Source: https://github.com/dennisrongo/spec-forge/blob/main/tests/QUICKSTART.md Set up your local environment variables, ensuring `STRAICO_API_KEY` is provided for E2E tests. The test suite defaults to Straico for AI. ```env # Required DATABASE_URL=postgresql://user:pass@host/dbname NEXTAUTH_SECRET=your-secret-key-here NEXTAUTH_URL=http://localhost:3000 STRAICO_API_KEY=your-straico-key # Required for E2E tests ENCRYPTION_KEY=your-32-character-key-here # Required for API key storage TRIGGER_SECRET_KEY=tr_dev_your-key # Optional (gracefully degrades if not set) CONTEXT7_API_KEY=your-context7-key ``` -------------------------------- ### Recommended Waiting Strategies Source: https://github.com/dennisrongo/spec-forge/blob/main/tests/README.md Shows preferred methods for waiting in tests, such as waiting for specific element visibility or URL changes. Avoid fixed timeouts ('waitForTimeout') as they can lead to flaky tests. ```typescript // ✅ Good: Wait for specific conditions await expect(page.getByText('Success')).toBeVisible() await page.waitForURL(///projects/) // ⚠️ Use sparingly: Fixed timeouts await page.waitForTimeout(1000) // ❌ Bad: No waiting await button.click() // Might fail if next element not ready ``` -------------------------------- ### Run Specific Database Migration Source: https://github.com/dennisrongo/spec-forge/blob/main/README.md Executes a specific database migration script. Ensure the script exists in `scripts/*.sql`. ```bash npx tsx scripts/run-migrations.ts ``` -------------------------------- ### Configure .env.local for E2E Tests Source: https://github.com/dennisrongo/spec-forge/blob/main/tests/API_KEY_SETUP_SUMMARY.md Add these environment variables to your `.env.local` file to enable E2E tests. Ensure you replace the placeholder values with your actual keys. ```env # Required for E2E tests STRAICO_API_KEY=your_straico_api_key_here ENCRYPTION_KEY=your-32-character-encryption-key-here ``` -------------------------------- ### Create Your First Playwright Test Source: https://github.com/dennisrongo/spec-forge/blob/main/tests/QUICKSTART.md Write a basic E2E test to create a project, including generating test data, performing the action, and verifying the result. Run this specific test file using `npx playwright test my-first-test.spec.ts`. ```typescript import { test, expect } from '../fixtures/auth.fixture' test.describe('My First Test', () => { test('should create a project', async ({ projectPage, testData }) => { // Generate test data const project = testData.generateTestProject() // Perform action await projectPage.createProject(project.title, project.description) // Verify result await projectPage.expectProjectCreated() console.log('✓ Test passed!') }) }) ``` -------------------------------- ### Configure Environment Variables Source: https://github.com/dennisrongo/spec-forge/blob/main/README.md Edit the .env.local file to set up required environment variables for database connection, NextAuth, and Trigger.dev. Optional keys for Context7 can also be configured. ```dotenv # Database (Required) DATABASE_URL="postgresql://user:password@host/database?sslmode=require" # NextAuth v4 Configuration (Required) NEXTAUTH_SECRET="your-super-secret-key-change-this-in-production" # Generate: openssl rand -base64 32 NEXTAUTH_URL="http://localhost:3000" # Trigger.dev (Required for spec generation) TRIGGER_SECRET_KEY="tr_dev_..." # Development key from Trigger.dev dashboard # Context7 API (Optional - for latest tech versions and documentation) CONTEXT7_API_KEY="your-context7-key" ``` -------------------------------- ### Configure ENCRYPTION_KEY for Tests Source: https://github.com/dennisrongo/spec-forge/blob/main/tests/AI_PROVIDER_SETUP.md Tests may fail due to encryption errors if ENCRYPTION_KEY is not set or is not 32 characters long. This shows how to generate and add a key. ```bash # Generate a new 32-character key openssl rand -base64 32 # Add to .env.local echo "ENCRYPTION_KEY=your_32_character_key_here" >> .env.local ``` -------------------------------- ### Run Specific Test File Source: https://github.com/dennisrongo/spec-forge/blob/main/tests/README.md Executes a single end-to-end test file. ```bash pnpm test tests/e2e/complete-workflow.spec.ts ``` -------------------------------- ### Database Schema for Context7 Library Cache Source: https://github.com/dennisrongo/spec-forge/blob/main/docs/VERSION_FETCHING.md SQL schema for the `context7_library_cache` table, including a new field for `latest_version`. ```sql CREATE TABLE context7_library_cache ( id SERIAL PRIMARY KEY, library_name VARCHAR(255) NOT NULL UNIQUE, library_id VARCHAR(500) NOT NULL, description TEXT, latest_version TEXT, -- Added: Latest stable version from Context7 cached_at TIMESTAMP NOT NULL DEFAULT NOW(), expires_at TIMESTAMP NOT NULL DEFAULT (NOW() + INTERVAL '30 days'), created_at TIMESTAMP NOT NULL DEFAULT NOW(), updated_at TIMESTAMP NOT NULL DEFAULT NOW() ); ``` -------------------------------- ### Fetch Latest Version for a Single Technology Source: https://github.com/dennisrongo/spec-forge/blob/main/docs/VERSION_FETCHING.md Use `getLatestTechVersion` to retrieve version information for a specific technology. The output includes the technology name, latest version, description, and library ID. ```typescript import { getLatestTechVersion } from "@/lib/context7" const versionInfo = await getLatestTechVersion("next.js") console.log(versionInfo) // Output: { // name: "next.js", // latestVersion: "15.1.8", // description: "Next.js enables you to create full-stack web applications...", // libraryId: "/vercel/next.js" // } ``` -------------------------------- ### Deletion Order for Cleanup Source: https://github.com/dennisrongo/spec-forge/blob/main/tests/CLEANUP_GUIDE.md Illustrates the specific order in which database records are deleted during cleanup to respect foreign key constraints. ```text 1. specifications (no FK dependencies) 2. tech_stacks (no FK dependencies) 3. clarifications (no FK dependencies) 4. project_features (no FK dependencies) 5. projects (depends on users) 6. user_preferences (depends on users) 7. users (last) ``` -------------------------------- ### Deploy Trigger.dev Tasks Locally Source: https://github.com/dennisrongo/spec-forge/blob/main/README.md Use this command to deploy your Trigger.dev tasks locally. This is part of the manual deployment process. ```bash npx trigger.dev@latest deploy ``` -------------------------------- ### Using Authenticated Fixtures Source: https://github.com/dennisrongo/spec-forge/blob/main/tests/README.md Shows how to use pre-authenticated fixtures for tests that require a logged-in state. Available fixtures include authenticatedPage, projectPage, testUser, and testData. ```typescript test('authenticated test', async ({ authenticatedPage, // Pre-authenticated page projectPage, // Page object with auth testUser, // Test user credentials testData, // Data helper }) => { // Test code here - already logged in }) ``` -------------------------------- ### ProjectPage Object Methods Source: https://github.com/dennisrongo/spec-forge/blob/main/tests/QUICKSTART.md Common methods for interacting with the Project page, including navigation, creation, and verification of project elements. ```typescript await projectPage.gotoNewProject() await projectPage.createProject(title, description, uiPreference) await projectPage.expectProjectCreated() const projectId = await projectPage.getProjectIdFromUrl() ``` -------------------------------- ### Running Development Server and Tests in Bash Source: https://github.com/dennisrongo/spec-forge/blob/main/tests/README.md Ensure the development server is running in one terminal before executing tests in another. This is crucial for tests that depend on a running application. ```bash # Terminal 1 pnpm dev:next # Terminal 2 pnpm test ``` -------------------------------- ### Fetch Versions for Multiple Technologies Source: https://github.com/dennisrongo/spec-forge/blob/main/docs/VERSION_FETCHING.md Use `getBatchTechVersions` to fetch the latest versions for an array of technology names. The result is a map where keys are technology names and values contain version information. ```typescript import { getBatchTechVersions } from "@/lib/context7" // Fetch versions for multiple technologies const techNames = ["react", "next.js", "typescript"] const versionsMap = await getBatchTechVersions(techNames) // Access version info for (const [techName, versionInfo] of versionsMap) { console.log(`${techName}: ${versionInfo.latestVersion}`) } ``` -------------------------------- ### Generating and Using Test Data Source: https://github.com/dennisrongo/spec-forge/blob/main/tests/README.md Demonstrates how to generate test data using the 'testData' fixture and create records in the database. Data created this way is automatically cleaned up after the test. ```typescript test('with test data', async ({ testData, testUser }) => { // Generate data const project = testData.generateTestProject() const user = testData.generateTestUser() // Create in database const userId = await testData.createUser(user.name, user.email, user.password) const projectId = await testData.createProject(userId, project.title, project.description) // Data is automatically cleaned up after test }) ``` -------------------------------- ### Run ESLint for Code Linting Source: https://github.com/dennisrongo/spec-forge/blob/main/README.md Executes ESLint to check for code style and potential errors. ```bash pnpm lint ``` -------------------------------- ### TechStackPage Object Methods Source: https://github.com/dennisrongo/spec-forge/blob/main/tests/QUICKSTART.md Methods for interacting with the Tech Stack page, including waiting for load, selecting a stack, and generating specifications. ```typescript await techStackPage.waitForTechStackToLoad() await techStackPage.selectDefaultTechStack() await techStackPage.generateSpecifications() ``` -------------------------------- ### Clear Next.js Cache and Restart Source: https://github.com/dennisrongo/spec-forge/blob/main/README.md To resolve hot reload issues, clear the Next.js cache by removing the .next directory and then restart the development server using pnpm. ```bash rm -rf .next && pnpm dev ``` -------------------------------- ### Multiple Users Cleanup Logs Source: https://github.com/dennisrongo/spec-forge/blob/main/tests/CLEANUP_GUIDE.md Log output for a test involving multiple users, showing the cleanup process correctly identifying and removing all created users. ```log [Test Helper] Starting cleanup (2 users, 0 projects)... [Test Helper] ✓ Cleaned up user [Test Helper] ✓ Cleaned up user [Test Helper] ✓ Cleanup complete - Removed 2 users and 0 projects ``` -------------------------------- ### GitHub Actions Environment Configuration Source: https://github.com/dennisrongo/spec-forge/blob/main/tests/AI_PROVIDER_SETUP.md This YAML snippet shows how STRAICO_API_KEY and ENCRYPTION_KEY are automatically configured as environment variables in GitHub Actions workflows. ```yaml env: STRAICO_API_KEY: ${{ secrets.STRAICO_API_KEY }} # Required ENCRYPTION_KEY: ${{ secrets.ENCRYPTION_KEY }} # Required ``` -------------------------------- ### Manual SQL Cleanup for Test Users Source: https://github.com/dennisrongo/spec-forge/blob/main/tests/CLEANUP_GUIDE.md Provides SQL queries to find and delete test users based on their email addresses. This is useful for manual intervention when test data is not cleaned up automatically. ```sql -- Find test users SELECT * FROM users WHERE email LIKE '%@specforge.test'; -- Delete manually DELETE FROM users WHERE email LIKE '%@specforge.test'; ``` -------------------------------- ### Add API Keys to .gitignore Source: https://github.com/dennisrongo/spec-forge/blob/main/tests/AI_PROVIDER_SETUP.md This .gitignore configuration prevents accidental commitment of sensitive API keys and environment files to version control. ```gitignore # .gitignore (already configured) .env .env.local .env*.local ``` -------------------------------- ### Viewing Playwright Traces with Bash Source: https://github.com/dennisrongo/spec-forge/blob/main/tests/README.md Use the `playwright show-trace` command to view detailed traces of failed tests. Traces include screenshots, network requests, and DOM snapshots for debugging. ```bash # View trace for failed test npx playwright show-trace test-results/path-to-trace.zip ``` -------------------------------- ### Run Tests in UI Mode Source: https://github.com/dennisrongo/spec-forge/blob/main/tests/README.md Launches Playwright's UI mode, which is recommended for debugging tests as it provides a visual interface to run and inspect tests. ```bash pnpm test:ui ``` -------------------------------- ### Running Specific Tests in Debug Mode with Bash Source: https://github.com/dennisrongo/spec-forge/blob/main/tests/README.md Execute a specific test file in debug mode to open a browser with the debugger attached. This is useful for stepping through test execution. ```bash # Opens browser with debugger pnpm test:debug tests/e2e/complete-workflow.spec.ts ``` -------------------------------- ### Context7 Integration with Error Handling Source: https://github.com/dennisrongo/spec-forge/blob/main/CLAUDE.md Wrap Context7 API calls in a try-catch block to prevent workflow interruptions if the API key is missing or the API is unavailable. This pattern fetches batch technology versions and documentation. ```typescript try { const versions = await getBatchTechVersions(techNames) const docs = await getBatchDocumentation(techsWithCategories) } catch (error) { console.error("[SpecForge] Context7 error:", error) // Continue without Context7 data } ```