Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Sruja — context engineering for software changes

Capture knowledge, retrieve context, verify changes. Sruja scans code, links decision context, reports structural drift, and plugs into Cursor and other agents via MCP. Optional repo.sruja is reviewed intent in Git, not the primary product.

Why Sruja?

The Problem

Most architecture tools make you choose:

  • Visual-only tools (Draw.io) – no code, no version control, hard to maintain
  • Code-only tools (Mermaid, PlantUML) – no validation, manual diagram updates
  • Stale diagrams – architecture drifts from reality, documentation gets outdated

Our Solution

Sruja gives AI assistants and humans evidence-backed context for software changes:

FeatureWhat you get
Structural scanCycles, layer violations, god modules — file-level evidence
Task contextfocus, ai, and MCP for targeted retrieval
Built-in gatesDrift, verification, CI-friendly outputs
Optional reviewed intentrepo.sruja when teams want durable intent in Git
Derived outputsMarkdown, Mermaid, and other exports when communication needs them

Who It's For

  • Engineering teams who want shared knowledge and safer AI-assisted changes
  • Tech leads who want decisions to stay visible at change time
  • Platform engineers building guardrails for distributed teams
  • AI agents that need grounded repo context before editing

The Core Loop

  1. Install CLIcurl -fsSL https://sruja.ai/install.sh | bash
  2. Scansruja start -r . then sruja drift -r . --structural-only --advisory
  3. Retrieve contextfocus, ai, or MCP before edits
  4. Verifyverify-task after edits
  5. Optional — reviewed intent in Git with repo.sruja

We're ultra simple – minimal surface area, no unnecessary apps or frameworks – and highly functional – what we ship works reliably for its scope.

Stack

  • Rust – CLI, engine, LSP, WASM (single language for core)
  • VS Code extension – Editor integration (briefing, validation, diagnostics)
  • Docs – This book (mdBook, Rust-based; no TypeScript/Node)

New here? Quick start: install CLI, scan current structure, retrieve context, and verify changes. Add reviewed intent only when you want repo.sruja in Git. Optional learning lives separately under Navigate; press / or S to search.

Sruja "Show diagram" in code blocks: Run just wasm (or make wasm) from the repo root once, then run just book-serve (or make book-serve, or ./serve.sh from the book directory) so the WASM files are copied into the book output.

Navigate

New here? Do Quick start first, then Getting started. Start with the core loop before exploring extensions.

Use one entry point below. The sidebar lists the full structure, but the recommended path is intentionally narrow.

WhereLinkWhat you get
Core documentationDocs →Capture, retrieve, verify; MCP; reviewed intent when needed
Extensions and advanced usageUsing Sruja in your project →Reviewed intent, CI, team rollout, exports, and wider adoption
TutorialsTutorials →Step-by-step workflows after the core path is familiar
Learning (optional)Learning →Long-form material; not required for default adoption

Quick Start

AI coding harness in about 5 minutes — structural scan, agent briefings, and verify gates. No repo.sruja required on day one.


Step 1: Install the CLI (1 minute)

curl -fsSL https://sruja.ai/install.sh | bash
sruja start -r .
sruja drift -r . --structural-only --advisory

You get file-level findings (cycles, layer violations, hub modules) and a could not infer section where the scan is uncertain.


Step 2: Wire your editor (MCP + harness skill)

MCP (Cursor template in the repo): register sruja mcp with profile coding and SRUJA_MCP_READONLY=1. See Host agent integration.

Skills:

npx skills add https://github.com/sruja-ai/sruja --skill sruja-harness

Optional — reviewed architecture in Git:

npx skills add https://github.com/sruja-ai/sruja --skill sruja-architecture

Host loop:

focus / drift  →  your agent edits code  →  verify-task  →  (optional) agent record on failure

Step 3: Run gates locally

# Before a task (paste briefing into the agent)
sruja focus -r . --file path/to/file.rs

# After the agent edits
sruja verify-task --profile coding -r .

In VS Code/Cursor: Sruja: Brief this file, Sruja: Verify task, Sruja: Register MCP Server.


Step 4 (optional) — Reviewed repo.sruja

When you want versioned architecture intent in CI, ask your agent:

Use sruja-architecture. Gather evidence, generate or update repo.sruja,
then sruja lint repo.sruja and sruja drift -r . -a repo.sruja.

Diagrams are exports, not the product center:

sruja export mermaid repo.sruja > architecture.mmd

Quick Reference

What you wantCommand
First scansruja start -r . then sruja drift -r . --structural-only --advisory
Harness skillnpx skills add … --skill sruja-harness
Brief agentsruja focus -r . --file <path>
After AI editsruja verify-task --profile coding -r .
Architecture skillnpx skills add … --skill sruja-architecture
Lint reviewed truthsruja lint repo.sruja

Common Questions

"What if sruja isn't found?"

export PATH="$HOME/.local/bin:$PATH"
# or: just build (or make build) && use target/release/sruja

"Do I need MCP?"

No for CLI-only workflows. MCP is the best experience inside Cursor/Claude Desktop.

"Is Sruja a coding agent?"

No. Cursor/Copilot own the LLM loop. Sruja is the harness (drift, focus, verify-task).

"What's the difference between quickstart and discover?"

  • quickstart / start — human-friendly onboarding
  • discover — detailed JSON for AI generation (architecture skill)

VS Code extension

Install Sruja Language Support for .sruja syntax, validation, harness commands, and MCP registration.


Learn more

VS Code extension

The Sruja VS Code extension provides:

  • Syntax highlighting for .sruja files
  • Diagnostics (errors, warnings) via the language server
  • WASM-based diagram preview – render diagrams from your DSL in the editor (no web server)

Install from the VS Code Marketplace or build from source in extension/.

Introduction

Context engineering for knowledge and decisions.

Sruja helps teams capture important engineering knowledge, retrieve the right task context for developers and AI agents, and verify that changes still align with those decisions. Optional repo.sruja is reviewed intent in Git, not the day-one requirement.

New here? Start with Quick start to learn the core loop: capture, retrieve, verify. Add repo.sruja only when you want reviewed intent in Git.

The Problem

How does your AI know the real architecture today?

Your approachProblems
Raw model contextEasy to miss boundaries, invent dependencies, or forget prior decisions
Drawings in Miro/LucidChartManual updates, easy to forget, drifts from code
Wiki pagesInconsistent, hard to maintain, no validation

Sound familiar? You're not alone. Most teams struggle with this.

The Solution

A small context loop with optional reviewed intent.

With Sruja:

  • Capture knowledge and decisions with docs, decision records, and optional reviewed intent
  • Retrieve grounded context with focus, ai, and MCP before the host agent edits
  • Verify the result with drift, intent, and verify-task
  • Add reviewed intent in Git (repo.sruja) only when the team wants stricter governance

Sruja is not a replacement for Cursor or Copilot — it is the guardrail layer beside them.

How This Helps

Before SrujaWith Sruja
AI guesses from partial contextAI works from repo evidence and linked decisions
Knowledge lives in stale docs or chat historyImportant context is captured and retrievable
Hard to catch generated mistakesDrift, intent, and verification gates catch regressions
Hard to brief agents consistentlyTask-scoped context is reusable
Diagrams become the truthDiagrams are optional outputs, not the product center

Start Here


What Sruja Optimizes For

  • Evidence over guesses: context starts from what exists in code and linked docs today
  • Small surface area: a few core workflows used consistently
  • Explicit trade-offs: reviewed intent is optional until the team needs it
  • Host-owned LLM loop: Sruja never replaces your editor or agent
  • Knowledge and decisions: context engineering, not a feature catalog

Who is Sruja For?

Software Architects

  • Review changes against evidence and intent
  • Prevent drift through automated gates
  • Document decisions with ADRs (Architecture Decision Records)
  • Keep reviewed truth in Git when needed

Developers Using AI

  • Brief agents before edits with the right task context
  • Reduce risky guesses from incomplete repo understanding
  • Verify generated changes before calling work done
  • Keep prior decisions visible at change time

Teams Maintaining Shared Knowledge

  • Capture docs and decisions in a durable, reviewable way
  • Integrate into CI/CD so alignment is checked continuously
  • Preserve reasoning so future maintainers and agents do not start cold
  • Export artifacts only when communication requires them

Next Steps

Getting Started

Sruja’s core value is capturing knowledge, retrieving task context, and verifying changes against decisions:

  • Capture: bring important docs and decisions into the repo
  • Retrieve: brief the next change with focus, ai, or MCP
  • Verify: run deterministic checks after editing

You can get value on day one without writing any .sruja files.


The core loop

  • Capture: ingest docs and record decisions you want future humans and AI to reuse
  • Retrieve: generate task-scoped context before touching code
  • Verify: confirm the result still matches structure and intent

Core workflow in 5 minutes

Step 1: Install the CLI

curl -fsSL https://sruja.ai/install.sh | bash

If you’re working from source in this repo:

just build  # or: make build
./target/release/sruja --help

Step 2: Get a first structural read

From your repo root:

sruja start -r .
sruja drift -r . --structural-only --advisory

This reports repo-level structural issues that AI edits tend to introduce, plus an “uncertain” section where inference is weaker.

Step 3: Retrieve task context before editing

Run a file-scoped briefing before a risky edit:

sruja focus -r . --file path/to/file.rs

For a paste-ready brief:

sruja ai -r . --task "Refactor auth boundary"

Step 4: Verify after editing

After the agent edits:

sruja verify-task --profile coding -r .

Step 5 (optional): Wire MCP for tool-based briefings

If your editor supports MCP, run Sruja as an MCP stdio server:

sruja mcp -r .

For host/editor setup details, see Host agent integration.


Optional: reviewed intent in Git

Add repo.sruja only when you want reviewed intent in Git and stricter CI enforcement. Keep it minimal at first.

Step 1: Generate and validate intent

Prerequisites:

  • AI editor – Cursor, Copilot, Claude, Continue.dev, etc.
  • AI skillnpx skills add https://github.com/sruja-ai/sruja --skill sruja-architecture (see Install as a Skill)

The skill uses repo evidence to propose repo.sruja. When you have a draft:

sruja lint repo.sruja

Step 2: Refresh evidence and check drift

sruja sync -r .
sruja drift -r . -a repo.sruja

One-time baseline:

sruja baseline -r . -o .sruja/violations.baseline.json

CI check that fails only on new problems:

sruja drift --ci -r . --baseline .sruja/violations.baseline.json -f github-actions

About reviewed intent

You can use Sruja for capture, retrieve, and verify without ever committing an architecture file.

If you do want reviewed intent in Git, today that intent is stored as an architecture file (repo.sruja). The exact authoring format is not the product center and may evolve; the stable value is the workflow around it:

  • evidence from code → task-scoped context → deterministic gates → drift checks in CI

Quick reference

GoalCommand
Structural scansruja start -r .
Structural driftsruja drift -r . --structural-only --advisory
Brief an agent before editssruja focus -r . --file <path>
Generate a paste-ready task briefsruja ai -r . --task "..."
Post-edit verificationsruja verify-task --profile coding -r .
Refresh evidencesruja sync -r .
Lint reviewed intentsruja lint repo.sruja
Drift vs reviewed intentsruja drift -r . -a repo.sruja
Start MCP serversruja mcp -r .

CLI Guide

The sruja command-line interface is your primary tool for interacting with Sruja. Start with the core loop first, then use the rest as supporting or advanced workflows.

Repository path

Most repo-scoped commands take -r with --repo as the long form (recommended). --path is accepted as an alias on many commands for older scripts. Positional paths (e.g. sruja scan .) remain valid where documented.

Commands

Start Here

If you are new, start with these commands:

sruja start -r .
sruja drift -r . --structural-only --advisory
sruja focus -r . --file path/to/file.rs
sruja verify-task --profile coding -r .

Use sruja ai -r . --task "..." or sruja mcp -r . when you want richer task context retrieval.

export

Exports the architecture to various formats.

Usage:

sruja export <format> <file>

Supported formats:

  • json: Structured JSON of the architecture.
  • mermaid: Mermaid diagram code.
  • markdown: Markdown docs with diagrams.
  • context: Architecture context for AI tools (Cursor, Copilot).
  • dsl: Pretty-printed DSL (canonical form).

Options:

  • --extended: Include pre-computed views in JSON output.
  • --view-level <1|2|3>: C4 view level for mermaid (1=context, 2=container, 3=component).
  • --target <id>: Focus node ID for view levels 2/3.

Examples:

sruja export json architecture.sruja
sruja export json architecture.sruja --extended
sruja export mermaid architecture.sruja
sruja export markdown architecture.sruja
sruja export mermaid architecture.sruja --view-level 2 --target Shop.WebApp

tree

Displays the architecture structure as a tree in the terminal.

Usage:

sruja tree <file>

Example:

sruja tree architecture.sruja

fmt

Formats the Sruja file to a canonical style.

Usage:

sruja fmt [file]

lint

Validates the Sruja file against rules and best practices.

Usage:

sruja lint [file]
# Machine-readable output for CI/agents:
sruja lint [file] --format json

For the JSON schema and diagnostic codes, see LINT_JSON_OUTPUT.md in the repo (or online).

Discovery (for skills and agents)

sruja discover --context -r .          # Human-readable repo context
sruja discover --context -r . --format json   # Machine-readable (components, areas, framework)
sruja discover                          # Question bank only

Optional reviewed-intent and advanced commands

These commands are useful when you want reviewed intent in Git, richer automation, or advanced team workflows.

CommandPurpose
sruja sync -r <path>Refresh evidence files
sruja drift -r <path> -a repo.srujaCompare reviewed intent to actual code
sruja ai-context -r <path>Export structured context for host tools
sruja why "question" -r <path>Investigate architecture questions with deterministic evidence
sruja drift --ci -r <path> -f github-actionsCI-focused drift check output
sruja baseline -r <path>Snapshot current violations to ignore them in CI
sruja compliance -r <path> -a repo.sruja -i <intent_dir>Structural drift + intent + policy violations
sruja publish -r <path> -o repo.bundle.jsonExport repo truth + evidence for federation
sruja compose -i <bundle.json> -o system.index.jsonCompose repo bundles into a system index
sruja mcpStart MCP stdio server
sruja scan <path> --output graph.jsonRaw graph JSON for scripting and advanced use

Examples (skill workflow / CI):

sruja discover --context -r . --format json
sruja drift -r . -a repo.sruja
sruja impact Shop.WebApp -r .
sruja why "why did we choose PostgreSQL?" -r .
sruja ai-context -r . -f markdown -o .cursor/rules/architecture.md

Older or supporting workflow aliases

These still exist, but they are not the main path to teach first.

# First-time setup
sruja start -r . --prompt

# First look (no files required)
sruja overview -r .

# Day-to-day review
sruja daily -r .

# Quick repo health check
sruja doctor -r .

# Keep feedback live while coding
sruja watch -r .

Aliases:

  • start = init
  • daily = review
  • overview = quickstart
  • doctor = status

CI workflow

# Snapshot current violations (one-time)
sruja baseline -r . -o .sruja/violations.baseline.json

# CI check that ignores existing issues and reports only new ones
sruja drift --ci -r . --baseline .sruja/violations.baseline.json -f github-actions

MCP (optional)

If your editor/tooling supports MCP, Sruja can run as an MCP stdio server:

sruja mcp

How Sruja Works

Sruja is built for context engineering during software changes. The center is simple: gather repo evidence, retrieve the right context before editing, and verify the result after editing. Reviewed intent in Git is optional.

The Sruja Platform

The platform consists of several key components working together:

  1. Scan and evidence: Rust crates gather structure and context from code.
  2. CLI: Local and CI workflows for retrieve and verify steps.
  3. WASM: Shared core for the docs book and VS Code.
  4. VS Code extension: Editor support for validation and previews.
  5. Docs: This site, built from the book/ directory.

How the pieces work together

Sruja’s core loop is evidence → context → edit → verify:

  1. The CLI scans real code into an evidence model.
  2. focus, ai, or MCP turns that evidence into task-scoped context.
  3. The host agent or developer edits code with that context in mind.
  4. verify-task, drift, and intent checks keep regressions from silently accumulating.

When teams want stricter governance, repo.sruja becomes reviewed intent in Git and drift -a repo.sruja becomes part of the CI gate.

Context graph and AI context

Sruja is primarily a context engineering system. The core artifact is a repo-derived context graph, not a hand-authored diagram.

Typical outputs:

  • .sruja/graph.json: full dependency graph (evidence)
  • .sruja/context.json: smaller, cache-friendly summary for agents
  • sruja ai-context -r .: structured AI context export for host tools

MCP tools expose the same evidence and briefings in a tool-friendly form so the host agent can fetch exactly what it needs without dumping the whole repo into a prompt.

Architecture files (repo.sruja) are optional; they exist only if you want reviewed intent in Git and stricter drift enforcement in CI.

Key Components

Core Engine (Rust)

The sruja-language and sruja-engine crates form the foundation. They define the DSL grammar, parse input files into an AST (Abstract Syntax Tree), and run validation rules (like cycle detection and layer enforcement).

WebAssembly (WASM)

The Rust core is compiled to WebAssembly (sruja-wasm). The same parsing and validation logic runs in:

  • VS Code Extension: For local preview without needing a CLI binary.
  • Documentation site: For "Show diagram" in code blocks (like the one above).

CLI & CI/CD

The sruja CLI wraps the core engine. The most important public workflows are:

  • Retrieve: focus, ai, mcp
  • Verify: drift, intent check, verify-task
  • Optional reviewed intent: lint, sync, drift -a repo.sruja

Context Engineering

Sruja provides context engineering across four progressive layers:

┌─────────────────────────────────────────────────────────────┐
│  Layer 4: Intent                                            │
│  "What did we intend vs what exists?"                       │
│  Commands: sruja drift -a, sruja intent check               │
├─────────────────────────────────────────────────────────────┤
│  Layer 3: Semantic                                          │
│  "What does this mean? (vocabulary, patterns)"              │
│  Commands: sruja analyze --semantic                         │
├─────────────────────────────────────────────────────────────┤
│  Layer 2: Structural                                        │
│  "What exists? (components, deps, metrics)"                 │
│  Commands: sruja scan, sruja quickstart, sruja discover    │
├─────────────────────────────────────────────────────────────┤
│  Layer 1: Syntactic                                         │
│  "Is the DSL valid?"                                        │
│  Commands: sruja lint                                       │
└─────────────────────────────────────────────────────────────┘

Each layer builds on the previous:

  • Syntactic: Is the .sruja file valid? (lint)
  • Structural: What components and dependencies exist? (scan, discover)
  • Semantic: What patterns and relationships mean? (analyze)
  • Intent: Does reality match declared architecture? (drift, intent check)

Optional Reviewed-Intent Layer

The sruja-architecture skill is an optional accelerator for teams that want reviewed intent in Git:

LayerCore pathOptional reviewed-intent path
Syntacticno file requiredsruja lint
Structuralsruja start, sruja driftevidence-backed modeling
Semanticfocus, ai, MCP retrievalricher architecture interpretation
Intentverify-task, intent checksruja drift -a repo.sruja

Install the skill only when you want that reviewed-intent workflow:

