Especificação Formal

IDL - Institutional Definition Language

Uma linguagem declarativa para especificar sistemas institucionais completos: atores, entidades, casos de uso, integrações e requisitos não-funcionais.

O que é IDL?

IDL (Institutional Definition Language) é uma linguagem de especificação que permite definir todos os aspectos de um sistema institucional de forma declarativa e validável.

📋 Declarativa

Descreva O QUE o sistema deve fazer, não COMO implementar. O motor Libervia cuida da implementação.

✓ Validada

Cada especificação passa por 3 gates de validação: estrutural, compilação e integridade SHA256.

🔗 Completa

Uma única especificação define atores, entidades, casos de uso, integrações e requisitos não-funcionais.

As 6 Seções do IDL

Todo arquivo IDL é composto por 6 seções obrigatórias que definem completamente um sistema.

1

SYSTEM

Metadados do sistema: nome, versão, domínio e descrição.

name version domain
2

ACTORS

Usuários e sistemas que interagem: humanos, sistemas internos e externos.

human system external
3

ENTITIES

Modelo de dados com campos tipados, modificadores e relacionamentos.

string required has_many
4

USECASES

Operações do sistema com atores, entidades, pré-condições e fluxos.

actor preconditions flow
5

INTEGRATIONS

Conexões com sistemas externos: APIs, webhooks, filas de mensagens.

rest_api webhook message_queue
6

NONFUNCTIONAL

Requisitos de performance, segurança, disponibilidade e compliance.

performance security compliance

Pipeline de Validação

Todo arquivo IDL passa por 3 gates de validação antes de ser aceito pelo motor.

1

GATE 1: Estrutural

Valida sintaxe YAML, seções obrigatórias e estrutura básica.

2

GATE 2: Compilação

Verifica tipos, referências cruzadas e consistência semântica.

3

GATE 3: Integridade

Calcula e valida hash SHA256 para garantir imutabilidade.

Referência de Sintaxe

Guia rápido dos tipos, modificadores e relacionamentos disponíveis no IDL.

Tipos de Dados

  • string Texto simples
  • text Texto longo
  • int Número inteiro
  • float Número decimal
  • decimal Precisão monetária
  • bool Verdadeiro/Falso
  • datetime Data e hora
  • uuid Identificador único
  • list<T> Lista de tipo T

Modificadores

  • required Campo obrigatório
  • unique Valor único
  • indexed Índice de busca
  • default(v) Valor padrão
  • min(n) Valor mínimo
  • max(n) Valor máximo
  • pattern(r) Regex de validação

Relacionamentos

  • has_one Tem um
  • has_many Tem muitos
  • belongs_to Pertence a
  • many_to_many Muitos para muitos

Tipos de Ator

  • human Usuário humano
  • system Sistema interno
  • external Sistema externo

Exemplos Completos

Três sistemas reais especificados em IDL, demonstrando todas as capacidades da linguagem.

PetClinic - Sistema Veterinário

Sistema completo para gestão de clínica veterinária com agendamentos, prontuários e faturamento.

petclinic.idl
# ═══════════════════════════════════════════════════════════════
# PetClinic - Sistema de Clínica Veterinária
# ═══════════════════════════════════════════════════════════════

SYSTEM:
  name: "PetClinic"
  version: "1.0.0"
  domain: "veterinary"
  description: "Sistema de gestão para clínicas veterinárias"

ACTORS:
  Veterinarian:
    type: human
    description: "Médico veterinário responsável por consultas"
    permissions:
      - "manage_appointments"
      - "access_medical_records"
      - "prescribe_treatments"

  Receptionist:
    type: human
    description: "Atendente de recepção"
    permissions:
      - "schedule_appointments"
      - "register_clients"
      - "process_payments"

  PetOwner:
    type: human
    description: "Tutor do animal"
    permissions:
      - "view_own_pets"
      - "request_appointments"
      - "view_invoices"

  NotificationService:
    type: system
    description: "Serviço de notificações automáticas"

