Skip to content
Merged
Show file tree
Hide file tree
Changes from 45 commits
Commits
Show all changes
46 commits
Select commit Hold shift + click to select a range
d2c43ec
feat(visualizer): add zero-latency static analysis suite
Sidhant0707 May 29, 2026
5f61b5a
refactor(analyze): decompose page.tsx into modular hooks and UI compo…
Sidhant0707 May 29, 2026
5919ceb
Merge branch 'main' into feat/static-analysis
Sidhant0707 May 29, 2026
eaf7813
fix: restore clean refactored page.tsx, remove merge pollution
Sidhant0707 May 29, 2026
5f9c558
feat(visualizer): implement multi-source reverse BFS for PR blast radius
Sidhant0707 May 29, 2026
148e87e
fix: restore missing AiGate import in DoctorPanel
Sidhant0707 May 29, 2026
d16e2db
merge: sync with main, keep feat/pr-blast-radius changes
Sidhant0707 May 29, 2026
aad4d37
feat(analysis): implement pure DSA architecture insights and interact…
Sidhant0707 May 29, 2026
a9b3931
fix: resolve merge conflicts with main — keep pagerank feature, add c…
Sidhant0707 May 29, 2026
ada8623
feat: add Lemon Squeezy payment integration
Sidhant0707 May 30, 2026
726d72c
fix: replace auth-helpers-nextjs with supabase/ssr in checkout route
Sidhant0707 May 30, 2026
ed52cb4
fix: use correct SUPABASE_SERVICE_KEY env var in webhook
Sidhant0707 May 30, 2026
f88ae31
feat: wire up Specialist tier on pricing page
Sidhant0707 May 30, 2026
bee687b
fix: update free tier limit from 10 to 5 autopsies per day
Sidhant0707 May 30, 2026
f7ffc83
fix: resolve merge conflict in DoctorPanel
Sidhant0707 May 30, 2026
099023f
feat: update pricing constants - Specialist tier live at ₹99/mo
Sidhant0707 May 30, 2026
9abefa0
feat: reduce token usage and add deepseek-r1 for pro chat tier
Sidhant0707 May 30, 2026
679503e
fix: add missing isPro and diagnosticCount props to DebugInterface in…
Sidhant0707 May 30, 2026
4e9b6d6
Merge branch 'main' into feat/token-optimization
Sidhant0707 May 30, 2026
a4d341b
feat: gate Auto-Patch behind pro tier in RiskDashboard
Sidhant0707 May 30, 2026
840c63a
fix: replace amber pro accents with project-native slate/white palette
Sidhant0707 May 30, 2026
7df0a03
Merge branch 'main' into feat/token-optimization
Sidhant0707 May 30, 2026
fc17a29
fix: replace amber pro accents with project-native slate/white palette
Sidhant0707 May 30, 2026
a0b35d4
refactor(debug): optimise engine pipeline
Sidhant0707 May 30, 2026
6b7892c
refactor(arch-insights): fix AP algorithm, types, tests, and Pro gate UI
Sidhant0707 May 30, 2026
3171587
The graph computation layer — wherever computePageRank / findSCCs live
Sidhant0707 May 30, 2026
0001c25
fix(blueprint-map): compute PageRank internally when scores not passe…
Sidhant0707 May 31, 2026
88c979f
merge: integrate remote main with nerve-center pagerank fix
Sidhant0707 May 31, 2026
ad7f486
merge: use fix/nerve-center-pagerank version of ArchitectureMap
Sidhant0707 May 31, 2026
21969b1
fix: always insert new row for logged-in users on re-analysis
Sidhant0707 May 31, 2026
8319650
perf: reduce groq token spend with caching and model switch
Sidhant0707 May 31, 2026
0f89444
feat: integrate lemon squeezy, semantic caching, betweenness centrali…
Sidhant0707 Jun 1, 2026
31ccefd
seo: og-image, sitemap, robots.txt, schema markup
Sidhant0707 Jun 7, 2026
714cfb3
seo: add google search console verification
Sidhant0707 Jun 7, 2026
e9cfb04
changed pricing section
Sidhant0707 Jun 15, 2026
88af031
feat: complete razorpay checkout and webhook integration
Sidhant0707 Jun 16, 2026
c048846
Merge branch 'main' into feat/razorpay-integration
Sidhant0707 Jun 16, 2026
6468681
feat: hardened razorpay subscription route
Sidhant0707 Jun 16, 2026
75fe065
Merge branch 'main' into feat/razorpay-integration
Sidhant0707 Jun 16, 2026
5979dff
ci: retrigger build with env vars
Sidhant0707 Jun 16, 2026
816fd7f
fix: sync usage limits with shared constants, add pro tier support
Sidhant0707 Jun 16, 2026
1b3c803
fix: resolve isPro crash, import diagnostic limit from constants
Sidhant0707 Jun 16, 2026
daccdd6
fix: tighten pricing page spacing, fix TS errors, swap decommissioned…
Sidhant0707 Jun 16, 2026
59806c1
fix: rename gemini/groq refs to cerebras, fix chat runtime and pro model
Sidhant0707 Jun 16, 2026
6133448
changed cerebras to groq
Sidhant0707 Oct 30, 2026
ca5445f
Merge branch 'main' into fix/analysis-groq-fallback
Sidhant0707 Oct 30, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 12 additions & 12 deletions app/analyze/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -66,28 +66,28 @@ const AnalyzeContent = memo(() => {
} = await supabase.auth.getUser();
if (!user) return;

const [profileRes, diagRes] = await Promise.all([
const today = new Date();
today.setUTCHours(0, 0, 0, 0);

const [profileRes, diagRes] = await Promise.allSettled([
supabase
.from("profiles")
.select("plan_tier")
.eq("id", user.id)
.single(),
supabase
.from("diagnostic_runs")
.from("debug_analyses")
.select("*", { count: "exact", head: true })
.eq("user_id", user.id)
.gte(
"created_at",
(() => {
const d = new Date();
d.setUTCHours(0, 0, 0, 0);
return d.toISOString();
})(),
),
.gte("created_at", today.toISOString()),
]);

setIsPro(profileRes.data?.plan_tier === "pro");
setDiagnosticCount(diagRes.count ?? 0);
if (profileRes.status === "fulfilled") {
setIsPro(profileRes.value.data?.plan_tier === "pro");
}
if (diagRes.status === "fulfilled") {
setDiagnosticCount(diagRes.value.count ?? 0);
}
}

resolveProStatus();
Expand Down
4 changes: 2 additions & 2 deletions app/api/ai/route.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { streamAnalyzeWithGemini } from "@/lib/gemini";
import { streamAnalyzeWithCerebras } from "@/lib/cerebras";
import { NextRequest, NextResponse } from "next/server";
import { cookies } from "next/headers";
import { createServerClient } from "@supabase/ssr";
Expand Down Expand Up @@ -108,7 +108,7 @@ export async function POST(req: NextRequest) {
}

// ── 6. Stream AI response ─────────────────────────────────────────────────
const responseStream = await streamAnalyzeWithGemini(
const responseStream = await streamAnalyzeWithCerebras(
repoName,
description,
entryPoints,
Expand Down
163 changes: 114 additions & 49 deletions app/api/chat/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,44 +5,83 @@ import { checkUsageLimit } from "@/lib/usage";

export const maxDuration = 60;
export const dynamic = "force-dynamic";
export const runtime = "edge";
export const runtime = "nodejs";

// ── Groq config ───────────────────────────────────────────────────────────────
const GROQ_API_KEY = process.env.GROQ_API_KEY;
const GROQ_URL = "https://api.groq.com/openai/v1/chat/completions";
const GROQ_URL = "https://api.groq.com/openai/v1/chat/completions";

// Free tier: fast + cheap, smaller context
// Free tier
const FREE_MODEL = "llama-3.3-70b-versatile";
const FREE_CONTEXT_SIZE = 6000;
const FREE_CONTEXT_SIZE = 6_000;
const FREE_MAX_TOKENS = 512;

// Pro tier: smarter, larger context
const PRO_MODEL = "deepseek-r1-distill-llama-70b";
const PRO_CONTEXT_SIZE = 14000;
const PRO_MAX_TOKENS = 1024;
// Pro tier
const PRO_MODEL = "openai/gpt-oss-120b";
const PRO_CONTEXT_SIZE = 20_000;
const PRO_MAX_TOKENS = 2_048;

// ── Types ─────────────────────────────────────────────────────────────────────
interface ChatMessage {
role: "user" | "assistant" | "system";
content: string;
}

interface RequestBody {
messages: ChatMessage[];
repoContext?: unknown;
}

// ── Helper: build a typed error response ─────────────────────────────────────
function errorResponse(message: string, status: number) {
return NextResponse.json({ error: message }, { status });
}

// ── Route handler ─────────────────────────────────────────────────────────────
export async function POST(req: NextRequest) {
// 1. Guard: API key must be present
if (!GROQ_API_KEY) {
console.error("GROQ_API_KEY is not set.");
return errorResponse("Server misconfiguration: missing API key.", 500);
}

// 2. Parse + validate body
let body: RequestBody;
try {
if (!GROQ_API_KEY) {
return NextResponse.json({ error: "Missing Groq API Key" }, { status: 500 });
}
body = await req.json();
} catch {
return errorResponse("Invalid JSON body.", 400);
}

const { messages, repoContext } = await req.json();
const { messages, repoContext } = body;

if (!messages || !Array.isArray(messages)) {
return NextResponse.json({ error: "Messages missing" }, { status: 400 });
}
if (!Array.isArray(messages) || messages.length === 0) {
return errorResponse("'messages' must be a non-empty array.", 400);
}

// 3. Auth + plan check via Supabase
let isPro = false;

try {
const cookieStore = await cookies();
const supabase = createServerClient(
process.env.NEXT_PUBLIC_SUPABASE_URL!,
process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY!,
{ cookies: { get(name: string) { return cookieStore.get(name)?.value; } } }
{
cookies: {
get(name: string) {
return cookieStore.get(name)?.value;
},
},
}
);

let isPro = false;
const {
data: { user },
} = await supabase.auth.getUser();

const { data: { user } } = await supabase.auth.getUser();
if (user) {
// Fetch plan tier
const { data: profile } = await supabase
.from("profiles")
.select("plan_tier")
Expand All @@ -51,66 +90,92 @@ export async function POST(req: NextRequest) {

isPro = profile?.plan_tier === "pro";

// Rate-limit free users only
if (!isPro) {
const isUnderLimit = await checkUsageLimit(supabase, user.id, user.email);
if (!isUnderLimit) {
return NextResponse.json(
{ error: "RATE_LIMIT_REACHED", message: "Daily limit reached." },
{
error: "RATE_LIMIT_REACHED",
message: "Daily free limit reached. Upgrade to Pro for unlimited access.",
},
{ status: 429 }
);
}
}
}
} catch (authErr) {
// Non-fatal: unauthenticated users fall through as free-tier
console.warn("Auth check failed, treating as free user:", authErr);
}

const contextSize = isPro ? PRO_CONTEXT_SIZE : FREE_CONTEXT_SIZE;
const model = isPro ? PRO_MODEL : FREE_MODEL;
const maxTokens = isPro ? PRO_MAX_TOKENS : FREE_MAX_TOKENS;
// 4. Select tier config
const model = isPro ? PRO_MODEL : FREE_MODEL;
const contextSize = isPro ? PRO_CONTEXT_SIZE : FREE_CONTEXT_SIZE;
const maxTokens = isPro ? PRO_MAX_TOKENS : FREE_MAX_TOKENS;

let contextText = "No repository context provided.";
if (repoContext) {
contextText = JSON.stringify(repoContext).substring(0, contextSize);
}
// 5. Build system prompt with truncated repo context
const contextText = repoContext
? JSON.stringify(repoContext).slice(0, contextSize)
: "No repository context provided.";

const systemPrompt = `You are a Senior Systems Architect analyzing a codebase.
Use the provided JSON context about the repository to answer the user's questions.
const systemPrompt = `You are a Senior Systems Architect with deep expertise in software design, \
architecture patterns, and code analysis.

Analyze the repository context below to answer the user's questions accurately and concisely. \
When referencing files or modules, cite them by name. If the context is insufficient to answer \
definitively, say so clearly rather than guessing.

REPOSITORY CONTEXT (JSON):
${contextText}`;

const res = await fetch(GROQ_URL, {
// 6. Call Groq with streaming
let groqRes: Response;
try {
groqRes = await fetch(GROQ_URL, {
method: "POST",
headers: {
"Content-Type": "application/json",
"Authorization": `Bearer ${GROQ_API_KEY}`,
Authorization: `Bearer ${GROQ_API_KEY}`,
},
body: JSON.stringify({
model,
messages: [
{ role: "system", content: systemPrompt },
...messages,
],
messages: [{ role: "system", content: systemPrompt }, ...messages],
temperature: 0.1,
max_tokens: maxTokens,
stream: true,
}),
});
} catch (networkErr) {
console.error("Network error reaching Groq:", networkErr);
return errorResponse("Failed to reach Groq API. Please retry.", 502);
}

if (!res.ok) {
const errorText = await res.text();
throw new Error(`Groq API Error: ${errorText}`);
// 7. Surface Groq-level errors clearly
if (!groqRes.ok) {
const errText = await groqRes.text();
console.error(`Groq ${groqRes.status} error:`, errText);

// Parse Groq error for a cleaner client message
let clientMessage = `Groq API Error (${groqRes.status})`;
try {
const parsed = JSON.parse(errText);
if (parsed?.error?.message) clientMessage = parsed.error.message;
} catch {

}

return new Response(res.body, {
headers: {
"Content-Type": "text/event-stream",
"Cache-Control": "no-cache",
"Connection": "keep-alive",
},
});

} catch (err: unknown) {
const error = err instanceof Error ? err : new Error(String(err));
console.error("Chat API Error:", error.message);
return NextResponse.json({ error: error.message }, { status: 500 });
return errorResponse(clientMessage, groqRes.status >= 500 ? 502 : groqRes.status);
}

// 8. Stream the response body back to the client
return new Response(groqRes.body, {
status: 200,
headers: {
"Content-Type": "text/event-stream",
"Cache-Control": "no-cache, no-transform",
"X-Accel-Buffering": "no",
Connection: "keep-alive",
},
});
}
Loading