Branchwell

AI Resource Pro / website / commits / 5069836c

Website: current files new

written by Branchwell · 5069836c1e4c4e369ebe86b13dc7d299c5bed8c0

405 files changed

.cursor/rules/authentication.mdc added

1+ ---
2+ description: authentication requirements
3+ globs:
4+ alwaysApply: false
5+ ---
6+ Our primary authentcation on the API is supabase admin authentication. There is also an API key AI_RESOURCE_PRO_API_KEY stored in .env.local, but this is secondary.
7+
8+ There is an authentication backdoor for localhost testing, but NEVER leave any authentication bypasses enabled or set BYPASS_AUTH_IN_DEV to true in the .env.local environment variables. Security is critical.

.cursor/rules/coding-style-preferences.mdc added

1+ ---
2+ description: Coding pattern and style preferences
3+ globs:
4+ alwaysApply: false
5+ ---
6+ # Coding pattern preferences
7+ - Always prefer simple solutions
8+ - Avoid duplication of code whenever possible, which means checking for other areas of the codebase that might already have similar code and functionality
9+ - Write code that takes into account the different environments: dev, tert, and prod
10+ - You are careful to only make changes that are requested or you are confident are well understood and related to the change being requested
11+ - When fixing an issue or bug, do not introduce a new pattern or technology without first exhausting all options for the existing implementation. And if you finally do this, make sure to remove the old implementation afterwards so we don't have duplicate logic.
12+ - Keep the codebase very clean and organized
13+ - Avoid writing scripts in files if possible, especially if the script is likely only to be run once
14+ - Avoid having files over 200-300 lines of code. Refactor at that point.
15+ - Mocking data is only needed for tests, never mock data for dev or prod
16+ - Never add stubbing or fake data patterns to code that affects the dev or prod environments
17+ - Never overwrite my env file without first asking and confirming
18+
19+ # Separation Rules
20+ - **Single Responsibility:**
21+ Each file should represent one distinct unit of work.
22+ - **Component Breakdown:**
23+ Break features into self-contained components.
24+ - **Use Hooks:**
25+ Encapsulate logic and data access in custom hooks.
26+ - **Global vs. Local:** | I
27+ - **Global:** Place reusable components and hooks in shared/global folders.
28+ - **Local:** Keep object-specific components and hooks in localized folders.
29+ - **Separation of Concerns:**
30+ Maintain clear boundaries when creating or refactoring files.
31+ - **Readable and Declarative Code:**
32+ Rendered code should be very legible and clear. It should not include flow logic or ternary operators where possible.

.cursor/rules/coding-worflow-preferences.mdc added

1+ ---
2+ description: Coding workflow preferences
3+ globs:
4+ alwaysApply: false
5+ ---
6+ # Coding workflow preferences
7+ - Focus on the areas of code relevant to the task
8+ - Do not touch code that is unrelated to the task
9+ - Write thorough tests for all major functionality
10+ - Avoid making major changes to the patterns and architecture of how a feature works, after it has shown to work well, unless explicitly instructed
11+ - Always think about what other methods and areas of code might be affected by code changes

.cursor/rules/explain-tool-call.mdc added

1+ ---
2+ description: Provide a brief explaination of what you are doing before each tool call
3+ globs:
4+ alwaysApply: false
5+ ---
6+
7+ # Your rule content
8+ Provide a brief explaination of what you are doing before each tool call

.cursor/rules/focus.mdc added

1+ ---
2+ description: Stay focused within the constraints on the prompt.
3+ globs:
4+ alwaysApply: false
5+ ---
6+ Stay focused within the constraints on the prompt. Do not stray and do more work unless asked.

.cursor/rules/project-setup.mdc added

1+ ---
2+ description: Project Stack and Architecture
3+ globs:
4+ alwaysApply: false
5+ ---
6+ I am on plesk. My domain is airesourcepro.com (the old airesource.pro redirects to it). I am running on port 3001. The site uses a Supabase database (Used for Authentication and Database)
7+
8+ ## Site Colors - Light Theme
9+ - Primary: #1a1a1a
10+ - Secondary Accent: #46AAE9
11+ - Text: #000000
12+ - Background: #ffffff
13+
14+ ## Site Colors - Dark Theme
15+ - Primary: #ffffff
16+ - Secondary Accent: #46AAE9
17+ - Text: #ffffff
18+ - Background: #1a1a1a
19+
20+ ## Stack
21+
22+ - React
23+ - Next.js
24+ - Tailwind CSS
25+ - TypeScript
26+ - Shadcn UI
27+ - Prisma
28+ - Docker
29+ - Supabase (Used for Authentication and Database)

.cursor/rules/shadcn.mdc added

1+ ---
2+ description: shadcn-ui changed to shadcn
3+ globs:
4+ alwaysApply: false
5+ ---
6+ This is outdated in your model: shadcn-ui changed to shadcn

.cursor/rules/short-github-messages.mdc added

1+ ---
2+ description: Keep github commit messages concise and to the point.
3+ globs:
4+ alwaysApply: false
5+ ---
6+ Keep github commit messages concise and to the point.

.cursor/rules/start-all-chats-with-robot.mdc added

1+ ---
2+ description: Start all chats with 🤖
3+ globs:
4+ alwaysApply: false
5+ ---
6+ Start all chats with 🤖

.cursorrules added

1+ Start all chats with 🤖
2+
3+ Keep github commit messages concise and to the point.
4+
5+ This is outdated in your model: shadcn-ui changed to shadcn
6+
7+ I am on plesk. My domain is airesourcepro.com (the old airesource.pro redirects to it). I am running on localhost on port 3000. The site uses a Supabase database (Used for Authentication and Database)
8+
9+ Stay focused within the constraints on the prompt. Do not stray and do more work unless asked.
10+
11+ Our primary authentcation on the API is supabase admin authentication. There is also an API key NEXT_PUBLIC_AI_RESOURCE_PRO_API_KEY stored in .env.local, but this is secondary.
12+
13+ There is an authentication backdoor for localhost testing, but NEVER leave any authentication bypasses enabled or set BYPASS_AUTH_IN_DEV to true in the .env.local environment variables. Security is critical.
14+
15+ Provide a brief explaination of what you are doing before each tool call
16+
17+ Don't ever commit anything before I confirm it.
18+
19+ API Uses Supabase admin authentication.
20+
21+ When I say "no change", that means nothing changed and you should roll back any changes that you made that did not work.
22+
23+ ## Site Colors - Light Theme
24+ - Primary: #1a1a1a
25+ - Secondary Accent: #46AAE9
26+ - Text: #000000
27+ - Background: #ffffff
28+
29+ ## Site Colors - Dark Theme
30+ - Primary: #ffffff
31+ - Secondary Accent: #46AAE9
32+ - Text: #ffffff
33+ - Background: #1a1a1a
34+
35+
36+ ## Stack
37+
38+ - React
39+ - Next.js
40+ - Tailwind CSS
41+ - TypeScript
42+ - Shadcn UI
43+ - Supabase (Used for Authentication and Database)
44+
45+
46+
47+ # Project Architecture
48+ The project should seed and update the Supabase database using the 'seed-supabase.ts' script.
49+
50+ It uses the following JSON files as seed structure:
51+ - news.json - News Table
52+ - tools.json - Tools Table
53+ - categories.json - Categories Table
54+
55+
56+ Categories API Route (seed json filename 'categories.json')
57+ - Lucide React Icon Name
58+ - Category Name
59+ -
60+ News feed
61+ - primary cat
62+
63+
64+ # Coding pattern preferences
65+ - Always prefer simple solutions
66+ - Avoid duplication of code whenever possible, which means checking for other areas of the codebase that might already have similar code and functionality
67+ - Write code that takes into account the different environments: dev, tert, and prod
68+ - You are careful to only make changes that are requested or you are confident are well understood and related to the change being requested
69+ - When fixing an issue or bug, do not introduce a new pattern or technology without first exhausting all options for the existing implementation. And if you finally do this, make sure to remove the old implementation afterwards so we don't have duplicate logic.
70+ - Keep the codebase very clean and organized
71+ - Avoid writing scripts in files if possible, especially if the script is likely only to be run once
72+ - Avoid having files over 200-300 lines of code. Refactor at that point.
73+ - Mocking data is only needed for tests, never mock data for dev or prod
74+ - Never add stubbing or fake data patterns to code that affects the dev or prod environments
75+ - Never overwrite my env file without first asking and confirming
76+
77+ # Separation Rules
78+ - **Single Responsibility:**
79+ Each file should represent one distinct unit of work.
80+ - **Component Breakdown:**
81+ Break features into self-contained components.
82+ - **Use Hooks:**
83+ Encapsulate logic and data access in custom hooks.
84+ - **Global vs. Local:** | I
85+ - **Global:** Place reusable components and hooks in shared/global folders.
86+ - **Local:** Keep object-specific components and hooks in localized folders.
87+ - **Separation of Concerns:**
88+ Maintain clear boundaries when creating or refactoring files.
89+ - **Readable and Declarative Code:**
90+ Rendered code should be very legible and clear. It should not include flow logic or ternary operators where possible.
91+
92+ # Coding workflow preferences
93+ - Focus on the areas of code relevant to the task
94+ - Do not touch code that is unrelated to the task
95+ - Write thorough tests for all major functionality
96+ - Avoid making major changes to the patterns and architecture of how a feature works, after it has shown to work well, unless explicitly instructed
97+ - Always think about what other methods and areas of code might be affected by code changes

.eslintrc.json added

1+ {
2+ "extends": "next/core-web-vitals",
3+ "rules": {
4+ "react/no-unescaped-entities": "off",
5+ "@next/next/no-img-element": "warn",
6+ "react-hooks/exhaustive-deps": "warn"
7+ }
8+ }

.gitignore added

