### InsightLoop MCP Server v2 - Local Development Setup Source: https://github.com/thiagobutignon/clean-insightloop/blob/main/README.md Guides users through the local development setup for InsightLoop MCP Server v2. This involves cloning the repository, installing dependencies, configuring environment variables, running migrations, seeding data, and starting the development server. ```bash # Clone the repository git clone https://github.com/yourusername/insightloop-mcp-server-v2.git cd insightloop-mcp-server-v2 # Install dependencies npm install # Setup environment variables cp .env.example .env # Edit .env with your configuration # Run database migrations npm run db:migrate # Seed initial data (development only) npm run db:seed # Start development server npm run dev ``` -------------------------------- ### Prompt Engineering Guide for MCP Source: https://github.com/thiagobutignon/clean-insightloop/blob/main/epic/002-examples.md This guide covers the fundamentals, techniques, and implementation of prompt engineering within the MCP framework. It details prompt structure, advanced strategies like CoT and ToT, optimization methods, and evaluation metrics. ```APIDOC Prompt Engineering Fundamentals: Elements of an effective prompt Structure and organization Role definition and task context Output formatting Fundamental Techniques: Zero-shot prompting Few-shot prompting Chain-of-Thought (CoT) Self-consistency Advanced Techniques: Role prompting and personas Prompt chaining Tree-of-Thought (ToT) Knowledge generation Optimization: Clarity optimization Data separation Hallucination prevention Token efficiency MCP Implementation: Prompt service architecture Multi-tenant registry Testing framework Clean Architecture integration Metrics and Evaluation: Quality metrics Response relevance Accuracy measurement Continuous improvement ``` -------------------------------- ### InsightLoop MCP Server v2 - Getting Started with Docker Source: https://github.com/thiagobutignon/clean-insightloop/blob/main/README.md Provides instructions for setting up and running the InsightLoop MCP Server v2 using Docker Compose. This includes building the services, viewing logs, and stopping the services. ```bash docker-compose up -d docker-compose logs -f app docker-compose down ``` -------------------------------- ### Install OpenTelemetry Dependencies Source: https://github.com/thiagobutignon/clean-insightloop/blob/main/epic/007-observability-examples.md Installs core OpenTelemetry packages, auto-instrumentation, various exporters (Prometheus, Jaeger, OTLP), specific instrumentations (HTTP, Express, gRPC, pg, Redis), and the NestJS integration package. ```bash # Core OpenTelemetry npm install --save @opentelemetry/api @opentelemetry/sdk-node # Instrumentação Automática npm install --save @opentelemetry/auto-instrumentations-node # Exportadores npm install --save @opentelemetry/exporter-prometheus npm install --save @opentelemetry/exporter-jaeger npm install --save @opentelemetry/exporter-trace-otlp-http npm install --save @opentelemetry/exporter-metrics-otlp-http # Instrumentações Específicas npm install --save @opentelemetry/instrumentation-http npm install --save @opentelemetry/instrumentation-express npm install --save @opentelemetry/instrumentation-grpc npm install --save @opentelemetry/instrumentation-pg npm install --save @opentelemetry/instrumentation-redis # Para NestJS npm install --save nestjs-otel ``` -------------------------------- ### Claude Code - Configuration Source: https://github.com/thiagobutignon/clean-insightloop/blob/main/epic/002-examples.md Details the advanced configuration options, including CLAUDE.md project context, .mcp.json server setup, settings.json customization, and hooks for automation. ```TypeScript // CLAUDE.md project context // .mcp.json server setup // settings.json customization // Hooks and automation ``` -------------------------------- ### Install Packages in Sandbox (TypeScript) Source: https://github.com/thiagobutignon/clean-insightloop/blob/main/epic/010-ai-integration.md This function iterates through a list of packages, enqueuing an 'npm install' command for each. It then executes the command in the sandbox and enqueues the output or error, indicating success or failure for each package installation. ```TypeScript private async installPackages( packages: string[], sandboxId: string, controller: ReadableStreamDefaultController ): Promise { for (const pkg of packages) { controller.enqueue(JSON.stringify({ type: 'package-install', name: pkg, message: `$ npm install ${pkg}`, }) + '\n'); try { const result = await this.sandboxService.runCommand(sandboxId, `npm install ${pkg}`); controller.enqueue(JSON.stringify({ type: 'package-output', name: pkg, output: result.stdout, success: result.exitCode === 0, }) + '\n'); } catch (error) { controller.enqueue(JSON.stringify({ type: 'package-error', name: pkg, error: (error as Error).message, }) + '\n'); } } } ``` -------------------------------- ### Observability Layer Components Source: https://github.com/thiagobutignon/clean-insightloop/blob/main/epic/002-examples.md Examples of setting up OpenTelemetry for tracing, metrics, and logging, including automatic and manual instrumentation, and integration with frameworks. ```typescript import { NodeSDK } from '@opentelemetry/sdk-node'; import { OTLPTraceExporter } from '@opentelemetry/exporter-trace-otlp-grpc'; import { PrometheusExporter } from '@opentelemetry/exporter-prometheus'; import { ConsoleLogger } from '@opentelemetry/core'; const sdk = new NodeSDK({ traceExporter: new OTLPTraceExporter({ url: 'http://localhost:4317' }), metricExporter: new PrometheusExporter({ port: 9090 }), // logger: new ConsoleLogger() }); sdk.start(); import { trace, context, SpanStatusCode } from '@opentelemetry/api'; const tracer = trace.getTracer('my-app-tracer'); // Manual instrumentation const processData = (data: string) => { const span = tracer.startSpan('processData'); span.setAttribute('input.data', data); try { // Simulate processing const result = data.toUpperCase(); span.addEvent('Data processed', { result }); span.setStatus({ code: SpanStatusCode.OK }); return result; } catch (error) { span.setStatus({ code: SpanStatusCode.ERROR, message: error.message }); throw error; } finally { span.end(); } }; // Auto-instrumentation for Express import express from 'express'; import { ExpressInstrumentation } from '@opentelemetry/instrumentation-express'; import { HttpInstrumentation } from '@opentelemetry/instrumentation-http'; const app = express(); const expressInstrumentation = new ExpressInstrumentation(); const httpInstrumentation = new HttpInstrumentation(); expressInstrumentation.enable(); httpInstrumentation.enable(); // Example of database instrumentation (e.g., with pg) // import { PgInstrumentation } from '@opentelemetry/instrumentation-pg'; // const pgInstrumentation = new PgInstrumentation(); // pgInstrumentation.enable(); ``` -------------------------------- ### Husky Git Hooks Setup and Protocol Source: https://github.com/thiagobutignon/clean-insightloop/blob/main/epic/015-claude-code-resources.md Guides on setting up Husky for Git hooks, including pre-commit and pre-push scripts, and outlines a protocol for handling CI failures. ```bash # Setup npx husky install npx husky add .husky/pre-commit "npm test" npx husky add .husky/pre-push "npm run lint" # Protocolo para CI quebrado # 1. Explicar o problema # 2. Propor e implementar fix # 3. Verificar bugs similares # 4. Limpar código temporário ``` -------------------------------- ### Bootstrap Application with OpenTelemetry Source: https://github.com/thiagobutignon/clean-insightloop/blob/main/epic/007-observability-examples.md Ensures the OpenTelemetry tracing configuration is imported and initialized before the application is created and started, guaranteeing that all subsequent operations are instrumented. ```typescript // src/main/server.ts import './shared/infrastructure/telemetry/tracing'; // Importar primeiro! import { createApp } from './config/app'; const startServer = async () => { const app = await createApp(); const port = process.env.PORT || 3000; app.listen(port, () => { console.log(`🚀 Server running on port ${port}`); }); }; startServer(); ``` -------------------------------- ### Data Processing Example with Claude Source: https://github.com/thiagobutignon/clean-insightloop/blob/main/epic/012-system-prompts-reference.md A Python example demonstrating data processing using NumPy, as might be used with the Claude AI assistant. ```python # Exemplo de processamento de dados com Claude import numpy as np def process_data(data): # Processar dados usando NumPy return np.mean(data) if __name__ == "__main__": sample_data = [1, 2, 3, 4, 5] result = process_data(sample_data) print(f"A média é: {result}") ``` -------------------------------- ### Data Layer Components Source: https://github.com/thiagobutignon/clean-insightloop/blob/main/epic/002-examples.md Examples of data access implementations, database connections, external service integrations, cryptography, and caching within the Data Layer. ```typescript import { EntityRepository } from 'typeorm'; import { AccountEntity } from '../../domain/entities/AccountEntity'; import { AccountModel } from '../../domain/models/AccountModel'; import { AccountRepository } from '../../domain/protocols/AccountRepository'; @EntityRepository(AccountEntity) export class TypeOrmAccountRepository implements AccountRepository { async add(accountData: AccountModel): Promise { const account = new AccountEntity(); account.id = accountData.id; account.email = accountData.email; account.password = accountData.password; await account.save(); } async findByEmail(email: string): Promise { const account = await AccountEntity.findOne({ where: { email } }); if (!account) { return null; } return { id: account.id, email: account.email, password: account.password, }; } } import axios from 'axios'; interface ExternalApiResult { // ... structure of the external API response } export class AxiosHttpClient { async get(url: string): Promise { const response = await axios.get(url); return response.data; } } import * as bcrypt from 'bcrypt'; export class BcryptAdapter { constructor(private readonly salt: number) {} async encrypt(value: string): Promise { return await bcrypt.hash(value, this.salt); } async compare(value: string, hash: string): Promise { return await bcrypt.compare(value, hash); } } ``` -------------------------------- ### Context Engineering Best Practices - MCP Source: https://github.com/thiagobutignon/clean-insightloop/blob/main/epic/002-examples.md Provides best practices for Context Engineering specifically for MCP. ```APIDOC Context Engineering Best Practices for MCP: - Strategies for effective context management - Techniques for optimizing context flow - Guidelines for context-aware development ``` -------------------------------- ### Presentation Layer Components Source: https://github.com/thiagobutignon/clean-insightloop/blob/main/epic/002-examples.md Examples of controllers handling HTTP requests, validators for input data, and middlewares for request interception in the Presentation Layer. ```typescript import { Controller, HttpRequest, HttpResponse } from '../protocols/http'; import { AddAccountUseCase } from '../../domain/usecases/AddAccountUseCase'; import { badRequest, ok, serverError } from '../helpers/httpHelper'; import { ValidationComposite } from '../validation/ValidationComposite'; export class SignUpController implements Controller { constructor( private readonly addAccountUseCase: AddAccountUseCase, private readonly validation: ValidationComposite ) {} async handle(request: HttpRequest): Promise { const error = this.validation.validate(request.body); if (error) { return badRequest(error); } try { const { name, email, password } = request.body; const account = await this.addAccountUseCase.execute({ name, email, password }); return ok(account); } catch (error) { return serverError(error as Error); } } } import { Validator } from '../protocols/Validator'; export class EmailValidator implements Validator { validate(input: any): Error | null { const emailRegex = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/; if (!emailRegex.test(input.email)) { return new Error('Invalid email format'); } return null; } } export class RequiredFieldValidator implements Validator { constructor(private readonly fieldName: string) {} validate(input: any): Error | null { if (!input[this.fieldName]) { return new Error(`The ${this.fieldName} field is required`); } return null; } } import { Middleware } from '../protocols/Middleware'; import { HttpRequest, HttpResponse } from '../protocols/http'; export class AuthMiddleware implements Middleware { constructor(private readonly loadAccountByToken: LoadAccountByToken) {} async execute(httpRequest: HttpRequest): Promise { const accessToken = httpRequest.headers?.['x-access-token']; if (accessToken) { const account = await this.loadAccountByToken.loadByToken(accessToken); if (account) { Object.assign(httpRequest, { account }); return ok({ accountId: account.id }); } } return forbidden(new AccessDeniedError()); } } ``` -------------------------------- ### Model Context Protocol (MCP) Layer Integration Source: https://github.com/thiagobutignon/clean-insightloop/blob/main/epic/002-examples.md Examples demonstrating integration with the Model Context Protocol (MCP) for managing model contexts and data flow. ```typescript // Assuming an MCP client library exists import { MCPClient } from '@example/mcp-client'; interface UserContext { userId: string; permissions: string[]; } interface ProductContext { productId: string; price: number; } const mcpClient = new MCPClient({ // MCP client configuration }); async function getUserData(userId: string) { const context: UserContext = await mcpClient.getContext('user', userId); // Use context.userId and context.permissions console.log(`User ID: ${context.userId}, Permissions: ${context.permissions.join(', ')}`); return context; } async function getProductDetails(productId: string) { const context: ProductContext = await mcpClient.getContext('product', productId); // Use context.productId and context.price console.log(`Product ID: ${context.productId}, Price: ${context.price}`); return context; } // Example of updating a context async function updateUserPermissions(userId: string, newPermissions: string[]) { await mcpClient.updateContext('user', userId, { permissions: newPermissions }); console.log(`Updated permissions for user ${userId}`); } ``` -------------------------------- ### Clean Architecture Command Examples Source: https://github.com/thiagobutignon/clean-insightloop/blob/main/epic/011-claude-code.md Provides examples of bash commands for common Clean Architecture tasks, such as implementing use cases, analyzing dependencies, refactoring legacy code, generating tests, and updating documentation. ```bash # Implementação de novos casos de uso > "Create a new use case for user registration following our Clean Architecture" # Análise de dependências > "Check if we have any dependency inversions violations" # Refactoring de código legado > "Refactor this service to follow Clean Architecture principles" # Criação de testes > "Generate comprehensive tests for the authentication domain layer" # Documentação > "Update the README with our current Clean Architecture implementation" ``` -------------------------------- ### Initial Project Setup - First Conversation Message Source: https://github.com/thiagobutignon/clean-insightloop/blob/main/epic/012-system-prompts-reference.md Provides guidelines for the initial message of a project's conversation, focusing on understanding user intent, gathering inspiration, defining initial features, setting up visual styles (colors, gradients, animations), and configuring essential project files like `tailwind.config.ts` and `index.css`. ```yaml Primeira Mensagem da Conversa: - Tomar tempo para pensar sobre o que o usuário quer construir - Escrever o que evoca e quais designs bonitos existentes podem servir de inspiração - Listar quais recursos serão implementados nesta primeira versão - Listar possíveis cores, gradientes, animações, fontes e estilos - Nunca implementar feature para alternar entre modo claro e escuro - Listar arquivos em que trabalhará, incluindo tailwind.config.ts e index.css - Editar primeiro os arquivos tailwind.config.ts e index.css se cores padrão não combinarem - Criar arquivos para novos componentes necessários - Garantir que o app seja bonito e funcione sem erros de build ``` -------------------------------- ### TraceService Implementation Source: https://github.com/thiagobutignon/clean-insightloop/blob/main/epic/007-observability-examples.md Provides a service for creating and managing OpenTelemetry spans. It includes methods to start spans, get the active span, and execute functions within a span's context, with support for both synchronous and asynchronous operations. Dependencies include '@opentelemetry/api'. ```typescript // src/shared/infrastructure/telemetry/trace-service.ts import { trace, Tracer, Span, SpanStatusCode, SpanKind, context, SpanOptions, Context } from '@opentelemetry/api'; export class TraceService { private readonly tracer: Tracer; constructor(serviceName: string = 'clean-node-api') { this.tracer = trace.getTracer(serviceName, '1.0.0'); } startSpan(name: string, options?: SpanOptions): Span { return this.tracer.startSpan(name, options); } getActiveSpan(): Span | undefined { return trace.getSpan(context.active()); } withSpan(span: Span, fn: () => T): T { return context.with(trace.setSpan(context.active(), span), fn); } async traceAsync( name: string, fn: (span: Span) => Promise, options?: SpanOptions ): Promise { const span = this.startSpan(name, options); try { const result = await this.withSpan(span, () => fn(span)); span.setStatus({ code: SpanStatusCode.OK }); return result; } catch (error) { span.recordException(error as Error); span.setStatus({ code: SpanStatusCode.ERROR, message: (error as Error).message, }); throw error; } finally { span.end(); } } trace( name: string, fn: (span: Span) => T, options?: SpanOptions ): T { const span = this.startSpan(name, options); try { const result = this.withSpan(span, () => fn(span)); span.setStatus({ code: SpanStatusCode.OK }); return result; } catch (error) { span.recordException(error as Error); span.setStatus({ code: SpanStatusCode.ERROR, message: (error as Error).message, }); throw error; } finally { span.end(); } } } export const traceService = new TraceService(); ``` -------------------------------- ### Claude Code Integration Commands and Configuration Source: https://github.com/thiagobutignon/clean-insightloop/blob/main/epic/002-examples.md Details on using slash commands for orchestration, configuring CLAUDE.md, managing parallelization settings, and token budget. ```bash # Example of a slash command for agent orchestration /orchestrate --agent-type DomainTestAgent --task "test_user_creation" # Example CLAUDE.md configuration snippet { "parallelization": { "max_concurrency": 5 }, "token_budget": { "max_tokens": 4000 } } ``` -------------------------------- ### Express i18n Middleware Setup Source: https://github.com/thiagobutignon/clean-insightloop/blob/main/epic/008-i18n-examples.md Sets up Express middleware for i18next, integrating language detection and providing translation helpers to the response locals. ```typescript import { Request, Response, NextFunction } from 'express'; import i18next from 'i18next'; import middleware from 'i18next-http-middleware'; export const i18nMiddleware = middleware.handle(i18next); export const languageMiddleware = (req: Request, res: Response, next: NextFunction) => { // Adicionar helper de tradução ao response res.locals.t = req.t; res.locals.language = req.language; // Adicionar headers de idioma res.setHeader('Content-Language', req.language); next(); }; ``` -------------------------------- ### System Prompts Reference - Comparative Analysis Source: https://github.com/thiagobutignon/clean-insightloop/blob/main/epic/002-examples.md Presents a comparative analysis of common architectural structures, tool calling patterns, communication systems, and their application in the project. ```APIDOC Comparative Analysis: Architectural Structures Tool Calling Patterns Communication Systems Project Application ``` -------------------------------- ### System Prompts Reference - Manus Source: https://github.com/thiagobutignon/clean-insightloop/blob/main/epic/002-examples.md Details the Manus system, including its sandbox capabilities, execution and communication tools, operational rules, deployment, and integration with browser and shell. ```APIDOC Manus System: Capabilities: - Sandbox execution environment - Execution and communication tools Operational Rules: - Deployment procedures Integration: - Browser integration - Shell integration ``` -------------------------------- ### Detect and Install Packages (TypeScript) Source: https://github.com/thiagobutignon/clean-insightloop/blob/main/epic/010-ai-integration.md This snippet detects package names from a buffer using regular expressions, either individually or within a block. Detected packages are added to a list and enqueued for installation, ensuring no duplicates are added. It handles both single package detection and bulk detection from a comma or newline-separated list. ```TypeScript while ((match = packageRegex.exec(buffer)) !== null) { const packageName = match[1].trim(); if (packageName && !packagesToInstall.includes(packageName)) { packagesToInstall.push(packageName); controller.enqueue(JSON.stringify({ type: 'package-detected', name: packageName, message: `📦 Package detected: ${packageName}`, }) + '\n'); } } // Detectar packages em bloco const packagesBlockRegex = /(.*?)/gs; const packagesMatch = packagesBlockRegex.exec(buffer); if (packagesMatch) { const packagesText = packagesMatch[1]; const packages = packagesText .split(/[\n,]/) .map(pkg => pkg.trim()) .filter(pkg => pkg && !packagesToInstall.includes(pkg)); packages.forEach(pkg => { if (!packagesToInstall.includes(pkg)) { packagesToInstall.push(pkg); controller.enqueue(JSON.stringify({ type: 'package-detected', name: pkg, message: `📦 Package detected: ${pkg}`, }) + '\n'); } }); } ``` -------------------------------- ### System Prompts Reference - Claude Source: https://github.com/thiagobutignon/clean-insightloop/blob/main/epic/002-examples.md Provides guidelines for Claude's response quality, code and documentation standards, error handling, and personalization. ```APIDOC Claude AI Assistant: Response Guidelines: - Quality standards - Code and documentation standards Error Handling: - Customization options ``` -------------------------------- ### System Prompts Reference - Claude Code Source: https://github.com/thiagobutignon/clean-insightloop/blob/main/epic/002-examples.md Outlines Claude Code's features, including native MCP integration, commands for Clean Architecture, TypeScript and Python SDKs, and project configuration and workflows. ```APIDOC Claude Code Agentic Tool: Integration: - Native MCP integration - Commands for Clean Architecture SDKs: - TypeScript SDK - Python SDK Configuration: - Project setup - Workflows ``` -------------------------------- ### Next.js i18n Configuration with next-intl Source: https://github.com/thiagobutignon/clean-insightloop/blob/main/epic/008-i18n-examples.md Configures internationalization for a Next.js application using next-intl. Defines supported locales, message loading, time zone, and date/number formatting. This setup is crucial for multi-language support. ```typescript import { notFound } from 'next/navigation'; import { getRequestConfig } from 'next-intl/server'; export const locales = ['en', 'pt', 'es'] as const; export type Locale = typeof locales[number]; export default getRequestConfig(async ({ locale }) => { if (!locales.includes(locale as any)) notFound(); return { messages: (await import(`../messages/${locale}.json`)).default, timeZone: 'America/Sao_Paulo', now: new Date(), formats: { dateTime: { short: { day: 'numeric', month: 'short', year: 'numeric' } }, number: { precise: { minimumFractionDigits: 2, maximumFractionDigits: 2 } } } }; }); ``` -------------------------------- ### Zero-Shot Prompting Example Source: https://github.com/thiagobutignon/clean-insightloop/blob/main/epic/014-prompt-engineering-guide.md Implementa a técnica de Zero-Shot Prompting, onde o modelo é instruído a realizar uma tarefa sem exemplos prévios. Inclui um método estático `create` para tarefas genéricas e um método `classifySentiment` para um caso de uso específico. ```typescript export class ZeroShotPrompt { static create(task: string): string { return `${task}`; } // Exemplo de uso static classifySentiment(text: string): string { return `Classify the sentiment of the following text as positive, negative, or neutral: Text: "${text}" Sentiment:` } } ``` -------------------------------- ### Recommended Development Workflow Source: https://github.com/thiagobutignon/clean-insightloop/blob/main/epic/015-claude-code-resources.md Outlines the recommended workflow for the project, covering initial setup with CLAUDE.md and MCP servers, development tasks using vibe-tools and Claude Code, and the review/deploy process. ```bash # Configurar CLAUDE.md # Instalar ferramentas essenciais npm install -g vibe-tools ccusage ccexp # Configurar MCP servers claude mcp add --transport sse basic-memory ./basic-memory # Planejar implementação vibe-tools plan "implement authentication" # Desenvolver com Claude Code # Usar /todo para tracking # Testar continuamente npm run test:watch # Análise de código vibe-tools repo "review recent changes" # Criar PR /create-pull-request # Deploy npm run deploy ``` -------------------------------- ### Docker Compose for Observability Stack Source: https://github.com/thiagobutignon/clean-insightloop/blob/main/epic/007-observability-examples.md Defines a Docker Compose setup for an observability stack, including Jaeger for distributed tracing, Prometheus for metrics collection and alerting, Grafana for visualization, and an OpenTelemetry Collector for processing telemetry data. ```yaml # docker-compose.observability.yml version: '3.8' services: jaeger: image: jaegertracing/all-in-one:latest ports: - "16686:16686" # Jaeger UI - "14268:14268" # Collector HTTP environment: - COLLECTOR_ZIPKIN_HOST_PORT=:9411 prometheus: image: prom/prometheus:latest ports: - "9091:9090" volumes: - ./prometheus.yml:/etc/prometheus/prometheus.yml command: - '--config.file=/etc/prometheus/prometheus.yml' grafana: image: grafana/grafana:latest ports: - "3001:3000" environment: - GF_SECURITY_ADMIN_PASSWORD=admin volumes: - grafana-storage:/var/lib/grafana otel-collector: image: otel/opentelemetry-collector:latest ports: - "4317:4317" # OTLP gRPC - "4318:4318" # OTLP HTTP - "8888:8888" # Prometheus metrics volumes: - ./otel-collector-config.yml:/etc/otel-collector-config.yml command: ["--config=/etc/otel-collector-config.yml"] volumes: grafana-storage: ``` -------------------------------- ### Redis Adapter for Caching Source: https://github.com/thiagobutignon/clean-insightloop/blob/main/epic/004-data-examples.md Implements the CacheStore protocol using Redis for caching data. It supports connecting, setting, getting, deleting, clearing, and disconnecting from the Redis client. Requires a running Redis instance. ```typescript // src/shared/infrastructure/cache/redis-adapter.ts import { createClient, RedisClientType } from 'redis' import { CacheStore } from '@/shared/domain/protocols' export class RedisAdapter implements CacheStore { private client?: RedisClientType async connect(): Promise { this.client = createClient({ url: process.env.REDIS_URL || 'redis://localhost:6379' }) await this.client.connect() } async set(key: string, value: any, expirationInSeconds?: number): Promise { if (!this.client) throw new Error('Redis client not connected') const serialized = JSON.stringify(value) if (expirationInSeconds) { await this.client.setEx(key, expirationInSeconds, serialized) } else { await this.client.set(key, serialized) } } async get(key: string): Promise { if (!this.client) throw new Error('Redis client not connected') const data = await this.client.get(key) if (!data) return null return JSON.parse(data) as T } async delete(key: string): Promise { if (!this.client) throw new Error('Redis client not connected') await this.client.del(key) } async clear(): Promise { if (!this.client) throw new Error('Redis client not connected') await this.client.flushAll() } async disconnect(): Promise { if (this.client) { await this.client.quit() } } } ``` -------------------------------- ### Email Value Object with Validation Source: https://github.com/thiagobutignon/clean-insightloop/blob/main/epic/003-domain-examples.md A value object representing an email address. It enforces email format validation upon instantiation and provides methods for getting the value and checking equality with other Email objects. ```typescript // src/features/authentication/domain/value-objects/email.ts export class Email { private readonly value: string constructor(email: string) { if (!this.isValid(email)) { throw new InvalidParamError('email') } this.value = email.toLowerCase() } private isValid(email: string): boolean { const emailRegex = /^[^s@]+@[^s@]+.[^s@]+$/ return emailRegex.test(email) } getValue(): string { return this.value } equals(other: Email): boolean { return this.value === other.value } } ``` -------------------------------- ### Middleware Chain: Defining Request Flow Source: https://github.com/thiagobutignon/clean-insightloop/blob/main/epic/005-presentation-examples.md Illustrates the setup of a middleware chain for handling cross-cutting concerns like content type, CORS, and authentication before reaching the main route handlers. This ensures a well-defined request processing pipeline. ```typescript const authRoutes = Router() authRoutes.use(adaptMiddleware(makeContentTypeMiddleware())) authRoutes.use(adaptMiddleware(makeCorsMiddleware())) authRoutes.use(adaptMiddleware(makeAuthMiddleware())) authRoutes.post('/surveys', adaptRoute(makeAddSurveyController())) authRoutes.get('/surveys', adaptRoute(makeLoadSurveysController())) ``` -------------------------------- ### Prompt Engineering vs. Context Engineering Source: https://github.com/thiagobutignon/clean-insightloop/blob/main/epic/014-prompt-engineering-guide.md Diferenciação conceitual entre Prompt Engineering e Context Engineering, destacando o foco de cada um na interação com modelos de linguagem. Prompt Engineering foca na instrução direta, enquanto Context Engineering otimiza o contexto dinâmico. ```plaintext Prompt Engineering: output = f(prompt + input) Context Engineering: output = f(Assemble(instructions, knowledge, tools, memory, state, query)) ``` -------------------------------- ### Claude Code - SDKs Source: https://github.com/thiagobutignon/clean-insightloop/blob/main/epic/002-examples.md Lists the available SDKs for programmatic integration, including TypeScript SDK, Python SDK, GitHub Actions integration, and CI/CD automation. ```TypeScript // TypeScript SDK // Python SDK // GitHub Actions integration // CI/CD automation ``` -------------------------------- ### Process Buffer Content for Code Generation (TypeScript) Source: https://github.com/thiagobutignon/clean-insightloop/blob/main/epic/010-ai-integration.md This function orchestrates the code generation process by parsing a buffer for files, commands, and packages. It then sequentially installs packages, creates files, and executes commands within a sandbox, providing progress updates via a controller. Finally, it sends a completion message with the results. ```TypeScript private async processBufferContent( buffer: string, packagesToInstall: string[], filesToCreate: { path: string; content: string }[], commandsToRun: string[], sandboxId: string, controller: ReadableStreamDefaultController ): Promise { // 1. Extrair arquivos const fileRegex = /(.*?)/gs; let fileMatch; while ((fileMatch = fileRegex.exec(buffer)) !== null) { filesToCreate.push({ path: fileMatch[1], content: fileMatch[2].trim(), }); } // 2. Extrair comandos const commandRegex = /([^<]+)/g; let commandMatch; while ((commandMatch = commandRegex.exec(buffer)) !== null) { commandsToRun.push(commandMatch[1].trim()); } // 3. Instalar packages if (packagesToInstall.length > 0) { controller.enqueue(JSON.stringify({ type: 'step', step: 1, message: `📦 Installing ${packagesToInstall.length} packages...`, }) + '\n'); await this.installPackages(packagesToInstall, sandboxId, controller); } // 4. Criar arquivos if (filesToCreate.length > 0) { controller.enqueue(JSON.stringify({ type: 'step', step: 2, message: `📝 Creating ${filesToCreate.length} files...`, }) + '\n'); await this.createFiles(filesToCreate, sandboxId, controller); } // 5. Executar comandos if (commandsToRun.length > 0) { controller.enqueue(JSON.stringify({ type: 'step', step: 3, message: `⚡ Executing ${commandsToRun.length} commands...`, }) + '\n'); await this.executeCommands(commandsToRun, sandboxId, controller); } // 6. Finalizar controller.enqueue(JSON.stringify({ type: 'complete', message: '✅ Code generation completed successfully!', results: { packagesInstalled: packagesToInstall, filesCreated: filesToCreate.map(f => f.path), commandsExecuted: commandsToRun, }, }) + '\n'); } ``` -------------------------------- ### Example English Error Translations Source: https://github.com/thiagobutignon/clean-insightloop/blob/main/epic/008-i18n-examples.md Provides an example of a JSON file containing error messages for the 'en' locale, categorized by domain (authentication, validation, database). ```json { "authentication": { "invalidCredentials": "Invalid email or password", "accountNotFound": "Account not found", "tokenExpired": "Your session has expired", "unauthorized": "You are not authorized to access this resource" }, "validation": { "required": "{{field}} is required", "email": "Please provide a valid email address", "minLength": "{{field}} must be at least {{min}} characters", "maxLength": "{{field}} must not exceed {{max}} characters", "pattern": "{{field}} format is invalid" }, "database": { "connectionError": "Failed to connect to database", "queryError": "Database query failed", "transactionError": "Transaction failed" } } ``` -------------------------------- ### Claude Code Resources and Ecosystem Source: https://github.com/thiagobutignon/clean-insightloop/blob/main/epic/002-examples.md This section details the Claude Code ecosystem, including primary CLI tools, MCP integration, SDKs, slash commands for task automation, browser automation with Stagehand, analysis and monitoring tools, and best practices for development. ```APIDOC Primary CLI Tools: vibe-tools (repo, plan, doc, web, browser) Basic Memory MCP MCP Marketplace tools Interactive CLIs (ccexp, cusage) MCP Integration: Server configuration Transports (SSE, HTTP, stdio) OAuth 2.0 and authentication Multi-tenancy SDKs and Integrations: TypeScript SDK Python SDK (cchooks) GitHub Actions VS Code extensions Slash Commands: Project management (/todo) Version control (/create-pull-request) Documentation (/add-to-changelog) Git hooks (/husky) Browser Automation (Stagehand): Web scraping and testing Chrome debug mode Video recording Interaction automation Analysis and Monitoring: Token usage tracking Cost analysis Community leaderboards Performance metrics Best Practices: CLAUDE.md configuration Project structure Testing workflows Development patterns ``` -------------------------------- ### AWS MCP Server Installation and Execution Source: https://github.com/thiagobutignon/clean-insightloop/blob/main/epic/015-claude-code-resources.md Instructions for installing and running the AWS MCP server using uv and Python. Includes commands for system installation and different execution methods, including specifying the transport protocol. ```bash # Installation with uv uv pip install --system -e . uv pip install --system -e ".[dev]" # Run server python -m aws_mcp_server AWS_MCP_TRANSPORT=sse python -m aws_mcp_server mcp run src/aws_mcp_server/server.py ``` -------------------------------- ### AI Integration Layer - Vercel AI SDK Source: https://github.com/thiagobutignon/clean-insightloop/blob/main/epic/002-examples.md Explains the use of the Vercel AI SDK for streaming and tool calling, supporting StreamText with SSE, native tool calling, MCP client integration, and multi-provider support. ```TypeScript // StreamText with SSE // Native tool calling // MCP client integration // Multi-provider support ``` -------------------------------- ### Domain Layer Components Source: https://github.com/thiagobutignon/clean-insightloop/blob/main/epic/002-examples.md Examples of core business objects in the Domain Layer, including Entities, Value Objects, Errors, Models, and Protocols/Interfaces. ```typescript /** * Represents a User entity. */ interface UserEntity { id: string; name: string; email: string; } /** * Represents an Email value object. */ class Email { constructor(private readonly value: string) { if (!value.includes('@')) { throw new Error('Invalid email format'); } } getValue(): string { return this.value; } } /** * Represents an Invalid Param Error. */ class InvalidParamError extends Error { constructor(paramName: string) { super(`Invalid parameter: ${paramName}`); this.name = 'InvalidParamError'; } } /** * Represents an Account Model. */ interface AccountModel { id: string; email: string; password: string; } /** * Protocol for Account Repository. */ interface AccountRepository { add(accountData: AccountModel): Promise; findByEmail(email: string): Promise; } /** * Protocol for Authentication Use Case. */ interface AuthenticationUseCase { authenticate(params: AuthenticationParams): Promise; } interface AuthenticationParams { email: string; password: string; } interface AuthenticationResult { accessToken: string; } ``` -------------------------------- ### AI Integration Layer - Sandbox Services Source: https://github.com/thiagobutignon/clean-insightloop/blob/main/epic/002-examples.md Explains the sandbox services implementation, inspired by E2B, utilizing Docker containers, WebContainers support, and resource isolation for secure execution. ```TypeScript // E2B-inspired implementation // Docker containers // WebContainers support // Resource isolation ```