Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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
9 changes: 7 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ Each generated report includes:

## Intelligent Repository Analysis

- Upload repositories as ZIP archives
- Analyze a public GitHub repository by URL (any branch, tag or commit), or upload a ZIP archive
- Automatic repository extraction
- Repository root detection
- Recursive repository traversal
Expand Down Expand Up @@ -324,6 +324,11 @@ FRONTEND_URL=https://your-frontend.example
# Optional: analyses allowed to run at once (extra uploads get HTTP 429)
MAX_CONCURRENT_JOBS=2

# Optional: GitHub token for analyzing by URL. Without it GitHub allows
# 60 API requests/hour from the server's IP; with it, 5,000. A fine-grained
# token with no extra permissions is enough (public repositories only).
# GITHUB_TOKEN=github_pat_...

# Optional: rate limits on starting analyses (0 = no limit)
RATE_LIMIT_PER_HOUR=5 # per visitor (IP address)
RATE_LIMIT_PER_DAY=100 # whole site
Expand All @@ -347,6 +352,7 @@ SAVE_DEBUG_ARTIFACTS=false
| Method | Path | Description |
|---|---|---|
| `POST` | `/api/analyze` | Upload a ZIP (`repository` form field). Returns `202 { jobId }`. |
| `POST` | `/api/analyze/github` | JSON `{ "url": "https://github.com/owner/repo" }`. Public repositories only; checked on GitHub before the job starts. Returns `202 { jobId, repository }`. |
| `GET` | `/api/jobs/:id/events` | Server-Sent Events: `progress`, then `completed` (report + markdown) or `failed` (error body). |
| `GET` | `/api/jobs/:id` | Current job state as JSON. |
| `GET` | `/api/health` | Health check. |
Expand Down Expand Up @@ -381,7 +387,6 @@ Each analysis runs as its own job, so concurrent users never see each other's pr

## Version 1.1

- GitHub Repository URL Analysis
- Drag & Drop Uploads
- Improved Language Detection
- Repository Metrics Dashboard
Expand Down
5 changes: 5 additions & 0 deletions apps/backend/.env.example
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,11 @@ GEMINI_MODEL=gemini-2.5-flash
# Analyses allowed to run at once; extra uploads get HTTP 429.
MAX_CONCURRENT_JOBS=2

# Optional GitHub token for analyzing repositories by URL.
# Without it, GitHub allows 60 API requests/hour from the server's IP; with it, 5,000.
# A fine-grained token with no extra permissions is enough (public repos only).
# GITHUB_TOKEN=

