BlackLang Documentation

BlackLang

BlackLang, AI ajanlarının uygulama niyetini kısa, net ve doğrulanabilir bir kaynak dille yazması için tasarlanan deterministik bir dildir.

Current version: 0.1.0-dev Target: Web + API-only applications Source: .black / .black.enc Theme: .blackthm
Minimal fikir
Human request
  to AI coding agent
  to .black source
  to black compiler
  to generated web/API application

İlk hedef Python veya JavaScript'i tamamen değiştirmek değildir. İlk hedef, web uygulamalarında tekrar eden model, form, tablo, validation, API ve güvenlik niyetlerini daha küçük bir kaynak temsille anlatmaktır.

Quick Start

En küçük çalışan akış bir `.black` dosyası yazmak, validate etmek ve web çıktısı üretmektir. AI ajanı da insan geliştirici de aynı dosyayı okuyup aynı sonucu alır.

examples/warehouse/app.black
app Warehouse

entity Product {
  sku text required unique
  name text required
  photo image optional accept "image/*"
  stock number default 0
  price money
  computed inventoryValue money = stock * price label "Inventory Value"
}

action RestockProduct {
  source Product
  input quantity number required min 1 label "Quantity"
  value restockValue = quantity
  if restockValue > 0 and stock >= 0
    set stock = stock + restockValue
  else
    set stock = stock
  success "Stock updated"
}

transaction RestockAtomic {
  action RestockProduct
}


page Products {
  source Product

  table {
    columns sku, name, stock, price, inventoryValue
    search sku, name
  }

  form {
    fields sku, name, stock, price
  }

  actions create, edit, delete, RestockProduct
}

Bu blok Product verisini, Products ekranını, tablo kolonlarını, form alanlarını ve CRUD/custom action davranışlarını tek kaynakta toplar. Generator bu niyetten TypeScript, React, API, validation ve database tarafını üretir.

Kurulum

BlackLang'in hedef dağıtımı tek binary modelidir. Olgun sürümde kullanıcı sadece `black` komutunu indirip çalıştırabilmelidir; compiler için ayrıca Python veya Node.js zorunlu olmamalıdır.

Bugünkü public bootstrap
git clone https://github.com/enesburul-arch/blacklang.git
cd blacklang/packages/cli
go run ./cmd/black --help
go run ./cmd/black version --json
go run ./cmd/black docs agent-contract --json
go run ./cmd/black validate ../../examples/warehouse/app.black --json
go run ./cmd/black build ../../examples/warehouse/app.black --out ../../generated --json

`black` komutu sistemde yoksa resmi geçici yol budur: repo klonlanır ve CLI `packages/cli` içinden `go run ./cmd/black ...` ile çalıştırılır. Signed GitHub Release arşivleri ve npm yolu yaygın public kurulum için planlanır; npm paketi platforma uygun binary'yi çağırır, compiler mantığı yine tek binary içinde kalır.

Proje Yapısı

BlackLang projelerinde kaynak gerçekliği `.black` dosyalarıdır. Generated dosyalar compiler çıktısıdır ve normalde elle düzenlenmez.

Temel klasör mantığı
blacklang/
  BLACKLANG.md
  SPEC.md
  AGENTS.md
  blacklang.toml
  examples/
    warehouse/
      app.black
  generated/
  packages/
    cli/

AI ajanı projeye girdiğinde önce yerel öğrenme dosyalarını ve `blacklang.toml` sürüm bilgisini okur. Sonra sadece gereken `.black` kaynaklarını değiştirir.

Syntax Temeli

Dil kısa olmalı ama şifreli olmamalıdır. `app`, `target`, `entity`, `page`, `table`, `form`, `actions`, `when` gibi tanıdık kelimeler AI'nin ilk okuma maliyetini düşürür.

Top-level bloklar
app Warehouse

target web {
  frontend react
  backend node
  database sqlite
}

entity Product {
  name text required
}

page Products {
  source Product
}

Her davranış için tek syntax hedeflenir. Bu, hem compiler hatalarını daha stabil yapar hem de AI ajanının "hangi kullanım doğru" diye tahmin yürütmesini azaltır.

app

`app`, uygulamanın adını belirler. Bir BlackLang projesinde tam olarak bir ana uygulama adı olmalıdır.

Syntax
app Warehouse

Generator bu adı package metadata, arayüz başlığı ve çıktı dokümantasyonu gibi yerlerde kullanabilir. İsim PascalCase yazıldığında hem insan hem AI için daha okunaklı kalır.

target

`target`, `.black` kaynağının hangi platform ve generated stack için yazıldığını açıkça belirtir. Current web generator React frontend, Node backend ve SQLite, PostgreSQL veya MySQL runtime üretebilir; API-only target aynı backend/runtime yüzeyini React ve Vite dosyaları olmadan üretir.

Web target
target web {
  frontend react
  backend node
  database sqlite
}
API-only target
target api {
  backend node
  database sqlite
}

PostgreSQL için aynı blokta `database postgres`, MySQL için `database mysql` yazılır. Bu seçim Prisma provider'ı, provider adapter'ı ve Docker Compose database servisi üretir. `target api`, Express server, Prisma, OpenAPI, validation, API smoke test, seed/job/deploy/ops çıktısını üretir; `index.html`, Vite, React page/component, frontend smoke, browser-check, browser e2e ve matrix dosyalarını üretmez. Browser `test` deklarasyonları yalnızca `target web` içinde desteklenir. Mobile, desktop veya farklı backend hedefleri generator gerçekten o çıktıları üretebildiğinde açılmalıdır. Blok yoksa mevcut generator eski varsayılan stack'i kullanır: `web`, `react`, `node`, `sqlite`.

entity

`entity`, saklanacak uygulama verisini anlatır. Normal web stack'te model, validation, database schema ve API type parçalarına bölünen niyet burada tek blokta ifade edilir.

Ürün modeli
entity Product {
  sku text required unique length 3..40
  name text required label "Product Name"
  photo image optional accept "image/*" label "Product Photo"
  stock number default 0 min 0
  price money min 0
  computed inventoryValue money = stock * price label "Inventory Value"
  index stock
}

Field adı solda, tipi yanında, kuralları ise aynı satırda yer alır. `image` yerel formdan data URL olarak okunan stored media field üretir. `computed` database kolonu değildir; `index` ise stored field database index niyetini generator'a taşır. Bu sıra, AI'nin satırı tek seferde okuyup veri niyetini anlamasını kolaylaştırır.

computed

`computed`, saklanan field'lardan okuma amaçlı hesaplanan değer üretir. İlk sürümde database kolonu değildir, form input'u değildir; generated table ve detail UI içinde hesaplanır.

Computed display field
entity Product {
  stock number default 0
  price money default 0
  tax money default 0
  computed inventoryValue money = stock * (price + tax) label "Inventory Value"
}

page Products {
  source Product

  table {
    columns stock, price, inventoryValue
  }
}

v0.2 syntax'ı `computed name type = numericExpression` şeklindedir. Desteklenen tipler `number`, `integer`, `decimal`, `money`; expression içinde `+`, `-`, `*`, `/`, parantez ve deterministic operator precedence desteklenir. Operand'lar aynı entity içindeki number-like field'lar veya numeric literal değerler olmalıdır.

Generated React mantığı
function computeInventoryValue(item: Product) {
  const value = Number(item.stock ?? 0) * Number(item.price ?? 0);
  return Number.isFinite(value) ? value : null;
}

Bir computed field, kaynak aldığı field'lardan biri role/field-level permission ile gizlenmişse generated UI'da kendisi de gizlenir. Search, filter ve sort desteği sonraki data logic aşamasına bırakılmıştır.

media

`file` ve `image`, generated web app içinde yerel dosya seçimi için stored scalar field tipleridir. Generator upload provider kurmaz; form seçilen dosyayı data URL olarak okur, API validation zincirinden geçirir ve string kolon olarak saklar.

Local media fields
entity Product {
  photo image optional accept "image/*" label "Product Photo"
  specSheet file optional accept "application/pdf" label "Spec Sheet"
}

page Products {
  source Product

  table {
    columns photo, specSheet
  }

  form {
    fields photo, specSheet
  }
}

Generated UI image değerlerini thumbnail, file değerlerini link olarak gösterir. OpenAPI içinde `x-blacklang-media` ve `x-blacklang-encoding: data-url` metadata'sı yer alır. `accept` sadece file/image entity field'larında geçerlidir; storage bucket, token ve özel endpoint değerleri `.black` içine yazılmaz.

AI commands
black docs media --json
black explain media --json
black inspect examples/warehouse/app.black --affected Product.photo --json

relation-load

Relation load policy, entity relation field'larının generated API response içinde hangi context'lerde ilişki objesini attach edeceğini `.black` kaynakta belirler. Böylece tablo, detay, query sonucu ve mutation response davranışı generated JS'e dokunmadan, deterministic ve AI-readable kalır.

Relation response load policy
entity Order {
  customer Customer required load list detail query mutation label "Customer"
  total money default 0
}

Desteklenen scope'lar `list`, `detail`, `query`, `mutation` ve `none` değerleridir. `load` yazılmazsa eski davranış korunur ve relation obje tüm response context'lerinde attach edilir. `load none`, sadece generated relation ID field'ını bırakır. Generated list/query route'lar relation ID'lerini batch toplayıp her relation field için tek target lookup yapar; permission-aware build attached target record'ları sanitize eder. Bu policy database schema'yı değiştirmez ve custom query filtrelerine relation join eklemez.

AI commands
black docs relation-load --json
black explain relation-load --json
black inspect examples/warehouse/app.black --affected Order.customer --json

Generated OpenAPI operations `x-blacklang-relation-load-context` ve `x-blacklang-relation-load` metadata'sı taşır. Bu metadata, ajanların hangi route response'unun relation object beklediğini hızlıca anlamasını sağlar.

index

`index`, stored entity field'ları için database index niyetini `.black` kaynakta tutar. Generator Prisma schema içinde `@@index`, SQLite setup içinde de `CREATE INDEX IF NOT EXISTS` üretir.

Stored field index
entity Order {
  customer Customer required
  status text default draft
  index customer, status
}

Relation field index'leri generated foreign-key kolona maplenir; örneğin `index customer, status`, Prisma tarafında `@@index([customerId, status])` olur. Computed display field'lar database kolonu olmadığı için indexlenemez. Index değişikliği için `black inspect app.black --affected Order.index --json` generated database schema/setup etkisini gösterir.

migration

`migrate plan`, eski ve yeni `.black` source dosyasını karşılaştırır ve generated database shape değişikliklerini deployment öncesi risk seviyelerine ayırır. Komut read-only çalışır; database'e bağlanmaz, SQL uygulamaz, dosya yazmaz. Explicit rename deklarasyonları ise generated `db:setup`/`db:push` içinde schema setup öncesi idempotent uygulanır.

Read-only schema migration plan
black migrate plan app-v1.black app-v2.black --json
black migrate plan app-v1.black app-v2.black --ir

