Metadata-Version: 2.4
Name: sdat-niriksha
Version: 1.0.1
Summary: System Design Audit Tool (NIRĪKṢĀ) — deterministic, language-agnostic architecture auditor
Author-email: Subhadip Paul <subhadippaulff@gmail.com>
License: MIT
Project-URL: Homepage, https://github.com/Subhadip-Paul2006/sdat-niriksha
Project-URL: Repository, https://github.com/Subhadip-Paul2006/sdat-niriksha
Project-URL: Documentation, https://github.com/Subhadip-Paul2006/sdat-niriksha#readme
Project-URL: Issues, https://github.com/Subhadip-Paul2006/sdat-niriksha/issues
Project-URL: Changelog, https://github.com/Subhadip-Paul2006/sdat-niriksha/blob/main/CHANGELOG.md
Keywords: system-design,audit,architecture,scanner,resilience,distributed-systems
Classifier: Development Status :: 5 - Production/Stable
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: MIT License
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Topic :: Software Development :: Quality Assurance
Classifier: Topic :: System :: Distributed Computing
Requires-Python: >=3.10
Description-Content-Type: text/markdown
License-File: LICENSE
License-File: NOTICE
Requires-Dist: pyyaml>=6.0
Requires-Dist: jinja2>=3.1
Requires-Dist: pydantic>=2.0
Requires-Dist: rich>=13.0.0
Provides-Extra: dev
Requires-Dist: pytest>=7.0; extra == "dev"
Requires-Dist: pytest-cov>=4.0; extra == "dev"
Requires-Dist: ruff>=0.1; extra == "dev"
Requires-Dist: mypy>=1.5; extra == "dev"
Requires-Dist: build; extra == "dev"
Requires-Dist: twine; extra == "dev"
Requires-Dist: types-pyyaml; extra == "dev"
Requires-Dist: tomli>=1.1.0; python_version < "3.11" and extra == "dev"
Dynamic: license-file

# SDAT — System Design Audit Tool (NIRĪKṢĀ)