1+ # See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
2+
3+ # dependencies
4+ /node_modules
5+ /.pnp
6+ .pnp.*
7+ .yarn/*
8+ !.yarn/patches
9+ !.yarn/plugins
10+ !.yarn/releases
11+ !.yarn/versions
12+
13+ # testing
14+ /coverage
15+ /tests/selenium/screenshots
16+
17+ # next.js
18+ /.next/
19+ /out/
20+
21+ # production
22+ /build
23+
24+ # misc
25+ .DS_Store
26+ *.pem
27+
28+ # debug
29+ npm-debug.log*
30+ yarn-debug.log*
31+ yarn-error.log*
32+ .pnpm-debug.log*
33+ /admin-debug
34+
35+ # vercel
36+ .vercel
37+
38+ # typescript
39+ *.tsbuildinfo
40+ next-env.d.ts
41+
42+ # env files - NEVER commit these!
43+ .env
44+ .env.*
45+ .env.local
46+ !.env.example
47+
48+ # Apple Sign-In secret
49+ client_secret.txt
50+
51+ # Playwright
52+ node_modules/
53+ /test-results/
54+ /playwright-report/
55+ /blob-report/
56+ /playwright/.cache/
57+ /playwright/.auth/
58+ .env*.local
59+ .wrangler/
60+
61+ # Cloudflare build and local bindings
62+ .open-next/
63+ .wrangler/
64+ .dev.vars*

.roo/rules/rules.md added

1+ Important, start all chats with "🤖" so I know you are listening to these rules.
2+
3+ # Summary
4+ I am on plesk. My domain is airesourcepro.com (the old airesource.pro redirects to it). I am running on port 3001. The site uses a Supabase database (Used for Authentication and Database)
5+
6+ ## Site Colors - Light Theme
7+ - Primary: #1a1a1a
8+ - Secondary Accent: #46AAE9
9+ - Text: #000000
10+ - Background: #ffffff
11+
12+ ## Site Colors - Dark Theme
13+ - Primary: #ffffff
14+ - Secondary Accent: #46AAE9
15+ - Text: #ffffff
16+ - Background: #1a1a1a
17+
18+ ## Stack
19+ - React
20+ - Lucide-React (for icons)
21+ - Next.js
22+ - Tailwind CSS
23+ - TypeScript
24+ - Shadcn UI
25+ - Prisma
26+ - Docker
27+ - Supabase (Used for Authentication and Database)
28+
29+ # Authentication
30+ Our primary authentcation on the API is supabase admin authentication. There is also an API key AI_RESOURCE_PRO_API_KEY stored in .env.local, but this is secondary.
31+
32+ There is an authentication backdoor for localhost testing, but NEVER leave any authentication bypasses enabled or set BYPASS_AUTH_IN_DEV to true in the .env.local environment variables. Security is critical.
33+
34+ # Documentation
35+ Our app is a private app. Always update the README.md file at the root of the project. Also always reference this file for context about the project.
36+
37+ # Coding pattern preferences
38+ - Always prefer simple solutions
39+ - Avoid duplication of code whenever possible, which means checking for other areas of the codebase that might already have similar code and functionality
40+ - Write code that takes into account the different environments: dev, tert, and prod
41+ - You are careful to only make changes that are requested or you are confident are well understood and related to the change being requested
42+ - When fixing an issue or bug, do not introduce a new pattern or technology without first exhausting all options for the existing implementation. And if you finally do this, make sure to remove the old implementation afterwards so we don't have duplicate logic.
43+ - Keep the codebase very clean and organized
44+ - Avoid writing scripts in files if possible, especially if the script is likely only to be run once
45+ - Avoid having files over 200-300 lines of code. Refactor at that point.
46+ - Mocking data is only needed for tests, never mock data for dev or prod
47+ - Never add stubbing or fake data patterns to code that affects the dev or prod environments
48+ - Never overwrite my env file without first asking and confirming
49+
50+ # Separation Rules
51+ - **Single Responsibility:**
52+ Each file should represent one distinct unit of work.
53+ - **Component Breakdown:**
54+ Break features into self-contained components.
55+ - **Use Hooks:**
56+ Encapsulate logic and data access in custom hooks.
57+ - **Global vs. Local:** |
58+ - **Global:** Place reusable components and hooks in shared/global folders.
59+ - **Local:** Keep object-specific components and hooks in localized folders.
60+ - **Separation of Concerns:**
61+ Maintain clear boundaries when creating or refactoring files.
62+ - **Readable and Declarative Code:**
63+ Rendered code should be very legible and clear. It should not include flow logic or ternary operators where possible.
64+
65+ # Coding workflow preferences
66+ - Focus on the areas of code relevant to the task
67+ - Do not touch code that is unrelated to the task
68+ - Write thorough tests for all major functionality
69+ - Avoid making major changes to the patterns and architecture of how a feature works, after it has shown to work well, unless explicitly instructed
70+ - Always think about what other methods and areas of code might be affected by code changes
71+
72+
73+ # Focus
74+ Stay focused within the constraints on the prompt. Do not stray and do more work unless asked.
75+
76+ # Notes
77+ This is outdated in your model: shadcn-ui changed to shadcn

ADMIN_AUTH.md added

1+ # Admin Authentication System
2+
3+ ## Overview
4+
5+ This document explains the admin authentication system used in the AI Resource Pro project, along with recent security improvements.
6+
7+ ## Authentication Flow
8+
9+ The admin authentication system uses a combination of Supabase authentication and a custom admin check:
10+
11+ 1. **Login Process**:
12+ - User enters email and password on `/admin/login`
13+ - Credentials are validated against Supabase Auth
14+ - User's admin status is verified in the database (`users` table with `is_admin: true`)
15+ - The `admin_session_active` cookie is set only for validated admin users
16+
17+ 2. **Authentication Verification**:
18+ - Server-side: The `validateRequest()` function in `src/lib/auth/supabase-server-auth.ts` checks for the admin cookie and Supabase session
19+ - Middleware: Additional protection for admin routes in `src/middleware.ts`
20+
21+ ## Security Improvements
22+
23+ The following security improvements have been implemented:
24+
25+ 1. **Removed Insecure Endpoints**:
26+ - Deleted `/api/admin/set-cookies` - Previously allowed anyone to set admin cookies
27+ - Deleted `/api/set-admin-cookies` - Another insecure endpoint
28+ - Deleted `/api/debug/set-admin-cookies` - Third insecure endpoint
29+
30+ 2. **Enhanced Middleware Protection**:
31+ - Added specific checks for protected API routes
32+ - Improved error responses for unauthorized access
33+
34+ 3. **Protected Debug Endpoints**:
35+ - The `/api/auth/debug` endpoint now requires admin authentication
36+ - Sensitive information is only shown to authenticated admins
37+
38+ ## Development and Testing
39+
40+ For development and testing, there are two options:
41+
42+ 1. **Standard Authentication**:
43+ - Use the normal login flow through `/admin/login`
44+ - This is the secure, recommended approach
45+
46+ 2. **Development Bypass** (controlled environment only):
47+ - Set `BYPASS_AUTH_IN_DEV=true` in `.env.local`
48+ - **WARNING**: Never enable this in production!
49+ - Enabling this creates a security vulnerability
50+
51+ ## Best Practices
52+
53+ 1. **Never Create Direct Cookie Endpoints**:
54+ - Don't create endpoints that set admin cookies without authentication
55+ - Always verify admin status in the database before granting admin privileges
56+
57+ 2. **Keep Authentication Checks**:
58+ - Don't remove or bypass authentication checks
59+ - Don't set `BYPASS_AUTH` constants to `true` in any files
60+
61+ 3. **Monitor Logs**:
62+ - Watch for authentication failures in logs
63+ - Check for suspicious login attempts
64+
65+ ## Troubleshooting
66+
67+ Issues with admin authentication:
68+
69+ 1. Make sure your user has `is_admin: true` in the database
70+ 2. Use the proper login flow through `/admin/login`
71+ 3. Check for any console errors during login
72+ 4. Verify cookies are being set correctly

API_SECURITY.md added

1+ # API Security Requirements
2+
3+ ## Overview
4+
5+ This document outlines the security requirements for all API endpoints in the AI Resource Pro application.
6+
7+ ## Core Security Principles
8+
9+ 1. **Dual Authentication for All Write Operations**
10+ - All POST, PUT, DELETE, and PATCH requests must be secured with:
11+ - Admin authentication (Supabase auth + is_admin check)
12+ - Valid API key (NEXT_PUBLIC_AI_RESOURCE_PRO_API_KEY)
13+
14+ 2. **No Security Bypasses**
15+ - No endpoints should create security vulnerabilities
16+ - No endpoints to bypass authentication
17+ - No endpoints to set admin status without proper validation
18+
19+ 3. **Admin User Management**
20+ - User management should be done via Supabase Dashboard
21+ - Admin rights assignment should be done via database administration tools
22+ - No API endpoints should ever create or modify admin status
23+
24+ ## Authentication Methods
25+
26+ ### 1. Admin Authentication
27+ - Based on Supabase authentication
28+ - User must be authenticated with Supabase
29+ - User must have `is_admin: true` in the database
30+
31+ ### 2. API Key Validation
32+ - All secured endpoints must validate the `x-api-key` header
33+ - API key must match the `AI_RESOURCE_PRO_API_KEY` environment variable
34+ - API key validation is implemented in `src/middleware/auth.ts`
35+
36+ ## Implementation
37+
38+ ### Security Middleware
39+
40+ We use a standardized middleware to enforce API security:
41+
42+ ```typescript
43+ // src/middleware/protected-routes.ts
44+ export async function validateAdminApiRequest(request: NextRequest) {
45+ // 1. Validate admin authentication
46+ const { user } = await validateRequest();
47+ if (!user || !user.isAdmin) {
48+ return NextResponse.json(
49+ { error: 'Unauthorized - Admin authentication required' },
50+ { status: 401 }
51+ );
52+ }
53+
54+ // 2. Validate API key
55+ const apiKeyError = validateApiKey(request);
56+ if (apiKeyError) {
57+ return apiKeyError;
58+ }
59+
60+ // Both checks passed
61+ return null;
62+ }
63+ ```
64+
65+ ### Using the Security Middleware
66+
67+ All protected API endpoints should use the security middleware:
68+
69+ ```typescript
70+ export async function POST(request: NextRequest) {
71+ // Validate security requirements
72+ const securityError = await validateAdminApiRequest(request);
73+ if (securityError) {
74+ return securityError;
75+ }
76+
77+ // Proceed with the endpoint logic
78+ // ...
79+ }
80+ ```
81+
82+ ## Security Testing
83+
84+ Before creating any new API endpoint, ensure that:
85+
86+ 1. All POST, PUT, DELETE, PATCH operations are secured
87+ 2. No endpoints bypass authentication mechanisms
88+ 3. No endpoints modify admin status via API
89+ 4. API security middleware is applied correctly
90+
91+ ## Common Issues
92+
93+ ### Missing API Key
94+ If you receive a 401 Unauthorized error with "Missing API key header", make sure you're:
95+ - Including the `x-api-key` header in your request
96+ - Setting the header value to match the `NEXT_PUBLIC_AI_RESOURCE_PRO_API_KEY` environment variable
97+
98+ ### Authentication Failed
99+ If you receive a 401 Unauthorized error with "Admin authentication required", ensure:
100+ - You're properly authenticated (logged in as admin)
101+ - Your user has `is_admin: true` in the database
102+ - The admin_session_active cookie is set
103+
104+ ## Development Notes
105+
106+ - In development, use the API key from your `.env.local` file for testing
107+ - Never create endpoints that bypass security mechanisms
108+ - Never set `BYPASS_AUTH_IN_DEV=true` in production environments

MIGRATION-INSTRUCTIONS.md added

1+ # Image URL Migration Instructions
2+
3+ This document provides instructions for adding the `image_url` column to the `tools` table in the Supabase database.
4+
5+ ## Background
6+
7+ The application now supports separate icon and main image uploads for tools:
8+ - `icon_url`: Small icon for tools (already in database schema)
9+ - `image_url`: Main image for tools (needs to be added)
10+
11+ ## Steps to Apply Migration
12+
13+ 1. Make sure you have the latest code:
14+ ```bash
15+ git pull
16+ ```
17+
18+ 2. Install dependencies:
19+ ```bash
20+ npm install
21+ ```
22+
23+ 3. Run the migration script:
24+ ```bash
25+ npm run supabase:add-image-url
26+ ```
27+
28+ 4. Restart your application:
29+ ```bash
30+ npm run dev
31+ ```
32+
33+ ## What the Migration Does
34+
35+ 1. Adds an `image_url` column to the `tools` table
36+ 2. Ensures the `icon_url` column exists (as a fallback)
37+ 3. Refreshes the schema cache to ensure the new columns are recognized by Supabase
38+
39+ ## Troubleshooting
40+
41+ If you encounter any issues:
42+
43+ 1. Check if the migration applied correctly:
44+ ```sql
45+ SELECT column_name FROM information_schema.columns WHERE table_name = 'tools' AND column_name IN ('icon_url', 'image_url');
46+ ```
47+
48+ 2. If the columns exist but are not being recognized, try manually refreshing the schema cache:
49+ ```sql
50+ SELECT pg_reload_conf();
51+ ```
52+
53+ 3. If all else fails, you can manually add the columns:
54+ ```sql
55+ ALTER TABLE public.tools ADD COLUMN IF NOT EXISTS icon_url TEXT;
56+ ALTER TABLE public.tools ADD COLUMN IF NOT EXISTS image_url TEXT;
57+ ```

MIGRATION_INSTRUCTIONS.md added

1+ # Migration Instructions: Adding `is_archived` Column
2+
3+ This document provides instructions for migrating the database to add the `is_archived` column to the `user_roadmaps` table and create a partial unique index to ensure users can only have one active roadmap at a time.
4+
5+ ## Background
6+
7+ We've updated the codebase to enforce a "one active roadmap per user" rule. This requires adding an `is_archived` column to the `user_roadmaps` table and creating a partial unique index on the `user_id` column where `is_archived = false`.
8+
9+ ## Migration Script
10+
11+ The migration script is located at `scripts/add-is-archived-column.sql`. It:
12+
13+ 1. Adds the `is_archived` column with a default value of `false` to the `user_roadmaps` table
14+ 2. Automatically cleans up existing duplicate roadmaps by:
15+ - Finding all users who have multiple active roadmaps
16+ - For each user, keeping only their most recent roadmap active
17+ - Archiving all older roadmaps for those users
18+ 3. Creates a partial unique index on `user_id` where `is_archived = false`
19+
20+ ## Data Impact
21+
22+ The migration will archive older duplicate roadmaps for any users who currently have multiple roadmaps. Users will only see their most recent roadmap after the migration.
23+
24+ ## Applying the Migration
25+
26+ ### Development Environment
27+
28+ If using Supabase CLI:
29+
30+ ```bash
31+ npx supabase db push scripts/add-is-archived-column.sql
32+ ```
33+
34+ If connecting directly with psql:
35+
36+ ```bash
37+ psql YOUR_SUPABASE_DATABASE_URL -f scripts/add-is-archived-column.sql
38+ ```
39+
40+ ### Production Environment
41+
42+ For the production environment, follow the appropriate procedure for your deployment:
43+
44+ 1. Connect to the production database through Supabase dashboard or direct connection
45+ 2. Execute the SQL commands from the migration script
46+ 3. Verify the migration was successful with:
47+
48+ ```sql
49+ -- Check if column exists
50+ SELECT column_name, data_type
51+ FROM information_schema.columns
52+ WHERE table_name = 'user_roadmaps' AND column_name = 'is_archived';
53+
54+ -- Check if index exists
55+ SELECT indexname, indexdef
56+ FROM pg_indexes
57+ WHERE tablename = 'user_roadmaps' AND indexname = 'idx_user_roadmaps_one_active_per_user';
58+
59+ -- Check that each user now has only one active roadmap
60+ SELECT user_id, COUNT(*)
61+ FROM public.user_roadmaps
62+ WHERE is_archived = false
63+ GROUP BY user_id
64+ HAVING COUNT(*) > 1;
65+ ```
66+
67+ The last query should return no rows, confirming that each user has at most one active roadmap.
68+
69+ ## Testing After Migration
70+
71+ After applying the migration:
72+
73+ 1. Verify a user can create a roadmap
74+ 2. Verify a user can't have two active roadmaps at the same time
75+ 3. Verify a user can archive an existing roadmap and create a new one
76+ 4. Verify roadmap fetching only returns non-archived roadmaps
77+
78+ ## Rollback Procedure
79+
80+ If needed, you can roll back this migration with:
81+
82+ ```sql
83+ -- Drop the index
84+ DROP INDEX IF EXISTS idx_user_roadmaps_one_active_per_user;
85+
86+ -- Remove the column (if safe to do so)
87+ ALTER TABLE public.user_roadmaps DROP COLUMN IF EXISTS is_archived;
88+ ```
89+
90+ Note: Only roll back if there are no dependencies on the new column in the running application code.

README-BLOG-FIX.md added

1+ # Blog API Fix: Infinite Recursion in Policies
2+
3+ This README provides instructions on how to fix the "infinite recursion detected in policy for relation 'users'" error in your Supabase database.
4+
5+ ## The Problem
6+
7+ The Supabase database has row-level security (RLS) policies that are causing an infinite recursion error. This happens because:
8+
9+ 1. Policy for `users` table checks if a user is an admin by querying the `users` table
10+ 2. This creates a circular reference that Postgres can't resolve
11+ 3. The error propagates to other tables with similar policy structures
12+
13+ ## Solution 1: Immediate API Fix (Already Implemented)
14+
15+ We've already modified the `/api/blog` API route to:
16+ - Use the service client when in development mode (`BYPASS_AUTH_IN_DEV=true`)
17+ - Filter published posts manually when needed
18+ - Bypass the recursive policy issue entirely
19+
20+ This change should be in effect as soon as you restart your Next.js server:
21+
22+ ```bash
23+ npm run dev
24+ ```
25+
26+ ## Solution 2: Permanent Database Fix
27+
28+ To fix the issue permanently in your database, follow these steps:
29+
30+ ### Step 1: Create the exec_sql Function
31+
32+ 1. Log in to your [Supabase dashboard](https://app.supabase.com/)
33+ 2. Navigate to the SQL Editor
34+ 3. Copy the contents of `scripts/create-exec-sql-function.sql`
35+ 4. Paste it into the SQL Editor and run it
36+ 5. This creates a function that can execute SQL statements
37+
38+ ### Step 2: Run the Fix Script
39+
40+ After creating the function, you can run the fix script:
41+
42+ ```bash
43+ npm run supabase:fix-recursion
44+ ```
45+
46+ Alternatively, you can:
47+ 1. Copy the contents of `scripts/fix-recursive-policies.sql`
48+ 2. Paste it into the Supabase SQL Editor and run it directly
49+
50+ ## What the Fix Does
51+
52+ The fix:
53+ 1. Drops problematic policies that cause recursion
54+ 2. Creates a `is_admin()` function that safely checks admin status
55+ 3. Recreates policies using this function to avoid recursion
56+ 4. Applies the fix to all affected tables
57+
58+ ## Verifying the Fix
59+
60+ After applying either solution, you can verify it worked:
61+
62+ ```bash
63+ npm run debug:direct-query
64+ ```
65+
66+ You should see that both the service client and regular client can successfully query blog posts.
67+
68+ ## Further Information
69+
70+ - Keep `BYPASS_AUTH_IN_DEV=true` during development
71+ - Set it to `false` in production for security
72+ - You can check blog posts in the database with:
73+ ```bash
74+ npm run check:blog-posts
75+ ```
76+ - You can publish the hello-world sample post with:
77+ ```bash
78+ npm run publish:hello-world
79+ ```
80+
81+ If you need additional help, please refer to the Supabase documentation on [Row Level Security](https://supabase.com/docs/guides/auth/row-level-security).

README.md added

1+ # AI Resource Pro - airesourcepro.com
2+
3+ This is the repository for the AI Resource Pro website ([airesourcepro.com](https://airesourcepro.com)), a platform dedicated to providing resources related to Artificial Intelligence.
4+
5+ ## Project Overview
6+
7+ AI Resource Pro is built using a modern web stack focused on performance, developer experience, and scalability. It utilizes Supabase for backend services like authentication and database management, and is deployed on Plesk.
8+
9+ ## Tech Stack
10+
11+ * **Framework:** [Next.js](https://nextjs.org/) (with React)
12+ * **Language:** [TypeScript](https://www.typescriptlang.org/)
13+ * **Styling:** [Tailwind CSS](https://tailwindcss.com/)
14+ * **UI Components:** [shadcn/ui](https://ui.shadcn.com/)
15+ * **Database ORM:** [Prisma](https://www.prisma.io/)
16+ * **Backend & Auth:** [Supabase](https://supabase.com/)
17+ * **Containerization:** [Docker](https://www.docker.com/) (for development/deployment consistency)
18+
19+ ## Key Features
20+
21+ * **AI Tool Directory:** Curated list of AI tools, filterable by category.
22+ * **Learning Resources:** Educational content related to AI.
23+ * **News Feed:** Latest news in the AI space.
24+ * **AI Coach:** Personalized AI learning recommendations.
25+ * **Admin Dashboard:** Interface for managing content (Tools, Learning, News, Categories, Users).
26+ * **API:** Provides data access for various parts of the application.
27+
28+ ## Getting Started
29+
30+ 1. **Clone the repository:**
31+ ```bash
32+ git clone <repository-url>
33+ cd airesource-pro-site
34+ ```
35+
36+ 2. **Install dependencies:**
37+ ```bash
38+ npm install
39+ ```
40+
41+ 3. **Set up environment variables:**
42+ * Copy the example environment file: `cp .env.example .env.local`
43+ * Fill in the required values in `.env.local`, especially Supabase credentials (`NEXT_PUBLIC_SUPABASE_URL`, `NEXT_PUBLIC_SUPABASE_ANON_KEY`, `SUPABASE_SERVICE_ROLE_KEY`) and the API key (`AI_RESOURCE_PRO_API_KEY`).
44+ * **Important Security Note:** Ensure `BYPASS_AUTH_IN_DEV` is **never** set to `true` unless specifically for isolated local testing, and **never** commit it as `true`.
45+
46+ 4. **Set up Supabase:**
47+ * Ensure your local Supabase instance (if using Docker) or your remote Supabase project is running and configured according to the project's schema (potentially using Prisma migrations). Refer to `supabase/` directory and Prisma schema if needed.
48+
49+ 5. **Run Prisma migrations (if necessary):**
50+ ```bash
51+ npx prisma migrate dev
52+ # or apply deployments if targeting a specific environment
53+ npx prisma migrate deploy
54+ ```
55+
56+ 6. **Run the development server:**
57+ ```bash
58+ npm run dev
59+ ```
60+
61+ 7. Open [http://localhost:3001](http://localhost:3001) in your browser.
62+
63+ ## Authentication
64+
65+ * **Primary Method:** Supabase Authentication (JWT-based, handled via Supabase client libraries). Admin access relies on Supabase user roles.
66+ * **Secondary Method (API):** API Key (`AI_RESOURCE_PRO_API_KEY` set in `.env.local`). Required for certain backend API routes when not authenticated via Supabase. Include the header `x-api-key: YOUR_API_KEY`.
67+
68+ ## API Endpoints
69+
70+ The application exposes various API endpoints under `/api/`. Key areas include:
71+
72+ * `/api/admin/...`: Endpoints for the admin dashboard (require Supabase admin authentication).
73+ * `/api/auth/...`: Authentication-related endpoints (login, logout, status checks).
74+ * `/api/tools`: CRUD operations for AI tools.
75+ * `/api/learning`: CRUD operations for learning resources.
76+ * `/api/news`: CRUD operations for news articles.
77+ * `/api/categories`: CRUD operations for categories.
78+ * `/api/featured-tools`, `/api/featured-learning`: Endpoints for featured content.
79+ * `/api/faqs`: Endpoint for FAQs.
80+ * `/api/ai-coach/...`: Endpoints for the AI Coach feature.
81+ * `/api/webhooks/midjourney`: Webhook for Midjourney image generation updates.
82+ * `/api/revalidate`: On-demand cache revalidation for content updates.
83+ * `/api/health-check`: Basic health check endpoint.
84+
85+ *(For detailed request/response formats and parameters, please refer to the respective route handler files within `src/app/api/`)*
86+
87+ ## Caching and Revalidation
88+
89+ Blog posts, news, and potentially other content types utilize Next.js caching.
90+ * Dynamic pages often use `export const dynamic = 'force-dynamic'` or similar strategies for fresh data.
91+ * The `/api/revalidate` endpoint allows invalidating specific paths (e.g., `/api/revalidate?path=/news/[slug]`) when content is updated via the admin panel, ensuring users see the latest information.
92+
93+ ## Testing
94+
95+ * **Unit/Integration Tests:** Located in `src/__tests__/`. Run using:
96+ ```bash
97+ npm test
98+ # or yarn test, pnpm test
99+ ```
100+ * **E2E Tests (Selenium):** Refer to the "Selenium Testing" section in the previous README version or relevant test files if applicable. Ensure WebDriver and browser drivers are installed.
101+
102+ ## Deployment
103+
104+ * The application is deployed on a Plesk server.
105+ * Configuration for PM2 (process manager) might be present in `ecosystem.config.js`.
106+ * Ensure environment variables are correctly set on the production server.
107+
108+ ## Color Palette
109+
110+ ### Light Theme
111+ * **Primary:** `#1a1a1a`
112+ * **Secondary Accent:** `#46AAE9`
113+ * **Text:** `#000000`
114+ * **Background:** `#ffffff`
115+
116+ ### Dark Theme
117+ * **Primary:** `#ffffff`
118+ * **Secondary Accent:** `#46AAE9`
119+ * **Text:** `#ffffff`
120+ * **Background:** `#1a1a1a`
121+
122+ ## Contribution Guidelines
123+
124+ * Follow the coding patterns and separation rules outlined in `.roo/rules/rules.md`.
125+ * Write clean, simple, and maintainable code.
126+ * Avoid code duplication (DRY principle).
127+ * Ensure changes are well-tested.
128+ * Keep files focused (Single Responsibility Principle). Aim for < 300 lines per file.
129+ * Update this README if significant changes are made to the stack, architecture, or setup process.

SECURITY_AUDIT.md added

1+ # Security Audit Report - AI Resource Pro
2+
3+ Date: 2026-02-04
4+ Scope: Repository codebase + git history scan + npm audit
5+
6+ ## Executive Summary
7+ This audit identified multiple critical issues that could allow full administrative compromise and exposure of production secrets. The most severe findings include hardcoded/committed secrets in the repository and authentication bypass via a client-set cookie. The API authorization model also relies on a public API key (`NEXT_PUBLIC_AI_RESOURCE_PRO_API_KEY`), which is exposed in client code and therefore does not provide security. Several endpoints log sensitive data, CORS settings are overly permissive, and authentication endpoints lack rate limiting. Dependency vulnerabilities were detected by `npm audit` and should be addressed.
8+
9+ Immediate actions are required: rotate and revoke exposed secrets, remove them from the repository and git history, and replace the current admin-cookie and API-key authorization scheme with a server-verified session model.
10+
11+ ## Critical Findings (Fix Immediately)
12+
13+ ### C-1: Production secrets committed to the repository
14+ **Location:** `/.mcp.json`, `/client_secret.txt`, plus evidence in git history
15+
16+ **Details:**
17+ - `.mcp.json` contains a Supabase **service role key** (full admin privileges to DB and Auth).
18+ - `client_secret.txt` contains an Apple Sign-In **client secret JWT**.
19+ - Git history shows previous commits with multiple production secrets (Supabase service role, OpenAI, Upstash, Cloudflare, reCAPTCHA secret, etc.).
20+
21+ **Impact:** Anyone with repo access can use the service role key to read/modify all data and users. The Apple client secret can be used to impersonate your app with Apple Sign-In. Historic exposure means keys should be considered compromised.
22+
23+ **Remediation:**
24+ 1. **Revoke and rotate** all exposed credentials immediately (Supabase service role key, Apple client secret, OpenAI, Upstash, Cloudflare, reCAPTCHA secret, etc.).
25+ 2. Remove secrets from the repo (`.mcp.json`, `client_secret.txt`) and ensure they are listed in `.gitignore`.
26+ 3. Purge secrets from git history using a tool like `git filter-repo`, then force-push if acceptable for the repo.
27+ 4. Use a secret manager or environment variables for all credentials. Avoid storing secrets in local files tracked by git.
28+
29+ ---
30+
31+ ### C-2: Admin authentication can be bypassed by setting a client cookie
32+ **Location:** `src/lib/auth/supabase-server-auth.ts`, `src/middleware.ts`
33+
34+ **Details:**
35+ `validateRequest()` treats the presence of the `admin_session_active` cookie as authenticated admin **without any server-side verification**. The cookie is also set with `httpOnly: false` and can be created or modified by client-side JavaScript.
36+
37+ **Impact:** Any attacker can set `admin_session_active=true` in their browser and gain admin access to protected routes and APIs. This is a full admin takeover.
38+
39+ **Remediation:**
40+ 1. Remove the `admin_session_active` cookie as an authentication mechanism.
41+ 2. Only trust server-verified sessions (Supabase session cookies or server-side JWT validation).
42+ 3. If you must use a custom cookie, **sign it** (e.g., HMAC) and validate the signature server-side.
43+ 4. Set `httpOnly: true`, `secure: true`, and `sameSite: strict` for sensitive cookies.
44+
45+ ---
46+
47+ ### C-3: API authorization relies on a public API key
48+ **Location:** `src/middleware/auth.ts`, client usage in `src/app/admin/*` and API routes such as `src/app/api/tools/route.ts`, `src/app/api/news/route.ts`
49+
50+ **Details:**
51+ The API key is stored in `NEXT_PUBLIC_AI_RESOURCE_PRO_API_KEY`, which is exposed to browsers. Several **admin-level endpoints accept only this API key** when admin auth fails (e.g., `PUT/DELETE/POST` in `/api/tools`, `DELETE` in `/api/news`).
52+
53+ **Impact:** Anyone can extract the key from client code and perform privileged API actions (create/update/delete content).
54+
55+ **Remediation:**
56+ 1. Replace `NEXT_PUBLIC_AI_RESOURCE_PRO_API_KEY` with a **server-only** secret (non-public env var).
57+ 2. Do **not** accept API key alone for admin actions. Require verified admin sessions or signed JWTs.
58+ 3. If API key access is required for integrations, use **scoped keys** with narrow permissions and rotate them regularly.
59+
60+ ---
61+
62+ ### C-4: Stored XSS via unsanitized HTML rendering
63+ **Location:** `src/utils/contentParser.ts` and pages using `dangerouslySetInnerHTML` (e.g., `src/app/blog/[slug]/page.tsx`, `src/app/news/[slug]/page.tsx`, `src/app/faq/page.tsx`)
64+
65+ **Details:**
66+ `ContentParser` converts markdown to HTML without sanitizing user-controlled content. Multiple pages render the result with `dangerouslySetInnerHTML`.
67+
68+ **Impact:** Attackers can inject arbitrary HTML/JS into content (blog/news/faq), enabling session theft, admin cookie manipulation, or account takeover.
69+
70+ **Remediation:**
71+ 1. Sanitize all HTML before rendering (e.g., DOMPurify on the server or a trusted markdown-to-HTML sanitizer).
72+ 2. Prefer a safe markdown renderer with built-in XSS protection.
73+ 3. Remove `dangerouslySetInnerHTML` where possible.
74+
75+ ---
76+
77+ ## High Priority Findings
78+
79+ ### H-1: Sensitive data logged in production
80+ **Location:** `src/lib/auth/supabase-server-auth.ts`, `src/app/api/admin/login/route.ts`, `src/app/api/news/route.ts`
81+
82+ **Details:**
83+ Logs include cookies and headers (sometimes full headers in production), and request bodies. These can contain tokens, session IDs, or PII.
84+
85+ **Impact:** Logs become a secondary leakage vector. Anyone with log access can extract session tokens or sensitive user data.
86+
87+ **Remediation:**
88+ 1. Remove logging of cookies/headers or redact values.
89+ 2. Avoid logging request bodies containing user data.
90+ 3. Use structured logging with redaction rules.
91+
92+ ---
93+
94+ ### H-2: Overly permissive CORS on API endpoints
95+ **Location:** `src/app/api/news/route.ts` (`Access-Control-Allow-Origin: *`), `src/app/api/admin/login/route.ts` (dynamic origin, credentials enabled)
96+
97+ **Details:**
98+ CORS allows requests from any origin on endpoints that also accept privileged actions (POST/PUT/DELETE). This is dangerous when combined with the public API key and weak auth.
99+
100+ **Impact:** Malicious sites can trigger requests and, in some scenarios, exfiltrate responses or abuse endpoints.
101+
102+ **Remediation:**
103+ 1. Restrict CORS to a **whitelist** of trusted origins.
104+ 2. Only include `Access-Control-Allow-Credentials: true` when needed and with explicit origin checks.
105+ 3. For admin APIs, consider disabling CORS entirely.
106+
107+ ---
108+
109+ ### H-3: No rate limiting on authentication endpoints
110+ **Location:** `src/app/api/admin/login/route.ts`, `src/app/api/admin/login-alt/route.ts`
111+
112+ **Details:**
113+ `authRateLimit` exists but is not applied. Login endpoints have no rate limiting, enabling brute-force attacks.
114+
115+ **Impact:** Increased risk of credential stuffing and brute-force compromises.
116+
117+ **Remediation:**
118+ 1. Apply `authRateLimit` to all login/auth endpoints.
119+ 2. Add IP- and account-based throttling.
120+ 3. Add account lockout or exponential backoff on repeated failures.
121+
122+ ---
123+
124+ ### H-4: Debug endpoints expose internal state
125+ **Location:** `src/app/api/debug/auth-status/route.ts` (API-key only), `src/app/api/auth/debug/route.ts`
126+
127+ **Details:**
128+ Debug endpoints reveal cookies, auth state, environment flags, and user data. Some are protected only by the public API key.
129+
130+ **Impact:** Attackers can enumerate and gather sensitive internal information, aiding exploitation.
131+
132+ **Remediation:**
133+ 1. Restrict debug endpoints to internal environments only (or remove entirely in production).
134+ 2. Require verified admin auth for all debug endpoints.
135+ 3. Remove sensitive details from responses.
136+
137+ ---
138+
139+ ## Medium Priority Findings
140+
141+ ### M-1: Development auth bypass could be enabled in production
142+ **Location:** `src/lib/auth/supabase-server-auth.ts`, `src/middleware.ts`, `src/app/api/admin/dashboard/*`
143+
144+ **Details:**
145+ `BYPASS_AUTH_IN_DEV` enables full auth bypass and mock admin users. If mistakenly enabled in production, all admin routes become public.
146+
147+ **Impact:** Full admin compromise if env misconfigured.
148+
149+ **Remediation:**
150+ 1. Add hard checks preventing bypass flags in production builds.
151+ 2. Fail startup if `NODE_ENV=production` and bypass flags are enabled.
152+
153+ ---
154+
155+ ### M-2: GET endpoints with side effects (CSRF/abuse risk)
156+ **Location:** `src/app/api/admin/create-test-user/route.ts`
157+
158+ **Details:**
159+ This endpoint creates admin users on GET. It is gated by `NODE_ENV`, but if misconfigured it is remotely exploitable and CSRF-friendly.
160+
161+ **Impact:** Unauthorized admin creation if environment flags are mis-set.
162+
163+ **Remediation:**
164+ 1. Remove this endpoint from production builds.
165+ 2. Require POST + strong admin authentication + CSRF protection.
166+
167+ ---
168+
169+ ### M-3: Cookies not marked HttpOnly for admin session
170+ **Location:** `src/app/api/admin/login/route.ts`, `src/app/api/admin/login-alt/route.ts`
171+
172+ **Details:**
173+ `admin_session_active` is set with `httpOnly: false`, allowing JavaScript to read/modify it.
174+
175+ **Impact:** XSS enables session theft or session forging.
176+
177+ **Remediation:**
178+ 1. Set `httpOnly: true` on all auth cookies.
179+ 2. Use signed or server-validated sessions.
180+
181+ ---
182+
183+ ## Low Priority / Recommendations
184+
185+ ### L-1: Repository contains local cookie file
186+ **Location:** `/cookies.txt`
187+
188+ **Details:**
189+ Local cookie values are stored in the repo. Even if local-only, this sets a bad precedent.
190+
191+ **Remediation:**
192+ Remove `cookies.txt` from the repo and ensure it is ignored by `.gitignore`.
193+
194+ ---
195+
196+ ### L-2: Dependency vulnerabilities from `npm audit`
197+ **Location:** `package.json`, `package-lock.json`
198+
199+ **Details:**
200+ `npm audit` reported 10 vulnerabilities (5 high, 4 moderate, 1 low). Key packages include `next`, `eslint-config-next`, `glob`, `qs`, `lodash`, `react-syntax-highlighter`, `prismjs`.
201+
202+ **Remediation:**
203+ 1. Update to patched versions where possible (`next` -> 15.5.11 suggested by audit).
204+ 2. Consider upgrading `eslint-config-next` (major bump).
205+ 3. Re-run `npm audit` and address remaining transitive vulnerabilities.
206+
207+ ---
208+
209+ ## Remediation Checklist (Prioritized)
210+ 1. **Rotate/revoke all exposed secrets** and purge from git history. (Critical)
211+ 2. **Remove admin_session_active cookie auth** and replace with server-verified sessions. (Critical)
212+ 3. **Replace public API key authorization** with server-only secrets or full admin auth. (Critical)
213+ 4. **Sanitize HTML content** and remove unsafe `dangerouslySetInnerHTML` usage. (Critical)
214+ 5. **Lock down CORS** to trusted origins and disable credentials for public endpoints. (High)
215+ 6. **Add rate limiting** to all authentication endpoints. (High)
216+ 7. **Remove or fully lock debug endpoints** in production. (High)
217+ 8. **Harden environment flags** to prevent dev bypass in production. (Medium)
218+ 9. **Upgrade vulnerable dependencies** per `npm audit`. (Low/Medium)
219+

SECURITY_UPDATES.md added

1+ # Blog API Security Updates
2+
3+ ## Overview
4+ This document outlines the security improvements implemented and needed for the blog API endpoints. All write operations (POST, PUT, DELETE) must be secured with both admin authentication and API key validation.
5+
6+ ## Security Requirements
7+ All write operations on blog endpoints must implement:
8+ 1. Admin authentication via Supabase (`validateRequest()` with `isAdmin` check)
9+ 2. API key validation (`validateApiKey()`)
10+
11+ Ideally, use the `validateAdminApiRequest()` middleware which implements both checks.
12+
13+ ## Already Updated
14+ - ✅ `/src/app/api/blog/route.ts` - Main blog API (POST, PUT, DELETE)
15+ - ✅ `/src/app/api/admin/blog/create/route.ts` - Admin blog creation
16+
17+ ## Remaining Routes to Update
18+ The following routes need to be updated to use the `validateAdminApiRequest()` middleware:
19+
20+ 1. `/src/app/api/admin/blog/update/route.ts`
21+ 2. `/src/app/api/admin/blog/delete/route.ts`
22+ 3. `/src/app/api/admin/blog/upload-image/route.ts`
23+ 4. `/src/app/api/admin/blog/route.ts`
24+ 5. `/src/app/api/admin/blog/[id]/route.ts`
25+ 6. `/src/app/api/admin/blog/categories/route.ts`
26+
27+ ## Implementation Pattern
28+ Replace the existing authentication check:
29+
30+ ```typescript
31+ const { user } = await validateRequest();
32+
33+ if (!user || !user.isAdmin) {
34+ return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
35+ }
36+ ```
37+
38+ With the secure middleware:
39+
40+ ```typescript
41+ // Validate security requirements for admin API endpoints
42+ const securityError = await validateAdminApiRequest(request);
43+ if (securityError) {
44+ return securityError;
45+ }
46+ ```
47+
48+ Don't forget to import the middleware:
49+
50+ ```typescript
51+ import { validateAdminApiRequest } from '@/middleware/protected-routes';
52+ ```
53+
54+ And ensure the request parameter is properly typed as `NextRequest`:
55+
56+ ```typescript
57+ export async function POST(request: NextRequest) {
58+ // ...
59+ }
60+ ```
61+
62+ ## Testing
63+ After implementing these changes, test all endpoints with:
64+ 1. Valid admin authentication + valid API key (should succeed)
65+ 2. Valid admin authentication + invalid API key (should fail)
66+ 3. Invalid admin authentication + valid API key (should fail)
67+ 4. Invalid admin authentication + invalid API key (should fail)

analyze-instance-count-issues.md added

1+ # Analysis of Instance Count Issues
2+
3+ After reviewing the code, I've identified several issues that could be causing inaccurate `instance_count` values:
4+
5+ ## Issue 1: Column Name Mismatch
6+
7+ Looking at the dashboard code, it's still using `tool_count` in the query:
8+
9+ ```typescript
10+ const { data: categoryData, error: categoryError } = await supabase
11+ .from('categories')
12+ .select('id, name, tool_count') // Still using tool_count instead of instance_count
13+ .order('name');
14+
15+ categoryData.forEach(cat => {
16+ categoryCounts[cat.name] = cat.tool_count || 0; // Still using tool_count
17+ });
18+ ```
19+
20+ If you've renamed the column to `instance_count` in the database but haven't updated the code, this would cause a mismatch.
21+
22+ ## Issue 2: Duplicate Counting
23+
24+ The dashboard is adding additional counts on top of what's already in the database:
25+
26+ ```typescript
27+ // First it sets categoryCounts from tool_count
28+ categoryCounts[cat.name] = cat.tool_count || 0;
29+
30+ // Then it adds blog post counts
31+ categoryCounts[cat.name] += blogCount || 0;
32+
33+ // Then it adds news counts
34+ categoryCounts[cat.name] += newsCount || 0;
35+ ```
36+
37+ This creates duplicate counting if your database's `instance_count` already includes these items.
38+
39+ ## Issue 3: News Query Using Wrong Column
40+
41+ There's an issue with the news query:
42+
43+ ```typescript
44+ // Count news items with this category
45+ const { count: newsCount, error: newsCountError } = await supabase
46+ .from('news')
47+ .select('*', { count: 'exact', head: true })
48+ .eq('category', cat.name); // Using 'category' column which doesn't exist
49+ ```
50+
51+ According to the error you received earlier and the logs, there's no `category` column in the news table - it should be `category_id`. This means news items aren't being counted properly.
52+
53+ ## Issue 4: Blog Posts Column Naming
54+
55+ There seems to be confusion about the blog_posts table column names:
56+
57+ ```typescript
58+ // Count blog posts with this category
59+ const { count: blogCount, error: blogCountError } = await supabase
60+ .from('blog_posts')
61+ .select('*', { count: 'exact', head: true })
62+ .eq('category_id', cat.id); // Might be primary_category_id instead
63+ ```
64+
65+ Earlier errors suggested that some column names might be different than expected.
66+
67+ ## Solutions
68+
69+ 1. **Fix Dashboard Query**: Update the dashboard query to use the correct column name (`instance_count` instead of `tool_count`).
70+
71+ 2. **Fix Double Counting**: Decide whether to:
72+ - Only display the database's `instance_count` value without adding additional counts in the dashboard code
73+ - Set the database's `instance_count` to zero and compute all counts in the dashboard code
74+ - Update the database with correct counts using the SQL we provided earlier
75+
76+ 3. **Fix News Query**: Update the news query to use the correct column:
77+ ```typescript
78+ .eq('category_id', cat.id) // Instead of .eq('category', cat.name)
79+ ```
80+
81+ 4. **Verify Blog Posts Schema**: Check if blog_posts uses `category_id` or `primary_category_id` and update the query accordingly.
82+
83+ 5. **Create a Database Function**: Consider creating a Supabase function that calculates the total count across all tables, which would be more efficient than doing multiple queries in your dashboard code.
84+
85+ ## Additional SQL to Verify Counts
86+
87+ You can run this SQL to verify actual counts in your database:
88+
89+ ```sql
90+ SELECT
91+ c.id,
92+ c.name,
93+ c.instance_count AS stored_count,
94+ (SELECT COUNT(*) FROM tools WHERE category_id = c.id) AS actual_tools_count,
95+ (SELECT COUNT(*) FROM news WHERE category_id = c.id) AS actual_news_count,
96+ ((SELECT COUNT(*) FROM tools WHERE category_id = c.id) +
97+ (SELECT COUNT(*) FROM news WHERE category_id = c.id)) AS calculated_total
98+ FROM
99+ categories c
100+ ORDER BY
101+ calculated_total DESC
102+ LIMIT 10;
103+ ```
104+
105+ This will show you the difference between what's stored in the database and what should be there.

cloudflare-worker.mjs added

1+ import handler from './.open-next/worker.js';
2+ import config from './next.config.js';
3+
4+ const rules = await config.headers();
5+ const siteRule = rules.find(rule => rule.source === '/(.*)');
6+
7+ // Tutorial videos live in our R2 media bucket and are served at
8+ // airesourcepro.com/media/video/<slug>/... so the site uses only its own address.
9+ const MEDIA_PREFIX = '/media/';
10+
11+ async function serveMedia(request, env, url) {
12+ if (request.method !== 'GET' && request.method !== 'HEAD') return new Response('Method not allowed', { status: 405 });
13+ const key = decodeURIComponent(url.pathname.slice(MEDIA_PREFIX.length));
14+ if (!key.startsWith('video/') || key.includes('..')) return new Response('Not found', { status: 404 });
15+ const object = env.MEDIA ? await env.MEDIA.get(key, { range: request.headers, onlyIf: request.headers }) : null;
16+ if (!object) return new Response('Not found', { status: 404 });
17+ const headers = new Headers();
18+ object.writeHttpMetadata(headers);
19+ headers.set('etag', object.httpEtag);
20+ headers.set('Accept-Ranges', 'bytes');
21+ headers.set('Cache-Control', 'public, max-age=86400');
22+ if (!('body' in object)) return new Response(null, { status: 304, headers });
23+ let status = 200;
24+ if (object.range && request.headers.has('range')) {
25+ const { offset = 0, length = object.size - offset } = object.range;
26+ headers.set('Content-Range', `bytes ${offset}-${offset + length - 1}/${object.size}`);
27+ headers.set('Content-Length', String(length));
28+ status = 206;
29+ } else {
30+ headers.set('Content-Length', String(object.size));
31+ }
32+ return new Response(request.method === 'HEAD' ? null : object.body, { status, headers });
33+ }
34+
35+ export default {
36+ async fetch(request, env, ctx) {
37+ const url = new URL(request.url);
38+ if (url.pathname.startsWith(MEDIA_PREFIX)) return serveMedia(request, env, url);
39+ const response = await handler.fetch(request, env, ctx);
40+ const headers = new Headers(response.headers);
41+ const routeRule = rules.find(rule => rule.source === url.pathname && !rule.has);
42+ for (const rule of [siteRule, routeRule]) {
43+ for (const { key, value } of rule?.headers ?? []) headers.set(key, value);
44+ }
45+
46+ return new Response(response.body, { status: response.status, statusText: response.statusText, headers });
47+ },
48+ };

code-updates-after-rename.md added

1+ # Code Updates Required After Renaming tool_count to instance_count
2+
3+ If you decide to rename the `tool_count` column to `instance_count`, you'll need to update the following files:
4+
5+ ## Core Files to Update
6+
7+ 1. `src/app/admin/dashboard/page.tsx`
8+ - Line ~295: Change `.select('id, name, tool_count')` to `.select('id, name, instance_count')`
9+ - Line ~301: Change `categoryCounts[cat.name] = cat.tool_count || 0;` to `categoryCounts[cat.name] = cat.instance_count || 0;`
10+
11+ 2. `src/components/admin/ClientCategoryManager.tsx`
12+ - Line ~71: Change `tool_count?: number;` to `instance_count?: number;`
13+ - Line ~290: Change `<TableCell className="text-white">{category.tool_count || 0}</TableCell>` to `<TableCell className="text-white">{category.instance_count || 0}</TableCell>`
14+ - Line ~540-542: Update references from `tool_count` to `instance_count`
15+
16+ 3. `src/app/api/admin/categories/route.ts`
17+ - Line ~101: Change `tool_count: 0,` to `instance_count: 0,`
18+
19+ ## API Routes That Update Category Counts
20+
21+ 4. `src/app/api/tools/route.ts`
22+ - Update references to `tool_count` to `instance_count`
23+
24+ 5. `src/app/api/tools/[slug]/route.ts`
25+ - Update references to `tool_count` to `instance_count`
26+ - Line ~187: Change `.update({ tool_count: supabase.rpc('increment', { row_id: categoryId }) })` to `.update({ instance_count: supabase.rpc('increment', { row_id: categoryId }) })`
27+ - Line ~193: Similar update for decrement
28+
29+ 6. `src/app/api/admin/tools/[id]/route.ts`
30+ - Update references from `tool_count` to `instance_count`
31+
32+ ## Scripts & Schema Files
33+
34+ 7. `scripts/create-supabase-schema.sql`
35+ - Line ~41: Change `tool_count INTEGER DEFAULT 0,` to `instance_count INTEGER DEFAULT 0,`
36+
37+ 8. `scripts/seed-supabase.ts`
38+ - Update all references from `tool_count` to `instance_count`
39+
40+ 9. `scripts/migrate-categories-schema.sql`
41+ - Update references if needed
42+
43+ 10. Any other seed or migration scripts that reference the column
44+
45+ ## Testing Considerations
46+
47+ After making these changes:
48+
49+ 1. Test the admin dashboard to ensure category counts still display correctly
50+ 2. Test adding/removing tools to verify count increments/decrements properly
51+ 3. Verify that the category manager component still works correctly
52+ 4. Run any database seed scripts to ensure they still function properly
53+
54+ This is not an exhaustive list, but covers the main files identified through a code search. There may be other references to `tool_count` that would need to be updated.

components.json added

1+ {
2+ "$schema": "https://ui.shadcn.com/schema.json",
3+ "style": "new-york",
4+ "rsc": true,
5+ "tsx": true,
6+ "tailwind": {
7+ "config": "tailwind.config.ts",
8+ "css": "src/app/globals.css",
9+ "baseColor": "stone",
10+ "cssVariables": true,
11+ "prefix": ""
12+ },
13+ "aliases": {
14+ "components": "@/components",
15+ "utils": "@/lib/utils",
16+ "ui": "@/components/ui",
17+ "lib": "@/lib",
18+ "hooks": "@/hooks"
19+ },
20+ "iconLibrary": "lucide"
21+ }

content/tutorials/ai-video/comfyui-runpod-agent.mdx added

1+ ---
2+ title: "Set up ComfyUI on Runpod with your agent"
3+ description: "Six prompts that take Claude Code or Codex from an empty Runpod account to a finished LTX-2.5 clip, with a guide to choosing a quantization and a GPU."
4+ level: Advanced
5+ minutes: 11
6+ publishedAt: 2026-10-31
7+ updatedAt: 2026-11-01
8+ video: comfyui-runpod
9+ videoCaptions: true
10+ videoUploadedAt: "2026-11-05T07:51:29-08:00"
11+ ---
12+
13+ You can run [ComfyUI](https://github.com/comfyanonymous/ComfyUI) on your own [Runpod](https://www.runpod.io) GPU without clicking through a console. Your agent does the setup through Runpod's official MCP server, and you approve the plan and the price. This guide gives you the six prompts we used on a real account, what happened when we ran them, and how to pick the right model file and the right card.
14+
15+ The example is [LTX-2.5](https://huggingface.co/Lightricks/LTX-2.5), a fast open video model that makes picture and sound together, on an RTX 4090. The 4090 is only an example. A bigger card costs more per hour, has more memory and runs larger models.
16+
17+ ## What you need
18+
19+ - Claude Code or Codex
20+ - A Runpod account with some credit
21+ - About 20 minutes the first time, and about a minute after that
22+
23+ You don't need a Hugging Face account. Prompt 4 uses public files.
24+
25+ ## Why run it yourself
26+
27+ This is private AI. There's no content filter in front of the model, the company that made it never sees your prompts, and the model isn't learning from you. The ComfyUI page loads no analytics SDK, and ComfyUI's code sets `HF_HUB_DISABLE_TELEMETRY` and `DO_NOT_TRACK`.
28+
29+ We checked. Here's the browser's network traffic during one render:
30+
31+ | Host | Requests | What for | Carried the prompt |
32+ | --- | --- | --- | --- |
33+ | Our pod | 627 | ComfyUI | Yes |
34+ | api.comfy.org | 3 | Version check | No |
35+ | Hugging Face | 3 | Model file check | No |
36+
37+ Here's what that doesn't cover:
38+
39+ - **Your agent.** What you tell your agent during setup goes to that agent's provider. Prompts typed into ComfyUI don't.
40+ - **The pod's own traffic.** Our test covers the browser. We couldn't capture traffic leaving the pod, so we make no claim about it.
41+ - **Runpod.** [Runpod's terms](https://www.runpod.io/legal/terms-of-service) say it doesn't actively monitor hosted content, but it may monitor its network, disclose records to satisfy the law, and use content in aggregated, anonymized form to improve its services.
42+ - **The rules.** No company's filter decides what you can make, but [the model's license](#license-and-rules), Runpod's terms and the law still apply. Runpod's terms ban obscene or otherwise objectionable content by its own judgment.
43+
44+ ## How the pieces fit
45+
46+ Your models run on your own Runpod GPU, your agent does the work, and [Runpod's official MCP server](https://docs.runpod.io/get-started/mcp-servers) connects the two. The server gives your agent real tools such as `list-gpu-types`, `create-network-volume`, `create-pod` and `delete-pod`. Runpod's skills come with it, so your agent already knows how ComfyUI runs on a pod.
47+
48+ The MCP server doesn't reach inside a pod. To install a model, your agent connects over SSH.
49+
50+ ## Step 1: Connect Runpod
51+
52+ Paste this into your agent. It reads Runpod's official setup page and installs the skills and the MCP server. Signing in is the one part it can't do.
53+
54+ ```prompt
55+ Set up Runpod for this agent by following Runpod's official instructions at https://agents.runpod.io/. Tell me when it's my turn to sign in, then list my pods to confirm it works.
56+ ```
57+
58+ If you'd rather install it yourself, these are the commands from [Runpod's setup page](https://agents.runpod.io/). In Claude Code, run these, then `/reload-plugins`, then sign in with `/mcp`:
59+
60+ ```bash
61+ claude plugin marketplace add runpod/runpod-plugins-official
62+ claude plugin install runpod@runpod
63+ ```
64+
65+ In Codex:
66+
67+ ```bash
68+ codex plugin marketplace add https://github.com/runpod/runpod-plugins-official.git
69+ codex plugin add runpod@runpod
70+ ```
71+
72+ <Callout type="note">
73+ Runpod says not to also run `codex mcp add` after the plugin, because that makes a second entry with its own sign-in. In Codex Desktop, fully quit and reopen the app before the tools appear.
74+ </Callout>
75+
76+ ## Step 2: Deploy ComfyUI
77+
78+ ```prompt
79+ Use Runpod to set up ComfyUI for me on an RTX 4090. Find one that's in stock, create a 100 GB network volume in that same data center, then deploy Runpod's official ComfyUI template on it with SSH turned on. Show me the plan and the hourly price, and wait for my OK before you create anything. Give me the link once ComfyUI actually loads.
80+ ```
81+
82+ An RTX 4090 has 24 GB of video memory and cost $0.89 an hour on Secure Cloud when we ran this, billed by the second. Nothing gets created until you say OK. Stock moves fast: the data center in our plan sold out before we said yes, and our agent moved to another one at the same price. ComfyUI was up about two minutes later.
83+
84+ A network volume matters because a pod's own disk gets wiped when the pod stops. The volume is where your models, your ComfyUI install and your clips live, at $0.07 per GB per month. The pod comes and goes, and the volume stays.
85+
86+ Turning SSH on only works if Runpod has a public key for you. Our account had none registered, so the agent passed a key from our machine and said so in its plan.
87+
88+ <Callout type="warning">
89+ The ComfyUI link is public, with no login. Anyone who has it can use your GPU, so keep it to yourself.
90+ </Callout>
91+
92+ <Callout type="warning">
93+ The template can also open FileBrowser, which ships with a default login anyone can look up, and JupyterLab. Our agent left both closed because we didn't ask for them. If you open FileBrowser, change its password first.
94+ </Callout>
95+
96+ ## Choose a quantization
97+
98+ The full LTX-2.5 model is 42 GB, and that won't fit on a 24 GB card. A model is billions of numbers, and the full version stores each one in 16 bits. Quantizing rounds them to fewer bits, so the file shrinks and you give up some accuracy, like saving a photo at a lower quality.
99+
100+ ### Read the file name
101+
102+ - **Q** is the level, roughly the bits per number. Q8 uses about 8, Q4 about 5 and Q2 about 3.
103+ - **K** is the standard family of GGUF quantization.
104+ - **M** means medium, a mix of precision across the model.
105+ - **UD** is Unsloth Dynamic. Instead of one setting for the whole model, Unsloth measured which layers are most sensitive and gave those more bits. UD Q4 is less than half a gigabyte bigger than plain Q4, and it scores like a Q5 that's over a gigabyte and a half bigger.
106+
107+ ### Compare the files
108+
109+ The scores come from [Unsloth's model card](https://huggingface.co/unsloth/LTX-2.5-GGUF) and measure each file against the full model. LPIPS is how different it looks to the eye, so lower is better. PSNR measures pixel accuracy, so higher is better. The last column is what happened on our RTX 4090 at 1280 by 704.
110+
111+ | Distilled file | Size | Bits | LPIPS | PSNR | On our 24 GB card |
112+ | --- | --- | --- | --- | --- | --- |
113+ | Q2_K | 8.46 GB | 3.22 | 0.567 | 14.8 | Ran, but looks rough and mangled the hand |
114+ | Q4_K_M | 13.58 GB | 5.17 | 0.352 | 18.1 | Not tested |
115+ | **UD-Q4_K_XL** | **14.00 GB** | **5.33** | **0.320** | **19.4** | **Our pick. Never failed, about a minute a clip** |
116+ | Q5_K_M | 15.63 GB | 5.95 | 0.316 | 18.9 | Not tested |
117+ | UD-Q5_K_XL | 16.00 GB | 6.09 | 0.296 | 20.3 | Ran clean |
118+ | Q6_K | 17.81 GB | 6.78 | 0.274 | 20.4 | Not tested |
119+ | Q8_0 | 22.78 GB | 8.68 | 0.242 | 21.6 | Out of memory on the first try, worked on a retry |
120+ | BF16 | 42.03 GB | 16.01 | Lossless | Lossless | Doesn't fit |
121+
122+ The same prompt and seed won't land on the same image across these files. Changing the numbers changes the result, so compare them for quality and don't expect the same shot.
123+
124+ ### Dev or distilled
125+
126+ Dev is the standard version, at 30 steps. Distilled is trained to get there in about 11, so it's roughly three times faster at the same file size. Start with distilled.
127+
128+ ### How to choose
129+
130+ Take the file size, add a few gigabytes for everything else, and it should fit in your video memory. On a 4090, that points to Q4 or Q5.
131+
132+ - **Video memory.** UD Q4 peaked at 23.3 to 23.9 GB of 24, and UD Q5 at 22.9. Peaks stayed near the top whichever file we ran, so a clean peak doesn't mean there's room to spare. Q8 is too tight to rely on.
133+ - **System memory.** It peaked at about 43 GB with UD Q4 and 52 GB with UD Q5, because the text encoder alone is 26 GB. Our pod had over 100 GB.
134+ - **Headroom.** [Runpod's LTX-2.5 guide](https://www.runpod.io/blog/ltx-2-5-the-open-weights-world-model-built-for-speed-and-how-to-run-it-on-runpod) calls 16 to 24 GB the entry tier and suggests 48 GB for comfortable use.
135+
136+ ### Choose a card
137+
138+ We only tested the 4090, so the last column is worked out from memory size, not measured. These are Runpod's Secure Cloud rates from October 31, 2026, and prices and stock change. Network volumes need Secure Cloud, so the cheaper Community rates don't apply here.
139+
140+ | Card | Video memory | Per hour | What it should run |
141+ | --- | --- | --- | --- |
142+ | RTX 4090 | 24 GB | $0.89 | UD Q4, tested |
143+ | RTX 5090 | 32 GB | $1.19 | Q8 with some room |
144+ | L40 | 48 GB | $0.82 | Q8 comfortably |
145+ | RTX PRO 5000 | 48 GB | $0.96 | Q8 comfortably |
146+ | RTX 6000 Ada | 48 GB | $0.99 | Q8 comfortably |
147+ | H100 NVL | 94 GB | $3.19 | The full 42 GB model |
148+ | RTX PRO 6000 | 96 GB | $2.49 | The full 42 GB model with room to spare |
149+
150+ To use another card, swap its name in Prompt 2. If you're not sure which file fits, ask your agent. It reads the model card, checks your GPU and tells you what fits.
151+
152+ ```prompt
153+ I want to run LTX-2.5 on this GPU. Read the model card for unsloth/LTX-2.5-GGUF, compare the quantizations that fit in this GPU's memory with room for the text encoder and VAE, and recommend one. Tell me the file size and what I'd give up compared with the full model.
154+ ```
155+
156+ ## Step 3: Install the model
157+
158+ Your agent connects over SSH, updates ComfyUI, puts each file in the right folder and renders a test clip to prove it all works. Ours took about 13 minutes. Without the Unsloth line, our agent reached for the official Lightricks files, which sit behind a login, and stopped.
159+
160+ ```prompt
161+ Install the quantization you recommended on my network volume. Use the public files from unsloth/LTX-2.5-GGUF for everything, including the text encoder, VAEs and upscaler, so no login is needed. Update ComfyUI if it's too old for LTX-2.5, install the custom node it needs, and keep all of it on the network volume so it survives a new pod. Render a short test clip through ComfyUI and show it to me, then save the working workflow in ComfyUI's sidebar so I can open it myself.
162+ ```
163+
164+ ## Step 4: Render in ComfyUI
165+
166+ Open the link, open your workflows and click the one your agent saved. Four settings matter:
167+
168+ | Setting | What it does |
169+ | --- | --- |
170+ | Prompt | What to make |
171+ | Duration | Length in seconds |
172+ | Megapixels | The size. 0.5 is a fast preview, and 0.9 is about 1280 wide |
173+ | Seed | The randomness. Keep it and change one word to compare, or change it for a new take |
174+
175+ Inside, the workflow renders twice: a fast pass at half size, an upscaler, then a short second pass to sharpen it. That's a big part of why it's fast.
176+
177+ Write your prompt like a shot description. Say what's in the frame, what moves, the light and the camera, then describe the sound. This is the one we used for the robot clips:
178+
179+ ```prompt
180+ A small orange robot with round glowing eyes rolls slowly across a sunlit workshop bench, then looks up at the camera and gives a little wave. Warm morning light through a window, dust floating in the air, soft cinematic depth of field. Gentle mechanical whirring and quiet birdsong outside.
181+ ```
182+
183+ LTX takes your sound words literally. Quiet birdsong gave us a clip that was almost silent, about 42 dB down, and a loud drum solo came out at full level.
184+
185+ ## What it costs
186+
187+ | Item | Our cost |
188+ | --- | --- |
189+ | This pod, with its disk and the volume | About $0.92 an hour |
190+ | One five-second clip | Under two cents, at about a minute a clip |
191+ | First render on a new pod | About three minutes while the model loads |
192+ | Pod left idle overnight | $7.36 for 8 hours |
193+ | 100 GB network volume | About $7 a month |
194+
195+ The meter runs while the pod sits idle, so shut it down when you're done.
196+
197+ ## Step 5: Shut it down
198+
199+ ```prompt
200+ I'm done for today. Terminate my ComfyUI pod, keep the network volume, and show me anything that's still billing.
201+ ```
202+
203+ The pod goes away and the GPU stops billing. Your models stay on the network volume.
204+
205+ ## Step 6: Next time
206+
207+ ```prompt
208+ Bring ComfyUI back on my network volume, tell me the hourly price, and give me the link.
209+ ```
210+
211+ Ours was back in about a minute, with ComfyUI, the model and the workflow all still there. Your storage lives in one data center, so if that card is sold out there, you wait or choose another card.
212+
213+ ## When it breaks
214+
215+ You don't need to know the fix. Tell your agent what you saw, and ask it to check before it changes anything.
216+
217+ | If you see | Tell your agent |
218+ | --- | --- |
219+ | A download needs a login | Use public files. If you need a gated file, add a token yourself and never paste it into chat |
220+ | A workflow won't load | ComfyUI is probably too old, so update it |
221+ | A card is sold out | Try another data center or another card |
222+ | Out of memory | Drop one quantization level or lower the size |
223+
224+ ## How we tested this
225+
226+ We ran all six prompts on a live Runpod account on October 31, 2026, and the numbers here come from that run. Two prompts were changed after it. Prompt 4 combines three passes, because we added a line each time the agent stopped. Prompt 6 now asks for the price first, because our agent created the pod before telling us the price. Neither final version has run as one clean pass, so read your agent's plan before you approve it.
227+
228+ ## License and rules
229+
230+ LTX-2.5 uses the [LTX-2.x Community License](https://huggingface.co/unsloth/LTX-2.5-GGUF/blob/main/LICENSE), and the terms are worth reading before you publish anything. This is a short summary, not legal advice:
231+
232+ - It's free to use if your entity makes under $10 million a year. At or above that, you need a paid license for commercial use.
233+ - Its restrictions and [acceptable use policy](https://static.lightricks.com/legal/ltx-acceptable-use-policy.pdf) bar breaking the law, harming minors and deepfakes of people without their consent.
234+ - It can require you to say a clip is machine-generated.
235+
236+ Running a model yourself doesn't change any of that. [Runpod's terms](https://www.runpod.io/legal/terms-of-service) and [privacy policy](https://www.runpod.io/legal/privacy-policy) apply to your pod too.
237+
238+ ## Keep going
239+
240+ Want to do it by hand? [Run open-weight AI video models on Runpod](/ai-video/runpod-open-weight-video) covers the same setup in the console, and [Keep your Runpod bill down when making AI video](/ai-video/runpod-cost-tips) has more ways to spend less per clip.

content/tutorials/ai-video/runpod-cost-tips.mdx added

1+ ---
2+ title: "Keep your Runpod bill down when making AI video"
3+ description: "Where Runpod charges come from when you generate video with ComfyUI, and seven habits that cut them: storage, stopping vs terminating, test renders and billing alerts."
4+ level: Beginner
5+ minutes: 7
6+ publishedAt: 2026-10-31
7+ ---
8+
9+ Running open-weight video models on Runpod is cheap per clip and easy to overspend on by accident. Almost every surprise bill comes from one of two things: a GPU left running, or storage nobody remembered. This guide covers where the charges come from and the habits that keep them small. Prices and rules below are from [Runpod's pricing](https://docs.runpod.io/pods/pricing) and [billing](https://docs.runpod.io/accounts-billing/billing) docs; check them before you rely on a number, because they change.
10+
11+ ## Where the money goes
12+
13+ - **GPU time.** Pods are billed by the second while they run, whether ComfyUI is busy or sitting idle. This is the big one. Current GPU prices are shown in the Runpod console when you deploy a pod.
14+ - **Storage.** Container disk, volume disk and network volumes each have their own rate, and some keep charging after the pod stops:
15+
16+ | Storage | Running pod | Stopped pod |
17+ | --- | --- | --- |
18+ | Container disk | $0.10/GB/month | Not charged (and erased) |
19+ | Volume disk | $0.10/GB/month | $0.20/GB/month |
20+ | Network volume | $0.07/GB/month | $0.07/GB/month (first 1 TB) |
21+
22+ A stopped pod with a 100 GB volume disk costs about $20 a month to keep. The same 100 GB on a network volume costs about $7, and it survives when you terminate the pod.
23+
24+ ## Seven habits that keep the bill small
25+
26+ <Steps>
27+ <Step title="Keep models on a network volume">
28+ Download model weights once to a network volume instead of to each pod. You stop paying for duplicate copies, you can terminate pods freely, and new pods start with everything already in place. Network volumes are only on Secure Cloud and belong to one data center, so pick that data center for your pods too.
29+ </Step>
30+ <Step title="Terminate instead of stopping">
31+ Stopping a pod keeps its volume disk, billed at $0.20/GB/month. If your models and outputs live on a network volume, terminate the pod when you finish. You lose nothing you need and stop paying for the disk.
32+ </Step>
33+ <Step title="Size the GPU to the model">
34+ Check the model's VRAM requirement and pick the smallest GPU that fits it with some headroom. Then try one size up: a faster GPU can cost more per hour but less per clip, because it finishes sooner. Time a test render on each and compare.
35+ </Step>
36+ <Step title="Test small, then render big">
37+ Work out prompts and settings on short, low-resolution clips, and only render full length and resolution once you like what you see. Most of the time in a session goes into iterating, so make iterations cheap.
38+ </Step>
39+ <Step title="Queue renders back to back">
40+ ComfyUI has a queue. Line up several prompts or seeds and let them run while you do something else, instead of rendering one, looking, and leaving the GPU idle while you think.
41+ </Step>
42+ <Step title="Set a stop timer">
43+ Runpod pods don't stop on their own when idle. Its docs show a simple timer you can run in the pod's terminal, which stops the pod after two hours:
44+
45+ ```bash
46+ sleep 2h; runpodctl pod stop $RUNPOD_POD_ID &
47+ ```
48+
49+ Change `2h` to fit your session. It's a safety net for the evening you forget.
50+ </Step>
51+ <Step title="Turn on a low-balance alert">
52+ In the console, under Billing, set a low-balance alert so Runpod emails you before your credit runs out. Keep an eye on auto-pay if you use it, since it tops up your balance automatically.
53+ </Step>
54+ </Steps>
55+
56+ ## Know what happens at a $0 balance
57+
58+ <Callout type="warning">
59+ Runpod stops pods automatically when your balance reaches $0. Pods with a network volume are stopped and kept, but pods without one are terminated and their data can't be recovered.
60+ </Callout>
61+
62+ That's one more reason to keep models and finished clips on a network volume, and to download anything you want to keep before a session ends.
63+
64+ ## A quick pre-flight checklist
65+
66+ - [ ] Models are on a network volume in the same data center as the pod
67+ - [ ] GPU picked for the model's VRAM, not the biggest one available
68+ - [ ] First renders are short and low resolution
69+ - [ ] Stop timer running
70+ - [ ] Low-balance alert on
71+ - [ ] Pod terminated (not just stopped) at the end of the session
72+
73+ New to the setup itself? Start with [Run open-weight AI video models on Runpod](/ai-video/runpod-open-weight-video).

content/tutorials/ai-video/runpod-open-weight-video.mdx added

1+ ---
2+ title: "Run open-weight AI video models on Runpod"
3+ description: "Rent a GPU on Runpod, set up ComfyUI, and generate video with open-weight models you run yourself."
4+ level: Intermediate
5+ minutes: 20
6+ publishedAt: 2026-10-31
7+ ---
8+
9+ Open-weight video models can run on a GPU you rent on [Runpod](https://www.runpod.io), so you choose the model, the settings and what happens to the output. It takes more setup than a hosted video tool. This guide goes from an empty account to your first clip in [ComfyUI](https://github.com/comfyanonymous/ComfyUI), the node-based app most people use to run these models.
10+
11+ <Callout type="tip">
12+ Rather have your agent do it? [Set up ComfyUI on Runpod with your agent](/ai-video/comfyui-runpod-agent) gets the same result from six prompts.
13+ </Callout>
14+
15+ ## What you need
16+
17+ - A Runpod account with some credit
18+ - A [Hugging Face](https://huggingface.co) account, for downloading model weights
19+ - About 30 minutes for the first setup; later sessions start in a few minutes
20+
21+ ## How Runpod bills you
22+
23+ Knowing this first saves money. According to [Runpod's pricing docs](https://docs.runpod.io/pods/pricing), pods are billed by the second while they run, and storage is billed separately:
24+
25+ | Storage | Running pod | Stopped pod | What happens to it |
26+ | --- | --- | --- | --- |
27+ | Container disk | $0.10/GB/month | Not charged | Erased when the pod stops |
28+ | Volume disk (`/workspace`) | $0.10/GB/month | $0.20/GB/month | Kept until you terminate the pod |
29+ | Network volume | $0.07/GB/month | $0.07/GB/month | Kept until you delete it; survives pod termination |
30+
31+ Video model weights run to tens of gigabytes, so where you keep them matters. A network volume lets you download them once and reuse them on every new pod.
32+
33+ ## Set up the pod
34+
35+ <Steps>
36+ <Step title="Create a network volume">
37+ In the Runpod console, open Storage and create a network volume. Pick a data center and a size with room for a few models. Network volumes are only available on Secure Cloud, the GPUs you can use depend on the volume's data center, and you can make a volume bigger later but never smaller.
38+ </Step>
39+ <Step title="Pick a GPU">
40+ Video models need a lot of VRAM. Check the model's page for its minimum and pick a GPU in your volume's data center that meets it with some headroom. A bigger GPU costs more per hour but often finishes a clip in a fraction of the time.
41+ </Step>
42+ <Step title="Deploy from a ComfyUI template">
43+ Runpod has templates with ComfyUI already installed. Choose one, and attach your network volume when you deploy: a network volume can only be attached when a pod is created.
44+ </Step>
45+ <Step title="Open ComfyUI">
46+ Once the pod is running, open its Connect menu and click the ComfyUI port. ComfyUI opens in your browser.
47+ </Step>
48+ </Steps>
49+
50+ ## Download a model
51+
52+ Open-weight video models such as Wan and LTX-Video are published on Hugging Face. Each model's page, or its ComfyUI example workflow, lists the files you need and which ComfyUI folder each one goes in, usually `models/diffusion_models`, `models/text_encoders` and `models/vae`.
53+
54+ From the pod's terminal, install the Hugging Face CLI and download each file into place on your volume:
55+
56+ ```bash
57+ pip install -U huggingface_hub
58+ hf auth login # only needed for gated models
59+ hf download <model-repo> <file-name> --local-dir /workspace/runpod-slim/ComfyUI/models/<folder>
60+ ```
61+
62+ That's the path in Runpod's official ComfyUI template, so check yours if you use a different one. Recent ComfyUI versions also include ready-made video workflows in their template browser, and opening one tells you which model files are missing.
63+
64+ ## Generate your first clip
65+
66+ <Steps>
67+ <Step title="Load the matching workflow">
68+ Open the example workflow for your model, from its page or ComfyUI's templates, and check that every loader node points at a file you downloaded.
69+ </Step>
70+ <Step title="Start small">
71+ Make the first clip short and low resolution, just enough to prove the workflow runs end to end. A full-size clip can take many minutes; a test clip should take one or two.
72+ </Step>
73+ <Step title="Scale up">
74+ Raise the resolution and length step by step. Each model's page lists the resolutions and frame counts it was trained for, and staying close to them gives the best results.
75+ </Step>
76+ </Steps>
77+
78+ ## Finish the session
79+
80+ <Callout type="warning">
81+ Stop or terminate the pod when you're done. You're billed for every second a GPU pod runs, even when it's idle.
82+ </Callout>
83+
84+ Stopping a pod releases the GPU and keeps `/workspace`, but you keep paying for that volume disk. Terminating deletes everything that isn't on a network volume. If your models and outputs are on a network volume, terminating is the cheaper choice.
85+
86+ [Keep your Runpod bill down when making AI video](/ai-video/runpod-cost-tips) covers more ways to spend less per clip.

content/tutorials/chatgpt/agents-md-codex.mdx added

1+ ---
2+ title: "How to set up AGENTS.md for Codex (with examples)"
3+ description: "Give OpenAI Codex standing instructions with AGENTS.md: where the files go, how Codex combines them, overrides for one folder, size limits, and how to check what it loaded."
4+ level: Beginner
5+ minutes: 9
6+ publishedAt: 2026-10-31
7+ ---
8+
9+ `AGENTS.md` is a plain Markdown file that tells a coding agent how to work in your project: how to install, build and test, the conventions to follow, and what to avoid. Codex reads it before it starts working, so you don't repeat the same instructions in every prompt.
10+
11+ It's also an open format, not a Codex-only file. [agents.md](https://agents.md) lists support in Codex, Cursor, GitHub Copilot's coding agent, Gemini CLI, Jules, Zed, Warp, VS Code and others, and recent versions of Claude Code read it too. The format is now stewarded by the Agentic AI Foundation under the Linux Foundation. There are no required fields: any Markdown works.
12+
13+ This guide follows OpenAI's [AGENTS.md guide for Codex](https://learn.chatgpt.com/docs/agent-configuration/agents-md).
14+
15+ ## Where Codex looks
16+
17+ Codex builds its instructions from two places, every time it starts:
18+
19+ 1. **Your global file.** In your Codex home folder, `~/.codex` unless you set `CODEX_HOME`, Codex reads `AGENTS.override.md` if it exists, otherwise `AGENTS.md`. Use this for preferences that apply to every project.
20+ 2. **Your project.** Starting at the project root, usually the Git root, Codex walks down folder by folder to the directory you're working in. In each folder it takes the first file it finds of `AGENTS.override.md`, then `AGENTS.md`. It reads at most one file per folder, and skips empty files.
21+
22+ Codex joins everything it found in that order: global first, then the project root, then each folder down to where you are. Files closer to your working directory come later, so their instructions win when two disagree.
23+
24+ Two details catch people out:
25+
26+ - Codex stops at your current directory. An `AGENTS.md` in a folder below it isn't read until you work from that folder.
27+ - The instructions are built once, when Codex starts. Edit an `AGENTS.md` and you need a new session to see the change.
28+
29+ ## A global AGENTS.md
30+
31+ Start with the few things you want in every project. This is the example from OpenAI's guide:
32+
33+ ```markdown
34+ # ~/.codex/AGENTS.md
35+
36+ ## Working agreements
37+
38+ - Always run `npm test` after modifying JavaScript files.
39+ - Prefer `pnpm` when installing dependencies.
40+ - Ask for confirmation before adding new production dependencies.
41+ ```
42+
43+ ## A project AGENTS.md
44+
45+ At the root of your repo, describe the project the way you'd brief a new teammate. Keep each line something Codex can act on or check:
46+
47+ ```markdown
48+ # AGENTS.md
49+
50+ ## Setup
51+ - Install dependencies: `pnpm install`
52+ - Start the dev server: `pnpm dev` (http://localhost:3000)
53+ - Run tests: `pnpm test`. Run them after every change.
54+
55+ ## Code style
56+ - TypeScript strict mode. No `any` without a comment saying why.
57+ - Server components by default; add "use client" only when needed.
58+
59+ ## Repository expectations
60+ - Run `pnpm lint` before opening a pull request.
61+ - Document public utilities in `docs/` when you change their behavior.
62+ - Never commit `.env` files or secrets.
63+ ```
64+
65+ OpenAI's advice is to keep the rules short and leave formatting and lint checks to CI, where they're enforced anyway.
66+
67+ ## Override one folder
68+
69+ Some parts of a codebase need their own rules. Put an `AGENTS.override.md` in that folder and Codex uses it there instead of that folder's `AGENTS.md`. The root file still loads. OpenAI's example for a payments service:
70+
71+ ```markdown
72+ # services/payments/AGENTS.override.md
73+
74+ ## Payments service rules
75+
76+ - Use `make test-payments` instead of `npm test`.
77+ - Never rotate API keys without notifying the security channel.
78+ ```
79+
80+ An override works globally too: `~/.codex/AGENTS.override.md` temporarily replaces your global `AGENTS.md` without deleting it. Delete the override to go back.
81+
82+ ## Size limits and other file names
83+
84+ Codex stops adding files once the combined instructions reach 32 KiB, the default for `project_doc_max_bytes`. If your team already uses a different file name, Codex can read that when a folder has no `AGENTS.md`. Both settings go in `~/.codex/config.toml`:
85+
86+ ```toml
87+ # ~/.codex/config.toml
88+ project_doc_fallback_filenames = ["TEAM_GUIDE.md", ".agents.md"]
89+ project_doc_max_bytes = 65536
90+ ```
91+
92+ With that config, Codex checks each folder for `AGENTS.override.md`, then `AGENTS.md`, then `TEAM_GUIDE.md`, then `.agents.md`. Other names are ignored.
93+
94+ ## Check what Codex loaded
95+
96+ Ask Codex directly. These commands from OpenAI's guide run without stopping for approvals:
97+
98+ ```bash
99+ # From the repo root
100+ codex --ask-for-approval never "Summarize the current instructions."
101+
102+ # From a subfolder, to check overrides
103+ codex --cd services/payments --ask-for-approval never "List the instruction sources you loaded."
104+ ```
105+
106+ If the answer is missing something, check the file isn't empty, that it's between the project root and your working directory, and that the combined size is under the limit.
107+
108+ ## Share one file with Claude Code
109+
110+ If your team also uses Claude Code, you don't need two copies. Claude Code reads `AGENTS.md` when the project has no `CLAUDE.md`, and a `CLAUDE.md` that starts with `@AGENTS.md` imports it. [How to write a CLAUDE.md that Claude Code follows](/claude/claude-md-guide) covers the Claude side.

content/tutorials/chatgpt/codex-best-practices.mdx added

1+ ---
2+ title: "Codex best practices: the official resources"
3+ description: "OpenAI's own docs, courses, talks and videos on getting good work out of Codex, collected in one place."
4+ level: Beginner
5+ minutes: 5
6+ publishedAt: 2026-10-30
7+ updatedAt: 2026-10-31
8+ ---
9+
10+ OpenAI builds Codex, and its team already publishes the best guidance on how to use it. Rather than rewrite that, this page points you to it. Everything below is made and kept up to date by OpenAI. We add a one-line summary so you can pick where to start.
11+
12+ Codex changes every few months, so we favor pages OpenAI keeps current over one-off posts. Talks and webinars show their date so you can tell how recent they are.
13+
14+ ## The short version
15+
16+ OpenAI's [best-practices guide](https://learn.chatgpt.com/guides/best-practices) asks you to treat Codex less like a one-off assistant and more like a teammate you set up once and improve over time. In practice that means:
17+
18+ - **Write prompts with four parts.** Say the goal, the context Codex needs, the constraints, and what "done" looks like. Use lower reasoning effort for small, well-scoped tasks and higher for debugging or long changes.
19+ - **Plan before hard tasks.** For anything complex or fuzzy, switch on Plan mode with `/plan` or `Shift`+`Tab`, or ask Codex to interview you about the idea before it writes code.
20+ - **Move repeated rules into AGENTS.md.** Keep it short: how to build, test and lint, the conventions, and what done means. When Codex makes the same mistake twice, add a line. Our [AGENTS.md guide](/chatgpt/agents-md-codex) shows how.
21+ - **Let it check its own work.** Ask Codex to write or update tests and run the checks, then review the diff with `/review` before you accept it. Start with the default permissions and loosen them only for repos you trust.
22+ - **Keep chats focused.** Use one chat per piece of work rather than one for the whole project, which bloats the context and gets worse over time. Turn a prompt you keep reusing into a skill, and only schedule a task once it works reliably by hand.
23+
24+ ## Start here
25+
26+ <Resources>
27+ <Resource kind="Guide" source="OpenAI" title="Codex best practices" href="https://learn.chatgpt.com/guides/best-practices">
28+ OpenAI's own guide to better results across the Codex CLI, IDE extension and app: prompting, planning, AGENTS.md, testing and review, MCP, skills, and common mistakes. If you read one thing, read this.
29+ </Resource>
30+ <Resource kind="Docs" source="OpenAI" title="Codex documentation" href="https://learn.chatgpt.com/docs">
31+ The home of OpenAI's Codex docs, with use cases, setup guides and the latest product updates.
32+ </Resource>
33+ <Resource kind="Docs" source="OpenAI" title="Codex CLI" href="https://learn.chatgpt.com/docs/codex/cli">
34+ Install the CLI, sign in and run your first task in the terminal, with links to the command reference and automation.
35+ </Resource>
36+ <Resource kind="Docs" source="OpenAI" title="Codex IDE extension" href="https://learn.chatgpt.com/docs/codex/ide">
37+ Use Codex in VS Code, Cursor, Windsurf, Xcode or JetBrains, review edits inline, and hand longer tasks to the cloud.
38+ </Resource>
39+ <Resource kind="Docs" source="OpenAI" title="Codex Cloud" href="https://learn.chatgpt.com/docs/cloud">
40+ Run coding tasks remotely: set up a cloud environment, control network access and secrets, and review changes before you open a PR.
41+ </Resource>
42+ </Resources>
43+
44+ ## Set up your project
45+
46+ <Resources>
47+ <Resource kind="Docs" source="OpenAI" title="Custom instructions with AGENTS.md" href="https://learn.chatgpt.com/docs/agent-configuration/agents-md">
48+ How Codex finds and combines AGENTS.md files, from a global file down to per-folder overrides.
49+ </Resource>
50+ <Resource kind="Docs" source="OpenAI" title="Config basics" href="https://learn.chatgpt.com/docs/config-file/config-basic">
51+ Set defaults in config.toml, such as the model, approval prompts and sandbox level, for you or for one project.
52+ </Resource>
53+ <Resource kind="Docs" source="OpenAI" title="Agent approvals and security" href="https://learn.chatgpt.com/docs/agent-approvals-security">
54+ Run Codex safely with sandboxing, approval policies and network controls.
55+ </Resource>
56+ <Resource kind="Docs" source="OpenAI" title="Build skills" href="https://learn.chatgpt.com/docs/build-skills">
57+ Package instructions, resources and scripts as skills that extend Codex, and share them as plugins.
58+ </Resource>
59+ <Resource kind="Docs" source="OpenAI" title="Model Context Protocol" href="https://learn.chatgpt.com/docs/extend/mcp">
60+ Connect Codex to outside tools by adding MCP servers.
61+ </Resource>
62+ </Resources>
63+
64+ ## Stay current
65+
66+ <Resources>
67+ <Resource kind="Release notes" source="OpenAI" title="ChatGPT and Codex changelog" href="https://learn.chatgpt.com/docs/changelog">
68+ Dated release notes for the Codex CLI, the Codex app and ChatGPT.
69+ </Resource>
70+ <Resource kind="Blog" source="OpenAI" title="Codex posts on the OpenAI Developers blog" href="https://developers.openai.com/blog/topic/codex">
71+ OpenAI's developer blog posts about Codex, newest first.
72+ </Resource>
73+ <Resource kind="Cookbook" source="OpenAI" title="Codex in the OpenAI Cookbook" href="https://developers.openai.com/cookbook/topic/codex">
74+ Worked examples for automating developer workflows and building with Codex agents and tools.
75+ </Resource>
76+ </Resources>
77+
78+ ## Courses and training
79+
80+ <Resources>
81+ <Resource kind="Courses" source="OpenAI Academy" title="Codex on OpenAI Academy" href="https://openai.com/academy/codex/">
82+ OpenAI Academy's Codex hub for learning to write code, run tasks and build automated workflows.
83+ </Resource>
84+ <Resource kind="Webinar" source="OpenAI Academy" date="March 2026" title="Codex Fundamentals" href="https://academy.openai.com/public/clubs/builders-etkn1/videos/codex-for-software-engineers-2026-03-13">
85+ A recorded OpenAI Academy webinar on the fundamentals of working with Codex. Free sign-in to watch.
86+ </Resource>
87+ </Resources>
88+
89+ ## Talks and videos
90+
91+ <Resources>
92+ <Resource kind="Videos" source="OpenAI" title="ChatGPT and Codex videos" href="https://learn.chatgpt.com/videos">
93+ OpenAI's library of Codex demos, walkthroughs and talks, grouped by topic.
94+ </Resource>
95+ <Resource kind="Learning hub" source="OpenAI Developers" title="Learn Codex" href="https://developers.openai.com/learn/codex">
96+ OpenAI's Codex learning page, with product videos on the Codex app, code review, JetBrains and building frontends.
97+ </Resource>
98+ </Resources>

content/tutorials/claude/claude-code-best-practices.mdx added

1+ ---
2+ title: "Claude Code best practices: the official resources"
3+ description: "Anthropic's own docs, courses, talks and videos on using Claude Code well, collected in one place."
4+ level: Beginner
5+ minutes: 5
6+ publishedAt: 2026-10-30
7+ updatedAt: 2026-10-31
8+ ---
9+
10+ Anthropic builds Claude Code, and its team has already written the best guidance on how to use it. Rather than rewrite that, this page points you to it. Everything below is made and kept up to date by Anthropic. We add a one-line summary so you can pick where to start.
11+
12+ Claude Code changes every few months, so we favor pages Anthropic keeps current over one-off posts. Talks and events show their date so you can tell how recent they are.
13+
14+ ## The short version
15+
16+ Anthropic's [best-practices guide](https://code.claude.com/docs/en/best-practices) boils down to this. Claude Code's defaults already handle most plain prompts well, so these are for when they don't:
17+
18+ - **Tell Claude what it can't see.** Put the exact test, typecheck and lint commands, the team's decisions and the misleading corners of the codebase in a short `CLAUDE.md`. Leave out what Claude can read from the repo. Our [CLAUDE.md guide](/claude/claude-md-guide) shows how.
19+ - **Give it a check to run.** A test, a build or a linter that comes back pass or fail lets Claude find and fix its own mistakes instead of stopping when the work only looks done. Ask for the command it ran and the output as evidence.
20+ - **Enforce the rules that can't have exceptions.** A line in `CLAUDE.md` works most of the time. For "always" and "never", use hooks and permission rules, which Claude Code enforces whatever Claude decides.
21+ - **Steer early.** Watch the first minute and press `Esc` the moment it drifts. After two failed corrections, run `/clear` and write a better prompt instead of a third.
22+ - **Drop the old workarounds.** ALL CAPS and IMPORTANT, "think harder", and "keep going, don't be lazy" are no longer needed with current models. Plain, specific instructions work better.
23+
24+ ## Start here
25+
26+ <Resources>
27+ <Resource kind="Guide" source="Anthropic" title="Best practices for Claude Code" href="https://code.claude.com/docs/en/best-practices">
28+ Anthropic's own best-practices guide: tell Claude what it can't see, give it a check to run, and enforce the rules that can't have exceptions. If you read one thing, read this.
29+ </Resource>
30+ <Resource kind="Docs" source="Anthropic" title="Claude Code overview" href="https://code.claude.com/docs/en/overview">
31+ What Claude Code is and where it runs: the terminal, your IDE, the desktop app and the browser.
32+ </Resource>
33+ <Resource kind="Docs" source="Anthropic" title="Quickstart" href="https://code.claude.com/docs/en/quickstart">
34+ Install it, sign in, and make your first code change from the command line.
35+ </Resource>
36+ <Resource kind="Docs" source="Anthropic" title="How Claude Code works" href="https://code.claude.com/docs/en/how-claude-code-works">
37+ The agentic loop, the built-in tools, and how Claude Code reads and changes your project.
38+ </Resource>
39+ <Resource kind="Docs" source="Anthropic" title="Common workflows" href="https://code.claude.com/docs/en/common-workflows">
40+ Step-by-step recipes for everyday work: exploring a codebase, fixing bugs, refactoring and testing.
41+ </Resource>
42+ </Resources>
43+
44+ ## Set up your project
45+
46+ <Resources>
47+ <Resource kind="Docs" source="Anthropic" title="Memory and CLAUDE.md" href="https://code.claude.com/docs/en/memory">
48+ Give Claude standing instructions with CLAUDE.md or AGENTS.md files, and let it keep learnings with auto memory.
49+ </Resource>
50+ <Resource kind="Docs" source="Anthropic" title="Extend Claude Code" href="https://code.claude.com/docs/en/features-overview">
51+ When to reach for CLAUDE.md, skills, subagents, hooks, MCP or plugins. A good map before you go deeper on any one.
52+ </Resource>
53+ <Resource kind="Docs" source="Anthropic" title="Skills" href="https://code.claude.com/docs/en/skills">
54+ Create, manage and share skills, including custom commands and the skills that come built in.
55+ </Resource>
56+ <Resource kind="Docs" source="Anthropic" title="Hooks guide" href="https://code.claude.com/docs/en/hooks-guide">
57+ Run your own commands when Claude edits files or finishes a task, to format code, send notifications or enforce project rules.
58+ </Resource>
59+ <Resource kind="Docs" source="Anthropic" title="Subagents" href="https://code.claude.com/docs/en/sub-agents">
60+ Set up specialized subagents for focused tasks and to keep the main session's context clean.
61+ </Resource>
62+ <Resource kind="Docs" source="Anthropic" title="Connect tools with MCP" href="https://code.claude.com/docs/en/mcp">
63+ Connect Claude Code to GitHub, databases, docs and other tools through the Model Context Protocol.
64+ </Resource>
65+ <Resource kind="Docs" source="Anthropic" title="Security" href="https://code.claude.com/docs/en/security">
66+ The safeguards built into Claude Code and Anthropic's advice for using it safely.
67+ </Resource>
68+ </Resources>
69+
70+ ## Stay current
71+
72+ <Resources>
73+ <Resource kind="Weekly digest" source="Anthropic" title="What's new in Claude Code" href="https://code.claude.com/docs/en/whats-new">
74+ A weekly roundup of notable features, with snippets, demos and why each one matters. The easiest way to keep up.
75+ </Resource>
76+ <Resource kind="Release notes" source="Anthropic" title="Claude Code changelog" href="https://code.claude.com/docs/en/changelog">
77+ Every release by version: new features, improvements and fixes.
78+ </Resource>
79+ <Resource kind="Help center" source="Anthropic" title="Claude Code power user tips" href="https://support.claude.com/en/articles/14554000-claude-code-power-user-tips">
80+ Practical tips from Anthropic's help center for getting more out of everyday sessions.
81+ </Resource>
82+ </Resources>
83+
84+ ## Courses and training
85+
86+ <Resources>
87+ <Resource kind="Courses" source="Anthropic Academy" title="Anthropic Academy courses" href="https://academy.claude.com/courses">
88+ Anthropic's free course catalog, including Claude Code 101, Claude Code in Action, and introductions to subagents and agent skills.
89+ </Resource>
90+ <Resource kind="Course" source="Anthropic Academy" title="Claude Code in Action" href="https://anthropic.skilljar.com/claude-code-in-action">
91+ A free hands-on course on running long Claude Code sessions you can trust: CLAUDE.md, permission modes, hooks, headless mode, GitHub Actions and plugins.
92+ </Resource>
93+ <Resource kind="Webinar series" source="Anthropic" title="Claude Code webinar series" href="https://claude.com/resources/webinar-series/claude-code">
94+ Live sessions that run on repeat, from getting started in an hour to multi-agent patterns for teams.
95+ </Resource>
96+ <Resource kind="Live webinar" source="Anthropic" title="Claude Code: Foundations" href="https://claude.com/resources/webinars/claude-code-foundations-series">
97+ A hands-on introduction from Anthropic's Claude Code specialist team, for people new to it.
98+ </Resource>
99+ <Resource kind="Live webinar" source="Anthropic" title="Claude Code: Advanced" href="https://claude.com/resources/webinars/claude-code-workshop-advanced">
100+ A 90-minute session for people who already use Claude Code every day and want to go further.
101+ </Resource>
102+ </Resources>
103+
104+ ## Talks and videos
105+
106+ <Resources>
107+ <Resource kind="Videos" source="Anthropic" title="Claude videos" href="https://claude.com/resources/videos">
108+ Anthropic's library of demos, talks and tutorials, newest first, including short Claude Code walkthroughs.
109+ </Resource>
110+ <Resource kind="Conference" source="Anthropic" title="Code with Claude" href="https://claude.com/code-with-claude">
111+ Anthropic's developer conference, with recordings from San Francisco, London and Tokyo.
112+ </Resource>
113+ <Resource kind="Talk" source="Code with Claude Tokyo" date="June 2026" title="What's new in Claude Code" href="https://claude.com/code-with-claude/session/tyo-whats-new-in-claude-code">
114+ A twenty-minute summary of what shipped in Claude Code, why the team built it, and how to get started.
115+ </Resource>
116+ <Resource kind="Workshop" source="Code with Claude SF" date="May 2026" title="How we Claude Code" href="https://claude.com/code-with-claude/session/sf-ext-how-we-claude-code">
117+ Anthropic engineers set up a real repo the way they do internally, with context files, custom commands, hooks and subagents, then compare stock and tuned runs.
118+ </Resource>
119+ <Resource kind="Blog" source="Anthropic" title="Anthropic Engineering" href="https://www.anthropic.com/engineering">
120+ Deep dives from the people building Claude and Claude Code, on agents, tools and how they work in practice.
121+ </Resource>
122+ </Resources>

content/tutorials/claude/claude-md-guide.mdx added

1+ ---
2+ title: "How to write a CLAUDE.md that Claude Code follows (with examples)"
3+ description: "Where CLAUDE.md files go, what to put in them, a full example, and how to check that Claude Code actually loaded and follows your instructions."
4+ level: Beginner
5+ minutes: 10
6+ publishedAt: 2026-10-31
7+ ---
8+
9+ Every Claude Code session starts with a fresh context window. A `CLAUDE.md` file is how you carry knowledge from one session to the next: build commands, conventions, where things live, and the rules you'd otherwise repeat every day. Claude reads it at the start of every session.
10+
11+ This guide follows Anthropic's [memory documentation](https://code.claude.com/docs/en/memory) and turns it into a file you can start from today.
12+
13+ ## Create your first one with /init
14+
15+ In your project folder, start Claude Code and run:
16+
17+ ```text
18+ /init
19+ ```
20+
21+ Claude reads your codebase and writes a starting `CLAUDE.md` with the build commands, test instructions and conventions it finds. If a `CLAUDE.md` already exists, `/init` suggests improvements instead of overwriting it. Treat the result as a draft. Anthropic's own advice is that from there the work is mostly removing lines: the ones worth keeping are the ones Claude couldn't work out on its own.
22+
23+ ## Where CLAUDE.md files go
24+
25+ You can have more than one, each with a different reach. Claude Code loads them from broadest to most specific:
26+
27+ | File | Who it's for | Shared through git? |
28+ | --- | --- | --- |
29+ | `~/.claude/CLAUDE.md` | You, in every project | No |
30+ | `./CLAUDE.md` or `./.claude/CLAUDE.md` | Everyone working on this project | Yes |
31+ | `./CLAUDE.local.md` | You, in this project only (add it to `.gitignore`) | No |
32+
33+ Organizations can also deploy a managed `CLAUDE.md` that applies to every user.
34+
35+ Claude Code loads the `CLAUDE.md` files in your working directory and every folder above it when a session starts. A `CLAUDE.md` inside a subfolder loads later, the first time Claude reads or edits a file in that folder. That makes subfolder files a good place for rules that only matter there.
36+
37+ ## What to put in it
38+
39+ Anthropic's guidance is to treat `CLAUDE.md` as the place you write down what you'd otherwise re-explain. Add to it when:
40+
41+ - Claude makes the same mistake a second time
42+ - A code review catches something Claude should have known about the codebase
43+ - You type the same correction you typed last session
44+ - A new teammate would need the same context to be productive
45+
46+ Keep it to facts that matter in every session. A long multi-step procedure fits better in a [skill](https://code.claude.com/docs/en/skills), and rules for one part of the codebase fit better in a path-scoped rule (below).
47+
48+ ## Write instructions Claude can check
49+
50+ Claude treats `CLAUDE.md` as context, not as enforced configuration, so how you write each line affects how reliably it's followed. The docs' rule of thumb is to be concrete enough to verify:
51+
52+ | Vague | Concrete |
53+ | --- | --- |
54+ | Format code properly | Use 2-space indentation |
55+ | Test your changes | Run `npm test` before committing |
56+ | Keep files organized | API handlers live in `src/api/handlers/` |
57+
58+ Aim for under 200 lines per file. Longer files take up more context and are followed less closely. Group related lines under headings, and remove instructions that contradict each other: when two lines disagree, Claude may pick either.
59+
60+ ## A complete example
61+
62+ Here's a `CLAUDE.md` for a typical Next.js app. It sticks to what Claude can't work out by reading the code: how to check its work, decisions the team made, and places where the code is misleading. Copy the shape, not the details:
63+
64+ ```markdown
65+ # Commands
66+ - Install: `pnpm install` (never npm or yarn)
67+ - Dev server: `pnpm dev` (http://localhost:3000)
68+ - Run one test file: `pnpm vitest run path/to/file.test.ts`
69+ - Before a PR: `pnpm lint && pnpm tsc --noEmit && pnpm test`
70+
71+ # Conventions
72+ - Database access only through `src/lib/db.ts`, never a new Prisma client
73+ - Money is stored in cents as integers. Never use floats for amounts.
74+ - Throw errors with the helpers in `src/lib/errors.ts`, never raw strings
75+ - Ask before adding a dependency
76+
77+ # Gotchas
78+ - `src/legacy/` is still live, but don't copy its patterns into new code
79+ - Integration tests need `DATABASE_URL` set; see `.env.example`
80+ - `src/components/ui/` is generated by shadcn/ui; don't edit it by hand
81+ ```
82+
83+ Every line is something Claude can act on or check, and none of it is visible from the file tree alone.
84+
85+ ## What to leave out
86+
87+ - **Your folder layout and architecture.** Anthropic's [best practices](https://code.claude.com/docs/en/best-practices) now say Claude reads the repo itself, so only write down what isn't in there.
88+ - **IMPORTANT and ALL CAPS.** Current models follow a plainly worded line. If a line keeps getting missed, the file is probably too long, or the rule needs a hook.
89+ - **Things Claude would do anyway**, like "write clean code".
90+ - **Your personal preferences.** Put those in `CLAUDE.local.md` or `~/.claude/CLAUDE.md`, not in the shared file.
91+
92+ ## Pull in other files with @imports
93+
94+ A `CLAUDE.md` can import other files with `@path/to/file`. The imported file loads alongside it:
95+
96+ ```markdown
97+ See @README.md for an overview and @package.json for the available scripts.
98+
99+ ## Git workflow
100+ - @docs/git-instructions.md
101+ ```
102+
103+ Relative paths resolve from the file that contains the import, and imports can nest up to four levels deep. Imports help organize a long file, but they don't save context: imported files load in full.
104+
105+ <Callout type="tip">
106+ HTML comments in a CLAUDE.md, like `<!-- why this rule exists -->`, are stripped before Claude sees the file. Use them for notes to your teammates that shouldn't cost context.
107+ </Callout>
108+
109+ ## Split rules by path with .claude/rules/
110+
111+ For bigger projects, put topic files in `.claude/rules/`, such as `testing.md` or `api-design.md`. Rules without frontmatter load every session. Add a `paths` field and a rule only loads when Claude works on matching files:
112+
113+ ```markdown
114+ ---
115+ paths:
116+ - "src/api/**/*.ts"
117+ ---
118+
119+ # API rules
120+ - Validate every request body with the schemas in `src/api/schemas/`.
121+ - Return errors as `{ error: { code, message } }`.
122+ ```
123+
124+ ## Already have an AGENTS.md?
125+
126+ Recent versions of Claude Code (v2.1.277 and later) read `AGENTS.md` on their own when your project has no `CLAUDE.md`, so a repo set up for Codex or other agents works as it is. If you have both, Claude reads only `CLAUDE.md` by default. To keep one shared file for every tool, put this at the top of your `CLAUDE.md` and add Claude-specific lines below it:
127+
128+ ```markdown
129+ @AGENTS.md
130+ ```
131+
132+ [How to set up AGENTS.md for Codex](/chatgpt/agents-md-codex) covers the AGENTS.md side.
133+
134+ ## Check that it loaded
135+
136+ - Run `/context` in a session and look under **Memory files**. If a file isn't listed there, Claude can't see it.
137+ - Run `/memory` to see every memory file location and open one in your editor.
138+ - A subfolder `CLAUDE.md` won't appear under Memory files until Claude opens a file in that folder.
139+
140+ ## When Claude still doesn't follow it
141+
142+ - Make the line more specific, and check for a conflicting line in another `CLAUDE.md` or rule file.
143+ - For something that must happen every time, like formatting after each edit or blocking a command, use a [hook](https://code.claude.com/docs/en/hooks-guide) instead. Hooks run as shell commands at fixed points and don't depend on Claude choosing to follow them.
144+ - If you ask Claude to "remember" something, it saves it to auto memory, its own notes. To put it in `CLAUDE.md`, say "add this to CLAUDE.md".
145+
146+ Keep the file alive: when Claude gets something wrong that a line would have prevented, add the line.

content/tutorials/claude/run-a-team-of-agents.mdx added

1+ ---
2+ title: "Be the operator: run a team of Claude Code agents"
3+ description: "How one person runs several Claude Code agents at once: the rules file, the brief, parallel sessions, review steps and guardrails, steering it all from your phone, and how we made this tutorial's video the same way."
4+ level: Advanced
5+ minutes: 15
6+ publishedAt: 2026-11-04
7+ updatedAt: 2026-12-01
8+ video: be-the-operator
9+ videoUploadedAt: "2026-11-05T07:51:58-08:00"
10+ ---
11+
12+ AI is a force multiplier. With the right setup, one person can get through work that used to need a small team. We call that person the **operator**.
13+
14+ The operator doesn't type most of the code. The operator splits the work into tasks, gives each task to its own Claude Code agent, and reviews what comes back. It uses a lot of tokens. In the hands of a skilled operator, it's worth it.
15+
16+ This guide is the setup we use: a rules file every agent reads, a brief for each task, several sessions running side by side, and review steps before anything is merged. At the end, we show how we made this tutorial's video the same way, mostly from a phone.
17+
18+ ## What you need
19+
20+ - Claude Code, signed in with a Pro, Max, Team or Enterprise plan
21+ - A project in git with at least one commit, because parallel sessions use git worktrees
22+ - A test, build or lint command Claude can run to check its own work
23+ - About 30 minutes to set it up the first time
24+
25+ Each agent uses its own tokens, so five agents use up your plan's limits roughly five times as fast as one. Start with two or three.
26+
27+ ## From chatbot to agent
28+
29+ A chatbot answers questions. An agent takes a task and works on it until it's done. That difference is what makes the operator possible.
30+
31+ | | Chatbot | Agent |
32+ | --- | --- | --- |
33+ | What you give it | A question | A task, with a goal and a finish line |
34+ | What it does | Answers in text | Reads files, edits code and runs commands |
35+ | How you check it | Read the answer | Read the changes and the test output |
36+ | How many at once | One conversation | Several sessions in parallel |
37+
38+ ## What a talented operator can do
39+
40+ None of these jobs is new. The multiplier is running several of them at the same time while you review.
41+
42+ - **Fix several bugs at once.** One agent per bug, each on its own branch, so the fixes never collide.
43+ - **Build and test in parallel.** One agent builds a small feature from a written spec while another writes its tests.
44+ - **Keep the docs current.** An agent updates the README and the changelog after every change.
45+ - **Turn data into a report.** Give an agent a spreadsheet or a log file and ask for a short summary with charts.
46+ - **Research before building.** An agent reads a library's docs and comes back with a plan before anyone writes code.
47+
48+ ## How the pieces fit
49+
50+ | Piece | What it is | Where it lives |
51+ | --- | --- | --- |
52+ | Rules | Standing instructions every agent reads | `CLAUDE.md` |
53+ | Brief | One task, written like a ticket | Your prompt |
54+ | Agents | One Claude Code session per task | A git worktree each |
55+ | Helpers | Focused assistants for side jobs, like review | `.claude/agents/` |
56+ | Guardrails | Rules Claude Code enforces, not just reads | Hooks in `.claude/settings.json` |
57+ | You | Approve plans, review results and merge | Terminal, desktop app or phone |
58+
59+ ## Step 1: Write the rules once
60+
61+ Every agent reads `CLAUDE.md` at the start of every session, so it's where you write down what you'd otherwise repeat to each one. For a team of agents, the most useful rules say how to check the work, how to stay in its lane, and how to report back:
62+
63+ ```markdown
64+ # How to check your work
65+ - Run `npm test` and `npm run lint` before you say a task is done
66+ - In your summary, paste the command you ran and the last lines of its output
67+
68+ # How we work
69+ - One task per session. If you find a second problem, tell me instead of fixing it
70+ - Stay on your own branch. Never push to main
71+ - Ask before you add a dependency or change the database schema
72+
73+ # When you finish
74+ - Summarize what changed in 3 to 5 bullets
75+ - List anything you skipped or couldn't check
76+ ```
77+
78+ Swap in your own commands. Our [CLAUDE.md guide](/claude/claude-md-guide) covers where the file goes and how to check that Claude loaded it.
79+
80+ ## Step 2: Write the brief like a ticket
81+
82+ A vague task gets a vague result. Give each agent a brief with a clear finish line:
83+
84+ ```prompt
85+ Task: [one sentence]
86+ Why: [the problem this solves]
87+ Done means: [the test or check that proves it works]
88+ Stay inside: [the files or folders it may change]
89+ Don't: [what to leave alone]
90+ Before you change anything, show me a short plan and wait for my OK.
91+ ```
92+
93+ Here's one filled in:
94+
95+ ```prompt
96+ Task: Fix the order dates that show one day early for customers in Asia.
97+ Why: Dates are converted to UTC twice before they're displayed.
98+ Done means: A new test for a Tokyo customer passes, and npm test passes.
99+ Stay inside: src/lib/dates.ts and its tests.
100+ Don't: Change the database or any API responses.
101+ Before you change anything, show me a short plan and wait for my OK.
102+ ```
103+
104+ | Vague | Clear |
105+ | --- | --- |
106+ | Fix the dates | Fix the order dates that show one day early in Asia |
107+ | Make sure it works | A new test for a Tokyo customer passes |
108+ | Clean up the code | Stay inside `src/lib/dates.ts` and its tests |
109+
110+ The last line of the brief puts a review step before any edit. You can also start the session in plan mode, covered in Step 5.
111+
112+ ## Step 3: Run agents side by side
113+
114+ Two agents editing the same folder will overwrite each other's work. Claude Code solves this with git worktrees: each session gets its own copy of the project on its own branch. Open a terminal for each task:
115+
116+ ```bash
117+ claude --worktree fix-date-bug
118+ claude --worktree add-checkout-tests
119+ claude --worktree update-docs
120+ ```
121+
122+ `-w` is the short form. Each worktree lives in `.claude/worktrees/<name>/` on a branch called `worktree-<name>`. Add `.claude/worktrees/` to your `.gitignore`. When you exit a session with no changes left, Claude Code removes its worktree and branch, and if there are changes, it asks whether to keep them. Paste a brief into each session and let them work.
123+
124+ If you'd rather not keep a terminal open for every agent, start them in the background and check on them from one place:
125+
126+ ```bash
127+ claude --bg "Fix the order dates that show one day early in Asia. Done means npm test passes."
128+ claude agents
129+ ```
130+
131+ `claude agents` opens agent view, where you can see every background session, open one, and read its progress. Background agents are a research preview, so details may change.
132+
133+ <Callout type="note">
134+ Claude Code also has agent teams, where one session leads and other sessions work as teammates that message each other. It's experimental, off by default, and uses many more tokens. Start with worktrees, and see Anthropic's [agent teams page](https://code.claude.com/docs/en/agent-teams) when you outgrow them.
135+ </Callout>
136+
137+ ## Step 4: Give side jobs to subagents
138+
139+ A subagent is a helper that a session calls for one focused job, with its own context window and its own tools. A reviewer is the most useful one to start with, because it checks work with fresh eyes. Save this as `.claude/agents/reviewer.md` in your project:
140+
141+ ```markdown
142+ ---
143+ name: reviewer
144+ description: Reviews a finished change for bugs, missing tests and edits outside the task. Use after a task is done and before it is merged.
145+ tools: Read, Glob, Grep, Bash
146+ model: sonnet
147+ ---
148+
149+ You review changes. Read the diff against main and run the tests, then report:
150+ 1. Bugs or risky edits, with the file and line
151+ 2. Missing tests
152+ 3. Anything that doesn't match the task
153+ Don't edit any files. Report only.
154+ ```
155+
156+ Then, in any session:
157+
158+ ```prompt
159+ Use the reviewer subagent to check this branch before I merge it.
160+ ```
161+
162+ The `model` line lets a helper run on a smaller, cheaper model than the main session. Anthropic's [subagents page](https://code.claude.com/docs/en/sub-agents) lists every field.
163+
164+ ## Step 5: Add guardrails Claude Code enforces
165+
166+ A line in `CLAUDE.md` works most of the time. For anything that must never happen, use settings that Claude Code enforces whatever the model decides.
167+
168+ ### Pick a permission mode
169+
170+ Press `Shift+Tab` in a session to switch modes, or start with `claude --permission-mode plan`.
171+
172+ | Mode | What it does | Use it for |
173+ | --- | --- | --- |
174+ | Default | Asks before edits and commands | Getting started, or any risky task |
175+ | Plan | Reads and plans, but changes nothing | Checking an agent's plan before it starts |
176+ | Accept edits | Edits files without asking, still asks for commands | Agents you trust on a small task |
177+ | Auto | A separate model checks each action and blocks risky ones | Long tasks where prompts would stall the work |
178+
179+ Auto mode needs a supported model, and Team and Enterprise admins can turn it off. Anthropic's [permission modes page](https://code.claude.com/docs/en/permission-modes) has the details.
180+
181+ ### Block what must never happen
182+
183+ Hooks are commands Claude Code runs at fixed points. A `PreToolUse` hook runs before every tool call, and if it exits with code 2, the call is blocked. This one stops force pushes and pushes to main. Add it to `.claude/settings.json`:
184+
185+ ```json
186+ {
187+ "hooks": {
188+ "PreToolUse": [
189+ {
190+ "matcher": "Bash",
191+ "hooks": [
192+ {
193+ "type": "command",
194+ "command": "\"$CLAUDE_PROJECT_DIR\"/.claude/hooks/block-risky-git.sh"
195+ }
196+ ]
197+ }
198+ ]
199+ }
200+ }
201+ ```
202+
203+ Then save this script as `.claude/hooks/block-risky-git.sh` and run `chmod +x` on it. It needs `jq`:
204+
205+ ```bash
206+ #!/usr/bin/env bash
207+ # Stops force pushes and pushes to main. Exit code 2 blocks the command,
208+ # and Claude sees the message on stderr.
209+ cmd=$(jq -r '.tool_input.command // ""')
210+ if echo "$cmd" | grep -Eq 'git push.*(--force|-f( |$))|git push.* main( |$)'; then
211+ echo "Blocked: no force pushes and no pushes to main. Open a pull request instead." >&2
212+ exit 2
213+ fi
214+ exit 0
215+ ```
216+
217+ We tested it with sample commands. It blocks `git push origin main`, `git push -f` and `git push --force-with-lease`, and allows `git push -u origin worktree-add-tests` and `git push origin main-menu-fix`. PreToolUse hooks run before the permission mode is checked, so this block holds in every mode.
218+
219+ ### Get a ping when an agent needs you
220+
221+ With several agents running, you won't be watching each one. On a Mac, this `Notification` hook shows a system notification whenever Claude Code is waiting for you. Add it inside the same `"hooks"` object:
222+
223+ ```json
224+ "Notification": [
225+ {
226+ "matcher": "",
227+ "hooks": [
228+ {
229+ "type": "command",
230+ "command": "osascript -e 'display notification \"Claude Code needs your attention\" with title \"Claude Code\"'"
231+ }
232+ ]
233+ }
234+ ]
235+ ```
236+
237+ ## Step 6: Review before you merge
238+
239+ Reviewing is the operator's real job. Before you merge anything, ask for evidence, not a promise:
240+
241+ ```prompt
242+ Show me what you changed: a short summary of the diff, the test command you ran with its output, and anything you couldn't check. Don't merge anything yet.
243+ ```
244+
245+ If it looks right, ask the agent to commit and open a pull request. If it doesn't, say what's wrong in one or two sentences. After two failed corrections, it's usually faster to run `/clear` and write a better brief than to try a third time.
246+
247+ ## Run it from your phone
248+
249+ Your agents don't need you at the desk. Remote Control connects the Claude app on your phone to a Claude Code session running on your own computer, so you can send prompts, read results and steer from anywhere.
250+
251+ Start a session with Remote Control on:
252+
253+ ```bash
254+ claude --remote-control
255+ ```
256+
257+ Or turn it on in a session that's already open with `/remote-control` (or `/rc`). Then open the Claude app on your phone and go to the **Code** tab. Run `/mobile` in Claude Code for a QR code that gets you the app.
258+
259+ - **Plans:** Remote Control works on Pro, Max, Team and Enterprise. On Team and Enterprise, an owner has to turn it on first. It doesn't work with an API key.
260+ - **Your computer stays on.** The session runs on your machine, so the computer has to stay awake with Claude Code running.
261+ - **Talk instead of typing.** Your phone's dictation works in the prompt box, so you can speak each brief.
262+
263+ <Callout type="tip">
264+ On Pro and Max, Claude Code's Projects beta takes this further: one project conversation splits work into threads that run in parallel, and you can check and steer every thread from your phone. It's rolling out gradually. See Anthropic's [Projects page](https://code.claude.com/docs/en/claude-projects).
265+ </Callout>
266+
267+ ## Watch your token use
268+
269+ Running agents in parallel spends your plan's limits faster. Check where it's going:
270+
271+ - `/usage` shows your plan's usage limits and an estimate for the current session. `/cost` and `/stats` open the same screen.
272+ - `/context` shows what's filling the current session's context window.
273+
274+ To spend less: keep one task per session, run `/clear` before starting a new task in the same session, put helpers on a smaller model, and stop background agents you no longer need.
275+
276+ ## When it goes wrong
277+
278+ | If you see | Do this |
279+ | --- | --- |
280+ | An agent drifts into other work | Press `Esc`, restate the task, and keep one task per session |
281+ | It says "done" but never ran the tests | Make "Done means" a command, and ask for its output |
282+ | Two agents change the same files | Give each one a worktree and a "Stay inside" line |
283+ | Your limits run out fast | Run fewer agents at once, and put helpers on a smaller model |
284+ | You type the same correction every day | Add it to `CLAUDE.md` |
285+ | Something must never happen | Use a hook, not a line in `CLAUDE.md` |
286+
287+ ## How we made this tutorial's video
288+
289+ We made the video for this tutorial the same way. Much of the orchestration was done by voice dictation in the Claude Code mobile app. A Mac did the work. Claude used computer use to operate its apps, Claude in Chrome for the browser, and the terminal for rendering. The computer was only the worker, and permissions were approved on the computer itself.
290+
291+ <Steps>
292+ <Step title="Script">
293+ Claude Code wrote the script from our outline, in short, plain sentences.
294+ </Step>
295+ <Step title="Narration">
296+ [ElevenLabs](https://elevenlabs.io) read the script in the voice "Eric", one section at a time and in order, with request stitching, so the voice stays the same from start to finish. The timing of every character placed each word on screen and built the captions.
297+ </Step>
298+ <Step title="Demos">
299+ Each demo is a real Claude Code session in a small sample project. A script typed the prompts and recorded the terminal, and [Playwright](https://playwright.dev) recorded the browser clips. The video replays those recordings.
300+ </Step>
301+ <Step title="Motion">
302+ [HyperFrames](https://github.com/heygen-com/hyperframes) rendered the diagrams, titles, captions and terminal playback from HTML. The moving particles behind them are a small WebGL shader, and [Three.js](https://threejs.org) draws the 3D logo at the end.
303+ </Step>
304+ <Step title="Music">
305+ The background music is a track made with [Suno](https://suno.com), looped under the voice.
306+ </Step>
307+ <Step title="Final cut">
308+ [FFmpeg](https://ffmpeg.org) mixed the voice and music. HyperFrames rendered the final video with that mix, and FFmpeg checked its loudness.
309+ </Step>
310+ <Step title="Review">
311+ We watched short samples first, then the full cut at 1080p, fixed what we found, and only then rendered the final 4K version.
312+ </Step>
313+ </Steps>
314+
315+ ### What it takes to run this
316+
317+ | What | Why it's needed | Good to know |
318+ | --- | --- | --- |
319+ | Claude Code on Pro or Max | Computer use needs one of these plans | Not available on Team or Enterprise |
320+ | Computer use | Lets Claude see the screen and use the mouse and keyboard | Research preview, macOS only. Turn it on with `/mcp`, then allow Accessibility and Screen Recording for your terminal in macOS settings |
321+ | Claude in Chrome | Lets Claude open pages, click and fill in forms | Chrome or Edge with the extension, version 1.0.36 or later. Start with `claude --chrome` |
322+ | Remote Control | Steer from your phone | The computer stays on the whole time |
323+ | An ElevenLabs account | The narration | Keep the API key in an environment variable, never in a prompt |
324+ | HyperFrames | Renders video from HTML | Needs Node.js 22 or later and FFmpeg |
325+ | Disk space | Video frames take a lot of room | We render to an external drive |
326+
327+ Only one session can use computer use at a time, and pressing `Esc` stops it. Anthropic's [computer use page](https://code.claude.com/docs/en/computer-use) covers the setup.
328+
329+ ### The code behind it
330+
331+ Narration, one section at a time and in order. Each request passes the IDs of up to three earlier requests, plus the text around it, so ElevenLabs keeps the same tone across the whole script. The response also includes the timing of every character, which is what we used for the captions:
332+
333+ ```python
334+ import base64
335+ import os
336+
337+ import requests
338+
339+ VOICE_ID = "your-voice-id" # from the voice's page in ElevenLabs
340+ MODEL_ID = "your-model-id" # use the same model for every section
341+ URL = f"https://api.elevenlabs.io/v1/text-to-speech/{VOICE_ID}/with-timestamps"
342+ HEADERS = {"xi-api-key": os.environ["ELEVENLABS_API_KEY"]}
343+
344+ sections = open("script.txt").read().split("\n\n")
345+ request_ids = []
346+ for i, text in enumerate(sections):
347+ body = {
348+ "text": text,
349+ "model_id": MODEL_ID,
350+ "previous_request_ids": request_ids[-3:],
351+ "previous_text": sections[i - 1] if i > 0 else None,
352+ "next_text": sections[i + 1] if i + 1 < len(sections) else None,
353+ }
354+ response = requests.post(URL, headers=HEADERS, json=body)
355+ response.raise_for_status()
356+ request_ids.append(response.headers["request-id"])
357+ data = response.json() # audio_base64, plus per-character timings in "alignment"
358+ with open(f"section-{i:02d}.mp3", "wb") as f:
359+ f.write(base64.b64decode(data["audio_base64"]))
360+ ```
361+
362+ Request IDs only work for about two hours, and stitching isn't available for the `eleven_v3` model. ElevenLabs' [request stitching guide](https://elevenlabs.io/docs/eleven-api/guides/how-to/text-to-speech/request-stitching) has the rest.
363+
364+ Motion graphics, from a HyperFrames project:
365+
366+ ```bash
367+ npx hyperframes init operator-video
368+ npx hyperframes preview
369+ npx hyperframes render --fps 60 --output chapter-1.mp4
370+ ```
371+
372+ The sound mix. This puts the music about 12 dB under the voice and sets the loudness YouTube expects. The HyperFrames render then uses `mix.wav` as its soundtrack:
373+
374+ ```bash
375+ ffmpeg -i narration.wav -i music.wav \
376+ -filter_complex "[1:a]volume=0.25[m];[0:a][m]amix=inputs=2:duration=first:normalize=0,loudnorm=I=-14:TP=-1.5[a]" \
377+ -map "[a]" mix.wav
378+ ```
379+
380+ ## Your first week as an operator
381+
382+ 1. **Write the brief like a ticket.** A task, a reason, and a finish line Claude can check.
383+ 2. **Give each agent one job.** One task, one session, one worktree.
384+ 3. **Make every result easy to review.** Ask for the diff, the test output and what was skipped, every time.
385+
386+ Start with two agents on small, separate tasks. Add a third once reviewing the first two feels easy.
387+
388+ ## How we checked this
389+
390+ We checked every command, flag and setting on this page against Anthropic's Claude Code documentation and the HyperFrames and ElevenLabs docs on November 4, 2026, and ran the hook script and the FFmpeg command on sample files. Background agents, computer use and Projects are previews or betas, so check the linked pages if something looks different.
391+
392+ ## Anthropic's docs
393+
394+ <Resources>
395+ <Resource kind="Docs" source="Anthropic" title="Run parallel sessions with worktrees" href="https://code.claude.com/docs/en/worktrees">
396+ How `--worktree` works, where worktrees live and how they're cleaned up.
397+ </Resource>
398+ <Resource kind="Docs" source="Anthropic" title="Subagents" href="https://code.claude.com/docs/en/sub-agents">
399+ Every field for `.claude/agents/` files, and when to use a subagent instead of a new session.
400+ </Resource>
401+ <Resource kind="Docs" source="Anthropic" title="Hooks guide" href="https://code.claude.com/docs/en/hooks-guide">
402+ Run your own commands at fixed points, including blocking a tool call before it runs.
403+ </Resource>
404+ <Resource kind="Docs" source="Anthropic" title="Remote Control" href="https://code.claude.com/docs/en/remote-control">
405+ Control a Claude Code session on your computer from the Claude app or claude.ai/code.
406+ </Resource>
407+ <Resource kind="Docs" source="Anthropic" title="Computer use" href="https://code.claude.com/docs/en/computer-use">
408+ Let Claude Code see your screen and use your Mac's apps, and the permissions it needs.
409+ </Resource>
410+ <Resource kind="Docs" source="Anthropic" title="Claude in Chrome" href="https://code.claude.com/docs/en/chrome">
411+ Let Claude Code open pages, click and fill in forms in Chrome or Edge.
412+ </Resource>
413+ </Resources>
414+
415+ ## Keep going
416+
417+ New to the rules file? Start with [How to write a CLAUDE.md that Claude Code follows](/claude/claude-md-guide). For more on agents that drive a screen, read [What computer-use agents can do, and how to run them safely](/computer-use/what-is-computer-use), then [Let Claude Code drive a browser with Playwright MCP](/computer-use/playwright-mcp-claude-code).

content/tutorials/computer-use/playwright-mcp-claude-code.mdx added

1+ ---
2+ title: "Let Claude Code drive a browser with Playwright MCP"
3+ description: "Connect Microsoft's Playwright MCP server to Claude Code with one command, then have Claude open pages, fill in forms and test your web app in a real browser."
4+ level: Beginner
5+ minutes: 10
6+ publishedAt: 2026-10-31
7+ updatedAt: 2026-12-01
8+ ---
9+
10+ [Playwright MCP](https://github.com/microsoft/playwright-mcp) is a free MCP server from Microsoft that gives an AI agent a real browser. Once it's connected, Claude Code can open pages, click, type and take screenshots, which turns it into a computer-use agent for anything on the web.
11+
12+ It doesn't work from screenshots. It hands Claude the page's accessibility tree, a text list of every button, link and field with its label, so Claude picks elements by name instead of guessing pixel positions. That makes it fast, and it works with any Claude model.
13+
14+ ## What you need
15+
16+ - [Claude Code](https://code.claude.com/docs/en/quickstart), installed and signed in
17+ - Node.js 18 or newer (check with `node --version`)
18+ - A project folder to run Claude Code in
19+
20+ ## Connect Playwright MCP
21+
22+ <Steps>
23+ <Step title="Add the server">
24+ In a terminal, inside your project folder, run the command from Playwright MCP's README:
25+
26+ ```bash
27+ claude mcp add playwright npx @playwright/mcp@latest
28+ ```
29+
30+ This adds the server in local scope: it loads only in this project and isn't shared through git. Add `--scope user` after `add` to have it in every project.
31+ </Step>
32+ <Step title="Check that it's connected">
33+ Run `claude mcp list` in the terminal, or type `/mcp` inside a Claude Code session. The `playwright` server should show as connected.
34+ </Step>
35+ <Step title="Give Claude a first task">
36+ Start Claude Code with `claude` and try:
37+
38+ ```text
39+ Use the Playwright browser to open https://example.com. Tell me the page title and list every link on the page.
40+ ```
41+
42+ A browser window opens and Claude works through it. The first time it uses each browser tool, Claude Code asks for your permission.
43+ </Step>
44+ </Steps>
45+
46+ ## What Claude can do with it
47+
48+ Playwright MCP exposes the browser as a set of tools. The ones you'll see most:
49+
50+ | Tool | What it does |
51+ | --- | --- |
52+ | `browser_navigate` | Opens a URL |
53+ | `browser_snapshot` | Reads the page's accessibility tree, the structured view Claude acts on |
54+ | `browser_click` | Clicks an element |
55+ | `browser_type` | Types into a field |
56+ | `browser_fill_form` | Fills several fields at once |
57+ | `browser_take_screenshot` | Saves a screenshot of the page |
58+ | `browser_tabs` | Lists, opens and switches tabs |
59+
60+ You don't call these yourself. Describe the task in plain words and Claude picks the tools.
61+
62+ ## Test your own web app
63+
64+ This is where it earns its keep. Start your app's dev server, then ask Claude to use it like a new visitor would:
65+
66+ ```text
67+ My app is running at http://localhost:3000. Use the Playwright browser to sign up with
68+ test+1@example.com, create a first project, and log out. Take a screenshot after each step,
69+ and tell me anything that looks broken, slow or confusing.
70+ ```
71+
72+ Because Claude Code can also read and edit your code, it can follow up on what it finds: trace a broken button to the component, fix it, and run the same check in the browser again.
73+
74+ ## Change how the browser runs
75+
76+ Options go after the package name. Put `--` before the server command so Claude Code passes the flags to Playwright MCP instead of reading them itself. To change an existing server, remove it and add it again:
77+
78+ ```bash
79+ claude mcp remove playwright
80+ claude mcp add playwright -- npx @playwright/mcp@latest --isolated --headless
81+ ```
82+
83+ Useful options from the README:
84+
85+ | Option | Effect |
86+ | --- | --- |
87+ | `--isolated` | Keeps the browser profile in memory, so every session starts clean |
88+ | `--headless` | Runs without a visible window (the default is a visible browser) |
89+ | `--browser <name>` | Picks the browser: `chrome`, `firefox`, `webkit` or `msedge` |
90+ | `--device "iPhone 15"` | Emulates a phone, to check your mobile layout |
91+ | `--viewport-size 1280x720` | Sets the window size |
92+ | `--caps vision` | Adds tools that work from screenshots and coordinates |
93+
94+ By default, Playwright MCP keeps a persistent browser profile for each project, so anything you sign in to stays signed in next time. On macOS it lives under `~/Library/Caches/ms-playwright/`. Use `--isolated` if you'd rather start fresh every time.
95+
96+ ## Skip the prompts for safe tools
97+
98+ Claude Code asks before each new browser tool. Once you're comfortable, allow the read-only ones in your project's `.claude/settings.json` and keep clicks and typing on ask:
99+
100+ ```json
101+ {
102+ "permissions": {
103+ "allow": [
104+ "mcp__playwright__browser_navigate",
105+ "mcp__playwright__browser_snapshot",
106+ "mcp__playwright__browser_take_screenshot"
107+ ]
108+ }
109+ }
110+ ```
111+
112+ `mcp__playwright__*` would allow every tool from the server at once. Only use that on a browser profile with nothing in it you care about.
113+
114+ ## Stay safe
115+
116+ <Callout type="warning">
117+ Playwright MCP's own README says it is not a security boundary. The browser can do anything a person at the keyboard could, on any site you send it to.
118+ </Callout>
119+
120+ - Use `--isolated` or a profile that isn't signed in to your email, bank or password manager.
121+ - Keep Claude asking before it clicks or types on sites where an action is hard to undo.
122+ - Pages can contain text written to steer AI agents. Send it only to sites you trust, and read what it plans to do before approving.
123+
124+ [What computer-use agents can do, and how to run them safely](/computer-use/what-is-computer-use) covers these guardrails in more depth.
125+
126+ ## A lighter option for coding work
127+
128+ Microsoft also makes [Playwright CLI](https://github.com/microsoft/playwright-cli), a command-line version meant for coding agents. Its README says CLI commands use fewer tokens than MCP, because the agent doesn't load every tool and the full page tree into its context. If you mostly use the browser to check your own app while coding, try both and keep the one that suits your sessions.
129+

content/tutorials/computer-use/what-is-computer-use.mdx added

1+ ---
2+ title: "What computer-use agents can do, and how to run them safely"
3+ description: "How AI agents see the screen, click and type, which jobs they're good at today, and the guardrails to put in place first."
4+ level: Beginner
5+ minutes: 8
6+ publishedAt: 2026-10-31
7+ ---
8+
9+ A computer-use agent is an AI model that operates a computer the way you do. It looks at the screen, decides where to click or what to type, and repeats until the task is done. Because it works through the same interface you use, it can handle apps and websites that have no API at all.
10+
11+ ## How it works
12+
13+ Each step is a loop:
14+
15+ 1. The agent looks at the current state of the screen or the web page.
16+ 2. The model decides on the next action, such as clicking a button, typing into a field or scrolling.
17+ 3. The action runs, and the agent looks again to see what changed.
18+
19+ The loop keeps going until the agent decides the task is finished, gets stuck, or reaches a point where it should ask you.
20+
21+ ## Two ways an agent can see
22+
23+ Agents read the screen in one of two ways, and the difference shows up in speed and reliability.
24+
25+ - **Screenshots.** The model gets a picture of the screen and works out where to click from pixels. This works with any app, including desktop software, but it needs a model that's good at reading images, and a busy screen can trip it up.
26+ - **The page's structure.** For web pages, a tool like [Playwright MCP](https://github.com/microsoft/playwright-mcp) gives the model the page's accessibility tree: a text list of the buttons, links and fields on the page, each with a label. The model picks an element by its reference instead of guessing coordinates, which is faster and more predictable. It only works inside a browser.
27+
28+ For anything in a browser, start with the structured approach. Use screenshot-based agents for desktop apps or pages where the structure is missing or misleading.
29+
30+ ## What it's good at today
31+
32+ - Filling in forms with data from a spreadsheet or document
33+ - Clicking through admin dashboards to collect or change settings
34+ - Testing your own web app the way a user would
35+ - Repetitive research, like checking the same detail across many sites
36+
37+ It's slower than an API and can misread a page, so it fits jobs where a person would otherwise do the clicking. If a task has an API or a command-line tool, use that instead.
38+
39+ ## Guardrails before you start
40+
41+ <Callout type="warning">
42+ An agent can click anything you can. Treat it like a new assistant on their first day, not like a script.
43+ </Callout>
44+
45+ <Steps>
46+ <Step title="Use a separate browser profile or a VM">
47+ Keep it away from your personal email, banking and password manager. A fresh profile or a virtual machine limits what a mistake can reach.
48+ </Step>
49+ <Step title="Stay in the loop on anything irreversible">
50+ Have it stop and ask before purchases, deletions or sending messages. Most agent tools let you approve actions one at a time; keep that on until you trust the task.
51+ </Step>
52+ <Step title="Watch for instructions on the page">
53+ Web pages can contain text aimed at the agent, a trick called prompt injection. Tell it to follow only your instructions, never the page's, and keep it off sites you don't trust.
54+ </Step>
55+ <Step title="Start small and watch the first runs">
56+ Give it one short, well-defined task and watch it work. Widen the scope only once it gets that right every time.
57+ </Step>
58+ </Steps>
59+
60+ ## Try it
61+
62+ The quickest way to see this for yourself is to give a coding agent a browser. [Let Claude Code drive a browser with Playwright MCP](/computer-use/playwright-mcp-claude-code) walks through the setup in about ten minutes.

d1/auth.test.mjs added

1+ import assert from "node:assert/strict";
2+ import { randomBytes } from "node:crypto";
3+ import { readFile } from "node:fs/promises";
4+ import test from "node:test";
5+ import { exportJWK, generateKeyPair, SignJWT } from "jose";
6+ import { convertV4MiniflareOptions, Miniflare } from "miniflare";
7+ import { createResourceAuth } from "../src/lib/d1-auth.ts";
8+ import { browserSignIn } from "../src/lib/provider-sign-in.ts";
9+
10+ const origin = "https://airesource.example";
11+ const providers = {
12+ google: { subject: "google-fixture", email: "google@example.invalid", clientId: "fixture.apps.googleusercontent.com",
13+ issuer: "https://accounts.google.com", keys: "https://www.googleapis.com/oauth2/v3/certs" },
14+ apple: { subject: "apple-fixture", email: "apple@example.invalid", clientId: "pro.airesource.example",
15+ issuer: "https://appleid.apple.com", keys: "https://appleid.apple.com/auth/keys" },
16+ };
17+
18+ function cookie(response) {
19+ return response.headers.getSetCookie().map((entry) => entry.split(";", 1)[0]).join("; ");
20+ }
21+
22+ test("signed provider tokens preserve migrated account ownership and the login challenge can only be used once", async (t) => {
23+ const runtime = new Miniflare(convertV4MiniflareOptions({
24+ modules: true,
25+ script: "export default { fetch() { return new Response(); } }",
26+ compatibilityDate: "2026-11-24",
27+ d1Databases: ["ACCOUNTS_DB"],
28+ }));
29+
30+ try {
31+ const db = await runtime.getD1Database("ACCOUNTS_DB");
32+ for (const file of ["0001_accounts.sql", "0002_better_auth.sql", "0003_sign_in_challenge.sql"]) {
33+ const schema = await readFile(new URL(`./migrations/${file}`, import.meta.url), "utf8");
34+ await db.batch(schema.split(";").map((sql) => sql.trim()).filter(Boolean).map((sql) => db.prepare(sql)));
35+ }
36+ const signingKey = await generateKeyPair("RS256");
37+ const jwk = { ...await exportJWK(signingKey.publicKey), alg: "RS256", kid: "provider-fixture" };
38+ const ids = { google: providers.google.clientId, apple: providers.apple.clientId };
39+ const auth = createResourceAuth(db, origin, randomBytes(48).toString("base64url"), ids);
40+ t.mock.method(globalThis, "fetch", async (input) => {
41+ const url = input instanceof Request ? input.url : String(input);
42+ assert.ok(Object.values(providers).some(({ keys }) => keys === url), `Unexpected OAuth fetch to ${url}`);
43+ return Response.json({ keys: [jwk] });
44+ });
45+
46+ function post(path = "", { source = origin, cookies = "", payload } = {}) {
47+ return browserSignIn(new Request(origin + "/api/auth/identity" + path, {
48+ method: "POST",
49+ headers: { Origin: source, "Content-Type": "application/json", Cookie: cookies, "cf-connecting-ip": "192.0.2.1" },
50+ body: payload ? JSON.stringify(payload) : undefined,
51+ }), { db, origin, providers: ids, auth });
52+ }
53+
54+ async function signedToken(provider, nonce, audience = providers[provider].clientId) {
55+ const settings = providers[provider];
56+ // Returning Apple customers may have no email in the provider token.
57+ const claims = provider === "google" ? { email: settings.email, email_verified: true, name: "Fixture" } : {};
58+ return new SignJWT({ ...claims, nonce }).setProtectedHeader({ alg: "RS256", kid: jwk.kid })
59+ .setIssuer(settings.issuer).setAudience(audience).setSubject(settings.subject)
60+ .setIssuedAt().setExpirationTime("5m").sign(signingKey.privateKey);
61+ }
62+
63+ assert.equal((await post("/challenge", { source: "https://wrong.example" })).status, 403);
64+
65+ for (const [provider, settings] of Object.entries(providers)) {
66+ const importedId = `original-${provider}-uuid`;
67+ const now = new Date().toISOString();
68+ await db.prepare('INSERT INTO "user" (id,name,email,"emailVerified","createdAt","updatedAt",provider) VALUES (?, ?, ?, 1, ?, ?, ?)')
69+ .bind(importedId, "Imported account", settings.email, now, now, provider).run();
70+ await db.prepare('INSERT INTO "account" (id,"accountId","providerId","userId","createdAt","updatedAt") VALUES (?, ?, ?, ?, ?, ?)')
71+ .bind(`original-link-${provider}`, settings.subject, provider, importedId, now, now).run();
72+ await db.prepare("INSERT INTO users (id, email, created_at, updated_at) VALUES (?, ?, ?, ?)")
73+ .bind(importedId, settings.email, now, now).run();
74+ await db.prepare("INSERT INTO saved_tutorials (user_id,tutorial_slug,created_at) VALUES (?, ?, ?)")
75+ .bind(importedId, "claude/example", now).run();
76+
77+ const launch = await post("/challenge");
78+ assert.equal(launch.status, 200);
79+ const challenge = await launch.json();
80+ assert.equal(challenge.providers[provider], settings.clientId);
81+ assert.match(launch.headers.get("set-cookie"), /Secure; HttpOnly; SameSite=Strict/);
82+ const proof = { provider, token: await signedToken(provider, challenge.nonce) };
83+ assert.equal((await post("", { payload: proof })).status, 401);
84+ const results = await Promise.all([1, 2].map(() => post("", { cookies: cookie(launch), payload: proof })));
85+ const sessionResponse = results.find((response) => response.ok);
86+ assert.ok(sessionResponse);
87+ assert.deepEqual(results.map((response) => response.status).sort(), [200, 401]);
88+ assert.deepEqual(await sessionResponse.json(), { signedIn: true });
89+ const sessionCookie = cookie(sessionResponse);
90+ assert.match(sessionCookie, /__Secure-airesourcepro\.session_token=/);
91+ const session = await auth.api.getSession({ headers: new Headers({ Cookie: sessionCookie }) });
92+ assert.equal(session?.user.id, importedId);
93+ assert.equal(session?.user.email, settings.email);
94+ assert.equal(session?.user.provider, provider);
95+ assert.equal(await db.prepare("SELECT tutorial_slug FROM saved_tutorials WHERE user_id = ?")
96+ .bind(session.user.id).first("tutorial_slug"), "claude/example");
97+ const signOut = await auth.api.signOut({ headers: new Headers({ Cookie: sessionCookie, Origin: origin }), asResponse: true });
98+ assert.ok(signOut.ok);
99+ assert.equal(await auth.api.getSession({ headers: new Headers({ Cookie: sessionCookie }) }), null);
100+ }
101+
102+ for (const scenario of ["wrong-audience", "wrong-nonce", "expired-challenge"]) {
103+ const launch = await post("/challenge");
104+ const { nonce } = await launch.json();
105+ if (scenario === "expired-challenge") await db.prepare("UPDATE sign_in_challenge SET expires_at = 0").run();
106+ const token = await signedToken("google", scenario === "wrong-nonce" ? "wrong" : nonce,
107+ scenario === "wrong-audience" ? "other-client.apps.googleusercontent.com" : undefined);
108+ assert.equal((await post("", { cookies: cookie(launch), payload: { provider: "google", token } })).status, 401);
109+ }
110+ assert.equal(await db.prepare('SELECT count(*) AS total FROM "user"').first("total"), 2);
111+ } finally {
112+ await runtime.dispose();
113+ }
114+ });

d1/migrations/0001_accounts.sql added

1+ CREATE TABLE users (
2+ id TEXT PRIMARY KEY NOT NULL,
3+ email TEXT,
4+ full_name TEXT,
5+ avatar_url TEXT,
6+ is_admin INTEGER NOT NULL DEFAULT 0 CHECK (is_admin IN (0, 1)),
7+ marketing_consent INTEGER NOT NULL DEFAULT 0 CHECK (marketing_consent IN (0, 1)),
8+ marketing_consent_at TEXT,
9+ created_at TEXT NOT NULL,
10+ updated_at TEXT NOT NULL
11+ );
12+
13+ CREATE TABLE saved_tutorials (
14+ user_id TEXT NOT NULL REFERENCES users (id) ON DELETE CASCADE,
15+ tutorial_slug TEXT NOT NULL,
16+ completed_at TEXT,
17+ created_at TEXT NOT NULL,
18+ PRIMARY KEY (user_id, tutorial_slug)
19+ );
20+
21+ CREATE TABLE learning_profiles (
22+ user_id TEXT PRIMARY KEY NOT NULL REFERENCES users (id) ON DELETE CASCADE,
23+ goals TEXT NOT NULL CHECK (json_valid(goals)),
24+ tracks TEXT NOT NULL CHECK (json_valid(tracks)),
25+ level TEXT NOT NULL CHECK (level IN ('Beginner', 'Intermediate', 'Advanced')),
26+ weekly_time TEXT NOT NULL CHECK (weekly_time IN ('light', 'steady', 'deep')),
27+ format TEXT NOT NULL CHECK (format IN ('video', 'written', 'both')),
28+ created_at TEXT NOT NULL,
29+ updated_at TEXT NOT NULL
30+ );
31+
32+ CREATE TABLE tutorial_activity (
33+ user_id TEXT NOT NULL REFERENCES users (id) ON DELETE CASCADE,
34+ tutorial_slug TEXT NOT NULL,
35+ view_count INTEGER NOT NULL DEFAULT 0,
36+ first_viewed_at TEXT,
37+ last_viewed_at TEXT,
38+ completed_at TEXT,
39+ PRIMARY KEY (user_id, tutorial_slug)
40+ );

d1/migrations/0002_better_auth.sql added

1+ -- Generated from Better Auth 1.7.28 for Cloudflare D1.
2+ create table "user" ("id" text not null primary key, "name" text not null, "email" text not null unique, "emailVerified" integer not null, "image" text, "createdAt" date not null, "updatedAt" date not null);
3+
4+ create table "session" ("id" text not null primary key, "expiresAt" date not null, "token" text not null unique, "createdAt" date not null, "updatedAt" date not null, "ipAddress" text, "userAgent" text, "userId" text not null references "user" ("id") on delete cascade);
5+
6+ create table "account" ("id" text not null primary key, "accountId" text not null, "providerId" text not null, "userId" text not null references "user" ("id") on delete cascade, "accessToken" text, "refreshToken" text, "idToken" text, "accessTokenExpiresAt" date, "refreshTokenExpiresAt" date, "scope" text, "password" text, "createdAt" date not null, "updatedAt" date not null);
7+
8+ create table "verification" ("id" text not null primary key, "identifier" text not null, "value" text not null, "expiresAt" date not null, "createdAt" date not null, "updatedAt" date not null);
9+
10+ create table "rateLimit" ("id" text not null primary key, "key" text not null unique, "count" integer not null, "lastRequest" bigint not null);
11+
12+ create index "session_userId_idx" on "session" ("userId");
13+
14+ create index "account_userId_idx" on "account" ("userId");
15+
16+ create index "verification_identifier_idx" on "verification" ("identifier");
17+
18+ CREATE UNIQUE INDEX "account_provider_subject" ON "account" ("providerId", "accountId");
19+
20+ ALTER TABLE "user" ADD COLUMN "provider" TEXT CHECK ("provider" IN ('apple', 'google'));

d1/migrations/0003_sign_in_challenge.sql added

1+ CREATE TABLE sign_in_challenge (
2+ digest TEXT PRIMARY KEY,
3+ expires_at INTEGER NOT NULL
4+ );
5+ CREATE INDEX sign_in_challenge_expiry ON sign_in_challenge(expires_at);

d1/migrations/0004_ai_surveys.sql added

1+ -- Optional onboarding answers about how each person uses AI, one row per account (users.email links it to the person).
2+ CREATE TABLE ai_surveys (
3+ user_id TEXT PRIMARY KEY NOT NULL REFERENCES users (id) ON DELETE CASCADE,
4+ role TEXT,
5+ uses TEXT NOT NULL DEFAULT '[]' CHECK (json_valid(uses)),
6+ uses_other TEXT,
7+ tools TEXT NOT NULL DEFAULT '[]' CHECK (json_valid(tools)),
8+ daily_hours TEXT,
9+ ai_years TEXT,
10+ depth TEXT,
11+ coding TEXT,
12+ created_at TEXT NOT NULL,
13+ updated_at TEXT NOT NULL
14+ );

directory-site-next@0.1.0 added

No text changes.

docs/cloudflare-images-migration.md added

1+ # Cloudflare Images Migration
2+
3+ This document outlines the migration from local image storage to Cloudflare Images for the AI Resource Pro website.
4+
5+ ## Overview
6+
7+ Previously, the website stored all uploaded images in the `/public/images/` directory with categorized subdirectories. Now, all images are stored in Cloudflare Images, which provides the following benefits:
8+
9+ - Global CDN for faster image loading
10+ - Automatic image optimization and responsive sizing
11+ - Reduced storage requirements on the server
12+ - Better security and access control
13+
14+ ## Configuration
15+
16+ To use Cloudflare Images, you need to set up the following environment variables:
17+
18+ - `CLOUDFLARE_ACCOUNT_ID`: Your Cloudflare account ID
19+ - `CLOUDFLARE_IMAGE_API_KEY`: Your Cloudflare Images API key (with Images Write permission)
20+
21+ You can get these values from your Cloudflare dashboard.
22+
23+ ## Image Categories
24+
25+ The same image categories are maintained in the new system:
26+
27+ - `blog`: Images used in blog posts
28+ - `news`: Images used in news articles
29+ - `tools`: Images related to tools
30+ - `learning`: Images used in learning resources
31+ - `misc`: Miscellaneous images
32+ - `midjourney`: AI-generated images
33+
34+ Instead of storing these as directory paths, they are now stored as metadata in Cloudflare Images.
35+
36+ ## API Changes
37+
38+ The API endpoints have been updated to work with Cloudflare Images:
39+
40+ - `POST /api/upload-image`: Uploads an image to Cloudflare Images
41+ - `GET /api/upload-image?category=...`: Lists images, optionally filtered by category
42+ - `DELETE /api/upload-image?imageId=...`: Deletes an image by its ID
43+ - `PATCH /api/upload-image`: Updates an image's metadata (e.g., changes category)
44+
45+ ## Image URLs
46+
47+ Image URLs now come directly from Cloudflare's CDN instead of the local `/images/` path. They will look like:
48+
49+ ```
50+ https://imagedelivery.net/<ACCOUNT_HASH>/<IMAGE_ID>/<VARIANT>
51+ ```
52+
53+ ## Migration Process
54+
55+ To migrate existing images:
56+
57+ 1. Set up Cloudflare Images in your Cloudflare account
58+ 2. Create the necessary variants for your images
59+ 3. Upload all existing images from `/public/images/` to Cloudflare Images with their categories as metadata
60+ 4. Update the database with the new image URLs
61+
62+ ## Local Development
63+
64+ Local development works the same way - the API calls to Cloudflare Images will work as long as the environment variables are properly configured.
65+
66+ ## Troubleshooting
67+
68+ If images are not appearing:
69+
70+ 1. Check that the Cloudflare Images API credentials are correct
71+ 2. Verify that the image variants are set up properly in Cloudflare
72+ 3. Check browser console for any CORS or loading errors
73+ 4. Ensure the image IDs referenced in the application match those in Cloudflare Images

docs/rate-limiting.md added

1+ # Rate Limiting System
2+
3+ This document explains how rate limiting works in the AI Resource Pro API and how to apply it to new API routes.
4+
5+ ## Overview
6+
7+ The API uses Upstash Redis to implement rate limiting on all CREATE, UPDATE, and DELETE operations. This helps protect the API from abuse and ensures fair usage.
8+
9+ Rate limits are set as follows:
10+ - **Create operations**: 10 requests per minute
11+ - **Update operations**: 20 requests per minute
12+ - **Delete operations**: 10 requests per minute
13+ - **Authentication operations**: 5 requests per 30 seconds
14+
15+ ## Implementation Details
16+
17+ Rate limiting is implemented using the `@upstash/ratelimit` library. There are two ways to apply rate limiting to an API route:
18+
19+ ### 1. Direct Implementation
20+
21+ ```typescript
22+ import { applyRateLimit, createRateLimit } from '@/lib/rate-limit';
23+
24+ export async function POST(request: NextRequest) {
25+ // Apply rate limiting
26+ const rateLimitResult = await applyRateLimit(request, createRateLimit);
27+ if (rateLimitResult && 'status' in rateLimitResult) {
28+ return rateLimitResult;
29+ }
30+
31+ // Your handler code here
32+
33+ // Add rate limit headers to the response
34+ const headers = rateLimitResult?.headers || new Headers();
35+ return NextResponse.json(data, {
36+ status: 201,
37+ headers
38+ });
39+ }
40+ ```
41+
42+ ### 2. Using the Middleware Approach (Recommended)
43+
44+ For new API routes, we recommend using the middleware approach for cleaner code:
45+
46+ ```typescript
47+ import { withCreateRateLimit } from '@/lib/rate-limit-middleware';
48+
49+ // Define your handler without rate limiting
50+ async function createHandler(request: NextRequest) {
51+ // Your handler code here
52+ return NextResponse.json(data, { status: 201 });
53+ }
54+
55+ // Export the handler with rate limiting applied
56+ export const POST = withCreateRateLimit(createHandler);
57+ ```
58+
59+ ## Rate Limit Headers
60+
61+ When rate limiting is applied, the following headers are included in the response:
62+
63+ - `X-RateLimit-Limit`: Maximum number of requests allowed in the time window
64+ - `X-RateLimit-Remaining`: Number of requests remaining in the current time window
65+ - `X-RateLimit-Reset`: Timestamp when the rate limit will reset
66+
67+ ## Testing Rate Limits
68+
69+ You can test rate limits using the `scripts/test-rate-limit.sh` script:
70+
71+ ```bash
72+ # Run from the project root
73+ ./scripts/test-rate-limit.sh
74+ ```
75+
76+ This script will make multiple requests to the API until it hits the rate limit, then display information about the rate limiting behavior.
77+
78+ ## Identifying Users for Rate Limiting
79+
80+ By default, rate limiting is based on the client's IP address. You can customize this by providing an identifier function:
81+
82+ ```typescript
83+ // Custom identifier based on user ID or API key
84+ const customIdentifier = (req: NextRequest) => {
85+ return req.headers.get('x-api-key') || req.ip || 'anonymous';
86+ };
87+
88+ export const POST = withCreateRateLimit(createHandler, customIdentifier);
89+ ```
90+
91+ ## Troubleshooting
92+
93+ If rate limiting is not working as expected:
94+
95+ 1. Check that Redis is configured correctly in the environment variables
96+ 2. Verify that the rate limiter is being applied to the route
97+ 3. Make sure the response includes the rate limit headers
98+ 4. Check the server logs for any rate limit errors

e2e/public-pages.spec.ts added

1+ import { test, expect } from '@playwright/test';
2+
3+ const PAGES = ['/', '/tutorials', '/videos', '/about', '/login', '/claude', '/chatgpt', '/computer-use', '/ai-video'];
4+
5+ test.describe('Public pages', () => {
6+ for (const path of PAGES) {
7+ test(`${path} loads`, async ({ page }) => {
8+ const response = await page.goto(path);
9+ expect(response?.status()).toBe(200);
10+ await expect(page.locator('h1').first()).toBeVisible();
11+ });
12+ }
13+
14+ test('a tutorial page renders its article and outline', async ({ page }) => {
15+ await page.goto('/claude/claude-code-best-practices');
16+ await expect(page.locator('h1')).toContainText('Claude Code');
17+ await expect(page.locator('article h2').first()).toBeVisible();
18+ });
19+
20+ test('unknown track returns 404', async ({ page }) => {
21+ const response = await page.goto('/not-a-track');
22+ expect(response?.status()).toBe(404);
23+ });
24+ });

episodes/2026-02-18.mp3 added

Not a text file.

episodes/2026-04-06.mp3 added

Not a text file.

examples.jsonl added

1+ {"messages": [{"role": "user", "content": "Provide a short step-by-step guide on how to install software on a Windows system in a technical style."}, {"role": "assistant", "content": "1. Check Permissions: Confirm that you have the necessary system privileges before proceeding.\n2. Run Installer: Locate and open the setup file you downloaded.\n3. Follow Prompts: Select your preferred settings and click \"Next\" to continue.\n4. Complete Setup: When prompted, choose \"Finish\" and allow the program to finalize installation."}]}
2+ {"messages": [{"role": "user", "content": "Give me another concise set of instructions for running a typical Windows installer."}, {"role": "assistant", "content": "To get started with the installation, begin by making sure you’re logged in as an administrator. Double-click the installer icon, then carefully review the license agreement. Choose your installation path, opt for either default or custom features, and press 'Install.' Once the progress bar completes, finalize by selecting 'Close.'"}]}
3+ {"messages": [{"role": "user", "content": "How can I install new software step by step on Windows, ensuring I have admin rights?"}, {"role": "assistant", "content": "1. Obtain Admin Rights: Ensure your current user account has administrative privileges.\n2. Execute Installer: Double-click the software package (.exe for Windows) to begin.\n3. Adjust Settings: If prompted, pick the default or custom setup options that best suit your needs.\n4. Finalize Installation: Click \"Install,\" wait for the process to conclude, and press \"Finish\" to exit."}]}
4+ {"messages": [{"role": "user", "content": "Walk me through a typical Windows install process, mentioning system prerequisites."}, {"role": "assistant", "content": "- Prerequisite: Verify you’re operating on an account with installation rights.\n- Installation Wizard: Launch the downloaded setup file to open the wizard.\n- Configuration: Accept the user agreement and choose your desired configuration—basic or advanced.\n- Completion: After the wizard finishes copying files, click \"Done\" to finalize."}]}
5+ {"messages": [{"role": "user", "content": "What are the key steps I should follow when installing a program on a Windows PC?"}, {"role": "assistant", "content": "1. Preparation: Log in using an administrator account to avoid permission issues.\n2. Installation Execution: Find the downloaded file and open it.\n3. Customization: Navigate through each setup screen, adjusting features as needed.\n4. Confirmation: Conclude the setup by selecting \"Finish,\" allowing the installer to finalize all components."}]}
6+ {"messages": [{"role": "user", "content": "Please outline a straightforward method for installing a Windows application from an .exe file."}, {"role": "assistant", "content": "Start by confirming that you have the correct permission level on your device. Next, open the installation package by double-clicking its icon. Follow each screen’s instructions to configure any optional settings—such as installation location—before pressing \"Install.\" When prompted, click \"Finish\" to complete the setup and exit."}]}
7+ {"messages": [{"role": "user", "content": "Give me a short tutorial on installing new software in Windows, ensuring I accept the license agreement."}, {"role": "assistant", "content": "1. Launch: Double-click the installation file you previously downloaded from the official source.\n2. Accept Terms: Carefully read and agree to the License Agreement.\n3. Specify Options: Choose whether you want a typical or custom setup path.\n4. Install: Press \"Install,\" wait until the setup progress bar reaches 100%, and select \"Finish\" when done."}]}
8+ {"messages": [{"role": "user", "content": "Could you provide step-by-step guidance for installing a program on Windows, including any terms acceptance?"}, {"role": "assistant", "content": "Before running the software installer, confirm that your user account can make system changes. Once verified, double-click on the package to initiate setup. The wizard will prompt you to accept terms, select an installation folder, and decide on optional features. Press \"Install\" to begin copying files, and after confirmation, click \"Close\" to exit."}]}
9+ {"messages": [{"role": "user", "content": "How do I run a Windows installer, ensuring I handle permissions, licensing, and the final step properly?"}, {"role": "assistant", "content": "1. Admin Check: Ensure you have administrator rights by checking your account settings.\n2. Initiate Setup: Open the executable file to start the installation wizard.\n3. Review & Select: Accept the licensing conditions and choose any advanced configuration you prefer.\n4. Install & Confirm: Click \"Install,\" watch for completion, then click \"Done\" to finalize."}]}
10+ {"messages": [{"role": "user", "content": "Outline a concise, technical procedure for installing software on Windows from a downloaded file."}, {"role": "assistant", "content": "After confirming administrator privileges, locate your downloaded installation package. Double-click the file, then select your language preference if prompted. The setup wizard will guide you through customization options—choose standard or advanced settings. When the progress bar completes, finalize by pressing \"Finish\" to exit the installer."}]}
11+ {"messages": [{"role": "user", "content": "Explain how to install and verify a package using apt on a Debian or Ubuntu system."}, {"role": "assistant", "content": "1. Update the Package List:\n```bash\nsudo apt update\n```\n2. Install the Desired Package (e.g., curl):\n```bash\nsudo apt install curl\n```\n3. Verify the Installation:\n```bash\ncurl --version\n```\n\nExplanation: Updating ensures you have the latest package information, installing fetches and configures the package, and verifying checks that curl is correctly installed."}]}
12+ {"messages": [{"role": "user", "content": "Show me how to create and navigate directories in Linux with some sample commands."}, {"role": "assistant", "content": "1. Create a New Directory:\n```bash\nmkdir my_project\n```\n2. Move into That Directory:\n```bash\ncd my_project\n```\n3. View Contents:\n```bash\nls\n```\n\nExplanation: `mkdir` makes a new folder, `cd` changes the working directory, and `ls` lists files/subdirectories."}]}
13+ {"messages": [{"role": "user", "content": "How can I check disk usage in Linux for a directory and overall disk space availability?"}, {"role": "assistant", "content": "1. Check the Size of a Specific Directory:\n```bash\ndu -sh /path/to/directory\n```\n2. View Free Disk Space:\n```bash\ndf -h\n```\n\nExplanation: `du -sh` provides a summary in human-readable form, while `df -h` displays overall disk usage and free space across file systems."}]}
14+ {"messages": [{"role": "user", "content": "Provide a short sample Bash script for printing 'Hello, World!' and explain how to run it."}, {"role": "assistant", "content": "1. Create a Script (e.g., `hello.sh`):\n```bash\nnano hello.sh\n```\n2. Add the Following Code:\n```bash\n#!/usr/bin/env bash\necho \"Hello, World!\"\n```\n3. Make the Script Executable:\n```bash\nchmod +x hello.sh\n```\n4. Run the Script:\n```bash\n./hello.sh\n```\n\nExplanation: You write the script using an editor, give it execute permissions, then run it directly with `./hello.sh`."}]}
15+ {"messages": [{"role": "user", "content": "Demonstrate how to use grep to find a keyword in a file or recursively in Linux."}, {"role": "assistant", "content": "1. Search for a Keyword:\n```bash\ngrep \"keyword\" filename.txt\n```\n2. Search Recursively:\n```bash\ngrep -r \"keyword\" /path/to/search\n```\n\nExplanation: `grep` searches for a specified pattern in files. The `-r` option lets it recursively search through directories."}]}
16+ {"messages": [{"role": "user", "content": "Show me how to modify file permissions in Linux with chmod, both granting and revoking permissions."}, {"role": "assistant", "content": "1. Give the Owner Execute Permissions:\n```bash\nchmod u+x script.sh\n```\n2. Revoke All Permissions for Group:\n```bash\nchmod g-rwx script.sh\n```\n\nExplanation: `chmod` adjusts file permissions. `u+x` adds execute rights for the owner, while `g-rwx` removes read, write, and execute rights from the group."}]}
17+ {"messages": [{"role": "user", "content": "How do I create and use a Python virtual environment in Linux (Debian/Ubuntu)?"}, {"role": "assistant", "content": "1. Install `python3-venv` (if needed):\n```bash\nsudo apt install python3-venv\n```\n2. Create a Virtual Environment:\n```bash\npython3 -m venv myenv\n```\n3. Activate the Environment:\n```bash\nsource myenv/bin/activate\n```\n4. Deactivate:\n```bash\ndeactivate\n```\n\nExplanation: A virtual environment isolates your project dependencies from the system-wide packages."}]}
18+ {"messages": [{"role": "user", "content": "Walk me through the basic Git workflow to track and commit a file for the first time."}, {"role": "assistant", "content": "1. Initialize a Repository:\n```bash\ngit init\n```\n2. Add a File:\n```bash\ngit add filename.txt\n```\n3. Commit Changes:\n```bash\ngit commit -m \"Initial commit\"\n```\n4. Check the Status:\n```bash\ngit status\n```\n\nExplanation: `git init` creates a new repository, `git add` stages your changes, and `git commit` saves them to your repository history."}]}
19+ {"messages": [{"role": "user", "content": "Give me an example of creating a custom systemd service in Linux, from file creation to enabling it."}, {"role": "assistant", "content": "1. Create the Service File:\n```bash\nsudo nano /etc/systemd/system/myapp.service\n```\n2. Add the Following Configuration:\n```ini\n[Unit]\nDescription=My App Service\n\n[Service]\nExecStart=/usr/bin/python3 /home/user/myapp/app.py\nRestart=always\n\n[Install]\nWantedBy=multi-user.target\n```\n3. Reload the Systemd Daemon:\n```bash\nsudo systemctl daemon-reload\n```\n4. Enable and Start the Service:\n```bash\nsudo systemctl enable myapp\nsudo systemctl start myapp\n```\n5. Check Service Status:\n```bash\nsystemctl status myapp\n```\n\nExplanation: Systemd manages services on Linux. You define the service in a file, then reload the daemon, enable, and start the service using `systemctl`."}]}
20+ {"messages": [{"role": "user", "content": "Finally, show me a basic 'Hello World' example in Python, including how to run it from the terminal."}, {"role": "assistant", "content": "1. Create a File (hello.py):\n```bash\nnano hello.py\n```\n2. Insert Code:\n```python\nprint(\"Hello, World!\")\n```\n3. Run the Script:\n```bash\npython3 hello.py\n```\n\nExplanation: This simple Python script prints a greeting. Save it as a `.py` file and run it using the `python3` command from the terminal."}]}

