# Generated Project Configuration

> **Auto-generated by `analyze_project`**, customized manually
> **Project:** blue-green
> **Type:** infrastructure + TypeScript CLI
> **Last updated:** 2026-06-11

---

## 🚨 MANDATORY: Load CodeOps Rules Before Any Work

**Before ANY planning or implementation, the AI agent MUST load these rules
using the codeops-mcp tools:**

1. `get_rule("agents")` — Load agent behavior rules **(REQUIRED FIRST)**
2. `get_rule("code")` — Load coding standards
3. `get_rule("testing")` — Load testing workflows
4. `get_rule("git-commands")` — Load git commit protocols

**Roadmap directive:** If `plans/00-roadmap.md` exists, you MUST read it at the start of every task and update it at every lifecycle stage transition. See `get_rule("roadmap")`.

These rules are **mandatory** and must be consulted before every task.
**Do NOT skip this step. Do NOT proceed without reading these documents.**

---

## Project Overview

- **Name:** blue-green
- **Description:** Blue-green deployment template and scaffold generator for BlendSDK/WebAFX applications. Provides zero-downtime deployments via Nginx-based blue/green routing, designed to run behind ProxyBuilder for SSL termination. Includes a curl-installable scaffold system that generates project-specific deployment infrastructure, and a TypeScript Deploy CLI that orchestrates deployments from CI runners via SSH.
- **Type:** infrastructure + TypeScript CLI

### Architecture

```
Internet → ProxyBuilder (SSL termination, passthrough mode)
         → HTTP → Blue-Green Nginx (security hardening, rate limiting, blue/green routing)
         → App replicas (BlendSDK/WebAFX)
```

- **ProxyBuilder passthrough mode:** Only does SSL termination + basic proxy headers (Host, X-Real-IP, X-Forwarded-For/Proto/Host/Port). NO security headers, no gzip, no WAF.
- **Blue-Green Nginx:** Handles ALL security hardening, rate limiting, and blue/green traffic routing.
- **Ecosystem stack:** Every app = BlendSDK/WebAFX + blue-green template + ProxyBuilder

### Deploy CLI

The Deploy CLI is a TypeScript tool bundled via esbuild into a single JavaScript file (`deploy-cli.js`). It runs on CI runners and orchestrates blue-green deployments to remote servers over SSH.

- **Source:** `src/deploy-cli/` (TypeScript, ~2800 lines across 15 files)
- **Bundle output:** `scaffold/templates/deployment/scripts/deploy-cli.js` (~41KB, ESM format)
- **Bundler:** esbuild (configured in `esbuild.config.mjs`)
- **Commands:** prepare, switch, deploy, upload, deploy-config, operate, registry
- **Two-phase deploy:** prepare (build/pull + start + health) → barrier → switch (nginx swap)
- **Multi-server support:** Parallel execution with configurable batching (`--max-parallel`)
- **Strategy auto-detection:** In-place (tarball + local build) or registry (pull pre-built image)

### Deployment Strategies

| Strategy | How it works | When to use |
|----------|-------------|-------------|
| `in-place` | Upload tarball, Docker builds locally on each server | Simple setups, few servers |
| `registry` | Build once on CI, push to registry, servers pull | Many servers, faster deploys |

Strategy is auto-detected at runtime by `remote-ops.sh` based on `REGISTRY_URL` in `.env`.

### Scaffold System

```
curl -fsSL <repo-url>/install.sh | bash
  → Downloads repo tarball
  → Runs scaffold/scaffold.js (Node.js, zero external deps, built-in readline)
  → Interactive prompts: project name, app port, nginx port, entrypoint, replicas
  → Conditional: strategy, PostgreSQL, Redis, pg-backup (yes/no prompts)
  → Generates deployment/ directory with fully configured infrastructure
```

- **Entry point:** `install.sh` (thin bash wrapper, downloads repo, invokes scaffold.js)
- **Generator:** `scaffold/scaffold.js` (~580 lines, zero external dependencies)
- **Templates:** `scaffold/templates/` (42 template files for deployment infrastructure)
- **Partials:** `scaffold/partials/` (16 conditional partial files for strategy/PostgreSQL/Redis/pg-backup)
- **Template placeholders:** `{{PROJECT_NAME}}`, `{{APP_PORT}}`, `{{NGINX_PORT}}`, `{{ENTRYPOINT}}`, `{{APP_REPLICAS}}`, `{{APP_BUILD_SECTION}}`
- **Conditional generation:** `{{PARTIAL_*}}` placeholders inject content from `scaffold/partials/` based on user answers
- **Comment-wrapped placeholders:** In bash templates, `# {{PARTIAL}}` so `bash -n` syntax checks pass on raw templates
- **Conflict detection:** Skips existing files by default; `--force` flag overwrites

