# Sanicode — Project Context

Sanicode is a PyPI-distributed CLI tool that uses an AI agent (configurable LLM backend) to build a codebase-level knowledge graph, then outputs security/sanitization recommendations mapped to OWASP ASVS, NIST 800-53, and ASD STIG controls. The key differentiator over tools like Bandit or Semgrep is data flow context via LLM reasoning over a knowledge graph, not just AST pattern matching.

See `RESEARCH.md` for the full standards baseline, architecture rationale, and tooling landscape.

## Getting Started

Start with issue #1 in the Phase 1 milestone. Issues have dependency notes in their descriptions — check "blocked by" before starting. Work issues in order within each milestone.

## Tech Stack

- Python 3.10+, package name `sanicode`
- CLI: Click or Typer (decided in issue #1)
- AST parsing: Python `ast` module (tree-sitter for multi-language, later)
- Knowledge graph: NetworkX (in-memory); Neo4j for persistent/large codebases
- LLM integration: LiteLLM (multi-provider, tiered endpoints)
- API server: FastAPI (`sanicode serve`)
- Config: TOML (`sanicode.toml` or `~/.config/sanicode/config.toml`)
- Output formats: Markdown, JSON, SARIF
- Container base: `registry.redhat.io/ubi9/python-311` (UBI9, multi-stage)
- Phase 3 operator: kopf (Python); Phase 4: Go Operator SDK if needed

## Project Structure

```
sanicode/
├── src/sanicode/       # Main package
├── data/               # Compliance cross-reference DB (JSON/TOML)
├── rules/              # Rule definitions (YAML, Bandit-style)
├── prompts/            # Prompt templates (YAML, with {variable} substitution)
├── tests/              # Mirrors src/sanicode/ structure; pytest, 80%+ coverage
└── sanicode.toml       # Project config (or ~/.config/sanicode/)
```

## Phase Structure

- **Phase 1** (starting now): Python package + CLI. Scan → knowledge graph → compliance-mapped report. Local mode + `sanicode serve` API mode.
- **Phase 2**: Containerized deployment on OpenShift. Helm chart, Prometheus metrics, Grafana dashboard, MLflow integration, Tekton task, KFP pipeline.
- **Phase 3**: Lightweight Python Operator via kopf. CRDs: SanicodeConfig, SanicodeScan, SanicodeProfile, SanicodeException. Auto-discover InferenceService CRs.
- **Phase 4**: Production Operator (Go/Operator SDK or Helm-based), OLM packaging, OperatorHub submission.

## CLI Surface

```
sanicode config    # Configure LLM backend (tiered endpoints)
sanicode scan      # Scan codebase, build knowledge graph
sanicode serve     # Start FastAPI server (containerized/remote mode)
sanicode report    # Generate compliance-mapped report
sanicode recommend # Output prioritized recommendations
sanicode graph     # Inspect/export the knowledge graph
```

The CLI operates in three modes: **local** (all in-process), **remote** (thin client to sanicode-api), **hybrid** (AST local, LLM remote).

## Key Architectural Decisions

**Degraded mode is not optional.** With no LLM configured, sanicode must still produce useful output: AST pattern matching, known-bad function detection, data flow graph construction, compliance lookups, and SARIF output. LLM adds context-awareness and false-positive reduction on top.

**Compliance mapping is cross-cutting.** Every finding must carry: CWE ID, OWASP ASVS 5.0 requirement (with L1/L2/L3 level), NIST 800-53 control (SI-10, SI-15, etc.), ASD STIG check ID and CAT level (I/II/III). PCI DSS mapping where applicable.

**Knowledge graph is the differentiator.** Graph nodes: entry points, sanitization points, sink points, trust boundaries. Edges: data flow paths. LLM reasons over the graph to assess whether sanitization actually covers the identified threat.

**API is designed for machine consumption first.** A refactoring agent (Konveyor, custom agent) needs to iterate programmatically. REST endpoints: `POST /api/v1/scan`, `GET /api/v1/scan/{id}`, `GET /api/v1/scan/{id}/findings`, `GET /api/v1/scan/{id}/graph`, `POST /api/v1/analyze`, `GET /api/v1/compliance/map`.

**Offline-native, not offline-compatible.** Zero egress at runtime. All compliance data, rules, and prompt templates ship in the package. Model weights are a separate supply chain artifact (PVC or ModelCar OCI image) — never bundled with sanicode.

**Tiered model support.** `sanicode.toml` allows separate endpoints for fast (classification), analysis (data flow), and reasoning (compliance mapping + report generation) tiers. Recommended: Granite Nano → Granite Code 8B → Llama 3.1 70B.

## Backlog Discipline

Work backlog items until they are 100% complete. 99% rounds to zero. If during implementation we discover scope that should wait (separate concern, large effort, blocked on something else), the standard procedure is:

1. Create a new backlog issue for the carved-out work, with full context.
2. Update the current issue to document what moved and reference the new issue(s).
3. Only then close the current issue.

This prevents hidden technical debt from accumulating behind "done" items. An agent should never offer to close an item until the carve-out issues exist and the current item's description reflects the reduced scope.

## Releasing

The version lives in two files that must stay in sync:
- `src/sanicode/version.py` — `__version__ = "x.y.z"`
- `pyproject.toml` — `version = "x.y.z"`

To release, run from the project root:

```bash
./scripts/release.sh <version> "<description>"
```

This updates both version files, commits, tags, and pushes. GitHub Actions handles testing, GitHub Release creation, and PyPI publishing via OIDC trusted publishing. See `PUBLISHING.md` for one-time setup steps.

Never update version files manually — always use the release script to ensure consistency.

## Don't Forget

- SARIF output is critical for ecosystem interoperability (GitHub Code Scanning, VS Code, Azure DevOps, Tekton gating). Prioritize this over custom formats.
- OWASP ASVS reference is version **5.0** (released May 2025). The chapter is now "V1: Encoding and Sanitization" — not the old V5. Use `v5.0.0-V1-x.x` identifiers.
- ASD STIG version is **v4 r11**. Key IDs: APSC-DV-002510 (command injection, CAT I), APSC-DV-002520 (XSS, CAT II), APSC-DV-002530 (input validation, CAT II).
- CWE is the lingua franca across all frameworks. Core sanitization CWEs: 20, 77, 78, 79, 89, 94, 116, 918, 1333.
- `SanicodeException` CRs (Phase 3) are critical for ATO workflows — RBAC-controlled, expiring, GitOps-managed risk acceptances.
- Expose `/metrics` (Prometheus) from day one in `sanicode serve`. Compliance score, findings by severity/CWE/namespace, LLM usage.
