Skip to content
VerificationWould you notice if your agent drifted in production?Explore the 5-stage harness›
Specification Language

Introduction & Language Tour

TypeSpec (.tsp) is a concise, declarative API and data modeling language that feels natural to Dart and Flutter developers. Aegil compiles these high-level specifications directly into Serverpod PostgreSQL tables, zero-trust authorization filters, cross-stack validation logic, and reactive Flutter BLoCs.

Explore the complete language reference:

  1. Types, Nullability & Enums: Primitive scalars, nullability syntax (?), and enums.
  2. Models, Entities & Relations: Database tables, primary keys, and foreign keys.
  3. Operations: Queries, Mutations & Streams: @autoQuery, @autoMutation, @autoStream, and @mutation.
  4. Validation & Constraints: Field bounds (minLength, max, regex patterns).
  5. Access Control & CEL Policies: Row-level security rules and CEL expressions.
  6. State Machines & Lifecycle: Finite state machines and lifecycle transitions.
  7. Platforms & Permissions: Native platform shells and device permissions.
  8. Keywords & Decorators Reference: Full syntax reference table.

Dart developers are accustomed to strong typing, sound null safety, and expressive metadata annotations (@override, @immutable, @JsonSerializable).

TypeSpec brings that exact clarity to full-stack modeling. Instead of writing verbose YAML schemas or repetitive ORM classes in multiple languages, you write clean, declarative declarations in specs/<feature>/*.tsp.

namespace Helpdesk;
@entity({ table: "tickets" })
model Ticket {
@pk
id: uuid;
@owner
reporterId: uuid;
@validate({ minLength: 5, maxLength: 100 })
title: string;
status: TicketStatus = TicketStatus.Open;
createdAt: utcDateTime;
}

If you can write a Dart class, you already understand TypeSpec.


Feature folder organization (specs/<feature>/*.tsp)

Section titled “Feature folder organization (specs/<feature>/*.tsp)”

Aegil organizes domain specifications into modular feature folders:

specs/
app.tsp # Project identity and global metadata
platforms.tsp # Target platforms (@platform) & device permissions (@permission)
helpdesk/ # Feature folder
helpdesk.tsp # Ticket model, queries, mutations
comments.tsp # Optional sub-domain models for helpdesk
billing/ # Another feature folder
subscriptions.tsp # Invoices, plans, billing operations

The root boundary rule: Only root configuration (app.tsp and platforms.tsp) may live directly in specs/. All domain models, queries, and mutations must be placed inside a feature subfolder (e.g. specs/helpdesk/helpdesk.tsp). Placing domain specs directly at specs/tickets.tsp will be rejected by the compiler with ERR_SPEC_MISPLACED.


Type mappings: TypeSpec to Dart and PostgreSQL

Section titled “Type mappings: TypeSpec to Dart and PostgreSQL”

Aegil maps TypeSpec types directly to idiomatic Dart types and PostgreSQL database columns:

TypeSpec Type Dart Type (package:uuid, dart:core) PostgreSQL Column Type Example Value
string String text "Hello world"
int / int32 int integer 42
int64 int bigint 9007199254740991
float / float64 double double precision 3.14159
boolean bool boolean true, false
uuid UuidValue (or String representation) uuid "123e4567-e89b-12d3-a456-426614174000"
utcDateTime DateTime timestamp with time zone DateTime.now().toUtc()
T? T? (nullable) nullable column null
T[] List<T> jsonb array or relation target ["dart", "flutter"]
Page<T> Page<T> (cursor pagination) query result with next cursor Page(items: [...], nextCursor: "...")
enum Dart enum (lowerCamelCase values) text (serialized by name) TicketStatus.open

In TypeSpec, model defines a structured data type. Decorating a model with @entity({ table: "..." }) tells Aegil that this model is backed by a PostgreSQL database table:

@entity({ table: "tickets" })
model Ticket {
@pk
id: uuid;
@owner
reporterId: uuid;
@index
assignedAgentId?: uuid;
@validate({ minLength: 3, maxLength: 80 })
title: string;
description?: string;
createdAt: utcDateTime;
}
  1. Serverpod Server Model: A .spy.yaml file and Dart model class with table mapping, foreign keys, and indexes.
  2. PostgreSQL Migration: DDL statements creating the tickets table with primary keys, indexes, and nullability constraints.
  3. Client Protocol Model: A typed Dart class in package:<app>_flutter/api.dart with fromJson, toJson, and copy methods.
  4. Validation Logic: Both client-side and server-side checks enforcing that title is between 3 and 80 characters.

In Dart, you use annotations like @override or @JsonKey(name: 'first_name') to attach metadata for the compiler or code generators. In TypeSpec, decorators (starting with @) serve the exact same role.

TypeSpec Decorator Equivalent Concept in Dart / Serverpod What it tells Aegil
@entity({ table: "name" }) Serverpod table model (table: name) Back this model with a PostgreSQL table.
@pk Primary key (id: uuid or id: int32) Use this field as the primary key.
@owner Owner identification Designates caller ownership field for zero-trust security checks.
@index Serverpod database index Create a PostgreSQL index for fast querying.
@validate({ minLength, maxLength, min, max }) Custom validator or assert Generate boundary assertions on both client and server.
@relation({ name, target, kind }) Foreign key relationship Establish a oneToMany or manyToOne relationship.
@policy({ read, write, delete }) Row-Level Security (RLS) Restrict data access via CEL expressions compiled into SQL WHERE clauses.
@stateMachine({ field, states, transitions }) Finite State Machine (FSM) Enforce valid state transitions and guard rules.
@public Public API endpoint Bypass session authentication checks.
@health({ path }) Health check route Expose a lightweight HTTP liveness check route (e.g. /health).

Enums are declared cleanly in TypeSpec and compile to idiomatic Dart enums with lowerCamelCase member names:

enum TicketStatus {
Open,
InProgress,
Resolved,
Closed,
}

In Dart, this generates:

enum TicketStatus {
open,
inProgress,
resolved,
closed;
}

Aegil configures Serverpod to serialize enums by name (serialized: byName), keeping your database readable and portable.


In traditional development, creating an endpoint requires defining route paths, HTTP verbs, payload serializers, error handlers, and client methods.

In TypeSpec, you declare operations as concise function signatures:

1. Automatic Queries with Cursor Pagination (@autoQuery)

Section titled “1. Automatic Queries with Cursor Pagination (@autoQuery)”
@autoQuery({
entity: "Ticket",
paginate: "cursor",
filterBy: ["status", "assignedAgentId"],
sortBy: ["createdAt"]
})
op listTickets(limit?: int, status?: TicketStatus): Page<Ticket>;
@autoMutation({ entity: "Ticket", action: "create", touches: ["Ticket"] })
op createTicket(title: string, description?: string): Ticket;
@autoMutation({ entity: "Ticket", action: "update", touches: ["Ticket"] })
op updateTicket(id: uuid, title?: string, description?: string): Ticket;
@autoMutation({ entity: "Ticket", action: "delete", touches: ["Ticket"] })
op deleteTicket(id: uuid): boolean;
@mutation({ touches: ["Ticket"] })
op escalateTicket(ticketId: uuid, assignedAgentId: string): Ticket;

Aegil marks this operation as an agentTask in the Action Manifest and generates a hook interface in hooks/escalate_ticket_hook.dart for you or your AI agent to implement.


What you see Why What to do
ERR_SPEC_MISPLACED A domain spec file was placed in specs/ root rather than specs/<feature>/. Move domain specs into specs/<feature>/<feature>.tsp. Only app.tsp and platforms.tsp belong at root.
ERR_NAMESPACE_MISMATCH The namespace declared in .tsp does not match aegil.yaml. Ensure every .tsp file uses the exact namespace configured in aegil.yaml.
ERR_DUPLICATE_DECLARATION Two models, enums, or operations share the same name across .tsp files. Rename one of the declarations to be unique.
ERR_VALIDATION_SYNTAX A @validate decorator has invalid bounds (e.g. min > max or minLength < 0). Correct the validation arguments in the .tsp file.