# Rate limits on starting analyses (0 = no limit).
# Per visitor (IP address) per hour, and for the whole site per day.
RATE_LIMIT_PER_HOUR=5
Expand Down
2 changes: 1 addition & 1 deletion apps/backend/src/ai/analysis/ai-analysis.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -150,7 +150,7 @@ export async function analyzeRepository(

job.setStage("GENERATING_MARKDOWN");

const markdown = buildMarkdown(report);
const markdown = buildMarkdown(report, request.repository);

await job.logger.markdown(markdown);

Expand Down
3 changes: 3 additions & 0 deletions apps/backend/src/ai/analysis/analysis.types.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,12 @@
import type { RepositoryMetadata } from "../../types/repository.js";
import type { EngineeringReport } from "../report/report.types.js";
import type { GenerationTrace } from "../trace/trace.types.js";
import type { RepositoryInfo } from "../../types/repository-info.js";

export interface AnalysisRequest {
metadata: RepositoryMetadata;
/** Shown in the Markdown report header. */
repository?: RepositoryInfo;
}

export interface AnalysisResult {
Expand Down
21 changes: 21 additions & 0 deletions apps/backend/src/ai/report/markdown.service.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import type { RepositoryInfo } from "../../types/repository-info.js";
import type {
EngineeringReport,
EvidenceReference,
Expand Down Expand Up @@ -36,6 +37,23 @@ function formatEvidence(evidence: EvidenceReference[]): string {
return ["", "**Evidence**", "", ...items].join("\n");
}

/**
* "**Repository:** [owner/repo](url) · `main` @ `abc1234`"
*/
function formatRepositoryLine(repository: RepositoryInfo): string {
const name = repository.url
? `[${repository.name}](${repository.url})`
: repository.name;

const ref = repository.ref ? ` · \`${repository.ref}\`` : "";

const commit = repository.commitSha
? ` @ \`${repository.commitSha.slice(0, 7)}\``
: "";

return `**Repository:** ${name}${ref}${commit}`;
}

/**
* Formats a bullet list.
*/
Expand Down Expand Up @@ -141,10 +159,13 @@ ${question.expectedAnswer}
*/
export function buildMarkdown(
report: EngineeringReport,
repository?: RepositoryInfo,
): string {
return [
"# AI Project Review",

...(repository ? [formatRepositoryLine(repository)] : []),

"---",

"## Project Summary",
Expand Down
69 changes: 65 additions & 4 deletions apps/backend/src/application/analysis-job.runner.ts
Original file line number Diff line number Diff line change
@@ -1,17 +1,74 @@
import fs from "node:fs/promises";
import path from "node:path";
import { randomUUID } from "node:crypto";

import { analyzeUploadedRepository } from "./repository-analysis.service.js";
import { jobStore } from "../jobs/job.store.js";
import { JobLogger } from "../logger/logger.service.js";
import { toErrorResponse } from "../http/error-response.js";
import { downloadRepositoryZip } from "../github/github.client.js";
import { MAX_UPLOAD_SIZE } from "../constants/upload.js";

import type { AnalysisSource, JobContext } from "../jobs/job.types.js";
import type { RepositoryInfo } from "../types/repository-info.js";

const DOWNLOAD_DIRECTORY = "tmp/uploads";

/**
* Name shown in the report for an uploaded ZIP: its file name.
*/
function uploadName(fileName: string): string {
const name = path.basename(fileName).replace(/\.zip$/i, "").trim();

return (name || "repository").slice(0, 100);
}

/**
* Gets the ZIP for a job: the uploaded file, or a fresh download
* of the resolved GitHub commit.
*/
async function prepareSource(
source: AnalysisSource,
context: JobContext,
): Promise<{ zipPath: string; repository: RepositoryInfo }> {
if (source.type === "upload") {
return {
zipPath: source.zipPath,
repository: { name: uploadName(source.fileName) },
};
}

context.setStage("DOWNLOADING");

await fs.mkdir(DOWNLOAD_DIRECTORY, { recursive: true });

const zipPath = path.join(DOWNLOAD_DIRECTORY, `${randomUUID()}.zip`);

import type { JobContext } from "../jobs/job.types.js";
await downloadRepositoryZip(source.repository, zipPath, MAX_UPLOAD_SIZE);

await context.logger.info("Repository downloaded from GitHub", {
repository: source.repository.fullName,
commit: source.repository.commitSha,
});

return {
zipPath,
repository: {
name: source.repository.fullName,
url: source.repository.htmlUrl,
ref: source.repository.ref,
commitSha: source.repository.commitSha,
},
};
}

/**
* Runs one analysis job in the background and records the outcome
* in the job store. Never throws: every failure becomes a failed job.
*/
export async function runAnalysisJob(
jobId: string,
zipFilePath: string,
source: AnalysisSource,
): Promise<void> {
const logger = new JobLogger(jobId);

Expand All @@ -22,13 +79,17 @@ export async function runAnalysisJob(
};

try {
await logger.info("Repository analysis started");
await logger.info("Repository analysis started", { source: source.type });

const { zipPath, repository } = await prepareSource(source, context);

const result = await analyzeUploadedRepository(zipFilePath, context);
// Deletes the ZIP and extracted files when done.
const result = await analyzeUploadedRepository(zipPath, context, repository);

jobStore.complete(jobId, {
report: result.report,
markdown: result.markdown,
repository,
});

await logger.info("Repository analysis completed", result.trace);
Expand Down
5 changes: 4 additions & 1 deletion apps/backend/src/application/repository-analysis.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import { analyzeRepository } from "../ai/analysis/ai-analysis.service.js";

import type { AnalysisResult } from "../ai/analysis/analysis.types.js";
import type { JobContext } from "../jobs/job.types.js";
import type { RepositoryInfo } from "../types/repository-info.js";

/**
* Runs the full analysis for an uploaded ZIP.
Expand All @@ -17,6 +18,7 @@ import type { JobContext } from "../jobs/job.types.js";
export async function analyzeUploadedRepository(
zipFilePath: string,
job: JobContext,
repository: RepositoryInfo,
): Promise<AnalysisResult> {
const extractionDirectory = await fs.mkdtemp(
path.join(os.tmpdir(), "repository-"),
Expand All @@ -27,9 +29,10 @@ export async function analyzeUploadedRepository(
zipFilePath,
extractionDirectory,
job,
repository.name,
);

return await analyzeRepository({ metadata }, job);
return await analyzeRepository({ metadata, repository }, job);
} finally {
await Promise.allSettled([
fs.rm(extractionDirectory, {
Expand Down
10 changes: 10 additions & 0 deletions apps/backend/src/config/env.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,16 @@ const envSchema = z.object({
* 0 if the server is reached directly.
*/
TRUST_PROXY_HOPS: z.coerce.number().int().min(0).default(1),
/**
* Optional GitHub token for analyzing repositories by URL. Without it,
* GitHub allows 60 API requests per hour from the server's IP; with it,
* 5,000. A fine-grained token with no permissions is enough (public
* repositories only).
*/
GITHUB_TOKEN: z
.string()
.optional()
.transform((value) => value?.trim() || undefined),
/**
* Upper bound on the prompt size sent to Gemini. Source files are
* ranked by importance and added until this budget is reached.
Expand Down
100 changes: 100 additions & 0 deletions apps/backend/src/github/github-url.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
import { GitHubError } from "./github.errors.js";

export interface GitHubRepositoryRef {
owner: string;
repo: string;
/** Branch, tag or commit from a /tree/<ref> URL; default branch if absent. */
ref?: string;
}

/**
* GitHub's own limits: owners are letters, digits and single hyphens;
* repository names are letters, digits, '.', '-' and '_'.
*/
const OWNER = /^[A-Za-z0-9](?:[A-Za-z0-9-]{0,38})$/;
const REPO = /^[A-Za-z0-9._-]{1,100}$/;
const REF = /^[A-Za-z0-9._\-/]{1,255}$/;

const INVALID_MESSAGE =
"Enter a public GitHub repository, like https://github.com/owner/repo or owner/repo.";

/**
* Parses what a user pastes into the GitHub URL field:
*
* https://github.com/owner/repo
* https://github.com/owner/repo.git
* https://github.com/owner/repo/tree/branch-or-tag
* github.com/owner/repo
* owner/repo
*
* Only github.com is accepted, and every part is validated against
* GitHub's naming rules, so the values are safe to put in API URLs.
*/
export function parseGitHubUrl(input: string): GitHubRepositoryRef {
let text = input.trim();

if (!text || text.length > 500) {
throw new GitHubError("INVALID_GITHUB_URL", INVALID_MESSAGE);
}

// "." and ".." segments would be silently resolved by URL parsing
// (github.com/a/b/../c → github.com/a/c): reject them instead.
if (/(^|\/)\.{1,2}(\/|$|[?#])/.test(text.replace(/^https?:\/\//i, ""))) {
throw new GitHubError("INVALID_GITHUB_URL", INVALID_MESSAGE);
}

let path: string;

if (/^[A-Za-z0-9-]+\/[A-Za-z0-9._-]+\/?$/.test(text)) {
// owner/repo shorthand
path = text;
} else {
if (!/^https?:\/\//i.test(text)) {
text = `https://${text}`;
}

let url: URL;

try {
url = new URL(text);
} catch {
throw new GitHubError("INVALID_GITHUB_URL", INVALID_MESSAGE);
}

const host = url.hostname.toLowerCase();

if (host !== "github.com" && host !== "www.github.com") {
throw new GitHubError(
"INVALID_GITHUB_URL",
"Only github.com repositories are supported.",
);
}

path = decodeURIComponent(url.pathname);
}

const segments = path.split("/").filter(Boolean);

if (segments.length < 2) {
throw new GitHubError("INVALID_GITHUB_URL", INVALID_MESSAGE);
}

const owner = segments[0];
const repo = segments[1].replace(/\.git$/i, "");

if (!OWNER.test(owner) || !REPO.test(repo) || repo === "." || repo === "..") {
throw new GitHubError("INVALID_GITHUB_URL", INVALID_MESSAGE);
}

let ref: string | undefined;

if (segments[2] === "tree" && segments.length > 3) {
ref = segments.slice(3).join("/");

if (!REF.test(ref) || ref.split("/").some((part) => part === "..")) {
throw new GitHubError("INVALID_GITHUB_URL", "That branch name is not valid.");
}
}

return { owner, repo, ref };
}
Loading
Loading