Prismatic Tidewave

Prismatic Tidewave

85 files DevOps

Overview

Prismatic Tidewave integrates the Tidewave library for AI-accelerated development workflows within the Prismatic Platform. By combining large language model capabilities with deep knowledge of the platform's architecture, Tidewave automates the most time-consuming aspects of application development: REST API scaffolding, test suite generation, and iterative code review. Rather than generating generic boilerplate, Tidewave produces code that already conforms to the platform's NO MERCY NO DOUBTS quality standards, including proper {:ok, _} / {:error, _} return patterns, supervision tree integration, and typespec annotations.

The module operates as an OTP application with a pool of AI worker processes, each capable of analyzing Elixir AST, inspecting module documentation via Code.fetch_docs/1, and reading @spec annotations to understand function contracts. This introspection-first approach means Tidewave generates endpoints and tests that accurately reflect actual module behavior rather than relying on naming conventions alone. The BEAM virtual machine's hot code reload capability enables Tidewave to regenerate and reload modules in a running development environment without restarting the application.

Tidewave is particularly valuable when onboarding new umbrella applications into the platform. A single command can produce a complete REST API layer with OpenAPI documentation, a property-based testing suite, and integration test scaffolding -- reducing what typically takes days to under an hour. This acceleration compounds across the platform's 90+ applications, where consistent patterns and quality gates must be maintained without manual enforcement bottlenecks.

Architecture

Module Introspection -> Semantic Model -> Code Generation -> Validation -> Output
        |                    |                |                |           |
   Code.fetch_docs/1    Function Map     Template Engine    Credo +      File Write
   @spec Analysis       Arity/Type       AI Expansion       Compile      + Format
   @moduledoc Parse     Documentation    Pattern Match      Test Run     Reload
   Behaviour Detection  Dependency Map   Style Conform      Dialyzer     Notify

Tidewave follows a pipeline architecture with three stages. The Analyzer stage introspects target modules using Elixir's reflection capabilities to build a semantic model of available functions, their arities, specs, and documentation. The Generator stage transforms this model into code artifacts using configurable templates and AI-assisted expansion. The Validator stage compiles generated code, runs Credo checks, and executes the generated tests to ensure correctness before writing files to disk.

Process Topology

PrismaticTidewave.Application (Supervisor, :one_for_one)
+-- PrismaticTidewave.Analyzer (GenServer)
|     Module introspection and semantic model construction
+-- PrismaticTidewave.Generator (DynamicSupervisor)
|     Concurrent code generation workers
+-- PrismaticTidewave.Validator (GenServer)
|     Compilation, Credo, Dialyzer, and test execution
+-- PrismaticTidewave.TemplateRegistry (GenServer)
|     ETS-cached generation templates with versioning
+-- PrismaticTidewave.Telemetry (setup)
      Generation metrics and output tracking

All three stages are supervised under a DynamicSupervisor, allowing concurrent generation across multiple target modules with automatic restart on failure. Each worker process is monitored by Telemetry events that report generation times, validation pass rates, and output artifact counts for observability.

Introspection-First Design

The fundamental design principle of Tidewave is that code generation should be informed by actual module behavior rather than assumptions based on naming conventions. The Analyzer stage uses four Elixir reflection mechanisms to build a complete semantic model of each target module.

Code.fetch_docs/1 retrieves the module's documentation, including @moduledoc, @doc, and @typedoc attributes. This documentation provides semantic context that guides API endpoint naming, test description generation, and OpenAPI documentation content.

Code.Typespec.fetch_specs/1 retrieves function type specifications. These specs define the input types, output types, and error conditions for each function, enabling Tidewave to generate accurate request validation, response serialization, and property-based test generators without manual type annotation.

Module.__info__(:functions) lists all exported functions with their arities. Combined with the documentation and specs, this provides a complete catalog of the module's public interface.

Behaviour detection identifies which behaviours the module implements (GenServer, Supervisor, Application, custom behaviours). This information guides the generation of supervision tree integration, process lifecycle tests, and GenServer-specific API patterns.

defmodule PrismaticTidewave.SemanticModel do
  @type t :: %__MODULE__{
    module: module(),
    functions: [%{name: atom(), arity: non_neg_integer(), spec: term(), doc: String.t()}],
    behaviours: [module()],
    moduledoc: String.t() | nil,
    types: [%{name: atom(), definition: term()}],
    dependencies: [module()]
  }
end

The semantic model produced by the Analyzer is a structured representation of the module's public interface that the Generator stage uses as input. This model captures function signatures, return types, documentation strings, callback implementations, and dependency relationships in a format that is independent of the generation templates.

Key Features

API Generation

  • Automatic REST endpoint scaffolding from Ecto schemas and facade modules
  • OpenAPI 3.0 specification generation with accurate type mappings from @spec annotations
  • Request validation and response serialization derived from behaviour contracts
  • Phoenix router integration with proper scope and pipeline configuration

Test Automation

  • Property-based testing generation using StreamData for exhaustive input coverage
  • Integration test scaffolding with database sandbox and Phoenix LiveView endpoint setup
  • Edge case identification through boundary value analysis of type specs
  • Coverage gap detection by comparing generated tests against module function lists

Development Workflow

  • AI-assisted code review with platform-specific quality gates awareness
  • Refactoring suggestions that preserve OTP supervision tree integrity and process isolation
  • Documentation generation from module source and @moduledoc attributes
  • Architecture recommendations based on existing umbrella application patterns

