# Project Bootstrap Guide

> Load this guide when setting up a new project for AI-assisted development.

## Overview

This guide covers how to bootstrap a project so AI agents (Claude, Codex, etc.) can work on it effectively. Proper bootstrapping ensures:

1. Agents understand the project structure and conventions
2. Orchestration works correctly with quality gates
3. Independent code review and security review are configured
4. Issue tracking is consistent across projects
5. Documentation standards and API contracts are enforced from day one
6. PRD requirements are established before coding begins
7. Branching/merging is consistent: branch -> integration trunk (default `main`) via PR with squash-only merges
8. Steered-autonomy execution is enabled so agents can run end-to-end with escalation-only human intervention

## Agent Host Prerequisites

Agent hosts must provide the Python runtime shape that runtime agents and
Mosaic automation assume is present.

For Debian/Ubuntu hosts:

```bash
sudo apt-get update
# #561: bare python invocations from agents must resolve.
sudo apt-get install -y python3 python-is-python3
```

For non-Debian hosts, install the equivalent Python 3 runtime and ensure
`/usr/bin/python` resolves to `python3` (for example, via a managed symlink).

## Quick Start

```bash
# Automated bootstrap (recommended)
~/.config/mosaic/tools/bootstrap/init-project.sh \
  --name "my-project" \
  --type "nestjs-nextjs" \
  --repo "https://git.mosaicstack.dev/owner/repo"

# Or manually using templates
export PROJECT_NAME="My Project"
export PROJECT_DESCRIPTION="What this project does"
export TASK_PREFIX="MP"
envsubst < ~/.config/mosaic/templates/agent/AGENTS.md.template > AGENTS.md
envsubst < ~/.config/mosaic/templates/agent/CLAUDE.md.template > CLAUDE.md
```

---

## Step 0: Enforce Sequential-Thinking MCP (Hard Requirement)

`sequential-thinking` MCP must be installed and configured before project bootstrapping.

```bash
# Auto-configure sequential-thinking MCP for installed runtimes
~/.config/mosaic/bin/mosaic-ensure-sequential-thinking

# Verification-only check
~/.config/mosaic/bin/mosaic-ensure-sequential-thinking --check
```

If this step fails, STOP and remediate Mosaic runtime configuration before continuing.

---

## Step 1: Detect Project Type

Check what files exist in the project root to determine the type:

| File Present                                            | Project Type              | Template                  |
| ------------------------------------------------------- | ------------------------- | ------------------------- |
| `package.json` + `pnpm-workspace.yaml` + NestJS+Next.js | NestJS + Next.js Monorepo | `projects/nestjs-nextjs/` |
| `pyproject.toml` + `manage.py`                          | Django                    | `projects/django/`        |
| `pyproject.toml` (no Django)                            | Python (generic)          | Generic template          |
| `package.json` (no monorepo)                            | Node.js (generic)         | Generic template          |
| Other                                                   | Generic                   | Generic template          |

```bash
# Auto-detect project type
detect_project_type() {
  if [[ -f "pnpm-workspace.yaml" ]] && [[ -f "turbo.json" ]]; then
    # Check for NestJS + Next.js
    if grep -q "nestjs" package.json 2>/dev/null && grep -q "next" package.json 2>/dev/null; then
      echo "nestjs-nextjs"
      return
    fi
  fi
  if [[ -f "manage.py" ]] && [[ -f "pyproject.toml" ]]; then
    echo "django"
    return
  fi
  if [[ -f "pyproject.toml" ]]; then
    echo "python"
    return
  fi
  if [[ -f "package.json" ]]; then
    echo "nodejs"
    return
  fi
  echo "generic"
}
```

---

## Step 2: Create AGENTS.md (Primary Project Contract)

`AGENTS.md` is the primary project-level contract for all agent runtimes.
It defines project-specific requirements, quality gates, patterns, and testing expectations.

### Using a Tech-Stack Template

```bash
# Set variables
export PROJECT_NAME="My Project"
export PROJECT_DESCRIPTION="Multi-tenant SaaS platform"
export PROJECT_DIR="my-project"
export REPO_URL="https://git.mosaicstack.dev/owner/repo"
export TASK_PREFIX="MP"

# Use tech-stack-specific template if available
TYPE=$(detect_project_type)
TEMPLATE_DIR="$HOME/.config/mosaic/templates/agent/projects/$TYPE"

if [[ -d "$TEMPLATE_DIR" ]]; then
  envsubst < "$TEMPLATE_DIR/AGENTS.md.template" > AGENTS.md
else
  envsubst < "$HOME/.config/mosaic/templates/agent/AGENTS.md.template" > AGENTS.md
fi
```

