@storylet-studio/play-helpers 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/index.ts","../../../../expr/packages/scoperegistry/src/state-logger.ts","../../../../expr/packages/scoperegistry/src/index.ts","../src/logger.ts","../../model/src/index.ts","../src/save.ts","../src/inspector.ts","../src/bundle-inspector.ts","../src/live-link.ts","../src/refresh.ts","../src/world.ts"],"sourcesContent":["// @storylet-studio/play-helpers - the dev-experience layer over the pure\n// runtime (design/engine-runtimes.md 1: the split is purity, not\n// distribution; the runtime never touches the DOM or I/O, this does).\nexport { createKernelStateLogger, createStateLogger, snapshotState, diffState } from \"./logger.js\";\nexport type { StateChange, StateLogger, StateLoggerAdapter, StateLoggerOptions, StateSnapshot } from \"./logger.js\";\nexport { serializeState, deserializeState, saveState, loadState } from \"./save.js\";\nexport { createPropertyInspector, ensureInspectorStyle, formatLogEntry } from \"./inspector.js\";\nexport type { PropertyInspector, PropertyInspectorOptions } from \"./inspector.js\";\nexport { createBundleInspector, formatPropertySummary, formatScopeLabel } from \"./bundle-inspector.js\";\nexport type { BundleInspector, BundleInspectorOptions } from \"./bundle-inspector.js\";\nexport { createLiveLink, boardFrame } from \"./live-link.js\";\nexport type { LiveLink, LiveLinkOptions, LiveSocketLike, LiveFrame } from \"./live-link.js\";\nexport { applyLiveBundle } from \"./refresh.js\";\nexport type { LiveBundleResult } from \"./refresh.js\";\nexport { createWorldContainer } from \"./world.js\";\nexport type { WorldContainer } from \"./world.js\";\n","// ---------------------------------------------------------------------------\n// The state logger: what changed in the state kernel, as it changes.\n//\n// Both product families shipped one of these, in four runtimes each, and they\n// were not the same shape. The Storylet Engine's was PUSH-based on the\n// PropertyBag audit hook - a write logs the moment it lands, with the previous\n// value straight off the event. Patterplay's diffed whole saveGame() snapshots,\n// so it could only ever say what changed BETWEEN captures, and only for state a\n// save persists. This is the first one, because it is the better one: a diff\n// cannot tell a write from a write-and-write-back, cannot name the reason a\n// host attached to a write, and cannot see a value that changed and changed\n// back.\n//\n// A diff is still needed, and is kept, for everything that is NOT in a bag: a\n// product's own non-property state (turns, cooldowns, visit counts) arrives\n// through the adapter's `extra()` and is diffed on capture. Bags replaced\n// wholesale by a load fire no audit events either, so capture() re-reads and\n// re-mounts.\n//\n// Line format: `${label}${path}: ${from} -> ${to}`, `<unset>` for a value that\n// was not there.\n// ---------------------------------------------------------------------------\n\nimport type { PropertyBag, ScalarValue } from \"./index.js\";\n\n/** A flattened snapshot: path -> value. */\nexport type StateSnapshot = Record<string, ScalarValue>;\n\nexport interface StateChange {\n path: string;\n from: ScalarValue | undefined;\n to: ScalarValue | undefined;\n}\n\n/**\n * One bag on the logger's path space.\n *\n * Named for the LOG, not the bag: a product may already have its own type for enumerating\n * bags (the Storylet Engine's LogMount, which labels a mount \"story\" for its own purposes),\n * and in the ported runtimes both land in one namespace. They are also not the same thing,\n * which the prefix rule below is about.\n *\n * `pathPrefix` is used VERBATIM, separator included, exactly as the bag's own\n * is - it is not a scope token with a dot implied. Omit it and the bag's own\n * `pathPrefix` is used, which is what a product wants whenever its log paths\n * and its property addresses agree.\n *\n * They do not always agree, which is why this can be overridden: Patterplay\n * addresses a scene property `@scene.mood` (relative to the flow's current\n * scene) but has to LOG it as `@scene:kitchen.mood`, because a log covering\n * several scenes needs to say which one.\n */\nexport interface LogMount {\n bag: PropertyBag;\n pathPrefix?: string;\n}\n\n/** What a product supplies: its kernel bags (re-read on every capture, so a\n * product that replaces its bags on load re-mounts), and its non-property\n * state as flattened paths. */\nexport interface StateLoggerAdapter {\n mounts(): LogMount[];\n extra?(): StateSnapshot;\n}\n\nexport interface StateLoggerOptions {\n /** Where lines go; defaults to console.log. */\n sink?: (line: string) => void;\n /** Prefixed to every line, verbatim (e.g. `\"[board] \"`). */\n label?: string;\n}\n\nexport interface StateLogger {\n /** The current flattened state. Logs nothing. */\n snapshot(): StateSnapshot;\n /** Everything since the last capture: the audited writes already logged as\n * they landed, plus anything that changed WITHOUT an audit event, diffed,\n * logged and re-baselined. */\n capture(): StateChange[];\n /** Unhook the bag auditors. The logger is inert afterwards. */\n dispose(): void;\n}\n\n/** The sorted set of paths that differ between two snapshots. */\nexport function diffState(prev: StateSnapshot, next: StateSnapshot): StateChange[] {\n const changes: StateChange[] = [];\n const paths = new Set([...Object.keys(prev), ...Object.keys(next)]);\n for (const path of [...paths].sort()) {\n const from = prev[path], to = next[path];\n if (JSON.stringify(from) !== JSON.stringify(to)) changes.push({ path, from, to });\n }\n return changes;\n}\n\nconst show = (v: ScalarValue | undefined): string => (v === undefined ? \"<unset>\" : JSON.stringify(v));\n\nconst prefixOf = (m: LogMount): string => m.pathPrefix ?? m.bag.pathPrefix;\n\nexport function createStateLogger(adapter: StateLoggerAdapter, opts: StateLoggerOptions = {}): StateLogger {\n const sink = opts.sink ?? ((line: string) => console.log(line));\n const label = opts.label ?? \"\";\n const emit = (c: StateChange): void => { sink(`${label}${c.path}: ${show(c.from)} -> ${show(c.to)}`); };\n\n const full = (): StateSnapshot => {\n const out: StateSnapshot = {};\n for (const m of adapter.mounts()) {\n const prefix = prefixOf(m);\n for (const [name, value] of Object.entries(m.bag.values)) out[prefix + name] = value;\n }\n Object.assign(out, adapter.extra?.() ?? {});\n return structuredClone(out);\n };\n\n let baseline = full();\n let pushed: StateChange[] = [];\n let mounted: { bag: PropertyBag; off: () => void }[] = [];\n\n const hook = (prefix: string, bag: PropertyBag): (() => void) =>\n bag.onAudit((change) => {\n // The write logs as it lands, `from` straight off the event; the baseline\n // moves with it so capture() never re-reports what was already said.\n const c: StateChange = structuredClone({ path: prefix + change.name, from: change.prev, to: change.next });\n emit(c);\n pushed.push(c);\n baseline[c.path] = structuredClone(change.next);\n });\n\n const mount = (): void => {\n const mounts = adapter.mounts();\n const same = mounted.length === mounts.length && mounts.every((m, i) => mounted[i]!.bag === m.bag);\n if (same) return;\n for (const m of mounted) m.off();\n mounted = mounts.map((m) => ({ bag: m.bag, off: hook(prefixOf(m), m.bag) }));\n };\n mount();\n\n return {\n snapshot: full,\n capture(): StateChange[] {\n // Whatever arrived WITHOUT an audit event: the adapter's non-property\n // paths, and bag values replaced wholesale by a load (which fires none).\n const next = full();\n const diffed = diffState(baseline, next);\n for (const c of diffed) emit(c);\n const changes = [...pushed, ...diffed];\n pushed = [];\n baseline = next;\n mount(); // a load replaces a product's bags; re-hook them\n return changes;\n },\n dispose(): void {\n for (const m of mounted) m.off();\n mounted = [];\n pushed = [];\n },\n };\n}\n","// ---------------------------------------------------------------------------\n// @wildwinter/scoperegistry - the scope registry / runtime state container that\n// sits on top of @wildwinter/expr.\n//\n// expr is a stateless calculator: given an AST, an EvalContext (the state), and\n// a Dialect, it computes. This package is the *state* layer: it owns the world\n// state as a set of named scopes - each either an **owned** scope (a property\n// bag this registry stores and saves) or a **foreign** scope (host- or\n// other-engine-resolved at runtime, never stored here) - and produces the\n// `EvalContext` (for evaluation) and `ExpressionSchema` (for validation) that\n// expr consumes. Plus the `scopeRegistrySpec` interop format for importing a\n// foreign owner's scope declarations.\n//\n// Design: design/scope-registry.md (in the patter repo). expr never depends on\n// this; this depends one-way on expr.\n// ---------------------------------------------------------------------------\n\nimport type {\n EvalContext, ExpressionSchema, PropertyType, ScalarValue, ScopeResolver,\n} from \"@wildwinter/expr\";\n\nexport type { EvalContext, ExpressionSchema, PropertyType, ScalarValue, ScopeResolver } from \"@wildwinter/expr\";\n\n// ---------------------------------------------------------------------------\n// Declarations + the scopeRegistrySpec interop format\n// ---------------------------------------------------------------------------\n\n/**\n * A property declaration. `default` is used by an *owned* scope to seed its bag\n * (foreign scopes ignore it - the host owns the value). `writable: false` makes\n * a property read-only; default is read/write. (`type`/`values` feed validation.)\n */\nexport interface ScopeDeclaration {\n name: string;\n type: PropertyType;\n values?: string[]; // for enum / flags\n /** A quality's ordered ladder of stage names (quality.md). */\n stages?: string[];\n default?: ScalarValue; // owned scopes: seed value\n writable?: boolean; // default true\n}\n\n/** One scope in a `scopeRegistrySpec`: a token + (optional) declarations. */\nexport interface ScopeSpec {\n token: string;\n /** Scope-level read/write default for its declarations (default true). */\n writable?: boolean;\n /** Property declarations; omit for an opaque scope (any name, unchecked). */\n declarations?: ScopeDeclaration[];\n}\n\n/**\n * The interop format an owner (Storylet Studio, a host game) exports so another\n * engine can validate references into its scopes. Carried under the well-known\n * `scopeRegistrySpec` JSON key (inside a `.storyworld`, or a standalone file).\n */\nexport interface ScopeRegistrySpec {\n version: number;\n scopes: ScopeSpec[];\n}\n\n/** The spec versions this build understands. */\nexport const SUPPORTED_SPEC_VERSIONS = [1] as const;\n\n/**\n * Extract + validate a `scopeRegistrySpec` from any JSON value (a parsed\n * `.storyworld` bundle, or a vanilla `{ scopeRegistrySpec: ... }` manifest).\n * Returns null when the key is absent (so callers can probe arbitrary files);\n * throws on a malformed or unsupported-version spec.\n */\nexport function readScopeRegistrySpec(source: unknown): ScopeRegistrySpec | null {\n if (!source || typeof source !== \"object\") return null;\n const raw = (source as Record<string, unknown>).scopeRegistrySpec;\n if (raw === undefined) return null;\n if (typeof raw !== \"object\" || raw === null) throw new Error(\"scopeRegistrySpec must be an object\");\n const spec = raw as Record<string, unknown>;\n if (typeof spec.version !== \"number\") throw new Error(\"scopeRegistrySpec.version must be a number\");\n if (!(SUPPORTED_SPEC_VERSIONS as readonly number[]).includes(spec.version)) {\n throw new Error(`unsupported scopeRegistrySpec version ${spec.version} (supported: ${SUPPORTED_SPEC_VERSIONS.join(\", \")})`);\n }\n if (!Array.isArray(spec.scopes)) throw new Error(\"scopeRegistrySpec.scopes must be an array\");\n for (const s of spec.scopes) {\n if (!s || typeof s !== \"object\" || typeof (s as ScopeSpec).token !== \"string\") {\n throw new Error(\"each scopeRegistrySpec scope needs a string token\");\n }\n }\n return spec as unknown as ScopeRegistrySpec;\n}\n\n// ---------------------------------------------------------------------------\n// PropertyBag - the state kernel's unit of state (added 0.2.0; design:\n// storylets-new/design/engine-runtimes.md 3.1). A typed, declared property\n// bag with defaults, the firing rule (engine writes notify subscribers;\n// host writes are silent but always auditable), examiner rows, one\n// sanctioned clone door, and bare-value save/load. Owned registry scopes\n// are bags; products may also hold bag families of their own (per-box,\n// per-scene) and mount the shared ones.\n// ---------------------------------------------------------------------------\n\n/** One property change. `silent` marks a host write (the firing rule: it\n * reaches the audit hook but not subscribers); `reason` is the host's own\n * note for its log. */\nexport interface BagChange {\n name: string;\n prev?: ScalarValue;\n next: ScalarValue;\n silent: boolean;\n reason?: string;\n}\n\n/** One examiner row: what a property examiner/editor needs to render and\n * edit a declared property. */\nexport interface PropertyRow {\n name: string;\n /** The address this property answers to - what getProperty/setProperty take.\n * A bag composes it from its own `pathPrefix` and the name, so a row is\n * self-describing: an examiner can render and write a row without being told\n * separately where it came from.\n *\n * The PREFIX CARRIES ITS OWN SEPARATOR rather than the bag assuming a dot,\n * because a prefix is not always a bare scope token: the Storylet Engine\n * addresses a deck's properties as `deck.<id>.name`, so the prefix is already\n * a dotted path. Patterplay's `@patter.gold` and `@scene.mood` are the plain\n * case. (`@gold` also resolves - splitRef defaults an unqualified name to the\n * patter scope - but it is the shorthand, not the address a row reports.)\n *\n * With no prefix this is just the name. Both families forked this interface\n * to add exactly this field - once per runtime - which is the same reason\n * `stages` is here. */\n path: string;\n type: PropertyType;\n value: ScalarValue | undefined;\n default: ScalarValue;\n values?: string[];\n /** A quality's ordered stage ladder, so an inspector can offer the stages\n * instead of a free-text box. `quality` has been in PropertyType since the\n * ladder landed, and the evaluator compares stages by LADDER POSITION and\n * refuses an unknown one, so free text is not a soft failure: a typo breaks\n * play rather than being corrected. This row is the only thing an examiner\n * sees, so a ladder it cannot carry is a ladder no editor can offer. One\n * consumer forked this whole interface to add the field; the field belongs\n * here, beside the `values` it is the closed-set twin of. */\n stages?: string[];\n writable: boolean;\n}\n\nexport class PropertyBag {\n /** The live values record (stable identity across reseed, so an\n * EvalContext built over it stays valid). Read-path for evaluation;\n * writes go through `set` so the firing rule applies. */\n readonly values: Record<string, ScalarValue> = {};\n private decls = new Map<string, ScopeDeclaration>();\n private readonly subscribers = new Set<(change: BagChange) => void>();\n private readonly auditors = new Set<(change: BagChange) => void>();\n /** Name normalisation policy: lowercase by default (the registry's\n * long-standing contract); a product whose names are case-significant\n * passes identity. */\n private readonly norm: (name: string) => string;\n\n /** The address prefix this bag's rows carry, separator included (`@`,\n * `@scene.`, `world.`, `deck.<id>.`). Empty means a row's path is its name. */\n readonly pathPrefix: string;\n\n constructor(\n declarations: ScopeDeclaration[] = [],\n opts?: { normalise?: (name: string) => string; pathPrefix?: string },\n ) {\n this.norm = opts?.normalise ?? ((n) => n.toLowerCase());\n this.pathPrefix = opts?.pathPrefix ?? \"\";\n this.seed(declarations);\n }\n\n private seed(declarations: ScopeDeclaration[]): void {\n for (const d of declarations) {\n const name = this.norm(d.name);\n this.decls.set(name, d);\n // Cloned so bags seeded from one declaration set never share a\n // mutable default (flags arrays).\n this.values[name] = structuredClone(d.default ?? defaultFor(d));\n }\n }\n\n get(name: string): ScalarValue | undefined {\n return this.values[this.norm(name)];\n }\n\n /** Write a property. Engine writes (the default) notify subscribers;\n * pass `silent: true` for a host write, which reaches only the audit\n * hook. Throws on a read-only property. Returns the change. */\n set(name: string, value: ScalarValue, opts?: { silent?: boolean; reason?: string }): BagChange {\n const n = this.norm(name);\n if (this.decls.get(n)?.writable === false) throw new Error(`'${name}' is read-only`);\n const change: BagChange = {\n name: n,\n prev: this.values[n],\n next: value,\n silent: opts?.silent ?? false,\n reason: opts?.reason,\n };\n this.values[n] = value;\n for (const audit of this.auditors) audit(change);\n if (!change.silent) for (const fn of this.subscribers) fn(change);\n return change;\n }\n\n /** Notified of engine (non-silent) writes. Returns the unsubscribe. */\n subscribe(fn: (change: BagChange) => void): () => void {\n this.subscribers.add(fn);\n return () => this.subscribers.delete(fn);\n }\n\n /** Notified of EVERY write, silent or not. Returns the unsubscribe. */\n onAudit(fn: (change: BagChange) => void): () => void {\n this.auditors.add(fn);\n return () => this.auditors.delete(fn);\n }\n\n /** Examiner rows: the declared surface only (stray values are storage,\n * not surface). */\n rows(): PropertyRow[] {\n return [...this.decls.entries()].map(([name, d]) => rowFor(d, this.get(name), undefined, name, this.pathPrefix));\n }\n\n declarations(): ScopeDeclaration[] {\n return [...this.decls.values()];\n }\n\n /** The one sanctioned copy door: values deep-copied, declarations\n * duplicated, the normalisation policy carried, subscriptions NOT\n * carried. */\n clone(): PropertyBag {\n const c = new PropertyBag([], { normalise: this.norm, pathPrefix: this.pathPrefix });\n c.decls = new Map(this.decls);\n Object.assign(c.values, structuredClone(this.values));\n return c;\n }\n\n /** Clear and re-seed from new declarations, in place (the values record\n * keeps its identity, so contexts built over it stay valid). */\n reseed(declarations: ScopeDeclaration[]): void {\n for (const k of Object.keys(this.values)) delete this.values[k];\n this.decls.clear();\n this.seed(declarations);\n }\n\n /** Bare values, ready to embed in a product's save. */\n save(): Record<string, ScalarValue> {\n return structuredClone(this.values);\n }\n\n /** Lay saved values over the current ones (call after a fresh seed:\n * orphans land as strays, new declarations keep their defaults; the\n * product decides whether to prune). Does not fire events. */\n load(values: Record<string, ScalarValue>): void {\n for (const [k, v] of Object.entries(values)) this.values[this.norm(k)] = v;\n }\n}\n\nfunction rowFor(\n d: ScopeDeclaration,\n value: ScalarValue | undefined,\n writable?: boolean,\n name?: string,\n pathPrefix = \"\",\n): PropertyRow {\n const rowName = name ?? d.name.toLowerCase();\n return {\n name: rowName,\n path: pathPrefix + rowName,\n type: d.type,\n value,\n default: d.default ?? defaultFor(d),\n ...(d.values !== undefined ? { values: d.values } : {}),\n // `stages` was added to the row so an examiner could offer a quality's ladder\n // instead of a free-text box, and then never populated here: every quality row\n // this function built came out without one. Fixed 2026-09-02.\n ...(d.stages !== undefined ? { stages: d.stages } : {}),\n writable: writable ?? d.writable ?? true,\n };\n}\n\n// ---------------------------------------------------------------------------\n// The registry / state container\n// ---------------------------------------------------------------------------\n\ninterface OwnedScope {\n kind: \"owned\";\n bag: PropertyBag;\n}\ninterface ForeignScope {\n kind: \"foreign\";\n resolver: ScopeResolver;\n decls: Map<string, ScopeDeclaration>;\n scopeWritable: boolean;\n}\ntype Entry = OwnedScope | ForeignScope;\n\n/** The versioned owned-state fragment both product save envelopes embed\n * (design/engine-runtimes.md 3.1: one serialisation shape for bags). */\nexport interface OwnedStateFragment {\n version: number;\n scopes: Record<string, Record<string, ScalarValue>>;\n}\n\nexport const SAVE_FRAGMENT_VERSION = 1;\n\nexport class ScopeRegistry {\n private readonly scopes = new Map<string, Entry>();\n\n /**\n * Register a scope this registry **owns and stores**. Its bag is seeded from\n * each declaration's `default` (or a type default). Owned scopes are\n * type-checked (declarations) and serialized by `save`/`load`.\n */\n defineOwned(token: string, declarations: ScopeDeclaration[], pathPrefix?: string): this {\n // The scope knows its own token, so its rows can address themselves: `world.hp`.\n // The ADDRESS GRAMMAR is the product's, though, not the registry's - Patterplay\n // writes `@patter.gold` where the Storylet Engine writes `world.gold` - so a\n // caller may say how its addresses look. A bag MOUNTED here keeps whatever prefix\n // its holder gave it: the holder owns the addressing.\n return this.mountOwned(token, new PropertyBag(declarations, { pathPrefix: pathPrefix ?? `${token}.` }));\n }\n\n /**\n * Attach an EXISTING bag as an owned scope - the shared-container move: a\n * host (or the other product) holds the bag; this registry reads, writes\n * and lists it like its own, but the holder saves it.\n */\n mountOwned(token: string, bag: PropertyBag): this {\n this.assertFree(token);\n this.scopes.set(token, { kind: \"owned\", bag });\n return this;\n }\n\n /** An owned scope's bag (subscribe, audit, rows live there). */\n ownedBag(token: string): PropertyBag {\n const e = this.scopes.get(token);\n if (!e || e.kind !== \"owned\") throw new Error(`'@${token}' is not an owned scope`);\n return e.bag;\n }\n\n /**\n * Re-initialise an existing **owned** scope's bag from new declarations,\n * clearing its current values. For scope-local state that resets on a context\n * change (e.g. entering a new scene / site / deck) without disturbing other\n * scopes. Mutates the bag in place, so an `EvalContext` already built from this\n * registry stays valid.\n */\n reseedOwned(token: string, declarations: ScopeDeclaration[]): this {\n this.ownedBag(token).reseed(declarations);\n return this;\n }\n\n /**\n * Register a **foreign** scope backed by a host `{ get, set? }` resolver. The\n * values live in the host/other engine and are never stored or saved here.\n * `declarations` (optional, e.g. imported from a `scopeRegistrySpec`) are used\n * only for validation; omit them for an opaque scope.\n */\n defineForeign(\n token: string,\n resolver: ScopeResolver,\n declarations: ScopeDeclaration[] = [],\n scopeWritable = true,\n ): this {\n this.assertFree(token);\n const decls = new Map<string, ScopeDeclaration>();\n for (const d of declarations) decls.set(d.name.toLowerCase(), d);\n this.scopes.set(token, { kind: \"foreign\", resolver, decls, scopeWritable });\n return this;\n }\n\n has(token: string): boolean {\n return this.scopes.has(token);\n }\n\n /** Read a property; undefined if the scope or property is not present. */\n get(scope: string, name: string): ScalarValue | undefined {\n const e = this.scopes.get(scope);\n if (!e) return undefined;\n return e.kind === \"owned\" ? e.bag.get(name) : e.resolver.get(name.toLowerCase());\n }\n\n /** Write a property (an ENGINE write: the bag's subscribers fire; use\n * the bag directly for silent host writes). Throws on an unknown or\n * read-only scope/property. */\n set(scope: string, name: string, value: ScalarValue): void {\n const e = this.scopes.get(scope);\n if (!e) throw new Error(`unknown scope '@${scope}'`);\n if (e.kind === \"owned\") {\n try {\n e.bag.set(name, value);\n } catch {\n throw new Error(`'@${scope}.${name}' is read-only`);\n }\n return;\n }\n const n = name.toLowerCase();\n if (!this.foreignWritable(e, n)) throw new Error(`'@${scope}.${name}' is read-only`);\n e.resolver.set!(n, value);\n }\n\n private foreignWritable(e: ForeignScope, name: string): boolean {\n if (!e.resolver.set) return false; // no setter => read-only scope\n return e.decls.get(name)?.writable ?? e.scopeWritable;\n }\n\n /** Examiner rows across every scope with a declared surface: owned bags\n * first, then declared foreign scopes (values read through, writability\n * reflecting the resolver). Opaque foreign scopes are not listed. */\n listProperties(): ({ scope: string } & PropertyRow)[] {\n const out: ({ scope: string } & PropertyRow)[] = [];\n for (const [token, e] of this.scopes) {\n if (e.kind === \"owned\") {\n for (const row of e.bag.rows()) out.push({ scope: token, ...row });\n } else {\n for (const d of e.decls.values()) {\n out.push({\n scope: token,\n ...rowFor(d, e.resolver.get(d.name.toLowerCase()), this.foreignWritable(e, d.name.toLowerCase()),\n undefined, `${token}.`),\n });\n }\n }\n }\n return out;\n }\n\n /**\n * Build the `EvalContext` expr's `evaluate` consumes: owned scopes as static\n * bags, foreign scopes as their resolvers. `host` carries dialect-function\n * callbacks (PRNG, tag lookups) and is passed through untouched.\n */\n toEvalContext(host?: Record<string, unknown>): EvalContext {\n const scopes: EvalContext[\"scopes\"] = {};\n for (const [token, e] of this.scopes) {\n scopes[token] = e.kind === \"owned\" ? e.bag.values : e.resolver;\n }\n // The quality channel (quality.md): declared here once, so a host that\n // registers a quality gets ordering comparisons and advance() with no\n // further wiring. Only added when a quality exists, so contexts stay\n // byte-identical for products that declare none.\n const qualities = this.qualityLadders();\n return qualities.size === 0 ? { scopes, host } : {\n scopes, host,\n qualities: (scope, name) => qualities.get(scope)?.get(name.toLowerCase()),\n };\n }\n\n /** Every quality declaration's ladder, keyed scope token then name. */\n private qualityLadders(): Map<string, Map<string, readonly string[]>> {\n const out = new Map<string, Map<string, readonly string[]>>();\n for (const [token, e] of this.scopes) {\n const decls = e.kind === \"owned\" ? e.bag.declarations() : [...e.decls.values()];\n for (const d of decls) {\n if (d.type !== \"quality\" || d.stages === undefined) continue;\n let m = out.get(token);\n if (!m) { m = new Map(); out.set(token, m); }\n m.set(d.name.toLowerCase(), d.stages);\n }\n }\n return out;\n }\n\n /**\n * Build the `ExpressionSchema` expr's validator consumes. Scopes with no\n * declarations are **omitted** (opaque - references into them are not flagged);\n * declared scopes contribute their property types for validation.\n */\n toSchema(): ExpressionSchema {\n const properties = new Map<string, Map<string, { type: PropertyType; enumValues?: string[]; stages?: string[] }>>();\n for (const [token, e] of this.scopes) {\n const decls = e.kind === \"owned\" ? e.bag.declarations() : [...e.decls.values()];\n if (decls.length === 0) continue;\n const m = new Map<string, { type: PropertyType; enumValues?: string[]; stages?: string[] }>();\n for (const d of decls) m.set(d.name.toLowerCase(), {\n type: d.type, enumValues: d.values,\n ...(d.stages !== undefined ? { stages: d.stages } : {}),\n });\n properties.set(token, m);\n }\n return { properties };\n }\n\n /** Serialize **owned** scopes only (foreign scopes are host-owned,\n * host-saved), as bare bags - the 0.1.x shape, kept stable so existing\n * consumers' save formats are untouched. A product embedding the\n * versioned cross-product shape uses `saveFragment`. */\n save(): Record<string, Record<string, ScalarValue>> {\n const out: Record<string, Record<string, ScalarValue>> = {};\n for (const [token, e] of this.scopes) if (e.kind === \"owned\") out[token] = e.bag.save();\n return out;\n }\n\n /** Restore owned-scope values from a `save` blob. Unknown/foreign scopes\n * are ignored. */\n load(blob: Record<string, Record<string, ScalarValue>>): void {\n for (const [token, vals] of Object.entries(blob)) {\n const e = this.scopes.get(token);\n if (e?.kind === \"owned\") e.bag.load(vals);\n }\n }\n\n /** The versioned owned-state fragment (the one serialisation shape both\n * product families' save envelopes embed when they adopt the kernel;\n * design/engine-runtimes.md 3.1). `save()` wrapped with a version stamp. */\n saveFragment(): OwnedStateFragment {\n return { version: SAVE_FRAGMENT_VERSION, scopes: this.save() };\n }\n\n /** Restore from a versioned fragment; an unsupported version throws. */\n loadFragment(fragment: OwnedStateFragment): void {\n if (fragment.version !== SAVE_FRAGMENT_VERSION) {\n throw new Error(`unsupported owned-state fragment version ${fragment.version} (supported: ${SAVE_FRAGMENT_VERSION})`);\n }\n this.load(fragment.scopes);\n }\n\n private assertFree(token: string): void {\n if (this.scopes.has(token)) throw new Error(`scope '@${token}' is already registered`);\n }\n}\n\n/** The seed value for a declared property: its own `default`, else the type's.\n *\n * Exported because it was being written again wherever a declaration needed seeding, and a\n * copy of a defaults table is a copy that stops agreeing. Patterplay carried three of them in\n * one file, for its shared decls, its host-scope decls and its scene decls - three declaration\n * TYPES, one behaviour, and nothing to notice if a case drifted. The parameter is structurally\n * typed for exactly that reason: anything with `type` and the optional `default` / `values` /\n * `stages` fits, whatever the caller calls its declaration.\n *\n * A quality seeds at the FIRST rung of its ladder: the ladder's start is the story's start. */\nexport function defaultFor(d: Pick<ScopeDeclaration, \"type\" | \"default\" | \"values\" | \"stages\">): ScalarValue {\n if (d.default !== undefined) return d.default;\n switch (d.type) {\n case \"boolean\": return false;\n case \"number\": return 0;\n case \"string\": return \"\";\n case \"enum\": return d.values?.[0] ?? \"\";\n case \"flags\": return [];\n // A quality starts at the first rung of its ladder.\n case \"quality\": return d.stages?.[0] ?? \"\";\n // Unreachable for a well-typed declaration, and deliberately present anyway: a bundle\n // is DATA, and a hand-edited or newer-than-this-build one can carry a type string the\n // union does not have. Falling off the switch would seed `undefined`, which is not a\n // ScalarValue and travels a long way before it fails. Patterplay's copy of this had the\n // guard and this one did not, which is the drift you only find by removing a duplicate.\n default: return false;\n }\n}\n\n// ---------------------------------------------------------------------------\n// The state logger, which both product families had written twice each.\n// ---------------------------------------------------------------------------\nexport type {\n StateSnapshot, StateChange, LogMount, StateLoggerAdapter, StateLoggerOptions, StateLogger,\n} from \"./state-logger.js\";\nexport { createStateLogger, diffState } from \"./state-logger.js\";\n","// ---------------------------------------------------------------------------\n// The storylets state logger: an ADAPTER over the kernel logger in\n// @wildwinter/scoperegistry (design/engine-runtimes.md 3.4 is the design of\n// record). The kernel does the work - push-based property logging on the\n// PropertyBag audit hook, so a write logs the moment it lands, plus a diff of\n// everything that has no audit hook - and this supplies the two product-shaped\n// pieces: which bags to watch, and the non-property state (turns / cooldowns /\n// board) as flattened paths.\n//\n// The core lived here, marked \"moves into the kernel package wholesale when the\n// vendor-sync slice lands\". It has. Patterplay's logger, which diffed save\n// snapshots and so could not see a value that changed and changed back, is an\n// adapter over the same core now.\n//\n// Flattened path scheme:\n// world.x / story.x / box.<id>.x / deck.<id>.x / hand.<id>.x / value.<id>.x\n// turn:<boxId> per-box clocks\n// cooldown:<cardId> next-eligible turns\n// board:<handId> hand contents (card ids, dealt order)\n// Line format: `${label}${path}: ${from} -> ${to}`, `<unset>` for undefined.\n// ---------------------------------------------------------------------------\n\nimport type { Engine, Flow } from \"@storylet-studio/runtime\";\nimport type { FlowSave, ScalarValue } from \"@storylet-studio/model\";\nimport {\n createStateLogger as createKernelStateLogger, diffState,\n} from \"@wildwinter/scoperegistry\";\nimport type {\n StateSnapshot, StateChange, StateLogger, StateLoggerAdapter, StateLoggerOptions,\n} from \"@wildwinter/scoperegistry\";\n\n// Re-exported: these were declared here, and a host importing them from\n// @storylet-studio/play-helpers should not have to care that they moved.\nexport { createKernelStateLogger, diffState };\nexport type { StateSnapshot, StateChange, StateLogger, StateLoggerAdapter, StateLoggerOptions };\n\n/** The full flattened snapshot of ONE FLOW's view - the shared partitions\n * plus that flow's own - straight off the save envelope, so \"what the\n * snapshot sees\" is by construction \"what a save persists\". @world is not\n * here for the same reason it is not in the envelope: the host owns that\n * container and mounts/saves it itself (createWorldContainer). */\nexport function snapshotState(engine: Engine, flow: Flow): StateSnapshot {\n const env = engine.saveGame();\n const flowSave = env.flows[flow.id];\n const out: StateSnapshot = {};\n const bag = (prefix: string, values: Record<string, ScalarValue> | undefined): void => {\n for (const [name, value] of Object.entries(values ?? {})) out[`${prefix}.${name}`] = value;\n };\n // Shared under the flow's own: names are disjoint (shared XOR per-flow by\n // declaration), so one path space holds both without collision.\n bag(\"story\", env.shared.props.story);\n bag(\"story\", flowSave?.props.story);\n for (const kind of [\"box\", \"deck\", \"hand\", \"value\"] as const) {\n for (const [id, values] of Object.entries(env.shared.props[kind])) bag(`${kind}.${id}`, values);\n for (const [id, values] of Object.entries(flowSave?.props[kind] ?? {})) bag(`${kind}.${id}`, values);\n }\n Object.assign(out, extraState(env.flows[flow.id]));\n return out;\n}\n\n/** The storylets path-provider adapter for non-property state (design 3.4):\n * one flow's turns / cooldowns / board as flattened paths, off its blob in\n * the envelope (absent for a just-closed flow: no paths). */\nfunction extraState(saved: FlowSave | undefined): StateSnapshot {\n const out: StateSnapshot = {};\n if (saved === undefined) return out;\n for (const [boxId, turn] of Object.entries(saved.turns)) out[`turn:${boxId}`] = turn;\n for (const [cardId, at] of Object.entries(saved.cooldowns)) out[`cooldown:${cardId}`] = at;\n for (const [handId, cards] of Object.entries(saved.board)) out[`board:${handId}`] = [...cards];\n return out;\n}\n\n/** The storylets state logger: the kernel core mounted on the SHARED bags\n * (engine.listBags()) and one flow's own (flow.listBags()) - the same\n * prefixes, one path space, names disjoint - plus the flow's turns /\n * cooldowns / board adapter. A host that wants @world lines mounts its\n * world container's bag through createKernelStateLogger itself. */\nexport function createStateLogger(engine: Engine, flow: Flow, opts: StateLoggerOptions = {}): StateLogger {\n // By NAME, not by handle: loadGame rebuilds every flow and the handle we\n // were given goes inert; capture()'s re-mount picks up the rebuilt one.\n const id = flow.id;\n const live = (): Flow | undefined => engine.getFlow(id);\n return createKernelStateLogger({\n // A BagMount's `prefix` (\"story\", \"deck.<id>\") is the engine's label for the mount;\n // the kernel composes paths from the BAG's own pathPrefix (\"story.\", \"deck.<id>.\")\n // and needs none passed. Same strings, one owner.\n mounts: () => [...engine.listBags(), ...(live()?.listBags() ?? [])].map(({ bag }) => ({ bag })),\n extra: () => extraState(engine.saveGame().flows[id]),\n }, opts);\n}\n","// ---------------------------------------------------------------------------\n// @storylet-studio/model - the shape source-of-truth.\n//\n// Transcribes design/storylets-schema.md (bundle, save) and\n// design/storylets-source.md (shards). Entity shapes are generic over their\n// expression representation E: source shards use plain `src` strings\n// (Card<string>), the compiled bundle uses { src, ast } envelopes\n// (Card<Expression>). No behaviour lives here.\n// ---------------------------------------------------------------------------\n\nimport type { Expression, ScalarValue } from \"@wildwinter/expr\";\n\nexport type { Expression, ScalarValue, AstNode } from \"@wildwinter/expr\";\n\n// --- shared declarations -----------------------------------------------------\n\nexport type PropertyType = \"boolean\" | \"number\" | \"string\" | \"enum\" | \"flags\" | \"quality\";\n\n/** A property declaration: @world / @story / @box / @deck / tag / hand\n * state. A declared property always has a value (`default` is required);\n * referencing an undeclared property is a publish-time error. */\nexport interface PropertyDecl {\n name: string;\n type: PropertyType;\n default: ScalarValue;\n values?: string[];\n /**\n * A quality's ordered ladder of stage names (design/quality.md). Order IS\n * the meaning: `>=` compares by position here, and `advance()` steps along\n * it. The one order-semantic list in the format, accepted as such: it is a\n * declaration, and inserting a stage mid-ladder is the design's whole point.\n */\n stages?: string[];\n /**\n * `@world` only. `false` makes the property read-only TO THE STORY: a\n * condition may read it, an outcome that writes it is a compile error. The\n * game still moves it through its resolver; this is the story's statement\n * of intent, not the game's policy. Mirrors Patter's `HostScopeDecl.writable`\n * name for name (Reboot.md 10, ruled 2026-09-03). Ignored on every other\n * scope. Absent = writable.\n */\n writable?: boolean;\n /**\n * The sharing axis (design/flows.md, Patter's flag adopted): is this\n * property's value one world value across all flows, or a copy per flow?\n * It does NOT change reference syntax - sharing is set here, on the\n * declaration, not by a different scope token. Absent = the scope\n * default: `@story` shared; box, deck, hand and tag properties per-flow.\n * On a `@world` declaration the flag is a validation error - `@world` is\n * the game's own state, always engine-level, never per-flow.\n */\n shared?: boolean;\n purpose?: string;\n}\n\n/** A card-template field (box-defined). Data for the host; the engine never\n * interprets fields and they are not addressable from expressions. */\nexport interface FieldDecl {\n name: string;\n type: PropertyType;\n default: ScalarValue;\n values?: string[];\n purpose?: string;\n}\n\n/** Cooldown policy, in turns (schema 3.4). */\nexport type RedrawPolicy = \"always\" | \"never\" | number;\n\n// --- gameId derivation (Patter's effectiveGameId, adopted 2026-07-20) --------\n//\n// gameId is the renameable host-facing address; it is OPTIONAL in source and\n// derived from the entity's title until the author pins one, so a rename of\n// the title carries the address with it (no \"new-deck\" stuck placeholder).\n// The compiler fills a concrete gameId into every bundle entity.\n\n/** Slugify a human label into a filename- / address-safe gameId. */\nexport function gameIdify(text: string): string {\n return text.toLowerCase().replace(/['’]/g, \"\")\n .replace(/[^a-z0-9-]+/g, \"-\").replace(/-+/g, \"-\").replace(/^-+|-+$/g, \"\");\n}\n\nexport function isValidGameId(gameId: string): boolean {\n return /^[a-z0-9]([a-z0-9-]*[a-z0-9])?$/.test(gameId);\n}\n\n// --- property names (adopted 2026-08-18, with Patter, from one rule) ---------\n//\n// Design and argument: `@wildwinter/app-shell` src/property-names.ts. Not house\n// style: the rule is what `@wildwinter/expr` can parse. Its lexer takes an\n// identifier as /[a-zA-Z_][a-zA-Z0-9_]*/ and folds it to lower case, so\n// `@story.isNight` reaches a property called `isnight`, `@story.9lives` and\n// `@story.not` are parse errors, and `@story.is-night` is not an error at all: it\n// compiles to `@story.is` MINUS the string \"night\". That last one is why the rule\n// is enforced rather than trusted - it is the only violation that silently means\n// something else.\n//\n// Here rather than behind an import of the UI kit because the compiler, the CLI\n// and the embedded runtime resolve state by these. `property-name-parity.test.ts`\n// holds them to the shell's, and `property-name-grammar.test.ts` holds them to the\n// parser they came from.\n\n/** The words `@wildwinter/expr` lexes as keywords, so no property may be called one. */\n// A legal property NAME is a fact about the expression language, not about this\n// model: `not` is reserved because the tokeniser reads it as an operator. Both\n// families kept their own copy of the rule AND of the keyword list, a list\n// neither owned. @wildwinter/expr derives the list from its own tokeniser, so a\n// keyword added there cannot leave a stale copy here.\n//\n// Re-exported so nothing that imports them has to move.\nexport {\n propertyNameify, isValidPropertyName, isCaseOnlyPropertyName, RESERVED_PROPERTY_NAMES,\n} from \"@wildwinter/expr\";\n/** The effective address: a pinned gameId, else derived from the title, else\n * the immutable id (so there is always something addressable). */\nexport function effectiveGameId(entity: { gameId?: string; title?: string; id: string }): string {\n const pinned = entity.gameId?.trim();\n if (pinned) return pinned;\n const fromTitle = entity.title ? gameIdify(entity.title) : \"\";\n return fromTitle || entity.id;\n}\n\n/**\n * The first free gameId of the form `base`, `base-2`, `base-3`, ... not already\n * in `taken`.\n *\n * A gameId is API - `deal()` and the play log speak it - so a name minted for a\n * new or duplicated entity must not collide with an existing one. This lived in\n * two copies, one in the editor and one in the CLI's kit scaffolder, character\n * for character the same; two copies of an addressing rule can drift, and a\n * drift here means the same act produces different addresses depending on which\n * program did it. It is here, beside `gameIdify`, because both programs need it\n * and no UI touches it.\n */\nexport function freeGameId(base: string, taken: ReadonlySet<string>): string {\n let gameId = base;\n for (let n = 2; taken.has(gameId); n++) gameId = `${base}-${n}`;\n return gameId;\n}\n\n/**\n * The first free TITLE of the form `base`, `base 2`, `base 3`, ... whose\n * derived gameId is not already in `taken`.\n *\n * The sibling of `freeGameId` for the \"New box\", \"New deck\" case, where the\n * author is given a title and the address follows from it. The dedupe is on the\n * DERIVED gameId rather than the title, because two titles that slug to one\n * address are the collision that matters.\n */\n/**\n * An id-sorted collection in the order a person should SEE it.\n *\n * Storage is sorted by immutable id (source rule 5) so that two authors adding\n * one item each never touch the same line. That makes array position useless as\n * display order, so the order the author arranged rides in a sparse `order`\n * field, with position as the fallback and id to break a tie.\n *\n * One definition, because this rule has to give the same answer in four places\n * that a reader compares side by side: the compiler (what the bundle carries),\n * the editor (what the card document lists), the exports, and Find. When they\n * disagree, the editor shows one order and the game plays another.\n */\nexport function byDisplayOrder<T extends { id?: string; order?: number }>(items: readonly T[]): T[] {\n return items\n .map((x, i) => ({ x, key: x.order ?? i, i }))\n .sort((a, b) => a.key - b.key || ((a.x.id ?? \"\") < (b.x.id ?? \"\") ? -1 : (a.x.id ?? \"\") > (b.x.id ?? \"\") ? 1 : a.i - b.i))\n .map((e) => e.x);\n}\n\nexport function freeTitle(base: string, taken: ReadonlySet<string>): string {\n let title = base;\n for (let n = 2; taken.has(gameIdify(title)); n++) title = `${base} ${n}`;\n return title;\n}\n\n// --- entities (generic over expression representation E) ---------------------\n\nexport interface Outcome<E> {\n id: string;\n gameId?: string;\n title?: string;\n purpose?: string;\n /** Authored display order (sparse; one without it falls back to its id\n * position). Unlike `Card.order` this one IS compiled into the bundle:\n * which option is offered first is authorial, and a host reading a dealt\n * card's outcomes is building the player's menu. */\n order?: number;\n /** Gating; availability is always evaluated against current state. */\n condition?: E;\n /** Target (\"@scope.name\") -> expression; all right-hand sides evaluate\n * against pre-play state (schema 3.7). */\n changes: Record<string, E>;\n}\n\nexport interface Card<E> {\n id: string;\n gameId?: string;\n title?: string;\n purpose?: string;\n /** Authored display order within the deck (sparse; a card without one falls\n * back to its id position). Merges as a per-card value, so id-sorted storage\n * stays merge-clean (Reboot 7.4); dropped from the compiled bundle. */\n order?: number;\n condition?: E;\n /** Default 0; an expression must evaluate to a number. */\n priority: number | E;\n redraw: RedrawPolicy;\n /** Tags: tag group id -> tag ids. An absent group is a wildcard (matches\n * any binding of it), except the reserved home group, whose default\n * inverts (schema 2.4). Editors and fixtures speak gameIds; stored\n * references are ids. */\n tags?: Record<string, string[]>;\n /** How many hands may hold this card at once (schema 3.5): integer >= 1,\n * default 1. One copy is the exclusivity rule; copies: N is the\n * deliberate opt-out for interchangeable filler. Always counted WITHIN a\n * flow, whether or not the card is shared. */\n copies?: number;\n /** Scarcity across flows (design/shared-scarcity.md). Absent takes the\n * deck's flag; set here it overrides the deck, so a single unique card can\n * stay in the content it belongs to. A shared card's claims count every\n * flow's board, and a shared `redraw: \"never\"` is spent for everyone the\n * first time anyone plays it.\n *\n * A finite `redraw` stays PER FLOW even when shared: a cooldown is an\n * absolute turn of the card's box clock and clocks are per flow, so\n * \"3 turns of whose clock?\" has no answer. A world-wide timer is a @world\n * question, not an engine one (shared-scarcity 9.3.3). */\n shared?: boolean;\n /** The world cap: how many hands ACROSS EVERY FLOW may hold this at once.\n * Read only when the card is shared, and defaults to `copies`, so the\n * common case writes one number and \"five in the world, one to a customer\"\n * is `copies: 1, sharedCopies: 5`. */\n sharedCopies?: number;\n /** Card-template data: field name -> value, validated at publish. */\n fields?: Record<string, ScalarValue>;\n outcomes: Outcome<E>[];\n}\n\nexport interface Deck<E> {\n id: string;\n gameId?: string;\n title?: string;\n purpose?: string;\n /** The deck gate, evaluated once per draw in the draw's environment. */\n condition?: E;\n /** This pile is scarce across flows (design/shared-scarcity.md): every card\n * in it is shared unless the card says otherwise. The container is where\n * Patter puts its own shared-memory flag, and the deck is our container. */\n shared?: boolean;\n properties: PropertyDecl[];\n cards: Card<E>[];\n}\n\nexport interface Tag {\n id: string;\n gameId?: string;\n /**\n * This tag's own starting values for properties its GROUP declares\n * (design/hand-typing.md). The group says what the property IS; a tag says\n * only where it starts, so \"every zone has a haunting level\" is written once\n * and \"the cave starts at 2\" is written where it belongs.\n *\n * A name here that the group does not declare is an error: it would be a\n * value for nothing.\n */\n values?: Record<string, ScalarValue>;\n /** Authored display order (sparse; one without it falls back to its id\n * position). Merges as a per-item value, so id-sorted storage stays\n * merge-clean (Reboot 7.4). */\n order?: number;\n properties?: PropertyDecl[];\n /** Template-of-play extras (e.g. spatial geometry). Source only: preserved\n * in shards, never compiled into the bundle. */\n templates?: Record<string, unknown>;\n}\n\n/** A named axis for cross-cutting cards (schema 2.4, renamed from\n * Dimension). Tags are declared, not freeform. */\nexport interface TagGroup {\n id: string;\n gameId?: string;\n purpose?: string;\n /**\n * A property reference (`\"@story.act\"`) whose value names a tag in this group\n * by gameId. The engine reads it at every ask and binds the group, exactly as\n * if the asking hand had chosen that tag; a hand's own binding wins.\n *\n * For an axis driven by STATE rather than by place: acts, chapters, a\n * difficulty band. Without it, only a hand can bind a group, so such an axis\n * had nowhere to gate and every card needed its own condition.\n *\n * A reference rather than an expression on purpose (design/where-and-\n * selectors.md Part B): a computed binding belongs in a property the outcomes\n * maintain, and an expression here would make this type generic for no gain.\n */\n boundBy?: string;\n /**\n * What omitting this group means for a card. Default false: omission is a\n * wildcard, so the card matches whatever the group is bound to. True inverts\n * it, so a card that names no tag here is unavailable wherever the group IS\n * bound (and unaffected where it is not).\n *\n * `place` is the built-in instance of this pair: bound to the asking hand,\n * and inverted per card rather than per group.\n */\n required?: boolean;\n /** Authored display order (sparse; one without it falls back to its id\n * position). Merges as a per-item value, so id-sorted storage stays\n * merge-clean (Reboot 7.4). */\n order?: number;\n /**\n * Properties EVERY tag in this group has (design/hand-typing.md). The\n * declaration lives here and each tag carries only its own starting value in\n * `Tag.values`, which is the separation the format was missing: a tag's own\n * `properties` entry has to restate the type on every tag purely in order to\n * say the value, and a tag added later silently arrives without it.\n *\n * Compiled by FLATTENING onto each tag, so the bundle keeps its per-tag\n * shape and no runtime, port or bundle schema changes: source is where the\n * author works and where merges happen, the bundle is a compiled artefact\n * that can afford to be explicit.\n *\n * A tag may still declare its own `properties` for a group whose tags\n * genuinely differ. Declaring the same NAME both ways is an error.\n */\n properties?: PropertyDecl[];\n tags: Tag[];\n /** Template-of-play extras for the GROUP, the same bag its tags carry: this is\n * where a group is marked spatial and where that template keeps its own\n * group-level configuration. Source only, preserved but never compiled.\n *\n * A bag rather than a `spatial: true` flag because the marker and the\n * configuration are one thing (see model/spatial.ts), and because core is not\n * meant to grow a field per template of play. */\n templates?: Record<string, unknown>;\n}\n\n/** The reserved tag group (schema 2.4): present in every box without\n * declaration, its tags the box's hand ids. Every hand implicitly binds it to\n * itself; a card that names a place is available only at that place.\n *\n * Called `place` rather than `home` since 2026-08-21: one word for one thing\n * across the format, the editor and the exports. \"Where\" is the QUESTION a\n * card answers (at a place, or anywhere in a region); \"place\" is the direct\n * half of that answer. `home` was a metaphor an author had to learn, and it\n * leaked into hand-edited shards and the docs. */\nexport const PLACE_GROUP = \"place\";\n\n/** A declared kind of hand (schema 2.6): live-inherited, author-side only,\n * never called from game code. One condition governs every instance. */\nexport interface HandTemplate<E> {\n id: string;\n gameId?: string;\n title?: string;\n purpose?: string;\n /** Authored display order (sparse; one without it falls back to its id\n * position). Merges as a per-item value, so id-sorted storage stays\n * merge-clean (Reboot 7.4). */\n order?: number;\n\n /** Fixed tag bindings: tag group id -> tag id. */\n bindings?: Record<string, string>;\n /** The holes: tag group ids each instance fills (one tag each). */\n chooses?: string[];\n /** Shared availability condition, ANDed in (schema 3.1); evaluated per\n * instance against that instance's composed @hand. */\n condition?: E;\n /** Default slot cap. */\n slots: number | \"unbounded\";\n /** Declared @hand state every instance carries. */\n properties: PropertyDecl[];\n}\n\n/** A standalone hand's inline rule (schema 2.6): owned by the hand. */\nexport interface HandRule<E> {\n bindings?: Record<string, string>;\n condition?: E;\n slots: number | \"unbounded\";\n}\n\n/** A hand (schema 2.6): a template instance (template + chosen) or a\n * standalone hand (rule). Exactly one of template / rule. Fully concrete:\n * deal is name-only. */\nexport interface Hand<E> {\n id: string;\n /** The name deal() is called with; a rename is a breaking change\n * (Reboot 7.4). */\n gameId?: string;\n title?: string;\n purpose?: string;\n /** Hand template id (not gameId). */\n template?: string;\n /** Template instances: tag group id -> tag id, one per `chooses` hole. */\n chosen?: Record<string, string>;\n /** Standalone hands: the inline rule. */\n rule?: HandRule<E>;\n /** Override; defaults to the template's / rule's slots. The ONLY template\n * field an instance may override (schema 2.6). */\n slots?: number;\n /** Standalone hands' own @hand state (template instances inherit the\n * template's declarations). */\n properties?: PropertyDecl[];\n /** Authored display order within the box (sparse; authoring-only, never\n * compiled into the bundle - the compiler's explicit field list drops it). */\n order?: number;\n /** Template-of-play extras (e.g. a spatial pin). Source only. */\n templates?: Record<string, unknown>;\n}\n\nexport interface Box<E> {\n id: string;\n gameId?: string;\n title?: string;\n purpose?: string;\n /** The only per-box ranking policy (Reboot 2.2). */\n ranking: { specificity: boolean };\n /** The card template: what every card in this box carries. */\n fields: FieldDecl[];\n properties: PropertyDecl[];\n tagGroups: TagGroup[];\n decks: Deck<E>[];\n handTemplates: HandTemplate<E>[];\n hands: Hand<E>[];\n}\n\n// --- the compiled bundle (.storyletsc) ---------------------------------------\n\nexport const BUNDLE_SCHEMA = \"storylets/bundle@0\";\n\n/** Binds bundles to shards (staleness gate) and saves to bundles. */\nexport interface BundleContent {\n project: string;\n version: string;\n /** hash32 over the canonical source shards (schema 2.8). */\n hash: string;\n}\n\nexport interface BundleSettings {\n playAdvancesTurns: number;\n}\n\n/**\n * A map that a bundle was asked to carry: one spatial tag group's geometry,\n * flattened for a host to draw (design/graphical-views.md 2, \"The map MAY ship\").\n *\n * INERT PAYLOAD. Nothing in the engine reads this and nothing ever will: the\n * runtime deals in tag names. It is here so a host that wants an in-game map does\n * not have to invent its own export, and it is absent unless the project asked\n * for it (`export.map`), so a build that does not want a map carries no bytes.\n *\n * GAME IDS throughout, never internal ids. Internal ids are authoring identity\n * and mean nothing outside the project; a host matches these against the same\n * names it passes to `peek`. There is nothing here to strip either, which is why\n * `metadata: \"stripped\"` needs no special case: no titles, no purposes.\n *\n * Sites are deliberately NOT here. A site is where an author parked a hand while\n * working, held in the view sidecar precisely because it is not content, and a\n * host that wants to place a hand already has its zone from the compiled binding.\n */\nexport interface BundleMap {\n /** The owning box, by gameId (tag groups are box-scoped). */\n box: string;\n /** The tag group this is a map of, by gameId. */\n group: string;\n /** One entry per zone that has been drawn; a tag with no polygon is not a\n * place yet and is left out rather than shipped as an empty shape. */\n zones: { tag: string; polygon: ViewPoint[] }[];\n /** Background pictures, back to front, as bundle-relative paths. Hidden ones\n * do not ship: what an author put away is not something to spring on a host. */\n backgrounds?: BundleBackground[];\n}\n\n/** One shipped picture. `locked` and `hidden` are authoring state and do not\n * travel; the draw order is the array order. */\nexport interface BundleBackground {\n /** Where the file sits relative to the bundle (\"assets/<box>/<file>\"). */\n file: string;\n x: number;\n y: number;\n width: number;\n height: number;\n opacity?: number;\n}\n\nexport interface Bundle {\n schema: typeof BUNDLE_SCHEMA;\n content: BundleContent;\n metadata: \"full\" | \"stripped\";\n settings: BundleSettings;\n world: {\n properties: PropertyDecl[];\n /** ScopeRegistrySpec (@wildwinter/scoperegistry): the owned/foreign\n * split. Absent = engine-owned @world (standalone play). */\n registry?: unknown;\n };\n story: {\n properties: PropertyDecl[];\n };\n boxes: Box<Expression>[];\n /** Maps, when the project asked for them. Absent is the normal state. */\n maps?: BundleMap[];\n}\n\n// --- the save envelope --------------------------------------------------------\n\nexport const SAVE_SCHEMA = \"storylets/save@1\";\n\nexport interface PlayRecord {\n /** Card and outcome by gameId (feeds the play-history functions). */\n card: string;\n outcome: string;\n turn: number;\n}\n\n/** A property bag: name -> value. */\nexport type PropertyBag = Record<string, ScalarValue>;\n\n/** The per-scope property partitions one side of the sharing flag holds:\n * a save carries one of these for the shared values and one per flow\n * (design/flows.md). NO world key, in either: @world is the game's own\n * state, resolved through the world resolver and saved by whoever owns\n * it - \"host saves its container once, each engine saves its own\n * envelope\" (engine-runtimes.md 3.1). */\nexport interface PropsPartition {\n story: PropertyBag;\n box: Record<string, PropertyBag>;\n deck: Record<string, PropertyBag>;\n hand: Record<string, PropertyBag>;\n /** Tag state, keyed by tag id. */\n value: Record<string, PropertyBag>;\n}\n\n/** One flow's snapshot inside the envelope (schema 4). */\nexport interface FlowSave {\n /** The per-flow property partitions. */\n props: PropsPartition;\n /** Per-box turn counters, keyed by box id (schema 3.4) - per flow: there\n * is deliberately no global turn. */\n turns: Record<string, number>;\n /** mulberry32 state, uint32 (schema 3.3), per flow. */\n prng: number;\n /** Absolute next-eligible turn (of the card's box's clock) per card id;\n * MAX_SAFE_INTEGER = never (deliberately not Infinity, which\n * JSON-serialises to null). */\n cooldowns: Record<string, number>;\n /** Hand contents (card ids, in dealt order), keyed by hand id. The claims\n * ledger is derived from this (schema 3.5). */\n board: Record<string, string[]>;\n playLog: PlayRecord[];\n}\n\n/** The whole engine, one envelope: the shared partitions once, then every\n * live flow keyed by its id - Patter's shape (one shared blob + N flow\n * blobs; multi-flow and save/load are the same feature). */\n/** The engine's half of a save: what every flow shares. Properties, and the\n * cards a shared `redraw: \"never\"` has taken out of the world for good\n * (design/shared-scarcity.md). Claims are NOT here: they are derived from the\n * live boards, and each flow's board rides its own blob. */\nexport interface SharedSave {\n props: PropsPartition;\n /** Card ids, sorted, so a save is byte-stable for a diff. */\n spent: string[];\n}\n\nexport interface SaveEnvelope {\n schema: typeof SAVE_SCHEMA;\n content: BundleContent;\n shared: SharedSave;\n flows: Record<string, FlowSave>;\n}\n\n/** The .storyletsave FILE: the HOST's file, not the engine's - the engine's\n * envelope plus, when the host keeps one, its @world container. This is\n * \"host saves its container once, each engine saves its own envelope\"\n * folded into one file for the single-host case; the ENGINE never reads or\n * writes `world` (loadGame takes the envelope alone). */\nexport const SAVEFILE_SCHEMA = \"storylets/savefile@1\";\n\nexport interface SaveFile {\n schema: typeof SAVEFILE_SCHEMA;\n engine: SaveEnvelope;\n /** The host's @world values, saved and restored by the host. */\n world?: PropertyBag;\n}\n\n// --- source shards (design/storylets-source.md) --------------------------------\n\n/** The project folder: a macOS package, a plain folder elsewhere. */\nexport const PROJECT_FOLDER_EXTENSION = \".storylets\";\n/** The compiled bundle (strict JSON; generated, never hand-edited). */\nexport const BUNDLE_EXTENSION = \".storyletsc\";\n\n/**\n * Where a shipped background sits, relative to the bundle file.\n *\n * One function so the compiler (which writes the name into the bundle) and the\n * export op (which writes the bytes) cannot drift apart: a path agreed in two\n * places is a path that eventually disagrees. Per BOX, because two boxes may\n * each have their own `plan.png` and a build must not silently keep one of them.\n */\nexport const bundleAssetPath = (boxGameId: string, file: string): string =>\n `assets/${boxGameId}/${file}`;\n/** Per-type shard extensions, JSON5 inside (source doc section 2). */\nexport const SHARD_EXTENSIONS = {\n project: \".storyletproj\",\n box: \".storyletbox\",\n tags: \".storylettags\",\n hands: \".storylethands\",\n deck: \".storyletdeck\",\n /** The arrangement layer: where things SIT, never what they are. Its own shard\n * because positions churn (an afternoon of tidying a canvas touches every\n * card) and content does not, so a designer arranging and a writer editing\n * never collide on one file (design/graphical-views.md section 1.2). */\n view: \".storyletview\",\n /** Threaded comments: content-ADJACENT, so neither in a content shard (a\n * writer's deck edit must not conflict with a reviewer's comment) nor in the\n * arrangement sidecar (this is not where anything sits). One per box,\n * id-keyed (design/annotation.md). Documentation NOTES used to share this\n * file and were retired: `purpose` already says why a thing exists, and\n * Patterpad's typed routing has no destination here. */\n notes: \".storyletnotes\",\n} as const;\n\nexport const PROJECT_SCHEMA = \"storylets/project@0\";\nexport const BOX_SCHEMA = \"storylets/box@0\";\nexport const TAGS_SCHEMA = \"storylets/tags@0\";\nexport const HANDS_SCHEMA = \"storylets/hands@0\";\nexport const DECK_SCHEMA = \"storylets/deck@0\";\nexport const VIEW_SCHEMA = \"storylets/view@0\";\n/** The comment sidecar's schema. Still called \"notes\" on disk: the file already\n * held both, and renaming it would break every project for no gain. */\nexport const NOTES_SCHEMA = \"storylets/notes@0\";\n\n/** A point in a canvas's own coordinates. */\nexport interface ViewPoint {\n x: number;\n y: number;\n}\n\n/**\n * Canvas furniture: what an author draws AROUND the content to make sense of it\n * (design/graphical-views.md 3, \"Frames and sites\").\n *\n * Both canvases carry the same thing, which is why they share a type: a node\n * canvas and a map are different views of different material, but \"put a box\n * round this lot and call it act two\" is the same thought on either.\n *\n * It lives in the view sidecar because it is ARRANGEMENT. Nothing here is\n * content: no runtime reads it, no bundle carries it, and deleting the sidecar\n * loses only the drawing. Threaded comments are the\n * other thing entirely - they attach to entities and they travel - but a canvas\n * DRAWS their markers, while owning none of them.\n */\nexport interface CanvasFurniture {\n /** Titled areas behind the content, back to front (see `stacked`).\n *\n * There was a second kind, a `stickies` list, retired on 2026-08-10\n * (design/annotation.md): a dropped comment marker does the same job in a\n * fraction of the space, and an annotation that takes as much room as the\n * thing it is about is a bad trade on a canvas. */\n frames?: Frame[];\n}\n\n/**\n * A titled area behind a group of things: Unreal's comment box.\n *\n * Deliberately dumb about what is inside it. It has no membership list and\n * computes none: a frame is a thing an author DREW, and the cards under it are\n * whatever happens to be under it now. That is what keeps it honest when content\n * moves, and it is the same reasoning that keeps a zone's sites out of the map's\n * sidecar.\n */\nexport interface Frame extends ViewPoint {\n id: string;\n w: number;\n h: number;\n /** Shown in the frame's bar, and the handle it is dragged by. */\n title?: string;\n /** One of the furniture palette's names (see `FURNITURE_COLOURS`); the theme\n * decides what that looks like, so a frame does not carry a hex value that\n * would fight the palette on the day somebody switches theme. */\n colour?: string;\n /** Place in the frame band (sparse, `stacked`). Frames can nest. */\n z?: number;\n}\n\n/** The furniture palette: names, not colours. The theme maps them, so the same\n * shard reads correctly on linen and on baize. */\nexport const FURNITURE_COLOURS = [\"paper\", \"amber\", \"sage\", \"sky\", \"rose\", \"slate\"] as const;\nexport type FurnitureColour = typeof FURNITURE_COLOURS[number];\n\n/** One deck's node canvas: where its cards sit, and the furniture around them.\n * Sparse throughout. A card with no entry lays out by default, and an entry for\n * a card that no longer exists is inert, so there is no referential integrity to\n * maintain against content that moves underneath. */\nexport interface DeckCanvas extends CanvasFurniture {\n /** Keyed by CARD id. */\n cards?: Record<string, ViewPoint>;\n}\n\n/** The box's map: where its hands sit in space, and the furniture around them. */\nexport interface BoxMap extends CanvasFurniture {\n /** Keyed by HAND id. WHERE a site is, and nothing else.\n *\n * Which zone it is IN is not recorded here, and deliberately (2026-08-06,\n * with the rebinding drag): a hand that binds a zone already says so in its\n * own shard, as `chosen` or as a rule binding, and that is the truth the\n * runtime deals from. A copy here could only ever go on to disagree with it,\n * and a site whose recorded zone contradicts the hand it stands for would be\n * the most misleading thing on the map.\n *\n * Called `pins` until 2026-08-10 (design/annotation.md). No compatibility\n * branch: the only projects that exist are the examples in this repo, and they\n * were edited. */\n sites?: Record<string, ViewPoint>;\n}\n\n/** The arrangement layer for one box: where things SIT, never what they are.\n *\n * Its own shard on purpose (design/graphical-views.md section 1.2). Positions\n * churn, content does not: an afternoon of tidying a canvas touches every card,\n * and if that lived in the deck shard then a designer arranging and a writer\n * editing card text would collide on one file all day, while a content review\n * would be full of coordinates. Keyed by id throughout so the existing merge\n * engine handles two designers rearranging different things without a conflict.\n *\n * Source-only. It never reaches the compiled bundle, exactly as `order` does\n * not: the compiler reads the fields it names and this is not among them. */\nexport interface ViewShard {\n schema: typeof VIEW_SCHEMA;\n /** Keyed by DECK id: one node canvas each. */\n canvases?: Record<string, DeckCanvas>;\n map?: BoxMap;\n}\n\n/** A coverage input driver: during a coverage run the harness feeds a\n * host-seam property (`@world.x`) values from `values`, so content gated on\n * external state gets exercised (Patter's coverageDrivers, carried whole). */\nexport interface CoverageDriver {\n /** \"initial\": set once as each playthrough starts. \"recurring\": re-rolled\n * per turn at the cadence, so one run passes through several states. */\n kind: \"initial\" | \"recurring\";\n /** For recurring drivers: how often to re-roll per turn (default \"sometimes\"). */\n cadence?: \"rarely\" | \"sometimes\" | \"often\";\n /** The pool the harness picks from (uniform). Empty = inert. */\n values: ScalarValue[];\n}\n\n/** Authoring-side coverage configuration (never compiled into the bundle). */\nexport interface CoverageConfig {\n /** Property drivers, keyed by ref (\"@world.danger\"). */\n drivers?: Record<string, CoverageDriver>;\n\n}\n\nexport interface ProjectShard {\n schema: typeof PROJECT_SCHEMA;\n project: {\n id: string;\n name: string;\n version: string;\n };\n settings: BundleSettings;\n /** Coverage drivers + argument domains (authoring/testing config; stays\n * out of the compiled bundle). */\n coverage?: CoverageConfig;\n /** Validation switches (authoring config; never compiled). Off is written\n * as ABSENT, like `export.map`: a shard says what an author chose. */\n validation?: {\n /** Also warn when state is WRITTEN but nothing reads it. Off by default:\n * cards are routinely written ahead of the content that will read them,\n * so mid-development this warning is mostly noise. The read side (a gate\n * on state nothing writes) always warns, because that kills cards now. */\n warnUnreadWrites?: boolean;\n };\n world: {\n properties: PropertyDecl[];\n registry?: unknown;\n };\n story: {\n properties: PropertyDecl[];\n };\n /** Templates of play: configuration bags keyed by template name. Core\n * validates only what it knows. */\n templates: Record<string, unknown>;\n export: {\n bundle: string;\n metadata: \"full\" | \"stripped\";\n /**\n * Does a `.storyletpack` carry the boxes' binary assets (background images)?\n *\n * Default false, and a project-level DEFAULT rather than a rule: a pack is a\n * delivery, so the caller can override it per pack (2026-08-07). Some\n * projects would benefit from sending their pictures in certain\n * circumstances and others never would, which is why neither \"always\" nor\n * \"never\" is the answer.\n *\n * Nothing to do with the compiled bundle, which has its own switch: `map`.\n */\n packAssets?: boolean;\n /**\n * Does the compiled bundle carry the maps (zone shapes and background\n * pictures)?\n *\n * Default false, and the default matters: geometry is authoring data, the\n * runtime deals in tag names, and a shipping build should carry nothing it\n * does not use. But a host that wants an in-game map should not have to\n * invent its own export, and it is most useful early - a prototype with a\n * real map beats a prototype with a list of zone names.\n *\n * It sits beside `metadata` on purpose: that is already the switch for\n * \"authoring data that may or may not ship\", and this is its sibling rather\n * than a new concept. With it on, `export` also writes the background files\n * next to the bundle, and `describeBundle` says what is in there.\n */\n map?: boolean;\n };\n}\n\nexport interface BoxShard {\n schema: typeof BOX_SCHEMA;\n box: {\n id: string;\n gameId?: string;\n title?: string;\n purpose?: string;\n /** Authored display order among boxes (sparse; absent falls back to the\n * folder-name position). Authoring-only, like a card's (never compiled\n * into the bundle); merges as a per-field value. */\n order?: number;\n ranking: { specificity: boolean };\n fields: FieldDecl[];\n properties: PropertyDecl[];\n };\n}\n\n/** The box's tag groups: how its cards are filed. */\nexport interface TagsShard {\n schema: typeof TAGS_SCHEMA;\n groups: TagGroup[];\n}\n\n/** The box's hand templates + hands (the writer/programmer contract). */\nexport interface HandsShard {\n schema: typeof HANDS_SCHEMA;\n templates: HandTemplate<string>[];\n hands: Hand<string>[];\n}\n\nexport interface DeckShard {\n schema: typeof DECK_SCHEMA;\n deck: {\n id: string;\n gameId?: string;\n title?: string;\n purpose?: string;\n condition?: string;\n /** Scarce across flows: see Deck.shared. */\n shared?: boolean;\n /** Authored display order within the box (sparse; see BoxShard). */\n order?: number;\n properties: PropertyDecl[];\n };\n cards: Card<string>[];\n}\n\n// --- templates of play --------------------------------------------------------\n// The spatial template's types, field access and geometry. Re-exported here so the\n// package has one entry point, and kept in its own module because core schema and\n// a template of play are different things (Reboot 6).\nexport * from \"./spatial.js\";\n\n// How a hand reaches a tag group, and whether that binding is the hand's own to\n// change. Core schema rather than a template of play, but the map is what needed\n// it said out loud.\nexport * from \"./hands.js\";\n\n// Frames: what an author draws around the content. Arrangement,\n// so it lives in the sidecar and reads forgivingly (furniture.ts says why).\nexport * from \"./furniture.js\";\n\n// Threaded comments: the conversation about a thing, in its own sidecar.\nexport * from \"./comments.js\";\n\n// Guessing a property's type from what an outcome writes: the quick fix's input.\nexport * from \"./infer.js\";\n","// ---------------------------------------------------------------------------\n// Save-file plumbing over the .storyletsave file (storylets/savefile@1): the\n// HOST's file - the engine's envelope (storylets/save@1, shared partitions +\n// every flow) plus, when the host keeps one, its @world container. That is\n// \"host saves its container once, each engine saves its own envelope\"\n// (design/flows.md) folded into one file for the single-host case. These\n// helpers are the string boundary - a foreign or malformed blob throws\n// rather than corrupting a run.\n// ---------------------------------------------------------------------------\n\nimport { SAVEFILE_SCHEMA, SAVE_SCHEMA } from \"@storylet-studio/model\";\nimport type { PropertyBag, SaveFile } from \"@storylet-studio/model\";\nimport type { Engine } from \"@storylet-studio/runtime\";\n\n/** The current engine state (and the host's @world values, if given) as\n * pretty-printed .storyletsave JSON. */\nexport function serializeState(engine: Engine, world?: PropertyBag): string {\n return JSON.stringify(saveState(engine, world), null, 2);\n}\n\n/**\n * Capture the whole engine (and the host's @world values, if it keeps any) as\n * the tagged save-file OBJECT.\n *\n * Four verbs, in Patterplay's pairing (`patter` play-helpers `save.ts`, and\n * the same in all four of its runtimes): saveState / loadState work on the\n * PARSED object, serializeState / deserializeState work on TEXT.\n *\n * This reference had a different shape until 2026-08-29 - `deserializeState`\n * parsed and did not restore, `loadState` took text - so one name meant two\n * things across the four Storylets runtimes, and neither matched the family.\n * Godot and Unreal already had Patter's shape; these two were brought to it.\n */\nexport function saveState(engine: Engine, world?: PropertyBag): SaveFile {\n return {\n schema: SAVEFILE_SCHEMA,\n engine: engine.saveGame(),\n ...(world !== undefined ? { world } : {}),\n };\n}\n\n/** Restore a {@link saveState} file into an engine. EVERY FLOW IS REBUILT, so\n * the Flow handles you held before are inert: re-take them with\n * `engine.getFlow(id)`, NOT `engine.openFlow(id)`. `openFlow` on an existing\n * id REPLACES it, which here throws away the hand the file just restored, and\n * the failure lands later, as `play()` refusing a card as \"not dealt\". (The\n * engine's `onReplacedFlow` hook reports exactly this.) Throws on a foreign or malformed\n * file, and the runtime's own project check still applies. Returns the file's\n * @world values, if any - the HOST applies them to its container; the engine\n * never touches them. */\nexport function loadState(engine: Engine, file: SaveFile): PropertyBag | undefined {\n if (!file || typeof file !== \"object\"\n || file.schema !== SAVEFILE_SCHEMA || file.engine?.schema !== SAVE_SCHEMA) {\n throw new Error(`not a storylets save (expected schema \"${SAVEFILE_SCHEMA}\")`);\n }\n engine.loadGame(file.engine);\n return file.world;\n}\n\n/** Parse + restore a {@link serializeState} string: the TEXT twin of\n * loadState, as Patterplay pairs them. Throws on malformed JSON, a foreign\n * file or a project mismatch. Returns the file's @world values for the host. */\nexport function deserializeState(engine: Engine, json: string): PropertyBag | undefined {\n let parsed: unknown;\n try {\n parsed = JSON.parse(json);\n } catch {\n throw new Error(\"not valid JSON\");\n }\n return loadState(engine, parsed as SaveFile);\n}\n","// ---------------------------------------------------------------------------\n// The property examiner/editor, JS idiom: a self-styled DOM panel (the\n// parity member Unity renders as an EditorWindow, Unreal as a Slate tab,\n// Godot as an in-game panel). Rows come from live().listProperties() and\n// are built once (declared properties are fixed for a bundle); values\n// refresh on a poll that SKIPS the focused widget; every row has a\n// reset-to-default that disables itself at the default. Edits commit via\n// flow.setProperty, which is a silent host write under the firing rule.\n// Save state / Load state carry the whole run over the .storyletsave string\n// boundary (save.ts); a filter narrows the property rows; the read-only\n// turns and board sections mirror the engine examiners (design 2.4).\n// The JS game runs in-process, so the engine and a flow are passed directly\n// (no debug registry needed here).\n//\n// The log panel (design 2.3: the flow's retained log surfaced in every\n// examiner; the old port's Unreal log panel is the high-water mark): the\n// lines of live().log() behind per-kind filters (a peek files under Deal -\n// both are asks), with Autoscroll, Copy and Clear. Empty until the engine\n// is created with the log option.\n// ---------------------------------------------------------------------------\n/// <reference lib=\"dom\" />\n\nimport type { Engine, EngineLogEntry, Flow, LogEntry, PropertyRow } from \"@storylet-studio/runtime\";\nimport type { ScalarValue } from \"@storylet-studio/model\";\nimport { serializeState, deserializeState } from \"./save.js\";\n\nexport interface PropertyInspectorOptions {\n /** Mount point; defaults to document.body. */\n container?: HTMLElement;\n title?: string;\n /** Value-refresh poll; 0 disables polling. */\n pollMs?: number;\n}\n\nexport interface PropertyInspector {\n el: HTMLElement;\n refresh(): void;\n destroy(): void;\n}\n\nconst STYLE_ID = \"sl-inspector-style\";\nconst CSS = `\n.sl-insp { font: 12px system-ui, sans-serif; color: var(--ink, #222); background: var(--surface, #fafafa);\n border: 1px solid var(--line, #ccc); border-radius: 8px; padding: 10px 12px; max-width: 26rem; }\n.sl-insp h3 { margin: 0 0 8px; font-size: 12px; text-transform: uppercase; letter-spacing: 0.06em;\n color: var(--muted, #666); }\n.sl-insp .sl-head { display: flex; align-items: baseline; gap: 6px; }\n.sl-insp .sl-head h3 { flex: 1; }\n.sl-insp .sl-save, .sl-insp .sl-load { font: inherit; font-size: 11px; padding: 1px 6px; cursor: pointer; }\n.sl-insp .sl-filter { display: block; width: 100%; box-sizing: border-box; margin: 0 0 6px; }\n.sl-insp .sl-group { margin: 8px 0 2px; font-weight: 600; font-size: 11px; color: var(--muted, #666); }\n.sl-insp .sl-section { margin: 10px 0 2px; font-weight: 600; font-size: 11px; text-transform: uppercase;\n letter-spacing: 0.06em; color: var(--muted, #666); }\n.sl-insp .sl-line { padding: 1px 0; }\n.sl-insp .sl-row { display: flex; align-items: center; gap: 6px; padding: 2px 0; }\n.sl-insp .sl-name { flex: 1; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }\n.sl-insp input[type=\"text\"], .sl-insp input[type=\"number\"], .sl-insp select {\n font: inherit; width: 9rem; padding: 1px 4px; }\n.sl-insp .sl-reset { border: 0; background: none; cursor: pointer; color: var(--muted, #666); }\n.sl-insp .sl-reset:disabled { opacity: 0.3; cursor: default; }\n.sl-insp .sl-logbar { display: flex; flex-wrap: wrap; align-items: center; gap: 8px; padding: 2px 0; }\n.sl-insp .sl-logbar label { display: inline-flex; align-items: center; gap: 2px; }\n.sl-insp .sl-logbar button { font: inherit; font-size: 11px; padding: 1px 6px; cursor: pointer; }\n.sl-insp .sl-log { font-family: ui-monospace, monospace; font-size: 11px; max-height: 12rem;\n overflow: auto; white-space: pre; border: 1px solid var(--line, #ccc); padding: 4px 6px; }\n.sl-insp details.sl-fold > summary { cursor: pointer; margin: 10px 0 2px; font-weight: 600;\n font-size: 11px; text-transform: uppercase; letter-spacing: 0.06em; color: var(--muted, #666); }\n.sl-insp .sl-ident { font-family: ui-monospace, monospace; font-size: 11px; }\n.sl-insp .sl-ident b { font-weight: 600; }\n.sl-insp .sl-note { color: var(--muted, #666); }\n`;\n\n/** Inject the shared panel stylesheet once. Exported so the bundle inspector\n * (bundle-inspector.ts) renders in the same CSS grammar. */\nexport function ensureInspectorStyle(): void {\n if (document.getElementById(STYLE_ID)) return;\n const style = document.createElement(\"style\");\n style.id = STYLE_ID;\n style.textContent = CSS;\n document.head.append(style);\n}\n\nconst eq = (a: ScalarValue | undefined, b: ScalarValue | undefined): boolean =>\n JSON.stringify(a) === JSON.stringify(b);\n\n// --- the log panel (design 2.3) ---------------------------------------------\n\n/** The filterable kinds; a peek files under \"deal\" (both are asks). */\nconst LOG_KINDS = [\"deal\", \"play\", \"write\", \"evict\", \"turns\", \"diagnostic\"] as const;\nconst LOG_KIND_LABELS: Record<(typeof LOG_KINDS)[number], string> = {\n deal: \"Deal\", play: \"Play\", write: \"Write\", evict: \"Evict\", turns: \"Turns\", diagnostic: \"Diag\",\n};\n\nconst logKindOf = (e: LogEntry): (typeof LOG_KINDS)[number] =>\n e.type === \"peek\" ? \"deal\" : e.type;\n\nconst showVal = (v: ScalarValue | undefined): string =>\n v === undefined ? \"<unset>\" : JSON.stringify(v);\n\n/** One line per entry, `[turn]`-stamped where the event has a box context\n * (write lines share the state logger's `path: from -> to` reading). */\nexport function formatLogEntry(e: LogEntry | EngineLogEntry): string {\n // The run's log names the flow that acted, after the turn stamp and in the\n // same place all four examiners put it; a flow's own log omits it, because\n // its section heading already says whose it is.\n return formatLogBody(e, \"flow\" in e && e.flow ? `${e.flow} ` : \"\");\n}\n\nfunction formatLogBody(e: LogEntry, flow: string): string {\n const stamp = (e.turn !== undefined ? `[${e.turn}] ` : \"[-] \") + flow;\n switch (e.type) {\n case \"deal\": {\n const dealt = e.cards.filter((c) => c.verdict === \"dealt\").map((c) => c.id);\n return `${stamp}deal ${e.hand}: ${dealt.length > 0 ? dealt.join(\", \") : \"(none)\"} (${e.cards.length} considered)`;\n }\n case \"peek\": {\n const crit = Object.entries(e.criteria).map(([g, t]) => `${g}=${t}`).join(\", \");\n const listed = e.cards.filter((c) => c.verdict === \"dealt\").map((c) => c.id);\n return `${stamp}peek ${e.box}${crit ? ` [${crit}]` : \"\"}: `\n + `${listed.length > 0 ? listed.join(\", \") : \"(none)\"} (${e.cards.length} considered)`;\n }\n case \"evict\": return `${stamp}evict ${e.card} from ${e.hand} (${e.reason})`;\n case \"play\": return `${stamp}play ${e.card} -> ${e.outcome}`;\n case \"write\": return `${stamp}write ${e.path}: ${showVal(e.prev)} -> ${showVal(e.value)}`;\n case \"turns\": return `${stamp}turns ${e.box} -> ${e.turn}`;\n default: return `${stamp}diagnostic ${e.where}: ${e.message}`;\n }\n}\n\n/** The group label a row files under (\"world\", \"story\", \"box <id>\", ...). */\nconst groupOf = (path: string): string => {\n const parts = path.split(\".\");\n return parts.length === 3 ? `${parts[0]} ${parts[1]}` : parts[0]!;\n};\n\nexport function createPropertyInspector(engine: Engine, flow: Flow, opts: PropertyInspectorOptions = {}): PropertyInspector {\n ensureInspectorStyle();\n\n // loadGame rebuilds every flow and the handle we were given goes inert\n // (the runtime's stale-handle rule), so every read goes through this\n // accessor and Load state re-takes the same-named flow.\n let liveFlow = flow;\n const live = (): Flow => liveFlow;\n\n const el = document.createElement(\"div\");\n el.className = \"sl-insp\";\n\n // Header: the title plus Save state / Load state (the .storyletsave\n // string boundary, in every examiner - the parity rule, design 2.4).\n const head = document.createElement(\"div\");\n head.className = \"sl-head\";\n const h = document.createElement(\"h3\");\n h.textContent = opts.title ?? \"Runtime state\";\n head.append(h);\n\n const saveBtn = document.createElement(\"button\");\n saveBtn.type = \"button\";\n saveBtn.className = \"sl-save\";\n saveBtn.textContent = \"Save state\";\n saveBtn.addEventListener(\"click\", () => {\n const blob = new Blob([serializeState(engine)], { type: \"application/json\" });\n const url = URL.createObjectURL(blob);\n const a = document.createElement(\"a\");\n a.href = url;\n a.download = \"save.storyletsave\";\n a.click();\n URL.revokeObjectURL(url);\n });\n head.append(saveBtn);\n\n const filePicker = document.createElement(\"input\");\n filePicker.type = \"file\";\n filePicker.accept = \".storyletsave,application/json\";\n filePicker.hidden = true;\n filePicker.addEventListener(\"change\", () => {\n const file = filePicker.files?.[0];\n if (!file) return;\n const reader = new FileReader();\n reader.onload = () => {\n // A foreign or malformed blob is refused by deserializeState, never applied.\n try {\n deserializeState(engine, String(reader.result));\n liveFlow = engine.getFlow(flow.id) ?? engine.openFlow(flow.id);\n refresh();\n } catch (e) {\n console.error(\"storylets inspector: load failed:\", e instanceof Error ? e.message : e);\n }\n filePicker.value = \"\";\n };\n reader.readAsText(file);\n });\n\n const loadBtn = document.createElement(\"button\");\n loadBtn.type = \"button\";\n loadBtn.className = \"sl-load\";\n loadBtn.textContent = \"Load state\";\n loadBtn.addEventListener(\"click\", () => filePicker.click());\n head.append(loadBtn, filePicker);\n el.append(head);\n\n // The property filter (name/path substring, case-blind - the parity\n // member Unreal renders as an SSearchBox).\n const filter = document.createElement(\"input\");\n filter.type = \"text\";\n filter.className = \"sl-filter\";\n filter.placeholder = \"Filter properties\";\n el.append(filter);\n\n // Rows are built once: the declared surface is fixed for a bundle. The\n // filter only toggles visibility (a group hides with its last row).\n const editors: { row: PropertyRow; read: () => void }[] = [];\n const groups: { el: HTMLElement; rows: { el: HTMLElement; text: string }[] }[] = [];\n let lastGroup = \"\";\n for (const row of live().listProperties()) {\n const group = groupOf(row.path);\n if (group !== lastGroup) {\n const g = document.createElement(\"div\");\n g.className = \"sl-group\";\n g.textContent = group;\n el.append(g);\n groups.push({ el: g, rows: [] });\n lastGroup = group;\n }\n const rowEl = buildRow(live, row, editors);\n groups[groups.length - 1]!.rows.push({ el: rowEl, text: `${row.name} ${row.path}`.toLowerCase() });\n el.append(rowEl);\n }\n\n filter.addEventListener(\"input\", () => {\n const q = filter.value.trim().toLowerCase();\n for (const group of groups) {\n let any = false;\n for (const row of group.rows) {\n const show = q === \"\" || row.text.includes(q);\n row.el.style.display = show ? \"\" : \"none\";\n any = any || show;\n }\n group.el.style.display = any ? \"\" : \"none\";\n }\n });\n\n // Read-only: each box's clock, then the board's current hands (title or\n // gameId, never internal ids) - the same sections as the engine examiners.\n const turnsHead = document.createElement(\"div\");\n turnsHead.className = \"sl-section\";\n turnsHead.textContent = \"Turns (per box)\";\n const turnsBody = document.createElement(\"div\");\n turnsBody.className = \"sl-turns\";\n const boardHead = document.createElement(\"div\");\n boardHead.className = \"sl-section\";\n boardHead.textContent = \"Board\";\n const boardBody = document.createElement(\"div\");\n boardBody.className = \"sl-board\";\n el.append(turnsHead, turnsBody, boardHead, boardBody);\n\n // A retained log (design 2.3), behind per-kind filters, with Autoscroll,\n // Copy and Clear - the JS rendering of the engine examiners' log panel.\n // Built twice: once for the RUN (every flow's events in one order, each line\n // naming its flow) and once for this flow's own. Both exist because a flow's\n // log cannot show a story action in another flow moving shared state\n // (design/shared-scarcity.md 8.2). Empty until the engine had the log option.\n const check = (text: string, onChange: (on: boolean) => void, cls: string): HTMLLabelElement => {\n const label = document.createElement(\"label\");\n label.className = cls;\n const box = document.createElement(\"input\");\n box.type = \"checkbox\";\n box.checked = true;\n box.addEventListener(\"change\", () => onChange(box.checked));\n label.append(box, text);\n return label;\n };\n\n interface LogPanel { render: (force?: boolean) => void }\n const buildLogPanel = (\n which: \"flow\" | \"run\",\n caption: string,\n entriesOf: () => readonly (LogEntry | EngineLogEntry)[],\n clear: () => void,\n empty: string,\n ): LogPanel => {\n // Both panels carry the same controls, so each element takes a `sl-flow` /\n // `sl-run` modifier: without one, a selector for \"the Clear button\" is\n // ambiguous, which is exactly what the inspector test caught.\n const head = document.createElement(\"div\");\n head.className = `sl-section sl-${which}`;\n head.textContent = caption;\n const bar = document.createElement(\"div\");\n bar.className = `sl-logbar sl-${which}`;\n const body = document.createElement(\"div\");\n body.className = `sl-log sl-${which}`;\n\n const kindOn = new Map<string, boolean>();\n const visibleLines = (): string[] =>\n entriesOf().filter((e) => kindOn.get(logKindOf(e)) !== false).map(formatLogEntry);\n let autoscroll = true;\n let stampSeen = \"\";\n const render = (force = false): void => {\n const entries = entriesOf();\n const stamp = `${entries.length}:${entries.length > 0 ? entries[entries.length - 1]!.seq : -1}`;\n if (!force && stamp === stampSeen) return;\n stampSeen = stamp;\n const lines = visibleLines();\n body.textContent = lines.length > 0 ? lines.join(\"\\n\") : empty;\n if (autoscroll) body.scrollTop = body.scrollHeight;\n };\n\n for (const kind of LOG_KINDS) {\n kindOn.set(kind, true);\n bar.append(check(LOG_KIND_LABELS[kind], (on) => {\n kindOn.set(kind, on);\n render(true);\n }, \"sl-logkind\"));\n }\n bar.append(check(\"Autoscroll\", (on) => { autoscroll = on; }, \"sl-logscroll\"));\n const copyBtn = document.createElement(\"button\");\n copyBtn.type = \"button\";\n copyBtn.className = \"sl-logcopy\";\n copyBtn.textContent = \"Copy\";\n copyBtn.title = \"Copy the visible (filtered) log to the clipboard\";\n copyBtn.addEventListener(\"click\", () => { void navigator.clipboard?.writeText(visibleLines().join(\"\\n\")); });\n const clearBtn = document.createElement(\"button\");\n clearBtn.type = \"button\";\n clearBtn.className = \"sl-logclear\";\n clearBtn.textContent = \"Clear\";\n clearBtn.title = \"Drop the retained log entries (cosmetic - no game state changes)\";\n clearBtn.addEventListener(\"click\", () => { clear(); render(true); });\n bar.append(copyBtn, clearBtn);\n el.append(head, bar, body);\n return { render };\n };\n\n // This flow's own log first: it is what the panel was mounted on. The run's\n // log follows, because it is the wider view and it only earns its space once\n // a second flow exists.\n const flowLog = buildLogPanel(\"flow\", \"Log\", () => live().log(), () => live().clearLog(),\n \"(empty - new Engine(bundle, { log: true }) retains the flow log)\");\n const runLog = buildLogPanel(\"run\", \"Run log (every flow)\", () => engine.log(), () => engine.clearLog(),\n \"(empty - new Engine(bundle, { log: true }) retains the run log)\");\n const renderLog = (force = false): void => { runLog.render(force); flowLog.render(force); };\n\n const line = (parent: HTMLElement, text: string): void => {\n const div = document.createElement(\"div\");\n div.className = \"sl-line\";\n div.textContent = text;\n parent.append(div);\n };\n const readLive = (): void => {\n turnsBody.textContent = \"\";\n for (const box of live().listBoxes()) {\n line(turnsBody, `${box.title ?? box.gameId}: turn ${box.turn}`);\n }\n boardBody.textContent = \"\";\n for (const [hand, cards] of Object.entries(live().board())) {\n const names = cards.map((c) => c.title ?? c.gameId);\n line(boardBody, `${hand}: ${names.length > 0 ? names.join(\", \") : \"(empty)\"}`);\n }\n };\n\n const refresh = (): void => {\n for (const e of editors) e.read();\n readLive();\n renderLog();\n };\n readLive();\n renderLog(true);\n\n let timer: ReturnType<typeof setInterval> | undefined;\n const pollMs = opts.pollMs ?? 250;\n if (pollMs > 0) timer = setInterval(refresh, pollMs);\n\n (opts.container ?? document.body).append(el);\n return {\n el,\n refresh,\n destroy(): void {\n if (timer !== undefined) clearInterval(timer);\n el.remove();\n },\n };\n}\n\nfunction buildRow(\n live: () => Flow,\n row: PropertyRow,\n editors: { row: PropertyRow; read: () => void }[],\n): HTMLElement {\n const div = document.createElement(\"div\");\n div.className = \"sl-row\";\n const name = document.createElement(\"span\");\n name.className = \"sl-name\";\n name.textContent = row.name;\n name.title = row.path;\n\n const current = (): ScalarValue | undefined => {\n try { return live().getProperty(row.path); } catch { return undefined; }\n };\n // Forward-declared so commit can refresh the whole row (widget + reset\n // state) once everything below is built.\n let sync: () => void = () => {};\n const commit = (value: ScalarValue): void => { live().setProperty(row.path, value); sync(); };\n\n const reset = document.createElement(\"button\");\n reset.type = \"button\";\n reset.className = \"sl-reset\";\n reset.textContent = \"↺\";\n reset.title = \"Reset to default\";\n reset.addEventListener(\"click\", () => commit(row.default));\n\n let widget: HTMLElement;\n let read: () => void;\n const focused = (w: HTMLElement): boolean => document.activeElement === w;\n\n switch (row.type) {\n case \"boolean\": {\n const input = document.createElement(\"input\");\n input.type = \"checkbox\";\n input.addEventListener(\"change\", () => commit(input.checked));\n widget = input;\n read = () => { if (!focused(input)) input.checked = current() === true; };\n break;\n }\n case \"number\": {\n const input = document.createElement(\"input\");\n input.type = \"number\";\n input.addEventListener(\"change\", () => commit(Number(input.value)));\n widget = input;\n read = () => { if (!focused(input)) input.value = String(current() ?? 0); };\n break;\n }\n case \"enum\":\n case \"quality\": {\n // A quality edits as a dropdown of its STAGE LADDER, closed exactly like an\n // enum's values. It fell to the string branch until 2026-09-01, so a free-text\n // box accepted any stage name at all - and an unknown stage is not a harmless\n // typo: the evaluator refuses it (\"X is not a stage of this quality\"), so a\n // slip here broke play rather than being corrected. listProperties has carried\n // `stages` for this since it was written; nothing consumed it.\n const select = document.createElement(\"select\");\n for (const v of (row.type === \"quality\" ? row.stages : row.values) ?? []) {\n const o = document.createElement(\"option\");\n o.value = v;\n o.textContent = v;\n select.append(o);\n }\n select.addEventListener(\"change\", () => commit(select.value));\n widget = select;\n read = () => { if (!focused(select)) select.value = String(current() ?? \"\"); };\n break;\n }\n case \"flags\": {\n const input = document.createElement(\"input\");\n input.type = \"text\";\n input.placeholder = \"comma, separated, flags\";\n input.addEventListener(\"change\", () =>\n commit(input.value.split(\",\").map((s) => s.trim()).filter((s) => s.length > 0)));\n widget = input;\n read = () => { if (!focused(input)) input.value = ((current() as string[] | undefined) ?? []).join(\", \"); };\n break;\n }\n default: { // string\n const input = document.createElement(\"input\");\n input.type = \"text\";\n input.addEventListener(\"change\", () => commit(input.value));\n widget = input;\n read = () => { if (!focused(input)) input.value = String(current() ?? \"\"); };\n }\n }\n\n const readAll = (): void => { read(); reset.disabled = eq(current(), row.default); };\n sync = readAll;\n readAll();\n editors.push({ row, read: readAll });\n div.append(name, widget, reset);\n return div;\n}\n","// ---------------------------------------------------------------------------\n// The bundle inspector, JS idiom (design/engine-runtimes.md 2, piece 6).\n//\n// describeBundle() IS the JS half of the parity member - JS has no engine\n// asset pipeline to hang an editor view off - so this is the optional DOM\n// rendering of it: a read-only panel over a compiled bundle, in the property\n// examiner's CSS grammar (inspector.ts), with NO session anywhere. Identity\n// first, then collapsible sections: hands (the deal() surface), tags by box\n// (the peek() criteria surface), declared properties, counts.\n//\n// Read-only by construction: there is no state to edit here, only the shape\n// that shipped.\n// ---------------------------------------------------------------------------\n/// <reference lib=\"dom\" />\n\nimport { describeBundle } from \"@storylet-studio/runtime\";\nimport type {\n BundleDescription, PropertyScopeSummary, PropertySummary,\n} from \"@storylet-studio/runtime\";\nimport type { Bundle, ScalarValue } from \"@storylet-studio/model\";\nimport { ensureInspectorStyle } from \"./inspector.js\";\n\nexport interface BundleInspectorOptions {\n /** Mount point; defaults to document.body. */\n container?: HTMLElement;\n title?: string;\n /** Start the collapsible sections open (default true). */\n open?: boolean;\n}\n\nexport interface BundleInspector {\n el: HTMLElement;\n /** The description this panel rendered (the API is the parity member). */\n description: BundleDescription;\n destroy(): void;\n}\n\nconst showVal = (v: ScalarValue | undefined): string =>\n v === undefined ? \"<unset>\" : JSON.stringify(v);\n\n/** \"name: type = default\", plus enum/flags options where declared. */\nexport function formatPropertySummary(p: PropertySummary): string {\n const options = p.values !== undefined && p.values.length > 0 ? ` [${p.values.join(\", \")}]` : \"\";\n return `${p.name}: ${p.type} = ${showVal(p.default)}${options}`;\n}\n\n/** The scope label a declaration block files under (\"world\", \"box box\",\n * \"tag docks (zone)\"). */\nexport function formatScopeLabel(scope: PropertyScopeSummary): string {\n if (scope.scope === \"world\" || scope.scope === \"story\") return scope.scope;\n const group = scope.group !== undefined ? ` (${scope.group})` : \"\";\n return `${scope.scope} ${scope.owner}${group}`;\n}\n\nconst line = (parent: HTMLElement, text: string, cls = \"sl-line\"): HTMLElement => {\n const div = document.createElement(\"div\");\n div.className = cls;\n div.textContent = text;\n parent.append(div);\n return div;\n};\n\n/** A collapsible section in the examiner's grammar. */\nconst fold = (parent: HTMLElement, label: string, open: boolean): HTMLElement => {\n const details = document.createElement(\"details\");\n details.className = \"sl-fold\";\n details.open = open;\n const summary = document.createElement(\"summary\");\n summary.textContent = label;\n details.append(summary);\n const body = document.createElement(\"div\");\n details.append(body);\n parent.append(details);\n return body;\n};\n\n/** Render a read-only summary of a compiled bundle: what an integrator may\n * call, with no session and no game running. */\nexport function createBundleInspector(\n bundle: Bundle,\n opts: BundleInspectorOptions = {},\n): BundleInspector {\n ensureInspectorStyle();\n const description = describeBundle(bundle);\n const open = opts.open ?? true;\n\n const el = document.createElement(\"div\");\n el.className = \"sl-insp\";\n\n const head = document.createElement(\"div\");\n head.className = \"sl-head\";\n const h = document.createElement(\"h3\");\n h.textContent = opts.title ?? \"Bundle\";\n head.append(h);\n el.append(head);\n\n // --- identity (always visible: which bundle is this?) --------------------\n const { identity, totals } = description;\n const ident = document.createElement(\"div\");\n ident.className = \"sl-ident\";\n el.append(ident);\n line(ident, `${identity.project} ${identity.version}`, \"sl-line\");\n line(ident, `schema ${identity.schema}`, \"sl-line sl-note\");\n line(ident, `hash ${identity.hash === \"\" ? \"(none)\" : identity.hash} - metadata ${identity.metadata}`,\n \"sl-line sl-note\");\n\n // --- hands: the deal() surface -------------------------------------------\n const handsBody = fold(el, \"Hands (deal)\", open);\n handsBody.className = \"sl-hands\";\n if (description.hands.length === 0) {\n line(handsBody, \"(no hands - this bundle is peek-only)\", \"sl-line sl-note\");\n }\n for (const hand of description.hands) {\n const template = hand.template !== undefined ? `, template ${hand.template}` : \"\";\n line(handsBody, `${hand.gameId}: box ${hand.box}, slots ${hand.slots}${template}`\n + (hand.title !== undefined ? ` - ${hand.title}` : \"\"));\n }\n\n // --- tag groups by box: the peek() criteria surface ----------------------\n const tagsBody = fold(el, \"Tags by box (peek criteria)\", open);\n tagsBody.className = \"sl-tags\";\n for (const box of description.boxes) {\n line(tagsBody, `${box.title ?? box.gameId}`, \"sl-group\");\n if (box.tagGroups.length === 0) {\n line(tagsBody, \" (no tag groups)\", \"sl-line sl-note\");\n }\n for (const group of box.tagGroups) {\n line(tagsBody, ` ${group.gameId}: ${group.tags.length > 0 ? group.tags.join(\", \") : \"(no tags)\"}`);\n }\n }\n\n // --- declared properties: what expressions read, what a host may set ----\n const propsBody = fold(el, \"Properties (declared)\", open);\n propsBody.className = \"sl-props\";\n for (const scope of description.properties) {\n line(propsBody, formatScopeLabel(scope), \"sl-group\");\n if (scope.properties.length === 0) {\n line(propsBody, \" (none declared)\", \"sl-line sl-note\");\n }\n for (const p of scope.properties) {\n line(propsBody, ` ${formatPropertySummary(p)}`);\n }\n }\n\n // --- maps: inert payload, and therefore worth saying out loud -----------\n //\n // Only when there ARE some. An empty section on every ordinary bundle would\n // teach the reader to skip a section that only ever matters when it is not\n // empty, and most bundles carry no geometry at all.\n if (description.maps.length > 0) {\n const mapsBody = fold(el, \"Maps (carried, not read)\", open);\n mapsBody.className = \"sl-maps\";\n line(mapsBody, \"Geometry the build was asked to carry. The engine ignores it.\", \"sl-line sl-note\");\n for (const map of description.maps) {\n line(mapsBody, `${map.box} - ${map.group}: zones ${map.zones}, pictures ${map.backgrounds}`);\n }\n }\n\n // --- counts: orientation, not inventory ---------------------------------\n const countsBody = fold(el, \"Counts\", open);\n countsBody.className = \"sl-counts\";\n line(countsBody, `boxes ${totals.boxes} - decks ${totals.decks} - cards ${totals.cards}`);\n line(countsBody, `hands ${totals.hands} - templates ${totals.templates} - tag groups ${totals.tagGroups}`);\n for (const box of description.boxes) {\n line(countsBody, `${box.gameId}: decks ${box.counts.decks}, cards ${box.counts.cards}, `\n + `hands ${box.counts.hands}, templates ${box.counts.templates}, `\n + `tag groups ${box.counts.tagGroups}, ranking.specificity ${box.ranking.specificity}`);\n }\n\n (opts.container ?? document.body).append(el);\n return {\n el,\n description,\n destroy(): void {\n el.remove();\n },\n };\n}\n","// ---------------------------------------------------------------------------\n// Live Link (design/live-link.md): the game-side client.\n//\n// Joins a running game to Storyletter over a loopback WebSocket. Two things\n// travel on it: the flow's trace stream and board snapshots go UP, so the\n// editor's Board can show the game's run instead of its own (observe-only: the\n// editor never drives the game); freshly compiled bundles come DOWN after a\n// save, so the run picks up the edit without restarting (applyLiveBundle in\n// refresh.ts does the swap).\n//\n// Wire protocol `storyletengine/debug@1` (one JSON object per message):\n// hello : { t:\"hello\", v:2, build, project?, boxes?, flows:[id...] }\n// - on open, and again on setBuild\n// flowOpen / flowClose : { t:\"flowOpen\"|\"flowClose\", flow }\n// - a flow appeared or went\n// trace : { t:\"trace\", flow, event } - every TraceEvent any flow emits\n// board : { t:\"board\", flow, hands:{ hand: [card...] }, turns:{ box: n } }\n// - after hello, and after every deal /\n// play / evict / turns event\n// bundle: { t:\"bundle\", v:1, build, data } - EDITOR -> game: the full .storyletsc\n// JSON as a string\n// Identity in frames is by gameId (hands, boxes, cards); the trace event is\n// the runtime's own object, verbatim, whatever ids it carries.\n//\n// Patterpad's createDebugLink is the template (Patter play-helpers/debug.ts):\n// hello first, frames queue until the socket opens, a missing editor is a\n// silent no-op, nothing here ever throws into the game, and no WebSocket\n// implementation at all degrades to a no-op handle. `observe(...)` became a\n// trace subscription, which is why this one takes an ENGINE: attach(engine)\n// subscribes, detach() stops, and a live refresh replaces the flow\n// (detach the old one, attach the new one, then setBuild).\n//\n// const link = createLiveLink({ build: bundle.content.hash, onBundle: ... });\n// link.attach(engine); // the ENGINE: the link discovers your flows itself\n// ---------------------------------------------------------------------------\n\nimport type { Engine, Flow, TraceEvent } from \"@storylet-studio/runtime\";\n\n/** A minimal structural type for a WebSocket implementation (browsers and\n * Node 22+ have a global one). */\nexport interface LiveSocketLike {\n readyState: number;\n send(data: string): void;\n close(): void;\n addEventListener(type: \"open\" | \"close\" | \"error\", listener: () => void): void;\n /** Incoming editor messages (the pushed bundle). Optional so a bare\n * send-only socket still fits. */\n addEventListener(type: \"message\", listener: (ev: { data: unknown }) => void): void;\n}\ntype LiveSocketCtor = new (url: string) => LiveSocketLike;\n\nexport interface LiveLinkOptions {\n /** The running bundle's build identity: pass `bundle.content.hash`. The\n * editor compares it with its own compiled hash (in sync / stale). */\n build: string;\n /** Optional project name, shown in the editor's connect-chip tooltip. */\n project?: string;\n /** Editor WebSocket URL. Default `ws://127.0.0.1:4472`. */\n url?: string;\n /** A WebSocket constructor to use instead of the global one (tests with a\n * fake socket, or a host without a global WebSocket). */\n WebSocket?: LiveSocketCtor;\n /** Live refresh: the editor pushed a freshly compiled bundle. `data` is\n * the .storyletsc JSON; hand it (with your current Engine) to\n * `applyLiveBundle`, `attach` the engine it returns, then call\n * `link.setBuild(build)`. Never called with a malformed frame. */\n onBundle?: (msg: { build: string; data: string }) => void;\n}\n\nexport interface LiveLink {\n /** Start forwarding this ENGINE's trace: every flow's events, each frame\n * naming the flow it came from, so the editor can follow one participant\n * and switch. An earlier engine is detached first. Sends a board snapshot\n * per open flow straight away, queued behind the hello if the socket is\n * not open yet.\n *\n * Flows are discovered rather than declared: the link diffs `engine.flows()`\n * whenever anything happens and emits `flowOpen` / `flowClose` itself. That\n * is a deliberate departure from Patterplay, whose host calls `FlowOpened`\n * by hand - it has no engine-level trace tap to hang the diff on and we do,\n * so the host has nothing to remember and cannot get the editor's flow list\n * wrong. The one cost: a flow that opens and then does nothing at all is not\n * announced until the next event anywhere in the run. */\n attach(engine: Engine): void;\n /** Stop forwarding. A refresh replaces the engine, so attach the new one\n * afterwards. */\n detach(): void;\n /** After applying a pushed bundle: report the build now running (re-hellos\n * with the new build and a fresh board snapshot, so the editor's chip goes\n * back to in sync and it stops re-pushing the same bundle). */\n setBuild(build: string): void;\n /** Close the link; every later call is a no-op. */\n close(): void;\n}\n\n/** One game-to-editor frame, as the client serialises it. Exported for the\n * fixture test; hosts never build these by hand. */\nexport type LiveFrame =\n | { t: \"hello\"; v: 2; build: string; project?: string; boxes?: string[]; flows: string[] }\n | { t: \"flowOpen\"; flow: string }\n | { t: \"flowClose\"; flow: string }\n | { t: \"trace\"; flow: string; event: TraceEvent }\n | { t: \"board\"; flow: string; hands: Record<string, string[]>; turns: Record<string, number> };\n\nconst OPEN = 1; // WebSocket.OPEN\n\n/** How many frames may wait for a socket that has not opened yet. Generous:\n * the point of queueing is that a game's first moments are not lost while the\n * editor's socket is still connecting. */\nconst QUEUE_CAP = 512;\nconst DEFAULT_URL = \"ws://127.0.0.1:4472\";\n\n/** The trace kinds that move the board, and so are followed by a snapshot. */\nconst BOARD_EVENTS: ReadonlySet<TraceEvent[\"type\"]> = new Set([\"deal\", \"play\", \"evict\", \"turns\"]);\n\n/** The cheap snapshot: hands by gameId holding card gameIds in dealt order,\n * and every box's clock by gameId. */\nexport function boardFrame(flow: Flow): Extract<LiveFrame, { t: \"board\" }> {\n const id = flow.id;\n const hands: Record<string, string[]> = {};\n for (const [hand, cards] of Object.entries(flow.board())) hands[hand] = cards.map((c) => c.gameId);\n const turns: Record<string, number> = {};\n for (const box of flow.listBoxes()) turns[box.gameId] = box.turn;\n return { t: \"board\", flow: id, hands, turns };\n}\n\n/**\n * Open a Live Link to Storyletter. Returns a handle whose calls are no-ops once\n * the editor disconnects or if it was never listening: safe to leave wired into\n * a shipping build behind a flag.\n */\nexport function createLiveLink(opts: LiveLinkOptions): LiveLink {\n const url = opts.url ?? DEFAULT_URL;\n const Ctor: LiveSocketCtor | undefined = opts.WebSocket ?? (globalThis as { WebSocket?: LiveSocketCtor }).WebSocket;\n let queue: string[] = [];\n let sock: LiveSocketLike | null = null;\n let closed = false;\n let build = opts.build; // mutable: setBuild() after a live refresh lands\n let engine: Engine | null = null;\n let unsubscribe: (() => void) | null = null;\n // The flows the EDITOR believes are open. Diffed against engine.flows() so\n // flowOpen / flowClose are the link's own business, not the host's.\n let announced = new Set<string>();\n\n if (!Ctor) {\n // No WebSocket available (no global, none passed): a silent no-op link.\n return { attach() {}, detach() {}, setBuild() {}, close() { closed = true; } };\n }\n\n const flush = (): void => {\n if (!sock || sock.readyState !== OPEN) return;\n for (const m of queue) { try { sock.send(m); } catch { /* socket went away */ } }\n queue = [];\n };\n const post = (frame: LiveFrame): void => {\n if (closed) return;\n queue.push(JSON.stringify(frame));\n // A cap for the CONNECTING window, where queueing is the point: the hello\n // and the frames a game emits during those first milliseconds have to\n // land. Beyond that many, the editor is not coming - drop the oldest, so\n // what survives is the most recent story rather than the first moments of\n // it. Once the socket has actually closed the queue is dropped outright\n // (see the close listener); this is only the never-opened case.\n if (queue.length > QUEUE_CAP) queue.splice(0, queue.length - QUEUE_CAP);\n flush();\n };\n\n // The handshake goes straight to the socket, never through the queue: it\n // must be the first thing the editor reads, ahead of anything queued while\n // the socket was still connecting.\n const liveFlows = (): Flow[] => {\n try { return engine ? engine.flows() : []; } catch { return []; }\n };\n const sendHello = (): void => {\n const flows = liveFlows();\n const hello: LiveFrame = { t: \"hello\", v: 2, build, flows: flows.map((f) => f.id) };\n if (opts.project !== undefined) hello.project = opts.project;\n const first = flows[0];\n if (first) {\n try { hello.boxes = first.listBoxes().map((b) => b.gameId); } catch { /* mid-swap: no boxes */ }\n }\n // The editor's list starts from the hello, so the diff starts there too.\n announced = new Set(flows.map((f) => f.id));\n try { sock?.send(JSON.stringify(hello)); } catch { /* race: closed immediately */ }\n };\n const postBoard = (flow: Flow): void => {\n try { post(boardFrame(flow)); } catch { /* never into the game */ }\n };\n /** Announce anything that opened or closed since the last look. Runs before\n * each forwarded event, so a frame never names a flow the editor has not\n * been told about. */\n const syncFlows = (): void => {\n const now = liveFlows();\n const ids = new Set(now.map((f) => f.id));\n for (const f of now) {\n if (announced.has(f.id)) continue;\n announced.add(f.id);\n post({ t: \"flowOpen\", flow: f.id });\n postBoard(f);\n }\n for (const id of [...announced]) {\n if (ids.has(id)) continue;\n announced.delete(id);\n post({ t: \"flowClose\", flow: id });\n }\n };\n const onTrace = (flowId: string, event: TraceEvent): void => {\n try {\n syncFlows();\n post({ t: \"trace\", flow: flowId, event });\n if (BOARD_EVENTS.has(event.type)) {\n const f = engine?.getFlow(flowId);\n if (f) postBoard(f);\n }\n } catch { /* never into the game */ }\n };\n\n try {\n sock = new Ctor(url);\n sock.addEventListener(\"open\", () => {\n sendHello();\n flush();\n });\n // Live refresh: the editor pushed a new bundle. The shape is checked here\n // so the host's handler never sees a malformed frame; anything else the\n // editor might send is ignored.\n sock.addEventListener(\"message\", (ev: { data: unknown }) => {\n if (!opts.onBundle || typeof ev.data !== \"string\") return;\n try {\n const msg = JSON.parse(ev.data) as Record<string, unknown>;\n if (msg.t === \"bundle\" && typeof msg.build === \"string\" && typeof msg.data === \"string\") {\n opts.onBundle({ build: msg.build, data: msg.data });\n }\n } catch { /* not for us */ }\n });\n sock.addEventListener(\"error\", () => { /* editor not listening: stay a no-op */ });\n // The socket is gone and this link does not reconnect, so the link is\n // INERT from here rather than merely unable to send. It used to set `sock`\n // to null and nothing else, leaving `closed` false, so every later trace\n // event pushed another string onto a queue nothing would ever drain: one\n // heap allocation per deal, play and write for the rest of the session.\n // Godot and Unity both already stopped at this point; JS and Unreal did\n // not. Found by the pre-release audit, 2026-08-29.\n sock.addEventListener(\"close\", () => { sock = null; closed = true; queue = []; });\n } catch { sock = null; closed = true; } // malformed URL etc.: never throw into the game\n\n const detach = (): void => {\n unsubscribe?.();\n unsubscribe = null;\n engine = null;\n announced = new Set();\n };\n\n return {\n attach(next: Engine): void {\n if (closed) return;\n detach();\n engine = next;\n try { unsubscribe = next.subscribeTrace(onTrace); } catch { engine = null; return; }\n // Every open flow's board up front: the editor can show any of them the\n // moment it connects, without waiting for that participant to move.\n announced = new Set(liveFlows().map((f) => f.id));\n for (const f of liveFlows()) postBoard(f);\n },\n detach,\n setBuild(next: string): void {\n if (closed || next === build) return;\n build = next;\n // Re-handshake: the editor re-reads the build, then gets every flow's\n // table as the new engine has it.\n if (sock && sock.readyState === OPEN) {\n sendHello();\n for (const f of liveFlows()) postBoard(f);\n }\n },\n close(): void {\n closed = true;\n detach();\n queue = [];\n try { sock?.close(); } catch { /* already gone */ }\n sock = null;\n },\n };\n}\n","// ---------------------------------------------------------------------------\n// Live refresh (design/live-link.md): the game-side applier. The editor pushes\n// a freshly compiled bundle over the Live Link (createLiveLink's `onBundle`);\n// this swaps it in under the running engine: a new Engine over the new\n// bundle, loaded from the old one's save. The runtime's loadGame() already\n// tolerates edited content (a deleted card leaves the table, orphaned\n// cooldowns and hand contents drop, a new property takes its default), so the\n// run carries across - every flow of it; it refuses only a save from another\n// project.\n//\n// Patter's applyLiveBundle has two tiers (strings-only vs hot swap) because it\n// has string tables and a cursor to re-find; we have neither, so this is the\n// one tier. Wire-up:\n//\n// let engine = new Engine(bundle, { seed: 7, log: true });\n// let flow = engine.openFlow(\"main\");\n// const link = createLiveLink({\n// build: bundle.content.hash,\n// onBundle: ({ build, data }) => {\n// const r = applyLiveBundle(engine, data, { log: true });\n// if (!r.ok) return console.warn(r.error);\n// engine = r.engine; // re-bind your handles: loadGame\n// flow = engine.getFlow(\"main\") // rebuilt every flow, so the old\n// ?? engine.openFlow(\"main\"); // Flow objects are inert\n// link.attach(engine); // re-attach the ENGINE: loadGame rebuilt every flow\n// link.setBuild(build);\n// },\n// });\n// ---------------------------------------------------------------------------\n\nimport type { Bundle } from \"@storylet-studio/model\";\nimport { Engine } from \"@storylet-studio/runtime\";\nimport type { EngineOptions } from \"@storylet-studio/runtime\";\n\nexport type LiveBundleResult =\n /** The new engine, carrying the old one's run (all flows), and the bundle\n * it runs. */\n | { ok: true; engine: Engine; bundle: Bundle }\n /** Nothing changed: keep the engine you have. */\n | { ok: false; error: string };\n\n/**\n * Apply a bundle the editor pushed over the Live Link: `new Engine(parsed,\n * opts)` then `loadGame(engine.saveGame())`, returning the new engine. Never\n * throws; a failure (unparseable JSON, a bundle the runtime rejects, a\n * different project) comes back as `{ ok: false, error }` and the old engine\n * is untouched.\n *\n * `opts` are the options the old engine was created with. An engine does\n * not expose its seed, and it does not matter here: the save envelope carries\n * each flow's PRNG state, so `loadGame` resumes the draw sequences exactly\n * where they were and `seed` only shapes fresh flows. `log` does matter (the\n * retained log is per flow), and so does `world` (the host's binding does not\n * ride the envelope), so pass them if you had them.\n */\nexport function applyLiveBundle(engine: Engine, bundleJson: string, opts: EngineOptions = {}): LiveBundleResult {\n let bundle: Bundle;\n try {\n bundle = JSON.parse(bundleJson) as Bundle;\n } catch {\n return { ok: false, error: \"pushed bundle is not valid JSON\" };\n }\n try {\n const next = new Engine(bundle, opts);\n next.loadGame(engine.saveGame());\n return { ok: true, engine: next, bundle };\n } catch (e) {\n return { ok: false, error: e instanceof Error ? e.message : String(e) };\n }\n}\n","// ---------------------------------------------------------------------------\n// The host's @world container (design/flows.md; engine-runtimes.md 3.1).\n//\n// @world is the game's own state: the engine resolves it through a resolver\n// and NEVER saves it - \"host saves its container once, each engine saves its\n// own envelope\". A real game binds its own state here; a host that has no\n// state of its own (the demos, the playable page, the Board) uses this\n// ready-made container so @world still persists across its save/load.\n//\n// This is also what keeps a mixed Patter + Storylet Engine game honest: ONE\n// container, both engines mounting it foreign, neither writing it into its\n// envelope.\n// ---------------------------------------------------------------------------\n\nimport { PropertyBag as StateBag } from \"@wildwinter/scoperegistry\";\nimport type { ScalarValue } from \"@wildwinter/expr\";\nimport type { ScopeResolver } from \"@wildwinter/expr\";\nimport type { Bundle, PropertyBag } from \"@storylet-studio/model\";\n\nexport interface WorldContainer {\n /** Pass as `new Engine(bundle, { world: container.resolver })`. */\n resolver: ScopeResolver;\n /** The kernel bag itself (subscribe, audit, rows live there) - mount it\n * into a state logger or examiner beside the engine's own bags. */\n bag: StateBag;\n /** The current values, for saving beside the engine's envelope. */\n values(): PropertyBag;\n /** Restore saved values over fresh defaults: orphaned keys drop, new\n * declarations keep their defaults - the same drift rule as loadGame. */\n load(values: PropertyBag): void;\n}\n\n/** A world container seeded from the bundle's @world declarations. */\nexport function createWorldContainer(bundle: Bundle): WorldContainer {\n const bag = new StateBag(bundle.world.properties, { normalise: (n) => n });\n return {\n resolver: {\n get: (n) => bag.get(n),\n set: (n: string, v: ScalarValue) => { bag.set(n, v); },\n },\n bag,\n values: () => bag.values,\n load: (values) => bag.load(values),\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,2BAAAA;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACoFO,SAAS,UAAU,MAAqB,MAAoC;AACjF,QAAM,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