Plugin engine: discovery, installation and execution

Handbook · Coverage · Code reference

A plugin is a directory of PHP code plus plugin.json, optionally accompanied by Vue components and a compiled runtime bundle. Discovery finds code; installation records it; enabling makes its runtime features available. These are separate operations. A manifest's enabled: true does not override the installed database registry.

For a first exercise use the beginner lessons. This chapter explains the real engine contract. Related chapters cover hooks, packages, frontend, data, and security.

Directory and namespace contract

backend/app/Plugins/journal/
  plugin.json
  JournalPlugin.php          optional plugin class
  Lifecycle.php              optional lifecycle fallback
  hooks.php                  optional hook registration
  config.php                 optional config defaults
  Controllers/
  Models/
  routes/api.php
  routes/public.php          explicit public API capability
  routes/admin.php
  routes/web.php
  database/migrations/
  database/Seeders/
  views/
  lang/
  assets/
  frontend/dist/plugin.js    required for declared runtime UI

Use URL slugs such as journal or faction-wars, and PHP namespaces such as App\Plugins\Journal or App\Plugins\FactionWars. PHP namespace case must match class declarations even when your local filesystem is case insensitive. The loader adds explicit Composer PSR-4 mappings to each discovered real path and maps <namespace>\Database\ to its lowercase database/ directory. This matters on Linux and for plugin seeders.

What discovery searches

PluginServiceProvider::getPluginSearchPaths(): array returns existing unique paths in this order:

  1. backend/app/Plugins.
  2. backend/app/Plugins/external.
  3. backend/app/Plugins/external/packages.
  4. backend/external-plugins.
  5. backend/external-plugins/packages.
  6. backend/../packages.
  7. EXTERNAL_PLUGINS_PATH, then its packages subdirectory, when configured.

The provider scans immediate child directories, looking for plugin.json or legacy module.json. Internal/first-discovered slugs win. Invalid JSON logs a warning and is skipped. Discovery defaults the namespace to App\Plugins\ plus the StudlyCase slug. Explicit manifest values override discovery defaults.

Do not assume every operation searches exactly the same paths. Packaging and staged installation have their own resolution logic. A plugin visible through an external mount may need copying into the packaging search root or an explicit build workflow; inspect the command before moving files.

Minimal backend-only manifest

Put this at backend/app/Plugins/journal/plugin.json:

{
  "name": "Journal",
  "slug": "journal",
  "version": "1.0.0",
  "author": "Your studio",
  "description": "A private player journal API.",
  "namespace": "App\\Plugins\\Journal",
  "license_required": false,
  "requires": { "plugins": {} },
  "routes": { "api": true },
  "permissions": []
}

This declares metadata and an authenticated API route file. It does not create an installed row, database tables or permissions in Spatie. Do not add frontend routes or slots until you have their runtime bundle.

Manifest field Source contract / effect
name, author, description Required strings; name/author max 255 characters
slug Required lowercase alphanumeric segments separated by hyphens
version Required numeric major.minor.patch; validator does not accept prerelease suffixes
namespace, class Optional PHP namespace / explicit plugin class; declared class file must exist
enabled Optional boolean metadata; database runtime state remains authoritative
license_required Optional boolean; plugin route middleware checks core license coverage
requires.laravel Optional semver constraint against running framework version
requires.plugins Map of dependency slug to version constraint; dependency must be installed and enabled during validation
settings Registry/menu presentation configuration
permissions Capability/permission metadata; inspect consumer before choosing list versus map
hooks Metadata; does not execute callbacks
routes.web/api/admin Optional booleans; validation requires corresponding files when true. The provider mounts routes/web.php, routes/api.php and routes/admin.php whenever the file exists, so these flags describe the package rather than gate mounting
routes.public_api Optional boolean, default false. Explicit opt-in for routes/public.php mounting; validation requires the file when true
routes.moderator Optional boolean, default false. When true, routes/moderator.php mounts under the admin prefix with role:admin|moderator; every route in routes/admin.php stays admin-only. Validation requires the file when true and rejects a non-boolean value such as 1, because the provider mounts only for a literal true
frontend.routes Objects with path, name and component, plus optional meta
frontend.slots Slot names mapped to arrays of component references
frontend.runtime Compiled entry, format and SRI; required when routes/slots exist

The five routes keys in the table above (web, api, admin, public_api, moderator) are the only routes keys the engine reads (PluginValidationService::ROUTE_FILES); PluginIntegrationTest fails if a bundled plugin uses any other key or a non-boolean value.

