- DevCraft Platform
- Documentation
- Architecture
Concepts
Architecture
This page describes how DevCraft Platform is built today: the stack, the backend modules, the path a request takes from HTTP to the database, how records are stored, and where each kind of logic lives. It is written for developers and administrators who run, extend or review the platform, and it marks clearly which parts are implemented and which are planned.
What the platform is and is not
DevCraft Platform is an open-source, self-hostable, metadata-driven enterprise workflow platform. Administrators define tables, fields, references, forms, lists, access rules, business rules and workflows as data, and the platform renders a working application from that data. Service management, HR cases or asset management are applications built on the platform, not the platform itself. The licence is AGPL-3.0-only.
The project's vision statement sets four boundaries:
- Not a ticketing application. A service-management application is one thing the platform must be able to express. It is used as the proof that the platform is sufficient.
- Not a clone. General concepts of enterprise workflow platforms are borrowed; implementation, naming and UI are DevCraft's own.
- Not a microservice landscape. It is a modular monolith on Laravel and PostgreSQL, by choice.
- Not a low-code toy. The target is real tables, real columns, real constraints and predictable performance at millions of rows. The current interim record store does not meet that target yet (see Storage strategy).
Four non-negotiables guide every design decision:
- Metadata first. If a feature needs per-table PHP, the design is wrong.
- The server decides everything security-relevant. The browser renders and offers convenience; it is never the authority.
- One write path, one read path. Every record read goes through
RecordQuery, every record write throughRecordWriter. There is no fast path that skips access checks or audit. - Foundations before features. Dictionary, record engine and access control come before application screens.
The platform's own system tables (sys_user, sys_table, syslog and others) are described in the same dictionary as application tables, and administration uses the same generic list and form screens. This is deliberate dogfooding: it forces the generic UI to be good and avoids a second code path.
Technology stack
The original architecture proposal planned an Inertia.js application. ADR 0001 replaced that with a standalone Vue single-page application talking to a versioned Laravel REST API. Wherever older design text says "Inertia", read "REST API consumed by the SPA". The versions below are taken from backend/composer.json, frontend/package.json, compose.yaml and the Dockerfiles.
| Layer | Implemented | Notes |
|---|---|---|
| Runtime | PHP 8.4 ("php": "^8.4"; image php:8.4-cli-alpine) | PHP runs only inside Docker in the reference setup. |
| Framework | Laravel 12 (laravel/framework ^12.0), slim skeleton in backend/bootstrap/app.php | No code in app/Http; everything lives in app/Platform/<Module>. |
| Authentication | Laravel Sanctum 4 (laravel/sanctum ^4.0) | Cookie sessions for the SPA, personal access tokens with abilities for integrations. |
| Database | PostgreSQL 17 (postgres:17-alpine in compose) | 17 is the minimum, 18 is recommended. The test suite also runs a second pass on SQLite in memory. |
| Cache and queue | Redis 7 (redis:7-alpine) | Holds the shared metadata cache (CACHE_STORE=redis) and the queue connection. |
| Frontend | Vue 3.5, TypeScript 5.9 (strict), Vite 7, Vue Router 4, Pinia 3 | Standalone SPA in frontend/, built as static assets. |
| UI components | Tailwind CSS 4, shadcn-vue on reka-ui, TanStack Table 8, @lucide/vue icons | Monaco editor for scripts, @vue-flow/core only inside the Flow Designer canvas. |
| Script runner | Node 22 (node:22-alpine), no npm dependencies | Separate compose service runner; see The runner service. |
| Mail (development) | Mailpit | Web UI on port 8025. |
| Quality tools | Pest 3, Larastan 3 (PHPStan level 6), Pint, ESLint 9, vue-tsc, Vitest 3 | All run in GitHub Actions, plus the baseline guard node scripts/check-baseline.mjs. |
Some packages named in the original proposal are not used: there is no Inertia, Fortify, Horizon, spatie/laravel-data or symfony/expression-language in composer.json. Playwright end-to-end tests are still open from milestone M0.
Modular monolith and backend modules
The backend is one deployable and one database. Code is split into modules under backend/app/Platform/<Module>. Each module keeps its own Http (controllers, resources, requests, middleware), Models and Exceptions folders where it needs them. Microservices are out of scope; a module could be extracted into a Composer package later, and that is the only "service readiness" the design pays for.
The following modules exist in the repository today:
| Module | Responsibility |
|---|---|
Kernel | ExecutionContext, identifier grammar (Identifier), platform exceptions, ProblemDetails error rendering, AssignRequestId middleware, health endpoint. |
Access | Authentication and tokens (AuthController, TokenController), the thin Eloquent User, roles, effective roles through groups (RoleResolver), ExecutionContextFactory, the role: middleware. |
Metadata | The dictionary: Eloquent models for tables, fields, choices, overrides, forms and lists; MetadataWriter; MetadataRepository (the metadata cache); FieldTypeRegistry with ten field types; LayoutResolver; the /meta and admin metadata controllers; the update set controller. |
Records | The record engine: Record, RecordQuery, RecordWriter, RecordNumbering, ReferenceResolver, table and field access (TableAccess, FieldAccess), storage drivers, update set capture (RecordCapture), the Table API controller. |
Audit | AuditWriter and the sys_audit model: field-level audit written inside the write transaction. |
Configuration | Configuration identity and versioning: ConfigVersioning, CanonicalJson, DeterministicId, InstanceIdentity, ChangeSetService (local update sets). |
Logging | SystemLogger, ContextSanitizer, LogPruner: platform events into the read-only syslog table. |
Transfer | XML record export and import per table (RecordExporter, RecordImporter, hardened XML parser). |
Packaging | Update set packages: XML export of completed sets, upload, validation, dependency analysis and preview. |
Remote | Remote instances, the read-only DevCraft remote protocol, retrieved update sets, comparison, conflict detection and resolution, and the application engine. |
Scripting | ScriptRunner and the sys_script_execution history: hands background scripts to the runner service. |
Portal | The Service Portal's "mine" scope: a person's own requests and tasks through /api/v1/portal/*. |
The originally proposed modules Scopes, Rules, Workflow, Ui, Api and Attachments do not exist yet Planned. Their responsibilities are partly covered elsewhere (form and list layouts live in Metadata, the REST controllers in each module's Http folder) or belong to later milestones.
Boundaries enforced by architecture tests
backend/tests/Arch/ArchitectureTest.php (Pest arch()) enforces these rules in CI:
- No
dd,dump,ray,var_dump,print_r,eval,exec,shell_exec,passthruorsystemin application code. Kerneldoes not depend onAccess,Metadata,Records,ConfigurationorAudit.ConfigurationandAuditare generic and do not useMetadata,RecordsorAccess.- Raw query expressions (
Illuminate\Database\Query\Expression) are used only inApp\Platform\Records\Storage. - Nothing in
App\Platform\Recordsextends an Eloquent model: records are value objects.
Layered view
The diagram shows the runtime layers and the direction of calls. Everything below the controllers is shared by every entry point: the SPA, API tokens, background scripts, XML import and update set application.
+-----------------------------------------------------------------------+
| Vue 3 SPA (frontend/) Integrations Runner service |
| pages -> definitions/records (Bearer token) (Node, per-run |
| -> api/index.ts (http | mock) token) |
+------------------------------------+----------------------------------+
| HTTPS, /api/v1, JSON
+------------------------------------v----------------------------------+
| Laravel middleware: AssignRequestId -> Sanctum (session | token) |
| -> throttle -> role:/ability: -> ExecutionContext |
+-----------------------------------------------------------------------+
| Module controllers (Records, Metadata, Transfer, Packaging, Remote, |
| Scripting, Portal, Access) -> TableController::resolve / resolveFull|
+-----------------------------------------------------------------------+
| Engines: RecordQuery | RecordWriter | MetadataWriter |
| TableAccess, FieldAccess, validation, numbering, |
| audit (AuditWriter), versions, update set capture |
+-----------------------------------------------------------------------+
| MetadataRepository (cache: Redis, key meta:v{N}, version meta:version)|
+-----------------------------------------------------------------------+
| Storage drivers (Records/Storage): JsonbStorage | PhysicalStorage |
| [planned: SchemaSynchronizer -> physical tables per hierarchy root] |
+------------------------------------+----------------------------------+
|
+------------------------------------v----------------------------------+
| PostgreSQL: sys_record (JSONB), adopted physical tables (sys_user), |
| dictionary, sys_audit, sys_config_version, syslog |
+-----------------------------------------------------------------------+
Request lifecycle
All API routes live in backend/routes/api.php under the prefix /api/v1. The middleware stack is configured in backend/bootstrap/app.php.
- Request id.
AssignRequestIdis prepended to every request, including unmatched routes. It accepts a well-formed incomingX-Request-Id(8 to 64 characters of[A-Za-z0-9._-]) or generates a UUIDv7, does the same forX-Correlation-Id(falling back to the request id), shares both with the log context and theSystemLogger, and echoes both headers on the response. - Authentication.
statefulApi()gives cookie sessions to the SPA origins inSANCTUM_STATEFUL_DOMAINS; everything else authenticates withAuthorization: Bearer. Protected route groups useauth:sanctum. Login isPOST /api/v1/auth/loginwiththrottle:login; data routes usethrottle:api. - Role and ability gates. The
role:adminalias (EnsureUserHasRole) guards the/admingroup; theability:alias (SanctumCheckForAnyAbility) guards the remote protocol (ability:remote:read). Write endpoints of the Table API also check the token'stable:writeability. - Execution context. Controllers inject an
ExecutionContext, built once per request byExecutionContextFactory::fromRequest. It carries the actor, the actor kind, the source, the effective roles, the request id, the current update set (from theX-Change-Setheader, else the user's preference) and a transaction id. CLI commands build their own withExecutionContext::cli(). - Table resolution. Controllers never read a table schema for a request from the repository directly.
TableController::resolvereturns the visible projection of a readable table: unknown and retired tables answer 404 (unknown_table), forbidden ones 403, and fields the caller may not read are removed.resolveFullreturns the full schema and is used only by writers, which must validate fields the caller cannot see. - Read or write. Reads go through
RecordQuery(filters, search, sort, pagination, class-aware reads), reference display values throughReferenceResolver. Writes go throughRecordWriter: input coercion and field write checks, type validation, references, uniqueness andunique_together, numbering, optimistic locking (a version mismatch is a 409),on_deletehandling, audit, configuration versioning and update set capture, all in one transaction. - Storage.
StorageDrivers::for($table)picksJsonbStorageorPhysicalStoragefrom the table'sstorageattribute. Only the drivers build query expressions, and only from identifiers that come from the metadata cache. - Errors. Any exception on an
api/*route, or on a request that expects JSON, is rendered byProblemDetailsas RFC 9457application/problem+json.
Problem details
The error body has the shape { type, title, status, detail, instance, code, requestId, errors? }. Clients branch on code, never on title. Platform exceptions carry their own code; framework exceptions are mapped:
| Status | code | Typical cause |
|---|---|---|
| 400 | bad_request, invalid_query | Malformed request or list query |
| 401 | unauthenticated | No session or token |
| 403 | forbidden | Role, ability or table access denied |
| 404 | not_found, unknown_table | Missing record or table |
| 409 | conflict | Optimistic lock or state conflict |
| 419 | csrf_token_mismatch | Missing or stale XSRF token on a cookie session |
| 422 | validation_failed, metadata_invalid | Field errors are listed in errors |
| 423 | account_locked | Sign-in locked after failed attempts |
| 429 | rate_limited | Throttle exceeded |
{
"type": "about:blank",
"title": "Unknown table.",
"status": 404,
"detail": "The table \"x_demo\" does not exist.",
"instance": "/api/v1/table/x_demo",
"code": "unknown_table",
"requestId": "0192f3a4-..."
}
The full endpoint list is on the REST API page; access rules are on Access control.
Storage strategy
The long-term decision is one physical table per hierarchy root with real columns, generated by a SchemaSynchronizer. That decision stands. For the first metadata engine, ADR 0004 chose an interim store so that tables and records could work through metadata before any runtime DDL exists.
Two storage drivers
sys_table.storage | Driver | Where rows live | Used for |
|---|---|---|---|
jsonb | JsonbStorage | The shared table sys_record (id, table_id, sys_class_name, data jsonb, display_value, system columns) | Default for tables created through the API and for most seeded tables |
physical | PhysicalStorage | An existing migrated table named in physical_table, whose columns match the field names | Adopted tables such as sys_user |
Controllers, validation, audit, versioning and the frontend do not know which driver serves a table. JsonbStorage builds typed JSON path expressions (for example ("data"->>'name')::numeric on PostgreSQL, json_extract(...) on SQLite) only from identifiers that passed the dictionary grammar ^[a-z][a-z0-9_]{0,62}$ when they were written, and re-checks them when the expression is built.
Table inheritance
ADR 0005 makes inheritance real on the interim store. A child table (for example incident extending task) has no rows of its own: its records are sys_record rows whose table_id and sys_class_name name the child class. A query on a table covers the table and every descendant (table_id IN (...)), which is table-per-hierarchy semantics on a shared table. MetadataRepository computes each table's effective schema (ancestors' fields, own fields, overrides, inherited access, display field and numbering, at most five levels). Inherited fields are changed with MetadataWriter::overrideField, never redeclared. Details are on the Metadata engine page.
Schema synchronizer
Metadata cache
App\Platform\Metadata\MetadataRepository is the only source of table and field definitions at runtime. It caches each built TableSchema, the table name list and the hierarchy in the Laravel cache store, and memoises them in the process.
- Keys are versioned:
meta:v{N}:table:<name>,meta:v{N}:hierarchyand so on, whereNis the integer stored undermeta:version(default 1). - Invalidation is a version bump.
MetadataWritercallsinvalidate()after every dictionary write; every process sees new definitions on its next lookup. There is no per-row invalidation logic. - Misses are not cached, because a table may be created a moment later.
- After the database was reset underneath a running instance (for example
migrate:freshwhile Redis kept the old dictionary), clear it by hand. Seeding also invalidates the cache.
docker compose exec api php artisan platform:meta:cache-clear
Metadata ETag headers derived from the version, proposed in ADR 0002, are not implemented Planned.
Where logic lives
The server is the only authority. The table summarises the split as implemented.
| Concern | PostgreSQL | Laravel API | Runner service | Vue SPA |
|---|---|---|---|---|
| Record validation (types, mandatory, choices, references, uniqueness) | Storage only (constraints arrive with physical tables) | Owns (RecordWriter) | — | Mirrors for instant feedback |
| Table and field access | — | Owns (TableAccess, FieldAccess) | Subject to it through the API | Hides what it never receives |
| Filtering, sorting, paging | Executes | Validates against the projection, builds the query | — | Builds conditions, keeps list state in the URL |
| Audit and configuration versions | Stores | Writes inside the transaction | — | Displays |
| Admin-authored JavaScript | — | Records the run, mints and revokes a token | Executes | Editor only |
| Flow definitions | — | — Planned | — | Designer; stored in the browser for now |
| Business rules and workflow execution | — | Planned (M5, M7) | — | — |
| Business logic in triggers or PL/pgSQL | Never | |||
| Security decisions | Always | Never | Never |
PostgreSQL stores and guards; it does not think. Triggers lack the execution context (user, source, update set, request id) the platform needs, so business logic stays in PHP.
The runner service
Background scripts are server-side JavaScript that administrators write on the Background Scripts page. They are never executed in PHP or in the browser. The flow:
- The SPA posts the source to
POST /api/v1/admin/scripts/run(role:admin). App\Platform\Scripting\ScriptRunnerrecords the run insys_script_executionand mints a Sanctum token for the running administrator with the abilitiestable:readandmeta:read, plustable:writeonly when the run confirmed writes. The token expires at the timeout plus 60 seconds.- The source and token go to the runner (
SCRIPT_RUNNER_URL, optional shared secretSCRIPT_RUNNER_SECRETsent asX-Runner-Secret). - The runner starts
runner/worker.mjsas a child process with an empty environment,--disallow-code-generation-from-stringsand a heap limit, and kills it at the wall-clock timeout. The script sees only theDevCraftandconsoleglobals. - Every data operation is an ordinary API call back to
SCRIPT_RUNNER_API_URLwith the run token, soRecordQuery,RecordWriter, access checks and audit apply unchanged. - The platform revokes the token in a
finallyblock, whatever happened.
Setting (backend/.env) | Default | Range |
|---|---|---|
SCRIPT_TIMEOUT_MS | 30000 | 1000 to 120000 |
SCRIPT_MEMORY_MB | 256 | 64 to 512 |
The compose service runs read_only with mem_limit: 768m, pids_limit: 64 and a tmpfs /tmp. It holds no database credentials and no application secrets. Without a runner URL, or when the runner does not answer, the run is recorded as unavailable and nothing executes. The isolation protects the platform process, database and host from the script; it does not protect one administrator from another, because a script has exactly its administrator's authority. More on the Scripting and flows page.
Frontend architecture
The SPA in frontend/src is organised so that screens never hard-code a table's fields or talk to HTTP directly.
api/: data accessapi/contracts.tsdefines thePlatformApicontracts.api/index.tsis the single binding point: withVITE_API_MODE=mock(the default) every contract is served by in-memory mocks inapi/mock; withVITE_API_MODE=httpthe contractsauth,meta,records,references,portal,scripts,transfer,updateSets,packagesandremoteuseapi/http. The prototype contractsusers,catalogItems,dashboard,notificationsandflowsstay mocked in both modes. Screens callapi.*only;liveContractstells them which features are live so that mock-only features can hide or label themselves.definitions/: typed layoutsListDefinitionandFormDefinitionobjects for the remaining application pages (update sets, package and remote changes, the prototype user screens) and the user preference catalogue (preferences.ts). Dictionary tables do not use them: their layouts come from/api/v1/meta.records/: generic record adapters- The generic list and form at
pages/recordsrender any table fromapi.metaandapi.records.listColumns.tsbuilds columns from the backend field resources,encodedQuery.tsandlistUrlState.tskeep filters (as the encoded queryq), sort, page, page size and search in the URL, andrecords/actionsis the registry of every list and form menu item. router/andnavigation/routes.tsholds explicit application paths and the generic/{table}/list,/{table}/newand/{table}/{recordId}routes. Links are built only withlistRoute,newRecordRouteandrecordRoutefromlinks.ts;RESERVED_SEGMENTSkeeps page paths from colliding with table names.navigation/modules.tsandnavigation.tsdefine the navigator; every item resolves to a real or placeholder route.stores/: Piniasession,ui,preferences,updateSets(the current update set and the top-bar picker) andremoteDialogs.- Separate surfaces
portal/is the end-user Service Portal with its own shell under/portal;flows/is the Flow Designer, whose document model is independent of the canvas library.
Quality gates before any frontend change: npm run typecheck, npm run lint, npm test, npm run build. See the List and form and Development guide pages.
Deployment model
- One installation per organisation. The platform is single-tenant: one organisation per database. There is no
tenant_idcolumn, so no row-level tenant filter can be forgotten. Organisations that need isolation run separate databases, ideally separate instances. - Two deployables. A static SPA and a PHP API, with one SPA origin and one API origin per installation, or the same host behind a reverse proxy with
/apirouted to Laravel.SANCTUM_STATEFUL_DOMAINSandCORS_ALLOWED_ORIGINSlist the SPA origins; credentials are allowed only for them. - Supporting services. PostgreSQL, Redis, the script runner and a scheduler. The compose
schedulerservice runsphp artisan schedule:work, which firesplatform:logs:prune(03:15),platform:packages:prune-previews(hourly) andplatform:remote-sets:prune(03:45). In production a cron entry callingphp artisan schedule:runevery minute does the same. - Environments are instances. Development, test and production are separate installations with their own instance id. Configuration moves between them as update sets (Update sets, Promotion).
Today's compose.yaml is a development stack. A hardened production compose and Dockerfile (pinned digests, non-root, read-only file system, php-fpm and a web server), reverse proxy and TLS documentation are part of milestone M9 Planned. See Operations.
Decisions that are expensive to change
The architecture lists fifteen decisions that are costly to reverse once installations and applications exist. Changing any of them requires an ADR first (see Architecture decisions).
| # | Decision | Chosen | Why it is sticky | Status |
|---|---|---|---|---|
| 1 | Record storage | Real tables and columns; interim JSONB store behind a storage driver (ADR 0004) | Every feature builds on it | Partial |
| 2 | Inheritance | Table-per-hierarchy | Changes physical layout and reference targets | Partial logical semantics only (ADR 0005) |
| 3 | Primary keys | UUIDv7 everywhere | Changes every key, API and export | Implemented |
| 4 | Scope on all metadata | A scope on every metadata row | Retrofitting ownership is a rewrite | Partial global only; application scopes planned |
| 5 | Access default | Deny by default, most specific wins | Changing semantics breaks installed apps | Partial table and field access; ACL engine planned |
| 6 | Audit | Written in the write transaction, partitioned by month | Partitioning a large table later needs downtime | Partial in-transaction; partitioning planned |
| 7 | Tenancy | Single tenant per installation | A tenant column cannot be added later | Implemented |
| 8 | Identifier rules | ^[a-z][a-z0-9_]{0,62}$, scoped prefixes, reserved words | Renaming physical objects is painful | Partial grammar and reserved words enforced; scope prefixes arrive with application scopes |
| 9 | Filter contract | Structured conditions (JSON condition AST) | Shared by UI, REST, rules and saved filters | Partial flat conditions with any/all match |
| 10 | Scripting | Declarative and PHP code rules; runtime scripts only behind an isolation boundary; never PHP eval | Security model and admin expectations | Partial runner for admin scripts; rules planned |
| 11 | Metadata-as-code format | Manifests per scope, one file per artifact, stable ids | Becomes the packaging and CI contract | Planned; update set packages use an XML format today |
| 12 | API shape | /api/v1/table/{table}, RFC 9457 errors, keyset pagination | Public contract for integrations | Partial offset pagination today |
| 13 | Records are not Eloquent models | Own Record value object over the query builder | Eloquent assumes a static schema | Implemented (architecture test) |
| 14 | Licence | AGPL-3.0-only | Relicensing needs every contributor's consent | Implemented |
| 15 | Vendor prefix for bundled apps | x_dc_ | Appears in every physical table name of bundled apps | Planned no bundled app yet |