### Using the Generic Template

```bash
# Set all required variables
export PROJECT_NAME="My Project"
export PROJECT_DESCRIPTION="What this project does"
export REPO_URL="https://git.mosaicstack.dev/owner/repo"
export PROJECT_DIR="my-project"
export SOURCE_DIR="src"
export CONFIG_FILES="pyproject.toml / package.json"
export FRONTEND_STACK="N/A"
export BACKEND_STACK="Python / FastAPI"
export DATABASE_STACK="PostgreSQL"
export TESTING_STACK="pytest"
export DEPLOYMENT_STACK="Docker"
export BUILD_COMMAND="pip install -e ."
export TEST_COMMAND="pytest tests/"
export LINT_COMMAND="ruff check ."
export TYPECHECK_COMMAND="mypy ."
export QUALITY_GATES="ruff check . && mypy . && pytest tests/"

envsubst < ~/.config/mosaic/templates/agent/AGENTS.md.template > AGENTS.md
```

### Required Sections

Every AGENTS.md should contain:

1. **Project description** — One-line summary
2. **Quality gates** — Commands that must pass
3. **Codebase patterns** — Reusable implementation rules
4. **Common gotchas** — Non-obvious constraints
5. **Testing approaches** — Project-specific test strategy
6. **Testing policy** — Situational-first validation and risk-based TDD
7. **Orchestrator integration** — Task prefix, worker checklist
8. **Documentation contract** — Required documentation gates and update expectations
9. **PRD requirement** — `docs/PRD.md` or `docs/PRD.json` required before coding

---

## Step 3: Create Runtime Context File (Runtime-Specific)

Runtime context files are runtime adapters. They are not the primary project contract.
Use `CLAUDE.md` for Claude runtime compatibility. Use other runtime adapters as required by your environment.

Claude runtime mandate (HARD RULE):

- `CLAUDE.md` MUST explicitly instruct Claude agents to read and use `AGENTS.md`.
- `CLAUDE.md` MUST treat `AGENTS.md` as the authoritative project-level contract.
- If `AGENTS.md` and runtime wording conflict, `AGENTS.md` project rules win.

```bash
TYPE=$(detect_project_type)
TEMPLATE_DIR="$HOME/.config/mosaic/templates/agent/projects/$TYPE"

if [[ -d "$TEMPLATE_DIR" ]]; then
  envsubst < "$TEMPLATE_DIR/CLAUDE.md.template" > CLAUDE.md
else
  envsubst < "$HOME/.config/mosaic/templates/agent/CLAUDE.md.template" > CLAUDE.md
fi
```

### Required Runtime Sections

Every runtime context file should contain:

1. **AGENTS handoff rule** — Runtime MUST direct agents to read/use `AGENTS.md`
2. **Conditional documentation loading** — Required guide loading map
3. **Technology stack** — Runtime-facing architecture summary
4. **Repository structure** — Important paths
5. **Development workflow** — Build/test/lint/typecheck commands
6. **Issue tracking** — Issue and commit conventions
7. **Code review** — Required review process
8. **Runtime notes** — Runtime-specific behavior references
9. **Branch and merge policy** — Trunk workflow (branch -> integration trunk via PR, squash-only)
10. **Autonomy and escalation policy** — Agent owns coding/review/PR/release/deploy lifecycle

---

## Step 4: Create Directory Structure

```bash
# Create standard directories
mkdir -p docs/scratchpads
mkdir -p docs/templates
mkdir -p docs/reports/qa-automation/pending
mkdir -p docs/reports/qa-automation/in-progress
mkdir -p docs/reports/qa-automation/done
mkdir -p docs/reports/qa-automation/escalated
mkdir -p docs/reports/deferred
mkdir -p docs/tasks
mkdir -p docs/releases
mkdir -p docs/USER-GUIDE docs/ADMIN-GUIDE docs/DEVELOPER-GUIDE docs/API

# Documentation baseline files
touch docs/USER-GUIDE/README.md
touch docs/ADMIN-GUIDE/README.md
touch docs/DEVELOPER-GUIDE/README.md
touch docs/API/OPENAPI.yaml
touch docs/API/ENDPOINTS.md
touch docs/SITEMAP.md

# PRD baseline file (requirements source before coding)
cp ~/.config/mosaic/templates/docs/PRD.md.template docs/PRD.md

# TASKS baseline file (canonical tracking)
cp ~/.config/mosaic/templates/docs/TASKS.md.template docs/TASKS.md

# Deployment baseline file (target/platform/runbook)
touch docs/DEPLOYMENT.md
```

