Skip to content
Documentation

ARXD architecture

Rendered from the repository’s own documentation directory.

ARXD architecture

This is the authoritative description of how the platform is put together. Where a subsystem has a deeper document, this file names it rather than repeating it.

  • Request lifecycle and layout: this file
  • Integration and agent wire protocol: docs/api.md, docs/agent-protocol.md
  • How code reaches the server: ARXD_DEPLOYMENT.md
  • Configuration surface: ARXD_ENVIRONMENT.md
  • Controls and threat model: ARXD_SECURITY.md

1. What the system is

ARXD is a multi-tenant control plane. A tenant owns websites, projects, agents and billing. The platform builds and hosts the websites, runs AI agents that act through an allow-listed tool layer, monitors what it deploys, and bills for it.

It runs on one Plesk host. There is no Docker, no Redis, no message queue and no container isolation. That is not an accident to be corrected later; it is the constraint every design decision below respects. Anything that would need a separate build host or a queue server is documented as blocked rather than faked.


2. Directory map

httpdocs/
  index.php              single entry point for every HTTP request
  app/
    bootstrap.php        .env loading, autoloader, error handler, container
    Core/                infrastructure: no domain rules
    Services/            domain invariants: no SQL strings
    Controllers/         HTTP: request in, Response out
    Support/             read-only catalogues and presentational data
    Console/             CLI commands
  routes/
    web.php              browser routes (338 registrations)
    api.php              agent and machine routes (19 registrations)
  views/                 server-rendered PHP; no queries
  migrations/            0001 … 0034, applied in order
  assets/                one stylesheet, progressive JS, images
  tools/                 console.php, worker.php, maintenance scripts
  storage/               logs, agent signing key, uploads (inside docroot)
  tests/                 the suites referenced in ARXD_IMPLEMENTATION_STATUS

ARXD_ROOT is httpdocs/. Every path in the codebase is derived from it, so the tree can be relocated without editing a single constant.


3. Request lifecycle

  1. index.php defines ARXD_ROOT and requires app/bootstrap.php.
  2. bootstrap.php parses .env without overwriting variables that already

exist in the real environment, registers the Arxd\ autoloader over app/, installs Core\ErrorHandler, and builds the container.

  1. Core\Request captures method, path, query, body, headers and the files

array. It is immutable; the router receives a value object.

  1. Core\Router matches against routes/web.php and then routes/api.php.

Route parameters are typed and passed positionally. Middleware attached to a group runs in declaration order.

  1. The controller returns a Core\Response — HTML, JSON, a redirect or a

file. A controller never echoes; producing bytes is the response object's job.

  1. Core\Application::finalise() adds the response headers that must never

depend on the controller remembering them, including the Content-Security-Policy built from a per-request nonce.

  1. Core\ErrorHandler converts any uncaught throwable into a rendered error

page and writes the exception to storage/logs/exception.log.

Middleware

| Group | Effect | | --- | --- | | csrf | Rejects state-changing requests without a matching token | | auth | Requires a signed-in session | | tenant | Binds the request to the caller's organisation | | platform | Requires platform staff rather than a tenant user | | 2fa | Requires a completed second factor | | can:<permission> | Permission check against the RBAC catalogue | | rank:<n> | Minimum rank inside the staff hierarchy | | agent | Authenticates a device credential, not a user | | throttle:api | Rate limit with Retry-After on refusal |

Denials are audited, not just refused. A 403 on an API token is written to the audit log with the ability that was missing.


4. The layer rule

Controller → Service → Core → Database. Enforced by convention and by review, and it is the single most important rule in the codebase.

  • A controller may read the request, call services, and choose a response.

It may not contain a SQL string or a business invariant.

  • A service owns invariants: what may be billed, which state transitions are

legal, what a rollout may expose. It may call db(). It may not touch $_POST, header() or the session directly.

  • Core is infrastructure. It does not know what a customer is.
  • Core\Database is PDO with emulated prepares off, so a bound parameter