npx skills add https://github.com/sruja-ai/sruja --skill sruja-architecture

Core And Extensions In Your Project

This guide is for teams that want to adopt Sruja without letting advanced features take over the product story. Start with the core loop, then add extensions only when they clearly help.

Start with the core

These are the defaults to adopt first:

  • Capture – ingest docs and record decisions you want future humans and AI to reuse.
  • Retrievefocus, ai, and MCP before editing.
  • Verifydrift, intent check, and verify-task after editing.
  • Optional reviewed intentrepo.sruja only when you want durable, reviewable intent in Git.

Then add extensions deliberately

Only add these after the core loop is working:

  • Reviewed intent workflows – richer repo.sruja authoring and stricter CI gates
  • Visualization – Markdown, Mermaid, and other exports
  • Team review flows – critique, PR drift checks, policy-oriented enforcement
  • Federation and multi-repo – cross-repo packaging and retrieval
  • Advanced agent ops – plans, learnings, and memory workflows

What you get from the core path

  • Small default workflow – easier to explain and adopt
  • Repo-grounded context – no need to start with modeling everything
  • Deterministic verification – changes get checked after editing
  • Safer expansion – extensions stay available without cluttering onboarding
  • MCP integration – tool-based editor and agent workflows when needed

1. Install (your machine and/or CI)

CLI

Option A – install script (downloads from GitHub Releases):

curl -fsSL https://sruja.ai/install.sh | bash

Option B – from Git (requires Rust):

cargo install sruja-cli --git https://github.com/sruja-ai/sruja

Option C – build from source:

git clone https://github.com/sruja-ai/sruja.git && cd sruja && just build  # or: make build

Ensure the install directory is on your PATH (install script uses ~/.local/bin by default; Option B uses ~/.cargo/bin; Option C uses target/release).

Check:

sruja --help
sruja lint --help

VS Code extension

Install Sruja Language Support from the VS Code Marketplace (or Open VSX). You get syntax highlighting, LSP diagnostics, and optional diagram preview for .sruja files.


2. Add Sruja to your repo (5 minutes)

Step 1: Start with the core loop

# From your repo root
sruja start -r .
sruja drift -r . --structural-only --advisory

This gives you immediate value without committing any new architecture files.

Step 2: Retrieve context before editing

If you use an AI editor/agent, use Sruja as the guardrail:

sruja focus -r . --file path/to/file.rs
sruja ai -r . --task "Refactor auth boundary"
sruja verify-task --profile coding -r .

To enable tool-based integration, start MCP:

sruja mcp -r .

See Host agent integration for editor setup.

Step 3 (optional): Add reviewed intent in Git

When the team is ready to review architecture intent like code, generate repo.sruja using the architecture skill:

npx skills add https://github.com/sruja-ai/sruja --skill sruja-architecture

Then validate and compare intent to reality:

sruja lint repo.sruja
sruja sync -r .
sruja drift -r . -a repo.sruja

Optional: generate prompt/helper files for Cursor/Copilot once and commit:

sruja start -r . --prompt

See AI editor integration for details.

Step 4: Validate in CI

In CI, keep it simple: lint reviewed intent and check drift. For incremental adoption, use a baseline so existing issues don’t block you.

GitHub Actions example:

name: Validate Sruja

on:
  push:
    branches: [main, develop]
  pull_request:
    branches: [main, develop]
  paths:
    - '**/*.sruja'

jobs:
  sruja:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4

      - name: Install Sruja CLI
        run: curl -fsSL https://sruja.ai/install.sh | bash

      - name: Lint baseline
        run: sruja lint repo.sruja

      - name: Drift check (declared vs actual)
        run: sruja drift -r . -a repo.sruja

If you prefer PR annotations, use the sruja-check action (see the main README).

Optional – export docs in CI:

      - name: Export architecture to Markdown
        run: |
          for f in $(find . -name '*.sruja' -not -path './target/*'); do
            out="${f%.sruja}.md"
            sruja export markdown "$f" > "$out" || true
          done
      - name: Upload architecture docs
        uses: actions/upload-artifact@v4
        with:
          name: architecture-docs
          path: '**/*.sruja.md'

3. Where extensions fit

Once the core path works, add extensions based on a real need:

NeedAdd
Reviewable intent in Gitrepo.sruja, lint, sync, drift -a repo.sruja
Better documentation outputsexport commands
Stricter review flowsCI drift checks, critique, policy-oriented docs
Cross-repo understandingfederation docs and tooling
Advanced agent workflowsplans, learnings, memory, and other advanced surfaces

4. How this enhances your code

PracticeHow Sruja helps
PR reviewsCI fails if .sruja is invalid; reviewers see architecture changes in the diff.
OnboardingNew devs read .sruja and exported docs instead of hunting for "the" diagram.
AI-generated codeThe skill and editor integrations steer AI to valid DSL; sruja lint catches mistakes.
Compliance / governancePolicies and constraints in the DSL; lint enforces structure; export for auditors.
Multi-repoEach repo can have its own architecture.sruja (or one per service); same CLI and CI pattern.

5. Using Sruja across multiple repos

  • Per-repo – Each repository that owns a service or app can have its own .sruja file(s). Add the same CI job and the same AI setup (e.g. copy .cursorrules and .copilot-instructions.md from a template, install the skill, or run sruja start -r . --prompt once and commit).
  • Central docs repo – Some teams keep a single "docs" or "architecture" repo with one or more .sruja files and run Sruja CI there; link to exported Markdown/JSON from other repos. Other repos don't need the CLI unless they also own architecture files.
  • Shared rules – Use the same sruja-architecture skill (npx skills add sruja-ai/sruja --skill sruja-architecture) across repos so AI and humans share the same patterns and trade-offs.

6. Where to go next

Sruja is open source. To report issues or suggest improvements, use GitHub Issues or Discussions.

VS Code Extension

The Sruja VS Code extension provides language support for .sruja files with bundled WebAssembly for validation, formatting, export, and preview flows. CLI-backed commands such as refresh context, status, review, drift, and MCP registration work when the Sruja CLI is installed and available on PATH or configured via sruja.lsp.path.

Installation

From VS Code Marketplace

Install directly (opens the extension page), or:

  1. Open VS Code
  2. Go to Extensions (Cmd+Shift+X or Ctrl+Shift+X)
  3. Search for "Sruja"
  4. Click Install on "Sruja"

From VSIX File

  1. Download the .vsix file from GitHub Releases
  2. In VS Code, go to Extensions
  3. Click the ... menu → "Install from VSIX..."
  4. Select the downloaded .vsix file

Features

The extension provides a complete LSP implementation with the following features:

✨ Core Editing Features

1. Diagnostics (Errors & Warnings)

  • Real-time error detection as you type
  • Syntax errors highlighted immediately
  • Validation errors (duplicate IDs, invalid references, etc.)
  • Hover over errors to see detailed messages

2. Hover Information

  • Hover over any symbol to see its definition
  • Shows system/container/component information
  • Displays labels and descriptions

Usage: Hover your mouse over any identifier

3. Autocomplete (IntelliSense)

  • Keyword suggestions (architecture, system, container, etc.)
  • Symbol completion (suggests existing systems, containers, components)
  • Context-aware suggestions

Usage: Type Ctrl+Space (or Cmd+Space on Mac) to trigger autocomplete

4. Go to Definition

  • Navigate to symbol definitions with F12 or Cmd+Click
  • Works with qualified names (e.g., App.API)
  • Supports both root and child paths in FQNs

Usage:

  • F12 - Go to definition
  • Cmd+Click (Mac) or Ctrl+Click (Windows/Linux) - Go to definition
  • Cmd+F12 - Go to implementation

5. Find All References

  • Find all places where a symbol is used
  • Shows references in relations and qualified names
  • Opens in the References panel

Usage:

  • Shift+F12 - Find all references
  • Right-click → "Find All References"

6. Rename Symbol

  • Rename a symbol and all its references
  • Updates both definitions and usages
  • Handles qualified names correctly

Usage:

  • F2 - Rename symbol
  • Right-click → "Rename Symbol"

7. Document Symbols (Outline)

  • View all symbols in the current file
  • Navigate quickly through your architecture
  • Shows hierarchy: systems → containers → components

Usage:

  • Cmd+Shift+O (Mac) or Ctrl+Shift+O (Windows/Linux) - Go to symbol in file
  • View → Outline

8. Workspace Symbols

  • Search for symbols across all open files
  • Quick navigation to any symbol in your workspace

Usage:

  • Cmd+T (Mac) or Ctrl+T (Windows/Linux) - Go to symbol in workspace

9. Code Formatting

  • Format your Sruja DSL code
  • Consistent indentation and spacing

Usage:

  • Shift+Alt+F (Windows/Linux) or Shift+Option+F (Mac) - Format document
  • Right-click → "Format Document"

🎨 Additional Features

Syntax Highlighting

  • Color-coded keywords, strings, and identifiers
  • Makes code easier to read and understand

Architecture Previews

  • Open Diagram Preview renders the active .sruja file as Mermaid in a side panel
  • Open Focused Diagram Preview renders a sliced view around the selected element
  • Open Markdown Preview opens the extension's custom markdown preview

Usage:

  • Command palette: Cmd+Shift+P / Ctrl+Shift+P
  • Run one of:
    • Sruja: Open Diagram Preview
    • Sruja: Open Focused Diagram Preview
    • Sruja: Open Markdown Preview

Register MCP Server (Cursor)

  • Registers the Sruja MCP server with Cursor so Cursor can call Sruja tools (repomap, context, drift)
  • Requires the Sruja CLI (configure sruja.lsp.path if needed)

Usage:

  • Command palette: Cmd+Shift+P → "Sruja: Register MCP Server (Cursor)"

Keyboard Shortcuts

FeatureMacWindows/Linux
Go to DefinitionF12 or Cmd+ClickF12 or Ctrl+Click
Find All ReferencesShift+F12Shift+F12
Rename SymbolF2F2
Go to Symbol in FileCmd+Shift+OCtrl+Shift+O
Go to Symbol in WorkspaceCmd+TCtrl+T
Format DocumentShift+Option+FShift+Alt+F
Trigger AutocompleteCmd+SpaceCtrl+Space

Configuration

The extension supports the following settings:

Available Settings

  • sruja.lsp.path - Optional absolute path to the Sruja CLI binary. This is used for CLI-backed workspace commands such as refresh context, status, review, drift, and MCP registration.
  • sruja.skills.path - Optional path to a skills folder for AI rules. If unset, the extension uses the workspace skills folder or bundled skills when available.

To configure:

  1. Open Settings (Cmd+, or Ctrl+,)
  2. Search for "Sruja"
  3. Adjust the formatting options as needed

Debugging

If you encounter issues with the extension:

Check Output Channel

  1. Open Output panel: View → Output
  2. Select Sruja from the dropdown
  3. Check for command output and error messages

Common Issues

Extension not working?

  • Check the Sruja output channel for errors
  • Ensure WASM files are present (should be installed automatically)
  • Try reloading the window: Cmd+Shift+P → "Developer: Reload Window"

LSP features not responding?

  • Check if the file has a .sruja extension
  • Verify the language mode is set to "Sruja" (bottom-right of VS Code)
  • Run Sruja: Run validation on the active file and check the Problems panel

Rename not working?

  • Make sure you're clicking on a valid symbol (not a keyword)
  • Check the output channel for error messages
  • Confirm the file is valid first with Sruja: Run validation

Architecture

The extension uses WebAssembly (WASM) for core language features, which means:

  • No CLI dependency for core language features - Diagnostics, hover, completion, formatting, preview, and markdown export work without installing the Sruja CLI
  • Fast - WASM provides near-native performance
  • Portable - Same code runs in browser and VS Code
  • Self-contained - All functionality bundled in the extension

The extension also bridges into the CLI for workspace-level context engineering: refresh repo context, review, drift, status, and MCP registration.

What's Next?

Contributing

Found a bug or have a feature request?

Examples & Patterns

Theory is good, but code is better. Below are production-grade Sruja models that you can copy, paste, and adapt.

Every example here follows our quality standards:

  1. Clear Requirements: Functional & Non-functional.
  2. Proper Hierarchies: Context -> Container -> Component.
  3. Real Tech Stacks: No generic "Database" boxes.

1. Banking System (Fintech)

Note

Ideally Suited For: Highly regulated industries requiring audit trails, security policies, and strict latency SLAs.

Scenario: A regional bank needs to modernize its legacy mainframe interactions while providing a slick mobile experience.

Why review this example?

  • Security: Uses policy blocks for PCI-DSS.
  • Hybrid Cloud: Connects modern Cloud Containers to an on-premise "Mainframe" System.
  • Complexity: Models the "Legacy Core" vs "Modern Interface" pattern often seen in enterprise.
// partial
import { * } from 'sruja.ai/stdlib'


// --- REQUIREMENTS ---
// We start with the 'Why'. These drive the architecture.
R1 = requirement functional "Customers must be able to view balances"
R2 = requirement functional "Customers can transfer money internally"
R3 = requirement security "All PII must be encrypted at rest (PCI-DSS)"
R4 = requirement stability "99.99% Availability (Target: <52m downtime/year)"

// --- ACTORS ---
Customer = person "Banking Customer" {
    description "A holder of one or more accounts"
}

// --- SYSTEMS ---
BankingSystem = system "Internet Banking Platform" {
    description "Allows customers to view information and make payments."

    // Containers (Deployable units)
    WebApp = container "Single Page App" {
        technology "React / TypeScript"
    }

    MobileApp = container "Mobile App" {
        technology "Flutter"
    }

    API = container "Main API Gateway" {
        technology "Java / Spring Boot"
        description "Orchestrates calls to core services"
    }

    Database = container "Main RDBMS" {
        technology "PostgreSQL"
        tags ["database", "storage"]
    }

    // Relationships
    WebApp -> API "Uses (JSON/HTTPS)"
    MobileApp -> API "Uses (JSON/HTTPS)"
    API -> Database "Reads/Writes (JDBC)"
}

// --- EXTERNAL SYSTEMS ---
Mainframe = system "Legacy Core Banking" {
    tags ["external"] // This is outside our scope of control
    description "The heavy iron that stores the actual money."
}

EmailSystem = system "Email Service" {
    tags ["external"]
    description "SendGrid / AWS SES"
}

// --- INTEGRATIONS ---
Customer -> BankingSystem.WebApp "Views dashboard"
BankingSystem.API -> Mainframe "Syncs transactions (XML/SOAP)"
BankingSystem.API -> EmailSystem "Sends alerts"

view index {
include *
}

👉 Deep Dive this Architecture using our Course


2. Global E-Commerce Platform

Note

Ideally Suited For: High-scale B2C applications. Focuses on caching, asynchronous processing, and eventual consistency.

Scenario: An Amazon-like store preparing for Black Friday traffic spikes.

Why review this example?

  • Scalability: Explains how to handle high reads (Product Catalog) vs transactional writes (Checkout).
  • Async Messaging: Shows usages of Queues/Topics (Apache Kafka) to decouple services.
  • Caching: Strategic placement of Redis caches.
// partial
import { * } from 'sruja.ai/stdlib'


R1 = requirement scale "Handle 100k concurrent users"
R2 = requirement performance "Product pages load in <100ms"

ShopScale = system "E-Commerce Platform" {

    // --- EDGE LAYER ---
    CDN = container "Content Delivery Network" {
        technology "Cloudflare"
        description "Caches static assets and product images"
    }

    LoadBalancer = container "Load Balancer" {
        technology "NGINX"
    }

    // --- SERVICE LAYER ---
    Storefront = container "Storefront Service" {
        technology "Node.js"
        description "SSR for SEO-friendly product pages"
    }

    Checkout = container "Checkout Service" {
        technology "Rust"
        description "Handles payments and inventory locking"
    }

    // --- DATA LAYER ---
    ProductCache = container "Product Cache" {
        technology "Redis Cluster"
        description "Stores hot product data"
    }

    MainDB = database "Product Database" {
        technology "MongoDB"
        description "Flexible schema for diverse product attributes"
    }

    OrderQueue = queue "Order Events" {
        technology "Kafka"
        description "Async order processing pipeline"
    }

    // --- FLOWS ---
    CDN -> LoadBalancer "Forwards dynamic requests"
    LoadBalancer -> Storefront "Routes traffic"
    Storefront -> ProductCache "Read-through cache"
    Storefront -> MainDB "Cache miss / heavy query"

    // The Checkout Flow
    Checkout -> OrderQueue "Publishes 'OrderCreated'"
}

view index {
include *
}

What Next?

Advanced Modeling Path

Optional path for teams that want reviewed intent in Git.

If you just did Quick start, you already have the core workflow. This page is for the next step: using Sruja to maintain reviewed intent with repo.sruja and the sruja-architecture skill.

Tip

Use this later: This is not required for default adoption. Come here only when you want explicit, reviewable architecture modeling.


Step 1: Generate Reviewed Intent ⏱️ 20–30 min

What you'll do: Let AI analyze your code and create repo.sruja

Instructions:

  1. Open your project in your AI editor
  2. Run this prompt:
Use sruja-architecture. Run `sruja discover --context -r . --format json`,
gather evidence, identify systems and containers,
generate repo.sruja with C4 context and container levels,
then run `sruja lint` and fix until it passes.
  1. Wait for AI to ask 2-3 questions
  2. Answer the questions (be specific: "Production database is PostgreSQL")
  3. Review the generated repo.sruja file

Success check: You have a repo.sruja file that passes sruja lint

What you learned:

  • How AI analyzes your codebase
  • What questions it asks
  • What a valid repo.sruja looks like

Step 2: Understand What Was Generated ⏱️ 15–20 min

What you'll do: Read and understand your AI-generated architecture

Instructions:

  1. Open repo.sruja in your editor
  2. Read it section by section:
    • person entries = external actors
    • system entries = your major boundaries
    • container entries = deployable units
    • -> lines = relationships
  3. Run sruja tree repo.sruja to see structure visually
  4. Ask AI to explain:
Read repo.sruja and explain:
1. What systems are defined?
2. How do containers connect?
3. What external actors use this system?

Success check: You can explain your architecture in plain English

What you learned:

  • How reviewed intent is expressed
  • How to read relationships
  • What each component does

Step 3: Validate and Fix Errors ⏱️ 15–20 min

What you'll do: Learn to validate and fix issues with AI help

Instructions:

  1. Run sruja lint repo.sruja
  2. If you see errors, copy them to clipboard
  3. Ask AI:
I got these lint errors. Fix them in repo.sruja:
[paste errors here]

Common errors:

ErrorWhat It MeansHow to Fix
E204: Circular dependencyA → B → ARemove one edge in the cycle
E205: Orphan elementSomething with no connectionsAdd relationships or remove it
E201: Invalid kindUnknown typeUse person, system, container, database
  1. Re-run sruja lint until clean

Success check: sruja lint repo.sruja shows "All checks passed"

What you learned:

  • How validation works
  • Common architecture errors
  • How to ask AI to fix issues

Step 4: Make a Specific Change ⏱️ 20–30 min

What you'll do: Direct AI to add or modify something specific

Instructions:

Think of a change you want. Examples:

  • Add component: "Add a logging service container"
  • Add relationship: "Connect the new logger to all existing containers"
  • Modify description: "Update the API container description to say it handles webhooks"