JSON çıktısında `success`, `safe`, `destructive`, `summary`, `changes`, `steps` ve `changes[].risk` alanları bulunur. `safe` risk stored data shape'i koruyan değişiklikleri ve explicit rename'i, `manual` backfill veya veri kontrolü isteyen değişiklikleri, `destructive` ise tablo/kolon silme, generated kolon adı değişimi veya tip dönüşümü gibi veri kaybı ihtimali olan değişiklikleri ifade eder.

Explicit rename migration
migration RenameProductName {
  rename entity ProductItem to Product
  rename field Product.title to name
}

Entity ve field rename otomatik tahmin edilmez. `to` entity veya stored field current source içinde var olmalı, `from` adı current source içinde kalmamalıdır. Build çıktısı `migrations/manifest.json`, `migrations/*.sql`, `src/migrate.ts`, `src/setup-db.ts` ve Prisma `BlackMigration` ledger modelini üretir.

Generated migration runner
npm run db:migrate:plan
npm run db:migrate
npm run db:setup

`db:migrate:plan` target database'e read-only bakar; SQLite'ta eksik DB dosyasını oluşturmaz ve PostgreSQL connection string değerini JSON'a basmaz. `db:migrate` yalnızca declared rename migration'larını uygular, sonucu `BlackMigration` ledger'ına işler ve ardından `db:setup` normal generated setup ve seed yolunu çalıştırır.

seed

`seed`, local demo ve test fixture verisini `.black` kaynağında deterministik şekilde tanımlar. Row key stable generated `id` olur; generated `db:setup` schema setup sonrası `db:seed` çalıştırır ve declared rows idempotent upsert edilir.

Warehouse: deterministic fixture rows
seed DemoProducts {
  source Product

  row DemoProductLow {
    tenantId "default"
    sku "LOW-001"
    name "Low Stock Widget"
    stock 3
    price 19.99
  }
}

seed DemoOrders {
  source Order

  row DemoOrderDraft {
    customer ref DemoCustomerAcme
    total 320.50
  }
}

Seed değerleri stored field'lara yazılır. Text/email/date/datetime literal'ları tırnaklıdır; numeric ve boolean değerler tırnaksızdır. Relation field'lar `ref OtherRowKey` kullanır ve referans verilen row ilgili entity için tanımlı olmalıdır. Computed display field, generated system field, raw SQL, expression, environment read ve secret değerleri seed içinde desteklenmez.

AI için kısa öğrenme ve etki analizi
black docs seed --json
black explain seed --json
black inspect --affected DemoProducts --json
black inspect --affected seed --json
black validate --json
black build --json
cd generated && npm run db:setup

Tam kurallar seed referansında, stabil hata kodları diagnostics referansında bulunur. Seed tanımları JSON, BlackIR, inspect/affected, benchmark generated file kinds ve generated `package.json`/`src/seed.ts` çıktısında görünür.

query

`query`, düşük stok gibi özel listeleri saklanan entity field'ları üzerinden tanımlar. Filtre, aggregate summary, sıralama ve kayıt sınırı server tarafında uygulanır; aynı sorgu birden fazla generated sayfaya bağlanabilir.

Warehouse: düşük stok listesi
query LowStockProducts {
  source Product
  where stock < 10
  aggregate lowStockCount count
  aggregate totalStock sum stock
  aggregate averagePrice avg price
  sort stock asc
  limit 50
}

page LowStock {
  source Product
  query LowStockProducts

  table {
    columns sku, name, stock, price, inventoryValue
    search sku, name
    paginate 10
  }

  actions RestockProduct
}

Bu örnek, yukarıdaki Product modelinden stok adedi 10'dan küçük olan en fazla 50 ürünü seçer. Stok artan sıradadır; eşit stok değerlerinde `id asc` kullanılır. LowStock sayfası `RestockProduct` aksiyonunu kullanır; aksiyon sonrası query ve summary tekrar yüklenir. Summary kartları düşük stok sayısını, toplam stoğu ve ortalama fiyatı gösterir. Computed `inventoryValue` tabloda gösterilebilir; query koşulunda, sort alanında veya aggregate field olarak kullanılamaz.

Query top-level tanımlanır ve tek `source Entity` kullanır. Sayfa kendi `source` satırını korur, `query Name` ile sorguya bağlanır; iki source aynı olmalıdır. Birden fazla `where` satırı AND ile birleşir. `aggregate name count` rows sayar; `aggregate name sum|avg|min|max field` stored numeric field ister. Tek bir opsiyonel `sort field asc|desc` kullanılabilir. Sort yoksa varsayılan `id asc`; limit yoksa varsayılan 100'dür. `limit`, 1 ile 1000 arasında tam sayı olmalıdır.

Field tipine göre literal örnekleri
where status == "draft"
where stock < 10
where price >= 12.50
where active == true
where dueDate < "2026-09-06"
where scheduledAt >= "2026-09-06T12:00:00Z"

Her koşul query source entity'sinde bulunan, örnekteki tipe uygun bir field gerektirir. Text/email/date/datetime değerleri tırnaklı, numeric ve boolean değerler tırnaksızdır. `number` ve `integer` 32-bit tam sayı; `decimal` ve `money` sonlu ondalık literal kabul eder. `==` ve `!=` tüm desteklenen stored primitive tiplerde; `<`, `<=`, `>`, `>=` numeric/date/datetime tiplerinde geçerlidir. Relation, computed ve generated system field'ları, parametreler, OR, join, raw SQL ve arbitrary code bu MVP'nin dışındadır.

Generated LowStock sayfası `GET /api/lowstock/query` ve `GET /api/lowstock/query/summary` üzerinden yüklenir. Summary route aynı source, where, archive ve row policy kurallarını kullanır; sort ve limit'i uygulamaz. Mevcut entity listesi ve CRUD route'ları kendi davranışını sürdürür; relation seçenekleri normal entity listesinden gelir. Sayfaya bağlanmamış query bağımsız endpoint oluşturmaz. Table search/filter/pagination ve opsiyonel table sort, server'ın döndürdüğü sınırlı liste üzerinde çalışır. Bağlı sayfadaki başarılı mutation sonrası query yeniden yüklenir.

Auth, page access, entity read, response field hiding ve entity row policy kuralları korunur. Koşul, sort veya aggregate alanı mevcut role için okunabilir değilse query endpoint'i 403 döndürür. Query filtreleri liste seçimidir; ownership/tenant authorization için entity içinde `policy` kullanılır.

AI için kısa öğrenme ve etki analizi
black docs query --json
black explain query --json
black inspect --affected LowStockProducts --json
black inspect --affected Product.stock --json
black validate --json
black build --json

Tam kurallar query referansında, stabil hata kodları diagnostics referansında bulunur. Query tanımı ve page bağlantısı JSON, BlackIR, inspect/affected ve generated OpenAPI çıktısında görünür.

job

`job`, public endpoint açmadan generated worker içinde read-only query işi çalıştırır. İlk MVP güvenli ve deterministik kalır: tek schedule syntax'ı, tek run mode ve query tabanlı kayıt seçimi vardır.

Warehouse: düşük stok monitor job'u
job LowStockMonitor {
  schedule every 15 minutes
  run query LowStockProducts
}

`run query`, mevcut bir top-level query'ye bağlanır. Worker query'nin stored-field `where`, deterministic `sort` ve `limit` kurallarını uygular, yalnızca kayıt ID'lerini seçer ve job adı, schedule, query, source, count, limit ve timestamp içeren kompakt JSON log üretir.

Generated output
jobs/manifest.json
src/worker.ts
npm run jobs:run
npm run jobs:loop
openapi.json x-blacklang-jobs

Desteklenen schedule aralıkları `1..1440 minutes`, `1..168 hours` ve `1..365 days` şeklindedir. Queue provider, retry, delayed queue, mutating job, external call, provider scheduler config, cron expression syntax ve arbitrary code bu MVP dışındadır.

AI için kısa öğrenme ve etki analizi
black docs job --json
black explain job --json
black inspect --affected LowStockMonitor --json
black inspect --affected LowStockProducts --json
black build --json
cd generated && npm run jobs:run

Tam kurallar job referansında, stabil hata kodları diagnostics referansında bulunur. Job tanımı JSON, BlackIR, inspect/affected, generated worker, package scripts ve OpenAPI metadata çıktısında görünür.

action

`action`, CRUD dışındaki güvenli satır işlemlerini `.black` içinde tanımlar. Örneğin stok eklemek, bir talebi onaylamak veya bir kaydı iş kuralına göre güncellemek için tek bir deterministik action declaration kullanılabilir.

Warehouse: stok ekleme aksiyonu
action RestockProduct {
  source Product
  input quantity number required min 1 label "Quantity"
  value restockValue = quantity
  if restockValue > 0 and stock >= 0
    set stock = stock + restockValue
  else
    set stock = stock
  allow Admin, Worker
  success "Stock updated"
}

transaction RestockAtomic {
  action RestockProduct
  api StockWebhook
}

page Products {
  source Product
  actions edit, RestockProduct
}

Action top-level tanımlanır ve tek `source Entity` kullanır. Page aynı source ile `actions ..., ActionName` yazdığında generator route, client metodu, input validation, row button, form panel, OpenAPI schema ve auth/role varsa audit log üretir. Page'e bağlanmamış action bağımsız endpoint oluşturmaz.

Input'lar primitive field type ve normal validation modifier kullanır. `number` ve `integer` mevcut SQLite/Prisma runtime'da 32-bit tam sayı olarak validate edilir; kesirli değer için `decimal` veya `money` kullanılmalıdır. Input adı source entity field adıyla çakışamaz; böylece `set` expression içindeki identifier'ların anlamı tek kalır.

`value`, action içinde sıralı local expression adı üretir; daha sonraki `value`, `set` ve `if` satırları bu adı kullanabilir. Python-like indentation-based `if`/`else` branch'leri `value`, `set` ve nested `if` statement'larını taşır. `set`, yalnızca saklanan primitive source field'larını değiştirebilir. Değerler typed literal, action input, source field, local value veya bounded numeric expression olabilir. Numeric expression için `+`, `-`, `*`, `/`, parantez ve deterministic precedence desteklenir. Condition comparison'ları `==`, `!=`, `<`, `<=`, `>` ve `>=` kullanır; comparison'lar `and`, `or`, `not` ve parantez ile bağlanabilir, precedence `not`, sonra `and`, sonra `or` şeklindedir. Computed display field, relation field, entity policy field, join, aggregate, raw SQL, function call, loop, external call ve multi-row mutation MVP dışındadır.

Atomic çalışma niyeti action içinde değil, top-level `transaction` bloğunda durur. Böylece action yalnızca mutation'ı anlatır; transaction bloğu generated action/API update route'unun source row lookup, deterministic update ve auth/role varsa audit log yazımını tek `prisma.$transaction` içinde çalıştırır.

Generated runtime contract
POST /api/products/:id/actions/restockproduct

