# CLAUDE.md

This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.

## Project Overview

`augint-org` (CLI: `ai-org`) -- AWS Control Tower landing zone using direct StackSets for automated multi-account provisioning. Published to PyPI as `augint-org`. Python 3.12+, built with uv and hatchling.

## Development Commands

```bash
# Dependencies
uv sync                              # Install all deps (dev included)
uv pip install -e .                  # Editable install

# Testing
uv run pytest tests/ -v              # All tests
uv run pytest tests/unit/ -v         # Unit tests only
uv run pytest tests/integration/ -v  # Integration tests only
uv run pytest tests/unit/test_cli.py -v                    # Single file
uv run pytest tests/unit/test_cli.py::test_version -v      # Single test
uv run pytest tests/ --cov=src/ai_org --cov-report=term-missing  # Coverage

# Code quality
uv run pre-commit run --all-files    # All checks (lint + format + typecheck)
uv run ruff check src/ tests/ scripts/   # Lint only
uv run ruff format src/ tests/ scripts/  # Format only
uv run mypy src/                         # Type check only

# Infrastructure deployment (requires AWS credentials)
make deploy                          # Deploy all StackSets and SCPs
make bootstrap                       # Create OU structure (idempotent)
make status                          # Show deployment status
```

## Code Architecture

### CLI Layer (Click)
Entry point: `src/ai_org/cli.py` -> `ai-org` command. Global options: `--profile`, `--region`, `--debug`, `--json`.

Command groups in `src/ai_org/commands/`:
- `account.py` -- account create/list
- `billing.py` -- Stripe billing link/unlink/list
- `config.py` -- config init/set
- `dns.py` -- DNS delegation
- `ou.py` -- OU list/status
- `sso.py` -- SSO permission assign/list/unassign
- `stackset.py` -- StackSet deploy/status/list

### Core Managers (`src/ai_org/core/`)
Each domain has a manager class that encapsulates business logic:
- **AWSClient** (`aws_client.py`) -- Central AWS abstraction. Lazy-loading boto3 session, service client creation, pagination helpers. All AWS calls go through this.
- **AccountManager** (`account_manager.py`) -- Account creation via Control Tower Account Factory
- **BillingManager** (`billing_manager.py`) -- Stripe integration, DynamoDB account-customer mappings
- **OUManager** (`ou_manager.py`) -- OU hierarchy tree, OU ID lookup by name
- **SSOManager** (`sso_manager.py`) -- Identity Center permission sets and assignments
- **StackSetManager** (`stackset_manager.py`) -- CloudFormation StackSet create/update/deploy
- **ConfigManager** (`config_manager.py`) -- Config file handling

### Utilities (`src/ai_org/utils/`)
- `output.py` -- Rich console formatting, JSON output mode
- `config_loader.py` -- Config file loading
- `cache.py` -- Caching utilities
- `validators.py` -- Input validation

### Infrastructure (`stacksets/`, `scripts/`)
- `stacksets/` -- CloudFormation templates, one directory per StackSet (01-pipeline-bootstrap through 08-apigateway-logging), plus `scps/` for Service Control Policies
- `scripts/stackset_registry.py` -- Central registry defining all StackSets, their deployment mode (auto/manual), target OUs, parameters, and priority
- `scripts/deploy.py` -- Orchestrator that reads registry and deploys StackSets + SCPs