Then ask AI:

Use sruja-architecture. Read repo.sruja and:
[your change here]
Then run sruja lint and fix any errors.

Success check: Your change is added and sruja lint passes

What you learned:

  • How to make targeted updates
  • To validate after each change
  • That iteration is normal (AI can refine it)

Step 5: Export for Your Team ⏱️ 10–15 min

What you'll do: Share reviewed intent with stakeholders when needed

Instructions:

  1. Export Markdown:
sruja export markdown repo.sruja > ARCHITECTURE.md
  1. Export diagram:
sruja export mermaid repo.sruja > ARCHITECTURE.mmd
  1. Open ARCHITECTURE.md and review
  2. Open ARCHITECTURE.mmd in Mermaid Live Editor

Success check: You can send ARCHITECTURE.md to your team and they understand it

What you learned:

  • Different export formats
  • How to share reviewed intent
  • That diagrams are output, not the source

Step 6: Detect and Fix Drift ⏱️ 20–30 min

What you'll do: Keep architecture in sync as code changes

Instructions:

  1. Make a small change to your actual code

    • Add a new function
    • Rename a file
    • Move a module
  2. Run drift detection:

sruja drift -r . --format json
  1. Ask AI:
Use sruja-architecture. Here's drift output:
[paste JSON]
Analyze what changed and update repo.sruja to match current code.
  1. Review the changes AI made
  2. Run sruja lint repo.sruja