{
  "quantity": 7
}

Runtime page access, entity update permission, yazılan her field için field-level update permission, entity row policy ve opsiyonel action `allow` kuralını birlikte uygular. Query-bound sayfada aksiyon başarılı olursa liste server query'den tekrar yüklenir.

AI için kısa öğrenme ve etki analizi
black docs action --json
black docs transaction --json
black docs service --json
black explain action --json
black explain transaction --json
black explain service --json
black inspect --affected RestockProduct --json
black inspect --affected RestockAtomic --json
black inspect --affected InventoryIntegration --json
black inspect --affected Product.stock --json
black validate --json
black build --json

Tam kurallar action referansında, stabil hata kodları diagnostics referansında bulunur. Action tanımı JSON, BlackIR, inspect/affected ve generated OpenAPI çıktısında görünür.

transaction

`transaction`, mevcut custom action veya explicit API update handler için atomic generated runtime boundary bildirir. Yeni endpoint üretmez; hangi write route'unun Prisma transaction içinde çalışacağını deterministik şekilde işaretler.

Action/API update route transaction binding
transaction RestockAtomic {
  action RestockProduct
  api StockWebhook
}

Her hedef tek satırdır: `action ActionName` veya `api ApiName`. API hedefleri bounded single-line veya block-form update handler'a sahip olmalıdır. Bir action/API aynı anda yalnızca bir transaction bloğuna bağlanabilir.

Generator targeted custom action route'larında ve explicit API update handler'larında lookup, update ve audit log işini `prisma.$transaction` içine alır. Request parsing, auth, page access ve field permission kontrolleri transaction açılmadan önce çalışır. OpenAPI targeted operasyonlara `x-blacklang-transaction` ve `x-blacklang-transaction-name` metadata'sı ekler.

AI için kısa öğrenme ve etki analizi
black docs transaction --json
black explain transaction --json
black inspect --affected RestockAtomic --json
black validate --json
black build --json

service

`service`, mevcut explicit API deklarasyonlarını generated service/module metadata altında gruplar. Endpoint üretmez ve handler tanımlamaz; route sözleşmesi hâlâ top-level `api` bloğundadır. Service bloğu AI ajanları, OpenAPI client üreticileri ve API-only projeler için hangi endpointlerin aynı servis yüzeyine ait olduğunu kompakt biçimde görünür kılar.

Explicit API service grouping
service InventoryIntegration {
  api StockWebhook
}

Her hedef tek satırdır: `api APIName`. Bir API aynı anda yalnızca bir service bloğuna bağlanabilir. Bu seçim generated `services/manifest.json`, `src/services/<service>.ts`, OpenAPI root `tags`, root `x-blacklang-services` ve operation-level `x-blacklang-service` metadata'sı üretir.

Transaction ile service ayrı niyetlerdir: `transaction` atomic runtime boundary'yi, `service` ise API module boundary'yi anlatır. Warehouse örneğinde `StockWebhook` hem `RestockAtomic` transaction'ına hem `InventoryIntegration` service'ine bağlıdır.

AI için kısa öğrenme ve etki analizi
black docs service --json
black explain service --json
black inspect --affected InventoryIntegration --json
black inspect --affected StockWebhook --json
black validate --json
black build --json

policy

`policy`, generated web route'larında owner ve tenant satır kapsamını `.black` kaynağında açıkça tanımlar. Bu, query'den farklıdır: query hangi listeyi istediğini, policy ise o listenin hangi güvenli satır havuzundan okunacağını söyler.

Owner ve tenant row policy
auth {
  strategy emailPassword
  session cookie
  user {
    name text required
    email email required
  }
}

entity Order {
  tenantId text required default "default"
  ownerId text required default "system"
  total money default 0
  status text default draft
  policy tenant tenantId
  policy owner ownerId
}

page Orders {
  source Order
  actions create, edit, delete
  table {
    columns total, status
  }
  form {
    fields total, status
  }
}

Policy field'ı aynı entity içinde saklanan `text required` field olmalıdır ve `unique` olamaz. `policy owner ownerId`, satırı authenticated user `id` değerine; `policy tenant tenantId`, satırı authenticated user `tenantId` değerine bağlar. Generated auth runtime tenant alanını `BlackUser` üzerinde üretir ve yeni kullanıcılar için varsayılan tenant `"default"` olur. Tenant policy varsa generated Users sayfası kullanıcı tenant ID değerini düzenleyebilir.

Policy field'ları database kolonu olarak kalır, fakat generated form input'u, API client input type'ı veya OpenAPI input schema alanı olmaz. Create/update route'ları bu değerleri current user context'ten damgalar; list, query, detail, archive, restore, delete, workflow transition ve custom action route'ları aynı scope ile çalışır. Custom action `set` satırları policy field yazamaz.

AI için kısa öğrenme ve etki analizi
black docs policy --json
black explain policy --json
black inspect --affected policy --json
black inspect --affected Order.ownerId --json
black validate --json
black build --json

Tam kurallar policy referansında, stabil hata kodları diagnostics referansında bulunur. Policy tanımı JSON, BlackIR, inspect/affected, generated route, API client ve OpenAPI çıktısında görünür.

Field Tipleri

Field tipi verinin nasıl saklanacağını ve hangi validation davranışlarının üretileceğini belirler.

Desteklenen temel tipler
name text required
stock number default 0
quantity integer min 1
price money min 0
email email unique
active boolean default true
createdAt datetime

v0.1 alan tipleri: `text`, `number`, `integer`, `decimal`, `money`, `email`, `boolean`, `date`, `datetime`. Entity adı da relation tipi olarak kullanılabilir. Mevcut generated Prisma runtime'da `number` ve `integer` tam sayı, `decimal` ve `money` kesirli sayı için kullanılır.

Modifier örnekleri
sku text required unique length 3..40 regex "^[A-Z0-9]+$"
website text optional url
discount money min 0
name text required placeholder "Enter product name" help "Visible in lists"

page

`page`, generated web uygulamasındaki ekran niyetini anlatır. Sayfa hangi entity'den beslenecek, hangi tablo ve form alanlarını gösterecek, hangi aksiyonları açacak burada belirlenir.

Sayfa tanımı
page Products {
  source Product

  table {
    columns sku, name, stock, price
    search sku, name
  }

  form {
    fields sku, name, stock, price
  }

  actions create, edit, delete
}

`source`, var olan bir entity'yi göstermelidir. Table ve form alanları source entity içinde yoksa validator stabil hata kodu üretir. İsteğe bağlı `query Name` satırı, listeyi aynı source entity'yi kullanan özel sorguya bağlar. `actions` satırı CRUD davranışlarının yanında aynı source entity'ye sahip custom action adlarını da açabilir.

view

`view`, bir page içindeki generated section sırasını, reusable component section'ları ve ilk layout composition niyetini `.black` kaynakta kontrol eder. Böylece table/detail/form/component yerleşimi için React veya CSS çıktısını elle düzenlemek gerekmez.

Sayfa içi section composition
page Products {
  source Product

  view {
    order table, StockSummary, StockCards, detail, form
    compose grid columns 2 gap md stackAt md
    section table span 2
    section StockSummary component StockBadge bind selected span 1 title "Stock Summary"
    section StockCards component StockBadge bind each span 1 title "Stock Cards"
    section detail display drawer side right title "Product Details"
    section form display modal title "Product Form"
    trigger detail on rowSelect
    trigger form on createStart
    trigger form on editStart
    trigger detail on saveSuccess
    trigger table on close
  }

  table {
    columns sku, name, stock, price
  }

  form {
    fields sku, name, stock, price
  }
}

Desteklenen section adları `table`, `detail`, `form` ve açıkça declared component section adlarıdır. `compose stack` dikey akışı korur; `compose grid`, `columns 1..4`, `gap sm|md|lg` ve `stackAt sm|md|lg|none` seçeneklerinden deterministik CSS grid üretir. `compose tabs`, `tab List sections table` ve `tab Record sections StockSummary, StockCards, detail, form` gibi satırlardan generated React tab control üretir. Generated JSX/DOM section sırası effective `view.order` ile aynıdır; CSS order kuralları stable metadata ve layout backstop olarak kalır. `stackAt`, grid için canonical responsive breakpoint syntax'ıdır; generator lg/md/sm media query'leri üretir ve responsive kolon sayısından büyük section span'lerini clamp eder. `section table span 2` grid span'ini belirler; `section StockSummary component StockBadge bind selected` declared component'i selected row'a bağlı reusable inline panel olarak üretir. `section StockCards component StockBadge bind each`, aynı component'i loaded list/query collection içindeki her row için render eder. `section detail display drawer side right` ve `section form display modal` generated detail/form panellerini overlay olarak açar. `group Record sections detail, form compose stack gap md span 1 title "Record"` contiguous inline section'ları tek generated wrapper altında toplar. `trigger detail on rowSelect`, `trigger form on createStart|editStart`, `trigger detail|table on saveSuccess` ve `trigger table on close` generated tab/overlay akışını deterministik hale getirir. Component section input'ları source entity'deki stored veya computed field'larla isim/tip olarak eşleşmelidir. Modal/drawer display ve group, tabs ile bu MVP'de birleşmez; arbitrary frontend handler'lar sonraki layout aşamalarına bırakılmıştır.

table

`table`, listeleme yüzeyini tarif eder. Kolonlar, arama alanları, filtreler, sıralama ve pagination aynı blokta tutulur.

Tablo davranışı
table {
  columns sku, name, stock, price
  search sku, name
  filter stock
  sort stock desc
  paginate 10
}

Generator table tanımından React liste görünümü, search state, filtre kontrolleri, pagination ve field bazlı görünürlük kontrollerini üretebilir. Query'ye bağlı sayfalarda bu araçlar query'nin döndürdüğü sınırlı liste üzerinde çalışır; table sort belirtilmezse query sırası korunur.

form

`form`, create ve edit işlemlerinde kullanılacak alanları belirler. Field metadata varsa label, placeholder, help ve inline validation mesajları buradan üretilir.

Form alanları
form {
  fields sku, name, stock, price
}

Relation field kullanıldığında generator select input üretir. Zorunlu relation için ilişkili kayıt yoksa submit kapatılıp kullanıcıya önce hangi kaydı oluşturması gerektiği gösterilir.

actions

`actions`, sayfada hangi veri işlemlerinin aktif olacağını söyler. Aynı liste, API route üretimini ve arayüz kontrol görünürlüğünü etkiler.

Desteklenen action değerleri
actions create, edit, delete, archive, restore, RestockProduct

`archive`, soft delete mantığıyla `archivedAt` set eder. `restore`, kaydı tekrar görünür yapar. PascalCase değerler, page source'u ile aynı source'a sahip top-level custom action tanımlarına bağlanır. Role sistemi varsa action butonları izinlere göre gizlenir.

layout

`layout`, sayfaların generated uygulama kabuğunda hangi sırayla görüneceğini kontrol eder. Şimdilik sidebar odaklıdır.

