Architecture
21 modules, one assembly root
The backend ships as one executable jar, but the source is split into a shared contract layer, plugins, a container and a single assembly root. Plugins have no compile-time dependencies on each other.
Star topology
Business plugins may depend only on actor-shared; technical mechanisms may also depend on actor-support. Plugins may not depend on each other, on the container or on the app.
actor-app (the only assembly root / packaging point)
│ assembles every artefact
┌────────────────┼──────────────────┐
actor-runtime actor-infra-ai actor-module-* ×16
│ │ │
└────────────────┴───────────────────┘
│ depends on contracts only
actor-sharedThe parent POM blocks this at validate time with maven-enforcer-plugin bannedDependencies, and ModuleBoundaryTest checks it again with ArchUnit.
Three engines
The 16 plugins are grouped as world facts, character cognition and shared capability; the mapping lives in EngineCatalog.
| Engine | Modules | Responsibility |
|---|---|---|
| World (WE, 5) | world / map / item / worldgen / unity | Time and facts, space, material economy, world birth, external engine adaptation |
| Character (CE, 6) | npc / agent / growth / memory / dialogue / companion | Body and state, decision and expression, personality and life course, memory, sessions, companionship |
| Shared (5) | project / decision / platform / ops / infra-ai | World shell and archives, judgement and guardrails, settings and prompts, observability, AI gateway |
Compile-time dependencies across engines are flagged by EngineBoundaryTest; cross-engine work defines a port in actor-shared and lets the target engine implement it.
The contract layer
The only shared language between plugins and the container, with zero framework dependencies: no Spring, JPA or Jackson runtime types.
| Package | Contents |
|---|---|
| shared/port/ | Cross-module call surface: capabilities with return values that need strongly consistent reads |
| shared/dto/ | Immutable records: commands, views, reports, specs |
| shared/view/ | Cross-engine read-only views: world snapshot, environment, graph, item flow, resource balance |
| shared/event/ | The sealed DomainEvent set |
| shared/kernel/ | SimClock, DomainEventBus, EventJournal, DeterministicRandom |
| shared/error/ | R, PageResult, ErrorResponse, BizException, AiCallException |
| shared/contract/ | @FrozenApi, @MultiProvider |
| shared/spi/ | @ActorModule, PluginDescriptor |
Every port carries @FrozenApi(owner) and the owner must be registered in EngineCatalog.OWNER_ENGINES; signatures may only use records, JDK types and shared types.
The runtime container
actor-runtime makes no business judgements; it answers which plugins are installed, who implements each port, and when things fire.
- ModuleRegistry
- Scans @ActorModule, validates requires and fails fast on a missing dependency; checks implementation counts per port — zero is a WARN, multiple without @MultiProvider is a conflict.
- EngineCatalog
- The engine ownership table for modules and port owners, read by /actuator/engines and the engine guards.
- WorldTickScheduler
- Three @Scheduled jobs — world advance scan, due action dispatch, journal retention — depending on four contracts only.
- InProcessEventBus
- Synchronous delivery with per-subscriber exception isolation; JournalSinkAdapter subscribes to write domain events into the world journal, so publishers never know they are being recorded.
- HashedDeterministicRandom
- Derives deterministic seeds from (module, aggregateRef, gameSecond, purpose).
The assembly root
actor-app is the only Spring context entry point; a new port implementation placed elsewhere fails ModuleBoundaryTest.
- Startup and scanning
- HolzynActorApplication owns the start-up class, root package scanning and JPA entity and repository scanning.
- Wiring
- app/wiring/** holds per-domain wiring packages and whitelisted adapters that connect every shared.port implementation and cross-module @Bean.
- Global facilities
- app/common/** holds global exception handling, SPA forward fallback, static resource caching, the H2 file-lock guard, graceful shutdown, health checks and schema validation.
- Assembly smoke test
- ApplicationContextSmokeTest is the only test that loads the full context: random port, temporary data directory, one directory-database migration.
Swappable implementations
The acceptance test for plugin architecture is "swap the implementation, change nothing else"; a bad enum value fails start-up instead of silently falling back.
| Capability | Switch / contract | Implementations |
|---|---|---|
| Memory | holzyn.actor.plugins.memory.implementation + MemoryPort and 3 more ports | legacy (persisted, default), ephemeral (in-process), life (life memory) |
| Companion | holzyn.actor.plugins.companion.enabled | Entries hidden and endpoints return 501 when off; data is kept |
| Map generation | mapgen.ai-enabled | On: AI contract plus deterministic algorithms; off: pure deterministic fallback |
| AI vendor | AiGateway + AiRoutePort | The gateway implementation routes by scenario to different endpoints |
| Judge model | DecisionGatePort | A local small model over side-channel HTTP, falling back to a text model or a procedural default |
Module inventory
21 Maven artefacts: 4 kernel artefacts, 16 plugins and 1 alternative memory implementation. Each has its own README.md.
| Artefact | Engine | Responsibility |
|---|---|---|
| actor-shared | Kernel | Ports, DTOs, read-only views, domain events, simulation kernel, error envelope |
| actor-support | Kernel | SSE lifecycle, JSON column conversion, after-commit callbacks, tick barrier |
| actor-runtime | Kernel | Module registry, port binding, tick scheduling, event bus, journal sink, deterministic randomness |
| actor-app | Kernel | Startup, wiring, global web facilities, packaging |
| actor-infra-ai | Shared | AI gateway, vendor and scenario routing, concurrency gate, semantic cache, embeddings, judge bypass |
| actor-module-world | World engine | World clock, events and journal, fact layer, places, macro and meso, information diffusion, daily frame, adjudication, chronicle, run modes, player avatar |
| actor-module-map | World engine | S0–S5 map generation, plots and features, coordinates and pathfinding, placement and addresses, sandbox projection, world map data |
| actor-module-item | World engine | Item definitions and stacks, ledger, crafting, market and credit, equipment, durability and spoilage, starting supplies |
| actor-module-worldgen | World engine | Generation workflow, checkpoint resume, SSE progress, structure validation, six-dimension persistence, cast, story plan |
| actor-module-unity | World engine | Unity protocol bridge, WebSocket sessions, sandbox intervention translation, environment frames, coordinate transform, external clock alignment, perception feedback |
| actor-module-npc | Character engine | Profiles, needs and mood, current action, goals, relations, physiology coupling, ordinary crowd, combat |
| actor-module-agent | Character engine | Decision runtime, retry and ledger, strategy chain, perception and stimuli, context assembly, portrayal, action execution, learning, knowledge bridge |
| actor-module-growth | Character engine | Personality versions, life stages, marriage and birth, lineage, heredity, social mask, possible-space, cognitive attention and LOD |
| actor-module-memory | Character engine | Four memory layers, write deduplication, retrieval and injection, reflection, distillation, forgetting, memory health |
| actor-module-life-memory | Character engine (implementation) | Life memory: episodes, moments, clues, unfinished business, impressions, diary — the second MemoryPort implementation |
| actor-module-dialogue | Character engine | Conversation sessions and messages, group chat, context assembly, worldbook, player profile, summarisation, frozen snapshots |
| actor-module-companion | Character engine | Companion profile, companion space, conversation rhythm, mood and diary, proactive messages, reminders, private notes, entry |
| actor-module-project | Shared | Project entity, setup wizard, import and export, registry and world databases, mounting and gates, archive lifecycle |
| actor-module-decision | Shared | Decision gate, local judge model, escalation fallback, judge scoring, A/B experiments, guardrails |
| actor-module-platform | Shared | Settings, model access configuration, prompt templates and scenario assembly, usage accounting, local accounts, project assistant |
| actor-module-ops | Shared | Debug endpoints, AI call tracing, developer console, evaluation, timeline audit, observability, test runs |
Data and storage
The registry database holds cross-world data; each world has its own database. Both are migrated programmatically by Flyway with ddl-auto=none, so JPA never alters a table.
- Registry database
- data/holzyn-registry.mv.db: world index, accounts, global settings and companion profiles — data that spans worlds.
- World database
- data/worlds/<uid>/: that world’s characters, memories, events, map, items and usage in one H2 file database.
- Migration authority
- New tables and columns always arrive as V*.sql. Schema name, migration directory and Flyway history table agree, derived only from WorldSchemas.location() and historyTable().
- Table ownership
- backend/architecture/table-owners.yaml registers the single write service per table, and TableOwnershipTest asserts it table by table.
Ten world schemas
Defined once in WorldSchemas; the strings are not written anywhere else.
act actions and results eco economy and market mnd memory and mind
ops operations per person records sct social relations
soc society and groups spc space and maps sys system tables
wld world facts and timeGuards in the test suite
Architecture and contracts are enforced by assertions, not discipline. As of 2026-11-26: 589 test source files and roughly 4,900 test methods.
| Test | What it protects |
|---|---|
| ContractGuardTest | Zero framework dependencies, package shape, @FrozenApi completeness, signature width, sealed event set, annotation purity |
| ArchitectureTest | ArchUnit rules and the frozen store; no new violations |
| EngineBoundaryTest | Module and port-owner engine ownership; all 16 @ActorModule entries registered |
| ModuleBoundaryTest | Star topology: no compile-time edges between plugins; wiring whitelist |
| TableOwnershipTest | One write entry per business table |
| ModuleCouplingBudgetTest | Module coupling-edge budget |
| AiCallOutsideTransactionTest | Methods containing AI calls are not @Transactional |
| SchedulerOwnershipTest | @Scheduled only in registered classes, and maintenance jobs pass the world gate |
| RandomSourceGuardTest | Randomness goes only through DeterministicRandom |
| MappingsSnapshotTest / OpenApiSpecExportTest | Endpoints and the OpenAPI contract do not drift |
| VersionConsistencyTest | POM, code and frontend version strings agree |
| ApplicationContextSmokeTest | Full assembly, random port, temporary data directory, registry migration |
Extending it
The standard moves for new capability, in order; each step has a guard that checks it.
- Add a business plugin
- Create a module under backend/ and register it in <modules>; depend only on actor-shared (mechanisms may use actor-support); add the @ActorModule declaration; register the engine in EngineCatalog; ship a README inside the module.
- Add a cross-module port
- Confirm a real caller first; add the interface in shared/port with @FrozenApi; register the owner in EngineCatalog; record the port in port-catalog.md with provider and consumers; implement it in the provider’s plugin/ package.
- Add a swappable implementation
- Define the port and command/result DTOs first; put the implementation in its own artefact or the module’s plugin package and select it with @ConditionalOnProperty; enum switches must validate and fail fast on illegal values.
- Add a table or migration
- Add a V*.sql in the right schema directory and never edit a released migration; register the single write service in table-owners.yaml; tables needing concurrency carry row_version, tables queried by world time carry game_second.
- Add a frontend page
- Create the page under frontend/src/features/<domain>; register the route in shared/router and the nav entry in navModel.js; new top-level routes must be added to the SpaForwardController whitelist.
Key invariants
Rules that can be broken — and that will be caught.
- AI calls stay outside transactions
- A method containing a model call may not be @Transactional; persistence goes through a short transaction service.
- Plugins do not depend on each other
- Cross-module work goes through shared.port; another actor-module-* in a plugin POM is an architecture violation.
- One write entry per table
- Other modules read or call that entry; a second save is not allowed.
- Time comes only from SimClock
- No second clock, and no "real elapsed × rate" as a second time source.
- AI calls go only through AiGateway
- Business code does not import a concrete gateway implementation.
- Contracts live only in actor-shared
- A new port needs @FrozenApi, an owner and a catalogue entry; a port without a real consumer does not enter the contract layer.
- Flyway is the only schema authority
- New tables and columns arrive as migrations; JPA never alters the schema.
- The frozen store only shrinks
- After changing architecture rules, restore backend/archunit_store before judging results.
Want the source, or a world of your own?