Success check: sruja drift shows no issues (or you've addressed them)

What you learned:

  • How to detect changes over time
  • To let AI update architecture automatically
  • That architecture stays in sync with code

Step 7: Explore Patterns with AI ⏱️ 15–20 min

What you'll do: Use AI as an architecture advisor

Instructions:

Pick a pattern and ask AI to explain it:

Monolith:

Use sruja-architecture. Explain the monolith pattern:
When to use it, pros/cons, and show an example in Sruja syntax.

Microservices:

Use sruja-architecture. Explain microservices:
When to split, trade-offs, and generate an example architecture.

Event-driven:

Use sruja-architecture. Show me an event-driven architecture
with Kafka, producers, and consumers. Explain trade-offs.

Success check: You understand different patterns and when to use them

What you learned:

  • Architectural patterns
  • When each pattern makes sense
  • That AI can be your advisor, not just generator

Tips for Success

PracticeWhy It Helps
Be specific"Add logging to API container" works better than "Improve architecture"
Validate oftenRun sruja lint after each AI edit—catch mistakes early
Ask questions"Why did you model it this way?" helps you learn
Start simpleGet context + container levels right, add detail later
Trust evidenceIf sruja discover doesn't find something, tell your AI—don't let it guess
IterateFirst attempt won't be perfect—refine with feedback

Before You Spend Time Here

Make sure the core path is already useful for your team:

  • sruja start -r .
  • sruja drift -r . --structural-only --advisory
  • sruja focus -r . --file <path>
  • sruja verify-task --profile coding -r .

If that loop is not already helping, do not invest in advanced modeling yet.

Common Mistakes to Avoid

Don't: "Generate full architecture for everything"

Do: Start with context + container levels, add components when needed

Don't: Guess at missing information

Do: Ask targeted questions, list what's unknown

Don't: Skip validation

Do: Always run sruja lint after AI edits

Don't: Model for completeness

Do: Model what evidence supports—minimal is better


What's Next?

Go deeper:

Practice:

  • Try different codebases (your own or open-source examples)
  • Practice making specific changes
  • Compare different patterns with AI

Connect:


Quick Reference

Want toHow
Generate architecturePrompt AI from Step 1
Validatesruja lint repo.sruja
Export docssruja export markdown repo.sruja > doc.md
Export diagramsruja export mermaid repo.sruja > diagram.mmd
Check driftsruja drift -r . --format json
Fix errorsPaste lint output to AI and say "fix these"
Explain pattern"Explain [pattern] with pros/cons and example"

Remember: You're not learning a language. You're learning how to:

  1. Guide AI with clear requests
  2. Validate results
  3. Iterate and refine
  4. Use AI as an advisor

The skill handles the syntax—you handle the thinking.

Frequently Asked Questions

New to Sruja? Start here.


Installation

Do I need to know programming to use Sruja?

Not really. You need:

  • Basic comfort with terminals (running commands)
  • A codebase to document (any language)
  • An AI editor (Cursor, Copilot, Claude, etc.)

You don't write the .sruja files manually—your AI does it.

What editors work with Sruja?

AI editors with skill support:

  • Cursor ✅ (built-in support)
  • GitHub Copilot ✅ (requires skills.sh)
  • Claude ✅ (requires skills.sh)
  • Continue.dev ✅ (requires skills.sh)
  • Any editor with skills.sh support

Manual use:

  • VS Code with Sruja extension (syntax highlighting, preview)
  • Terminal (run commands manually, write .sruja by hand)

What's the difference between the CLI and the skill?

CLISkill
Analyzes codeGenerates .sruja files
Validates filesKnows syntax and patterns
Exports diagramsInterprets and refines
No AI requiredRequires AI editor

You need both: CLI for validation, skill for generation.

Can I use Sruja without an AI editor?

Yes, but it's more work.

You can:

  • Run sruja discover and manually create .sruja files
  • Use the VS Code extension for syntax highlighting
  • Write .sruja by hand using the language reference

However, AI makes it 10x easier. Consider using Cursor or installing skills.sh for your current editor.


Workflow

How long does it take to generate architecture?

First time: 5-10 minutes

  • AI analyzes code
  • AI asks 2-3 questions
  • AI generates and validates

Updates: 2-5 minutes

  • AI reads existing file
  • AI makes your change
  • AI validates

With practice: Most updates are 1-2 minutes

What information does AI need from me?

Usually just 2-3 questions:

  1. System boundaries: "What are the main systems?"
  2. External actors: "Who or what calls your system?"
  3. Deployment: "How is this deployed?"

The AI gets everything else from your code.

What if I don't know the answer to a question?

That's fine! Tell your AI:

I don't know the answer to "What's the deployment model?"
Please assume [state your best guess or leave as TODO].

The AI can generate a TODO or make reasonable assumptions, which you can refine later.


Files and Syntax

What's the difference between repo.sruja and architecture.sruja?

They're the same thing, just different names.

  • repo.sruja – Recommended for new projects
  • architecture.sruja – Supported for backward compatibility

Use whichever you like—Sruja detects both.

Where should I put repo.sruja?

Repository root (same folder as package.json, pom.xml, etc.)

Example structure:

my-project/
├── src/
├── package.json
├── README.md
└── repo.sruja          ← Put it here

Can I have multiple .sruja files?

Yes. Common patterns:

  • One file per system: user-service.sruja, order-service.sruja
  • One per module: auth.sruja, api.sruja, db.sruja
  • Nested: arch/repo.sruja, arch/services.sruja

Sruja will detect any .sruja file when you run commands.

Do I need to import from stdlib?

Recommended: yes.

import { * } from 'sruja.ai/stdlib' gives you standard types:

  • person, system, container, database, queue
  • Without needing to define them manually

You can still define types manually (see Quick Start), but imports save time.


Validation

What does sruja lint check?

CheckWhat It FindsSeverity
Syntax errorsInvalid keywords, bad structureHigh
Circular dependenciesA → B → A loopsMedium
Orphan elementsComponents with no connectionsLow
Missing fieldsRequired description/technology missingMedium

Run sruja lint repo.sruja before committing changes.

What if I see errors?

Copy and paste to AI:

Fix these lint errors in repo.sruja:
[paste errors]

Common fixes:

ErrorAI Prompt
Circular"Remove one relationship in the cycle"
Orphan"Add a relationship to this component or remove it"
Missing field"Add a description field to this container"

Can I ignore lint errors?

Not recommended. Lint errors indicate real issues:

  • Your architecture might not match reality
  • Team members might misunderstand the design
  • Documentation might be incomplete

Fix errors or add a comment explaining why it's okay.


Using with AI

How specific should I be with prompts?

More specific = better results.

Too vague:

Improve my architecture.

Specific:

Add error handling to the API container.
Update the description to mention rate limiting.

What if AI generates something wrong?

Don't panic. This is normal.

  1. Tell AI: "This isn't quite right. Here's what I want: [describe]"
  2. Or: "Undo that change. Try again with these constraints: [list]"
  3. Or: Make the change yourself, then ask AI to validate

Validation catches mistakes, and iteration is expected.

Can AI handle large codebases?

Yes. Sruja scales:

  • Small (10-100 files): Full analysis in seconds
  • Medium (100-1000 files): Full analysis in 1-2 minutes
  • Large (1000+ files): May take several minutes

AI can handle any size—it just processes more data for larger projects.


Comparison to Other Tools

How is Sruja different from diagramming tools (Miro, LucidChart)?

Diagramming ToolsSruja
Manual drawingAI generates from code
Drifts from realityAlways in sync
Can't validateLinting catches errors
Hard to version controlGit diff shows changes
Output, not sourceSingle source of truth

Think of it this way: Diagrams are like screenshots—great for viewing, but not the source.

How is Sruja different from architecture frameworks (Spring, DDD)?

Sruja doesn't replace frameworks—it documents them.

  • Frameworks (Spring, DDD, Clean Architecture) – Guide how to write code
  • Sruja – Documents what your code actually does

You can use both: Sruja documents your Spring-based microservices architecture.


AI and Architecture

Why do I need the Sruja skill when I can just ask AI for architecture?

AI proposes; Sruja grounds, validates, and persists.

Without Sruja, AI can suggest architecture, but it's:

  • Ungrounded: AI may invent components or dependencies that don't exist in your code
  • Ephemeral: You get ad-hoc text or diagrams with no single source of truth

The Sruja skill gives AI:

  • Real evidence (from your codebase) to reason about
  • Validation (lint, drift) to ensure accuracy
  • Persistence (repo.sruja as a first-class artifact in your repo)

Three pillars:

  1. Grounding — The skill feeds the model real data (discover, context, graph) so it reasons on what's actually in the codebase, not on guesses. Without Sruja, the model can hallucinate modules and edges.
  2. Validation and sync — The skill uses sruja lint (valid DSL), sruja drift (declared vs actual), and intent check. So you get architecture that is valid and stays in sync with code, not a one-off diagram.
  3. Persistence and reuse — Architecture lives as repo.sruja in the repo: versionable, exportable, comparable over time. The model without Sruja gives ad-hoc text or Mermaid; with Sruja, the output is a first-class artifact the whole team and CI can use.

Think of it this way: AI is the architect proposing designs. Sruja is the structural engineer providing real data, validating plans, and making sure the blueprint is saved in your repo.


Language Support

What programming languages does Sruja support?

LanguageSupportNotes
JavaScript / TypeScript✅ ExcellentBest support
Python✅ ExcellentStrong framework detection (Django, Flask, FastAPI)
Go✅ ExcellentGreat for microservices
Rust✅ ExcellentNative language support
Java✅ GoodSpring Boot, Jakarta EE
C#✅ Good.NET applications
Ruby✅ GoodRails and Ruby apps
PHP✅ GoodPHP frameworks
Scala⚠️ LimitedPartial support

What if my language isn't listed?

Try it! Run:

sruja discover -r . --format json

If you see reasonable output, Sruja can analyze it. If not, please open an issue.


Troubleshooting

"sruja: command not found"

The CLI isn't on your PATH.

Try:

# Check if installed
which sruja

# Add to PATH (if using install script)
export PATH="$HOME/.local/bin:$PATH"

# Or restart your terminal

Skill not loading in my editor

Common causes:

  1. Didn't restart editor after installing
  2. Editor doesn't support skills.sh
  3. Typed wrong skill name

Fixes:

  • Restart your editor
  • Try: npx skills list to see installed skills
  • Check editor has skills.sh support

"Command fails: directory not found"

You're in the wrong folder.

Make sure:

# You should be IN your project
cd your-project

# Not AT the Sruja repo
# ❌ Wrong: cd ~/sruja
# ✅ Right: cd ~/my-project

Discovery shows nothing

Possible causes:

  1. No supported files – Empty directory or wrong language
  2. Wrong directory – Not in the project root
  3. Language limitation – Partial support for that language

Try:

# See what's detected
sruja discover -r . --format json

# Try quickstart for better visibility
sruja quickstart -r .

Best Practices

Start small

Do:

  • Get person + system + container levels working first
  • Add components only when needed
  • Model what evidence supports

Don't:

  • Model everything you can think of
  • Add components "for completeness"
  • Over-complicate simple systems

Validate often

Do:

  • Run sruja lint after each AI edit
  • Check before committing
  • Fix errors before calling it "done"

Don't:

  • Skip validation to "save time"
  • Commit known errors with a TODO

Iterate with AI

Do:

  • Treat first attempt as draft, not final
  • Provide feedback: "Good, but add X"
  • Ask AI to refine specific parts

Don't:

  • Expect perfection on first try
  • Give up if it's not exactly right
  • Start over from scratch instead of refining

Document decisions

Do:

  • Add descriptions to components
  • Note why you chose a pattern
  • Explain trade-offs

Don't:

  • Leave components unlabeled
  • Assume everyone knows your intent

Getting Help

Where can I ask questions?

How do I report a bug?

  1. Check if it's already reported: https://github.com/sruja-ai/sruja/issues
  2. If not, create a new issue with:
    • Steps to reproduce
    • What you expected
    • What actually happened
    • Your environment (OS, editor, language)

How do I contribute?

See Contributing Guide for guidelines.


Quick Command Reference

CommandWhen to UseExample
sruja quickstart -r .First look at a codebaseInstant overview
sruja discover -r .When generating with AIGather evidence
sruja lint repo.srujaAfter AI editsValidate file
sruja export mermaidNeed a diagramGenerate for docs
sruja export markdownNeed readable docsExport ARCHITECTURE.md
sruja drift -r .After code changesDetect what's different

Key Takeaways

  1. You don't learn a language—you guide AI
  2. Validation is your friend—run lint often
  3. Start minimal—add detail only when needed
  4. Iterate—refine with feedback
  5. Use AI as advisor—ask about patterns and trade-offs

The skill handles syntax. You handle thinking.

Design philosophy

Objective

Create a modeling language that helps all developers — from students to enterprise architects — design systems with confidence, while guiding them toward simplicity and preventing over-engineering.

Core Principles:

  1. Start simple, stay simple: A 1st-year CS student should be productive in 10 minutes, and advanced developers should be guided away from unnecessary complexity.
  2. Empower, don't restrict: The language should enable all developers, not limit them, but guide them toward good design.
  3. Approachability first: Complex concepts should be available but not encouraged unless truly needed.
  4. Prevent over-engineering: The language itself should make simple designs easier than complex ones.
  5. Systems thinking made simple: Enable full system understanding through intuitive syntax, without requiring complex theory.

Methodology Analysis

MethodologyCore ConceptsJargon LevelStudent IntuitionSruja Mapping
C4System, Container, ComponentLow"Boxes and lines" - Easy to grasp.system, container, component
DDDBounded Context, Aggregate, Entity, Value Object, Domain EventHigh"Aggregate Root" is confusing. "Value Object" is abstract.Not currently supported
ER (DB)Entity, Attribute, Relationship, Table, ColumnMedium"Entity" is standard. "Relationship" is clear.data, datastore, -> (relation)
API (OpenAPI)Path, Method, Schema, PropertyMedium"Endpoint" is clear. "Schema" is clear.api, data (as schema)
DODData, Struct, Array, TransformLow"Data" and "Struct" are very familiar to coders.data, [] (arrays)

The "Unified" Proposal

We need a set of keywords that map to these concepts without forcing the user to learn the specific theory first. The language should support progressive disclosure: simple concepts first, advanced concepts when needed.

1. Grouping (The "Container")

Problem: Different methodologies use different terms for logical boundaries.

MethodologyTermSruja KeywordWhen to Use
C4ContainercontainerTechnical deployment boundary (e.g., "Web Server", "Database")
GeneralGroupingmoduleGeneric logical grouping (most intuitive)

Decision:

  • module: Primary keyword for logical grouping. Familiar to Python/JS/Go developers.
  • container: For C4-style technical containers (deployment units).

Rationale: module is the most universal term. Students learn "modules" in their first programming course.

2. The "Thing" (Data Structure)

Problem: Entity vs Value Object vs Table vs Struct - all represent "data" but with different semantics.

MethodologyTermSruja KeywordSemantics
GeneralEntity/Structdata (with id)Has identity, mutable
GeneralValue/Structdata (no id)Immutable, defined by values
ERTable/Entitydata or datastorePersistent storage
DODStructdataIn-memory structure
APISchemadataRequest/response structure

Decision: data is the unified keyword.

Rules:

  • If data has an id field → Implicitly an Entity (has identity)
  • If data has no id → Implicitly a Value Object (value-based)
  • If data is in a datastore → Implicitly a database table
  • If data is in an api → Implicitly a request/response schema

Rationale: Students understand "data" immediately. The semantics emerge from context, not explicit keywords.

3. The "Action" (Behavior/Event)

Problem: Different types of actions need different modeling approaches.

TypeSruja KeywordPurposeExample
API EndpointapiExternal interfaceREST endpoint, GraphQL query
EventeventSomething that happenedOrderPlaced, PaymentProcessed
Function/Method(implicit in component)Internal behaviorBusiness logic in components

Decision:

  • api: Explicit API endpoints (students understand "API")
  • event: Events (something that happened)
  • Component behavior: Implicit (components contain behavior)

Rationale: Students learn APIs early. Events are intuitive ("something happened").

4. Relationships

Problem: How to model connections between elements?

Decision: Use arrow syntax -> for relationships.

User -> ShopAPI.WebApp "Uses"
ShopAPI.WebApp -> ShopAPI.Database "Reads/Writes"
Order -> Payment "Triggers"

Rationale: Arrows are universal. Everyone understands "A -> B" means "A relates to B".

Level 1: Beginner (C4 Style)

// partial
// Element kinds
person = kind "Person"
system = kind "System"
container = kind "Container"

// Elements
user = person "End User"

shop = system "Shop API" {
    webApp = container "Web Application" {
        technology "React"
    }

    db = container "PostgreSQL Database" {
        technology "PostgreSQL 14"
    }
}

// Relationships
user -> shop.webApp "Uses"
shop.webApp -> shop.db "Reads/Writes"

Level 2: Intermediate (Detailed Architecture)

// partial
// Element kinds
system = kind "System"
container = kind "Container"
component = kind "Component"
database = kind "Database"

// Architecture
ShopAPI = system "Shop API" {
    WebApp = container "Web Application" {
        technology "React"
        Cart = component "Shopping Cart"
        Checkout = component "Checkout Service"
    }

    API = container "API Gateway" {
        technology "Node.js"
    }

    DB = database "PostgreSQL Database" {
        technology "PostgreSQL 14"
    }
}

// Relationships
ShopAPI.WebApp -> ShopAPI.API "Calls"
ShopAPI.API -> ShopAPI.DB "Reads/Writes"

Level 3: Advanced (Governance + Operations)

// partial
// Element kinds
person = kind "Person"
system = kind "System"
container = kind "Container"
database = kind "Database"

// Elements
Customer = person "Customer"

Shop = system "E-commerce Shop" {
    description "High-performance e-commerce platform"

    API = container "API Gateway" {
        technology "Node.js"
        slo {
            latency {
                p95 "200ms"
                p99 "500ms"
            }
        }
        scale {
            min 3
            max 10
        }
    }

    DB = database "PostgreSQL" {
        technology "PostgreSQL 14"
    }
}

// Governance
R1 = requirement functional "Must support 10k concurrent users"
SecurityPolicy = policy "Encrypt all data" category "security" enforcement "required"

// Relationships
Customer -> Shop.API "Uses"
Shop.API -> Shop.DB "Reads/Writes"

1. Progressive Disclosure

  • Beginner: Start with system, container, component (C4)
  • Intermediate: Add module, data, api, event (Unified)
  • Advanced: Use all features together for complex architectures

Rationale: Students can start simple and learn advanced concepts when needed.

2. Arrays: DOD-Style Syntax

Support [] syntax (e.g., items OrderItem[]) instead of just implied relationships.

Rationale: Very familiar to programmers. Makes data structures explicit.

3. Unified data Keyword

The data keyword represents data structures. The presence of an id field indicates an entity with identity.

Rationale: Reduces cognitive load. Students can model data structures without learning complex theory.

4. Explicit api Keyword

Model APIs alongside data to connect "Backend" to "Database".

Rationale: Students understand "APIs". This bridges the gap between data modeling and API design.

5. Context-Aware Semantics

The same keyword (data) means different things in different contexts:

  • In a module: Domain model
  • In a datastore: Database table
  • In an api: Request/response schema
  • In a component: Internal data structure

Rationale: One keyword, multiple interpretations based on context. Reduces vocabulary size.

How Sruja Guides Toward Simplicity

1. Start Simple

  • Use system for technical/deployment modeling (C4 style)
  • Use module for logical grouping when needed
  • Keep it simple - don't add complexity unless necessary

2. Progressive Disclosure

  • Start with basic C4 concepts: system, container, component
  • Add module, data, api, event when you need more detail
  • Use only what you need for your use case

3. Natural Constraints

  • system syntax is straightforward for deployment modeling
  • The language guides you to use the right level of detail
  • Simple designs are easier to write than complex ones

4. Validation & Guidance (Future)

  • Warn if over-engineering simple systems
  • Help users choose the right level of detail
  • Guide toward simplicity

5. Clear Mental Models

  • system = "How is this deployed?" (Physical/Technical)
  • module = "How is this organized?" (Logical grouping)
  • Keep it focused on what you're actually modeling

Currently Missing (but important):

  1. Constraints/Validation: How to express "email must be valid", "age > 0"?
  2. Relationships with Cardinality: User -> Order[1:*] (one-to-many)?
  3. Inheritance/Polymorphism: How to model "Payment extends Transaction"?
  4. Enums: status: OrderStatus where OrderStatus = [PENDING, COMPLETED, CANCELLED]
  5. Optional Fields: email?: string vs email string
  6. Defaults: status string = "PENDING"
  7. Computed Fields: total: float = items.sum(price * qty)

Recommendations:

  • Add enum keyword for enumerations
  • Support ? for optional fields: email? string
  • Support = for defaults: status string = "PENDING"
  • Consider constraint keyword for validation rules
  • Consider relationship syntax: User -> Order[1:*]
  • flow and scenario/story already implemented for flow thinking (DFD and BDD-style)

From C4 to Sruja:

<!-- partial -->
// C4: System Context
system "E-Commerce System" {
    // C4: Container
    container "Web Application" {
        // C4: Component
        component "Order Controller"
    }
}

From Data Modeling to Sruja:

<!-- partial -->
// Data structures
module Orders {
    data Order {
        id string
        items OrderItem[]
    }

    data OrderItem {
        product_id string
        qty int
    }

    data ShippingAddress {
        street string
        city string
    }
}

From ER to Sruja:

<!-- partial -->
datastore Database {
    data User {
        id string
        email string
    }

    data Order {
        id string
        user_id string  // Foreign key relationship
    }
}

Systems Thinking: Simple and Intuitive

Goal: Help developers think about systems as a whole — understanding how parts interact, boundaries, and emergent behavior — without requiring complex theory.

Core Systems Thinking Concepts (Simplified)

Systems thinking is about understanding:

  1. Parts and Relationships: How components connect and interact
  2. Boundaries: What's inside vs outside the system
  3. Flows: How information/data moves through the system
  4. Feedback Loops: How actions create reactions
  5. Context: The environment the system operates in

How Sruja Makes Systems Thinking Simple

1. Parts and Relationships (Already Built-In)

<!-- partial -->
system ShopAPI {
    container WebApp
    container Database
}

ShopAPI.WebApp -> ShopAPI.Database "Reads/Writes"

Simple Insight: Just draw boxes and connect them with arrows. The relationships show how parts interact.

2. Boundaries (Natural in Sruja)

<!-- partial -->
system ShopAPI {  // Inside boundary
    container WebApp
}

person User  // Outside boundary
User -> ShopAPI "Uses"

Simple Insight: system defines the boundary. person and external systems are outside. Clear and intuitive.

3. Flows (Built-In Flow Syntax)

<!-- partial -->
// Data Flow Diagram (DFD) style — use scenario
scenario OrderProcess "Order Processing" {
    Customer -> Shop.WebApp "Order Details"
    Shop.WebApp -> Shop.Database "Save Order"
    Shop.Database -> Shop.WebApp "Confirmation"
}

// User Story/Scenario style
story Checkout "User Checkout Flow" {
    User -> ECommerce.CartPage "adds item to cart"
    ECommerce.CartPage -> ECommerce "clicks checkout"
    ECommerce -> Inventory "Check Stock"
}

// Or using simple qualified relationships
Customer -> Shop.WebApp "Submits Order"
Shop.WebApp -> Shop.OrderService "Processes"
Shop.OrderService -> Shop.PaymentService "Charges"

Simple Insight: Use flow for data flows (DFD), story/scenario for user stories, or simple relationships for basic flows. Events show what happens: event OrderPlaced.

4. Feedback Loops (Cycles in Relationships)

<!-- partial -->
// Simple feedback: User action triggers system response
User -> System "Requests"
System -> User "Responds"

// System feedback: Component A affects Component B, which affects A
ComponentA -> ComponentB "Updates"
ComponentB -> ComponentA "Notifies"

// Event-driven cycles: Service A triggers Service B, which triggers A
ServiceA -> ServiceB "Sends Event"
ServiceB -> ServiceA "Responds with Event"

// Mutual dependencies: Microservices that call each other
OrderService -> PaymentService "Charges Payment"
PaymentService -> OrderService "Confirms Payment"

Simple Insight: When arrows form a cycle, that's a feedback loop. The system responds to itself. Cycles are valid in many architectures:

  • Feedback loops: User interactions, system responses
  • Event-driven patterns: Services triggering each other via events
  • Mutual dependencies: Microservices that need to communicate bidirectionally
  • Bidirectional flows: API <-> Database (read/write operations)

Note: Sruja allows cycles - they're a natural part of system design. The validator will inform you about cycles but won't block them, as they're often intentional architectural patterns.

5. Context (Persons and External Systems)

<!-- partial -->
person Customer "End User"
person Admin "System Administrator"

system PaymentGateway "Third-party service" {
  tags ["external"]
}

Customer -> ShopAPI "Uses"
ShopAPI -> PaymentGateway "Processes payments"

Simple Insight: person and external show the context - who/what the system interacts with.

Progressive Systems Thinking

Beginner: Just model the parts and connections

// partial
// Element kinds
system = kind "System"
container = kind "Container"

// Elements
myApp = system "MyApp" {
    frontend = container "Frontend"
    backend = container "Backend"
}

// Relationships
myApp.frontend -> myApp.backend "Calls"

Intermediate: Add flows and events

<!-- partial -->
// Simple qualified relationships
user -> myApp.frontend "Clicks"
myApp.frontend -> myApp.backend "Sends request"
myApp.backend -> myApp.database "Saves"

// DFD-style — use scenario
```sruja
<!-- partial -->
scenario OrderFlow "Order Processing" {
    user -> myApp.frontend "Submits"
    myApp.frontend -> myApp.backend "Processes"
    myApp.backend -> myApp.database "Stores"
}

Advanced: Model feedback loops and system behavior

<!-- partial -->
// Feedback loop: User action -> System response -> User sees result
story CompleteOrder "Order Completion Flow" {
    user -> shop.system "Submits"
    shop.system -> shop.database "Stores"
    shop.system -> user "Confirms"
}

// Complex flow with multiple steps — use scenario
scenario PaymentFlow "Payment Processing" {
    orders.orderService -> orders.paymentGateway "Charge"
    orders.paymentGateway -> orders.orderService "Confirms"
    orders.orderService -> user "Notifies"
}

Key Principle: No Jargon Required

  • Don't say: "Model the feedback loop using systems thinking principles"
  • Do say: "Use flow or story to show how data/actions move through the system"
  • Don't say: "Define the system boundary using context mapping"
  • Do say: "Use system to show what's inside, person to show who uses it"
  • Don't say: "Create a DFD (Data Flow Diagram)"
  • Do say: "Use flow to show how data moves between components"

Result: Developers naturally think in systems without learning theory first. The syntax guides them to see:

  • How parts connect (relationships: ->)
  • What's inside vs outside (boundaries: system vs person/external)
  • How things flow (flow for data flows, story/scenario for user stories, or simple -> relationships)
  • How actions create reactions (cycles in relationships, feedback in flows)

Additional Design Philosophy Assessment

After assessing various design philosophies (Event-Driven Architecture, Hexagonal Architecture, CQRS, BDD, Reactive Systems, etc.) through a strict lens of "does this help developers learn system design?", we found:

✅ Accepted: Simple & Valuable

  1. Flows and Scenarios: Already implemented! flow for data flows (DFD), scenario/story for user stories (BDD-style Given-When-Then)
  2. Optional Fields: Practical data modeling (email? string)
  3. Enums: Practical data modeling (status: OrderStatus)

❌ Rejected: Too Complex or Unnecessary

  • Hexagonal Architecture (Ports & Adapters) - Too abstract
  • Clean Architecture / Layers - Too theoretical
  • CQRS - Too specialized, can use existing api
  • Advanced Event-Driven - Current event is sufficient
  • Reactive Systems - Too complex
  • Actor Model - Too specialized
  • GraphQL/Protocol Buffers - Technology-specific
  • Semantic Web - Overkill
  • SOLID (as syntax) - Principles, not syntax

Note: Systems thinking is accepted - but implemented simply through existing syntax (relationships, boundaries, flows). No new keywords needed.

Key Finding: Most "advanced" concepts should be rejected. Only 3 simple additions are recommended, and everything else can wait until developers master the basics. Systems thinking is naturally supported through intuitive syntax.

Conclusion

By using system, module, data, api, and event, we cover 90% of use cases with words that a 1st-year CS student already knows.

Key Success Metrics:

  • ✅ Can a beginner model a simple system in 10 minutes? Yes (C4 style)
  • ✅ Can an intermediate model data + APIs? Yes (Unified style)
  • ✅ Can an advanced user model complex architectures? Yes (Extended features)
  • ✅ Does it prevent over-engineering? Yes (simplicity by design)
  • ✅ Is it approachable for all developers? Yes (progressive disclosure)

Next Steps:

  1. Add enum support
  2. Add optional fields (? syntax)
  3. Add relationship cardinality
  4. Add constraint/validation syntax
  5. flow and scenario/story already implemented - enhance documentation and examples
  6. Improve error messages for beginners
  7. Add validation rules to guide simplicity

Key Principle: Less is more. Don't add complexity unless it clearly helps developers learn system design better. The goal is to build confidence through simplicity, not complexity through features.

Sruja Adoption Guide

Using Sruja in your repo

For a short, practical guide to the new product shape, see Core vs extensions. The rest of this adoption guide helps you evaluate fit and plan rollout.

Use a single, repeatable workflow to evaluate Sruja. Start with the core loop first:

curl -fsSL https://sruja.ai/install.sh | bash
sruja start -r .
sruja drift -r . --structural-only --advisory
sruja focus -r . --file path/to/file.rs
sruja verify-task --profile coding -r .

Only after that should you decide whether to add reviewed intent in Git:

npx skills add https://github.com/sruja-ai/sruja --skill sruja-architecture
sruja lint repo.sruja
sruja sync -r .
sruja drift -r . -a repo.sruja

This keeps evaluation honest: prove the core loop first, then layer on richer authoring and governance only when needed.

Is Sruja Right for Your Organization?

Quick Self-Assessment

Answer these questions to determine if Sruja addresses your needs:

Architecture & Documentation Pain Points

  • Do your architecture diagrams become outdated within weeks?
  • Do engineers spend significant time maintaining documentation?
  • Is there confusion about "the latest architecture diagram"?
  • Do new engineers struggle to understand system architecture?
  • Are architectural decisions lost when senior engineers leave?

If 3+ are "Yes" → Sruja can help

Compliance & Governance Needs

  • Do you need to comply with regulations (HIPAA, SOC2, PCI-DSS, GDPR)?
  • Are compliance audits time-consuming and risky?
  • Do you struggle to prove architectural controls meet requirements?
  • Are security policies documented but not enforced?
  • Do you need to demonstrate compliance to auditors?

If 2+ are "Yes" → Sruja's policy-as-code is valuable

Technical Architecture Challenges

  • Do you have microservices that need explicit guardrails?
  • Are you experiencing architectural drift (implementation vs. design)?
  • Do you need to enforce service boundaries and dependencies?
  • Are circular dependencies causing issues?
  • Do you need to generate infrastructure from architecture?

If 2+ are "Yes" → Sruja's validation and enforcement help

DevOps & Engineering Culture

  • Do you use Git/GitOps workflows?
  • Do you have CI/CD pipelines?
  • Do you value "everything as code" (IaC, GitOps)?
  • Do you want architecture changes in PR reviews?
  • Do you need architecture to integrate with Terraform/Istio/etc.?

If 3+ are "Yes" → Sruja fits your workflow

Organization Size & Maturity

Sruja is ideal for:

  • Startups (10-50 engineers): Fast scaling, need consistency
  • Scale-ups (50-200 engineers): Managing complexity, compliance needs
  • Enterprises (200+ engineers): Governance, compliance, knowledge management

Sruja may not be ideal if:

  • ❌ You have < 5 engineers (overhead may outweigh benefits)
  • ❌ You don't use version control or CI/CD
  • ❌ You prefer visual-only tools (no code/DSL)
  • ❌ You have no need for shared architecture context, CI checks, or policy guardrails

Decision Framework

Step 1: Define Your Goals

What problem are you trying to solve?

GoalSruja BenefitPriority
Reduce documentation overheadArchitecture-as-code stays currentHigh
Ensure compliancePolicy-as-code with automated validationHigh
Prevent architectural driftAutomated validation in CI/CDMedium
Faster onboardingLiving documentation in codebaseMedium
Enforce service boundariesLayer and dependency validationMedium
Generate infrastructureTerraform/OpenTofu generation (roadmap)Low

Action: Rank your top 3 goals. Sruja should address at least 2.

Step 2: Calculate Value & ROI

Note: Sruja is free and open source. This ROI calculation measures time savings and value, not purchase cost.

Quick Value Calculator:

Time Savings = (Engineers × Hours/Week × 0.7) × 50 weeks × $100/hour
Onboarding Savings = (New Engineers/Year × 2 weeks × 0.5) × $150k/year ÷ 50
Risk Reduction = Compliance Failures Avoided × $100k

Total Value = Time Savings + Onboarding + Risk Reduction

Example (10 senior engineers, 20 new engineers/year):

  • Time: 10 × 4 hours × 0.7 × 50 × $100 = $140k/year
  • Onboarding: 20 × 2 × 0.5 × $150k ÷ 50 = $60k/year
  • Risk: 1 failure avoided = $100k (one-time)
  • Total Value: $200k+ per year

ROI: Since Sruja is free, ROI is essentially infinite - you get value with zero cost.

Step 3: Assess Technical Fit

Evaluate your technical stack:

TechnologySruja IntegrationStatus
Git/GitHub/GitLabNative integration✅ Available
CI/CD (GitHub Actions, GitLab CI)Validation in pipelines✅ Available
Terraform/OpenTofuInfrastructure generation🚧 Roadmap (Medium-Term)
Kubernetes/IstioService mesh config generation🚧 Roadmap (Long-Term)
API Gateways (Kong, Apigee)Config generation🚧 Roadmap (Long-Term)
OPA (Open Policy Agent)Policy integration🚧 Roadmap (Medium-Term)

Action:

  • If you need Git/CI/CD integration → ✅ Ready now
  • If you need Terraform/Istio/OPA → 🚧 On roadmap (see Roadmap Discussions) — you can pilot with current features now

Evaluation Process

Phase 1: Discovery (Week 1)

Activities:

  1. Review Sruja documentation
  2. Install CLI: curl -fsSL https://sruja.ai/install.sh | bash
  3. Run the core loop: sruja start -r ., sruja drift -r . --structural-only --advisory, sruja focus -r . --file <path>, sruja verify-task --profile coding -r .
  4. If the team needs reviewed intent, author repo.sruja with the skill, then validate and refresh evidence: sruja lint repo.sruja then sruja sync -r .
  5. Capture the first alignment signal: sruja drift -r . -a repo.sruja when reviewed intent exists
  6. Install VS Code extension for syntax highlighting and diagnostics if the team will edit .sruja files

Deliverable: Understanding of Sruja capabilities

Phase 2: Proof of Concept (Weeks 2-4)

Activities:

  1. Expand repo.sruja to cover the repo boundary and core containers that matter for reviews
  2. Integrate validation and drift into CI/CD (sruja lint repo.sruja and sruja drift -r . -a repo.sruja)
  3. Establish a PR review rule: architecture changes ship with code changes (same diff)
  4. Measure signal vs noise (how many findings you keep vs ignore)

Success Criteria:

  • Can model systems accurately
  • Validation catches real issues
  • Team sees value
  • Time savings measurable

Deliverable: PoC report with value estimate

Phase 3: Pilot (Months 2-3)

Activities:

  1. Roll out to 1-2 teams
  2. Establish best practices
  3. Create internal documentation
  4. Measure compliance improvements

Success Criteria:

  • Architecture stays current
  • Compliance validation working
  • Team adoption > 80%
  • Positive value demonstrated

Deliverable: Pilot report with go/no-go recommendation

Decision Checklist

Must-Have Requirements

  • Problem Fit: Sruja addresses 2+ of your top goals
  • Value Positive: Calculated value > $100k/year (or equivalent time savings)
  • Technical Fit: Git/CI/CD integration available (or roadmap acceptable)
  • Team Readiness: Team comfortable with code-based tools
  • Leadership Support: Time allocated for adoption (no budget needed - Sruja is free)

Nice-to-Have Requirements

  • Advanced features needed (Terraform, Istio, OPA)
  • Compliance requirements (HIPAA, SOC2, PCI-DSS)
  • Large team (100+ engineers)
  • Microservices architecture

Decision Matrix

CriteriaWeightYour Score (1-5)Weighted Score
Problem fit30%______
Value/ROI25%______
Technical fit20%______
Team readiness15%______
Leadership support10%______
Total100%___/5.0

Decision Rule:

  • > 4.0: Strong fit → Proceed with pilot
  • 3.5-4.0: Good fit → Consider pilot
  • < 3.5: Weak fit → Reassess or wait

Common Concerns & Objections

"We already have architecture documentation"

Response: Sruja doesn't replace documentation — it makes it executable. Your documentation becomes code that:

  • Stays current (version-controlled)
  • Validates automatically
  • Enforces policies
  • Integrates with DevOps

"Our team isn't technical enough for a DSL"

Response: Sruja's DSL is designed for all developers:

  • 1st-year CS students productive in 10 minutes
  • Progressive disclosure (simple → advanced)
  • Rich error messages guide users
  • VS Code extension with full LSP support (autocomplete, go-to-definition, rename, find references, and more) - see VS Code Extension Guide

"We don't have compliance requirements"

Response: Sruja provides value beyond compliance:

  • Faster onboarding (50% reduction)
  • Reduced documentation time (20-30%)
  • Architectural validation (prevents drift)
  • Knowledge preservation

"The roadmap features we need aren't ready"

Response:

  • Core features (validation, CI/CD) are available now
  • Roadmap features (Terraform, Istio, OPA) are planned for Medium-Term to Long-Term (see Roadmap Discussions)
  • You can start with core features and add advanced later
  • Early adoption gives you influence on roadmap priorities

Success Metrics

Track These KPIs

MetricBaselineTarget (3 months)Target (6 months)
Documentation timeX hours/weekX × 0.7 hours/weekX × 0.5 hours/week
Onboarding timeX weeksX × 0.7 weeksX × 0.5 weeks
Architecture freshnessX% outdated< 10% outdated< 5% outdated
Compliance violationsX per quarterX × 0.5 per quarter0 per quarter
Architectural issues caughtX in productionX × 0.3 in productionX × 0.1 in production

Next Steps

Immediate Actions

  1. Complete Self-Assessment (above)
  2. Calculate Value (Step 2)
  3. Try Sruja (see Getting Started)
  4. Join Community (GitHub Discussions)

Decision Timeline

  • Week 1: Self-assessment and value calculation
  • Week 2-4: Proof of concept
  • Month 2-3: Pilot program
  • Month 4+: Full rollout (if successful)

Resources

Open Source & Community Support

Sruja is free and open source (Apache 2.0 licensed), developed by and for the community. You can:

  • Use it freely: No licensing fees or restrictions
  • Contribute: Submit PRs, report issues, suggest features
  • Extend it: Build custom validators, exporters, and integrations
  • Join the community: Participate in GitHub Discussions, share use cases, and learn from others

Professional Services

While Sruja is open source and free to use, professional consulting services are available for organizations that need:

  • Implementation support: Help rolling out Sruja across teams and systems
  • Context workflow guidance: Establish evidence, validation, and review patterns for AI-assisted architecture work
  • Custom integrations: Integrate Sruja with existing CI/CD, infrastructure, and monitoring tools
  • Training: Team training on Sruja DSL, validation patterns, and architectural modeling
  • Custom development: Build custom validators, exporters, or platform integrations

Contact the team through GitHub Discussions to discuss your needs.

Future Platform Vision

Sruja is designed to evolve as a context engineering platform for AI-assisted architecture work:

  • Live System Review: Compare actual runtime behavior against reviewed architecture truth to detect drift and violations.
  • Gap Analysis: Identify missing components, undocumented dependencies, and architectural gaps from evidence.
  • Continuous Validation: Keep repo context fresh as code, docs, and deployment artifacts change.
  • Review Support: Help humans and AI agents evaluate whether proposed changes still match intent.

These capabilities are planned for future releases. The current open source foundation provides the evidence, validation, and context layers for this evolution, and community feedback helps shape the roadmap.


Note: This guide helps you evaluate whether Sruja is the right fit for your organization and how to adopt it successfully.

Ready to evaluate Sruja? Start with the Self-Assessment above.

Adoption Playbook

Week 1: Baseline & CI

  • Structural draft: sruja quickstart -r . --generate-baseline (writes repo.sruja.draft)
  • Author reviewed repo.sruja (sruja-architecture skill), then validate and refresh evidence: sruja lint repo.sruja then sruja sync -r .
  • Add sruja lint repo.sruja and sruja drift -r . -a repo.sruja to CI; fail on violations
  • Export docs: sruja export markdown repo.sruja

Week 2: Targets & Guardrails

  • Add slo and scale for critical paths.
  • Encode constraints and conventions; publish to teams.
  • Introduce views for API/Data/Auth focus.

Week 3: Governance & Evolution

  • Add policy pages for security/operability.
  • Document decisions with adr blocks; track evolution with slo values (target vs current).
  • Use Git for automatic change tracking (git log, git diff, version tags).
  • Wire linting to PR checks; require green builds.

CI Example (GitHub Actions)

name: sruja
on: [push, pull_request]
jobs:
  validate:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - name: Install Sruja CLI
        run: curl -fsSL https://sruja.ai/install.sh | bash
      - name: Lint baseline
        run: sruja lint repo.sruja
      - name: Drift check (declared vs actual)
        run: sruja drift -r . -a repo.sruja
      - name: Export Docs
        run: sruja export markdown repo.sruja

Success Metrics

  • Review cycle time ↓
  • Incident rate for architecture errors ↓
  • Consistency across services ↑

Note: Sruja is free and open source (Apache 2.0 licensed). Need help with implementation? Professional consulting services are available. Contact the team through GitHub Discussions to learn more.

Sruja Community

Welcome to the Sruja community! Sruja is an open source project built by and for developers who care about software architecture. Whether you're here to learn, contribute, or get help, we're glad you're here.

Join the Conversation

💬 GitHub Discussions

For longer-form discussions, feature requests, and Q&A:

GitHub Discussions

GitHub Discussions is ideal for:

  • Feature proposals and RFCs
  • Technical discussions
  • Sharing tutorials and examples
  • Asking detailed questions

🐛 GitHub Issues

Found a bug or have a feature request?

Open an Issue

Ways to Contribute

Sruja is an open source project, and we welcome contributions of all sizes! There are many ways to contribute, even if you're not a developer.

No Code Required

Documentation

  • Fix typos or improve clarity
  • Add examples and tutorials
  • Translate documentation
  • Write blog posts or courses

Testing & Feedback

  • Test new features and report bugs
  • Share your use cases
  • Provide feedback on design decisions
  • Help improve error messages

Community

  • Answer questions in Discussions
  • Help newcomers get started
  • Share your Sruja projects and experiences

Beginner-Friendly Code

Small Improvements

  • Add test cases
  • Fix small bugs
  • Improve error messages
  • Add examples to book/valid-examples/ and a matching page under book/src/examples/
  • Improve CLI help text

Documentation Code

  • Add code examples
  • Update API documentation
  • Create tutorials

More Advanced Contributions

Features & Enhancements

  • Implement new features
  • Add new export formats
  • Add validation rules
  • Improve tooling and developer experience

Core Development

  • Work on the language parser
  • Enhance the validation engine
  • Build platform integrations
  • Develop plugins and extensions

Getting Started with Contributions

🎯 First Time Contributing?

Start here: Contribution Guide

This step-by-step guide walks you through:

  • Finding your first issue
  • Setting up your development environment
  • Making and submitting changes
  • Getting help when stuck

Contribution Workflow

  1. Fork and Branch: Fork the repo and create a topic branch
  2. Implement: Make your changes and test locally
  3. Commit: Follow Conventional Commits
  4. Pull Request: Open a PR with a clear description
  5. Review: Address feedback and iterate
  6. Merge: Once approved, your contribution is merged!

For detailed instructions, see the Contribution Guide.

Roadmap & Transparency

Sruja is developed transparently with community input. Our roadmap is public and open for discussion.

Current Roadmap

View Roadmap Discussions

The roadmap outlines our path to v1.0, including:

  • Advanced Governance & Compliance: Policy as code, architectural guardrails
  • Production Reality & Data Flow: Service mesh integration, runtime verification
  • Extensibility & Ecosystem: Plugin system, DevOps integrations
  • Platform Evolution: Live system review, gap detection, violation monitoring

Shaping the Roadmap

Your feedback shapes the roadmap! We welcome:

  • Feature requests via GitHub Discussions
  • Use case sharing to prioritize features
  • RFCs (Request for Comments) for major changes
  • Community voting on priorities

Community Expectations

We're committed to maintaining a welcoming and respectful community. When participating:

  • Be respectful and constructive: Treat everyone with kindness
  • Provide actionable feedback: Help others improve their contributions
  • Prefer documented decisions: Link to ADRs or issues when relevant
  • Start small: You can always contribute more later!

Recognition

We value all contributions, big and small. Contributors are recognized through:

  • GitHub contributor list
  • Release notes (for significant contributions)
  • Community highlights in discussions

Professional Services

While Sruja is open source and free to use, professional consulting services are available for organizations that need:

  • Implementation support: Help rolling out Sruja across teams
  • Best practices guidance: Establish architectural governance patterns
  • Custom integrations: Integrate with existing CI/CD and infrastructure
  • Training: Team training on Sruja DSL and architectural modeling
  • Custom development: Build custom validators, exporters, or integrations

Contact the team through GitHub Discussions to discuss your needs.

Resources

Documentation

Development

Community

Get Involved Today

Ready to contribute? Here are some quick ways to get started:

  1. Join Discussions and introduce yourself
  2. Star the repository on GitHub to show your support
  3. Fix a typo in the documentation
  4. Add an example to book/valid-examples/ and a matching page under book/src/examples/
  5. Share your use case in GitHub Discussions

Every contribution, no matter how small, helps make Sruja better for everyone. Thank you for being part of the community!


Questions? Reach out on GitHub Discussions. We're here to help!

Glossary

Quick reference for technical terms and concepts used throughout Sruja documentation.

A

ADR (Architecture Decision Record)

A document that captures an important architectural decision made along with its context and consequences. In Sruja, ADRs are defined using the adr keyword and can be linked to specific architecture elements.

Example:

ADR001 = adr "Use Microservices" {
  status "Accepted"
  context "Need to scale independently"
  decision "Adopt microservices architecture"
  consequences "Increased complexity but better scalability"
}

Architecture-as-Code

The practice of defining software architecture using code (text-based DSL) instead of static diagrams. This enables version control, validation, and automated documentation generation.

C

C4 Model

A hierarchical model for visualizing software architecture, created by Simon Brown. It consists of four levels:

  • Level 1 (Context): System context diagram showing the system and its users
  • Level 2 (Container): Container diagram showing high-level technical building blocks
  • Level 3 (Component): Component diagram showing internal structure of containers
  • Level 4 (Code): Code-level diagram (typically managed by IDEs, not Sruja)

Sruja is based on the C4 model and automatically generates C4-compliant diagrams.

Component

A structural element within a container that represents a major building block. Components are optional and provide additional detail when needed.

Example:

// partial
App = system "App" {
  API = container "API" {
    Auth = component "Authentication"
    Payment = component "Payment Processing"
  }
}

Container

A deployable unit within a system. In C4 terminology, a container is NOT a Docker container, but rather any separately deployable unit like:

  • Web applications
  • Mobile apps
  • Server-side applications
  • Databases
  • File systems

Example:

// partial
App = system "E-commerce" {
  Web = container "React App"
  API = container "Node.js API"
  DB = database "PostgreSQL"
}

D

Database

A type of container that represents a data store. In Sruja, databases are defined using the database keyword.

Example:

// partial
DB = database "PostgreSQL"

Note: Sruja also supports datastore as an alias, but database is the recommended term.

DSL (Domain-Specific Language)

A programming language specialized for a particular domain. Sruja DSL is a text-based language specifically designed for defining software architecture.

E

Element

Any architectural construct in Sruja: person, system, container, component, database, queue, etc. Elements are the building blocks of your architecture model.

K

Kind

A type definition for elements. Kinds can be imported from the standard library (import { * } from 'sruja.ai/stdlib') or declared manually for custom types.

Example:

// Using stdlib (recommended)
import { * } from 'sruja.ai/stdlib'

// Or declaring manually
microservice = kind "Microservice"

M

Metadata

Additional information attached to elements, such as team ownership, tier, or custom tags. Metadata helps with governance and organization.

Example:

App = system "My App" {
  metadata {
    team "Platform"
    tier "critical"
  }
}

P

Person

An actor or user of the system. Persons are defined at the context level and represent external users or roles.

Example:

User = person "Customer"
Admin = person "Administrator"

Q

Queue

A message queue or event stream used for asynchronous communication between containers.

Example:

// partial
EventQueue = queue "Kafka Topic"

R

Relation

A connection between two elements, showing how they interact. Relations are defined using the -> operator.

Example:

<!-- partial -->
User -> App.Web "Visits"
App.Web -> App.API "Calls"

Requirement

A functional or non-functional requirement that can be linked to architecture elements using tags. Requirements help trace business needs to technical implementation.

Example:

R001 = requirement "User Authentication" {
  description "Users must be able to log in securely"
  tags ["App.Web", "App.API"]
}

S

Scenario

A sequence of interactions that describe how users or systems interact to accomplish a goal. Scenarios help document user flows and system behavior.

Example:

<!-- partial -->
scenario Checkout "Checkout Flow" {
  User -> App.Web "adds items to cart"
  App.Web -> App.API "validates cart"
  App.API -> App.DB "stores order"
}

System

The highest-level element in C4 Level 1. A system represents a software system that delivers value to its users.

Example:

ECommerce = system "E-commerce Platform" {
  description "Online shopping platform"
}

stdlib (Standard Library)

The Sruja standard library that provides common element kinds (person, system, container, database, etc.). Importing from stdlib is the recommended way to use standard types.

Example:

import { * } from 'sruja.ai/stdlib'

T

Tag

A label that can be attached to elements, requirements, or ADRs to enable filtering, grouping, and traceability.

Example:

App = system "My App" {
  tags ["production", "critical"]
}

V

View

A diagram perspective that shows a subset of the architecture. Views can be explicit (defined with view blocks) or implicit (automatically generated by Sruja).

Example:

view index {
  title "Complete System View"
  include *
}

Documentation Style Guide

Goals

  • Align with the Diátaxis framework: Tutorials, How‑to Guides, Reference, Explanation
  • Improve clarity, consistency, and task‑orientation
  • Raise quality to industry standards (Stripe, React, Kubernetes, MDN)

Front Matter

  • Required: title, summary
  • Recommended: prerequisites, learning_objectives, estimated_time, difficulty, tags, last_updated

Headings

  • Use Title Case for H1/H2/H3
  • Keep headings unique; avoid duplicates within a page

Code Blocks

  • Always specify language fences: bash, sh, json, yaml, go, ts, tsx, md, sruja
  • Prefer copy‑ready commands; avoid interactive prompts where possible

Admonitions

  • Use standard callouts: Note, Tip, Warning
  • Keep callouts short and action‑oriented
  • Prefer descriptive link text (not raw URLs)
  • Cross‑link to Reference and Examples when teaching a concept or task

Images & Diagrams

  • Include small screenshots or diagram previews for expected outcomes
  • Use alt text that describes the intent and context

Tutorials

  • Structure: Overview → Prerequisites → Steps → Outcome → Troubleshooting → Next Steps
  • Include at least one end‑to‑end task with an expected output

How‑to Guides

  • Task‑oriented and concise
  • Structure: Purpose → Steps → Validation → References

Reference

  • Precise, complete, and skimmable tables/lists
  • Avoid narrative; link outward to tutorials for workflows

Explanation

  • Conceptual background, rationale, trade‑offs
  • Link to reference for details and to tutorials for practice

Quality Gates

  • Markdown lint for headings, lists, links
  • Link checking for external and internal links
  • Optional accessibility lint (alt text, heading levels)

Review Checklist

  • Front matter present and complete
  • Headings consistent and unique
  • Code fences have language tags
  • Cross‑links added to relevant Reference/Examples
  • Outcome preview or screenshot included where appropriate

Tutorials

Step-by-step guides to get things done with Sruja.

Basic

Advanced

Combine with the Beginner path or Courses for a full learning path.

DSL Basics

Sruja is an architecture DSL. This tutorial introduces its core elements.

Elements

// partial
import { * } from 'sruja.ai/stdlib'


Shop = system "Shop API" {
  WebApp = container "Web" {
    description "Gateway layer"
  }
  CatalogSvc = container "Catalog"
  MainDB = database "Database"
}

User = person "User"

User -> Shop.WebApp "Uses"
Shop.WebApp -> Shop.CatalogSvc "Routes"
Shop.CatalogSvc -> Shop.MainDB "Reads/Writes"

view index {
  include *
}

Descriptions and Metadata

import { * } from 'sruja.ai/stdlib'


Payments = system "Payments" {
  description "Handles payments and refunds"
  // metadata
  metadata {
    team "FinTech"
    tier "critical"
  }
}

Component‑level Modeling

// partial
import { * } from 'sruja.ai/stdlib'


App = system "App" {
  Web = container "Web" {
    Cart = component "Cart"
  }
}

Next Steps

Validation & Linting

Sruja ships with a validation engine that helps keep architectures healthy. This tutorial covers how to use it effectively and troubleshoot common issues.

Quick Start

# Lint a single file
sruja lint architecture.sruja

# Lint all .sruja files in a directory
sruja lint ./architectures/

# Get detailed output
sruja lint --verbose architecture.sruja

# Export validation report as JSON (for CI/CD)
sruja lint --json architecture.sruja > lint-report.json

Common Validation Checks

Sruja validates:

  1. Unique IDs: No duplicate element IDs
  2. Valid references: Relations must connect existing elements
  3. Cycle detection: Informational (cycles are valid for many patterns)
  4. Orphan detection: Elements not used by any relation
  5. Simplicity guidance: Suggests simpler syntax when appropriate
  6. Constraint violations: Policy and constraint rule violations

Real-World Example: E-Commerce Platform

Let's validate a real architecture:

// partial
import { * } from 'sruja.ai/stdlib'


Customer = person "Customer"

ECommerce = system "E-Commerce Platform" {
    WebApp = container "Web Application" {
        technology "React"
    }
    API = container "REST API" {
        technology "Rust"
    }
    ProductDB = database "Product Database" {
        technology "PostgreSQL"
    }
    OrderDB = database "Order Database" {
        technology "PostgreSQL"
    }
}

Customer -> ECommerce.WebApp "Browses products"
ECommerce.WebApp -> ECommerce.API "Calls API"
ECommerce.API -> ECommerce.ProductDB "Reads products"
ECommerce.API -> ECommerce.OrderDB "Writes orders"

view index {
include *
}

Validation output:

✅ Valid architecture
✅ All references valid
✅ No orphan elements
ℹ️  Cycle detected: ECommerce.WebApp ↔ ECommerce.API (this is valid for request/response)

Troubleshooting Common Errors

Error 1: Invalid Reference

Error message:

❌ Invalid reference: ECommerce.API -> ECommerce.NonExistent "Calls"
   Element 'NonExistent' not found in system 'ECommerce'

Problem: You're referencing an element that doesn't exist.

Fix:

// partial
// ❌ Wrong
ECommerce.API -> ECommerce.NonExistent "Calls"

// ✅ Correct - element exists
ECommerce.API -> ECommerce.ProductDB "Reads"

Real-world scenario: You renamed a service but forgot to update all references.

Error 2: Duplicate ID

Error message:

❌ Duplicate ID: 'API' found in system 'ECommerce'
   First occurrence: line 5
   Second occurrence: line 12

Problem: Two elements have the same ID in the same scope.

Fix:

import { * } from 'sruja.ai/stdlib'


// EXPECTED_FAILURE: unexpected token
// ❌ Wrong
ECommerce = system "E-Commerce" {
API = container "REST API"
API = container "GraphQL API"  // Duplicate ID!
}

// ✅ Correct - use unique IDs
ECommerce = system "E-Commerce" {
RESTAPI = container "REST API"
GraphQLAPI = container "GraphQL API"
}

Real-world scenario: You added a new API type but used the same ID.

Error 3: Orphan Element

Warning message:

⚠️  Orphan element: ECommerce.Cache
   This element is not referenced by any relation

Problem: An element exists but nothing connects to it.

Fix options:

  1. Add a relation (if the element should be used):
// partial
// Add relation to use the cache
ECommerce.API -> ECommerce.Cache "Reads cache"
  1. Remove the element (if it's not needed):
// Remove if not part of current architecture
// datastore Cache "Cache" { ... }
  1. Document why it's isolated (if intentional):
// partial
datastore Cache "Cache" {
    description "Future: Will be used for product catalog caching"
    metadata {
        status "planned"
    }
}

Real-world scenario: You added a component for future use but haven't integrated it yet.

Error 4: Constraint Violation

Error message:

❌ Constraint violation: 'NoDirectDB' violated
   ECommerce.WebApp -> ECommerce.ProductDB "Direct database access"
   Constraint: Frontend containers cannot access databases directly

Problem: A constraint rule is being violated.

Fix:

// EXPECTED_FAILURE: Invalid reference
// ❌ Wrong - violates constraint
ECommerce.WebApp -> ECommerce.ProductDB "Direct access"

// ✅ Correct - go through API
ECommerce.WebApp -> ECommerce.API "Calls API"
ECommerce.API -> ECommerce.ProductDB "Reads products"

Real-world scenario: Enforcing architectural standards (e.g., "no direct database access from frontend").

Understanding Validation Messages

Cycles Are Valid

Sruja detects cycles but doesn't block them - cycles are valid architectural patterns:

  • Feedback loops: User ↔ System interactions
  • Event-driven: Service A ↔ Service B via events
  • Mutual dependencies: Microservices that call each other
  • Bidirectional flows: API ↔ Database (read/write)
// partial
import { * } from 'sruja.ai/stdlib'


// ✅ Valid - feedback loop
User = person "User"
Platform = system "Platform"
User -> Platform "Makes request"
Platform -> User "Sends response"

// ✅ Valid - event-driven pattern
ServiceA = system "Service A"
ServiceB = system "Service B"
ServiceA -> ServiceB "Publishes event"
ServiceB -> ServiceA "Publishes response event"

// ✅ Valid - mutual dependencies
PaymentService = system "Payment Service"
OrderService = system "Order Service"
PaymentService -> OrderService "Updates order status"
OrderService -> PaymentService "Requests payment"

view index {
include *
}

The validator will inform you about cycles but won't prevent compilation, as they're often intentional.

Simplicity Guidance

Sruja suggests simpler syntax when appropriate:

Example:

ℹ️  Simplicity suggestion: Consider using 'system' instead of nested 'container'
   Current: system App { container Web { ... } }
   Simpler: system Web { ... }

This is informational only - use the level of detail that matches your modeling goal.

CI/CD Integration

GitHub Actions Example

Add validation to your CI pipeline:

name: Validate Architecture

on: [push, pull_request]

jobs:
  validate:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v6

      - name: Install Sruja
        run: cargo install sruja-cli --git https://github.com/sruja-ai/sruja --locked

      - name: Lint Architecture
        run: |
          sruja lint architecture.sruja

      - name: Export Validation Report
        if: always()
        run: |
          sruja lint --json architecture.sruja > lint-report.json

      - name: Upload Report
        if: always()
        uses: actions/upload-artifact@v3
        with:
          name: lint-report
          path: lint-report.json

GitLab CI Example

validate-architecture:
  image: rust:1.70
  script:
    - cargo install sruja-cli --git https://github.com/sruja-ai/sruja
    - sruja lint architecture.sruja
  only:
    - merge_requests
    - main

Pre-commit Hook

Validate before every commit:

#!/bin/sh
# .git/hooks/pre-commit

sruja lint architecture.sruja
if [ $? -ne 0 ]; then
    echo "❌ Architecture validation failed. Fix errors before committing."
    exit 1
fi

Advanced: Custom Validation Rules

Use constraints and conventions for custom validation:

// partial
import { * } from 'sruja.ai/stdlib'


// Define constraints
constraints {
    "Frontend cannot access databases directly"
}

// Apply conventions
conventions {
    "Layered Architecture: Frontend → API → Database"
}

Platform = system "Platform" {
    Frontend = container "React App"
    API = container "REST API"
    DB = database "PostgreSQL"

    // ✅ Valid
    Frontend -> API "Calls API"
    API -> DB "Reads/Writes"

    // ❌ Will be caught by validator
    // Frontend -> DB "Direct access"  // Violates constraint
}

view index {
include *
}

Real-World Workflow

Step 1: Write Architecture

// partial
import { * } from 'sruja.ai/stdlib'


App = system "App" {
    Web = container "Web"
    DB = datastore "Database"
}

view index {
include *
}

Step 2: Validate

sruja lint architecture.sruja

Step 3: Fix Errors

Address any validation errors or warnings.

Step 4: Commit to CI/CD

Once validation passes locally, commit. CI/CD will validate again.

Step 5: Monitor in Production

Use validation in CI/CD to catch issues before they reach production.

Key Takeaways

  1. Validate early and often: Run sruja lint frequently during development
  2. Fix errors immediately: Don't accumulate validation debt
  3. Integrate with CI/CD: Catch issues before they reach production
  4. Understand cycles: They're often valid patterns, not errors
  5. Use constraints: Enforce architectural standards automatically

Exercise: Fix Validation Errors

Scenario: You have an architecture file with several validation errors.

Tasks:

  1. Run sruja lint on a file
  2. Identify all errors and warnings
  3. Fix each error
  4. Re-validate to confirm fixes

Time: 10 minutes

Further Reading

Export Diagrams

Sruja currently supports export to Mermaid (for Markdown) and interactive visualization in Studio.

Export Formats

1. Mermaid (Markdown)

Export to Mermaid code fences for use in Markdown pages:

sruja export mermaid architecture.sruja > architecture.md

The output includes ```mermaid blocks that render in most Markdown engines with Mermaid enabled.

Use cases:

  • Documentation sites using Markdown
  • Lightweight diagrams without external tooling

2. Studio (Interactive)

Open and preview diagrams interactively in Studio:

Open in Studio from the Learn examples or visit /studio/

Features:

  • Interactive preview and navigation
  • C4 model views (context, containers, components)
  • Embedded documentation and metadata

Use cases:

  • Architecture reviews
  • Presentations
  • Iterative modeling and validation

Mermaid Styling

You can customize Mermaid via frontmatter or exporter configuration. See the Mermaid exporter in crates/sruja-export/src/mermaid/ for options.

Choosing the Right Path

  • Mermaid: For Markdown-first workflows and lightweight sharing
  • Studio: For interactive exploration and richer documentation

Systems Thinking

Systems thinking helps you understand how components interact as part of a whole. Sruja supports five core systems thinking concepts.

1. Parts and Relationships

Systems thinking starts with understanding what the system contains (parts) and how they connect (relationships).

// partial
import { * } from 'sruja.ai/stdlib'


Customer = person "End User"

Shop = system "E-Commerce System" {
WebApp = container "Web Application" {
  technology "React"
}

API = container "API Service" {
  technology "Rust"
}

DB = database "PostgreSQL Database" {
  technology "PostgreSQL 14"
}
}

// Relationships show how parts interact
Customer -> Shop.WebApp "Uses"
Shop.WebApp -> Shop.API "Calls"
Shop.API -> Shop.DB "Reads/Writes"

view index {
include *
}

Key insight: Identify the parts first, then define how they relate.

2. Boundaries

Boundaries define what's inside the system vs. what's outside (the environment).

// partial
import { * } from 'sruja.ai/stdlib'


// Inside boundary: System contains these components
Shop = system "Shop" {
  WebApp = container "Web App"
  API = container "API"
  DB = database "Database"
}

// Outside boundary: External entities
Customer = person "End User"
Admin = person "System Administrator"

PaymentGateway = system "Third-party Payment Service" {
metadata {
  tags ["external"]
}
}

// Relationships cross boundaries
Customer -> Shop.WebApp "Uses"
Shop.API -> PaymentGateway "Processes"

view index {
include *
}

Key insight: Use system to define internal boundaries, person and external for external boundaries.

3. Flows

Flows show how information and data move through the system. Sruja supports two flow styles:

Data Flow Diagram (DFD) Style

Use scenario for data-oriented flows:

// EXPECTED_FAILURE: Layer violation
// SKIP_ORPHAN_CHECK
import { * } from 'sruja.ai/stdlib'


Customer = person "Customer"
Shop = system "Shop" {
  WebApp = container "Web App"
  API = container "API"
  DB = database "Database"
}
PaymentGateway = system "PaymentGateway" {
  tags ["external"]
}

OrderProcess = scenario "Order Processing" {
Customer -> Shop.WebApp "Submits Order"
Shop.WebApp -> Shop.API "Sends Order Data"
Shop.API -> Shop.DB "Saves Order"
Shop.API -> PaymentGateway "Charges Payment"
Shop.API -> Shop.WebApp "Returns Result"
Shop.WebApp -> Customer "Shows Confirmation"
}

view index {
include *
}

User Story/Scenario Style

Use scenario for behavioral flows:

// EXPECTED_FAILURE: Layer violation
import { * } from 'sruja.ai/stdlib'


Customer = person "End User"
ECommerce = system "E-Commerce System" {
CartPage = container "Shopping Cart Page"
WebApp = container "Web Application"
API = container "API Service"
DB = database "Database"
}
PaymentGateway = system "Payment Service" {
metadata {
  tags ["external"]
}
}

Checkout = story "User Checkout Flow" {
Customer -> ECommerce.CartPage "adds items to cart"
ECommerce.CartPage -> ECommerce.WebApp "clicks checkout"
ECommerce.WebApp -> ECommerce.API "validates cart"
ECommerce.API -> ECommerce.DB "checks inventory"
ECommerce.DB -> ECommerce.API "returns stock status"
ECommerce.API -> PaymentGateway "processes payment"
PaymentGateway -> ECommerce.API "confirms payment"
ECommerce.API -> ECommerce.DB "creates order"
ECommerce.API -> ECommerce.WebApp "returns order confirmation"
ECommerce.WebApp -> Customer "displays success message"
}

view index {
include *
}

Key insight: Use flow for data flows (DFD), story/scenario for behavioral flows (BDD).

4. Feedback Loops

Feedback loops show how actions create reactions that affect future actions. Cycles are valid patterns in Sruja.

Simple Feedback Loop

// EXPECTED_FAILURE: Layer violation
person = kind "Person"
system = kind "System"
container = kind "Container"
component = kind "Component"
database = kind "Database"
queue = kind "Queue"

User = person "End User"
App = system "Application" {
WebApp = container "Web Application"
API = container "API Service"
}

// Feedback loop: User action → System response → User reaction
User -> App.WebApp "Submits Form"
App.WebApp -> App.API "Validates"
App.API -> App.WebApp "Returns Validation Result"
App.WebApp -> User "Shows Feedback"
// The feedback affects user's next action (completing the loop)

System Feedback Loop

// partial
import { * } from 'sruja.ai/stdlib'


Admin = person "Administrator"
Shop = system "Shop" {
  API = container "API"
  Inventory = database "Inventory"
}

// Event-driven feedback loop
Shop.API -> Shop.Inventory "Updates Stock"
Shop.Inventory -> Shop.API "Notifies Low Stock"
Shop.API -> Admin "Sends Alert"
Admin -> Shop.API "Adjusts Inventory"
// Creates feedback: API ↔ Inventory ↔ Admin

view index {
include *
}

Key insight: Cycles model natural feedback loops, event-driven patterns, and mutual dependencies. They're valid architectural patterns.

5. Context

Context defines the environment the system operates in - external dependencies, stakeholders, and surrounding systems.

// partial
import { * } from 'sruja.ai/stdlib'


// Internal system
Shop = system "Shop" {
  WebApp = container "Web Application"
  API = container "API Service"
  DB = database "Database"
}

// Context: Stakeholders
Customer = person "End User"
Admin = person "System Administrator"
Support = person "Customer Support"

// Context: External dependencies
PaymentGateway = system "Third-party Payment" {
metadata {
  tags ["external"]
}
}

EmailService = system "Email Notifications" {
metadata {
  tags ["external"]
}
}

AnalyticsService = system "Usage Analytics" {
metadata {
  tags ["external"]
}
}

// Context relationships
Customer -> Shop "Uses"
Admin -> Shop "Manages"
Support -> Shop "Monitors"
Shop -> PaymentGateway "Depends on"
Shop -> EmailService "Sends notifications"
Shop -> AnalyticsService "Tracks usage"

view index {
include *
}

Key insight: Context includes all external entities and dependencies that affect or are affected by your system.

Putting It All Together

Here's a complete example combining all five concepts:

// EXPECTED_FAILURE: Layer violation
person = kind "Person"
system = kind "System"
container = kind "Container"
component = kind "Component"
database = kind "Database"
queue = kind "Queue"

// 1. PARTS AND RELATIONSHIPS
Customer = person "End User"
Admin = person "System Administrator"

ECommerce = system "E-Commerce System" {
WebApp = container "Web Application" {
  technology "React"
}
API = container "API Service" {
  technology "Rust"
}
DB = database "PostgreSQL Database" {
  technology "PostgreSQL 14"
}
}

// 2. BOUNDARIES
PaymentGateway = system "Third-party Payment Service" {
metadata {
  tags ["external"]
}
}

// 3. FLOWS
OrderProcess = scenario "Order Processing" {
Customer -> ECommerce.WebApp "Submits Order"
ECommerce.WebApp -> ECommerce.API "Sends Order Data"
ECommerce.API -> ECommerce.DB "Saves Order"
ECommerce.API -> PaymentGateway "Charges Payment"
ECommerce.API -> ECommerce.WebApp "Returns Result"
ECommerce.WebApp -> Customer "Shows Confirmation"
}

// 4. FEEDBACK LOOPS
Customer -> ECommerce.WebApp "Submits Form"
ECommerce.WebApp -> ECommerce.API "Validates"
ECommerce.API -> ECommerce.WebApp "Returns Validation Result"
ECommerce.WebApp -> Customer "Shows Feedback"

ECommerce.API -> ECommerce.DB "Updates Inventory"
ECommerce.DB -> ECommerce.API "Notifies Low Stock"
ECommerce.API -> Admin "Sends Alert"
Admin -> ECommerce.API "Adjusts Inventory"

// 5. CONTEXT
Support = person "Customer Support"
EmailService = system "Email Notifications" {
metadata {
  tags ["external"]
}
}

Customer -> ECommerce "Uses"
Admin -> ECommerce "Manages"
Support -> ECommerce "Monitors"
ECommerce -> PaymentGateway "Depends on"
ECommerce -> EmailService "Sends notifications"

Why Systems Thinking Matters

  • Holistic understanding: See the whole system, not just parts
  • Natural patterns: Model real-world interactions and feedback
  • Clear boundaries: Understand what's in scope vs. context
  • Flow visualization: See how data and information move
  • Valid cycles: Feedback loops are natural, not errors

Next Steps

  • Try the complete example: book/valid-examples/feedback-loops-basic.sruja and book/valid-examples/causal-loops-basic.sruja
  • Learn Deployment Modeling for infrastructure perspective

Design Mode Workflow

Design Mode helps you build architecture assets step by step, starting with high‑level context and progressively adding detail. It also lets you focus on a specific system or container and share audience‑specific views.

Workflow Steps

Step 1: Context — define person and system

Start with the high-level context:

import { * } from 'sruja.ai/stdlib'


User = person "User"
Shop = system "Shop"

view index {
include *
}

Step 2: Containers — add container, datastore, queue to a chosen system

Add containers and datastores:

// partial
import { * } from 'sruja.ai/stdlib'


User = person "User"
App = system "App" {
WebApp = container "Web Application"
API = container "API Service"
DB = database "Database"
}

User -> App.WebApp "Uses"
App.WebApp -> App.API "Calls"
App.API -> App.DB "Reads/Writes"

view index {
include *
}

Step 3: Components — add component inside a chosen container

Drill down into components:

// partial
import { * } from 'sruja.ai/stdlib'


App = system "App" {
WebApp = container "Web Application" {
  UI = component "User Interface"
}
API = container "API Service" {
  Auth = component "Auth Service"
}
}

// Component‑level interaction
App.WebApp.UI -> App.API.Auth "Calls"

view index {
include *
}

Step 4: Stitch — add relations and optional scenarios; share focused views

Add relations and scenarios to complete the model.

Layers and Focus

  • Levels: L1 Context, L2 Containers, L3 Components, All
  • Focus:
    • L2 focus by systemId
    • L3 focus by systemId.containerId

When focused, non‑relevant nodes/edges are dimmed so you can work deeper without distractions.

Viewer opens focused views via URL params:

  • ?level=1 → Context
  • ?level=2&focus=Shop → Containers of system Shop
  • ?level=3&focus=Shop.API → Components in container API of system Shop
  • DSL payload is passed with #code=<lz-base64> or ?code=<urlencoded>.

Studio Experience

  • Diagram‑first: Studio opens with the diagram; a Design Mode overlay guides steps
  • Contextual palette: add containers at L2 (focused system), components at L3 (focused container)
  • Autosave on close: resume drafts; share per‑layer links from the toolbar

Viewer Experience

  • Use level buttons and focus to tailor the view
  • Dimming clarifies what's relevant at each depth
  • Share via copied URL (includes level, focus, and DSL)

See Also

Demo Script: Quick 10-Minute Walkthrough

This tutorial provides a quick 10-minute walkthrough to demonstrate Sruja's core capabilities: modeling, validation, and export.

1) Model (2 minutes)

