Imported from rishabhsharmaa/LogSense (
AGENTS.md). Install upstream withnpx skills add rishabhsharmaa/LogSense. Copyright stays with the author.
LogSense — Agent & Developer Codebase Map
This document is the fast-routing guide for the LogSense project. Whenever a task or prompt is received, use this document to immediately jump to the exact file and symbol rather than running global searches across the repository.
⚡ Fast Task-to-File Routing Directory
| When the task is about... | Jump directly to file | Key Symbols / Details |
|---|---|---|
| Gemini AI Prompt & Model Logic | backend/src/controllers/analyzeController.js |
buildprompt(), getModel(), DEFAULT_MODEL = "gemini-2.5-flash", retry logic with backoff |
| Log Response Parsing & Output Sanitization | backend/src/controllers/analyzeController.js |
Section extraction (## Explanation, ## Original Code, ## Suggested Fix), diff marker strip regex |
| Secrets & File Path Redaction (Sanitizer) | backend/src/middlewares/sanitizer.js |
SECRET_PATTERNS (API keys, AWS, tokens), PATH_PATTERNS (Windows, macOS, Linux paths), sanitize(), sanitizerMiddleware() |
| History API & Aggregation Pipeline | backend/src/controllers/historyController.js |
getHistory() with facet pagination ($facet, page, limit) |
| Database Schema & Indexes | backend/src/models/LogHistory.js |
logHistorySchema (userId, rawLog, languageContext, aiExplanation, aiSuggestedFix), compound index { userId: 1, createdAt: -1 } |
| Backend Server, CORS, Port & Startup | backend/src/server.js |
PORT (3001), express.json({ limit: "1mb" }), mongoose.connect(), GET /health |
| Backend API Route Definitions | backend/src/routes/api.js |
POST /api/v1/analyze, GET /api/v1/history/:userId |
| Backend Environment Variables | backend/.env |
PORT, MONGODB_URI, GEMINI_API_KEY |
| VS Code Commands & Menus Configuration | extension/package.json |
contributes.commands, editor/context, terminal/context, keybindings (ctrl+shift+l), config logsense.backendUrl |
| Extension Lifecycle & Command Handlers | extension/src/extension.ts |
activate(), logsense.start, logsense.analyzeSelection, logsense.analyzeTerminalSelection, logsense.setApiKey, logsense.removeApiKey |
| VS Code Secret Storage (API Key / BYOK) | extension/src/extension.ts |
SECRET_KEY = "logsense.geminiApiKey", context.secrets.store/get/delete |
| Apply Fix Logic & Replacement Strategies | extension/src/extension.ts |
case "applyFix": Strategy 1 (Exact substring), Strategy 2 (Tighter contiguous line match), Guarded fallback (interactive prompt: Insert at Cursor or Replace Current Selection) |
| Webview Panel Setup & CSP Security | extension/src/extension.ts |
openPanel(), getWebviewContent(), CSP nonce and allowed origins |
| Webview Main State & API Dispatch | extension/webview-ui/src/App.tsx |
handleAnalyze(), requestApiKey(), handleModelChange(), selectedModel, backendUrl, abort controller |
| Webview Supported Gemini Models | extension/webview-ui/src/App.tsx |
GEMINI_MODELS array (gemini-2.5-flash, gemini-2.5-pro, gemini-2.5-flash-lite, gemini-3-flash, gemini-3.1-pro) |
| Webview Log Textarea & Capture Hint | extension/webview-ui/src/components/LogInputArea.tsx |
<LogInputArea />, textarea handling, Ctrl+Shift+L shortcut badge |
| Webview Language & Framework Dropdowns | extension/webview-ui/src/components/ContextSelectors.tsx |
LANGUAGES array (14 langs), FRAMEWORKS array (15 frameworks) |
| Webview Results, Code Highlighting & Diff Stripping | extension/webview-ui/src/components/ResultPanel.tsx |
parseBlocks(), extractRawCode(), stripDiffMarkers(), <CodeBlockView />, <ApplyFixButton />, react-syntax-highlighter |
| Webview VS Code Bridge IPC Hook | extension/webview-ui/src/hooks/useVscode.ts |
acquireVsCodeApi() singleton cache, postMessageToExtension() |
| Webview Styles, Themes & Glow Effects | extension/webview-ui/src/index.css |
Glassmorphic variables, dark theme palette, animations (.ambient-glow, .ls-card, .ls-button) |
| Webview Entry & Root Render | extension/webview-ui/src/main.tsx |
createRoot(document.getElementById('root')!) |
| Webview Build Config (Vite + Tailwind) | extension/webview-ui/vite.config.ts |
Tailwind Vite plugin, build output setup |
| Render Cloud Deployment Spec | render.yaml |
Service logsense-backend, Node runtime, env var declarations |
🏛️ Architecture Overview
[VS Code User / Editor]
│
│ (Select error -> Ctrl+Shift+L or Right-Click Context Menu)
▼
[extension/src/extension.ts] (Extension Host)
│
│ postMessage ("setLog", "apiKeyStatus", "modelStatus")
▼
[extension/webview-ui/src/App.tsx] (React 19 + Tailwind Webview)
│
│ HTTP POST /api/v1/analyze (with log, language, context, optional BYOK key & model)
▼
[backend/src/server.js]
│
├──> [backend/src/middlewares/sanitizer.js] (Strips sk-*, AKIA*, paths before AI)
│
└──> [backend/src/controllers/analyzeController.js]
│
├──> Google Gemini AI (@google/generative-ai)
│ └─ Prompt: Explanation, Original Code, Suggested Fix
│
└──> [backend/src/models/LogHistory.js] -> MongoDB Atlas
📁 Detailed Codebase Breakdown
1. Backend (/backend)
backend/package.json: Node.js dependencies (@google/generative-ai,express,mongoose,cors,dotenv). Scripts:npm start,npm run dev(node --watch).backend/src/server.js: Express application initialization, MongoDB connection via Mongoose, CORS configuration, JSON body parsing limit (1mb),/healthendpoint, listening on portprocess.env.PORT || 3001.backend/src/routes/api.js:POST /api/v1/analyze: Chained withsanitizerMiddleware, runsanalyze.GET /api/v1/history/:userId: RunsgetHistory.
backend/src/controllers/analyzeController.js:getModel(userApiKey, modelName): Instantiates Gemini model using per-request user BYOK key if supplied; otherwise uses cached instance withprocess.env.GEMINI_API_KEY.buildprompt(log, language, context): Strict 3-section prompt asking for## Explanation,## Original Code(verbatim for search matching), and## Suggested Fix(drop-in replacement).analyze(req, res): Manages Gemini generation with 5x exponential backoff retry on 429 quota errors, regex extracts the 3 sections, strips diff prefixes (+/-), persists record to MongoDB, and returns JSON payload.
backend/src/controllers/historyController.js:getHistory(req, res): Single aggregation pipeline using$facetto simultaneously count total and retrieve paginated history records sorted newest first.
backend/src/middlewares/sanitizer.js:sanitize(text): Redacts API keys (sk-...,AKIA..., generictoken/secret/apikey) and user file paths (C:\Users\...,/Users/...,/home/...) using string guards prior to regex execution for speed.sanitizerMiddleware(req, res, next): Middleware mutatingreq.body.login place.
backend/src/models/LogHistory.js:- Mongoose model for
LogHistorystoringuserId,rawLog(capped at 5,000 chars),languageContext,aiExplanation,aiSuggestedFix,createdAt. - Compound index:
{ userId: 1, createdAt: -1 }.
- Mongoose model for
2. Extension Host (/extension)
extension/package.json:- Extension ID:
logsensebyRishabh-Sharma. - Contributed commands:
logsense.start,logsense.analyzeSelection,logsense.analyzeTerminalSelection,logsense.setApiKey,logsense.removeApiKey. - Context menus: Editor selection (
logsense.analyzeSelection), Terminal selection (logsense.analyzeTerminalSelection). - Keybinding:
Ctrl+Shift+L(Cmd+Shift+Lon macOS). - Settings:
logsense.backendUrl(default:https://logsense-backend.onrender.com).
- Extension ID:
extension/src/extension.ts:- Secret Management: Stores user's personal Gemini key in VS Code
context.secretsunder"logsense.geminiApiKey". - Model Storage: Persists user model choice in
context.globalStateunder"logsense.selectedModel". - Terminal Selection: Uses
workbench.action.terminal.copySelectionwith clipboard snapshot/restore with 1s safety timeouts. - Webview Host:
openPanel()opensWebviewPanelbeside the editor with local resource roots towebview-ui/dist. - IPC Protocol:
- Host $\rightarrow$ Webview:
apiKeyStatus,apiKeyValue,modelStatus,modelValue,backendUrl,setLog. - Webview $\rightarrow$ Host:
webviewReady,getApiKey,promptSetApiKey,setModel,getModel,applyFix,showError,showInfo.
- Host $\rightarrow$ Webview:
- "Apply Fix" 3-Tier Algorithm:
- Exact substring matching (
docText.indexOf(trimmedOrig)). - Sliding window trimmed-line sequence matching.
- Anchor matching (first line to last line of original block).
- Guarded fallback to selection or cursor position with safety modal if selection is >3x fix line count.
- Exact substring matching (
- Secret Management: Stores user's personal Gemini key in VS Code
3. Webview UI (/extension/webview-ui)
extension/webview-ui/src/App.tsx:- Root component coordinating state for log text, language, framework, API keys, selected model, and backend URL.
- Handles asynchronous
fetch()requests to${backendUrl}/api/v1/analyze. - Supports request abortion (
AbortController) when user re-analyzes or clears.
extension/webview-ui/src/components/LogInputArea.tsx:- Monospace input area with glassmorphic styling and visual hint badge for
Ctrl+Shift+L.
- Monospace input area with glassmorphic styling and visual hint badge for
extension/webview-ui/src/components/ContextSelectors.tsx:- Language dropdown: TypeScript, JavaScript, Python, Java, C#, C++, Go, Rust, Ruby, PHP, Swift, Kotlin, Dart, Shell.
- Framework dropdown: None, React, Next.js, Angular, Vue.js, Express.js, Spring Boot, Django, Flask, Rails, Laravel, ASP.NET, Flutter, NestJS, FastAPI.
extension/webview-ui/src/components/ResultPanel.tsx:- Renders Explanation and Suggested Fix blocks.
- Custom non-backtracking markdown parser
parseBlocks(). stripDiffMarkers()removes accidental diff markers (+,-) from code outputs.- Syntax highlighting with line numbers via Prism
oneDark. - "Apply Fix" button sending
postMessage("applyFix", { text, originalCode })to extension host.
extension/webview-ui/src/hooks/useVscode.ts:- Singleton caching wrapper around
window.acquireVsCodeApi(). - Exported helper
postMessageToExtension(command, data).
- Singleton caching wrapper around
extension/webview-ui/src/index.css:- CSS custom properties for LogSense theme (
--ls-bg,--ls-card,--ls-accent,--ls-glow).
- CSS custom properties for LogSense theme (
🛠️ Build & Development Commands
| Action | Command | Working Directory |
|---|---|---|
| Run backend locally | npm run dev |
/backend |
| Run backend production | npm start |
/backend |
| Build webview UI | npm run build |
/extension/webview-ui |
| Run webview dev server | npm run dev |
/extension/webview-ui |
| Compile extension | npm run compile |
/extension |
| Watch extension | npm run watch |
/extension |
| Build all extension assets | npm run build:webview && npm run compile |
/extension |
🧭 Step-by-Step Scenario Guide
Scenario 1: Changing or improving the Gemini prompt
- Open
backend/src/controllers/analyzeController.js. - Locate
buildprompt(log, language, context)around line 53. - Update instructions, section headers, or formatting guidelines.
- If output structure changes, adjust regex parsing around line 145 in
analyze().
Scenario 2: Adding a new programming language or framework
- Open
extension/webview-ui/src/components/ContextSelectors.tsx. - Add the item to
LANGUAGESorFRAMEWORKSarrays at lines 10–20. - Run
npm run buildinsideextension/webview-ui.
Scenario 3: Modifying how "Apply Fix" updates user files
- Open
extension/src/extension.ts. - Locate
case "applyFix":around line 357. - Modify or add replacement matching strategies (exact match, line-by-line, or AST).
- Run
npm run compileinsideextension.
Scenario 4: Adding secret or path redaction patterns
- Open
backend/src/middlewares/sanitizer.js. - Add a new
{ guard, regex, replacement }object toSECRET_PATTERNSorPATH_PATTERNS.