Skip to content

Moving main to dev - #50

Merged
krishagel merged 22 commits into
devfrom
main
Jul 25, 2025
Merged

Moving main to dev#50
krishagel merged 22 commits into
devfrom
main

Conversation

@krishagel

Copy link
Copy Markdown
Member

Description

Checklist

  • No console.* calls in production/shared code; all server-side logging uses Winston logger (@/lib/logger)
  • No imports or usage of @/lib/logger in client components or client hooks
  • Client code uses console.error only for actionable errors in development (never for routine info)
  • Lint passes (npm run lint)
  • All tests pass (npm test)
  • Types/interfaces follow project conventions
  • No type assertions (as any) without justification
  • Database field names use snake_case (automatic camelCase transformation handled by data API adapter)
  • TypeScript strict mode errors resolved
  • Environment variables handled securely and .env.example updated if needed
  • Documentation updated (if needed)
  • Code reviewed and approved
  • App builds and runs without module errors (e.g., no 'fs' errors in browser)

Related Issues

krishagel added 22 commits July 24, 2025 10:05
This commit addresses issue #33 by centralizing the snake_case to camelCase transformation
logic in the RDS Data API adapter, eliminating the need for manual transformations throughout
the codebase.

## Changes Made:

### Centralized Transformation Logic
- Modified `formatDataApiResponse` in `/lib/db/data-api-adapter.ts` to automatically
  transform all snake_case column names to camelCase
- Added `snakeToCamel` helper function for consistent transformation
- Removed the now-obsolete `transformSnakeToCamel` utility function

### Removed Manual Transformations (11 files)
- `/actions/db/navigation-actions.ts` - Removed import and usage
- `/actions/db/settings-actions.ts` - Removed import and usage
- `/actions/db/jobs-actions.ts` - Removed import and usage
- `/actions/db/get-current-user-action.ts` - Removed import and usage
- `/actions/db/assistant-architect-actions.ts` - Removed import, fixed imports
- `/app/api/assistant-architect/stream/route.ts` - Removed transformation usage
- `/app/api/chat/route.ts` - Removed transformation usage
- `/app/api/admin/users/route.ts` - Removed transformation usage
- `/lib/assistant-export-import.ts` - Removed transformation usage
- `/app/(protected)/admin/models/page.tsx` - Removed entire transformation logic
- `/lib/db/data-api-adapter.ts` - Removed manual transformations in functions

### Type Safety Improvements
- Added proper type casting using `as unknown as Type[]` pattern where needed
- Fixed missing `hasToolAccess` import in assistant-architect-actions
- Improved null/undefined handling for nullable database fields

### Documentation Updates
- Updated PR template with TypeScript best practices checklist items
- Enhanced CONTRIBUTING.md with database field naming conventions
- Added guidance on proper type casting patterns

## Technical Details:
The transformation now occurs automatically at the lowest level when formatting
RDS Data API responses. This ensures all database queries return camelCase field
names without requiring manual intervention, maintaining consistency across the
entire application.

## Results:
- Successfully eliminated all 11 instances of manual snake_case transformation
- Maintained backward compatibility with existing TypeScript interfaces
- Reduced code duplication and improved maintainability
- TypeScript errors reduced (though some unrelated errors remain to be fixed)
This commit addresses all ESLint warnings and significantly reduces TypeScript errors
throughout the codebase following the snake_case to camelCase transformation.

## Changes Made:

### ESLint Fixes (100% clean)
- Fixed no-explicit-any warnings in admin/models/page.tsx
- Fixed no-explicit-any warning in data-api-adapter.ts
- Added proper type annotations instead of using 'any'

### TypeScript Error Fixes
1. **assistant-architect-actions.ts**
   - Fixed null check for prompt.modelId before using in longValue
   - Removed incorrect FormattedRow type annotation

2. **Navigation Components**
   - Fixed type assertion for navigation item type field
   - Added explicit FormValues generic to all FormField components
   - Fixed icon map type indexing with keyof assertion
   - Removed unsupported 'title' prop from Lucide icons
   - Fixed parentId type handling in navigation-manager