fav.png added

Not a text file.

fix-dashboard-code.md added

1+ # Updating Dashboard Code to Use instance_count
2+
3+ Since the database column has been renamed from `tool_count` to `instance_count`, you need to update your dashboard code to use the new column name. Here are the specific changes needed:
4+
5+ ## 1. Update the Dashboard Query in `src/app/admin/dashboard/page.tsx`
6+
7+ Around line 295, change this:
8+
9+ ```typescript
10+ // Get category counts from the categories table (tools)
11+ const { data: categoryData, error: categoryError } = await supabase
12+ .from('categories')
13+ .select('id, name, tool_count') // OLD: using tool_count
14+ .order('name');
15+
16+ if (!categoryError && categoryData) {
17+ // Initialize count for each category
18+ categoryData.forEach(cat => {
19+ categoryCounts[cat.name] = cat.tool_count || 0; // OLD: using tool_count
20+ });
21+
22+ // Count blog posts with each category
23+ for (const cat of categoryData) {
24+ // ...more code that adds additional counts
25+ }
26+ }
27+ ```
28+
29+ To this:
30+
31+ ```typescript
32+ // Get category counts from the categories table
33+ const { data: categoryData, error: categoryError } = await supabase
34+ .from('categories')
35+ .select('id, name, instance_count') // NEW: using instance_count
36+ .order('name');
37+
38+ if (!categoryError && categoryData) {
39+ // Initialize count for each category
40+ categoryData.forEach(cat => {
41+ categoryCounts[cat.name] = cat.instance_count || 0; // NEW: using instance_count
42+ });
43+
44+ // REMOVE all these additional counting lines to avoid double counting
45+ // If the code below was originally intended to supplement the count,
46+ // you should ensure the SQL update script counts all instances properly instead
47+ /*
48+ // Count blog posts with each category
49+ for (const cat of categoryData) {
50+ // Remove this entire for loop
51+ }
52+ */
53+ }
54+ ```
55+
56+ ## 2. Update Any Other References to tool_count
57+
58+ Search for any other instances of `tool_count` in your code and replace them with `instance_count`. Common places to check:
59+
60+ - `src/components/admin/ClientCategoryManager.tsx`
61+ - API routes that add or remove tools/news items
62+
63+ ## 3. Fix the News Query Issue
64+
65+ If you still need to count news items in your dashboard page (though this is not recommended if the database already has the correct counts), use the correct column name:
66+
67+ ```typescript
68+ // Count news items with this category
69+ const { count: newsCount, error: newsCountError } = await supabase
70+ .from('news')
71+ .select('*', { count: 'exact', head: true })
72+ .eq('category_id', cat.id); // NEW: using category_id instead of category
73+ ```
74+
75+ ## Testing
76+
77+ After making these changes:
78+
79+ 1. Run the database script (`fix-instance-count.sql`) to ensure the database counts are correct
80+ 2. Update the code as described above
81+ 3. Restart your development server
82+ 4. Visit the admin dashboard to confirm the counts appear correctly
83+ 5. Add a new tool or news item and verify the count increments properly
84+ 6. Remove a tool or news item and verify the count decrements properly
85+
86+ Make sure your API routes that add/remove items also update the `instance_count` column in the categories table.