### Key Pattern: StackSet Deployment Modes
- **Auto-deploy**: `deployment_mode: "auto"` + `target_ous: ["workloads", "sandbox"]` -- deploys to all accounts in OUs, new accounts get it automatically
- **Manual-deploy**: `deployment_mode: "manual"` + `target_ous: []` -- deploy per-account via `ai-org stackset deploy <account-id> --stackset <name>`
- All StackSets use SERVICE_MANAGED permission model (Control Tower's existing roles, never SELF_MANAGED)

## Testing

Tests use pytest + moto for AWS mocking. Fixtures in `tests/conftest.py` provide mock AWS environments.

Markers: `@pytest.mark.unit`, `@pytest.mark.integration`, `@pytest.mark.slow`

Coverage threshold: 80% (configured in pyproject.toml, enforced in CI).

## CI/CD

Two GitHub Actions workflows:
- **publish.yaml** -- Triggers on push/PR to main and dev. Runs pre-commit, tests, security scans (bandit/pip-audit/semgrep), compliance (license checks), semantic-release, publishes to PyPI. Dev branch publishes prereleases to Test PyPI.
- **infrastructure.yaml** -- Triggers on stacksets/scripts changes. Validates CloudFormation, deploys StackSets to AWS

Versioning: python-semantic-release with conventional commits. `feat:` = minor, `fix:/perf:/docs:/refactor:` = patch.

## Environment Variables

Required for deployment:
- `GH_ACCOUNT` / `GH_REPO` -- GitHub org and repo for OIDC
- `NOTIFICATIONS_EMAIL` -- Alert recipient

Optional:
- `AWS_PROFILE` (default: org), `AWS_REGION` (default: us-east-1)
- `BUDGETS_MONTHLY_DEFAULT` (default: 1000), `BUDGETS_ANOMALY_THRESHOLD` (default: 100)
- `TEST_STRIPE_SECRET_KEY` or `STRIPE_SECRET_KEY` -- Billing integration

## Important Constraints

- **No IAM Users**: SCP-enforced -- only SSO users and OIDC roles
- **No SELF_MANAGED StackSets**: Always SERVICE_MANAGED with Control Tower roles
- **Control Tower Ownership**: Don't reimplement CloudTrail, Config, or guardrails
- **Region Restrictions**: SCPs enforce region allow-list for workload accounts
- **Ruff line length**: 100 characters
- **Commit format**: Conventional commits (`feat:`, `fix:`, `docs:`, etc.)

## Critical Rules

- **No rebase on main**: NEVER use `git pull --rebase` or `git rebase` on the default branch. Use merge commits only.
- **No manual versioning**: NEVER manually edit version numbers. Semantic Release manages versions via conventional commits.
- **No lock file edits**: NEVER directly write text into lock files (uv.lock, package-lock.json, poetry.lock, yarn.lock). Always use package manager commands (`uv lock`, `uv add`, `npm install`) to regenerate them.
- **No .env commits**: NEVER commit .env files. Use .env.example for templates.
- **No force push to main**: NEVER use `git push --force` on main or the default branch.

## Conventions

- **Commits**: Conventional commits required. `fix:` = patch, `feat:` = minor, `feat!:` / `BREAKING CHANGE` = major.
- **Pre-commit**: Run `uv run pre-commit run --all-files` explicitly before committing. No automatic git hooks -- they break across Windows/WSL. If checks fail, fix the issue and create a NEW commit (do not amend).
- **Branches**: `{feat|fix|docs|refactor|test|chore|ci|build|style|revert|perf}/issue-N-description`
- **PRs**: Target the default development branch. Enable automerge.
- **Tests**: Write tests for all new functionality. Bug fixes require regression tests.

## Development Workflow

**IMPORTANT**: Always follow this sequence. Do NOT skip to step 3 without completing step 2 first.

1. **Pick an issue**: `/ai-pick-issue` -- find or get assigned work
2. **Prepare branch**: `/ai-prepare-branch` -- REQUIRED before any code changes. Creates a fresh branch from the latest base (main or dev), syncs upstream, sets up remote tracking. Never start coding on an existing branch from a previous task.
3. **Develop**: Write code with tests, following project conventions
4. **Submit**: `/ai-submit-work` -- runs all checks locally, commits, pushes, creates automerge PR
5. **Monitor**: `/ai-monitor-pipeline` -- watches CI, diagnoses failures, auto-fixes and re-pushes

## Key Commands

```bash
# Git
git status                    # Check working tree
git log --oneline -10         # Recent commits

# GitHub CLI
gh issue list --state open    # View open issues
gh pr create                  # Create pull request
gh pr merge --auto --squash   # Enable automerge
gh run list                   # List workflow runs
gh run view <id>              # View run details
gh run watch <id>             # Watch run in real-time
```