Create a simple e-commerce architecture:

// partial
import { * } from 'sruja.ai/stdlib'


User = person "User"
Shop = system "Shop" {
  WebApp = container "Web App"
  API = container "API"
  DB = datastore "Database"
}

User -> Shop.WebApp "Uses"
Shop.WebApp -> Shop.API "Calls"
Shop.API -> Shop.DB "Reads/Writes"

view index {
include *
}

2) Validate (2 minutes)

Format and validate your model:

sruja fmt architecture.sruja
sruja lint architecture.sruja

3) Add Targets (3 minutes)

Add SLOs and scaling configuration:

// partial
import { * } from 'sruja.ai/stdlib'


Shop = system "Shop" {
API = container "API" {
  scale {
    metric "req/s"
    min 200
    max 2000
  }

  slo {
    availability {
      target "99.9%"
      window "30 days"
    }
    latency {
      p95 "200ms"
      window "7 days"
    }
    errorRate {
      target "< 0.1%"
      window "30 days"
    }
  }
}
}

view index {
include *
}

4) Export (3 minutes)

Export to various formats:

sruja export markdown architecture.sruja
sruja export mermaid architecture.sruja
sruja export mermaid architecture.sruja

Outcome: Living docs and diagrams generated from the model.


Note: Sruja is free and open source (Apache 2.0 licensed). Need help with adoption? Professional consulting services are available. Contact the team through GitHub Discussions to learn more.

