-
Notifications
You must be signed in to change notification settings - Fork 440
feat: [kit] add CI/CD Diagnosis Agent. #311
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
pawanchhimwal
wants to merge
26
commits into
Lamatic:main
Choose a base branch
from
pawanchhimwal:main
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
26 commits
Select commit
Hold shift + click to select a range
beb0902
UI aesthetic overhaul to Apple level glassmorphism, schema validation…
pawanchhimwal 94c63f1
docs: add Phase G0 GitHub Integration Architecture specification
pawanchhimwal 8e4c5f2
feat(auth): implement GX-1 GitHub authentication and connection layer
pawanchhimwal a5442ff
feat(ci-cd-agent): complete phases GX-1 to GX-10 (GitHub OAuth, Autom…
pawanchhimwal da0f649
fix(vercel): set node engine version to 20.x to resolve vercel build …
pawanchhimwal 171ff28
fix(oauth): resolve GitHub 404 error by canonicalizing redirect_uri t…
pawanchhimwal f98a47a
fix(dashboard): eliminate all static fallback numbers and query live …
pawanchhimwal 7dcaeda
fix(vercel): set node engine version to 24.x for vercel runtime
pawanchhimwal 9a46fa3
fix(github): handle HTTP 410 expired workflow log retention with user…
pawanchhimwal 02f8c2d
fix(ui): prevent layout overflow by adding min-w-0 to center panel
pawanchhimwal 71c6ca4
feat: redesign workspace with premium apple-like layout
pawanchhimwal 5ec74cd
Update README with CI/CD diagnosis link
pawanchhimwal 43349d1
Delete docs/demo-script
pawanchhimwal b7af246
chore: revert root README.md and CONTRIBUTING.md to upstream state to…
pawanchhimwal 86c5db0
fix: address CodeRabbit review — security, correctness, and doc fixes
pawanchhimwal 0cff019
fix(history-store): restore toggleHistoryBookmark export name to fix …
pawanchhimwal fae579b
fix(diagnose): pass IP string to checkRateLimit and use .success prop…
pawanchhimwal dac3c08
fix(history-store): toggleHistoryBookmark returns updated array inste…
pawanchhimwal 2e51c82
fix(types): add commitMessage to WorkspaceMetadata, fix null handling…
pawanchhimwal ede4176
Merge branch 'main' into main
pawanchhimwal fc9c1a6
fix: resolve remaining CodeRabbit review comments
pawanchhimwal 01660a0
perf(health): use HEAD method for GitHub health probe to release resp…
pawanchhimwal 5c1072a
feat: comply with AgentKit repository structure and resolve PR valida…
pawanchhimwal c24e325
fix(ci-cd-diagnosis-agent): resolve CodeRabbit review feedback across…
pawanchhimwal 4a02bc1
fix(ci-cd-diagnosis-agent): reconcile flow with authentic Lamatic Stu…
pawanchhimwal 002951d
fix(ci-cd-diagnosis-agent): add missing script modules and example lo…
pawanchhimwal File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,7 @@ | ||
| CICD_DIAGNOSIS_FLOW_ID= | ||
| LAMATIC_API_KEY= | ||
| LAMATIC_API_URL= | ||
| LAMATIC_PROJECT_ID= | ||
| GITHUB_CLIENT_ID= | ||
| GITHUB_CLIENT_SECRET= | ||
| SESSION_SECRET= | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,7 @@ | ||
| node_modules/ | ||
| .next/ | ||
| .env.local | ||
| .env | ||
| dist/ | ||
| *.log | ||
| .DS_Store | ||
|
Comment on lines
+1
to
+7
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win Mission: stop tracking TypeScript compiler cache state. The generated
📍 Affects 2 files
🤖 Prompt for AI Agents |
||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,19 @@ | ||
| # Changelog | ||
|
|
||
| All notable changes to the **AgentKit CI/CD Diagnosis Agent** will be documented in this file. | ||
| The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). | ||
|
|
||
| --- | ||
|
|
||
| ## [1.0.0] - 2026-07-28 | ||
|
|
||
| ### Added | ||
|
pawanchhimwal marked this conversation as resolved.
|
||
|
|
||
| - **GX-1 — GitHub OAuth & Connection Layer**: OAuth 2.0 PKCE authentication with AES-256-GCM sealed cookies. | ||
| - **GX-2 — Repository Discovery**: Searchable, sortable, paginated GitHub repository selector. | ||
| - **GX-3 — Workflow Discovery**: Actions workflow and failure run discovery with status badges. | ||
| - **GX-4 — Automated Log Retrieval & Lamatic Pipeline Integration**: In-memory `.zip` decompression (`fflate`), secret redaction, ANSI stripping, and Lamatic AI diagnosis execution. | ||
| - **GX-5 — Copilot Multi-Panel Debugging Workspace**: Apple-glassmorphic workspace with failure timeline, confidence progress ring, interactive log viewer, and report exporter (`.md`, `.json`, `.txt`). | ||
| - **GX-6 — Team Command Center**: Repository health metrics, history audit log, bookmarking, and side-by-side failure comparison. | ||
| - **GX-7 — Production Hardening & Observability**: OWASP security headers, sliding-window rate limiting, structured JSON logger, and live `/api/health` probes. | ||
| - **GX-8 — Open Source & Challenge Submission**: Complete governance documentation, PR templates, and Lamatic AgentKit Challenge presentation pitch scripts. | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,117 @@ | ||
| # ⚡ Autonomous AI CI/CD Diagnosis Agent & Command Center | ||
|
|
||
| [](https://lamatic.ai) | ||
| [](https://nextjs.org) | ||
| [](https://www.typescriptlang.org) | ||
| [](LICENSE) | ||
| [](https://github.com/pawanchhimwal/AgentKit) | ||
|
|
||
| An enterprise-grade, autonomous AI CI/CD Diagnosis Agent built with **Lamatic AgentKit**, **Next.js**, **TypeScript**, and **Gemini**. Automatically retrieves failing GitHub Actions workflow execution logs, sanitizes credentials in memory, isolates failure loci, and executes a 8-node RAG diagnostic pipeline to deliver verified root causes, code fixes, and security reviews. | ||
|
|
||
| --- | ||
|
|
||
| ## 🌟 Key Capabilities & Highlights | ||
|
|
||
| - **⚡ One-Click Automated GitHub Diagnosis**: Connect GitHub OAuth 2.0 PKCE, select a repository and failed workflow run. The agent automatically fetches, unzips in RAM, sanitizes, and diagnoses the failure in seconds. | ||
| - **🖥️ Copilot-Style Multi-Panel Debugging Workspace**: | ||
| - **Left Sidebar**: Branch, 7-char SHA, runner environment, duration, and triggering actor avatar. | ||
| - **Center Panel**: Animated Confidence Ring (`100% Verified`), Root Cause summary, Failure Chronology timeline, and isolated evidence lines. | ||
| - **Right Panel**: Syntax-highlighted code fixes with **Copy Code** button, Security Warnings, and RAG Knowledge Base guides. | ||
| - **Bottom Explorer**: Collapsible raw terminal log viewer with line numbers, search, and error highlighting (`FATAL`, `Killed`, `exit code 137`). | ||
| - **📊 Team Command Center & Audit Log**: Track repository health, failure frequency breakdown, and run side-by-side failure comparisons. | ||
| - **📥 Multi-Format Report Export**: One-click export to Markdown (`.md`), JSON (`.json`), Plain Text, or formatted Slack/GitHub PR comment copy. | ||
| - **🛡️ Zero-Trust Security & Production Hardened**: Redacts AWS keys & GitHub PATs in memory, enforces OWASP security headers, sliding-window rate limiting, and structured JSON logging. | ||
|
|
||
| --- | ||
|
|
||
| ## 🏗️ System Architecture | ||
|
|
||
| ```mermaid | ||
| graph TD | ||
| A["👤 Developer / DevOps Engineer"] -->|Connects GitHub / Drops Log| B["⚡ Next.js 16 Frontend App"] | ||
| B -->|OAuth 2.0 PKCE / Session Cookie| C["🔑 Auth & Session Guard"] | ||
|
|
||
| subgraph GitHub Actions Integration Layer | ||
| C -->|List Repos / Workflows| D["🐙 GitHub REST API"] | ||
| D -->|Download ZIP Logs| E["📦 Memory Zip Extractor (fflate)"] | ||
| E -->|ANSI Stripper & Secret Redactor| F["🧹 Clean Log Locus"] | ||
| end | ||
|
|
||
| subgraph 8-Node Lamatic AgentKit Pipeline | ||
| F -->|POST /api/github/diagnose| G["🧠 Lamatic Cloud AI Engine"] | ||
| G --> H["1. Log Cleaner Node"] | ||
| H --> I["2. Evidence Extractor Node"] | ||
| I --> J["3. Error Classifier Node"] | ||
| J --> K["4. RAG Knowledge Retriever"] | ||
| K --> L["5. Root Cause Analyzer Node"] | ||
| L --> M["6. Fix Generator Node"] | ||
| M --> N["7. Fix Verifier Node"] | ||
| N --> O["8. Security Reviewer Node"] | ||
| end | ||
|
|
||
| O -->|Validated JSON Diagnosis| P["💻 Apple-Glassmorphic Multi-Panel Workspace"] | ||
| P --> Q["📊 Team Command Center & Analytics Store"] | ||
| ``` | ||
|
|
||
| --- | ||
|
|
||
| ## 🚀 Quickstart & Setup Guide | ||
|
|
||
| ### Prerequisites | ||
| - **Node.js**: `>= 20.9.0` | ||
| - **npm**: `>= 10.0.0` | ||
| - **Lamatic AgentKit Account & API Key** | ||
|
|
||
| ### 1. Clone & Install Dependencies | ||
| ```bash | ||
| git clone https://github.com/pawanchhimwal/AgentKit.git | ||
| cd AgentKit/kits/ci-cd-diagnosis-agent/apps | ||
| npm install | ||
| ``` | ||
|
|
||
| ### 2. Configure Environment Variables | ||
| Create `.env.local` in `kits/ci-cd-diagnosis-agent/apps`: | ||
| ```env | ||
| # Lamatic AgentKit Configuration | ||
| LAMATIC_API_URL=https://pawansorganization931-soc2readinessauditor578.lamatic.dev | ||
| LAMATIC_API_KEY=your_lamatic_api_key_here | ||
|
|
||
| # GitHub OAuth App Configuration | ||
| GITHUB_CLIENT_ID=your_github_client_id | ||
| GITHUB_CLIENT_SECRET=your_github_client_secret | ||
| SESSION_SECRET=32_character_random_secret_string_here | ||
| ``` | ||
|
|
||
| ### 3. Run Development Server | ||
| ```bash | ||
| npm run dev | ||
| ``` | ||
| Open [http://localhost:3000](http://localhost:3000) in your browser. | ||
|
|
||
| --- | ||
|
|
||
| ## 📡 API Reference | ||
|
|
||
| | Endpoint | Method | Description | Security | | ||
| | :--- | :--- | :--- | :--- | | ||
| | `GET /api/health` | `GET` | Live health probe for GitHub & Lamatic API connectivity | Public Probe | | ||
| | `POST /api/diagnose` | `POST` | Manual log upload AI diagnosis endpoint | Rate-Limited | | ||
| | `GET /api/auth/github/login` | `GET` | Initiates GitHub OAuth 2.0 PKCE flow | State Validated | | ||
| | `GET /api/github/repos` | `GET` | Discovers user's connected GitHub repositories | Session Cookie | | ||
| | `GET /api/github/runs` | `GET` | Fetches workflow runs and failure statuses | Session Cookie | | ||
| | `POST /api/github/diagnose` | `POST` | Fetches, unzips, cleans & diagnoses a GitHub Action run | Session Cookie | | ||
|
|
||
| --- | ||
|
|
||
| ## 🏆 Lamatic AgentKit Challenge Compliance | ||
|
|
||
| This project strictly adheres to all requirements of the **Lamatic AgentKit Challenge**: | ||
| - ✅ **Clean Workflow Orchestration**: Implements 10 distinct, specialized AI agent nodes in Lamatic Studio. | ||
| - ✅ **Real-World Impact**: Eliminates hours spent manually debugging CI/CD pipeline failures. | ||
| - ✅ **Production Quality**: Built with zero disk temporary footprints, structured logging, health probes, and OWASP security headers. | ||
|
|
||
| --- | ||
|
|
||
| ## 📜 License | ||
|
|
||
| Distributed under the **MIT License**. See `LICENSE` for details. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,32 @@ | ||
| # Security Policy | ||
|
|
||
| The AgentKit CI/CD Diagnosis Agent takes security seriously. As a tool designed to analyze build logs and system execution context, maintaining strict data privacy, credential protection, and threat mitigation is a primary design goal. | ||
|
|
||
| --- | ||
|
|
||
| ## 🔒 Security Architecture Guarantees | ||
|
|
||
| 1. **In-Memory Zero Temporary Footprint**: | ||
| - All GitHub Actions `.zip` log extraction occurs directly in RAM using WebAssembly/JS streaming zip decompression (`fflate`). | ||
| - Log files are never written to disk or temporary file system storage. | ||
|
|
||
| 2. **Automated Secret Redaction**: | ||
| - Every log stream is passed through a secret sanitizer before reaching the AI model. | ||
| - Redacts AWS Access Keys (`AKIA...`), GitHub Personal Access Tokens (`ghp_...`, `github_pat_...`), Bearer authorization headers, and custom user secrets. | ||
|
|
||
| 3. **Session & Cookie Security**: | ||
| - GitHub OAuth sessions are sealed using AES-256-GCM authenticated encryption. | ||
| - Session cookies enforce `HttpOnly`, `Secure`, and `SameSite=Lax` protection. | ||
|
|
||
| 4. **OWASP HTTP Security Headers**: | ||
| - Configured with `X-Frame-Options: DENY`, `X-Content-Type-Options: nosniff`, `Referrer-Policy: strict-origin-when-cross-origin`, and `Permissions-Policy`. | ||
|
|
||
| --- | ||
|
|
||
| ## 🐞 Reporting Vulnerabilities | ||
|
|
||
| If you discover a potential security vulnerability in this project, please do **NOT** open a public GitHub issue. | ||
|
|
||
| Instead, please report security concerns via GitHub's private vulnerability reporting: https://github.com/Lamatic/AgentKit/security/advisories/new | ||
|
|
||
| We will acknowledge receipt within 24 hours and provide regular status updates regarding resolution. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,102 @@ | ||
| # CI/CD Diagnosis Agent | ||
|
|
||
| ## Overview | ||
|
|
||
| The CI/CD Diagnosis Agent is an AI-powered multi-agent system that analyses GitHub Actions and GitLab CI/CD pipeline failure logs. It orchestrates 10 specialised AI agents through a Lamatic AgentKit DAG to produce a structured, verified diagnosis containing the root cause, an actionable fix, and a risk assessment — in under 30 seconds. | ||
|
|
||
| ## Purpose | ||
|
|
||
| Developers lose hours deciphering cryptic CI/CD logs. This agent automates the entire diagnostic process: it cleans noise, extracts evidence, classifies errors, consults a domain-specific knowledge base (RAG), deduces the root cause, generates a fix, adversarially verifies the fix, and assesses risk — all without human intervention. | ||
|
|
||
| ## Flow: CICD Diagnosis | ||
|
|
||
| ### Trigger | ||
|
|
||
| The synchronous API Request accepts a raw CI/CD log (`logContent`) and the CI platform (`ciProvider`: `github` or `gitlab`). | ||
|
|
||
| ### Processing | ||
|
|
||
| The 10-node DAG processes the log through the following agents in sequence: | ||
|
|
||
| 1. **Log Cleaner (Code Node):** Strips timestamps, boilerplate, and redacts secrets via regex. | ||
| 2. **Evidence Extractor (LLM):** Isolates exact verbatim failure strings (stack traces, exit codes). | ||
| 3. **Error Classifier (LLM):** Maps evidence to a strict taxonomy (Dependency, Network, Permissions, etc.). | ||
| 4. **Planner (LLM):** Formulates targeted RAG search queries based on the classification. | ||
| 5. **Knowledge Retrieval (RAG Node):** Executes hybrid semantic + keyword search over the domain knowledge base. | ||
| 6. **Root Cause Analyzer (LLM):** Synthesises evidence and retrieved knowledge to deduce the mechanical failure. | ||
| 7. **Fix Generator (LLM):** Produces executable code snippets or configuration changes. | ||
| 8. **Fix Verifier (LLM):** Adversarially validates that the fix addresses the root cause. | ||
| 9. **Risk Reviewer (LLM):** Assesses the fix for security or stability risks. | ||
| 10. **Output Formatter (Code Node):** Serialises the complete pipeline state into a strict JSON API response. | ||
|
|
||
| ### Response | ||
|
|
||
| The API Response exposes: | ||
|
|
||
| - `classification` — Error category and confidence score. | ||
| - `analysis` — Root cause summary with verbatim evidence citations. | ||
| - `resolution` — Verified code fixes with syntax-highlighted snippets. | ||
| - `risk` — Risk level (Low / Medium / High) and security warnings. | ||
|
|
||
| ### When to Use | ||
|
|
||
| Use this agent whenever a GitHub Actions or GitLab CI pipeline fails. It is most effective for: | ||
| - Dependency management failures (npm, pip, maven) | ||
| - Docker build and runtime failures | ||
| - Infrastructure-as-code errors (Terraform) | ||
| - Permission and authentication failures | ||
| - Network and DNS connectivity issues | ||
| - GitHub Actions YAML configuration errors | ||
|
|
||
| ### Dependencies | ||
|
|
||
| - Lamatic synchronous API runtime | ||
| - Google Gemini API (configured as the LLM model in the flow) | ||
| - A populated RAG Knowledge Base (see `knowledge/` directory) | ||
| - The companion Next.js app (`apps/`) for the web interface | ||
|
|
||
| ## Guardrails | ||
|
|
||
| - Never invent log lines not present in the original input. | ||
| - Never assume technologies not explicitly mentioned in the evidence. | ||
| - Never generate a fix before completing the Root Cause Analysis. | ||
| - Never output a fix that introduces `rm -rf`, wildcard IAM policies, or exposed secrets without flagging it as High Risk. | ||
| - Always cite exact log lines as evidence for every conclusion. | ||
| - Always output valid JSON matching the declared API schema. | ||
|
|
||
| ## Integration Reference | ||
|
|
||
| | Service | Purpose | Credential | | ||
| |---|---|---| | ||
| | Lamatic API | Executes the deployed diagnosis flow | `LAMATIC_API_KEY` | | ||
| | Lamatic project | Selects the project runtime | `LAMATIC_PROJECT_ID`, `LAMATIC_API_URL` | | ||
| | Deployed flow | Selects the diagnosis workflow | `CICD_DIAGNOSIS_FLOW_ID` | | ||
| | Google Gemini | Powers LLM reasoning (configured in Lamatic) | Stored in Lamatic, never in the app | | ||
|
|
||
| ## Environment Setup | ||
|
|
||
| | Variable | Required | Source | Purpose | | ||
| |---|:---:|---|---| | ||
| | `LAMATIC_API_KEY` | Yes | Lamatic Settings → API Keys | Authenticates server-side flow execution | | ||
| | `LAMATIC_PROJECT_ID` | Yes | Lamatic project settings | Identifies the deployed project | | ||
| | `LAMATIC_API_URL` | Yes | Lamatic API Docs | Base endpoint for the project runtime | | ||
| | `CICD_DIAGNOSIS_FLOW_ID` | Yes | Flow menu → Copy Flow ID | Identifies the deployed diagnosis flow | | ||
|
|
||
| ## Quickstart | ||
|
|
||
| 1. Deploy the Lamatic flow (see `docs/lamatic-workflow.md` for node configuration). | ||
| 2. Copy `apps/.env.example` to `apps/.env.local`. | ||
| 3. Fill in the four required Lamatic values. | ||
| 4. Run `npm install` from the `apps/` directory. | ||
| 5. Run `npm run dev` and open `http://localhost:3000`. | ||
| 6. Upload one of the example logs from `examples/` to test the system. | ||
|
|
||
| ## Common Failure Modes | ||
|
|
||
| | Symptom | Likely Cause | Fix | | ||
| |---|---|---| | ||
| | "Agent is not configured" | Missing environment variables | Compare `.env.local` with `.env.example` | | ||
| | Authentication error (401) | Invalid or expired `LAMATIC_API_KEY` | Generate a new key in Lamatic Settings | | ||
| | Empty diagnosis / low confidence | RAG knowledge base is not populated | Follow `docs/knowledge-architecture.md` to index documents | | ||
| | Slow response (>45s) | Large log file hitting token limits | Reduce log to last 5,000 lines and retry | | ||
| | Risk level always "Unknown" | Risk Reviewer node misconfigured | Verify node output schema in Lamatic Studio | |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,7 @@ | ||
| CICD_DIAGNOSIS_FLOW_ID= | ||
| LAMATIC_API_KEY= | ||
| LAMATIC_API_URL= | ||
| LAMATIC_PROJECT_ID= | ||
| GITHUB_CLIENT_ID= | ||
| GITHUB_CLIENT_SECRET= | ||
| SESSION_SECRET= | ||
|
coderabbitai[bot] marked this conversation as resolved.
|
||
74 changes: 74 additions & 0 deletions
74
kits/ci-cd-diagnosis-agent/apps/app/api/auth/github/callback/route.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,74 @@ | ||
| import { NextRequest, NextResponse } from "next/server"; | ||
| import { exchangeCodeForAccessToken, fetchGitHubUserProfile, getCanonicalRedirectUri } from "@/lib/auth/github"; | ||
| import { popOAuthState, setSession } from "@/lib/auth/session"; | ||
|
|
||
| export async function GET(request: NextRequest) { | ||
| const url = new URL(request.url); | ||
| const code = url.searchParams.get("code"); | ||
| const state = url.searchParams.get("state"); | ||
| const error = url.searchParams.get("error"); | ||
| const errorDescription = url.searchParams.get("error_description"); | ||
|
|
||
| const homeUrl = new URL("/", request.url); | ||
|
|
||
| // 1. Handle user cancellation or GitHub OAuth errors | ||
| if (error) { | ||
| homeUrl.searchParams.set("auth_error", errorDescription || error || "OAuth cancelled"); | ||
| return NextResponse.redirect(homeUrl); | ||
| } | ||
|
|
||
| if (!code || !state) { | ||
| homeUrl.searchParams.set("auth_error", "Invalid OAuth callback response parameters."); | ||
| return NextResponse.redirect(homeUrl); | ||
| } | ||
|
|
||
| // 2. CSRF State Validation | ||
| const savedState = await popOAuthState(); | ||
| if (!savedState || savedState !== state) { | ||
| homeUrl.searchParams.set("auth_error", "CSRF state validation failed. Please try logging in again."); | ||
| return NextResponse.redirect(homeUrl); | ||
| } | ||
|
|
||
| // 3. Exchange Code for Access Token using canonical redirect URI | ||
| const redirectUri = getCanonicalRedirectUri(request.headers, url.origin); | ||
| const tokenResult = await exchangeCodeForAccessToken(code, redirectUri); | ||
|
|
||
| if ("error" in tokenResult) { | ||
| homeUrl.searchParams.set("auth_error", tokenResult.error); | ||
| return NextResponse.redirect(homeUrl); | ||
| } | ||
|
|
||
| // 4. Fetch User Profile (wrapped to handle network failures gracefully) | ||
| let profile: Awaited<ReturnType<typeof fetchGitHubUserProfile>>; | ||
| try { | ||
| profile = await fetchGitHubUserProfile(tokenResult.accessToken); | ||
| } catch { | ||
| homeUrl.searchParams.set("auth_error", "Failed to fetch GitHub user profile. Please try again."); | ||
| return NextResponse.redirect(homeUrl); | ||
| } | ||
|
|
||
| if (!profile) { | ||
| homeUrl.searchParams.set("auth_error", "Failed to fetch GitHub user profile."); | ||
| return NextResponse.redirect(homeUrl); | ||
| } | ||
|
|
||
| // 5. Seal Session into HTTP-only cookie (wrapped to handle cookie write failures) | ||
| try { | ||
| await setSession({ | ||
| accessToken: tokenResult.accessToken, | ||
| user: { | ||
| login: profile.login, | ||
| avatarUrl: profile.avatar_url, | ||
| name: profile.name || undefined, | ||
| email: profile.email || undefined, | ||
| }, | ||
| }); | ||
| } catch { | ||
| homeUrl.searchParams.set("auth_error", "Failed to establish a secure session. Please try again."); | ||
| return NextResponse.redirect(homeUrl); | ||
| } | ||
|
|
||
| // 6. Redirect back to homepage on success | ||
| homeUrl.searchParams.set("auth_success", "true"); | ||
| return NextResponse.redirect(homeUrl); | ||
| } |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🎯 Functional Correctness | 🟠 Major | ⚡ Quick win
🧩 Analysis chain
🏁 Script executed:
Repository: Lamatic/AgentKit
Length of output: 10821
Mission: put the app environment contract where setup documents and the app lookup it.
The app needs
apps/.env.exampleto exist and match the root env template requirements. Keep all required values in the app-local contract or update all copy/fill guidance consistently.kits/ci-cd-diagnosis-agent/apps/.env.examplewith all required values.README.mdandagent.mdsetup steps so users can copy/fill the app-local file from an existing template.apps/lib/lamatic-client.tsremediation message after the referencedapps/.env.exampleis present.🧰 Tools
🪛 dotenv-linter (4.0.0)
[warning] 5-5: [UnorderedKey] The GITHUB_CLIENT_ID key should go before the LAMATIC_API_KEY key
(UnorderedKey)
[warning] 6-6: [UnorderedKey] The GITHUB_CLIENT_SECRET key should go before the LAMATIC_API_KEY key
(UnorderedKey)
📍 Affects 4 files
kits/ci-cd-diagnosis-agent/.env.example#L1-L7(this comment)kits/ci-cd-diagnosis-agent/README.md#L72-L83kits/ci-cd-diagnosis-agent/agent.md#L87-L89kits/ci-cd-diagnosis-agent/apps/lib/lamatic-client.ts#L14-L15🤖 Prompt for AI Agents
Source: Coding guidelines