1. DevCraft Platform
  2. Documentation
  3. Architecture

Concepts

Architecture

Describes the development build as of 2026-10-11. The platform is under active development; statuses are marked on each page.

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:

  1. Metadata first. If a feature needs per-table PHP, the design is wrong.
  2. The server decides everything security-relevant. The browser renders and offers convenience; it is never the authority.
  3. One write path, one read path. Every record read goes through RecordQuery, every record write through RecordWriter. There is no fast path that skips access checks or audit.
  4. 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.

LayerImplementedNotes
RuntimePHP 8.4 ("php": "^8.4"; image php:8.4-cli-alpine)PHP runs only inside Docker in the reference setup.
FrameworkLaravel 12 (laravel/framework ^12.0), slim skeleton in backend/bootstrap/app.phpNo code in app/Http; everything lives in app/Platform/<Module>.
AuthenticationLaravel Sanctum 4 (laravel/sanctum ^4.0)Cookie sessions for the SPA, personal access tokens with abilities for integrations.
DatabasePostgreSQL 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 queueRedis 7 (redis:7-alpine)Holds the shared metadata cache (CACHE_STORE=redis) and the queue connection.
FrontendVue 3.5, TypeScript 5.9 (strict), Vite 7, Vue Router 4, Pinia 3Standalone SPA in frontend/, built as static assets.
UI componentsTailwind CSS 4, shadcn-vue on reka-ui, TanStack Table 8, @lucide/vue iconsMonaco editor for scripts, @vue-flow/core only inside the Flow Designer canvas.
Script runnerNode 22 (node:22-alpine), no npm dependenciesSeparate compose service runner; see The runner service.
Mail (development)MailpitWeb UI on port 8025.
Quality toolsPest 3, Larastan 3 (PHPStan level 6), Pint, ESLint 9, vue-tsc, Vitest 3All 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:

ModuleResponsibility
KernelExecutionContext, identifier grammar (Identifier), platform exceptions, ProblemDetails error rendering, AssignRequestId middleware, health endpoint.
AccessAuthentication and tokens (AuthController, TokenController), the thin Eloquent User, roles, effective roles through groups (RoleResolver), ExecutionContextFactory, the role: middleware.
MetadataThe 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.
RecordsThe record engine: Record, RecordQuery, RecordWriter, RecordNumbering, ReferenceResolver, table and field access (TableAccess, FieldAccess), storage drivers, update set capture (RecordCapture), the Table API controller.
AuditAuditWriter and the sys_audit model: field-level audit written inside the write transaction.
ConfigurationConfiguration identity and versioning: ConfigVersioning, CanonicalJson, DeterministicId, InstanceIdentity, ChangeSetService (local update sets).
LoggingSystemLogger, ContextSanitizer, LogPruner: platform events into the read-only syslog table.
TransferXML record export and import per table (RecordExporter, RecordImporter, hardened XML parser).
PackagingUpdate set packages: XML export of completed sets, upload, validation, dependency analysis and preview.
RemoteRemote instances, the read-only DevCraft remote protocol, retrieved update sets, comparison, conflict detection and resolution, and the application engine.
ScriptingScriptRunner and the sys_script_execution history: hands background scripts to the runner service.
PortalThe 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, passthru or system in application code.
  • Kernel does not depend on Access, Metadata, Records, Configuration or Audit.
  • Configuration and Audit are generic and do not use Metadata, Records or Access.
  • Raw query expressions (Illuminate\Database\Query\Expression) are used only in App\Platform\Records\Storage.
  • Nothing in App\Platform\Records extends 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.

  1. Request id. AssignRequestId is prepended to every request, including unmatched routes. It accepts a well-formed incoming X-Request-Id (8 to 64 characters of [A-Za-z0-9._-]) or generates a UUIDv7, does the same for X-Correlation-Id (falling back to the request id), shares both with the log context and the SystemLogger, and echoes both headers on the response.
  2. Authentication. statefulApi() gives cookie sessions to the SPA origins in SANCTUM_STATEFUL_DOMAINS; everything else authenticates with Authorization: Bearer. Protected route groups use auth:sanctum. Login is POST /api/v1/auth/login with throttle:login; data routes use throttle:api.
  3. Role and ability gates. The role:admin alias (EnsureUserHasRole) guards the /admin group; the ability: alias (Sanctum CheckForAnyAbility) guards the remote protocol (ability:remote:read). Write endpoints of the Table API also check the token's table:write ability.
  4. Execution context. Controllers inject an ExecutionContext, built once per request by ExecutionContextFactory::fromRequest. It carries the actor, the actor kind, the source, the effective roles, the request id, the current update set (from the X-Change-Set header, else the user's preference) and a transaction id. CLI commands build their own with ExecutionContext::cli().
  5. Table resolution. Controllers never read a table schema for a request from the repository directly. TableController::resolve returns 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. resolveFull returns the full schema and is used only by writers, which must validate fields the caller cannot see.
  6. Read or write. Reads go through RecordQuery (filters, search, sort, pagination, class-aware reads), reference display values through ReferenceResolver. Writes go through RecordWriter: input coercion and field write checks, type validation, references, uniqueness and unique_together, numbering, optimistic locking (a version mismatch is a 409), on_delete handling, audit, configuration versioning and update set capture, all in one transaction.
  7. Storage. StorageDrivers::for($table) picks JsonbStorage or PhysicalStorage from the table's storage attribute. Only the drivers build query expressions, and only from identifiers that come from the metadata cache.
  8. Errors. Any exception on an api/* route, or on a request that expects JSON, is rendered by ProblemDetails as RFC 9457 application/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:

StatuscodeTypical cause
400bad_request, invalid_queryMalformed request or list query
401unauthenticatedNo session or token
403forbiddenRole, ability or table access denied
404not_found, unknown_tableMissing record or table
409conflictOptimistic lock or state conflict
419csrf_token_mismatchMissing or stale XSRF token on a cookie session
422validation_failed, metadata_invalidField errors are listed in errors
423account_lockedSign-in locked after failed attempts
429rate_limitedThrottle 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.storageDriverWhere rows liveUsed for
jsonbJsonbStorageThe 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
physicalPhysicalStorageAn existing migrated table named in physical_table, whose columns match the field namesAdopted 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}:hierarchy and so on, where N is the integer stored under meta:version (default 1).
  • Invalidation is a version bump. MetadataWriter calls invalidate() 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:fresh while 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.

ConcernPostgreSQLLaravel APIRunner serviceVue 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 APIHides what it never receives
Filtering, sorting, pagingExecutesValidates against the projection, builds the query—Builds conditions, keeps list state in the URL
Audit and configuration versionsStoresWrites inside the transaction—Displays
Admin-authored JavaScript—Records the run, mints and revokes a tokenExecutesEditor 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/pgSQLNever
Security decisionsAlwaysNeverNever

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:

  1. The SPA posts the source to POST /api/v1/admin/scripts/run (role:admin).
  2. App\Platform\Scripting\ScriptRunner records the run in sys_script_execution and mints a Sanctum token for the running administrator with the abilities table:read and meta:read, plus table:write only when the run confirmed writes. The token expires at the timeout plus 60 seconds.
  3. The source and token go to the runner (SCRIPT_RUNNER_URL, optional shared secret SCRIPT_RUNNER_SECRET sent as X-Runner-Secret).
  4. The runner starts runner/worker.mjs as a child process with an empty environment, --disallow-code-generation-from-strings and a heap limit, and kills it at the wall-clock timeout. The script sees only the DevCraft and console globals.
  5. Every data operation is an ordinary API call back to SCRIPT_RUNNER_API_URL with the run token, so RecordQuery, RecordWriter, access checks and audit apply unchanged.
  6. The platform revokes the token in a finally block, whatever happened.
Setting (backend/.env)DefaultRange
SCRIPT_TIMEOUT_MS300001000 to 120000
SCRIPT_MEMORY_MB25664 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 access
api/contracts.ts defines the PlatformApi contracts. api/index.ts is the single binding point: with VITE_API_MODE=mock (the default) every contract is served by in-memory mocks in api/mock; with VITE_API_MODE=http the contracts auth, meta, records, references, portal, scripts, transfer, updateSets, packages and remote use api/http. The prototype contracts users, catalogItems, dashboard, notifications and flows stay mocked in both modes. Screens call api.* only; liveContracts tells them which features are live so that mock-only features can hide or label themselves.
definitions/: typed layouts
ListDefinition and FormDefinition objects 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/records render any table from api.meta and api.records. listColumns.ts builds columns from the backend field resources, encodedQuery.ts and listUrlState.ts keep filters (as the encoded query q), sort, page, page size and search in the URL, and records/actions is the registry of every list and form menu item.
router/ and navigation/
routes.ts holds explicit application paths and the generic /{table}/list, /{table}/new and /{table}/{recordId} routes. Links are built only with listRoute, newRecordRoute and recordRoute from links.ts; RESERVED_SEGMENTS keeps page paths from colliding with table names. navigation/modules.ts and navigation.ts define the navigator; every item resolves to a real or placeholder route.
stores/: Pinia
session, ui, preferences, updateSets (the current update set and the top-bar picker) and remoteDialogs.
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_id column, 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 /api routed to Laravel. SANCTUM_STATEFUL_DOMAINS and CORS_ALLOWED_ORIGINS list the SPA origins; credentials are allowed only for them.
  • Supporting services. PostgreSQL, Redis, the script runner and a scheduler. The compose scheduler service runs php artisan schedule:work, which fires platform:logs:prune (03:15), platform:packages:prune-previews (hourly) and platform:remote-sets:prune (03:45). In production a cron entry calling php artisan schedule:run every 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).

#DecisionChosenWhy it is stickyStatus
1Record storageReal tables and columns; interim JSONB store behind a storage driver (ADR 0004)Every feature builds on itPartial
2InheritanceTable-per-hierarchyChanges physical layout and reference targetsPartial logical semantics only (ADR 0005)
3Primary keysUUIDv7 everywhereChanges every key, API and exportImplemented
4Scope on all metadataA scope on every metadata rowRetrofitting ownership is a rewritePartial global only; application scopes planned
5Access defaultDeny by default, most specific winsChanging semantics breaks installed appsPartial table and field access; ACL engine planned
6AuditWritten in the write transaction, partitioned by monthPartitioning a large table later needs downtimePartial in-transaction; partitioning planned
7TenancySingle tenant per installationA tenant column cannot be added laterImplemented
8Identifier rules^[a-z][a-z0-9_]{0,62}$, scoped prefixes, reserved wordsRenaming physical objects is painfulPartial grammar and reserved words enforced; scope prefixes arrive with application scopes
9Filter contractStructured conditions (JSON condition AST)Shared by UI, REST, rules and saved filtersPartial flat conditions with any/all match
10ScriptingDeclarative and PHP code rules; runtime scripts only behind an isolation boundary; never PHP evalSecurity model and admin expectationsPartial runner for admin scripts; rules planned
11Metadata-as-code formatManifests per scope, one file per artifact, stable idsBecomes the packaging and CI contractPlanned; update set packages use an XML format today
12API shape/api/v1/table/{table}, RFC 9457 errors, keyset paginationPublic contract for integrationsPartial offset pagination today
13Records are not Eloquent modelsOwn Record value object over the query builderEloquent assumes a static schemaImplemented (architecture test)
14LicenceAGPL-3.0-onlyRelicensing needs every contributor's consentImplemented
15Vendor prefix for bundled appsx_dc_Appears in every physical table name of bundled appsPlanned no bundled app yet