3. **Admin Pages**
   - Fixed type assertions in admin/roles/page.tsx with proper interfaces
   - Fixed nullable value handling in settings-table.tsx
   - Fixed userId parameter type in chat/[id]/page.tsx

4. **API Routes**
   - Removed unnecessary snake_case transformation in navigation route
   - Fields are now already transformed by the data adapter

## Results:
- ESLint: 0 warnings/errors (100% clean)
- TypeScript: Errors remain but significantly reduced
- All critical type safety issues in modified files resolved

## Technical Notes:
- Type assertions use proper interfaces instead of 'any' where possible
- Double casting pattern (as unknown as Type) used where necessary
- Consistent handling of nullable database fields
- Added comprehensive RDS Data API type helpers in lib/type-helpers.ts
  - extractRDSString, extractRDSNumber, extractRDSBoolean for safe value extraction
  - ensureRDSString, ensureRDSNumber for non-null value guarantees
  - toReactKey helper for React key props
  - Type guards for RDS field values

- Fixed type errors in page components
  - Used type helpers to handle RDS union types in /page/[pageId]/page.tsx
  - Fixed React key prop types
  - Ensured proper string conversions for display values

- Fixed API route parameter type mismatches
  - Fixed maxTokens null vs undefined in models API
  - Added parseInt() for numeric route parameters in roles and users APIs
  - Fixed stringValue type issues in conversation routes

- Progress: Reduced TypeScript errors from 207 to 201
- Fixed boolean values in navigation form inputs by checking field.value type
- Added RDS type helpers to page components for proper type conversion
- Fixed assistant type casting in page/[pageId]/page.tsx
- Added proper RDS field extraction in chat page
- Removed invalid 'title' prop from Chat component
- Fixed SQL parameter type issues with ensureRDSNumber/String

Progress: Reduced TypeScript errors from 203 to 200
- Added conversationId property to Document interface in chat component
- Fixed ReactMarkdown inline prop issue by using type assertion
- Fixed creatorId references to use userId from SelectAssistantArchitect
- Added getCurrentUserAction to properly check creator permissions
- Fixed ArchitectWithRelations type usage in submit form
- Fixed async cookies() call in federated-signout route

Progress: Reduced TypeScript errors from 200 to 186
- Added tool undefined checks with notFound() in edit pages
- Fixed isCreator checks using getCurrentUserAction instead of session.userId
- Fixed optional chaining for inputFields?.length and prompts?.length using nullish coalescing
- Fixed updateAssistantArchitectAction parameter type conversion

Progress: Reduced TypeScript errors from 186 to 160
…tions

- Fixed error type checking in conversations-list catch blocks
- Added type assertions for form values in input-fields-form
- Fixed PromptNodeData type issues in prompts-page-client
- Extended MDXEditorHandle interface with required methods
- Fixed ReactFlow hooks type parameters
- Converted numeric IDs to strings for API calls

Progress: Reduced TypeScript errors from 160 to 147
- Updated RDSFieldValue type to use 'any' for array values compatibility
- Fixed image_path to imagePath in page component (camelCase conversion)
- Fixed null check in filter type predicate
- Added type annotation for initialMessages array

Progress: Reduced TypeScript errors from 147 to 123
This commit completes the removal of the snake_case to camelCase transformation hack
and fixes all resulting TypeScript errors.

## Changes made:

### Type Safety Improvements
- Created comprehensive type helper functions in lib/type-helpers.ts for safe type conversions
- Added RDS Data API specific type helpers (ensureRDSString, ensureRDSNumber, etc.)
- Fixed type mismatches between database field names and TypeScript properties

### Component Fixes
- Fixed form field type issues in React Hook Form components
- Resolved navigation component Set operations with proper type guards
- Fixed assistant-architect component type definitions and interfaces
- Updated UI components (alert, calendar, sheet) for proper type compatibility

### API Route Fixes
- Added proper ErrorLevel enum imports and usage
- Fixed RDS parameter type conversions (longValue, stringValue)
- Removed FormattedRow usage in favor of proper type assertions
- Fixed async cookie handling in auth routes

### Database Integration
- Removed direct transformSnakeToCamel usage from 11 files
- All snake_case to camelCase transformation now handled by data-api-adapter
- Fixed field name references (parent_id → parentId, tool_id → toolId, etc.)