Reserved slugs are enabled, slots, menus, permissions, status and admin. Plugin frontend routes may not claim /ban-appeal or /appeal (core's ban appeal page) or the other core paths. They protect registry endpoints. Invalid/reserved/duplicate route slugs are rejected from mounting instead of sharing another plugin's URL namespace.

Dependency constraint language

App\Core\Services\SemverResolver::satisfies(string $installedVersion, string $constraint): bool checks requires.plugins and requires.laravel during validation. This is a small engine resolver; use the following supported forms when authoring a manifest.

Constraint Implemented rule Examples
* or empty string Any version 9.0.0 matches *.
1.2.3 or =1.2.3 Exact three-part numeric comparison 1.2 compares as 1.2.0.
>=1.2, >1.2, <=1.2, <1.2 One comparison 1.3.0 matches >=1.2.
^1.2.3 At least the required version, same major 1.9.0 matches; 2.0.0 does not.
^0.2.3 At least required version, major zero and same minor 0.2.9 matches; 0.3.0 does not. ^0.0.3 also accepts 0.0.9.
~1.2.3 At least required version, below next minor 1.2.9 matches; 1.3.0 does not. ~1 means below 1.1.0.
Pipe-separated alternatives Any nonempty branch matches ^1.0 or ^2.0 can be written `^1.0

Whitespace around the whole constraint and individual alternatives is trimmed. There is no AND, hyphen-range or 1.* wildcard grammar. Version components are cast to integers, not validated here; malformed strings, prerelease tags and build metadata have no supported semantic meaning. A boolean result is not proof the input used a recognized grammar. Manifest versions themselves must pass the validator's numeric major.minor.patch rule. For example, in an isolated PHP test:

$resolver = new \App\Core\Services\SemverResolver;
$this->assertTrue($resolver->satisfies('1.4.0', '^1.2'));
$this->assertFalse($resolver->satisfies('2.0.0', '^1.2'));

Source: resolver, validator. Dependency validation still requires an installed, enabled dependency; matching a version alone does not install it.

Boot lifecycle versus administrative lifecycle

At application registration the provider discovers manifests, maps namespaces, resolves order, merges config.php under plugins.<id>, and registers optional plugin classes as singletons. An explicit class or inferred <namespace>\<namespace-basename>Plugin can supply register().

During boot the provider overlays installed_plugins state. Console boot only reads registry state: it must not create records before read-only readiness checks or explicit installation commands. HTTP boot may register newly discovered filesystem plugins when the registry is available, using explicit manifest enablement (default false); existing operator records are preserved. Unavailable registry queries fail closed inside the guarded lookup. The provider then mounts routes/resources, calls enabled classes' boot(), and shares safe view metadata. app('plugins') contains internal metadata; Blade exposes only ID/name/version/enabled.

autoSeedInstalledPlugins() handles an empty HTTP registry and autoRegisterDiscoveredPlugin() creates only missing records. This discovery does not replace app:register-plugins --force for validated runtime publication. The frontend manifest service may seed a truly empty HTTP registry, but does not reseed an existing registry merely because every plugin was intentionally disabled. The additive registration migration likewise preserves existing configuration/runtime/enablement and defaults unspecified enablement to false. Ordinary unit tests suppress filesystem discovery; explicit local-environment fixtures and disposable Docker checks exercise it.

Important limits: class register() and config merging happen before that registry overlay. View, translation and migration-path registration do not individually filter on enabled state. Disabling is not a filesystem sandbox or a guarantee that no plugin PHP can execute during registration. Install only trusted PHP packages.

Dependency traversal visits dependencies first, logs cycles/missing entries, and then applies an order sort. That secondary sort can affect the traversal order. Use explicit service contracts and installation validation rather than assuming provider ordering is a complete dependency solver.

Management API

Resolve app(\App\Core\Services\PluginManagerService::class) in application code. Most management methods return an array with success and message, with additional data or errors for the operation. Always inspect success.

Signature Purpose / meaningful failure
getAllPlugins(): array Installed/available plugin listing
getStagingPlugins(): array Pending staged packages
getAllThemes(): array Theme listing
getAllAssetPacks(): array Asset-pack listing
registerPlugin(string $slug): array Register existing filesystem code and publish runtime
validatePlugin(string $slug): array Validate existing plugin
installPlugin(string $slug, ?array $approvedPermissions = null): array Install/upgrade staged package; missing staging/dependencies/invalid code fail
enablePlugin(string $slug): array Validate and publish before enabling; fails if missing/already enabled/invalid
disablePlugin(string $slug): array Disable registered plugin; enabled dependents block it
uninstallPlugin(string $slug): array Requires disabled state; rolls back migrations/removes files and registry
removeStagingPlugin(string $slug): array Remove pending staged code
uploadAndExtract($zipFile, string $type = 'plugin'): array Uploaded ZIP staging entry point
stageZipFromPath(string $realPath, string $type = 'plugin', bool $marketplaceVerified = false): array Local ZIP staging entry point; $marketplaceVerified only for a MarketplaceClient::downloadAndVerify() archive (see first-party only)
installTheme(string $slug): array Install staged theme
activateTheme(string $slug): array Activate registered theme
getActiveTheme(): ?InstalledPlugin First enabled theme row
validatePluginStructure(array $data, string $path): bool Structure helper; prefer full validation for diagnostics
createPluginStructure(string $slug, string $name): array Legacy/basic structure generator

Full validator signatures are validate(string $slug): array and validatePath(string $path, ?string $expectedSlug = null, bool $checkFrontendFiles = true): array. They return valid, errors, warnings, manifest, path. Explicit path validation is used before staged PHP is installed. Check all errors; JSON syntax success alone does not prove a valid plugin.

Archive and control-plane boundaries

The admin plugin control plane uses /admin/plugin-settings and the admin plugin API. Its lists distinguish installed registry rows, available filesystem packages without a row, and pending staging packages. Disabling changes the row flag; it does not move PHP into a separate directory. Registration through registerPlugin() creates a disabled row for review.

stageZipFromPath() accepts package type plugin or theme, checks the ZIP before extraction, then checks the manifest and safe slug for both types. Only plugin invokes full validatePath() before staging; theme handling does not perform that dependency/compatibility validation. Its archive inspection rejects empty archives, over 2,000 entries, absolute/drive/NUL/traversal paths and unsupported root layouts. Expanded-size accounting (50 MiB limit) and Unix symlink checks skip __MACOSX entries, although extraction processes the ZIP as a whole; those checks are not a complete archive-wide guarantee. It accepts a single package root, flat root manifest, or supported developer-bundle backend/plugin.json layout. These checks apply to the manager staging path; developer-bundle import has a distinct pipeline. See manager source.

Registry queries versus lifecycle management

PluginService is a small database-query/mutation helper. It is separate from PluginManagerService, which validates dependencies, publishes files and invokes lifecycle callbacks. Resolve either by its fully qualified class, for example app(App\Core\Services\PluginService::class).

PluginService method Result / boundary
getEnabledPlugins(): Collection Enabled type=plugin rows ordered by order.
getPluginsForPlayer(User $user): Collection The same enabled rows; currently does not personalize or authorize using $user.
getNavigationItems(User $user): Collection Navigation arrays grouped by section; resolves named Laravel routes and can throw if a stored route name is missing.
isPluginEnabled(string $pluginName): bool Enabled plugin row matching exact name or slug.
canPlayerAccessPlugin(User $user, string $pluginName): bool Same enabled/name-or-slug existence check; does not enforce user role, license or route policy.
getPlugin(string $slug): ?InstalledPlugin First row by slug, including disabled rows and types other than plugin.
getAllPlugins(): Collection All plugin-type rows ordered by order.
togglePlugin(string $pluginName): bool Directly flips the row flag and forgets manifest cache; false means either disabled now or no matching row.
updatePluginSettings(string $pluginName, array $settings): bool Shallow-merges into row config, saves and invalidates manifest cache; false when absent. No settings-schema validation here.
reorderPlugins(array $order): void Updates slug-to-position pairs and invalidates manifest cache; no transaction or plugin-type filter.

Compatibility methods getEnabledModules(), isModuleEnabled(string $name) and canPlayerAccessModule(User $user, string $name) delegate to their plugin equivalents. They do not describe a separate module system. None of these helper methods automatically authorizes the caller. Use the manager's enablePlugin() / disablePlugin() for the documented validated lifecycle; direct toggling skips those protections.

Public frontend manifest projection

Resolve app(App\Core\Services\PluginManifestService::class). Constructor injection supplies PluginRuntimeAssetService and optionally SlotLayoutStudioService (resolved from the container if omitted).

Method Result / side effect
getEnabledPluginsForFrontend(): Collection Public manifests for enabled plugin-type rows; cached at plugins.frontend_manifest for 60 seconds. Returns an already cached array/Collection without rebuilding.
getPluginManifest(string $slug): ?array Builds one enabled row's manifest directly; null when missing/disabled. Unlike the collection query, does not add the plugin-type scope.
getPluginRoutes(): array Flattens projected frontend_routes with plugin, path, name, component and meta. Does not mount a PHP or Vue route itself.
getNavigationItems(): array Enabled menu entries sorted by section/order, carrying role metadata; does not filter against an authenticated user.
getApiRoutes(): array Plugin slugs and /api/plugins/{slug} prefixes for manifests declaring API routes, not a live endpoint catalogue.
getPluginsBySection(): array Groups projected navigation items by section.
clearCache(): void Forgets only plugins.frontend_manifest; does not clear browser state or reset provider boot.

The projection includes identity/version, row config as settings, display/menu metadata, routes, effective Studio slots, runtime URLs/SRI and permission metadata. Put secrets in a private server-owned store, not this projected config. config.menu must be nonempty for navigation to be enabled; a roles array is metadata for consumers, not backend authorization.

Explicit frontend_routes take precedence. Otherwise a stored route_name is converted to a path and a guessed <StudlySlug>View component. Guessing a component name does not create or compile it. After a registry/slot change, check both this server projection and the actual browser runtime. See frontend, PluginService source and manifest source.

Installation and upgrades

installPlugin validates the staged directory, checks dependencies, backs up an existing installed copy on upgrade, moves code into app/Plugins/<slug>, runs plugin migrations, publishes assets/runtime, and creates or updates the registry. It commits database state before calling install/upgrade lifecycle callbacks.

On pre-commit failure it attempts database rollback, migration rollback, file restoration and runtime restoration. Filesystem changes and MariaDB DDL are not made perfectly atomic by a database transaction. Keep real backups and inspect migration history after a failed upgrade. A post-commit lifecycle failure is logged and cannot roll back a completed install.

Approved capabilities, when supplied, are stored in config.approved_permissions and on the permissions field. Enable preserves existing approvals while refreshing manifest attributes/runtime. Cache clearing includes frontend registry cache and PluginContext::reset().

First-party only on live installs

Plugin bundles still run in the same page and session as the player and admin apps, and a plugin ships PHP. Until plugins are isolated, a live install only installs, updates, uploads, enables or activates first-party plugins and themes. The switch is config('plugins.first_party_only'), from PULSE_FIRST_PARTY_ONLY. Left unset (or empty, PULSE_FIRST_PARTY_ONLY=) it is on unless APP_ENV is local or testing, so a live site running as staging, prod or demo is covered too; an explicit true or false always wins. The rules live in App\Core\Services\FirstPartyPackagePolicy.

First-party means the strongest proof the engine has at each entry point:

Entry point With the policy on
Marketplace install and update (POST /api/v1/admin/marketplace/plugins/{slug}/install, /update), and every kit download (MarketplaceClient::downloadAndVerify()) The effective hub must be the configured MARKETPLACE_URL (config('plugins.marketplace.url')), not the admin-editable connection setting, and PUT /api/v1/admin/marketplace/connection refuses any other URL while the policy is on: the hub's vendor listing is the proof of who published a package, so an admin session must not be able to point it at a host that lies. An empty MARKETPLACE_URL refuses every download (set it on the server). Before downloading, that hub's product answer (GET {MARKETPLACE_URL}/products/{slug}) decides: a 2xx answer must carry vendor.slug in plugins.first_party.vendor_slugs (lf-studio by default, from PULSE_FIRST_PARTY_VENDORS), and an answer with no vendor, or vendor: null, is refused, never judged by its author text (see the hub author fallback below). Any 4xx answer (an unknown, unpublished or unapproved product) is refused. Only when the hub cannot answer at all (a connection failure, timeout or 5xx) is the local CDN catalogue (storage/marketplace/catalog.json, written only by the CLI publish command) used: its entry must name a first-party author and record a SHA-384 checksum (or package_sha384), and the downloaded archive must have exactly that SHA-384, so the entry vouches for those bytes only. The archive must then verify against the pinned marketplace key as before, and its own signed plugin.json (or a kit's recipe.json) must name a first-party author and the requested slug (a kit's id): the signature does not cover the slug, so a vouched product must not carry another package. installRemote() also installs only the slug that staging reported, so a theme archive staged under another name cannot make it install an older themes/<requested slug> folder. The signature alone is not enough: the marketplace hub re-signs third-party vendor uploads with the same key. These checks run whatever category the request or the hub names: the marketplace installer stages anything that is not a theme as a plugin, so an artwork label could carry code. downloadAndVerify() returns first_party_verified: true only when every check ran and passed, and only then is the staged copy marked.
Admin ZIP upload (POST /api/v1/admin/plugins/upload) Refused for every package, including one whose manifest says Blackwave Studios: an upload has no signature, and an author field is text anyone can type. Install official packages from the marketplace.
Install from staging (POST /api/v1/admin/plugins/{slug}/install) Needs the marker storage/plugins/first-party/<slug>.json, written only when an archive that passed the first-party download checks (with the policy on) was staged, and a first-party manifest. The marker records the slug, version and SHA-256 of the staged plugin.json, and install refuses when they do not match what is staged now. A package uploaded or downloaded into staging while the policy was off cannot be installed after it is switched on.
Enable (PUT /api/v1/admin/plugins/{slug}/enable, hub:enable, kits, marketplace auto-enable) The plugin's plugin.json must name Blackwave Studios. Refused before any plugin migration runs.
app:register-plugins and web-request discovery A new third-party row is registered disabled whatever its manifest's enabled says.
hub:import bundles (PluginBundleService::import()) A bundle whose backend/plugin.json is not first-party is refused before extraction.
Theme install and activate (/install-theme, /activate-theme, kit themes) The theme's plugin.json must name Blackwave Studios (the recorded author when its source folder is gone).
Kit install (kit:install, POST /api/v1/admin/kits/{slug}/install) The kit's own recipe.json must name a first-party author, checked first (dry run included), because the kit's seeders run and its frontend files are copied. A kit cannot pull in a third-party plugin or theme: a required one fails the preflight (dry run included) before any migration, registration or file write; an optional one is skipped with a warning. A plugin that is already enabled is left as it is. The kit theme is judged by the plugin.json of the source the kit will copy (theme.path in the recipe, otherwise kits.theme_source_paths). Plugins the kit downloads from the marketplace go through the marketplace checks above.

For code already on the server the manifest author is the only identity there is. Putting files there already needs server access, so those checks guard against a mistake rather than an attacker; the marketplace and upload paths are the ones an admin session (or a script running in it) can reach.

Refusals return success: false, first_party_only: true and a message that starts Refused: this site only allows first-party (Blackwave Studios) plugins and themes. The admin shows that message as it does any other failure.

Nothing already installed is deleted or disabled. Third-party plugins and themes that are enabled keep running and are reported: GET /api/v1/admin/plugins returns first_party_only and third_party_enabled (slug, type and recorded author), and app:register-plugins prints a warning for each. Disable one with hub:disable <slug> if it should not run. A theme is judged by the author in its own plugin.json on disk when that file exists (older theme rows have no recorded author); a plugin row whose recorded author is empty is reported as Unknown until app:register-plugins re-syncs it.

Rollout to existing sites

Official packages are only recognised by the exact author Blackwave Studios. Some downstream product checkouts still ship official manifests with older author strings (LF Studio, Pulse Engine, Pulse Engine Core Team), and some kit recipes have no author. Before this engine version reaches such a site, either normalise those manifests to Blackwave Studios, or set PULSE_FIRST_PARTY_AUTHORS (a comma list added to Blackwave Studios) for the legacy names, or set PULSE_FIRST_PARTY_ONLY=false on that site for now. Otherwise those packages keep running if enabled, but are reported as third-party and cannot be re-enabled or activated, and those kits cannot be installed. A kit refused this way stops before any of its seeder PHP is required and before any frontend or theme file is copied.

The official game kits (Cookie Raid, Cyberpunk Grid, Mafia Underworld, Space Colony) name Blackwave Studios in their recipe.json. They come from the marketplace; the Community release contains no kit. The three commerce kits in backend/storage/kits/ (digital-creator-hub, hybrid-storefront and retail-pro) have no author on purpose: they stay exact 1.0.0 mirrors of the engine copy until their canonical release is settled, so with the policy on they are refused like any third-party kit. That matches their current state, since they are not installable on a live site yet. Their author is added at the canonical source (game-kits) with a patch bump when they are released.

Legacy author names (PULSE_FIRST_PARTY_AUTHORS) count wherever an author is judged: on-disk manifests and kit recipes, the signed manifest inside a marketplace download, and the local catalogue entry used when the hub cannot be reached. They never replace the hub's vendor check: a product the hub answers for still needs the official vendor.slug.

Hub author fallback and its risk

PULSE_FIRST_PARTY_HUB_AUTHOR_FALLBACK (config plugins.first_party.hub_author_fallback, default false) exists only for a hub that does not send vendor in its product answer yet. With it on, a hub answer without a vendor is judged by its author text instead. That text is not proof: a third-party marketplace vendor can write "author": "Blackwave Studios" in its listing and plugin.json, the marketplace hub signs the upload with the same pinned key, and the package would then be installed as first-party with full same-page access. The current hub product endpoint (/api/v1/marketplace-hub/products/{slug}) sends vendor.slug, so leave the fallback off; before relying on that, check that an official product's live answer has vendor.slug equal to lf-studio. A hub that does not, or a MARKETPLACE_URL pointed at a storefront-style endpoint, refuses every marketplace install while the policy is on until the hub exposes the vendor . Turning the fallback on accepts the spoofing risk above for that time.

PULSE_FIRST_PARTY_ONLY accepts the usual boolean spellings (true/false, 1/0, on/off, yes/no). Any other value (a typo such as ture) counts as unset, so the APP_ENV default applies and a live site stays on.

Third-party developers working locally keep the old behaviour, because local and testing installs default to off. A private deployment that trusts its own packages sets PULSE_FIRST_PARTY_ONLY=false and accepts the same-page risk.

Administrative lifecycle contract

PluginLifecycleInterface defines the following methods. Extend AbstractPluginLifecycle to inherit no-op implementations and override only what you need:

Signature When manager invokes it
install(): void First successful staged install, after migrations/commit
upgrade(string $fromVersion, string $toVersion): void Successful staged upgrade, after commit
enable(): void After enabled state is set
disable(): void After disabled state is set
uninstall(): void Before migration rollback and removal

Resolution first tries the registered plugin instance and requested method. Fallback classes are <StudlySlug>Plugin, Lifecycle, then Installer under App\Plugins\<StudlySlug>. Only the first matching fallback class is considered. Failures are logged. These are method calls, not evidence that a corresponding plugin.installed hook is dispatched.

For example, place this at backend/app/Plugins/journal/Lifecycle.php:

<?php

namespace App\Plugins\Journal;

use App\Core\Lifecycle\AbstractPluginLifecycle;

final class Lifecycle extends AbstractPluginLifecycle
{
    public function enable(): void
    {
        logger()->info('Journal enabled');
    }
}

Expected effect: enabling Journal through the manager writes that log entry. Do not put required schema changes here; use migrations and make lifecycle side effects safe to repeat.

PluginInterface is a separate runtime class contract: metadata accessors getId/getName/getVersion/getManifest/getPath/getNamespace, register/boot, and accessors for routes, middleware, dependencies, view namespace, migrations, slots, licensing, permissions and admin settings. The generic base App\Plugins\Plugin implements this pattern. Read actual provider behavior when overriding an accessor: not every accessor is consulted by every loader.

Base Plugin API

Subclass App\Plugins\Plugin for reusable defaults. __construct(string $path) loads plugin.json once, resolves legacy paths through discovery roots, and requires nonempty name, slug, version. Missing files/required fields throw RuntimeException; malformed or non-object JSON can also fail during decoding/typed assignment. Constructor loading is narrower than full PluginValidationService validation.

Method Return / default behavior
getId(): string, getName(): string, getVersion(): string, getManifest(): array, getPath(): string Loaded slug/name/version, full manifest and resolved path. Name falls back to ID; version falls back to 1.0.0. No file reread.
getNamespace(): string App\Plugins\ plus StudlyCase ID; this base accessor does not read an explicit manifest namespace, whereas provider discovery does.
getRoutes(): array Cached descriptors for enabled manifest web/api/admin route files that exist. Keys are route type; each descriptor has path, file, middleware and optional prefix. API/admin defaults match the route section below. This accessor does not include public_api and does not mount routes.
getMiddleware(): array Cached middleware manifest value, default [].
getDependencies(): array requires.plugins, cast to array; default [].
getViewNamespace(): string, getMigrationsPath(): string ID; <path>/database/migrations.
getFrontendSlots(): array, getPermissions(): array Respective manifest arrays; default [].
requiresLicense(): bool license_required, default false.
hasMigrations(): bool Migrations directory exists and contains files.
hasViews(): bool, hasTranslations(): bool views / lang directory exists; no check of contents.
assetUrl(string $asset = ''): string Application asset URL /plugins/<id>, optionally followed by supplied asset. No existence check, version segment or runtime descriptor lookup. Use the runtime descriptor for versioned compiled files.
resolveClass(string $className): ?string Class name under getNamespace() if autoloadable, otherwise null; never an instance.
getModelClass(string $modelName): ?string, getControllerClass(string $controllerName): ?string Class-name lookup below Models\ / Controllers\; never constructs a model/controller.
getMenuItems(): array [] unless settings.menu.enabled is truthy. Otherwise section main, order 100, parent null by default, icon/color/route from settings, title from name. This differs from database manifest projection/navigation.
log(string $level, string $message, array $context = []): void Calls Laravel logging at supplied level with [Plugin:<id>] prefix; invalid levels/errors can propagate.
broadcast(string $event, array $data = []): void Calls global broadcastToPlugin only when available; otherwise silently returns. See plugin broadcasts.

register(): void is a no-op default. boot(): void loads hooks; an overriding boot method must call parent::boot() if it wants that behavior. Lifecycle defaults log the operation. The provider also loads enabled hook files once per container using canonical-path tracking. A hooks.php may register listeners directly or return ['hook.name' => callable]; returned callables receive default priority 10. Use direct registration for multiple listeners or explicit priority. A returned array does not dispatch the hook. See hooks.

PluginServiceProvider::getPluginInstance(string $pluginId): ?object resolves a matching discovered plugin class only when the class exists and its binding is present. It returns null otherwise and does not require enabled state. Other static accessors are getPlugins(): array, getPlugin(string $name): ?array, isEnabled(string $name): bool, plus getModules()/getModule() compatibility aliases. getPlugins() returns only enabled entries; getPlugin() matches an enabled entry by slug/ID, and isEnabled() tests that lookup. These read container metadata; they do not run validated lifecycle operations.

Manifest config and persisted plugin settings

These three stores have separate readers:

Call Reads/writes
$plugin->config(string $key, mixed $default = null): mixed Dot traversal of the loaded manifest, including stored null values. Returns fallback if a segment is absent. It does not read Laravel config or database rows.
$plugin->getSetting(string $key, mixed $default = null): mixed SettingService::get('plugins.<id>.<key>', $default); fallback if the service class is unavailable.
$plugin->setSetting(string $key, mixed $value): void SettingService::set('plugins.<id>.<key>', $value) in default group general; no action if service class unavailable.
$plugin->getAdminSettings(): array Projects admin_settings groups, rewriting each key to plugin.<id>.<key> and adding original_key/plugin_id; it does not persist defaults.

A manifest can supply an operator-editable group like this (inside its existing root object):

{
  "admin_settings": {
    "journal_preferences": {
      "label": "Journal",
      "icon": "Cog6ToothIcon",
      "order": 20,
      "settings": {
        "report_limit": {
          "type": "number",
          "label": "Report limit",
          "default": 25,
          "min": 1,
          "max": 100,
          "step": 1
        },
        "visibility": {
          "type": "select",
          "label": "Default visibility",
          "default": "private",
          "options": [{ "value": "private", "label": "Private" }]
        }
      }
    }
  }
}

Expected projection for plugin ID journal: keys plugin.journal.report_limit and plugin.journal.visibility, each carrying original-key/plugin metadata. Enabled plugin instances supply these groups to the settings controller; defaults are displayed without creating stored rows. Use unique group IDs because groups are merged by their ID. The current Slate settings view renders boolean, number and select controls, then a text input fallback for other types; declaring json does not create a JSON editor there. Number min/max/step and select options are UI metadata; enforce domain values in the actual handler. Source: settings API, Slate settings view.

The singular plugin. admin-schema prefix and plural plugins. base helper prefix currently differ. An admin control for report_limit therefore does not feed getSetting('report_limit') automatically. For an admin-schema-backed value in a Journal handler, read its exact key:

$limit = app(\App\Core\Services\SettingService::class)
    ->get('plugin.journal.report_limit', 25);

Expected: the typed stored value or 25 if no row exists. Choose one explicit key contract for the feature. Do not save both variants as a hidden workaround. SettingService caching still applies; base writes invalidate the per-key cache, not its aggregate cache.

The global setting(?string $key = null, $default = null) helper is loaded by Composer. setting() returns SettingService; setting('journal.limit', 25) only reads with fallback 25. Its second argument never writes. Use setting()->set('journal.limit', 25) for an intentional persisted write, with the same service cache rules. Source: Plugin, settings helper.

The admin.sidebar hook contract defines the actual contribution pipeline. AdminSidebarService::getSidebarItems($user): array builds core sections, applies the filter, validates plugin sections, filters disabled plugins and sorts the result; $user does not cause per-user authorization here.

SidebarItemValidator::validate(array $sections, array &$existingIds): array returns cleaned plugin sections, logging/dropping invalid entries. It requires id, label, icon, numeric order, adds accepted IDs to the passed array by reference, and removes children without a label. Missing named child routes are warned about and retained. Core-ID sections bypass this validator. CoreAdminMenu::items(): array supplies the initial core list.

AdminMenuSchema::schema(): array is a separate declarative list: string-required id, label, icon, route, permission, integer-optional order. The runtime validator does not consume that schema; its required order and child handling differ. Follow the actual hook/validator contract when contributing a menu. Neither schema nor menu visibility grants access to a route. Admin helper source.

Building plugin admin views and operations

When a plugin needs more than simple key-value admin_settings—such as dedicated data tables, moderation logs, blueprint management, or action buttons—it exports an Admin View. A complete plugin admin interface requires four coordinated parts:

1. Declare the admin route in plugin.json

Enable admin routing in routes and declare an admin frontend route with requiresAdmin: true:

{
  "name": "Journal",
  "slug": "journal",
  "routes": {
    "api": true,
    "admin": true
  },
  "frontend": {
    "routes": [
      {
        "path": "/admin/plugins/journal",
        "name": "admin.journal.manage",
        "component": "AdminJournalView.vue",
        "meta": {
          "title": "Journal Moderation",
          "requiresAdmin": true
        }
      }
    ]
  }
}

The admin SPA's initializeAdminPluginRoutes(router) scans for frontend routes whose path starts with /admin/. It loads the plugin's compiled bundle, strips the leading /admin prefix, and dynamically registers the route under the admin-shell layout.

2. Implement backend admin endpoints in routes/admin.php

When "admin": true is enabled in plugin.json, Pulse automatically mounts routes/admin.php under /api/plugins/<slug>/admin/ with auth:sanctum, plugin.access:<slug> and the plugin admin guard. Administrators are admitted, and so is a role an administrator granted this plugin's admin access (or every plugin, *) on the Roles page, for controller actions in the plugin's own namespace. Moderators without such a grant are not admitted, whatever middleware the file adds itself; a route that declares role:admin itself stays admin-only. To give moderators specific moderation endpoints, set "moderator": true under routes and put only those endpoints in routes/moderator.php; it mounts under the same prefix with role:admin|moderator:

<?php

use App\Plugins\Journal\Controllers\AdminJournalController;
use Illuminate\Support\Facades\Route;

Route::middleware(['auth:sanctum', 'role:admin', 'plugin.access:journal'])
    ->group(function (): void {
        Route::get('overview', [AdminJournalController::class, 'overview']);
        Route::get('entries', [AdminJournalController::class, 'index']);
        Route::delete('entries/{id}', [AdminJournalController::class, 'destroy'])->whereNumber('id');
    });

Because the provider applies the /api/plugins/<slug>/admin prefix, relative paths inside routes/admin.php map directly (e.g. overview becomes /api/plugins/journal/admin/overview).

3. Build the admin Vue component (AdminJournalView.vue)

Plugin admin components run inside the admin application's runtime. The component uses window.LFStudioPluginRuntime.http to send authenticated, CSRF-protected requests to its backend admin routes:

<template>
  <div class="space-y-6">
    <div class="flex items-center justify-between">
      <div>
        <h1 class="text-2xl font-bold text-white">Journal Management</h1>
        <p class="text-sm text-slate-400">Review community entries and moderation status</p>
      </div>
      <button @click="refreshData" :disabled="loading" class="px-4 py-2 bg-slate-800 hover:bg-slate-700 text-white rounded-xl border border-slate-700 transition">
        {{ loading ? 'Refreshing...' : 'Refresh' }}
      </button>
    </div>

    <!-- Data Table Card -->
    <div class="bg-slate-800/50 backdrop-blur border border-slate-700/50 rounded-2xl p-6">
      <div v-if="loading" class="text-center py-8 text-slate-400">Loading entries...</div>
      <div v-else-if="entries.length === 0" class="text-center py-8 text-slate-400">No journal entries recorded.</div>
      <table v-else class="w-full text-left border-collapse">
        <thead>
          <tr class="border-b border-slate-700/50 text-xs font-semibold text-slate-400 uppercase tracking-wider">
            <th class="py-3 px-4">Author</th>
            <th class="py-3 px-4">Title</th>
            <th class="py-3 px-4">Date</th>
            <th class="py-3 px-4 text-right">Actions</th>
          </tr>
        </thead>
        <tbody class="divide-y divide-slate-700/30 text-sm">
          <tr v-for="entry in entries" :key="entry.id" class="hover:bg-slate-800/30 transition">
            <td class="py-3 px-4 text-white font-medium">{{ entry.author_name }}</td>
            <td class="py-3 px-4 text-slate-300">{{ entry.title }}</td>
            <td class="py-3 px-4 text-slate-400">{{ entry.created_at }}</td>
            <td class="py-3 px-4 text-right">
              <button @click="deleteEntry(entry.id)" class="text-red-400 hover:text-red-300 font-medium">Delete</button>
            </td>
          </tr>
        </tbody>
      </table>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'

const entries = ref([])
const loading = ref(true)

async function refreshData() {
  loading.value = true
  try {
    const http = window.LFStudioPluginRuntime.http
    const res = await http.get('/api/plugins/journal/admin/entries')
    entries.value = res.data?.data || []
  } catch (error) {
    console.error('[journal admin] Failed to fetch entries:', error)
  } finally {
    loading.value = false
  }
}

async function deleteEntry(id) {
  if (!confirm('Are you sure you want to delete this entry?')) return
  try {
    const http = window.LFStudioPluginRuntime.http
    await http.delete(`/api/plugins/journal/admin/entries/${id}`)
    await refreshData()
  } catch (error) {
    alert('Failed to delete entry.')
  }
}

onMounted(refreshData)
</script>

Plugin views should adhere to Pulse Admin theme styling using Slate Tailwind tokens (bg-slate-800/50, border-slate-700/50, text-slate-400, text-white, rounded-2xl).

Class naming and styling

Give every plugin admin screen its own clear, prefixed class names. Do not reuse the core admin's wf-* design-system classes, and do not invent bare generic names such as asset-card, breadcrumbs or field-error that can collide with another plugin's view in the same app.

  • Pattern: <plugin-slug>-admin-<element>, with --<variant> for variants — for example properties-admin-card, properties-admin-btn properties-admin-btn--primary, and referrals-admin-badge referrals-admin-badge--warn.
  • Put the structural CSS in the component's own <style scoped> block, so the plugin ships its styles inside its own bundle and cannot leak into the admin app.
  • Read the admin theme variables instead of hardcoding a second palette: --admin-panel, --admin-border, --admin-radius, --admin-text. Always supply a fallback, because a plugin screen can render before those variables are defined.
  • Keep Tailwind utilities for layout and spacing; the bespoke classes should cover panels, headers, buttons, badges, tables and empty states.

Reference implementations: rounds (rounds-admin-*), forum (fa-*) and town-square (town-*). A class-name audit of these three shows the intended result: every bespoke class is namespaced to its plugin.

4. Dock into the Admin Sidebar (hooks.php)

To make the view accessible to administrators, register a listener for the admin.sidebar filter hook inside the plugin's hooks.php:

<?php

app('hook')->addFilter('admin.sidebar', function (array $sections): array {
    // Dock cleanly under the standard Community domain group
    $sections[] = [
        'section' => 'community',
        'route'   => '/admin/plugins/journal',
        'label'   => 'Journal',
        'icon'    => 'ClipboardDocumentListIcon',
        'plugin'  => 'journal',
        'order'   => 15,
    ];

    return $sections;
});
  • Standard Domain Groups: Target 'section' => 'gameplay', 'section' => 'economy', or 'section' => 'community' to keep the sidebar organized. Pulse automatically prunes domain groups that have no active children.
  • Automatic Lifecycle Handling: If the journal plugin is disabled or uninstalled, AdminSidebarService automatically strips its menu items.
  • Standalone Sections: If your plugin represents an entire ecosystem category, you can supply a full section array with unique id, label, icon, and order. Validated by SidebarItemValidator.

In backend/app/Plugins/journal/routes/api.php:

<?php

use Illuminate\Support\Facades\Route;

Route::get('/status', fn () => response()->json(['ready' => true]));

After registration/enabling, GET /api/plugins/journal/status returns {"ready":true} for an authenticated authorized request. The provider supplies api, auth:sanctum, and plugin.access:journal middleware. Do not repeat the plugin prefix inside the file. Legacy direct/plural API aliases may also mount; use the canonical URL in new code.

routes/admin.php mounts under /api/plugins/<slug>/admin with the same checks plus the plugin admin guard: administrators, and holders of a role an administrator granted this plugin's admin access (Roles page, "Plugin admin access"; PluginAdminAccess). Only controller actions in the plugin's own namespace, declared in a file inside the plugin's own directory, whose URI stays under that prefix get the engine's signed approval; closures, foreign or core controllers, routes moved out of the prefix and routes that declare role:admin themselves stay admin-only. A plugin admin route from which Laravel would not run the engine's access guard (withoutMiddleware('api'), an alias of the guard, or a #[WithoutMiddleware] controller attribute) is refused with 403 for everyone. With routes.moderator: true, routes/moderator.php mounts under the same prefix with role:admin|moderator instead; keep only moderation endpoints there, as controller actions in the plugin's own namespace whose class file is inside the plugin's own directory (closures and foreign controllers stay admin-only, and the approval is re-checked on every request). A signed route that is later moved off the admin path stays admin-only. Add operation-specific permissions and ownership checks in your own code. routes/public.php mounts only with explicit routes.public_api: true, omits auth, and keeps plugin access checking. routes/web.php gets the web stack but no automatic plugin API prefix or auth; protect those routes deliberately.

ValidatePluginAccess returns JSON 404 plugin_not_installed, 403 plugin_disabled, or 402 license_required when appropriate, and stores the row in request attribute current_plugin on success. It does not authorize ownership of player records.

Capabilities and active context

Every route group the engine mounts for a plugin (web, public API, API, legacy API aliases, admin and moderator) also carries plugin.context:<slug> (EnterPluginContext), so the whole request runs inside that plugin's PluginContext. A controller that calls EconomyService directly is therefore checked against the plugin's declared ledger.write permission even without an explicit run(). A streamed response body runs after the middleware returns, so code inside a stream callback runs as core.

Hook listeners run in the context of the plugin that registered them, not the plugin whose route fired the hook. Listeners registered from a plugin's register(), boot() or hooks.php belong to that plugin; listeners registered by core run as core (PluginContext::runAsCore). For example, a crime fired from the crimes route that triggers quests.activity runs the quests listener with quests' permissions.

Use PluginContext::run('journal', fn () => ...) around protected service calls that can also run outside a request, such as jobs, commands and scheduled ticks. It pushes context and restores the previous context in finally, including when the operation throws. enter(string): void and exit(): void are lower level stack operations; prefer run(string, callable): mixed.

active(): ?string / getActiveSlug(): ?string return the innermost slug. assertPermission(string): void throws when an active plugin lacks a required capability; hasPermission(string): bool checks without throwing. PluginPermissionException extends RuntimeException and exposes readonly string pluginSlug and permission properties for diagnostics. With no active plugin context, these permit core calls. This is cooperative capability checking at explicit API boundaries, not isolation from arbitrary PHP or SQL.

matchesPermission(array $granted, string $required): bool recognizes exact, wildcard and documented aliases. setPermissions(string $slug, array $permissions): void seeds cache, useful in tests; reset(): void clears cache and stack. normalizePermissionArray(array): array and describePermissions(array): array normalize/display declarations. Approved database permissions override manifest permissions when present. These capabilities differ from a human user's Spatie permissions; enforce both where the operation needs both.

Views, migrations, slots and verification

Blade views use <slug>::view-name; PHP translations use the plugin namespace. Frontend translations have a different client registration path. Assets can be published through provider publish tags, while compiled runtime publication uses the service in packages.

A slot needs a manifest entry, registered component, published bundle and a host screen that actually renders that slot. A menu item needs a resolvable route; a manifest alone does not create a Vue component or API implementation.

Use PluginRouteSecurityTest, PluginKernelTest, PluginContextTest, PluginManagerServiceTest, and PluginRuntimeAssetServiceTest as source-backed verification patterns. The provider skips normal discovery in unit tests; App\Core\Testing\PulsePluginTestCase::enablePluginForTest supplies explicit initialization for plugin tests. See testing.

Sources: providers (backend/app/Core/Providers), PluginManagerService (backend/app/Core/Services/PluginManagerService.php), PluginValidationService (backend/app/Core/Services/PluginValidationService.php), PluginContext (backend/app/Core/Services/PluginContext.php), contracts (backend/app/Core/Contracts).