is a real server-side parameter and not string interpolation done by the driver. Errors are exceptions, not silent falses.

Views never query the database. A template receives everything it needs. This is why adding a page is cheap: the data is already assembled, and a view cannot accidentally issue a query inside a loop.


5. Core subsystems

5.1 Identity, tenancy and permissions

Core\Auth handles sessions, password verification and TOTP. Core\Rbac holds the role and permission catalogue; roles are data, so a new role does not need a deploy. Core\AuthenticatedUser is the value object handed to templates.

Organisation scoping is applied in the service layer, not the view layer. A tenant identifier is never accepted from a request parameter as a way to widen a query — it comes from the credential.

5.2 AI engines — app/Core/Ai/

Engine is the interface; EngineRegistry chooses an implementation; DeepSeekEngine and OpenAiCompatibleEngine are the two concrete adapters, so a third provider that speaks the OpenAI shape needs no new class. ModelCatalogue holds the known models and their prices.

CallRecorder writes to ai_calls: model, token counts, cost and latency. It records no prompts, no completions and no keys. Usage limits are enforced from those rows, which is why the table exists at all.

5.3 Agents — app/Core/Agent/

  • AgentRole and AgentCatalogue define eleven roles: orchestrator,

research, brand, design, development, content, qa, deployment, maintenance, seo_marketing, customer_support.

  • ToolPolicy is deny-by-default. A role gets a tool only when the policy

lists it and the caller's permissions allow it.

  • AgentRuntime runs the loop, capped at MAX_ROUNDS = 6. A run that needs

more rounds fails visibly rather than spinning.

  • Orchestrator dispatches between roles; Memory keeps a scoped, reconstructable

record so a run can be explained afterwards.

The tool set is deliberately small and every name is a real method:

platform_health  read_file  list_dir  search_code  db_query  db_schema
git_query  lint_php  tail_log  console_read  propose_console_command
propose_file_edit

There is no general-purpose shell tool and no arbitrary SQL tool. db_query runs a bounded, read-scoped query; propose_console_command and propose_file_edit propose — they return a proposal that a human approves, which is then executed by the normal code path with its normal checks.

5.4 Website pipeline — app/Core/Website/, app/Services/Website/

A build takes a brief, produces a set of files, validates them, and publishes them. The output is portable files, not a proprietary blob: export is tested byte-for-byte against what was deployed, which is what makes "your work leaves with you" a factual statement rather than a marketing one.

Publishing is gated: the pre-publish checks include the same exposure checks the public free check runs, so a claim that would be flagged publicly is flagged before a build ships.

5.5 Billing — app/Core/Payments/, Services/SubscriptionService.php

BillingGateway abstracts the provider; PayPalGateway is the live one and Stripe is present but disabled. BillingReconciliation and InvoiceService handle the state machine, and Entitlement enforcement reads plan limits in SQL rather than trusting the UI to hide a button.

The plan limits are the contract. If a limit is not enforced in the query path, it is not a limit.

5.6 Telephony and voice — Core/Voice/, Services/Voice/

SignalWire and Cartesia adapters behind a gateway. The voice paths are switched by environment flags; when a provider is off, the endpoints report the true state rather than accepting a call and dropping it.

5.7 Console and worker — app/Console/, tools/

tools/console.php is the operator interface: migrations, role and plan sync, user administration, and a *:check command per integration that verifies credentials against the live provider rather than trusting a config value. *:status commands answer "why is this not happening" without needing log archaeology.

tools/worker.php runs from cron every minute and does the work that must not happen inside an HTTP request: lapsed heartbeats, monitor evaluation, command expiry, retention, scheduled publishing, queued sends, build jobs. Every sweep is a bounded UPDATE over rows matching a condition and is safe to run concurrently — two workers racing means one finds nothing to do.

5.8 Developer Hub — app/Core/Developer/, app/Services/Developer/

A tenant connects a repository account, imports a repository at a commit, and sees every build with its log.

  • GitHubClient is the only class that speaks to the provider. It never throws:

a failure is a value, so a page reports "GitHub said no, and here is what it said" instead of a stack trace. TLS is verified, redirects are not followed, and neither the token nor a response body is ever logged.

  • DeveloperHubService owns the domain rules: one connection per organisation

per provider, an encrypted token, and a project whose branch is validated against the provider before a job is queued.

  • BuildQueue is the state machine. claim() is a conditional

UPDATE … WHERE status = 'queued' and the affected-row count decides the winner, so two workers cannot both run one job. Two clocks expire stale work: a job claimed and never started, and a job started and hung.

  • BuildRunner does the work and knows nothing about HTTP. A successful import

queues the build for the same commit, so the two steps cannot drift apart.

There is deliberately no run job kind. This host has no container isolation; a shell would run as the web user on a machine holding every tenant's data. Executing a repository's own build script is therefore not implemented, rather than implemented unsafely. The kind enum is ('import','build') and the migration header says why, so the next reader meets the reason before the code.

A missing credential is a first-class state: with no OAuth application configured, the page names the absent variables and offers no button, and developer:status prints the same answer.

5.9 Incidents — app/Services/IncidentService.php

An alert records a condition that is true now. An incident records a period of time: when it started, who noticed, what was tried, when it ended and why. The product needed the second one, because "the email server is down" is not the same sentence as "email was degraded for forty minutes on Tuesday".

incidents holds the record — a reference (INC-YYYY-NNNN, unique per organisation), severity minor|major|critical, a four-state lifecycle investigating → identified → monitoring → resolved, source monitor|manual|automation|agent, and the resolution note. incident_updates is the timeline: append-only, no updated_at, each entry carrying its own is_public flag and a source of system|user|monitor|agent. alerts gained a nullable incident_id with ON DELETE SET NULL — deleting an incident must not delete the evidence that produced it.

The service enforces four rules:

  • Correlation, not multiplication. correlateAlert() attaches an alert to

an existing incident when the alert is already attached, when the same device has one open, or when the same customer has one open that began inside the sixty-minute window. An unlinked dedup_key of NULL means a person opened the incident, not a monitor.

  • Thresholds that decline to invent. info never opens an incident. A

warning opens one only when at least AMPLIFICATION_THRESHOLD (3) other alerts are firing in the same fifteen minutes — deliberately excluding the alert being judged. A single warning is a condition, not a failure in progress.

  • A timeline of one entry per event. An incident opened by a monitor has

exactly one opening entry, which names the alert that caused it; the writer passes it in as opening_note rather than appending after the fact.

  • Closure with a reason. resolve() demands a non-blank note. sweep(),

which the worker runs after the monitors, moves an open incident to monitoring when its checks pass again and only resolves it once it has been quiet for QUIET_MINUTES (30) — writing its own sentence into the timeline, attributed to the platform, not to a person who did not say it.

Both consoles read it, neither writes without permission. /portal/incidents is read-only: incidents are worked by ARXD from the control plane, where the severity judgment and the internal notes live. /admin/incidents requires alert.manage to post an update, change status or resolve — deliberately no new permission, because an incident is the lifecycle over alerts and a role trusted to resolve the alert is trusted with its record. Staff notifications about an incident link to /admin/incidents/{id}; the recipients are platform staff, who are refused at /portal by design.

The public status page reads one more method, publicFeed(), and it is the only query in the service with no organization filter. That is safe for exactly one reason: is_public is 0 unless somebody set it. The incident flag and the update flag are independent, so a public incident can carry an internal note and the reader sees the customer-facing sentence only. The page's empty state says an empty list is not proof of a quiet week, because on this platform it is not.

5.10 Remote deployment — app/Services/Website/RemoteDeploy.php

The managed-hosting pipeline publishes into a directory ARXD owns, which means the platform can look at the result and describe it. A customer's own VPS is the opposite case: the only thing that can be observed from here is what the agent says. So the design starts from a refusal — the platform does not believe a success report it cannot check.