Deployment Modeling

Model production environments and map containers onto infrastructure nodes.

// partial
import { * } from 'sruja.ai/stdlib'


WebServer = container "Nginx"
AppServer = container "Python App"
Database = database "Postgres"


deployment Production "Production" {
  node AWS "AWS" {
    node USEast1 "US-East-1" {
      node EC2 "EC2 Instance" {
        containerInstance WebServer
        containerInstance AppServer
      }
      node RDS "RDS" {
        containerInstance Database
      }
    }
  }
}

view index {
include *
}

CI/CD Integration

Integrate Sruja into your CI/CD pipeline to automatically validate architecture, enforce standards, and generate documentation on every commit.

Why CI/CD Integration?

For DevOps teams:

  • Catch architecture violations before they reach production
  • Automate documentation generation
  • Enforce architectural standards across teams
  • Reduce manual review overhead

For software architects:

  • Ensure architectural decisions are documented
  • Prevent architectural drift
  • Scale governance across multiple teams

For product teams:

  • Keep architecture docs up-to-date automatically
  • Track architecture changes over time
  • Ensure compliance with requirements

Real-World Scenario

Challenge: A team of 50 engineers across 10 microservices. Architecture documentation is outdated, and violations happen frequently.

Solution: Integrate Sruja validation into CI/CD to:

  • Validate architecture on every PR
  • Generate updated documentation automatically
  • Block merges if constraints are violated
  • Track architecture changes over time

