### Setup Development Environment Source: https://github.com/melagiri/code-insights/blob/master/cli/README.md Commands to clone the repository, install dependencies, build the project, and link the CLI for local testing. ```bash # Clone git clone https://github.com/melagiri/code-insights.git cd code-insights # Install all dependencies pnpm install # Build all packages pnpm build # Link CLI for local testing cd cli && npm link code-insights --version # Watch mode (CLI only) cd cli && pnpm dev ``` -------------------------------- ### Quick Start CLI Commands Source: https://context7.com/melagiri/code-insights/llms.txt Commands for installing the CLI and initializing the automatic analysis hook. ```bash # Try instantly without installation npx @code-insights/cli # Or install globally npm install -g @code-insights/cli code-insights # Install hook for automatic analysis after each Claude Code session code-insights install-hook ``` -------------------------------- ### Quick Start Code Insights CLI Source: https://github.com/melagiri/code-insights/blob/master/cli/README.md Try Code Insights CLI instantly without installation using npx, or install it globally for direct command access. The global install also provides commands to sync sessions and open the dashboard. ```bash # Try instantly (no install needed) npx @code-insights/cli # Or install globally npm install -g @code-insights/cli code-insights # sync sessions + open dashboard code-insights install-hook # auto-sync + auto-analyze on session end ``` -------------------------------- ### Clone and Install Dependencies Source: https://github.com/melagiri/code-insights/blob/master/CONTRIBUTING.md Clone the repository and install project dependencies using pnpm. ```bash git clone https://github.com/melagiri/code-insights.git cd code-insights pnpm install ``` -------------------------------- ### Development Setup Source: https://github.com/melagiri/code-insights/blob/master/README.md Commands to clone, build, and link the project for local development. ```bash git clone https://github.com/melagiri/code-insights.git cd code-insights pnpm install pnpm build cd cli && npm link code-insights --version ``` -------------------------------- ### Launch Dashboard Source: https://github.com/melagiri/code-insights/blob/master/MIGRATION.md Starts the local dashboard server at localhost:7890. ```bash code-insights dashboard ``` -------------------------------- ### Install Code Insights Globally Source: https://github.com/melagiri/code-insights/blob/master/README.md Install the Code Insights CLI globally on your system for easier access. After global installation, you can run the tool using the `code-insights` command. ```bash npm install -g @code-insights/cli ``` -------------------------------- ### Initialize and Run CLI Development Source: https://github.com/melagiri/code-insights/blob/master/CLAUDE.md Commands to set up the CLI environment and start development in watch mode. ```bash cd cli pnpm install # Install dependencies pnpm dev # Watch mode (tsc --watch) pnpm build # Compile TypeScript to dist/ ``` -------------------------------- ### Install Sync-Only Hook Source: https://github.com/melagiri/code-insights/blob/master/cli/README.md Install only the synchronization hook, without enabling auto-analysis. ```bash code-insights install-hook --sync-only ``` -------------------------------- ### Verify CLI Version Source: https://github.com/melagiri/code-insights/blob/master/MIGRATION.md Confirms the installation of version 3.0.0. ```bash code-insights --version # Should print 3.0.0 ``` -------------------------------- ### Install Analysis-Only Hook Source: https://github.com/melagiri/code-insights/blob/master/cli/README.md Install only the analysis hook, without enabling auto-sync. ```bash code-insights install-hook --analysis-only ``` -------------------------------- ### Copilot CLI Event Structure Example Source: https://github.com/melagiri/code-insights/blob/master/docs/source-tool-format-analysis.md This JSONL structure represents various events logged by the Copilot CLI, including session start, user messages, assistant responses, tool executions, and session state changes. Ensure correct parsing of each event type for accurate session state tracking. ```jsonl {"type":"session.start","data":{"sessionId":"...","version":"...","copilotVersion":"...","context":{"cwd":"...","gitRoot":"...","branch":"..."}}} ``` ```jsonl {"type":"user.message","data":{"content":"user prompt"}} ``` ```jsonl {"type":"assistant.turn_start","data":{}} ``` ```jsonl {"type":"assistant.message","data":{"content":"partial text...","toolRequests":[{"toolCallId":"...","name":"...","arguments":"..."}]}} ``` ```jsonl {"type":"tool.execution_start","data":{"toolCallId":"...","model":"...","name":"..."}} ``` ```jsonl {"type":"tool.execution_complete","data":{"toolCallId":"...","success":true,"result":{"content":"..."}}} ``` ```jsonl {"type":"assistant.turn_end","data":{}} ``` ```jsonl {"type":"session.idle","data":{}} ``` ```jsonl {"type":"session.model_change","data":{"model":"gpt-4.1"}} ``` ```jsonl {"type":"session.error","data":{"message":"query execution error"}} ``` -------------------------------- ### Start Development Watch Mode Source: https://github.com/melagiri/code-insights/blob/master/CONTRIBUTING.md Run development servers in watch mode for the CLI, dashboard, or server. ```bash cd cli && pnpm dev ``` ```bash cd dashboard && pnpm dev ``` ```bash cd server && pnpm dev ``` -------------------------------- ### Example Search Query Source: https://github.com/melagiri/code-insights/blob/master/docs/postmortems/2026-03-21-search-escape-bug.md This is an example of a search query used before the ESCAPE clause was added. It demonstrates the basic structure of a LIKE query without specific wildcard escaping. ```sql GET /api/search?q=test&limit=5 → sessions: 5, insights: 5 ``` -------------------------------- ### Install v3 CLI Source: https://github.com/melagiri/code-insights/blob/master/MIGRATION.md Updates the global CLI package to the latest version. ```bash npm install -g @code-insights/cli@latest ``` -------------------------------- ### Link CLI for Local Testing Source: https://github.com/melagiri/code-insights/blob/master/CONTRIBUTING.md Link the CLI package for local testing after installation. ```bash cd cli && npm link ``` -------------------------------- ### Setup Test Database and Mocks Source: https://github.com/melagiri/code-insights/blob/master/docs/superpowers/plans/2026-03-12-test-coverage-75-percent.md Initializes an in-memory SQLite database for testing and mocks necessary modules like database client, telemetry, and LLM. ```typescript import Database from 'better-sqlite3'; import { vi, describe, it, expect, beforeEach, afterEach } from 'vitest'; import { runMigrations } from '@code-insights/cli/db/schema'; let testDb: Database.Database; vi.mock('@code-insights/cli/db/client', () => ({ getDb: () => testDb, closeDb: () => {}, })); vi.mock('@code-insights/cli/utils/telemetry', () => ({ trackEvent: vi.fn(), captureError: vi.fn(), })); vi.mock('../llm/client.js', () => ({ isLLMConfigured: () => false, createLLMClient: vi.fn(), loadLLMConfig: () => null, })); const { createApp } = await import('../index.js'); function initTestDb(): Database.Database { const db = new Database(':memory:'); runMigrations(db); return db; } describe('Analysis routes', () => { beforeEach(() => { testDb = initTestDb(); }); afterEach(() => { testDb.close(); }); ``` -------------------------------- ### Test Prompt Quality Analysis Setup and Validation Source: https://github.com/melagiri/code-insights/blob/master/docs/superpowers/plans/2026-03-12-test-coverage-75-percent.md Tests the initialization, error handling, and successful execution of the prompt quality analysis function. ```typescript describe('analyzePromptQuality', () => { beforeEach(() => { testDb = initTestDb(); mockChat.mockReset(); mockIsConfigured.mockReturnValue(true); }); afterEach(() => { testDb.close(); }); it('returns error when LLM not configured', async () => { mockIsConfigured.mockReturnValue(false); const result = await analyzePromptQuality(makeSession(), [makeMessage()]); expect(result.success).toBe(false); }); it('returns error for empty messages', async () => { const result = await analyzePromptQuality(makeSession(), []); expect(result.success).toBe(false); expect(result.error).toContain('No messages'); }); it('returns error when fewer than 2 user messages', async () => { const result = await analyzePromptQuality(makeSession(), [ makeMessage({ type: 'user' }), makeMessage({ id: 'msg-2', type: 'assistant' }), ]); expect(result.success).toBe(false); expect(result.error).toContain('at least 2'); }); it('successfully analyzes prompt quality', async () => { testDb.prepare(`INSERT INTO projects (id, name, path, last_activity, session_count) VALUES ('proj-test', 'test-project', '/test', datetime('now'), 1)`).run(); testDb.prepare(`INSERT INTO sessions (id, project_id, project_name, project_path, started_at, ended_at, message_count, source_tool) VALUES ('sess-test', 'proj-test', 'test-project', '/test', '2025-06-15T10:00:00Z', '2025-06-15T11:00:00Z', 5, 'claude-code')`).run(); const pqResponse = JSON.stringify({ efficiency_score: 75, assessment: 'Good prompting overall.', message_overhead: 'low', takeaways: [{ before: 'vague request', after: 'specific request', category: 'vague-request' }], findings: [{ category: 'precise-request', type: 'strength', description: 'Clear goals' }], dimension_scores: { context_provision: 80, request_specificity: 70, scope_management: 85, information_timing: 75, correction_quality: 75, }, }); mockChat.mockResolvedValue({ content: pqResponse, usage: { inputTokens: 200, outputTokens: 100 } }); const messages = [ makeMessage({ type: 'user', content: 'First request' }), makeMessage({ id: 'msg-2', type: 'assistant', content: 'Response' }), ``` -------------------------------- ### Setup LLM and DB Mocks for Analysis Tests Source: https://github.com/melagiri/code-insights/blob/master/docs/superpowers/plans/2026-03-12-test-coverage-75-percent.md Sets up mocks for LLM client and database interactions using Vitest. This allows for isolated testing of the analysis functions without relying on actual external services. Ensure the database migrations are run before tests. ```typescript import Database from 'better-sqlite3'; import { vi, describe, it, expect, beforeEach, afterEach } from 'vitest'; import { runMigrations } from '@code-insights/cli/db/schema'; let testDb: Database.Database; vi.mock('@code-insights/cli/db/client', () => ({ getDb: () => testDb, closeDb: () => {}, })); const mockChat = vi.fn(); const mockIsConfigured = vi.fn(() => true); vi.mock('./client.js', () => ({ isLLMConfigured: () => mockIsConfigured(), createLLMClient: () => ({ provider: 'test', model: 'test-model', chat: mockChat, estimateTokens: (text: string) => Math.ceil(text.length / 4), }), })); const { analyzeSession, analyzePromptQuality, findRecurringInsights, extractFacetsOnly } = await import('./analysis.js'); import type { SessionData, SQLiteMessageRow } from './analysis.js'; function initTestDb(): Database.Database { const db = new Database(':memory:'); runMigrations(db); return db; } function makeSession(overrides: Partial = {}): SessionData { return { id: 'sess-test', project_id: 'proj-test', project_name: 'test-project', project_path: '/test', summary: 'Test session', ended_at: '2025-06-15T11:00:00Z', ...overrides, }; } function makeMessage(overrides: Partial = {}): SQLiteMessageRow { return { id: 'msg-1', session_id: 'sess-test', type: 'user', content: 'Hello, please help me with testing.', thinking: null, tool_calls: null, tool_results: null, usage: null, timestamp: '2025-06-15T10:00:00Z', parent_id: null, ...overrides, } as SQLiteMessageRow; } ``` -------------------------------- ### Manage Auto-Sync Hook Source: https://github.com/melagiri/code-insights/blob/master/MIGRATION.md Removes legacy hooks and installs the updated v3 auto-sync hook. ```bash code-insights uninstall-hook # Remove old hook if installed code-insights install-hook # Install v3 hook ``` -------------------------------- ### Code Insights CLI Setup and Configuration Source: https://github.com/melagiri/code-insights/blob/master/cli/README.md Commands for setting up and configuring the Code Insights CLI, including initial sync, customization, viewing configuration, setting LLM providers, and disabling telemetry. ```bash # Sync sessions and open dashboard — no setup required code-insights # Customize settings (optional) — prompts for Claude dir, excluded projects, etc. code-insights init # Show current configuration code-insights config # Configure LLM provider for session analysis (interactive) code-insights config llm # Configure LLM provider with flags (non-interactive) code-insights config llm --provider anthropic --model claude-sonnet-4-20250514 --api-key sk-ant-... # Show current LLM configuration code-insights config llm --show # Set a config value (e.g., disable telemetry) code-insights config set telemetry false ``` -------------------------------- ### Configure Git Hooks for Sync and Analysis Source: https://github.com/melagiri/code-insights/blob/master/docs/plans/2026-03-28-native-analysis-hooks.md Updates `installHookCommand` to include both a 'Stop' hook for synchronization and a new 'SessionEnd' hook for analysis. Also introduces flags for granular control over hook installation. ```typescript // Existing Stop hook (sync) const stopHook: HookConfig = { hooks: [{ type: 'command', command: `node ${cliPath} sync -q` }], }; // New SessionEnd hook (analysis) const sessionEndHook: HookConfig = { hooks: [{ type: 'command', command: `node ${cliPath} insights --hook --native -q`, timeout: 120000, // 2 minutes }], }; ``` -------------------------------- ### View Cross-Session Patterns Source: https://github.com/melagiri/code-insights/blob/master/cli/README.md Get a summary of patterns observed across different sessions. ```bash code-insights stats patterns ``` -------------------------------- ### Start dashboard without syncing Source: https://github.com/melagiri/code-insights/blob/master/docs/PRODUCT.md Launch the code-insights dashboard server without performing an initial sync using the '--no-sync' flag. ```bash code-insights dashboard --no-sync ``` -------------------------------- ### Start a New Feature with Agent Team Source: https://github.com/melagiri/code-insights/blob/master/docs/AGENTS.md Initiates a coordinated agent team for developing non-trivial features. Use this command when modifying 3 or more files or when architectural decisions are involved. ```bash /start-feature "add demo mode onboarding" ``` -------------------------------- ### Start a Code Review for a Pull Request Source: https://github.com/melagiri/code-insights/blob/master/docs/AGENTS.md Triggers a triple-layer code review process for an existing Pull Request. This includes an insider review, an outsider review, and a synthesis phase. ```bash /start-review ``` -------------------------------- ### Implement Native Claude CLI Runner Source: https://github.com/melagiri/code-insights/blob/master/docs/plans/2026-03-28-native-analysis-hooks.md Uses `execFileSync` for security and pipes conversation text via stdin. Requires the 'claude' CLI to be installed and available in the PATH. ```typescript import { execFileSync } from 'child_process'; import { writeFileSync, unlinkSync } from 'fs'; import { tmpdir } from 'os'; import { join } from 'path'; import type { AnalysisRunner, RunAnalysisParams, RunAnalysisResult } from './runner-types.js'; export class ClaudeNativeRunner implements AnalysisRunner { readonly name = 'claude-code-native'; /** Validate claude CLI is available. Throws if not found. */ static validate(): void { try { execFileSync('claude', ['--version'], { stdio: 'pipe' }); } catch { throw new Error( 'claude CLI not found in PATH. --native requires Claude Code to be installed.' ); } } async runAnalysis(params: RunAnalysisParams): Promise { const start = Date.now(); // Write system prompt to temp file const promptFile = join(tmpdir(), `ci-prompt-${Date.now()}.txt`); writeFileSync(promptFile, params.systemPrompt); // Write JSON schema to temp file (if provided) let schemaFile: string | undefined; if (params.jsonSchema) { schemaFile = join(tmpdir(), `ci-schema-${Date.now()}.json`); writeFileSync(schemaFile, JSON.stringify(params.jsonSchema)); } try { const args = [ '-p', '--output-format', 'json', '--append-system-prompt-file', promptFile, '--bare', ]; if (schemaFile) { args.push('--json-schema', schemaFile); } const result = execFileSync('claude', args, { input: params.userPrompt, encoding: 'utf-8', timeout: 120_000, // 2 minute timeout per call maxBuffer: 10 * 1024 * 1024, // 10MB }); return { rawJson: result, durationMs: Date.now() - start, inputTokens: 0, // Counted in session's overall tokens outputTokens: 0, model: 'claude-native', provider: 'claude-code-native', }; } finally { // Clean up temp files try { unlinkSync(promptFile); } catch { /* ignore */ } if (schemaFile) try { unlinkSync(schemaFile); } catch { /* ignore */ } } } } ``` -------------------------------- ### Initialize Configuration Source: https://github.com/melagiri/code-insights/blob/master/MIGRATION.md Creates the local configuration file and SQLite database required for v3. ```bash code-insights init ``` -------------------------------- ### Run Code Insights CLI Source: https://github.com/melagiri/code-insights/blob/master/README.md Execute the Code Insights CLI to start analyzing your AI coding sessions. No installation is required for immediate use. ```bash npx @code-insights/cli ``` -------------------------------- ### Initialize Theme Based on Local Storage and System Preference Source: https://github.com/melagiri/code-insights/blob/master/dashboard/index.html This script initializes the application theme by checking local storage for a stored theme preference. If no preference is found or 'system' is selected, it checks the system's preferred color scheme. The theme is then applied by adding a class to the document's root element. It handles potential errors during local storage access by defaulting to a 'light' theme. ```javascript (function () { try { var stored = localStorage.getItem('code-insights-theme'); var isDark = stored === 'dark'; var isSystem = !stored || stored === 'system' || (stored !== 'light' && stored !== 'dark'); var resolved = isDark || (isSystem && window.matchMedia('(prefers-color-scheme: dark)').matches) ? 'dark' : 'light'; } catch (e) { var resolved = 'light'; } document.documentElement.classList.remove('light', 'dark'); document.documentElement.classList.add(resolved); })(); ``` -------------------------------- ### Build All Packages Source: https://github.com/melagiri/code-insights/blob/master/CONTRIBUTING.md Build all packages within the monorepo. ```bash pnpm build ``` -------------------------------- ### Get Cached Reflection Snapshot Source: https://context7.com/melagiri/code-insights/llms.txt Retrieves a cached snapshot of a reflection for a specific period. Use '__all__' for the project to get a snapshot across all projects. ```bash curl "http://localhost:7890/api/reflect/snapshot?period=2026-W11&project=__all__" ``` -------------------------------- ### Start dashboard without opening browser Source: https://github.com/melagiri/code-insights/blob/master/docs/PRODUCT.md Start the code-insights dashboard server without automatically opening the browser using the '--no-open' flag. ```bash code-insights dashboard --no-open ``` -------------------------------- ### Initialize Test Environment and Seed Helpers Source: https://github.com/melagiri/code-insights/blob/master/docs/superpowers/plans/2026-03-12-test-coverage-75-percent.md Sets up the Vitest mock environment for database and LLM clients, and provides a helper to seed session data into the in-memory SQLite database. ```typescript import Database from 'better-sqlite3'; import { vi, describe, it, expect, beforeEach, afterEach } from 'vitest'; import { runMigrations } from '@code-insights/cli/db/schema'; let testDb: Database.Database; vi.mock('@code-insights/cli/db/client', () => ({ getDb: () => testDb, closeDb: () => {}, })); vi.mock('@code-insights/cli/utils/telemetry', () => ({ trackEvent: vi.fn(), captureError: vi.fn(), })); vi.mock('../llm/client.js', () => ({ isLLMConfigured: () => false, createLLMClient: vi.fn(), loadLLMConfig: () => null, })); const { createApp } = await import('../index.js'); function initTestDb(): Database.Database { const db = new Database(':memory:'); runMigrations(db); return db; } function seedSessionWithFacets(id: string, overrides: Record = {}) { const projId = (overrides.projectId as string) || 'proj-1'; const projName = (overrides.projectName as string) || 'test-project'; testDb.prepare(` INSERT OR IGNORE INTO projects (id, name, path, last_activity, session_count) VALUES (?, ?, ?, datetime('now'), 1) `).run(projId, projName, `/projects/${projName}`); testDb.prepare(` INSERT INTO sessions (id, project_id, project_name, project_path, started_at, ended_at, message_count, source_tool, session_character) VALUES (?, ?, ?, '/test', ?, ?, 5, 'claude-code', ?) `).run(id, projId, projName, (overrides.startedAt as string) || '2025-06-15T10:00:00Z', (overrides.endedAt as string) || '2025-06-15T11:00:00Z', (overrides.sessionCharacter as string) || 'feature_build'); testDb.prepare(` INSERT INTO session_facets (session_id, outcome_satisfaction, workflow_pattern, had_course_correction, course_correction_reason, iteration_count, friction_points, effective_patterns, analysis_version) VALUES (?, ?, ?, 0, NULL, 1, ?, ?, '3.0.0') `).run(id, (overrides.outcomeSatisfaction as string) || 'high', (overrides.workflowPattern as string) || 'plan-then-implement', JSON.stringify((overrides.frictionPoints as unknown[]) || []), JSON.stringify((overrides.effectivePatterns as unknown[]) || [])); } ``` -------------------------------- ### Install Claude Code Hook Source: https://github.com/melagiri/code-insights/blob/master/README.md Install the hook for Claude Code users to enable zero-config, automatic analysis of every session. This ensures all sessions are analyzed without manual intervention. ```bash code-insights install-hook ``` -------------------------------- ### Remove All Hooks Source: https://github.com/melagiri/code-insights/blob/master/cli/README.md Uninstall all previously installed hooks. ```bash code-insights uninstall-hook ``` -------------------------------- ### Preview Sync Operation Source: https://github.com/melagiri/code-insights/blob/master/cli/README.md Use the `--dry-run` flag to preview what would be synced without making any changes. ```bash code-insights sync --dry-run ``` -------------------------------- ### Configure LLM Provider Source: https://github.com/melagiri/code-insights/blob/master/MIGRATION.md Sets up the API credentials for AI-powered session analysis. ```bash code-insights config llm ``` -------------------------------- ### Run Primary Testing Path Source: https://github.com/melagiri/code-insights/blob/master/CONTRIBUTING.md Execute the main testing command which syncs sessions and opens the dashboard. ```bash code-insights ``` -------------------------------- ### Template Literal Escaping Examples Source: https://github.com/melagiri/code-insights/blob/master/docs/REVIEW-SPECIALISTS.md Demonstrates correct and incorrect handling of backslash escaping within JavaScript template literals, specifically when used with SQL ESCAPE clauses. The first example shows a broken pattern, while the second shows the correct way to escape a backslash. ```javascript ESCAPE '\\' ``` ```javascript ESCAPE '\\\\' ``` -------------------------------- ### GET /api/sessions Source: https://context7.com/melagiri/code-insights/llms.txt List sessions with support for filtering, pagination, and search. ```APIDOC ## GET /api/sessions ### Description Retrieves a list of sessions from the local SQLite database with support for filtering, pagination, and searching. ### Method GET ### Endpoint /api/sessions ### Parameters #### Query Parameters - **limit** (integer) - Optional - Number of sessions to return - **offset** (integer) - Optional - Number of sessions to skip - **projectId** (string) - Optional - Filter by project ID - **sourceTool** (string) - Optional - Filter by source tool - **q** (string) - Optional - Search term for title/summary/project - **from** (string) - Optional - Start date (ISO 8601) - **to** (string) - Optional - End date (ISO 8601) ``` -------------------------------- ### Test GET /api/reflect/weeks Source: https://github.com/melagiri/code-insights/blob/master/docs/superpowers/plans/2026-03-12-test-coverage-75-percent.md Placeholder test suite for the reflect weeks endpoint. ```typescript describe('GET /api/reflect/weeks', () => { ``` -------------------------------- ### GET /api/health Source: https://github.com/melagiri/code-insights/blob/master/docs/ARCHITECTURE.md Standard health check endpoint to verify server status. ```APIDOC ## GET /api/health ### Description Performs a server health check. ### Method GET ### Endpoint /api/health ``` -------------------------------- ### Configure CLI Settings Source: https://github.com/melagiri/code-insights/blob/master/docs/PRODUCT.md Use these commands to manage local configuration, including LLM provider settings and telemetry preferences. ```bash code-insights config # Show current configuration code-insights config set # Set config value (e.g., telemetry) code-insights config llm # Configure LLM provider interactively code-insights config llm --provider openai # Set provider directly code-insights config llm --model gpt-4o # Set model code-insights config llm --api-key # Set API key code-insights config llm --base-url # Set custom base URL (Ollama, proxies) code-insights config llm --show # Show current LLM configuration ``` -------------------------------- ### Dashboard and Configuration CLI Commands Source: https://context7.com/melagiri/code-insights/llms.txt Commands for managing the web dashboard and CLI configuration. ```bash # Start dashboard server and open browser code-insights dashboard # Start dashboard without auto-sync code-insights dashboard --no-sync # Open dashboard in browser (server must be running) code-insights open # Show current configuration code-insights config # Configure LLM provider interactively code-insights config llm # Show sync statistics code-insights status # Delete all local data code-insights reset --confirm ``` -------------------------------- ### View Today's Sessions Source: https://github.com/melagiri/code-insights/blob/master/cli/README.md Show details for today's sessions, including time, cost, and model used. ```bash code-insights stats today ``` -------------------------------- ### Count Deleted Sessions Source: https://context7.com/melagiri/code-insights/llms.txt Get the count of sessions that have been soft-deleted, optionally filtered by project. ```bash curl "http://localhost:7890/api/sessions/deleted/count?projectId=abc123" ``` -------------------------------- ### View Model Usage Distribution Source: https://github.com/melagiri/code-insights/blob/master/cli/README.md Visualize the distribution of model usage and associated costs. ```bash code-insights stats models ``` -------------------------------- ### Test GET /api/facets/missing-pq and /outdated-pq Source: https://github.com/melagiri/code-insights/blob/master/docs/superpowers/plans/2026-03-12-test-coverage-75-percent.md Validates prompt quality insight presence and metadata structure. ```typescript describe('GET /api/facets/missing-pq', () => { it('returns sessions with insights but no prompt_quality insight', async () => { seedProject('proj-1', 'alpha'); seedSession('sess-1', 'proj-1'); seedInsight('sess-1', 'proj-1', 'decision'); const app = createApp(); const res = await app.request('/api/facets/missing-pq?period=all'); const body = await res.json(); expect(body.count).toBe(1); expect(body.sessionIds).toContain('sess-1'); }); it('excludes sessions that have prompt_quality insights', async () => { seedProject('proj-1', 'alpha'); seedSession('sess-1', 'proj-1'); seedInsight('sess-1', 'proj-1', 'decision'); seedInsight('sess-1', 'proj-1', 'prompt_quality'); const app = createApp(); const res = await app.request('/api/facets/missing-pq?period=all'); const body = await res.json(); expect(body.count).toBe(0); }); }); describe('GET /api/facets/outdated-pq', () => { it('detects PQ insights missing findings array in metadata', async () => { seedProject('proj-1', 'alpha'); seedSession('sess-1', 'proj-1'); seedInsight('sess-1', 'proj-1', 'prompt_quality', JSON.stringify({ efficiency_score: 70, message_overhead: 'moderate', })); const app = createApp(); const res = await app.request('/api/facets/outdated-pq?period=all'); const body = await res.json(); expect(body.count).toBe(1); }); it('does not flag PQ insights with findings array', async () => { seedProject('proj-1', 'alpha'); seedSession('sess-1', 'proj-1'); seedInsight('sess-1', 'proj-1', 'prompt_quality', JSON.stringify({ efficiency_score: 70, findings: [{ category: 'vague-request', type: 'deficit' }], })); const app = createApp(); const res = await app.request('/api/facets/outdated-pq?period=all'); const body = await res.json(); expect(body.count).toBe(0); }); }); ``` -------------------------------- ### Test GET /api/facets/outdated Source: https://github.com/melagiri/code-insights/blob/master/docs/superpowers/plans/2026-03-12-test-coverage-75-percent.md Validates detection of facets missing required attribution or category fields. ```typescript describe('GET /api/facets/outdated', () => { it('detects facets with missing attribution on friction points', async () => { seedProject('proj-1', 'alpha'); seedSession('sess-1', 'proj-1'); seedFacets('sess-1', { friction_points: [{ category: 'wrong-approach', description: 'bad', severity: 5 }], }); const app = createApp(); const res = await app.request('/api/facets/outdated?period=all'); const body = await res.json(); expect(body.count).toBe(1); expect(body.sessionIds).toContain('sess-1'); }); it('detects facets with missing category on effective patterns', async () => { seedProject('proj-1', 'alpha'); seedSession('sess-1', 'proj-1'); seedFacets('sess-1', { effective_patterns: [{ description: 'good pattern', confidence: 80 }], }); const app = createApp(); const res = await app.request('/api/facets/outdated?period=all'); const body = await res.json(); expect(body.count).toBe(1); }); it('returns empty when all facets are up to date', async () => { seedProject('proj-1', 'alpha'); seedSession('sess-1', 'proj-1'); seedFacets('sess-1', { friction_points: [{ category: 'wrong-approach', description: 'bad', severity: 5, attribution: 'user-actionable' }], effective_patterns: [{ category: 'structured-planning', description: 'good', confidence: 80, driver: 'user-driven' }], }); const app = createApp(); const res = await app.request('/api/facets/outdated?period=all'); const body = await res.json(); expect(body.count).toBe(0); }); }); ``` -------------------------------- ### View Cost Breakdown Source: https://github.com/melagiri/code-insights/blob/master/cli/README.md Analyze the cost breakdown by project and the models used. ```bash code-insights stats cost ``` -------------------------------- ### Get Global Cumulative Usage Stats Source: https://context7.com/melagiri/code-insights/llms.txt Fetches global cumulative usage statistics for the service. ```bash curl "http://localhost:7890/api/analytics/usage" ``` -------------------------------- ### Get Current LLM Config Source: https://context7.com/melagiri/code-insights/llms.txt Retrieves the current LLM configuration. The API key will be masked in the response. ```bash curl "http://localhost:7890/api/config/llm" ``` -------------------------------- ### View Project Detail Cards Source: https://github.com/melagiri/code-insights/blob/master/cli/README.md Display detailed cards for each project, summarizing key metrics. ```bash code-insights stats projects ``` -------------------------------- ### Get Single Session by ID Source: https://context7.com/melagiri/code-insights/llms.txt Fetch a specific session's data using its unique identifier. ```bash curl "http://localhost:7890/api/sessions/abc-123-def" ``` -------------------------------- ### Initialize Test Database and Seed Helpers Source: https://github.com/melagiri/code-insights/blob/master/docs/superpowers/plans/2026-03-12-test-coverage-75-percent.md Sets up an in-memory SQLite database for testing and provides helper functions to seed projects, sessions, facets, and insights. Mocks external dependencies like the database client and telemetry. ```typescript import Database from 'better-sqlite3'; import { vi, describe, it, expect, beforeEach, afterEach } from 'vitest'; import { runMigrations } from '@code-insights/cli/db/schema'; let testDb: Database.Database; vi.mock('@code-insights/cli/db/client', () => ({ getDb: () => testDb, closeDb: () => {}, })); vi.mock('@code-insights/cli/utils/telemetry', () => ({ trackEvent: vi.fn(), captureError: vi.fn(), })); vi.mock('../llm/client.js', () => ({ isLLMConfigured: () => false, createLLMClient: vi.fn(), loadLLMConfig: () => null, })); const { createApp } = await import('../index.js'); function initTestDb(): Database.Database { const db = new Database(':memory:'); runMigrations(db); return db; } function seedProject(id: string, name: string) { testDb.prepare(` INSERT INTO projects (id, name, path, last_activity, session_count) VALUES (?, ?, ?, datetime('now'), 1) `).run(id, name, `/projects/${name}`); } function seedSession(id: string, projectId: string, overrides: Record = {}) { const defaults = { project_name: 'test-project', project_path: '/test', started_at: '2025-06-15T10:00:00Z', ended_at: '2025-06-15T11:00:00Z', message_count: 5, source_tool: 'claude-code', }; const row = { ...defaults, ...overrides }; testDb.prepare(` INSERT INTO sessions (id, project_id, project_name, project_path, started_at, ended_at, message_count, source_tool) VALUES (?, ?, ?, ?, ?, ?, ?, ?) `).run(id, projectId, row.project_name, row.project_path, row.started_at, row.ended_at, row.message_count, row.source_tool); } function seedFacets(sessionId: string, overrides: Partial<{ outcome_satisfaction: string; workflow_pattern: string | null; had_course_correction: number; friction_points: unknown[]; effective_patterns: unknown[]; }> = {}) { const defaults = { outcome_satisfaction: 'high', workflow_pattern: 'plan-then-implement', had_course_correction: 0, friction_points: [], effective_patterns: [], }; const d = { ...defaults, ...overrides }; testDb.prepare(` INSERT INTO session_facets (session_id, outcome_satisfaction, workflow_pattern, had_course_correction, course_correction_reason, iteration_count, friction_points, effective_patterns, analysis_version) VALUES (?, ?, ?, ?, NULL, 1, ?, ?, '3.0.0') `).run(sessionId, d.outcome_satisfaction, d.workflow_pattern, d.had_course_correction, JSON.stringify(d.friction_points), JSON.stringify(d.effective_patterns)); } function seedInsight(sessionId: string, projectId: string, type: string = 'decision', metadata: string | null = null) { testDb.prepare(` INSERT INTO insights (id, session_id, project_id, project_name, type, title, content, summary, bullets, confidence, source, metadata, timestamp, created_at, scope, analysis_version) VALUES (?, ?, ?, 'test-project', ?, 'Test', 'Content', 'Summary', '[]', 0.85, 'llm', ?, datetime('now'), datetime('now'), 'session', '3.0.0') `).run(`ins-${sessionId}-${type}`, sessionId, projectId, type, metadata); } ``` -------------------------------- ### Stream Prompt Quality Analysis Source: https://context7.com/melagiri/code-insights/llms.txt Initiate a prompt quality analysis that streams results in real-time. ```bash curl "http://localhost:7890/api/analysis/prompt-quality/stream?sessionId=abc-123" ``` -------------------------------- ### Test GET /api/reflect/snapshot Source: https://github.com/melagiri/code-insights/blob/master/docs/superpowers/plans/2026-03-12-test-coverage-75-percent.md Tests retrieval of reflect snapshots, verifying behavior when snapshots are missing or present in the database. ```typescript describe('GET /api/reflect/snapshot', () => { it('returns null when no snapshot exists', async () => { const app = createApp(); const res = await app.request('/api/reflect/snapshot?period=2026-W10'); expect(res.status).toBe(200); const body = await res.json(); expect(body.snapshot).toBeNull(); }); it('returns saved snapshot', async () => { testDb.prepare(` INSERT INTO reflect_snapshots (period, project_id, results_json, generated_at, window_start, window_end, session_count, facet_count) VALUES ('2026-W10', '__all__', '{"friction-wins":{"section":"friction-wins"}}', datetime('now'), '2026-03-02', '2026-03-09', 10, 5) `).run(); const app = createApp(); const res = await app.request('/api/reflect/snapshot?period=2026-W10'); const body = await res.json(); expect(body.snapshot).not.toBeNull(); expect(body.snapshot.period).toBe('2026-W10'); expect(body.snapshot.sessionCount).toBe(10); }); }); ``` -------------------------------- ### Test GET /api/reflect/results Source: https://github.com/melagiri/code-insights/blob/master/docs/superpowers/plans/2026-03-12-test-coverage-75-percent.md Tests the aggregation logic for reflect results, covering both empty and populated database states. ```typescript describe('Reflect routes', () => { beforeEach(() => { testDb = initTestDb(); }); afterEach(() => { testDb.close(); }); describe('GET /api/reflect/results', () => { it('returns aggregated data with zero sessions', async () => { const app = createApp(); const res = await app.request('/api/reflect/results?period=all'); expect(res.status).toBe(200); const body = await res.json(); expect(body.totalSessions).toBe(0); }); it('returns aggregated friction and patterns', async () => { seedSessionWithFacets('sess-1', { frictionPoints: [{ category: 'wrong-approach', description: 'bad', severity: 5, attribution: 'user-actionable' }], effectivePatterns: [{ category: 'structured-planning', description: 'good', confidence: 80, driver: 'user-driven' }], }); const app = createApp(); const res = await app.request('/api/reflect/results?period=all'); const body = await res.json(); expect(body.totalSessions).toBe(1); expect(body.frictionCategories.length).toBeGreaterThan(0); expect(body.effectivePatterns.length).toBeGreaterThan(0); }); ``` -------------------------------- ### Backfill Facets for Sessions (Streaming) Source: https://context7.com/melagiri/code-insights/llms.txt Initiate a backfill process for facet analysis on specified sessions. Supports forcing the update and provides streaming progress. ```bash curl -X POST "http://localhost:7890/api/facets/backfill" \ -H "Content-Type: application/json" \ -d '{"sessionIds": ["abc-123", "def-456"], "force": true}' ``` -------------------------------- ### Test GET /api/facets/missing Source: https://github.com/melagiri/code-insights/blob/master/docs/superpowers/plans/2026-03-12-test-coverage-75-percent.md Validates that the endpoint correctly identifies sessions containing insights but lacking associated facets. ```typescript describe('GET /api/facets/missing', () => { it('returns session IDs with insights but no facets', async () => { seedProject('proj-1', 'alpha'); seedSession('sess-1', 'proj-1'); seedSession('sess-2', 'proj-1'); seedInsight('sess-1', 'proj-1'); seedInsight('sess-2', 'proj-1'); seedFacets('sess-1'); // sess-1 has facets, sess-2 does not const app = createApp(); const res = await app.request('/api/facets/missing?period=all'); expect(res.status).toBe(200); const body = await res.json(); expect(body.sessionIds).toEqual(['sess-2']); expect(body.count).toBe(1); }); it('returns empty when all sessions have facets', async () => { seedProject('proj-1', 'alpha'); seedSession('sess-1', 'proj-1'); seedInsight('sess-1', 'proj-1'); seedFacets('sess-1'); const app = createApp(); const res = await app.request('/api/facets/missing?period=all'); const body = await res.json(); expect(body.count).toBe(0); }); }); ``` -------------------------------- ### Build Project Across Workspace Source: https://github.com/melagiri/code-insights/blob/master/docs/AGENTS.md Run this command to build the project and ensure it passes across the entire workspace. This is a mandatory step before creating a Pull Request. ```bash pnpm build # Must pass across the workspace ``` -------------------------------- ### Get Analysis Usage/Cost for a Session Source: https://context7.com/melagiri/code-insights/llms.txt Retrieve information about the usage or cost associated with the analysis performed for a specific session. ```bash curl "http://localhost:7890/api/analysis/usage?sessionId=abc-123" ``` -------------------------------- ### Get Raw Aggregated Results Source: https://context7.com/melagiri/code-insights/llms.txt Retrieves raw aggregated reflection results for a specified period. No LLM synthesis is applied. ```bash curl "http://localhost:7890/api/reflect/results?period=30d" ```