[![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)](LICENSE)
[![Python: 3.10+](https://img.shields.io/badge/Python-3.10%20%7C%203.11%20%7C%203.12%20%7C%203.13-brightgreen.svg)](pyproject.toml)
[![Architecture: Two-Tier Swarm](https://img.shields.io/badge/Architecture-Two--Tier%20Swarm-purple.svg)](docs/architecture.md)
[![Concept Invariant: Zero False-PASS](https://img.shields.io/badge/Concepts-124%20Canonical-orange.svg)](docs/concept-coverage.md)

**SDAT (System Design Audit Tool / NIRĪKṢĀ / तन्त्रविन्यास-निरीक्षा)** is an open-source, provider-agnostic, portable architecture auditor designed to bridge the chasm between high-level architectural theories and actual source-code implementation truth.

Repository: **[https://github.com/Subhadip-Paul2006/sdat-niriksha](https://github.com/Subhadip-Paul2006/sdat-niriksha)**  
PyPI Distribution: **[`sdat-niriksha`](https://pypi.org/project/sdat-niriksha/)**  
Current Target Version: **`1.0.1`**

---

## 1. The Problem SDAT Solves

Software engineering teams often design robust architectures on whiteboards—specifying circuit breakers, exponential backoff with jitter, rate limiters, caching with TTL, and isolated connection pools. In practice, production outages frequently occur because:

1. **Dead or Decorative Imports:** A client library (e.g. `redis`, `pybreaker`, or `tenacity`) is imported, but actual network calls bypass it.
2. **Missing Invariants:** Caches are written without TTL; retries execute in tight loops without backoff or jitter, creating accidental self-inflicted denial-of-service (retry storms).
3. **Static Analysis Overreach:** Conventional linters flag cosmetic syntax errors but cannot evaluate distributed systems patterns; conversely, superficial tools emit false "PASS" results simply because a file or class contains the word "Cache".

**SDAT evaluates behavior, not symbol names:** *"Names are clues; behavior is evidence."* It extracts concrete AST evidence across multi-language codebases and audits them against canonical distributed systems rules.

---

## 2. Core Architectural Philosophy: AI is Optional

SDAT enforces strict offline determinism:

```
┌─────────────────────────────────────────────────────────────┐
│ SDAT WITHOUT AI = FULLY FUNCTIONAL DETERMINISTIC AUDITOR    │
│ SDAT WITH AI    = DETERMINISTIC AUDIT + ENRICHED EXPLAINERS │
└─────────────────────────────────────────────────────────────┘
```

- **Deterministic Core (Default):** Static AST scanners (Python, TypeScript, Go, Rust, C/C++, PHP, Java), Common Evidence Model (CEM), 124 canonical concepts, two-tier multi-agent swarm, and Jinja2 report renderers operate **100% offline with zero external network calls**.
- **Optional AI Enhancement:** An AI Gateway abstraction (`sdat.ai.gateway`) supports local models (**Ollama**) and cloud APIs (**OpenRouter**, **Google Gemini**, **Anthropic**, **OpenAI**). If an AI provider fails, times out, or is unconfigured, SDAT **fails open** and renders deterministic reports without aborting.

---

## 3. High-Level Architecture

The public-facing audit lifecycle proceeds deterministically from raw source code to actionable architecture reports:

```mermaid
flowchart TD
    subgraph S_TARGET["1. Target Repository"]
        REPO["Target Source Files\n(Read-Only Inspection)"] --> DISCO["Discovery & Path Sanitizer\n(Rejects drive roots & secret files)"]
    end

    subgraph S_SCAN["2. Multi-Language AST Scanners"]
        DISCO --> S_PY["Python AST Scanner"]
        DISCO --> S_TS["TypeScript / JS Scanner"]
        DISCO --> S_GO["Go AST Scanner"]
        DISCO --> S_RS["Rust Parser"]
        DISCO --> S_CPP["C / C++ Scanner"]
        DISCO --> S_PHP["PHP Scanner"]
        DISCO --> S_JV["Java / Kotlin Scanner"]
    end

    subgraph S_CEM["3. Common Evidence Model (CEM)"]
        S_PY & S_TS & S_GO & S_RS & S_CPP & S_PHP & S_JV --> AGG["Evidence Aggregator\n(Correlation & Deduplication)"]
        AGG --> FACTS["list[EvidenceFact]\n(Strongly Typed Structural Facts)"]
    end

    subgraph S_EVAL["4. Foundation & Domain Evaluation"]
        FACTS --> SWARM["Swarm Orchestrator\n(Bounded Workers + Timeouts)"]
        SWARM --> TIER1["Tier 1: Foundation Agents\n(Caching, Retries, CB, Auth, DB)"]
        SWARM --> TIER2["Tier 2: Domain Agents\n(APIs, DevOps, Web3, ML, Frontend)"]
        TIER1 & TIER2 --> MERGER["Decision Merger\n(Conflict Resolution)"]
    end

    subgraph S_AI["5. Optional AI Explanation Layer"]
        MERGER --> GATEWAY["AI Gateway (Fail-Open)\n(Local Ollama / Cloud LLMs)"]
        GATEWAY -.-> ENRICH["Narrative Remediation Cards\n& Plain-Language Summaries"]
    end

    subgraph S_OUTPUT["6. Deterministic Report Renderer"]
        MERGER --> RENDER["Report Renderer (Jinja2)"]
        ENRICH -.-> RENDER
        RENDER --> OUT1["01-inventory.md"]
        RENDER --> OUT2["02-gaps.md"]
        RENDER --> OUT3["03-misconfigurations.md"]
        RENDER --> OUT4["04-remediation.md"]
        RENDER --> OUT5["index.html Dashboard"]
        RENDER --> OUT6["telemetry.json"]
    end

    classDef blue fill:#2563eb,stroke:#1d4ed8,color:#ffffff;
    classDef green fill:#16a34a,stroke:#15803d,color:#ffffff;
    classDef purple fill:#7c3aed,stroke:#6d28d9,color:#ffffff;
    class DISCO,AGG,SWARM,MERGER,RENDER blue;
    class OUT1,OUT2,OUT3,OUT4,OUT5,OUT6 green;
    class GATEWAY,ENRICH purple;
```

---

## 4. Supported Programming Languages

| Language | Extractor Engine | Verified Patterns & Frameworks |
|:---------|:-----------------|:-------------------------------|
| **Python** | Native `ast` module | FastAPI, Flask, Django, Celery, Redis, Tenacity, PyBreaker, SQLAlchemy, Structlog. |
| **TypeScript / JS** | Babel AST / Token Regex | Express, Fastify, NestJS, Axios, IORedis, BullMQ, Pino, Winston, Prisma. |
| **Go** | Go AST Parser / Regex | Gin, Echo, Fiber, Go-Redis, GoBreaker, Kafka-Go, Zap, GORM. |
| **Rust** | Syntax & Manifest Parser | Tokio, Actix, Reqwest, Tower, Redis-rs, SQLx. |
| **Java / Kotlin** | Structural AST Scanner | Spring Boot, Resilience4j, Spring Retry, Jedis, Hibernate. |
| **C / C++** | Macro & Include Scanner | POSIX sockets, Pthreads, Libcurl, OpenSSL. |
| **PHP** | Token & Include Scanner | PDO, Laravel Service Providers, Symfony HttpClient. |

---

## 5. Supported Concept Categories

SDAT audits **124 canonical system-design concepts** organized across 15 architectural categories:

1. **Caching:** TTL configuration, cache invalidation, cache-aside, eviction policies.
2. **Resilience & Fault Tolerance:** Circuit breakers, retry loops with jitter, fallback wrappers, bulkheads.
3. **Observability:** Structured logging, metrics instrumentation (Prometheus), distributed tracing (OpenTelemetry).
4. **Concurrency & Threading:** Thread pools, async event loops, race condition mitigations.
5. **Connection Management:** Connection pooling, bounded pool sizes, pool timeouts, resource cleanup.
6. **Data & Storage:** ORM sanitization, raw SQL injection prevention, migration versioning, read replicas.
7. **Security & Secrets:** Secret sanitization, authentication middleware, HTTPS enforcement, security headers.
8. **Rate Limiting & Throttling:** Token bucket, leaky bucket, IP/user throttling, backpressure.
9. **Idempotency:** Idempotency-Key headers, deduplication stores, at-most-once processing.
10. **Scalability & Load Balancing:** Reverse proxies, consistent hashing, horizontal partition boundaries.
11. **Messaging & Streaming:** Message brokers (Kafka, RabbitMQ), WebSocket lifecycles, dead-letter queues.
12. **API & Web Architecture:** REST conventions, payload validation, status codes, timeout propagation.
13. **DevOps & Infrastructure:** Health checks (`/healthz`, `/livez`), container hygiene, CI/CD gates.
14. **Frontend Architecture:** Perceived performance, client caching, asset optimization, accessibility contracts.
15. **Machine Learning & NLP:** Serialization safety, model checkpointing, attention masking, tensor contracts.

For full coverage details, see [Concept Coverage & Taxonomy](docs/concept-coverage.md).

---

## 6. Installation

SDAT requires **Python 3.10+** (tested on 3.10, 3.11, 3.12, and 3.13).

### Method A: Standard PyPI Installation
```bash
pip install sdat-niriksha
```

### Method B: Developer Clone (from Source)
```bash
git clone https://github.com/Subhadip-Paul2006/sdat-niriksha.git sdat
cd sdat
python -m venv .venv

# On Linux / macOS:
source .venv/bin/activate
# On Windows PowerShell:
.venv\Scripts\Activate.ps1

pip install -e ".[dev]"
```

### Method C: Git Submodule (Embedded in Existing Project)
```bash
git submodule add https://github.com/Subhadip-Paul2006/sdat-niriksha.git tools/sdat
pip install -e tools/sdat
```

---

## 7. Quick Start & CLI Examples

Both `sdat` and `niriksha` CLI binaries point to the identical command runner:

### 1. Run a Deterministic Offline Audit
Audit a project in 100% offline mode:
```bash
sdat audit /path/to/my-project
```

### 2. Specify Output Directory & Workload Type
```bash
sdat audit /path/to/my-project --output-dir reports/arch --project-type backend
```

### 3. Headless CI/CD Pipeline Execution
Fail fast without interactive prompts, suitable for automated GitHub Actions or GitLab CI:
```bash
sdat audit . --no-ai --non-interactive --output-dir reports/audit
```

### 4. Interactive Configuration Setup
Launch the interactive terminal configuration wizard:
```bash
sdat setup
```

### 5. Inspect Active Configuration & Providers
```bash
# Display active sanitized configuration:
sdat config show

# Check supported AI providers and credential status:
sdat providers
```

### 6. Enable Local Offline AI Remediation (Ollama)
```bash
export SDAT_AI_PROVIDER=ollama
export SDAT_AI_MODEL=qwen2.5-coder
sdat audit .
```

### 7. Check Version
```bash
sdat version
# or
niriksha version
```

---

## 8. Sample Report Findings

### Sample Implemented Finding (`01-inventory.md`)
```markdown
### Distributed Caching with Redis
- **Status:** implemented
- **Priority:** info
- **Confidence:** 0.92/1.0
- **Evidence:**
  - `app/cache.py:12`
    ```python
    client = redis.Redis(host=settings.REDIS_HOST, port=6379, decode_responses=True)
    ```
```

### Sample Misconfiguration Finding (`03-misconfigurations.md`)
```markdown
### Cache Write Without TTL
- **Status:** misconfigured
- **Priority:** high
- **Confidence:** 0.88/1.0
- **Evidence:**
  - `app/services/session.py:45`
    ```python
    cache.set(f"session:{user_id}", session_data)
    ```
- **Misconfiguration:** Redis `.set()` call invoked without `ex=` or `px=` TTL parameter. Risk of unbounded memory growth and stale session data.
- **Remedy:** Pass an explicit expiration window: `cache.set(f"session:{user_id}", session_data, ex=3600)`.
```

---

## 9. Generated Report Outputs

SDAT produces structured, audit-ready artifacts in the configured output directory (`.sdat/reports` or `--output-dir`):

| File | Format | Description |
|:---|:---:|:---|
| **`01-inventory.md`** | Markdown | Discovered system-design patterns positively verified from AST facts. |
| **`02-gaps.md`** | Markdown | Missing architectural patterns grouped by priority (Critical, High, Medium, Low). |
| **`03-misconfigurations.md`** | Markdown | Fragile configurations and anti-patterns with exact file and line citations. |
| **`04-remediation.md`** | Markdown | Actionable fix cards with tailored code snippets and step-by-step guidance. |
| **`index.html`** | Standalone HTML5 | Self-contained interactive dashboard with client-side search and filtering. |
| **`telemetry.json`** | JSON | Machine-readable metrics: execution timings, files scanned, and findings summary. |

---

## 10. Configuration Overview

SDAT resolves configuration using a three-tier hierarchy:
1. Explicit CLI flag: `--config <path>`
2. Repository checkout: `config/sdat.config.yaml`
3. Bundled package defaults: `sdat/resources/config/sdat.config.yaml`

### Key Environment Variables
| Variable | Default | Purpose |
|:---|:---|:---|
| `SDAT_OUTPUT_DIR` | `.sdat/reports` | Output directory for audit reports. |
| `SDAT_AI_PROVIDER` | `none` | AI provider (`none`, `ollama`, `openrouter`, `gemini`, `anthropic`, `openai`). |
| `SDAT_AI_MODEL` | Provider default | Model override (e.g. `qwen2.5-coder`, `gemini-2.5-flash`). |
| `SDAT_MAX_WORKERS` | `4` | Concurrency limit for scanning and swarm evaluation. |

See the [Configuration Reference](docs/configuration.md) for full YAML schemas and options.

---

## 11. Limitations & Unsupported Functionality

To maintain absolute architectural credibility, SDAT explicitly defines what it **cannot** and **does not** do:

1. **Zero Target Code Mutation:** SDAT is strictly a non-invasive auditor. It never edits, patches, refactors, or deletes code in your repository.
2. **Static vs. Runtime Telemetry Boundary:** Static AST analysis cannot verify runtime SLA behavior under production load (such as P99 tail latency, connection pool exhaustion, or hot-partition balancing). These concepts strictly yield `REQUIRES_EXTERNAL_EVIDENCE` until verified production metrics are supplied.
3. **No Target Code Execution:** SDAT never imports, executes, or sandboxes target project code. All analysis is performed via static AST parsing.
4. **Unexecuted Concepts are Explicitly Disclosed:** Any taxonomy concept that lacks an automated scanner rule is classified as `SPECIFICATION ONLY` or `NOT EVALUATED`, never silently skipped or marked as passing.

---

## 12. Security, Privacy & Safety Invariants

- **Read-Only Target Operation:** SDAT never writes files into the target repository.
- **Root Safety Guard:** Scans targeting drive roots (e.g. `C:\` or `/`) are rejected immediately to prevent unbounded traversal.
- **Automated Secret Filtering:** Files matching `.env*`, `*.pem`, `*.key`, `id_rsa*`, and certificate stores are permanently excluded from scanning.
- **Bounded AI Context:** AI enrichment passes receive only small, sanitized snippets within a strict token budget (`4,000 tokens`).

For details, see [Security & Privacy Guide](docs/security-and-privacy.md) and [Security Policy](SECURITY.md).

---

## 13. Documentation Hub

- 📖 **[Documentation Index](docs/index.md):** Complete navigation roadmap.
- 🚀 **[Getting Started Guide](docs/getting-started.md):** 3-step introductory walkthrough.
- ⚙️ **[Installation Guide](docs/installation.md):** Step-by-step setup across operating systems.
- ⚡ **[Quick-Start Tutorial](docs/quickstart.md):** Minimal reproducible audit workflow.
- 🖥️ **[CLI Reference](docs/cli-reference.md):** Exhaustive command and option syntax.
- 🔧 **[Configuration Guide](docs/configuration.md):** Configuration schemas and environment variables.
- 🏛️ **[Architecture Overview](docs/architecture.md):** Subsystem boundaries, AST scanners, and CEM.
- 📊 **[Concept Coverage & Taxonomy](docs/concept-coverage.md):** 124 canonical concepts and detection integrity.
- 🤖 **[AI Providers Guide](docs/ai-providers.md):** Setup for Ollama, OpenRouter, Google, and Anthropic.
- 📋 **[Reports Reference](docs/reports.md):** Specifications for all generated report files.
- ❓ **[Troubleshooting & Diagnostics](docs/troubleshooting.md):** Recipes for common errors and edge cases.
- 💡 **[Frequently Asked Questions](docs/faq.md):** High-level concepts and architectural FAQ.
- 🛠️ **[Developer Guide](docs/development.md):** Contributing AST extractors and signal rules.
- 📦 **[Release Engineering Guide](docs/release.md):** Packaging standards and OIDC publication.

---

## 14. License, Citation & Community

- **License:** [MIT License](LICENSE) (see also [NOTICE](NOTICE)).
- **Contributing:** Please review [CONTRIBUTING.md](CONTRIBUTING.md) and [CODE_OF_CONDUCT.md](CODE_OF_CONDUCT.md).
- **Support & Issues:** See [SUPPORT.md](SUPPORT.md) for assistance and bug reporting.
- **Security Vulnerabilities:** Follow our responsible disclosure guidelines in [SECURITY.md](SECURITY.md).
- **Academic & Technical Citation:** See [CITATION.cff](CITATION.cff) for citation metadata.

*Developed by Subhadip Paul (`shubh06`) — तन्त्रविन्यास-निरीक्षा*
