Skip to content

Spec-Driven Development (OpenSpec)

A specification-first development methodology for designing, implementing, and tracking changes across the Bast AI platform using structured artifacts, BDD requirements, and AI-assisted workflows.


Overview

Bast AI uses OpenSpec to manage all feature work through a disciplined, artifact-driven lifecycle. Every change — from security hardening to billing integration — follows a structured flow: explore the problem, write a proposal, design the solution, define BDD specs, break into tasks, implement, and archive.

This methodology ensures:

  • Requirements are captured before code is written — in testable BDD format
  • Design decisions are explicit and documented — not buried in PR comments
  • Implementation is traceable — every task maps to specs, every spec maps to a capability
  • AI agents can participate effectively — structured artifacts give agents the context they need

The OpenSpec Lifecycle

    ┌──────────┐     ┌──────────┐     ┌──────────┐     ┌──────────┐
    │          │     │          │     │          │     │          │
    │ EXPLORE  │────▶│ PROPOSE  │────▶│  APPLY   │────▶│ ARCHIVE  │
    │          │     │          │     │          │     │          │
    └──────────┘     └──────────┘     └──────────┘     └──────────┘
         │                │                │                │
    Think through    Create change    Implement tasks   Archive with
    the problem      with artifacts   from task list    delta spec sync
         │                │                │                │
    Read-only        proposal.md      Code changes      Move to archive/
    investigation    design.md        Mark checkboxes   Sync specs
                     tasks.md
                     specs/

Phase 1: Explore (/opsx:explore)

A thinking mode — not a workflow. The agent acts as a curious thinking partner, exploring the problem space, investigating the codebase, and surfacing options. No code is written. ASCII diagrams are used liberally.

When to use: Before starting any non-trivial change, when stuck mid-implementation, or when comparing architectural approaches.

Phase 2: Propose (/opsx:propose)

Creates a change directory with three core artifacts generated in dependency order:

Artifact Purpose Contents
proposal.md What & Why Scope, rationale, dependencies, capabilities, impact analysis
design.md How Context analysis, goals/non-goals, technical decisions with rationale and alternatives
tasks.md Implementation steps Numbered, checkboxed task list grouped by subsystem

Additionally, delta specs (specs/<capability>/spec.md) capture new or modified BDD requirements for each capability the change touches.

Phase 3: Apply (/opsx:apply)

Implementation mode. The agent reads all context files (proposal, design, specs, tasks), then works through the task list sequentially:

  • Shows progress (N/M tasks complete)
  • Makes focused code changes per task
  • Marks tasks complete (- [ ] → - [x])
  • Pauses on blockers or ambiguity — never guesses

The workflow is fluid and non-linear: you can apply before all artifacts are complete, update artifacts mid-implementation, or interleave with explore sessions.

Phase 4: Archive (/opsx:archive)

Finalizes a completed change:

  1. Checks artifact and task completion (warns if incomplete)
  2. Compares delta specs with main specs — shows add/modify/remove summary
  3. Syncs delta specs into the main spec repository (if approved)
  4. Moves the change to openspec/changes/archive/YYYY-MM-DD-<name>/

Directory Structure

openspec/
├── SEQUENCING.md                    # Change execution plan and priority tracking
├── specs/                           # Main capability specification repository
│   ├── activation-contract/
│   │   └── spec.md                  # BDD requirements for activation
│   ├── billing-model/
│   │   └── spec.md
│   ├── deployment-model/
│   │   └── spec.md
│   ├── totp-mfa/
│   │   └── spec.md
│   ├── limiter-unit-tests/
│   │   └── spec.md
│   └── ... (44 capability specs)
└── changes/
    ├── <active-change>/             # Work in progress
    │   ├── .openspec.yaml           # Metadata (schema, created date)
    │   ├── proposal.md              # What & why
    │   ├── design.md                # How (decisions, architecture)
    │   ├── tasks.md                 # Implementation checklist
    │   └── specs/                   # Delta specs for this change
    │       └── <capability>/
    │           └── spec.md
    └── archive/                     # Completed changes
        ├── 2026-03-13-security-hardening-implementation/
        ├── 2026-03-13-activation-flow-implementation/
        ├── 2026-03-16-billing-implementation/
        ├── 2026-03-16-rate-limiting-implementation/
        └── ... (10 archived changes)