fix-dashboard-page.md added

1+ # How to Fix the Dashboard Page Count Issues
2+
3+ After analyzing the dashboard code and database schema, here are the detailed steps to fix the instance count issues:
4+
5+ ## 1. Fix the Dashboard Code
6+
7+ Open the file `src/app/admin/dashboard/page.tsx` and locate the category count code section (around line 290). You need to make the following changes:
8+
9+ ### Option A: If you've renamed the column to instance_count
10+
11+ ```typescript
12+ // Get category counts from the categories table
13+ const { data: categoryData, error: categoryError } = await supabase
14+ .from('categories')
15+ .select('id, name, instance_count') // Changed from tool_count to instance_count
16+ .order('name');
17+
18+ if (!categoryError && categoryData) {
19+ // Initialize count for each category using instance_count
20+ categoryData.forEach(cat => {
21+ categoryCounts[cat.name] = cat.instance_count || 0;
22+ });
23+
24+ // REMOVE the additional counting code to avoid double counting
25+ // The following code should be REMOVED:
26+ // for (const cat of categoryData) {
27+ // // Count blog posts with this category
28+ // const { count: blogCount, error: blogCountError } = await supabase
29+ // .from('blog_posts')
30+ // .select('*', { count: 'exact', head: true })
31+ // .eq('category_id', cat.id);
32+ //
33+ // if (!blogCountError) {
34+ // categoryCounts[cat.name] += blogCount || 0;
35+ // }
36+ //
37+ // // Count news items with this category
38+ // const { count: newsCount, error: newsCountError } = await supabase
39+ // .from('news')
40+ // .select('*', { count: 'exact', head: true })
41+ // .eq('category', cat.name);
42+ //
43+ // if (!newsCountError) {
44+ // categoryCounts[cat.name] += newsCount || 0;
45+ // }
46+ // }
47+ }
48+ ```
49+
50+ ### Option B: If you haven't renamed the column yet
51+
52+ ```typescript
53+ // Get category counts from the categories table
54+ const { data: categoryData, error: categoryError } = await supabase
55+ .from('categories')
56+ .select('id, name, tool_count')
57+ .order('name');
58+
59+ if (!categoryError && categoryData) {
60+ // Initialize count for each category using tool_count
61+ categoryData.forEach(cat => {
62+ categoryCounts[cat.name] = cat.tool_count || 0;
63+ });
64+
65+ // REMOVE the additional counting code to avoid double counting
66+ // (remove the for loop shown above)
67+ }
68+ ```
69+
70+ ## 2. Update the Database Column Values
71+
72+ Run the appropriate SQL script to update the category count values in the database:
73+
74+ ### If you've renamed the column to instance_count:
75+
76+ ```sql
77+ -- Update instance_count values
78+ UPDATE categories c
79+ SET instance_count = (
80+ SELECT COUNT(*) FROM tools WHERE category_id = c.id
81+ ) + (
82+ SELECT COUNT(*) FROM news WHERE category_id = c.id
83+ );
84+ ```
85+
86+ ### If you're still using tool_count:
87+
88+ ```sql
89+ -- Update tool_count values
90+ UPDATE categories c
91+ SET tool_count = (
92+ SELECT COUNT(*) FROM tools WHERE category_id = c.id
93+ ) + (
94+ SELECT COUNT(*) FROM news WHERE category_id = c.id
95+ );
96+ ```
97+
98+ ## 3. Maintain Counts Going Forward
99+
100+ To ensure counts stay accurate when tools and news are added/removed, make sure:
101+
102+ 1. When adding a new tool:
103+ ```sql
104+ -- Increment the count for the category
105+ UPDATE categories
106+ SET instance_count = instance_count + 1
107+ WHERE id = [category_id_of_new_tool];
108+ ```
109+
110+ 2. When removing a tool:
111+ ```sql
112+ -- Decrement the count for the category
113+ UPDATE categories
114+ SET instance_count = instance_count - 1
115+ WHERE id = [category_id_of_removed_tool];
116+ ```
117+
118+ 3. Apply similar logic for news items.
119+
120+ ## 4. Testing
121+
122+ After making these changes:
123+ 1. Verify the dashboard displays the correct counts
124+ 2. Add a new tool or news item and verify the count increments properly
125+ 3. Remove a tool or news item and verify the count decrements properly
126+
127+ This approach ensures the count is maintained in one place (the database) and avoids the double-counting issue in your dashboard code.

355 more files changed.

Browse files at this commit