ENTITIES:
  Owner:
    fields:
      name: string required
      email: string required unique
      phone: string required
      address: text
      cpf: string unique pattern("^\d{11}$")
    relations:
      pets: has_many Pet

  Pet:
    fields:
      name: string required
      species: string required  # dog, cat, bird, etc.
      breed: string
      birth_date: datetime
      weight: float min(0.1)
      microchip: string unique
    relations:
      owner: belongs_to Owner required
      appointments: has_many Appointment
      medical_records: has_many MedicalRecord

  Appointment:
    fields:
      scheduled_at: datetime required indexed
      type: string required  # consultation, vaccination, surgery
      status: string default("scheduled")
      notes: text
      duration_minutes: int default(30)
    relations:
      pet: belongs_to Pet required
      veterinarian: belongs_to Veterinarian required

  MedicalRecord:
    fields:
      date: datetime required
      diagnosis: text required
      treatment: text
      prescriptions: list<string>
      follow_up_date: datetime
    relations:
      pet: belongs_to Pet required
      veterinarian: belongs_to Veterinarian required
      appointment: belongs_to Appointment

USECASES:
  ScheduleAppointment:
    actor: Receptionist
    entities: [Pet, Appointment, Veterinarian]
    preconditions:
      - "Pet must be registered"
      - "Veterinarian must be available"
    flow:
      - "Search for pet by owner name or pet name"
      - "Select appointment type and preferred date"
      - "Check veterinarian availability"
      - "Create appointment record"
      - "Send confirmation to pet owner"
    postconditions:
      - "Appointment created with status 'scheduled'"
      - "Notification sent to owner"

  ConductConsultation:
    actor: Veterinarian
    entities: [Appointment, Pet, MedicalRecord]
    preconditions:
      - "Appointment exists and is scheduled for today"
    flow:
      - "Check in patient"
      - "Review pet history"
      - "Perform examination"
      - "Record diagnosis and treatment"
      - "Generate prescription if needed"
    postconditions:
      - "Medical record created"
      - "Appointment marked as completed"

INTEGRATIONS:
  SMSNotification:
    type: rest_api
    provider: "twilio"
    purpose: "Send appointment reminders"
    triggers:
      - "24h before appointment"
      - "On appointment confirmation"

  PaymentGateway:
    type: rest_api
    provider: "stripe"
    purpose: "Process payments"

NONFUNCTIONAL:
  performance:
    response_time: "<500ms for 95th percentile"
    concurrent_users: 50
  security:
    authentication: "JWT"
    data_encryption: "AES-256"
  compliance:
    - "LGPD"

E-Commerce - Loja Virtual

Sistema completo de e-commerce com catálogo, carrinho, pedidos e integrações de pagamento.

ecommerce.idl
# ═══════════════════════════════════════════════════════════════
# E-Commerce - Sistema de Loja Virtual
# ═══════════════════════════════════════════════════════════════

SYSTEM:
  name: "ECommerce"
  version: "2.0.0"
  domain: "retail"
  description: "Plataforma completa de comércio eletrônico"

ACTORS:
  Customer:
    type: human
    description: "Cliente da loja"
    permissions:
      - "browse_catalog"
      - "manage_cart"
      - "place_orders"
      - "view_order_history"

  StoreAdmin:
    type: human
    description: "Administrador da loja"
    permissions:
      - "manage_products"
      - "manage_inventory"
      - "view_reports"
      - "manage_promotions"

  InventorySystem:
    type: system
    description: "Sistema de controle de estoque"

  PaymentProvider:
    type: external
    description: "Gateway de pagamento externo"