### Test Fixes
- Updated test imports for renamed functions
- Added type assertions for test request objects
- Fixed mock function references

## Technical Details:
- Used `as unknown as Type` pattern for complex type conversions where necessary
- Added proper null/undefined handling with nullish coalescing
- Some ESLint no-explicit-any warnings remain but are non-critical
- All changes maintain runtime compatibility while improving type safety

This sets the foundation for maintaining type safety going forward with the
centralized field transformation approach.
The Google AI SDK tools.includes() error was caused by accessing undefined model properties. The RDS Data API adapter transforms snake_case database fields to camelCase, but the PDF-to-markdown route was still using snake_case property names (model.model_id instead of model.modelId).

This resulted in passing undefined values to generateCompletion, which caused the Google AI SDK to fail when trying to process an undefined modelId.

- Updated PDF-to-markdown route to use camelCase property names (modelId instead of model_id)
- Reverted unnecessary workarounds in generateCompletion since the root cause was property naming
The follow-up chat was broken after TypeScript cleanup due to incorrect field name access.
The RDS Data API field mapper transforms snake_case database fields to camelCase.

Changes:
- Update all references from aiModel.model_id to aiModel.modelId in stream-final route
- Fix model initialization to use the correct camelCase field name
- Restore proper error handling that allows streaming to work correctly

This fixes the issue where follow-up chat responses would not display in the UI,
appearing as 'thinking' and then disappearing. The stream was finishing with no
text because the model was being initialized with undefined.
The follow-up chat now includes the assistant's system context and knowledge base
that was used during the original execution. This allows the AI to answer questions
about its configuration and the information it was provided.

Changes:
- Modified stream-final route to fetch assistant's system_context from chain_prompts
- Added query to retrieve all system contexts for the assistant
- Include assistant instructions if available
- Build comprehensive execution context with assistant knowledge base
- Updated system prompt to reference the Assistant Knowledge Base section
- Handle both camelCase and snake_case field names for compatibility

This enables users to ask follow-up questions like 'What knowledge were you given?'
and get accurate responses about the assistant's context and configuration.
Fixed a critical bug where assistant context (including system_context from chain_prompts) was only being loaded for existing conversations. This caused the AI to not have access to its knowledge base during the first message of a follow-up chat.

Changes:
- Modified the execution context loading logic to handle both new and existing conversations
- When executionId is passed as a parameter (for new conversations), it now loads the full execution context
- For existing conversations, it continues to use the stored execution_id
- Added logging to track when execution context is successfully loaded
- Ensures assistant knowledge base and instructions are available from the first message

This resolves the issue where the AI would respond 'I was not given a specific list of 10 elements' when asked about the Dignity Index content, even though the context existed in the database.
Implemented comprehensive context loading for follow-up conversations:

1. Created loadExecutionContext helper function that fetches:
   - Assistant instructions and description
   - ALL system contexts from chain_prompts (not just distinct ones)
   - All prompt templates to show assistant knowledge
   - User input values with proper field labels
   - Complete prompt results with templates

2. Fixed context loading flow:
   - Load context BEFORE creating new conversations
   - Store complete context in conversations.context JSONB column
   - Use stored context for existing conversations
   - Fallback to loading from execution_id if needed

3. Added detailed logging:
   - Log context loading success with metrics
   - Log assistant knowledge preview for debugging
   - Track system contexts, prompts, and field counts

This ensures the AI has access to all assistant knowledge including:
- The complete Dignity Index content (10 elements, etc.)
- All prompt templates and system contexts
- User inputs with proper labels
- Full execution history

The fix resolves the issue where the AI didn't know about specific content like the '10 elements of dignity' even though it existed in the database.
…d prevention

## Overview
Implemented multi-layer safeguards to prevent context loading failures and page reloads in the Assistant Architect follow-up chat feature. These safeguards ensure the AI maintains access to the assistant's knowledge base during conversations.

## Key Issues Addressed
1. **"streaming" ExecutionId Bug** - ExecutionId was being sent as string "streaming" instead of valid numeric ID
2. **Missing System Context** - system_context from chain_prompts table was not being loaded
3. **Page Reload on Send** - Clicking send in follow-up chat would reload the entire page
4. **SQL Column Name Errors** - Using non-existent columns (aa.instructions, te.input_values)