### Docker Compose Profiles

| Profile | Services |
|---------|----------|
| `core` | nginx, postgres, redis |
| `blue` | app-blue replicas |
| `green` | app-green replicas |
| `all` | core + blue + green |
| `db` | postgres only |

### Nginx Modular Config

```
nginx/nginx.conf              — Main config, includes all modules
nginx/conf.d/                  — Server-level config (server-name)
nginx/includes/                — Shared includes (headers, proxy, timeouts, etc.)
nginx/locations/               — Location blocks (health, ping, status, default)
nginx/upstreams/               — Upstream definitions (blue, green, active)
```

## Toolchain

- **Language(s):** TypeScript (Deploy CLI), Docker, Nginx config, Bash scripts, Node.js (app + scaffold)
- **Framework(s):** BlendSDK/WebAFX (app layer)
- **Package Manager:** npm
- **Bundler:** esbuild (bundles TypeScript Deploy CLI to single JS file)
- **Test Framework:** Node.js built-in test runner (`node:test`) for Deploy CLI
- **Test Runner:** `node --experimental-strip-types --test src/deploy-cli/__tests__/*.test.ts`
- **Scaffold Runtime:** Node.js (zero external dependencies, built-in readline)

**Manifest files found:** package.json, docker-compose.yml, app/package.json, scaffold/package.json, tsconfig.json

## Commands

All commands assume execution from the project root. Prefix all shell commands with `clear && sleep [delay] &&` (see Terminal Delay below).

### Terminal Delay

- **Delay (seconds):** 3
- The `clear` ensures a clean terminal; the `sleep` gives VS Code time to initialize the terminal before the command runs.
- Adjust the delay for your environment: `1` for fast machines, `3` (default) for normal, `5` for slower environments.
- All command examples below use `sleep 3` — replace `3` with your configured delay.

### Build

```bash
# Build Deploy CLI bundle
clear && sleep 3 && npm run build:cli

# Build Docker containers
clear && sleep 3 && docker compose build
```

### Test / Validate

```bash
# Run Deploy CLI unit tests (57 tests)
clear && sleep 3 && npm run test:cli

# Validate docker-compose configuration
clear && sleep 3 && docker compose config

# Type-check TypeScript
clear && sleep 3 && npx tsc --noEmit
```

### Verify (before commit)

```bash
# Full verification — run this before any git commit
clear && sleep 3 && npm run verify && bash -n scaffold/templates/deployment/scripts/remote-ops.sh
```

### Blue-Green Switch

```bash
# Switch active environment (blue↔green)
clear && sleep 3 && bash scripts/switch-environment.sh
```

### Scaffold (run from target project)

```bash
# Install scaffold into a new project (from target project root)
curl -fsSL https://raw.githubusercontent.com/blendsdk/blue-green/master/install.sh | bash

# Or run scaffold.js directly during development
clear && sleep 3 && node scaffold/scaffold.js
```

## Project Structure

### Type: Single repository

### Directory Layout

