This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.
Total CMS is a modern PHP-based Content Management System using flat-file JSON storage. Built with Slim 4 framework, it provides a RESTful API with Twig templating and a comprehensive admin interface. The product is in production with 200+ sites. Version 3.5 (shipped 2026-08-26) added the CLI, extension system, event system, Composer distribution, Site Builder, public registration, platform-installation flow, built-in MCP server, and Automations. Active development is on develop toward 3.6.
- Total CMS License API (totalcms/license.totalcms.co): License validation and trial management with similar Slim 4 architecture
- Total CMS 3 Stacks: Stacks plugin for the Stacks platform
- Documentation Site (totalcms/docs.totalcms.co): Public docs at docs.totalcms.co (Astro Starlight). Source of truth is
/resources/docs/in this repo; synced to the docs site via the build script - Marketing Site: totalcms.co — built with Total CMS itself (Site Builder), so it doubles as the dogfood install (local:
~/Websites/totalcms.co) - Extension Starter (totalcms/extension-starter): Template repo for building T3 extensions, demonstrates every extension point
- Official Docs Connector:
https://totalcms.co/mcp— the marketing site's own MCP server serves the T3 documentation to AI agents (docs_search,docs_get,docs_lookup) via a private extension. Successor to the retired standalone mcp.totalcms.co app. - Project Repo (totalcms/totalcms-project): Composer project template for installing T3 via
composer create-project
Specs, plans, audits, and release write-ups live outside this repo, in the Obsidian Total CMS folder: ~/Library/Mobile Documents/iCloud~md~obsidian/Documents/KnowledgeBase/Total CMS/. Read and write them there, and do not recreate these folders under docs/.
planning/: specs and plans, one folder per target release (3.6/,3.7/,3.8/), plusfuture/(no release assigned) anddone/(shipped).planning/README.mdis the index.audits/: security and performance audits.releases/: release notes, blog posts, community posts, and newsletters for each version.
Older code comments cite docs/planning/...; those paths now mean the planning/ folder above.
- Backend: PHP 8.2+, Slim 4, Twig 3, PHP-DI 7, PSR-7/PSR-15
- Frontend: ESBuild, Sass/SCSS, TypeScript/ES6+, HTMX 4.x, Node.js with pnpm via Vite+ (
vp) - Rich Text: Tiptap editor (replaced Froala)
- Search:
SearchProviderabstraction — built-intextprovider by default, optional Algolia (algolia/algoliasearch-client-php) - Testing: Pest (PHP testing), PHPStan Level 8, PHP-CS-Fixer, PHPMD, Rector; Vitest + Oxlint for JS, both run through
vp
You do not need to worry about frontend asset building (primary development command).
There is a watch script in dev that will autobuild all front end assets and
rebuild the bundle integrity manifest (resources/bundle) on every change.
# Development with file watching (typically runs in background)
bin/watch.sh
# Full application build (manual release builds only)
composer run build
# JS toolchain: Vite+ (`vp`, install with `curl -fsSL https://vite.plus | bash`)
# fronts pnpm (pinned in package.json#devEngines), Vitest and Oxlint. The
# esbuild build itself is unchanged — vp only replaced Yarn and the test/lint
# runners. There is no yarn.lock any more; pnpm-lock.yaml is the lockfile.
vp install # dependencies (bin/build-assets.sh runs this)
vp run test:js # Vitest, ~5s
vp run lint:js # Oxlint over javascript/, warnings fail (.oxlintrc.json)
vp run lint:js:fix # Oxlint safe auto-fixes; also part of `composer run clean`
# Create distribution bundle (manual release builds only)
composer run bundle# Static analysis (PHPStan Level 8)
composer run stan
# Code style checking and fixing
composer run cs
composer run cs:fix
# Run tests — bin/runtests.sh is the normal entry point.
# No args: every check CI runs (~48s): dependencies vs. what CI resolves,
# composer validate, bundle:check, stan, md, docs:validate, JS lint, JS tests
# with the coverage gate, PHP tests, golden snapshots. The quick gates run
# first; dependencies, md, docs and the JS checks then run in the background
# (at low priority) beside the PHP suite and report after it. -v runs them in order.
# With a filter: ONLY the matching PHP tests, for a fast edit-run loop.
# composer.lock is gitignored, so CI installs the newest versions composer.json
# allows; the Dependencies step fails when vendor/ is behind (a newer PHPStan
# once failed CI on code that was clean locally) — run `composer update`.
bin/runtests.sh # everything
bin/runtests.sh SomeTest # tests matching a name
bin/runtests.sh tests/Feature/Foo.php # a single file or directory
bin/runtests.sh --lint # also run phplint (~36s)
bin/runtests.sh --serial # PHP suite serially, exactly as CI (~140s)
# The underlying Composer scripts, if you need one directly:
composer run test # serial, ~140s
composer run test:parallel # parallel, ~40s
composer run test:parallel -- --filter=SomeTest # parallel + filter
composer run test:all:parallel # stan + docs + PHP + JS
# Verify the bundle integrity manifest is current (~0.3s).
# Run this after editing anything under config/, resources/templates/,
# or the covered src/ files — a stale manifest breaks writes at runtime
# with 400 "installation has been corrupted", and the test suite does NOT
# catch it. See "Bundle integrity" under Testing Best Practices.
# `bin/watch.sh` rebuilds it for you while it is running; this is the check
# for when it was not.
composer run bundle:check
# Run all quality checks
composer run test:allcomposer.json defines ~40 scripts; the others worth knowing are quality /
quality:full, docs:validate, rector / rector:fix, and mcp:inspect.
composer run md runs PHPMD 3 over src/ and config/ with phpmd.yml and
reports only violations not in phpmd.baseline.xml — the baseline holds the
structural debt accepted when the gate was set up (large methods, high
coupling, etc.), keyed by rule + file + method so line edits do not disturb it.
It is part of bin/runtests.sh and test:build, so a new over-complex method,
unused variable or superglobal fails CI. When you refactor something that is in
the baseline, delete its <violation> line from phpmd.baseline.xml by hand and
run composer run md — a still-needed entry resurfaces as a violation. Do NOT run
composer run md:baseline: under PHPMD 3.0.0 --update-baseline keeps only the
violations it reports, which are the ones the baseline does not cover, so it
empties the file (verified 2026-10-17, with and without the PDepend cache). Prefer a @SuppressWarnings("PHPMD.Rule")
docblock with a reason over a baseline entry for anything deliberate.
pdepend.yml.dist runs PDepend with its cache in memory: the on-disk cache in
~/.cache/pdepend has produced both phantom violations and (2026-10-17) a clean
local run for code CI then failed, so the local gate now always recomputes.
/src/Action/- HTTP action handlers organized by domain (Admin, Auth, Collection, Extension, Upload, etc.)/src/Domain/- Business logic layer with services, repositories, and data objects/src/Domain/Extension/- Extension system: discovery, lifecycle, permissions, settings, route collection/src/Domain/Event/- Core event dispatcher (used by extensions and internal services)/src/Domain/Automation/- Automations: schedule/webhook/event triggers, queue, runner, state store/src/Domain/DataView/- Data Views: saved cross-collection queries (Pro+ edition feature)/src/Domain/Search/- Search provider abstraction, indexing jobs, reindex listeners/src/Domain/XmlRpc/- WordPress-compatible XML-RPC publishing endpoint (off by default)/src/Domain/JumpStart/- JumpStart data import/export system/src/Domain/Import/- CMS import systems (Alloy, Total CMS 1, Wordpress, CSV, JSON, RSS, URL)/src/Domain/Factory/- Factory system for generating test data using Faker/src/Domain/ImageWorks/- Image processing with watermarking, font management, and caching/src/Domain/Twig/- Twig templating system with adapters, extensions, and custom functions/src/Domain/Mailer/- Transactional + bulk mailer (bulk is edition-gated)/src/Domain/AccessGroup/+/src/Domain/ApiKey/+/src/Domain/OAuth/- Authorization credentials and grouping/src/Domain/Sync/-tcms push/tcms pullcollection sync (6-collection allowlist)/src/Domain/Visualizer/- Collection + object relationship diagrams (Mermaid)- (53 domains total — the above are the high-traffic ones; browse
src/Domain/for the rest)
/src/CLI/- Symfony Console CLI application and commands/src/Middleware/- HTTP middleware for auth, CORS, licensing, edition gating, validation/src/Renderer/- Response rendering (JSON, XML, Twig, Raw)/src/Infrastructure/- Framework wiring, diagnostics, server checks/src/Composer/- Composer plugin (ships the agent skill, install hooks)/src/Handler/,/src/Support/,/src/Traits/,/src/Transformer/- Cross-cutting helpers/src/Utils/- Utility classes for file handling, image processing, QR codes/config/- Hierarchical PHP configuration and route definitions/tcms-data/- JSON-based flat-file storage for collections/tcms-data/extensions/- Third-party extensions installed as{vendor}/{name}//resources/schemas/- JSON schemas for data validation/resources/templates/- Twig templates for admin interface/resources/docs/- Documentation files (source of truth for docs.totalcms.co)/resources/fonts/- Centralized font storage (default: RobotoRegular.ttf)/tests/test-data/- Test datasets for integration testing/tests/fixtures/extensions/- Test extension fixtures (must be committed to git)
- Domain-Driven Design: Clear separation between Actions, Domain services, and Data layers
- Repository Pattern: Data access abstraction with JSON storage
- Dependency Injection: PHP-DI container with interface-based design
- Middleware Pipeline: Authentication, CORS, license validation, request transformation
- HTMX Integration: Server-rendered partial HTML responses for interactive UI without heavy JS
- Collection System: 33 reserved schemas (
SchemaData::RESERVED_SCHEMAS— blog, image, gallery, builder-page, automations, mcp-*, etc.) plus user-defined custom schemas, all stored as JSON files - Collection Reports: Reporting API and admin utility for collection data
- Data Views: Saved, filtered, dependency-resolved views across collections, rebuilt on a schedule. Pro+ edition feature with its own access middleware; exposed to MCP via
list_views/get_view/query_view/describe_view - Search: Pluggable
SearchProviderabstraction (built-intextby default, Algolia optional), with index jobs and event listeners;tcms search:reindexrebuilds - XML-RPC Publishing: WordPress-compatible endpoint so MarsEdit/Byword/Ulysses can publish into T3. Off by default — gated behind
$settings['xmlrpc'] - Data Visualizers: Admin relationship diagrams — collection ERD and object flowchart, both Mermaid, sharing one
RelationshipAnalyzer - Site Builder: Dynamic page router serving
builder-pagescollection objects at configurable URL patterns, with starter scaffolding, template designer, and optional Vite frontend pipeline - Setup Wizard: First-run web wizard (welcome → environment → data-path → account → license → server-config → complete) for operator onboarding, with auto-login on account creation
- Public Registration:
/admin/register/{collection}endpoint with opt-in allow-list for self-signup forms; auto-logs the new user in viaSessionLogin - Load More System: Frontend pagination with
loadMoreButtonfor progressive content loading - Template Designer:
{% templatedesigner %}Twig tag for inline template definition synced to local + production servers (complements Load More) - Twig Playground: Admin tool for testing and prototyping Twig templates with autosave
- RSS & Sitemap Builders: User-facing utilities for generating RSS feeds and sitemaps from collections
- JumpStart System: Data import/export with streaming support for large datasets; also powers starter-kit content seeding
- Import Systems: Migration from other platforms (Total CMS 1, Alloy CMS, Wordpress, CSV, JSON, RSS, URL) via job queue
- ImageWorks System: Image processing with text/image watermarking, custom font support, EXIF metadata
- Twig Integration: Custom filters/functions,
{% cmsgrid %}tag, markdown processing, barcode extension - Admin Interface: Form builder with 20+ field types, JavaScript components
- Passkey Authentication: WebAuthn passkey support for passwordless admin login
- Cache System: Multi-backend caching with APCu-first priority (APCu -> Redis -> Memcached -> Filesystem)
- CLI Tool (
tcms): Symfony Console CLI for collections, schemas, objects, JumpStart, sync, updates, builder scaffolding, search reindexing, and extension management - Extension System: Two-phase lifecycle (register → boot) for third-party extensions with capability-based permissions
- Event System: Synchronous event dispatcher with 22 core events (object/collection/schema/template/user CRUD, import.*, bulk.deleted, extension lifecycle, devmode, cache.cleared, access.denied, file.downloaded); every payload carries
actor - Automations: Schedule, webhook, and event-triggered automations with a job queue, run history, and guard rails; handlers are externalized code fields
- Built-in MCP Server: OAuth 2.1, schema/collection/data-view tools, read-only Site Builder template tools, resources, prompts, and search providers so AI agents can query the site directly
- Composer Distribution: Public Packagist distribution via
composer create-project totalcms/totalcms - Build System: ESBuild with code splitting
- Storage: Flat-file JSON storage (no traditional database)
- Caching: Multi-backend Twig caching with APCu-first priority (APCu, Redis, Memcached, filesystem, OPcache)
- Modern PHP: Strict typing, PSR standards, PHP 8.2+ features with PHP 8.4 compatibility
- Distribution: Public Packagist via
totalcms/cms(the library). Installed withcomposer create-project totalcms/totalcms(the project skeleton) - Extensions: Third-party extensions in
tcms-data/extensions/{vendor}/{name}/with auto-detected capability permissions - Enhanced Libraries: Custom couleur fork with OKLCH improvements (joeworkman-forks/couleur)
- Memory Management: Streaming patterns for large datasets (see
JumpStartData::streamJsonToFile()for examples) - Emergency Cache:
/api/emergency/cache/clearand/api/emergency/cache/clear-licenseendpoints for customer self-service cache clearing (note the/apiprefix — both are registered inside the/apigroup) - Logging: Zip installs log to
tcms-data/.system/logs(survives updates); Composer installs log toprojectRoot/logs. Nine-file LogFile/LogChannel taxonomy. - Releases:
bin/prepare-release.shbuilds the dist zip, registers the version with the license API, and uploads to S3 (totalcms-archive/releases/). Licensed downloads vialicense.totalcms.co/version/download/{version|latest}; public latest-zip vialicense.totalcms.co/download/latest.
- Session Management: Use
Odan\Session\PhpSessioninstead of direct$_SESSIONaccess - CSRF Protection:
CSRFTokenManager+CSRFProtectionMiddlewarewith token validation from POST/headers/query - HTML Sanitization:
HTMLSanitizerinsrc/Utils/handles XSS prevention, castpreg_replace()to(string)for PHPStan - SVG Sanitization:
SvgDataautomatically sanitizes SVG content usingenshrined/svg-sanitize - CSP Middleware: Content Security Policy headers
- CORS: Limited to specific routes
- File Upload Validation: Security validation on all file uploads
- File Path Protection: Prevention of path traversal attacks
- Use tabs for indentation (not spaces)
- Private/protected class properties and methods use camelCase
- Constructor property promotion with
private/protectedvisibility - Array type hints:
@param array<string,mixed> $data - Method return types always specified
- Handlers contain minimal HTTP logic, delegate to Services
- Services contain business logic and orchestrate Repositories
- Repositories handle database/storage operations
- Proper HTTP status codes (400 for validation, 404 for not found, 500 for server errors)
- Constructor dependency injection for repositories and other services
- Business logic validation in services (not handlers)
- Comprehensive error handling with meaningful exception messages
- Return arrays or data objects, not HTTP responses
- Type Safety: All methods must have explicit return types
- Null Handling: Use proper null checks and casting, especially for
preg_replace()which can return null - Array Types: Use specific array type hints like
@param array<string,mixed> $data - Property Annotations: Use
@phpstan-ignore-next-linesparingly for edge cases - Testing: Always run
composer run stanafter making changes to maintain Level 8 compliance
- Code Style: Only run
composer run cs:fixwhen explicitly requested - avoid during development as it makes tracking changes difficult - Quality Checks: Use
composer run stanfor type checking, avoid mass formatting changes - Code Reports: Only run
bin/code-report.shwhen creating new builds, not during development sessions - Change Tracking: Keep git diffs clean by focusing on specific files being worked on
- Run tests via
bin/runtests.sh(or a Composer script) — never invokevendor/bin/pestdirectly. Both setapc.enable_cli, which avoids MCP rate-limit flakiness.bin/runtests.sh Xfilters to matching PHP tests; with no argument it runs the full battery. bin/runtests.shruns on the PHP version CI pins (php-versionin.github/workflows/build.yml). If your defaultphpis a different minor and Homebrew hasphp@<that version>, the script puts it first on PATH for the run and says so; without it, a filtered run warns and the full battery refuses. Two failures that only ever showed on CI were ordering differences between APFS and ext4 directory reads — both listers now sort, but a version gap hides the same class of thing.- Do not run two test batteries at once. Parallel runs share
tests/.workers/, and a second run (or anrm -rf tests/.workers) mid-flight deletes the first run's sandboxes: symptoms areSiteKey::get()returning null, "Invalid password" on the first-login workflow, and phantom users in the auth index. - Parallel is the default and the suite is parallel-safe.
--parallelneeds no flag from you —test:parallelis ~40s against ~140s serial. Each worker gets its own sandbox undertests/.workers/{TEST_TOKEN}/{tcms-data,cache,tmp}viatests/worker-paths.php, whichtests/bootstrap.php,tests/Pest.phpandconfig/local.test.phpall read. If you add a path that tests write to, route it through there too or workers will race. Delete every sandbox withrm -rf tests/.workers. - A global function declared in one
*Test.phpis invisible to another under--parallel(the two files can land in different workers). Shared test helpers belong intests/Pest.php. - Paratest gives each file to one worker, so a slow file sets the end of the run.
AuthorizationMatrixTest(20s) ran alone for the last 13s until it was split into three files sharingtests/Security/AuthorizationMatrix.php. After adding a heavy file, check per-file times withcomposer run test:parallel -- --log-junit=…. phpunit.xmlsetsresolveDependencies="false". PHPUnit's@dependssorting grows with the square of the suite size and cost every worker ~5s before its first test. No test usesdepends; if one ever needs it, expect startup to grow again.- Never let a test reach the network.
tests/bootstrap.phpcallsContainerFactory::override()before any container is built, bindingHttpClientInterfacetoTests\Fakes\OfflineHttpClient(every request fails as if the network were down) andLicenseValidatortoTests\Fakes\FakeLicenseValidator(a valid Pro license). Binding them after the build, asbootstrap()intests/Pest.phpalso does, is too late for services resolved while the app boots: until 2026-11-02 that let ~100 live requests per run through, to the license server among others. Anything going through that interface is covered; code that builds its own Guzzle client takesTests\Fakes\OfflineGuzzle::client()— saving a Vimeo video URL used to make a live oEmbed call per test. Code that bypasses the interface still needs its own stub:tests/Feature/SyncMediaFieldTest.phpused to download from picsum.photos through theimagefactory rule, and broke whenever that service did — e.g.FakerPicsum::setHttpClient() - Test memory limit:
tests/bootstrap.phpsets it fromTCMS_TEST_MEMORY_LIMIT(default1G). It runs after PHPUnit appliesphpunit.xml's<ini>block, so a plain-d memory_limit=on the command line is silently clobbered — use the env var. The coverage scripts set4G, without which the parallel run dies in paratest'sCoverageMergerwhile merging per-worker data. A test that runs code callingini_set('memory_limit', …)in-process must put the old value back inafterEach—jobs:processsets its--memorydefault of 512M that way, and beforeJobsProcessCommandTestrestored it, CI's serial run (which, unlike the local parallel battery, keeps one process for all 12k tests) ran out of memory 500 files later (2026-10-17). The same goes for any process-global state:session_save_path(),$_SERVER,ini_set(). - Coverage: use
test:coverage:parallel. It passes and takes ~40s. Serialtest:coveragehas ~37 pre-existing failures (mostly 403s inIndexQueryTestandMcp/McpAuthPersonaGroupAccessTest) that look like rate limiting during the much longer single-process run — unrelated to the memory limit, and not present in parallel. - API Endpoint Testing: Use
postJson()instead ofpost()for JSON endpoints - Flexible Status Codes: Use
toBeIn([200, 400, 404, 405])instead of exact matches for better test framework compatibility - Framework Compatibility: Follow existing working test patterns (e.g.,
AuthTest.php) for reliable results - Test Data: Maintain comprehensive test datasets in
/tests/test-data/for integration testing - Error Handling: Test both success and failure scenarios with graceful error handling
- Golden snapshots:
tests/Feature/FormGoldenTest.phppins the HTML of every form the factory builds against Pest snapshots intests/.pest/snapshots/, which are committed. Pest never fails on a missing snapshot — it recreates it silently and marks the test incomplete,--ciincluded — sobin/check-snapshots.phpfails when a snapshot is untracked or deleted-unstaged; it runs after the PHP tests inbin/runtests.sh, incomposer test:build, and in the pre-commit hook. A snapshot diff is a behaviour change: intended → delete the file and re-run, then commit the new one; not intended → that is the regression - Stale Twig cache: Twig render tests can serve stale compiled templates after a
.twigedit (test env hasauto_reloadoff) —rm -rf cache/*before re-running locally. Under--parallelthe cache is per-worker, so cleartests/.workers/*/cache(or justrm -rf tests/.workers) instead - Bundle integrity:
resources/bundlehashesconfig/,resources/templates/and selectsrc/files — not just config. After editing anything it covers, rebuild withcomposer run bundleand commit the manifest alongside the change.bin/watch.shdoes the rebuild automatically while it runs. Never hand-edit it. A stale manifest makes every write fail at runtime with 400 "installation has been corrupted"- Tests do not catch this.
tests/bootstrap.phpsetsAPP_ENV=test, which switchesBundleMiddleware's check off so the suite doesn't have to regenerate the manifest after every edit, and no test covers the manifest.composer testis plain pest with no bundle step. The gate iscomposer run bundle:check(~0.3s), which CI runs — but only after a push, so an install trackingdev-developcan pull the broken commit first.bin/runtests.shruns it as its first step, so use that and you cannot miss it - Install the pre-commit hook with
bin/install-hooks.shto run that check automatically. Note the manifest hashes the working tree, not the index: rebuild with unstaged edits to a covered file present and it records content that isn't in the commit
- Tests do not catch this.
- Use Design System Variables: Always use CSS variables from
/css/variables.scssinstead of hardcoding colors or values - Variable Format: Use
oklch(var(--totalform-*))for colors to ensure consistency with the design system - Common Variables:
- Border color:
oklch(var(--totalform-border-color)) - Background colors:
oklch(var(--totalform-nearwhite)),oklch(var(--totalform-icon-bg)) - Text colors:
oklch(var(--totalform-darkgray)),oklch(var(--totalform-text-color)) - Accent colors:
oklch(var(--totalform-accent)),oklch(var(--totalform-success)) - Border radius:
var(--totalform-radius)
- Border color:
- Avoid: Custom colors, hardcoded values, non-existent variables
When working with large datasets (JumpStart exports, imports, bulk operations):
- Streaming Pattern: Process data incrementally instead of loading everything into memory
- Immediate Cleanup: Use
unset()to free memory after processing each item in loops - Real-World Example: See
JumpStartData::streamJsonToFile()for complete streaming implementation - Key Principle: Default to streaming patterns for any dataset that could potentially grow large
These are non-obvious details that are important when working in these areas:
- Global Variable: Use
cmsfor accessing configuration, collections, and services - Configuration:
cms.config('key')notconfig(which doesn't exist) - Common Usage:
cms.env,cms.config('debug'),cms.gallery(),cms.image() - Grid System:
{% cmsgrid %}tag for content grids with helper methods incms.grid.*
- Font Support: TTF/OTF fonts from depot storage (default: RobotoRegular.ttf)
- Configuration:
watermarkFontsDepotsetting (default: 'watermark-fonts') - Color System: Enhanced OKLCH color manipulation via custom couleur fork
- Architecture: Custom Twig Loader preprocessor extracts raw block content before Twig compilation
- API:
PUT/HEAD /designer/templates/{path}withDesignerAccessMiddleware(public, token-gated) - Schema:
designerEnabled(toggle) +designerToken(UUID, readonly) - Metadata: Companion
.designer.jsonfiles alongside.twigfiles
- Concept: Dynamic page system where
builder-pagescollection objects are routed at request time byPageRouterMiddleware. No build/generate step — add a page in the admin, it's live. - Page records: Objects in the
builder-pagescollection (schema:builder-page). Fields:id,title,route(template URL with{id}style placeholders),template,draft,nav,data(free-form JSON exposed aspage.data.*),status(HTTP),redirectTo,sitemap,middleware,accessGroups - Templates: Live at
tcms-data/builder/{layouts,pages,partials,macros}/*.twig.BuilderTwigAdapterprovidescms.builder.nav(),cms.builder.url(pageId, params),cms.builder.css/js/asset()with mtime cache-busting - Page router:
src/Middleware/PageRouterMiddleware.phpmatches request paths against page routes, dispatches templated routes throughObjectUrlBuilder. Templated URLs (containing{...}placeholders) are implicitly pretty — theprettyUrlflag only applies to non-templated URL prefixes. - Starters:
tcms builder:init <starter>scaffolds fromresources/builder/starters/{name}/— copies templates, ensures thebuilder-pagescollection, runs the starter'sjumpstart.jsonto seed pages + demo content. Bundled:minimal,blog,business,portfolio - JumpStart-driven: Starter pages live in
jumpstart.jsonasbuilder-pagesobjects (NOT inmanifest.json— manifest is metadata only). Reserved-collection entries support overrides (e.g.{"id": "blog", "url": "/blog/{id}"}) to set the URL/sortBy alongside the schema-bound default. - Frontend pipeline: Optional Vite scaffold via
tcms builder:frontend(or--frontendflag onbuilder:init) — drops a customer-editablefrontend/directory withvite.config.js, compiles topublic/assets/ - Key files:
PageRouterMiddleware,BuilderTwigAdapter,BuilderInstaller,StarterService,BuilderOrderService(sidebar ordering via.order.json)
- Flow: First-run web wizard —
welcome→environment→data-path→account→license→server-config→complete. State persisted in<datadir>/.system/setup-state.json(HMAC-signed elsewhere; here it's just step tracking) - Middleware:
SetupCheckMiddlewareruns BEFORE Slim's RoutingMiddleware so it can intercept unrouted requests (like/). When setup is incomplete it redirects page navigation to the current wizard step; asset/API requests fall through to normal 404 handling. - Account step:
AccountSetupSubmitActioncreates the first admin user viaFirstLoginChecker, stashes the email in session (setup_admin_email) so it pre-fills the form on validation-failure redirects AND displays on the complete page. After successful save it auto-logs the operator in viaSessionLogin::establish()so they don't have to retype credentials at the end of the wizard. - Server-config step: Renders rewrite-rule snippets for Apache + Nginx. Detects whether
public/.htaccessalready ships (Composer install) and switches the Apache panel between "rules already in place" and "paste this in" messaging. - Subpath layout:
bin/post-install.phpin the project skeleton supports asubpathlayout option that movespublic/index.phpandpublic/.htaccessintopublic/tcms/and bumps theTCMS_PROJECT_ROOTdirname depth. - Key files:
src/Domain/Setup/,src/Action/Setup/,SetupCheckMiddleware,DataPathInstaller
SessionLogin(src/Domain/Auth/Service/SessionLogin.php): Single source of truth for "log this user in." Writes the four session keys (AUTH_USER,AUTH_COLLECTION,AUTH_PERSISTENT_LOGIN,LICENSE_CHECK_DUE) in the same order across every entry point. Used byAuthLoginSubmitAction,AccountSetupSubmitAction, andAuthRegisterSubmitAction. Does NOT authenticate — caller verifies the user first.- Public registration endpoint:
POST /admin/register/{collection}(AuthRegisterSubmitAction). Creates a user viaObjectSaver, callsLoginService::authenticate()for verification, thenSessionLogin::establish(). Returns JSON in the same shape asObjectSaveActionso the form builder can chain deferred uploads + actions. - Allow-list:
$config->auth['publicRegistration']is an opt-in list of collection IDs. Empty by default — the defaultauthcollection (operator-only) is never exposed. Endpoint throwsHttpForbiddenExceptionfor collections not in the list. - Form builder integration:
cms.form.builder('members', {register: true})retargets the form at/admin/register/{collection}, forcesaddOnly: true(the endpoint has no PUT route), and rewritesdata-apito drop the/apiprefix auth.loginWithconfig:'email','id', or'both'.UserValidationService::validateUser($idOrEmail, $collection)dispatches transparently; for'both'it picks based on@in the input. The login form's identifier field is always POSTed asemailfor backwards-compat — the variable name is misleading.- Security caveats the operator owns (documented in
auth.publicRegistrationconfig block +wizard.accountflow): registrants are auto-logged in, so any unprotected form on a site with gated content exposes that content to bots. Gate with CAPTCHA / rate limit / email verification when the access group new users land in reaches sensitive content.
- Lifecycle: Two-phase —
register()during container build,boot()after routes are loaded - API Surface:
ExtensionContextprovides curated methods; extensions never touch the raw container directly - Extension Points: Twig functions/filters, CLI commands, routes (API/public/admin), admin nav items, dashboard widgets, custom field types, event listeners, admin assets, container definitions, schemas
- Capability Detection: After
register(), the system detects what the extension actually registered (not self-declared). Capabilities become toggleable permissions in the admin UI. - Permissions: Stored in
tcms-data/.system/extensions.jsonper-extension. Admins can disable individual capabilities without uninstalling. AllgetAll*()accessors filter by permission state. - Settings: Per-extension custom settings in
tcms-data/.system/extension-settings/{vendor}/{name}.json. Settings schemas use the sametype+fieldformat as collection/settings schemas. - Routes: Extensions register routes via
RouteCollector(not Slim directly). Three static route handlers dispatch at runtime:ExtensionRouteAction(API),ExtensionAdminRouteAction(admin),ExtensionAssetAction(static assets). - Admin UI: Extension management page with enable/disable, auto-generated permission toggles, and custom settings forms via
TotalFormFactory::extensionSettings(). - Twig Collision Protection:
TwigExtensionRegistrarblocks extensions from overriding core Twig functions/filters and warns on extension-to-extension collisions. - Fault Isolation: Every
register()andboot()call is wrapped in try/catch. Failures are logged, recorded in state, and the extension is skipped. - Key Files:
ExtensionManager(orchestrator),ExtensionContext(public API),ExtensionDiscovery(filesystem scanner),ExtensionState(runtime state with permissions)
- Framework: Symfony Console via
CliApplication - Entry Point:
resources/bin/tcms(shipped; exposed asvendor/bin/tcmsvia Composerbin). In this repo run it asphp resources/bin/tcms— there is nobin/tcmssymlink. - Commands:
collection:list|get|create|update|delete|export|import|query|convert,access-group:list|get|set|patch,object:list|get|create|patch|export|delete,schema:list|get|export|import|lint|delete,jumpstart:export|import,builder:init|frontend|routes|history,extension:list|enable|disable|remove,update:check|apply|rollback,automations:process,jobs:process,mcp:status,mcp:test,oauth:setup,oauth:gc,repair:files,repair:index,rss:import,search:reindex,deck:import,cache:clear,skill:install,deploy,info,check,pull,push - Extension Commands: Loaded after core commands with collision protection (extensions cannot shadow built-in command names)
- Output Formats: Human-readable tables by default,
--jsonflag for machine-readable output
- Dispatcher:
src/Domain/Event/Service/EventDispatcher.php— synchronous, priority-ordered - Event names: Always use the
CoreEventconsts (src/Domain/Event/Data/CoreEvent.php) atdispatch()/listen()call sites, never raw strings - Core Events (22):
object.created,object.updated,object.deleted,collection.created,collection.updated,collection.deleted,schema.saved,schema.deleted,template.saved,user.login,user.logout,import.created,import.updated,import.completed,bulk.deleted,extension.enabled,extension.disabled,devmode.enabled,devmode.disabled,cache.cleared,access.denied,file.downloaded - Integration: EventDispatcher is injected into ObjectSaver, ObjectUpdater, ObjectRemover, CollectionSaver, CollectionRemover, LoginService, LogoutService, SchemaSaver, SchemaRemover, TemplateSaver, ExtensionManager, ObjectImporter, JumpStartImporter, DeckJsonImporter, DeckCsvImporter
- Extension Listeners: Registered via
$context->addEventListener(), wired into the dispatcher during boot. Listeners execute in try/catch so a broken listener cannot affect core operations. - Import-Time Behavior: While a collection is mid-import (
EventDispatcher::suspendForImport($collection)),object.createdandobject.updatedevents are suppressed for that collection — importers fireimport.created/import.updatedper object instead, with the sameObjectEventPayloadshape. Listeners that want to react to import-time writes specifically subscribe to theimport.*events.import.completedauto-resumes the suspension (safety net for forgetful importers).ObjectImporterself-suspends when called outside an explicit lifecycle (e.g.JobRunnerprocessing a single queued job).
- Triggers:
schedule(cron-style viaScheduleTicker),webhook(AutomationWebhookAction), andevent(AutomationEventSubscriberbridging the core event dispatcher) - Storage: Automations are objects in the reserved
automationscollection (automations+automation-triggerschemas); handlers are externalized code fields (code.json$ref→CodeData) - Execution:
AutomationRunnerexecutes handlers with anAutomationContext(schedule runs haverequest/eventnull; event runs carry the event payload).AutomationQueue+tcms automations:processhandle queued runs;AutomationGuardprovides guard rails; run history viaRunRecord/AutomationRunReader - Key files:
src/Domain/Automation/,src/Action/Automation/(webhook, run-now, re-enable),src/Middleware/Automation/
- Providers:
$settings['search']['activeProvider']is'text'(built-in) or a registered provider id such as'algolia'. Providers register through theSearchProviderinterface, so extensions can add their own. indexOnSavegotcha: when true,object.created/object.updatedevents push straight to the active provider'sindex(). Disable it during bulk imports to avoid hammering an external embedding/index API, then re-enable and runtcms search:reindex.- Structure:
src/Domain/Search/splits Data / Job / Listener / Service
- Concept: A saved, filtered, dependency-resolved query across one or more collections, materialized on a schedule rather than computed per request. Stored via the reserved
dataviewsschema. - Double gate:
DataViewsEditionMiddleware(Pro+ edition,EditionFeature::DATA_VIEWS) andDataViewsAccessMiddleware(per-user access groups). Both must pass — an edition check alone is not authorization. - Services:
src/Domain/DataView/Service/—DataViewBuilder(materialize),DataViewFetcher,DataViewQueryService,DataViewFilter,DataViewDependencyResolver(which collections a view depends on),DataViewUpdateScheduler(rebuild cadence),DataViewLister,DataViewRemover - Surfaces: admin page (
AdminDataViewsAction), REST actions (src/Action/DataView/— query, fetch, rebuild, test), and MCP tools (list_views,get_view,query_view,describe_view) - Access groups:
dataviewsis a grantable resource inAccessGroupData— checkAccessControlServicewhen changing view visibility
- Purpose: WordPress-compatible XML-RPC so desktop editors (MarsEdit, Byword, Ulysses) publish into T3
- Off by default:
$settings['xmlrpc']is['enable' => false, 'ratePerIp' => 60](config/defaults.php); route inconfig/routes/public/xmlrpc.php - Structure:
src/Domain/XmlRpc/splits Transport (parser/writer/fault), Handler (blog, post read/write, taxonomy, system, unsupported), and Service (MethodRouter,PostMapper,BlogRegistry,XmlRpcAuth) - Auth: API keys as the credential, not session cookies — see
XmlRpcAuth editPostmust patch, not replace — clients send partial post structs; a full replace silently drops fields the editor did not send
- Deep Merge: Override specific nested settings without replacing entire arrays
- Usage: Return array from tcms.php for deep merging
- Type Safety: All array properties protected with
is_array()validation
- Validation Flow: Middleware -> Service -> API call -> JWT validation -> Cache
- Data Structure: 8 essential fields (valid, trial, domain, edition, message, validationToken, updatesValid, trialDaysRemaining)
- Cache Integration: Multi-backend with 24-hour TTL
- Version Authorization: License API validates the running T3 version is authorized for the license. Unauthorized versions show a dashboard warning.
- Pattern: Paid features are gated per-edition at the route level, not inline in services.
EditionFeature(src/Domain/License/Data/EditionFeature.php) enumerates the gated features; each gets a thin middleware extendingBaseEditionMiddlewarethat returns itsEditionFeature, attached to the relevant route group. - Current features (9):
custom_schemas,external_rest_api,qr_codes,barcodes,data_views,rss_import,bulk_mailer,passkeys,access_groups - Middlewares live in
src/Middleware/License/— 14 of them, since some features gate more than one route group (collections, schemas, templates, API keys, OAuth, automations, mailer) - When adding a feature: decide early whether it is edition-gated. Adding the gate later means retrofitting routes, and the middleware is the only enforcement point — services do not check editions themselves.
- Source of truth:
resources/docs/*.mdis mirrored to docs.totalcms.co. Template changes toresources/templates/admin/docs.twigonly affect the in-admin viewer — the public site has its own template that needs parallel changes. - Sidebar menu lives in
resources/docs/menu.php(shared byAdminDocsActionandbin/build-docs-index.php). 15 top-level groups: Get Started, Collections, Schemas, Fields, Site Builder, Twig, Forms, Automations, Admin, Notifications, Auth, APIs, MCP, Extensions & CLI, Operations. Adding a new doc page = add a{title, path}entry to the appropriate group. Fields, Twig, and Extensions & CLI use nested subgroups (the last via mixedsub+groups); everything else is flat. Groups carrying'sort' => 'alpha'(Operations, Field Types, Bundled Extensions) sort themselves by title insidemenu.php, with'pinned' => trueentries held at the top — append new pages anywhere in those; learning-path groups are hand-ordered. - Folder convention: each doc lives in
resources/docs/<kebab-cased-group-name>/<page>.mdmatching its menu group (e.g.get-started/,site-builder/,apis/,operations/). Subgroups (Field Types, Field Options, Twig Basics, etc.) exist only in the menu — the files themselves are flat within the group folder. URL = path = file path underresources/docs/. - Images & screenshots: co-locate with the section that uses them, in
resources/docs/<section>/images/<name>.png. Reference in markdown asdocs/<section>/images/<name>.png(thedocs/prefix is required because of the admin's<base href>).AdminDocsActionserves png/jpg/gif/svg/webp at the same route as markdown pages — see the image-mime branch in that file. Use kebab-case filenames. - Navigation primitives: breadcrumbs, prev/next, and the related-pages footer are all derived from the menu — no extra config needed. Breadcrumb group label = whichever menu group the page lives in.
- No synthetic landing pages: each group's first sub-entry is its natural overview (e.g.
builder/overviewfor Site Builder,extensions/overviewfor Extensions). Avoid adding "Overview" entries that point to fabricated section landings — keep the natural intro page first instead. - Frontmatter conventions (all optional):
title:— H1 fallback, displayed in breadcrumbs and search resultsdescription:— used by searchrelated:— list of paths (e.g.twig/data) to render a "Related pages" block at the bottom of the page. Resolved against the menu for titles.audience:—beginner | intermediate | advanced. Stored but not displayed yet.updated:— date string, displayed in the page footer when present.
- Doc indexes:
bin/build-docs-index.phpregenerates BOTHresources/docs/search-index.json(page search) andresources/docs/reference-index.json(structured reference: Twig functions/filters via reflection, field types, API endpoints, schema config, CLI commands, extension/builder API — consumed by the docs MCP extension'sdocs_lookup). Both are checked into git because they ship with the Composer package. Rebuild and commit after adding, renaming, or substantially editing doc pages;tests/Unit/Docs/ReferenceIndexTest.phpfails on staleness or under-populated kinds.
This project has a knowledge graph at graphify-out/ with god nodes, community structure, and cross-file relationships.
Rules:
- For codebase questions, first run
graphify query "<question>"when graphify-out/graph.json exists. Usegraphify path "<A>" "<B>"for relationships andgraphify explain "<concept>"for focused concepts. These return a scoped subgraph, usually much smaller than GRAPH_REPORT.md or raw grep output. - If graphify-out/wiki/index.md exists, use it for broad navigation instead of raw source browsing.
- Read graphify-out/GRAPH_REPORT.md only for broad architecture review or when query/path/explain do not surface enough context.
- After modifying code, run
graphify update .to keep the graph current (AST-only, no API cost).