Sidebar düzeni
layout AdminLayout {
  sidebar {
    item Products
    item Customers
    item Orders
  }
}

page Products {
  layout AdminLayout
  source Product
}

Explicit layout yoksa navigation sayfa tanım sırasından türetilebilir. Küçük ekranlarda generated app drawer menüye geçer.

auth

`auth`, giriş ve oturum niyetini kaynak dil seviyesinde tanımlar. v0.1 email ve password stratejisiyle cookie session üretimini destekler.

Cookie session auth
auth {
  strategy emailPassword
  session cookie

  user {
    name text required
    email email required unique
  }
}

Bu blok register, login, logout, `/api/auth/me`, password hashing ve cookie session davranışlarının üretilmesine temel olur.

role ve access

`role`, kullanıcı izinlerini tanımlar. `access`, sayfanın hangi role veya auth kapsamına açık olduğunu söyler.

Rol ve sayfa erişimi
role Admin {
  allow all
}

role Worker {
  allow read Product
  deny read Product price
  allow update Product stock
}

page Products {
  source Product
  access Admin, Worker
}

Generated API, sayfa ve action seviyesinde izinleri uygular. Field-level `deny` ile hassas alanlar API response ve React görünümünden gizlenebilir.

workflow

`workflow`, bir entity'nin iş süreci durumlarını ve geçişlerini tanımlar. Özellikle sipariş, destek talebi, onay akışı gibi sistemlerde kullanılır.

Durum geçişleri
workflow OrderPreparation {
  source Order
  states draft, picking, verified, packaged, shipped

  transition ship {
    from packaged
    to shipped
    allow Admin
  }
}

Workflow source entity içinde `status text` olmalıdır. Generator transition route, permission check, status update, UI button ve audit log kaydı üretebilir.

state

`state`, generated React ekranında kullanılacak client-side UI durumunu ifade eder. Modal, seçili kayıtlar ve aktif filtre gibi davranışlar burada tanımlanabilir.

Sayfa state'i
state OrdersPageState {
  selectedOrders Order[]
  activeFilter text
  modal createOrder closed
}

`OrdersPageState` veya `OrdersState`, `page Orders` ile eşleşebilir. Modal tanımı open/close helper üretimine temel olur.

component

`component`, tekrarlı UI niyetlerini kaynak seviyesinde tanımlar. İlk kullanımda field değerine göre variant seçimi desteklenir.

StockBadge
component StockBadge {
  input stock number

  variant low when stock < 10
  variant normal when stock >= 10
}

Tek input, entity field adı ve tipiyle eşleşirse generated table, detail ve form preview alanlarında otomatik kullanılabilir. Page `view` içinde `section StockSummary component StockBadge bind selected` yazıldığında aynı component selected source record'a bağlı reusable inline page section olarak render edilir; `bind each` ise loaded list/query collection üstünde bir component listesi üretir.

theme

`.blackthm`, BlackLang'in UI tema ve profil bilgisini raw CSS yerine deterministik kaynak olarak saklaması için eklenen ilk dosya formatıdır. Generator artık bu dosyadaki okuma sırasını kullanarak kompakt inline UI değerlerini CSS property'lerine bağlayabilir.

Warehouse theme profile
blackthm WarehouseTheme {
  version 1
  target web
  locked true

  token color primary "#2563eb"
  token color surface "#ffffff"
  token space sm 8
  token radius md 6

  profile UICompact {
    version 1
    baseline box color width style pt pr pb pl radius place
    baseline text color size weight align
    baseline table color width style density zebra
    baseline button bg color radius size variant

    ui box = color width style pt pr pb pl radius place;
    ui text = color size weight align;
    ui table = color width style density zebra;
    ui button = bg color radius size variant;
  }
}
Inspect command
black theme inspect --json
black theme inspect examples/warehouse/theme.blackthm --ir
black theme migrate old.blackthm new.blackthm --json

Hex renkler tırnak içinde yazılır, çünkü `#` tırnak dışında comment başlatır. `profile.modeGroups` standart UI gruplarını, `profile.baselines` kilitli sırayı, `profile.modes[].slots` ise güncel sırayı gösterir. Compiler, locked profilde UI slot sırasının baseline ile başlamasını zorunlu tutar. Theme değiştirirken `black theme migrate`, eski inline UI değerlerinin aynı slotlara bağlanmaya devam edip etmediğini raporlar.

theme-migration

`theme migrate`, eski ve yeni `.blackthm` dosyasını karşılaştırır ve profil değişikliğinin mevcut `.black` inline UI değerlerini yanlış slotlara kaydırıp kaydırmayacağını söyler. Komut read-only çalışır; theme veya generated çıktıyı değiştirmez.

Migration check
black theme migrate theme-v1.blackthm theme-v2.blackthm --json
black theme migrate theme-v1.blackthm theme-v2.blackthm --ir
Safe append-only change
ui box = color width style;
ui box = color width style shadow;

Güvenli migration için theme adı, target, profile adı ve sürüm yönü uyumlu kalır; eski her mode yeni profilde bulunur; eski slot listesi yeni slot listesinin birebir prefix'i olur. Yeni slotlar sadece sona eklenirse JSON'da `slot-appended` olarak görünür. Araya slot ekleme, reorder veya silme `UI_SLOT_MIGRATION_BREAK` diagnostic kodunu üretir.

ui-profile

UI profile, `.black` içinde yazılan kompakt `ui` satırlarının hangi sırayla okunacağını belirler. Amaç, CSS benzeri uzun anahtarlar yazmadan generator için tek anlamlı bir stil niyeti vermektir.

Slot order
profile UICompact {
  version 1
  baseline box color width style pt pr pb pl radius place
  baseline text color size weight align
  baseline table color width style density zebra
  baseline button bg color radius size variant

  ui box = color width style pt pr pb pl radius place;
  ui text = color size weight align;
  ui table = color width style density zebra;
  ui button = bg color radius size variant;
}
Inline mapping
ui box black 1 solid 8 8 5 5 6 center | text "#172026" 14 regular left

Değerler soldan sağa okunur. Eksik sondaki değerler default alır, fazladan değer hata sayılır, aynı mode içinde aynı slot iki kez yazılamaz. Profile kilitlendiğinde mevcut slotlar taşınamaz; yeni slotlar sadece sona eklenir. `ui = ;` generator'ın okuma sırasıdır. Araya slot eklenirse compiler `NON_APPEND_ONLY_UI_SLOT` hatası verir.

ui-modes

Standart UI mode grupları, kompakt `ui` satırlarının hangi görsel bağlama ait olduğunu compiler ve AI ajanı için açık hale getirir. Web profilleri `box`, `text`, `table` ve `button` gruplarını içermelidir.

Standart gruplar
box     form, panel ve component container stilleri
text    label, heading, help text ve body typography
table   tablo border, density ve row pattern stilleri
button  generated veya explicit action control stilleri
Theme inspect JSON
{
  "profile": {
    "modeGroups": [
      {
        "name": "box",
        "required": true,
        "defaultSlots": ["color", "width", "style", "pt", "pr", "pb", "pl", "radius", "place"],
        "appliesTo": ["field", "form", "table", "component", "panel"]
      }
    ],
    "modes": [
      {
        "name": "box",
        "standard": true,
        "slots": ["color", "width", "style", "pt", "pr", "pb", "pl", "radius", "place"]
      }
    ]
  }
}

Standart gruplardan biri eksikse `black theme inspect --json` `MISSING_STANDARD_UI_MODE` diagnostic kodu döner. Bu kural, inline UI intent ve CSS generation aşamalarında her projenin aynı temel görsel sözlüğü paylaşmasını sağlar.

inline-ui

`ui`, görsel niyeti `.black` dosyasında ilgili field, form, table veya action button yanında tutar. Web target artık bu intent bilgisinden stable `.bl-ui-*` class adları ve `src/styles.css` içinde CSS kuralları üretir.

Field, table, form ve action button
entity Product {
  name text required ui text "#172026" 14 semibold left
}

page Products {
  source Product

  table {
    id ProductsTable
    class inventoryTable
    columns name
    ui table border 1 solid compact true
  }

  form {
    id ProductForm
    class inventoryForm
    fields name
    ui box black 1 solid 8 8 5 5 6 center | text "#172026" 14 regular left
  }

  actions create, RestockProduct
  action create id CreateProductButton
  action create class primaryAction
  action create ui button primary white 6 md solid
  action RestockProduct id RestockProductButton
  action RestockProduct class restockAction
  action RestockProduct ui button success white 6 sm solid
}
Explicit UI identity
table {
  id ProductsTable
  class inventoryTable compactPanel
}

form {
  id ProductForm
  class inventoryForm
}

action create id CreateProductButton
action create class primaryAction
action RestockProduct id RestockProductButton
action RestockProduct class restockAction
Geçerli mode bağlamları
field   box, text
form    box, text, button
table   box, text, table
button  button

`action ui button ...`, aynı page içindeki CRUD veya custom action listesine bağlıdır. Mode hataları `UNSUPPORTED_UI_MODE`, yanlış bağlamlar `UNSUPPORTED_UI_TARGET_MODE`, tekrar eden mode kullanımı `DUPLICATE_UI_INTENT` olarak raporlanır. `id` ve `class` değerleri generated HTML'de kebab-case'e çevrilir; row action butonlarında tekrarlı DOM id oluşmaması için `-item-<recordId>` gibi suffix'ler eklenir. Field satırında normal modifier'lar `ui` öncesinde kalmalıdır.

Generated class düzeni
table   .bl-ui-table-<page>
form    .bl-ui-form-<page>
field   .bl-ui-field-<entity>-<field>
action  .bl-ui-action-<page>-<action>

i18n

`i18n`, generated web uygulamasının başlangıç dilini, desteklenen locale listesini, runtime field/UI text ve display formatting davranışını tanımlar.

Locale ve field text translation
i18n {
  default tr
  locales tr, en
}

label Product.name {
  tr "Ürün Adı"
  en "Product Name"
}

label app.title {
  tr "Depo"
  en "Warehouse"
}

label page.Products {
  tr "Ürünler"
  en "Products"
}

label action.create {
  tr "Oluştur"
  en "Create"
}

placeholder Product.name {
  tr "Ürün adını gir"
  en "Enter product name"
}

help Product.name {
  tr "Listelerde görünen ürün adı"
  en "Visible product name in lists"
}

message Product.stock {
  tr "Geçerli bir stok adedi gir"
  en "Enter a valid stock count"
}

Birden fazla locale varsa generator App içine language selector üretir ve aktif locale'i sayfalara geçirir. App shell `lang` ve deterministic `dir` attribute'larını üretir. App chrome, navigation page name, table tool, status label, CRUD/custom action button, workflow transition button, form label, table header, detail label, column visibility label, filter label, form placeholder, form help text ve field-level frontend validation message alanları kullanıcı dil değiştirdiğinde yeniden render olur. Table/detail number, integer, decimal, money, date ve datetime değerleri aktif locale ile `Intl` üzerinden formatlanır. Computed display field label'ları aynı `label Entity.computedField { ... }` biçimini kullanır; placeholder/help/message translation blokları stored form field hedefler.