GitHub Actions Integration

Sruja’s CLI is written in Rust. In CI you can either build from source in this repo or install from the Git repo with cargo install. A reusable composite action is available in the Sruja repo for building and validating.

Using the Sruja repo reusable action (this repository)

If your workflow runs inside the sruja repo, use the composite action so the CLI is built once and lint/export run on your files:

- uses: actions/checkout@v6
- uses: ./.github/actions/sruja-validate
  with:
    working-directory: .
    files: "book/valid-examples/**/*.sruja" # or '**/*.sruja'
    run-export: "false"

Basic setup (any repository)

Install the CLI from the Sruja Git repo with Cargo, then run sruja lint and sruja export:

name: Architecture Validation

on:
  push:
    branches: [main, develop]
  pull_request:
    branches: [main, develop]

jobs:
  validate-architecture:
    runs-on: ubuntu-latest
    steps:
      - name: Checkout code
        uses: actions/checkout@v6

      - name: Install Rust
        uses: dtolnay/rust-toolchain@stable
      - name: Install Sruja CLI
        run: cargo install sruja-cli --git https://github.com/sruja-ai/sruja

      - name: Validate Architecture
        run: sruja lint architecture.sruja

      - name: Export Documentation
        run: |
          sruja export markdown architecture.sruja > architecture.md
          sruja export json architecture.sruja > architecture.json

      - name: Upload Artifacts
        uses: actions/upload-artifact@v3
        with:
          name: architecture-docs
          path: |
            architecture.md
            architecture.json

Advanced: Enforce Constraints

name: Architecture Governance

on: [pull_request]

jobs:
  enforce-architecture:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v6
        with:
          fetch-depth: 0 # Full history for diff

      - name: Install Rust
        uses: dtolnay/rust-toolchain@stable
      - name: Install Sruja CLI
        run: cargo install sruja-cli --git https://github.com/sruja-ai/sruja

      - name: Validate Architecture
        id: validate
        run: |
          sruja lint architecture.sruja > lint-output.txt 2>&1
          exit_code=$?
          echo "exit_code=$exit_code" >> $GITHUB_OUTPUT
          cat lint-output.txt

      - name: Check for Constraint Violations
        if: steps.validate.outputs.exit_code != 0
        run: |
          echo "❌ Architecture validation failed!"
          echo "Please fix the errors before merging."
          exit 1

      - name: Comment PR with Validation Results
        if: always()
        uses: actions/github-script@v6
        with:
          script: |
            const fs = require('fs');
            const lintOutput = fs.readFileSync('lint-output.txt', 'utf8');
            github.rest.issues.createComment({
              issue_number: context.issue.number,
              owner: context.repo.owner,
              repo: context.repo.repo,
              body: `## Architecture Validation Results\n\n\`\`\`\n${lintOutput}\n\`\`\``
            });

Multi-Architecture Validation

For monorepos with multiple architecture files:

name: Validate All Architectures

on: [push, pull_request]

jobs:
  validate-all:
    runs-on: ubuntu-latest
    strategy:
      matrix:
        architecture:
          - architecture.sruja
          - services/payment-service.sruja
          - services/order-service.sruja
          - services/user-service.sruja
    steps:
      - uses: actions/checkout@v6

      - name: Install Rust
        uses: dtolnay/rust-toolchain@stable
      - name: Install Sruja CLI
        run: cargo install sruja-cli --git https://github.com/sruja-ai/sruja

      - name: Validate ${{ matrix.architecture }}
        run: sruja lint ${{ matrix.architecture }}

GitLab CI Integration

stages:
  - validate

validate-architecture:
  stage: validate
  image: rust:1.70
  before_script:
    - cargo install sruja-cli --git https://github.com/sruja-ai/sruja
  script:
    - sruja lint architecture.sruja
    - sruja export markdown architecture.sruja > architecture.md
    - sruja export json architecture.sruja > architecture.json
  artifacts:
    paths:
      - architecture.md
      - architecture.json
    expire_in: 30 days
  only:
    - merge_requests
    - main

Jenkins Integration

pipeline {
    agent any

    stages {
        stage('Install Sruja CLI') {
            steps {
                sh 'cargo install sruja-cli --git https://github.com/sruja-ai/sruja'
            }
        }
        stage('Validate Architecture') {
            steps {
                sh 'sruja lint architecture.sruja'
            }
        }

        stage('Generate Documentation') {
            steps {
                sh '''
                    sruja export markdown architecture.sruja > architecture.md
                    sruja export json architecture.sruja > architecture.json
                '''
            }
        }

        stage('Archive Documentation') {
            steps {
                archiveArtifacts artifacts: 'architecture.*', fingerprint: true
            }
        }
    }

    post {
        failure {
            emailext (
                subject: "Architecture Validation Failed: ${env.JOB_NAME} - ${env.BUILD_NUMBER}",
                body: "Architecture validation failed. Please check the build logs.",
                to: "${env.CHANGE_AUTHOR_EMAIL}"
            )
        }
    }
}

CircleCI Integration

version: 2.1

jobs:
  validate-architecture:
    docker:
      - image: rust:1.70
    steps:
      - checkout
      - run:
          name: Install Sruja CLI
          command: cargo install sruja-cli --git https://github.com/sruja-ai/sruja
      - run:
          name: Validate
          command: sruja lint architecture.sruja
      - run:
          name: Generate Docs
          command: sruja export markdown architecture.sruja > architecture.md
      - store_artifacts:
          path: architecture.md

workflows:
  version: 2
  validate:
    jobs:
      - validate-architecture

Pre-commit Hooks