ENTITIES:
  Product:
    fields:
      sku: string required unique indexed
      name: string required
      description: text
      price: decimal required min(0.01)
      stock_quantity: int default(0) min(0)
      weight_kg: float min(0)
      is_active: bool default(true)
      images: list<string>
    relations:
      category: belongs_to Category required
      reviews: has_many Review

  Category:
    fields:
      name: string required unique
      slug: string required unique indexed
      description: text
      image_url: string
    relations:
      parent: belongs_to Category
      products: has_many Product

  Customer:
    fields:
      email: string required unique indexed
      name: string required
      phone: string
      cpf: string unique pattern("^\d{11}$")
      created_at: datetime default(now())
    relations:
      addresses: has_many Address
      orders: has_many Order
      cart: has_one Cart

  Address:
    fields:
      label: string default("Principal")
      street: string required
      number: string required
      complement: string
      city: string required
      state: string required max(2)
      zip_code: string required pattern("^\d{8}$")
    relations:
      customer: belongs_to Customer required

  Cart:
    fields:
      updated_at: datetime
    relations:
      customer: belongs_to Customer required
      items: has_many CartItem

  CartItem:
    fields:
      quantity: int required min(1)
      unit_price: decimal required
    relations:
      cart: belongs_to Cart required
      product: belongs_to Product required

  Order:
    fields:
      order_number: string required unique indexed
      status: string default("pending")  # pending, paid, shipped, delivered
      subtotal: decimal required
      shipping_cost: decimal default(0)
      total: decimal required
      created_at: datetime required indexed
      tracking_code: string
    relations:
      customer: belongs_to Customer required
      shipping_address: belongs_to Address required
      items: has_many OrderItem
      payment: has_one Payment

  OrderItem:
    fields:
      quantity: int required min(1)
      unit_price: decimal required
      total: decimal required
    relations:
      order: belongs_to Order required
      product: belongs_to Product required

  Payment:
    fields:
      method: string required  # credit_card, pix, boleto
      status: string default("pending")
      amount: decimal required
      external_id: string
      paid_at: datetime
    relations:
      order: belongs_to Order required

USECASES:
  PlaceOrder:
    actor: Customer
    entities: [Cart, Order, OrderItem, Payment]
    preconditions:
      - "Cart has items"
      - "All items in stock"
      - "Valid shipping address"
    flow:
      - "Review cart items"
      - "Select shipping address"
      - "Calculate shipping cost"
      - "Select payment method"
      - "Create order from cart"
      - "Process payment"
      - "Reserve inventory"
      - "Clear cart"
    postconditions:
      - "Order created with unique number"
      - "Inventory updated"
      - "Confirmation email sent"

  ManageInventory:
    actor: StoreAdmin
    entities: [Product]
    flow:
      - "View current stock levels"
      - "Update stock quantities"
      - "Set low stock alerts"
    postconditions:
      - "Stock levels updated"
      - "Alerts configured"

INTEGRATIONS:
  PaymentGateway:
    type: rest_api
    provider: "mercadopago"
    purpose: "Process payments via PIX, credit card, boleto"
    endpoints:
      - "POST /payments"
      - "GET /payments/{id}"

  ShippingCalculator:
    type: rest_api
    provider: "correios"
    purpose: "Calculate shipping costs"

  EmailService:
    type: message_queue
    provider: "sendgrid"
    purpose: "Transactional emails"
    events:
      - "order.created"
      - "order.shipped"
      - "order.delivered"

NONFUNCTIONAL:
  performance:
    response_time: "<200ms for catalog"
    concurrent_users: 1000
    transactions_per_second: 100
  availability:
    uptime: "99.9%"
  security:
    authentication: "OAuth2"
    pci_dss: true
  compliance:
    - "LGPD"
    - "CDC"

HRSystem - Gestão de RH

Sistema de recursos humanos com gestão de funcionários, folha de pagamento e benefícios.

hrsystem.idl
# ═══════════════════════════════════════════════════════════════
# HRSystem - Sistema de Gestão de Recursos Humanos
# ═══════════════════════════════════════════════════════════════

SYSTEM:
  name: "HRSystem"
  version: "1.5.0"
  domain: "human_resources"
  description: "Sistema integrado de gestão de recursos humanos"

ACTORS:
  HRManager:
    type: human
    description: "Gestor de RH"
    permissions:
      - "manage_employees"
      - "manage_payroll"
      - "manage_benefits"
      - "view_reports"

  Employee:
    type: human
    description: "Funcionário da empresa"
    permissions:
      - "view_own_profile"
      - "request_time_off"
      - "view_payslips"
      - "update_personal_info"

  Manager:
    type: human
    description: "Gestor de equipe"
    permissions:
      - "view_team"
      - "approve_time_off"
      - "conduct_reviews"

  PayrollSystem:
    type: system
    description: "Sistema de processamento de folha"

  GovernmentAPI:
    type: external
    description: "APIs do eSocial"

