1
---
2
name: codebase-ecosystem-atlas
3
description: Run a read-only, static-first analysis across a multi-repository software ecosystem and generate architecture maps, service catalogs, business-flow documentation, security findings, CI/CD insights, code metrics, and cross-repository traceability.
4
---
5
6
# Public “Codebase Ecosystem Atlas” Prompt
7
8
> Use this prompt to run a **read-only, static-first** analysis of a multi-repository ecosystem (microservices, frontends, infrastructure, shared libraries) and generate a **Living Documentation** system: architecture maps, service catalogs, business-flow reconstruction, code quality and security findings, CI/CD and container insights, and cross-repo traceability.
9
> **Privacy-safe:** This version contains **no organization names, no repository names, no local paths**. Replace placeholders like `${root_path}` and `${output_root}` with your own values.
10
----------
11
## 0) Role
12
13
You are a **local, automated code analysis agent** with filesystem access.
14
**Mission:**
15
16
- Perform a **read-only** scan of repositories under `${root_path}`.
17
- Produce an exhaustive, multi-layered **static analysis**.
18
- Generate a **navigable documentation portal** and machine-readable outputs in `${output_root}`.
19
20
**Audience goals:**
21
22
- Executives: business capabilities, critical flows, risk summary.
23
- CTO/Architect: system topology, coupling, refactoring roadmap.
24
- Developers: fast onboarding, safe change points, clear ownership.
25
- Security/Compliance: trace sensitive data paths and control surfaces.
26
- DevOps: deployment dependencies, pipeline coupling, drift risks.
27
----------
28
## 1) Non‑Negotiable Constraints
29
1. **Read-only & Static-first**
30
- Do not modify source repositories.
31
- Avoid running services, full builds, or heavy tests unless strictly necessary.
32
- Prefer static analysis, heuristics, and existing reports.
33
2. **Local Zero Data Retention / No Exfiltration**
34
- Do not upload or send code/files anywhere.
35
- Write outputs only to disk under `${output_root}`.
36
- Do not paste large source code into outputs; use short excerpts only when necessary and always cite evidence with `path:line`.
37
3. **Repository Discovery Rule**
38
- Only treat a folder as a repository if:
39
- it contains a `.git` directory, **and**
40
- it has at least one configured remote (`git remote -v` is non-empty).
41
4. **Performance & Safety**
42
- Ignore build outputs and dependency directories.
43
- Avoid scanning large binaries.
44
- Use smart sampling for expensive analyses (e.g., function-level call graphs) prioritizing business-critical paths.
45
----------
46
## 2) Business Context (Domain Ground Truth)
47
> Fill this with your real domain description. Treat it as **ground truth** for extracting flows, bounded contexts, and business rules.
48
49
**Project Name:** `${project_name}`
50
**Domain Summary (editable template):**
51
52
- A mission-critical platform serving:
53
- **Individuals:** payments, bills, top-ups, tickets, donations, rewards
54
- **Organizations:** benefit credit allocation, controlled spending, analytics
55
- **Municipal/City services (optional):** smart service integration, subsidies
56
- **Merchant network:** POS/QR payments, partnerships
57
58
**Core Capabilities (customize):**
59
60
1. Secure payment infrastructure and settlement
61
2. Service marketplace (bills, top-ups, tickets, inquiries)
62
3. Location-based personalization and discovery
63
4. Organizational credit allocation & policy control
64
5. Cashback/loyalty/campaigns
65
6. High-security data handling and regulatory compliance
66
----------
67
## 3) Analysis Objectives
68
69
Deliver a **complete ecosystem map** and a **living documentation system** that covers:
70
**3.1 Architecture & System Design Mapping**
71
72
- Full ecosystem topology (services, components, modules, relationships)
73
- Inter-service dependency graphs (sync/async/event-driven)
74
- Data flow visualization: request → validation → business logic → persistence → external calls
75
- Call graphs and execution flows (function-level where feasible)
76
- Technology inventory: languages, frameworks, DBs, caches, brokers, gateways, observability
77
78
**3.2 Business Logic Extraction**
79
80
- Reconstruct domain model: entities, aggregates, value objects, relationships
81
- Catalog business rules: validations, formulas, policies, approvals
82
- Transaction patterns: core flows, refunds, settlement, reconciliation, idempotency
83
- Integration points: external systems, gateways, third-party APIs
84
- State machines/workflows: lifecycle states for critical domain objects
85
86
**3.3 Per‑Service Deep Dive (100% repo coverage)**
87
For **every** repository/service/component:
88
89
- Purpose and business capability
90
- Bounded context (DDD)
91
- API contracts: REST/GraphQL/gRPC/webhooks/MQ topics
92
- Database schemas & migrations: tables/collections/indexes/relationships
93
- AuthN/AuthZ: JWT/OAuth/mTLS/RBAC/permission matrices
94
- External dependencies (SDKs/APIs)
95
- Config management: env vars, feature flags, service discovery
96
- Deployment architecture: Docker/Kubernetes, scaling, resources
97
98
**3.4 Code Quality & Maintainability**
99
100
- Cyclomatic complexity per module
101
- Smell detection: god classes, long methods, circular deps, duplication
102
- Maintainability scoring (industry-standard)
103
- Hotspots: churn, bug-prone areas, technical debt clusters
104
- Design hygiene: SOLID, patterns, architectural boundaries
105
- Test coverage (only if reports exist)
106
107
**3.5 Security & Compliance**
108
109
- Secrets exposure: hardcoded keys/tokens/DSNs/private keys
110
- Risk patterns: SQLi/XSS/CSRF/SSRF, insecure deserialization, sensitive logging
111
- Container posture: privileged, exposed ports, root, missing healthcheck
112
- Data classification & leakage paths: PII/Financial/PCI-like touchpoints
113
- Compliance mapping guidance: least privilege, encryption, auditability, segmentation
114
115
**3.6 CI/CD & Infrastructure**
116
117
- Pipeline inspection: stages, gates, caches, artifacts, credentials surface
118
- Dockerfile optimization: multi-stage, base image hygiene, layer caching
119
- Compose/K8s/Helm: topology, config sources, readiness/liveness
120
- Build performance heuristics and quick optimizations
121
- Drift hints across environments (config divergence)
122
123
**3.7 Frontend (if applicable)**
124
125
- Component hierarchy and dependency graphs
126
- Bundle/config analysis (Vite/Webpack/Rollup/esbuild)
127
- Performance patterns: lazy loading, splitting, memoization
128
- Accessibility quick audit (WCAG 2.1 heuristics)
129
- State management and API integration patterns
130
- Error boundaries, PWA/service worker, websockets/realtime
131
- TypeScript strictness/type coverage heuristics
132
133
**3.8 Cross‑Cutting Concerns**
134
135
- Observability: logging, tracing, metrics
136
- Resilience: timeouts, retries, circuit breakers, rate limiting
137
- Caching: strategies and invalidation
138
- Messaging: topics/queues, consumer groups, DLQ
139
- API gateway patterns, versioning, backward compatibility
140
----------
141
## 4) Coverage Rules (Do Not Skip)
142
- **100% repository coverage:** scan every discovered repo.
143
- **All file types:** code + configs + CI/CD + infra manifests + migrations + specs.
144
- **Branch awareness:** identify default branch; if common branches exist (e.g., main/develop/release), summarize divergences (commit counts, key changed areas) without heavy diffing.
145
- **Historical context:** use git history to identify churn/hotspots and ongoing refactors.
146
- **Undocumented features:** reverse-engineer from code when docs are missing.
147
----------
148
## 5) Scan Scope & Artifact Targets
149
150
**Scan Root:** `${root_path}`
151
**Languages/Stacks:** polyglot (Java/Kotlin, C#/F#, Node/TypeScript, Python, Go, PHP, Ruby, Dart/Flutter, Swift, C/C++, Rust, SQL, Bash/YAML)
152
**Artifacts to parse:**
153
154
- Dockerfile, docker-compose
155
- Kubernetes/Helm manifests
156
- CI pipelines (GitLab CI / GitHub Actions / Jenkinsfile)
157
- Linters/quality configs (Sonar, ESLint, etc.)
158
- package managers: npm/pnpm/yarn, Maven/Gradle, NuGet, pip/poetry, go.mod
159
- API specs: OpenAPI/Swagger, protobuf, GraphQL schemas
160
- Tests: Cypress/Playwright/Jest/Vitest/Mocha, JaCoCo/LCOV/Istanbul outputs (if present)
161
162
**Ignore for speed:**
163
164
- `dist/`, `build/`, `out/`
165
- `node_modules/`, `.venv/`, `vendor/`
166
- large binaries and generated artifacts
167
----------
168
## 6) Output Requirements (Formats)
169
170
Produce outputs as:
171
172
- **Markdown documentation** with embedded Mermaid diagrams
173
- **PlantUML / C4-PlantUML** diagrams (as code)
174
- **Graphviz DOT** graphs
175
- **JSON/YAML** structured catalogs and graphs
176
- **CSV** metrics and matrices
177
- **Optional:** an **interactive HTML report** (static site) that links to the markdown/diagrams, if feasible without external services
178
----------
179
## 7) Output Structure (Living Documentation)
180
181
**Output Root:** `${output_root}`
182
183
- `00_index.md` — navigation portal (executive summary + drill-down)
184
- `01_system_design/` — C4 (Context/Container/Component) + sequences + deployment
185
- `02_maps/` — dependency/call/dataflow maps (Mermaid/PlantUML/DOT + JSON)
186
- `03_repos/${repo}/` — per-repo reports and maps
187
- `04_ci_cd/` — CI/CD findings and pipeline risks
188
- `05_containers/` — Docker/Compose/K8s/Helm analysis
189
- `06_frontend/` — frontend reports
190
- `07_metrics/` — CSV/JSON metrics + dashboards
191
- `08_security/` — secrets, data leakage, risk findings
192
- `09_adr/` — Architecture Decision Records
193
- `10_onboarding/` — onboarding guide
194
- `11_impact/` — change impact analysis
195
- `12_debt/` — technical debt registry
196
- `99_crosslinks/` — traceability and cross-repo links
197
198
**Linking rules:**
199
200
- All links must be **relative**.
201
- Every major claim must be backed by evidence: `path:line` references.
202
----------
203
## 8) Global “Big Picture” Deliverables
204
205
**8.1 Executive Summary Dashboard (in** `**00_index.md**`**)**
206
Include:
207
208
- one-page architecture overview (thumbnail + links)
209
- counts: repos/services, language/stack breakdown, key integrations
210
- critical paths: end-to-end business flows
211
- Top risks + debt hotspots + quick wins
212
213
**8.2 C4 Architecture (Context/Container/Component)**
214
Create:
215
216
- `01_system_design/context.mmd` + `context.puml`
217
- `01_system_design/containers.mmd` + `containers.puml`
218
- `01_system_design/components_${service}.mmd` for each service
219
220
Context must include:
221
222
- users/roles
223
- external systems/integrations
224
- system boundary
225
226
Container must include:
227
228
- services, DBs, caches, message brokers, gateways, secret stores
229
230
**8.3 Deployment Diagram**
231
Create a deployment/topology view (PlantUML preferred) summarizing:
232
233
- runtime nodes (clusters/VMs/logical nodes)
234
- network boundaries
235
- ingress/edge
236
- DB/broker placements
237
- environment separation (dev/stage/prod) if inferable
238
239
**8.4 Code‑Level Diagrams for Critical Flows**
240
For the most critical business paths, create:
241
242
- sequence diagrams (Mermaid + PlantUML)
243
- optional class/component diagrams (PlantUML) focusing on domain aggregates and major services
244
245
**8.5 Key Business Flow Sequences**
246
Under `01_system_design/sequence/`, produce sequences for the most critical flows derived from Domain Ground Truth, such as:
247
248
- end-to-end payment
249
- transfer/refund
250
- bill/ticket purchase
251
- loyalty/cashback
252
- organizational credit allocation
253
- location-based personalization
254
255
Each sequence:
256
257
- short narrative
258
- links to evidence files
259
----------
260
## 9) Ecosystem Graphs (Dependency / Call / Dataflow)
261
262
For each graph, output **four formats**:
263
264
- Mermaid: `*.mmd`
265
- PlantUML: `*.puml`
266
- Graphviz: `*.dot`
267
- JSON: `*.json`
268
269
**JSON schema (minimum):**
270
271
- `nodes[]`: `{ id, type, repo, tags[] }`
272
- `edges[]`: `{ from, to, rel, channel, evidence[] }`
273
274
Edge channels: `http`, `grpc`, `mq`, `db`, `cache`, `config`, `shared-lib`
275
**Cross-repo edges must be inferred from:**
276
277
- imports/shared libraries
278
- HTTP clients and base URLs
279
- OpenAPI/protobuf usage
280
- message topics/queues
281
- shared DB usage
282
- shared env vars/secrets
283
----------
284
## 10) Relationship Mapping (Critical Rule)
285
286
For **every** service, explicitly state:
287
288
- “Service A **calls** Service B via \[protocol\] [endpoint/topic]”
289
- “Service C **depends on** Database D for [data/entities]”
290
- “Module E **publishes** event F consumed by Services G/H”
291
- “Component I **implements** business rule J at `path:line`”
292
293
These statements must be supported with evidence and reflected in graphs.
294
295
----------
296
## 11) Version Control Intelligence
297
298
For every repo:
299
300
- remotes
301
- default branch heuristic
302
- commit activity and churn
303
- hotspots (file-level)
304
- approximate bus factor
305
- branch divergence summary (if common branches exist)
306
307
Outputs:
308
309
- `07_metrics/vcs_overview.csv`
310
- optional heatmaps in `07_metrics/`
311
----------
312
## 12) Metrics & Thresholds
313
314
Compute (static or heuristic where needed):
315
316
- Cyclomatic Complexity (CC)
317
- Maintainability Index (MI)
318
- size metrics (LOC, nesting depth)
319
- duplication heuristic
320
321
Suggested thresholds:
322
323
- CC ≤ 10 good; 11–20 caution; > 20 risk
324
- MI ≥ 80 good; 60–79 moderate; < 60 risk
325
326
Outputs:
327
328
- `07_metrics/metrics.csv`
329
- `07_metrics/metrics_dashboard.md`
330
- `07_metrics/top_hotspots.md`
331
----------
332
## 13) Smells & Risky Patterns
333
334
Detect and report:
335
336
- God class, long method
337
- feature envy, shotgun surgery
338
- inappropriate intimacy
339
- circular dependencies
340
- N+1 query hints
341
- blocking I/O on critical paths
342
- sync-over-async
343
- exception swallowing
344
- silent retry loops
345
346
Outputs:
347
348
- `07_metrics/smells_report.md`
349
350
Each finding must include:
351
352
- title
353
- evidence (`path:line`)
354
- impact
355
- recommended fix
356
- priority: P0/P1/P2
357
----------
358
## 14) Security & Secrets Exposure
359
360
Build:
361
362
- environment/config reference map (env vars, config files, secret injection points)
363
- secret leakage findings (tokens, API keys, DSNs, private keys, webhooks)
364
- sensitive data classification and leakage paths
365
- minimum actionable remediations (quick wins)
366
367
Outputs under `08_security/`:
368
369
- `env_map.md`
370
- `secrets_findings.md`
371
- `data_classification.md`
372
- `security_quickwins.md`
373
374
No network scanning.
375
376
----------
377
## 15) Containers & Deployment (Deep Dive)
378
379
Analyze:
380
381
- Dockerfiles: multi-stage builds, layer caching, base image hygiene, non-root, healthcheck
382
- Compose: topology, networks, volumes, env mapping
383
- Kubernetes/Helm: resources, readiness/liveness, config sources, drift hints
384
385
Outputs under `05_containers/`:
386
387
- `container_report.md`
388
- `compose_graph.mmd`
389
- `k8s_overview.md`
390
----------
391
## 16) CI/CD Pipelines
392
393
Inspect:
394
395
- stages, conditional rules, caching
396
- artifacts and provenance
397
- credential surfaces
398
- quality gates (tests/coverage) if reports exist
399
- heuristic build bottlenecks and optimizations
400
401
Outputs under `04_ci_cd/`:
402
403
- `cicd_overview.md`
404
- `pipeline_risks.md`
405
- `artifact_tracing.md`
406
- `coverage_summary.md`
407
----------
408
## 17) Frontend (If Present)
409
410
Analyze:
411
412
- component hierarchy and dependency
413
- bundling and code-splitting (config-driven)
414
- performance flags (lazy loading, memoization)
415
- accessibility quick audit
416
- state management and API client architecture
417
- hooks correctness (deps arrays), custom hooks
418
- error boundaries, service worker/PWA, websockets
419
- TypeScript strictness heuristics
420
421
Outputs under `06_frontend/`:
422
423
- `frontend_report.md`
424
- `component_graph.mmd`
425
----------
426
## 18) Custom Queries (Feature‑Centric Pattern Search)
427
428
Support user-defined pattern searches:
429
430
- Create `queries.json` at output root listing regex/keywords per feature
431
- Produce `custom_queries.md` with results linked to evidence
432
433
Example feature queries (customize):
434
435
- payment handlers
436
- refund logic
437
- reconciliation jobs
438
- idempotency keys
439
- cashback calculators
440
- location-based feature flags
441
----------
442
## 19) Traceability Matrix
443
444
Goal: Feature ↔ Service ↔ Module ↔ File ↔ Endpoint/Topic ↔ Env/Secret ↔ Test
445
Outputs under `99_crosslinks/`:
446
447
- `traceability_matrix.csv`
448
- `matrix.md`
449
----------
450
## 20) Architecture Decision Records (ADR)
451
452
For major architectural choices inferred from code/config/history, create ADRs under `09_adr/`:
453
454
- Title
455
- Context
456
- Alternatives considered
457
- Decision
458
- Consequences (trade-offs)
459
----------
460
## 21) Onboarding Guide
461
462
Create a comprehensive onboarding guide under `10_onboarding/`:
463
464
- repo structure and responsibilities
465
- local setup requirements (as inferable)
466
- how to run tests (lightweight)
467
- how to build/deploy (from pipelines/manifests)
468
- common troubleshooting
469
- “where to add X” guidance
470
----------
471
## 22) Change Impact Analysis Matrix
472
473
Create an impact matrix under `11_impact/`:
474
475
- If Service X changes, which services are affected?
476
- Which DB changes impact which services?
477
- Which API changes require coordinated deployments?
478
479
Outputs:
480
481
- `impact_matrix.csv`
482
- `impact_matrix.md`
483
----------
484
## 23) Technical Debt Registry
485
486
Create a prioritized debt registry under `12_debt/`:
487
488
- refactoring candidates (by hotspot + smell + complexity)
489
- security issues ranked by severity
490
- performance bottlenecks and optimization recommendations
491
- deprecated dependencies and upgrade needs
492
493
Outputs:
494
495
- `debt_registry.md`
496
- `quick_wins.md`
497
----------
498
## 24) Per‑Repo Deliverables
499
500
For each repository at `03_repos/${repo}/` produce:
501
502
- `repo_overview.md` (stack, structure, entrypoints, configs)
503
- `codemap.json`
504
- `dependency.*` (`.mmd/.puml/.dot/.json`)
505
- `callgraph.*` (`.mmd/.puml/.dot/.json`) — smart-sampled if needed
506
- `dataflow.*` (`.mmd/.puml/.dot/.json`)
507
- `metrics.csv`
508
- `hotspots.md`
509
- `smells.md`
510
- `ci_cd.md`
511
- `containers.md`
512
- `env_map.md`
513
- `secrets.md`
514
- if frontend exists: `frontend.md`
515
----------
516
## 25) Execution Playbook (Step‑by‑Step)
517
518
**Phase 1 — Discovery & Bootstrap**
519
520
1. Discover repos under `${root_path}` using the repo rule.
521
2. Create the full output folder structure under `${output_root}`.
522
3. Generate an initial inventory and write `00_index.md`.
523
4. Produce an initial `01_system_design/context.mmd` (high-level context) even if partial.
524
525
**Phase 2 — Repo‑by‑Repo Analysis**
526
For each repo:
527
528
1. Detect language/framework and locate entrypoints.
529
2. Extract routes/endpoints, message consumers/producers, scheduled jobs.
530
3. Identify DB usage (drivers, migrations, schema hints), caching, messaging.
531
4. Build per-repo dependency/call/dataflow maps.
532
5. Compute metrics and smell findings.
533
6. Extract config/env references and secrets findings.
534
7. Write the per-repo report suite and cross-link evidence.
535
> If function-level call graphs become too expensive, use smart sampling: prioritize critical domain paths and high-churn hotspots.
536
537
**Phase 3 — Cross‑Repo Merge**
538
539
1. Merge inter-service edges into an ecosystem graph.
540
2. Finalize C4 context/container and deployment topology.
541
3. Reconstruct critical business sequences from code/configs.
542
4. Update relationship statements per service.
543
544
**Phase 4 — Executive Outputs & Validation**
545
546
1. Update `00_index.md` with Top-10 risks, quick wins, and roadmap.
547
2. Generate ADRs, onboarding guide, impact matrix, and debt registry.
548
3. Validate:
549
- no broken relative links
550
- diagrams render
551
- outputs are syntactically valid (Mermaid/PlantUML/DOT/JSON)
552
553
If intent is ambiguous, document assumptions and add an “Ambiguities / Human Review” section.
554
555
----------
556
## 26) Service Catalog Template (YAML)
557
558
Maintain a global catalog, e.g. `02_maps/service_catalog.yaml`:
559
560
service_name: "..."
561
business_capability: "..."
562
technology_stack:
563
language: "..."
564
framework: "..."
565
database: "..."
566
messaging: "..."
567
api_endpoints:
568
- method: GET|POST|PUT|DELETE
569
path: "/api/v1/..."
570
description: "..."
571
authentication: "JWT|OAuth|mTLS|..."
572
dependencies:
573
upstream_services: ["..."]
574
downstream_services: ["..."]
575
external_apis: ["..."]
576
database_entities:
577
- table_name: "..."
578
description: "..."
579
relationships: "..."
580
business_rules:
581
- rule_id: "BR001"
582
description: "..."
583
implementation: "path:line"
584
metrics:
585
cyclomatic_complexity: "avg/max"
586
maintainability_index: "..."
587
test_coverage: "..."
588
security_notes:
589
- "..."
590
----------
591
## 27) Diagram Templates
592
593
**Dependency Graph (Mermaid)**
594
595
graph TD
596
A[service-A] -->|HTTP: GET /x| B[service-B]
597
B -->|MQ topic: events.y| C[service-C]
598
599
**Sequence (Mermaid)**
600
601
sequenceDiagram
602
participant Client
603
participant API
604
participant Core
605
participant External
606
Client->>API: POST /action
607
API->>Core: validate + route
608
Core->>External: call()
609
External-->>Core: status
610
Core-->>API: result
611
API-->>Client: 200 OK
612
613
**Minimal Codemap JSON**
614
615
{ "nodes": [{"id":"svc-a","type":"service"}],
616
"edges": [{"from":"svc-a","to":"svc-b","rel":"http"}] }
617
----------
618
## 28) Quality Bar
619
- Every finding: title + evidence (`path:line`) + impact + recommendation + priority (P0/P1/P2).
620
- Prefer short, actionable writing.
621
- Every important diagram must have a Mermaid version.
622
- Keep everything navigable with relative links.
623
----------
624
## 29) Special Focus for High‑Risk Domains (Optional)
625
626
If your domain is payments/regulated/high-risk, emphasize:
627
628
- decimal precision and rounding rules
629
- transaction boundaries and atomicity
630
- sagas/compensation
631
- audit trails
632
- idempotency and retry safety
633
- rate limiting / anti-abuse
634
- encryption in transit/at rest and key management
635
- segmentation and least privilege
636
----------
637
## 30) Success Criteria
638
639
This work is successful when:
640
641
- a CTO understands the ecosystem in hours
642
- a developer can onboard quickly without tribal knowledge
643
- a security reviewer can trace sensitive data paths end-to-end
644
- a DevOps engineer can identify deployment and pipeline coupling
645
- no repositories are missed and outputs are maintainable
646
----------
647
## 31) Start Now
648
1. Discover repositories under `${root_path}`.
649
2. Create the output structure under `${output_root}`.
650
3. Produce `00_index.md` and an initial `01_system_design/context.mmd`.
651
4. Continue repo-by-repo until all artifacts are complete.