Generated field text fallback sırası
1. placeholder Product.name { tr "Ürün adını gir" }
2. name text placeholder "Enter product name"
3. deterministic generated fallback
Generated UI label targets
app.title
app.menu
app.language
page.Products
action.create
action.RestockProduct
action.new.Product
action.edit.Product
table.search
table.columns
table.previous
status.active
status.loadingRecords

api

`api`, generated CRUD dışındaki explicit endpoint niyetlerini anlatır. v0.2 bu bilgiyi OpenAPI çıktısına taşır ve generated Express server içinde declared-runtime route olarak üretir. POST/PUT/PATCH endpointleri typed body doğrulaması ve bounded update handler ile güvenli iş mantığı taşıyabilir.

Explicit API declared runtime
api LowStockReport {
  method GET
  path "/api/reports/low-stock/{warehouseId}"
  param warehouseId text
  query limit integer
  private
}

api StockWebhook {
  method POST
  path "/api/webhooks/stock"
  body tenantId text required
  body sku text required
  body stock number required min 0
  update Product where sku == body.sku {
    value incomingStock = body.stock
    if incomingStock >= 0 and tenantId == body.tenantId
      set stock = incomingStock
    else
      set stock = stock
  }
  respond accepted
  webhook
  public
}

`black build` generated OpenAPI contract oluşturur ve aynı deklarasyondan path/query/body parametrelerini doğrulayan route üretir. Service bloğuna bağlı API'ler OpenAPI `tags`, `x-blacklang-service`, root `x-blacklang-services`, `services/manifest.json` ve `src/services/<service>.ts` metadata çıktısı alır. Handler update'leri `id` veya stored `unique` field ile tek bounded row seçer, stored primitive non-policy field'ları günceller ve OpenAPI'de `x-blacklang-handler` metadata'sı yayımlar. Block-form update handler'lar ordered local `value`, indentation-based `if`/`else` ve nested deterministic branch statement'ları taşıyabilir. Webhook route'ları `202 accepted`, private route'lar ise projede `auth` varsa auth middleware arkasında çalışır.

security

BlackLang kaynak dosyaları yüksek değerli source asset olarak görülür. Secret, password, API key, token ve private key değerleri `.black` dosyasına yazılmamalıdır.

Doğru secret yaklaşımı
database {
  url env DATABASE_URL
}

security {
  cors {
    origins env CORS_ORIGINS
    credentials true
  }
}
Kaçınılacak kullanım
database {
  url "postgres://user:password@example.com/app"
}

Production deployment için hedef, mümkünse `.black` kaynaklarını sunucuya taşımadan generated production artifact yayınlamaktır. `black security scan --json` olası hardcoded secret izlerini raporlar.

Generated web/API output `security/secrets.json`, `scripts/secrets-plan.mjs` ve `scripts/secrets-provider.mjs` üretir. `npm run security:secrets:plan`, `DATABASE_URL`, CORS env'i, cloud env'leri ve observability endpoint gibi referansların environment readiness durumunu JSON olarak raporlar. `npm run security:secrets:preflight`, provider label/prefix ve provider CLI availability bilgisini kontrol eder; secret değerlerini fetch etmez veya yazdırmaz.

Public install ve package/adapter publish akışları için `scripts/verify-release-trust.mjs` read-only verifier vardır. `release.blackdir`, `checksums.sha256`, archive hash'leri, detached Ed25519 `<artifact>.sig` dosyaları, `BLACKLANG_RELEASE_PUBLIC_KEY` veya `BLACKLANG_RELEASE_PUBLIC_KEY_FILE` public key referansı, release transparency metadata'sı ve key rotation policy uyuşmadan strict trust workflow publish-ready vermez.

protected source

`.black.enc`, BlackLang kaynak dosyasını production paketlerinden ayırmak ve gerektiğinde güvenilir developer/CI ortamında bellekten build etmek için eklenen protected source formatıdır.

Encrypted source komutları
black security encrypted-source --json
BLACKLANG_SOURCE_KEY=local-key black security encrypt app.black --out app.black.enc --json
BLACKLANG_SOURCE_KEY=local-key black security decrypt app.black.enc --stdout

Encrypted dosya `BLACKLANG-ENC v1`, `AES-256-GCM`, `SHA256-ENV`, `keyEnv` ve nonce içeren küçük bir plaintext header taşır; source body encrypted base64 ciphertext olarak saklanır. Key değeri `.black` veya `.black.enc` içine yazılmaz, yalnızca environment'tan okunur.

`parse`, `lint`, `validate`, `inspect`, `benchmark`, `security scan` ve `build`, gerekli key environment variable set edildiğinde `.black.enc` source'u bellekte okuyabilir. `black format` encrypted source dosyalarını rewrite etmez; plaintext source formatlanıp tekrar encrypt edilmelidir. Production package hem `.black` hem `.black.enc` dosyalarını dışarıda bırakır.

cors

`cors`, tarayıcıdan generated API'ye hangi origin'lerin erişebileceğini tanımlar. Domain listesi `.black` içine gömülmez; deployment ortamında environment olarak verilir.

CORS policy
security {
  cors {
    origins env CORS_ORIGINS
    credentials true
  }
}

Generated Express server `CORS_ORIGINS` değerini virgülle ayrılmış liste olarak okur, listede olmayan browser origin'lerini `403` ile reddeder, `OPTIONS` preflight yanıtı üretir ve `credentials true` varsa cookie-auth uyumlu header ekler.

deploy

`deploy`, generated web uygulamasının production ortamında nasıl ayağa kalkacağını tarif eder. İlk çalışan hedef Docker'dır.

Docker deployment
deploy {
  target docker
  port env PORT default 3001
  env DATABASE_URL required
  env CORS_ORIGINS optional
  preview local
  rollback keep 3
  cloud fly app env FLY_APP_NAME region env FLY_REGION
}

Bu niyet `Dockerfile`, `.dockerignore`, `docker-compose.yml`, `.env.example` içinde `PORT`, generated `package.json` içinde `start` scripti ve generated server içinde `process.env["PORT"]` kullanımı üretir. `preview local`, `docker-compose.preview.yml`, `BLACKLANG_PREVIEW_PORT` ve preview scriptleri üretir. `rollback keep 3`, `deploy/manifest.json`, `deploy/rollback.json` ve read-only rollback plan scripti üretir. `cloud fly app env FLY_APP_NAME region env FLY_REGION`, `deploy/cloud.json`, deploy manifest cloud metadata'sı, read-only cloud plan/preflight scriptleri ve açık apply gerektiren provider CLI runner üretir. SQLite target'ında local database `/app/data` altında tutulur; PostgreSQL ve MySQL target'larında ayrı database service, service healthcheck ve app `DATABASE_URL` fallback'i üretilir. MySQL compose çıktısı `MYSQL_*` local env default'larını da taşır. `ops.health` varsa Dockerfile ve docker-compose app service healthcheck'i aynı path'i probe eder.

ops

`ops`, generated web uygulamasına public runtime probe endpoint'leri ve structured request log niyeti ekler. Bu bölüm deploy sonrası “process ayakta mı, database hazır mı, temel sayaçlar ne durumda?” sorularını generated dosya düzenlemeden cevaplar.

Runtime operation signals
ops {
  health path "/healthz"
  readiness path "/readyz"
  metrics path "/metrics"
  logging requests
  observe otlp endpoint env BLACKLANG_OTLP_ENDPOINT
}

`health path`, uptime, start time, app adı ve compiler version bilgisini dönen public GET endpoint üretir. `readiness path`, generated database adapter üzerinden `SELECT 1` çalıştırır ve database ulaşılamazsa `503` döner. `metrics path`, process-local request, error ve status-code sayaçlarını gösterir. `logging requests`, her gözlenen istek bitince tek satır JSON log yazar. `observe webhook endpoint env NAME`, env set edilmişse response yolunu bloklamadan structured request event POST eder. `observe otlp endpoint env NAME` aynı observe syntax'ı ile non-blocking OTLP HTTP JSON trace payload üretir. Observe middleware W3C `traceparent` context üretir veya gelen context'i taşır.

Ops path'leri root-level public path olmalıdır; `/api`, `/openapi.json`, query string, fragment, brace, whitespace ve unsafe karakterler reddedilir. Route'lar API auth ve CSRF middleware'inden önce üretildiği için infrastructure health check'leri login akışına takılmaz.

Generated contract
GET /healthz
GET /readyz
GET /metrics

OpenAPI:
x-blacklang-ops: health | readiness | metrics
x-blacklang-public: true
x-blacklang-observability: webhook | otlp
ops/observability.json: provider + exporter metadata

Generated contract/API smoke testleri ops path, observability metadata, trace context ve lokal hook/exporter delivery davranışını doğrular. `deploy { target docker }` ile beraber `health path` varsa Dockerfile ve docker-compose healthcheck'i Node'un built-in `fetch` fonksiyonuyla aynı public path'i çağırır.

AI için kısa öğrenme ve etki analizi
black docs ops --json
black explain ops --json
black inspect --affected ops --json
black validate --json
black build --json
cd generated && npm test

CLI

CLI, AI ajanlarının BlackLang projesini tahmin ederek değil compiler'dan öğrenerek değiştirmesini sağlar. Önemli komutlar JSON çıktı verebilmelidir.

AI dostu komutlar
black version --json
black agent startup --json
black format --check --json
black lint --json
black parse examples/warehouse/app.black --json
black validate examples/warehouse/app.black --json
black build examples/warehouse/app.black --json
black inspect --ir
black inspect examples/project-management/app.black --affected ProjectTask.status --json
black theme inspect --json
black docs migrate --json
black explain migrate --json
black migrate plan old.black new.black --json
black docs ui --json
black docs ui-modes --json
black docs query --json
black explain query --json
black inspect --affected LowStockProducts --json
black docs action --json
black explain action --json
black inspect --affected RestockProduct --json
black docs policy --json
black explain policy --json
black inspect --affected policy --json
black docs ops --json
black explain ops --json
black inspect --affected ops --json
black docs generated-test --json
black docs benchmark --json
black benchmark --json
black benchmark tasks --json
black ide --json
black ide diagnostics examples/warehouse/app.black --json
black audit accessibility --json
black security encrypted-source --json
black security encrypt app.black --out app.black.enc --json
black security decrypt app.black.enc --stdout
black docs --all --json
black explain entity --json
black security scan --json