BDD Specification Format

All requirements are written in Behavior-Driven Development (BDD) format with WHEN/THEN scenarios and acceptance criteria.

Spec Structure

## ADDED Requirements

### Requirement: <Requirement title>
<Requirement statement using SHALL language>

#### Scenario: <Scenario name>
- **WHEN** <precondition or trigger>
- **THEN** <expected behavior using SHALL>

#### Scenario: <Another scenario>
- **WHEN** <different condition>
- **THEN** <different expected behavior>

Example: Activation Contract Spec

### Requirement: Canonical activation-status endpoint
The backend SHALL expose a canonical activation-status endpoint
returning: required step flags, is_complete, can_enter_admin,
can_publish, missing_requirements, next_required_step, and
completed_at.

#### Scenario: All required steps complete
- WHEN all required activation steps are completed
- THEN the response SHALL include is_complete: true,
  can_enter_admin: true, next_required_step: null

#### Scenario: Partial completion
- WHEN some required steps are incomplete
- THEN the response SHALL include is_complete: false,
  next_required_step set to the first incomplete step

Example: Rate Limiter Unit Test Spec

### Key Derivation
- Auth key builder produces IP-based keys with optional
  email prefix hash
- Keys from different actor types never collide

### Sliding-Window Counter
- Increment and check within window
- Counter resets after window expiry
- Requests at limit boundary: last allowed request vs
  first denied request

### Fail-Open
- When counter store is unavailable, requests pass through
- Fail-open emits high-severity alert log

Task Structure

Tasks are organized by subsystem with numbered checkboxes:

## 1. Backend — Shared Limiter Abstraction

- [x] 1.1 Create reusable limiter module with key builder
      interface, policy definition model, counter operations
- [x] 1.2 Implement Redis-backed sliding-window counter store
- [ ] 1.3 Implement in-memory counter fallback

## 2. Testing — Backend Unit

- [ ] 2.1 Test key derivation for each actor type
- [ ] 2.2 Test policy selection by endpoint group
- [ ] 2.3 Test 429 metadata generation

Task Conventions

  • Tasks are grouped by subsystem (Backend, BFF, Frontend, Testing)
  • Each task has a section.number ID (e.g., 1.1, 2.3)
  • - [x] = completed, - [ ] = pending
  • Tasks are atomic — one task, one focused code change
  • Testing tasks are explicit — unit, integration, and E2E are separate sections

Proposal Structure

A proposal answers What and Why:

## Why
<Problem statement with specific code references (file, line)>

## What Changes
<Bulleted list of concrete changes by subsystem>

## Depends On
<List of prerequisite changes>

## Capabilities
### New Capabilities
- capability-name: Description
### Modified Capabilities
- capability-name: What changes

## Impact
- Backend (bast-ai): affected files and modules
- BFF (apps/bff): affected routes
- Frontend: affected components

Design Structure

A design document answers How:

## Context
<Current state with specific code references>

## Goals / Non-Goals
Goals: What we're solving
Non-Goals: What we're explicitly NOT solving

## Decisions

### 1. Decision Title
**Decision**: The chosen approach
**Rationale**: Why this approach
**Alternatives considered**: What else was evaluated and why rejected

Each decision includes:

  • The decision itself
  • Rationale explaining why
  • Alternatives considered with reasons for rejection

Change Sequencing

The SEQUENCING.md file tracks cross-change dependencies and execution order:

## Active Changes

| Priority | Change               | Tasks | Repo          | Depends On |
|----------|----------------------|-------|---------------|------------|
| P1       | rate-limit-tests     | 12    | bast-admin-ui | —          |
| P2       | deployment-endpoints | 12    | bast-ai       | —          |
| P2       | e2e-backend-contracts| 10    | bast-ai       | —          |

## Execution Sequence

NOW (this repo)           NEXT (bast-ai)
───────────────           ──────────────
rate-limit-tests     ──▶  deployment-endpoints
                          e2e-backend-contracts

Testing in OpenSpec

OpenSpec treats testing as a first-class concern. Tests are captured at multiple levels:

Capability Specs as Test Requirements

Each capability spec defines testable scenarios in BDD format. These scenarios drive test implementation:

Spec Tests It Drives
limiter-unit-tests Unit tests for key derivation, sliding window, fail-open, backoff
limiter-integration-tests Integration tests for multi-layer enforcement
browser-harness Playwright E2E configuration with multi-app coverage
release-blocking-scenarios Release-gate browser scenarios for auth → deploy → chat
deterministic-test-env Backend seed/reset endpoints for reproducible test state

Test Task Organization

In tasks.md, testing sections follow implementation:

## 12. Testing — Backend Unit
- [ ] 12.1 Test key derivation for each actor type
- [ ] 12.2 Test policy selection by endpoint group
- [ ] 12.3 Test sliding-window counter behavior

## 13. Testing — Backend Integration
- [ ] 13.1 Test BFF auth throttling (429 after limit)
- [ ] 13.2 Test cross-replica counter sharing

## 14. Testing — Frontend
- [ ] 14.1 Test cooldown UX rendering

## 15. Testing — End-to-End
- [ ] 15.1 Failed login → throttle → cooldown → retry

Test Environment Strategy

OpenSpec specifies deterministic test infrastructure:

  • Seed endpoints — create test users, orgs, CATs, deployments via production code paths
  • Reset endpoint — clean up all fixtures by test run identifier
  • External adapters — deterministic stubs for billing, email, OAuth in CI
  • Observable async state — polling endpoints for provisioning, ingestion, deployment status

Capability Spec Registry

The platform maintains 173 capability specs across 18 domains — 165 in bast-admin-ui (frontend, BFF, org & deployment platform) and 8 in bast-ai (Cat Runtime backend, ontology, documentation infrastructure):

Domain Count Capabilities
Security 15 totp-mfa, security-audit-events, security-ux, public-access-enforcement, snippet-output-sanitization, figma-capture-hardening, widget-session-secret-hardening, widget-session-secret-enforcement, widget-session-origin-enforcement, security-headers, cors-enforcement, error-sanitization, cookie-security, mfa-totp-strict-validation, security-compliance-dashboard
Auth & Session 11 cookie-first-session-restore, fresh-org-metadata, faithful-org-status-sync, authenticated-fetch-helper, auth-error-sanitization, auth-context-splitting, bff-member-auth-guard, password-reset-flow, first-time-user-routing, auth-error-differentiation, jwt-role-resolution
Activation & Setup 12 activation-contract, activation-observability, gated-activation-flow, canonical-org-state, activation-step-error-propagation, setup-wizard-persistence, existing-org-detection, atomic-register-with-org, onboarding-checklist-state, registration-error-recovery, setup-bootstrap-orchestration, setup-flow-ui
Billing 5 billing-model, billing-ux, billing-activation-gate, checkout-lifecycle, free-tier-publish
Deployment 17 deployment-model, deployment-crud, deployment-client, deployment-domain, deployment-workspace, publish-contract, deployment-detail-error-states, deployment-activity-log, deployment-analytics-view, deployment-approval-gates, deployment-config-audit-trail, deployment-environment-promotion, deployment-preview, deployment-publish-confirmation, deployment-reverse-lookup, deployment-rollback, deployment-version-snapshots
Org Management 12 org-scoped-security-settings, org-scoped-billing, org-scoped-endpoints, org-scoped-audit-log, org-switch-data-isolation, bff-org-create-orchestration, org-name-collision-handling, org-dropdown-data-alignment, last-admin-safeguard, member-deactivation, org-create-auto-provisioning, org-membership-atomicity
Invitations & Members 6 invitation-lifecycle-management, invitation-email-delivery, invitation-visibility, members-card-display, direct-member-invite-flow, invitation-acceptance-registration
Rate Limiting 9 limiter-infrastructure, throttle-enforcement, throttle-ux, throttle-observability, throttle-observability-ui, limiter-unit-tests, limiter-integration-tests, rate-limit-reset-accuracy, stable-kb-polling-backoff
Knowledge Base 10 kb-job-lifecycle, resumable-kb-ux, idempotent-pipeline, kb-flagged-issues, kb-answer-grounding, kb-answer-retrieval, kb-auto-confirm, kb-topic-enrichment, knowledge-ontology-concept-editing, kb-intake-structural-fields ⁂
Analytics 7 usage-analytics-live-data, usage-analytics-pagination, usage-analytics-action-workflow, usage-analytics-conversation-context, usage-analytics-quality-signals, analytics-kb-deep-link, analytics-positive-feedback
Chat & Runtime 4 chat-refusal-ux, chat-source-trace, action-resolution-workflow, cat-os-behavior-structural-fields
Cat Runtime (Backend) ⁂ 6 cat-os-onto-answer-resolution, cat-os-structural-fields, cat-runtime-anti-hallucination-guard, cat-runtime-step-0-normalization, cat-runtime-step-2-persona, cat-runtime-structured-failure-state
Governance 4 governance-posture-view, platform-baseline-policies, trust-readiness-dashboard, executive-trust-view
Testing & CI 11 browser-harness, deterministic-test-env, release-blocking-scenarios, ci-integration, test-env-mode, seed-reset-endpoints, test-state-polling, bff-test-proxy, ci-workflow-hardening, pre-commit-hooks, accessibility-testing
Infrastructure 8 durable-queue-architecture, provisioning-orchestration, provisioning-ux, cleanup-orchestration, retirement-lifecycle, retirement-ux, pants-bootstrap-validation, sponsor-docs-public-routing ⁂
Access 8 access-management-ux, api-key-lifecycle, api-key-input-validation, widget-session-auth, persisted-sessions, public-edge, register-phone-field, backend-phone-wiring
Performance 6 bundle-optimization, vendor-chunk-splitting, render-optimization, catdrawer-cleanup, component-refactoring, ai-model-simplification
UX & Accessibility 17 focus-management, error-feedback, form-accessibility, responsive-layout, ux-polish, honest-action-controls, color-consistency, chart-css-sanitization, detail-header-alignment, infra-card-footer-layout, graph-view-topic-editing, cross-app-shared-styles, dashboard-repartition-polish, screen-reader-compliance, topbar-user-menu, user-profile-view, wcag-contrast
Frontend Infra 5 shared-styles-integration, company-details-contract-safety, upstream-response-safety, local-qr-generation, patient-journey-proxy-fix