```
install.sh                     — Curl-installable entry point (downloads repo, runs scaffold.js)
package.json                   — Root package.json (type: module, esbuild + TypeScript devDeps)
tsconfig.json                  — TypeScript config (strict, ESNext, noEmit)
esbuild.config.mjs             — esbuild bundler config for Deploy CLI
app/                           — Application container (BlendSDK/WebAFX)
  Dockerfile                   — Multi-stage Node.js build
  package.json                 — App dependencies
  server.js                    — Application entry point
  start.sh                     — Container startup script
  healthcheck.sh               — Docker health check script
data/
  postgresql/                  — PostgreSQL data volume mount
nginx/                         — Nginx configuration (modular)
  nginx.conf                   — Main config
  conf.d/                      — Server-level includes
  includes/                    — Shared config fragments
  locations/                   — Location blocks (numbered for ordering)
  upstreams/                   — Blue/green/active upstream definitions
src/deploy-cli/                — Deploy CLI TypeScript source
  index.ts                     — Entry point, argument parser, command dispatcher
  types.ts                     — All interfaces and type definitions
  lib/                         — Core libraries
    process.ts                 — Spawn helper with timeout and stream capture
    logger.ts                  — Structured output with emoji prefixes
    ssh.ts                     — SSH setup, exec, SCP upload, cleanup
    config.ts                  — Config resolution ({ENV} placeholders)
    inventory.ts               — Server inventory resolution (scope/filter)
  commands/                    — Command implementations
    shared.ts                  — Common infrastructure (parseDeployOptions, executeOnServers)
    upload.ts                  — Multi-step file upload to servers
    deploy-config.ts           — Config file deployment from secrets
    operate.ts                 — Generic remote-ops.sh subcommand runner
    prepare.ts                 — Blue-green prepare (phase 1)
    switch.ts                  — Blue-green switch (phase 2)
    deploy.ts                  — Coordinated deploy with barrier
    registry.ts                — Docker build + push (CI-side)
  __tests__/                   — Unit tests (57 tests)
    config.test.ts             — Config resolution tests (13)
    inventory.test.ts          — Server inventory tests (24)
    parser.test.ts             — Argument parser tests (20)
    fixtures/                  — Test fixture files
      deploy-config.json       — Test config fixture
      deploy-inventory.json    — Test inventory fixture
scaffold/                      — Scaffold generator system
  package.json                 — CJS override (type: commonjs for scaffold.js)
  scaffold.js                  — Interactive generator (~580 lines, Node.js, zero deps)
  templates/                   — Template files (42 files, mirrors deployment structure)
    .gitignore.template        — Generated .gitignore for target projects
    deploy-config.json         — Deploy configuration template
    deploy-inventory.json      — Server inventory template
    deploy-package.sh          — Deploy packaging script template
    deployment/                — Full deployment infrastructure templates
      .env.example             — Environment variable template
      docker-compose.yml       — Docker Compose template with conditional services
      Dockerfile               — App Dockerfile template
      pg-backup.sh             — PostgreSQL backup script (conditional)
      nginx/                   — Nginx config templates (mirrors nginx/ structure)
        nginx.conf
        conf.d/server-name.conf
        includes/*.conf        — All include templates
        locations/*.conf       — All location templates
        upstreams/*.conf       — All upstream templates
      scripts/                 — Deployment scripts (3 files)
        deploy-cli.js          — Deploy CLI bundle (ESM, ~41KB)
        remote-ops.sh          — Remote operations script (SSH commands)
        health-check-wait.sh   — Health check wait script
    .github/                   — GitHub Actions workflow templates
      SECRETS-SETUP.md         — GitHub Secrets documentation
      workflows/
        build-test.yml         — CI: build + test on every push/PR
        release-single.yml     — CD: single-server release
        release-multi.yml      — CD: multi-server release (three-job barrier)
        operations-single.yml  — Ops: single-server operations
        operations-multi.yml   — Ops: multi-server operations
    local_data/                — Local data directory template
      .gitkeep                 — Keeps directory in git
    scripts/                   — Project-level script templates
      push-secrets.sh          — Secret pushing script template
  partials/                    — Conditional partial files (16 files)
    compose-build-inplace.yml  — In-place Docker build section
    compose-build-registry.yml — Registry Docker image section
    docker-compose-postgres.yml  — PostgreSQL service block
    docker-compose-redis.yml     — Redis service block
    docker-compose-pgbackup.yml  — pg-backup service block
    env-postgres.txt             — PostgreSQL env vars
    env-redis.txt                — Redis env vars
    env-backup.txt               — Backup env vars
    env-registry.txt             — Registry env vars
    remote-ops-database-commands.sh   — Database command functions
    remote-ops-dispatcher-database.sh — Database dispatcher entries
    remote-ops-health-check-db.sh     — Database health check
    remote-ops-help-database.sh       — Database help text
    operations-database-options.yml   — GitHub Actions database options
    operations-database-steps.yml     — GitHub Actions database steps
plans/                         — Implementation plans and notes
  deploy-cli/                  — Deploy CLI implementation plan (9 phases, 66 tasks)
    00-index.md                — Plan index
    01-requirements.md         — Requirements document
    02-current-state.md        — Current state analysis
    03-deploy-cli-architecture.md — Deploy CLI architecture
    04-remote-ops-updates.md   — Remote ops two-phase + registry updates
    05-registry-deployment.md  — Registry deployment templates
    06-workflow-refactoring.md — Workflow YAML refactoring
    07-scaffold-updates.md     — Scaffold generator updates
    08-scaffoldapp-migration.md — ScaffoldApp migration
    09-testing-strategy.md     — Testing strategy
    99-execution-plan.md       — Execution plan (66/66 tasks complete)
  scaffold-deployment/         — Scaffold system implementation plan (47/47 tasks complete)
  remove-internet-mode/        — Completed: removed internet/certbot mode
  refactor-blue-green/         — Original refactoring plan
  security-hardening/          — Security hardening plan (in progress)
  security-hardening-notes.md  — Future security improvements
scripts/                       — Operational scripts
  agent.sh                     — VS Code agent mode switching
  health-check-wait.sh         — Wait for healthy containers
  switch-environment.sh        — Blue↔green environment switcher
```