`agent startup`, AI ajanına proje girişinde okunacak dosyaları, source/out yollarını, generated dosya sınırlarını ve doğrulama komutlarını tek JSON çıktıda verir. `ide`, compiler-owned completion, snippet ve diagnostic metadata üretir. `ide diagnostics`, editor-friendly zero-based range'lerle format, parse, validate ve source-security bulgularını döner. `lint` format, parse, validate ve source-security bulgularını tek raporda toplar. `inspect --affected`, bir entity, field, policy, ops, migration, query, action, page, role, workflow, state, component veya api değiştiğinde hangi kaynak parçalarının ve generated dosyaların etkileneceğini JSON olarak döner. `migrate plan`, eski/yeni `.black` source arasındaki database shape farklarını read-only şekilde safe/manual/destructive olarak sınıflandırır. `explain`, tek keyword için amaç, syntax, örnek, agent notu ve hata kodlarını döner. `docs generated-test`, build sonrası generated app içindeki contract/API/frontend/browser-check smoke test ve browser e2e davranışını açıklar. `docs test`, `.black` kaynak içindeki deterministic browser test niyetini açıklar. `benchmark`, source/generated dosya ve satır ölçümünü geçici build üzerinden üretir. `audit accessibility`, generated UI intent için source-level erişilebilirlik policy finding'leri üretir. `security encrypt/decrypt`, `.black.enc` protected source akışını environment key ile yönetir.

IDE Metadata and Diagnostics

BlackLang IDE desteği compiler-owned contract olarak başlar. Editor, LSP bridge veya AI ajanı keyword/snippet/diagnostic listesini kopyalamak yerine `black ide` çıktısından okur. Bu sayede autocomplete ve diagnostics davranışı local compiler sürümüyle aynı kalır.

IDE contract
black ide --json
black ide --ir
black ide diagnostics examples/warehouse/app.black --json
black ide diagnostics examples/warehouse/app.black --ir

`black ide --json`; language id, `.black`/`.blackthm` extension bilgisi, completion items, canonical snippets ve diagnostic code catalog döndürür. `black ide diagnostics <file> --json`, source'u değiştirmeden format, parse, validate ve source-security bulgularını zero-based, end-exclusive range'lerle verir. Okunabilir ama hatalı dosyada `success: true` ve `valid: false` döner; böylece editor ordinary source diagnostics'i command failure ile karıştırmaz. `editors/vscode-blacklang` içindeki packageable editor bridge bu contract'ı kullanarak VS Code, Open VSX ve Cursor-compatible VSIX kanalları için dynamic autocomplete/snippet, diagnostics, format quick fix ve affected-symbol inspection sağlar.

Ecosystem Discovery

BlackLang core her provider'ı içine almak yerine package, release, registry, editor, adapter ve marketplace bilgisini compiler-owned discovery çıktısıyla görünür kılar. `black ecosystem --json`, local npm wrapper, VS Code/Open VSX/Cursor-compatible editor package channel metadata, release manifest/checksum/signature trust akışı, release transparency/key rotation policy, prepared package registry manifestleri, built-in target/deploy, cloud deploy, observability adapterları, prepared provider adapter marketplace manifestlerini ve `publicIndex.path` üzerinden `website/ecosystem-index.json` static index kaynağını tek deterministik raporda verir.

Ecosystem contract
black ecosystem --json
black ecosystem --ir
black docs release-trust --json
black docs package-registry --json
black docs adapter-marketplace --json
black docs editor-marketplace --json
node scripts/verify-release-trust.mjs artifacts/releases/<version> --json --strict
node packages/registry/scripts/validate-registry.mjs
cd packages/npm && npm test
cd editors/vscode-blacklang && npm test
cd editors/vscode-blacklang && npm run package:vsix

`packages/npm` native `black` binary'sine forward eden ince npm/npx wrapper'dır. `editors/vscode-blacklang` da `black ide` contract'ını tüketen ince editor bridge'dir; aynı kaynak VS Code Marketplace, Open VSX ve Cursor-compatible VSIX kanal metadata'sına bağlanır. `packages/registry/package-index.blackdir` ve `adapters/marketplace/adapter-index.blackdir` package/provider ekosistemini stable ID'lerle listeler; trust policy dosyaları external publish veya provider mutation öncesi koşulları açıklar. `packages/registry/public-index.blackdir` ve `website/ecosystem-index.json` gelecekte hosted package/provider adapter discovery için deploy edilebilir, secret-free index kaynağını temsil eder. `release.trust`, Ed25519 detached signature pattern'ini, public key env adlarını, strict verifier command'ini, transparencyLog metadata'sını ve keyRotation policy'sini gösterir. `deploy-cloud:docker-provider` Docker image cloud plan/preflight metadata'sını ve explicit apply provider CLI runner sınırını, `observability:webhook` request event hook'unu, `observability:otlp` ise env-referenced OTLP HTTP trace exporter metadata'sını bildirir. Provider-specific davranışlar core syntax'a girmeden önce extension/adapter disiplininden geçmelidir: parser, validator, docs, JSON/BlackIR, diagnostics, affected analysis, tests, manifest metadata, signed package verification, trust checks ve kısa AI öğrenme dokümanı.

Generated Contract/API/Frontend/Browser-Check/E2E/Matrix Tests

`black build`, web ve API-only output içinde deterministik contract/API smoke testleri üretir. `target web` ayrıca frontend ve declared browser-check smoke testleri ile gerçek browser e2e testini ve cross-browser matrix runner'ını üretir. Bu testler, generated app'in OpenAPI sözleşmesini, validation yüzeyini, temel HTTP davranışını, React render zincirini ve `.black` içinde yazılan page/action/text beklentilerini target'a göre kontrol eder.

Generated app içinde
cd generated
npm test
npm run test:e2e:plan
npm run test:e2e:matrix

Test dosyaları her target için `src/blacklang.contract.test.ts` ve `src/blacklang.api.test.ts` içinde üretilir. Generated `npm test` önce `npm run db:generate` çalıştırır, sonra smoke test dosyalarını koşar. `target web` ayrıca `src/blacklang.frontend.test.tsx` ve kaynak `test` deklarasyonları varsa `src/blacklang.browser.test.tsx`, `src/blacklang.e2e.test.ts`, `src/blacklang.e2e.matrix.ts` ve `tests/browser-matrix.json` üretir. `target api` React, Vite, frontend smoke, browser-check, e2e ve matrix test dosyalarını üretmez. Contract test `openapi.json` version, ops path/metadata, observability metadata, schema, CRUD path, bound query path, custom action path, explicit API path/runtime metadata ve transaction flag dahil action metadata kayıtlarını denetler. API smoke test generated Express app'i random localhost portunda açar, `/openapi.json`, explicit API runtime route'ları, ops endpoint'leri, local observability hook delivery, anonymous API status ve varsa CORS allow/deny davranışını kontrol eder. Frontend smoke test `target web` içinde generated React `App` bileşenini `react-dom/server` ile render eder. Browser-check smoke test `target web` içinde generated page metadata, action listesi ve text/render katalogları üzerinden deterministic beklentileri doğrular. Browser e2e test `target web` içinde `playwright-core` ile local Chrome/Chromium/Edge başlatır, ephemeral SQLite database, generated setup/seed, auth register, navigation ve action button görünürlüğünü gerçek DOM'da doğrular. Browser matrix plan custom, Chrome, Edge ve Chromium executable availability bilgisini read-only JSON olarak raporlar; matrix run aynı generated e2e intent'ini her available hedef için çalıştırır ve compact pass/fail/skip sonucu döndürür. `blacklang.toml` farklı bir `out` dizini tanımlıyorsa `npm test` o generated output dizininde çalıştırılır.

`test` declaration arbitrary browser automation dili değildir ve `target api` içinde `UNSUPPORTED_API_TARGET_TEST` üretir; generated auth, setup/seed, navigation, text/page/action kontrolleriyle sınırlı deterministic bir browser koşumudur. Generated dosyalar elle düzenlenmemelidir.

test

`test`, generated `target web` output için deterministic browser-check, browser e2e ve browser matrix niyeti tanımlar. Tek bir page hedefler; hızlı smoke testte generated metadata/text catalog, E2E'de gerçek browser DOM'u üzerinden güvenli beklentiler çalıştırır. `target api` içinde browser runtime üretilmediği için `UNSUPPORTED_API_TARGET_TEST` diagnostic'i döner.

Browser source intent
test WarehouseBrowserSmoke {
  page Products
  expect text "Depo"
  expect page LowStock
  expect action RestockProduct
}

`expect text`, hızlı testte generated render yüzeyi/text catalog içinde, E2E'de gerçek DOM'da literal arar. `expect page`, declared metadata ve gerçek navigation/page label davranışını kontrol eder. `expect action`, hedef page'in CRUD veya custom action listesinde action bulunduğunu ve E2E'de ilgili action button'ın göründüğünü doğrular. Kaynakta en az bir `expect` olmalıdır.

AI/CI kontrolü
black docs test --json
black explain test --json
black inspect examples/warehouse/app.black --affected WarehouseBrowserSmoke --json
black build examples/warehouse/app.black --out generated --json
cd generated
npm test
npm run test:e2e:plan
npm run test:e2e:matrix

Generated output `src/blacklang.browser.test.tsx` üretir ve `npm test` zincirine ekler. Ayrıca `src/blacklang.e2e.test.ts`, `src/blacklang.e2e.matrix.ts`, `tests/browser-matrix.json`, `test:e2e`, `test:e2e:plan`, `test:e2e:matrix` ve `test:all` üretir. Browser executable otomatik bulunamazsa `BLACKLANG_E2E_BROWSER_PATH` verilebilir; matrix hedefleri için `BLACKLANG_E2E_CHROME_PATH`, `BLACKLANG_E2E_EDGE_PATH` ve `BLACKLANG_E2E_CHROMIUM_PATH` kullanılabilir.

Accessibility Audit

`black audit accessibility`, generated UI intent için read-only policy check çalıştırır. Kaynak önce parse ve validate edilir; geçerli kaynakta modal/drawer section ve nested group gibi layout niyetleri erişilebilir adlandırma açısından incelenir.

AI/CI kontrolü
black audit accessibility --json
black audit accessibility examples/warehouse/app.black --ir

Current policy findings `ACCESSIBILITY_MISSING_OVERLAY_TITLE` ve `ACCESSIBILITY_MISSING_GROUP_TITLE` kodlarıdır. Çözüm generated React/CSS dosyasını düzenlemek değil; `.black` içinde ilgili `section ... title "..."` veya `group ... title "..."` niyetini eklemektir.

Hata Çıktıları

Hatalar stabil code, dosya, satır, kolon ve öneri alanlarıyla dönmelidir. Böylece AI ajanı hata metnini yorumlamak yerine error code üzerinden doğru referansa gider.

JSON error shape
{
  "success": false,
  "errors": [
    {
      "file": "examples/warehouse/app.black",
      "line": 17,
      "column": 13,
      "code": "UNKNOWN_TABLE_COLUMN",
      "message": "Page Products table uses unknown field Product.barcode.",
      "suggestion": "Add the field to the source entity or remove it from columns."
    }
  ]
}

