delphi-spec-kit
Copilot instructions53 starsChanged 8 months agoMITView on GitHub
This is a Delphi (Object Pascal) project that follows SOLID principles, clean code and the Object Pascal Style Guide. See AGENTS.md in the project root for the complete convention reference. When creating new features, follow the layered architecture: - Domain: Entities, Value Objects, Interfaces - Application: Services, Use Cases, DTOs - Infrastructure: Repositories (FireDAC), external APIs - Presentation: Forms VCL/FMX
- Reads credentials
In this repository35 other files it gives its agents.
- AGENTS.mdAGENTS.md
- .claude/CLAUDE.mdCLAUDE.md
- .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 copilot-instructions.md into the rules it gives an agent
20 rules. About 0 are common, 5 are distinctive, and 15 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.
15
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Distinctive: line 63
Use specific exceptions (create exception classes per domain):
- Distinctive: line 71
Try/except: only for actual error handling, never for control flow
- Distinctive: line 77
Do not comment self-explanatory code
- Distinctive: line 81
When creating new features, follow the layered architecture:
- Distinctive: line 105
Always delegate to Services — never access data in the controller
- Very specific: line 123
Prefer TdxLayoutControl to manual positioning
- Very specific: line 128
Golden Rule: Do not attach components (TACBrNFe, TACBrCTe, etc.) directly to UI forms.
- Very specific: line 131
Always guarantee memory freeing if you build ACBr components dynamically in a Service (try...finally Free;).
- Very specific: line 137
Generators: Use GEN_ID(generator, 1) in BEFORE INSERT or IDENTITY triggers (Firebird 3+).
- Very specific: line 140
Error Handling: Treat EFDDBEngineException.Kind → ekRecordLocked (deadlock), ekUKViolated (duplicate), ekFKViolated (FK).
- Very specific: line 141
Domains: Use Domains (DM_ID, DM_NAME, DM_MONEY) to centralize types and validations in the schema.
- Very specific: line 146
IDENTITY: Use GENERATED ALWAYS AS IDENTITY instead of SERIAL for new projects (PG 10+).
- Very specific: line 149
JSONB: Use for semi-structured data.
- Very specific: line 152
Metadata: Use information_schema.tables / information_schema.columns (not RDB$).
- Very specific: line 166
Stateful Web: Never use global variables (variables declared in the unit interface) for interactive data (they leak cross-session).
- Very specific: line 167
Avoid blocking UI code from Classic VCL (ShowMessage(), InputBox(), Modal calls).
- Very specific: line 175
Golden Rule: NEVER access visual components (VCL/FMX) directly from secondary thread.
- Very specific: line 181
Cancellation: Check Terminated in TThread loops, or use custom cancellation token.
- Very specific: line 190
Do not create instances in parameters directly: If the Foo(TObjeto.Create) calls do not belong to a native release managed by the signed …
- Very specific: line 191
Domain-Based Exception Handling: Use and create Exception Classes customized for your logics.
≈ “Common” is an estimate: at least 1 in 5 of the 1,644 Copilot instructions 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
GitHub Copilot — Instructions for Delphi Projects
Contexto
This is a Delphi (Object Pascal) project that follows SOLID principles, clean code and the Object Pascal Style Guide. See AGENTS.md in the project root for the complete convention reference.
General Guidelines
- Always generate code in Object Pascal (Delphi) unless explicitly requested in another language.
- Use PascalCase for all identifiers. Lowercase reserved words.
- Respect the prefixes of the Pascal convention:
T(classes),I(interfaces),E(exceptions),F(private fields),A(parameters),L(local variables). - Prefer interfaces over concrete classes for dependencies.
- Use constructor injection for dependency injection.
- Never put business logic in form event handlers (
OnClick,OnChange, etc.). Delegate to services.
Code Style
Indentation and Formatting
- Indentation: 2 spaces (no tabs)
beginon the same line ofif,for,while,withwhen in a single blockbeginon new line for method implementations- Limit of 120 characters per line
Unit Sections
Order unit sections according to:
unit Nome;
interface
uses
{ RTL units },
{ Units do projeto };
type
{ Enums e Records }
{ Interfaces }
{ Classes }
implementation
uses
{ Units adicionais só necessárias na implementação };
{ Implementações }
end.Variable Declaration
// Preferir inline var quando disponível (Delphi 10.3+)
var LCustomer := TCustomer.Create('João');
// Ou declaraction explícita com prefixo L
var
LCustomer: TCustomer;
LCount: Integer;Error Handling
- Use specific exceptions (create exception classes per domain):
EBusinessRuleException = class(Exception); EEntityNotFoundException = class(Exception); EValidationException = class(Exception); - Guard clauses at the beginning of the method instead of deep nesting
- Try/finally for memory management
- Try/except only for actual error handling, never for control flow
Documentation
- Generate XMLDoc for public methods and properties
- Comments in Portuguese for Brazilian projects
- Do not comment self-explanatory code
Design Patterns
When creating new features, follow the layered architecture:
- Domain: Entities, Value Objects, Interfaces
- Application: Services, Use Cases, DTOs
- Infrastructure: Repositories (FireDAC), external APIs
- Presentation: Forms VCL/FMX
What NOT to generate
- ❌ Do not use
withstatement - ❌ Do not create global variables
- ❌ Do not use
AnsiStringwhenstring(UnicodeString) is appropriate - ❌ Don't use magic numbers — declare constants
- ❌ Don't do generic catch (
except on E: Exception do ShowMessage) - ❌ Don't mix UI logic with business logic
- ❌ Do not create methods with more than 20 lines
- ❌ Don't ignore
Freeof temporary objects (use try/finally)
REST Frameworks
Horse
- Controller: class with
class procedure RegisterRoutes - Handler:
class procedure Nome(AReq: THorseRequest; ARes: THorseResponse; ANext: TProc) - Middleware:
THorse.Use(Jhonson),THorse.Use(CORS),THorse.Use(HandleException) - Routes: kebab-case, plural —
/api/customers,/api/order-items - Always delegate to Services — never access data in the controller
DelphiMVCFramework
- Controller: inherits
TMVCControllerwith[MVCPath('/api/resource')] - Routes: attributes
[MVCPath],[MVCHTTPMethod([httpGET])] - Active Record: inherits
TMVCActiveRecordwith[MVCTable],[MVCTableField] - Serialization via
Render()— do not useResponse.Contentdirectly - JWT:
TMVCJWTAuthenticationMiddleware
Dext Framework
- Minimal API:
App.Builder.MapGet,MapPostusing anonymous functions (handlers) - Native routing with Auto Model Binding populating DTOs
- Dependency Injection:
App.Services.AddSingleton,AddScoped - Entity ORM:
DbContext.Where(U.Age > 18)(Smart Properties expressions instead of SQL strings) - Async: use
TAsyncTaskfor asynchronism and promises
DevExpress Components
- DevExpress component prefixes:
grd(TcxGrid),tvw(TcxGridDBTableView),lyt(TdxLayoutControl),skn(TdxSkinController) - Prefer
TdxLayoutControlto manual positioning - Configure grid via code when columns are dynamic
- Export: use
cxGridExportLinkfor Excel/PDF
ACBr Project (Commercial Automation)
- Golden Rule: Do not attach components (
TACBrNFe,TACBrCTe, etc.) directly to UI forms. - Isolate tax logic in Service classes (e.g.
TNFeService) or Repositories. - Configure certificates and cryptographic libraries (WinCrypt/OpenSSL) via code, with data dynamically obtained from abstraction classes.
- Always guarantee memory freeing if you build ACBr components dynamically in a Service (
try...finally Free;). - Common prefixes in the base UI or DataModules:
acbrNFe,acbrECF,acbrTef,acbrBoleto.
Firebird Database
- Rule of Thumb: Dialect 3 ALWAYS (
SQLDialect := '3'), CharacterSet UTF8, PageSize 16384. - RETURNING:
INSERT INTO ... RETURNING idrequiresLQuery.Open, NEVERExecSQL(which discards the result). - Generators: Use
GEN_ID(generator, 1)inBEFORE INSERTorIDENTITYtriggers (Firebird 3+). - Stored Procedures: Selectable (with
SUSPEND) →SELECT * FROM SP_NOME(...). Executable →EXECUTE PROCEDURE SP_NOME(...). - Transactions: Explicitly use
StartTransaction/Commit/Rollbackfor compound operations. Isolation pattern:xiReadCommitted. - Error Handling: Treat
EFDDBEngineException.Kind→ekRecordLocked(deadlock),ekUKViolated(duplicate),ekFKViolated(FK). - Domains: Use Domains (
DM_ID,DM_NAME,DM_MONEY) to centralize types and validations in the schema. - Anti-patterns: ❌ Concatenate SQL, ❌
ExecSQLwithRETURNING, ❌ IgnoreCharacterSet, ❌CREATE TABLE IF NOT EXISTS(useRDB$RELATIONS).
PostgreSQL Database
- Driver:
DriverName := 'PG',CharacterSet := 'UTF8', default port 5432. - IDENTITY: Use
GENERATED ALWAYS AS IDENTITYinstead ofSERIALfor new projects (PG 10+). - RETURNING: Same rule as Firebird —
INSERT ... RETURNING idrequiresLQuery.Open, notExecSQL. - UPSERT:
INSERT ... ON CONFLICT (col) DO UPDATE SET ...— native to PostgreSQL. - JSONB: Use for semi-structured data. Cast in SQL with
::jsonb. Indexable with GIN. - ENUM Types:
CREATE TYPE status AS ENUM (...)mapped to Pascal enum via string constants. - Functions: Return value or table —
SELECT * FROM fn_nome(...). Procedures (PG 11+):CALL sp_nome(...). - Metadata: Use
information_schema.tables/information_schema.columns(notRDB$). - Anti-patterns: ❌
SERIAL(useIDENTITY), ❌SELECT *in large tables, ❌ N+1 queries, ❌ JSON as TEXT (useJSONB).
MySQL / MariaDB Database
- Driver:
DriverName := 'MySQL', default port 3306. Client library:libmysql.dll(orlibmariadb.dll). - Charset:
utf8mb4ALWAYS. MySQL'sutf8is only 3 bytes long (does not support emoji). Collation:utf8mb4_unicode_ci. - AUTO_INCREMENT: MySQL DOES NOT support
RETURNING. Get ID viaLAST_INSERT_ID()orFConnection.GetLastAutoGenValue(''). - UPSERT:
INSERT ... ON DUPLICATE KEY UPDATE name = VALUES(name)— native to MySQL. - JSON: Native
JSONtype (MySQL 5.7+).->>/JSON_EXTRACToperators. Index via Generated Column. - Engine:
InnoDBALWAYS (never MyISAM). Need FK and transactions. - Procedures:
CALL sp_nome(...). Functions:SELECT fn_nome(...).SIGNAL SQLSTATEfor errors. - Anti-patterns: ❌
utf8(useutf8mb4), ❌RETURNING(useLAST_INSERT_ID()), ❌ MyISAM, ❌ N+1 queries.
Intraweb Framework
- Stateful Web: Never use global variables (variables declared in the unit interface) for interactive data (they leak cross-session). Save status to
UserSession. - Avoid blocking UI code from Classic VCL (
ShowMessage(),InputBox(), Modal calls). - Give full preference to asynchronous rendering using Ajax interrupts, encoding events in type
OnAsyncClickinstead of standard entire posts. - Standard component prefixes: always use
iwbase (iwBtnSave,iwEdtUser).
🧵 Threads and Multi-Threading
- Golden Rule: NEVER access visual components (VCL/FMX) directly from secondary thread. Use
TThread.Synchronize(blocking) orTThread.Queue(non-blocking). - Simple tasks:
TThread.CreateAnonymousThreadorTTask.Run(PPL — modern form, managed pool). - Parallel loops:
TParallel.Forto process independent collections. Protect shared variables withTInterlockedorTCriticalSection. - Asynchronous result:
TFuture<T>—.Valueblocks until the result is ready. - Thread-Safety:
TCriticalSection(Enter/Leave infinally),TMonitor,TInterlocked(atomic operations),TThreadList<T>,TMultiReadExclusiveWriteSynchronizer(cache). - Producer-Consumer:
TThreadedQueue<T>withPushItem/PopItem. - Cancellation: Check
TerminatedinTThreadloops, or use custom cancellation token. - Debugging:
TThread.NameThreadForDebugging('NomeDaThread')to facilitate identification in the IDE. - Anti-patterns: ❌
Sleep()in the main thread, ❌FreeOnTerminate + WaitFor, ❌ Shared variables without lock, ❌ Unhandled exceptions in threads (they are silent).
🛑 Memory Management and Exception Control
- Never suggest code prone to Memory Leaks: In Delphi, every
TObjectcreated withoutOwneror outsideInterfaces(ARC) must obligatorily be protected bytry..finallyandFreeand the keywordtrymust come IMMEDIATELY AFTER its creation. No exception between Create and Try. - Do not create instances in parameters directly: If the
Foo(TObjeto.Create)calls do not belong to a native release managed by the signed receiver, you must instantiate first, protect with try and send the var. - Domain-Based Exception Handling: Use and create
ExceptionClasses customized for your logics. - Exception Transparency: When using the
exceptblock, be strictly focused on specific exceptions (on E: EFDDBEngineException do). If you use the genericExceptionfrom scratch, NEVER stop using the pureraise;at the end of the exception block so as not to hide technical errors from global Stack Traces.
🚫 Context Scope for Copilot
Recommended Context (always relevant)
AGENTS.md,README.md,.github/copilot-instructions.md.claude/rules/**/*.md,.claude/skills/**/SKILL.mdexamples/**/*.pas,docs/**/*.md
Excludes (never useful as context)
- Build artifacts:
*.dcu,*.exe,*.dll,*.bpl,*.dcp,*.map - IDE temporaries:
*.local,*.identcache,__history/,__recovery/ - Output dirs:
Win32/,Win64/,Debug/,Release/ - Secrets and noise:
*.key,*.pfx,.env,*.log,*.bak
Full strategy:
docs/ai-ignore-strategy.md. Patterns enforced via.gitignore,.cursorignoreand.vscode/settings.json.
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.

