From e9b3824b474ae8ad85a92955a33a81a2b3aa184f Mon Sep 17 00:00:00 2001 From: Basar Tuncay Date: Mon, 9 Nov 2026 13:09:44 +0100 Subject: [PATCH] Ship CodeAtlas as a GitHub Action; lock down the dashboard API - action.yml: composite action that installs only the engine and runs the deterministic analysis on the caller's repo; writes a hotspot/cycle/risk report to the job summary, saves the JSON model, optional max-hotspot gate - scripts/analyze.ts replaces self-analyze.ts: generic CLI (path, --out, --summary, --max-hotspot, --top); renderSummary/evaluateQualityGate in the engine with tests - churn: use --relative so analyzing a subfolder (monorepo package) no longer reports zero churn; raise execFile maxBuffer for busy histories - web API: drop client-supplied repoPath (arbitrary filesystem read on a public deployment); repo comes from CODEATLAS_REPO_PATH; paid runs are limited by a cooldown and share one in-flight run - CI dogfoods the action (uses: ./) and lints the web package Co-Authored-By: Claude Opus 5.5 --- .env.example | 4 + .github/workflows/ci.yml | 17 ++-- .gitignore | 2 +- README.md | 39 ++++++++- action.yml | 58 +++++++++++++ packages/engine/package.json | 3 +- packages/engine/scripts/analyze.ts | 61 ++++++++++++++ packages/engine/scripts/self-analyze.ts | 58 ------------- packages/engine/src/churn/compute-churn.ts | 6 +- packages/engine/src/index.ts | 3 + packages/engine/src/report/render-summary.ts | 83 +++++++++++++++++++ .../engine/tests/churn/compute-churn.test.ts | 35 ++++++++ .../tests/report/render-summary.test.ts | 82 ++++++++++++++++++ packages/web/app/api/analyze/route.ts | 80 +++++++++++------- packages/web/components/RunAnalysisButton.tsx | 11 ++- 15 files changed, 441 insertions(+), 101 deletions(-) create mode 100644 action.yml create mode 100644 packages/engine/scripts/analyze.ts delete mode 100644 packages/engine/scripts/self-analyze.ts create mode 100644 packages/engine/src/report/render-summary.ts create mode 100644 packages/engine/tests/report/render-summary.test.ts diff --git a/.env.example b/.env.example index bcd2e33..0211b1e 100644 --- a/.env.example +++ b/.env.example @@ -1 +1,5 @@ ANTHROPIC_API_KEY=sk-ant-your-key-here +# Optional: repo the dashboard analyzes (default: this monorepo). +CODEATLAS_REPO_PATH= +# Minimum seconds between paid analysis runs (default 600). +CODEATLAS_ANALYZE_COOLDOWN_SECONDS=600 diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 5e3ed01..1e93f3a 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -23,6 +23,8 @@ jobs: - run: npm test --workspaces --if-present + - run: npm run lint --workspace=@codeatlas/web + self-analysis: runs-on: ubuntu-latest steps: @@ -38,13 +40,14 @@ jobs: node-version: "20" cache: "npm" - - run: npm ci - - # Deterministic engine only — analyzeRepository never calls the LLM - # (that's packages/llm-synthesis's separate concern, already covered - # by its own contract tests with no live API call). No API key, no - # spend, on every push. - - run: npm run self-analyze --workspace=@codeatlas/engine + # Dogfoods the published GitHub Action (action.yml) on this repo: + # deterministic engine only, no LLM, no API key, no spend. + # 0.95 is deliberately high: legitimately complex test files already + # score ~0.87, so the gate catches an extreme regression, not normal work. + - uses: ./ + with: + max-hotspot: "0.95" + output: packages/engine/analysis.json - uses: actions/upload-artifact@v4 if: always() diff --git a/.gitignore b/.gitignore index edd57e6..7dcb869 100644 --- a/.gitignore +++ b/.gitignore @@ -145,5 +145,5 @@ vite.config.ts.timestamp-* # macOS .DS_Store -# self-analysis output (generated by packages/engine/scripts/self-analyze.ts, published as a CI artifact instead) +# self-analysis output (generated by packages/engine/scripts/analyze.ts, published as a CI artifact instead) packages/engine/analysis.json diff --git a/README.md b/README.md index ac1081e..0cb1919 100644 --- a/README.md +++ b/README.md @@ -12,6 +12,36 @@ This isn't a claim of novelty — tools like ArchMind, CodeMap, DevLens, and Cod 2. **A grounding/hallucination-rejection validator sits between the LLM and the user**: schema validation, referential integrity against real module IDs, and numeric-tolerance checks against the real computed values. Rejections are logged and shown, not hidden. 3. **CodeAtlas analyzes itself in CI as a quality gate**, not just as a demo target — see the [`self-analysis`](.github/workflows/ci.yml) job. +## Use it in your repo (GitHub Action) + +Add a step to any TypeScript/JavaScript repo's workflow. It runs the deterministic engine only +(no LLM, no API key), writes a hotspot table, cycles and high-severity risks to the job summary, +saves the full JSON model, and can fail the build past a threshold: + +```yaml +jobs: + codeatlas: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + with: + fetch-depth: 0 # churn needs real history; a shallow clone reads as zero churn + - uses: basartuncay/CodeAtlas@v1 + with: + path: . # or a package folder in a monorepo + max-hotspot: "0.9" # optional quality gate (0-1); omit to report only + top: "10" +``` + +Locally, the same analysis is one command: + +```bash +npm ci --workspace=@codeatlas/engine +npm run analyze --workspace=@codeatlas/engine -- /path/to/repo --summary report.md --out analysis.json +``` + +This repo's own CI runs the action on itself (`uses: ./`), so the published action is tested on every push. + ## Screenshot / demo GIF ![CodeAtlas dashboard](docs/screenshot.png) @@ -46,7 +76,7 @@ flowchart LR M --> DASH["packages/web — dashboard
(ranking + graph + narrative)"] OK --> DASH NO --> DASH - M --> CI["GitHub Actions:
self-analyze.ts + quality gate"] + M --> CI["GitHub Action:
analyze.ts + quality gate"] end ``` @@ -96,6 +126,13 @@ npm run dev --workspace=@codeatlas/web # open http://localhost:3000 ``` +### Deploying the dashboard publicly + +The dashboard analyzes one server-chosen repo (`CODEATLAS_REPO_PATH`, default: this monorepo) — +the API never takes a path from the request. Each "Run analysis" makes a paid Claude call, so runs +are limited to one per `CODEATLAS_ANALYZE_COOLDOWN_SECONDS` (default 600) and concurrent clicks share +one in-flight run; inside the cooldown the latest result is returned with HTTP 429. + ## How this was built — real bugs found along the way This project was built test-first throughout, and that discipline is what actually caught the three most interesting bugs below — none of them were hypothetical, all three were found by running real code against real (or precisely reproduced) conditions, not by inspection. diff --git a/action.yml b/action.yml new file mode 100644 index 0000000..c64d8b0 --- /dev/null +++ b/action.yml @@ -0,0 +1,58 @@ +name: CodeAtlas +description: >- + Deterministic hotspot analysis for TypeScript/JavaScript repos: fuses dependency + coupling, cyclomatic complexity and git churn into one ranking, posts it to the job + summary, and optionally fails the build past a hotspot threshold. No LLM, no API key. +author: basartuncay +branding: + icon: map + color: orange + +inputs: + path: + description: Directory to analyze, relative to the workspace (use a subfolder for monorepo packages). + default: "." + max-hotspot: + description: Fail the step if any module's hotspot score (0-1) exceeds this. Empty = report only. + default: "" + top: + description: Number of hotspots listed in the job summary. + default: "10" + output: + description: Where to write the full JSON model, relative to the workspace. + default: codeatlas-analysis.json + +outputs: + report: + description: Path to the JSON analysis model. + value: ${{ steps.analyze.outputs.report }} + +runs: + using: composite + steps: + - uses: actions/setup-node@v4 + with: + node-version: "20" + + - name: Install CodeAtlas engine + shell: bash + working-directory: ${{ github.action_path }} + run: npm ci --workspace=@codeatlas/engine --include-workspace-root=false --no-audit --no-fund + + - name: Analyze + id: analyze + shell: bash + working-directory: ${{ github.action_path }}/packages/engine + env: + TARGET: ${{ github.workspace }}/${{ inputs.path }} + OUTPUT: ${{ github.workspace }}/${{ inputs.output }} + MAX_HOTSPOT: ${{ inputs.max-hotspot }} + TOP: ${{ inputs.top }} + run: | + if [ "$(git -C "$TARGET" rev-parse --is-shallow-repository 2>/dev/null)" = "true" ]; then + echo "::warning::Shallow clone: churn numbers will be near zero. Use actions/checkout with fetch-depth: 0." + fi + args=("$TARGET" --out "$OUTPUT" --summary "$GITHUB_STEP_SUMMARY" --top "$TOP") + if [ -n "$MAX_HOTSPOT" ]; then args+=(--max-hotspot "$MAX_HOTSPOT"); fi + echo "report=$OUTPUT" >> "$GITHUB_OUTPUT" + npx tsx scripts/analyze.ts "${args[@]}" diff --git a/packages/engine/package.json b/packages/engine/package.json index 1f7ad70..60afa33 100644 --- a/packages/engine/package.json +++ b/packages/engine/package.json @@ -8,7 +8,8 @@ "test": "vitest run", "test:watch": "vitest", "typecheck": "tsc --noEmit", - "self-analyze": "tsx scripts/self-analyze.ts" + "analyze": "tsx scripts/analyze.ts", + "self-analyze": "tsx scripts/analyze.ts ../.. --out analysis.json --max-hotspot 0.95" }, "dependencies": { "dependency-cruiser": "^17.4.3", diff --git a/packages/engine/scripts/analyze.ts b/packages/engine/scripts/analyze.ts new file mode 100644 index 0000000..7b894b6 --- /dev/null +++ b/packages/engine/scripts/analyze.ts @@ -0,0 +1,61 @@ +import { appendFileSync, writeFileSync } from 'node:fs'; +import path from 'node:path'; +import { parseArgs } from 'node:util'; +import { analyzeRepository, evaluateQualityGate, renderSummary } from '../src/index'; + +/** + * Deterministic analysis CLI (no LLM, no API key). Used by this repo's own CI + * (`npm run self-analyze`) and by the GitHub Action in /action.yml. + * + * tsx scripts/analyze.ts [repoPath] [--out analysis.json] [--summary report.md] + * [--max-hotspot 0.95] [--top 10] + * + * --summary appends (GITHUB_STEP_SUMMARY is append-only by convention). + * Exit code 1 when --max-hotspot is given and exceeded. + */ +async function main(): Promise { + const { values, positionals } = parseArgs({ + allowPositionals: true, + options: { + out: { type: 'string' }, + summary: { type: 'string' }, + 'max-hotspot': { type: 'string' }, + top: { type: 'string', default: '10' }, + }, + }); + + const repoPath = path.resolve(positionals[0] ?? process.cwd()); + const threshold = values['max-hotspot'] ? Number(values['max-hotspot']) : null; + const topN = Number(values.top); + if (threshold !== null && !(threshold >= 0 && threshold <= 1)) { + throw new Error(`--max-hotspot must be a number between 0 and 1, got ${values['max-hotspot']}`); + } + if (!Number.isInteger(topN) || topN < 1) { + throw new Error(`--top must be a positive integer, got ${values.top}`); + } + + // No injected `asOf`: analyze the commit being built, as of now (see AnalyzeOptions). + const result = await analyzeRepository(repoPath); + const gate = evaluateQualityGate(result, threshold); + + if (values.out) writeFileSync(values.out, JSON.stringify(result, null, 2)); + if (values.summary) appendFileSync(values.summary, `${renderSummary(result, gate, topN)}\n`); + + console.log(`Modules analyzed: ${result.modules.length}`); + console.log(`Cycles detected: ${result.cycles.length}`); + console.log(`Risks flagged: ${result.risks.length}`); + console.log( + `Max hotspot_score: ${gate.maxHotspotScore.toFixed(4)}` + + (threshold === null ? '' : ` (gate: ${threshold})`), + ); + + if (!gate.passed) { + console.error(`Quality gate FAILED: max hotspot_score exceeds ${threshold}`); + process.exit(1); + } +} + +main().catch((error: unknown) => { + console.error(error instanceof Error ? error.message : error); + process.exit(1); +}); diff --git a/packages/engine/scripts/self-analyze.ts b/packages/engine/scripts/self-analyze.ts deleted file mode 100644 index db3a6ab..0000000 --- a/packages/engine/scripts/self-analyze.ts +++ /dev/null @@ -1,58 +0,0 @@ -import { fileURLToPath } from 'node:url'; -import { writeFileSync } from 'node:fs'; -import path from 'node:path'; -import { analyzeRepository } from '../src/index'; - -const HERE = path.dirname(fileURLToPath(import.meta.url)); -const REPO_ROOT = path.resolve(HERE, '../../..'); -const OUTPUT_PATH = path.resolve(HERE, '../analysis.json'); - -/** - * CI quality gate — one simple condition, per docs/PLAN.md's Self-analysis - * section ("optionally fail the build if hotspot count or max complexity - * regresses past a defined threshold"). - * - * 0.95 is deliberately high, not a typical "quality bar": this repo - * already has legitimately complex test files scoring ~0.87 today (see - * fixtures/complex-functions, the engine's own complexity tests). This - * gate exists to catch a genuinely extreme regression, not to block - * ordinary development — a lower threshold like 0.7 (PLAN.md's own - * high_hotspot risk-rule example) would fail on the very first CI run. - */ -const MAX_HOTSPOT_SCORE_GATE = 0.95; - -async function main(): Promise { - // No injected `asOf` — this is the one real place the default - // (new Date()) path is meant to run: analyzing the actual commit being - // built, as of now. See AnalyzeOptions's doc comment. - const result = await analyzeRepository(REPO_ROOT); - writeFileSync(OUTPUT_PATH, JSON.stringify(result, null, 2)); - - // hotspot_score is NaN only when the whole analysis has <=1 module - // (see ADR 0004) — not a real scenario for this repo, but coerced to 0 - // rather than left to poison Math.max into NaN (which would silently - // never fail the gate). - const hotspotScores = result.modules.map((module) => - Number.isNaN(module.hotspot_score) ? 0 : module.hotspot_score, - ); - const maxHotspotScore = hotspotScores.length > 0 ? Math.max(...hotspotScores) : 0; - - console.log(`Modules analyzed: ${result.modules.length}`); - console.log(`Cycles detected: ${result.cycles.length}`); - console.log(`Risks flagged: ${result.risks.length}`); - console.log(`Max hotspot_score: ${maxHotspotScore.toFixed(4)} (gate: ${MAX_HOTSPOT_SCORE_GATE})`); - - if (maxHotspotScore > MAX_HOTSPOT_SCORE_GATE) { - console.error( - `Quality gate FAILED: max hotspot_score ${maxHotspotScore.toFixed(4)} exceeds ${MAX_HOTSPOT_SCORE_GATE}`, - ); - process.exit(1); - } - - console.log('Quality gate passed.'); -} - -main().catch((error: unknown) => { - console.error(error); - process.exit(1); -}); diff --git a/packages/engine/src/churn/compute-churn.ts b/packages/engine/src/churn/compute-churn.ts index ca86fd5..657904d 100644 --- a/packages/engine/src/churn/compute-churn.ts +++ b/packages/engine/src/churn/compute-churn.ts @@ -54,12 +54,16 @@ export async function computeChurn(repoPath: string, window: ChurnWindow): Promi [ 'log', '--no-renames', + // Paths relative to repoPath (and limited to it), so analyzing a + // subdirectory of a repo still lines up with the module ids. + '--relative', '--numstat', `--since=${since}`, `--until=${until}`, `--pretty=format:${COMMIT_MARKER}`, ], - { cwd: repoPath }, + // Default 1 MB stdout cap is too small for a busy 90-day history. + { cwd: repoPath, maxBuffer: 256 * 1024 * 1024 }, ); const commitCountByModule = countCommitsPerFile(stdout); diff --git a/packages/engine/src/index.ts b/packages/engine/src/index.ts index f680af5..5c2552f 100644 --- a/packages/engine/src/index.ts +++ b/packages/engine/src/index.ts @@ -30,3 +30,6 @@ export type { Risk, RiskSeverity } from './risks/types'; export { analyzeRepository } from './analyze/analyze-repository'; export type { AnalysisResult, AnalyzeOptions, ModuleResult } from './analyze/types'; + +export { evaluateQualityGate, renderSummary } from './report/render-summary'; +export type { QualityGateResult } from './report/render-summary'; diff --git a/packages/engine/src/report/render-summary.ts b/packages/engine/src/report/render-summary.ts new file mode 100644 index 0000000..fee0c35 --- /dev/null +++ b/packages/engine/src/report/render-summary.ts @@ -0,0 +1,83 @@ +import type { AnalysisResult } from '../analyze/types'; + +export interface QualityGateResult { + maxHotspotScore: number; + threshold: number | null; + passed: boolean; +} + +/** + * hotspot_score is NaN only when the whole analysis has <=1 module (ADR 0004). + * Coerced to 0 so Math.max never turns into NaN and silently skips the gate. + */ +export function evaluateQualityGate( + result: AnalysisResult, + threshold: number | null, +): QualityGateResult { + const scores = result.modules.map((m) => (Number.isNaN(m.hotspot_score) ? 0 : m.hotspot_score)); + const maxHotspotScore = scores.length > 0 ? Math.max(...scores) : 0; + return { maxHotspotScore, threshold, passed: threshold === null || maxHotspotScore <= threshold }; +} + +function escapeCell(value: string): string { + return value.replaceAll('|', '\\|'); +} + +/** Markdown report for a GitHub job summary or PR comment: deterministic, no LLM. */ +export function renderSummary( + result: AnalysisResult, + gate: QualityGateResult, + topN = 10, +): string { + const top = [...result.modules] + .filter((m) => !Number.isNaN(m.hotspot_score)) + .sort((a, b) => b.hotspot_score - a.hotspot_score || a.id.localeCompare(b.id)) + .slice(0, topN); + + const lines = [ + '## CodeAtlas report', + '', + `Commit \`${result.repo.commit.slice(0, 12)}\` · ${result.modules.length} modules · ` + + `${result.cycles.length} cycles · ${result.risks.length} risks`, + '', + gate.threshold === null + ? `Max hotspot score: **${gate.maxHotspotScore.toFixed(4)}** (no gate)` + : `Quality gate: ${gate.passed ? '✅ passed' : '❌ failed'} — max hotspot score ` + + `**${gate.maxHotspotScore.toFixed(4)}** (threshold ${gate.threshold})`, + '', + ]; + + if (top.length > 0) { + lines.push( + `### Top ${top.length} hotspots`, + '', + '| Module | Hotspot | Complexity | Churn (90d) | Fan-in | Blast radius | In cycle |', + '|---|---:|---:|---:|---:|---:|:---:|', + ...top.map( + (m) => + `| \`${escapeCell(m.id)}\` | ${m.hotspot_score.toFixed(3)} | ${m.cyclomatic_complexity} | ` + + `${m.churn_commits_90d} | ${m.fan_in} | ${m.blast_radius} | ${m.in_cycle ? '⚠️' : ''} |`, + ), + '', + ); + } + + if (result.cycles.length > 0) { + lines.push('### Dependency cycles', ''); + for (const cycle of result.cycles) { + lines.push(`- ${cycle.map((id) => `\`${escapeCell(id)}\``).join(' → ')}`); + } + lines.push(''); + } + + const highRisks = result.risks.filter((r) => r.severity === 'high'); + if (highRisks.length > 0) { + lines.push('### High-severity risks', ''); + for (const risk of highRisks) { + lines.push(`- \`${escapeCell(risk.module_id)}\` — ${risk.rule}`); + } + lines.push(''); + } + + return lines.join('\n'); +} diff --git a/packages/engine/tests/churn/compute-churn.test.ts b/packages/engine/tests/churn/compute-churn.test.ts index 1bfb6e6..cd60286 100644 --- a/packages/engine/tests/churn/compute-churn.test.ts +++ b/packages/engine/tests/churn/compute-churn.test.ts @@ -65,3 +65,38 @@ describe('computeChurn — asOf is injected, not read from the real clock', () = expect(results).toEqual([]); }); }); + +describe('computeChurn — repoPath is a subdirectory of the git repo', () => { + it('reports paths relative to repoPath and ignores files outside it', async () => { + const { execFileSync } = await import('node:child_process'); + const { mkdirSync, mkdtempSync, rmSync, writeFileSync } = await import('node:fs'); + const { tmpdir } = await import('node:os'); + const path = await import('node:path'); + + const root = mkdtempSync(path.join(tmpdir(), 'codeatlas-churn-subdir-')); + try { + const env = { + ...process.env, + GIT_AUTHOR_DATE: '2023-12-01T00:00:00Z', + GIT_COMMITTER_DATE: '2023-12-01T00:00:00Z', + }; + const git = (...args: string[]) => + execFileSync('git', ['-c', 'user.name=t', '-c', 'user.email=t@t', ...args], { cwd: root, env }); + git('init', '-q'); + mkdirSync(path.join(root, 'pkg')); + writeFileSync(path.join(root, 'pkg', 'inner.ts'), 'export {};\n'); + writeFileSync(path.join(root, 'outer.ts'), 'export {};\n'); + git('add', '.'); + git('commit', '-q', '-m', 'init'); + + const results = await computeChurn(path.join(root, 'pkg'), { + asOf: new Date('2024-01-01T00:00:00Z'), + windowDays: 90, + }); + + expect(results).toEqual([{ module_id: 'inner.ts', churn_commits: 1 }]); + } finally { + rmSync(root, { recursive: true, force: true }); + } + }); +}); diff --git a/packages/engine/tests/report/render-summary.test.ts b/packages/engine/tests/report/render-summary.test.ts new file mode 100644 index 0000000..4e6cec0 --- /dev/null +++ b/packages/engine/tests/report/render-summary.test.ts @@ -0,0 +1,82 @@ +import { describe, expect, it } from 'vitest'; +import { evaluateQualityGate, renderSummary } from '../../src/report/render-summary'; +import type { AnalysisResult, ModuleResult } from '../../src/analyze/types'; + +function moduleResult(id: string, hotspot: number, overrides: Partial = {}): ModuleResult { + return { + id, + loc: 10, + cyclomatic_complexity: 3, + fan_in: 1, + fan_out: 1, + instability: 0.5, + churn_commits_90d: 2, + hotspot_score: hotspot, + blast_radius: 1, + in_cycle: false, + ...overrides, + }; +} + +function result(modules: ModuleResult[], extra: Partial = {}): AnalysisResult { + return { + schema_version: '1.0', + repo: { url: null, commit: '0123456789abcdef', analyzed_at: '2026-01-01T00:00:00.000Z' }, + modules, + edges: [], + cycles: [], + risks: [], + ...extra, + }; +} + +describe('evaluateQualityGate', () => { + it('passes without a threshold and reports the max score', () => { + const gate = evaluateQualityGate(result([moduleResult('a.ts', 0.2), moduleResult('b.ts', 0.9)]), null); + expect(gate).toEqual({ maxHotspotScore: 0.9, threshold: null, passed: true }); + }); + + it('fails when the max score exceeds the threshold', () => { + const gate = evaluateQualityGate(result([moduleResult('a.ts', 0.96)]), 0.95); + expect(gate.passed).toBe(false); + }); + + it('treats NaN scores as 0 instead of silently skipping the gate', () => { + const gate = evaluateQualityGate(result([moduleResult('only.ts', Number.NaN)]), 0.5); + expect(gate).toEqual({ maxHotspotScore: 0, threshold: 0.5, passed: true }); + }); + + it('handles an empty module list', () => { + expect(evaluateQualityGate(result([]), 0.5).maxHotspotScore).toBe(0); + }); +}); + +describe('renderSummary', () => { + it('ranks hotspots, lists cycles and high risks, and escapes pipes', () => { + const analysis = result( + [ + moduleResult('src/low.ts', 0.1), + moduleResult('src/a|b.ts', 0.8, { in_cycle: true }), + moduleResult('src/nan.ts', Number.NaN), + ], + { + cycles: [['src/a|b.ts', 'src/low.ts']], + risks: [ + { module_id: 'src/a|b.ts', rule: 'high_hotspot', evidence: {}, severity: 'high' }, + { module_id: 'src/low.ts', rule: 'minor', evidence: {}, severity: 'low' }, + ], + }, + ); + + const md = renderSummary(analysis, evaluateQualityGate(analysis, 0.95)); + + expect(md).toContain('Commit `0123456789ab` · 3 modules · 1 cycles · 2 risks'); + expect(md).toContain('✅ passed'); + expect(md).toContain('### Top 2 hotspots'); + expect(md.indexOf('src/a\\|b.ts')).toBeLessThan(md.indexOf('`src/low.ts` | 0.100')); + expect(md).not.toContain('src/nan.ts'); + expect(md).toContain('- `src/a\\|b.ts` → `src/low.ts`'); + expect(md).toContain('- `src/a\\|b.ts` — high_hotspot'); + expect(md).not.toContain('minor'); + }); +}); diff --git a/packages/web/app/api/analyze/route.ts b/packages/web/app/api/analyze/route.ts index 078a2f0..383a448 100644 --- a/packages/web/app/api/analyze/route.ts +++ b/packages/web/app/api/analyze/route.ts @@ -1,45 +1,63 @@ import path from 'node:path'; import { analyzeRepository } from '@codeatlas/engine'; import { synthesizeFindings, validateFindings } from '@codeatlas/llm-synthesis'; -import { getCachedAnalysis, setCachedAnalysis } from '@/lib/analysis-cache'; - -// Assumes this route runs with cwd = packages/web (true for `next dev`/`next -// start` run from this package, whether directly or via an npm workspace -// script). Self-analysis by default — demo beat 1 in docs/PLAN.md. -// Known fragility: this breaks if the server is ever started with a -// different cwd (e.g. a process manager that launches from the repo -// root). Not worth generalizing for a single-deployment demo project. -const DEFAULT_REPO_PATH = path.resolve(process.cwd(), '..', '..'); - -interface AnalyzeRequestBody { - repoPath?: unknown; +import { getCachedAnalysis, setCachedAnalysis, type CachedAnalysis } from '@/lib/analysis-cache'; + +// The analyzed repo is fixed by the server, never by the request body: +// accepting a path from the client would be an arbitrary filesystem read / +// git-in-any-directory primitive on a public deployment. +// CODEATLAS_REPO_PATH overrides the default (this monorepo, which assumes +// cwd = packages/web as with `next start` via the workspace script). +const REPO_PATH = process.env.CODEATLAS_REPO_PATH + ? path.resolve(process.env.CODEATLAS_REPO_PATH) + : path.resolve(process.cwd(), '..', '..'); + +// Each POST makes a paid Claude call. On a public deployment that must be +// bounded: at most one run per cooldown window, and never two at once. +const COOLDOWN_MS = Number(process.env.CODEATLAS_ANALYZE_COOLDOWN_SECONDS ?? '600') * 1000; + +const globalForRun = globalThis as typeof globalThis & { + __codeatlasAnalysisInFlight?: Promise | null; +}; + +async function runAnalysis(): Promise { + const model = await analyzeRepository(REPO_PATH); + const rawOutput = await synthesizeFindings(model); + const narrative = validateFindings(rawOutput, model); + const cached = { model, narrative, cachedAt: new Date().toISOString() }; + setCachedAnalysis(cached); + return cached; } /** * Runs the full pipeline once — analyzeRepository (engine) -> * synthesizeFindings (live Claude API call) -> validateFindings (grounding) - * — and caches the combined result. Expensive; call this to (re-)run an - * analysis, not on every page load (see GET below for that). - * - * SECURITY: `repoPath` from the request body is passed straight to - * `analyzeRepository`, which reads that filesystem path and shells out to - * `git` inside it — no sanitization, no allowlist. Fine for local/demo use - * (trusted caller, single user) but this must NOT be exposed as-is on a - * public deployment: a malicious `repoPath` is an arbitrary local - * filesystem read / git-command-in-arbitrary-directory primitive. + * — and caches the combined result. Concurrent callers share one in-flight + * run; within the cooldown the cached result is returned with 429. */ -export async function POST(request: Request): Promise { - const body: AnalyzeRequestBody = await request.json().catch(() => ({})); - const repoPath = typeof body.repoPath === 'string' ? body.repoPath : DEFAULT_REPO_PATH; - - const model = await analyzeRepository(repoPath); - const rawOutput = await synthesizeFindings(model); - const narrative = validateFindings(rawOutput, model); +export async function POST(): Promise { + const inFlight = globalForRun.__codeatlasAnalysisInFlight; + if (inFlight) { + return Response.json(await inFlight); + } - const cached = { model, narrative, cachedAt: new Date().toISOString() }; - setCachedAnalysis(cached); + const previous = getCachedAnalysis(); + const ageMs = previous ? Date.now() - Date.parse(previous.cachedAt) : Infinity; + if (previous && ageMs < COOLDOWN_MS) { + const retryAfter = Math.ceil((COOLDOWN_MS - ageMs) / 1000); + return Response.json(previous, { status: 429, headers: { 'Retry-After': String(retryAfter) } }); + } - return Response.json(cached); + const run = runAnalysis(); + globalForRun.__codeatlasAnalysisInFlight = run; + try { + return Response.json(await run); + } catch (error) { + console.error('analysis failed', error); + return Response.json({ error: 'Analysis failed.' }, { status: 500 }); + } finally { + globalForRun.__codeatlasAnalysisInFlight = null; + } } /** Cheap: returns whatever the last POST computed, without re-running anything. */ diff --git a/packages/web/components/RunAnalysisButton.tsx b/packages/web/components/RunAnalysisButton.tsx index ea4fe22..2ab31d4 100644 --- a/packages/web/components/RunAnalysisButton.tsx +++ b/packages/web/components/RunAnalysisButton.tsx @@ -5,12 +5,18 @@ import { useState } from "react"; export function RunAnalysisButton() { const router = useRouter(); - const [status, setStatus] = useState<"idle" | "running" | "error">("idle"); + const [status, setStatus] = useState<"idle" | "running" | "error" | "cooldown">("idle"); async function runAnalysis() { setStatus("running"); try { const response = await fetch("/api/analyze", { method: "POST" }); + if (response.status === 429) { + // Rate-limited, but the body is the latest cached analysis: show it. + setStatus("cooldown"); + router.refresh(); + return; + } if (!response.ok) { throw new Error(`analyze request failed: ${response.status}`); } @@ -32,6 +38,9 @@ export function RunAnalysisButton() { {status === "running" ? "Analyzing…" : "Run analysis"} {status === "error" ? Analysis failed. : null} + {status === "cooldown" ? ( + Analyzed recently; showing the latest result. + ) : null} ); }