Bu model, insan için okunabilir; AI için de deterministik onarım akışı sağlar. AI ajanı hata metnine göre değil, `code` alanına göre karar vermelidir. Tam referans `/diagnostics.md` ve `docs/diagnostics.md` içinde tutulur; kısa CLI açıklaması `black docs diagnostics --json` ile alınabilir.

Diagnostic code families
UNKNOWN_*     referenced symbol does not exist
DUPLICATE_*   declaration appears more than once
MISSING_*     required block, field, value, or option is absent
INVALID_*     syntax or value shape is malformed
UNSUPPORTED_* value is known but not supported in this version
UNCLOSED_*    block or string is not closed
UNEXPECTED_*  token is not valid in that location
HARDCODED_*   likely secret is stored in source

Agent Contract

Bu bölüm dış AI ajanlarının BlackLang'i yanlış yorumlamasını engeller. Resmi çalışma yolu `.black` kaynak, `.blackthm` tema profili ve `black` CLI üzerinden generated web/API output üretmektir.

Resmi akış
black agent startup --json
black docs agent-contract --json
black inspect app.black --json
black format --check --json
black lint --json
black validate --json
black build
cd generated && npm test

`black` komutu kurulu değilse ajan syntax uydurmamalıdır. Bugünkü güvenilir yol GitHub reposunu klonlayıp `packages/cli` içinde `go run ./cmd/black ...` komutlarını kullanmak, önce `docs agent-contract --json` çıktısını okumak ve sonra format/lint/ validate/build akışını JSON çıktılarla çalıştırmaktır.

Existing database schema etkileniyorsa deploy öncesi `black migrate plan old.black new.black --json` çalıştırılır; komut read-only plan üretir ve `safe/manual/destructive` riskleri ayrıştırır. Rename gerekiyorsa current source içinde explicit `migration` bloğu yazılır; generated setup runtime bunu schema setup öncesi uygular.

Şu an BlackLang genel amaçlı browser runtime değildir. Calculator, game, arbitrary click handler veya JavaScript replacement gibi davranışlar ilerideki frontend logic/event aşamalarına aittir. Entity tabanlı computed display değerleri ve page-bound custom row action'lar desteklenir; calculator tarzı lokal expression state henüz desteklenmez. Basit öğrenme örneklerinde `+`, `-`, `*`, `/` için computed alanlar kullanılabilir; fakat `validate rightValue != 0` gibi literal karşılaştırmalı entity validation henüz resmi syntax değildir. Sınırlı local `value` ve `if`/`else` logic şu an custom action ve explicit API update handler içinde desteklenir.

Desteklenmeyen resmi syntax
<script type="text/black">
  button 7
</script>

Bir AI ajanı desteklenmeyen bir işi normal HTML/JavaScript ile prototiplerse bunu açıkça prototip olarak etiketlemelidir. Resmi BlackLang çıktısı demek, desteklenen `.black` syntax'ının resmi `black` compiler tarafından üretilmesi demektir.

AI Agents

BlackLang yeni olduğu için modellerin eğitim verisinde bulunmayabilir. Bu normaldir. Dil, yerel öğrenme paketi ve küçük CLI açıklamalarıyla hızlı öğrenilecek şekilde tasarlanır.

Agent başlangıç akışı
1. Run black agent startup --json
2. Read returned readFirst files that exist
3. Run black inspect --json or --ir
4. Run black inspect --affected Product.stock --json before high-impact edits
5. Edit only .black source files
6. Run black format --check --json
7. Run black lint --json
8. Run black build
9. Run generated npm test
10. Do not manually edit generated files
Startup JSON özeti
{
  "command": "agent startup",
  "readFirst": [
    { "path": "AGENTS.md", "exists": true },
    { "path": "blacklang.toml", "exists": true },
    { "path": "docs/diagnostics.md", "exists": true }
  ],
  "sourceFiles": ["examples/warehouse/app.black"],
  "generatedDirs": ["generated"],
  "commands": [
    { "name": "inspect", "command": "black inspect examples/warehouse/app.black --json" },
    { "name": "lint", "command": "black lint examples/warehouse/app.black --json" }
  ]
}

Hedef sıfır öğrenme maliyeti değildir. Hedef, ilk öğrenmeden sonra tekrar eden web geliştirme görevlerinin normal stack'e göre daha ucuz ve daha az hatalı hale gelmesidir.

Örnekler

İlk örnek Warehouse uygulamasıdır. Bu örnek auth, role, relation, workflow, state, component, reusable page component section, table, form, relation load policy, computed display, custom query, custom action, owner/tenant policy, ops runtime signals, validation, generated contract test ve explicit API runtime özelliklerini aynı kaynakta gösterir. Salt okunur LowStock sayfası özel sorguyla düşük stoklu ürünleri listeler; RestockProduct action'ı Products ve LowStock satırlarında stok artırır.

Relation ve validation örneği
entity Order {
  customer Customer required load list detail query mutation label "Customer"
  total money default 0 min 0
  discount money default 0 min 0
  status text default draft
  trackingNumber text optional
  validate discount <= total message "Discount cannot exceed total"
  validate trackingNumber required when status == shipped message "Tracking number is required when shipped"
}

Uzun vadede CRM, inventory, helpdesk, invoice, appointment ve project management şablonları eklenerek gerçek uygulama desenleri ölçülebilir hale getirilir.

CRM Template

SalesCRM, gerçek uygulama şablonlarının ilkidir. Company, Contact, Deal ve Activity kayıtlarını tek `.black` kaynakta tanımlar; auth, role/access, workflow, state, component, validation, OpenAPI ve explicit API runtime davranışlarını birlikte gösterir.

examples/crm/app.black
app SalesCRM

entity Company {
  name text required unique label "Company Name"
  website text optional url
  segment text default prospect
  annualRevenue money default 0 min 0
}

entity Deal {
  company Company required
  contact Contact required
  name text required length 3..80
  expectedRevenue money default 0 min 0
  discount money default 0 min 0
  probability number default 25 min 0 max 100
  status text default lead
  validate discount <= expectedRevenue message "Discount cannot exceed expected revenue"
}

workflow DealPipeline {
  source Deal
  states lead, qualified, proposal, negotiation, won, lost
}
264 BlackLang source lines
39 Generated files
7480 Generated lines
Build passed TypeScript and Vite production build

Bu şablon yeni syntax eklemeden bugünkü compiler kapasitesini kullanır. Template benchmark raporu `benchmarks/crm-v0.2.md` altında tutulur.

Inventory Template

InventoryControl, ikinci gerçek uygulama şablonudur. Warehouse, Supplier, Category, Item, PurchaseOrder ve StockMovement kayıtlarını tek `.black` kaynakta tanımlar; stok yönetimi, satın alma akışı, stok hareketi akışı, field-level access, validation, OpenAPI ve explicit API runtime davranışlarını birlikte ölçer.

examples/inventory/app.black
app InventoryControl

entity Item {
  warehouse Warehouse required
  supplier Supplier required
  category Category required
  sku text required unique length 3..40 regex "^[A-Z0-9-]+$"
  onHand number default 0 min 0
  reserved number default 0 min 0
  reorderPoint number default 5 min 0
  unitCost money default 0 min 0
  status text default active
  validate reserved <= onHand message "Reserved stock cannot exceed on-hand stock"
}

workflow PurchaseOrderFlow {
  source PurchaseOrder
  states draft, submitted, approved, received, closed, cancelled
}

page StockMovements {
  source StockMovement

  table {
    columns item, warehouse, type, quantity, reason, status, completed
  }

  form {
    fields item, warehouse, type, quantity, reason, status, completed
  }
  actions create, edit, delete, archive, restore
}
340 BlackLang source lines
47 Generated files
9826 Generated lines
Build passed TypeScript and Vite production build

Bu şablon inventory alanında iki kelimeli entity adlarını da test eder: `PurchaseOrder` ve `StockMovement` generated TypeScript tarafında `purchaseOrder` ve `stockMovement` olarak doğru kullanılır. Benchmark raporu `benchmarks/inventory-v0.2.md` altında tutulur.

Helpdesk Template

SupportDesk, üçüncü gerçek uygulama şablonudur. Organization, Customer, Team, SupportAgent, ServiceLevelAgreement, Ticket, TicketComment ve KnowledgeArticle kayıtlarını tek `.black` kaynakta tanımlar; destek kuyruğu, SLA takibi, ticket lifecycle, bilgi bankası yayını, field-level access ve API contract davranışlarını birlikte ölçer.

examples/helpdesk/app.black
app SupportDesk

entity Ticket {
  organization Organization required
  requester Customer required
  assignedTeam Team required
  assignedAgent SupportAgent optional
  sla ServiceLevelAgreement required
  ticketNumber text required unique length 3..40
  subject text required length 3..120
  description text required length 10..500
  priorityScore number default 2 min 1 max 5
  status text default open
  resolution text optional length 3..500
  internalNotes text optional length 3..500
  validate resolution required when status == resolved message "Resolution is required when ticket is resolved"
}

workflow TicketLifecycle {
  source Ticket
  states open, triaged, inProgress, waitingCustomer, resolved, closed
}

page Tickets {
  source Ticket

  table {
    columns organization, requester, assignedTeam, ticketNumber, subject, priorityScore, status
  }

  form {
    fields organization, requester, assignedTeam, sla, ticketNumber, subject, description, status
  }
  actions create, edit, delete, archive, restore
}
423 BlackLang source lines
55 Generated files
12466 Generated lines
Build passed TypeScript and Vite production build

Bu şablon destek operasyonlarının yoğun ilişki yapısını test eder: müşteriler, ekipler, ajanlar, SLA kayıtları, ticket yorumları ve bilgi bankası aynı uygulama kabuğunda üretilir. Benchmark raporu `benchmarks/helpdesk-v0.2.md` altında tutulur.

Invoice Template

InvoiceFlow, dördüncü gerçek uygulama şablonudur. Client, BillingContact, TaxRate, CatalogItem, Invoice, InvoiceLine, Payment ve CreditNote kayıtlarını tek `.black` kaynakta tanımlar; fatura onayı, ödeme takibi, iade notları, field-level access, validation, OpenAPI ve explicit API runtime davranışlarını birlikte ölçer.

examples/invoice/app.black
app InvoiceFlow

entity Invoice {
  client Client required
  billingContact BillingContact optional
  invoiceNumber text required unique length 3..40
  issueDate date optional
  dueDate date optional
  currency text default USD
  subtotal money default 0 min 0
  taxTotal money default 0 min 0
  discountTotal money default 0 min 0
  grandTotal money default 0 min 0
  paidAmount money default 0 min 0
  balanceDue money default 0 min 0
  paymentStatus text default unpaid
  status text default draft
  validate discountTotal <= subtotal message "Discount cannot exceed subtotal"
  validate paidAmount <= grandTotal message "Paid amount cannot exceed grand total"
}

workflow InvoiceLifecycle {
  source Invoice
  states draft, approved, sent, partiallyPaid, paid, overdue, void
}

