### Start Development Stack Source: https://github.com/rutvij26/incident-orchestration-agent/blob/main/README.md Initializes the full development environment including Temporal, Postgres, Loki, Grafana, and the agent worker using npm scripts. ```bash npm run dev:all ``` -------------------------------- ### Worker and CLI Commands Source: https://context7.com/rutvij26/incident-orchestration-agent/llms.txt Commands for starting the Temporal worker, running the agent, and performing various utility operations. ```APIDOC ## CLI Commands ### Starting Services - **Start the full observability stack (Loki, Grafana, Temporal, Postgres):** ```bash npm run dev:stack ``` - **Start the Temporal worker (processes workflows):** ```bash npm run dev:agent ``` ### Incident Management - **Run a single incident sweep:** ```bash npm run run ``` ### RAG (Retrieval-Augmented Generation) - **Index repository for RAG:** ```bash npm run rag:index ``` - **Refresh RAG index (only changed files):** ```bash npm run rag:refresh ``` ``` -------------------------------- ### CLI Commands for Agent Management Source: https://context7.com/rutvij26/incident-orchestration-agent/llms.txt Common CLI commands to manage the observability stack, start the Temporal worker, and perform indexing tasks. ```bash npm run dev:stack npm run dev:agent npm run run npm run rag:index npm run rag:refresh ``` -------------------------------- ### Configure Environment Variables Source: https://github.com/rutvij26/incident-orchestration-agent/blob/main/README.md Sets up the necessary environment configuration for the agent, including API keys for LLM providers and GitHub integration credentials. ```bash cp .env.example .env # Set OPENAI_API_KEY (or ANTHROPIC_API_KEY / GEMINI_API_KEY) # Set GITHUB_TOKEN, GITHUB_OWNER, GITHUB_REPO for issue creation ``` -------------------------------- ### Run Development Environment with Docker Compose Source: https://github.com/rutvij26/incident-orchestration-agent/blob/main/docs/architecture.md Command for contributors to launch the development environment by overriding the production image references with local build contexts. ```bash docker-compose -f docker-compose.yml -f docker-compose.dev.yml up ``` -------------------------------- ### Retrieve Application Configuration Source: https://context7.com/rutvij26/incident-orchestration-agent/llms.txt Demonstrates how to fetch and validate application settings using Zod-backed configuration management. This ensures type safety for environment variables like LLM providers and database connection strings. ```typescript import { getConfig } from "./lib/config.js"; const config = getConfig(); console.log(config.LLM_PROVIDER); // "auto" | "openai" | "anthropic" | "gemini" console.log(config.AUTO_FIX_MODE); // "off" | "on" console.log(config.AUTO_ESCALATE_FROM); // "low" | "medium" | "high" | "critical" | "none" console.log(config.LOKI_URL); // "http://localhost:3100" console.log(config.POSTGRES_URL); // PostgreSQL connection string console.log(config.RAG_TOP_K); // Number of chunks to retrieve (default: 6) ``` -------------------------------- ### LLM Connector Interface and Usage Source: https://context7.com/rutvij26/incident-orchestration-agent/llms.txt This section demonstrates the implementation of the LlmConnector interface by various LLM providers (OpenAI, Anthropic, Gemini). It shows how to instantiate these connectors with API keys and models, and how to use the common 'complete' method for prompt completion, with configurable parameters like maxTokens and temperature. ```typescript import { OpenAILlmConnector } from "./connectors/llm/openai.js"; import { AnthropicLlmConnector } from "./connectors/llm/anthropic.js"; import { GeminiLlmConnector } from "./connectors/llm/gemini.js"; // OpenAI connector const openai = new OpenAILlmConnector( process.env.OPENAI_API_KEY, "gpt-4o-mini" ); // Anthropic connector const anthropic = new AnthropicLlmConnector( process.env.ANTHROPIC_API_KEY, "claude-sonnet-4-5" ); // Gemini connector const gemini = new GeminiLlmConnector( process.env.GEMINI_API_KEY, "gemini-1.5-flash" ); // All connectors use the same interface const response = await openai.complete( "Analyze this incident and return JSON with summary, root_cause, recommended_actions...", { maxTokens: 512, temperature: 0.2 } ); ``` -------------------------------- ### Run Project Tests Source: https://github.com/rutvij26/incident-orchestration-agent/blob/main/README.md Executes the test suite and health checks to verify the agent's business logic and integration stability. ```bash npm run test npm run healthcheck ``` -------------------------------- ### Environment Configuration Variables Source: https://context7.com/rutvij26/incident-orchestration-agent/llms.txt Key environment variables required for configuring services, LLM providers, GitHub integration, and auto-fix policies. ```bash TEMPORAL_ADDRESS=localhost:7233 POSTGRES_URL=postgresql://agentic:agentic@localhost:5432/agentic LOKI_URL=http://localhost:3100 LLM_PROVIDER=auto GITHUB_TOKEN=ghp_... AUTO_FIX_MODE=on AUTO_ESCALATE_FROM=high ``` -------------------------------- ### Resolve and Execute LLM Connectors with Fallback Source: https://context7.com/rutvij26/incident-orchestration-agent/llms.txt Shows how to resolve LLM connectors based on configuration and execute them using a fallback mechanism. This ensures high availability by automatically trying secondary providers if the primary fails. ```typescript import { resolveLlmConnectors, withFallback } from "./connectors/registry.js"; import { getConfig } from "./lib/config.js"; const config = getConfig(); const connectors = resolveLlmConnectors(config); const response = await withFallback(connectors, async (connector) => { return connector.complete( "Analyze this error log and return JSON with root cause...", { maxTokens: 512, temperature: 0.2 } ); }); ``` -------------------------------- ### Define Database Schema for Configuration and Workflows Source: https://github.com/rutvij26/incident-orchestration-agent/blob/main/docs/architecture.md Creates the necessary PostgreSQL tables to store agent configurations, track workflow execution history, and manage scheduling intervals. These tables support dynamic configuration updates and audit logging for the orchestration agent. ```sql -- Config store: replaces .env for all non-bootstrap settings CREATE TABLE agent_config ( key TEXT PRIMARY KEY, value TEXT NOT NULL, -- AES-256-GCM encrypted if sensitive=true config_group TEXT NOT NULL, -- 'general'|'integrations'|'autofix'|'rag'|'advanced' sensitive BOOLEAN NOT NULL DEFAULT FALSE, updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW() ); -- Per-run audit log CREATE TABLE workflow_runs ( id TEXT PRIMARY KEY, -- Temporal workflow ID status TEXT NOT NULL, -- 'running'|'completed'|'failed' started_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), completed_at TIMESTAMPTZ, incidents_found INTEGER DEFAULT 0, issues_created INTEGER DEFAULT 0, error_message TEXT, trigger TEXT NOT NULL DEFAULT 'schedule' -- 'schedule'|'manual' ); -- Scheduling config managed via dashboard CREATE TABLE schedule_config ( id TEXT PRIMARY KEY DEFAULT 'default', enabled BOOLEAN NOT NULL DEFAULT TRUE, interval_minutes INTEGER NOT NULL DEFAULT 15, lookback_minutes INTEGER NOT NULL DEFAULT 15, updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW() ); ``` -------------------------------- ### Deploy Incident Orchestration Agent via Docker Compose Source: https://github.com/rutvij26/incident-orchestration-agent/blob/main/docs/architecture.md A simple command to download the production docker-compose configuration and launch the entire SRE dashboard stack. This eliminates the need for manual cloning or environment variable configuration. ```bash curl -O https://raw.githubusercontent.com/rutvij26/incident-orchestration-agent/main/docker-compose.yml docker-compose up ``` -------------------------------- ### LLM Functions - verifyFixPatch Source: https://context7.com/rutvij26/incident-orchestration-agent/llms.txt LLM-based verification that the generated patch correctly implements the plan. ```APIDOC ## verifyFixPatch ### Description LLM-based verification that the generated patch correctly implements the plan. ### Method POST (Assumed, as it verifies a patch) ### Endpoint /llm/verify-fix-patch (Assumed) ### Parameters #### Request Body - **incident** (object) - Required - The incident object. - **plan** (object) - Required - The fix plan generated by `generateFixPlan`. - **diff** (string) - Required - The generated unified diff patch to verify. ### Request Example ```json { "incident": { "id": "abc-123", "title": "Incident: error (error:/api/orders)", "severity": "high", "evidence": ["{\"msg\":\"Simulated error\",\"route\":\"/api/orders\"}"], "firstSeen": "1704067200000000000", "lastSeen": "1704067260000000000", "count": 10 }, "plan": { "files": ["src/api/orders.ts"], "approach": "Add null check before accessing order.items", "reasoning": "Root cause is null reference in the order processing logic." }, "diff": "diff --git a/src/api/orders.ts b/src/api/orders.ts\nindex ...\n--- a/src/api/orders.ts\n+++ b/src/api/orders.ts\n@@ -10,5 +10,7 @@\n function processOrder(order) {\n // ... existing code ...\n const items = order.items;\n+ if (!items) {\n+ return; // Or throw an error, depending on desired behavior\n+ }\n // ... more code ...\n }" } ``` ### Response #### Success Response (200) - **valid** (boolean) - Indicates if the patch is considered valid. - **confidence** (number) - The confidence score of the verification (0-1). - **issues** (array of strings) - Any identified issues with the patch. - **verdict** (string) - A summary verdict of the verification. #### Response Example ```json { "valid": true, "confidence": 0.95, "issues": [], "verdict": "Patch correctly implements the fix plan." } ``` #### Response Example (Invalid Patch) ```json { "valid": false, "confidence": 0.8, "issues": ["Patch does not address the root cause."], "verdict": "Patch rejected by verification." } ``` ``` -------------------------------- ### Postgres Memory Management Source: https://context7.com/rutvij26/incident-orchestration-agent/llms.txt APIs for initializing the PostgreSQL database schema and persisting incident data. ```APIDOC ## POST /api/memory/init ### Description Initializes the PostgreSQL database schema with all required tables for storing incident data, auto-fix attempts, agent configuration, workflow runs, and schedule configurations. ### Method POST ### Endpoint /api/memory/init ### Parameters None ### Request Example ```json {} ``` ### Response #### Success Response (200) - **message** (string) - Confirmation message indicating successful initialization. #### Response Example ```json { "message": "PostgreSQL schema initialized successfully." } ``` ## POST /api/memory/incidents ### Description Persists detected incidents to the database. ### Method POST ### Endpoint /api/memory/incidents ### Parameters #### Request Body - **incidents** (array) - Required - A list of incident objects to save. ### Request Example ```json [ { "id": "incident-123", "summary": "High CPU usage on web server", "severity": "high" } ] ``` ### Response #### Success Response (200) - **message** (string) - Confirmation message. #### Response Example ```json { "message": "Incidents saved successfully." } ``` ## POST /api/memory/autofix ### Description Records an auto-fix attempt outcome in the database. ### Method POST ### Endpoint /api/memory/autofix ### Parameters #### Request Body - **incidentId** (string) - Required - The ID of the incident. - **issueNumber** (integer) - Optional - The GitHub issue number associated with the auto-fix. - **outcome** (string) - Required - The outcome of the auto-fix attempt (e.g., "pr_created", "failed", "skipped"). - **reason** (string) - Optional - The reason for failure, if applicable. - **fixabilityScore** (float) - Optional - The score indicating the fixability of the incident. ### Request Example ```json { "incidentId": "abc-123", "issueNumber": 42, "outcome": "pr_created", "fixabilityScore": 0.75 } ``` ### Response #### Success Response (200) - **message** (string) - Confirmation message. #### Response Example ```json { "message": "Auto-fix attempt recorded successfully." } ``` ``` -------------------------------- ### Environment Configuration Source: https://context7.com/rutvij26/incident-orchestration-agent/llms.txt Environment variables for configuring the agent's core services, LLM providers, GitHub integration, auto-fix, and escalation policies. ```APIDOC ## Environment Variables ### Core Services - **TEMPORAL_ADDRESS**: Address of the Temporal server (e.g., `localhost:7233`). - **POSTGRES_URL**: PostgreSQL connection URL (e.g., `postgresql://agentic:agentic@localhost:5432/agentic`). - **LOKI_URL**: Loki logging endpoint URL (e.g., `http://localhost:3100`). - **LOKI_QUERY**: Default Loki query for fetching logs (e.g., `{job="demo-services"}`). ### LLM Providers - **LLM_PROVIDER**: Primary LLM provider to use (e.g., `auto`, `openai`, `anthropic`, `gemini`). - **LLM_CONNECTORS**: Comma-separated list of fallback LLM connectors (e.g., `openai,anthropic`). - **OPENAI_API_KEY**: API key for OpenAI. - **ANTHROPIC_API_KEY**: API key for Anthropic. ### GitHub Integration - **GITHUB_TOKEN**: Personal Access Token for GitHub. - **GITHUB_OWNER**: GitHub repository owner. - **GITHUB_REPO**: GitHub repository name. ### Auto-fix Configuration - **AUTO_FIX_MODE**: Enable or disable auto-fix (e.g., `on`, `off`). - **AUTO_FIX_SEVERITY**: Minimum incident severity to attempt auto-fix (e.g., `high`). - **AUTO_FIX_MIN_SCORE**: Minimum fixability score required for auto-fix. - **AUTO_FIX_TEST_COMMAND**: Command to run tests before applying a fix (e.g., `npm run test`). ### Escalation Policy - **AUTO_ESCALATE_FROM**: Minimum severity level for automatic escalation (e.g., `low`, `medium`, `high`, `critical`, `none`). ``` -------------------------------- ### Execute Incident Orchestration Workflow Source: https://context7.com/rutvij26/incident-orchestration-agent/llms.txt Demonstrates how to trigger the main incident orchestration workflow using the Temporal client. It configures lookback parameters and severity thresholds for incident detection. ```typescript import { Client, Connection } from "@temporalio/client"; import { incidentOrchestrationWorkflow } from "./workflows/incidentWorkflow.js"; const connection = await Connection.connect({ address: "localhost:7233" }); const client = new Client({ namespace: "default", connection }); const result = await client.workflow.execute(incidentOrchestrationWorkflow, { taskQueue: "incident-orchestration", workflowId: `incident-run-${Date.now()}`, workflowExecutionTimeout: "2 minutes", args: [{ lookbackMinutes: 15, query: '{job="demo-services"}', autoEscalateFrom: "high" }] }); console.log(`Detected ${result.incidents.length} incidents`); console.log(`Created ${result.issuesCreated} GitHub issues`); ``` -------------------------------- ### Configuration API Source: https://github.com/rutvij26/incident-orchestration-agent/blob/main/docs/architecture.md Endpoints for managing the agent's configuration, including fetching all configurations, specific group configurations, and validating configurations. ```APIDOC ## GET /api/config ### Description Retrieves all configuration settings for the agent. ### Method GET ### Endpoint /api/config ### Parameters None ### Request Example None ### Response #### Success Response (200) - **config** (object) - A JSON object containing all configuration settings. #### Response Example ```json { "config": { "log_source": "loki", "escalation_policy": "default", "api_keys": { "github": "***" } } } ``` ## GET /api/config/[group] ### Description Retrieves configuration settings for a specific group. ### Method GET ### Endpoint /api/config/[group] ### Parameters #### Path Parameters - **group** (string) - Required - The name of the configuration group to retrieve. ### Request Example None ### Response #### Success Response (200) - **config** (object) - A JSON object containing the configuration settings for the specified group. #### Response Example ```json { "config": { "embedding_model": "openai", "chunk_size": 1024 } } ``` ## PUT /api/config ### Description Updates all configuration settings for the agent. ### Method PUT ### Endpoint /api/config ### Parameters #### Request Body - **config** (object) - Required - A JSON object containing the updated configuration settings. ### Request Example ```json { "config": { "log_source": "loki", "escalation_policy": "new_policy" } } ``` ### Response #### Success Response (200) - **message** (string) - Confirmation message indicating the configuration was updated. #### Response Example ```json { "message": "Configuration updated successfully." } ``` ## PUT /api/config/[group] ### Description Updates configuration settings for a specific group. ### Method PUT ### Endpoint /api/config/[group] ### Parameters #### Path Parameters - **group** (string) - Required - The name of the configuration group to update. #### Request Body - **config** (object) - Required - A JSON object containing the updated configuration settings for the group. ### Request Example ```json { "config": { "embedding_model": "anthropic", "chunk_size": 512 } } ``` ### Response #### Success Response (200) - **message** (string) - Confirmation message indicating the configuration was updated. #### Response Example ```json { "message": "Configuration for group updated successfully." } ``` ## POST /api/config/validate ### Description Validates configuration settings using Zod schemas without applying changes. ### Method POST ### Endpoint /api/config/validate ### Parameters #### Request Body - **config** (object) - Required - A JSON object containing the configuration settings to validate. ### Request Example ```json { "config": { "log_source": "invalid_source", "escalation_policy": "default" } } ``` ### Response #### Success Response (200) - **isValid** (boolean) - Indicates if the configuration is valid. - **errors** (array) - An array of validation errors, if any. #### Response Example ```json { "isValid": false, "errors": [ "Invalid log_source value." ] } ``` ``` -------------------------------- ### Loki Source Connector for Log Fetching Source: https://context7.com/rutvij26/incident-orchestration-agent/llms.txt Demonstrates how to use the LokiSourceConnector to fetch logs from Grafana Loki. It requires the Loki endpoint URL and a LogQL query. The fetchLogs method accepts time range and limit parameters, returning an array of log events with timestamps, messages, and labels. ```typescript import { LokiSourceConnector } from "./connectors/source/loki.js"; const loki = new LokiSourceConnector( "http://localhost:3100", '{job="demo-services"}' // LogQL query ); const logs = await loki.fetchLogs({ start: new Date(Date.now() - 15 * 60 * 1000), end: new Date(), limit: 500 }); // Returns array of LogEvent objects logs.forEach(log => { console.log(`[${log.timestamp}] ${log.message}`); console.log("Labels:", log.labels); }); ``` -------------------------------- ### Aggregate Logs from Multiple Sources Source: https://context7.com/rutvij26/incident-orchestration-agent/llms.txt Demonstrates parallel log fetching and deduplication from multiple configured log backends. This is essential for centralizing observability data across different infrastructure components. ```typescript import { resolveSourceConnectors, aggregateLogs } from "./connectors/registry.js"; import { getConfig } from "./lib/config.js"; const config = getConfig(); const sourceConnectors = resolveSourceConnectors(config); const logs = await aggregateLogs(sourceConnectors, { start: new Date(Date.now() - 15 * 60 * 1000), end: new Date(), limit: 500 }); console.log(`Fetched ${logs.length} unique log events`); ``` -------------------------------- ### LLM Functions - generateFixRewrite Source: https://context7.com/rutvij26/incident-orchestration-agent/llms.txt Alternative to diff - generates complete rewritten file contents (used when diff fails). ```APIDOC ## generateFixRewrite ### Description Alternative to diff - generates complete rewritten file contents (used when diff fails). ### Method POST (Assumed, as it generates rewrites) ### Endpoint /llm/generate-fix-rewrite (Assumed) ### Parameters #### Request Body - **incident** (object) - Required - The incident object. - **repoContext** (array of objects) - Required - An array of objects, each containing `path` (string) and `content` (string) for relevant files in the repository. - **trackedFiles** (array of strings) - Required - A list of file paths that are being tracked for changes. - **currentFiles** (array of objects) - Required - An array of objects, each containing `path` (string) and `content` (string) representing the current state of files to be rewritten. ### Request Example ```json { "incident": { "id": "abc-123", "title": "Incident: error (error:/api/orders)", "severity": "high", "evidence": ["{\"msg\":\"Simulated error\",\"route\":\"/api/orders\"}"], "firstSeen": "1704067200000000000", "lastSeen": "1704067260000000000", "count": 10 }, "repoContext": [ { "path": "src/api/orders.ts", "content": "..." } ], "trackedFiles": ["src/api/orders.ts"], "currentFiles": [ { "path": "src/api/orders.ts", "content": "// Full current file content..." } ] } ``` ### Response #### Success Response (200) - **files** (array of objects) - An array of objects, each containing `path` (string) and `content` (string) for the rewritten files. #### Response Example ```json { "files": [ { "path": "src/api/orders.ts", "content": "// Full corrected file content..." } ] } ``` ``` -------------------------------- ### LLM Functions - generateFixPlan Source: https://context7.com/rutvij26/incident-orchestration-agent/llms.txt Creates a targeted fix plan identifying which files to modify and the approach. ```APIDOC ## generateFixPlan ### Description Creates a targeted fix plan identifying which files to modify and the approach. ### Method POST (Assumed, as it generates a plan) ### Endpoint /llm/generate-fix-plan (Assumed) ### Parameters #### Request Body - **incident** (object) - Required - The incident object. - **repoContext** (array of objects) - Required - An array of objects, each containing `path` (string) and `content` (string) for relevant files in the repository. - **trackedFiles** (array of strings) - Required - A list of file paths that are being tracked for changes. ### Request Example ```json { "incident": { "id": "abc-123", "title": "Incident: error (error:/api/orders)", "severity": "high", "evidence": ["{\"msg\":\"Simulated error\",\"route\":\"/api/orders\"}"], "firstSeen": "1704067200000000000", "lastSeen": "1704067260000000000", "count": 10 }, "repoContext": [ { "path": "src/api/orders.ts", "content": "..." }, { "path": "src/utils/validation.ts", "content": "..." } ], "trackedFiles": ["src/api/orders.ts", "src/utils/validation.ts", "src/index.ts"] } ``` ### Response #### Success Response (200) - **files** (array of strings) - A list of file paths identified for modification. - **approach** (string) - The suggested approach for fixing the incident. - **reasoning** (string) - The reasoning behind the generated fix plan. #### Response Example ```json { "files": ["src/api/orders.ts"], "approach": "Add null check before accessing order.items", "reasoning": "Root cause is null reference in the order processing logic." } ``` ``` -------------------------------- ### Initialize PostgreSQL Memory Source: https://context7.com/rutvij26/incident-orchestration-agent/llms.txt Initializes the database schema required for the agent. This function creates necessary tables like incident_memory and auto_fix_attempts and is safe to run multiple times. ```typescript import { initMemory } from "./memory/postgres.js"; await initMemory(); ``` -------------------------------- ### createIssueForIncident Source: https://context7.com/rutvij26/incident-orchestration-agent/llms.txt Creates a GitHub Issue with formatted incident details and LLM enrichment. Requires GITHUB_TOKEN, GITHUB_OWNER, and GITHUB_REPO environment variables. ```APIDOC ## createIssueForIncident ### Description Creates a GitHub Issue with formatted incident details and LLM enrichment. ### Method POST (Assumed, as it creates a resource) ### Endpoint /api/issues (Assumed) ### Parameters #### Request Body - **incident** (object) - Required - Details of the incident. - **summary** (object) - Required - Enriched summary of the incident from an LLM. ### Request Example ```json { "incident": { "id": "abc-123", "title": "Incident: error (error:/api/orders)", "severity": "high", "evidence": ["{\"msg\":\"Simulated error\",\"route\":\"/api/orders\"}"], "firstSeen": "1704067200000000000", "lastSeen": "1704067260000000000", "count": 10 }, "summary": { "summary": "Multiple errors detected on orders API", "rootCause": "Null reference in order processing", "recommendedActions": ["Add null checks", "Validate input"], "suggestedSeverity": "high", "suggestedLabels": ["api", "orders"], "confidence": 0.85 } } ``` ### Response #### Success Response (200) - **created** (boolean) - Indicates if the issue was successfully created. - **url** (string) - The URL of the created GitHub Issue. - **number** (integer) - The number of the created GitHub Issue. #### Error Response (e.g., 400, 500) - **reason** (string) - Description of the failure. #### Response Example (Success) ```json { "created": true, "url": "https://github.com/owner/repo/issues/123", "number": 123 } ``` #### Response Example (Failure) ```json { "created": false, "reason": "Failed to authenticate with GitHub API" } ``` ``` -------------------------------- ### Configuration Management API Source: https://github.com/rutvij26/incident-orchestration-agent/blob/main/docs/architecture.md Provides endpoints for managing the agent's configuration, including updating settings and retrieving configuration details. Sensitive fields are encrypted. ```APIDOC ## PUT /api/config/{group} ### Description Updates configuration settings for a specific group. Sensitive fields are encrypted using AES-256-GCM before being stored. ### Method PUT ### Endpoint /api/config/{group} ### Parameters #### Path Parameters - **group** (string) - Required - The configuration group to update (e.g., 'integrations', 'autofix', 'rag'). #### Request Body - **key** (string) - Required - The configuration key to update. - **value** (string) - Required - The new value for the configuration key. ### Request Example ```json { "key": "GITHUB_TOKEN", "value": "your_github_token" } ``` ### Response #### Success Response (200) - **message** (string) - Confirmation message. #### Response Example ```json { "message": "Configuration updated successfully." } ``` ## GET /api/config ### Description Retrieves all agent configuration settings. Sensitive values are decrypted. Bootstrap environment variables override stored configurations. ### Method GET ### Endpoint /api/config ### Response #### Success Response (200) - **agent_config** (object) - A key-value map of all configuration settings. #### Response Example ```json { "agent_config": { "LOKI_URL": "http://localhost:3100", "GITHUB_TOKEN": "decrypted_github_token" } } ``` ``` -------------------------------- ### Retrieve Repository Context Source: https://context7.com/rutvij26/incident-orchestration-agent/llms.txt Performs a semantic similarity search to retrieve relevant code chunks based on a natural language query. Useful for providing context to LLMs during incident analysis. ```typescript import { retrieveRepoContext } from "./rag/retrieveRepo.js"; const query = `Error in /api/orders endpoint Null reference exception when processing order items`; const chunks = await retrieveRepoContext(query); chunks.forEach(chunk => { console.log(`File: ${chunk.path}`); console.log(`Score: ${chunk.score}`); console.log(`Content: ${chunk.content.substring(0, 200)}...`); }); ``` -------------------------------- ### Summarize Incident with LLM Source: https://context7.com/rutvij26/incident-orchestration-agent/llms.txt The summarizeIncident activity leverages an LLM to generate a comprehensive analysis of an incident. It produces an enriched summary, identifies the root cause, suggests a severity level, provides a confidence score, and lists recommended actions. This activity returns null if no LLM provider is configured. ```typescript import { summarizeIncident } from "./activities/incidentActivities.js"; const summary = await summarizeIncident(incident); if (summary) { console.log("Summary:", summary.summary); console.log("Root Cause:", summary.rootCause); console.log("Severity:", summary.suggestedSeverity); console.log("Confidence:", summary.confidence); console.log("Actions:", summary.recommendedActions.join("\n")); } // Returns null if no LLM provider configured ``` -------------------------------- ### Summarize Incident with LLM Source: https://context7.com/rutvij26/incident-orchestration-agent/llms.txt Generates a structured analysis of an incident using a configured LLM provider. It takes incident details as input and returns a summary, root cause, recommended actions, and suggested severity/labels. ```typescript import { summarizeIncident } from "./lib/llm.js"; const incident = { id: "abc-123", title: "Incident: error (error:/api/orders)", severity: "high", evidence: ['{\"msg\":\"Simulated error\",\"route\":\"/api/orders\"}'], firstSeen: "1704067200000000000", lastSeen: "1704067260000000000", count: 10 }; const summary = await summarizeIncident(incident); // Returns: { // summary: "Multiple errors detected on orders API", // rootCause: "Null reference in order processing", // recommendedActions: ["Add null checks", "Validate input"], // suggestedSeverity: "high", // suggestedLabels: ["api", "orders"], // confidence: 0.85 // } ``` -------------------------------- ### Create GitHub Issue for Incident Source: https://context7.com/rutvij26/incident-orchestration-agent/llms.txt Creates a GitHub issue to document an incident, including formatted details and LLM-enriched information. Requires GITHUB_TOKEN, GITHUB_OWNER, and GITHUB_REPO environment variables. ```typescript import { createIssueForIncident } from "./activities/incidentActivities.js"; const result = await createIssueForIncident(incident, summary); if (result.created) { console.log(`Issue created: ${result.url}`); console.log(`Issue number: ${result.number}`); } else { console.log(`Failed: ${result.reason}`); } // Requires: GITHUB_TOKEN, GITHUB_OWNER, GITHUB_REPO environment variables ``` -------------------------------- ### Generate Fix Plan with LLM Source: https://context7.com/rutvij26/incident-orchestration-agent/llms.txt Creates a targeted plan for fixing an incident by identifying specific files to modify and outlining the approach. It uses incident details, repository context, and tracked files as input. ```typescript import { generateFixPlan } from "./lib/llm.js"; const plan = await generateFixPlan({ incident, repoContext: [ { path: "src/api/orders.ts", content: "..." }, { path: "src/utils/validation.ts", content: "..." } ], trackedFiles: ["src/api/orders.ts", "src/utils/validation.ts", "src/index.ts"] }); if (plan) { console.log("Files to modify:", plan.files); // ["src/api/orders.ts"] console.log("Approach:", plan.approach); // "Add null check before accessing order.items" console.log("Reasoning:", plan.reasoning); // "Root cause is null reference..." } ``` -------------------------------- ### Incident Orchestration Workflow Source: https://context7.com/rutvij26/incident-orchestration-agent/llms.txt This section describes the main workflow for orchestrating the incident detection and response pipeline using Temporal. ```APIDOC ## POST /api/workflows/incidentOrchestration ### Description Executes the main incident orchestration workflow to detect and respond to incidents. ### Method POST ### Endpoint /api/workflows/incidentOrchestration ### Parameters #### Query Parameters - **lookbackMinutes** (integer) - Optional - The number of minutes to look back for logs. - **query** (string) - Optional - The log query to use for fetching logs. - **autoEscalateFrom** (string) - Optional - The minimum severity level to auto-escalate incidents from (e.g., 'high'). ### Request Example ```json { "lookbackMinutes": 15, "query": "{job=\"demo-services\"}", "autoEscalateFrom": "high" } ``` ### Response #### Success Response (200) - **incidents** (array) - A list of detected incidents. - **issuesCreated** (integer) - The number of GitHub issues created. #### Response Example ```json { "incidents": [ { "id": "incident-123", "summary": "High CPU usage on web server" } ], "issuesCreated": 1 } ``` ``` -------------------------------- ### Fetch Recent Logs Activity Source: https://context7.com/rutvij26/incident-orchestration-agent/llms.txt The fetchRecentLogs Temporal activity retrieves logs from all configured source connectors within a specified lookback period. It returns a list of log events, each containing a timestamp, message, and associated labels. ```typescript import { fetchRecentLogs } from "./activities/incidentActivities.js"; const logs = await fetchRecentLogs({ lookbackMinutes: 15 }); console.log(`Fetched ${logs.length} log events`); // Each log: { timestamp: string, message: string, labels: Record } ``` -------------------------------- ### LLM Functions - summarizeIncident Source: https://context7.com/rutvij26/incident-orchestration-agent/llms.txt Generates structured incident analysis using a configured LLM provider. ```APIDOC ## summarizeIncident ### Description Generates structured incident analysis using configured LLM provider. ### Method POST (Assumed, as it processes data) ### Endpoint /llm/summarize (Assumed) ### Parameters #### Request Body - **incident** (object) - Required - The incident object containing details like id, title, severity, evidence, timestamps, and count. ### Request Example ```json { "incident": { "id": "abc-123", "title": "Incident: error (error:/api/orders)", "severity": "high", "evidence": ["{\"msg\":\"Simulated error\",\"route\":\"/api/orders\"}"], "firstSeen": "1704067200000000000", "lastSeen": "1704067260000000000", "count": 10 } } ``` ### Response #### Success Response (200) - **summary** (string) - A concise summary of the incident. - **rootCause** (string) - The identified root cause of the incident. - **recommendedActions** (array of strings) - Suggested actions to resolve the incident. - **suggestedSeverity** (string) - The LLM's suggested severity level for the incident. - **suggestedLabels** (array of strings) - Suggested labels for categorizing the incident. - **confidence** (number) - The confidence score of the LLM's analysis (0-1). #### Response Example ```json { "summary": "Multiple errors detected on orders API", "rootCause": "Null reference in order processing", "recommendedActions": ["Add null checks", "Validate input"], "suggestedSeverity": "high", "suggestedLabels": ["api", "orders"], "confidence": 0.85 } ``` ``` -------------------------------- ### Index Repository for RAG Source: https://context7.com/rutvij26/incident-orchestration-agent/llms.txt Indexes local repository files into PostgreSQL using pgvector embeddings for semantic search. The process is incremental, skipping unchanged files based on content hashes. ```typescript import { indexRepository } from "./rag/indexRepo.js"; await indexRepository(); ``` -------------------------------- ### LLM Functions - generateFixProposal Source: https://context7.com/rutvij26/incident-orchestration-agent/llms.txt Generates a unified diff patch based on the fix plan. ```APIDOC ## generateFixProposal ### Description Generates a unified diff patch based on the fix plan. ### Method POST (Assumed, as it generates a proposal) ### Endpoint /llm/generate-fix-proposal (Assumed) ### Parameters #### Request Body - **incident** (object) - Required - The incident object. - **repoContext** (array of objects) - Required - An array of objects, each containing `path` (string) and `content` (string) for relevant files in the repository. - **strictDiff** (boolean) - Optional - If true, enforces strict diff generation. - **plan** (object) - Required - The fix plan generated by `generateFixPlan`. - **trackedFiles** (array of strings) - Required - A list of file paths that are being tracked for changes. ### Request Example ```json { "incident": { "id": "abc-123", "title": "Incident: error (error:/api/orders)", "severity": "high", "evidence": ["{\"msg\":\"Simulated error\",\"route\":\"/api/orders\"}"], "firstSeen": "1704067200000000000", "lastSeen": "1704067260000000000", "count": 10 }, "repoContext": [ { "path": "src/api/orders.ts", "content": "..." } ], "strictDiff": true, "plan": { "files": ["src/api/orders.ts"], "approach": "Add null check before accessing order.items", "reasoning": "Root cause is null reference in the order processing logic." }, "trackedFiles": ["src/api/orders.ts"] } ``` ### Response #### Success Response (200) - **summary** (string) - A summary of the proposed fix. - **reason** (string) - The reasoning behind the proposed fix. - **test_plan** (string) - A plan for testing the proposed fix. - **diff** (string) - The generated unified diff patch. #### Response Example ```json { "summary": "Add null check for order items", "reason": "Prevents null reference exception when processing orders.", "test_plan": "Test with orders that have empty items array and orders with valid items.", "diff": "diff --git a/src/api/orders.ts b/src/api/orders.ts\nindex ...\n--- a/src/api/orders.ts\n+++ b/src/api/orders.ts\n@@ -10,5 +10,7 @@\n function processOrder(order) {\n // ... existing code ...\n const items = order.items;\n+ if (!items) {\n+ return; // Or throw an error, depending on desired behavior\n+ }\n // ... more code ...\n }" } ``` ``` -------------------------------- ### Temporal Scheduling API Source: https://github.com/rutvij26/incident-orchestration-agent/blob/main/docs/architecture.md APIs for managing Temporal Schedules, including creating, updating, pausing, unpausing, and triggering workflows. Schedule configurations are persisted in the `schedule_config` table. ```APIDOC ## Temporal Scheduling Management ### Description This section outlines the API operations for managing Temporal Schedules used by the agent. These operations allow for dynamic control over when and how workflows are executed. ### Methods #### `createOrUpdateSchedule(opts)` - **Description**: Creates a new Temporal Schedule or updates an existing one based on the provided options. - **Parameters**: `opts` (object) - Configuration options for the schedule (e.g., interval, lookback). #### `pauseSchedule()` - **Description**: Pauses the currently active Temporal Schedule. #### `unpauseSchedule()` - **Description**: Resumes a paused Temporal Schedule. #### `triggerNow()` - **Description**: Initiates a single workflow run immediately, independent of the schedule. #### `getScheduleStatus()` - **Description**: Retrieves the current status of the Temporal Schedule, including details like the last run time, next scheduled run, and worker connectivity. ### Persistence Schedule settings are persisted in the `schedule_config` table. ``` -------------------------------- ### Generate Fix Rewrite with LLM Source: https://context7.com/rutvij26/incident-orchestration-agent/llms.txt Generates the complete rewritten content for files targeted by a fix plan, used as an alternative when diff generation fails. Requires current file contents. ```typescript import { generateFixRewrite } from "./lib/llm.js"; const rewrite = await generateFixRewrite({ incident, repoContext, trackedFiles: ["src/api/orders.ts"], currentFiles: [ { path: "src/api/orders.ts", content: "// Full current file content..." } ] }); if (rewrite) { rewrite.files.forEach(file => { console.log(`Rewrite ${file.path}:`); console.log(file.content); // Complete corrected file content }); } ``` -------------------------------- ### GitHub Issue and PR Management Source: https://context7.com/rutvij26/incident-orchestration-agent/llms.txt Provides utilities to create GitHub issues and pull requests programmatically. These functions handle metadata, labels, and body content for automated reporting and fix submission. ```typescript import { createIssue, createPullRequest } from "./lib/github.js"; // Create Issue const issue = await createIssue({ title: "Incident: Critical error in /api/orders", body: "## Incident Details...", labels: ["incident", "critical"] }); // Create PR const pr = await createPullRequest({ title: "fix: Null reference in order processing", body: "## Summary...", head: "agentic-fix/abc-123", base: "main", labels: ["autofix"] }); ``` -------------------------------- ### Execute Auto-Fix Pipeline Source: https://context7.com/rutvij26/incident-orchestration-agent/llms.txt Runs a complete auto-fix pipeline to assess, plan, patch, validate, and submit a PR for an incident. It relies on environment variables for configuration like severity thresholds and test commands. ```typescript import { autoFixIncident } from "./autofix/autoFix.js"; const result = await autoFixIncident({ incident, summary, issueNumber: 42, issueUrl: "https://github.com/owner/repo/issues/42" }); switch (result.status) { case "pr_created": console.log(`PR created: ${result.prUrl}`); break; case "skipped": console.log(`Skipped: ${result.reason}`); break; case "failed": console.log(`Failed: ${result.reason}`); break; } ``` -------------------------------- ### Real-Time Incidents Feed (SSE) Source: https://github.com/rutvij26/incident-orchestration-agent/blob/main/docs/architecture.md Provides a real-time stream of new incidents using Server-Sent Events (SSE). The endpoint polls for new incident entries and pushes them to connected clients. ```APIDOC ## GET /api/incidents/feed ### Description Establishes a Server-Sent Events (SSE) connection to receive real-time updates on new incidents. The server polls the `incident_memory` table for entries created after the last seen timestamp and pushes them as events. ### Method GET ### Endpoint /api/incidents/feed ### Query Parameters - **lastSeen** (string) - Optional - The timestamp of the last incident seen by the client, used for incremental updates. ### Response #### Success Response (200) - **EventStream** - A stream of Server-Sent Events, where each event contains a new incident record. ### Response Example ``` : event: incident data: {"id": "inc-123", "status": "open", "created_at": "2023-10-27T10:00:00Z"} ``` ``` -------------------------------- ### Define Incident and Summary Data Structures Source: https://context7.com/rutvij26/incident-orchestration-agent/llms.txt Defines the core TypeScript interfaces for incident reporting and LLM-generated analysis. These structures are used across the system to track incident state and recommended remediation steps. ```typescript import type { Incident, IncidentSummary, LogEvent, IncidentSeverity } from "@agentic/shared"; const incident: Incident = { id: "550e8400-e29b-41d4-a716-446655440000", title: "Incident: error_burst (error_burst:/api/orders)", severity: "high", evidence: [ '{"msg":"Synthetic error burst","type":"error_burst","route":"/api/orders"}', '{"msg":"Simulated error triggered","level":"error","route":"/api/orders"}' ], firstSeen: "1704067200000000000", lastSeen: "1704067260000000000", count: 15 }; const summary: IncidentSummary = { summary: "Multiple error bursts detected on /api/orders endpoint", rootCause: "Null reference in order item processing logic", recommendedActions: [ "Add null check before accessing order.items", "Implement input validation for order payload", "Add circuit breaker for downstream service calls" ], suggestedSeverity: "high", suggestedLabels: ["api", "orders", "null-reference"], confidence: 0.85 }; ```