## Coding Conventions

### Naming

- **Files:** kebab-case (`switch-environment.sh`, `proxy_headers.conf`)
- **TypeScript files:** kebab-case (`deploy-config.ts`, `shared.ts`)
- **Nginx configs:** Numbered prefix for ordering in `locations/` (`10-health.conf`, `99-default.conf`)
- **Scripts:** kebab-case with descriptive names
- **Environment variables:** UPPER_SNAKE_CASE (`ACTIVE_ENV`, `APP_REPLICAS`)
- **Template files:** Same name as target output file (e.g., `docker-compose.yml` template → generates `docker-compose.yml`)
- **Partial files:** Descriptive kebab-case with service prefix (`docker-compose-postgres.yml`, `env-redis.txt`, `remote-ops-health-check-db.sh`)

### TypeScript / Deploy CLI Style

- **Import convention:** All internal imports use `.ts` extensions for `--experimental-strip-types` compatibility
- **Module format:** ESM (`"type": "module"` in root package.json)
- **Type imports:** Use `import type { ... }` for type-only imports
- **JSDoc comments:** Required on all exported functions and interfaces
- **Constants:** UPPER_SNAKE_CASE for module-level constants
- **Error handling:** Commands exit with `process.exit(1)` on failure, never throw uncaught
- **No private members:** Use `protected` instead of `private` (per code.md)

### Nginx Config Style

- Use `include` directives for modularity — one concern per file
- Comment every config file with its purpose
- Reference ProxyBuilder in upstream/architecture comments
- Use `conf.d/`, `includes/`, `locations/`, `upstreams/` subdirectories

### Shell Script Style

- Always include `#!/bin/bash` shebang
- Use `set -e` for error handling
- Add descriptive comments explaining purpose

### Scaffold Template Style

- **Placeholders:** Use `{{UPPER_SNAKE_CASE}}` for variable substitution (e.g., `{{PROJECT_NAME}}`, `{{APP_PORT}}`)
- **Conditional partials:** Use `{{PARTIAL_NAME}}` for content injection from `scaffold/partials/`
- **Comment wrapping:** In bash/shell templates, wrap partials in comments: `# {{PARTIAL_NAME}}` so `bash -n` passes on raw templates
- **Template mirroring:** Templates in `scaffold/templates/deployment/` mirror the exact directory structure of the generated output
- **Zero dependencies:** scaffold.js uses only Node.js built-in modules (`fs`, `path`, `readline`)

## Git & Commit Conventions

### Commit Scope

```
# Use module/feature as scope:
# feat(deploy-cli): description
# feat(nginx): description
# feat(docker): description
# feat(scripts): description
# feat(scaffold): description
# chore(plans): description
# docs(readme): description
```

### Valid Scopes

- `deploy-cli` — Deploy CLI TypeScript source and tests
- `nginx` — Nginx configuration changes
- `docker` — Docker Compose, Dockerfile changes
- `scripts` — Script additions/modifications
- `app` — Application code changes
- `scaffold` — Scaffold generator, templates, partials, install.sh
- `plans` — Plan documents
- `readme` / `docs` — Documentation
- `env` — Environment variable changes
- `security` — Security-related changes

### Branch Strategy

- **Main branch:** `master`
- **Feature branches:** `feature/[name]`