The bytes are packed once, hashed with SHA-256, and stored under storage/deployments/<website>/<deployment>.zip with the digest written into the row. A deploy_site command is queued carrying deployment_id, remote_root and artefact{path,name,sha256}. The agent fetches from GET /api/agent/deployments/{id}/artefact, which serves only when three things hold: the deployment belongs to the device presenting the credential, the command is in dispatched or running, and the file is still on disk. Fetching stamps fetched_at and moves the row to transferring; the archive is deleted after ARTEFACT_TTL_HOURS (12), because it is a copy of a customer's website and its only purpose is to be collected.

recordResult() is where the claim meets the evidence. active is reachable only when the reported digest matches under hash_equals(); a report with no digest is recorded as failed and audited as website.remote_deploy_unverified, because an unverifiable success is the one outcome worse than a failure. On a confirmed deploy the previous active row for the same (website_id, device_id, remote_root) becomes superseded inside the same transaction, so exactly one version is live in any folder.

normaliseRoot() is a policy, not a sanitiser: absolute only, two segments minimum, ../. resolved lexically, and the result matched against FORBIDDEN_ROOTS (/etc, /bin, /usr, /boot, /dev, /proc, /sys, /root, /lib, /lib64, /run, /snap). Anything else is refused with a sentence the customer can act on. The agent reimplements the same check rather than trusting the command it was sent — the server stops a bad command being queued, the agent stops a bad command being obeyed.

Two tables, never merged: website_deployments is what ARXD's own hosting observed, remote_deployments is what was asked for and what was claimed. A single table would make a claim indistinguishable from an observation, which is precisely the distinction this platform is built to preserve.


6. Front end

Server-rendered PHP with progressive enhancement. The site works without JavaScript; JavaScript makes it faster, it does not make it work.

  • One stylesheet, assets/css/app.css, built from CSS custom properties.

No framework, no build step, no compiled artefact to drift from source.

  • CSP nonce from Core\Application, so the handful of legitimate inline

scripts carry proof of authorship and everything else is blocked.

  • Fonts come from fonts.bunny.net only. Icons are inline SVG — the

gd extension is not loaded, so nothing may generate images at runtime.

  • Forms carry a CSRF token and are rendered with real <label> elements; the

markup is written to be usable by keyboard and screen reader, not retrofitted.


7. Data model shape

93 tables, described by 37 migrations. The shape, not the full column list:

| Area | Tables | | --- | --- | | Tenancy and identity | organisations, users, sessions, roles, permissions, api tokens | | Customers | customers, locations, contacts | | Estate | devices, device state, commands, inventory, telemetry | | Support | tickets, messages, attachments, SLA state | | Billing | plans, subscriptions, invoices, invoice lines, payments, refunds | | Websites | websites, hosting bindings, deployments, exported artefacts | | Agent | agent roles, runs, steps, memory, tool calls | | Operations | monitors, probes, alerts, incidents, health snapshots | | Compliance | scans, findings, schedules, reports | | Marketing | pages, findings, calendar, published items | | AI | ai_calls, usage counters |

Migrations are additive and numbered. A destructive migration would need a review that this repository's history has never required, and the convention is to deprecate a column in code before removing it in SQL.


8. Extension rules

When adding a surface:

  1. Name the invariant first. If it belongs in a service, it does not belong in

a controller or a view.

  1. Add the route to routes/web.php with the narrowest middleware that works.

can: before auth is a bug; order matters.

  1. Add a migration, not a manual ALTER. The ledger is the record of what the

database is; a row written outside it is drift.

  1. Add an assertion to the closest existing suite. Every claim in

ARXD_IMPLEMENTATION_STATUS.md is expected to be reproducible by a command.

  1. If the feature needs a credential that is not present, render the exact

missing state. Do not stub a success path — a fake green check is worse than an honest red one, because it stops anyone from fixing it.

Rendered from docs/ in the repository and escaped before display. The directory itself is not served.