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
4 changes: 4 additions & 0 deletions .env.example
Original file line number Diff line number Diff line change
@@ -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
17 changes: 10 additions & 7 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand All @@ -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()
Expand Down
2 changes: 1 addition & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -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
39 changes: 38 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -46,7 +76,7 @@ flowchart LR
M --> DASH["packages/web — dashboard<br/>(ranking + graph + narrative)"]
OK --> DASH
NO --> DASH
M --> CI["GitHub Actions:<br/>self-analyze.ts + quality gate"]
M --> CI["GitHub Action:<br/>analyze.ts + quality gate"]
end
```

Expand Down Expand Up @@ -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.
Expand Down
58 changes: 58 additions & 0 deletions action.yml
Original file line number Diff line number Diff line change
@@ -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[@]}"
3 changes: 2 additions & 1 deletion packages/engine/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
61 changes: 61 additions & 0 deletions packages/engine/scripts/analyze.ts
Original file line number Diff line number Diff line change
@@ -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<void> {
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);
});
58 changes: 0 additions & 58 deletions packages/engine/scripts/self-analyze.ts

This file was deleted.

6 changes: 5 additions & 1 deletion packages/engine/src/churn/compute-churn.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
3 changes: 3 additions & 0 deletions packages/engine/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Loading
Loading