## Special Rules (Project-Specific)

### ProxyBuilder Awareness

- This template NEVER handles SSL/TLS directly — ProxyBuilder does SSL termination
- HSTS headers are set at the Nginx layer but work because ProxyBuilder passes them through to browsers over HTTPS
- Security headers are ALL set at the blue-green Nginx layer (ProxyBuilder is a "dumb passthrough")
- No certbot, no SSL certificates, no HTTPS port in this template

### Environment Variables

- Core env vars: `COMPOSE_PROJECT_NAME`, `APP_REPLICAS`, `ACTIVE_ENV`, `NGINX_HTTP_PORT`
- Service-specific: `HEALTH_CHECK_*`, `POSTGRES_*`, `REDIS_*`
- Registry-specific: `REGISTRY_URL`, `REGISTRY_USER`, `REGISTRY_PASSWORD`, `IMAGE_NAME`
- No `NGINX_MODE`, `NGINX_HTTPS_PORT`, `DOMAIN_NAME`, or `CERTBOT_EMAIL` (removed in remove-internet-mode)

### Security Model (rated 7/10)

- Strong SSL at edge (ProxyBuilder), comprehensive headers at Nginx layer
- Rate limiting, IP anonymization via trusted_proxies
- Known gaps documented in `plans/security-hardening-notes.md`:
  - trusted_proxies too broad (trusts all private ranges)
  - No per-endpoint rate limits
  - CSP not flexible for HTML apps
  - No WAF

### Deploy CLI Rules

- **Bundle format:** ESM — runs in contexts where parent `package.json` has `"type": "module"`
- **scaffold/package.json** has `"type": "commonjs"` for scaffold.js — the bundle under `scaffold/templates/` inherits CJS context locally, but works in generated projects
- **SSH key is optional:** CI environments may provide key via `SSH_PRIVATE_KEY` env var, or use pre-configured SSH agents
- **Jump host:** Uses `ProxyCommand` with `ssh -W %h:%p` (not `ProxyJump`) for older SSH compatibility
- **DEPLOY_PATH:** Must be absolute path (`/opt/app`), NOT `~/path` (tilde expands on CI runner, not remote server)
- **Two-phase deploy safety:** If ANY server fails prepare, the deploy command aborts without switching any server

### Scaffold System Rules

- **Template placeholders** (`{{...}}`) are replaced at generation time — they do NOT appear in generated output
- **Partial injection** is all-or-nothing: if user says "no" to PostgreSQL, the entire PostgreSQL partial is omitted (empty string)
- **Conflict detection:** scaffold.js skips files that already exist unless `--force` is passed
- **Generated output structure:** Target project gets `deployment/`, `scripts/push-secrets.sh`, `deploy-config.json`, `deploy-inventory.json`, `deploy-package.sh`, `.gitignore`, `local_data/.gitkeep`, `.github/workflows/`, `.github/SECRETS-SETUP.md`
- **No runtime dependencies:** scaffold.js and all generated scripts use only bash and Node.js built-ins
- **install.sh requirements:** Must work with `curl -fsSL <url> | bash` — no interactivity in the download phase, interactivity starts when scaffold.js runs
- **GitHub Actions workflows** are generated into `.github/workflows/` — single-server gets `release.yml` + `operations.yml`, multi-server gets `release-multi.yml` + `operations-multi.yml`

## Cross-References

The generic rule files that read this `project.md`:

- **make_plan.md** — Uses verify command, file paths, commit scope, task file path patterns
- **code.md** — Uses language conventions, architecture rules
- **testing.md** — Uses test commands, test locations, test framework
- **git-commands.md** — Uses commit scope, verify command
- **agents.md** — Uses shell commands, verify command
- **requirements.md** — Uses project type, tech stack, and conventions for requirements discovery
- **retro_requirements.md** — Uses project type, tech stack for codebase analysis adaptation
- **techdocs.md** — Uses project type, tech stack for documentation generation
- **upgrade_plan.md** — Uses project context for upgrade compatibility checks
- **grill_me.md** — Uses project context for deep disambiguation before planning or requirements
- **preflight.md** — Uses project type, tech stack, and conventions for grounded quality audits
- **roadmap.md** — Tracks RDs/plans across the feature-set lifecycle if a roadmap exists (make_roadmap)
