systems

package
v0.0.0-...-95891f2 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 25, 2026 License: AGPL-3.0 Imports: 49 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

campaign_system_handler.go adds HTTP endpoints for campaign owners to upload, view, and remove custom game systems.

campaign_systems.go manages per-campaign custom game systems. Campaign owners can upload ZIP files containing manifest.json + data/*.json to create custom reference content for their campaign. These modules use GenericSystem (no Go code needed) and are stored in the media directory.

character_choices.go answers "which names can this character field be picked from?" for the active game system, so the attributes editor can offer a list (Ancestry, Kit, Race, Class) instead of a bare text box.

The stored value stays the chosen entry's NAME string in fields_data: the Foundry module writes item names into the same fields, so a richer stored shape would break its pulls. This package therefore only SUGGESTS names; it never validates a stored value against the list, and free text is always allowed.

Package systems — event_log.go provides an in-memory ring buffer for system loading events. Captures manifest discoveries, successful instantiations, and failures so the admin diagnostics page can show what happened without requiring external log access.

Package modules — generic tooltip renderer.

GenericTooltipRenderer produces HTML tooltip fragments for any module by reading the field schema from the module manifest. No custom code is needed — just declare fields in manifest.json and the renderer will display matching properties from each ReferenceItem.

Game-system modules can override this by implementing their own TooltipRenderer for richer formatting (e.g., stat blocks, icons).

Package systems — health.go exposes a read-only "deployment health" view of every LOADED system: the version + on-disk directory actually being served, plus a content fingerprint (size + sha256 + mtime) of each widget/manifest file. It answers the operator question "is the server serving the file I think it is?" — the failure mode where Admin▸Packages reports one version but a stale copy is what actually renders — without shell/SSH access to the host.

Read-only by construction: it only stats and hashes files the loader already serves. Surface it behind an admin-gated route.

Package systems — operator_batch.go implements the BATCH half of the operator AI workspace: a request/approve/execute protocol, all read-only. The operator downloads FunctionsSpecJSON (the catalog); an external AI composes ONE batch-request naming the diagnostics it wants; ParseBatch validates it and produces a PLAN the operator reviews before approving (prompt-injection containment — unknown names and full-dump requests are flagged); RunBatch then executes only the named, read-only diagnostics, redacts the output, and returns one compact document. The heavy full dump (system.health) needs an explicit `full_dump: true` so it can't leak by accident.

Package systems — operator_diag.go is the operator-facing analogue of the campaign AI-Export: a catalog of named, read-only diagnostics the admin runs and pastes to the AI assistant.

Why a CATALOG and not one big dump: a monolithic export wastes the assistant's context with data it didn't ask for. Instead the assistant requests ONE named diagnostic at a time (e.g. "run `system.files drawsteel`"); the operator runs just that and pastes a small, targeted result. The full dump (`system.health`) exists but is opt-in — requested by name only when actually needed.

Safety: read-only by construction (only stats/hashes files the loader already serves; the probe commands are SUGGESTED, never executed by Chronicle). All output passes through redactSecrets as defense-in-depth, so a future diagnostic that accidentally surfaces a config value can't leak a credential.

Package systems — operator_diag_assets.go answers which ASSETS the running binary is serving (host.build in operator_diag_host.go answers which binary), across both places Chronicle keeps them: the on-disk static root (a bare relative path "static", resolved against the process working directory — hardcoded identically in internal/app/app.go and internal/templates/layouts/assets.go, so a diagnostic must resolve it the same way rather than hardcode an absolute path), and each plugin's //go:embed-ed static FS, visible only from inside the binary.

These diagnostics call layouts.AssetURL for the `?v=` cache-bust token rather than reimplementing its hashing, so it can never disagree with what the browser is served. A mismatch against the on-disk sha256 means either the file changed under a running process (the digest is memoised for process lifetime) or the asset never resolved and fell back to the per-build token.

Package systems — operator_diag_calendar.go is the calendar plugin's own operator diagnostic: "is the calendar plugin actually live for THIS campaign, and is it up to date?" — a narrower question than campaign.config (which addons are enabled) or campaign.surfaces (which page a URL renders), and one campaign.config's own CALV5-PLACEHOLDER notes explicitly deferred to this file once the calendar plugin had counts worth reading again (calendar-v5 seams, #778).

COUNTS ONLY. Never event text, never member names, never an answer to "what does the calendar say" — this is a state check, not a content export (that is aiexport's CategoryCalendarEvents, gated Director-only). RunDiagnostic's redactSecrets pass still runs over the output as defense in depth.

Package systems — operator_diag_campaign.go is the CAMPAIGN half of the operator diagnostic catalog: "why does MY campaign look like this?" — as opposed to the host.* family, which answers WHICH CODE IS RUNNING.

Two diagnostics live here, both reading campaign CONFIG: `campaign.surfaces` (which live route serves a URL, and where the sidebar points) and `campaign.config` (enabled addons and every block a campaign has placed).

DEGRADE LOUDLY. An unwired provider prints "provider not wired"; a read that failed prints the error. A plausible-looking empty answer is the one thing neither of these may ever produce.

Package systems — operator_diag_deploy.go answers "I deployed, and I see no change. Did it land?" as one composite diagnostic: build identity, the fingerprints of the assets that move on essentially every build, an optional marker search, and the installed-vs-loaded package summary.

It DELEGATES rather than restates. The package summary is renderInstalledVsLoaded() itself, the build identity comes from hostIdentityLines() beside host.build's own renderer, and every token comes from layouts.AssetURL — reimplementing any of those would risk a second opinion that disagrees with the diagnostic it summarizes.

The marker search spans all THREE places a shipped string can live: the on-disk static root, the binary's embedded plugin filesystems, and the compiled-in strings of the executable itself (Templ markup lives in compiled Go string literals and appears in neither of the other two, so searching only two scopes can wrongly conclude a deploy hasn't landed).

Package systems — operator_diag_entities.go adds the data-tracing half of the operator diagnostics: read-only inspectors for served file CONTENT, an entity's stored field values, a type's field-population coverage, and the most recent inbound sync payloads. Together they form a three-way "where does the data die?" compare:

Foundry SENT  (sync.inbound)  ->  Chronicle STORED (entity.fields)  ->  schema DECLARED (entity.field-coverage)

All read-only, redacted by RunDiagnostic's redactSecrets pass, admin-gated and audited by the AI-workflow workspace. Cross-layer reads (entity data, inbound sync) arrive via injected providers — systems must not import entities/syncapi, so the app layer wires these at startup (mirrors SetInstalledPackagesProvider).

Package systems — operator_diag_errors.go is the "what has this server been getting wrong?" half of the host diagnostics, answerable without shell access. The audit plugin can't fill this gap: it records USER ACTIONS, DB-backed and scoped to a campaign and a user, so a 500 on /healthz or an anonymous request has neither key it needs.

What these diagnostics deliberately do NOT claim. The ring is in process memory: a restart empties it, and each replica keeps its own. So an empty result has THREE different meanings that must never be flattened into one — nothing was recorded, nothing is recording, or the process restarted since the failure. Every render below states which of those it is looking at, and the header always prints the ring's capacity and hold count so "only 4 errors" is visibly different from "the ring was never wired".

operator_diag_host.go is the "which Chronicle am I actually running?" half of the operator diagnostic catalog.

These diagnostics report ONLY what the process can observe about itself, and each line says whether the fact is actually known: "not stamped" is a real answer; a blank field or a plausible-looking guess is not. This matters because `docker inspect <tag>` describes whichever image holds that tag NOW, never the image a running container was created from — the closing trust note names that trap explicitly.

Package systems — operator_diag_plugins.go is the EXTENSION-TIER half of the host diagnostics: which PLUGINS the binary registered and which WIDGET assets it serves (host.build/host.assets/host.embedded cover the binary and its raw bytes).

Widgets have no version number — nothing declares or stores one, and there's no server-side widget registry, just a JS file that registers itself with boot.js on mount — so the Desc reports a content fingerprint plus build time rather than inventing a meaningless number. Their assets also live in two unrelated places: `static/js/widgets/` on disk, and each plugin's `js/` `//go:embed`-ed into the binary, so grepping the container filesystem can miss an asset that is still served.

Chronicle has no plugin loader — every plugin compiles in and registers routes unconditionally — so the two registries this file reads are opt-in METADATA; host.plugins always says a missing row is not a missing feature.

operator_picker.go shapes the diagnostic catalog for the AI helper page: six everyday questions that each pick their checks, the whole catalog in plain-word groups for picking by hand, and ComposeBatch, which turns either pick into the same batch request an outside AI would paste. The page never runs a check from here; it hands the composed request to ParseBatch and the usual review step, so a picked request is validated exactly like a pasted one.

preview.go provides dry-run inspection of game system packages before installation. Validates ZIP contents, parses manifests, counts reference data, and builds a tree structure for impact visualization — all without writing anything to disk.

Package modules defines the system registry for Chronicle. Modules are game system content packs (e.g., D&D 5e, Pathfinder) that provide reference data, tooltips, and stat blocks. They are read-only and enabled per campaign via campaign settings.

The registry auto-discovers modules by scanning subdirectories for manifest.json files at startup. See SystemManifest for the JSON spec.

Package modules defines the system framework for Chronicle. Modules are read-only game system content packs that provide reference data (spells, monsters, items, stat blocks) and tooltip rendering. They implement sandboxed interfaces and never access the database, Echo router, or plugin services directly.

Index

Constants

View Source
const (
	PageStatePackage = "package" // untouched package page
	PageStateEdited  = "edited"  // campaign copy of an unchanged package page
	PageStateChanged = "changed" // campaign copy, but the package page moved on or is gone
	PageStateMine    = "mine"    // a page the campaign added
)

Page states shown to Directors as the editor's status dots.

View Source
const (
	// MaxCardLookKeyLen is the entry_key column's width. Package slugs are not
	// length-limited by the package format, so a longer key is refused rather
	// than truncated into another entry's key.
	MaxCardLookKeyLen = 150
	// MaxCardLookChanges bounds the items one Customizer save may carry.
	MaxCardLookChanges = 500
)
View Source
const (
	// RuleOpen is a per-player exception: the entry is offered to that
	// player whatever a rule for everyone says. For everyone it is the
	// default and is never stored.
	RuleOpen = "open"
	// RuleAskFirst offers the entry, but picking it goes to a Director to
	// allow or answer with another suggestion.
	RuleAskFirst = "ask_first"
	// RuleNotOffered takes the entry off the list.
	RuleNotOffered = "not_offered"
	// RuleRequired makes the entry part of the short list a step must be
	// chosen from.
	RuleRequired = "required"

	// RuleGroupKey as an entry key marks every entry of a source at once,
	// including entries added later.
	RuleGroupKey = "*"

	// RequestWaiting is a pick that waits for a Director.
	RequestWaiting = "waiting"
	// RequestAllowed is a request a Director said yes to.
	RequestAllowed = "allowed"
	// RequestSuggested is a request a Director closed with a note asking the
	// player to choose something else.
	RequestSuggested = "suggested"
	// RequestWithdrawn is a request that no longer has anything to decide,
	// because its entry was deleted.
	RequestWithdrawn = "withdrawn"
)
View Source
const (
	BreakNotOffered = "not_offered"
	BreakOffList    = "off_list"
)

Kinds of HeroBreak.

View Source
const (
	JudgeEach  = "each"
	JudgeTotal = "total"
)

Judge values of a CritRule.

View Source
const (
	// OriginCampaign is an entry the campaign wrote beside the package.
	OriginCampaign = "campaign"
	// OriginRewritten is a campaign entry that takes a standard entry's place.
	OriginRewritten = "rewritten"
	// OriginStandard is the package's own entry, credited to the system.
	OriginStandard = "standard"
)

Where an entry's words come from.

View Source
const (
	// ResolvedEntry: this is the entry to show.
	ResolvedEntry = "entry"
	// ResolvedRedirect: go to Resolution.Slug instead (Entry is its target).
	ResolvedRedirect = "redirect"
	// ResolvedLeftOut: the campaign does not offer it; Entry still carries
	// its content, so a hero who already is one can read the traits.
	ResolvedLeftOut = "left_out"
	// ResolvedPrinted: the Director's printed original of a rewritten entry.
	ResolvedPrinted = "printed"
	// ResolvedNotFound: nothing this reader may see answers.
	ResolvedNotFound = "not_found"
)

What resolving an address or a name gave.

View Source
const (
	ViaRewritten = "rewritten"
	ViaOldName   = "old_name"
	ViaOldSlug   = "old_slug"
)

Why a redirect leads elsewhere.

View Source
const (
	// EntityPanelAppliesNPC is pages whose type the owner listed as NPCs,
	// with their sub-types.
	EntityPanelAppliesNPC = "npc"
	// EntityPanelAppliesCreature is pages of a creature type (the "creature"
	// preset category, or a slug of "creature" or "*-monster"), with their
	// sub-types, so a bestiary page gets its stat block without being an NPC.
	EntityPanelAppliesCreature = "creature"
)

The audiences an entity panel can target.

View Source
const (
	PlayEditOwner = "owner" // the claimed owner, or Scribe and above
	PlayEditGM    = "gm"    // Scribe and above only
	PlayEditNone  = "none"  // nobody through the play door
)

Play edit modes: who may change a field during play.

View Source
const (
	PlayKindCounter    = "counter"
	PlayKindResource   = "resource"
	PlayKindConditions = "conditions"
	PlayKindChoice     = "choice"
	PlayKindText       = "text"
)

Play kinds: the control shape and the value check a field gets.

View Source
const (
	PlayAuthorityFoundry   = "foundry"
	PlayAuthorityChronicle = "chronicle"
)

Combat authority values: which side wins when Chronicle and Foundry disagree about a field during combat.

View Source
const (
	MaxPackageDesigns = 100
	// MaxPackageDesignBytes matches the designs plugin's own data cap, so a
	// package design can always be copied into a library.
	MaxPackageDesignBytes = 16 * 1024
)

Limits on the designs a package ships. They bound what a third-party package can put in front of every Owner of a campaign on its system.

View Source
const (
	RunOnly    = "only"
	RunChanged = "changed"
	RunNotIn   = "not-in"
)

The three runs, in the order the page draws them.

View Source
const (
	// ToolsStandard: an untouched standard entry of a kind ("Rewrite for
	// <campaign>", "Not in <campaign>").
	ToolsStandard = "standard"
	// ToolsLeftOut: a standard entry the campaign left out ("Bring back").
	ToolsLeftOut = "left_out"
	// ToolsRewritten: a campaign entry that takes a standard entry's place.
	ToolsRewritten = "rewritten"
	// ToolsCampaign: the campaign's own entry, tied to nothing.
	ToolsCampaign = "campaign"
)

Which amber words an entry's page offers the Director.

View Source
const (
	// ShopTestTiers bands the total with two cut-offs, like a power roll.
	ShopTestTiers = "tiers"
	// ShopTestDC compares the total with a difficulty: meet it for the middle
	// outcome, beat it by 5 for the best.
	ShopTestDC = "dc"
)

Shop test styles: how a total becomes one of three outcomes.

View Source
const (
	// EntryVisibilityEveryone lists the entry for every campaign member.
	EntryVisibilityEveryone = "everyone"
	// EntryVisibilityDirectors keeps the entry to the owner and co-Directors,
	// for an option the party has not discovered yet.
	EntryVisibilityDirectors = "directors"
	// EntryVisibilityCharacter shows the entry to Directors and to whoever
	// plays one character page (ForEntityID): a penciled option shown to the
	// one player it is meant for.
	EntryVisibilityCharacter = "character"

	// ChoiceSourceCampaign marks pick-list entries a campaign made itself.
	ChoiceSourceCampaign = "campaign"

	// EntryStatusAccepted is every Director's entry and a player's once a
	// Director accepts it: visibility alone decides who sees it.
	EntryStatusAccepted = "accepted"
	// EntryStatusDraft is a player's entry they are still writing, or one a
	// Director handed back with a note. Only its writer and the Directors
	// see a draft, whatever its visibility says.
	EntryStatusDraft = "draft"
	// EntryStatusSent is a player's draft handed in for a Director to accept.
	EntryStatusSent = "sent"
)
View Source
const ChoiceSourcePackage = "package"

ChoiceSourcePackage marks entries that come from a system's own data file. Later features register further sources (for example campaign-made entries, "campaign").

View Source
const ChoiceStateAskFirst = RuleAskFirst

ChoiceStateAskFirst marks a Choice the viewer must ask a Director for.

View Source
const CreatorOptionsSuffix = "_choices_json"

CreatorOptionsSuffix names the field beside a step's field that keeps what a hero bought from the chosen entry's list (ancestry_choices_json).

View Source
const EntryHiddenKey = "director_only"

A campaign entry's details can be kept from players one by one: the detail EntryHiddenKey lists the names of the details only Directors read (a complication's drawback, a kit's secret rider). It is the one place that says so, and visible() drops those details and the list itself for everyone else, so the sheet, the pick lists, the rules pages and the Foundry sync, which all read through it, never carry them.

View Source
const MultiPickSeparator = ", "

MultiPickSeparator joins the picks of a Multi step in its field.

View Source
const ToldWindow = 14 * 24 * time.Hour

ToldWindow is how long a change the players were told about stays marked.

Variables

View Source
var ValidFieldTypes = map[string]bool{
	"string":   true,
	"number":   true,
	"boolean":  true,
	"list":     true,
	"markdown": true,
	"enum":     true,
	"url":      true,
}

ValidFieldTypes is the whitelist of accepted field type values. Manifests with unknown field types are rejected during validation.

Functions

func ApplyCampaignPick

func ApplyCampaignPick(plan *BatchPlan, campaignID string)

ApplyCampaignPick substitutes the operator-chosen campaign into every call whose campaign slot was left ambiguous. Called by the run handler when the review dropdown was used. The id comes from the server-rendered campaign list and all calls are read-only + campaign-scoped, so substitution is safe.

func ApplyEntityPick

func ApplyEntityPick(plan *BatchPlan, entityRef string)

ApplyEntityPick substitutes the operator-supplied entity ref into every call whose entity slot was left ambiguous.

func BeforeURL

func BeforeURL(campaignID, systemID string) string

BeforeURL is the gathered page's address.

func BookAsset

func BookAsset(sysDir, name string) ([]byte, string, error)

BookAsset returns the bytes and content type of the cover or font file called name, but only if book.yaml declares it. Anything else is os.ErrNotExist, whatever is on disk.

func CampaignSlotIsAmbiguous

func CampaignSlotIsAmbiguous(name, arg string) bool

CampaignSlotIsAmbiguous reports whether a call is campaign-scoped but left its campaign as a placeholder (`<...>`) or empty — i.e. the review step should ask the operator to pick one.

func CardBorderGuide

func CardBorderGuide() string

CardBorderGuide is the plain-words note on the two card details, with every border key and its shown name, for the people and tools that write entries.

func ChoiceFor

func ChoiceFor(ctx context.Context) string

ChoiceFor is the account the pick list is for: what WithChoiceFor recorded, else the viewer.

func ChoiceViewerIsDirector

func ChoiceViewerIsDirector(ctx context.Context) bool

ChoiceViewerIsDirector reports what WithChoiceViewer recorded; a context without it is treated as a player's, so sources fail closed.

func ChoiceViewerUser

func ChoiceViewerUser(ctx context.Context) string

ChoiceViewerUser reports what WithChoiceViewerUser recorded, "" when none.

func ComposeBatch

func ComposeBatch(in ComposeInput) string

ComposeBatch turns a pick into the batch request text ParseBatch reads. A blank left empty becomes the placeholder the review step already asks about, so nothing is guessed. Ticking a large check is the full-dump opt-in.

func DescribeStandardChange

func DescribeStandardChange(was, now StandardSnapshot) string

DescribeStandardChange says what changed between the snapshot of a standard entry and the entry today, in one short line such as "Grounded reworded; Iron Gut added; speed 5 → 6." Empty when nothing did.

func DiagnosticCheckTitle

func DiagnosticCheckTitle(name string) string

DiagnosticCheckTitle returns the plain title of a catalog check, or "".

func Dir

func Dir(id string) string

Dir returns the absolute directory path for a system by ID, or empty string if not found. Used to serve system widget JS files from the filesystem.

func EntitySlotIsAmbiguous

func EntitySlotIsAmbiguous(name, arg string) bool

EntitySlotIsAmbiguous reports whether an entity-targeted call left its entity ref as a placeholder or empty — the review step should offer an entity field.

func EntryEditorURL

func EntryEditorURL(campaignID, fieldKey string, entryID int64, back string) string

EntryEditorURL opens the entry editor straight on one campaign entry; back is the page the editor returns to when it closes.

func EntryURL

func EntryURL(campaignID, systemID, category, slug string, printed bool) string

EntryURL is an entry's own address; printed adds the printed original's mark.

func ForceLoadDir

func ForceLoadDir(dir string) error

ForceLoadDir loads the system at dir and replaces any loaded copy of the same system ID regardless of version comparison. Called by the app layer after a package install so the loader serves exactly what the admin installed — including deliberate rollbacks to an older version, which the regular rescan ("highest version wins") would silently ignore.

func FunctionsSpecJSON

func FunctionsSpecJSON() string

FunctionsSpecJSON returns the indented functions list the operator copies and feeds to the AI. Stable, pretty-printed (it's read by a human and a model).

func HasBook

func HasBook(sysDir string) bool

HasBook reports whether the system in sysDir ships a book.

func HiddenDetails

func HiddenDetails(p map[string]any) map[string]bool

HiddenDetails is the set of detail names p keeps from players.

func HiddenPartsOf

func HiddenPartsOf(ch BookChapterEntry) int

HiddenPartsOf counts the Director-only pages and blocks of a chapter as the editor holds it, so a replacement that drops them can say so.

func HouseChapterYAML

func HouseChapterYAML(ch BookChapterEntry, director bool, playerChapters map[string]bool) (out []byte, hidden int, err error)

HouseChapterYAML writes a house chapter in the draft format, so an AI can change it and send it back whole. With director false it is the player's view: Director-only pages and blocks are left out (and counted in hidden), a creature keeps only what players see, and a link keeps only chapters in playerChapters (the ids players can open), as the reader trims them.

func Init

func Init(modulesDir string) error

Init initializes the system registry by scanning the given directory for module subdirectories containing manifest.json files. Must be called once at application startup before any Registry()/Find() calls.

func KindPhrase

func KindPhrase(fieldKey string) string

KindPhrase is how a line names one of a kind: "a people" for ancestries, otherwise the field's own word ("a kit", "a culture").

func LoadAdditionalDir

func LoadAdditionalDir(dir string) error

LoadAdditionalDir scans an additional directory for system manifest.json files. This is used by the package manager to load systems from external repos installed to media/packages/systems/<slug>/<version>/. Systems found here override bundled systems with the same ID.

func NormalizeTermKey

func NormalizeTermKey(term string) string

NormalizeTermKey is the one rule both ends use to match a word: the term as written in {@category term|label} markup, trimmed, lowercased, runs of whitespace turned into "-". The builder applies the same rule to the markup it meets, so the two never disagree about "Save Ends" and "save-ends".

func NotInLine

func NotInLine(name, fieldKey, campaignName, sentence string) string

NotInLine is the one line a left-out entry answers with everywhere: "Polder is not a people of Therin." plus the Director's sentence.

func ParseCritDice

func ParseCritDice(s string) (count, sides int, explicit, ok bool)

ParseCritDice reads a rule's Dice. explicit says the count was written, which a "total" rule needs so it knows how big a group to sum.

func ParseDice

func ParseDice(s string) (count, size int, ok bool)

ParseDice reads NdS into its count and size.

func PlainTermText

func PlainTermText(s string) string

PlainTermText turns a glossary text into what a tooltip can print verbatim: reference markup becomes its shown words, tags and entities are dropped, and whitespace is collapsed. Nothing downstream renders it as HTML, so this is for legibility, not the safety boundary.

func PlanNeedsCampaign

func PlanNeedsCampaign(plan *BatchPlan) bool

PlanNeedsCampaign reports whether any call in the plan left its campaign slot ambiguous (so the review step should show the campaign picker).

func PlanNeedsEntity

func PlanNeedsEntity(plan *BatchPlan) bool

PlanNeedsEntity reports whether any call left its entity slot ambiguous.

func PlayerChapters

func PlayerChapters(src *BookEditorSource) map[string]bool

PlayerChapters is the set of chapter ids a player can open in the edition.

func PlayerProperties

func PlayerProperties(p map[string]any) map[string]any

PlayerProperties is p as a player may read it: without the hidden details and without the list naming them. p itself is not changed.

func RecordEvent

func RecordEvent(event LoadEvent)

RecordEvent adds a system loading event to the global event log.

func RegisterCharacterChoiceRoutes

func RegisterCharacterChoiceRoutes(e *echo.Echo, h *CharacterChoiceHandler, authSvc auth.AuthService, campaignSvc campaigns.CampaignService)

RegisterCharacterChoiceRoutes mounts the pick-list endpoint.

func RegisterChoiceOverlay

func RegisterChoiceOverlay(fn ChoiceOverlay)

RegisterChoiceOverlay sets the overlay. Call at start-up; the last call wins.

func RegisterChoiceRuleRoutes

func RegisterChoiceRuleRoutes(e *echo.Echo, h *ChoiceRuleHandler, authSvc auth.AuthService, campaignSvc campaigns.CampaignService)

RegisterChoiceRuleRoutes mounts the rules and requests API. The groups admit any member; every handler's service call refuses anyone but the owner and co-Directors, a rule a role middleware cannot express (a Scribe is a role above Player yet is not a Director).

func RegisterChoiceSource

func RegisterChoiceSource(src ChoiceSource)

RegisterChoiceSource adds a source whose entries are appended after the system package's own. Call at start-up; a failing source is logged and skipped rather than blanking the package's list.

func RegisterCustomSystemRoutes

func RegisterCustomSystemRoutes(e *echo.Echo, ch *CampaignSystemHandler, authSvc auth.AuthService, campaignSvc campaigns.CampaignService)

RegisterCustomSystemRoutes sets up campaign owner routes for uploading and managing custom game systems.

func RegisterHouseRulesRoute

func RegisterHouseRulesRoute(e *echo.Echo, h *SystemHandler, authSvc auth.AuthService, campaignSvc campaigns.CampaignService)

RegisterHouseRulesRoute mounts the campaign home's House rules block. It is campaign-scoped rather than system-scoped because the home does not know the campaign's game system; the handler reads it from the campaign's settings.

func RegisterMakeOwnCheck

func RegisterMakeOwnCheck(fn MakeOwnCheck)

RegisterMakeOwnCheck adds a check. Call at start-up.

func RegisterRoutes

func RegisterRoutes(e *echo.Echo, h *SystemHandler, addonSvc addons.AddonService, authSvc auth.AuthService, campaignSvc campaigns.CampaignService)

RegisterRoutes sets up system reference page and API routes. System routes are scoped to a campaign and gated by per-module addon checks (each module ID is an addon slug). Custom module upload/delete routes are also registered here for campaign owners.

func RegisterSystemEntryChoices

func RegisterSystemEntryChoices(svc SystemEntryService)

RegisterSystemEntryChoices plugs the campaign's entries into the character pick lists through the catalog's merge, for the viewer the pick-list handler marked on the context; an unmarked context reads as a player with no account, so a hidden entry never reaches a player.

func RegisterSystemEntryRoutes

func RegisterSystemEntryRoutes(e *echo.Echo, h *SystemEntryHandler, authSvc auth.AuthService, campaignSvc campaigns.CampaignService)

RegisterSystemEntryRoutes mounts the entry API. The group admits any member (they may read their own view of the list); writes are refused by the service unless the caller is the owner or a co-Director, or a player writing the one entry a Director let them make, rules a role middleware cannot express.

func RenderDiagnosticsHTML

func RenderDiagnosticsHTML(cat []Diagnostic) string

RenderDiagnosticsHTML builds a self-contained interactive admin page (no Templ dependency): a Run button per catalog diagnostic, an arg box for the ones that take one, a result pane, and a Copy button. It fetches the SAME endpoint with ?name=… (which returns markdown) — so the human clicks instead of typing URLs, then copies the small result to the assistant. Browsers reach this via content negotiation on the bare /admin/diagnostics path.

func RunBatch

func RunBatch(plan *BatchPlan) string

RunBatch executes the runnable calls in a (re-validated) plan and returns ONE compact, secret-redacted document: a manifest line, each result, a footer with the runnable count and byte size. Non-runnable rows are listed in the manifest (so the AI learns what was skipped and why) but contribute no payload.

It re-derives runnability from the live catalog rather than trusting the plan's flags — defense against a stale/forged plan slipping a gated call through.

func RunDiagnostic

func RunDiagnostic(cat []Diagnostic, name, arg string) (string, bool)

RunDiagnostic looks up a named diagnostic and returns its REDACTED markdown, or ("", false) if no such name. Pure dispatch — unit-tested directly.

func SetCalendarDiagProvider

func SetCalendarDiagProvider(p CalendarDiagProvider)

SetCalendarDiagProvider wires the per-campaign read window for calendar.stats.

func SetCampaignDiagProvider

func SetCampaignDiagProvider(p CampaignDiagProvider)

SetCampaignDiagProvider wires the per-campaign read window for the campaign.* diagnostics.

func SetCampaignListProvider

func SetCampaignListProvider(fn func(ctx context.Context) ([]CampaignInfo, error))

SetCampaignListProvider wires the campaigns service for the campaigns.list diagnostic (so the operator can resolve a campaign id by name).

func SetDesignKinds

func SetDesignKinds(k DesignKindChecker)

SetDesignKinds gives the loader the kind registry. App wiring calls it once the designs plugin is up; without it a package's designs are reported as not yet readable rather than trusted.

func SetEmbeddedAssetsProvider

func SetEmbeddedAssetsProvider(fn func() []EmbeddedAssetSet)

SetEmbeddedAssetsProvider wires the app's plugin registry into the embedded asset diagnostics. Called once at startup from the app wiring.

func SetEntityDiagProvider

func SetEntityDiagProvider(p EntityDiagProvider)

SetEntityDiagProvider wires the entities read window for the entity.* diagnostics.

func SetHostPluginsProvider

func SetHostPluginsProvider(fn func() []HostPlugin)

SetHostPluginsProvider wires the app's plugin registries into host.plugins. Called once at startup from the app wiring.

func SetInstalledPackagesProvider

func SetInstalledPackagesProvider(fn func() []InstalledPackage)

SetInstalledPackagesProvider wires the packages plugin's installed-system list so the cross-layer diagnostics can compare DB state to the live loader. Called once at startup from the app wiring.

func SetRecentErrorsProvider

func SetRecentErrorsProvider(fn func(limit int) RecentErrors)

SetRecentErrorsProvider wires the process error ring into the diagnostics. Called once at startup from the app wiring. limit <= 0 must return every held entry (host.errors-summary groups over the whole ring).

func SetSyncInboundProvider

func SetSyncInboundProvider(fn func(entityID string, limit int) []InboundSyncRecord)

SetSyncInboundProvider wires the syncapi inbound-payload buffer for sync.inbound.

func SetSyncMappingProvider

func SetSyncMappingProvider(fn func(ctx context.Context, campaignID, entityID string) ([]SyncMappingInfo, error))

SetSyncMappingProvider wires the sync-mapping reader for entity.sync-mappings.

func UnloadPackageDirsUnder

func UnloadPackageDirsUnder(root string) []string

UnloadPackageDirsUnder drops every package-loaded system whose folder is root or inside it, so a removed package stops being served at once rather than at the next restart. It returns the ids it dropped.

func ValidChoiceFieldKey

func ValidChoiceFieldKey(key string) bool

ValidChoiceFieldKey reports whether key is a plain identifier.

func ValidateEntryProperties

func ValidateEntryProperties(p map[string]any) error

ValidateEntryProperties checks details for a new entry (AI import's review step). Nothing is carried.

func ValidateEntryPropertiesOnto

func ValidateEntryPropertiesOnto(p, stored map[string]any) error

ValidateEntryPropertiesOnto checks details that will replace stored ones, letting values the validator does not understand through only when they are unchanged from stored (AI import's update review).

func ValidateManifest

func ValidateManifest(m *SystemManifest) error

ValidateManifest checks that a manifest has all required fields and valid values. Returns a descriptive error for the first violation found.

func WithCampaign

func WithCampaign(name, arg, campaignID string) string

WithCampaign returns arg with its campaign slot replaced by campaignID (no-op for non-campaign-scoped diagnostics).

func WithChoiceFor

func WithChoiceFor(ctx context.Context, userID string) context.Context

WithChoiceFor records the account the pick list is for. Rules about a player apply to this account; without it they apply to the viewer.

func WithChoiceUnlimited

func WithChoiceUnlimited(ctx context.Context) context.Context

WithChoiceUnlimited reads the pick list without the campaign's rules.

func WithChoiceViewer

func WithChoiceViewer(ctx context.Context, isDirector bool) context.Context

WithChoiceViewer records whether the pick list is being read by a Director.

func WithChoiceViewerUser

func WithChoiceViewerUser(ctx context.Context, userID string) context.Context

WithChoiceViewerUser records which account is reading the pick list.

func WithChoiceVisitor

func WithChoiceVisitor(ctx context.Context) context.Context

WithChoiceVisitor reads the pick list as a look-around visitor does.

func WithEntity

func WithEntity(name, arg, entityRef string) string

WithEntity returns arg with its entity slot replaced by entityRef, preserving the campaign part.

Types

type AddonFact

type AddonFact struct {
	Slug      string
	Name      string
	Status    string
	Enabled   bool
	Installed bool
}

AddonFact is one row of `campaign_addons` joined to `addons`.

type AddonInfo

type AddonInfo struct {
	Slug        string
	Name        string
	Description string
	Version     string
	Icon        string
	Author      string
}

AddonInfo contains the metadata needed to register a discovered system as an addon in the addons database. This bridges the systems registry with the addons plugin so new systems are auto-registered without hardcoding addon definitions.

func AddonInfos

func AddonInfos() []AddonInfo

AddonInfos returns addon registration metadata for all discovered systems with status "available". Called during app wiring to auto-register systems as addons — no hardcoded addon definitions needed.

type AllowOutcome

type AllowOutcome struct {
	// HeroUpdated is false when the hero page is gone or no longer the
	// player's; the player can then pick the entry themselves.
	HeroUpdated bool `json:"heroUpdated"`
}

AllowOutcome says what allowing a request did.

type ArgKind

type ArgKind string

ArgKind says which blank a check needs filled before it can run.

const (
	ArgNone         ArgKind = ""              // no argument
	ArgCampaign     ArgKind = "campaign"      // a campaign id
	ArgCampaignPage ArgKind = "campaign-page" // campaign id + a page's name, slug or id
	ArgCampaignText ArgKind = "campaign-text" // campaign id + free text (a name to find, a category)
	ArgText         ArgKind = "text"          // free text in the check's own arg shape
)

type AskCounter

type AskCounter interface {
	WaitingRequests(ctx context.Context, campaignID string, actor EntryActor) ([]WaitingChoiceRequest, error)
}

AskCounter lists the Ask-first picks waiting on a Director.

type BatchCall

type BatchCall struct {
	Name string `json:"name"`
	Arg  string `json:"arg,omitempty"`
}

BatchCall is one diagnostic invocation in a batch request.

type BatchPlan

type BatchPlan struct {
	Request   BatchRequest
	Calls     []PlannedCall
	RunnableN int // count of Status==PlanOK (how many will actually run)
}

BatchPlan is the validated, reviewable result of parsing a pasted request.

func ParseBatch

func ParseBatch(raw string) (*BatchPlan, error)

ParseBatch parses a pasted batch-request string and validates every call against the catalog, returning a reviewable plan. It returns an error only for a structurally invalid request (bad JSON, no calls, too many calls) — unknown or gated call NAMES are not errors; they surface as non-OK plan rows so the operator sees the whole picture before approving.

type BatchRequest

type BatchRequest struct {
	V        int         `json:"v"`
	Note     string      `json:"note,omitempty"`
	FullDump bool        `json:"full_dump,omitempty"`
	Calls    []BatchCall `json:"calls"`
}

BatchRequest is the single pastable object the AI composes. `FullDump` is the explicit authorization gate for heavy diagnostics; `Note` is free text the AI uses to record what it is investigating (echoed into the result for audit).

type BeforeView

type BeforeView struct {
	CampaignID   string
	CampaignName string
	SystemID     string
	SystemName   string
	URL          string
	// Runs holds only the runs that have rows.
	Runs       []beforeRun
	IsDirector bool
	// For the Director: kinds a new entry can be, old names, and the editor's
	// page with how many players' drafts wait there.
	NewKinds  []kindLink
	OldNames  []oldNameRow
	DraftsURL string
	Waiting   int
	APIBase   string
}

BeforeView is the gathered page as one reader has it.

func (*BeforeView) Empty

func (v *BeforeView) Empty() bool

Empty reports whether no run has a row.

type Book

type Book struct {
	Title      string            `json:"title"`
	Mark       string            `json:"mark,omitempty"`
	SystemName string            `json:"systemName"`
	Turn       string            `json:"turn"`
	Theme      map[string]string `json:"theme,omitempty"`
	// Look "paper" draws the book as a printed handbook and "bold" as a
	// poster-styled one; "" is the default.
	Look string `json:"look,omitempty"`
	// Cover is the drawn cover art and Fonts the package's own faces. After
	// loading they hold package-relative paths; WithAssetBase turns them into
	// the URLs the browser fetches.
	Cover string     `json:"cover,omitempty"`
	Fonts []BookFont `json:"fonts,omitempty"`
	// Tabs are the chapter ids given an edge tab. Start is the chapter the
	// book opens on, and First the one it opens on for a first-time reader.
	// Screen is the chapter the reader drops over any page as a quick
	// reference instead of showing it as pages of the book.
	Tabs       []string            `json:"tabs,omitempty"`
	Start      string              `json:"start,omitempty"`
	First      string              `json:"first,omitempty"`
	Screen     string              `json:"screen,omitempty"`
	IsDirector bool                `json:"isDirector"`
	CanEdit    bool                `json:"canEdit"`
	Terms      map[string]BookTerm `json:"terms"`
	Parts      []BookPart          `json:"parts"`
}

Book is the wire shape of a system's rulebook book (camelCase JSON).

func ApplyBookEdits

func ApplyBookEdits(pkg *BookPackage, edits *BookEdits) *Book

ApplyBookEdits merges a campaign's edits over the package book. It does not filter: callers run FilterBook on the result.

func FilterBook

func FilterBook(b *Book, director bool) *Book

FilterBook returns the copy of b a viewer may receive. Directors get everything. Players never receive Director-only parts, chapters, pages, blocks, creature numbers or notes, nor broken chapters: this is the only place that decision is made, so the browser never holds what it must not show.

func HouseChapterPreview

func HouseChapterPreview(pkg *BookPackage, title, intro string, director bool, d *HouseChapterDraft) *Book

HouseChapterPreview is a one-chapter Book of the draft, in the package's own theme, for a Director to read before it is written: the same shape GET /book returns, so the reader draws it with its usual look and motion. Nil when the draft carries no pages.

func LoadBook

func LoadBook(sysDir string, manifest *SystemManifest) (*Book, error)

LoadBook reads and checks the book in sysDir. An error means the cover file (book.yaml) itself is unusable. A broken chapter does not fail the book: it becomes a chapter holding one "problem" block naming the mistake, so the rest of the book keeps working. The manifest's widget slugs are the only ones a "widget" block may mount.

func (*Book) WithAssetBase

func (b *Book) WithAssetBase(base string) *Book

WithAssetBase returns a copy of the book whose cover and font paths are URLs under base (the book's asset route, no trailing slash). The shared Fonts slice is copied so a cached book is never rewritten in place.

type BookBand

type BookBand struct {
	Max   *int   `json:"max"`
	Label string `json:"label"`
	Text  string `json:"text,omitempty"`
}

BookBand is one result band of a roll; Max is nil on the last band.

type BookBlock

type BookBlock struct {
	Type        string     `json:"type"`
	Director    bool       `json:"director"`
	Title       string     `json:"title,omitempty"`
	Text        string     `json:"text,omitempty"`
	Label       string     `json:"label,omitempty"`
	Dice        *BookDice  `json:"dice,omitempty"`
	Modifier    bool       `json:"modifier,omitempty"`
	Bands       []BookBand `json:"bands,omitempty"`
	Items       []BookItem `json:"items,omitempty"`
	Steps       []string   `json:"steps,omitempty"`
	Name        string     `json:"name,omitempty"`
	Tagline     string     `json:"tagline,omitempty"`
	Look        string     `json:"look,omitempty"`
	Notice      []string   `json:"notice,omitempty"`
	Stats       []BookStat `json:"stats,omitempty"`
	Note        string     `json:"note,omitempty"`
	HiddenStats bool       `json:"hiddenStats,omitempty"`
	Widget      string     `json:"widget,omitempty"`
	// An "index" block (generated pages only) lists the entries of a data
	// category: those whose Key property equals Value, From..To in name order.
	Category string `json:"category,omitempty"`
	Key      string `json:"key,omitempty"`
	Value    string `json:"value,omitempty"`
	From     int    `json:"from,omitempty"`
	To       int    `json:"to,omitempty"`
	Count    int    `json:"count,omitempty"`
	// List is how an index page lays its entries out: the choices it offers
	// and the properties it heads and draws specially.
	List *BookIndexList `json:"list,omitempty"`
}

BookBlock is one block on a page. Only the fields of its Type are set.

type BookChapter

type BookChapter struct {
	ID       string `json:"id"`
	Title    string `json:"title"`
	Intro    string `json:"intro,omitempty"`
	Director bool   `json:"director"`
	// Generated chapters are made from the system's reference data (a rules
	// index); they are not edited in the campaign's book editor.
	Generated bool       `json:"generated,omitempty"`
	Pages     []BookPage `json:"pages"`
}

BookChapter is one chapter file.

type BookChapterEntry

type BookChapterEntry struct {
	ID        string          `json:"id"`
	Title     string          `json:"title"`
	Intro     string          `json:"intro"`
	Director  bool            `json:"director"`
	House     bool            `json:"house"`
	Generated bool            `json:"generated,omitempty"`
	Problem   string          `json:"problem,omitempty"`
	Pages     []BookPageEntry `json:"pages"`
}

BookChapterEntry is one chapter as the editor sees it. A package chapter that failed to load carries Problem and no pages: it cannot be edited. A rules-index chapter carries Generated and no pages: it is made from the system's data, so it changes with the package, not here.

type BookDice

type BookDice struct {
	Count int `json:"count"`
	Sides int `json:"sides"`
}

BookDice is a parsed dice expression such as 2d10.

type BookEditRepository

type BookEditRepository interface {
	// Load returns everything the campaign has changed for the system.
	Load(ctx context.Context, campaignID, systemID string) (*BookEdits, error)

	// SaveCopy creates or replaces the campaign's copy of a package page.
	SaveCopy(ctx context.Context, p StoredBookPage) error
	// AddOwn appends a page the campaign adds and returns its row id.
	AddOwn(ctx context.Context, p StoredBookPage) (int64, error)
	// UpdateOwn replaces the content of a page the campaign added.
	UpdateOwn(ctx context.Context, campaignID, systemID, chapterID string, id int64, pageJSON, userID string) error
	// DeleteCopy drops the copy of a package page; false when there was none.
	DeleteCopy(ctx context.Context, campaignID, systemID, chapterID string, index int) (bool, error)
	// DeleteOwn deletes a page the campaign added; false when there was none.
	DeleteOwn(ctx context.Context, campaignID, systemID, chapterID string, id int64) (bool, error)
	// PromoteCopy turns a copy whose package page is gone into a page the
	// campaign owns, at the end of the chapter, and returns its new row id.
	PromoteCopy(ctx context.Context, campaignID, systemID, chapterID string, index int) (int64, error)
	// AddChapter stores a new house chapter together with its first page, so
	// a chapter is never left without one.
	AddChapter(ctx context.Context, ch HouseChapter, firstPage StoredBookPage) error
	UpdateChapter(ctx context.Context, ch HouseChapter) error
	// DeleteChapter removes a house chapter and its pages; false when absent.
	DeleteChapter(ctx context.Context, campaignID, systemID, chapterID string) (bool, error)
	// WriteHouseChapter stores a house chapter's row (a new one when create)
	// and, when pages is not nil, replaces all its pages with them, in order,
	// in one transaction.
	WriteHouseChapter(ctx context.Context, ch HouseChapter, create bool, pages []StoredBookPage) error
}

BookEditRepository is the data access contract for a campaign's edits to a system's book. All SQL lives in the implementation. Every method is scoped by campaign and system, so one campaign can never read or write another's rows by guessing an id.

func NewBookEditRepository

func NewBookEditRepository(db *sql.DB) BookEditRepository

NewBookEditRepository creates the MariaDB-backed repository.

type BookEditService

type BookEditService interface {
	// Edition is the book a campaign reads: the package book with its edits
	// merged in, before the per-viewer filter.
	Edition(ctx context.Context, campaignID string, pkg *BookPackage) (*Book, error)
	EditorSource(ctx context.Context, campaignID string, pkg *BookPackage) (*BookEditorSource, error)

	SavePage(ctx context.Context, campaignID, userID string, pkg *BookPackage, chapterID, key string, rawPage []byte) (*BookPageEntry, error)
	AddPage(ctx context.Context, campaignID, userID string, pkg *BookPackage, chapterID string, rawPage []byte) (*BookPageEntry, error)
	// DeletePage drops a copy (the package page returns) or deletes an own
	// page. The entry is nil when no page is left at that key.
	DeletePage(ctx context.Context, campaignID string, pkg *BookPackage, chapterID, key string) (*BookPageEntry, error)
	KeepPage(ctx context.Context, campaignID, userID string, pkg *BookPackage, chapterID, key string) (*BookPageEntry, error)

	CreateChapter(ctx context.Context, campaignID, userID string, pkg *BookPackage, title string) (*BookChapterEntry, error)
	UpdateChapter(ctx context.Context, campaignID string, pkg *BookPackage, chapterID string, in UpdateBookChapterInput) (*BookChapterEntry, error)
	DeleteChapter(ctx context.Context, campaignID string, pkg *BookPackage, chapterID string) error
	// WriteHouseChapter writes a whole house-rules chapter from a draft (see
	// book_house_draft.go): a new one when chapterID is "".
	WriteHouseChapter(ctx context.Context, campaignID, userID string, pkg *BookPackage, chapterID, title string, d *HouseChapterDraft) (*BookChapterEntry, error)

	// Export returns the campaign's edition as a zip of package-format files.
	Export(ctx context.Context, campaignID string, pkg *BookPackage) ([]byte, error)
}

BookEditService owns everything about a campaign's edits to a system's book: merging them over the package book, validating what a Director sends, and the limits. It never sees a request, so who may edit is the handler's decision, made before any method here is reached.

func NewBookEditService

func NewBookEditService(repo BookEditRepository) BookEditService

NewBookEditService creates the service over a repository.

type BookEditorPart

type BookEditorPart struct {
	Title    string             `json:"title"`
	Director bool               `json:"director"`
	House    bool               `json:"house"`
	Chapters []BookChapterEntry `json:"chapters"`
}

BookEditorPart groups chapters like BookPart does for readers.

type BookEditorSource

type BookEditorSource struct {
	Title      string              `json:"title"`
	Mark       string              `json:"mark,omitempty"`
	SystemName string              `json:"systemName"`
	Theme      map[string]string   `json:"theme,omitempty"`
	Turn       string              `json:"turn"`
	Terms      map[string]BookTerm `json:"terms"`
	Widgets    []string            `json:"widgets"`
	ExportURL  string              `json:"exportUrl"`
	Parts      []BookEditorPart    `json:"parts"`
}

BookEditorSource is the editor's whole starting state (GET /book/source).

type BookEdits

type BookEdits struct {
	Chapters []HouseChapter
	Pages    []StoredBookPage
}

BookEdits is everything a campaign has changed for one system's book.

type BookFindResult

type BookFindResult struct {
	Chapter string `json:"chapter"`
	Page    int    `json:"page"`
	ID      string `json:"id"`
	Name    string `json:"name"`
	Summary string `json:"summary,omitempty"`
	Where   string `json:"where"`
}

BookFindResult is one rules-index entry a search found, with the chapter and page that show it.

type BookFont

type BookFont struct {
	Family string `json:"family"`
	URL    string `json:"url"`
	Weight int    `json:"weight,omitempty"`
	Style  string `json:"style,omitempty"`
}

BookFont is one font face the package ships. URL is a package-relative path until WithAssetBase resolves it.

type BookIndexEntry

type BookIndexEntry struct {
	ID      string     `json:"id"`
	Name    string     `json:"name"`
	Summary string     `json:"summary,omitempty"`
	Text    string     `json:"text,omitempty"`
	Fields  []BookStat `json:"fields,omitempty"`
	// Facets are the entry's values for its page's filters and sections.
	Facets []BookIndexFacet `json:"facets,omitempty"`
}

BookIndexEntry is one entry as a generated page lists it. Text and field values use the book's own markup, so rule words become hover terms.

type BookIndexFacet

type BookIndexFacet struct {
	Key    string   `json:"key"`
	Values []string `json:"values"`
}

BookIndexFacet is one entry's values for one filter.

type BookIndexFilter

type BookIndexFilter struct {
	Key   string `json:"key"`
	Label string `json:"label"`
}

BookIndexFilter is one property a reader can narrow an index page by.

type BookIndexList

type BookIndexList struct {
	Filters  []BookIndexFilter `json:"filters,omitempty"`
	Sections string            `json:"sections,omitempty"`
	// SectionLabel names the sections ("Level" makes "Level 2").
	SectionLabel string   `json:"sectionLabel,omitempty"`
	Tiers        []string `json:"tiers,omitempty"`
}

BookIndexList is the reader's layout for an index page.

type BookItem

type BookItem struct {
	Title   string `json:"title"`
	Summary string `json:"summary,omitempty"`
	Text    string `json:"text,omitempty"`
	Chapter string `json:"chapter,omitempty"`
	// Entry ties a card to the rules entry it describes ("ancestries/human"),
	// so each reader's book shows that entry as the campaign has it for them
	// (book_reading.go). Never matched by name.
	Entry string `json:"entry,omitempty"`
}

BookItem is a card, a flap or a link. A link's Chapter is the chapter id it turns to.

type BookKindList

type BookKindList func(category string) (*CatalogList, error)

BookKindList is the reader's catalog of a category when it is a kind of the campaign's own system, else nil: that category reads as the package.

type BookPackage

type BookPackage struct {
	SystemID   string
	SystemName string
	Book       *Book
	Source     *BookSource
	Widgets    map[string]bool
}

BookPackage is the loaded package book the merge starts from. The handler builds it from the system's folder so the service never touches the disk.

func LoadBookPackage

func LoadBookPackage(sysDir string, manifest *SystemManifest) (*BookPackage, error)

LoadBookPackage reads the package book with its authored source and the widget slugs its pages may mount.

type BookPage

type BookPage struct {
	Title    string      `json:"title,omitempty"`
	Director bool        `json:"director"`
	Wide     bool        `json:"wide"`
	Columns  bool        `json:"columns,omitempty"`
	Blocks   []BookBlock `json:"blocks"`
}

BookPage is one page of a chapter; Wide spans the whole spread and Columns flows its blocks into two columns.

type BookPageEntry

type BookPageEntry struct {
	Key     string        `json:"key"`
	State   string        `json:"state"`
	Page    authoredPage  `json:"page"`
	Theirs  *authoredPage `json:"theirs"`
	Problem string        `json:"problem,omitempty"`
}

BookPageEntry is one page as the editor sees it.

type BookPart

type BookPart struct {
	Title    string        `json:"title"`
	Director bool          `json:"director"`
	Chapters []BookChapter `json:"chapters"`
}

BookPart groups chapters ("Player's book", "Director's book").

type BookSource

type BookSource struct {
	// contains filtered or unexported fields
}

BookSource is the authored form of the package book that loaded: the cover file and, per chapter that loaded cleanly, its pages as written. Campaign edits are hashed against it, compared with it and exported from it, which the built Book cannot serve (it has lost the authored shape).

type BookStat

type BookStat struct {
	Label string `json:"label"`
	Value string `json:"value"`
	// Key is the data property a rules-index field came from, so the reader
	// can leave out a field it already shows as a choice or a tier.
	Key string `json:"key,omitempty"`
}

BookStat is one creature number.

type BookTerm

type BookTerm struct {
	Name string `json:"name"`
	Text string `json:"text"`
}

BookTerm is one hover definition.

type BrokenHero

type BrokenHero struct {
	HeroID     string `json:"heroId"`
	HeroName   string `json:"heroName"`
	PlayerID   string `json:"playerId"`
	PlayerName string `json:"playerName"`
	HeroBreak
}

BrokenHero is a hero that holds an entry a rule keeps off their player's list.

type CalendarDiagProvider

type CalendarDiagProvider interface {
	CalendarStats(ctx context.Context, campaignID string) (CalendarStatsFacts, error)
}

CalendarDiagProvider is the injected read-only window into per-campaign calendar state. Implemented by the app layer (dependency inversion — systems must not import the calendar/campaigns/addons plugins), wired once at startup by SetCalendarDiagProvider.

type CalendarStatsFacts

type CalendarStatsFacts struct {
	Found        bool
	CampaignID   string
	CampaignName string

	AddonEnabled *bool
	AddonNote    string

	CalendarCount  int
	EventCount     int
	MoonCount      int
	EraCount       int
	EventKindCount int

	// PluginHealthy/MigrationVersion/MigrationLatest report the calendar
	// plugin's OWN schema migration state — the same registry host.plugins
	// reads — distinct from whether the addon is enabled for this campaign:
	// a healthy plugin with the addon disabled and a campaign with the
	// addon enabled but an unhealthy plugin are different findings.
	PluginHealthy    bool
	MigrationVersion int
	MigrationLatest  int

	// FoundrySyncState is a fact of the current build, not a live probe: which
	// of the sync API's calendar routes serve the V5 calendar. See
	// internal/plugins/syncapi/calendar_api_handler.go.
	FoundrySyncState string

	Notes []string
}

CalendarStatsFacts is what `calendar.stats` reads.

type CampaignConfigFacts

type CampaignConfigFacts struct {
	Found        bool
	CampaignID   string
	CampaignName string

	Addons     []AddonFact
	AddonsNote string

	Layouts     []LayoutFact
	LayoutsNote string

	// DefaultDashboardBlocks is DefaultDashboardLayout()'s own block types,
	// printed so "not in any default" is a comparison the reader can see rather
	// than a claim they have to take on trust.
	DefaultDashboardBlocks []string

	Notes []string
}

CampaignConfigFacts is what `campaign.config` reads.

type CampaignDiagProvider

type CampaignDiagProvider interface {
	SurfaceFacts(ctx context.Context, campaignID string) (CampaignSurfaceFacts, error)
	ConfigFacts(ctx context.Context, campaignID string) (CampaignConfigFacts, error)
}

CampaignDiagProvider is the injected read-only window into per-campaign state. Implemented by the app layer (dependency inversion — systems must not import the campaigns / addons / entities plugins), wired once at startup by SetCampaignDiagProvider, exactly as SetInstalledPackagesProvider does.

type CampaignInfo

type CampaignInfo struct {
	ID   string
	Name string
	Slug string
}

CampaignInfo is one campaign for the campaigns.list discovery diagnostic.

type CampaignSurfaceFacts

type CampaignSurfaceFacts struct {
	Found        bool
	CampaignID   string
	CampaignName string

	Routes     []RouteFact
	RoutesNote string

	CalendarAddonEnabled *bool
	AddonNote            string

	// SidebarCalendarPath is the path the sidebar's Calendar item links to,
	// read from the SAME map the sidebar renders from (layouts' addon URL map)
	// rather than re-typed here.
	SidebarCalendarPath string
	SidebarItems        []SidebarItemFact
	SidebarNote         string

	Notes []string
}

CampaignSurfaceFacts is what `campaign.surfaces` reads.

type CampaignSystemHandler

type CampaignSystemHandler struct {
	// contains filtered or unexported fields
}

CampaignSystemHandler handles upload and management of per-campaign custom game systems. Only campaign owners can upload/remove.

func NewCampaignSystemHandler

func NewCampaignSystemHandler(mgr *CampaignSystemManager) *CampaignSystemHandler

NewCampaignSystemHandler creates a handler for custom system endpoints.

func (*CampaignSystemHandler) DeleteSystem

func (h *CampaignSystemHandler) DeleteSystem(c *echo.Context) error

DeleteSystem handles DELETE /campaigns/:id/systems/custom. Removes the campaign's custom game system from disk and memory.

func (*CampaignSystemHandler) GetCustomSystem

func (h *CampaignSystemHandler) GetCustomSystem(c *echo.Context) error

GetCustomSystem handles GET /campaigns/:id/systems/custom. Returns an HTMX fragment showing the custom system status with upload or manage controls.

func (*CampaignSystemHandler) PreviewSystem

func (h *CampaignSystemHandler) PreviewSystem(c *echo.Context) error

PreviewSystem handles POST /campaigns/:id/systems/preview. Accepts a ZIP file, validates it without writing to disk, and returns a full preview of what the system contains (impact tree, categories, entity presets, warnings). The owner can then confirm installation.

func (*CampaignSystemHandler) SetEntityDeps

func (h *CampaignSystemHandler) SetEntityDeps(counter EntityCountProvider, typeLister EntityTypeProvider)

SetEntityDeps wires entity data providers for the diagnostics page.

func (*CampaignSystemHandler) SetUploadPolicy

func (h *CampaignSystemHandler) SetUploadPolicy(provider UploadPolicyProvider)

SetUploadPolicy wires the upload policy provider so the handler can check whether campaign owners are allowed to upload custom systems.

func (*CampaignSystemHandler) SystemStatus

func (h *CampaignSystemHandler) SystemStatus(c *echo.Context) error

SystemStatus handles GET /campaigns/:id/systems/status. Shows a diagnostics page for the currently enabled game system: manifest details, category item counts, entity presets, Foundry compatibility, and validation warnings.

func (*CampaignSystemHandler) UploadSystem

func (h *CampaignSystemHandler) UploadSystem(c *echo.Context) error

UploadSystem handles POST /campaigns/:id/systems/upload. Accepts a ZIP file containing manifest.json + data/*.json, validates it, and installs it as the campaign's custom game system.

type CampaignSystemManager

type CampaignSystemManager struct {
	// contains filtered or unexported fields
}

CampaignSystemManager manages custom game systems uploaded by campaign owners. Each campaign can have at most one custom system. Modules are stored on disk and loaded into memory as GenericSystem instances.

func NewCampaignSystemManager

func NewCampaignSystemManager(baseDir string) *CampaignSystemManager

NewCampaignSystemManager creates a manager that stores custom systems under baseDir/<campaignID>/. Discovers and loads any existing modules.

func (*CampaignSystemManager) Dir

func (m *CampaignSystemManager) Dir(campaignID string) string

Dir returns the absolute directory path for a campaign's custom system, or empty string if no custom system is installed.

func (*CampaignSystemManager) GetManifest

func (m *CampaignSystemManager) GetManifest(campaignID string) *SystemManifest

GetManifest returns the custom system manifest for a campaign, or nil.

func (*CampaignSystemManager) GetSystem

func (m *CampaignSystemManager) GetSystem(campaignID string) System

GetSystem returns the custom system for a campaign, or nil if none.

func (*CampaignSystemManager) Install

func (m *CampaignSystemManager) Install(campaignID string, zipData io.ReaderAt, zipSize int64) (*SystemManifest, error)

Install extracts a ZIP file containing a custom game system, validates it, stores it on disk, and loads it into memory. Returns the parsed manifest on success.

func (*CampaignSystemManager) Uninstall

func (m *CampaignSystemManager) Uninstall(campaignID string) error

Uninstall removes a campaign's custom game system from disk and memory.

type CardLookChange

type CardLookChange struct {
	FieldKey string
	Source   string
	Key      string
	Border   string
	Colour   string
	Reset    bool
}

CardLookChange is one owner's choice for one card, the unit of the Customizer's herolooks section. Source is ChoiceSourcePackage or ChoiceSourceCampaign; Key is Choice.Key. Reset (package entries only) drops the choice so the game system's own look applies again.

type CardLookEntries

type CardLookEntries interface {
	SetCardLook(ctx context.Context, campaignID string, actor EntryActor, id int64, border, colour string) (*SystemEntry, error)
}

CardLookEntries is the slice of the entry service the owner's choice for a campaign's own entry goes through, so the normal validation runs on it.

type CardLookReader

type CardLookReader interface {
	// CardLooks returns the stored looks of a field keyed by entry key.
	CardLooks(ctx context.Context, campaignID, systemID, fieldKey string) (map[string]StoredLook, error)
}

CardLookReader is what the pick list reads: the owner's looks for one field.

type CardLookRepository

type CardLookRepository interface {
	// List returns the rows of one field, keyed by entry key.
	List(ctx context.Context, campaignID, systemID, fieldKey string) (map[string]StoredLook, error)
	// Apply writes a batch in one transaction: upserts replace the row for the
	// same (field, entry), deletes remove it. A batch is all or nothing so an
	// owner's save never half-lands.
	Apply(ctx context.Context, upserts []CardLookRow, deletes []CardLookRow) error
	// DeleteDerived removes the rows of the derived entries (<slug>--...) of
	// one parent slug, in every field of the system; it returns how many went.
	DeleteDerived(ctx context.Context, campaignID, systemID, parentSlug string) (int, error)
}

CardLookRepository is the data access contract for the looks an owner gave package entries. Every method is scoped by campaign.

func NewCardLookRepository

func NewCardLookRepository(db *sql.DB) CardLookRepository

NewCardLookRepository creates the MariaDB-backed repository.

type CardLookRow

type CardLookRow struct {
	CampaignID string
	SystemID   string
	FieldKey   string
	EntryKey   string
	StoredLook
	UpdatedBy string
	UpdatedAt time.Time
}

CardLookRow is a full row, for the repository.

type CardLookService

type CardLookService interface {
	CardLookReader
	EntryLookForgetter
	// SetEntries plugs in the entry service. It is set after construction
	// because that service in turn takes this one as its forgetter.
	SetEntries(e CardLookEntries)
	// Apply checks every change, then writes them. An item whose card is no
	// longer on the field's list is dropped (a stale draft), not an error.
	// Who may change a campaign's card borders is the caller's to check: Apply
	// writes campaign entries as a Director.
	Apply(ctx context.Context, campaignID, userID string, changes []CardLookChange) error
}

CardLookService keeps an owner's choice of card borders. It checks a whole batch before writing anything, so a bad item never leaves the rest half applied.

func NewCardLookService

func NewCardLookService(repo CardLookRepository, choices CharacterChoiceService) CardLookService

NewCardLookService wires the service. choices is read as a Director sees the list, rules aside, to find which cards exist.

type CatalogEntry

type CatalogEntry struct {
	Category string `json:"category"`
	// FieldKey is the character field of a kind; "" for other categories.
	FieldKey string `json:"fieldKey,omitempty"`
	// Slug is the entry's address under the category.
	Slug string `json:"slug"`
	// Printed marks a standard entry whose plain address a campaign entry of
	// the same slug holds; its own address carries ?printed=1.
	Printed     bool           `json:"printed,omitempty"`
	Name        string         `json:"name"`
	Summary     string         `json:"summary"`
	Description string         `json:"description,omitempty"`
	Properties  map[string]any `json:"properties,omitempty"`
	Tags        []string       `json:"tags,omitempty"`
	// Origin is OriginCampaign, OriginRewritten or OriginStandard.
	Origin string `json:"origin"`
	// Credit is the system's name on a standard entry ("Draw Steel").
	Credit string `json:"credit,omitempty"`
	// StandsFor and StandsForName name the standard entry a rewritten one
	// replaces.
	StandsFor     string `json:"standsFor,omitempty"`
	StandsForName string `json:"standsForName,omitempty"`
	// DirectorsOnly is true when only Directors (and a draft's writer) see it.
	DirectorsOnly bool `json:"directorsOnly,omitempty"`
	// KeptFor names the one character an entry is kept to.
	KeptFor string `json:"keptFor,omitempty"`
	// LeftOut and Sentence describe a standard entry the campaign left out.
	LeftOut  bool   `json:"leftOut,omitempty"`
	Sentence string `json:"sentence,omitempty"`
	// EntryID is the campaign entry's id; 0 for a standard entry.
	EntryID int64 `json:"entryId,omitempty"`
	// Status is "draft" or "sent" on a player's entry not yet accepted.
	Status string `json:"status,omitempty"`
	// ToldRecently is true when the players were told about a change to this
	// entry within the last ToldWindow, so a hero's sheet can mark it.
	ToldRecently bool `json:"toldRecently,omitempty"`

	// Entry and Item are the underlying rows, for callers that render more.
	Entry *SystemEntry   `json:"-"`
	Item  *ReferenceItem `json:"-"`
}

CatalogEntry is one entry as a reader has it.

type CatalogList

type CatalogList struct {
	Category   string `json:"category"`
	FieldKey   string `json:"fieldKey,omitempty"`
	SystemName string `json:"systemName"`
	// Entries are the entries this reader has, by name.
	Entries []CatalogEntry `json:"entries"`
	// LeftOut is every left-out standard entry, for Directors only.
	LeftOut []CatalogEntry `json:"leftOut,omitempty"`
	// LeftOutNoted are the left-out entries with a sentence, which every
	// reader's list ends with.
	LeftOutNoted []CatalogEntry `json:"leftOutNoted"`
}

CatalogList is a category as one reader has it.

func (*CatalogList) Replaced

func (l *CatalogList) Replaced(slug string) bool

Replaced reports whether a standard slug is read rewritten in this list, so a caller adding left-out package content skips a slug that is both.

type CategoryDef

type CategoryDef struct {
	// Slug is the URL-safe identifier (e.g., "spells", "monsters").
	Slug string `json:"slug"`

	// Name is the human-readable display name (e.g., "Spells", "Monsters").
	Name string `json:"name"`

	// Icon is an optional Font Awesome icon class for this category.
	Icon string `json:"icon,omitempty"`

	// Fields defines the schema for Properties keys on ReferenceItems
	// in this category. Used for structured display and filtering.
	Fields []FieldDef `json:"fields,omitempty"`

	// Director keeps the category to the campaign's Directors: its reference
	// pages, search hits, tooltips and raw data/<slug>.json file. It is for
	// content the system's book keeps in a Director-only chapter, so the
	// data cannot show players what the book hides.
	Director bool `json:"director,omitempty"`
}

CategoryDef describes one category of reference content within a module.

type CategoryPreview

type CategoryPreview struct {
	Slug       string          `json:"slug"`
	Name       string          `json:"name"`
	Icon       string          `json:"icon,omitempty"`
	ItemCount  int             `json:"item_count"`
	FieldCount int             `json:"field_count"`
	Samples    []ReferenceItem `json:"samples,omitempty"` // First 3 items for preview.
}

CategoryPreview summarizes a reference data category for the preview.

type CharacterChoiceHandler

type CharacterChoiceHandler struct {
	// contains filtered or unexported fields
}

CharacterChoiceHandler serves the pick lists for character fields.

func NewCharacterChoiceHandler

func NewCharacterChoiceHandler(svc CharacterChoiceService) *CharacterChoiceHandler

NewCharacterChoiceHandler creates the handler.

func (*CharacterChoiceHandler) ChoicesAPI

func (h *CharacterChoiceHandler) ChoicesAPI(c *echo.Context) error

ChoicesAPI returns the pick list for one character field.

GET /campaigns/:id/character-choices/:fieldKey[?as=<userId>]

Players can read it, since a list of ancestries or kits is reference data they see in the system pages anyway; whether they may then write the field is the entity fields endpoint's decision.

type CharacterChoiceService

type CharacterChoiceService interface {
	// CharacterChoices returns the pick list for a character field, empty
	// when the active system has none.
	CharacterChoices(ctx context.Context, campaignID, fieldKey string) ([]Choice, error)
	// CharacterChoiceList is CharacterChoices plus the system's name.
	CharacterChoiceList(ctx context.Context, campaignID, fieldKey string) (*ChoiceList, error)
	// CreatorPlan lists every character field with entries, for the hero creator.
	CreatorPlan(ctx context.Context, campaignID string) (*CreatorPlan, error)
	// RulesTerms reads the rules words (the Rules book glossary) of the system
	// the creator builds from, for the builder's hover meanings.
	RulesTerms(ctx context.Context, campaignID string) (*RulesTerms, error)
	// SetChoiceLimiter plugs in the hero-choice rules. Every list is then
	// narrowed for the viewer after its sources are merged.
	SetChoiceLimiter(l ChoiceLimiter)
	// SetChoiceLooks plugs in the owner's card borders for package entries.
	// Every list then carries them, whoever reads it.
	SetChoiceLooks(r CardLookReader)
}

CharacterChoiceService resolves a field key to the campaign's pick list.

func NewCharacterChoiceService

func NewCharacterChoiceService(addons addonChecker, custom *CampaignSystemManager) CharacterChoiceService

NewCharacterChoiceService wires the service to the live system registry, the campaign's addon switches and its custom uploaded system (either may be nil).

type CharacterFieldExport

type CharacterFieldExport struct {
	Key               string            `json:"key"`
	Label             string            `json:"label"`
	Type              string            `json:"type"`
	FoundryPath       string            `json:"foundry_path,omitempty"`
	FoundryWritable   bool              `json:"foundry_writable"`
	FoundryChoices    string            `json:"foundry_choices,omitempty"`
	FoundryFormat     string            `json:"foundry_format,omitempty"`
	FoundryCollection string            `json:"foundry_collection,omitempty"`
	FoundryItemType   []string          `json:"foundry_item_type,omitempty"`
	FoundryItemFields map[string]string `json:"foundry_item_fields,omitempty"`
	FoundryItemSingle bool              `json:"foundry_item_single,omitempty"`
	FoundryItemJoin   bool              `json:"foundry_item_join,omitempty"`
}

CharacterFieldExport is a single field definition exported for the Foundry module's generic adapter.

type CharacterFieldsResponse

type CharacterFieldsResponse struct {
	SystemID         string `json:"system_id"`
	PresetSlug       string `json:"preset_slug"`
	PresetName       string `json:"preset_name"`
	FoundrySystemID  string `json:"foundry_system_id,omitempty"`
	FoundryActorType string `json:"foundry_actor_type,omitempty"`
	// FoundryItemType is the Foundry Item type an item preset's pages
	// become; empty for actor presets.
	FoundryItemType string `json:"foundry_item_type,omitempty"`
	// FoundryPullFields lists the only keys Foundry may send back; absent
	// means all mapped fields sync both ways.
	FoundryPullFields []string               `json:"foundry_pull_fields,omitempty"`
	Fields            []CharacterFieldExport `json:"fields"`
}

CharacterFieldsResponse is the API response shape for the character fields endpoint, containing field definitions with Foundry annotations.

type Choice

type Choice struct {
	Slug    string `json:"slug"`
	Name    string `json:"name"`
	Summary string `json:"summary"`
	Source  string `json:"source"`
	// Description and Properties are the entry's authored text and data,
	// untouched (reference markers intact), for features that show more than
	// the one-line Summary, such as a character creator. The picker ignores them.
	Description string         `json:"description,omitempty"`
	Properties  map[string]any `json:"properties,omitempty"`
	// ForName is set on a campaign entry kept to one character, so a picker
	// can say only that character's player and Directors see it.
	ForName string `json:"forName,omitempty"`
	// Status is "draft" or "sent" on a player's entry a Director has not
	// accepted yet; empty otherwise.
	Status string `json:"status,omitempty"`
	// Mine and EntryID are set for the player who wrote the entry.
	Mine    bool  `json:"mine,omitempty"`
	EntryID int64 `json:"entryId,omitempty"`
	// Key is what a hero-choice rule names the entry by: a package entry's
	// slug, a campaign entry's id (never its slug, which a deleted entry
	// hands to the next one of that name).
	Key string `json:"key,omitempty"`
	// State is ChoiceStateAskFirst on an entry the viewer may pick only with
	// a Director's yes; empty for an entry they may simply pick.
	State string `json:"state,omitempty"`
	// Visibility is a campaign entry's EntryVisibility*. Kept off the wire:
	// the Directors' rules screen needs it to say who can read the entry.
	Visibility string `json:"-"`
	// Origin says whose words these are: "standard" (the package's),
	// "campaign" (the campaign's own) or "rewritten" (a campaign entry in a
	// standard entry's place, named by StandsFor). Empty when no campaign
	// overlay ran.
	Origin    string `json:"origin,omitempty"`
	StandsFor string `json:"standsFor,omitempty"`
	// ToldRecently marks a campaign entry the players were told changed
	// within the last two weeks (ToldWindow).
	ToldRecently bool `json:"toldRecently,omitempty"`
	// Parent is the name of the parent step's entry this one belongs to, set
	// on entries of a step that declares creator.from (a subclass lists the
	// class it comes with). Empty on every other entry.
	Parent string `json:"parent,omitempty"`
	// SystemLook is the card look the game system itself gives a package entry
	// the campaign's owner has laid their own look over (LookChanged); nil when
	// the package names no valid border. A Director's plan carries it so the
	// owner can compare and reset; it is never served to players.
	SystemLook *cardborders.Look `json:"-"`
	// LookChanged marks a package entry whose card_border / card_colour are the
	// owner's choice, not the package's.
	LookChanged bool `json:"-"`
}

Choice is one pickable entry.

type ChoiceHero

type ChoiceHero struct {
	ID          string
	Name        string
	OwnerUserID string
	Fields      map[string]string
}

ChoiceHero is a character page a player plays, as the rules read it: the fields are the page's text values by key.

type ChoiceHeroes

type ChoiceHeroes interface {
	// Heroes lists the campaign's character pages that a player plays.
	Heroes(ctx context.Context, campaignID string) ([]ChoiceHero, error)
	// Members lists the campaign's members.
	Members(ctx context.Context, campaignID string) ([]ChoiceMember, error)
	// SetField writes one text field of a hero page the player owns, as a
	// Director would, and reports whether it did (false when the page is gone
	// or no longer theirs).
	SetField(ctx context.Context, campaignID, entityID, ownerUserID, fieldKey, value string) (bool, error)
}

ChoiceHeroes is what the rules need from the entities and campaigns plugins, implemented at the composition root so this package imports neither.

type ChoiceLimiter

type ChoiceLimiter interface {
	Limit(ctx context.Context, campaignID string, list *ChoiceList) error
}

ChoiceLimiter narrows a viewer's pick list by the campaign's rules. The character choice service calls it after every source is merged, so the plan, the picker, the AI's brief and every write check read one list.

type ChoiceList

type ChoiceList struct {
	FieldKey   string   `json:"fieldKey"`
	SystemID   string   `json:"systemId"`
	SystemName string   `json:"systemName"`
	Choices    []Choice `json:"choices"`
	// CanMake says the viewer may write their own entry for this field, a
	// permission a Director gave them (see EntryGrant).
	CanMake bool `json:"canMake,omitempty"`
	// Rules says what the campaign's hero-choice rules did to this list for
	// the viewer; nil when none applies.
	Rules *FieldRules `json:"rules,omitempty"`
	// Excluded holds the entries the rules took off the list, with their data,
	// so a hero that already holds one stays editable. Never served.
	Excluded []Choice `json:"-"`
}

ChoiceList is the full answer for one field: the choices plus the system they came from, so the UI can say "<System> doesn't list these yet" when the list is empty.

type ChoiceMark

type ChoiceMark struct {
	// Source is "package" or "campaign".
	Source string `json:"source"`
	// Key is an entry's key (Choice.Key) or "*" for the whole source.
	Key string `json:"key"`
	// Target is "" for everyone, else a player's account id.
	Target string `json:"target"`
	// State is open, ask_first, not_offered, required, or clear to remove
	// the mark. Open for everyone is the same as clear.
	State string `json:"state"`
	// Reason is shown to the player it applies to. Absent keeps the stored
	// reason; present (even "") replaces it.
	Reason *string `json:"reason"`
}

ChoiceMark is one mark in a request: the state of an entry (or, with Key "*", of a whole source) for everyone or for one player.

type ChoiceMarksInput

type ChoiceMarksInput struct {
	FieldKey string       `json:"fieldKey"`
	Marks    []ChoiceMark `json:"marks"`
}

ChoiceMarksInput is a batch of marks on one pick list.

type ChoiceMember

type ChoiceMember struct {
	UserID string `json:"userId"`
	Name   string `json:"name"`
}

ChoiceMember is a campaign member, for naming the person a rule is about.

type ChoiceOverlay

type ChoiceOverlay func(ctx context.Context, campaignID, systemID, fieldKey string, pkg []Choice) ([]Choice, error)

ChoiceOverlay merges the campaign's entries into the package's choices for the viewer the context marks, deciding which standard rows a stand-in replaces and which are left out. It replaces the plain append of ChoiceSources, so a tied entry never shows twice.

type ChoiceRequest

type ChoiceRequest struct {
	ID         int64  `json:"id"`
	CampaignID string `json:"-"`
	SystemID   string `json:"-"`
	FieldKey   string `json:"fieldKey"`
	Source     string `json:"source"`
	Key        string `json:"key"`
	// Name is the entry the player asked for.
	Name   string `json:"entryName"`
	UserID string `json:"userId"`
	// EntityID and EntityName are the hero the pick is for; empty when the
	// hero page is gone.
	EntityID   string     `json:"entityId,omitempty"`
	EntityName string     `json:"entityName,omitempty"`
	Status     string     `json:"status"`
	Message    string     `json:"message,omitempty"`
	DecidedBy  string     `json:"-"`
	CreatedAt  time.Time  `json:"createdAt"`
	DecidedAt  *time.Time `json:"decidedAt,omitempty"`
}

ChoiceRequest is a hero pick that needs a Director's yes. It is kept here, never in the hero's fields, which the sheet and Foundry read as real.

type ChoiceRequestInput

type ChoiceRequestInput struct {
	CampaignID string
	UserID     string
	// EntityID and EntityName name the hero the pick is for.
	EntityID   string
	EntityName string
	FieldKey   string
	EntryName  string
}

ChoiceRequestInput is a player's pick of an ask-first entry.

type ChoiceRequestOutcome

type ChoiceRequestOutcome struct {
	ID        int64  `json:"id"`
	FieldKey  string `json:"fieldKey"`
	EntryName string `json:"entryName"`
	Status    string `json:"status"`
}

ChoiceRequestOutcome is what a write answers with instead of storing the pick: the request now waits for a Director.

type ChoiceRule

type ChoiceRule struct {
	ID         int64  `json:"id"`
	CampaignID string `json:"-"`
	SystemID   string `json:"-"`
	FieldKey   string `json:"fieldKey"`
	// Source is ChoiceSourcePackage or ChoiceSourceCampaign.
	Source string `json:"source"`
	// Key is a package entry's slug, a campaign entry's id, or RuleGroupKey.
	Key string `json:"key"`
	// Name is the entry's name when the mark was last saved, so a package
	// entry that later leaves the package can still be named.
	Name string `json:"name,omitempty"`
	// Target is "" for everyone, else the player's account id.
	Target string `json:"target"`
	State  string `json:"state"`
	// Reason is shown to the player the mark applies to.
	Reason    string    `json:"reason,omitempty"`
	CreatedBy string    `json:"-"`
	CreatedAt time.Time `json:"-"`
	UpdatedAt time.Time `json:"updatedAt"`
}

ChoiceRule is one stored mark.

func (ChoiceRule) IsGroup

func (r ChoiceRule) IsGroup() bool

IsGroup reports whether the rule marks a whole source rather than an entry.

type ChoiceRuleHandler

type ChoiceRuleHandler struct {
	// contains filtered or unexported fields
}

ChoiceRuleHandler serves the hero-choice rules and the picks waiting on a Director. It binds, calls the service and renders; the Directors-only rule is the service's, with this handler stating who is asking (the owner and co-Directors, never a Scribe).

func NewChoiceRuleHandler

func NewChoiceRuleHandler(svc ChoiceRuleService) *ChoiceRuleHandler

NewChoiceRuleHandler creates the handler.

func (*ChoiceRuleHandler) AllowRequestAPI

func (h *ChoiceRuleHandler) AllowRequestAPI(c *echo.Context) error

AllowRequestAPI says yes to a waiting pick: the player may have the entry, and the hero's field is set as a Director would.

POST /campaigns/:id/choice-requests/:requestId/allow

func (*ChoiceRuleHandler) CheckMarksAPI

func (h *ChoiceRuleHandler) CheckMarksAPI(c *echo.Context) error

CheckMarksAPI is the dry run: the heroes already made that a batch of marks would newly break. Nothing is written.

POST /campaigns/:id/choice-rules/check

func (*ChoiceRuleHandler) CountAPI

func (h *ChoiceRuleHandler) CountAPI(c *echo.Context) error

CountAPI says how many rules name a campaign entry, for the delete confirmation ("in 2 hero rules").

GET /campaigns/:id/choice-rules/count?entryId=12

func (*ChoiceRuleHandler) EntriesAPI

func (h *ChoiceRuleHandler) EntriesAPI(c *echo.Context) error

EntriesAPI returns a pick list's every entry, the game's and the campaign's, with its marks; ?as= shows it as one player gets it.

GET /campaigns/:id/choice-rules/entries?fieldKey=ancestry&as=<userId>

func (*ChoiceRuleHandler) RequestsAPI

func (h *ChoiceRuleHandler) RequestsAPI(c *echo.Context) error

RequestsAPI lists the picks waiting on a Director.

GET /campaigns/:id/choice-requests

func (*ChoiceRuleHandler) RulesAPI

func (h *ChoiceRuleHandler) RulesAPI(c *echo.Context) error

RulesAPI lists the stored rules.

GET /campaigns/:id/choice-rules?fieldKey=ancestry

func (*ChoiceRuleHandler) SetMarksAPI

func (h *ChoiceRuleHandler) SetMarksAPI(c *echo.Context) error

SetMarksAPI writes a batch of marks on one pick list and answers with the list's rules after.

PUT /campaigns/:id/choice-rules

func (*ChoiceRuleHandler) SuggestRequestAPI

func (h *ChoiceRuleHandler) SuggestRequestAPI(c *echo.Context) error

SuggestRequestAPI closes a waiting pick with a note asking for another.

POST /campaigns/:id/choice-requests/:requestId/suggest {"message": "..."}

type ChoiceRuleOption

type ChoiceRuleOption func(*choiceRuleService)

ChoiceRuleOption adds an optional dependency to the service.

func WithChoiceHeroes

func WithChoiceHeroes(h ChoiceHeroes) ChoiceRuleOption

WithChoiceHeroes lets the rules read heroes and members and set a hero's field. Without it the dry run finds no heroes, names are blank and Allow records the player's open mark without touching a hero.

type ChoiceRuleRepository

type ChoiceRuleRepository interface {
	// List returns the system's rules, for one field when fieldKey is set.
	List(ctx context.Context, campaignID, systemID, fieldKey string) ([]ChoiceRule, error)
	// ListForViewer returns the rules that apply to one viewer: those for
	// everyone and those for userID (every field when fieldKey is "").
	ListForViewer(ctx context.Context, campaignID, systemID, fieldKey, userID string) ([]ChoiceRule, error)
	// Apply writes a batch of marks in one transaction: upserts replace the
	// row for the same (field, entry, target), deletes remove it.
	Apply(ctx context.Context, upserts []ChoiceRule, deletes []ChoiceRule) error
	// CountForEntry counts the rules naming one entry, for the delete warning.
	CountForEntry(ctx context.Context, campaignID, systemID, fieldKey, source, key string) (int, error)
	// DeleteForEntry removes every rule naming an entry, and withdraws the
	// requests waiting on it; it returns how many rules went.
	DeleteForEntry(ctx context.Context, campaignID, systemID, fieldKey, source, key string) (int, error)

	// UpsertWaiting records a waiting request, replacing the same player's
	// waiting request for the same hero and field.
	UpsertWaiting(ctx context.Context, r *ChoiceRequest) error
	// GetRequest returns one request; apperror not-found when absent.
	GetRequest(ctx context.Context, campaignID string, id int64) (*ChoiceRequest, error)
	// ListRequests returns the system's requests in one status, oldest first.
	ListRequests(ctx context.Context, campaignID, systemID, status string) ([]ChoiceRequest, error)
	// UserRequests returns one player's waiting requests and their recently
	// suggested ones for one field, newest first.
	UserRequests(ctx context.Context, campaignID, systemID, userID, fieldKey string, since time.Time) ([]ChoiceRequest, error)
	// HeroWaiting returns the waiting requests one player made for one hero.
	HeroWaiting(ctx context.Context, campaignID, userID, entityID string) ([]ChoiceRequest, error)
	// Close moves a waiting request to a decided status; false when it was
	// no longer waiting.
	Close(ctx context.Context, campaignID string, id int64, status, message, decidedBy string) (bool, error)
}

ChoiceRuleRepository is the data access contract for hero-choice rules and the picks waiting on a Director. Every method is scoped by campaign.

func NewChoiceRuleRepository

func NewChoiceRuleRepository(db *sql.DB) ChoiceRuleRepository

NewChoiceRuleRepository creates the MariaDB-backed repository.

type ChoiceRuleService

type ChoiceRuleService interface {
	ChoiceLimiter

	// Rules lists a pick list's stored rules (every list when fieldKey is
	// ""). Directors only.
	Rules(ctx context.Context, campaignID, fieldKey string, actor EntryActor) ([]ChoiceRule, error)
	// SetMarks writes a batch of marks and returns the list's rules after.
	// Directors only.
	SetMarks(ctx context.Context, campaignID string, actor EntryActor, in ChoiceMarksInput) ([]ChoiceRule, error)
	// CheckMarks says which heroes the batch would newly break, writing
	// nothing. Directors only.
	CheckMarks(ctx context.Context, campaignID string, actor EntryActor, in ChoiceMarksInput) (*MarksCheck, error)
	// DirectorEntries is a pick list's every entry with its marks, for the
	// Directors' screen; asUser shows it as that player gets it.
	DirectorEntries(ctx context.Context, campaignID string, actor EntryActor, fieldKey, asUser string) (*DirectorEntryList, error)
	// RuleCountForEntry counts the rules naming a campaign entry, for the
	// delete warning. Directors only.
	RuleCountForEntry(ctx context.Context, campaignID string, actor EntryActor, entryID int64) (int, error)
	// ForgetEntry removes the rules naming a deleted campaign entry.
	ForgetEntry(ctx context.Context, campaignID, systemID, fieldKey string, entryID int64) (int, error)

	// HeroBreaks lists the rules a hero already breaks. Never changes the hero.
	HeroBreaks(ctx context.Context, campaignID string, hero ChoiceHero) ([]HeroBreak, error)

	// HeroWaiting lists the picks one player has waiting on a Director for
	// one hero, so the sheet can show each blank as waiting.
	HeroWaiting(ctx context.Context, campaignID, userID, entityID string) ([]HeroWaitingPick, error)
	// RequestChoice records a player's pick of an ask-first entry.
	RequestChoice(ctx context.Context, in ChoiceRequestInput) (*ChoiceRequestOutcome, error)
	// WaitingRequests lists the picks waiting on a Director. Directors only.
	WaitingRequests(ctx context.Context, campaignID string, actor EntryActor) ([]WaitingChoiceRequest, error)
	// AllowRequest gives the player the entry (a per-player open mark) and
	// sets the hero's field as a Director would. Directors only.
	AllowRequest(ctx context.Context, campaignID string, actor EntryActor, id int64) (*AllowOutcome, error)
	// SuggestAnother closes a request with a note for the player; the step
	// stays empty. Directors only.
	SuggestAnother(ctx context.Context, campaignID string, actor EntryActor, id int64, message string) error
}

ChoiceRuleService owns the hero-choice rules: reading them for a viewer, the Directors' screens, and the picks that wait on a Director. It never sees a request; callers say who is asking through EntryActor.

func NewChoiceRuleService

NewChoiceRuleService wires the service. choices is read with the rules switched off (WithChoiceUnlimited) to see every entry.

type ChoiceSource

type ChoiceSource func(ctx context.Context, campaignID, fieldKey string) ([]Choice, error)

ChoiceSource contributes extra choices for a field. It lets a later feature add campaign-made entries (Source "campaign") without this package knowing about them. A source returns nil for fields it has nothing for.

type ComposeInput

type ComposeInput struct {
	Note     string            // the question asked, echoed into the result
	Calls    []string          // catalog names, in the order ticked
	Campaign string            // campaign id for every campaign blank
	Page     string            // page name, slug or id for every page blank
	Args     map[string]string // free-text blanks, by check name
}

ComposeInput is what the page sends: the ticked checks and the blanks.

type CraftingGoal

type CraftingGoal struct {
	Echelon int    `json:"echelon"`
	For     string `json:"for,omitempty"`
	Goal    int    `json:"goal"`
}

CraftingGoal is one published project goal: what a project of this kind (a "consumable", a "weapon"; empty for any) at this echelon needs.

type CraftingLabels

type CraftingLabels struct {
	Goal         string `json:"goal,omitempty"`
	Prerequisite string `json:"prerequisite,omitempty"`
	Source       string `json:"source,omitempty"`
}

CraftingLabels are a system's names for a project's goal, the item it needs before it can start, and where the knowledge comes from.

type CraftingRules

type CraftingRules struct {
	// Dice is the project roll, written NdS ("2d10").
	Dice string `json:"dice"`
	// Characteristics are the character sheet fields a recipe may add to
	// the roll, by field key, with the label shown in the editor.
	Characteristics []CraftingStat `json:"characteristics,omitempty"`
	// Edge and Bane are what clean and botched work add to the roll.
	Edge int `json:"edge"`
	Bane int `json:"bane"`
	// Tiers are the two highest totals of the first and second outcome of a
	// tiered test such as harvesting: a total at or below Tiers[0] is the
	// first tier, at or below Tiers[1] the second, anything higher the third.
	Tiers []int `json:"tiers,omitempty"`
	// Labels name the project's fields in the system's own words.
	Labels CraftingLabels `json:"labels"`
	// Goals are the project goals the system publishes, by echelon and by
	// what is made. Chronicle's recipe generator uses only these; with none
	// it says the goal is the Director's to set.
	Goals []CraftingGoal `json:"goals,omitempty"`
}

CraftingRules is how a game system rolls and counts a crafting project: the arithmetic only. Recipes, benches and steps are the campaign's own and work under any system's rules; a system with no block gets DefaultCraftingRules.

func DefaultCraftingRules

func DefaultCraftingRules() CraftingRules

DefaultCraftingRules is the crafting a campaign gets when its system declares none (or it has no system): a 2d10 roll with no characteristic, an edge of +2 and a bane of -2, and the 11 / 16 tiers of a power roll.

type CraftingStat

type CraftingStat struct {
	Key   string `json:"key"`
	Label string `json:"label"`
}

CraftingStat is one characteristic a project roll can add.

type CreateSystemEntryInput

type CreateSystemEntryInput struct {
	FieldKey    string         `json:"fieldKey"`
	Name        string         `json:"name"`
	Summary     string         `json:"summary"`
	Description string         `json:"description"`
	Properties  map[string]any `json:"properties"`
	// Visibility defaults to "everyone" when empty.
	Visibility string `json:"visibility"`
	// ForEntityID names the character page; required with visibility
	// "character" and refused with any other.
	ForEntityID string `json:"forEntityId"`
	// Status is for a player's own entry only: "sent" hands it in at once,
	// anything else keeps it a draft. A Director's entry is always accepted.
	Status string `json:"status"`
}

CreateSystemEntryInput is the body of a create.

type CreatorCount

type CreatorCount struct {
	Step     string `json:"step"`
	Property string `json:"property"`
	Note     string `json:"note,omitempty"`
}

CreatorCount names a step and a number property that sets how many of this step the entry chosen there allows; Note names a text property on the same entry that explains it to the player.

type CreatorDef

type CreatorDef struct {
	// Needed marks a pick the system's rules expect. The creator no longer
	// calls the step optional, but the server still accepts a hero without
	// it; only a Director's rule refuses.
	Needed bool `json:"needed,omitempty"`

	// From makes the step's entries the items of a property of the entry
	// chosen at another step (subclasses inside a class entry).
	From *CreatorFrom `json:"from,omitempty"`

	// CountFrom says how many of this step the chosen parent entries allow,
	// read from a number in their property. Later entries override earlier.
	CountFrom []CreatorCount `json:"count_from,omitempty"`

	// Multi lets the step take several picks: as many as CountFrom gives,
	// one when nothing gives a number. The field keeps them joined with
	// MultiPickSeparator, so a reader that wants one name still gets text.
	Multi bool `json:"multi,omitempty"`
}

CreatorDef is a preset field's declaration for the hero creator. It only DECLARES: the plan builder and the creator act on it, so core keeps no game system's step names.

type CreatorFrom

type CreatorFrom struct {
	Step     string `json:"step"`
	Property string `json:"property"`
}

CreatorFrom names the step and the entry property a dependent step reads.

type CreatorPlan

type CreatorPlan struct {
	SystemID   string        `json:"systemId"`
	SystemName string        `json:"systemName"`
	Steps      []CreatorStep `json:"steps"`
}

CreatorPlan is everything the creator needs to draw its steps. Steps is empty when neither the system nor the campaign lists anything yet, and the creator then asks only for a name.

type CreatorStep

type CreatorStep struct {
	FieldKey string   `json:"fieldKey"`
	Label    string   `json:"label"`
	Choices  []Choice `json:"choices"`
	// CanMake: the viewer may write their own entry for this step.
	CanMake bool `json:"canMake,omitempty"`
	// Rules says what the hero-choice rules did to this step for the viewer.
	Rules *FieldRules `json:"rules,omitempty"`
	// Excluded is what the rules took off the list, kept server-side so a
	// hero that already holds one stays editable. Never served.
	Excluded []Choice `json:"-"`
	// Needed: the system's rules expect this pick, so the creator does not
	// call it optional. The server still accepts a hero without it.
	Needed bool `json:"needed,omitempty"`
	// Parent is the field key of the step this step's entries live inside
	// (each entry carries the parent entry's name in Choice.Parent).
	Parent string `json:"parent,omitempty"`
	// CountFrom says how many of this step the chosen parent entries allow;
	// see CreatorCount.
	CountFrom []CreatorCount `json:"countFrom,omitempty"`
	// Multi: the step takes as many picks as CountFrom gives (CreatorDef.Multi).
	Multi bool `json:"multi,omitempty"`
}

CreatorStep is one question the hero creator asks: a text field on the system's character preset that has entries to pick from, whether the package lists them or the campaign's Directors added their own.

type CritRule

type CritRule struct {
	// Dice names the dice the rule covers: "d20" (every d20) or, with a count,
	// "2d10" (a group of exactly that many).
	Dice string `json:"dice"`
	// Judge is "each" (default: every die by its own face) or "total" (a
	// group of Dice's count is judged by its sum, because the system reads
	// the pair or pool as one result, like Draw Steel's 2d10 power roll).
	Judge string `json:"judge,omitempty"`
	// Succ and Fail are the faces (or, for "total", the sums) that count.
	Succ []int `json:"succ,omitempty"`
	Fail []int `json:"fail,omitempty"`
}

CritRule says which rolled dice a game system counts as a critical success or failure. Chronicle's server applies it to every roll it records, so both dice looks and the log mark the same crits; a browser never decides one.

func DefaultCritRules

func DefaultCritRules() []CritRule

DefaultCritRules is what a campaign gets when its system declares none or it has no system: a natural 20 on a d20 is a success, a natural 1 a failure.

type DMScreenConditions

type DMScreenConditions struct {
	Category string `json:"category"`
	Property string `json:"property,omitempty"`
	Value    string `json:"value,omitempty"`
}

DMScreenConditions selects conditions from one of the system's reference categories, optionally narrowed to entries whose property equals a value.

type DMScreenDef

type DMScreenDef struct {
	// Party lists the meters shown under each hero, in order.
	Party []DMScreenMeter `json:"party,omitempty"`

	// HeroSubtitle names the sheet field shown under a hero's name when it
	// is folded open (a class).
	HeroSubtitle string `json:"hero_subtitle,omitempty"`

	// HeroConditions names the sheet field listing the conditions a hero
	// has right now: a JSON list of names or {"name": …} objects, or a
	// comma-separated string.
	HeroConditions string `json:"hero_conditions,omitempty"`

	// Conditions points at the reference entries the rules tab lists.
	Conditions *DMScreenConditions `json:"conditions,omitempty"`
}

DMScreenDef is a system's contribution to the DM Screen. Chronicle can't know what "health" means in each game, so the package names the sheet fields to show and the reference category its conditions live in.

type DMScreenMeter

type DMScreenMeter struct {
	// Label is the fixed text shown before the value ("Stamina").
	Label string `json:"label,omitempty"`

	// LabelField names a sheet field whose value is the label instead, for
	// numbers whose name depends on the hero (a class's heroic resource).
	LabelField string `json:"label_field,omitempty"`

	// Current is the sheet field holding the value. Required.
	Current string `json:"current"`

	// Max is the sheet field holding the maximum; when set, the meter draws
	// as a bar.
	Max string `json:"max,omitempty"`

	// WarnBelow marks the bar as low when current/max drops under this
	// fraction (0.5 for Draw Steel's winded). Zero disables the warning.
	WarnBelow float64 `json:"warn_below,omitempty"`
}

DMScreenMeter is one number (or current/max pair) read from a hero's character-sheet fields.

type DataProvider

type DataProvider interface {
	// List returns all reference items in the given category.
	List(category string) ([]ReferenceItem, error)

	// Get returns a single reference item by category and ID (slug).
	// Returns nil and no error if the item does not exist.
	Get(category string, id string) (*ReferenceItem, error)

	// Search returns reference items matching the query string
	// across all categories. Used for tooltip lookups and autocomplete.
	Search(query string) ([]ReferenceItem, error)

	// Categories returns the list of available data category slugs.
	Categories() []string
}

DataProvider serves read-only reference data from a module. Implementations load data from static JSON files at startup and serve it from memory. They never access the database.

type DesignDef

type DesignDef struct {
	// Kind names a design kind the server knows ("room-theme", ...). The
	// designs kind registry is the authority, consulted when the file is read.
	Kind string `json:"kind"`
	// Name is what the library shows. Up to 60 characters.
	Name string `json:"name"`
	// Note is an optional line under the name. Up to 140 characters.
	Note string `json:"note,omitempty"`
	// Maker credits the person who made it. Optional, up to 100 characters.
	Maker string `json:"maker,omitempty"`
	// File is a JSON file inside the package holding the design's data: a
	// relative path with no "..", not absolute, ending in .json.
	File string `json:"file"`
}

DesignDef is one entry of a manifest's "designs" list: a saved design (a room theme, a magic circle...) the package ships for its campaigns to start from. The data itself lives in File, so the manifest stays readable.

type DesignKindChecker

type DesignKindChecker interface {
	// ValidateDesign returns the canonical data, or an error for an unknown
	// kind or data the kind refuses.
	ValidateDesign(ctx context.Context, kind string, raw json.RawMessage) (json.RawMessage, error)
}

DesignKindChecker is the designs kind registry as the loader needs it. App wiring adapts it, so this package never imports the designs plugin.

type DiagCategory

type DiagCategory struct {
	Slug  string
	Name  string
	Icon  string
	Count int
}

DiagCategory holds a category with its item count.

type DiagEntityType

type DiagEntityType struct {
	ID             int
	Name           string
	Slug           string
	PresetCategory string // Empty if not from a system preset.
	Count          int    // Populated separately from EntityCountProvider.
}

DiagEntityType holds entity type info needed by the diagnostics page.

type Diagnostic

type Diagnostic struct {
	Name     string                  // dotted id the assistant requests, e.g. "system.files"
	Title    string                  // human title
	Desc     string                  // one-line "what you get / when to use"
	ArgHint  string                  // "" when the diagnostic takes no argument
	FullDump bool                    // true = heavy/verbose; a batch must set full_dump:true to authorize it
	Run      func(arg string) string // produces the (pre-redaction) markdown result
}

Diagnostic is one named, read-only check in the catalog. Adding a diagnostic = appending one of these — the renderer, route, and redaction are unchanged ("modular and templated"). Run returns markdown; Arg is "" for no-argument diagnostics.

type DiagnosticQuestion

type DiagnosticQuestion struct {
	ID       string
	Icon     string // Font Awesome name
	Title    string
	Desc     string
	Sentence string
	Calls    []string
}

DiagnosticQuestion is one everyday problem and the checks that answer it. Sentence names what Chronicle will look at; {campaign} and {page} mark the blanks the operator fills in place.

func DiagnosticQuestions

func DiagnosticQuestions() []DiagnosticQuestion

DiagnosticQuestions returns the everyday questions in page order.

func (DiagnosticQuestion) NeedsCampaign

func (q DiagnosticQuestion) NeedsCampaign() bool

NeedsCampaign reports whether the question's sentence has a campaign blank.

func (DiagnosticQuestion) NeedsPage

func (q DiagnosticQuestion) NeedsPage() bool

NeedsPage reports whether the question's sentence has a page blank.

type DirectorEntry

type DirectorEntry struct {
	Key     string `json:"key"`
	Source  string `json:"source"`
	Slug    string `json:"slug,omitempty"`
	Name    string `json:"name"`
	Summary string `json:"summary,omitempty"`
	// EntryID, Visibility, Status and ForName describe a campaign entry.
	EntryID    int64  `json:"entryId,omitempty"`
	Visibility string `json:"visibility,omitempty"`
	Status     string `json:"status,omitempty"`
	ForName    string `json:"forName,omitempty"`
	// Everyone and Players are the marks stored on this entry itself.
	Everyone *MarkView    `json:"everyone"`
	Players  []PlayerMark `json:"players"`
	// State is what the entry is for the viewed audience (everyone, or the
	// player in "as"): open, ask_first, not_offered, required, or left_out
	// when a required short list does not include it.
	State string `json:"state"`
	// Inherited says State came from a group row rather than the entry's own.
	Inherited bool `json:"inherited,omitempty"`
	// Reason is the reason of the mark that decided State.
	Reason string `json:"reason,omitempty"`
	// RuleCount is how many rules (any audience) name this entry.
	RuleCount int `json:"ruleCount"`
}

DirectorEntry is one entry of the list with its marks.

type DirectorEntryList

type DirectorEntryList struct {
	FieldKey   string `json:"fieldKey"`
	SystemID   string `json:"systemId"`
	SystemName string `json:"systemName"`
	// As is the player the list is shown as, "" for everyone.
	As       string          `json:"as,omitempty"`
	Required bool            `json:"required,omitempty"`
	Groups   []DirectorGroup `json:"groups"`
	Entries  []DirectorEntry `json:"entries"`
	Members  []ChoiceMember  `json:"members"`
	// Orphans are package-entry rules whose entry is no longer in the
	// package: shown as "no longer in <system>", and inert.
	Orphans []ChoiceRule `json:"orphans"`
	// Warnings are plain sentences about the list, such as two entries that
	// share a name.
	Warnings []string `json:"warnings"`
}

DirectorEntryList is a pick list's every entry with its marks, for the Directors' screen.

type DirectorGroup

type DirectorGroup struct {
	Source string `json:"source"`
	Key    string `json:"key"`
	Label  string `json:"label"`
	// Everyone is the mark for everyone, nil when there is none.
	Everyone *MarkView    `json:"everyone"`
	Players  []PlayerMark `json:"players"`
}

DirectorGroup is the row that marks a whole source at once.

type EmbeddedAssetSet

type EmbeddedAssetSet struct {
	Slug      string
	URLPrefix string
	FS        fs.FS
}

EmbeddedAssetSet is one plugin's //go:embed-ed static filesystem as the app layer sees it: the plugin slug, the URL prefix App.mountPluginStatic() serves it under, and the FS itself (already rooted at the plugin's static/ subdir by echo.MustSubFS, so a walk yields "js/foo.js", not "static/js/foo.js").

Injected rather than imported: internal/systems must not import the plugins packages, so the app layer builds this list from its own registry. Same dependency inversion as SetInstalledPackagesProvider.

type EntityCountProvider

type EntityCountProvider func(ctx context.Context, campaignID string) (map[int]int, error)

EntityCountProvider returns entity counts grouped by type for a campaign. Decouples the system handler from the entities plugin.

type EntityDiagProvider

type EntityDiagProvider interface {
	EntityFields(ctx context.Context, campaignID, idOrSlug string) (EntityFieldDump, error)
	TypeFieldCoverage(ctx context.Context, campaignID, typeIDOrName string) (FieldCoverage, error)
	EntityTypes(ctx context.Context, campaignID string) ([]EntityTypeInfo, error)
	FindEntities(ctx context.Context, campaignID, query string) ([]EntityHit, error)
}

EntityDiagProvider is the injected read-only window into campaign entity data. Implemented by the app layer against the entities service (dependency inversion).

type EntityFieldDump

type EntityFieldDump struct {
	Found    bool
	ID       string
	Name     string
	TypeName string
	Fields   map[string]any
}

EntityFieldDump is one entity's stored field map for the entity.fields diagnostic.

type EntityHit

type EntityHit struct {
	ID       string
	Name     string
	Slug     string
	TypeName string
}

EntityHit is one search result for the entity.find discovery diagnostic.

type EntityPanelDef

type EntityPanelDef struct {
	// Widget is the slug of a widget declared in this manifest's widgets list.
	Widget string `json:"widget"`

	// AppliesTo names which pages get the panel: "npc" or "creature". Any
	// other value is rejected at load so a typo is loud, not a silently
	// missing panel.
	AppliesTo string `json:"applies_to"`
}

EntityPanelDef mounts one of this manifest's widgets on matching pages of campaigns that have the system enabled.

type EntityPresetDef

type EntityPresetDef struct {
	// Slug is the URL-safe identifier (e.g., "dnd5e-character").
	Slug string `json:"slug"`

	// Name is the display name (e.g., "D&D Character").
	Name string `json:"name"`

	// NamePlural is the plural display name (e.g., "D&D Characters").
	NamePlural string `json:"name_plural"`

	// Icon is the Font Awesome icon class.
	Icon string `json:"icon"`

	// Color is the hex color for the entity type badge.
	Color string `json:"color"`

	// Category classifies the preset for feature gating (e.g., "character",
	// "item", "creature"). Used to identify which entity types belong to
	// specific features like the Armory (items) or NPC gallery (characters).
	Category string `json:"category,omitempty"`

	// FoundryItemType is the Foundry Item type an item preset's pages become
	// when a hero carries them (Draw Steel's "treasure"). Only the Foundry
	// module reads it.
	FoundryItemType string `json:"foundry_item_type,omitempty"`

	// Switch, on a preset whose category a campaign already has (the Items
	// every campaign starts with), says the preset's fields reach that
	// category only when the owner accepts a one-time switch, never by
	// themselves on enable or on a package update. Nil: the fields are added
	// as for any other preset.
	Switch *PresetSwitchDef `json:"switch,omitempty"`

	// FoundryActorType is the Foundry VTT Actor type string that corresponds
	// to this preset (e.g., "character", "hero", "npc"). Different game
	// systems use different actor types — D&D 5e uses "character", Draw Steel
	// uses "hero". The Foundry module reads this from the API to create and
	// filter actors of the correct type. Defaults to "character" if omitted.
	FoundryActorType string `json:"foundry_actor_type,omitempty"`

	// FoundryPullFields, when set, are the only field keys Foundry may send
	// back for this preset; Chronicle owns the rest. Absent means every
	// mapped field syncs both ways, as for heroes.
	FoundryPullFields []string `json:"foundry_pull_fields,omitempty"`

	// Fields are the default field definitions for entities of this type.
	Fields []FieldDef `json:"fields,omitempty"`

	// CreatorOrder names the character fields the hero creator asks first,
	// in this order; any other step follows in field order. Unknown keys are
	// ignored, so a system can name a step a campaign has no list for.
	CreatorOrder []string `json:"creator_order,omitempty"`
}

EntityPresetDef describes an entity type template that a module provides. When a campaign enables the module, these presets become available as entity type starting points.

func (*EntityPresetDef) HeroPickKeys

func (p *EntityPresetDef) HeroPickKeys() []string

HeroPickKeys names the character fields whose value marks a page as a hero's: the class (the first field mapped to the system's class item, else "class") and each single-item hero choice mapped to one concrete item type (ancestry, culture, career, kit), leaving out subclass and the class item's read-outs (level, heroic resource). It matches how the Foundry module reads the same mapping to tell heroes from NPCs.

type EntityTypeInfo

type EntityTypeInfo struct {
	ID             int
	Name           string
	Slug           string
	PresetCategory string
	Count          int
}

EntityTypeInfo is one entity type for the entity.types discovery diagnostic.

type EntityTypeProvider

type EntityTypeProvider func(ctx context.Context, campaignID string) ([]DiagEntityType, error)

EntityTypeProvider returns entity types for a campaign. Decouples the system handler from the entities plugin.

type EntriesDeskProvider

type EntriesDeskProvider struct {
	// contains filtered or unexported fields
}

EntriesDeskProvider fills the desk's Own entries line.

func NewEntriesDeskProvider

func NewEntriesDeskProvider(svc SystemEntryService, asks AskCounter) *EntriesDeskProvider

NewEntriesDeskProvider returns the desk provider for Own entries. asks may be nil, which leaves Ask-first picks out of the figures.

func (*EntriesDeskProvider) Facts

Facts reads the entries as a Director, the same list the page draws, so the row and the page agree. A draft a player is still writing is not counted: only a handed-in draft waits on the owner, and so does an Ask-first pick.

func (*EntriesDeskProvider) Slot

Slot is the one desk line this provider fills.

type EntryActor

type EntryActor struct {
	UserID string
	// IsDirector is true for the campaign owner and co-Directors.
	IsDirector bool
}

EntryActor is who is asking. The service decides what they may do; the caller (handler or AI import) only states the facts about the person.

type EntryCatalog

type EntryCatalog interface {
	// Catalog returns a category as the reader has it. A Directors-only
	// category is empty for anyone else.
	Catalog(ctx context.Context, campaignID, category string, reader EntryActor) (*CatalogList, error)
	// FieldCatalog is Catalog for the category a character field's pick list
	// draws from; nil when the campaign has no game system with that field.
	FieldCatalog(ctx context.Context, campaignID, fieldKey string, reader EntryActor) (*CatalogList, error)
	// ResolveAddress resolves a slug under a category. printed asks for the
	// printed original, which only a Director gets for a rewritten entry;
	// for anyone else it answers as if not asked.
	ResolveAddress(ctx context.Context, campaignID, category, slug string, printed bool, reader EntryActor) (*Resolution, error)
	// ResolveName resolves a name (what a hero stores) the same way: the
	// stand-in a reader sees for a standard name, an old name's entry, or
	// left out.
	ResolveName(ctx context.Context, campaignID, category, name string, reader EntryActor) (*Resolution, error)
	// ResolveNames resolves many names against one reading built once, so a
	// page that resolves every hero's stored name costs the same few queries
	// however many heroes there are. The answers are in the order of names.
	ResolveNames(ctx context.Context, campaignID, category string, names []string, reader EntryActor) ([]*Resolution, error)
	// PickList is the hero creator's list for a field: the package's
	// choices merged with the campaign's for the viewer the context marks
	// (ChoiceViewerIsDirector, ChoiceViewerUser), by the catalog's rules.
	PickList(ctx context.Context, campaignID, systemID, fieldKey string, pkg []Choice) ([]Choice, error)
}

EntryCatalog is the per-reader list and resolver.

type EntryCharacter

type EntryCharacter struct {
	ID   string
	Name string
	// OwnerUserID is the player who plays it; empty when nobody has claimed it.
	OwnerUserID string
}

EntryCharacter is a character page an entry can be kept to.

type EntryCharacters

type EntryCharacters interface {
	// Character returns the character page with this id in the campaign, or
	// nil when there is none.
	Character(ctx context.Context, campaignID, entityID string) (*EntryCharacter, error)
	// CharacterNamed returns the campaign's one character page with this
	// name (any casing), or nil when there is none or more than one.
	CharacterNamed(ctx context.Context, campaignID, name string) (*EntryCharacter, error)
}

EntryCharacters finds the campaign's character pages for entries kept to one character. Implemented at the composition root over the entities plugin, which this package cannot import.

type EntryGrant

type EntryGrant struct {
	ID         int64  `json:"id"`
	CampaignID string `json:"-"`
	SystemID   string `json:"-"`
	FieldKey   string `json:"fieldKey"`
	UserID     string `json:"userId"`
	// Budget is the points total the player's entry gets (the "*_points"
	// property), so a player cannot grant themselves more; 0 for none.
	Budget int `json:"budget"`
	// EntryID is the entry the player made with it; 0 while unspent.
	EntryID   int64     `json:"entryId,omitempty"`
	GrantedBy string    `json:"-"`
	CreatedAt time.Time `json:"createdAt"`
}

EntryGrant lets one player write one entry of their own for a pick list. It is spent (EntryID set) when they save it; a Director can give it again.

func (*EntryGrant) Spent

func (g *EntryGrant) Spent() bool

Spent reports whether the player has already made their entry.

type EntryLookForgetter

type EntryLookForgetter interface {
	ForgetDerived(ctx context.Context, campaignID, systemID, parentSlug string) (int, error)
}

EntryLookForgetter removes the looks kept for the entries derived from a deleted campaign entry (a subclass key is <parent slug>--<name>), so none is left naming a card nothing can show. The card look service implements it.

type EntryManifestResolver

type EntryManifestResolver func(ctx context.Context, campaignID string) *SystemManifest

EntryManifestResolver returns the game system manifest active for a campaign (its custom upload, else the chosen built-in), or nil for none. The entry's system id is that manifest's id, so entries made under one system never show under another.

type EntryNote

type EntryNote struct {
	ID         int64     `json:"id"`
	CampaignID string    `json:"-"`
	EntryID    int64     `json:"entryId"`
	Line       string    `json:"line"`
	CreatedBy  string    `json:"-"`
	CreatedAt  time.Time `json:"createdAt"`
}

EntryNote is one line the Director told the players about a change to an entry.

type EntryOldName

type EntryOldName struct {
	ID         int64     `json:"id"`
	CampaignID string    `json:"-"`
	SystemID   string    `json:"-"`
	FieldKey   string    `json:"fieldKey"`
	Name       string    `json:"name"`
	EntryID    int64     `json:"entryId"`
	CreatedAt  time.Time `json:"createdAt"`
}

EntryOldName is a name a campaign entry used to have. Heroes store the name they picked, so a rename must not strand them.

type EntryPeople

type EntryPeople interface {
	// People lists up to limit characters the reader may see whose field
	// fieldKey is filled.
	People(ctx context.Context, campaignID, fieldKey string, reader PeopleReader, limit int) ([]EntryPerson, error)
	// Person returns one character the reader may see with what its field
	// fieldKey holds, or nil when there is none they may see.
	Person(ctx context.Context, campaignID, entityID, fieldKey string, reader PeopleReader) (*EntryPerson, error)
}

EntryPeople finds the campaign's characters by what their kind fields hold. Implemented at the composition root over the entities plugin, which this package cannot import, and always with the reader's own permissions.

type EntryPerson

type EntryPerson struct {
	ID   string
	Name string
	// Hero is true for a character a player has claimed.
	Hero bool
	// Mine is true when the reader plays it.
	Mine bool
	// Value is what the character's field stores (the entry's name, or an
	// old or printed name).
	Value string
	// Traits are the names it bought from the entry's list.
	Traits []string
}

EntryPerson is a character page whose field names an entry of a kind: what it stores there (a name, as heroes keep it) and the traits it bought from that entry's list.

type EntryReading

type EntryReading interface {
	// Rewritable reports whether the standard entry copies into a campaign
	// entry without loss: it passes every check a campaign entry must pass.
	// The page asks before offering "Rewrite"; false, not an error, when not.
	Rewritable(ctx context.Context, campaignID, fieldKey, slug string) (bool, error)
	// Rewrite copies the standard entry whole into a new Directors-only
	// campaign entry tied to it, with the snapshot stored.
	Rewrite(ctx context.Context, campaignID string, actor EntryActor, in RewriteInput) (*SystemEntry, error)
	// Tie lets an existing campaign entry take a standard entry's place.
	Tie(ctx context.Context, campaignID string, actor EntryActor, id int64, standardSlug string) (*SystemEntry, error)
	// Untie makes a tied entry the campaign's own again; its text stays.
	Untie(ctx context.Context, campaignID string, actor EntryActor, id int64) (*SystemEntry, error)
	// MarkSeen refreshes the snapshot to the standard entry as it is today.
	MarkSeen(ctx context.Context, campaignID string, actor EntryActor, id int64) (*SystemEntry, error)
	// StandardChange says in one short line what the package changed in the
	// standard entry since the snapshot; "" when nothing did. Directors only.
	StandardChange(ctx context.Context, campaignID string, actor EntryActor, id int64) (string, error)

	// LeaveOut stops offering a standard entry, or changes its sentence.
	LeaveOut(ctx context.Context, campaignID string, actor EntryActor, in LeftOutInput) (*LeftOut, error)
	// BringBack offers a left-out standard entry again.
	BringBack(ctx context.Context, campaignID string, actor EntryActor, fieldKey, slug string) error
	// LeftOutList returns the left-out standard entries of a field ("" = all).
	// Every reader may know them: the names still answer everywhere.
	LeftOutList(ctx context.Context, campaignID, fieldKey string) ([]LeftOut, error)

	// OldNames returns the old names of a field ("" = all) whose entries the
	// actor may see.
	OldNames(ctx context.Context, campaignID, fieldKey string, actor EntryActor) ([]EntryOldName, error)
	// FreeOldName lets another entry take the name; it no longer leads here.
	FreeOldName(ctx context.Context, campaignID string, actor EntryActor, id int64) error

	// AddNote records one line the players were told about an entry.
	AddNote(ctx context.Context, campaignID string, actor EntryActor, entryID int64, line string) (*EntryNote, error)
	// Notes returns an entry's lines newest first, for a reader who may see it.
	Notes(ctx context.Context, campaignID string, actor EntryActor, entryID int64) ([]EntryNote, error)
}

EntryReading is the service's half that ties, leaves out, renames and notes. Writes are Directors' only and refused in the service.

type EntryRuleForgetter

type EntryRuleForgetter interface {
	ForgetEntry(ctx context.Context, campaignID, systemID, fieldKey string, entryID int64) (int, error)
}

EntryRuleForgetter removes the hero-choice rules that name a campaign entry, so deleting the entry leaves no rule behind that nothing can show or undo. The rules service implements it.

type EntryServiceOption

type EntryServiceOption func(*systemEntryService)

EntryServiceOption adds an optional dependency to the service.

func WithEntryCharacters

func WithEntryCharacters(c EntryCharacters) EntryServiceOption

WithEntryCharacters lets entries be kept to one character. Without it an entry cannot be made for a character, and one already stored is shown to Directors only.

func WithEntryLooks

func WithEntryLooks(f EntryLookForgetter) EntryServiceOption

WithEntryLooks makes deleting an entry delete the looks of its derived entries.

func WithEntryPeople

func WithEntryPeople(p EntryPeople) EntryServiceOption

WithEntryPeople lets a save find the heroes who hold a changed trait. Without it no save asks to tell the players.

func WithEntryRules

func WithEntryRules(r EntryRuleForgetter) EntryServiceOption

WithEntryRules makes deleting an entry delete the rules that name it.

func WithStandardSystem

func WithStandardSystem(r StandardSystemResolver) EntryServiceOption

WithStandardSystem gives the service the game system's own entries, so ties, rewrites and the per-reader catalog can read them. Without it the catalog holds the campaign's entries only and every tie is refused.

type EntryView

type EntryView struct {
	CampaignID   string
	CampaignName string
	SystemID     string
	Category     CategoryDef
	CategoryURL  string
	// Redirect is where the handler sends the reader instead (303).
	Redirect string
	URL      string
	Kind     string
	Name     string
	Entry    CatalogEntry
	// LeftOut is a left-out entry's page: only LeftOutLine, and the traits
	// for a reader whose hero still is one.
	LeftOut     bool
	LeftOutLine string
	// Printed is the Director's printed original of a rewritten entry.
	Printed    bool
	Whose      *whoseWords
	Marks      []directorMark
	Summary    string
	Story      []para
	StoryHTML  string
	InCampaign *peopleView
	Table      []tableDetail
	Notes      []noteLine
	Hero       *heroView
	IsDirector bool
	Contents   []contentsLink
	// Tools are the Director's amber words; nil for anyone else.
	Tools *directorTools
}

EntryView is an entry's page, or its peek, as one reader has it.

type EventLog

type EventLog struct {
	// contains filtered or unexported fields
}

EventLog is a thread-safe ring buffer of system loading events.

func NewEventLog

func NewEventLog(capacity int) *EventLog

NewEventLog creates an event log with the given capacity.

func (*EventLog) Events

func (l *EventLog) Events() []LoadEvent

Events returns all recorded events in chronological order. Thread-safe.

func (*EventLog) Record

func (l *EventLog) Record(event LoadEvent)

Record adds an event to the log. Thread-safe.

type FieldCoverage

type FieldCoverage struct {
	Found       bool
	TypeName    string
	EntityCount int
	Declared    []FieldCoverageRow
}

FieldCoverage is the result of entity.field-coverage for one type.

type FieldCoverageRow

type FieldCoverageRow struct {
	Key      string
	Label    string
	NonEmpty int
}

FieldCoverageRow is one declared field's population count across a type's entities.

type FieldDef

type FieldDef struct {
	// Key is the property map key (e.g., "level", "school", "cr").
	Key string `json:"key"`

	// Label is the human-readable name (e.g., "Spell Level", "School").
	Label string `json:"label"`

	// Type is the field data type: "string", "number", "list", "markdown".
	Type string `json:"type"`

	// GMOnly marks a field as GM-only: its VALUE is stripped from entity API
	// responses served to non-GM (player / public) callers, so GM secrets
	// like a statblock's director notes never reach a player's browser.
	// Absent/false = player-visible. The systems tier only DECLARES this;
	// core enforces it at egress via preset application + the field-metadata
	// reconciler.
	GMOnly bool `json:"gm_only,omitempty"`

	// OwnerOnly marks a field as visible only to GM-tier callers AND the
	// entity's own claimed owner: its VALUE is stripped from responses served
	// to every other player, so player-private content like a backstory
	// isn't shared with the rest of the party. Absent/false = party-visible.
	// Enforced the same way as GMOnly.
	OwnerOnly bool `json:"owner_only,omitempty"`

	// Choices names a data file (data/<name>.json) listing the values this
	// field can be picked from. Absent: the character field picker falls back
	// to the plural of the field key (ancestry -> ancestries.json).
	Choices string `json:"choices,omitempty"`

	// Format says how the value is written when it is not plain text or a
	// number, such as the shape of one entry in a JSON list. AI Import shows
	// it beside the field so an AI writes what the system's widgets read.
	Format string `json:"format,omitempty"`

	// Options are the values an "enum" field is picked from; the page's
	// field becomes a pick list of them.
	Options []string `json:"options,omitempty"`

	// Section groups the field on a page ("Basics", "Making it"). Absent:
	// the page's single default group.
	Section string `json:"section,omitempty"`

	// Min and Max bound a number field's value when AI Import writes it.
	// Absent means no bound; a hand-typed sheet value is not checked.
	Min *float64 `json:"min,omitempty"`
	Max *float64 `json:"max,omitempty"`

	// JSONList marks a text field that holds a JSON list (a stat block's
	// abilities), so AI Import refuses text that does not parse as one.
	JSONList bool `json:"json_list,omitempty"`

	// Formula marks a number the system works out from other fields (a
	// stat block's EV or Stamina). AI Import's review may then fill it in on
	// a page where the AI left it out, with the figure the system's sheet
	// check proposes; any other key is still never added by the review.
	Formula bool `json:"formula,omitempty"`

	// FoundryPath is the dot-notation path to the corresponding field in
	// a Foundry VTT Actor's system data (e.g., "system.abilities.str.value").
	// Used by the generic Foundry adapter to auto-generate field mappings.
	// Only meaningful on entity preset fields, not category reference fields.
	FoundryPath string `json:"foundry_path,omitempty"`

	// FoundryWritable indicates whether the generic adapter should write
	// this field back to Foundry when syncing Chronicle → Foundry.
	// Fields that are derived/calculated in Foundry (e.g., PF2e ability mods)
	// should set this to false. Defaults to true when FoundryPath is set.
	FoundryWritable *bool `json:"foundry_writable,omitempty"`

	// FoundryChoices names a list in the Foundry system's CONFIG (e.g.
	// "DRAW_STEEL.monsters.roles") whose keys this field's values become in
	// Foundry, so a label like "Leader" is stored as the key "leader". Core
	// only passes it to the Foundry module.
	FoundryChoices string `json:"foundry_choices,omitempty"`

	// FoundryFormat names how the module converts the value between Chronicle
	// and Foundry ("set", "integer", "size"). Core only passes it on; the
	// module skips a field whose format it doesn't know.
	FoundryFormat string `json:"foundry_format,omitempty"`

	// FoundryCollection names the actor collection to read ("items", "effects").
	FoundryCollection string `json:"foundry_collection,omitempty"`

	// FoundryItemType optionally filters the collection by Foundry item type(s)
	// (e.g. ["ability"], ["equipment","consumable"]).
	FoundryItemType []string `json:"foundry_item_type,omitempty"`

	// FoundryItemFields projects each collection entry to a Chronicle-side shape:
	// outKey -> dot-path on the item (e.g. {"name":"name","keywords":"system.keywords"}).
	// Omit for a default {id,name,type} projection.
	FoundryItemFields map[string]string `json:"foundry_item_fields,omitempty"`

	// FoundryItemSingle, when true, collapses a collection mapping to the FIRST
	// matching item's name (a scalar string) instead of a JSON array — for the
	// "exactly one X item" shape (e.g. a hero's class/ancestry/kit, which live as
	// embedded items rather than a system.* path). Ignored unless
	// FoundryCollection is set.
	FoundryItemSingle bool `json:"foundry_item_single,omitempty"`

	// FoundryItemJoin, with FoundryItemSingle, takes every matching item's
	// name joined with MultiPickSeparator instead of the first: a field that
	// holds several picks (a creator Multi step, such as two kits).
	FoundryItemJoin bool `json:"foundry_item_join,omitempty"`

	// Play declares that this field may be changed during play and how, so
	// core never needs to know a system's field names. Optional; a block that
	// fails validation is dropped at load (see sanitizePlayBlocks) and the
	// rest of the field survives.
	Play *PlayDef `json:"play,omitempty"`

	// Creator declares how the hero creator treats this field as a step:
	// whether the rules expect it, where its list comes from and how many
	// the chosen parent allows. Optional; a part that fails validation is
	// dropped at load (see sanitizeCreatorBlocks) and the field survives.
	Creator *CreatorDef `json:"creator,omitempty"`
}

FieldDef describes a single field in a category's reference item schema. For entity preset fields, the optional FoundryPath and FoundryWritable annotations enable automatic Foundry VTT character sync without needing a hardcoded system adapter.

func (FieldDef) IsFoundryWritable

func (f FieldDef) IsFoundryWritable() bool

IsFoundryWritable returns whether this field should be written back to Foundry. Returns true if foundry_writable is nil (default) or explicitly true.

type FieldRules

type FieldRules struct {
	// Limited says some rule applies to this viewer on this list, so a typed
	// value must be on the list too.
	Limited bool `json:"limited"`
	// Required says the list is a short list the step must be chosen from.
	Required bool `json:"required,omitempty"`
	// Prefilled is the one entry a required list is left with: filled in
	// and locked.
	Prefilled    string    `json:"prefilled,omitempty"`
	NotHereCount int       `json:"notHereCount,omitempty"`
	NotHere      []NotHere `json:"notHere,omitempty"`
	// Waiting is the viewer's pick that waits for a Director.
	Waiting *RequestView `json:"waiting,omitempty"`
	// Suggested is a recent Director's note asking for another pick.
	Suggested *RequestView `json:"suggested,omitempty"`
}

FieldRules is what the viewer needs to know about the rules on one pick list: whether it is limited, whether it is a required short list (and the one entry it is filled in with), what is kept off it, and their own waiting request. It is nil for a viewer no rule applies to.

type FileFingerprint

type FileFingerprint struct {
	Path    string `json:"path"`             // path relative to the system dir
	Exists  bool   `json:"exists"`           // false → the loader's dir lacks this file
	Size    int64  `json:"size,omitempty"`   // bytes
	SHA256  string `json:"sha256,omitempty"` // first 16 hex chars of the content hash
	ModTime string `json:"mtime,omitempty"`  // file mtime, RFC3339 UTC
}

FileFingerprint identifies a single served file by size + content hash, so two installs can be compared without reading the whole file. A missing file (Exists=false) is itself diagnostic (e.g. a botched extraction).

type FunctionSpec

type FunctionSpec struct {
	Name     string `json:"name"`
	Title    string `json:"title"`
	Desc     string `json:"desc"`
	Arg      string `json:"arg,omitempty"`       // arg hint, omitted when the function takes none
	FullDump bool   `json:"full_dump,omitempty"` // true = requires full_dump:true in the request to run
}

FunctionSpec is one entry in the machine-readable functions list the AI reads. JSON tags are terse on purpose — this is the "less context heavy" payload.

type FunctionsSpec

type FunctionsSpec struct {
	V         int            `json:"v"`
	Purpose   string         `json:"purpose"`
	HowToUse  string         `json:"how_to_use"`
	Request   BatchRequest   `json:"request_format"` // canonical example request
	Functions []FunctionSpec `json:"functions"`
}

FunctionsSpec is the top-level functions list: a self-describing contract the external AI consumes, including the exact request shape and an example.

type GenericSystem

type GenericSystem struct {
	// contains filtered or unexported fields
}

GenericSystem is a System implementation that works for any game system without custom Go code. It loads data from JSON files and uses the manifest's field definitions for tooltip rendering. Drop a manifest.json + data/*.json files into a module directory and it Just Works.

func NewGenericSystem

func NewGenericSystem(manifest *SystemManifest, dataDir string) (*GenericSystem, error)

NewGenericSystem creates a module from its manifest and data directory using the generic JSON provider and manifest-driven tooltip renderer.

func (*GenericSystem) DataProvider

func (m *GenericSystem) DataProvider() DataProvider

DataProvider returns the JSON-file data provider.

func (*GenericSystem) Info

func (m *GenericSystem) Info() *SystemManifest

Info returns the module's manifest metadata.

func (*GenericSystem) TooltipRenderer

func (m *GenericSystem) TooltipRenderer() TooltipRenderer

TooltipRenderer returns the manifest-driven generic tooltip renderer.

type GenericTooltipRenderer

type GenericTooltipRenderer struct {
	// contains filtered or unexported fields
}

GenericTooltipRenderer produces HTML tooltips by iterating the manifest's field definitions for each category. Works for any module without custom Go code — just drop data files and a manifest.json.

func NewGenericTooltipRenderer

func NewGenericTooltipRenderer(manifest *SystemManifest) *GenericTooltipRenderer

NewGenericTooltipRenderer creates a tooltip renderer that uses the manifest's field definitions to render properties for each category.

func (*GenericTooltipRenderer) RenderTooltip

func (r *GenericTooltipRenderer) RenderTooltip(item *ReferenceItem) (string, error)

RenderTooltip returns an HTML fragment for a reference item, using the manifest's field definitions to determine which properties to show.

func (*GenericTooltipRenderer) SupportedCategories

func (r *GenericTooltipRenderer) SupportedCategories() []string

SupportedCategories returns all category slugs from the manifest.

type Good

type Good struct {
	Slug     string  `json:"slug"`
	Name     string  `json:"name"`
	Kind     string  `json:"kind,omitempty"`
	Category string  `json:"category"`
	Rarity   int     `json:"rarity"`
	Price    float64 `json:"price"`
	HasPrice bool    `json:"hasPrice"`
	Summary  string  `json:"summary,omitempty"`
}

Good is one stockable entry of a package, read for a shop's fill.

func GoodsOf

func GoodsOf(sys System) (goods []Good, rarityLabel string)

GoodsOf reads the stockable entries a system's manifest names. A category that cannot be read is skipped, so one bad file never empties the fill.

type GoodsDef

type GoodsDef struct {
	// Category is a category slug of this manifest.
	Category string `json:"category"`
	// KindKey is the property that says what kind of good an entry is
	// ("Consumable", "Trinket"); Kinds keeps only those kinds. Both empty
	// takes every entry.
	KindKey string   `json:"kind_key,omitempty"`
	Kinds   []string `json:"kinds,omitempty"`
	// RarityKey is the property holding the entry's rarity, an ordinal such
	// as "2nd" (an echelon) or a number. Entries without one count as the
	// commonest.
	RarityKey string `json:"rarity_key,omitempty"`
	// RarityLabel is the word for that scale in the draft ("echelon"), so
	// the picker can say "1st echelon". Empty reads "rarity".
	RarityLabel string `json:"rarity_label,omitempty"`
	// PriceKey is the property holding a price in the campaign's main coin.
	// Absent, or an entry with no number there, means the entry has no
	// price and the Director sets one: Chronicle never invents a number.
	PriceKey string `json:"price_key,omitempty"`
}

GoodsDef is one category of a package that a shop may stock, named in the manifest's optional "goods" list. Chronicle never guesses what is for sale: a package says which category holds goods and which of its fields say what kind of good it is, how rare, and what it costs.

type GrantInput

type GrantInput struct {
	FieldKey string `json:"fieldKey"`
	UserID   string `json:"userId"`
	Budget   int    `json:"budget"`
}

GrantInput is the body of a Director giving a player the permission. Giving it again to the same player for the same list renews it.

type HeroBreak

type HeroBreak struct {
	FieldKey string `json:"fieldKey"`
	Value    string `json:"value"`
	Kind     string `json:"kind"`
	Reason   string `json:"reason,omitempty"`
}

HeroBreak is one rule a hero already breaks. Kind is "not_offered" (the entry is kept off the list) or "off_list" (a required short list does not include it).

type HeroWaitingPick

type HeroWaitingPick struct {
	ID        int64  `json:"id"`
	FieldKey  string `json:"fieldKey"`
	EntryName string `json:"entryName"`
}

HeroWaitingPick is one blank on a hero that waits for a Director.

type HostPlugin

type HostPlugin struct {
	// Slug is the plugin's canonical identifier as the reporting registry
	// spells it.
	Slug string

	// SchemaKey is the key the migration runner and health registry use, when
	// it differs from Slug. It DOES differ in practice — foundry_vtt registers
	// as `foundry-vtt` in the metadata registry and `foundry_vtt` in the schema
	// runner — so an operator grepping logs for one spelling will miss the
	// other. Empty when the two agree.
	SchemaKey string

	// InMetadataRegistry reports presence in App.registeredPlugins.
	InMetadataRegistry bool

	// HasHealthCheck reports whether the metadata registration carried a health
	// callback; HealthErr is that callback's result ("" = healthy or not run).
	HasHealthCheck bool
	HealthErr      string

	// StaticURLPrefix is where the plugin's embedded assets are served, "" when
	// it registered none. StaticFS is that filesystem, walked here for the
	// count and aggregate size.
	StaticURLPrefix string
	StaticFS        fs.FS

	// DeclaresMigrations reports whether the plugin handed a MigrationsFS to
	// the schema runner at startup.
	DeclaresMigrations bool

	// SchemaKnown is true when the migration health registry holds a record for
	// this plugin. Without it, SchemaHealthy false would advertise a failure
	// that was never observed.
	SchemaKnown   bool
	SchemaHealthy bool
	SchemaVersion int // highest APPLIED migration version
	SchemaLatest  int // highest AVAILABLE migration version
	SchemaError   string
}

HostPlugin is one plugin as the APP layer sees it, flattened for reporting.

Injected rather than imported for the same dependency inversion as EmbeddedAssetSet: internal/systems must not import internal/app or the plugin packages, so the app layer merges its registries and hands over plain data.

The fields deliberately keep the two registries APART instead of collapsing them into one "registered" boolean. Chronicle has a metadata registry (PluginRegistration — slug, health hook, StaticFS) and a schema registry (database.PluginSchema — migrations), they contain different plugins, and a row present in one and absent from the other is normal rather than broken.

type HouseChapter

type HouseChapter struct {
	CampaignID string
	SystemID   string
	ChapterID  string
	Title      string
	Intro      string
	Director   bool
	SortOrder  int
	CreatedBy  string
}

HouseChapter is one campaign_book_chapters row.

type HouseChapterDraft

type HouseChapterDraft struct {
	// Intro and Director are nil when the draft leaves them as they are.
	Intro    *string
	Director *bool
	// contains filtered or unexported fields
}

HouseChapterDraft is a checked chapter, ready to preview or write.

func ParseHouseChapterDraft

func ParseHouseChapterDraft(raw []byte, pkg *BookPackage) (*HouseChapterDraft, error)

ParseHouseChapterDraft reads and checks a chapter-file draft against the package's rules (its widgets, the book's block checks and limits).

func (*HouseChapterDraft) Blocks

func (d *HouseChapterDraft) Blocks() string

Blocks describes the draft's blocks in plain words, in the order they first appear: "1 highlighted box, 2 dice rolls". "" when only text.

func (*HouseChapterDraft) DirectorPages

func (d *HouseChapterDraft) DirectorPages() []bool

DirectorPages reports, per page in order, whether it is Directors-only.

func (*HouseChapterDraft) HasPages

func (d *HouseChapterDraft) HasPages() bool

HasPages reports whether the draft replaces the chapter's pages.

func (*HouseChapterDraft) HiddenParts

func (d *HouseChapterDraft) HiddenParts() int

HiddenParts counts the Director-only pages and blocks in the draft.

func (*HouseChapterDraft) PageTitles

func (d *HouseChapterDraft) PageTitles() []string

PageTitles lists the draft's page titles, in order.

type InboundSyncRecord

type InboundSyncRecord struct {
	EntityID string
	At       time.Time
	Source   string         // e.g. "fields" (UpdateEntityFields) / "entity"
	Fields   map[string]any // the field map received
}

InboundSyncRecord is one captured inbound sync payload (what an external client like the Foundry module sent), held in an in-memory ring buffer by syncapi.

type InstalledPackage

type InstalledPackage struct {
	Slug        string
	Version     string // the DB's installed_version
	InstallPath string // the version dir the last install wrote
}

InstalledPackage is the package-manager's view of one installed system, injected from the packages plugin via SetInstalledPackagesProvider (dependency inversion — systems must not import packages). Powers the installed-vs-loaded and on-disk-versions diagnostics.

type JSONProvider

type JSONProvider struct {
	// contains filtered or unexported fields
}

JSONProvider loads reference data from JSON files in a module's data directory. Each file corresponds to one category (e.g., spells.json → "spells" category). Files contain arrays of ReferenceItem objects. Data is loaded into memory at construction time and served read-only.

func NewJSONProvider

func NewJSONProvider(moduleID, dataDir string) (*JSONProvider, error)

NewJSONProvider scans dataDir for *.json files, loading each as a category of ReferenceItem objects. The filename stem becomes the category slug (e.g., "spells.json" → "spells"). Returns an error if the directory cannot be read or a JSON file is malformed.

func (*JSONProvider) Categories

func (p *JSONProvider) Categories() []string

Categories returns the list of available data category slugs, sorted.

func (*JSONProvider) Get

func (p *JSONProvider) Get(category string, id string) (*ReferenceItem, error)

Get returns a single reference item by category and ID (slug). Returns nil and no error if the item does not exist.

func (*JSONProvider) List

func (p *JSONProvider) List(category string) ([]ReferenceItem, error)

List returns all reference items in the given category. Returns an empty slice if the category does not exist.

func (*JSONProvider) Search

func (p *JSONProvider) Search(query string) ([]ReferenceItem, error)

Search returns reference items matching the query string across all categories. Matches case-insensitively against Name, Summary, and Tags.

type LayoutFact

type LayoutFact struct {
	Surface  string // "dashboard_layout" | "owner_dashboard_layout" | "entity type <name> — page template" | …
	Stored   bool   // the column is non-NULL and parsed
	ParseErr string
	Blocks   []string
}

LayoutFact is one placed layout and the block TYPES in it.

Blocks carries the types in placement order WITH duplicates, because "two skybox blocks" and "one skybox block" are different findings.

type LeftOut

type LeftOut struct {
	CampaignID string    `json:"-"`
	SystemID   string    `json:"-"`
	FieldKey   string    `json:"fieldKey"`
	Slug       string    `json:"slug"`
	Sentence   string    `json:"sentence"`
	CreatedBy  string    `json:"-"`
	CreatedAt  time.Time `json:"createdAt"`
}

LeftOut is a standard entry the campaign does not offer. Its name still answers everywhere, with the Director's sentence when there is one.

type LeftOutInput

type LeftOutInput struct {
	FieldKey string `json:"fieldKey"`
	Slug     string `json:"slug"`
	Sentence string `json:"sentence"`
}

LeftOutInput leaves a standard entry out, with an optional sentence.

type LoadEvent

type LoadEvent struct {
	Timestamp time.Time
	SystemID  string
	Name      string
	Kind      LoadEventKind
	Source    string // "bundled" or "package"
	Error     string // non-empty on failure
	Dir       string // filesystem path
}

LoadEvent records a single system loading event.

func DiagnosticEvents

func DiagnosticEvents() []LoadEvent

DiagnosticEvents returns all recorded system loading events.

type LoadEventKind

type LoadEventKind string

LoadEventKind categorizes a system loading event.

const (
	// EventDiscovered means the manifest was parsed and added to the registry.
	EventDiscovered LoadEventKind = "discovered"

	// EventInstantiated means the system was successfully instantiated.
	EventInstantiated LoadEventKind = "instantiated"

	// EventFailed means the system failed to load or instantiate.
	EventFailed LoadEventKind = "failed"

	// EventSkipped means a duplicate manifest (same system ID) was ignored
	// because an already-loaded copy was preferred — a newer version, or the
	// owning package overlay. Distinct from EventFailed: nothing went wrong,
	// the loader deliberately kept the better copy (WS-6).
	EventSkipped LoadEventKind = "skipped"
)

type MakeOwnCheck

type MakeOwnCheck func(ctx context.Context, campaignID, fieldKey, userID string) (bool, error)

MakeOwnCheck reports whether a player may write their own entry for a field. Like ChoiceSource it lets campaign entries plug in from outside.

type ManifestTerms

type ManifestTerms struct {
	// GM is what the game calls its game master, as a capitalised noun
	// ("Director" in Draw Steel, "DM" in D&D). The host uses it as is, so it
	// is also the badge on GM-only things and takes a plain "s" for plurals.
	GM string `json:"gm,omitempty"`
}

ManifestTerms are a system's names for Chronicle's roles. An empty field means the host's default.

type MarkView

type MarkView struct {
	State  string `json:"state"`
	Reason string `json:"reason,omitempty"`
}

MarkView is one stored mark as the Directors' screen shows it.

type MarksCheck

type MarksCheck struct {
	// Count is how many heroes would newly break.
	Count  int          `json:"count"`
	Heroes []BrokenHero `json:"heroes"`
}

MarksCheck is the dry run of a batch of marks.

type NamedRef

type NamedRef struct {
	Kind string
	Name string
}

NamedRef is one kind and name a page asks about.

type NotHere

type NotHere struct {
	Name   string `json:"name"`
	Reason string `json:"reason,omitempty"`
}

NotHere names an entry a rule keeps off the viewer's list, with the Director's reason. Only entries the viewer can read are ever named.

type PackageDesign

type PackageDesign struct {
	DesignDef
	Data json.RawMessage
}

PackageDesign is a design read from a package and validated.

func LoadPackageDesigns

func LoadPackageDesigns(ctx context.Context, m *SystemManifest, dir string, kinds DesignKindChecker) ([]PackageDesign, []string)

LoadPackageDesigns reads and validates a manifest's designs from the package directory dir. A design that fails is left out and named in the second result, so the diagnostics page can say why; the rest still load.

func PackageDesignsFor

func PackageDesignsFor(ctx context.Context, systemID string) ([]PackageDesign, []string)

PackageDesignsFor returns the validated designs of a loaded system and the reasons any were skipped. A system with none, or one that is not loaded, yields nothing.

type PeopleReader

type PeopleReader struct {
	UserID string
	Role   int
}

PeopleReader is who is looking, in the terms the character pages use: the account and its visibility role, so a page they may not see is never returned.

type PickerCheck

type PickerCheck struct {
	Name     string
	Title    string
	Hint     string // the catalog's arg hint, shown as the placeholder of a text blank
	Kind     ArgKind
	Optional bool // the text blank may stay empty
	FullDump bool // large; picking it is the explicit opt-in
}

PickerCheck is one check as the page lists it: a plain title for people, the catalog name, and the blank it needs.

type PickerGroup

type PickerGroup struct {
	ID     string
	Title  string
	Desc   string
	Checks []PickerCheck
}

PickerGroup is one fold of the hand-picking list.

func DiagnosticGroups

func DiagnosticGroups() []PickerGroup

DiagnosticGroups returns the catalog in its plain-word folds.

type PlanStatus

type PlanStatus string

PlanStatus classifies one planned call after validation against the catalog.

const (
	PlanOK          PlanStatus = "ok"               // known, runnable as requested
	PlanUnknown     PlanStatus = "unknown"          // no such diagnostic name
	PlanNeedsFull   PlanStatus = "blocked-fulldump" // full-dump diagnostic but full_dump:false
	PlanMissingName PlanStatus = "missing-name"     // empty name in the request
	PlanDuplicate   PlanStatus = "duplicate"        // identical (name,arg) already runs earlier
)

type PlannedCall

type PlannedCall struct {
	Name     string
	Arg      string
	Title    string
	Desc     string
	FullDump bool
	Status   PlanStatus
	Note     string // human reason for a non-OK status
}

PlannedCall is one row the operator reviews before approving. It carries the resolved title/desc so the review screen is self-explanatory.

func (PlannedCall) Runnable

func (p PlannedCall) Runnable() bool

Runnable reports whether this planned call will actually execute on approval.

type PlayDef

type PlayDef struct {
	// Edit is who may change the field during play: owner, gm or none.
	Edit string `json:"edit"`

	// Kind is counter, resource, conditions, choice or text.
	Kind string `json:"kind"`

	// Min and Max bound counter and resource values. Pointers so an explicit
	// 0 is distinguishable from absent.
	Min *float64 `json:"min,omitempty"`
	Max *float64 `json:"max,omitempty"`

	// MaxField names another number field in the same preset whose current
	// value is the upper bound; it wins over Max.
	MaxField string `json:"max_field,omitempty"`

	// Step is the size of one +/- nudge in the sheet.
	Step float64 `json:"step,omitempty"`

	// Options lists the allowed values for conditions and choice.
	Options []string `json:"options,omitempty"`

	// MaxLength bounds text and choice values.
	MaxLength int `json:"max_length,omitempty"`

	// ToFoundry overrides whether a play edit is written to Foundry. Nil
	// means follow the field's foundry_writable.
	ToFoundry *bool `json:"to_foundry,omitempty"`

	// CombatAuthority is foundry or chronicle; empty leaves it undecided.
	CombatAuthority string `json:"combat_authority,omitempty"`
}

PlayDef is the manifest's per-field play-controls declaration. It only DECLARES; the write guard and sheet controls that act on it live elsewhere.

type PlayerMark

type PlayerMark struct {
	UserID     string `json:"userId"`
	PlayerName string `json:"playerName"`
	MarkView
}

PlayerMark is a mark for one player.

type PowerRollRules

type PowerRollRules struct {
	Dice            string         `json:"dice"`
	Characteristics []CraftingStat `json:"characteristics"`
	Edge            int            `json:"edge"`
	Bane            int            `json:"bane"`
	Tiers           []int          `json:"tiers"`
}

PowerRollRules is a system's power roll as the Table offers it: the project roll's dice, characteristics, edge and bane and tier breaks, read from the crafting block so a system states the roll once.

type PresetPreview

type PresetPreview struct {
	Slug             string     `json:"slug"`
	Name             string     `json:"name"`
	NamePlural       string     `json:"name_plural"`
	Icon             string     `json:"icon"`
	Color            string     `json:"color"`
	Category         string     `json:"category,omitempty"`
	Fields           []FieldDef `json:"fields"`
	FoundryActorType string     `json:"foundry_actor_type,omitempty"`
}

PresetPreview summarizes an entity preset for the preview.

type PresetSwitchDef

type PresetSwitchDef struct {
	// Label names the fields in the owner's offer ("treasure fields").
	Label string `json:"label"`

	// Summary says in a few words what the switch adds, for the offer's
	// first line ("Type, Kind, Echelon, ..."). Absent: the field labels.
	Summary string `json:"summary,omitempty"`

	// SetAside are the category's own field keys the switch takes off every
	// page. Their values are kept, shown only to the GM, and come back if the
	// owner switches back.
	SetAside []string `json:"set_aside,omitempty"`

	// Reuse are keys the category and the preset share whose old values may
	// not fit the preset's field (a free-text Type becoming a pick list): a
	// value that isn't one of the preset field's options is set aside too.
	Reuse []string `json:"reuse,omitempty"`
}

PresetSwitchDef is how a preset takes over a category the campaign already has. Core keeps no game system's field names: the package lists them.

type PreviewResult

type PreviewResult struct {
	// Manifest is the parsed system manifest.
	Manifest *SystemManifest `json:"manifest"`

	// Report is the validation summary (counts, Foundry compat, warnings).
	Report *ValidationReport `json:"report"`

	// Categories lists each category with item counts and samples.
	Categories []CategoryPreview `json:"categories"`

	// EntityPresets lists each entity preset with field details.
	EntityPresets []PresetPreview `json:"entity_presets"`

	// Warnings are non-fatal issues discovered during preview.
	Warnings []string `json:"warnings,omitempty"`

	// Errors are fatal issues that would prevent installation.
	Errors []string `json:"errors,omitempty"`

	// TreeData is the hierarchical structure for the impact diagram.
	TreeData *TreeNode `json:"tree_data"`

	// TotalItems is the total reference data item count across all categories.
	TotalItems int `json:"total_items"`

	// Valid indicates whether installation would succeed.
	Valid bool `json:"valid"`
}

PreviewResult holds the complete analysis of a game system package. Used by both admin package approval and campaign owner upload flows.

func PreviewFromPackage

func PreviewFromPackage(installPath string) (*PreviewResult, error)

PreviewFromPackage inspects an already-downloaded package directory. Used by admin approval flow for packages fetched from GitHub.

func PreviewFromZIP

func PreviewFromZIP(zipData []byte) (*PreviewResult, error)

PreviewFromZIP validates a ZIP file and produces a full preview without writing to disk. The ZIP data is read entirely in memory.

type Probe

type Probe struct {
	ID      string
	Title   string
	Where   ProbeWhere
	Command string // may carry <placeholder> tokens the operator fills locally
	Why     string
}

Probe is one run-and-paste-back diagnostic command. Adding one is appending to defaultProbes (the modular property).

type ProbeWhere

type ProbeWhere string

ProbeWhere names where a probe command is run.

const (
	ProbeDocker  ProbeWhere = "docker"          // host shell, against the running containers
	ProbeConsole ProbeWhere = "browser-console" // DevTools console on the relevant page
	ProbeSQL     ProbeWhere = "sql"             // a DB query (run via the DB container)
	ProbeURL     ProbeWhere = "url"             // open an admin URL and copy the response
)

type ReadingRepository

type ReadingRepository interface {
	// SetStandsFor ties the entry to a standard slug with the snapshot, or
	// with standsFor "" unties it and drops the snapshot. A second stand-in
	// for the same standard entry is a conflict.
	SetStandsFor(ctx context.Context, campaignID string, id int64, standsFor, seen string) error
	// SetStandsForSeen replaces the snapshot of an entry that stays tied.
	SetStandsForSeen(ctx context.Context, campaignID string, id int64, seen string) error
	// FindStandIn returns the entry tied to the standard slug; nil when none.
	FindStandIn(ctx context.Context, campaignID, systemID, fieldKey, slug string) (*SystemEntry, error)

	// ListLeftOut returns the left-out standard entries of a field ("" = all).
	ListLeftOut(ctx context.Context, campaignID, systemID, fieldKey string) ([]LeftOut, error)
	// PutLeftOut leaves a standard entry out, or changes its sentence.
	PutLeftOut(ctx context.Context, l *LeftOut) error
	// DeleteLeftOut brings it back; false when it was not left out.
	DeleteLeftOut(ctx context.Context, campaignID, systemID, fieldKey, slug string) (bool, error)

	// ListOldNames returns the old names in a field ("" = all).
	ListOldNames(ctx context.Context, campaignID, systemID, fieldKey string) ([]EntryOldName, error)
	// FindOldName is a case-insensitive lookup; nil when no entry had it.
	FindOldName(ctx context.Context, campaignID, systemID, fieldKey, name string) (*EntryOldName, error)
	// AddOldName records a name an entry gave up. Recording one it already
	// holds is a no-op.
	AddOldName(ctx context.Context, n *EntryOldName) error
	// DeleteOldName frees an old name; false when there was none.
	DeleteOldName(ctx context.Context, campaignID string, id int64) (bool, error)

	// AddNote stores a line the players were told.
	AddNote(ctx context.Context, n *EntryNote) error
	// ListNotes returns an entry's lines, newest first, at most limit.
	ListNotes(ctx context.Context, campaignID string, entryID int64, limit int) ([]EntryNote, error)
	// NotedSince returns the entries the players were told about at or after
	// since, so a list can mark a recent change without reading each entry.
	NotedSince(ctx context.Context, campaignID string, since time.Time) (map[int64]bool, error)
}

ReadingRepository holds what lets a campaign read its game system in its own words: ties from a campaign entry to the standard entry it replaces, the standard entries left out, the old names of renamed entries and the lines the players were told. Every method is scoped by campaign.

type RecentError

type RecentError struct {
	Time           time.Time
	Status         int
	Method         string
	Path           string
	PathIsTemplate bool
	Kind           string // "app" | "http" | "raw" | "panic"
	Err            string
}

RecentError is one recorded server error as the diagnostics see it. It mirrors internal/observability.Entry rather than importing it, for the same dependency inversion as EmbeddedAssetSet: the app layer owns the wiring and internal/systems stays free of it. The duplication is four scalar fields and buys a package boundary that cannot cycle.

Note what is NOT here: no request body, no headers, no query string, no client IP, no user id. Path is a route TEMPLATE whenever the router matched one, because Chronicle routes `/rsvp/:token` and `/join/:code` and a concrete path would put a live credential into output meant to be pasted into a chat window.

type RecentErrors

type RecentErrors struct {
	// Capacity is the ring's fixed size.
	Capacity int
	// Held is how many entries it currently contains.
	Held int
	// Total is every error recorded since process start, INCLUDING entries
	// since evicted. Total > Held is the only signal that history was lost,
	// and the renderer must surface it — an operator reading a full-looking
	// window that silently dropped the first failure is back to guessing.
	Total uint64
	// Entries are the requested entries, NEWEST FIRST.
	Entries []RecentError
}

RecentErrors is a snapshot of the error ring plus the counters that make an empty result interpretable.

type ReferenceItem

type ReferenceItem struct {
	// ID is the unique identifier within this category. Some data sources key
	// items by "id" directly; others (the documented data contract — see
	// Chronicle-Draw-Steel docs/DATA-SCHEMA.md) key by "slug" and never set
	// this field in the source JSON. Call sites must use the normalized ID —
	// see Slug and JSONProvider's load-time normalization — not this field
	// as read directly off disk.
	ID string `json:"id"`

	// Slug is the source data's unique-identifier field for data contracts
	// that key by "slug" instead of "id" (e.g. the Draw Steel package data
	// files — DnD-5.5e's package data is 100% id-keyed and never sets this).
	// JSONProvider normalizes ID from this at load time when ID is empty;
	// read sites should never need to consult Slug directly.
	Slug string `json:"slug"`

	// Category is the content type slug (e.g., "spells", "monsters", "items").
	Category string `json:"category"`

	// Name is the human-readable display name.
	Name string `json:"name"`

	// Summary is a short one-line description for list views and search results.
	Summary string `json:"summary"`

	// Description is the full reference text (may contain markdown or HTML).
	Description string `json:"description,omitempty"`

	// Properties holds system-specific fields (e.g., spell level, monster CR,
	// item weight). Keys are lowercase snake_case.
	Properties map[string]any `json:"properties,omitempty"`

	// Tags are searchable labels (e.g., "evocation", "fire", "cantrip").
	Tags []string `json:"tags,omitempty"`

	// Source identifies where this data comes from (e.g., "SRD 5.1", "ORC").
	Source string `json:"source,omitempty"`

	// SystemID identifies which module owns this item.
	SystemID string `json:"system_id"`
}

ReferenceItem is the standard struct for all system reference data. It provides a uniform shape regardless of game system, with system-specific details in the Properties map.

type RelationFieldSchema

type RelationFieldSchema struct {
	Type    string `json:"type"`    // "number", "boolean", "string"
	Default any    `json:"default"` // Default value for new relations.
}

RelationFieldSchema defines a single metadata field on a relation preset.

type RelationPresetDef

type RelationPresetDef struct {
	// Slug is the URL-safe identifier (e.g., "has-item").
	Slug string `json:"slug"`

	// Name is the display name (e.g., "Has Item").
	Name string `json:"name"`

	// ReverseName is the reverse direction label (e.g., "In Inventory Of").
	ReverseName string `json:"reverse_name"`

	// MetadataSchema defines the JSON metadata fields for this relation.
	// Keys are field names, values describe type and default value.
	MetadataSchema map[string]RelationFieldSchema `json:"metadata_schema,omitempty"`
}

RelationPresetDef describes a relation type template that a module provides. Used to create system-specific relation types (e.g., "has-item" for inventory).

type RendererDef

type RendererDef struct {
	// Slug is the entity_type slug whose show page this renderer takes
	// over. Must equal one of the entity_presets[].slug values declared
	// in the same manifest. Exactly one of Slug or PresetCategory is set.
	Slug string `json:"slug,omitempty"`

	// PresetCategory binds this renderer by entity-type preset_category
	// instead of by slug — the system-agnostic seam. The widget then renders
	// ANY type carrying that preset (e.g. the player-character addon's category,
	// whose slug Chronicle owns), not just one bespoke slug. Must equal one of
	// the entity_presets[].category values in this manifest. Exactly one of
	// Slug or PresetCategory is set.
	PresetCategory string `json:"preset_category,omitempty"`

	// Widget is the slug of the JS widget that should mount when an
	// entity of the matching type is rendered. Must equal one of the
	// widgets[].slug values declared in the same manifest.
	Widget string `json:"widget"`

	// Description is an optional human-readable note (shown in admin UI
	// or debug logs only — does not affect runtime behavior).
	Description string `json:"description,omitempty"`
}

RendererDef binds an entity_type slug to the widget that should render its show page. The slug must match a slug declared in this manifest's entity_presets list, and the widget must be declared in this manifest's widgets list — these constraints keep a manifest's renderers contained to its own contributions and prevent silent drift if a preset or widget is renamed.

type RequestView

type RequestView struct {
	ID        int64  `json:"id"`
	EntryName string `json:"entryName"`
	EntityID  string `json:"entityId,omitempty"`
	// Message is the Director's note on a suggested request.
	Message   string    `json:"message,omitempty"`
	CreatedAt time.Time `json:"createdAt"`
}

RequestView is a request as the player who made it reads it.

type Resolution

type Resolution struct {
	// Kind is one of the Resolved* values.
	Kind string `json:"kind"`
	// Entry is the entry to show, the redirect's target, or the left-out
	// entry's content; nil when not found.
	Entry *CatalogEntry `json:"entry,omitempty"`
	// Slug is the address to go to on a redirect.
	Slug string `json:"slug,omitempty"`
	// Via says why a redirect leads elsewhere (Via* values).
	Via string `json:"via,omitempty"`
}

Resolution is what one address or one name means for a reader.

type RewriteInput

type RewriteInput struct {
	FieldKey string `json:"fieldKey"`
	Slug     string `json:"slug"`
	Name     string `json:"name"`
}

RewriteInput names the standard entry to copy. Name is optional and gives the copy another name, for when the campaign already has an entry called the standard entry's name and wants a fresh copy beside it.

type RouteFact

type RouteFact struct {
	Method  string
	Path    string
	Handler string
}

RouteFact is one row of the LIVE Echo route table.

Handler is Echo's own handler name (the runtime function name), which is what makes `campaign.surfaces` a measurement rather than an assertion: the surface map below declares which handler should serve each path, and a disagreement is printed.

type RulesCatalog

type RulesCatalog interface {
	Catalog(ctx context.Context, campaignID, category string, reader EntryActor) (*CatalogList, error)
	ResolveAddress(ctx context.Context, campaignID, category, slug string, printed bool, reader EntryActor) (*Resolution, error)
	ResolveName(ctx context.Context, campaignID, category, name string, reader EntryActor) (*Resolution, error)
	ResolveNames(ctx context.Context, campaignID, category string, names []string, reader EntryActor) ([]*Resolution, error)
	Notes(ctx context.Context, campaignID string, actor EntryActor, entryID int64) ([]EntryNote, error)
	OldNames(ctx context.Context, campaignID, fieldKey string, actor EntryActor) ([]EntryOldName, error)
	LeftOutList(ctx context.Context, campaignID, fieldKey string) ([]LeftOut, error)
	Rewritable(ctx context.Context, campaignID, fieldKey, slug string) (bool, error)
	StandardChange(ctx context.Context, campaignID string, actor EntryActor, id int64) (string, error)
}

RulesCatalog is the part of the system entry service the reader's pages draw on. SystemEntryService satisfies it.

type RulesHit

type RulesHit struct {
	Slug     string
	Name     string
	Category string
	Summary  string
	URL      string
	// Kind is "entry", "trait" (Name is the trait, EntryName its entry) or
	// "left_out" (Summary is the one line).
	Kind      string
	EntryName string
	// Whose is "Rewritten" on a rewritten entry.
	Whose string
}

RulesHit is one search answer.

type RulesListView

type RulesListView struct {
	CampaignID   string
	CampaignName string
	SystemID     string
	Category     CategoryDef
	CategoryURL  string
	// Count is the number of entries the reader has, counted from the list.
	Count int
	Rows  []listRow
	// LeftOut ends the list: the left-out entries with a sentence, and for
	// the Director every left-out one.
	LeftOut    []listRow
	Query      string
	Filterable bool
	IsDirector bool
}

RulesListView is a category's page as one reader has it.

type RulesPages

type RulesPages struct {
	// contains filtered or unexported fields
}

RulesPages builds what a reader sees of a rules category: its list, an entry's page and peek, its hover card and search hits. Every answer is drawn from the per-reader catalog, so who sees which entry, where a rewritten or old name leads and what a left-out name says are decided in one place (entry_catalog.go) and never again here or in a handler. A system other than the campaign's own has no campaign overlay: its entries are read straight from the package.

func NewRulesPages

func NewRulesPages(catalog RulesCatalog, manifest EntryManifestResolver, people EntryPeople) *RulesPages

NewRulesPages wires the builder. Any argument may be nil: without the catalog or the manifest resolver every system reads as its package, and without people no page draws "In <campaign>" or a peek's hero.

func (*RulesPages) Before

func (p *RulesPages) Before(ctx context.Context, sys System, r RulesReader) (*BeforeView, error)

Before builds the gathered page. Only the campaign's own system has one.

func (*RulesPages) BookKind

func (p *RulesPages) BookKind(ctx context.Context, sys System, category string, r RulesReader) (*CatalogList, error)

BookKind is the catalog a book reads a category from, for one reader.

func (*RulesPages) KindData

func (p *RulesPages) KindData(ctx context.Context, sys System, category string, raw []byte, r RulesReader) (out []byte, handled bool, err error)

KindData answers a data file for one reader. handled is false when the file is not a kind of the campaign's own system, and the caller serves it as is.

func (*RulesPages) List

func (p *RulesPages) List(ctx context.Context, sys System, category, q string, r RulesReader) (*RulesListView, error)

List builds a category's page; q narrows the rows by name or line.

func (*RulesPages) NamedAddress

func (p *RulesPages) NamedAddress(ctx context.Context, sys System, kind, name string, r RulesReader) (string, error)

NamedAddress is the own address of the entry a kind and a name lead to for the reader; a left-out name's address answers with its one line.

func (*RulesPages) Page

func (p *RulesPages) Page(ctx context.Context, sys System, category, slug string, printed bool, r RulesReader) (*EntryView, error)

Page builds an entry's page. A redirect answers with only Redirect set; a name nobody may see here is not found.

func (*RulesPages) Peek

func (p *RulesPages) Peek(ctx context.Context, sys System, category, slug string, printed bool, heroID string, r RulesReader) (*EntryView, error)

Peek builds an entry's peek. A redirect is followed in place, since the panel fetches it; with a hero the reader may see and who is of this entry, it names the traits that hero holds.

func (*RulesPages) PeekNamed

func (p *RulesPages) PeekNamed(ctx context.Context, sys System, kind, name, heroID string, r RulesReader) (*EntryView, error)

PeekNamed is the peek of the entry a kind and a name lead to.

func (*RulesPages) Search

func (p *RulesPages) Search(ctx context.Context, sys System, query string, r RulesReader) ([]RulesHit, error)

Search finds entries of every category the reader may read. In the campaign's own kinds it searches the reader's list: an entry by its name, an old name or any of its traits' names, and a left-out name answers with its one line. Other categories keep the package's own search.

func (*RulesPages) Told

func (p *RulesPages) Told(ctx context.Context, sys System, refs []NamedRef, r RulesReader) ([]NamedRef, error)

Told returns the refs whose entry, for this reader, carries a change the players were told about lately. A name the reader cannot reach is simply not told, so the answer gives nothing away. The names of one kind are resolved against one reading, so a sheet's question costs the same few reads however many names it asks about.

func (*RulesPages) Tooltip

func (p *RulesPages) Tooltip(ctx context.Context, sys System, category, slug string, printed bool, r RulesReader) (*RulesTip, error)

Tooltip resolves one address for a hover card: a rewritten or old name shows the entry it leads to, a left-out name its one line.

type RulesReader

type RulesReader struct {
	CampaignID   string
	CampaignName string
	Actor        EntryActor
	// Role is the reader's visibility role for character pages.
	Role int
}

RulesReader is who is reading, as the handler knows them.

type RulesTerm

type RulesTerm struct {
	Name     string `json:"name"`
	Category string `json:"category"`
	Text     string `json:"text"`
}

RulesTerm is one rules word as the hero builder shows it: the name, the kind of word it is (condition, movement, ...) and a plain-text meaning.

type RulesTerms

type RulesTerms struct {
	Terms   map[string]RulesTerm
	Present bool
}

RulesTerms are a campaign system's rules words, keyed the way the builder looks them up (NormalizeTermKey). Present is false when the system has no Rules book glossary, so a caller can leave out the feature entirely.

func LoadRulesTerms

func LoadRulesTerms(sysDir string, m *SystemManifest) (*RulesTerms, error)

LoadRulesTerms reads the glossary the system's Rules book names (the book.yaml `glossary:` data file). A system with no book or no glossary answers Present=false with no error; a glossary that is declared but broken is an error, as it is for the book itself. Entries in a Director-only category are left out: the builder serves players, and a hover word must never carry what the Director keeps back.

type RulesTip

type RulesTip struct {
	Entry CatalogEntry
	URL   string
	// LeftOut marks a left-out name; Line is then its one line.
	LeftOut bool
	Line    string
	// Whose is the whose-words line for a rewritten entry.
	Whose string
}

RulesTip is what a hover card shows for one address.

type ShopTestDCDef

type ShopTestDCDef struct {
	Easy  int `json:"easy,omitempty"`
	Usual int `json:"usual,omitempty"`
	Hard  int `json:"hard,omitempty"`
}

ShopTestDCDef is the three difficulties of the dc style. Zero means the default (10, 15, 20).

type ShopTestRulesView

type ShopTestRulesView struct {
	Dice   string            `json:"dice"`
	Style  string            `json:"style"`
	Stats  []ShopTestStatDef `json:"stats"`
	Haggle string            `json:"haggle"`
	Look   string            `json:"look"`
	Tiers  []int             `json:"tiers"`
	Edge   int               `json:"edge"`
	Bane   int               `json:"bane"`
	DC     ShopTestDCDef     `json:"dc"`
}

ShopTestRulesView is a shop test with every part decided, so callers never check for a missing piece.

func DefaultShopTestRules

func DefaultShopTestRules() ShopTestRulesView

DefaultShopTestRules is the test of a campaign whose system declares neither shop_tests nor crafting: a d20 against a DC, adding nothing from the sheet, since no stat is known to be on it.

type ShopTestStatDef

type ShopTestStatDef struct {
	Key   string `json:"key"`
	Label string `json:"label"`
	Score bool   `json:"score,omitempty"`
}

ShopTestStatDef is one sheet number a shop test may add. Score marks a D&D style ability score, where the test adds the modifier floor((value-10)/2) rather than the value itself.

type ShopTestsDef

type ShopTestsDef struct {
	Dice   string            `json:"dice,omitempty"`
	Style  string            `json:"style,omitempty"`
	Stats  []ShopTestStatDef `json:"stats,omitempty"`
	Haggle string            `json:"haggle,omitempty"`
	Look   string            `json:"look,omitempty"`
	Tiers  []int             `json:"tiers,omitempty"`
	Edge   *int              `json:"edge,omitempty"`
	Bane   *int              `json:"bane,omitempty"`
	DC     *ShopTestDCDef    `json:"dc,omitempty"`
}

ShopTestsDef is the manifest's optional shop_tests block: the dice a player throws at a shop's counter to haggle or look closer, what the throw adds, and how the total reads. Every part is optional; ShopTestRules fills what is missing. Edge and Bane are pointers so a written 0 stays distinct from "not written".

type SidebarItemFact

type SidebarItemFact struct {
	Type    string
	Slug    string
	Label   string
	URL     string
	Visible bool
}

SidebarItemFact is one item from `campaigns.sidebar_config`.

type StandardSnapshot

type StandardSnapshot struct {
	Name        string         `json:"name"`
	Summary     string         `json:"summary"`
	Description string         `json:"description"`
	Properties  map[string]any `json:"properties"`
}

StandardSnapshot is a standard entry's words and figures at one moment, kept on its stand-in so a later package change can be described.

type StandardSystemResolver

type StandardSystemResolver func(ctx context.Context, campaignID string) System

StandardSystemResolver returns the game system whose entries a campaign's entries stand beside (the one EntryManifestResolver names), or nil.

func StandardSystemFor

func StandardSystemFor(custom *CampaignSystemManager, manifest EntryManifestResolver) StandardSystemResolver

StandardSystemFor resolves the system a campaign's entries were made under to its loaded package: the campaign's custom upload when that is the one, else the built-in system of that id.

type Status

type Status string

Status represents the implementation status of a module.

const (
	// StatusAvailable means the module is fully implemented and ready to enable.
	StatusAvailable Status = "available"

	// StatusComingSoon means the module is planned but not yet implemented.
	StatusComingSoon Status = "coming_soon"
)

type StoredBookPage

type StoredBookPage struct {
	ID           int64
	CampaignID   string
	SystemID     string
	ChapterID    string
	PackageIndex *int // nil: a page the campaign added
	SortOrder    int
	PageJSON     string
	BaseHash     string // "" when NULL
	UpdatedBy    string
}

StoredBookPage is one campaign_book_pages row.

type StoredLook

type StoredLook struct {
	Border string
	Colour string
}

StoredLook is one campaign_card_looks row as the choice list reads it. Border "" means "no border"; Colour "" means "the border's own colour".

type SyncMappingInfo

type SyncMappingInfo struct {
	ExternalSystem string
	ExternalID     string
	ChronicleType  string
	ChronicleID    string
	LastSync       string
}

SyncMappingInfo is one Foundry↔Chronicle sync link for the entity.sync-mappings diagnostic.

type System

type System interface {
	// Info returns the module's manifest metadata.
	Info() *SystemManifest

	// DataProvider returns the module's reference data provider, or nil
	// if the system has no data loaded yet (coming_soon modules).
	DataProvider() DataProvider

	// TooltipRenderer returns the module's tooltip renderer, or nil
	// if the module has no tooltip templates yet.
	TooltipRenderer() TooltipRenderer
}

System is the sandboxed interface that every game system content pack must implement. It provides metadata, reference data access, and tooltip rendering without any access to Chronicle's infrastructure.

func AllSystems

func AllSystems() []System

AllSystems returns all live System instances, for iteration. Only includes modules that have been successfully instantiated.

func FindSystem

func FindSystem(id string) System

FindSystem returns the live System instance for a given module ID, or nil if not found or not yet instantiated. Only modules with status "available" have live instances.

type SystemDiagnostics

type SystemDiagnostics struct {
	// SystemFound is true if any game system is enabled or custom-uploaded.
	SystemFound bool
	Manifest    *SystemManifest

	// Source is "builtin", "custom", or "package".
	Source string

	// Category item counts.
	Categories []DiagCategory

	// Entity types derived from this system's presets.
	EntityTypes []DiagEntityType

	// Total reference data items.
	TotalItems int

	// Foundry compatibility.
	FoundrySystemID string
	MappedFields    int
	TotalFields     int

	// Validation warnings.
	Warnings []string
}

SystemDiagnostics holds all data for the diagnostics page.

type SystemEntry

type SystemEntry struct {
	ID         int64  `json:"id"`
	CampaignID string `json:"campaignId"`
	SystemID   string `json:"systemId"`
	// FieldKey is the character field the entry is offered for ("ancestry").
	FieldKey string `json:"fieldKey"`
	// Slug is derived from the name once and never changes, so a rename does
	// not break anything that remembers the entry.
	Slug        string `json:"slug"`
	Name        string `json:"name"`
	Summary     string `json:"summary"`
	Description string `json:"description"`
	// Properties holds kind-specific details (size, speed...) as a flat object
	// of scalars, so every consumer can render a value without a schema.
	Properties map[string]any `json:"properties"`
	Visibility string         `json:"visibility"`
	// ForEntityID is the character page a 'character' entry is kept to;
	// empty for every other visibility.
	ForEntityID string `json:"forEntityId,omitempty"`
	// ForName is that character's name, filled for Directors on read so a
	// list can say who an entry is for. Not stored.
	ForName string `json:"forName,omitempty"`
	// Status is EntryStatusAccepted, or draft/sent for a player's entry a
	// Director has not accepted yet.
	Status string `json:"status"`
	// ReviewNote is what a Director asked the writer to change.
	ReviewNote string `json:"reviewNote,omitempty"`
	// StandsFor is the slug of the standard entry (same system and field)
	// this entry takes the place of, set only by a Director's tie; empty for
	// an entry the campaign wrote beside the package.
	StandsFor string `json:"standsFor,omitempty"`
	// StandsForSeen is the standard entry as it was when tied or last marked
	// seen (a StandardSnapshot as JSON). Directors read it through the
	// service; it never leaves in a list.
	StandsForSeen string `json:"-"`
	// StandsForName is the standard entry's name as the snapshot holds it,
	// so the entry editor can say whose words players still read.
	StandsForName string    `json:"standsForName,omitempty"`
	CreatedBy     string    `json:"createdBy,omitempty"`
	CreatedAt     time.Time `json:"createdAt"`
	UpdatedAt     time.Time `json:"updatedAt"`
}

SystemEntry is one campaign-made pick-list entry.

type SystemEntryHandler

type SystemEntryHandler struct {
	// contains filtered or unexported fields
}

SystemEntryHandler serves a campaign's own pick-list entries as JSON. It only binds, calls the service and renders; the Director rule is enforced by the service, with this handler stating who is asking.

func NewSystemEntryHandler

func NewSystemEntryHandler(svc SystemEntryService) *SystemEntryHandler

NewSystemEntryHandler creates the handler.

func (*SystemEntryHandler) AddNoteAPI

func (h *SystemEntryHandler) AddNoteAPI(c *echo.Context) error

AddNoteAPI records a line the players were told about an entry.

POST /campaigns/:id/system-entries/:entryId/notes {"line": "..."}

func (*SystemEntryHandler) BringBackAPI

func (h *SystemEntryHandler) BringBackAPI(c *echo.Context) error

BringBackAPI offers a left-out standard entry again.

DELETE /campaigns/:id/system-entries/left-out/:fieldKey/:slug

func (*SystemEntryHandler) CreateAPI

func (h *SystemEntryHandler) CreateAPI(c *echo.Context) error

CreateAPI adds an entry.

POST /campaigns/:id/system-entries

func (*SystemEntryHandler) DeleteAPI

func (h *SystemEntryHandler) DeleteAPI(c *echo.Context) error

DeleteAPI removes an entry. Characters that picked it keep the name they stored.

DELETE /campaigns/:id/system-entries/:entryId

func (*SystemEntryHandler) FreeOldNameAPI

func (h *SystemEntryHandler) FreeOldNameAPI(c *echo.Context) error

FreeOldNameAPI lets another entry take an old name.

DELETE /campaigns/:id/system-entries/old-names/:nameId

func (*SystemEntryHandler) GrantAPI

func (h *SystemEntryHandler) GrantAPI(c *echo.Context) error

GrantAPI lets a player make their own entry for a pick list, or renews the permission.

POST /campaigns/:id/system-entries/grants

func (*SystemEntryHandler) GrantsAPI

func (h *SystemEntryHandler) GrantsAPI(c *echo.Context) error

GrantsAPI lists the permissions to write an entry: every one for a Director, the caller's own for a player.

GET /campaigns/:id/system-entries/grants

func (*SystemEntryHandler) LeaveOutAPI

func (h *SystemEntryHandler) LeaveOutAPI(c *echo.Context) error

LeaveOutAPI leaves a standard entry out, or changes its sentence.

PUT /campaigns/:id/system-entries/left-out

func (*SystemEntryHandler) ListAPI

func (h *SystemEntryHandler) ListAPI(c *echo.Context) error

ListAPI returns the campaign's entries; a Director also sees the Directors-only ones.

GET /campaigns/:id/system-entries?fieldKey=ancestry

func (*SystemEntryHandler) RevokeGrantAPI

func (h *SystemEntryHandler) RevokeGrantAPI(c *echo.Context) error

RevokeGrantAPI takes a permission back.

DELETE /campaigns/:id/system-entries/grants/:grantId

func (*SystemEntryHandler) RewriteAPI

func (h *SystemEntryHandler) RewriteAPI(c *echo.Context) error

RewriteAPI copies a standard entry into a new Directors-only campaign entry tied to it.

POST /campaigns/:id/system-entries/rewrite

func (*SystemEntryHandler) SeenAPI

func (h *SystemEntryHandler) SeenAPI(c *echo.Context) error

SeenAPI marks the package's change to the standard entry as seen.

POST /campaigns/:id/system-entries/:entryId/seen

func (*SystemEntryHandler) TieAPI

func (h *SystemEntryHandler) TieAPI(c *echo.Context) error

TieAPI lets an existing campaign entry take a standard entry's place.

POST /campaigns/:id/system-entries/:entryId/tie {"slug": "dwarf"}

func (*SystemEntryHandler) UntieAPI

func (h *SystemEntryHandler) UntieAPI(c *echo.Context) error

UntieAPI makes a tied entry the campaign's own again.

DELETE /campaigns/:id/system-entries/:entryId/tie

func (*SystemEntryHandler) UpdateAPI

func (h *SystemEntryHandler) UpdateAPI(c *echo.Context) error

UpdateAPI changes an entry. The body is a partial update: absent keys keep their value, null clears, a value replaces. When the save removed or altered a trait a hero holds, the answer also carries "tellPlayers": who holds it and a suggested line, for the editor to ask once.

PUT /campaigns/:id/system-entries/:entryId

type SystemEntryRepository

type SystemEntryRepository interface {
	// List returns the entries for a system, optionally for one field key
	// ("" = all), ordered by name. includeDirectors false hides 'directors'
	// entries but keeps 'character' ones, which the service filters by who
	// plays the character.
	List(ctx context.Context, campaignID, systemID, fieldKey string, includeDirectors bool) ([]SystemEntry, error)
	// Get returns one entry; apperror not-found when absent.
	Get(ctx context.Context, campaignID string, id int64) (*SystemEntry, error)
	// FindByName is a case-insensitive name lookup within one field; nil when
	// there is none.
	FindByName(ctx context.Context, campaignID, systemID, fieldKey, name string) (*SystemEntry, error)
	// SlugExists reports whether the slug is taken in the field.
	SlugExists(ctx context.Context, campaignID, systemID, fieldKey, slug string) (bool, error)
	// Count returns how many entries a field has.
	Count(ctx context.Context, campaignID, systemID, fieldKey string) (int, error)
	// Create inserts the entry and fills its id; a duplicate slug is a conflict.
	Create(ctx context.Context, e *SystemEntry) error
	// Update replaces the editable columns of an existing entry.
	Update(ctx context.Context, e *SystemEntry) error
	// Delete removes an entry; false when there was none.
	Delete(ctx context.Context, campaignID string, id int64) (bool, error)

	// ListGrants returns a system's permissions, for one player when userID
	// is set, ordered by field.
	ListGrants(ctx context.Context, campaignID, systemID, userID string) ([]EntryGrant, error)
	// FindGrant returns one player's permission for a field; nil when none.
	FindGrant(ctx context.Context, campaignID, systemID, fieldKey, userID string) (*EntryGrant, error)
	// PutGrant gives the permission, or renews it (unspent, with the new
	// budget) when the player already had one for the field.
	PutGrant(ctx context.Context, g *EntryGrant) error
	// DeleteGrant takes a permission back; false when there was none.
	DeleteGrant(ctx context.Context, campaignID string, id int64) (bool, error)
	// ClaimGrant marks an unspent permission as being used, so two saves at
	// once cannot both use it; false when it was already spent.
	ClaimGrant(ctx context.Context, campaignID string, id int64) (bool, error)
	// SetGrantEntry records the entry a claimed permission made, or with
	// entryID 0 releases the claim after a failed save.
	SetGrantEntry(ctx context.Context, campaignID string, id, entryID int64) error

	// The ties, left-out lists, old names and notes live beside the entries
	// (system_entries_reading_repository.go).
	ReadingRepository
}

SystemEntryRepository is the data access contract for a campaign's own pick-list entries. Every method is scoped by campaign, so one campaign can never read or write another's rows by guessing an id.

func NewSystemEntryRepository

func NewSystemEntryRepository(db *sql.DB) SystemEntryRepository

NewSystemEntryRepository creates the MariaDB-backed repository.

type SystemEntryService

type SystemEntryService interface {
	// List returns the campaign's entries (all fields when fieldKey is "").
	// Non-Directors never receive 'directors' entries.
	List(ctx context.Context, campaignID, fieldKey string, actor EntryActor) ([]SystemEntry, error)
	// FindByName looks an entry up by field and name; nil when absent or not
	// visible to the actor.
	FindByName(ctx context.Context, campaignID, fieldKey, name string, actor EntryActor) (*SystemEntry, error)
	Create(ctx context.Context, campaignID string, actor EntryActor, in CreateSystemEntryInput) (*SystemEntry, error)
	// CheckCreate runs every validation Create would, without writing, so a
	// review screen can refuse a bad entry before anything is committed.
	CheckCreate(ctx context.Context, campaignID string, actor EntryActor, in CreateSystemEntryInput) error
	Update(ctx context.Context, campaignID string, actor EntryActor, id int64, in UpdateSystemEntryInput) (*SystemEntry, error)
	// UpdateTelling is Update for the entry editor: beside the saved entry
	// it returns the question to ask the Director when the save removed or
	// altered a trait a hero holds (system_entries_tell.go), else nil. role
	// is the actor's visibility role, for which heroes they may see.
	UpdateTelling(ctx context.Context, campaignID string, actor EntryActor, role int, id int64, in UpdateSystemEntryInput) (*SystemEntry, *TellQuestion, error)
	// Delete removes the entry only. Characters keep the name they stored.
	Delete(ctx context.Context, campaignID string, actor EntryActor, id int64) error
	// Choices is the ChoiceSource body: the entries this viewer may see
	// (ChoiceViewerIsDirector, ChoiceViewerUser), shaped for the picker.
	Choices(ctx context.Context, campaignID, fieldKey string) ([]Choice, error)
	// FindCharacter returns the campaign's character page with this name, for
	// callers that name the character an entry is kept to; nil when none.
	FindCharacter(ctx context.Context, campaignID, name string) (*EntryCharacter, error)

	// Grants returns the permissions to write an entry: all of them for a
	// Director, a player's own otherwise.
	Grants(ctx context.Context, campaignID string, actor EntryActor) ([]EntryGrant, error)
	// Grant lets a player write one entry of their own for a pick list, or
	// renews the permission. Directors only.
	Grant(ctx context.Context, campaignID string, actor EntryActor, in GrantInput) (*EntryGrant, error)
	// RevokeGrant takes a permission back; the player can then no longer
	// edit a draft they made with it. Directors only.
	RevokeGrant(ctx context.Context, campaignID string, actor EntryActor, id int64) error
	// CanMake reports whether the user holds an unspent permission for the
	// field, so a pick list can offer "make your own".
	CanMake(ctx context.Context, campaignID, fieldKey, userID string) (bool, error)

	// EntryReading is how the campaign reads the standard entries in its own
	// words: ties, left-out entries, old names and notes
	// (system_entries_reading.go).
	EntryReading
	// SetCardLook sets or clears the card border and colour of one ACCEPTED
	// entry, as a Director's change; nothing else on the entry changes.
	SetCardLook(ctx context.Context, campaignID string, actor EntryActor, id int64, border, colour string) (*SystemEntry, error)
	// EntryCatalog is the one per-reader list every consumer draws on
	// (entry_catalog.go).
	EntryCatalog
}

SystemEntryService owns the rules for a campaign's own pick-list entries. It never sees a request: callers say who is asking through EntryActor, and the service refuses every write unless that is a Director, or a player a Director gave the permission to write their own entry (EntryGrant), so a handler that forgets its own check still cannot let a player write.

func NewSystemEntryService

func NewSystemEntryService(repo SystemEntryRepository, manifest EntryManifestResolver, opts ...EntryServiceOption) SystemEntryService

NewSystemEntryService wires the service to its repository and to the resolver that says which system a campaign plays.

type SystemHandler

type SystemHandler struct {
	// contains filtered or unexported fields
}

SystemHandler serves reference pages and JSON API endpoints for any system. It checks both global built-in systems and per-campaign custom systems uploaded by campaign owners.

func NewSystemHandler

func NewSystemHandler() *SystemHandler

NewSystemHandler creates a new system handler.

func (*SystemHandler) BeforeYouPlay

func (h *SystemHandler) BeforeYouPlay(c *echo.Context) error

BeforeYouPlay is "Before you play in <campaign>": what the campaign wrote, rewrote and left out, as the reader may see it. GET /campaigns/:id/systems/:mod/before-you-play

func (*SystemHandler) BookAPI

func (h *SystemHandler) BookAPI(c *echo.Context) error

BookAPI serves the system's Rulebook book, checked and filtered for the viewer: Directors (the owner, or a member with Director visibility) get everything, players only the player view (FilterBook), and a Director who passes ?view=player gets what a player gets. Never cached shared, since the body depends on who asks.

GET /campaigns/:id/systems/:mod/book

func (*SystemHandler) BookChapterCreate

func (h *SystemHandler) BookChapterCreate(c *echo.Context) error

BookChapterCreate adds a house-rules chapter.

POST /campaigns/:id/systems/:mod/book/chapters

func (*SystemHandler) BookChapterDelete

func (h *SystemHandler) BookChapterDelete(c *echo.Context) error

BookChapterDelete removes a house-rules chapter and its pages.

DELETE /campaigns/:id/systems/:mod/book/chapters/:chapter

func (*SystemHandler) BookChapterUpdate

func (h *SystemHandler) BookChapterUpdate(c *echo.Context) error

BookChapterUpdate is a partial update of a house-rules chapter: only the keys sent change.

PUT /campaigns/:id/systems/:mod/book/chapters/:chapter

func (*SystemHandler) BookEditPage

func (h *SystemHandler) BookEditPage(c *echo.Context) error

BookEditPage renders the full-screen editor.

GET /campaigns/:id/systems/:mod/book/edit

func (*SystemHandler) BookEntryAPI

func (h *SystemHandler) BookEntryAPI(c *echo.Context) error

BookEntryAPI returns one rules-index entry, for a name in the book's text that opens its entry in place, with the chapter and page that list it and the page's title. Only an entry a page of the viewer's own book lists is served, as BookIndexAPI. GET /campaigns/:id/systems/:mod/book/entry/:cat/:entry

func (*SystemHandler) BookExport

func (h *SystemHandler) BookExport(c *echo.Context) error

BookExport downloads the campaign's edition as the package's own file format, ready to drop into a package's book/ folder.

GET /campaigns/:id/systems/:mod/book/export

func (*SystemHandler) BookFileAPI

func (h *SystemHandler) BookFileAPI(c *echo.Context) error

BookFileAPI serves one cover or font file the book declares, behind the same access checks as the book itself. The SVG cover is drawn by an <img>, where scripts never run; the sandbox policy keeps it inert if someone opens the address directly, and nosniff stops a font being read as anything else.

GET /campaigns/:id/systems/:mod/book/files/:name

func (*SystemHandler) BookFindAPI

func (h *SystemHandler) BookFindAPI(c *echo.Context) error

BookFindAPI searches the rules-index chapters the viewer's book shows. GET /campaigns/:id/systems/:mod/book/find?q=

func (*SystemHandler) BookIndexAPI

func (h *SystemHandler) BookIndexAPI(c *echo.Context) error

BookIndexAPI returns the entries one rules-index page shows. The query must name a slice a page of the viewer's own book shows, so a player can only list what their book lists (Director-only chapters are already gone). GET /campaigns/:id/systems/:mod/book/index/:cat?key=&value=&from=&to=

func (*SystemHandler) BookPageAdd

func (h *SystemHandler) BookPageAdd(c *echo.Context) error

BookPageAdd appends a page of the campaign's own to a chapter.

POST /campaigns/:id/systems/:mod/book/chapters/:chapter/pages

func (*SystemHandler) BookPageDelete

func (h *SystemHandler) BookPageDelete(c *echo.Context) error

BookPageDelete drops the campaign's copy of a package page, or deletes a page the campaign added.

DELETE /campaigns/:id/systems/:mod/book/chapters/:chapter/pages/:key

func (*SystemHandler) BookPageKeep

func (h *SystemHandler) BookPageKeep(c *echo.Context) error

BookPageKeep settles a page the package changed after the campaign edited it, in favour of the campaign's copy.

POST /campaigns/:id/systems/:mod/book/chapters/:chapter/pages/:key/keep

func (*SystemHandler) BookPageSave

func (h *SystemHandler) BookPageSave(c *echo.Context) error

BookPageSave replaces a page's content.

PUT /campaigns/:id/systems/:mod/book/chapters/:chapter/pages/:key

func (*SystemHandler) BookSourceAPI

func (h *SystemHandler) BookSourceAPI(c *echo.Context) error

BookSourceAPI is the editor's starting state: the merged edition with every page's state and the package's own page where it differs.

GET /campaigns/:id/systems/:mod/book/source

func (*SystemHandler) Browse

func (h *SystemHandler) Browse(c *echo.Context) error

Browse is the category browser at an address of its own. Index shows the book instead of the browser when a system has one, so without this the categories could not be reached from a reference page's breadcrumb. GET /campaigns/:id/systems/:mod/browse

func (*SystemHandler) CampaignBookPackage

func (h *SystemHandler) CampaignBookPackage(campaignID, systemID string) (*BookPackage, BookEditService, error)

CampaignBookPackage loads the editable book of the game system a campaign uses, for callers outside an editor request (AI Import). systemID is the campaign's settings value; the lookups match the editor routes', and the caller does its own Director check (bookEditorAllowed's rule).

func (*SystemHandler) CategoryList

func (h *SystemHandler) CategoryList(c *echo.Context) error

CategoryList is a category's page, as the reader's list has it. GET /campaigns/:id/systems/:mod/:cat?q=

func (*SystemHandler) EnabledSystem

func (h *SystemHandler) EnabledSystem(ctx context.Context, campaignID string) System

EnabledSystem returns the System enabled for a campaign, or nil. Other plugins (the DM Screen) read a system's manifest through it.

func (*SystemHandler) EntryPeek

func (h *SystemHandler) EntryPeek(c *echo.Context) error

EntryPeek is an entry as a fragment for the page peek; ?hero= names a character whose traits it marks, when the reader may see that character. GET /campaigns/:id/systems/:mod/:cat/:item/peek?hero=&printed=1

func (*SystemHandler) ExtensionsHealthAPI

func (h *SystemHandler) ExtensionsHealthAPI(c *echo.Context) error

ExtensionsHealthAPI returns read-only deployment health for every LOADED system — the version + on-disk directory the loader actually serves from, plus a content fingerprint (size + sha256 + mtime) of each widget/manifest file. Admin-gated. Lets an operator tell "registry didn't pick up the install" (loaded_version disagrees) apart from "extraction is wrong" (version agrees, file hash doesn't). GET /admin/extensions/health

func (*SystemHandler) GetSystemWidgetBlockMetas

func (h *SystemHandler) GetSystemWidgetBlockMetas(ctx context.Context, campaignID string) []entities.BlockMeta

GetSystemWidgetBlockMetas returns BlockMeta entries for widgets provided by the campaign's enabled game system. Used by the template editor palette.

func (*SystemHandler) GetSystemWidgetScriptURLs

func (h *SystemHandler) GetSystemWidgetScriptURLs(ctx context.Context, campaignID string) []string

GetSystemWidgetScriptURLs returns the URLs to load system widget JS files for the campaign's enabled game system. Injected into pages via base.templ. Text renderer scripts are included first so they define globals that widget scripts can depend on (e.g., DrawSteelRefRenderer).

func (*SystemHandler) HouseRulesBlock

func (h *SystemHandler) HouseRulesBlock(c *echo.Context) error

HouseRulesBlock draws the block, or an empty answer that removes the placeholder when the campaign has no house chapter the viewer can read. GET /campaigns/:id/house-rules

func (*SystemHandler) Index

func (h *SystemHandler) Index(c *echo.Context) error

Index lists all categories for a system. GET /campaigns/:id/systems/:mod

func (*SystemHandler) ItemDetail

func (h *SystemHandler) ItemDetail(c *echo.Context) error

ItemDetail is an entry's page. A rewritten entry's standard address and an old name redirect to the entry they lead to; a left-out entry answers with its one line. GET /campaigns/:id/systems/:mod/:cat/:item?printed=1

func (*SystemHandler) NamedEntry

func (h *SystemHandler) NamedEntry(c *echo.Context) error

NamedEntry sends the reader to the entry a kind and a name lead to, so a sheet that knows only the name can link to the entry's own page. GET /campaigns/:id/systems/:mod/named/:kind?name=

func (*SystemHandler) NamedEntryPeek

func (h *SystemHandler) NamedEntryPeek(c *echo.Context) error

NamedEntryPeek is the peek of the entry a kind and a name lead to; ?hero= marks that character's traits, as on the entry's own peek. GET /campaigns/:id/systems/:mod/named/:kind/peek?name=&hero=

func (*SystemHandler) OperatorDiagnosticsAPI

func (h *SystemHandler) OperatorDiagnosticsAPI(c *echo.Context) error

OperatorDiagnosticsAPI is a CATALOG of named, read-only, secret-redacted diagnostics the assistant requests one at a time, so the operator only ever pastes back the small, targeted result it asked for. Admin-gated.

GET /admin/diagnostics                      → the catalog (tiny menu, no payload)
GET /admin/diagnostics?name=system.versions → run one named diagnostic
GET /admin/diagnostics?name=system.files&arg=drawsteel

func (*SystemHandler) RulesGlossaryAPI

func (h *SystemHandler) RulesGlossaryAPI(c *echo.Context) error

RulesGlossaryAPI serves a system's raw data/rules-glossary.json — the authored [{slug,name,description,properties:{category}}] array a system's client-side reference-renderer needs to resolve {@category term} tokens. Served raw, not via the DataProvider's rendered-HTML category view. Returns an empty array when the system ships no glossary so references stay literal rather than erroring.

GET /campaigns/:id/systems/:mod/rules-glossary

func (*SystemHandler) SearchAPI

func (h *SystemHandler) SearchAPI(c *echo.Context) error

SearchAPI returns JSON search results across all system categories, from the reader's own list. GET /campaigns/:id/systems/:mod/search?q=...

func (*SystemHandler) SetAddonService

func (h *SystemHandler) SetAddonService(svc addonChecker)

SetAddonService wires the addon service for checking which system is enabled per campaign. Used by widget metadata methods.

func (*SystemHandler) SetBookEdits

func (h *SystemHandler) SetBookEdits(svc BookEditService)

SetBookEdits wires the service holding a campaign's edits to a system's book. Without it the book is served exactly as the package ships it and the editor routes answer 404.

func (*SystemHandler) SetCampaignSystems

func (h *SystemHandler) SetCampaignSystems(mgr *CampaignSystemManager)

SetCampaignSystems wires the per-campaign custom system manager.

func (*SystemHandler) SetRulesPages

func (h *SystemHandler) SetRulesPages(p *RulesPages)

SetRulesPages wires what a reader sees of a rules category: the per-reader catalog, ties, left-out entries and the campaign's characters. Without it every system reads as its package.

func (*SystemHandler) SystemDataAPI

func (h *SystemHandler) SystemDataAPI(c *echo.Context) error

SystemDataAPI serves a system's raw data/<file>.json verbatim — the generic form of RulesGlossaryAPI, for widgets that need the complete authored file as JSON rather than the DataProvider's rendered-HTML category view. The filename is validated to a safe JSON basename and the resolved path is clamped within the system's data dir. Returns 404 for an absent/unknown file so callers degrade gracefully instead of erroring.

GET /campaigns/:id/systems/:mod/data/:file

func (*SystemHandler) ToldAPI

func (h *SystemHandler) ToldAPI(c *echo.Context) error

ToldAPI answers which of a page's named entries carry a change the players were told about lately, so one request marks every link on a sheet. GET /campaigns/:id/systems/:mod/told?n=<kind>:<name>&n=... -> {"told": ["<kind>:<name>", ...]}

func (*SystemHandler) TooltipAPI

func (h *SystemHandler) TooltipAPI(c *echo.Context) error

TooltipAPI returns a JSON tooltip payload for one address, resolved for the reader: a rewritten or old name shows the entry it leads to, a left-out name its one line. GET /campaigns/:id/systems/:mod/:cat/:item/tooltip

func (*SystemHandler) WidgetScriptAPI

func (h *SystemHandler) WidgetScriptAPI(c *echo.Context) error

WidgetScriptAPI serves a system widget's JS file from the system directory. GET /campaigns/:id/systems/:mod/widgets/:slug

type SystemHealth

type SystemHealth struct {
	ID      string            `json:"id"`
	Name    string            `json:"name"`
	Version string            `json:"loaded_version"`
	Source  string            `json:"source"` // "bundled" | "package"
	Dir     string            `json:"dir"`
	Files   []FileFingerprint `json:"files"`
}

SystemHealth is the served reality for one loaded system: the version + dir the loader resolves (what WidgetScriptAPI reads from), its source, and fingerprints of its served files. If this Version disagrees with Admin▸Packages' installed version, the loader never picked up the install (a stale in-memory registry); if Version matches but a file's hash is the old one, the extraction is wrong.

func LoadedHealth

func LoadedHealth() []SystemHealth

LoadedHealth is the package-level accessor over the global loader. Returns nil before Init().

type SystemLoader

type SystemLoader struct {
	// contains filtered or unexported fields
}

SystemLoader discovers and loads system manifests from a directory tree. Each subdirectory containing a manifest.json is treated as a system. Invalid manifests are logged as warnings but do not prevent startup.

func NewSystemLoader

func NewSystemLoader(systemsDir string) *SystemLoader

NewSystemLoader creates a loader that will scan the given directory for system subdirectories containing manifest.json files.

func (*SystemLoader) All

func (l *SystemLoader) All() []*SystemManifest

All returns all discovered system manifests, sorted alphabetically by name.

func (*SystemLoader) AllSystems

func (l *SystemLoader) AllSystems() []System

AllSystems returns all live System instances.

func (*SystemLoader) Count

func (l *SystemLoader) Count() int

Count returns the number of discovered systems.

func (*SystemLoader) Dir

func (l *SystemLoader) Dir(id string) string

Dir returns the absolute directory path for a system by ID, or empty string.

func (*SystemLoader) DiscoverAll

func (l *SystemLoader) DiscoverAll() error

DiscoverAll scans the systems directory for subdirectories containing manifest.json files. Each valid manifest is loaded and registered. Invalid manifests are logged as warnings but do not cause an error. Returns an error only if the systems directory itself cannot be read.

func (*SystemLoader) DiscoverDir

func (l *SystemLoader) DiscoverDir(dir string) error

DiscoverDir scans a single directory for a manifest.json file and loads it as a system. Used to overlay package-manager-installed systems on top of bundled ones. Whether an existing same-ID system is replaced is decided by the version-aware policy in register/preferCandidate (WS-6): a package copy overlays a bundled one at equal version, a newer version always wins, and an older/stale duplicate is skipped rather than silently downgrading the load.

func (*SystemLoader) Get

func (l *SystemLoader) Get(id string) *SystemManifest

Get returns the manifest for a system by ID, or nil if not found.

func (*SystemLoader) GetSystem

func (l *SystemLoader) GetSystem(id string) System

GetSystem returns the live System instance by ID, or nil if not found or not instantiated.

func (*SystemLoader) Health

func (l *SystemLoader) Health() []SystemHealth

Health returns the served reality for every loaded system, sorted by ID for stable output. The loader maps are snapshotted under the read lock; the per-file disk I/O then runs UNLOCKED so a slow stat/read can't block package installs (which take the write lock). Manifests are immutable after load, so reading their widget lists outside the lock is safe.

func (*SystemLoader) RegisterSystem

func (l *SystemLoader) RegisterSystem(mod System)

RegisterSystem registers a live System instance. Called during discovery for systems with status "available" that have data loaded.

type SystemManifest

type SystemManifest struct {
	// PlayWarnings lists play blocks dropped at load. Never serialized: it is
	// kept across repeat validations (a dropped block is gone, so a second pass
	// finds nothing new) so the diagnostics report can show it.
	PlayWarnings []string `json:"-"`

	// DesignWarnings lists designs entries dropped at load (package_designs.go),
	// kept for the diagnostics report like PlayWarnings. Never serialized.
	DesignWarnings []string `json:"-"`

	// ID is the unique machine-readable identifier (e.g., "dnd5e").
	ID string `json:"id"`

	// Name is the human-readable display name.
	Name string `json:"name"`

	// Description is a short summary of what the module provides.
	Description string `json:"description"`

	// Version is the semantic version string (e.g., "0.1.0").
	Version string `json:"version"`

	// Author is the module creator's name or organization.
	Author string `json:"author"`

	// License identifies the content license (e.g., "OGL-1.0a", "ORC", "CC-BY-4.0").
	License string `json:"license"`

	// Icon is the Font Awesome icon class (e.g., "fa-dragon").
	Icon string `json:"icon"`

	// APIVersion is the system framework API version this manifest targets.
	// Used for forward compatibility checks (e.g., "1").
	APIVersion string `json:"api_version"`

	// Status indicates whether the module is available or coming soon.
	Status Status `json:"status"`

	// Categories lists the types of reference content this module provides.
	Categories []CategoryDef `json:"categories"`

	// DirectorData names data files with no category (read only by the
	// package's widgets) that SystemDataAPI keeps to Directors, as a
	// category's Director flag does for its own file.
	DirectorData []string `json:"director_data,omitempty"`

	// EntityPresets are entity type templates that campaigns can adopt when
	// enabling this module (e.g., "D&D Character" with predefined fields).
	EntityPresets []EntityPresetDef `json:"entity_presets,omitempty"`

	// RelationPresets are relation type templates that campaigns can adopt when
	// enabling this module (e.g., "has-item" for inventory tracking).
	RelationPresets []RelationPresetDef `json:"relation_presets,omitempty"`

	// FoundrySystemID is the Foundry VTT game.system.id that this system
	// corresponds to (e.g., "dnd5e", "pf2e"). When set, the Foundry module
	// can automatically match this Chronicle system to the running Foundry
	// game system, enabling character sync for custom-uploaded systems.
	FoundrySystemID string `json:"foundry_system_id,omitempty"`

	// TooltipTemplate is an optional HTML template string for rendering
	// hover tooltips. Uses Go text/template syntax with ReferenceItem data.
	TooltipTemplate string `json:"tooltip_template,omitempty"`

	// Widgets declares JS widgets provided by this system that can be added
	// to entity page layouts via the template editor. Each widget is a
	// self-contained JS file that registers via Chronicle.register().
	Widgets []WidgetDef `json:"widgets,omitempty"`

	// TextRenderers declares JS text renderers that define global utility
	// classes for processing text content. Loaded before widget scripts
	// so widgets can depend on them (e.g., DrawSteelRefRenderer).
	TextRenderers []TextRendererDef `json:"text_renderers,omitempty"`

	// Renderers declares page-level entity-show renderers. Each entry binds
	// an entity_type slug owned by this manifest to a widget that renders
	// the entity's show page in place of the standard layout-block dispatch.
	// The host auto-registers each entry into the EntityShowRendererRegistry
	// at system-load time so JSON-only system packages don't need a
	// Chronicle Go release to ship a custom renderer.
	Renderers []RendererDef `json:"renderers,omitempty"`

	// DMScreen tells the DM Screen which character-sheet numbers to show for
	// each hero and where this system's conditions live. Optional: without it
	// the screen shows hero names only and hides the rules tab.
	DMScreen *DMScreenDef `json:"dm_screen,omitempty"`

	// EntityPanels declares widgets the host mounts under the title of
	// matching entity pages, on top of whatever page renderer or layout the
	// page already uses. Unlike Renderers it adds to a page instead of
	// replacing it, and it is not tied to an entity type of this manifest.
	EntityPanels []EntityPanelDef `json:"entity_panels,omitempty"`

	// Terms are the words the system uses for Chronicle's own roles, so a
	// campaign reads in its game's language.
	Terms *ManifestTerms `json:"terms,omitempty"`

	// Crafting is how the system rolls and counts a crafting project
	// (crafting.go). Nil means DefaultCraftingRules.
	Crafting *CraftingRules `json:"crafting,omitempty"`

	// Crits are the dice faces or totals the system counts as critical
	// successes and failures (crits.go). Nil means DefaultCritRules; a
	// present empty list means the system has no crits.
	Crits *[]CritRule `json:"crits,omitempty"`

	// ShopTests is how a player's haggle or closer look at a shop counter is
	// thrown (shop_tests.go). Nil falls back to the crafting block, then to a
	// d20 against a DC.
	ShopTests *ShopTestsDef `json:"shop_tests,omitempty"`

	// Goods names the categories a shop may stock, and the fields that say
	// each entry's kind, rarity and price (shop_goods.go). Absent: a shop's
	// fill offers none of this system's entries.
	Goods []GoodsDef `json:"goods,omitempty"`

	// Designs are saved designs the package ships (room themes, crafting
	// designs). Campaigns on this system see them read-only under "From
	// <system>" in the design library. See package_designs.go.
	Designs []DesignDef `json:"designs,omitempty"`
}

SystemManifest describes a module's metadata, capabilities, and content structure. Each module declares its manifest in a manifest.json file in its directory root. The manifest is the single source of truth for what a module provides.

func Find

func Find(id string) *SystemManifest

Find returns the manifest for a given module ID, or nil if not found. Returns nil if Init() has not been called.

func LoadManifest

func LoadManifest(path string) (*SystemManifest, error)

LoadManifest reads a manifest.json file from disk, unmarshals it, and validates required fields. Returns the parsed manifest or an error.

func Registry

func Registry() []*SystemManifest

Registry returns all discovered module manifests, sorted by name. Returns nil if Init() has not been called.

func (*SystemManifest) BuildValidationReport

func (m *SystemManifest) BuildValidationReport() *ValidationReport

BuildValidationReport analyzes the manifest and produces a summary of capabilities, Foundry compatibility, and any warnings.

func (*SystemManifest) CategoryNames

func (m *SystemManifest) CategoryNames() []string

CategoryNames returns a flat list of category display names. Convenience method for backward-compatible display on admin pages.

func (*SystemManifest) CharacterFieldsForAPI

func (m *SystemManifest) CharacterFieldsForAPI() *CharacterFieldsResponse

CharacterFieldsForAPI builds the API response for character preset fields. Returns nil if no character preset exists.

func (*SystemManifest) CharacterPreset

func (m *SystemManifest) CharacterPreset() *EntityPresetDef

CharacterPreset returns the first entity preset whose slug ends with "-character", or nil if no character preset is defined. Used by the sync API to expose character field templates for actor sync.

func (*SystemManifest) CharacterPresetByCategory

func (m *SystemManifest) CharacterPresetByCategory() *EntityPresetDef

CharacterPresetByCategory returns the first entity preset with category "character", or nil. Preferred over CharacterPreset (slug-suffix heuristic) for player-character field adoption: category is the explicit marker a system declares, mirroring ItemPreset.

func (*SystemManifest) CraftingRules

func (m *SystemManifest) CraftingRules() CraftingRules

CraftingRules is the system's crafting rules with every empty part filled from DefaultCraftingRules, so callers never check for nil.

func (*SystemManifest) CreatureFieldsForAPI

func (m *SystemManifest) CreatureFieldsForAPI() *CharacterFieldsResponse

CreatureFieldsForAPI builds the API response for creature preset fields. Returns nil if no creature preset exists.

func (*SystemManifest) CreaturePreset

func (m *SystemManifest) CreaturePreset() *EntityPresetDef

CreaturePreset returns the first entity preset with category "creature", or nil. Used by creature sync to Foundry NPC actors.

func (*SystemManifest) CritRules

func (m *SystemManifest) CritRules() []CritRule

CritRules is the system's crit rules. A block that is absent means the default; one that is present but empty (`"crits": []`) means the system has no crits at all, which is why the field is a pointer: a nil slice and an empty one must stay different.

func (*SystemManifest) DirectorOnly

func (m *SystemManifest) DirectorOnly(slug string) bool

DirectorOnly reports whether the category slug is marked Director-only, or data/<slug>.json is listed in DirectorData.

func (*SystemManifest) GMTerm

func (m *SystemManifest) GMTerm() string

GMTerm is the system's name for the game master, or "" for the default.

func (*SystemManifest) HasCharacterSheet

func (m *SystemManifest) HasCharacterSheet() bool

HasCharacterSheet reports whether the system draws character pages itself: a renderer bound to the "character" category, or to the slug of one of its character presets. Only such a page carries a sheet for the sheet styles to dress, so without one a sheet style picks nothing a player can see.

func (*SystemManifest) HasWidget

func (m *SystemManifest) HasWidget(slug string) bool

HasWidget reports whether this manifest declares a widget with the given slug. Lets callers gate an optional page mount on "does the enabled system actually provide this widget" instead of hardcoding a check against one specific system package.

func (*SystemManifest) ItemFieldsForAPI

func (m *SystemManifest) ItemFieldsForAPI() *CharacterFieldsResponse

ItemFieldsForAPI builds the API response for item preset fields. Returns nil if no item preset exists.

func (*SystemManifest) ItemPreset

func (m *SystemManifest) ItemPreset() *EntityPresetDef

ItemPreset returns the first entity preset with category "item", or nil if no item preset is defined. Used by the Armory plugin and item sync.

func (*SystemManifest) PowerRoll

func (m *SystemManifest) PowerRoll() (PowerRollRules, bool)

PowerRoll is the system's power roll, and false when it declares none. The Table's power roll line is 2d10 plus one of the system's characteristics, so only a crafting block that names characteristics and rolls 2d10 counts; the defaults every other system gets are not a declaration.

func (*SystemManifest) ShopTestRules

func (m *SystemManifest) ShopTestRules() ShopTestRulesView

ShopTestRules decides how a shop test is thrown, in this order: the shop_tests block; else the crafting block's dice, characteristics, edge, bane and tiers (a power-roll style); else DefaultShopTestRules. Crafting is the fallback because a system that already says how its heroes roll should not need to say it twice.

type SystemSearchAdapter

type SystemSearchAdapter struct {
	// contains filtered or unexported fields
}

SystemSearchAdapter adapts the rules search to the entity handler's SystemSearcher interface. It checks which systems are enabled as addons for the campaign before searching, and searches each through RulesPages, so global search finds exactly what the reader's own list holds.

func NewSystemSearchAdapter

func NewSystemSearchAdapter(addonSvc addons.AddonService) *SystemSearchAdapter

NewSystemSearchAdapter creates an adapter that will check addon enablement before searching module content.

func (*SystemSearchAdapter) SearchSystemContent

func (a *SystemSearchAdapter) SearchSystemContent(ctx context.Context, campaignID, query string, director bool, userID, campaignName string) ([]map[string]string, error)

SearchSystemContent searches all enabled systems for the given campaign and returns results formatted for the entity search API response. Director-only categories and entries are left out unless director is set.

func (*SystemSearchAdapter) SetRulesPages

func (a *SystemSearchAdapter) SetRulesPages(p *RulesPages)

SetRulesPages gives the adapter the per-reader catalog. Without it every system answers from its package alone.

type TellQuestion

type TellQuestion struct {
	// Holders says who holds what changed: "Sable Varr holds this trait."
	Holders string `json:"holders"`
	// Line is the suggested line for the players, which the Director may edit.
	Line string `json:"line"`
	// Heroes and Traits name who and what, in the order they were found.
	Heroes []string `json:"heroes"`
	Traits []string `json:"traits"`
}

TellQuestion is what a save asks the Director, beside the saved entry.

type TextRendererDef

type TextRendererDef struct {
	// Slug is the unique identifier for the text renderer.
	Slug string `json:"slug"`

	// Name is the display name.
	Name string `json:"name"`

	// File is the relative path to the JS file within the system directory.
	File string `json:"file"`

	// EntryPoint is the global variable/class name exported by the script.
	EntryPoint string `json:"entry_point,omitempty"`

	// Description is a short summary of what the renderer does.
	Description string `json:"description,omitempty"`
}

TextRendererDef describes a JS text renderer provided by a game system. Text renderers define global classes/functions that process text content (e.g., resolving rule references to tooltips). They load before widgets so widgets can depend on them.

type TooltipRenderer

type TooltipRenderer interface {
	// RenderTooltip returns an HTML fragment for the given reference item.
	RenderTooltip(item *ReferenceItem) (string, error)

	// SupportedCategories returns which category slugs this renderer handles.
	SupportedCategories() []string
}

TooltipRenderer produces HTML tooltip fragments for reference items. Implementations use Go templates or Templ components to render hover-preview content for @mention popups.

type TraitChange

type TraitChange struct {
	// List is the property the trait sits in ("purchased_traits").
	List string `json:"list"`
	Name string `json:"name"`
	// Removed is true when the trait is gone; otherwise it was altered.
	Removed     bool `json:"removed,omitempty"`
	CostChanged bool `json:"costChanged,omitempty"`
	TextChanged bool `json:"textChanged,omitempty"`
	// CostBefore and CostAfter are set when the cost changed (nil = none).
	CostBefore *int `json:"costBefore,omitempty"`
	CostAfter  *int `json:"costAfter,omitempty"`
}

TraitChange is one trait a save removed or altered.

func ChangedTraits

func ChangedTraits(before, after *SystemEntry) []TraitChange

ChangedTraits lists the traits an update removed or altered, by name, so a save can ask whether to tell the players who hold them. A trait only added is not listed: nobody can hold it yet. Order is stable (list, then name).

type TreeNode

type TreeNode struct {
	// Label is the display text for this node.
	Label string `json:"label"`

	// Icon is an optional Font Awesome icon class.
	Icon string `json:"icon,omitempty"`

	// Badge is optional count or status text shown after the label.
	Badge string `json:"badge,omitempty"`

	// Type classifies the node for styling: "root", "section", "category",
	// "preset", "field", "foundry", "warning".
	Type string `json:"type"`

	// Children are nested sub-nodes.
	Children []*TreeNode `json:"children,omitempty"`
}

TreeNode represents a single node in the impact tree diagram. Nodes form a tree structure rendered by the client-side impact_tree widget.

func BuildImpactTree

func BuildImpactTree(manifest *SystemManifest, categories []CategoryPreview, warnings []string) *TreeNode

BuildImpactTree creates a hierarchical tree structure representing what a system package adds. Rendered as a visual flowchart in the UI.

type UpdateBookChapterInput

type UpdateBookChapterInput struct {
	Title    patch.Field[string] `json:"title"`
	Intro    patch.Field[string] `json:"intro"`
	Director patch.Field[bool]   `json:"director"`
}

UpdateBookChapterInput is a PARTIAL update of a house-rules chapter: an absent key keeps the stored value. An explicit null clears the intro; title and director cannot be empty, so null keeps them.

type UpdateSystemEntryInput

type UpdateSystemEntryInput struct {
	Name        patch.Field[string]         `json:"name"`
	Summary     patch.Field[string]         `json:"summary"`
	Description patch.Field[string]         `json:"description"`
	Properties  patch.Field[map[string]any] `json:"properties"`
	Visibility  patch.Field[string]         `json:"visibility"`
	// ForEntityID changes the character a 'character' entry is kept to.
	// Moving to another visibility clears it.
	ForEntityID patch.Field[string] `json:"forEntityId"`
	// Status moves a player's entry: its writer between draft and sent, a
	// Director to accepted, or back to draft with a ReviewNote.
	Status     patch.Field[string] `json:"status"`
	ReviewNote patch.Field[string] `json:"reviewNote"`
}

UpdateSystemEntryInput is a PARTIAL update: an absent key keeps the stored value, an explicit null clears it, a present value replaces it. Name and visibility cannot be empty, so null on them is refused rather than ignored. The field key and slug are fixed once created.

type UploadPolicyProvider

type UploadPolicyProvider func(ctx context.Context) string

UploadPolicyProvider returns the current owner upload policy setting. Decouples the campaign handler from the packages plugin.

type ValidationReport

type ValidationReport struct {
	// CategoryCount is the number of reference data categories.
	CategoryCount int `json:"category_count"`

	// TotalFields is the total number of fields across all categories.
	TotalFields int `json:"total_fields"`

	// PresetCount is the number of entity presets defined.
	PresetCount int `json:"preset_count"`

	// HasCharacterPreset indicates a character preset was found.
	HasCharacterPreset bool `json:"has_character_preset"`

	// CharacterFieldCount is the number of fields on the character preset.
	CharacterFieldCount int `json:"character_field_count"`

	// HasItemPreset indicates an item-category preset was found.
	HasItemPreset bool `json:"has_item_preset"`

	// ItemFieldCount is the number of fields on the item preset.
	ItemFieldCount int `json:"item_field_count"`

	// FoundryCompatible indicates foundry_system_id is set.
	FoundryCompatible bool `json:"foundry_compatible"`

	// FoundrySystemID is the declared Foundry system ID (if any).
	FoundrySystemID string `json:"foundry_system_id,omitempty"`

	// FoundryMappedFields is how many character fields have foundry_path set.
	FoundryMappedFields int `json:"foundry_mapped_fields"`

	// FoundryWritableFields is how many mapped fields are writable to Foundry.
	FoundryWritableFields int `json:"foundry_writable_fields"`

	// WidgetCount is the number of JS widgets provided by this system.
	WidgetCount int `json:"widget_count"`

	// Warnings lists non-fatal issues the owner should be aware of.
	Warnings []string `json:"warnings,omitempty"`
}

ValidationReport summarizes a system manifest's capabilities and readiness. Used to give campaign owners clear feedback after uploading a custom system.

type WaitingChoiceRequest

type WaitingChoiceRequest struct {
	ChoiceRequest
	FieldLabel string `json:"fieldLabel"`
	PlayerName string `json:"playerName"`
}

WaitingChoiceRequest is a waiting request as a Director reads it.

type WidgetDef

type WidgetDef struct {
	// Slug is the widget registration name (e.g., "dnd5e-stat-block").
	// Must be unique and match the name passed to Chronicle.register().
	Slug string `json:"slug"`

	// Name is the display name shown in the template editor palette.
	Name string `json:"name"`

	// Icon is the Font Awesome icon class (e.g., "fa-shield-halved").
	Icon string `json:"icon"`

	// Description is tooltip text shown in the template editor palette.
	Description string `json:"description"`

	// ScriptFile is the relative path to the JS file within the system
	// directory (e.g., "widgets/stat-block.js").
	ScriptFile string `json:"script_file"`

	// File is an alias for ScriptFile for backward compatibility.
	File string `json:"file"`

	// TileSizes are the "WxH" sizes the widget supports in a tile section on
	// a 4-column grid; the first is its default. Empty means it cannot be a
	// tile. The widget is told its current size by data-tile-w / data-tile-h.
	TileSizes []string `json:"tile_sizes,omitempty"`

	// HostMounted marks a widget Chronicle mounts itself somewhere other
	// than an entity page (the encounter builder's budget panel), so the
	// Customizer never offers it as a block.
	HostMounted bool `json:"host_mounted,omitempty"`
}

WidgetDef describes a JS widget provided by a game system module. Widgets are self-contained scripts that register via Chronicle.register() and can be placed on entity pages through the template editor palette.

Source Files

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL