delphi-spec-kit
AGENTS.md50 starsChanged 8 months agoMITView on GitHub
This file is automatically recognized by Antigravity, GitHub Copilot, Cursor and Kiro. It defines the universal rules for Delphi development with AI. Use PascalCase (InfixCaps) for all identifiers. Reserved words are always in **TOK_6__, end, if, then, else, nil, string). Use a 3-letter prefix indicating the type:
- Reads credentials
Where files are headingNew AGENTS.md files have more rules about keeping secrets out of the code, and fewer about code style.
Of the AGENTS.md files we read, the 33,398 first seen in the last six months, against the older ones: the kind of rule that gained most share, and the kind that lost most. About files like this in general, not this one, and an estimate, since a kind is a pattern in the words.
In this repository35 other files it gives its agents.
- .claude/CLAUDE.mdCLAUDE.md
- .github/copilot-instructions.mdCopilot instructions
- .cursor/rules/acbr-patterns.mdCursor rule
- .cursor/rules/delphi-conventions.mdCursor rule
- .cursor/rules/design-patterns.mdCursor rule
- .cursor/rules/dext-patterns.mdCursor rule
- .cursor/rules/dmvc-patterns.mdCursor rule
- .cursor/rules/firebird-patterns.mdCursor rule
- .cursor/rules/horse-patterns.mdCursor rule
- .cursor/rules/intraweb-patterns.mdCursor rule
- .cursor/rules/memory-exceptions.mdCursor rule
- .cursor/rules/mysql-patterns.mdCursor rule
- .cursor/rules/postgresql-patterns.mdCursor rule
- .cursor/rules/refactoring.mdCursor rule
- .cursor/rules/solid-patterns.mdCursor rule
- .cursor/rules/tdd-patterns.mdCursor rule
- .cursor/rules/threading-patterns.mdCursor rule
- acbr-componentsSkill
- Delphi Clean CodeSkill
- Delphi Code ReviewSkill
- Delphi Memory and ExceptionsSkill
- Delphi SOLID PatternsSkill
- Design Patterns GoF — DelphiSkill
- DevExpress/DEXT ComponentsSkill
- Dext Framework PatternsSkill
- DelphiMVCFrameworkSkill
- DUnitX Testing PatternsSkill
- Firebird DatabaseSkill
- Horse FrameworkSkill
- Intraweb FrameworkSkill
- MySQL DatabaseSkill
- PostgreSQL DatabaseSkill
- Delphi Code RefactoringSkill
- Delphi Test-Driven Development (TDD) and DUnitXSkill
- Threading & Multi-ThreadingSkill
The file
Show its rules and text
We split this AGENTS.md into the rules it gives an agent
13 rules. About 0 are common, 5 are distinctive, and 8 are very specific to this project.
≈0
Common · estimate
Many files like this have a rule of this kind.
≈5
Distinctive · estimate
This author's own choices. Worth a look.
8
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Very specific: line 20
Use PascalCase (InfixCaps) for all identifiers.
- Very specific: line 56
Follow the generic behavioral pattern in DUnitX tests: Action_Condition_ExpectedResult
- Very specific: line 58
Create fakes in the test unit with prefix TFake (ex: TFakeInventoryRepository)
- Distinctive: line 68
Use a 3-letter prefix indicating the type:
- Distinctive: line 126
ACBr Note: Avoid trapping the UI directly in component interactive events.
- Very specific: line 140
Intraweb Note: Avoid global unit variables to control user state.
- Very specific: line 148
Minimal APIs: Use App.Builder.MapGet with Auto-Binding for DTOs
- Very specific: line 151
Async: Use TAsyncTask.Run from Dext.Core.Tasks.
- Very specific: line 162
JSON: Use Jhonson middleware for automatic serialization
- Very specific: line 163
CORS: Use Horse.CORS middleware
- Distinctive: line 461
If a method needs a comment explaining "what it does", it should be extracted into a method with a descriptive name
- Distinctive: line 666
Use XMLDoc for public methods and interfaces:
- Distinctive: line 679
Don't comment obvious code — let the method name explain
≈ “Common” is an estimate: at least 1 in 5 of the 43,423 AGENTS.md files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.
Files
Delphi AI Spec-Kit — AGENTS.md
This file is automatically recognized by Antigravity, GitHub Copilot, Cursor and Kiro. It defines the universal rules for Delphi development with AI.
Language and Stack
- Language: Object Pascal (Delphi)
- Native IDE: RAD Studio / Delphi
- Frameworks: VCL, FMX, FireDAC
- Database: FireDAC (SQLite, PostgreSQL, Firebird, SQL Server)
- Tests: DUnitX
- Build: MSBuild / Delphi Compiler (dcc32/dcc64)
- File extensions:
.pas(units),.dfm/.fmx(forms),.dpr(project),.dpk(package),.dproj(project config)
Naming Conventions — Pascal Guide
General Rule
Use PascalCase (InfixCaps) for all identifiers. Reserved words are always in **TOK_6__, end, if, then, else, nil, string).
Mandatory Prefixes
| Type | Prefix | Example |
| Class | T | TCustomerRepository |
| Interface | I | ICustomerRepository |
| Exception | E | ECustomerNotFound |
| Private field | F | FCustomerName |
| Parameter | A | ACustomerName |
| Enumerated type | T | TOrderStatus |
| Enum Items | short prefix | osNew, osPending, osClosed |
Unit Naming
NomeProjeto.Camada.Dominio.Funcionalidade.pasExamples:
MyApp.Domain.Customer.Entity.pasMyApp.Infra.Customer.Repository.pasMyApp.Application.Customer.Service.pasMyApp.Presentation.Customer.View.pas
Method Naming
- Action methods: use verbs —
Execute,CreateOrder,ValidateCustomer - Getters: prefix
Get—GetCustomerName - Setters: prefix
Set—SetCustomerName - Boolean functions: prefix
Is,Has,Can—IsValid,HasPermission,CanDelete
Unit Test Naming (TDD)
- Follow the generic behavioral pattern in DUnitX tests:
Action_Condition_ExpectedResult - Example:
ProcessOrder_WithoutStock_RaisesException,CalculateTotal_WithDiscount_ReturnsLowerValue - Create fakes in the test unit with prefix
TFake(ex:TFakeInventoryRepository)
Naming of Forms and DataModules
- Type:
TfrmCustomerEdit,TdmDatabase - Variable:
frmCustomerEdit,dmDatabase - Unit:
MyApp.Presentation.Customer.Edit.pas
Components in Forms
Use a 3-letter prefix indicating the type:
| Component | Prefix | Example |
| TButton | btn | btnSave |
| TEdit | edt | edtName |
| TLabel | lbl | lblName |
| TComboBox | cmb | cmbStatus |
| TDBGrid | dbg | dbgCustomers |
| TPanel | pnl | pnlTop |
| TPageControl | pgc | pgcMain |
| TTabSheet | tab | tabSearch |
| TDataSource | ds | dsCustomers |
| TFDQuery | qry | qryCustomers |
| TFDConnection | con | conMain |
| TMemo | mmo | mmoObservation |
| TCheckBox | chk | chkActive |
| TDateTimePicker | dtp | dtpBirthDate |
| TImage | img | imgPhoto |
| TListView | lvw | lvwItems |
| TTreeView | tvw | tvwCategories |
| TToolBar | tlb | tlbMain |
| TActionList | act | actMain |
| TPopupMenu | pmn | pmnGrid |
| T Hours | tmr | tmrRefresh |
| TStatusBar | stb | stbMain |
DevExpress (DEXT) components in Forms
| Component | Prefix | Example |
| TcxGrid | grd | grdCustomers |
| TcxGridDBTableView | tvw | tvwCustomers |
| TcxDBTreeList | trl | trlCategories |
| TdxLayoutControl | lyt | lytMain |
| TdxLayoutGroup | lgrp | lgrpPersonal |
| TdxLayoutItem | litm | litmName |
| TcxDBTextEdit | edt | edtName |
| TcxDBComboBox | cmb | cmbStatus |
| TcxDBDateEdit | dte | dtpBirthDate |
| TcxDBCurrencyEdit | cur | curPrice |
| TcxDBLookupComboBox | lcb | lcbCity |
| TdxBarManager | bar | barMain |
| TdxRibbon | rbn | rbnMain |
| TdxSkinController | skn | sknController |
ACBr Project (Commercial Automation)
| Component | Prefix | Example |
| TACBrNFe | acbrNFe | acbrNFe1 ou acbrNfeEmissor |
| TACBrCTe | acbrCte | acbrCteMain |
| TACBrBoleto | acbrBoleto | acbrBoletoCob |
| TACBrTEFD | acbrTef | acbrTefVisa |
| TACBrPosPrinter | acbrPosPrinter | acbrPosPrinterCaixa |
| TACBrSAT | acbrSat | acbrSatFiscal |
| TACBrCEP | acbrCep | acbrCepBusca |
ACBr Note: Avoid trapping the UI directly in component interactive events. Isolate tax logic.
Intraweb Components (Web)
| Component | Prefix | Example |
| TIWAppForm | iwForm | iwFormLogin |
| TIWButton | iwBtn | iwBtnSave |
| TIWEdit | iwEdt | iwEdtName |
| TIWLabel | iwLbl | iwLblTitle |
| TIWComboBox | iwCmb | iwCmbStatus |
| TIWGrid | iwGrd | iwGrdItems |
| TIWRegion | iwReg | iwRegContainer |
Intraweb Note: Avoid global unit variables to control user state. Always store transient data in UserSession to avoid leaks between sessions.
REST Frameworks (Horse, DMVC, Dext)
Dext Framework
Dext (https://github.com/cesarliws/dext) is an enterprise landmark inspired by the .NET ecosystem. Conventions:
- Minimal APIs: Use
App.Builder.MapGetwith Auto-Binding for DTOs - Dependency Injection: Mandatory. Inject into endpoints:
function(Dto: MyDto; Rep: ICustomerRepository): IResult - Entity ORM: LINQ type queries (
DbContext.Where(U.Age > 18)). Do not use queries in pure SQL chained. - Async: Use
TAsyncTask.RunfromDext.Core.Tasks. - Results: Return typed frameworks or Records directly, serialized as JSON.
Horse Framework
Horse is a minimalist REST framework for Delphi (Express style). Conventions:
- Controller: Class with
class procedure RegisterRoutes - Handler:
class procedure Nome(AReq: THorseRequest; ARes: THorseResponse; ANext: TProc) - Middleware:
procedure Nome(AReq: THorseRequest; ARes: THorseResponse; ANext: TProc) - Routes: Kebab-case, plural —
/api/customers,/api/order-items - JSON: Use
Jhonsonmiddleware for automatic serialization - CORS: Use
Horse.CORSmiddleware - Structure: Controllers separated from Services, Services separated from Repositories
- Packages:
boss install horse horse-jhonson horse-cors horse-jwt
DelphiMVCFramework (DMVC)
DMVC is a classic MVC framework with Active Record, JWT and Swagger:
- Controller: Inherits from
TMVCControllerwith[MVCPath]attribute - Routes: Attributes —
[MVCPath],[MVCHTTPMethod],[MVCProduces],[MVCConsumes] - Active Record: Inherits from
TMVCActiveRecordwith[MVCTable],[MVCTableField] - Serialization: Automatic via
Render()(JSON by default) - WebModule:
TMVCEnginecreated in WebModule with controllers and middleware - JWT:
TMVCJWTAuthenticationMiddlewarebuilt-in - RQL: Resource Query Language for filters via query string
DevExpress Components
Advanced visual components for VCL:
- Grid:
TcxGridwithTcxGridDBTableView(data-aware) - Layout:
TdxLayoutControlfor responsive forms - Skins:
TdxSkinControllerfor global themes - Export:
cxGridExportLinkto Excel/PDF - Filters:
DataController.Filterfor programmatic filters
Firebird Database
Firebird is the most used corporate database with Delphi. Access via FireDAC (driver FB).
Mandatory Connection Configuration
FConnection.DriverName := 'FB';
FConnection.Params.Values['CharacterSet'] := 'UTF8'; //ALWAYS UTF8
FConnection.Params.Values['SQLDialect'] := '3'; //NEVER Dialect 1
FConnection.Params.Values['Protocol'] := 'TCPIP'; //Or 'Local' for embedded
FConnection.Params.Values['PageSize'] := '16384'; // 16KB recomendado
FConnection.TxOptions.Isolation := xiReadCommitted; //Standard isolationEssential Rules Firebird
- Dialect 3 ALWAYS — Dialect 1 is InterBase legacy and causes ambiguity with
DATE - CharacterSet UTF8 — required for correct accent support
- Parameterized queries — never concatenate strings in SQL
- RETURNING with Open —
INSERT ... RETURNING idrequiresLQuery.Open, notExecSQL - Generators for auto-increment with
BEFORE INSERTtriggers - Domains to centralize types and validations in the schema
- Stored Procedures: Selectable (with
SUSPEND) usesSELECT FROM SP; Executable usesEXECUTE PROCEDURE - Explicit transactions for compound operations (StartTransaction/Commit/Rollback)
- Treat deadlocks via
EFDDBEngineException.Kind = ekRecordLocked
Firebird Anti-Patterns
- ❌
SQLDialect := '1'— ALWAYS use'3' - ❌
ExecSQLwithRETURNING— useOpen - ❌ Concatenate SQL — use parameters
- ❌ Ignore
CharacterSet— setUTF8 - ❌
PAGE_SIZE 4096— use16384for production - ❌ Bypass deadlocks — handle
ekRecordLocked - ❌
CREATE TABLE IF NOT EXISTS— does not exist in Firebird (check viaRDB$RELATIONS)
Skills:
.gemini/skills/firebird-database/SKILL.mdRules:.cursor/rules/firebird-patterns.md
PostgreSQL Database
PostgreSQL is the most advanced open-source database, ideal for modern projects. Access via FireDAC (driver PG).
Connection Configuration
FConnection.DriverName := 'PG';
FConnection.Params.Values['Server'] := 'localhost';
FConnection.Params.Values['Port'] := '5432';
FConnection.Params.Database := 'meubanco';
FConnection.Params.UserName := 'postgres';
FConnection.Params.Password := 'senha';
FConnection.Params.Values['CharacterSet'] := 'UTF8';
FConnection.TxOptions.Isolation := xiReadCommitted;Essential Rules PostgreSQL
- IDENTITY instead of SERIAL — use
GENERATED ALWAYS AS IDENTITYfor new projects (PG 10+) - RETURNING with Open —
INSERT ... RETURNING idrequiresLQuery.Open, notExecSQL - native UPSERT —
INSERT ... ON CONFLICT (col) DO UPDATE SET ... - JSONB — for semi-structured data, indexable with GIN
- ENUM types —
CREATE TYPE status AS ENUM ('active', 'inactive')mapped to Pascal enum - PL/pgSQL — Functions (
RETURNS TABLE= Selectable), Procedures (CALL, PG 11+) - Explicit transactions —
StartTransaction/Commit/Rollback, supportsSAVEPOINT - Full-Text Search —
tsvector+tsquerywith GIN index - Metadata via
information_schema— do not useRDB$(this is Firebird)
PostgreSQL Anti-Patterns
- ❌ Concatenate SQL — use parameterized parameters
- ❌
ExecSQLwithRETURNING— useOpen - ❌
SERIALin new projects — useIDENTITY - ❌
SELECT *in large tables — select required columns - ❌ N+1 queries — use JOIN or subquery
- ❌ Save JSON as TEXT — use
JSONB - ❌ Ignore indexes on WHERE/JOIN columns
Skills:
.gemini/skills/postgresql-database/SKILL.mdRules:.cursor/rules/postgresql-patterns.md
MySQL / MariaDB Database
MySQL is the most popular open-source database in the world. MariaDB is a compatible fork. Access via FireDAC (driver MySQL).
Connection Configuration
FConnection.DriverName := 'MySQL';
FConnection.Params.Values['Server'] := 'localhost';
FConnection.Params.Values['Port'] := '3306';
FConnection.Params.Database := 'meubanco';
FConnection.Params.UserName := 'root';
FConnection.Params.Password := 'senha';
FConnection.Params.Values['CharacterSet'] := 'utf8mb4'; //NEVER 'utf8' (only 3 bytes!)
FConnection.TxOptions.Isolation := xiReadCommitted;Essential Rules MySQL
utf8mb4ALWAYS —utf8in MySQL only has 3 bytes (does not support emoji). Useutf8mb4- AUTO_INCREMENT + LAST_INSERT_ID() — MySQL does NOT support
RETURNING. Get ID viaLAST_INSERT_ID() - native UPSERT —
INSERT ... ON DUPLICATE KEY UPDATE - Native JSON —
JSONtype with->>/JSON_EXTRACToperators (MySQL 5.7+) - InnoDB ALWAYS — never MyISAM in new projects (needs FK and transactions)
- Stored Procedures —
CALL sp_nome(...)for procedures,SELECT fn_nome(...)for functions - Explicit transactions —
StartTransaction/Commit/Rollback, supportsSAVEPOINT - COLLATE —
utf8mb4_unicode_cifor correct case-insensitive comparison - Metadata via
information_schema— useDATABASE()for current schema
MySQL Anti-Patterns
- ❌
utf8as charset — useutf8mb4 - ❌ Try
RETURNING— does not exist, useLAST_INSERT_ID() - ❌
MyISAMin new tables — useInnoDB - ❌ Concatenate SQL — use parameters
- ❌
SELECT *withoutLIMIT— page results - ❌ N+1 queries — use JOIN or subquery
- ❌ Ignore indexes on WHERE/JOIN columns
Skills:
.gemini/skills/mysql-database/SKILL.mdRules:.cursor/rules/mysql-patterns.md
Threads and Multi-Threading
Threads are essential for keeping the UI responsive and processing data in parallel. Delphi offers TThread, PPL (TTask, TParallel.For, TFuture<T>) and synchronization primitives.
Golden Rule
NEVER access visual components (VCL/FMX) directly from a secondary thread. Use
TThread.Synchronize(blocking) orTThread.Queue(non-blocking) to update the UI.
Threading Approaches
| Approach | When to Use |
TThread.CreateAnonymousThread | Simple, one-shot tasks |
TTask.Run (PPL) | Modern way, managed pool |
TParallel.For | Parallel loop in independent collections |
TFuture<T> | Asynchronous result with return value |
TThread (inheritance) | Permanent workers, queues, servers |
Thread-Safety
TCriticalSection— Classic critical section (Enter/LeaveALWAYS infinally)TMonitor— Native object lock (Enter/Exit)TInterlocked— Atomic operations (Increment,Decrement,Exchange)TThreadList<T>— Thread-safe list withLockList/UnlockListTMultiReadExclusiveWriteSynchronizer— Cache: multiple reads, few writesTThreadedQueue<T>— Thread-safe queue for Producer-Consumer
Threading Anti-Patterns
- ❌ Access VCL/FMX directly from secondary thread
- ❌
Sleep()in the main thread (freezes the UI!) - ❌
FreeOnTerminate := True+WaitFor(crash!) - ❌ Access shared variables without locking
- ❌ Ignore exceptions in threads (they are silent!)
- ❌
TCriticalSection.Leavefora definally
Skills:
.gemini/skills/threading/SKILL.mdRules:.cursor/rules/threading-patterns.md
SOLID principles in Delphi
S — Single Responsibility Principle (SRP)
Each unit and each class must have a single responsibility:
//✅ GOOD — separate responsibilities
TCustomerValidator = class
function Validate(ACustomer: TCustomer): TValidationResult;
end;
TCustomerRepository = class(TInterfacedObject, ICustomerRepository)
function FindById(AId: Integer): TCustomer;
procedure Save(ACustomer: TCustomer);
end;
//❌ BAD — class doing it all
TCustomer = class
procedure Validate; //should be a Validator
procedure SaveToDb; //should be a Repository
procedure SendEmail; //should be a Service
end;O — Open/Closed Principle (OCP)
Classes should be open for extension, closed for modification. Use inheritance and interfaces:
type
IReportExporter = interface
procedure Export(AReport: TReport);
end;
TPdfExporter = class(TInterfacedObject, IReportExporter)
procedure Export(AReport: TReport);
end;
TExcelExporter = class(TInterfacedObject, IReportExporter)
procedure Export(AReport: TReport);
end;L — Liskov Substitution Principle (LSP)
Subtypes must be replaceable with the base type without breaking behavior:
//✅ GOOD — any ICustomerRepository works
procedure TCustomerService.LoadCustomer(ARepo: ICustomerRepository);
begin
//works with TFireDACCustomerRepo, TMemoryCustomerRepo, TMockCustomerRepo
FCustomer := ARepo.FindById(FCustomerId);
end;I — Interface Segregation Principle (ISP)
Small, cohesive interfaces, not "fat" interfaces:
//✅ GOOD — segregated interfaces
type
IReadableRepository<T> = interface
function FindById(AId: Integer): T;
function FindAll: TObjectList<T>;
end;
IWritableRepository<T> = interface
procedure Save(AEntity: T);
procedure Delete(AId: Integer);
end;
ICustomerRepository = interface(IReadableRepository<TCustomer>)
['{GUID}']
function FindByCpf(const ACpf: string): TCustomer;
end;D — Dependency Inversion Principle (DIP)
Depend on abstractions (interfaces), not concrete implementations. Use constructor injection:
type
TOrderService = class
private
FOrderRepo: IOrderRepository;
FNotifier: INotificationService;
public
constructor Create(AOrderRepo: IOrderRepository; ANotifier: INotificationService);
procedure PlaceOrder(AOrder: TOrder);
end;
constructor TOrderService.Create(AOrderRepo: IOrderRepository; ANotifier: INotificationService);
begin
inherited Create;
FOrderRepo := AOrderRepo;
FNotifier := ANotifier;
end;Clean Code — Essential Rules
1. Short Methods
- Maximum 20 lines per method (ideal: 5-10)
- If a method needs a comment explaining "what it does", it should be extracted into a method with a descriptive name
2. Self-Descriptive Names
//❌ SPACIOUS
procedure Proc1(S: string; N: Integer);
function Calc(V: Double): Double;
// ✅ BOM
procedure SendNotificationEmail(const ARecipientEmail: string; ATemplateId: Integer);
function CalculateDiscountedPrice(AOriginalPrice: Double): Double;3. Avoid Magic Numbers
//❌ SPACIOUS
if ACustomer.Age > 18 then
// ✅ BOM
const
MINIMUM_AGE = 18;
// ...
if ACustomer.Age > MINIMUM_AGE then4. Guard Clauses
//❌ BAD — excessive nesting
procedure ProcessOrder(AOrder: TOrder);
begin
if Assigned(AOrder) then
begin
if AOrder.Items.Count > 0 then
begin
if AOrder.IsValid then
begin
//real logic here
end;
end;
end;
end;
//✅ BOM — guard clauses
procedure ProcessOrder(AOrder: TOrder);
begin
if not Assigned(AOrder) then
raise EArgumentNilException.Create('AOrder cannot be nil');
if AOrder.Items.Count = 0 then
raise EBusinessRuleException.Create('Order must have at least one item');
if not AOrder.IsValid then
raise EValidationException.Create('Order validation failed');
//real logic here — no nesting
end;5. Focused and Typed Try/Except
//❌ BAD — generic catch swallowing critical errors (Access Violation, OOM)
try
//large block of long code
except
on E: Exception do //Or worse: without declaring "on E:"
ShowMessage(E.Message);
end;
//✅ GOOD — specific exceptions and granular recovery
try
FConnection.Open;
PerformCriticalAction;
except
on E: EFDDBEngineException do
raise EDatabaseConnectionException.Create('Falha local no banco: ' + E.Message);
on E: EBusinessRuleException do
raise; //Pass the exception to the Controller to catch
on E: Exception do
begin
Logger.LogError('Critical unexpected failure', E);
raise; //NEVER hide pure root Exception exceptions without rethrowing!
end;
end;6. Unit Organization
unit MyApp.Domain.Customer.Entity;
interface
uses
System.SysUtils,
System.Classes,
System.Generics.Collections;
type
//1. Types, enums and records first
TCustomerStatus = (csActive, csInactive, csSuspended);
//2. Interfaces
ICustomer = interface
['{GUID}']
function GetName: string;
property Name: string read GetName;
end;
//3. Classes
TCustomer = class(TInterfacedObject, ICustomer)
private
FId: Integer;
FName: string;
FStatus: TCustomerStatus;
function GetName: string;
public
//Constructor and Destructor first
constructor Create(const AName: string);
destructor Destroy; override;
//After public methods
function IsActive: Boolean;
procedure Activate;
procedure Deactivate;
//Properties last
property Id: Integer read FId write FId;
property Name: string read GetName;
property Status: TCustomerStatus read FStatus;
end;
implementation
{ TCustomer }
constructor TCustomer.Create(const AName: string);
begin
inherited Create;
if AName.Trim.IsEmpty then
raise EArgumentException.Create('Customer name cannot be empty');
FName := AName.Trim;
FStatus := csActive;
end;
//... other implementationsRecommended Design Patterns
| Standard | Use in Delphi |
| Repository | Abstracts data access via interface (FireDAC, REST, etc.) |
| Service | Contains business logic orchestrating repositories and other services |
| Factory | Creates instances of complex objects or with dependencies |
| Observer | Use TNotifyEvent or interfaces to decouple notifications |
| Strategy | Interfaces to vary algorithms (e.g. tax calculation) |
| Unit of Work | Manages database transactions |
Anti-Patterns to Avoid
- ❌ God class / God unit — units with thousands of lines doing everything
- ❌ Direct coupling to forms — business logic in
OnClickof buttons - ❌ Uses circular — resolved by separating into layers (Domain, Infra, Application, Presentation)
- ❌ Global variables — use dependency injection
- ❌ Hardcoded Strings — use
resourcestringor constants - ❌ Ignoring memory management — always free unmanaged objects by reference
- ❌
withstatement — avoidwithas it reduces readability and makes debugging difficult - ❌ Testing in Banco Real — attach DUnitX projects directly to
TFDConnection, skipping Mocks/Fakes.
Memory Management (Critical)
- Watched Blocks: The golden rule in Delphi: Whenever there is code calling
.Createfor instances of TObject Classes, the IMMEDIATELY subsequent line must be atry. NO intermediate lines of code!
//✅ The Gold Standard for Disposable Objects
var LList: TStringList;
begin
LList := TStringList.Create;
try
LList.Add('item');
// ...
finally
LList.Free; //i FreeAndNil(LList)
end;
end;
//✅ Objects with owner - VCL/FMX components
TMyComponent := TMyComponent.Create(Self); //Owner (Self) assumes release
//✅ Garbage Collection com Interfaces (ARC)
//The object will be automatically cleaned up at the end of the scope, eliminating the need for try..free
var LService: IMyService;
begin
LService := TMyService.Create;
LService.DoSomething;
end;
//✅ Local variables: use L prefix
var LCustomer: TCustomer;Documentation
- Use XMLDoc for public methods and interfaces:
///<summary>
///Locates a customer by the CPF entered.
///</summary>
///<param name="ACpf">Customer CPF (numbers only)</param>
///<returns>TCustomer instance or nil if not found</returns>
///<exception cref="EArgumentException">If ACpf is empty</exception>
function FindByCpf(const ACpf: string): TCustomer;- Comments in Portuguese for Brazilian projects
- Don't comment obvious code — let the method name explain
Layer Structure (Architecture)
src/
├── Domain/ ← Entidades, Value Objects, Interfaces de repositório
├── Application/ ← Services, Use Cases, DTOs
├── Infrastructure/ ← Implementações de repositório (FireDAC), APIs externas
└── Presentation/ ← Forms (VCL/FMX), ViewModels
tests/
└── Unit/ ← Projetos DUnitX e Fakes/Mocks isolados por contextoDependency rule:
Presentation → Application → Domain ← InfrastructureThe Domain never depends on other layers.testsdepend onApplicationandDomainbut inject Fake implementations by copyingInfrastructurealone.
🚫 AI Context Policy — What to Include and Exclude
Full strategy documented in
docs/ai-ignore-strategy.md.
Files AI Must Always Use as Context
AGENTS.md— universal rulesREADME.md— project overview.github/copilot-instructions.md— Copilot pre-prompt.claude/CLAUDE.md— Claude master prompt.claude/rules/**/*.md— context-specific rules.claude/skills/**/SKILL.md— on-demand skills.cursor/rules/**/*.md— Cursor rules.gemini/skills/**/SKILL.md— Gemini skills.kiro/steering/**/*.md— Kiro steering docsexamples/**/*.pas— good practice examplesdocs/**/*.md— documentation
Files AI Must Never Use as Context
- Build artifacts:
*.dcu,*.exe,*.dll,*.bpl,*.dcp,*.map,*.res - IDE temporaries:
*.local,*.identcache,*.stat,__history/,__recovery/ - Output directories:
Win32/,Win64/,Debug/,Release/,build/,dist/ - Secrets:
*.key,*.pfx,*.p12,.env,.env.* - Noise:
*.log,*.dmp,*.bak,*.tmp
See .cursorignore, .gitignore and .vscode/settings.json for the enforced patterns.
Does it work?
Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.
No reviews yet
People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.
- It worked
- Partly
- It didn't
Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.
Your trail
Files you open will collect here, so you can find them again.
Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.
Now do this for your own.
Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.

