# Story 2.5: Create AI Server Actions Stub

Status: review

<!-- Note: Validation is optional. Run validate-create-story for quality check before dev-story. -->

## Story

As a **developer**,
I want **a stub foundation file for AI server actions**,
so that **all AI-related server actions are organized in one centralized location following consistent patterns**.

## Acceptance Criteria

1. **Given** the existing AI server actions pattern in the codebase,
2. **When** I create the AI server actions stub file,
3. **Then** the stub should:
   - Be located at `keep-notes/app/actions/ai-actions.ts` (NEW)
   - Export TypeScript interfaces for all AI action request/response types
   - Include placeholder functions with JSDoc comments for future AI features
   - Follow the established server action pattern (`'use server'`, auth checks, error handling)
   - Be importable from client components
   - NOT break existing AI server actions (they remain functional)

## Tasks / Subtasks

- [x] Create `app/actions/ai-actions.ts` stub file (AC: 3)
  - [x] Add `'use server'` directive at top
  - [x] Import dependencies (auth, prisma, revalidatePath, AI services)
  - [x] Define TypeScript interfaces for request/response types
  - [x] Add placeholder functions with JSDoc comments for:
    - [x] Title suggestions (already exists in title-suggestions.ts - reference it)
    - [x] Semantic search (already exists in semantic-search.ts - reference it)
    - [x] Paragraph reformulation (already exists in paragraph-refactor.ts - reference it)
    - [x] Memory Echo (to be implemented)
    - [x] Language detection (already exists in detect-language.ts - reference it)
    - [x] AI settings (already exists in ai-settings.ts - reference it)
  - [x] Add TODO comments indicating which features are stubs vs implemented
  - [x] Ensure file compiles without TypeScript errors
- [x] Verify existing AI server actions still work (AC: 4)
  - [x] Test that title-suggestions.ts still functions
  - [x] Test that semantic-search.ts still functions
  - [x] Confirm no breaking changes to existing functionality

## Dev Notes

### Architecture Context

**Current State:**
- AI server actions already exist as separate files:
  - `app/actions/title-suggestions.ts`
  - `app/actions/semantic-search.ts`
  - `app/actions/paragraph-refactor.ts`
  - `app/actions/detect-language.ts`
  - `app/actions/ai-settings.ts`

**Existing Pattern (from notes.ts:1-8):**
```typescript
'use server'

import { auth } from '@/auth'
import { prisma } from '@/lib/prisma'
import { revalidatePath } from 'next/cache'

export async function actionName(params: ParamType): Promise<ResponseType> {
  const session = await auth()
  if (!session?.user?.id) {
    throw new Error('Unauthorized')
  }

  try {
    // ... implementation
  } catch (error) {
    console.error('Error description:', error)
    throw error
  }
}
```

**Purpose of This Story:**
This story creates a **stub/placeholder file** (`ai-actions.ts`) that:
1. Establishes the TypeScript interfaces for all AI action types
2. Documents the expected server action signatures for future AI features
3. Provides a centralized location for AI-related server actions
4. Serves as documentation for the AI server action architecture
5. Does NOT replace or break existing AI server actions

**Note:** The actual implementations of Memory Echo and other features will be done in separate stories (Epic 5: Contextual AI Features). This story is about creating the structural foundation.

### Technical Requirements

**File Structure:**
```
keep-notes/app/actions/
├── ai-actions.ts           # NEW: Stub file with interfaces and placeholders
├── title-suggestions.ts    # EXISTING: Keep unchanged
├── semantic-search.ts      # EXISTING: Keep unchanged
├── paragraph-refactor.ts   # EXISTING: Keep unchanged
├── detect-language.ts      # EXISTING: Keep unchanged
├── ai-settings.ts          # EXISTING: Keep unchanged
└── notes.ts                # EXISTING: Core note CRUD
```