Validate before every commit locally. Ensure the Sruja CLI is on your PATH (e.g. cargo install sruja-cli --git https://github.com/sruja-ai/sruja or build from the Sruja repo):

#!/bin/sh
# .git/hooks/pre-commit

if ! command -v sruja &> /dev/null; then
    echo "Sruja CLI not found. Install with: cargo install sruja-cli --git https://github.com/sruja-ai/sruja"
    exit 1
fi

sruja lint architecture.sruja
if [ $? -ne 0 ]; then
    echo "❌ Architecture validation failed. Fix errors before committing."
    exit 1
fi

sruja fmt architecture.sruja > architecture.formatted.sruja
mv architecture.formatted.sruja architecture.sruja
git add architecture.sruja

exit 0

Or use the pre-commit framework (requires Sruja on PATH):

# .pre-commit-config.yaml
repos:
  - repo: local
    hooks:
      - id: sruja-lint
        name: Sruja Lint
        entry: sruja lint
        language: system
        files: \.sruja$
        pass_filenames: true

Automated Documentation Updates

Generate and commit documentation automatically:

name: Update Architecture Docs

on:
  push:
    branches: [main]
    paths:
      - "architecture.sruja"

jobs:
  update-docs:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v6
        with:
          token: ${{ secrets.GITHUB_TOKEN }}

      - name: Install Rust
        uses: dtolnay/rust-toolchain@stable
      - name: Install Sruja CLI
        run: cargo install sruja-cli --git https://github.com/sruja-ai/sruja

      - name: Generate Documentation
        run: |
          sruja export markdown architecture.sruja > docs/architecture.md
          sruja export json architecture.sruja > docs/architecture.json

      - name: Commit Changes
        run: |
          git config user.name "github-actions[bot]"
          git config user.email "github-actions[bot]@users.noreply.github.com"
          git add docs/architecture.*
          git diff --staged --quiet || git commit -m "docs: update architecture documentation"
          git push

Architecture Change Tracking

Track architecture changes over time:

name: Track Architecture Changes

on:
  pull_request:
    paths:
      - "architecture.sruja"

jobs:
  track-changes:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v6
        with:
          fetch-depth: 0

      - name: Install Rust
        uses: dtolnay/rust-toolchain@stable
      - name: Install Sruja CLI
        run: cargo install sruja-cli --git https://github.com/sruja-ai/sruja

      - name: Compare Architectures
        run: |
          git show origin/${{ github.base_ref }}:architecture.sruja > base.sruja
          sruja export json base.sruja > base.json
          sruja export json architecture.sruja > current.json
          echo "## Architecture Changes" >> $GITHUB_STEP_SUMMARY
          echo "Comparing base and current architecture..." >> $GITHUB_STEP_SUMMARY

      - name: Comment Changes
        uses: actions/github-script@v6
        with:
          script: |
            github.rest.issues.createComment({
              issue_number: context.issue.number,
              owner: context.repo.owner,
              repo: context.repo.repo,
              body: '## Architecture Changes Detected\n\nReview the architecture changes in this PR.'
            });

Real-World Example: Microservices Platform

Complete CI/CD setup for a microservices platform:

name: Architecture Governance

on:
  push:
    branches: [main, develop]
  pull_request:
    branches: [main, develop]

jobs:
  validate-architecture:
    runs-on: ubuntu-latest
    strategy:
      matrix:
        service:
          - payment-service
          - order-service
          - user-service
          - inventory-service
    steps:
      - uses: actions/checkout@v6

      - name: Install Rust
        uses: dtolnay/rust-toolchain@stable
      - name: Install Sruja CLI
        run: cargo install sruja-cli --git https://github.com/sruja-ai/sruja

      - name: Validate ${{ matrix.service }}
        run: sruja lint services/${{ matrix.service }}/architecture.sruja

      - name: Generate Service Docs
        run: sruja export markdown services/${{ matrix.service }}/architecture.sruja > docs/services/${{ matrix.service }}.md

  validate-platform:
    runs-on: ubuntu-latest
    needs: validate-architecture
    steps:
      - uses: actions/checkout@v6

      - name: Install Rust
        uses: dtolnay/rust-toolchain@stable
      - name: Install Sruja CLI
        run: cargo install sruja-cli --git https://github.com/sruja-ai/sruja

      - name: Validate Platform Architecture
        run: sruja lint platform-architecture.sruja

      - name: Generate Platform Docs
        run: |
          sruja export markdown platform-architecture.sruja > docs/platform.md
          sruja export json platform-architecture.sruja > docs/platform.json

      - name: Upload Documentation
        uses: actions/upload-artifact@v3
        with:
          name: architecture-docs
          path: docs/

Key Takeaways

  1. Automate everything: Don't rely on manual validation
  2. Fail fast: Block merges if constraints are violated
  3. Generate docs automatically: Keep documentation up-to-date
  4. Track changes: Monitor architecture evolution over time
  5. Scale governance: Use CI/CD to enforce standards across teams

Exercise: Set Up CI/CD Integration

Tasks:

  1. Choose a CI/CD platform (GitHub Actions, GitLab CI, etc.)
  2. Create a workflow that validates architecture on every PR
  3. Add documentation generation
  4. Test the workflow with a sample architecture file

Time: 20 minutes

Further Reading

Agentic AI Modeling

This tutorial shows how to model agent-based systems with orchestrators, planners, executors, tools, and memory.

Core Structure

// partial
import { * } from 'sruja.ai/stdlib'


AgentSystem = system "Agentic System" {
Orchestrator = container "Agent Orchestrator"
Planner = container "Planner"
Executor = container "Executor"
Tools = container "Tooling API"
Memory = database "Long-Term Memory"
}

User = person "User"

User -> AgentSystem.Orchestrator "Requests task"
AgentSystem.Orchestrator -> AgentSystem.Planner "Plans steps"
AgentSystem.Orchestrator -> AgentSystem.Executor "Delegates execution"
AgentSystem.Executor -> AgentSystem.Tools "Calls tools"
AgentSystem.Executor -> AgentSystem.Memory "Updates state"

view index {
include *
}

Add Governance

Guardrails = policy "Safety Policies" {
  description "Limit tool calls, enforce approvals, track risky operations"
}

R1 = requirement functional "Explain actions"
R2 = requirement constraint "No PII exfiltration"

Integrate RAG

// partial
import { * } from 'sruja.ai/stdlib'


AgentSystem = system "Agent System" {
  Executor = container "Executor"
}

RAG = system "Retrieval-Augmented Generation" {
  Retriever = container "Retriever"
  Generator = container "Generator"
  VectorDB = database "VectorDB"
}

AgentSystem.Executor -> RAG.Retriever "Fetch contexts"
RAG.Retriever -> RAG.VectorDB "Search"
RAG.Generator -> AgentSystem.Executor "Produce answer"

Grounded harness (operational loop)

DSL models describe what you build; Sruja’s CLI enforces whether architecture matches code. For lint/drift loops, local --enrich-cmd inference, and host-owned continual learning, see Grounded harness and continual learning.

Next Steps

  • Explore book/valid-examples/pattern-agentic-ai.sruja and book/valid-examples/pattern-rag-pipeline.sruja
  • Add scenarios to capture common workflows
  • Use views to present developer vs. executive perspectives

Extending the CLI (Rust)

Sruja's CLI lives in crates/sruja-cli and uses clap for argument parsing. To add or change subcommands:

  1. Open crates/sruja-cli/src/main.rs (or the relevant module) and see how existing commands (e.g. lint, export) are defined.
  2. Add a subcommand using clap's Subcommand enum and match on it in the main entrypoint; run your logic and return Result with ? for errors.
  3. Run and test with cargo run -p sruja-cli -- <subcommand> ....

Shell completions are available:

sruja completion bash
sruja completion zsh
sruja completion fish

For patterns and conventions, see the repo's AGENTS.md (Rust skills) and docs/CODING_GUIDELINES.md.

Optional Learning

Long-form learning material for people who want extra background or structured study time. This is optional and not required to adopt Sruja's core workflow.

CourseDescription
Systems Thinking 101Fundamentals, parts & relationships, boundaries, flows, feedback loops, context
System Design 101Fundamentals, building blocks, advanced modeling, production readiness
System Design 201High throughput, real-time, data-intensive, consistency
Ecommerce PlatformVision, architecture, SDLC, ops, evolution, governance
Production ArchitecturePerformance, modular design, governance
Agentic AIFundamentals, patterns, modeling for AI systems
Advanced ArchitectsPolicy as code and advanced topics

If you're evaluating or adopting Sruja, start with Quick start and the core docs first. Come back here only when you want deeper study material.

Challenges

Hands-on exercises to practice Sruja. Each challenge has a goal and optional hints.

ChallengeFocus
Add ComponentAdd a component to a system
Deployment ArchitectureModel deployment
External ServiceIntegrate an external system
Fix RelationsCorrect relation definitions
Missing RelationsFind and add missing relations
Queue WorkerModel a queue-based flow
Syntax ErrorFix a syntax error

See the Beginner path for a suggested order with tutorials and courses.

Add Component

Deployment Architecture

External Service

Fix Relations

Missing Relations

Queue Worker

Syntax Error

CLI reference

Which command?

Onboarding & setup

User questionCommandOutput
"What is this repo?"sruja quickstart -r .Structural overview, scan findings, optional baseline
"Give me a complete architecture brief"sruja onboard -r .Full repo brief with trust signals
"I'm about to work on X"sruja ai -r . --task "..."Paste-ready AI coding brief
"Set me up"sruja init -r ..sruja/, .srujaignore, optional prompt

See feature tightening for canonical workflow paths

Health & status

User questionCommandOutput
"Is my repo.sruja current?"sruja status -r .Truth freshness + baseline state
"Is my repo.sruja current?" (alias)sruja doctor -r .Same as status
"Are there structural problems?"sruja health -r .Architecture health score (0-100) from violations
"Can AI work effectively here?"sruja context-score -r .AI-readiness score (0-100)
"What should I do today?"sruja review -r .Action list from evidence refresh (daily alias)

Retrieval ladder

StepCommandWhen to use
1. Before starting a tasksruja focus -r . --file <path>Blast radius, decisions, AI instructions
2. Paste-ready AI briefsruja ai -r . --task "..."Share context with AI assistant
3. Inside AI editor (MCP)MCP toolsCursor, Copilot, Claude integration
4. Investigationsruja why "..." / sruja query "...""Why is this like this?"

Discover vs onboarding

NeedCommand
Scanner explain / repomap / question bank for AI or debuggingsruja discover …
First human read of the reposruja quickstart -r .
Full architecture briefsruja onboard -r .

Stable commands

CommandDescription
sruja quickstart -r .First look: structural overview and baseline generation
sruja onboard -r .Single onboarding brief (deterministic; optional LLM enrichment with --enrich)
sruja lint <file>Validate .sruja file
sruja sync -r .Refresh evidence and cached graph/context
sruja status -r .Truth freshness and baseline state
sruja review -r .Review workflow: refresh evidence, detect drift, summarize
sruja drift -r . -a repo.srujaDeclared vs actual structure
sruja health -r .Architecture health score from violations
sruja context-score -r .AI-readiness score (0-100)
sruja publish -r .Export repo bundle for federation
sruja compose -i <bundle.json> -o system.index.jsonCompose bundles into a system index

Other commands

CommandDescription
sruja export json <file>Export to JSON
sruja export markdown <file>Export to Markdown
sruja export mermaid <file>Export to Mermaid
sruja fmt <file>Format DSL
sruja tree <file>Print element tree
sruja watch -r .Keep feedback live while coding
sruja doctor -r .Alias for status
sruja drift --ci -r .CI drift check (GitHub Actions annotations)
sruja baseline -r .Snapshot violations for baseline ignore in CI
sruja ai -r . --task "..."Paste-ready AI coding brief (optional --enrich / --enrich-cmd)
sruja focus -r . --file <path>Context briefing before starting work
sruja why "..."Investigate architecture decisions
sruja query "..."Query registry for elements and relationships
sruja ai-context -r .Structured context for AI editor integration
sruja ai-context -r . -f for-ai --cache-friendlyPrompt-cache-friendly JSON (invariant → tools → volatile; single repo)

Repo root: Prefer -r / --repo for the repository directory. Some commands also accept --path as an alias for backwards compatibility.

JSON output: metric hints

When -f json (or the command’s JSON mode) is used, some commands add stable metric_type and metric_description fields so parsers and dashboards do not confuse different scores:

Commandmetric_typeRole
sruja status -f jsontruth_freshnessBaseline / sync / truth status (not structural health alone)
sruja health -f jsonstructural_healthViolations vs declared repo.sruja (0–100)
sruja context-score -f jsonai_readinessAI preparedness (0–100)
sruja learn -f json(see artifact_kind)artifact_kind is learned_hypothesis — not reviewed DSL truth

Aliases

  • start = init (setup only)
  • daily = review
  • overview = quickstart
  • doctor = status

Feature Tightening (Phase T)

As part of feature tightening (Phase T), Sruja provides canonical paths for core workflows to reduce toolbox feeling:

WorkflowCanonical CommandDeprecated Alternatives
Onboardingsruja onboarddiscover explain
Health Checksruja status / doctorhealth
Retrievalsruja focus / MCP focus briefingget_architecture_context, get_hydrated_context
Drift Gatesruja drift, sruja drift-prdeprecated check

MCP tool profiles (minimal, coding, arch, full) control which tools are available via MCP. The default coding profile provides 15 tools focused on coding workflows.

Run sruja --help for full options.

Language reference

The Sruja DSL defines architecture using kinds (e.g. person, system, container) and relationships (e.g. ->).

For the full specification, see the Language specification in this book.

Sruja Language Specification

This document provides a complete specification of the Sruja architecture-as-code language for AI code assistants and developers.

Overview

Sruja is a domain-specific language (DSL) for defining software architecture models. It supports C4 model concepts (systems, containers, components), requirements, ADRs, scenarios, flows, policies, SLOs, and more.

Language Grammar

File Structure

Sruja uses a nested syntax that follows the C4 model hierarchy:

  • Systems are defined at the top level
  • Containers must be nested inside a system
  • Components must be nested inside a container
  • Persons can be defined at the top level (external actors)
// partial
// Element kinds (required at top of file)
person = kind "Person"
system = kind "System"
container = kind "Container"
component = kind "Component"

// External actors (top level)
User = person "User" {
  description "End user of the system"
}

// System with nested containers
Shop = system "E-commerce Shop" {
  description "Online shopping platform"

  // Containers MUST be nested inside systems
  WebApp = container "Web Application" {
    technology "React"
    description "Customer-facing web app"

    // Components MUST be nested inside containers
    Cart = component "Shopping Cart" {
      description "Shopping cart functionality"
    }
  }

  API = container "API Gateway" {
    technology "Node.js"
    description "API gateway"
  }

  DB = database "Product Database" {
    technology "PostgreSQL"
    description "Product catalog storage"
  }
}

// Relationships between nested elements use dot notation
User -> Shop.WebApp "Browses"
Shop.WebApp -> Shop.API "Calls"
Shop.API -> Shop.DB "Reads/Writes"

// Governance (top level)
R1 = requirement functional "Must handle 10k users"
SecurityPolicy = policy "Encrypt all data" category "security"

Element Kinds

Before using elements like person, system, container, etc., you must declare them as kinds. This establishes the vocabulary of element types available in your architecture.

// Standard C4 kinds (required at top of file)
person = kind "Person"
system = kind "System"
container = kind "Container"
component = kind "Component"
database = kind "Database"
datastore = kind "Datastore"  // Alias for 'database', but 'database' is the preferred standard
queue = kind "Queue"

Why kinds? This allows Sruja to:

  • Validate that you're using recognized element types
  • Enable custom element types for domain-specific modeling
  • Provide LSP autocompletion for your declared kinds

Custom Kinds

You can define custom element types for your domain:

// partial
// Custom kinds for microservices
microservice = kind "Microservice"
eventBus = kind "Event Bus"
gateway = kind "API Gateway"

// Now use them
Catalog = microservice "Catalog Service"
Kafka = eventBus "Kafka Cluster"

Schemas

Schemas allow you to define strict custom metamodels, specifying valid node kinds, edge kinds, and nesting rules for validation.

schema "compliance" {
  node_kinds: ["regulation", "policy", "system"]
  edge_kinds: ["mandates", "violates"]
  nesting {
    regulation -> policy
    system -> policy
  }
}

Imports

Import kinds and tags from the standard library or other Sruja files.

Standard Library Import

// Import all from stdlib
import { * } from 'sruja.ai/stdlib'

// Now you can use person, system, container, etc. without defining them
User = person "User"
Shop = system "Shop"

Named Imports

// Import specific kinds only
import { person, system, container } from 'sruja.ai/stdlib'

User = person "User"
Shop = system "Shop"

Relative Imports

// Import from a local file
import { * } from './shared-kinds.sruja'

Note: When using imports, you don't need to redeclare the imported kinds.

Elements

Persons

User = person "User" {
    description "End user of the system"
}

Systems

MySystem = system "My System" {
    description "Optional description"
    metadata {
        key "value"
        tags ["tag1", "tag2"]
    }
    slo {
        availability {
            target "99.9%"
            window "30d"
            current "99.95%"
        }
    }
}

Containers

// partial
MyContainer = container "My Container" {
    technology "Technology stack"
    description "Optional description"
    version "1.0.0"
    tags ["api", "backend"]
    scale {
        min 3
        max 10
        metric "cpu > 80%"
    }
    slo {
        latency {
            p95 "200ms"
            p99 "500ms"
        }
    }
}

Components

// partial
MyComponent = component "My Component" {
    technology "Technology"
    description "Optional description"
    scale {
        min 1
        max 5
    }
}

Data Stores

// partial
MyDB = database "My Database" {
    technology "PostgreSQL"
    description "Optional description"
}

Queues

// partial
MyQueue = queue "My Queue" {
    technology "RabbitMQ"
    description "Optional description"
}

Architecture Index Fields

Sruja can serve as an architecture index — linking architecture elements to external resources like OpenAPI specs, Kubernetes manifests, documentation, and more. This enables AI agents to discover and navigate complex software ecosystems.

All element types (person, system, container, component, database, queue) support these optional fields in their body block:

FieldTypeDescription
canonical_idstringUnique, stable identifier for cross-system reference (e.g., svc.payments, db.primary)
aliasesstring[]Alternative names used in code, configs, or documentation
ownerstringTeam or individual responsible for this element
domainstringBusiness domain (e.g., commerce, auth, platform)
criticalityenumImportance level: low, medium, high, critical
sourcesblockLinks to external resources (specs, configs, docs)

Source Types

TypeDescriptionExample
openapiOpenAPI/Swagger specification./specs/api.yaml
asyncapiAsyncAPI specification./specs/events.yaml
kubernetesKubernetes manifests directory./k8s/payments/
terraformTerraform/IaC configuration./infra/database/
docsDocumentation file./docs/services/payments.md
readmeREADME or guide./services/payments/README.md
urlExternal URLhttps://stripe.com/docs/api
// partial
Payments = container "Payment Service" {
    technology "Node.js"
    description "Handles payment processing with Stripe integration"

    // Architecture index fields
    canonical_id "svc.payments"
    aliases ["payments-api", "payments-service", "PAYMENTS_SVC"]
    owner "team-payments"
    domain "commerce"
    criticality "high"

    sources {
        openapi "./specs/payments.yaml"
        kubernetes "./k8s/payments/"
        readme "./services/payments/README.md"
        docs "./docs/services/payments.md"
    }
}
// partial
StripeAPI = system "Stripe Payment API" {
    description "Third-party payment processing"
    canonical_id "ext.stripe"
    owner "team-payments"

    sources {
        docs url "https://stripe.com/docs/api"
    }
}

Relationships

// partial
// Basic relationship
From -> To "Label"

// Nested element references use dot notation
System.Container -> System.Container.Component "calls"

// With tags
From -> To "Label" [tag1, tag2]

Requirements

// Minimal
R1 = requirement functional "Description"
R2 = requirement nonfunctional "Description"
R3 = requirement constraint "Description"
R4 = requirement performance "Description"
R5 = requirement security "Description"

// Enriched with PRD-aligned fields
R6 = requirement functional "User can checkout" {
    description "Detailed description"
    priority "must"                    // MoSCoW: must | should | could | wont
    status "accepted"                  // proposed | accepted | deprecated | superseded
    user_journey "Narrative of the user's path through the feature"
    acceptance_criteria {
        given "Precondition"
        when "User action"
        then "Expected outcome"
    }
    scenario CheckoutFlow              // Link to scenario element
    adr ADR001                         // Link to ADR element
    affects System.Container.Component // Link to architecture elements
    source "prd://checkout-prd"        // Cross-repo PRD reference
    tags ["checkout", "critical"]
}

Requirements support MoSCoW priority, acceptance criteria (Given-When-Then), and traceability links to scenarios, ADRs, and architecture elements. The source field enables cross-repo PRD linking — multiple repos can reference the same central PRD.

ADRs (Architectural Decision Records)

ADR001 = adr "Title" {
    status "accepted"
    context "What situation led to this decision"
    decision "What was decided"
    consequences "Trade-offs, gains, and losses"
}

Scenarios and Flows

Scenarios

// partial
MyScenario = scenario "Scenario Title" {
    step User -> System.WebApp "Credentials"
    step System.WebApp -> System.DB "Verify"
}

// 'story' is an alias for 'scenario'
CheckoutStory = story "User Checkout Flow" {
    step User -> ECommerce.CartPage "adds item to cart"
}

Note: The step keyword is recommended for clarity, but optional. Both syntaxes work:

  • With step: step User -> System.WebApp "action"
  • Without step: User -> System.WebApp "action" (inside scenario block)

Flows (DFD-style data flows)

// partial
OrderProcess = flow "Order Processing" {
    step Customer -> Shop.WebApp "Order Details"
    step Shop.WebApp -> Shop.Database "Save Order"
    step Shop.Database -> Shop.WebApp "Confirmation"
}

Note: Flows use the same syntax as scenarios. The step keyword is recommended for clarity.

Metadata

metadata {
    key "value"
    anotherKey "another value"
    tags ["tag1", "tag2"]
}

Overview Block

overview {
    summary "High-level summary of the architecture"
    audience "Target audience for this architecture"
    scope "What is covered in this architecture"
    goals ["Goal 1", "Goal 2"]
    nonGoals ["What is explicitly out of scope"]
    risks ["Risk 1", "Risk 2"]
}

SLO (Service Level Objectives)

// partial
slo {
    availability {
        target "99.9%"
        window "30 days"
        current "99.95%"
    }
    latency {
        p95 "200ms"
        p99 "500ms"
        window "7 days"
        current {
            p95 "180ms"
            p99 "420ms"
        }
    }
    errorRate {
        target "0.1%"
        window "7 days"
        current "0.08%"
    }
    throughput {
        target "10000 req/s"
        window "peak hour"
        current "8500 req/s"
    }
}

SLO blocks can be defined at:

  • Architecture level (top-level)
  • System level
  • Container level

Scale Block

// partial
scale {
    min 3
    max 10
    metric "cpu > 80%"
}

Scale blocks can be defined at:

  • Container level
  • Component level

Deployment

deployment Prod "Production" {
    node AWS "AWS" {
        node USEast1 "US-East-1" {
            infrastructure LB "Load Balancer"
            containerInstance Shop.API
        }
    }
}

API Contracts

API Contracts allow you to model precise request-response specifications, input/output structures, error conditions, and constraints.

// partial
contract "GetUserContract" {
  description "Fetch user details by ID"
  input {
    userId "string"
  }
  output {
    email "string"
    isActive "boolean"
  }
  error {
    "404" "User not found"
    "401" "Unauthorized access"
  }
  constraint "Response time must be < 50ms"
}

State Machines

State Machines let you model component lifecycles, states, and transition behaviors based on events, actions, and guards.

// partial
state_machine "OrderLifecycle" {
  description "Order lifecycle state machine"
  initial "Created"
  terminal ["Completed", "Cancelled"]

  "Created" -> "Processing" on "payment_received" {
    guard "payment.amount > 0"
    action "send_receipt()"
    description "Transition order to processing after successful payment"
  }
  "Processing" -> "Completed" on "shipment_delivered"
}

Systems Thinking Loops

Sruja supports causal loop diagrams and feedback loops to model complex system dynamics, reinforcing/balancing feedback loops, polarities, and delays.

Feedback Loops

// partial
UserLoop = feedback "User Growth" {
  loop_type "reinforcing"
  loop_id "R1"
  description "Growth in users leads to more word-of-mouth referrals"
  
  UserBase -> Referrals "increases"
  Referrals -> UserBase "leads to"
}

Causal Loops

// partial
InventoryLoop = causal_loop "Supply & Demand" {
  loop_type "balancing"
  loop_id "B1"
  
  variable Demand "Customer Demand"
  variable Price "Product Price"
  
  Demand -> Price {
    effect "increases"
    polarity "+"
  }
  Price -> Demand {
    effect "decreases"
    polarity "-"
    delay "2 days"
  }
}

Governance

Policies

// partial
// Two equivalent forms:
SecurityPolicy = policy "Enforce TLS 1.3" {
    category "security"
    enforcement "required"
}

policy SecurityPolicy "Enforce TLS 1.3" category "security" enforcement "required"

// Or with body block (and optional structured rules)
policy DataRetentionPolicy "Retain data for 7 years" {
    category "compliance"
    enforcement "required"
    description "Detailed policy description"
}

policy NoExtToDb "External APIs must not call databases" {
    category "security"
    enforcement "required"
    rule deny edge from { kind "external_api" } to { kind "database" }
}

Constraints

constraints {
    "Constraint description"
    "Another constraint"
}

Conventions

conventions {
    "Convention description"
    "Another convention"
}

Incidents

Incidents allow you to track production outages, capture post-mortems, and link them directly to affected architecture components.

// partial
incident INC001 "API Gateway Outage" {
  date "2026-05-01"
  severity "high"
  affected [Shop.API]
  cause "Memory leak under high load"
  resolution "Restarted cluster and updated memory limits"
  lesson "Implement auto-scaling based on memory thresholds"
}

Views (Optional)

Views are optional — if not specified, standard C4 views are automatically generated.

// partial
view index {
    title "System Context"
    include *
}

view container_view of Shop {
    title "Shop Containers"
    include Shop.*
    exclude Shop.WebApp
    autolayout lr
}

styles {
    element "Database" {
        shape "cylinder"
        color "#ff0000"
    }
}

View Types

  • index - System context view (C4 L1)
  • container - Container view (C4 L2)
  • component - Component view (C4 L3)
  • deployment - Deployment view

View Expressions

  • include * - Include all elements in scope
  • include Element1 Element2 - Include specific elements
  • exclude Element1 - Exclude specific elements
  • autolayout "lr"|"tb"|"auto" - Layout direction hint

Implied Relationships

Relationships are automatically inferred when child relationships exist:

// partial
User -> API.WebApp "Uses"
// Automatically infers: User -> API

This reduces boilerplate while maintaining clarity.

Complete Example

// partial
// Element Kinds (required)
person = kind "Person"
system = kind "System"
container = kind "Container"
component = kind "Component"
datastore = kind "Datastore"  // Alias for 'database'

// Overview
overview {
    summary "E-commerce platform architecture"
    audience "Development team"
    scope "Core shopping and payment functionality"
}

// Elements
Customer = person "Customer"
Admin = person "Administrator"

Shop = system "E-commerce Shop" {
    description "High-performance e-commerce platform"

    WebApp = container "Web Application" {
        technology "React"
        Cart = component "Shopping Cart"
        Checkout = component "Checkout Service"
    }

    API = container "API Gateway" {
        technology "Node.js"
        scale {
            min 3
            max 10
        }
        slo {
            latency {
                p95 "200ms"
                p99 "500ms"
            }
        }
    }

    DB = database "PostgreSQL Database" {
        technology "PostgreSQL 14"
    }
}

// Relationships
Customer -> Shop.WebApp "Browses"
Shop.WebApp -> Shop.API "Calls"
Shop.API -> Shop.DB "Reads/Writes"

// Requirements
R1 = requirement functional "Must support 10k concurrent users"
R2 = requirement constraint "Must use PostgreSQL"

// ADRs
ADR001 = adr "Use microservices architecture" {
    status "accepted"
    context "Need to scale different parts independently"
    decision "Adopt microservices architecture"
    consequences "Gain: Independent scaling. Trade-off: Increased complexity"
}

// Policies
SecurityPolicy = policy "Enforce TLS 1.3" {
    category "security"
    enforcement "required"
}

// Constraints and Conventions
constraints {
    "All APIs must use HTTPS"
    "Database must be encrypted at rest"
}

conventions {
    "Use RESTful API design"
    "Follow semantic versioning"
}

// Scenarios
PurchaseScenario = scenario "User purchases item" {
    step Customer -> Shop.WebApp "Adds item to cart"
    step Shop.WebApp -> Shop.API "Submits order"
    step Shop.API -> Shop.DB "Saves order"
}

// Views (optional - auto-generated if omitted)
view index {
    title "System Context"
    include *
}

view container_view of Shop {
    title "Shop Containers"
    include Shop.*
}

Key Rules

  1. Nested Syntax: Containers and components must be nested inside their parent element (system and container respectively). Only persons, systems, and governance items (requirements, ADRs, policies) can be at top level.
  2. IDs: Must be unique within their scope
  3. References: Use dot notation (e.g., System.Container, System.Container.Component)
  4. Relations: Can be defined anywhere (implied relationships are automatically inferred)
  5. Metadata: Freeform key-value pairs
  6. Descriptions: Optional string values
  7. Views: Optional — C4 views are automatically generated if not specified
  8. SLOs: Can be defined at architecture, system, or container level
  9. Scale: Can be defined at container or component level

Common Patterns

C4 Model Levels

  • Level 1 (System Context): Systems and persons
  • Level 2 (Container): Containers within systems
  • Level 3 (Component): Components within containers

Resources

E2E diagram smoke (CI)

Minimal Sruja block used by deploy E2E to verify WASM + Mermaid in the built book. Not linked from the public nav; referenced only by Playwright.

Shop = system "Shop" {
  description "Example system for CI diagram smoke"

  Web = container "Web" {
    technology "React"
    description "Storefront"
  }

  API = container "API" {
    technology "Rust"
    description "Backend API"
  }
}

Buyer = person "Buyer" {
  description "Customer"
}

Buyer -> Shop.Web "browses"
Shop.Web -> Shop.API "calls"