Introduction
Creating architectural design documents from existing code repositories is a tedious, error-prone task that most development teams either skip entirely or assign to junior developers as punishment. You spend hours reading through source code, extracting patterns, documenting module dependencies, and creating diagrams that go out of date before they're even finished. Then someone refactors the codebase and your documentation becomes fiction.
This workflow eliminates that pain by combining three specialised AI tools into an automated pipeline. SourceAI reads your repository structure and extracts code logic; bhava-ai generates architecture diagrams and design patterns; Mintlify transforms everything into polished documentation. Wire them together with an orchestration tool like n8n or Make, and you've got a system that can process an entire codebase without human intervention between each step.
The result: architecture documents that stay current, require minimal review, and actually reflect what your code does. For teams managing multiple services or working in fast-moving codebases, this saves the equivalent of several developer-days per month.
The Automated Workflow
This workflow works best with n8n because it handles file uploads cleanly and provides good error handling for long-running processes. However, Make works equally well if you prefer its interface.
Prerequisites
Before you start, you'll need API keys for:
- SourceAI (documentation API access)
- bhava-ai (diagram generation API)
- Mintlify (content generation API)
- n8n (self-hosted or cloud instance)
Gather your code repository access method: either a ZIP file upload, a Git webhook, or direct repository credentials.
Step 1: Repository Input and Parsing with SourceAI
The workflow begins when you trigger it manually or via webhook with a repository URL or uploaded codebase. SourceAI's first job is to extract structural information: file trees, function signatures, class hierarchies, and import statements.
Create an n8n workflow node that calls the SourceAI analysis endpoint:
POST https://api.sourceai.dev/v1/analyze
Authorization: Bearer YOUR_SOURCEAI_API_KEY
Content-Type: application/json
{
"repository_url": "https://github.com/your-org/your-repo",
"analysis_type": "architecture",
"include_patterns": ["src/**/*.ts", "src/**/*.js"],
"exclude_patterns": ["node_modules/**", "*.test.ts"],
"depth": "full"
}
SourceAI returns a JSON structure containing:
{
"project_name": "UserService",
"language": "TypeScript",
"modules": [
{
"path": "src/services/UserService.ts",
"exports": ["UserService", "IUserRepository"],
"imports": ["database/connection", "utils/validators"],
"functions": [
{
"name": "createUser",
"params": ["userData: IUserData"],
"return_type": "Promise<User>"
}
],
"dependencies": ["express", "postgres"]
}
],
"entry_points": ["src/index.ts"],
"architecture_patterns": ["MVC", "Repository Pattern"]
}
Store this JSON output in n8n's internal storage or a temporary database table. You'll reference it in the next steps.
Step 2: Architecture Diagram Generation with bhava-ai
Now pass the SourceAI JSON to bhava-ai, which specialises in converting code structure into architecture diagrams. This step produces visual representations of module relationships, data flow, and system boundaries.
Create an n8n node that calls bhava-ai:
POST https://api.bhava-ai.io/v1/generate-diagram
Authorization: Bearer YOUR_BHAVA_API_KEY
Content-Type: application/json
{
"architecture_data": {
"modules": [
{
"id": "UserService",
"type": "service",
"dependencies": ["DatabaseLayer", "AuthService"]
},
{
"id": "DatabaseLayer",
"type": "data_layer",
"dependencies": []
},
{
"id": "AuthService",
"type": "service",
"dependencies": ["DatabaseLayer"]
}
],
"diagram_type": "component",
"style": "c4_level_1",
"include_data_flow": true
}
}
bhava-ai returns:
{
"diagram_svg": "<svg>...</svg>",
"diagram_png": "base64-encoded-image-data",
"mermaid_code": "graph TD\n UserService --> DatabaseLayer\n AuthService --> DatabaseLayer",
"analysis": {
"layers": 2,
"coupling": "medium",
"circular_dependencies": []
}
}
Store the SVG and Mermaid code separately. The Mermaid code is text-based and version-controllable; the SVG is useful for rendering in documentation.
Step 3: Documentation Generation with Mintlify
This is where the raw technical data becomes readable prose. Mintlify takes the SourceAI extraction and bhava-ai diagrams and produces structured markdown documentation.
Create an n8n node calling Mintlify:
POST https://api.mintlify.com/v1/generate-docs
Authorization: Bearer YOUR_MINTLIFY_API_KEY
Content-Type: application/json
{
"code_structure": {
"modules": "[SourceAI JSON output]",
"diagrams": {
"component_diagram": "[bhava-ai mermaid code]"
}
},
"documentation_style": "technical",
"target_audience": "engineers",
"include_sections": [
"overview",
"architecture",
"module_descriptions",
"data_flow",
"deployment"
],
"formatting": "markdown"
}
Mintlify produces:
## System Overview
The UserService is a TypeScript-based microservice responsible for user account management, authentication, and profile operations.
## Architecture Diagram
## Core Modules
### UserService
**Location:** src/services/UserService.ts
**Exports:** UserService, IUserRepository
**Dependencies:** database/connection, utils/validators
#### Functions
- `createUser(userData: IUserData): Promise<User>`: Creates a new user account with validation.
- `getUserById(id: string): Promise<User | null>`: Retrieves user by ID.
## Data Flow
User requests → API Gateway → UserService → DatabaseLayer → PostgreSQL
## Dependencies
- express: ^4.18.0
- postgres: ^3.3.0
The output is a raw markdown string that you'll process in the next step.
Step 4: File Storage and Formatting
In n8n, add a node that:
- Receives the markdown from Mintlify
- Applies consistent formatting (heading levels, code block syntax)
- Embeds the diagram PNG or SVG inline
- Writes the output to a file
// n8n JavaScript node
const markdown = $node.Mintlify.json.documentation;
const diagramSvg = $node.bhava.json.diagram_svg;
// Embed the diagram into the markdown
const enrichedMarkdown = markdown.replace(
'
```mermaid\n' + $node.bhava.json.mermaid_code + '\n
```',
'<div class="diagram">\n' + diagramSvg + '\n</div>'
);
// Create timestamp for versioning
const timestamp = new Date().toISOString().split('T')[0];
const filename = `architecture-${timestamp}.md`;
return {
filename: filename,
content: enrichedMarkdown,
diagram_url: $node.bhava.json.diagram_png
};
Add a file write node that outputs to your chosen destination: S3, GitHub (via API), Confluence, or a shared drive.
Step 5: Notification and Review
Finally, send a notification to your team. This can be email, Slack, or a custom webhook:
POST https://hooks.slack.com/services/YOUR/WEBHOOK/URL
Content-Type: application/json
{
"text": "Architecture documentation updated",
"blocks": [
{
"type": "section",
"text": {
"type": "mrkdwn",
"text": "*New architecture documentation available*\nGenerated from latest codebase\nFile: architecture-2024-01-15.md"
}
},
{
"type": "actions",
"elements": [
{
"type": "button",
"text": {
"type": "plain_text",
"text": "Review Document"
},
"url": "https://your-docs-storage/architecture-2024-01-15.md"
}
]
}
]
}
Complete n8n Workflow Structure
Your workflow should look like this:
- Trigger node (manual or webhook)
- SourceAI API call (analyse repository)
- Store intermediate data
- bhava-ai API call (generate diagrams)
- Mintlify API call (generate documentation)
- JavaScript node (enrich and format)
- File write node (save to storage)
- Slack notification node
If you're using Make instead, the structure is identical but the node names and configuration panels differ. Make's HTTP request module works the same way as n8n's HTTP node, so copy the JSON payloads directly.
The Manual Alternative
If you prefer more control over the output or need to handle edge cases, you can run each tool independently and review intermediate outputs:
- Run SourceAI, export the JSON structure, review it for accuracy
- Manually adjust the architecture patterns if SourceAI misidentified them
- Run bhava-ai with the corrected JSON
- Review the diagram and adjust styling if needed
- Run Mintlify with explicit section templates
- Edit the resulting markdown before publication
This gives you the benefits of automation without sacrificing control. The tradeoff is that you're now doing manual steps between each tool, so updates to your codebase require a new manual run. Only choose this approach if your architecture documentation changes infrequently or if the automated output consistently requires significant revision.
Pro Tips
Handle Rate Limiting Gracefully
SourceAI and Mintlify apply rate limits (typically 100 requests per hour on free tiers). Add exponential backoff retry logic to your n8n workflow. Configure a retry node that waits 60 seconds after a 429 response, then tries again up to three times. This prevents failed workflows for large codebases that take several minutes to analyse.
// n8n node for exponential backoff
let retries = 0;
const maxRetries = 3;
while (retries < maxRetries) {
try {
const response = await fetch(apiUrl, requestOptions);
if (response.status === 429) {
const waitTime = Math.pow(2, retries) * 60000; // 60s, 120s, 240s
console.log(`Rate limited. Waiting ${waitTime}ms`);
await new Promise(resolve => setTimeout(resolve, waitTime));
retries++;
continue;
}
return response.json();
} catch (error) {
console.error('Request failed:', error);
throw error;
}
}
Filter Files Before Analysis
Large repositories with hundreds of files waste API quota. Configure SourceAI to exclude test files, vendor directories, and build artefacts. This typically reduces analysis time by 40-60% and costs proportionally.
"exclude_patterns": [
"node_modules/**",
"dist/**",
"build/**",
"*.test.ts",
"*.spec.ts",
".git/**",
"coverage/**"
]
Version Your Documentation
Store each generated document with a date prefix: architecture-2024-01-15.md. Don't overwrite previous versions. This lets you track how your architecture evolves over time and provides rollback if a code change breaks the analysis. Keep the last five versions and delete older ones to manage storage costs.
Validate bhava-ai Output for Circular Dependencies
bhava-ai detects circular dependencies in your code. Always review the circular_dependencies field in its output. These are architectural problems that should be fixed, not ignored. Add a check to your n8n workflow that flags these as warnings in your Slack notification.
const analysis = $node.bhava.json.analysis;
if (analysis.circular_dependencies.length > 0) {
return {
has_issues: true,
issues: analysis.circular_dependencies.map(dep =>
`Circular dependency: ${dep.from} <-> ${dep.to}`
)
};
}
Schedule Weekly Updates
Rather than running manually, schedule the workflow to run weekly on Monday mornings. This keeps documentation current without requiring developer intervention. Use n8n's cron trigger: `0 9 ?
- MON` runs at 9 AM every Monday. Stale documentation is nearly as bad as no documentation, so automation keeps it useful.
Cost Breakdown
| Tool | Plan Needed | Monthly Cost | Notes |
|---|---|---|---|
| SourceAI | Pro | £45 | Includes 10,000 API requests; larger codebases may need higher tier |
| bhava-ai | Standard | £60 | Unlimited diagram generation; includes SVG and PNG export |
| Mintlify | Team | £99 | Supports custom documentation templates and branding |
| n8n | Cloud Pro | £30 | Self-hosted option is free but requires infrastructure |
| Make | Free tier | £0 | 1,000 operations per month; upgrade to Pro (£10) if running weekly |
| Total | £234–£244 | Assumes weekly workflow runs; one-time setup only |
If you're already paying for n8n or Make for other workflows, add only the SourceAI, bhava-ai, and Mintlify costs to your budget. For teams managing 5+ microservices, this usually costs less than one developer-week per year of labour savings.
The cost per document generation (assuming weekly runs) is roughly £4.50. Generating the same documentation manually takes a developer 3-4 hours at typical London rates, making the automation 15-20 times cheaper per update cycle.