I need to understand the current state of these monolithic components/hooks to plan their decomposition. For each one, find: (1) the file path and current line count, (2) what props/fields it takes, (3) [REDACTED] it handles, (4) what contexts it uses/provides.
The targets are:
ShotEditor (~1140 lines, ~90 props)
ImageLightbox (~1030 lines, 47 props)
InlineEditView (~956 lines)
TimelineContainer (~988 lines)
SegmentSettingsForm (~1044 lines, 47+ props)
VideoLightbox (~903 lines)
EditModePanel (~628 lines, 95+ props)
MediaGallery (~752 lines, 119+ props)
useImageGenForm (~714 lines, returns 50+ fields)
useSharedLightboxState (~693 lines)
useGenerationActions (~727 lines, 14 refs)
useAutoSaveSettings (~720 lines)
useTrainingData (~588 lines)
Also check ImageEditContext and ImageGenerationFormContext for their field counts and what re-renders they cause.
Be very thorough - search across the whole codebase. For each item, just provide: file path, current line count, and a 2-3 sentence summary of responsibilities.
Assistant
I'll systematically locate and analyze each of these monolithic components and hooks. Let me start with a broad search across the codebase.
Assistant
Now let me find the hooks:
Assistant
Great! Now let me read all these files to get their line counts, props, and responsibilities:
User
Investigate the "inconsistency across similar things" problem in this codebase. I need concrete findings for:
Tools directory structure inconsistency: List all tool directories under src/tools/, for each show: number of files, whether it has lib/, how settings are defined, number of components. Focus on the structural differences.
Edge functions auth patterns: Check all 32 edge functions under supabase/functions/. For each, identify: (a) which auth pattern it uses (authenticateRequest from shared, manual JWT, raw Bearer comparison), (b) whether it has @ts-nocheck, (c) whether it uses SystemLogger or console.log, (d) CORS handling pattern, (e) response format pattern.
Task creation duplication: Find the 4 files with duplicated hires-fix param extraction. Find the files with processBatchResults() vs inline duplication. Find the inconsistent LoRA type definitions (path vs url, strength vs scale).
Device detection duplication: Find use-mobile.tsx and useDeviceDetection.ts, compare their implementations.
Be thorough - list every edge function and every tool.
Assistant
Now let me continue reading the remaining hook files:
Assistant
I'll conduct a thorough investigation of these inconsistencies. Let me start by gathering all the necessary information.
Assistant
Now let me check the structure and files for each tool:
Assistant
Perfect! Now let me get the line counts and compile my findings. Let me quickly check the line counts for all files:
Assistant
Now let me list all edge functions:
User
Investigate the "dead code and vestigial patterns" in this codebase. For each item below, find the file, confirm whether it's actually dead/unused, and note what references it (if any):
createSafeContext and DataContainer — documented but reportedly don't exist. Check if they were removed or still referenced anywhere.
useToolPageHeader — reportedly defined but marked "keep for potential future use" with void. Find it and check.
useGenerationTaskPreloader and useEnhancedGenerations — reportedly dead. Find them, check if they're imported/used anywhere.
invalidateGenerationUpdate — reportedly 30+ lines, marked @internal, not exported. Find it.
Deprecated fields in types: promptsByShot, masterPromptByShot, dimensionSource, customWidth, customHeight. Find their type definitions and check if they're actually used anywhere in runtime code.
useUpscale — reportedly returns 7 dead fields. Find it and check which fields are actually consumed by callers.
Empty useEffect in ProjectContext (lines ~148-153). Find and confirm.
Also do a broader sweep for:
Functions/hooks that are exported but never imported elsewhere
Components that are defined but never rendered
Type definitions that are never used
Be thorough - check each item individually.
Assistant
I'll conduct a thorough investigation of the dead code and vestigial patterns in this codebase. Let me start by systematically checking each item.
Assistant
That's 32 edge functions (excluding _shared). Now let me examine the auth patterns and other details for each. I'll check the main index.ts files:
Assistant
Now let me get individual line counts and check the MediaGallery file:
Assistant
Now let me search for these items specifically:
Assistant
Let me continue reading the remaining edge functions:
Assistant
Good start. Now let me search for the deprecated fields and read the specific files:
Assistant
Now let me find and check MediaGallery:
Assistant
Let me continue with the remaining edge functions. I'll use a more efficient approach:
Assistant
Let me check for the main MediaGallery component:
Assistant
Great! Now let me check the ProjectContext and read the invalidation hook:
User
Investigate the "architectural smells" in this codebase. For each item, find the actual code and assess severity:
11-level context nesting in App.tsx — Find App.tsx, count the provider nesting levels, and check where the auth check happens relative to provider initialization. List all providers in order.
Window globals as escape hatches — Search for: window.AUTH_MANAGER, window.PROJECT_CONTEXT, window.REACT_QUERY_CLIENT, window.supabase_client, window.__projectDebugLog. For each, find where it's set and where it's read. Are these actually needed or just debug artifacts?
ProjectContext is 653 lines — Find ProjectContext, count its lines, and list all the distinct responsibilities it handles (CRUD, selection persistence, default creation, settings inheritance, mobile timeout recovery, template copying, etc.)
Rate limiting is non-functional — Search for check_rate_limit RPC calls. Find where rate limiting is implemented and verify if the RPC exists in migrations. Check the ai-prompt edge function for IP-based rate limiting.
Billing logic scattered — Find billing/credit-related logic in edge functions. Identify the 3 edge functions with duplicated sub-task detection logic.
Task status guards incomplete — Find where task status transitions are enforced. Can completed tasks be moved back to Queued or In Progress? Check both frontend and backend.
Be thorough on each item.
Assistant
I'll investigate these architectural smells systematically. Let me start by searching for the key files and patterns.
Assistant
The output got malformed. Let me check more carefully by reading function headers directly:
Assistant
Perfect! Now let me read the MediaGallery to understand its props and responsibilities:
Assistant
Excellent! Now let me search for where these unused fields/functions are referenced and check for broader patterns:
Assistant
Now let me read the App.tsx file to analyze the provider nesting:
Assistant
Good, now let me check the auth and logging patterns for each:
Assistant
Now let me search for window globals and rate limiting:
Assistant
Now let me search for the deprecated fields in type definitions and where they're used:
Assistant
Let me read the rate limiting implementation:
Assistant
Now let me search for billing logic and edge functions:
Assistant
Excellent! Now let me look for task creation duplication and LoRA type definitions:
User
Investigate the "scattered mobile-specific logic" problem in this codebase. For each item, find the actual code and assess the pattern:
[MobileStallFix] in ProjectContext — Search for "MobileStallFix" comments across the codebase. Find all 3+ locations. What problem are they solving?
useSlidingPane mobile blocks — Find useSlidingPane, identify all 4 mobile-specific code blocks. What are they doing?
usePanesContext mobile branching — Find usePanesContext, identify the 3 nearly-identical setter functions with mobile branching. Could they be unified?
AuthContext [AuthDebounce] — Find AuthContext, locate the debounce system for mobile state transitions. What problem does it solve?
Fixed setTimeout(1000) in onboarding — Find the onboarding flow and the hardcoded timeout. What's it working around?
PaymentSuccessPage timeouts — Find PaymentSuccessPage, identify all 5 different timeouts and their purposes.
Also search broadly for:
Any other isMobile or useIsMobile or mobile-specific conditionals scattered in non-mobile components
Any UA sniffing patterns
The goal is to understand what a unified mobile handling architecture would need to cover.
Assistant
Let me read the complete_task billing logic and search for sub-task detection:
Assistant
Now let me check what calls useUpscale to see which fields are actually consumed:
Assistant
I'll investigate the scattered mobile-specific logic across this codebase systematically. Let me start by searching for the specific patterns you mentioned.
Assistant
Let me search for task status transitions and the task status guards:
Assistant
Now let me search for onboarding flow and additional mobile-specific patterns:
Assistant
Perfect! Now let me search for any exported but unused functions/hooks. Let me check the broader patterns:
Assistant
Let me search for other edge functions that might have sub-task detection logic:
Assistant
Let me check the ProjectContext useEffect more carefully - lines 148-153:
Assistant
Now let me read the key files to understand the patterns:
Assistant
Let me read the calculate-task-cost to see the duplicated logic:
Assistant
Good! Now let me search for exported functions that are never imported:
Assistant
Let me check the exported hooks/functions more methodically. Let me look at the invalid reference in the settings files:
Assistant
Now let me read the PaymentSuccessPage and search for other scattered patterns:
Assistant
Let me continue reading the calculate-task-cost function and search for more edge function patterns:
Assistant
Now let me check the complete_task orchestrator and search for where the third duplication might be:
User
Investigate these "notable specific issues" in the codebase. For each, find the actual code and assess:
ReferenceSectionProps drills 96 fields through 5+ levels — Find ReferenceSectionProps (likely in edit-images or image generation tool). Count the actual fields. Trace the prop drilling chain. Is there already a context that could replace this?
ImageLightbox local state mirroring — In ImageLightbox, find where it creates local state that mirrors hook returns with useEffect sync, causing a one-frame delay. What hook ordering issue is this working around?
useGenerationActions 14 useRef declarations — Find useGenerationActions, count the useRef declarations. What stale closure problem are they working around? What would the proper fix be?
imagesPerPrompt silent change — Find where imagesPerPrompt changes when toggling prompt mode (8 for automated, 1 for managed). Is the user notified?
Hardcoded colors in OnboardingModal and DatasetBrowserModal — Find these components and locate the hardcoded color values. What should they be replaced with?
complete_task double query — In the complete_task edge function, find where it does 2 queries for task context when 1 join would work. Find the "no FK" comment.
Be thorough on each item - read the actual source code.
Assistant
Let me search for where masterPromptByShot and promptsByShot are actually used at runtime:
Assistant
Now let me read PanesContext to understand the mobile branching pattern:
Assistant
Now let me check for the device detection files:
Assistant
I'll systematically investigate each of these issues. Let me start by searching for and reading the relevant code.
Assistant
Now let me read the ImageGenerationForm/types.ts to see context:
Assistant
Let me search for the onboarding flow and check for more scattered patterns:
Assistant
Let me search for ReferenceSectionProps and complete_task more broadly:
Assistant
Excellent! Now let me check if there are any references to createSafeContext and DataContainer in the docs:
Assistant
Now let me check the auth manager for window globals and read the browser extensions file:
Assistant
Perfect! Now let me search for task creation hires-fix parameter extraction in the different files to see duplication:
Assistant
Now let me search for more specific mobile detection patterns and examine GlobalHeader and other files with scattered logic:
Assistant
Now let me read the key files in detail:
Assistant
Let me check if there are any unexported barrel files that might need reviewing:
Assistant
Let me search more broadly for mobile-specific conditional renders and other patterns:
Assistant
Let me check the frontend status guards and search for any migration issues with rate limiting:
Assistant
Now let me read the remaining files:
Assistant
Let me check the invalidation barrel file to see if invalidateGenerationUpdate should be exported:
Assistant
Let me check if the rate limiting migration file exists:
Assistant
Now let me check the other two files that use processBatchResults and look for the pattern more:
Assistant
Now let me search for imagesPerPrompt to understand issue #4:
Assistant
Let me examine the Mobile/Desktop wrapper pattern more closely and search for other timeout patterns:
Assistant
Perfect! Now let me do a final comprehensive check on the unused fields in useUpscale. Let me check the code more carefully:
Assistant
Now let me check if rate limiting is actually being used in any edge functions:
Assistant
Perfect! Now let me check where the useUpscale fields are consumed by checking the callers more thoroughly:
Assistant
Let me read the complete_task params to understand the orchestrator reference extraction:
Assistant
Perfect! Now I have a complete picture. Let me gather the final information about lora type definitions and tool structure summary:
Assistant
Now let me search for where imagesPerPrompt changes with prompt mode:
Assistant
Now let me search for the AI prompt edge function to check rate limiting there:
Assistant
Now let me create a comprehensive summary document. Let me also check if there are any docs that reference these items:
Assistant
Now let me look at the mobile-specific hooks and gather more data on the scattered patterns:
Assistant
Good! Now let me compile all findings. Let me also quickly verify if there are actually tests for rate limiting and check if there are any frontend task status update guards:
Assistant
Perfect! Now let me create a comprehensive report. Let me make one final check on the complete_task database queries:
Assistant
Perfect! Now let me read a few more critical files to complete the picture:
Assistant
Let me check TasksPane to see if there are any task status changes:
Assistant
Excellent! Now let me create a comprehensive summary document. Let me search for a few more patterns to complete the picture:
Assistant
Now I have all the information I need. Let me compile the comprehensive report:
Perfect! Now I have all the data I need. Let me compile my comprehensive report:
COMPREHENSIVE INVESTIGATION REPORT: INCONSISTENCIES IN REIGH CODEBASE
1. TOOLS DIRECTORY STRUCTURE INCONSISTENCY
All 7 tools exist in /Users/user_c042661f/Documents/reigh/src/tools/:
Tool
Total Files
Has lib/
Components
Hooks
Settings Defined
Structure Pattern
character-animate
5
YES
0
2
✓
pages, hooks, settings (minimal)
edit-images
3
NO
1
0
✓
pages, components, settings (minimal)
edit-video
8
YES
4
2
✓
pages, components, hooks, lib, settings
image-generation
6
NO
2
4
✓
pages, components, hooks, settings (full)
join-clips
10
YES
1
3
✓
pages, components, hooks, lib, settings
training-data-helper
10
YES
11
4
✓
pages, components, hooks, lib, settings (full)
travel-between-images
56
NO
129
28
✓
pages, components, hooks, settings (massive)
Key Inconsistencies:
lib/ directory: Only 4 of 7 tools have lib/ (character-animate, edit-video, join-clips, training-data-helper). Three tools omit it (edit-images, image-generation, travel-between-images).
Component/Hook distribution: Highly variable (0-129 components, 0-28 hooks). travel-between-images is 10x larger than others.
File organization: No standardized structure; some tools emphasize hooks (image-generation: 4), others components (training-data-helper: 11, travel-between-images: 129).
2. EDGE FUNCTIONS AUTH & LOGGING PATTERNS
Assistant
Perfect! Now I have all the information I need. Let me compile the comprehensive investigation report:
Investigation Report: Notable Codebase Issues
Issue 1: ReferenceSectionProps - 35 Fields Through 5+ Levels
Provider Nesting Count: 10 levels of context providers
Reading from lines 242-268, the nesting order is:
QueryClientProvider (React Query)
TaskTypeConfigInitializer (component)
AuthProvider
UserSettingsProvider
ProjectProvider
RealtimeProvider
ShotsProvider
GenerationTaskProvider
IncomingTasksProvider
PanesProvider
LastAffectedShotProvider
CurrentShotProvider
ToolPageHeaderProvider
Auth Check Timing: Line 244, AuthProvider is the 3rd provider - comes BEFORE ProjectProvider (line 246), which is correct. The auth guard in AppInternalContent (line 73) uses useProject() which depends on being inside all providers.
Severity: HIGH
Each provider adds context overhead and component re-renders
13 nested providers create deep prop drilling chains if any need context from others
Line 26 imports mobileProjectDebug for debug-only instrumentation
Line 30 imports RefactorMetricsCollector (commented as "temporary")
Code comments indicate this structure was built incrementally without consolidation
I need to verify file overlaps between planned refactoring work. For each file below, tell me if it exists and its current line count. Just the path and line count, nothing else:
Responsibilities: Controlled form for segment generation settings. Manages prompt field state, advanced settings collapsible, motion presets, LoRA selection, structure video upload/management. Per-segment video CRUD. Submit/default save handlers. Multiple independent field handlers.
Responsibilities: Auto-save with debounce for any entity-scoped settings (shot/project). React Query or custom load/save backends. Deep equality checking. Dirty tracking. Error handling + callbacks. Reset/revert logic. HiresFixConfig migration example (see useImageGenForm).
Key Features: Dual backend support, debounce management, entity lifecycle handling.
Responsibilities: Training data CRUD (batches, videos, segments). Video URL caching. DB transform functions (snake_case ↔ camelCase). Batch/segment fetch + filtering. Upload state management. Video selection state.
Key Transforms: DB → client type transforms (TrainingDataBatchDB → TrainingDataBatch, etc.).
Responsibilities: Unified image edit state composition across 8 domain sub-interfaces. Shared by ImageLightbox, EditModePanel, InlineEditView. Enables deep tree of consumers without prop drilling.
Re-render Cause: Any mutation in any 70+ fields triggers context subscribers.
This is dead instrumentation code — was probably used for debugging and never removed
BROADER PATTERNS FOUND
Exports That Are Dead/Unused
Based on the investigation:
Properly marked dead code uses explicit void pattern — excellent for preventing "unused variable" lint errors while keeping code intentional
The codebase has good discipline about this in contexts (ToolPageHeaderContext, GenerationTaskContext, useGenerationInvalidation)
Living But Confusingly Marked
dimensionSource/customWidth/customHeight: Marked "DEPRECATED" in comments but actively used in UI. Should either be removed or comment should be updated.
Migration Debris
promptsByShot, masterPromptByShot: These are being actively deleted in settings inheritance (line 22 of projectSettingsInheritance.ts) but kept as dead type definitions for migration purposes. This is intentional but creates maintenance burden.
SUMMARY TABLE
Item
Type
File
Status
Action
createSafeContext
Function
—
Never existed
✅ OK
DataContainer
Type
—
Never existed
✅ OK
useToolPageHeader
Hook
ToolPageHeaderContext.tsx
Dead (marked)
✅ OK (marked explicitly)
useGenerationTaskPreloader
Hook
GenerationTaskContext.tsx
Dead (marked)
✅ OK (marked explicitly)
useEnhancedGenerations
Hook
GenerationTaskContext.tsx
Dead (marked)
✅ OK (marked explicitly)
invalidateGenerationUpdate
Function
useGenerationInvalidation.ts
Dead (internal, not exported)
⚠️ Consider removing or exporting; documented in data_fetching.md
promptsByShot
Type field
image-generation settings
Dead but kept for migration
⚠️ Migration debris
masterPromptByShot
Type field
image-generation settings
Dead but kept for migration
⚠️ Migration debris
dimensionSource
Field
travel-between-images
LIVE (confusingly marked deprecated)
⚠️ Update comment or remove
customWidth
Field
travel-between-images
LIVE (confusingly marked deprecated)
⚠️ Update comment or remove
customHeight
Field
travel-between-images
LIVE (confusingly marked deprecated)
⚠️ Update comment or remove
useUpscale.showingUpscaled
Field
useUpscale.ts
Dead stub
✅ OK (backwards compat)
useUpscale.handleToggleUpscaled
Field
useUpscale.ts
Dead stub
✅ OK (backwards compat)
useUpscale.sourceUrlForTasks
Field
useUpscale.ts
Dead stub
✅ OK (backwards compat)
useUpscale.isPendingUpscale
Field
useUpscale.ts
Dead stub
✅ OK (backwards compat)
useUpscale.hasUpscaledVersion
Field
useUpscale.ts
Dead stub
✅ OK (backwards compat)
useUpscale.upscaledUrl
Field
useUpscale.ts
Dead stub
✅ OK (backwards compat)
ProjectContext useEffect
Effect
ProjectContext.tsx L148-153
Dead instrumentation
⚠️ Remove empty effect
KEY OBSERVATIONS
Good discipline with dead code markers: The codebase uses void functionName; pattern consistently to mark intentional dead code, preventing lint warnings while being explicit about intent.
Documentation drift: invalidateGenerationUpdate is documented in data_fetching.md but not exported from barrel and never called. Should be consistent.
Migration burden: promptsByShot/masterPromptByShot are kept as migration shims but never actually used, just deleted. Could be cleaned up if migration is done.
Confusing deprecation markers: dimensionSource/customWidth/customHeight are marked DEPRECATED but actively used. Comments should be accurate.
Backwards compat stubs: The 6 dead fields in useUpscale are intentional backwards-compatibility stubs that return empty/false/null. This is reasonable but could be documented better.
Empty cleanup is suspicious: The ProjectContext useEffect (lines 148-153) is genuinely dead code that should be removed—it has no body and no cleanup logic.
32 edge functions in /Users/user_c042661f/Documents/reigh/supabase/functions/:
These are passed to useSharedLightboxState() at lines 301, 318-320 BEFORE the hooks that compute real values (useInpainting, useMagicEditMode) are called at lines 385-497.
Root Cause: Hook ordering - useSharedLightboxState (line 284) needs layout calculations based on edit modes, but those values come from hooks called after it. The comment on lines 278-280 explains:
"useSharedLightboxState needs isInpaintMode/isMagicEditModeLocal for layout calculations, but these come from hooks called AFTER it. Local state proxies are updated via useEffect below — one-frame delay is acceptable for swipe/layout calculations."
Result: One-frame delay in layout calculations when edit modes toggle. The developer intentionally accepted this trade-off rather than restructure hook order.
demoteOrphanedVariantsRef (line 114) - function reference
actionsRef (line 119) - action callbacks
Stale Closure Problem Being Worked Around:
All 14 callbacks (handleDeleteImageFromShot, handleBatchDeleteImages, handleDuplicateImage, etc.) have empty dependency arrays (e.g., line 227: }, [])). They use refs instead to access latest values without triggering callback recreation.
Why This Is Necessary:
React Query mutations change reference when their state changes (pending → success → idle)
Data objects refetch frequently, changing reference even if semantically identical
Callback recreation would trigger parent re-renders and potentially infinite loops
The Proper Fix Would Be:
Stable mutation handles - wrap mutations in useRef at mutation creation time, not every render
Location: Lines 70-77 in PromptsSection onChange handler
The Code:
typescript
onChangeMode={(mode) => {
form.setEffectivePromptMode(mode);
// Auto-set imagesPerPrompt based on mode
if (mode === 'automated') {
form.setImagesPerPrompt(8);
} else if (mode === 'managed') {
form.setImagesPerPrompt(1);
}
}}
User Notification:NONE. The value silently changes without toast, confirmation, or any UI feedback.
Impact:
User toggles "managed" mode → imagesPerPrompt silently becomes 1
User toggles back to "automated" → silently becomes 8
User may not realize their previous setting of (e.g.) 4 has been overwritten
No undo mechanism
Expected Behavior:
Per CLAUDE.md: "Toasts: errors only (no success toasts for task creation)." This rule correctly prevents toast spam, BUT silent parameter changes still violate the principle of explicit action feedback. Options:
Keep the change but add inline UI indicator (e.g., "Images per prompt reset to 8")
Only auto-set if it's the first time the mode is selected, preserve user values on toggle
Show a dismissible notification (not toast) when value changes
Issue 5: Hardcoded Colors in OnboardingModal and DatasetBrowserModal
// Fetch task_types metadata separately (no FK relationship exists)
Why 2 Queries Are Needed:
There is no foreign key relationship between tasks.task_type (string column) and task_types.name (primary key). The schema uses string matching instead of FK, forcing a second query.
Why This Isn't Fixed:
Creating a proper FK would require:
Changing tasks.task_type from a string reference to an integer/UUID ID
Adding a task_type_id column and FK constraint
Migrating all existing data
Updating all queries that reference task types
This is a major structural change that would ripple through the entire codebase.
Could Be Optimized:
A single JOIN query would work if there were an FK, or if task_types data were denormalized into tasks:
setIsShotsPaneLocked (lines 131-147):
Same pattern, different pane name.
setIsTasksPaneLocked (lines 149-171):
Same pattern, with additional sync of isTasksPaneOpen.
What they do:
On mobile/tablet when locking: Unlock ALL other panes (only one can be locked at a time)
On small phones: Never save to database (only local state)
On desktop: Standard toggle without exclusive behavior
Duplication issue: The conditional logic is nearly identical across all three - candidates for unification through a factory function or higher-order function.
Issue: Multiple overlapping timeouts with unclear coordination. The 5s timeout and 1.5s timeout can fire in either order, creating potential race conditions.
Problem: Three different UA regex patterns for "mobile" detection, with different sensitivity. Centralized in use-mobile.tsx but not consistently used in utility functions.
8. Unified vs. Scattered Components
Properly unified (good pattern):
use-mobile.tsx - centralized detection with three methods (width, UA, pointer, iPad OS detection)
✓ RPC function check_rate_limit() EXISTS in migration (lines 28-69)
✓ Rate limit table created (lines 14-22)
✓ Atomic upsert logic with sliding window implemented (lines 46-59)
✓ RLS policies configured (lines 105-112)
Rate Limiting Implementation Uses:
Called in 5 edge functions:
generate-pat/index.ts - 10 requests/60s per user
stripe-checkout/index.ts - 30 requests/60s per user (expensive)
ai-prompt/index.ts (line 64-72) - 30 requests/60s by IP (expensive, "IP-based")
create-task/index.ts - 120 requests/60s per user (task creation)
Other functions (stripe-webhook, etc.) - not checked
Issue Found - "IP-based" in ai-prompt:
Lines 62-69 in ai-prompt/index.ts shows:
typescript
// Rate limit by IP (this is an expensive AI endpoint)
const clientIp = getClientIp(req);
const rateLimitResult = await checkRateLimit(
supabaseAdmin,
'ai-prompt',
clientIp, // ← Uses IP instead of user_id
RATE_LIMITS.expensive,
BUT this is behind authentication (lines 56-59), so the identifier should be the user_id, not IP. The comment says "by IP" but for authenticated endpoints, this causes cross-user rate limit collisions if users share an IP (office, school, etc.).
Missing Functions Not Rate Limited:
complete_task - expensive operation, no rate limiting
calculate-task-cost - expensive operation, no rate limiting
delete-project - expensive operation, no rate limiting
Severity: MEDIUM
RPC and migration exist and work
"Non-functional" claim is wrong - they ARE implemented
Issue: ai-prompt uses IP for authenticated users (wrong)
Issue: expensive operations lack any rate limiting
Issue: RLS only prevents service_role bypass, not direct access
5. Billing Logic Scattered ✓ CONFIRMED - SEVERE
Three Edge Functions with Duplicated Sub-Task Detection Logic:
Duplication Pattern: All check the same 4 paths to find orchestrator references