ENTITIES:
  Employee:
    fields:
      employee_id: string required unique indexed
      name: string required
      email: string required unique
      cpf: string required unique pattern("^\d{11}$")
      hire_date: datetime required indexed
      birth_date: datetime required
      status: string default("active")  # active, on_leave, terminated
      salary: decimal required min(0)
      pis: string unique
      ctps: string
    relations:
      department: belongs_to Department required
      position: belongs_to Position required
      manager: belongs_to Employee
      time_off_requests: has_many TimeOffRequest
      payslips: has_many Payslip
      benefits: many_to_many Benefit

  Department:
    fields:
      name: string required unique
      code: string required unique indexed
      cost_center: string
    relations:
      head: belongs_to Employee
      employees: has_many Employee

  Position:
    fields:
      title: string required
      level: string required  # junior, pleno, senior, lead
      salary_range_min: decimal
      salary_range_max: decimal
      cbo_code: string  # Classificação Brasileira de Ocupações
    relations:
      employees: has_many Employee

  TimeOffRequest:
    fields:
      type: string required  # vacation, sick_leave, personal
      start_date: datetime required
      end_date: datetime required
      status: string default("pending")  # pending, approved, rejected
      reason: text
      approved_by: string
      approved_at: datetime
    relations:
      employee: belongs_to Employee required

  Payslip:
    fields:
      reference_month: string required indexed  # YYYY-MM
      gross_salary: decimal required
      inss_deduction: decimal
      irrf_deduction: decimal
      other_deductions: decimal default(0)
      bonuses: decimal default(0)
      net_salary: decimal required
      payment_date: datetime
    relations:
      employee: belongs_to Employee required

  Benefit:
    fields:
      name: string required unique
      type: string required  # health, dental, meal, transport
      provider: string
      monthly_cost: decimal
      employee_contribution: decimal default(0)
    relations:
      employees: many_to_many Employee

USECASES:
  RequestTimeOff:
    actor: Employee
    entities: [TimeOffRequest]
    preconditions:
      - "Employee is active"
      - "Has available balance for request type"
    flow:
      - "Select time off type"
      - "Choose start and end dates"
      - "Check balance availability"
      - "Submit request"
      - "Notify manager"
    postconditions:
      - "Request created with pending status"
      - "Manager notified for approval"

  ProcessPayroll:
    actor: PayrollSystem
    entities: [Employee, Payslip, Benefit]
    preconditions:
      - "All employee data complete"
      - "Benefits enrollment confirmed"
    flow:
      - "Calculate gross salary for each employee"
      - "Apply INSS deductions"
      - "Apply IRRF deductions"
      - "Apply benefit deductions"
      - "Calculate net salary"
      - "Generate payslips"
      - "Submit to eSocial"
    postconditions:
      - "Payslips generated for all employees"
      - "eSocial events submitted"

  HireEmployee:
    actor: HRManager
    entities: [Employee, Department, Position, Benefit]
    flow:
      - "Enter employee personal data"
      - "Assign department and position"
      - "Set salary and hire date"
      - "Enroll in mandatory benefits"
      - "Generate employee ID"
      - "Submit admission to eSocial"
    postconditions:
      - "Employee created with active status"
      - "eSocial S-2200 event submitted"

INTEGRATIONS:
  eSocial:
    type: rest_api
    provider: "governo_federal"
    purpose: "Submit labor events to government"
    events:
      - "S-2200: Admissão"
      - "S-2206: Alteração contratual"
      - "S-2299: Desligamento"
      - "S-1200: Remuneração"

  BankingAPI:
    type: rest_api
    provider: "banco_brasil"
    purpose: "Process salary payments"

  BenefitProviders:
    type: webhook
    purpose: "Sync benefit enrollment"
    providers:
      - "unimed"
      - "odontoprev"
      - "alelo"

NONFUNCTIONAL:
  performance:
    response_time: "<1s for reports"
    payroll_processing: "<30min for 1000 employees"
  security:
    authentication: "SSO/SAML"
    data_encryption: "AES-256"
    audit_logging: true
  compliance:
    - "LGPD"
    - "CLT"
    - "eSocial"
  availability:
    uptime: "99.5%"
    backup: "Daily with 30-day retention"