CoolFace
Apppublic

anmishka/LOKR-assistant

sourceHugging Faceupdated 4mo agoView on Hugging Face
0likes
App README

<div align="center">

πŸ›‘οΈ Lokr Assistant β€” Sentinel 2.0

Multi-Agent Codebase Defense & Orchestration

Diagnose bugs. Review diffs. Gate deployments. All grounded in your actual codebase.

![Python 3.8+](https://python.org) ![Streamlit](https://streamlit.io) ![Ollama](https://ollama.com) ![Agent Autonomy]() ![26x Efficient]() ![Fail-Loud]() ![License: MIT](LICENSE)

⭐ Hackathon Achievements

  • β€”βœ… 3 Equally-Polished Features β€” Repair, Review, Prevent modes (not 1 perfect feature)
  • β€”βœ… Real Agent Autonomy β€” Agents autonomously call Lokr via lokr_requests, not orchestrator-driven
  • β€”βœ… 26x Context Efficiency β€” Initial analyzer input: 21k β†’ 800 tokens through agentic discovery
  • β€”βœ… 3.1x Revision Speed β€” Safety β†’ Action targeted feedback saves 70% of tokens per revision cycle
  • β€”βœ… Forensically Hardened β€” Fail-loud validation, token tracking, grounding ratio logging

⚠️ Note for Judges (Configuration)

To properly evaluate this multi-agent architecture, please configure the LLM backend via the UI sidebar:

  1. 1.API URL & Key: Please input your own OpenAI-compatible API URL and API Key. Examples are provided in the UI placeholders.
  2. 2.Model Selection: Please input the exact Model Name for your chosen provider.
  3. 3.Minimum Requirements: You MUST use a highly capable model with 33B parameters or higher (e.g., Qwen2.5-Coder-32B-Instruct). The framework orchestrates multiple specialized agents that rely on complex JSON output parsing; smaller models will suffer from context truncation.

</div>


🎯 What Is Lokr Assistant?

Lokr Assistant: Sentinel 2.0 is a production-hardened multi-agent AI framework designed to act as a senior engineering copilot. Unlike generic LLM coding tools that suffer from context bloat and hallucination, Lokr Assistant grounds its decision-making in a localized dependency graph using our custom lokr engine.

⭐ Hackathon Innovations

  1. 1.Agentic Context Discovery β€” Analyzer starts with just 800 tokens (vs. 21k) and autonomously queries Lokr for precise dependencies. 26x context reduction, 62% inference cost savings.
  1. 1.Safety β†’ Action Fast-Path β€” Rejected patches don't trigger full pipeline restart. Safety agent provides targeted revision suggestions directly to Action. 70% token savings per revision cycle.
  1. 1.Deterministic Pre-Scan β€” Regex-based scanner catches CAT-0 backdoors (debug headers, hardcoded admin bypasses) before LLM runs. Critical vulnerabilities can't be hallucinated away.
  1. 1.Fail-Loud Architecture β€” All agents validate their own JSON output. Invalid schemas raise explicit errors instead of silently degrading to stub data. Zero silent failures.

Unlike generic AI coding tools, Lokr Assistant:

  • β€”Verifies findings against your actual code structure (not hallucinations)
  • β€”Stays focused through agentic context discovery (800 tokens, not 21k)
  • β€”Makes evidence-based decisions using Lokr's verified dependency graph
  • β€”Fails loudly when agents malfunction (no silent degradation to stub data)
  • β€”Revises efficiently through direct Safety β†’ Action feedback loops

πŸš€ Why Lokr Assistant Wins

Against Generic AI Assistants (ChatGPT, Copilot, Claude)

  • β€”βœ… Grounded in Code Reality β€” Every finding cross-referenced against Lokr's dependency graph. Generic assistants hallucinate; we verify.
  • β€”βœ… Agent Autonomy β€” Agents autonomously request code context via lokr_requests instead of receiving 21k-token brain dumps. Stays focused, reduces hallucination.
  • β€”βœ… Fail-Loud, Not Silent β€” Malformed LLM outputs raise explicit errors instead of degrading silently to stub data.
  • β€”βœ… 3.1x Faster Revisions β€” Safety rejections route directly to Action with revision_suggestions, not full pipeline restart. Saves 70% of tokens per revision.
  • β€”βœ… Deterministic Pre-Scan β€” Catches CAT-0 backdoors (debug headers, auth bypasses, logic inversions) with regex before LLM runs.

Against Static Analysis Tools (Bandit, ESLint, SonarQube)

  • β€”βœ… Human Context β€” Understands why code matters, not just AST patterns
  • β€”βœ… Intention Grounding β€” Distinguishes between "safe README update" and "removed auth middleware"
  • β€”βœ… Executive Summary β€” Produces human-readable diagnoses, not raw linter warnings
  • β€”βœ… Risk Scoring β€” Contextual severity (same bug is critical in payment code, minor in logging)

Against Manual Code Review

  • β€”βœ… 24/7 Availability β€” No context-switching overhead, consistent sleep schedule
  • β€”βœ… Evidence Trail β€” Every decision logged with forensic timestamps for audit
  • β€”βœ… Consistent Standards β€” Same rigor for 3am deploys and Monday code reviews
  • β€”βœ… Impossible to Skip β€” Deployment gate blocks unsafe changes automatically

πŸ“Š Performance & Efficiency

Context Optimization (Sentinel 2.0)

Lokr Assistant uses agentic context discovery instead of context bombing:

MetricBeforeAfterImprovement
Initial Analyzer Context21,000 tokens800 tokens26x smaller
Context + 2 Lokr Requests~25,000 tokens3,500 tokens7x smaller
Full Repair Pipeline8,500 tokens3,200 tokens62% reduction
Safety Revision Cost2,500 tokens700 tokens72% reduction
Cost per Repair Run$0.13$0.05$0.08 savings

What This Means:

  • β€”πŸš€ 4-8x faster LLM inference (smaller context = faster tokens)
  • β€”πŸ’° $3.75 saved per 50 runs (real cost reduction)
  • β€”πŸŽ― Better accuracy (focused context = fewer hallucinations)
  • β€”βš‘ Faster iteration on the hackathon (critical advantage)

Token Flow Visualization

β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚ BEFORE: Orchestrator Pre-Fetches Everything            β”‚
β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€
β”‚ Orchestrator:                                           β”‚
β”‚  - Finds 20 relevant files via Lokr                    β”‚
β”‚  - Dumps ALL file summaries (3k tokens)                β”‚
β”‚  - Includes full middleware source (5k tokens)         β”‚
β”‚  - Adds relationship graph (2k tokens)                 β”‚
β”‚  β†’ Analyzer receives 21k tokens of bloat               β”‚
β”‚  β†’ LLM struggles with unfocused context                β”‚
β”‚  β†’ Hallucinations increase with context size           β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚ AFTER: Agentic Context Discovery                       β”‚
β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€
β”‚ Orchestrator β†’ Analyzer (800 tokens):                  β”‚
β”‚  "Here's the bug report + 2-3 entry functions"         β”‚
β”‚                                                         β”‚
β”‚ Analyzer β†’ Orchestrator:                               β”‚
β”‚  "I need: dependencies of deletePet, auth middleware"  β”‚
β”‚                                                         β”‚
β”‚ Orchestrator β†’ Lokr β†’ Analyzer (2.7k tokens):          β”‚
β”‚  [Results of requested queries]                        β”‚
β”‚                                                         β”‚
β”‚ Analyzer re-runs with focused context                  β”‚
β”‚  β†’ Produces grounded diagnosis                         β”‚
β”‚  β†’ Fewer hallucinations (less context noise)           β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

Evidence Grounding Quality

Evidence TypeOld MatchingNew MatchingResult
Code with abbreviations (...)❌ False negativeβœ… Token-based matchGROUNDED
Comment-only evidenceβœ… False positive❌ Correctly rejectedUNGROUNDED
Partial code quotes❌ Substring failβœ… First/last tokens matchGROUNDED

Forensic Output Example:

[FORENSIC] βœ“ GROUNDED: Hardcoded debug header bypasses authentication
[FORENSIC] βœ“ GROUNDED: Missing ownership check before deleting pet
[FORENSIC] βœ— UNGROUNDED: Cache not invalidated (mentioned in comment only)
[FORENSIC] Evidence Verification: 2/3 findings grounded (67%) βœ“ PASS

πŸ—οΈ Architecture & Data Flow

System Architecture

Lokr-assistant/
β”œβ”€β”€ app.py                          # Streamlit UI with live agent progress
β”œβ”€β”€ main.py                         # CLI entry point
β”‚
β”œβ”€β”€ agents/                         # Individual agent implementations
β”‚   β”œβ”€β”€ analyzer.py                 # Diagnosis & readiness assessment
β”‚   β”œβ”€β”€ action.py                   # Patch generation & blocker identification
β”‚   β”œβ”€β”€ safety.py                   # Risk scoring & go/no-go decisions
β”‚   └── validator.py                # Fix validation & deploy checklists
β”‚
β”œβ”€β”€ modes/
β”‚   └── orchestrator.py             # Single entry point for intent classification, agent loop, pre-scan, and forensics
β”‚
β”œβ”€β”€ lokr/
β”‚   β”œβ”€β”€ client.py                   # HTTP client for Lokr
β”‚   └── service.py                  # Graph-RAG integration layer
β”‚
└── shared/
    β”œβ”€β”€ prompts.py                  # Mode-specific system prompts
    β”œβ”€β”€ llm_client.py               # Ollama LLM client
    └── base_agent.py               # Base agent class

Agent Pipeline Flow

The orchestrator (modes/orchestrator.py) is the single pipeline entry point for both the Streamlit app and the CLI. All requests follow a unified code path for intent classification and agent execution.

User Request
    ↓
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚ Intent Classifier                       β”‚
β”‚ (Fast: keywords + LLM tiebreaker)       β”‚
β””β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
     β”‚        β”‚        β”‚        β”‚
     ↓        ↓        ↓        ↓
  REPAIR   REVIEW   PREVENT  EXPLAIN
    β”‚        β”‚        β”‚        β”‚
    β””β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”˜
             ↓
    β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
    β”‚ Deterministic Pre-Scan         β”‚
    β”‚ (Regex for CAT-0 backdoors)    β”‚
    β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
                     ↓
    β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
    β”‚ ANALYZER AGENT                 β”‚
    β”‚ Input: Bug report + entry pts  β”‚
    β”‚ Output: Diagnosis + evidence   β”‚
    β”‚         + lokr_requests        β”‚
    β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
                 β”‚
    β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β–Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
    β”‚ Lokr Graph-RAG Loop           β”‚
    β”‚ Execute lokr_requests         β”‚
    β”‚ Append context, re-analyze    β”‚
    β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
                 ↓
    β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
    β”‚ ACTION AGENT                   β”‚
    β”‚ Input: Diagnosis + history     β”‚
    β”‚ Output: Patch/Blockers +       β”‚
    β”‚         revision_suggestions   β”‚
    β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
                 β”‚
    β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β–Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
    β”‚ SAFETY AGENT                  β”‚
    β”‚ Input: Proposed fix           β”‚
    β”‚ Output: Risk score + decision  β”‚
    β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
                 β”‚
        β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
        β”‚                  β”‚
    βœ… PASS           ❌ REJECT
        β”‚                  β”‚
        ↓              β”Œβ”€β”€β”€β”€β–Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
    β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”    β”‚ Fast Path:      β”‚
    β”‚ VALIDATOR  β”‚    β”‚ Route to Action β”‚
    β”‚ (optional) β”‚    β”‚ + suggestions   β”‚
    β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜    β”‚ Cap: 3 loops    β”‚
        β”‚              β”‚ Then: Escalate  β”‚
        ↓              β””β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
    πŸ“‹ RESULT              β”‚
                           ↓
                    Full Analyzer Restart
                      (fallback)

Mode-Specific Routing

INPUT: "Users can delete other people's pets"
  ↓
CLASSIFIER detects: repair
  ↓
REPAIR MODE PIPELINE:
  β”œβ”€ Pre-Scan: Checks for auth issues
  β”œβ”€ Analyzer: Diagnoses ownership check missing
  β”œβ”€ Action: Generates patch with ownership validation
  β”œβ”€ Safety: Confirms patch is safe
  β”œβ”€ Validator: Creates test cases
  └─ Output: Patch + tests + deployment notes

INPUT: "Is this code diff safe?"
  ↓
CLASSIFIER detects: review
  ↓
REVIEW MODE PIPELINE:
  β”œβ”€ Pre-Scan: Checks for logic inversions (|| β†’ &&)
  β”œβ”€ Analyzer: Understands what changed
  β”œβ”€ Action: Recommends improvements
  β”œβ”€ Safety: Assesses deployment risk
  └─ Output: Review report + approval decision

INPUT: "Can I deploy?"
  ↓
CLASSIFIER detects: prevent
  ↓
PREVENT MODE PIPELINE:
  β”œβ”€ Pre-Scan: Hard-checks for blockers
  β”œβ”€ Analyzer: Deployment readiness
  β”œβ”€ Action: Identifies pre-deploy requirements
  β”œβ”€ Safety: Go/No-Go decision
  └─ Output: Readiness report + blockers

πŸ”¬ Architectural Innovations (Hackathon Built)

1. Agentic Context Discovery

Problem: Most AI systems pre-fetch 21k tokens of context, overwhelming the LLM.

Solution: Analyzer starts with minimal context (800 tokens) and autonomously requests additional details:

Analyzer: "I see a bug in deletePet. I need to understand the ownership validation."
Orchestrator: [executes lokr_requests: ["get dependencies of deletePet"]]
Lokr: [returns dependency graph + validation functions]
Analyzer: [re-analyzes with new context, produces grounded diagnosis]

Benefit: Analyzer stays focused, fewer hallucinations, 26x context efficiency.

2. Safety β†’ Action Fast-Path Revision

Problem: When Safety rejects a patch, the entire pipeline restarts (2x cost).

Solution: Safety provides revision_suggestions; Action revises directly.

BEFORE (2x cost):
Safety rejects β†’ Analyzer re-analyzes β†’ Action re-patches β†’ Safety re-checks

AFTER (0.3x cost):
Safety rejects (with suggestions) β†’ Action revises β†’ Safety re-checks

Guardrails:

  • β€”Capped at 3 iterations (prevents infinite loops)
  • β€”Falls back to Analyzer if no suggestions provided
  • β€”Escapes to full restart if needed

3. Deterministic Pre-Scan

Problem: LLMs sometimes miss critical security issues.

Solution: Regex-based scanner catches CAT-0 patterns before LLM runsβ€”impossible to hallucinate away.

Patterns caught:

  • β€”πŸ”΄ X-Debug: true headers in middleware (instant auth bypass)
  • β€”πŸ”΄ req.user = {role: 'admin'} hardcoded assignments
  • β€”πŸ”΄ Removed authentication middleware
  • β€”πŸ”΄ Logic inversions (|| β†’ && in validation)
  • β€”πŸ”΄ Required DB fields without migrations

Output: Mandatory findings injected into Analyzer context:

[PRESCAN] πŸ”΄ Detected 2 backdoor pattern(s)
  [PRESCAN-001] Debug Header in middleware/auth.js:12
  [PRESCAN-002] Auth Bypass Pattern in middleware/auth.js:15

4. Fail-Loud Schema Validation

Problem: LLMs sometimes return malformed JSON; systems silently degrade to stubs.

Solution: All agents validate their own output; invalid schemas raise ValueError.

python
# BEFORE (silent failure):
if not parsed and response.strip():
    return {"diagnosis": "Code analysis (stub)...", "confidence": 0.5}  # Fake data!

# AFTER (explicit failure):
required_fields = {"chain_of_thought", "contribution", "lokr_requests"}
for field in required_fields:
    if field not in parsed:
        raise ValueError(f"Missing required field: {field}")

Orchestrator catches and terminates:

state["status"] = "failed"
state["error"] = "ANALYZER_VALIDATION_ERROR: Missing required field: contribution"

5. Token-Based Evidence Grounding

Problem: Substring matching fails when LLMs abbreviate code with ....

Solution: Token-based matching handles abbreviations gracefully.

Evidence: "const userId = req.params.userId; // ..."
Old: Exact substring β†’ NOT FOUND ❌
New: First 3 + last 3 tokens β†’ FOUND βœ…

Logs grounding ratio; warns if <50% of findings are grounded.


πŸ”‘ Key Design Decisions

DecisionRationaleImpact
Minimal Context InjectionAnalyzer starts with ~800 tokens instead of ~21k26x smaller context, fewer hallucinations
Deterministic Pre-ScanRegex catches CAT-0 patterns before LLMCan't hallucinate away security issues
Fail-Loud AgentsAgents raise ValueError on malformed outputNo silent degradation to stubs
Safety β†’ Action Fast-PathTargeted revisions skip Analyzer70% token savings per revision
Token-Based EvidenceMeaningful code tokens instead of substringsHandles LLM abbreviations correctly
Cascading SkepticismEach agent distrusts unverified claimsGrounded findings only
Cross-ReferencingAction reads both Analyzer + raw inputCatches dropped evidence
Automatic BlockersSecurity conditions hardcoded (LLM can't override)Prevents rubber-stamping
LLM + Fast-Path ClassificationKeywords + LLM tiebreakerInstant intent detection
Progress CallbacksReal-time st.status updatesTransparent pipeline

πŸš€ Features

πŸ”§ Repair Mode β€” "Fix this bug"

  • β€”Diagnoses bugs using verified code context from Lokr
  • β€”Proposes targeted patches with exact file paths and line numbers
  • β€”Safety agent evaluates risk before any fix is accepted
  • β€”Safety β†’ Action fast-path: Rejected patches get targeted revision suggestions without full pipeline restart
  • β€”Automatic revision loop if validation fails

πŸ“ Review Mode β€” "Is this diff safe?"

  • β€”Analyzes code diffs for logic regressions, security issues, and quality
  • β€”Mental execution of boolean logic β€” detects when || β†’ && weakens validation
  • β€”Produces structured observations, recommendations, and an approval decision
  • β€”Catches subtle issues like weakened error handling conditions

πŸ›‘οΈ Prevent Mode β€” "Can I deploy?"

  • β€”Deployment readiness gate with evidence-grounded analysis
  • β€”Automatic blocker detection for:
  • β€”πŸ”’ Removed authentication middleware
  • β€”πŸ’Ύ Required DB fields without migrations
  • β€”βš οΈ FIXME comments that warn against merging
  • β€”πŸ§ͺ Failing CI tests related to changed files
  • β€”Cross-references user claims against Lokr's file summaries
  • β€”Issues SAFE_TO_DEPLOY, PROCEED_WITH_CAUTION, or NO_GO_FIX_BLOCKERS

🎬 Demo Scenarios

Note: The repository includes a lokr-demo-app directory which acts as the vulnerable target application for these scenarios. Make sure ./lokr-demo-app is selected as the Project Directory in the UI.

Scenario 1: Safe Deployment βœ…

Input:

"We updated the README and tweaked some CSS. Can I deploy this?"

Expected Result:

βœ… SAFE_TO_DEPLOY
Readiness: 100% | Risk: LOW
No blockers detected

Scenario 2: Dangerous Deployment 🚫

Input:

"Can I deploy? I changed auth.js, admin.js, and User.js. I removed the admin middleware from the user list route and added a FIXME comment. I also added a required phoneNumber field to the User model without a migration. CI is showing one failing test."

Expected Result:

🚫 NO_GO_FIX_BLOCKERS
Readiness: 35% | Risk: CRITICAL

Blockers:
  [1] Authentication middleware removed from /admin route
  [2] FIXME comment warns against merging
  [3] Required DB field without migration plan
  [4] Failing CI test: test/users.spec.js (L45)

Scenario 3: Backdoor Detection πŸ”΄

Input:

"There's a bug in our pet API β€” users can delete other users' pets."

Pre-scan detects:

[PRESCAN] πŸ”΄ Detected 2 backdoor pattern(s)
  [PRESCAN-001] Hardcoded Debug Header in src/middleware/auth.js:12
  [PRESCAN-002] Authentication Bypass / Backdoor in src/middleware/auth.js:15

Expected Result: Analyzer is forced to include these CAT-0 findings in its diagnosis, ensuring the backdoor is addressed in the patch.

πŸ› BUG DIAGNOSIS

Root Cause:
Missing ownership check allows users to delete pets they don't own.
Additionally: Debug header in auth middleware disables authentication.

Findings:
  [CRITICAL] Missing ownershipCheck before deletePet()
  [CRITICAL] Debug header 'X-Debug: true' in auth.js:12 (pre-scanned)
  
Patch: Add ownership validation + remove debug header

Scenario 4: Logic Regression Review πŸ”

Input: Paste the following diff into the chat box:

diff
--- a/src/middleware/permission.js
+++ b/src/middleware/permission.js
@@ -10,7 +10,7 @@ function checkAccess(req, res, next) {
     const isAdmin = req.user.role === 'admin';
     const hasPermission = req.user.permissions.includes('write');
 
-    if (!isAdmin || !hasPermission) {
+    if (!isAdmin && !hasPermission) {
         return res.status(403).json({ error: "Access Denied" });
     }

Expected Result:

⚠️ REQUEST_CHANGES
Risk: HIGH

Observation:
The validation condition was weakened from 
  `if (!isAdmin || !hasPermission)` 
to 
  `if (!isAdmin && !hasPermission)`

This means unauthorized users can now pass if they're not an admin 
(regardless of permission check).

Recommendation:
Revert the operator change, or add explicit role checks.

🧠 How It Works: End-to-End

Evidence Grounding Pipeline

User Input
    ↓
Intent Classifier (keywords + LLM)
    ↓
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚ Deterministic Pre-Scan              β”‚
β”‚ (Regex for CAT-0 backdoors)         β”‚
β”‚ Output: Mandatory safety findings   β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
           ↓
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚ ANALYZER AGENT                      β”‚
β”‚ Input: Bug report + entry points    β”‚
β”‚        + pre-scan findings          β”‚
β”‚                                     β”‚
β”‚ Generates: diagnosis + evidence +   β”‚
β”‚            lokr_requests            β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
           ↓
   β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
   β”‚ lokr_requests     β”‚ (autonomous)
   β”‚ found?            β”‚
   β””β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”˜
        β”‚      β”‚
        ↓      ↓ No
       YES    Continue
        β”‚
        ↓
   β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
   β”‚ Execute Lokr calls β”‚
   β”‚ Append results     β”‚
   β”‚ Loop back to       β”‚
   β”‚ Analyzer (max 3x)  β”‚
   β””β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
            ↓
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚ ACTION AGENT                        β”‚
β”‚ Input: Diagnosis + history +        β”‚
β”‚        safety_feedback (if revision)β”‚
β”‚                                     β”‚
β”‚ Generates: patch OR blockers        β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
           ↓
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚ SAFETY AGENT                        β”‚
β”‚ Input: Proposed fix                 β”‚
β”‚ Output: Risk score + decision       β”‚
β”‚         + revision_suggestions      β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
           ↓
    β”Œβ”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”
    β”‚              β”‚
  SAFE        UNSAFE
    β”‚              β”‚
    ↓          β”Œβ”€β”€β”€β–Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
    β”‚          β”‚ Revision Loop?  β”‚
    β”‚          β””β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”˜
    β”‚              β”‚      β”‚
    β”‚            YES      NO
    β”‚              β”‚      β”‚
    β”‚              ↓      ↓
    β”‚          [Action]  [Analyzer]
    β”‚          (0.3x)    (fallback)
    β”‚              β”‚
    β””β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”˜
           ↓
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚ VALIDATOR AGENT                     β”‚
β”‚ (Optional)                          β”‚
β”‚ Input: Final fix                    β”‚
β”‚ Output: Test cases + checklists     β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
           ↓
      πŸ“‹ RESULT

Agent Responsibilities

AgentRoleKey Constraint
Pre-ScanDeterministic regex scan for backdoorsRuns before LLM; findings are injected as mandatory context
AnalyzerDiagnoses issues, assesses readinessStarts with minimal context; requests more via lokr_requests; raises ValueError on schema failure
ActionGenerates fixes / identifies blockersReads safety feedback for targeted revisions; cross-references raw user input
SafetyRisk scoring, go/no-go decisionProvides revision_suggestions for fast-path Action revision; can't rubber-stamp
ValidatorValidates fixes, generates checklistsTriggers revision loop on failure

πŸ” Pipeline Safety Guardrails

GuardrailMechanismBenefit
Schema ValidationAll agents raise ValueError on malformed JSONNo stub fallbacks, explicit errors
Evidence GroundingToken-based matching handles LLM abbreviations; logs ratio<10% false rejections, visible quality
Soft-Fail ThresholdWarns (not aborts) if <50% findings grounded; Safety is final judgeAllows imperfect-but-useful findings
Loop DetectionSafety↔Action: 3 iterations. Main: 25 iterationsPrevents infinite loops
Token BudgetForensic logging warns if analyzer input > 8k tokensEarly warning of context bloat
Context Growth Tracking[FORENSIC] logs track token delta per Lokr requestVisible efficiency gains
Hard BlockersSecurity conditions hardcoded (auth removal, DB migrations)LLM can't rubber-stamp

⚑ Quick Start

Prerequisites

  • β€”Python 3.8+
  • β€”Ollama (for local privacy) OR any OpenAI-compatible API
  • β€”Lokr (dev-oracle) indexed on your project (optional but recommended)

Installation

bash
# Clone the repository with the Lokr engine bundled (Submodule)
git clone --recurse-submodules https://github.com/Anasmtaweh/Lokr-assistant.git
cd Lokr-assistant

# (Optional) If you forgot --recurse-submodules, run:
# git submodule update --init --recursive

Running via Docker (Recommended)

The easiest way to run the assistant with all dependencies and the demo app mounted:

bash
# Export your API Key if you plan to use a remote model
export API_KEY="your_api_key_here"

# Build and start the container
docker-compose up -d --build

The UI will be available at http://localhost:8501.

Running Locally (Python Venv)

bash
# Create virtual environment
python -m venv venv
source venv/bin/activate

# Install dependencies
pip install -r requirements.txt

You can start the UI using the provided helper script:

bash
./start.sh

Or manually:

bash
streamlit run app.py
πŸ’‘ Tip for Local Users: If you are running the app locally, you can analyze your own codebase! Just change the "Project Directory" path in the UI sidebar to point to your local project folder and click "Re-index Project". This will trigger the Lokr engine to extract ASTs and build the semantic graph for your code.

🌐 Running on Public Environments (Hugging Face Spaces)

If you are hosting or visiting Lokr Assistant on a public platform like Hugging Face Spaces:

  • β€”Using Remote APIs: If the space owner configured an API_KEY secret, it will auto-populate. However, any user can simply delete the pre-filled key in the sidebar and paste their own API key without affecting the space or other users.
  • β€”Using Local Models (Ollama) Remotely: A public space runs on a remote server. Using http://localhost:11434 will try to connect to the space's server, not your personal computer. To connect a public space to your local Ollama:
  • β€”Expose your local Ollama port (11434) using a tool like Ngrok.
  • β€”Paste your Ngrok URL into the "Ollama Base URL" field in the sidebar.
  • β€”Select "Custom..." from the model dropdown and type your model name (e.g., qwen2.5-coder:7b).

The UI will:

  1. 1.Auto-detect available Ollama models
  2. 2.Allow switching between local Ollama and remote APIs
  3. 3.Show live agent progress with st.status updates
  4. 4.Display forensic logs and token counts in expanders

Run via CLI

bash
# Repair mode
python main.py repair -c "your code" --model <model> --api-url <url>

# Review mode
python main.py review -d "your diff" --model <model> --api-url <url>

# Prevent mode
python main.py prevent -c "your code" --model <model> --api-url <url>
Note: Add --api-key for remote APIs and --project /path/to/project to enable Lokr Graph-RAG context.

πŸ› οΈ Tech Stack

  • β€”LLM Backend: Dual-support for Ollama (local/private) and OpenAI-Compatible APIs via UI toggle.
  • β€”Code Intelligence: Lokr (Bundled as a submodule)
  • β€”Parsing: Tree-sitter (AST extraction for JS, TS, Python, etc.)
  • β€”Vector Search: ChromaDB (Semantic node retrieval)
  • β€”Graph Engine: NetworkX (Dependency graph + topological sorting)
  • β€”UI: Streamlit with real-time progress tracking
  • β€”Language: Python 3.8+

πŸ“„ License

MIT License β€” see LICENSE for details.


<div align="center">

Built for the hackathon. Hardened for production.

Lokr Assistant β€” because "LGTM" shouldn't be your deployment strategy.

Questions? Open an issue or ping the maintainer.

</div>