Documentation root hygiene (HARD RULE):

- Keep `docs/` root clean.
- Store reports in `docs/reports/`, archived task artifacts in `docs/tasks/`, releases in `docs/releases/`, and scratchpads in `docs/scratchpads/`.
- Do not place ad-hoc report files directly under `docs/`.

---

## Step 5: Initialize Repository Labels & Milestones

```bash
# Use the init script
~/.config/mosaic/tools/bootstrap/init-repo-labels.sh

# Or manually create standard labels
~/.config/mosaic/tools/git/issue-create.sh  # (labels are created on first use)
```

### Standard Labels

| Label           | Color     | Purpose                                |
| --------------- | --------- | -------------------------------------- |
| `epic`          | `#3E4B9E` | Large feature spanning multiple issues |
| `feature`       | `#0E8A16` | New functionality                      |
| `bug`           | `#D73A4A` | Defect fix                             |
| `task`          | `#0075CA` | General work item                      |
| `documentation` | `#0075CA` | Documentation updates                  |
| `security`      | `#B60205` | Security-related                       |
| `breaking`      | `#D93F0B` | Breaking change                        |

### Initial Milestone (Hard Rule)

Create the first pre-MVP milestone at `0.0.1`.
Reserve `0.1.0` for the MVP release milestone.

```bash
~/.config/mosaic/tools/git/milestone-create.sh -t "0.0.1" -d "Pre-MVP - Foundation Sprint"

# Create when MVP scope is complete and release-ready:
~/.config/mosaic/tools/git/milestone-create.sh -t "0.1.0" -d "MVP - Minimum Viable Product"
```

---

## Step 5b: Configure Trunk Branch Protection (Hard Rule)

Apply equivalent settings in Gitea, GitHub, or GitLab, targeting the project's integration trunk
(the branch its `.mosaic/repo.json` declares under `integration_trunk`; default `main` — see
`CONSTITUTION.md` Hard Gates):

1. Protect the integration trunk from direct pushes.
2. Require pull requests to merge into the integration trunk.
3. Require required CI/status checks to pass before merge.
4. Require code review approval before merge.
5. Allow **squash merge only** for PRs into the integration trunk (disable merge commits and rebase merges for it).

This enforces one merge strategy across human and agent workflows.

---

## Step 6: Set Up CI/CD Review Pipeline

### Woodpecker CI

```bash
# Copy Codex review pipeline
mkdir -p .woodpecker/schemas
cp ~/.config/mosaic/tools/codex/woodpecker/codex-review.yml .woodpecker/
cp ~/.config/mosaic/tools/codex/schemas/*.json .woodpecker/schemas/

# Add codex_api_key secret to Woodpecker CI dashboard
```

### GitHub Actions

For GitHub repos, use the official Codex GitHub Action instead:

```yaml
# .github/workflows/codex-review.yml
uses: openai/codex-action@v1
```

### Python Package Publishing (Gitea PyPI)

If the project publishes Python packages, use Gitea's PyPI registry.

```bash
# Build and publish
python -m pip install --upgrade build twine
python -m build
python -m twine upload \
  --repository-url "https://GITEA_HOST/api/packages/ORG/pypi" \
  --username "$GITEA_USERNAME" \
  --password "$GITEA_TOKEN" \
  dist/*
```

Use the same `gitea_username` and `gitea_token` CI secrets used for container and npm publishing.

---

## Step 7: Verify Bootstrap

After bootstrapping, verify everything works:

```bash
# Check files exist
ls AGENTS.md docs/scratchpads/
ls docs/reports/qa-automation/pending docs/reports/deferred docs/tasks docs/releases
ls docs/USER-GUIDE/README.md docs/ADMIN-GUIDE/README.md docs/DEVELOPER-GUIDE/README.md
ls docs/API/OPENAPI.yaml docs/API/ENDPOINTS.md docs/SITEMAP.md
ls docs/PRD.md
ls docs/TASKS.md

# Verify AGENTS.md has required sections
grep -c "Quality Gates" AGENTS.md
grep -c "Orchestrator Integration" AGENTS.md
grep -c "Testing Approaches" AGENTS.md
grep -c "Testing Policy" AGENTS.md
grep -c "Documentation Contract" AGENTS.md
grep -c "PRD Requirement" AGENTS.md

# Verify runtime context file has required sections
if [[ -f CLAUDE.md ]]; then
  grep -c "AGENTS.md" CLAUDE.md
  grep -c "Conditional Documentation Loading" CLAUDE.md
  grep -c "Technology Stack" CLAUDE.md
  grep -c "Code Review" CLAUDE.md
elif [[ -f RUNTIME.md ]]; then
  grep -c "Conditional Documentation Loading" RUNTIME.md
  grep -c "Technology Stack" RUNTIME.md
  grep -c "Code Review" RUNTIME.md
else
  echo "Missing runtime context file (CLAUDE.md or RUNTIME.md)" >&2
  exit 1
fi

# Run quality gates from AGENTS.md
# (execute the command block under "Quality Gates")

# Test Codex review (if configured)
~/.config/mosaic/tools/codex/codex-code-review.sh --help

# Verify sequential-thinking MCP remains configured
~/.config/mosaic/bin/mosaic-ensure-sequential-thinking --check
```

---

## Available Templates

### Generic Templates

| Template                     | Path                                | Purpose                                    |
| ---------------------------- | ----------------------------------- | ------------------------------------------ |
| `AGENTS.md.template`         | `~/.config/mosaic/templates/agent/` | Primary project agent contract             |
| `CLAUDE.md.template`         | `~/.config/mosaic/templates/agent/` | Runtime compatibility context (Claude)     |
| `DOCUMENTATION-CHECKLIST.md` | `~/.config/mosaic/templates/docs/`  | Documentation completion gate              |
| `PRD.md.template`            | `~/.config/mosaic/templates/docs/`  | Requirements source template               |
| `TASKS.md.template`          | `~/.config/mosaic/templates/docs/`  | Canonical task and issue tracking template |

### Tech-Stack Templates

| Stack            | Path                                                       | Includes                             |
| ---------------- | ---------------------------------------------------------- | ------------------------------------ |
| NestJS + Next.js | `~/.config/mosaic/templates/agent/projects/nestjs-nextjs/` | AGENTS.md + runtime context template |
| Django           | `~/.config/mosaic/templates/agent/projects/django/`        | AGENTS.md + runtime context template |

### Orchestrator Templates

| Template                               | Path                                       | Purpose                 |
| -------------------------------------- | ------------------------------------------ | ----------------------- |
| `tasks.md.template`                    | `~/.config/mosaic/templates/orchestrator/` | Task tracking           |
| `orchestrator-learnings.json.template` | `~/.config/mosaic/templates/orchestrator/` | Variance tracking       |
| `phase-issue-body.md.template`         | `~/.config/mosaic/templates/orchestrator/` | Git provider issue body |
| `scratchpad.md.template`               | `~/.config/mosaic/templates/`              | Per-task working doc    |

### Variables Reference

| Variable                 | Description                 | Example                                    |
| ------------------------ | --------------------------- | ------------------------------------------ |
| `${PROJECT_NAME}`        | Human-readable project name | "Mosaic Stack"                             |
| `${PROJECT_DESCRIPTION}` | One-line description        | "Multi-tenant platform"                    |
| `${PROJECT_DIR}`         | Directory name              | "mosaic-stack"                             |
| `${PROJECT_SLUG}`        | Python package slug         | "mosaic_stack"                             |
| `${REPO_URL}`            | Git remote URL              | "https://git.mosaicstack.dev/mosaic/stack" |
| `${TASK_PREFIX}`         | Orchestrator task prefix    | "MS"                                       |
| `${SOURCE_DIR}`          | Source code directory       | "src" or "apps"                            |
| `${QUALITY_GATES}`       | Quality gate commands       | "pnpm typecheck && pnpm lint && pnpm test" |
| `${BUILD_COMMAND}`       | Build command               | "pnpm build"                               |
| `${TEST_COMMAND}`        | Test command                | "pnpm test"                                |
| `${LINT_COMMAND}`        | Lint command                | "pnpm lint"                                |
| `${TYPECHECK_COMMAND}`   | Type check command          | "pnpm typecheck"                           |
| `${FRONTEND_STACK}`      | Frontend technologies       | "Next.js + React"                          |
| `${BACKEND_STACK}`       | Backend technologies        | "NestJS + Prisma"                          |
| `${DATABASE_STACK}`      | Database technologies       | "PostgreSQL"                               |
| `${TESTING_STACK}`       | Testing technologies        | "Vitest + Playwright"                      |
| `${DEPLOYMENT_STACK}`    | Deployment technologies     | "Docker"                                   |
| `${CONFIG_FILES}`        | Key config files            | "package.json, tsconfig.json"              |