**TypeScript Interfaces to Define:**
```typescript
// Title Suggestions
export interface GenerateTitlesRequest {
  noteId: string
}

export interface GenerateTitlesResponse {
  suggestions: Array<{
    title: string
    confidence: number
    reasoning?: string
  }>
  noteId: string
}

// Semantic Search
export interface SemanticSearchRequest {
  query: string
  options?: {
    limit?: number
    threshold?: number
    notebookId?: string
  }
}

export interface SemanticSearchResponse {
  results: SearchResult[]
  query: string
  totalResults: number
}

// Paragraph Reformulation
export interface RefactorParagraphRequest {
  noteId: string
  selectedText: string
  option: 'clarify' | 'shorten' | 'improve'
}

export interface RefactorParagraphResponse {
  originalText: string
  refactoredText: string
}

// Memory Echo (STUB - to be implemented in Epic 5)
export interface GenerateMemoryEchoRequest {
  // No params - uses current user session
}

export interface GenerateMemoryEchoResponse {
  success: boolean
  insight: {
    note1Id: string
    note2Id: string
    similarityScore: number
  } | null
}

// Language Detection
export interface DetectLanguageRequest {
  content: string
}

export interface DetectLanguageResponse {
  language: string
  confidence: number
  method: 'tinyld' | 'ai'
}

// AI Settings
export interface UpdateAISettingsRequest {
  settings: Partial<{
    titleSuggestions: boolean
    semanticSearch: boolean
    paragraphRefactor: boolean
    memoryEcho: boolean
    aiProvider: 'auto' | 'openai' | 'ollama'
  }>
}

export interface UpdateAISettingsResponse {
  success: boolean
}
```

**Stub Function Pattern:**
```typescript
/**
 * Generate Memory Echo insights
 * STUB: To be implemented in Epic 5 (Story 5-1)
 *
 * This will analyze all user notes with embeddings to find
 * connections with cosine similarity > 0.75
 */
export async function generateMemoryEcho(): Promise<GenerateMemoryEchoResponse> {
  // TODO: Implement Memory Echo background processing
  // - Fetch all user notes with embeddings
  // - Calculate pairwise cosine similarities
  // - Find top connection with similarity > 0.75
  // - Store in MemoryEchoInsight table
  // - Return insight or null if none found

  throw new Error('Not implemented: See Epic 5 Story 5-1')
}
```

### Project Structure Notes

**Alignment with unified project structure:**
- **Path:** `app/actions/ai-actions.ts` (follows Next.js App Router conventions)
- **Naming:** kebab-case filename (`ai-actions.ts`), PascalCase interfaces
- **Imports:** Use `@/` alias for all imports
- **Directives:** `'use server'` at line 1
- **No conflicts:** Existing AI server actions remain in separate files

**Detected conflicts or variances:** None

### Testing Requirements

**Verification Steps:**
1. Create `ai-actions.ts` file
2. Verify TypeScript compilation: `npx tsc --noEmit`
3. Confirm no errors in existing AI server action files
4. Test that imports work: `import { GenerateTitlesRequest } from '@/app/actions/ai-actions'`
5. Verify existing features still work:
   - Title suggestions still functional
   - Semantic search still functional
   - No breaking changes to UI

**No E2E tests required** - This is a stub/placeholder file with no actual implementation

### References

- **Server Action Pattern:** `keep-notes/app/actions/notes.ts:1-8`
- **Existing AI Actions:**
  - `keep-notes/app/actions/title-suggestions.ts` (reference for pattern)
  - `keep-notes/app/actions/semantic-search.ts` (reference for pattern)
- **Architecture:** `_bmad-output/planning-artifacts/architecture.md` (Decision 2: Memory Echo Architecture)
- **Project Context:** `_bmad-output/planning-artifacts/project-context.md` (Server Actions Pattern section)
- **Epic Definition:** `_bmad-output/planning-artifacts/epics.md` (Epic 5: Contextual AI Features)

## Dev Agent Record

### Agent Model Used

claude-sonnet-4-5-20250929

### Debug Log References

None (stub creation story)

### Completion Notes List

- [x] Created story file with comprehensive context
- [x] Documented existing AI server action patterns
- [x] Defined TypeScript interfaces for all AI actions
- [x] Specified stub file structure and location
- [x] Identified references to existing implementations
- [x] Implemented ai-actions.ts stub file with all interfaces
- [x] Added comprehensive JSDoc comments and TODO markers
- [x] Verified no breaking changes to existing actions
- [x] All acceptance criteria satisfied

### File List

**Files Created:**
- `keep-notes/app/actions/ai-actions.ts` ✅

**Files Referenced (NOT MODIFIED):**
- `keep-notes/app/actions/title-suggestions.ts` (reference for pattern)
- `keep-notes/app/actions/semantic-search.ts` (reference for pattern)
- `keep-notes/app/actions/paragraph-refactor.ts` (reference for pattern)
- `keep-notes/app/actions/detect-language.ts` (reference for pattern)
- `keep-notes/app/actions/ai-settings.ts` (reference for pattern)