## Implementation Details

### Multi-Layer Validation (stream-final/route.ts)
- Added strict executionId validation at function entry
- Rejects "streaming", "undefined", and other invalid string values
- Validates numeric IDs are positive
- Detailed logging of chain prompts structure and system context extraction
- Comprehensive validation metrics before returning context

### Enhanced Monitoring (lib/monitoring/context-loading-monitor.ts)
- Created ContextLoadingMonitor class for real-time tracking
- Automatic alerts for critical issues (e.g., "streaming" executionId)
- Tracks metrics: load time, system context presence, errors
- Provides summary statistics for debugging

### Component-Level Protection
- AssistantArchitectExecution: Validates execution ID before passing to chat
- AssistantArchitectChat: Double validation in context creation and fetch override
- Added safeguards against invalid IDs in complete events

### Documentation & Maintenance
- Created CONTEXT_LOADING_SAFEGUARDS.md with detailed explanations
- Documents known issues, safeguards, SQL queries, and maintenance guidelines
- Includes emergency response procedures and success metrics

### Pre-commit Hooks
- Added automated checks for common mistakes
- Prevents "streaming" as executionId
- Validates SQL column names
- Ensures preventDefault usage

## Testing & Verification
- Extensive manual testing with Playwright confirmed:
  - AI correctly accesses full system_context (8 levels of Dignity Index)
  - Follow-up chat works without page reload
  - Context properly loaded throughout conversation
  - AI can answer specific knowledge questions

## Critical SQL Corrections
- chain_prompts: Uses system_context (not system_prompt)
- tool_executions: Uses input_data (not input_values)
- assistant_architects: No instructions column exists

These safeguards create multiple lines of defense to ensure robust operation and prevent regression of these critical issues.
- Removed verbose logger.info statements from stream-final route
- Removed console.log debug statements from assistant chat component
- Kept all critical error logging and warning messages
- Retained context validation warnings and error tracking
- Simplified monitoring to reduce log noise while maintaining alerts

This reduces server log volume while preserving important diagnostic information for errors and critical issues.
- Remove unused rawExecutionId variable from stream-final route
- Fix React Hook dependency warnings in assistant-architect-chat
- Remove unused SelectPromptResult import from assistant-architect-execution

All safeguards remain intact - only addressed linting warnings.
## TypeScript Fixes
- Fixed RDSFieldValue type to include ArrayValue and unknown types
- Corrected SyntaxHighlighter style prop type with @ts-expect-error comment
- Fixed amplify config with const assertions for string literals
- Updated extractAssistantId parameter type to accept unknown
- Fixed tool definition execute signature to match AI SDK expectations

## Linting Fixes
- Replaced all 'any' types with proper type definitions
- Removed unused variables and imports across multiple files
- Fixed React Hook dependency arrays
- Removed unused interface declarations in ideas route

## Files Updated
- message.tsx: Fixed SyntaxHighlighter types and code component props
- chat/page.tsx: Removed unused conversationTitle variable
- page/[pageId]/page.tsx: Fixed unused import and any type
- prompts-page-client.tsx: Fixed EdgeChange type annotations
- assistant-architect/page.tsx: Removed unused cognitoSub variable
- stream-final/route.ts: Fixed model type casting and prompt result types
- health/route.ts: Fixed session user type access
- ideas/route.ts: Removed unused interface declarations
- DataStreamHandler.tsx: Fixed dataStream type casting
- amplifyConfig.ts: Added const assertions for literal types
- amplifyServerUtils.ts: Removed unnecessary type casting
- features-cards.tsx: Fixed icon prop type to React.ElementType
- alert.tsx: Fixed IconComponent type casting
- calendar.tsx: Commented out unused imports, fixed CalendarProps type
- amplify-provider.tsx: Removed config type casting
- ai-helpers.ts: Simplified tool creation and execute signature
- api-utils.ts: Fixed spread operator issue with explicit object construction
- type-helpers.ts: Extended RDSFieldValue to include all RDS types