Quality Integration

  • Generated code automatically validated against Dialyzer type specifications
  • Pattern matching completeness verification for generated function clauses
  • AIAD compliance checking for generated agent modules
  • Output artifacts tracked by Quality DNA for cross-session continuity

Generation Templates

The Generator stage uses configurable templates that encode the platform's coding patterns. Templates are version-controlled and updated as platform conventions evolve, ensuring that generated code always reflects current standards.

The API generation template produces a Phoenix controller with proper error handling, a router scope with authentication pipeline, an OpenAPI operation spec, and request/response serialization modules. The test generation template produces a comprehensive test file with unit tests for each function, property-based tests for data transformation functions, and integration tests with proper test setup and teardown.

Templates are extensible through a hook system. Before and after each generation step, hooks can modify the generated code to add application-specific logic. This extensibility enables domain teams to customize generated code for their specific requirements while inheriting the base quality standards from the platform templates.

TemplateOutputQuality Checks
API EndpointController + Router + OpenAPI specCredo, Dialyzer, compilation
Test SuiteUnit + property + integration testsCoverage, assertion completeness
DocumentationModuledoc + function docs + READMESpell check, link validation
Agent ModuleAIAD-compliant agent definitionAIAD schema validation
Storage AdapterAdapter module + contract testsContract test suite execution

Configuration

config :prismatic_tidewave,
  # AI model settings
  model: :qwen3_coder,
  fallback_model: :claude,
  temperature: 0.3,
  max_tokens: 4000,

  # Generation settings
  template_path: "priv/templates/",
  output_format: true,
  validation_enabled: true,

  # Concurrency
  max_concurrent_generators: 4,
  generation_timeout: 60_000,

  # Quality gates
  credo_strict: true,
  dialyzer_check: true,
  compile_check: true

Usage

# Generate API endpoints from a facade module
{:ok, endpoints} = PrismaticTidewave.generate_api(PrismaticPerimeter, router: PrismaticApiWeb.Router)

# Generate a full test suite for a module
{:ok, tests} = PrismaticTidewave.generate_tests(PrismaticDeduction.InferenceEngine,
  types: [:unit, :property, :integration])

# AI-assisted code review with platform standards
{:ok, review} = PrismaticTidewave.review("apps/prismatic_agents/lib/prismatic_agents/registry.ex",
  checks: [:otp_patterns, :naming, :typespecs, :error_handling])

# Batch generation for a new umbrella app
{:ok, artifacts} = PrismaticTidewave.scaffold(:prismatic_new_app,
  facades: [NewApp.Facade],
  generate: [:api, :tests, :docs])

# Analyze a module to inspect its semantic model
{:ok, model} = PrismaticTidewave.analyze(PrismaticPerimeter.SecurityRating)
# => %SemanticModel{functions: [...], behaviours: [...], types: [...]}

Testing

mix test apps/prismatic_tidewave/test
mix test apps/prismatic_tidewave/test --cover
Test CategoryTestsWhat It Verifies
Module Introspection10Spec extraction, doc parsing, behaviour detection
API Generation8Endpoint correctness, router integration, OpenAPI accuracy
Test Generation8Property test validity, integration test setup, coverage
Validation Pipeline6Credo compliance, Dialyzer pass, compilation success
Template System4Hook execution, customization, version compatibility
Semantic Model6Model completeness, dependency resolution, type mapping

Integration Points

ApplicationRelationship
Prismatic CredoValidates generated code against platform quality rules before writing output
Prismatic APIModule introspection capabilities to understand existing endpoint patterns
Prismatic SafetyQuality Floor Guardian verifies generated code meets platform minimums
Prismatic Storage CoreGenerated tests integrate with PrismaticStorage.AdapterContractTest
Prismatic OllamaLocal AI model for code generation without cloud dependency
Prismatic ClaudeCloud AI fallback for complex generation tasks

NABLA Compliance

Generated code carries provenance metadata in module attributes that trace each generated artifact back to the source module, generation timestamp, and template version, satisfying the Provenance Mandatory axiom. The validation pipeline ensures that generated code meets the same quality standards as hand-written code, preventing quality degradation from automated generation. The introspection-first approach satisfies the Signal Plurality axiom by deriving code from multiple independent sources (specs, docs, behaviours, function signatures) rather than relying on a single convention.

NABLA AxiomTidewave EnforcementImplementation
Provenance MandatoryGenerated artifacts carry source module, timestamp, template versionModule attributes with generation metadata
Signal PluralityMultiple introspection sources inform generationSpecs + docs + behaviours + function signatures
Unknown ValidGeneration confidence reported per artifactValidation results include confidence scores

Performance

MetricValueNotes
Module analysis< 100msPer module AST introspection
API endpoint generation2-5sIncluding AI expansion
Test suite generation3-8sIncluding property test generators
Validation pipeline5-30sCompile + Credo + Dialyzer + test run
Full scaffold (1 app)30-60sAPI + tests + docs + validation
  • Quality Gates -- Generated code must pass all quality gate checks before acceptance
  • AIAD Standard -- Generated agent modules conform to AIAD specification format
  • Autonomous Self-Healing -- Tidewave regeneration as part of automated quality repair cycles

Connect & Contribute

Created by Tomáš Korcak (korczis) | Open Source under GHL