⁂ = sourced from bast-ai repo. All others are from bast-admin-ui.


Change Flow

OpenSpec changes move through three states: active (proposed or in-progress in openspec/changes/<name>/), archived (completed and synced into the spec registry under openspec/changes/archive/YYYY-MM-DD-<name>/), and — when their delta specs land — promoted into the canonical openspec/specs/ registry shown in the table above.

Current snapshot

Repo Active changes Archived changes
bast-admin-ui 11 107
bast-ai 3 7
Total 14 114

The authoritative list lives in each repo's openspec/changes/ directory — this page only summarizes because a hand-curated catalog goes stale fast. Browse those directories directly for proposals, designs, BDD specs, and task lists.


Tool Integration

OpenSpec is available as AI agent skills across three environments:

Environment Commands Location
Claude Code /opsx:explore, /opsx:propose, /opsx:apply, /opsx:archive .claude/skills/openspec-*
GitHub Codespaces Same commands .github/skills/openspec-*
Codex Same commands .codex/skills/openspec-*

Quick Reference

# Explore a problem (read-only thinking mode)
/opsx:explore

# Propose a new change with full artifacts
/opsx:propose add-user-notifications

# Implement tasks from a change
/opsx:apply rate-limit-test-coverage

# Archive a completed change
/opsx:archive rate-limiting-implementation

Core Principles

  1. Specification First — Requirements in BDD format before implementation
  2. Explicit Decisions — Every design decision documented with rationale and alternatives
  3. Fluid Workflow — Non-linear; explore, propose, apply, and update interleave freely
  4. Artifact Dependencies — Artifacts build on each other in defined order
  5. Delta Spec Sync — Change-level specs sync back to the main capability registry
  6. Traceable Tasks — Every task maps to a spec, every spec maps to a capability
  7. Test as Spec — Testing requirements are captured as capability specs, not afterthoughts
  8. Blockers First — Pause and ask rather than guess when unclear