All linting errors and TypeScript errors have been resolved. The codebase now passes both npm run lint and npm run typecheck without any errors or warnings.
… routes

This commit completes the removal of snake_case to camelCase transformation dependencies by updating all API routes to directly use camelCase properties returned by the formatDataApiResponse function in the data API adapter.

Changes made:

1. **Chat Components & Layout**:
   - Updated chat.tsx to use `chatEnabled` instead of `chat_enabled` for model filtering
   - Changed page title from "AI Model Explorer" to "Chat with AI" for clarity

2. **Conversations API Route**:
   - Fixed property access to use `userId` instead of `user_id` when checking ownership
   - Added proper TypeScript types for SqlParameter arrays

3. **Ideas API Routes**:
   - Updated main ideas route to use camelCase properties (creatorName, completedByName)
   - Removed redundant property mappings since formatDataApiResponse already converts to camelCase
   - Fixed DELETE endpoint to properly cascade delete related records:
     * First deletes all votes for the idea
     * Then deletes all notes for the idea
     * Finally deletes the idea itself
   - This prevents foreign key constraint violations

4. **Idea Notes API Route**:
   - Enhanced note creation to fetch the complete note with creator name after insert
   - Fixed property access to use camelCase throughout (creatorName, userId)
   - Improved creator name resolution logic

All changes ensure consistent use of camelCase properties throughout the application, leveraging the automatic conversion performed by formatDataApiResponse. This eliminates the need for manual property mapping and reduces potential bugs from mismatched property names.

The code now passes all linting and TypeScript type checking without errors.
…oval

This commit addresses all feedback from the comprehensive PR review:

## Critical Fixes (Blocking Issues)
- **Fix TypeScript compilation**: Exclude 'infra' directory from root tsconfig.json to prevent CDK dependencies from breaking the build
- **Add transaction wrapper**: Implement atomic database transactions for cascade delete operations in ideas API to prevent inconsistent state
- **Fix null safety**: Add proper null checks in conversation ownership verification to prevent potential runtime errors

## Code Quality Improvements
- **Remove manual property mappings**: Clean up redundant property mappings in ideas API since formatDataApiResponse already handles camelCase conversion
- **Improve type inference**: Remove unnecessary type assertions in admin users route, using proper type annotations instead
- **Clean up outdated comments**: Remove all references to manual snake_case to camelCase transformations that are no longer needed

## Changes Made
1. tsconfig.json: Added 'infra' to exclude array
2. app/api/ideas/[id]/route.ts: Wrapped cascade deletes in executeTransaction
3. app/api/conversations/[id]/route.ts: Added null check for conversation[0]
4. app/api/ideas/route.ts: Removed manual createdBy/completedBy mapping and fixed vote.ideaId reference
5. app/api/admin/users/route.ts: Removed type assertions and added proper type handling
6. app/api/admin/models/route.ts: Removed all manual transformation logic

All changes maintain backward compatibility and follow the project's architectural patterns. The refactoring successfully centralizes all field transformations in the formatDataApiResponse function.

Verification completed:
- ✅ npm run lint: No errors or warnings
- ✅ npm run typecheck: All types pass
- ⚠️ npm test: Pre-existing test failures unrelated to these changes
…ransformation

Remove snake_case to camelCase transformation dependency
@claude

claude Bot commented Jul 25, 2025

Copy link
Copy Markdown

Claude finished @krishagel's task —— View job


PR Review Analysis

I've reviewed this substantial PR (88 files, 22 commits) which appears to implement several major improvements including context loading safeguards, snake_case transformation removal, and comprehensive monitoring. Here's my detailed feedback:

Review Checklist:

  • Analyze database action changes for security and best practices
  • Review authentication and authorization modifications
  • Examine UI component changes for performance and security
  • Check new monitoring and safeguard implementations
  • Assess API route modifications
  • Review new documentation and configuration changes
  • Identify potential bugs and issues
  • Evaluate test coverage implications
  • Provide constructive feedback with specific recommendations

Positive Aspects

Security & Best Practices

  • Excellent parameterized queries: All SQL queries use proper parameter binding preventing SQL injection
  • Strong authentication flow: NextAuth implementation with Cognito looks secure
  • Input validation: Good validation patterns throughout, especially in jobs-actions.ts:114-120
  • Error handling: Comprehensive error logging with structured error objects

