Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
134 changes: 134 additions & 0 deletions .github/workflows/mermaid-lint.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,134 @@
name: Mermaid Lint

on:
pull_request:
paths:
- "docs/**/*.mmd"
- ".github/workflows/mermaid-lint.yml"
push:
branches:
- main
paths:
- "docs/**/*.mmd"

jobs:
mermaid-lint:
runs-on: ubuntu-latest
name: Lint Mermaid Diagrams

steps:
- name: Checkout code
uses: actions/checkout@v4

- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version: "18"

- name: Install mermaid-cli
run: npm install -g @mermaid-js/mermaid-cli

- name: Install Chromium dependencies
run: |
sudo apt-get update
sudo apt-get install -y \
libnss3 \
libatk-bridge2.0-0 \
libdrm2 \
libxkbcommon0 \
libgbm1 \
libasound2t64

- name: Find Mermaid files
id: find-mermaid
run: |
files=$(find docs -name "*.mmd" | tr '\n' ' ')
echo "files=$files" >> $GITHUB_OUTPUT

- name: Validate Mermaid syntax
if: steps.find-mermaid.outputs.files != ''
run: |
set -e # Exit on first error
set -o pipefail

echo "🔍 Validating Mermaid diagram syntax..."
echo ""

FAILED=0
for file in ${{ steps.find-mermaid.outputs.files }}; do
echo "▶ Checking: $file"
if mmdc -i "$file" -o /tmp/output.png --puppeteerConfigFile <(echo '{"args":["--no-sandbox","--disable-setuid-sandbox"]}') 2>&1; then
echo "✓ Valid syntax: $file"
else
echo "✗ SYNTAX ERROR: $file"
FAILED=1
fi
echo ""
done

if [ $FAILED -eq 1 ]; then
echo "❌ Mermaid validation FAILED - fix syntax errors above"
exit 1
fi

echo "✅ All Mermaid diagrams validated successfully"

markdown-links:
runs-on: ubuntu-latest
name: Check Documentation Links

steps:
- name: Checkout code
uses: actions/checkout@v4

- name: Check for broken diagram references
run: |
set -e

echo "🔍 Checking for broken diagram references..."
echo ""

# Find all .mmd files
mmd_files=$(find docs -name "*.mmd" -type f)

# Find all markdown files that might reference diagrams
md_files=$(find docs -name "*.md" -type f)

BROKEN=0
for mmd in $mmd_files; do
basename=$(basename "$mmd")
filename="${basename%.mmd}"

# Check if this diagram is referenced in any markdown file
if ! grep -r "$basename\|$filename" $md_files > /dev/null 2>&1; then
echo "⚠️ WARNING: Unreferenced diagram: $mmd"
fi
done

# Check for broken references (references to diagrams that don't exist)
for md in $md_files; do
# Look for mermaid file references in markdown
refs=$(grep -oE '\{\{ [^}]*.mmd [^}]*\}\}|\[.*\]\(.*\.mmd\)' "$md" 2>/dev/null || true)

if [ -n "$refs" ]; then
while IFS= read -r ref; do
# Extract the .mmd filename from the reference
mmd_ref=$(echo "$ref" | grep -oE '[^/]+\.mmd' || true)

if [ -n "$mmd_ref" ]; then
if ! find docs -name "$mmd_ref" -type f | grep -q .; then
echo "✗ BROKEN REFERENCE in $md: $mmd_ref (file not found)"
BROKEN=1
fi
fi
done <<< "$refs"
fi
done

if [ $BROKEN -eq 1 ]; then
echo ""
echo "❌ Found broken diagram references - fix them before merging"
exit 1
fi

echo "✅ All diagram references validated successfully"
6 changes: 0 additions & 6 deletions components/backend/handlers/content.go
Original file line number Diff line number Diff line change
Expand Up @@ -544,12 +544,6 @@ func ContentWorkflowMetadata(c *gin.Context) {
displayName = commandName
}

// Extract short command (last segment after final dot)
shortCommand := commandName
if lastDot := strings.LastIndex(commandName, "."); lastDot != -1 {
shortCommand = commandName[lastDot+1:]
}