page Invoices {
  source Invoice

  table {
    columns client, invoiceNumber, dueDate, grandTotal, paidAmount, balanceDue, paymentStatus, status
  }

  form {
    fields client, invoiceNumber, dueDate, subtotal, taxTotal, discountTotal, grandTotal, paidAmount, balanceDue, status
  }
  actions create, edit, delete, archive, restore
}
435 BlackLang source lines
55 Generated files
12837 Generated lines
Build passed TypeScript and Vite production build

Bu şablon para alanları, fatura satırları, ödeme workflow'u ve client görünürlüğü gibi finansal uygulama ihtiyaçlarını bugünkü compiler kapasitesiyle ölçer. Benchmark raporu `benchmarks/invoice-v0.2.md` altında tutulur.

Appointment Template

AppointmentBook, beşinci gerçek uygulama şablonudur. Client, Location, Service, StaffMember, Room, AvailabilityBlock, Appointment, AppointmentReminder ve WaitlistEntry kayıtlarını tek `.black` kaynakta tanımlar; randevu planlama, uygunluk blokları, hatırlatmalar, bekleme listesi, field-level access, validation, OpenAPI ve explicit API runtime davranışlarını birlikte ölçer.

examples/appointment/app.black
app AppointmentBook

entity Appointment {
  client Client required
  service Service required
  staffMember StaffMember required
  location Location required
  room Room optional
  appointmentNumber text required unique length 3..40
  scheduledAt datetime optional
  durationMinutes number default 30 min 5 max 480
  channel text default onsite
  confirmed boolean default false
  status text default requested
  cancellationReason text optional length 3..160
  internalNotes text optional length 3..500
  validate cancellationReason required when status == cancelled message "Cancellation reason is required when appointment is cancelled"
}

workflow AppointmentLifecycle {
  source Appointment
  states requested, scheduled, confirmed, checkedIn, completed, cancelled, noShow
}

page Appointments {
  source Appointment

  table {
    columns client, service, staffMember, scheduledAt, durationMinutes, confirmed, status
  }

  form {
    fields client, service, staffMember, location, scheduledAt, durationMinutes, channel, confirmed, status
  }
  actions create, edit, delete, archive, restore
}
457 BlackLang source lines
59 Generated files
13944 Generated lines
Build passed TypeScript and Vite production build

Bu şablon zamanlama alanındaki `date`, `datetime`, regex tabanlı saat metni, relation yoğunluğu ve boolean onay göstergelerini bugünkü compiler kapasitesiyle ölçer. Benchmark raporu `benchmarks/appointment-v0.2.md` altında tutulur.

Project Management Template

ProjectPulse, altıncı gerçek uygulama şablonudur. Organization, Team, TeamMember, Project, Milestone, ProjectTask, TaskComment, TimeEntry, Risk ve ProjectUpdate kayıtlarını tek `.black` kaynakta tanımlar; proje teslimi, görev akışı, milestone takibi, zaman kaydı, risk yönetimi, field-level access, validation, OpenAPI ve explicit API runtime davranışlarını birlikte ölçer.

examples/project-management/app.black
app ProjectPulse

entity ProjectTask {
  project Project required
  assignee TeamMember optional
  taskCode text required unique length 3..40
  title text required length 3..120
  priority text default medium
  estimateHours number default 0 min 0 max 1000
  loggedHours number default 0 min 0 max 1000
  status text default todo
  blockedReason text optional length 3..200
  validate blockedReason required when status == blocked message "Blocked tasks must include a reason"
  validate loggedHours <= estimateHours message "Logged hours cannot exceed estimate"
}

workflow TaskLifecycle {
  source ProjectTask
  states todo, inProgress, blocked, review, done
}

page ProjectTasks {
  source ProjectTask

  table {
    columns taskCode, title, project, assignee, priority, estimateHours, loggedHours, status
  }

  form {
    fields project, assignee, taskCode, title, priority, estimateHours, loggedHours, status
  }
  actions create, edit, delete, archive, restore
}
519 BlackLang source lines
63 Generated files
15621 Generated lines
Build passed TypeScript and Vite production build

Bu şablon relation yoğunluğu, iki ayrı workflow, görev state'i, proje sağlık raporu API'si ve webhook declared-runtime davranışlarını bugünkü compiler kapasitesiyle ölçer. Benchmark raporu `benchmarks/project-management-v0.2.md` altında tutulur.

Web Coverage Status

BlackLang'in web hedefi “çalışan CRUD app” ile sınırlı değildir. Full web coverage; UI/layout, backend/API, database runtime, auth/security, deployment/ops, testing, docs/AI ergonomics ve ecosystem alanlarının birlikte olgunlaşması demektir. `black benchmark coverage --json`, bu alanları weighted matrix olarak raporlar.

100% Current weighted web coverage signal
9 Tracked coverage areas
54 Stable issue IDs
100% Full web target milestone
Coverage command
black benchmark coverage --json
black benchmark coverage --ir
black benchmark issues --json
Area Weight Score Next gap
data-model-crud10100multi-hop relation graph loading after explicit relation graph syntax
frontend-ui-layout15100client-side local expression state after Core Program Logic v1
backend-api-actions15100cross-service command orchestration beyond explicit API grouping
auth-permissions-security15100provider-owned runtime value injection adapters
database-runtime10100MySQL rename migration runner after provider-specific DDL safeguards
deployment-operations10100vendor-specific tracing backend packages after public adapter marketplace publishing
testing-benchmarks10100external multi-model scored eval board after independent harness runs
docs-ai-ergonomics10100external editor marketplace owner publication
ecosystem-integrations595external registry publication and deployed provider marketplace index after release-owner review

Coverage issue IDs such as `WEB-LAYOUT-001`, `WEB-LAYOUT-002`, `WEB-LAYOUT-003`, `WEB-LAYOUT-004`, `WEB-LAYOUT-005`, `WEB-LAYOUT-006`, `WEB-LAYOUT-007`, `WEB-DATA-002`, `WEB-DATA-003`, `WEB-DATA-007`, `WEB-DATA-008`, `WEB-DATA-009`, `WEB-SEC-001`, `WEB-SEC-002`, `WEB-SEC-003`, `WEB-SEC-004`, `WEB-SEC-007`, `WEB-SEC-005`, `WEB-SEC-006`, `WEB-API-002`, `WEB-API-003`, `WEB-API-004`, `WEB-API-005`, `WEB-OPS-001`, `WEB-OPS-002`, `WEB-OPS-003`, `WEB-OPS-004`, `WEB-OPS-005`, `WEB-DOCS-002`, `WEB-DOCS-003`, `WEB-DOCS-004`, `WEB-DOCS-005`, `WEB-TEST-001`, `WEB-TEST-003`, `WEB-TEST-004`, `WEB-TEST-005`, `WEB-TEST-006`, `WEB-TEST-007`, `WEB-ECO-001`, `WEB-ECO-002`, `WEB-ECO-003`, and `WEB-ECO-004` are emitted by the CLI so worklogs, docs, and future GitHub issues can refer to the same gaps without rewriting the taxonomy.

Benchmarks

BlackLang'in iddiası ölçülmelidir: kaç satır `.black` yazıldı, kaç satır generated kod üretildi, normal web stack karşılığı ne olurdu ve AI kaç dosyaya dokundu? `black benchmark --json`, source/generated ölçümlerini geçici build üzerinden üretir ve configured output dizinini değiştirmez. `black benchmark tasks --json`, common AI web değişiklikleri için deterministic scenario ve token estimate raporu üretir. `black benchmark eval --json`, aynı senaryoları repeat count, case prompt, evidence, scoring rubric ve required commands içeren long-running corpus'a dönüştürür. `black benchmark eval-history --json`, evidence-backed published-local history manifest'ini okur; local validation entry'leri billed model score olarak sunulamaz. Compiler testleri Warehouse generated output'u için kompakt golden manifest kullanır.

Source lines .black kaynak satırı
Generated lines Üretilen web kodu
Files edited AI'nin dokunduğu dosya
Errors Validate/build hata sayısı
Warehouse measured output
black benchmark examples/warehouse/app.black --out generated --json

source.lines = 770
generated.files = 66
generated.lines = 14665
generated/black-source line ratio = 19.05
Warehouse AI task benchmark signal
black benchmark tasks examples/warehouse/app.black --out generated --json

scenarios = 8
estimated BlackLang tokens = 10519
estimated conventional tokens = 90872
estimated savings = 88%
Warehouse long-running AI eval corpus
black benchmark eval examples/warehouse/app.black --out generated --json

suite = BLACKLANG-WEB-AI-EVAL-v0.2
cases = 8
repeat = 3
total runs = 24
max score = 2400
Warehouse AI eval history
black benchmark eval-history --json

history = BLACKLANG-WEB-AI-EVAL-HISTORY
status = published-local
runs = 1
total runs = 24
failed = 0

Roadmap

v0.1 web MVP tamamlandı: parser, validator, generator, CRUD, relation, auth, role/access, workflow, state, component, validation, OpenAPI ve source security temelleri var. v0.2 data logic kapsamında computed display fields, relation response load policies with generated batch prefetch, stored-field custom query aggregate summary MVP, background query worker job MVP, API-only target MVP, custom row action MVP, action/API local value + compound condition + if/else logic, transaction block MVP ve explicit API typed update handler tamamlandı. Database runtime tarafında entity index declarations, read-only schema migration plan, explicit rename runtime ve deterministic seed/fixture runtime eklendi. Phase 29 owner/tenant policy MVP ile generated route row scope eklendi. Phase 20 UI profile migration checks, Phase 22 generated contract/API/frontend/browser-check/e2e/matrix tests, first-class browser test declarations, benchmark command, long-running AI eval corpus, evidence-backed eval history, local preview deploy, rollback metadata reusable page component sections, collection-backed component sections, DOM-order rendering, protected source MVP ve secret provider preflight execution da eklendi. Web completion hedefi JavaScript runtime parity değil; deterministic web capability parity olarak takip ediliyor.

v0.2 odakları
Phase 18: Release and install path
Phase 19: Developer and AI ergonomics, including agent contract and inspect --affected
Phase 20: UI and theme language
Phase 21: Computed fields, relation response load policies with generated batch prefetch, custom queries, background query jobs, API-only target, custom actions, action/API local logic, explicit API handlers, and transaction blocks complete
Phase 22: Generated contract/API/frontend/browser-check/e2e/matrix tests, seed fixture runtime, and benchmark command complete
Phase 23: Protected source mode MVP
Phase 24: Documentation site
Phase 25: Real app templates
Phase 28: Page view order, DOM-order rendering, layout composition, tabs, overlays, groups, triggers, and reusable component sections
Phase 29: Ownership and tenant policies
Phase 30: Runtime ops signals, Docker healthchecks, local preview, and rollback metadata

Bu site Phase 24'ün ilk yayınlanabilir sürümüdür. Dil büyüdükçe her yeni syntax, CLI davranışı ve migration notu burada güncellenecektir.