---

## Bootstrap Scripts

### init-project.sh

Full project bootstrap with interactive and flag-based modes:

```bash
~/.config/mosaic/tools/bootstrap/init-project.sh \
  --name "My Project" \
  --type "nestjs-nextjs" \
  --repo "https://git.mosaicstack.dev/owner/repo" \
  --prefix "MP" \
  --description "Multi-tenant platform"
```

### init-repo-labels.sh

Initialize standard labels and the first pre-MVP milestone:

```bash
~/.config/mosaic/tools/bootstrap/init-repo-labels.sh
```

---

## Secrets Bootstrap (Required for Every New App)

Every new application MUST complete the following secrets bootstrap before deploying to any non-local environment. This is a hard gate — deployment without completed secrets bootstrap is forbidden.

### Secrets bootstrap checklist

- [ ] Vault path created: `vault kv put secret/k3s/<app>/ ...` with all required secret fields
- [ ] Required secrets listed in project README under a "Secrets architecture" section, including:
  - Vault path(s) used
  - All required secret keys and their purpose
  - Whether the app uses ESO bridge (default) or Direct-Vault (opt-in, with justification)
- [ ] `external-secret.yaml` manifest committed to repo's `deploy/` or `k8s/` directory
- [ ] Deployment YAML references the synced k8s Secret via `secretKeyRef` (not raw env vars or `.env` files)
- [ ] App startup has schema-based validation for all required env vars (zod / pydantic / envconfig equivalent) that exits non-zero on missing required values
- [ ] Direct-Vault opt-in (if applicable): justification documented in README + AppRole provisioned + bootstrap credentials stored in Vault and synced via a separate `ExternalSecret`

See `~/.config/mosaic/guides/VAULT-SECRETS.md` for full worked examples of the ESO bridge pattern, the Direct-Vault opt-in pattern, and the forbidden antipatterns.

---

## Checklist

After bootstrapping, verify:

- [ ] `AGENTS.md` exists and is the primary project contract
- [ ] Runtime context file exists (`CLAUDE.md` or `RUNTIME.md`)
- [ ] `docs/scratchpads/` directory exists
- [ ] `docs/reports/qa-automation/pending` directory exists
- [ ] `docs/reports/deferred/` directory exists
- [ ] `docs/tasks/` directory exists
- [ ] `docs/releases/` directory exists
- [ ] `docs/USER-GUIDE/README.md` exists
- [ ] `docs/ADMIN-GUIDE/README.md` exists
- [ ] `docs/DEVELOPER-GUIDE/README.md` exists
- [ ] `docs/API/OPENAPI.yaml` exists
- [ ] `docs/API/ENDPOINTS.md` exists
- [ ] `docs/SITEMAP.md` exists
- [ ] `docs/PRD.md` or `docs/PRD.json` exists
- [ ] `docs/TASKS.md` exists and is ready for active tracking
- [ ] `docs/DEPLOYMENT.md` exists with target platform and rollback notes
- [ ] `sequential-thinking` MCP is configured and verification check passes
- [ ] Git labels created (epic, feature, bug, task, etc.)
- [ ] Initial pre-MVP milestone created (0.0.1)
- [ ] MVP milestone reserved for release (0.1.0)
- [ ] The integration trunk is protected from direct pushes
- [ ] PRs into the integration trunk are required
- [ ] Merge method for the integration trunk is squash-only
- [ ] Quality gates run successfully
- [ ] `.env.example` exists (if project uses env vars)
- [ ] CI/CD pipeline configured (if using Woodpecker/GitHub Actions)
- [ ] Python publish path configured in CI (if project ships Python packages)
- [ ] Codex review scripts accessible (`~/.config/mosaic/tools/codex/`)