// Parse order field from frontmatter, default to MaxInt32 for unordered commands
order := int(^uint(0) >> 1) // MaxInt
if orderStr := metadata["order"]; orderStr != "" {
Expand Down
126 changes: 126 additions & 0 deletions docs/architecture/diagrams/index.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,126 @@
# Architecture Diagrams

Visual representations of the Ambient Code Platform's structure and behavior.

## Core Diagrams

### 1. System Overview

**Recommended for**: First-time learners, stakeholder presentations, deployment planning

High-level view of all major components and how they interact:

- User and frontend layers
- Backend API and Kubernetes control plane
- Execution and storage layers
- Data flow between components

**[View System Overview →](system-overview.md)**

### 2. Session Lifecycle

**Recommended for**: Understanding execution flow, troubleshooting, feature design

Detailed sequence showing how sessions progress from creation through completion:

- Session creation and validation
- Kubernetes job orchestration
- Pod initialization and execution
- Results capture and cleanup
- Error and timeout handling

**[View Session Lifecycle →](session-lifecycle.md)**

## Additional Diagrams

### Platform Architecture
Complete system diagram with all components and connections.
**File**: `platform-architecture.mmd`

### Component Structure
Relationship diagram showing how platform components interact.
**File**: `component-structure.mmd`

### Deployment Stack
Infrastructure topology for deployments.
**File**: `deployment-stack.mmd`

### UX Feature Workflow
Multi-agent workflow for Request For Enhancement features.
**[View UX Feature Workflow →](ux-feature-workflow.md)**

## Using These Diagrams

### For Understanding
1. Start with **System Overview** to understand component relationships
2. Review **Session Lifecycle** to see execution flow
3. Consult specific diagrams for component interactions

### For Debugging
- **Session Lifecycle**: Trace where an execution failed
- **Component Structure**: Verify relationships between components
- **Deployment Stack**: Check infrastructure configuration

### For Development
- **Session Lifecycle**: Reference when implementing new session features
- **System Overview**: Verify placement of new components
- **Platform Architecture**: Understand integration points

### For Documentation
- Reference these diagrams in ADRs and design documents
- Link to specific diagrams when explaining features
- Include in runbooks and troubleshooting guides

## Diagram Conventions

### Styling
- **Neutral/Grayscale Theme**: High contrast for accessibility and printing
- **Component Grouping**: Related components in subgraphs with labels
- **Flow Direction**: Top-to-bottom (TB) for readability
- **Node Types**: Rectangles for components, circles for start/end states

### Symbols
- 👤 User interactions
- 🌐 Web components
- ⚡ API endpoints
- ☸️ Kubernetes components
- 🏃 Execution/runtime
- 📄 Data/state
- 🤖 AI/intelligent components

### Color Coding
- **White/Light Gray**: Frontend and API layers
- **Gray**: Kubernetes and control components
- **Very Light Gray**: Execution components
- **Lightest Gray**: Storage components
- **Green**: Start states
- **Light Red**: Error states

## Maintaining These Diagrams

### Before Release
- Run `mermaid-lint` workflow to validate syntax
- Verify all referenced diagrams exist
- Update diagrams when architecture changes
- Keep documentation in sync with diagrams

### Making Changes
1. Update the Mermaid file (`.mmd`)
2. Update corresponding documentation (`.md`)
3. Run linting to validate syntax
4. Create PR with clear description of changes
5. Request review from architecture maintainers

### Validation
Diagrams are automatically validated via GitHub Actions. The `mermaid-lint` workflow:

- Checks Mermaid syntax validity
- Verifies diagram references in documentation
- Runs on PR and push to main

## Related Documentation

- [Architecture Overview](../README.md)
- [Architectural Decision Records](../adr/)
- [Component Documentation](../../../components/)
- [Deployment Guides](../../deployment/)
110 changes: 110 additions & 0 deletions docs/architecture/diagrams/session-lifecycle.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,110 @@
# Agentic Session Lifecycle

Detailed flow showing how an agentic session progresses from creation through execution to completion and cleanup.

## Lifecycle Diagram

```mermaid
--8<-- "session-lifecycle.mmd"
```

## Phase Breakdown

### Phase 1: Session Creation (Steps 1-3)
**Duration**: Milliseconds

The process starts when a user submits a session request:

1. **Frontend Submission**: User creates a new session with:
- Prompt or task description
- Repository selection
- Model choice
- Timeout configuration

2. **API Validation**: Backend validates:
- User authentication token is valid
- Request format is correct
- User has access to specified namespace (RBAC)
- Required resources are available

3. **Custom Resource Creation**: Backend creates an `AgenticSession` CR with:
```yaml
spec:
prompt: "user's task description"
repos: ["repo-url-1", "repo-url-2"]
model: "claude-3-5-sonnet-20241022"
timeout: 3600
```

### Phase 2: Kubernetes Reaction (Steps 4-7)
**Duration**: 5-30 seconds

Kubernetes orchestrates job creation:

4. **CR Storage**: Kubernetes API stores the Custom Resource
5. **Operator Detection**: Agentic Operator watches for new CRs
6. **Job Creation**: Operator creates a Kubernetes Job resource with container image, environment variables, volume mounts, and resource requests
7. **Job Scheduling**: Kubernetes scheduler assigns the job to an available node

### Phase 3: Pod Initialization (Steps 8-9)
**Duration**: 5-15 seconds

The execution environment starts:

8. **Pod Spawning**: Kubelet creates the execution pod
9. **Runner Initialization**: Claude Code Runner starts setup phase

### Phase 4: Task Execution (Steps 10-11)
**Duration**: Seconds to minutes (depends on task)

The AI reasoning and execution happens:

10. **Prompt Processing**: Claude Code CLI receives the user's prompt
11. **Execution**: Multi-stage process with Claude reasoning and MCP tool invocations

### Phase 5: Results & Completion (Steps 12-14)
**Duration**: Seconds

Results are finalized and cleanup proceeds.

### Phase 6: Frontend Update (Steps 15-17)
**Duration**: Milliseconds

User sees results via WebSocket or polling.

## Error Handling

### Execution Error Path
If the Claude Code CLI encounters an error:
1. Error is captured by the runner
2. CR is updated with error message and stack trace
3. Session phase set to `Failed`
4. Cleanup proceeds normally

### Timeout Handling
If execution exceeds the configured timeout:
1. Operator monitors elapsed time
2. When threshold reached, operator forces pod termination
3. Updates CR with `phase: Timeout`
4. Resources are freed immediately

## Typical Execution Times

| Phase | Duration | Notes |
|-------|----------|-------|
| Session Creation | < 100ms | Synchronous API call |
| Job Scheduling | 5-30s | Kubernetes scheduling + pod pull/init |
| Code Analysis | 10-60s | Claude reads repositories, analyzes structure |
| Task Execution | 30s-30m | Depends on task complexity and tool usage |
| Cleanup | < 10s | Pod termination and resource release |
| **Total** | **1-30+ min** | Highly variable based on task |

## When to Reference This Diagram

Use this diagram when:
- Understanding how sessions execute end-to-end
- Troubleshooting stuck or failing sessions
- Designing new session features
- Setting appropriate timeout values
- Explaining the execution model to users
- Debugging operator behavior
Loading