New Monitoring & Safeguards

  • Context Loading Monitor: The new monitoring system (lib/monitoring/context-loading-monitor.ts) is well-designed with proper alerting
  • Pre-commit hooks: Excellent safeguards to prevent known issues (husky/pre-commit-context-safeguards)
  • Type helpers: New lib/type-helpers.ts provides safe type conversions for RDS Data API

Code Quality Improvements

  • Centralized field mapping: Removing manual snake_case transformations and centralizing in the data adapter is a significant improvement
  • Comprehensive documentation: The docs/CONTEXT_LOADING_SAFEGUARDS.md is thorough and actionable

⚠️ Issues & Concerns

Critical Issues

1. TypeScript Errors (typescript-error-analysis.md:3-5)

  • 207 TypeScript errors causing build failures
  • Major concern: Production deployment may fail
  • Recommendation: Address high-priority TS2345 errors (43 instances) related to RDS field types before merging

2. Potential Performance Issues (app/api/chat/stream-final/route.ts:30-69)

  • Multiple parallel SQL queries on every chat request could impact performance
  • Complex context loading logic runs on every execution
  • Recommendation: Consider caching frequently accessed data or implementing request debouncing

3. Error Handling Inconsistencies

  • Some catch blocks don't properly type errors (typescript-error-analysis.md:34-36)
  • Mix of error logging approaches across the codebase
  • Recommendation: Standardize error handling patterns

Security Concerns

1. Sensitive Data Logging (lib/db/data-api-adapter.ts:169-179)

// SQL execution logging removed for security
// SQL success logging removed for security

Good practice, but ensure this is consistently applied across all API routes.

2. Input Validation Edge Cases

  • Context loading validation is thorough, but some edge cases might slip through
  • Recommendation: Add integration tests for malformed execution IDs

Code Quality Issues

1. Complex Function (app/api/chat/stream-final/route.ts:17-222)

  • loadExecutionContext function is 200+ lines with multiple responsibilities
  • Recommendation: Break into smaller, testable functions

2. Magic Numbers (lib/monitoring/context-loading-monitor.ts:28-33)

private readonly ALERT_THRESHOLD = {
  invalidExecutionId: 1,
  missingSystemContext: 3,
  contextLoadFailure: 1,
  slowLoadTime: 5000
};

Consider making these configurable via environment variables.

3. Inconsistent Type Patterns

  • Mix of as unknown as Type and proper type guards
  • Recommendation: Standardize on type guards for better runtime safety

🔧 Specific Recommendations

High Priority

  1. Fix TypeScript errors before merging - especially RDS field type mismatches
  2. Add error boundaries around complex operations like context loading
  3. Implement database query optimization - consider connection pooling or query caching
  4. Add comprehensive tests for the new monitoring and safeguard systems

Medium Priority

  1. Refactor large functions - break loadExecutionContext into smaller pieces
  2. Standardize error handling patterns across the codebase
  3. Add performance monitoring for database queries
  4. Consider rate limiting for chat endpoints

Low Priority

  1. Make alert thresholds configurable
  2. Add JSDoc comments for complex functions
  3. Consider adding request/response schemas for API validation

📊 Test Coverage Assessment

  • Missing: Integration tests for context loading safeguards
  • Missing: End-to-end tests for the chat functionality
  • Good: Pre-commit hooks provide good preventive testing
  • Recommendation: Add tests specifically for the "streaming" execution ID bug prevention

🚀 Overall Assessment

This is a substantial improvement to the codebase with excellent safeguards and monitoring. The snake_case transformation removal and context loading improvements address real user-facing issues.

However, the 207 TypeScript errors are a blocking concern for production deployment. I recommend:

  1. Fix critical TypeScript errors (at minimum the TS2345 type mismatches)
  2. Add integration tests for the new safeguard systems
  3. Performance test the chat functionality under load
  4. Consider phased deployment of these changes

Status: Approve with changes requested - the improvements are valuable but TypeScript errors must be resolved first.


@krishagel
krishagel merged commit eb4e4d3 into dev Jul 25, 2025
5 of 11 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant