@storylet-studio/play-helpers 0.8.2 → 0.9.1
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.
- package/README.md +2 -2
- package/dist/index.cjs +8 -7
- package/dist/index.cjs.map +1 -1
- package/dist/index.js +8 -7
- package/dist/index.js.map +1 -1
- package/dist/storyletengine.min.js +4 -4
- package/dist/storyletengine.min.js.map +1 -1
- package/package.json +2 -2
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/browser.ts","../../../../expr/packages/expr/src/ast.ts","../../../../expr/packages/expr/src/evaluate.ts","../../../../expr/packages/expr/src/prng.ts","../../../../expr/packages/expr-specificity/src/index.ts","../../dialect/src/engine-scopes.ts","../../dialect/src/index.ts","../../model/src/index.ts","../../../../expr/packages/scoperegistry/src/state-logger.ts","../../../../expr/packages/scoperegistry/src/index.ts","../../runtime/src/engine.ts","../../runtime/src/describe.ts","../src/logger.ts","../src/save.ts","../src/inspector.ts","../src/bundle-inspector.ts","../src/live-link.ts","../src/refresh.ts","../src/world.ts"],"sourcesContent":["// The browser drop-in: ONE classic script, no build step, defining the\n// `StoryletEngine` global with the runtime AND these helpers on it, so a plain\n// page can build an engine, deal, play, and save and load the family's\n// .storyletsave text, all from two script tags (this and Patterplay's).\n//\n// Built by this package rather than the runtime because this is the one\n// package that depends on both: the runtime cannot bundle the helpers without\n// bundling itself twice. The export names of the two do not overlap (checked\n// 2026-09-04), so `export *` from each is exact.\nexport * from \"@storylet-studio/runtime\";\nexport * from \"./index.js\";\n","// ---------------------------------------------------------------------------\n// AST - the in-memory expression tree and its serialised tagged-tuple form.\n//\n// The in-memory `ExprNode` is a discriminated union (kind field). The published\n// `AstNode` is the compact tagged-tuple form that goes into a compiled bundle's\n// { src, ast } envelope - what a runtime walks, never parses.\n//\n// This module is dialect-agnostic: scope tokens and function names are plain\n// strings here; meaning is supplied by a Dialect (see dialect.ts).\n// ---------------------------------------------------------------------------\n\nexport type ScalarValue = boolean | number | string | string[];\n\nexport type BinaryOp =\n | \"==\" | \"!=\" | \">\" | \">=\" | \"<\" | \"<=\"\n | \"+\" | \"-\" | \"*\" | \"/\"\n | \"and\" | \"or\";\n\nexport type UnaryOp = \"not\" | \"neg\";\n\nexport type ExprNode =\n | { kind: \"bool\"; value: boolean }\n | { kind: \"number\"; value: number }\n | { kind: \"string\"; value: string }\n // All property references are scoped: bare `@name` is canonicalised to\n // `@<defaultScope>.name` at parse time. Names are lowercased at parse time.\n | { kind: \"scopedvar\"; scope: string; name: string }\n | { kind: \"call\"; name: string; args: ExprNode[] }\n | { kind: \"unary\"; op: UnaryOp; operand: ExprNode }\n | { kind: \"binary\"; op: BinaryOp; left: ExprNode; right: ExprNode }\n // Produced only by flag-delta function argument parsing (see Dialect\n // `flagDeltaArgs`) - not valid elsewhere.\n | { kind: \"flagdelta\"; sign: \"+\" | \"-\"; name: string };\n\n/**\n * Path into an ExprNode tree. Each segment names the field on the parent node,\n * with numeric indices for array elements (call args).\n * binary.left -> [\"left\"]\n * binary.right.args[0] -> [\"right\", \"args\", 0]\n * top-level node -> []\n */\nexport type AstPath = readonly (string | number)[];\n\n// ---------------------------------------------------------------------------\n// Published tagged-tuple form (JSON arrays, opcode at index 0).\n// ---------------------------------------------------------------------------\n\nexport type AstNode =\n | [\"b\", boolean]\n | [\"n\", number]\n | [\"s\", string]\n | [\"sv\", string, string]\n | [\"u\", UnaryOp, AstNode]\n | [\"bin\", BinaryOp, AstNode, AstNode]\n | [\"call\", string, ...AstNode[]]\n | [\"fd\", \"+\" | \"-\", string];\n\n/** In-memory ExprNode -> published tagged-tuple AstNode. */\nexport function serialiseAst(node: ExprNode): AstNode {\n switch (node.kind) {\n case \"bool\": return [\"b\", node.value];\n case \"number\": return [\"n\", node.value];\n case \"string\": return [\"s\", node.value];\n case \"scopedvar\": return [\"sv\", node.scope, node.name];\n case \"unary\": return [\"u\", node.op, serialiseAst(node.operand)];\n case \"binary\": return [\"bin\", node.op, serialiseAst(node.left), serialiseAst(node.right)];\n case \"call\": return [\"call\", node.name, ...node.args.map(serialiseAst)];\n case \"flagdelta\": return [\"fd\", node.sign, node.name];\n }\n}\n\n/** Published tagged-tuple AstNode -> in-memory ExprNode. */\nexport function deserialiseAst(node: AstNode): ExprNode {\n switch (node[0]) {\n case \"b\": return { kind: \"bool\", value: node[1] };\n case \"n\": return { kind: \"number\", value: node[1] };\n case \"s\": return { kind: \"string\", value: node[1] };\n case \"sv\": return { kind: \"scopedvar\", scope: node[1], name: node[2] };\n case \"u\": return { kind: \"unary\", op: node[1], operand: deserialiseAst(node[2]) };\n case \"bin\": return { kind: \"binary\", op: node[1], left: deserialiseAst(node[2]), right: deserialiseAst(node[3]) };\n case \"call\": {\n const args = (node.slice(2) as AstNode[]).map(deserialiseAst);\n return { kind: \"call\", name: node[1], args };\n }\n case \"fd\": return { kind: \"flagdelta\", sign: node[1], name: node[2] };\n }\n}\n","// ---------------------------------------------------------------------------\n// Evaluator - walk an ExprNode against an EvalContext, parameterised by Dialect.\n//\n// Operators (binary/unary), short-circuiting, and type-checking are generic.\n// Scope resolution uses the context's scope maps + the Dialect's per-scope\n// missing-property policy. Function calls dispatch to the Dialect's functions.\n//\n// Ported from @storylets/engine (storylets/packages/engine/src/expression.ts),\n// generalised by injecting scopes + functions from the Dialect.\n// ---------------------------------------------------------------------------\n\nimport type { ExprNode, ScalarValue } from \"./ast.js\";\nimport type { Dialect, EvalContext, ScopeResolver } from \"./dialect.js\";\n\nexport class EvalError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"EvalError\";\n }\n}\n\nexport function evaluate(node: ExprNode, ctx: EvalContext, dialect: Dialect): ScalarValue {\n // Per-scope missing-property policy, precomputed once per top-level evaluate.\n const missingPolicy = new Map<string, \"false\" | \"throw\">(\n dialect.scopes.map((s) => [s.token, s.missing ?? \"false\"])\n );\n\n const rec = (n: ExprNode): ScalarValue => {\n switch (n.kind) {\n case \"bool\": return n.value;\n case \"number\": return n.value;\n case \"string\": return n.value;\n\n case \"scopedvar\": {\n const scope = ctx.scopes[n.scope];\n if (scope === undefined) {\n // Scope context absent -> graceful false. (A scope the dialect knows\n // about but the context didn't populate, or an unknown scope.)\n return false;\n }\n // A scope is either a static bag or a host resolver ({ get }). Bag values\n // are always ScalarValue (never functions), so a `get` function reliably\n // distinguishes a resolver.\n const val = typeof (scope as ScopeResolver).get === \"function\"\n ? (scope as ScopeResolver).get(n.name)\n : (scope as Record<string, ScalarValue>)[n.name];\n if (val === undefined) {\n // Property not declared on the present scope. Policy decides: \"false\"\n // for back-compat scopes, \"throw\" for scopes where a missing key is a\n // bug publish-time validation should have caught.\n if (missingPolicy.get(n.scope) === \"throw\") {\n throw new EvalError(`@${n.scope}.${n.name} is not declared on the current ${n.scope}.`);\n }\n return false;\n }\n return val;\n }\n\n case \"call\": {\n // `advance` is the language's own, the first core built-in: the next\n // stage in the argument's ladder, saturating at the last. Core rather\n // than dialect because it IS the quality design's insertion mechanism\n // (an outcome that never names its destination routes through an\n // inserted stage automatically), and every dialect should say it the\n // same way. A dialect that defines its own `advance` wins, for\n // back-compat with any dialect that already had one.\n if (n.name === \"advance\" && !dialect.functions[n.name]) {\n const arg = n.args[0];\n if (n.args.length !== 1 || arg === undefined) {\n throw new EvalError(`advance() takes exactly 1 argument, got ${n.args.length}`);\n }\n const ladder = ladderOf(arg, ctx);\n if (ladder === undefined) {\n throw new EvalError(\"advance() needs a quality reference (@scope.name of a quality property)\");\n }\n const current = stageIndex(rec(arg), ladder, \"advance\");\n return ladder[Math.min(current + 1, ladder.length - 1)]!;\n }\n const def = dialect.functions[n.name];\n if (!def) throw new EvalError(`unknown function '${n.name}'`);\n return def.eval(n.args, { evaluate: rec, ctx });\n }\n\n case \"flagdelta\":\n throw new EvalError(\"flagdelta node is only valid as an argument to a flag-delta function\");\n\n case \"unary\": {\n if (n.op === \"not\") {\n const val = rec(n.operand);\n if (typeof val !== \"boolean\") throw new EvalError(`'not' requires a boolean operand, got ${typeof val}`);\n return !val;\n }\n // neg\n const val = rec(n.operand);\n if (typeof val !== \"number\") throw new EvalError(`unary '-' requires a numeric operand, got ${typeof val}`);\n return -val;\n }\n\n case \"binary\": {\n // Short-circuit operators first\n if (n.op === \"and\") {\n const l = rec(n.left);\n if (typeof l !== \"boolean\") throw new EvalError(`'and' requires boolean operands, left is ${typeof l}`);\n if (!l) return false;\n const r = rec(n.right);\n if (typeof r !== \"boolean\") throw new EvalError(`'and' requires boolean operands, right is ${typeof r}`);\n return r;\n }\n if (n.op === \"or\") {\n const l = rec(n.left);\n if (typeof l !== \"boolean\") throw new EvalError(`'or' requires boolean operands, left is ${typeof l}`);\n if (l) return true;\n const r = rec(n.right);\n if (typeof r !== \"boolean\") throw new EvalError(`'or' requires boolean operands, right is ${typeof r}`);\n return r;\n }\n\n const left = rec(n.left);\n const right = rec(n.right);\n\n // Quality: when either operand REFERENCES a quality (the node carries\n // the scope+name the channel resolves), ordering compares by ladder\n // position and arithmetic is refused. Everything else is untouched,\n // so a context with no channel behaves exactly as before.\n const lLadder = ladderOf(n.left, ctx);\n const rLadder = ladderOf(n.right, ctx);\n const ladder = lLadder ?? rLadder;\n if (ladder !== undefined) {\n if (lLadder && rLadder && !sameLadder(lLadder, rLadder)) {\n if (n.op === \">\" || n.op === \">=\" || n.op === \"<\" || n.op === \"<=\") {\n throw new EvalError(`'${n.op}' compares two different qualities, whose stage orders are unrelated`);\n }\n }\n switch (n.op) {\n case \">\": return stageIndex(left, ladder, \">\") > stageIndex(right, ladder, \">\");\n case \">=\": return stageIndex(left, ladder, \">=\") >= stageIndex(right, ladder, \">=\");\n case \"<\": return stageIndex(left, ladder, \"<\") < stageIndex(right, ladder, \"<\");\n case \"<=\": return stageIndex(left, ladder, \"<=\") <= stageIndex(right, ladder, \"<=\");\n case \"+\": case \"-\": case \"*\": case \"/\":\n throw new EvalError(`'${n.op}' cannot be applied to a quality - a stage is a position, not a number; use advance() to move it`);\n default: break; // == and != fall through to plain value equality\n }\n }\n\n switch (n.op) {\n case \"==\": return valueEquals(left, right);\n case \"!=\": return !valueEquals(left, right);\n case \">\": assertNumbers(left, right, \">\"); return (left as number) > (right as number);\n case \">=\": assertNumbers(left, right, \">=\"); return (left as number) >= (right as number);\n case \"<\": assertNumbers(left, right, \"<\"); return (left as number) < (right as number);\n case \"<=\": assertNumbers(left, right, \"<=\"); return (left as number) <= (right as number);\n case \"+\":\n if (typeof left === \"number\" && typeof right === \"number\") return left + right;\n if (typeof left === \"string\" && typeof right === \"string\") return left + right;\n throw new EvalError(`'+' requires two numbers or two strings, got ${typeof left} and ${typeof right}`);\n case \"-\": assertNumbers(left, right, \"-\"); return (left as number) - (right as number);\n case \"*\": assertNumbers(left, right, \"*\"); return (left as number) * (right as number);\n case \"/\":\n assertNumbers(left, right, \"/\");\n if ((right as number) === 0) throw new EvalError(\"division by zero\");\n return (left as number) / (right as number);\n }\n }\n }\n };\n\n return rec(node);\n}\n\n/**\n * Equality for `==` / `!=`. Primitives compare by value (JS `===`); arrays\n * (the flags value type) compare as SETS: same members, ORDER IRRELEVANT.\n *\n * Plain `===` on arrays would be reference equality - two distinct arrays with\n * the same contents would never be equal, and a fresh array (from a scope read\n * or a function result) would never equal another. Mixed array/non-array\n * operands are unequal, and never an error.\n *\n * Order was significant until 2026-09-01, and that was wrong: a flags value IS\n * a set, and its stored order is an artefact of the order somebody happened to\n * add things in. `set_flags(@f, +a)` then `+b` compared UNEQUAL to the same two\n * flags added the other way round, which is a difference no author can see and\n * none intends. The Storylet Engine papered over it by sorting in `set_flags`,\n * which only holds while every producer sorts: a bundle's declared default, or\n * a host handing a list in, does not.\n *\n * Compared as MULTISETS (sorted copies), so a duplicated flag still counts. A\n * well-formed flags value has no duplicates, but equality should not be the\n * thing that decides what happens if one appears.\n */\nfunction valueEquals(a: ScalarValue, b: ScalarValue): boolean {\n if (Array.isArray(a) || Array.isArray(b)) {\n if (!Array.isArray(a) || !Array.isArray(b)) return false;\n if (a.length !== b.length) return false;\n const x = [...a].sort();\n const y = [...b].sort();\n for (let i = 0; i < x.length; i++) if (x[i] !== y[i]) return false;\n return true;\n }\n return a === b;\n}\n\nfunction assertNumbers(l: ScalarValue, r: ScalarValue, op: string): void {\n if (typeof l !== \"number\" || typeof r !== \"number\") {\n throw new EvalError(`'${op}' requires numeric operands, got ${typeof l} and ${typeof r}`);\n }\n}\n\n// --- quality (design: storylets-new/design/quality.md) -----------------------\n\n/** The ladder behind an operand NODE, when the context's quality channel says\n * it references a quality. Values are plain strings; the node is what carries\n * the (scope, name) the channel needs. */\nfunction ladderOf(node: ExprNode, ctx: EvalContext): readonly string[] | undefined {\n if (node.kind !== \"scopedvar\" || ctx.qualities === undefined) return undefined;\n return ctx.qualities(node.scope, node.name);\n}\n\n/** Index of a stage in a ladder; an unknown stage is an error naming the\n * value, never a silent pass (a drifted save is exactly what lands here). */\nfunction stageIndex(value: ScalarValue, ladder: readonly string[], op: string): number {\n if (typeof value !== \"string\") {\n throw new EvalError(`'${op}' on a quality compares stages, got ${typeof value}`);\n }\n const i = ladder.indexOf(value);\n if (i < 0) throw new EvalError(`\"${value}\" is not a stage of this quality (stages: ${ladder.join(\", \")})`);\n return i;\n}\n\nconst sameLadder = (a: readonly string[], b: readonly string[]): boolean =>\n a.length === b.length && a.every((x, i) => x === b[i]);\n","// ---------------------------------------------------------------------------\n// mulberry32 - the contractual PRNG.\n//\n// A fixed, published algorithm that both product families need and neither\n// owns. It lived in `@storylet-studio/runtime` as prng.ts and inline in\n// `@patterkit/runtime`'s engine.ts, plus separately in three of Patterplay's\n// harnesses, plus a hand port in each of six native runtimes: thirteen copies\n// of forty lines. It belongs here, in the package both families already depend\n// on, for the same reason the evaluator does.\n//\n// All arithmetic is unsigned 32-bit, matching JavaScript's `>>> 0` and\n// Math.imul.\n// ---------------------------------------------------------------------------\n\nexport interface Prng {\n /** One draw in [0, 1); advances the state. */\n next(): number;\n /** The persisted state (a uint32; feed back into makePrng to restore). */\n state(): number;\n}\n\n/**\n * ECMA-262 7.1.6 ToUint32, which is what `seed >>> 0` means.\n *\n * Written out rather than spelled `seed >>> 0` because THIS is the obligation a\n * port in a language without JavaScript's shift semantics has to reproduce, and\n * the shorthand hides it. Patterplay's C++ port cast the seed straight to an\n * integer type, which is undefined behaviour outside that type's range and gave\n * two wrong answers before the parity corpus pinned them.\n */\nexport function toUint32(seed: number): number {\n if (Number.isNaN(seed) || !Number.isFinite(seed)) return 0;\n const modded = Math.trunc(seed) % 4294967296;\n return modded < 0 ? modded + 4294967296 : modded;\n}\n\n/**\n * Seed a generator. The state is UNSIGNED throughout (`>>> 0`, never `| 0`):\n * the two produce identical draws and differ only in the sign of the number a\n * save persists, and Patterplay shipped `| 0` for long enough that over half of\n * all its saves carried a negative state its own native ports could not read\n * back.\n */\nexport function makePrng(seed: number): Prng {\n let s = toUint32(seed);\n return {\n next(): number {\n s = (s + 0x6d2b79f5) >>> 0;\n let t = Math.imul(s ^ (s >>> 15), 1 | s);\n t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;\n return ((t ^ (t >>> 14)) >>> 0) / 4294967296;\n },\n state(): number {\n return s;\n },\n };\n}\n\n/** The contractual shuffle: Fisher-Yates, descending. Runs of one element\n * consume no draws (the loop never executes for length < 2). */\nexport function shuffleInPlace<T>(arr: T[], prng: Prng): void {\n for (let i = arr.length - 1; i > 0; i--) {\n const j = Math.floor(prng.next() * (i + 1));\n [arr[i], arr[j]] = [arr[j]!, arr[i]!];\n }\n}\n","// ---------------------------------------------------------------------------\n// @wildwinter/expr-specificity - public surface.\n//\n// Matched-constraint specificity: score how many atomic constraints in an\n// expression are actively holding it true against the current state. An\n// evaluation-aware walk (unlike a static clause count, an `or`'s score depends\n// on which branch is currently matching). Shared by Storylet Studio (storylet\n// draw priority) and Patter (dialogue best-match), which had independently\n// grown the same algorithm.\n//\n// Built on @wildwinter/expr's `ExprNode`. The host supplies truthiness via an\n// `evalTruthy` closure, so this package stays ignorant of the eval context,\n// the dialect, and the host's truthiness rule - each host keeps its own\n// behaviour while sharing one definition of the walk.\n// ---------------------------------------------------------------------------\n\nimport type { ExprNode } from \"@wildwinter/expr\";\n\n/** A call node, narrowed from the ExprNode union. */\ntype CallNode = Extract<ExprNode, { kind: \"call\" }>;\n\n/**\n * Evaluate an expression subtree to a boolean. Host-bound: the host closes over\n * its own evaluate + eval context + dialect and applies its own truthiness\n * coercion (Storylets' `conditionPasses`, Patter's `truthy`, etc.).\n */\nexport type EvalTruthy = (node: ExprNode) => boolean;\n\n/**\n * A call treated as a conjunction of constraints rather than a single atom, so\n * it contributes its operand count instead of 1. `check_flags` is the built-in\n * example (see {@link CHECK_FLAGS_COUNTING_CALL}).\n */\nexport interface CountingCall {\n /** The function name this rule applies to. */\n name: string;\n /** How many constraints the call contributes when it holds (at least 1). */\n count: (node: CallNode) => number;\n}\n\nexport interface MatchedSpecificityOptions {\n /**\n * Root polarity - the truth value the whole condition must have. Production\n * only ever scores conditions already known eligible, so this defaults to\n * `true` and rarely needs setting.\n */\n want?: boolean;\n /**\n * Calls scored by operand count rather than as a single atom. Defaults to\n * `[CHECK_FLAGS_COUNTING_CALL]`. Supply your own to add or replace rules.\n */\n countingCalls?: readonly CountingCall[];\n}\n\n/**\n * `check_flags(v, f1..fN)` counts as N constraints - an N-ary AND over the flag\n * operands - never fewer than 1. `args[0]` is the flags source, so the operand\n * count is `args.length - 1`.\n */\nexport const CHECK_FLAGS_COUNTING_CALL: CountingCall = {\n name: \"check_flags\",\n count: (node) => Math.max(1, node.args.length - 1),\n};\n\nconst DEFAULT_COUNTING_CALLS: readonly CountingCall[] = [CHECK_FLAGS_COUNTING_CALL];\n\n/**\n * Score how many atomic constraints in `node` are actively holding it true\n * against current state, via `evalTruthy`.\n *\n * The walk carries a polarity flag `want` (\"the truth value this subtree must\n * have for the whole to hold\"), applying De Morgan as it descends:\n * - atom: 1 if its truth matches `want`, else 0\n * - and: under `want`, both must hold -> sum; under `!want`, behaves as or\n * - or: under `want`, strongest branch -> max; under `!want`, behaves as and\n * - not: recurse with `want` flipped\n * - counting call (e.g. check_flags): its operand count when it must hold and\n * does, else the negated rules apply\n *\n * @example\n * // `@x == 5 and @y > 3` with both holding -> 2\n * matchedSpecificity(ast, node => conditionPasses(evaluate(node, ctx)))\n */\nexport function matchedSpecificity(\n node: ExprNode,\n evalTruthy: EvalTruthy,\n opts?: MatchedSpecificityOptions,\n): number {\n const countingCalls = opts?.countingCalls ?? DEFAULT_COUNTING_CALLS;\n return walk(node, opts?.want ?? true, evalTruthy, countingCalls);\n}\n\nfunction walk(\n node: ExprNode,\n want: boolean,\n evalTruthy: EvalTruthy,\n countingCalls: readonly CountingCall[],\n): number {\n if (node.kind === \"binary\" && (node.op === \"and\" || node.op === \"or\")) {\n const l = walk(node.left, want, evalTruthy, countingCalls);\n const r = walk(node.right, want, evalTruthy, countingCalls);\n // De Morgan: an `and` under negation behaves like an `or`, and vice versa.\n const behaveAsAnd = (node.op === \"and\") === want;\n if (behaveAsAnd) return l > 0 && r > 0 ? l + r : 0; // both must hold -> sum\n return Math.max(l, r); // either holds -> strongest branch\n }\n if (node.kind === \"unary\" && node.op === \"not\") {\n return walk(node.operand, !want, evalTruthy, countingCalls);\n }\n if (node.kind === \"call\") {\n const rule = countingCalls.find((c) => c.name === node.name);\n if (rule) {\n const operands = rule.count(node);\n const holds = evalTruthy(node);\n if (want) return holds ? operands : 0;\n return holds ? 0 : 1; // negated: De Morgan -> at least one operand fails -> 1\n }\n }\n // Any other node is an atom worth one constraint when its truth matches want.\n return evalTruthy(node) === want ? 1 : 0;\n}\n","// GENERATED - vendored from expr/family/engine-scopes.json by scripts/sync-conformance.mjs.\n// Do not edit here; edit the shared list and re-run the script.\n\n/** Every engine's game-wide scope token across the family. A compiler accepts every token here\n * that is not its own engine's, unchecked: the other engine owns those names and types. */\nexport interface EngineScope {\n token: string;\n engine: string;\n means: string;\n}\n\nexport const ENGINE_SCOPES: readonly EngineScope[] = [\n { token: \"patter\", engine: \"Patterplay\", means: \"Patter's shared globals\" },\n { token: \"story\", engine: \"Storylet Engine\", means: \"the Storylet Engine's shared @story properties\" },\n];\n","// ---------------------------------------------------------------------------\n// @storylet-studio/dialect - the storylets expression dialect.\n//\n// One dialect drives runtime eval AND publish-time validation (schema 6.1).\n// Five scopes, fixed (Reboot 3); bare `@name` is `@story.name` (schema 6.2,\n// resolved 2026-07-19). Function eval semantics carry from the old engine's\n// storylets-dialect.ts where the function survives (random, check_flags,\n// set_flags); the play-history functions are the new set pinned in schema 6.3.\n// ---------------------------------------------------------------------------\n\nimport { EvalError } from \"@wildwinter/expr\";\nimport { ENGINE_SCOPES } from \"./engine-scopes.js\";\nexport { ENGINE_SCOPES } from \"./engine-scopes.js\";\nexport type { EngineScope } from \"./engine-scopes.js\";\nimport type { Dialect, EvalHelpers, ExprNode, ScalarValue } from \"@wildwinter/expr\";\n\n/** turns_since_played / _in when the card / value has never been played. */\nexport const NEVER_PLAYED = 9999;\n\n/**\n * Host callbacks the dialect's functions read from `EvalContext.host`. The\n * runtime supplies these (its PRNG, its play log); the compiler validates\n * without them.\n */\nexport interface StoryletsHost {\n /** One PRNG draw in [0, 1) - the session mulberry32 (schema 3.3). */\n nextRandom(): number;\n /** Plays of the card (gameId) from the play log. */\n countPlayed(card: string): number;\n /** Turns since the card (gameId) last played; NEVER_PLAYED when never. */\n turnsSincePlayed(card: string): number;\n /** Plays of cards belonging to the dimension value (both by gameId). */\n countPlayedIn(dimension: string, value: string): number;\n /** As above; NEVER_PLAYED when never. */\n turnsSincePlayedIn(dimension: string, value: string): number;\n}\n\nconst host = (h: EvalHelpers): Partial<StoryletsHost> =>\n (h.ctx.host ?? {}) as Partial<StoryletsHost>;\n\nconst stringArg = (fn: string, args: ExprNode[], h: EvalHelpers, i: number): string => {\n const v = h.evaluate(args[i]!);\n if (typeof v !== \"string\" || v === \"\") {\n throw new EvalError(`${fn}() argument ${i + 1} must be a non-empty string`);\n }\n return v;\n};\n\n/** Resolve the first argument of check_flags / set_flags to a flag set. */\nconst flagsArg = (fn: string, args: ExprNode[], h: EvalHelpers): string[] => {\n if (args.length === 0) {\n throw new EvalError(`${fn}() requires at least one argument (the flags property)`);\n }\n const v = h.evaluate(args[0]!);\n if (Array.isArray(v)) return v as string[];\n // An unset flags property may surface as false; treat as the empty set\n // (carried from the old dialect). Anything else is a type error.\n if (v === false) return [];\n throw new EvalError(`${fn}() first argument must be a flags property`);\n};\n\n/** The Storylet Engine's own five scope tokens. */\nexport const OWN_SCOPES = [\"story\", \"world\", \"box\", \"deck\", \"hand\"] as const;\n\n/**\n * Other engines' game-wide scopes a card may name, from the family's shared list\n * (expr/family/engine-scopes.json): `@patter.gold` reads Patterplay's shared\n * globals in a game that runs both. On by default, with no project setting, so\n * combining the engines needs no wiring. The compiler lets these through\n * unchecked (the other engine owns its names and types), and the engine reports\n * at run time when the game has not registered one.\n */\nexport const EXTERNAL_SCOPES: readonly string[] = ENGINE_SCOPES\n .map((s) => s.token)\n .filter((t) => !(OWN_SCOPES as readonly string[]).includes(t));\n\nexport const storyletsDialect: Dialect = {\n // A missing property in a PRESENT scope is always an error: every property\n // is declared with a default, so absence means a publish bug, a drifted\n // save, or a foreign scope the host never fed (schema 6.2). The same holds\n // for another engine's scope: `@patter.glod` is a typo, and it says so the\n // first time the card is evaluated rather than quietly reading false.\n scopes: [\n ...OWN_SCOPES.map((token) => ({ token, missing: \"throw\" as const })),\n ...EXTERNAL_SCOPES.map((token) => ({ token, missing: \"throw\" as const })),\n ],\n defaultScope: \"story\",\n functions: {\n random: {\n minArgs: 2, maxArgs: 2, returnType: \"number\",\n eval(args: ExprNode[], h: EvalHelpers): ScalarValue {\n if (args.length !== 2) throw new EvalError(\"random(a, b) requires exactly 2 arguments\");\n const nextRandom = host(h).nextRandom;\n if (!nextRandom) throw new EvalError(\"random() called without a PRNG in context\");\n const a = h.evaluate(args[0]!);\n const b = h.evaluate(args[1]!);\n if (typeof a !== \"number\" || typeof b !== \"number\") {\n throw new EvalError(\"random(a, b) arguments must be numbers\");\n }\n if (!Number.isInteger(a) || !Number.isInteger(b)) {\n throw new EvalError(\"random(a, b) arguments must be integers\");\n }\n const lo = Math.min(a, b);\n const hi = Math.max(a, b);\n return Math.floor(nextRandom() * (hi - lo + 1)) + lo;\n },\n },\n check_flags: {\n minArgs: 1, returnType: \"boolean\", flagDeltaArgs: true,\n eval(args: ExprNode[], h: EvalHelpers): ScalarValue {\n const flags = flagsArg(\"check_flags\", args, h);\n for (let i = 1; i < args.length; i++) {\n const arg = args[i]!;\n if (arg.kind !== \"flagdelta\") {\n throw new EvalError(\"check_flags() flag args must be +flagName or -flagName\");\n }\n if (arg.sign === \"+\" ? !flags.includes(arg.name) : flags.includes(arg.name)) {\n return false;\n }\n }\n return true;\n },\n },\n set_flags: {\n minArgs: 1, returnType: \"flags\", flagDeltaArgs: true,\n eval(args: ExprNode[], h: EvalHelpers): ScalarValue {\n const result = [...flagsArg(\"set_flags\", args, h)];\n for (let i = 1; i < args.length; i++) {\n const arg = args[i]!;\n if (arg.kind !== \"flagdelta\") {\n throw new EvalError(\"set_flags() flag args must be +flagName or -flagName\");\n }\n if (arg.sign === \"+\") {\n if (!result.includes(arg.name)) result.push(arg.name);\n } else {\n const idx = result.indexOf(arg.name);\n if (idx >= 0) result.splice(idx, 1);\n }\n }\n // Sorted so a SAVE is deterministic: the same flags reached by different routes\n // serialise to the same bytes, which keeps save diffs and cross-runtime byte\n // comparisons stable. It is no longer what makes equality work - flags compare\n // as a SET since 2026-09-01 - so this is now about the stored form only, and\n // Patterplay not sorting is a difference that costs nothing.\n return result.sort();\n },\n },\n count_played: {\n minArgs: 1, maxArgs: 1, returnType: \"number\",\n eval(args: ExprNode[], h: EvalHelpers): ScalarValue {\n const card = stringArg(\"count_played\", args, h, 0);\n const fn = host(h).countPlayed;\n if (!fn) throw new EvalError(\"count_played() called without a play log in context\");\n return fn(card);\n },\n },\n turns_since_played: {\n minArgs: 1, maxArgs: 1, returnType: \"number\",\n eval(args: ExprNode[], h: EvalHelpers): ScalarValue {\n const card = stringArg(\"turns_since_played\", args, h, 0);\n const fn = host(h).turnsSincePlayed;\n if (!fn) throw new EvalError(\"turns_since_played() called without a play log in context\");\n return fn(card);\n },\n },\n count_played_in: {\n minArgs: 2, maxArgs: 2, returnType: \"number\",\n eval(args: ExprNode[], h: EvalHelpers): ScalarValue {\n const dimension = stringArg(\"count_played_in\", args, h, 0);\n const value = stringArg(\"count_played_in\", args, h, 1);\n const fn = host(h).countPlayedIn;\n if (!fn) throw new EvalError(\"count_played_in() called without a play log in context\");\n return fn(dimension, value);\n },\n },\n turns_since_played_in: {\n minArgs: 2, maxArgs: 2, returnType: \"number\",\n eval(args: ExprNode[], h: EvalHelpers): ScalarValue {\n const dimension = stringArg(\"turns_since_played_in\", args, h, 0);\n const value = stringArg(\"turns_since_played_in\", args, h, 1);\n const fn = host(h).turnsSincePlayedIn;\n if (!fn) throw new EvalError(\"turns_since_played_in() called without a play log in context\");\n return fn(dimension, value);\n },\n },\n },\n};\n\n/**\n * The dialect, also accepting the game-wide scopes `tokens` names: every token a game's\n * shared scopes folder declares (`game-scopes/`, patterkit design/shared-scopes.md), so a\n * game's own scope such as `@player` parses where the shared vocabulary alone would not. A\n * token the dialect already has keeps its place and its policy; each new one gets the policy\n * another engine's scope has, since whoever declared it owns its names. With nothing new to\n * add this is `storyletsDialect` itself, so a project with no shared folder compiles exactly\n * as before. For editing and publishing only: a runtime evaluates a compiled bundle, which\n * names its scopes already.\n */\nexport function storyletsDialectWith(tokens: readonly string[]): Dialect {\n const known = new Set(storyletsDialect.scopes.map((s) => s.token));\n const added = [...new Set(tokens)].filter((t) => !known.has(t));\n if (added.length === 0) return storyletsDialect;\n return {\n ...storyletsDialect,\n scopes: [...storyletsDialect.scopes, ...added.map((token) => ({ token, missing: \"throw\" as const }))],\n };\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 /**\n * The durability axis (design/engine-server.md 4.2), valid wherever `shared`\n * is valid and orthogonal to it: `shared` says whose value this is WITHIN a\n * run, `durable` says whether the value survives the run at all. A durable\n * shared property is the installation's memory (\"trolls defeated since we\n * opened\"); a durable per-flow one is the player's pocket (visits,\n * allegiance, what they earned).\n *\n * INERT TO THE RUNTIME. The engine partitions by `shared` alone and never\n * reads this. Durability is what the SERVER does at a run boundary: it reads\n * the declarations, lifts the durable values out of the partitions before the\n * world restarts, and writes them back into the fresh engine afterwards,\n * entirely through `getProperty` / `setProperty`.\n *\n * On a `@world` declaration the flag is a validation error, for the reason\n * `shared` is: @world is the game's own state, and how long the game keeps it\n * is the game's business.\n */\n durable?: boolean;\n purpose?: string;\n}\n\n/** A template field (box-defined), of the card template or of the outcome\n * fields. Data for the host; the engine never interprets fields and they are\n * 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// --- the value scope's owner segment (design/engine-server.md 4.4) -----------\n//\n// Every other owned scope names its owner with a gameId that is unique across\n// the bundle: box, deck, hand and card. A TAG's gameId is unique only within\n// its group, and a group's only within its box, so two boxes may each name a\n// tag \"docks\" - as ordinary as two boxes each having a \"zone\" group - and\n// `value.docks.danger` then names two stores.\n//\n// So the value scope's owner segment is box-qualified where it has to be:\n// `value.<boxGameId>/<tagGameId>.<name>`. The slash sits INSIDE the owner\n// segment, so the address still splits into three on the dot and no parser\n// changes shape. The qualified form is always accepted; the short form is\n// accepted while exactly one tag in the bundle carries that gameId, and\n// refused when more do, naming the qualified candidates. What a runtime\n// PRINTS - `listProperties`, a write on the trace, a load report, an\n// examiner - is the short form except where the gameId repeats.\n//\n// One definition, because the Board draws these addresses from the bundle\n// while the engine builds them from its own index, and an address the editor\n// shows that the engine will not take is the fault 4.4 was fixing.\n\n/** The three answers a value address needs, all derived from the bundle. */\nexport interface ValueAddresses {\n /** Tag internal id -> the owner segment an address PRINTS for it. */\n print: Map<string, string>;\n /** Every owner segment a value address ACCEPTS -> the tag's internal id.\n * Holds the qualified form for every tag and the short form only for a\n * gameId no other tag shares. */\n accept: Map<string, string>;\n /** A tag gameId more than one box uses -> its qualified forms, in bundle\n * order. Empty for the overwhelming majority of projects, and what a\n * refusal lists. */\n repeated: Map<string, string[]>;\n}\n\n/** The owner segment of every tag in the bundle, both ways round. */\nexport function valueAddresses(bundle: {\n boxes: readonly { id: string; gameId?: string; title?: string; tagGroups: readonly TagGroup[] }[];\n}): ValueAddresses {\n const tags: { id: string; gameId: string; qualified: string }[] = [];\n for (const box of bundle.boxes) {\n const boxGameId = effectiveGameId(box);\n for (const group of box.tagGroups) {\n for (const tag of group.tags) {\n const gameId = effectiveGameId(tag);\n tags.push({ id: tag.id, gameId, qualified: `${boxGameId}/${gameId}` });\n }\n }\n }\n // Distinct qualified forms per gameId. Distinct rather than a count: two\n // groups in ONE box may also name a tag the same way, and a refusal that\n // offered the same address twice would be no help at all. Those two share\n // the qualified segment, and the first in bundle order answers to it, which\n // is what the short form did for everything before this rule.\n //\n // That last case is closing at the source rather than here (question 16,\n // ruled 2026-09-06): the compiler WARNS that a tag gameId must be unique\n // within its box, across all of that box's groups, and refuses it from the\n // next release. So this stays as the reading rule for a bundle built before\n // that, and a bundle built after it has no repeated qualified form to read.\n const forms = new Map<string, string[]>();\n for (const tag of tags) {\n const list = forms.get(tag.gameId) ?? [];\n if (!list.includes(tag.qualified)) list.push(tag.qualified);\n forms.set(tag.gameId, list);\n }\n const print = new Map<string, string>();\n const accept = new Map<string, string>();\n const repeated = new Map<string, string[]>();\n for (const tag of tags) {\n const candidates = forms.get(tag.gameId) ?? [tag.qualified];\n const ambiguous = candidates.length > 1;\n print.set(tag.id, ambiguous ? tag.qualified : tag.gameId);\n if (!accept.has(tag.qualified)) accept.set(tag.qualified, tag.id);\n if (!ambiguous && !accept.has(tag.gameId)) accept.set(tag.gameId, tag.id);\n if (ambiguous) repeated.set(tag.gameId, candidates);\n }\n return { print, accept, repeated };\n}\n\n/** What an ambiguous short-form value address is told: the candidates, in\n * full, because \"that names two tags\" without them leaves a host reading a\n * bundle it did not write to find out which boxes. */\nexport function ambiguousValueAddressMessage(\n segment: string, name: string, candidates: readonly string[],\n): string {\n const forms = candidates.map((q) => `\"value.${q}.${name}\"`);\n const list = forms.length <= 1 ? (forms[0] ?? \"\")\n : `${forms.slice(0, -1).join(\", \")} or ${forms[forms.length - 1]}`;\n return `\"value.${segment}.${name}\" names a tag in ${candidates.length} boxes; write ${list}`;\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/**\n * A count of a TIMED box's turns, said as time (design/engine-server.md 4.8):\n * `turnSpan(30, 60)` is \"30 min\", and `turnSpan(30, 60, true)` is \"30 minutes\".\n *\n * One definition, because the conversion appears wherever a designer might\n * otherwise have to do it in their head: the card editor's Redraw field, the\n * box page, the Board's advance buttons, and the coverage report's turn\n * budget. Two of those want the unit spelled out and two want it short, which\n * is the whole of `long`.\n */\nexport function turnSpan(turns: number, seconds: number, long = false): string {\n const total = Math.max(0, Math.round(turns * seconds));\n const say = (n: number, short: string, one: string, many: string): string =>\n long ? `${n} ${n === 1 ? one : many}` : `${n} ${short}`;\n if (total < 60) return long ? say(total, \"s\", \"second\", \"seconds\") : `${total}s`;\n if (total < 3600) {\n const minutes = total % 60 === 0 ? total / 60 : Math.round(total / 6) / 10;\n return say(minutes, \"min\", \"minute\", \"minutes\");\n }\n let hours = Math.floor(total / 3600);\n let rest = Math.round((total % 3600) / 60);\n if (rest === 60) { hours += 1; rest = 0; }\n const said = say(hours, \"hr\", \"hour\", \"hours\");\n return rest === 0 ? said : `${said} ${say(rest, \"min\", \"minute\", \"minutes\")}`;\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 /** Template data, as `Card.fields` is: field name -> value, declared by\n * the box's `outcomeFields`, validated at publish, and handed to the host\n * with the outcome. The engine never reads it: a press can say one line\n * (\"The notice is in your pocket\") without spending a card on it. */\n fields?: Record<string, ScalarValue>;\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 /** Does this card's `redraw: \"never\"` spend survive the run\n * (design/engine-server.md 4.2)? Absent takes the deck's flag, set here it\n * overrides the deck, exactly as `shared` does. `shared` decides who a\n * spend counts for WITHIN a run; this decides whether it outlives one.\n *\n * Only `\"never\"` crosses the run boundary, for the reason only `\"never\"`\n * crosses the flow boundary (shared-scarcity 9.3.2): a finite cooldown is\n * an absolute turn of a box clock, and the clock resets with the run. On\n * any other redraw the flag is a compile warning.\n *\n * INERT TO THE RUNTIME, like the declaration flag: the server lifts the\n * durable spends at run end (per-flow ones from the flow's `never`\n * cooldowns, shared ones from the engine's spent set) and puts them back\n * through `openFlow(id, { restore })` and `markTaken`. */\n durable?: boolean;\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 /** Every `redraw: \"never\"` card in this pile is spent for good, past the end\n * of the run, unless the card says otherwise (design/engine-server.md 4.2).\n * The container carries the flag for the reason `shared` is carried here:\n * a pile is what an author reaches for when a rule is true of all of it. */\n durable?: 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/** The scopes a movable hole may be filled from (design/engine-server.md 4.6):\n * the two `boundBy` already allows, plus `@hand` - the asking hand's OWN\n * declared property, resolved before tag composition so a movable hole can\n * never depend on the tags it is choosing. */\nexport type HoleRefScope = \"hand\" | \"story\" | \"world\";\n\n/** A parsed hole reference: `@hand.zone` -> `{ scope: \"hand\", name: \"zone\" }`. */\nexport interface HoleRef {\n scope: HoleRefScope;\n name: string;\n}\n\nconst HOLE_REF = /^@(hand|world|story)\\.([a-z][a-z0-9_-]*)$/;\n\n/**\n * Is this `chosen` / binding value MEANT as a property reference rather than a\n * tag id?\n *\n * The test is the leading `@` alone, deliberately: a value that starts with\n * one and does not parse is a mistyped reference, which the compiler should\n * name as such, not a tag id that happens to look odd. Tag ids never begin\n * with `@`.\n */\nexport const isHoleRef = (value: string): boolean => value.startsWith(\"@\");\n\n/** Parse a hole reference, or undefined when it is not one. The on-disk form\n * stays a plain string, so the canonical serialiser and the shard merge need\n * no change at all: a hole is still one group name against one value. */\nexport const parseHoleRef = (value: string): HoleRef | undefined => {\n const m = HOLE_REF.exec(value);\n return m === null ? undefined : { scope: m[1] as HoleRefScope, name: m[2]! };\n};\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. Literal tags only: what a\n * template FIXES is the same for every instance, and a hole that moves is\n * the instance's own business (`Hand.chosen`, 4.6). */\n bindings?: Record<string, string>;\n /** The holes: tag group ids each instance fills (one tag each, or one\n * property reference: 4.6). */\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 /**\n * Tag group id -> tag id, or a PROPERTY REFERENCE (`\"@hand.zone\"`,\n * `\"@story.where\"`, `\"@world.place\"`) the runtime resolves at ask time\n * (design/engine-server.md 4.6, the hand that moves). Still a plain string\n * on disk, so the canonical serialiser and the merge are untouched; what\n * widened is the meaning, and `parseHoleRef` is where it is read.\n *\n * `place` is never fillable this way: it is the hand's own name, not an axis.\n */\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 /**\n * Template instances: tag group id -> tag id, one per `chooses` hole.\n *\n * A value may instead be a PROPERTY REFERENCE (`\"@hand.zone\"`,\n * `\"@story.where\"`, `\"@world.place\"`), which makes the hole MOVABLE: the\n * runtime resolves the reference at ask time and binds the hole to the tag\n * the value names, so moving the Elder to the forest is `setProperty` and\n * nothing else (design/engine-server.md 4.6). Still a plain string on disk,\n * so the canonical serialiser and the shard merge need no change; read it\n * with `parseHoleRef`.\n */\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 /**\n * A TIMED box: its clock counts real time, one turn every `seconds` of the\n * run (design/engine-server.md 4.8). Absent is the ordinary box, whose turn\n * is a play.\n *\n * Two things follow, and only two. In the ENGINE, a play in this box\n * defaults to advancing nothing: `settings.playAdvancesTurns` does not\n * apply, so a designer cannot declare the convention and then forget to\n * switch play-advance off. Everywhere else it is what the tools SAY: the\n * host ticks the box (the runtime has no clock and gains none here), and a\n * card's `redraw: N` reads as N x `seconds`, which the editors, the bundle\n * inspectors and the coverage report spell out rather than leaving a\n * designer to know that 30 meant minutes.\n *\n * The number itself is inert to the runtime, which never reads it.\n */\n turn?: { seconds: number };\n /** The card template: what every card in this box carries. */\n fields: FieldDecl[];\n /** What every outcome in this box may carry, declared the same way.\n * Absent when the box declares none, so a bundle without them is byte for\n * byte what it was. */\n outcomeFields?: 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 * The play ladder (design/engine-server.md 4.10): how much of itself\n * Storyletter shows this project, in one setting with three rungs rather than\n * a set of toggles, because the features nest.\n *\n * solo one player, one flow: no sharing, no durability, no venue features\n * shared several players over one world: sharing appears\n * venue a production: nothing is hidden\n *\n * EDITOR-SIDE ONLY. It stays in the project shard beside `coverage` and\n * `export` and is never compiled: a solo project plays on the same Engine as a\n * venue one. Hidden is hidden rather than disabled, so going DOWN a rung is\n * refused when the project already contains what the rung would hide, and a\n * hand-edited shard above its rung is a compile warning.\n */\nexport type PlayRung = \"solo\" | \"shared\" | \"venue\";\n\n/** The default rung: a project shard that says nothing is a solo game. */\nexport const DEFAULT_PLAY_RUNG: PlayRung = \"solo\";\n\n/** The project shard's settings block: what the bundle carries, plus the\n * authoring-side play rung that it does not. */\nexport interface ProjectSettings extends BundleSettings {\n /** The play ladder rung (see `PlayRung`). Absent = \"solo\". */\n play?: PlayRung;\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 HERE, which reverses a ruling. Until 2026-09-05 this comment said\n * they were deliberately not: a site was where an author parked a hand while\n * working, held in the view sidecar precisely because it was not content, and a\n * host that wanted to place a hand had its zone from the compiled binding. That\n * held for a game, where a hand's zone is its only real-world meaning. It does\n * not hold for a physical experience (design/engine-server.md 4.3), where the\n * position IS content: it is where the kiosk stands, and a producer's map is\n * simply wrong without it. The alternative was a second file beside the bundle,\n * which would cost a format the inspectors do not read and would put the view\n * sidecar in the shipping path by the back door.\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 /** Where the placed hands stand on this map, by hand gameId, sorted by that\n * gameId so the bytes do not depend on authoring order. A hand nobody has\n * placed has no entry, and a map with no placed hand has no key at all. The\n * zone a site sits in is NOT repeated here: the hand's own binding is what\n * the runtime deals from, and a second copy could only go on to disagree. */\n sites?: { hand: string; x: number; y: number }[];\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 /** Other engines' game-wide scopes the content names (`patter`), sorted: the\n * family's shared vocabulary, let through unchecked by the compiler. The\n * engine reports when the game has not registered one. Absent when none. */\n externalScopes?: string[];\n}\n\n// --- the save envelope --------------------------------------------------------\n//\n// Version 2 (the one-registry model): property values are the game's\n// ScopeRegistry's, not the engine's. The envelope holds what is NOT a property\n// (boards, clocks, cooldowns, PRNGs, play logs, spent cards), plus, when the\n// engine made its own registry (a standalone game), that registry's values\n// under `registry`. A game that passed a registry saves it once itself.\n// Version 1 envelopes still load on every runtime: their property partitions\n// move into the registry under the keys below.\n//\n// Registry keys (identical on every runtime, since they are in the save):\n// `story` for the shared @story; `storylets/<kind>/<id>` for a shared box,\n// deck, hand, or value bag (kind is `box`, `deck`, `hand`, or `value`, id the\n// internal id); `storylets/flow/<flowId>/story` and\n// `storylets/flow/<flowId>/<kind>/<id>` for a flow's own. Ids escape `%` as\n// `%25` and `/` as `%2F`. A bag with no declared properties is not registered.\n// A self-backed @world (no resolver bound) is a stored property too, under\n// `world`.\n\nexport const SAVE_SCHEMA = \"storylets/save@2\";\n/** The version 1 envelope's schema tag, still read. */\nexport const SAVE_SCHEMA_V1 = \"storylets/save@1\";\n\nexport interface PlayRecord {\n /** Card and outcome by gameId (feeds the play-history functions). */\n card: string;\n /** \"\" for a card with no outcomes, played with none: the key is always\n * there, so a save's shape does not depend on the card. */\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), and the blob\n * `saveFlow` parks. */\nexport interface FlowSave {\n /** The per-flow property partitions. Carried by `saveFlow`, which parks one\n * flow whole; absent from a version 2 envelope's flows, whose properties\n * are the registry's. Present in every flow of a version 1 envelope. */\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 /** The shared property partitions: version 1 only. */\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 /** The engine's own registry's values, keyed by registry key: present only\n * when the engine made the registry itself (a standalone game). A game that\n * passed a registry saves it once, beside this envelope. */\n registry?: Record<string, PropertyBag>;\n shared: SharedSave;\n flows: Record<string, FlowSave>;\n}\n\n/** A version 1 envelope, from before the registry held the properties. Every\n * runtime still reads it: its partitions move into the registry as it loads. */\nexport interface SaveEnvelopeV1 {\n schema: typeof SAVE_SCHEMA_V1;\n content: BundleContent;\n shared: SharedSave & { props: PropsPartition };\n flows: Record<string, FlowSave & { props: PropsPartition }>;\n}\n\n// --- the load report (design/engine-server.md 4.9) ----------------------------\n//\n// `loadGame` is forgiving by design: a card the bundle no longer has drops off\n// the board, a property the save does not carry keeps its default, and a\n// version two builds newer loads without a word. That forgiveness is what makes\n// a save survive an edit, and it is also what hides the cost of a content\n// update from whoever is about to apply one. The report is the same walk,\n// itemised: `previewLoad` computes it and changes nothing, `loadGame` computes\n// it and applies it, and `previewFlowRestore` answers the same questions for\n// one flow (4.1's `openFlow(id, { restore })`).\n//\n// Card, hand and flow identities are GAME IDS: a report is host-facing and\n// internal ids mean nothing outside the project. The one exception is an\n// entity the edit DELETED - a vanished card, a vanished hand - which has no\n// gameId left to give, so the report carries the id the save itself carries.\n// There is nothing else to name it by.\n//\n// A property is named differently, and deliberately: by its ENGINE ADDRESS,\n// the string listProperties() prints and getProperty()/setProperty() accept.\n// A report entry is then something a host can act on rather than merely\n// print, and the runtimes have one property grammar instead of two.\n\n/** One card that a restore refused to put back on the board.\n *\n * `vanished` and `hand-vanished` are the edit's doing (the card, or the hand\n * it sat in, is no longer in the bundle). `claimed-elsewhere` is only ever a\n * single-flow restore into a LIVE engine: the card is shared, and the other\n * open flows already hold every copy the world has. */\nexport interface LoadEviction {\n flow: string;\n hand: string;\n card: string;\n reason: \"vanished\" | \"hand-vanished\" | \"claimed-elsewhere\";\n}\n\n/** One property the restore could not put back as it was. `flow` names the\n * flow whose half it belongs to; absent, it is the shared half.\n *\n * `path` is the engine's property address, spelled exactly as\n * `Flow.listProperties()` / `Engine.listProperties()` print it and exactly as\n * `getProperty` and `setProperty` accept it: `story.<name>` for the story\n * scope, `<scope>.<ownerGameId>.<name>` for the box, deck, hand and tag\n * scopes. No `@`, which belongs to the expression language and not to an\n * address.\n *\n * The owner segment is its GAMEID (design/engine-server.md 4.4), the name it\n * is called by everywhere else, so an operator reading a hot-swap report can\n * paste the address straight into `setProperty`. An owner the build no longer\n * has keeps the id the save carried: there is no gameId left to give it,\n * which is the rule the eviction list above has always used. */\nexport interface LoadProperty {\n flow?: string;\n path: string;\n}\n\n/** What a load or a flow restore would do that is not a plain restore\n * (design/engine-server.md 4.9). Arrays are sorted, so two runtimes given the\n * same save and bundle produce the same bytes; `flows` alone keeps the\n * envelope's own order, because a caller re-takes its handles in it. */\nexport interface LoadReport {\n /** No drift and nothing dropped, defaulted or retyped: the save goes back\n * exactly as it was. `flows` is not a divergence and does not count. */\n exact: boolean;\n project: string;\n /** Drift when the two differ; reported, never refused. */\n version: { saved: string; bundle: string };\n /** Drift when the two differ; reported, never refused. */\n hash: { saved: string; bundle: string };\n /** The flows this restores, in the order it restores them. */\n flows: string[];\n evicted: LoadEviction[];\n /** Cooldowns held for cards the bundle no longer has. */\n droppedCooldowns: { flow: string; card: string }[];\n /** Shared `redraw: \"never\"` entries for cards the bundle no longer has. */\n droppedSpent: string[];\n /** In the save, not declared any more. */\n droppedProperties: LoadProperty[];\n /** Declared, not in the save: it takes the declaration's default. */\n defaultedProperties: LoadProperty[];\n /** In the save, still declared, but the saved value no longer fits the\n * declaration (its type changed, or an enum value / quality stage was\n * edited away). It takes the declaration's default. */\n retypedProperties: LoadProperty[];\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 /** The engine's envelope: version 2 when written today, version 1 still read. */\n engine: SaveEnvelope | SaveEnvelopeV1;\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 AUTHOR's arrangement layer: the canvases, where cards sit on a deck's\n * node canvas and the furniture drawn round them. Its own shard because\n * positions churn (an afternoon of tidying a canvas touches every card) and\n * content does not, so a designer arranging and a writer editing never\n * collide on one file (design/graphical-views.md section 1.2). */\n view: \".storyletview\",\n /** The DESIGNER's map: where a box's hands stand in space, and the furniture\n * round them. One per box, beside the view shard.\n *\n * Split out of the view shard on 2026-09-06 (design/engine-server.md 9.1\n * point 5) because the two halves stopped having one owner. A hand's\n * position ships in the bundle's `maps` block (4.3) and is where a venue's\n * kiosk stands, so it is SHAPE, which a server's author key may not change;\n * the canvases are the author's own working drawing and never leave the\n * project folder. One file could not be both. */\n map: \".storyletmap\",\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 /** An installation contract: what a VENUE depends on, one file per\n * installation in `contracts/` at the project root\n * (design/engine-server.md 4.11). Its own shard, and its own folder, for the\n * walkthrough's reason (Reboot 7.5, S4): a different owner, a different\n * change rate, and a merge that must never collide with the author's edits,\n * since the server always wins its own file. */\n contract: \".storyletcontract\",\n} as const;\n\n/** Where the installation contracts live, relative to the project root. The\n * directory is the registry, as it is for a box's decks: a contract exists\n * because its file exists. */\nexport const CONTRACTS_DIR = \"contracts\";\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\";\nexport const MAP_SCHEMA = \"storylets/map@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\";\nexport const CONTRACT_SCHEMA = \"storylets/contract@0\";\n\n/**\n * What one installation depends on, written by the venue's server and read by\n * `validate` (design/engine-server.md 4.11).\n *\n * NOT THE AUTHOR'S FILE. A venue is provisioned against names - the hands its\n * stations deal, the boxes its scheduler ticks, the properties its clocks drive,\n * the fields its crew read - and the server writes them out so the tools that\n * already gate a build can refuse a rename before it reaches the venue. A\n * project playing at two venues has two of these. The author never edits one,\n * and today, with no server built, a project either receives one or has none.\n *\n * NEVER COMPILED. It is project-side config like `coverage` and `export`: the\n * server does not need its own contract handed back, it needs the bundle to\n * still honour it.\n *\n * BY GAMEID throughout, because a gameId is the name that crosses the project's\n * border and an internal id is authoring identity.\n */\nexport interface ContractShard {\n schema: typeof CONTRACT_SCHEMA;\n /** The installation this contract speaks for. One file per installation, and\n * two files naming the same one is an error. */\n installation: string;\n /** Who wrote it, for a human reading the file (\"Storylet Server 0.1.0\"). */\n by?: string;\n /** The server's revision when it wrote this. */\n revision?: number;\n /** Hands a station is bound to, by gameId: they may not be renamed or\n * removed. */\n hands?: string[];\n /** Timed boxes the venue's scheduler ticks, by box gameId, with the turn unit\n * in SECONDS it was provisioned against. A box whose unit changed means every\n * rest on its cards changed meaning. */\n boxes?: Record<string, { turn: number }>;\n /** Property paths the venue reads or drives, in the engine's own address\n * grammar with no `@` (\"world.time_wall\", \"story.visits\"), which is how\n * `listProperties()` prints them. */\n properties?: ContractProperty[];\n /** Card-template field names the crew and the bridges read. */\n fields?: string[];\n /** Outcome field names they read, the same way: the after-line a station\n * shows when a press lands. What `fields` is to the card template, this is\n * to the box's `outcomeFields`. */\n outcomeFields?: string[];\n}\n\n/**\n * One contracted property.\n *\n * A bare path is the common form and the one the spec's example writes. The\n * object form adds the TYPE the venue was provisioned against, which is the only\n * way `validate` can catch the break that costs a producer most: a property that\n * still exists under the same name and now holds something else. A server that\n * knows the type should write the object form; a hand-written contract may say\n * only the path and get the existence check alone.\n */\nexport type ContractProperty = string | { path: string; type?: PropertyType };\n\n/** The path a contracted property names, whichever form it was written in. */\nexport const contractPropertyPath = (p: ContractProperty): string =>\n typeof p === \"string\" ? p : p.path;\n\n/** The type a contracted property was provisioned against, when it says. */\nexport const contractPropertyType = (p: ContractProperty): PropertyType | undefined =>\n typeof p === \"string\" ? undefined : p.type;\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.\n * Carried by the MAP shard since 2026-09-06; `ViewShard.map` is the old\n * address, read for one release and never written. */\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 AUTHOR's arrangement layer for one box: where cards sit on their decks'\n * canvases, and the furniture drawn round them.\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 /** @deprecated The box map's old address, kept for one release and READ ONLY.\n * A reader that meets it uses it when the box has no `MapShard`, and the\n * formatter moves it; nothing writes it any more. Removed after the next\n * release, at which point a map left here is simply lost. */\n map?: BoxMap;\n}\n\n/** The DESIGNER's map for one box: where its hands stand in space.\n *\n * Split out of the view shard on 2026-09-06 (design/engine-server.md 9.1 point\n * 5). The two halves had stopped sharing an owner: a hand's position ships in\n * the bundle's `maps` block (4.3), which makes it the thing a venue provisions\n * its kiosks against, while a deck's canvas is a working drawing that never\n * leaves the folder. A server's author key may change the canvases and not\n * this.\n *\n * The map is NESTED under `map` rather than flattened to the top level, and\n * deliberately: the block's bytes are then exactly what the view shard held, so\n * the migration is a move of a value rather than a reshaping of it, the merge\n * strategy carries over word for word, and a reader that has to look in both\n * places is one expression (`box.map?.map ?? box.view?.map`).\n *\n * Source-only in the sense the view shard is not: `compileMaps` reads the\n * positions for the bundle's `maps` block, under `export.map`. */\nexport interface MapShard {\n schema: typeof MAP_SCHEMA;\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: ProjectSettings;\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 /**\n * Where the game's shared scopes folder is, relative to the folder holding this file\n * (`\"../../shared/game-scopes\"`). Authoring config, never compiled, and usually absent: the\n * tools find a `game-scopes/` folder by walking up from the project on their own, stopping at\n * the version-control root, so this is only for a folder that walk would not reach. A path\n * that doesn't exist is a project error. (patterkit design/shared-scopes.md.)\n */\n gameScopes?: string;\n /**\n * The Patter project this one is paired with: a `.patter` folder, relative to the folder\n * holding this file (`\"../story/the-hamlet.patter\"`). Authoring config, never compiled: the\n * engines still know nothing of each other (Reboot 10). With it, `validate` checks each card\n * against the scene of the same name in the Patter project's published bundle, and\n * Storyletter can open Patterpad at a card's scene. A folder that isn't there is a warning,\n * since a writer may hold the cards without the dialogue.\n */\n patter?: string;\n /**\n * The boxes the game performs through the paired Patter project, by box id: every card in them\n * plays the scene named after it. Authoring config, never compiled, and only meaningful beside\n * `patter`. With it, `validate` checks only these boxes and also reports a card with no scene;\n * Storyletter's Board plays their cards' scenes, and the playable export carries them.\n * Absent, every card that has a scene is checked and none is required to have one.\n */\n patterBoxes?: string[];\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 /** Declares a timed box (see `Box.turn`); compiled through unchanged. */\n turn?: { seconds: number };\n fields: FieldDecl[];\n /** The outcome fields (see `Box.outcomeFields`); a shard without the key\n * declares none. */\n outcomeFields?: 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 /** Its `redraw: \"never\"` cards are spent past the run: see Deck.durable. */\n durable?: 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// 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 TO THE STORY; the HOST still writes it, by passing\n * `{ host: true }` (see `set`). Default is read/write. (`type`/`values` feed\n * validation.)\n *\n * The distinction is the whole point of the flag on a foreign scope, where the\n * value is the game's own: a flag carried in the story's bundle must not lock a\n * game out of its own state. Ruled 2026-09-05, after both products met it - the\n * Storylet Engine's venue clock and Patter's coverage driver were each blocked\n * from the one property they existed to move.\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 /** The author's note on what the property is for, which another tool's picker shows as a tip\n * (shared game scopes, scopes.ts). The registry itself ignores it. */\n purpose?: string;\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 /** A name as this bag keys it: its normalisation policy applied. The registry\n * uses it to key quality ladders and the validation schema the bag's own way,\n * so a case-significant (identity) bag is not quietly folded to lower case\n * one layer up. */\n normalise(name: string): string {\n return 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 unless the caller says it is the\n * HOST (`host: true`), for whom `writable: false` was never a rule - it is\n * the story's promise, not the game's. `silent` and `host` are separate on\n * purpose: one is about who hears the write, the other about who may make\n * it. Returns the change. */\n set(name: string, value: ScalarValue, opts?: { silent?: boolean; reason?: string; host?: boolean }): BagChange {\n const n = this.norm(name);\n if (!opts?.host && 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 owner?: string;\n}\ninterface ForeignScope {\n kind: \"foreign\";\n resolver: ScopeResolver;\n decls: Map<string, ScopeDeclaration>;\n scopeWritable: boolean;\n norm: (name: string) => string;\n owner?: string;\n}\ntype Entry = OwnedScope | ForeignScope;\n\nconst lowerCase = (name: string): string => name.toLowerCase();\n\n/** Options for an owned scope the registry builds (`defineOwned`). */\nexport interface OwnedScopeOptions {\n /** The address prefix its examiner rows carry, separator included. Defaults\n * to `<token>.`; the address grammar is the product's, not the registry's. */\n pathPrefix?: string;\n /** Name normalisation: lower case by default; a case-significant product\n * passes identity. */\n normalise?: (name: string) => string;\n /** Who registered it (an engine's name). Named in a clash error and carried\n * on examiner rows, so one examiner can group a combined game by engine. */\n owner?: string;\n}\n\n/** Options for a foreign scope (`defineForeign`). */\nexport interface ForeignScopeOptions {\n /** Scope-level read/write default for its declarations (default true). */\n writable?: boolean;\n /** Name normalisation for the names passed to the resolver: lower case by\n * default; a case-significant product passes identity. */\n normalise?: (name: string) => string;\n /** Who registered it. See `OwnedScopeOptions.owner`. */\n owner?: string;\n}\n\n/** Options for a context or schema built from the registry. */\nexport interface AliasOptions {\n /**\n * Expression token -> registered key. `{ scene: \"patter/flow-2/scene/tavern\" }`\n * makes `@scene` read that instance bag, for this context only.\n *\n * The registry learns nothing about what the token MEANS: which flow, which\n * scene, which deck is an engine's own idea, and the engine names the key per\n * evaluation. It has to be the registry's mechanism rather than the engine\n * patching the context afterwards, because quality ladders and validation are\n * looked up by token too, and an alias applies to all three alike.\n *\n * An alias to a key that is not registered throws: a condition evaluated\n * against a scope that is not there is an engine bug, not a graceful false.\n */\n aliases?: Record<string, string>;\n}\n\n/** Options for `remove`. */\nexport interface RemoveOptions {\n /** Park an owned scope's values, to be handed back when the same key is next\n * registered (a live reload rebuilding an engine). No effect on a foreign\n * scope, whose values were never the registry's. */\n keep?: boolean;\n}\n\n/** Options for `load`. */\nexport interface LoadOptions {\n /** Keep what earlier loads parked, adding this blob's unclaimed sections to\n * it (a section for the same key replaces the parked one). Without it, each\n * load replaces whatever an earlier load parked. For an engine moving an\n * older save's values into a registry the game has already loaded. */\n keepParked?: boolean;\n}\n\n/**\n * The versioned owned-state fragment.\n *\n * @deprecated Versioning belongs to the save that embeds the values, not to the\n * registry; no engine ever called this. Embed `save()` in your own versioned\n * save instead. Removed at the next breaking release.\n */\nexport interface OwnedStateFragment {\n version: number;\n scopes: Record<string, Record<string, ScalarValue>>;\n}\n\n/** @deprecated See `OwnedStateFragment`. Removed at the next breaking release. */\nexport const SAVE_FRAGMENT_VERSION = 1;\n\nexport class ScopeRegistry {\n private readonly scopes = new Map<string, Entry>();\n /** Values loaded for keys nobody has registered yet, waiting to be claimed. */\n private readonly parked = new Map<string, Record<string, ScalarValue>>();\n private rev = 0;\n\n /**\n * A counter that moves whenever a scope is registered or removed, and at no\n * other time: it starts at 0 and each registration or removal adds 1. Values\n * changing does not move it. A caller that caches a context built by\n * `toEvalContext()` rebuilds it when this moves, because the context's set of\n * scopes is fixed when it is built while the values it reads stay live.\n */\n get revision(): number {\n return this.rev;\n }\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 * The third argument may be the path prefix alone (the pre-0.7 form) or an\n * options object.\n */\n defineOwned(token: string, declarations: ScopeDeclaration[], opts?: string | OwnedScopeOptions): this {\n const o: OwnedScopeOptions = typeof opts === \"string\" ? { pathPrefix: opts } : opts ?? {};\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 const bag = new PropertyBag(declarations, {\n pathPrefix: o.pathPrefix ?? `${token}.`,\n ...(o.normalise ? { normalise: o.normalise } : {}),\n });\n return this.mountOwned(token, bag, o.owner !== undefined ? { owner: o.owner } : undefined);\n }\n\n /**\n * Attach an EXISTING bag as an owned scope: an engine (or a host) holds the\n * bag and this registry reads, writes, lists and saves it like its own.\n *\n * If values were loaded for this key before anyone registered it, the bag\n * claims them now: laid over its seeded defaults by the bag's own `load` rule.\n */\n mountOwned(token: string, bag: PropertyBag, opts?: { owner?: string }): this {\n this.assertFree(token, opts?.owner);\n this.scopes.set(token, { kind: \"owned\", bag, ...(opts?.owner !== undefined ? { owner: opts.owner } : {}) });\n this.rev++;\n const waiting = this.parked.get(token);\n if (waiting) {\n bag.load(waiting);\n this.parked.delete(token);\n }\n return this;\n }\n\n /**\n * Unregister a scope. With `{ keep: true }` an owned scope's values are parked\n * and handed back when the same key is next registered, which is how a live\n * reload hands an engine's state to its replacement. Throws on an unknown key.\n */\n remove(token: string, opts?: RemoveOptions): this {\n const e = this.scopes.get(token);\n if (!e) throw new Error(`unknown scope '@${token}'`);\n if (opts?.keep && e.kind === \"owned\") this.parked.set(token, e.bag.save());\n this.scopes.delete(token);\n this.rev++;\n return this;\n }\n\n /**\n * Drop parked values nobody claimed. Parked values are kept in the next save by\n * default, so nothing loaded is lost to a flow or deck that simply has not\n * reopened yet; a game that knows they are dead drops them here.\n *\n * With a `prefix`, only keys starting with it are dropped: an engine resetting\n * itself drops its own instance keys (`my-engine/`) and leaves every other\n * engine's alone.\n */\n discardParked(prefix?: string): this {\n if (prefix === undefined) this.parked.clear();\n else for (const key of [...this.parked.keys()]) if (key.startsWith(prefix)) this.parked.delete(key);\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 opts: boolean | ForeignScopeOptions = true,\n ): this {\n // A boolean is the pre-0.7 form: the scope-level writable default alone.\n const o: ForeignScopeOptions = typeof opts === \"boolean\" ? { writable: opts } : opts;\n this.assertFree(token, o.owner);\n const norm = o.normalise ?? lowerCase;\n const decls = new Map<string, ScopeDeclaration>();\n for (const d of declarations) decls.set(norm(d.name), d);\n this.scopes.set(token, {\n kind: \"foreign\", resolver, decls, scopeWritable: o.writable ?? true, norm,\n ...(o.owner !== undefined ? { owner: o.owner } : {}),\n });\n this.rev++;\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(e.norm(name));\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 scope.\n *\n * `writable: false` is the STORY's promise, so a story write is refused and\n * a HOST write is not: pass `{ host: true }` from a host's own surface (its\n * `setProperty`, its tooling, a coverage driver) and never from the path an\n * outcome or effect takes. A foreign scope whose resolver has no `set` is\n * refused for everyone, host included - that is not a rule to bypass, it is\n * a game that gave no way to write. */\n set(scope: string, name: string, value: ScalarValue, opts?: { host?: boolean }): 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, opts?.host ? { host: true } : undefined);\n } catch {\n throw new Error(`'@${scope}.${name}' is read-only`);\n }\n return;\n }\n const n = e.norm(name);\n if (!e.resolver.set) throw new Error(`'@${scope}.${name}' is read-only`);\n if (!opts?.host && !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; owner?: string } & PropertyRow)[] {\n const out: ({ scope: string; owner?: string } & PropertyRow)[] = [];\n for (const [token, e] of this.scopes) {\n const owner = e.owner !== undefined ? { owner: e.owner } : {};\n if (e.kind === \"owned\") {\n for (const row of e.bag.rows()) out.push({ scope: token, ...owner, ...row });\n } else {\n for (const [n, d] of e.decls) {\n out.push({\n scope: token, ...owner,\n ...rowFor(d, e.resolver.get(n), this.foreignWritable(e, n), n, `${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>, opts?: AliasOptions): EvalContext {\n const view = this.view(opts?.aliases);\n const scopes: EvalContext[\"scopes\"] = {};\n for (const [token, e] of view) scopes[token] = e.kind === \"owned\" ? e.bag.values : e.resolver;\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(view);\n return qualities.size === 0 ? { scopes, host } : {\n scopes, host,\n qualities: (scope, name) => {\n const e = view.get(scope);\n return e ? qualities.get(scope)?.get(normOf(e)(name)) : undefined;\n },\n };\n }\n\n /**\n * The scopes an expression sees: every registered key under its own token,\n * then each alias token pointing at its key's entry (an alias shadows a key of\n * the same name). Keys an engine uses for instance bags (`engine/flow-2/...`)\n * are not valid expression tokens, so they are present but unreachable.\n */\n private view(aliases?: Record<string, string>): Map<string, Entry> {\n const out = new Map(this.scopes);\n for (const [token, key] of Object.entries(aliases ?? {})) {\n const e = this.scopes.get(key);\n if (!e) throw new Error(`alias '@${token}' names '${key}', which is not registered`);\n out.set(token, e);\n }\n return out;\n }\n\n /** Every quality declaration's ladder, keyed scope token then name (the\n * scope's own normalisation). */\n private qualityLadders(view: Map<string, Entry>): Map<string, Map<string, readonly string[]>> {\n const out = new Map<string, Map<string, readonly string[]>>();\n for (const [token, e] of view) {\n for (const [n, d] of declsOf(e)) {\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(n, 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. Aliases\n * apply as they do to `toEvalContext`, so a condition written against `@scene`\n * validates against the instance bag the engine names.\n */\n toSchema(opts?: AliasOptions): ExpressionSchema {\n const properties = new Map<string, Map<string, { type: PropertyType; enumValues?: string[]; stages?: string[] }>>();\n for (const [token, e] of this.view(opts?.aliases)) {\n const decls = declsOf(e);\n if (decls.length === 0) continue;\n const m = new Map<string, { type: PropertyType; enumValues?: string[]; stages?: string[] }>();\n for (const [n, d] of decls) m.set(n, {\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 (foreign scopes are the game's, and the game\n * saves them), as bare bags keyed by token, plus any values still parked, so\n * a save taken before every engine has re-registered loses nothing. The\n * registry knows nothing about game saves: a game embeds this in its own. */\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 for (const [token, vals] of this.parked) out[token] = structuredClone(vals);\n return out;\n }\n\n /**\n * Restore from a `save` blob. An owned scope lays its section over its current\n * values (the bag's `load` rule). A section for a key nobody has registered\n * yet is PARKED and handed over when that key registers, so a game can load\n * its registry before its engines have reopened their flows or decks. A\n * section for a foreign scope is ignored: those values are the game's.\n *\n * A load replaces whatever was parked before it: it is a whole restore, and\n * residue from an earlier load must not leak into this one.\n *\n * Changed in 0.7.0: sections for unregistered keys used to be dropped.\n */\n load(blob: Record<string, Record<string, ScalarValue>>, opts?: LoadOptions): void {\n if (!opts?.keepParked) this.parked.clear();\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 else if (!e) this.parked.set(token, structuredClone(vals));\n }\n }\n\n /**\n * `save()` wrapped with a version stamp.\n *\n * @deprecated Versioning belongs to the save that embeds the values; no\n * engine ever called this. Embed `save()` in your own versioned save.\n * Removed at the next breaking release.\n */\n saveFragment(): OwnedStateFragment {\n return { version: SAVE_FRAGMENT_VERSION, scopes: this.save() };\n }\n\n /**\n * Restore from a versioned fragment; an unsupported version throws.\n *\n * @deprecated See `saveFragment`. Removed at the next breaking release.\n */\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 /**\n * A token is taken once. There is no reserved-token list: a clash surfaces\n * here, the moment a game combines its engines, which is the only moment\n * anyone knows which engines are present. With owners recorded the error says\n * whose token it already is.\n */\n private assertFree(token: string, owner?: string): void {\n const e = this.scopes.get(token);\n if (!e) return;\n const by = e.owner !== undefined ? ` by ${e.owner}` : \"\";\n const wants = owner !== undefined ? ` (wanted by ${owner})` : \"\";\n throw new Error(`scope '@${token}' is already registered${by}${wants}`);\n }\n}\n\n/** A scope entry's declarations, keyed by its own normalisation. */\nfunction declsOf(e: Entry): [string, ScopeDeclaration][] {\n if (e.kind === \"foreign\") return [...e.decls.entries()];\n return e.bag.declarations().map((d) => [e.bag.normalise(d.name), d]);\n}\n\n/** A scope entry's name normalisation. */\nfunction normOf(e: Entry): (name: string) => string {\n return e.kind === \"foreign\" ? e.norm : (n) => e.bag.normalise(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 reference runtime: an Engine is the world + flow manager, and ALL play\n// happens on a Flow handle (design/flows.md; the shape is Patter's, adopted\n// deliberately so a host driving both engines holds two objects with the\n// same grammar). The dealing semantics of design/storylets-schema.md\n// section 3 run per flow, implemented exactly and held to the conformance\n// corpus.\n//\n// The flow model, in one place:\n// - an Engine owns the bundle, every lookup built from it, the SHARED\n// property partitions and the @world resolver; a Flow owns its own\n// PRNG, per-box clocks, cooldowns, board, claims, play history and the\n// per-flow property partitions. Flows meet only through shared state.\n// - sharing is a per-property `shared` flag on the declaration (never a\n// scope token): @story defaults shared; box, deck, hand and tag\n// properties default per-flow. Every name is shared XOR per-flow, so a\n// read is a union of two bags and a write routes by name.\n// - every property bag lives in ONE ScopeRegistry per game (the\n// one-registry model): the game hands the engine its registry\n// (EngineOptions.registry) or the engine makes its own and acts as its\n// own game. The shared @story registers under `story`, every other bag\n// under a key starting `storylets/`, which no expression can name.\n// saveGame() carries what is NOT a property, plus the registry's values\n// only when the engine made the registry itself.\n// - @world is the game's: a resolver it binds (EngineOptions.world, never\n// saved), a scope it registers in its registry, or, for a standalone\n// engine, a self-backed bag the registry stores and saves.\n// - there is no default flow and no ambient current flow: openFlow(id) is\n// the only way in, an existing id is REPLACED (the old flow closes),\n// and a closed flow's handle is INERT - every verb throws (Patter's\n// stale-handle rule).\n// - engine.getProperty serves world.* and shared refs only; a ref that\n// resolves per-flow throws, naming the fix (Patter's teaching rule).\n//\n// Key dealing contracts, unchanged from round 2 (all per flow now):\n// - two verbs: deal(hand) claims, peek(box, criteria) just looks; you can\n// never play a card you only peeked (3.1, look/use rule)\n// - availability order: deck gate -> cooldown -> tags -> hand condition ->\n// card condition -> claims (3.1)\n// - claims are physical WITHIN a flow: a card sits in at most `copies`\n// hands of that flow's board at once, at most once in any one hand; the\n// ledger is derived from the board contents (3.5)\n// - a SHARED card (its deck's flag, or its own overriding it) is scarce\n// across flows too: at most `sharedCopies` hands anywhere, counted over\n// every live flow's board, and a shared `redraw: \"never\"` is spent for\n// everyone the first time anyone plays it. A finite redraw deliberately\n// stays per flow - a cooldown is an absolute turn of a per-flow clock, so\n// there is nothing shared to compare it against (design/shared-scarcity.md)\n// - the reserved home group inverts the wildcard: a homed card is\n// available only to an ask binding its home (2.4)\n// - ranking: priority desc -> specificity desc (box toggle) -> seeded\n// shuffle of each maximal tie run (3.2)\n// - one PRNG per flow: expression random(), tie shuffles and the batch\n// deal's hand-order shuffle all advance it; state lives in the save (3.3)\n// - each box has its own turn counter PER FLOW; cooldowns are absolute\n// next-eligible turns of the card's box's clock, set at play time from\n// the post-advance turn; \"never\" is MAX_SAFE_INTEGER, not Infinity (3.4)\n// - @hand composes bound-tag props -> hand props -> chosen tags/criteria\n// (by group name), later shadowing earlier; writes route back to their\n// source; criteria names cannot be written (3.6)\n// - outcome availability is never snapshotted: outcomes() and play()\n// evaluate gates against current state (3.1, 3.7)\n// - a trace event fires after the state it reports has landed, so a\n// handler reading the flow inside it sees the effect (the Live Link's\n// board snapshot depends on this; the shared fixture pins it)\n// ---------------------------------------------------------------------------\n\nimport { deserialiseAst, evaluate } from \"@wildwinter/expr\";\nimport type { EvalContext, ExprNode, ScalarValue, ScopeResolver } from \"@wildwinter/expr\";\nimport { matchedSpecificity } from \"@wildwinter/expr-specificity\";\nimport { storyletsDialect, NEVER_PLAYED } from \"@storylet-studio/dialect\";\n\n/** The play-history indexes' key for one (group, tag) pair.\n *\n * A UNIT SEPARATOR (U+001F) joins them: ids are letters, digits and\n * underscores, so a control character cannot occur in one and two different\n * pairs can never collide into one key the way a \".\" or \":\" join could. NUL\n * would say the same thing and was the first choice, but GDScript will not\n * carry one in a string - it substitutes U+FFFD and warns on every parse - and\n * the four runtimes keep the same spelling. */\nconst tagKey = (groupId: string, tagId: string): string => `${groupId}\\u001f${tagId}`;\n\nimport type { StoryletsHost } from \"@storylet-studio/dialect\";\nimport {\n PLACE_GROUP, ambiguousValueAddressMessage, effectiveGameId, isHoleRef, parseHoleRef, valueAddresses,\n} from \"@storylet-studio/model\";\nimport type {\n Box, Bundle, BundleContent, Card, Deck, Expression, FlowSave, Hand, HandTemplate,\n LoadEviction, LoadProperty, LoadReport, PlayRecord, PropertyBag, PropertyDecl, PropsPartition,\n SaveEnvelope, SaveEnvelopeV1, Tag, TagGroup,\n} from \"@storylet-studio/model\";\nimport { SAVE_SCHEMA, SAVE_SCHEMA_V1 } from \"@storylet-studio/model\";\nimport { PropertyBag as StateBag, ScopeRegistry } from \"@wildwinter/scoperegistry\";\nimport type { PropertyRow, ScopeDeclaration } from \"@wildwinter/scoperegistry\";\nimport { makePrng, shuffleInPlace } from \"./prng.js\";\nimport type { Prng } from \"./prng.js\";\n\nexport interface EngineOptions {\n /** Default seed for each flow's PRNG; override per flow in openFlow\n * (cross-runtime determinism, schema 3.3). Default 0. */\n seed?: number;\n /** Retain each flow's event log for introspection - the game-engine seam\n * (schema 5): every trace event, sequence-stamped and turn-stamped where\n * the event has a box context. `true` keeps the default 1000 entries\n * (oldest dropped first). Off by default; subscribeTrace stays the\n * zero-retention stream. */\n log?: boolean | { cap?: number };\n /**\n * The host's resolver for @world - the values the game owns and the\n * story reads (and, where `set` is offered, writes). Engine-level, shared\n * by all flows, never saved: the game keeps these values. Omit it and a\n * standalone engine self-backs @world from the declared defaults, as a\n * property its registry stores and saves. A game running several engines\n * registers @world in its registry itself instead.\n */\n world?: ScopeResolver;\n /**\n * The game's registry: ONE per game, holding every engine's properties\n * except those the game keeps itself, saved once. Given one, the engine\n * registers its own scopes in it (@story under `story`, every other bag\n * under a key starting `storylets/`, and @world if `world` is passed),\n * reads every other scope from it, and `saveGame()` leaves the property\n * values to the game. @world is then the game's to register: owned if the\n * registry should store it, foreign if the game keeps it. Omit it and the\n * engine makes its own registry and acts as its own game: it self-backs\n * @world, and `saveGame()` carries the registry's values too.\n */\n registry?: ScopeRegistry;\n /**\n * Diagnostics hook (opt-in, dev tooling only): fired when `openFlow` REPLACES\n * a flow that still had cards dealt, with the flow id and how many. The\n * behaviour is unchanged - replacing is deliberate and the same in Patter -\n * this only makes it observable, because the case it catches is a host\n * calling `openFlow` straight after `loadGame` to \"re-take\" its handle and\n * silently discarding the hand the save just restored (`getFlow` is the\n * call). Zero cost when unset; leave it unset in shipped games.\n */\n onReplacedFlow?: (id: string, dealt: number) => void;\n}\n\nexport interface OpenFlowOptions {\n /** Seed for this flow's PRNG (defaults to the engine's `seed`). */\n seed?: number;\n /**\n * Open this flow AS IT WAS: a blob from `saveFlow`, applied to the freshly\n * opened (or replaced) flow before the handle comes back\n * (design/engine-server.md 4.1).\n *\n * An option on `openFlow` rather than a `Flow.restore` verb on purpose:\n * restoring INTO a running flow is the trap hosts keep falling into\n * (openFlow REPLACES), and \"open this flow as it was\" is one act. Drift is\n * tolerated exactly as `loadGame` tolerates it, with one addition, because\n * this restore lands in a LIVE engine: a shared card whose world copies are\n * all held by the OTHER open flows is not put back, and is reported as\n * `claimed-elsewhere`. Ask `previewFlowRestore` first to see that coming.\n */\n restore?: FlowSave;\n /** Handed the `restore`'s LoadReport as it happens - the same report\n * `previewFlowRestore` returns for the same blob. Ignored without\n * `restore`; the report has nowhere else to go, since `openFlow` returns\n * the handle. */\n onRestoreReport?: (report: LoadReport) => void;\n}\n\n/** A card view in a dealt hand or a peeked list. Carries NO outcome\n * availability - ask `outcomes()` for current truth (schema 5). */\nexport interface DealtCard {\n id: string;\n gameId: string;\n title?: string;\n purpose?: string;\n fields?: Record<string, ScalarValue>;\n}\n\nexport interface OutcomeView {\n id: string;\n gameId: string;\n title?: string;\n purpose?: string;\n /** The outcome's fields, exactly as the bundle carries them: game data\n * declared by the box's `outcomeFields`, never read by the engine. */\n fields?: Record<string, ScalarValue>;\n /** Evaluated against CURRENT state at the moment of the ask. */\n available: boolean;\n}\n\n/** What a peek returns: the top of the stock, looked at and put back.\n * The engine has no pick policy (Reboot 2.1). */\nexport interface RankedList {\n box: string;\n cards: DealtCard[];\n}\n\nexport interface PlayOptions {\n /** Turn advance override; default settings.playAdvancesTurns, or 0 when the\n * card's box is timed (design/engine-server.md 4.8). */\n advanceTurns?: number;\n}\n\n// --- the trace (schema 5): the deal/play log for tooling ----------------------\n\n/** Why a card did or did not make an ask, in availability order (schema 3.1). */\nexport type TraceVerdict =\n | \"dealt\" // in the hand / the returned list\n | \"capped\" // eligible, ranked below the size cap\n | \"cooldown\" // schema 3.1 step 1\n | \"deck-gate\" // step 2\n | \"tags\" // step 3 (incl. the home group's inverted default)\n | \"condition\" // steps 4-5 (a failing or erroring condition)\n | \"priority\" // a priority expression errored or was not a number\n | \"claimed\" // step 6: no free copy on YOUR board\n | \"claimed-elsewhere\" // step 6: another flow holds the world's copies\n | \"taken\"; // a shared redraw:never was spent, by anyone, for everyone\n\n/** One event on the deal/play log - \"why did Ambush at the ford get dealt\n * here?\" is answered by the ask event's per-card verdicts and keys. The\n * verb is the event type, so a peek is distinguishable from a deal when\n * reading a run back.\n *\n * IDENTITY IS BY GAMEID throughout (design/engine-server.md 4.4). It was\n * mixed until then: `deal.hand` and `peek.box` were gameIds while\n * `evict.hand`, `play.card` and every `cards[].id` were internal ids, so\n * every consumer outside the engine - the Board, the four examiners, the\n * Live Link, a wire a kiosk reads - mapped one to the other itself. */\nexport type TraceEvent =\n | {\n type: \"deal\";\n /** Hand gameId. */\n hand: string;\n /** `id` is the card's GAMEID (design/engine-server.md 4.4). */\n cards: { id: string; verdict: TraceVerdict; priority?: number; specificity?: number }[];\n }\n | {\n type: \"peek\";\n /** Box gameId. */\n box: string;\n criteria: Record<string, string>;\n /** `id` is the card's GAMEID (design/engine-server.md 4.4). */\n cards: { id: string; verdict: TraceVerdict; priority?: number; specificity?: number }[];\n }\n /** Hand and card gameIds. A card the build no longer has (`vanished`) has\n * no gameId left and is named by the id the board carried. */\n | { type: \"evict\"; hand: string; card: string; reason: TraceVerdict | \"hand-condition\" | \"vanished\" }\n /** Card and outcome gameIds; `outcome` is \"\" for a card with no outcomes,\n * played with none. */\n | { type: \"play\"; card: string; outcome: string; turn: number }\n /** One landed outcome change; `path` is the resolved store location, in the\n * address grammar `getProperty` takes - the owner segment is its gameId (a\n * routed @hand write shows where it actually went, schema 3.6). `prev`\n * is the value it replaced, so a log can read \"0 -> 1\". */\n | { type: \"write\"; target: string; path: string; value: ScalarValue; prev?: ScalarValue }\n /** An explicit clock advance via advanceTurns (schema 3.4); `turn` is the\n * box's new value. Plays stamp their own turn on the play event. */\n | { type: \"turns\"; box: string; turn: number }\n /** An expression eval error: never a silent pass (schema 3.1), always a\n * visible diagnostic. */\n | { type: \"diagnostic\"; where: string; message: string };\n\nexport type TraceHandler = (event: TraceEvent) => void;\n/** The engine-level tap: every flow's events, tagged with the flow id -\n * the tools' one stream. */\nexport type EngineTraceHandler = (flow: string, event: TraceEvent) => void;\n\n/** A retained log entry: the trace event plus its place in flow time.\n * `seq` orders the whole flow (monotonic; survives clearLog). `turn` is\n * the clock of the box the event happened in when it fired (peek: the box;\n * deal/evict: the hand's box; play and its writes: the played card's box,\n * stamped together with the play's own turn). Diagnostics carry no turn. */\nexport type LogEntry = TraceEvent & { seq: number; turn?: number };\n\n/** One entry on the ENGINE's log: the same event, plus the flow it happened\n * in. A run is several flows over shared state, so \"what happened in this\n * run\" is only answerable in one ordered stream, and only if each line says\n * who. The flow's own log stays flow-local and unchanged. */\nexport type EngineLogEntry = LogEntry & { flow: string };\n\n// --- internals ---------------------------------------------------------------\n\ninterface CardEntry {\n card: Card<Expression>;\n deck: Deck<Expression>;\n box: Box<Expression>;\n}\n\n/** Is this card scarce across flows (design/shared-scarcity.md)? The deck says\n * what the pile is for and the card may override it, the same inheritance a\n * property has with its scope default. Hoist the deck's flag out of a card\n * loop and pass the answer down: the ask runs this per card per deal. */\nconst cardIsShared = (card: Card<Expression>, deckShared: boolean): boolean =>\n card.shared ?? deckShared;\n\n/** How many hands ACROSS EVERY FLOW may hold this at once. Defaults to\n * `copies`, so the common case writes one number and only \"five in the world,\n * one to a customer\" needs both. Meaningless on an unshared card, and the\n * compiler warns when one sets it. */\nconst sharedCap = (card: Card<Expression>): number => card.sharedCopies ?? card.copies ?? 1;\n\ntype HandSource = { kind: \"value\"; id: string } | { kind: \"hand\"; id: string } | { kind: \"criteria\" };\n\n/** The composed @hand for one ask: the read bag, plus where each name\n * routes on write (schema 3.6). */\ninterface HandEnv {\n bag: PropertyBag;\n sources: Map<string, HandSource>;\n /** tag group id -> bound tag id (home included, its \"tag\" a hand id). */\n boundTags: Map<string, string>;\n}\n\n/** One ask, resolved: a deal (hand present, condition from its template or\n * rule) or a peek (criteria only, no condition - schema 3.1). */\ninterface AskDescriptor {\n box: Box<Expression>;\n hand?: Hand<Expression>;\n condition?: Expression;\n /** tag group id -> tag id, everything the ask binds (fixed + chosen +\n * criteria; for deals also home -> the hand's own id). */\n boundTags: Map<string, string>;\n /** Chosen tags / criteria surfaced into @hand by group gameId, the tag's\n * gameId as the value (schema 3.6). */\n askNames: Record<string, string>;\n}\n\n/** The owner label on everything this engine registers: named in a clash\n * error and carried on the registry's examiner rows. */\nconst OWNER = \"Storylet Engine\";\n\n/** Identity: storylets property names are case-significant as authored. */\nconst identity = (n: string): string => n;\n\n/** The registry keys this engine's bags live under. An id is escaped (`%` and\n * `/`) so no two keys can meet. Every runtime writes the same keys: they are\n * in the save. Owners are keyed by INTERNAL id, as the save always was, so a\n * save survives a rename. */\nconst esc = (id: string): string => id.replace(/%/g, \"%25\").replace(/\\//g, \"%2F\");\nconst unesc = (id: string): string => id.replace(/%2F/g, \"/\").replace(/%25/g, \"%\");\nconst sharedKey = (kind: OwnedScope, id: string): string => `storylets/${kind}/${esc(id)}`;\nconst flowPrefix = (flowId: string): string => `storylets/flow/${esc(flowId)}/`;\nconst flowKey = (flowId: string, kind: FlaggedScope, id?: string): string =>\n kind === \"story\" ? `${flowPrefix(flowId)}story` : `${flowPrefix(flowId)}${kind}/${esc(id!)}`;\n\n/** A registry section's values: registry key -> name -> value. */\ntype Sections = Record<string, PropertyBag>;\n\nconst emptyPartitionValues = (): PropsPartition => ({ story: {}, box: {}, deck: {}, hand: {}, value: {} });\n\n/** Sort a registry save's sections back into partitions, for the load walk:\n * the shared ones, each flow's (only the flows the save restores; the rest\n * are dropped), and everything that is not this engine's, passed through. */\nfunction partitionsFromSections(sections: Sections, flowIds: Set<string>): {\n shared: PropsPartition; flows: Map<string, PropsPartition>; rest: Sections;\n} {\n const shared = emptyPartitionValues();\n const flows = new Map<string, PropsPartition>();\n const rest: Sections = {};\n const flowOf = (escaped: string): PropsPartition | undefined => {\n const id = unesc(escaped);\n if (!flowIds.has(id)) return undefined;\n let p = flows.get(id);\n if (!p) { p = emptyPartitionValues(); flows.set(id, p); }\n return p;\n };\n for (const [key, values] of Object.entries(sections)) {\n let m: RegExpExecArray | null;\n if (key === \"story\") shared.story = values;\n else if ((m = /^storylets\\/(box|deck|hand|value)\\/([^/]+)$/.exec(key))) shared[m[1] as OwnedScope][unesc(m[2]!)] = values;\n else if ((m = /^storylets\\/flow\\/([^/]+)\\/story$/.exec(key))) { const p = flowOf(m[1]!); if (p) p.story = values; }\n else if ((m = /^storylets\\/flow\\/([^/]+)\\/(box|deck|hand|value)\\/([^/]+)$/.exec(key))) {\n const p = flowOf(m[1]!); if (p) p[m[2] as OwnedScope][unesc(m[3]!)] = values;\n } else if (!key.startsWith(\"storylets/\")) rest[key] = values;\n }\n return { shared, flows, rest };\n}\n\n/** A cleaned partition as registry sections, keyed the way its bags register.\n * Empty sections are left out: they would load nothing, and a section for a\n * bag that never registers would wait in the registry for ever. */\nfunction sectionsOf(p: PropsPartition, keyOf: (kind: FlaggedScope, id?: string) => string, out: Sections): void {\n if (Object.keys(p.story).length > 0) out[keyOf(\"story\")] = p.story;\n for (const kind of [\"box\", \"deck\", \"hand\", \"value\"] as const) {\n for (const [id, values] of Object.entries(p[kind])) if (Object.keys(values).length > 0) out[keyOf(kind, id)] = values;\n }\n}\n\n// Stores are shared-kernel bags (@wildwinter/scoperegistry, the properties\n// implementer Patter shares): identity normalisation because storylets\n// property names are case-significant as authored.\n// `pathPrefix` carries its own separator, so a bag composes its rows' addresses itself\n// (`story.gold`, `deck.tavern.drawn`) instead of every caller pasting a prefix onto a row.\nconst bagFromDecls = (decls: PropertyDecl[], pathPrefix: string): StateBag =>\n new StateBag(decls, { normalise: (n) => n, pathPrefix });\n\n// Truthiness for a bare condition. Booleans and numbers as you would expect;\n// a string passes when non-empty and a flag list when non-empty, matching\n// JavaScript's own coercion for those two.\n//\n// Until 2026-09-01 this admitted ONLY booleans and numbers, and Patterplay's\n// `truthy` admitted strings and lists as well. That was drift from writing the\n// two engines at different times, not a considered difference: the two share a\n// property registry, so the same value read from the same registry answered a\n// condition differently depending on which engine asked. expr-specificity calls\n// truthiness host-bound, and it is, but \"host-bound\" is licence for a host to\n// choose, not licence for two hosts in one family to disagree by accident.\nfunction conditionPasses(v: ScalarValue): boolean {\n if (typeof v === \"boolean\") return v;\n if (typeof v === \"number\") return v !== 0;\n if (typeof v === \"string\") return v !== \"\";\n return v.length > 0; // string[] (flags)\n}\n\n// PropertyView is gone. It was the shared PropertyRow plus a `path`, and `path` moved onto\n// that row on 2026-09-02 - so the name was a synonym, and a synonym for a shared type is how\n// the two families drifted in the first place: the same row called PropertyView here,\n// ScopePropertyRow next to it, PropertyRow in the kernel. listProperties() returns PropertyRow.\n\n/** One kernel bag with its store path prefix (story / box.<gameId> / deck.<gameId>\n * / hand.<gameId> / value.<gameId>): the state logger's mount surface\n * (design/engine-runtimes.md 3.4 - the logger builds on the PropertyBag\n * audit hook, so it needs the bags themselves, not just their rows).\n * The Engine lists the shared bags, a Flow its own; the @world container\n * is the host's bag and the host mounts it itself. loadGame() replaces\n * every bag, so re-enumerate after a load. */\nexport interface BagMount {\n prefix: string;\n bag: StateBag;\n}\n\n/** One box on the enumeration surface (examiners, hosts): identity plus\n * its clock (per flow). */\nexport interface BoxView {\n id: string;\n gameId: string;\n title?: string;\n turn: number;\n}\n\n/** The sharing default per scope (design/flows.md, the old system's rule):\n * @story is the playthrough family's globals, shared; the narrower scopes\n * are geographic, per-flow, so \"this flow's danger in the docks\" stays\n * expressible. A declaration's `shared` flag overrides. */\nconst SCOPE_DEFAULT_SHARED = { story: true, box: false, deck: false, hand: false, value: false } as const;\ntype FlaggedScope = keyof typeof SCOPE_DEFAULT_SHARED;\n\nconst isShared = (scope: FlaggedScope, d: PropertyDecl): boolean => d.shared ?? SCOPE_DEFAULT_SHARED[scope];\nconst sharedHalf = (scope: FlaggedScope, decls: PropertyDecl[]): PropertyDecl[] =>\n decls.filter((d) => isShared(scope, d));\nconst flowHalf = (scope: FlaggedScope, decls: PropertyDecl[]): PropertyDecl[] =>\n decls.filter((d) => !isShared(scope, d));\n\n/** One side's five declaration lists, keyed by owner id where the scope has\n * owners. The bags are built from these; so is the load report's answer to\n * \"what does this build declare that the save does not carry\". */\ninterface DeclSet {\n story: PropertyDecl[];\n box: Map<string, PropertyDecl[]>;\n deck: Map<string, PropertyDecl[]>;\n hand: Map<string, PropertyDecl[]>;\n value: Map<string, PropertyDecl[]>;\n}\n\n/** The four owned property scopes: the ones whose address carries an owner\n * segment. `story` has no owner and `world` is the host's. */\ntype OwnedScope = \"box\" | \"deck\" | \"hand\" | \"value\";\nconst OWNED_SCOPES = [\"box\", \"deck\", \"hand\", \"value\"] as const;\n\n/** The owner segment of a property address, both ways round\n * (design/engine-server.md 4.4).\n *\n * `gameId` is the segment the ADDRESS uses; `id` is the internal id everything\n * inside the engine is keyed by - the bags, the save envelope, the ladders.\n * Both maps are built in bundle order and a repeated gameId does NOT\n * overwrite the first.\n *\n * Box, deck, hand and card gameIds are unique bundle-wide, so for three of the\n * four scopes the segment is simply the gameId. A TAG's is unique only within\n * its group, and a group's only within its box, so two boxes may each name a\n * tag \"docks\": the value scope's segment is box-qualified,\n * `value.<boxGameId>/<tagGameId>.<name>`, wherever a gameId repeats, and the\n * short form is REFUSED there rather than resolved to the first in bundle\n * order. `valueAddresses` in the model is the one definition of that rule -\n * the Board draws these addresses from the bundle while the engine builds them\n * from this index, and the two have to agree - and `repeated` is what it\n * found, so a refusal can name the candidates.\n *\n * Two GROUPS in one box naming the same tag is the case the box qualifier\n * cannot separate, and it is closing at the source rather than here (question\n * 16, ruled 2026-09-06): the compiler warns that a tag gameId must be unique\n * within its box, and refuses it from the next release. Until then the first\n * in bundle order answers, as it always did.\n */\ninterface OwnerIndex {\n gameId: Map<string, string>; // internal id -> owner segment\n id: Map<string, string>; // owner segment -> internal id (first in bundle order wins)\n repeated: Map<string, string[]>; // an ambiguous short form -> the qualified candidates\n}\n\ntype OwnerIndexes = Record<OwnedScope, OwnerIndex>;\n\nconst emptyOwnerIndexes = (): OwnerIndexes => ({\n box: { gameId: new Map(), id: new Map(), repeated: new Map() },\n deck: { gameId: new Map(), id: new Map(), repeated: new Map() },\n hand: { gameId: new Map(), id: new Map(), repeated: new Map() },\n value: { gameId: new Map(), id: new Map(), repeated: new Map() },\n});\n\nconst indexOwner = (index: OwnerIndex, entity: { id: string; gameId?: string; title?: string }): void => {\n const gameId = effectiveGameId(entity);\n index.gameId.set(entity.id, gameId);\n if (!index.id.has(gameId)) index.id.set(gameId, entity.id);\n};\n\n/** The value scope's index, whole: the segments to print, the segments to\n * accept, and the gameIds that need qualifying. Built from the bundle rather\n * than tag by tag, because whether a tag's own gameId is enough is a question\n * about the OTHER boxes. */\nconst indexValueOwners = (index: OwnerIndex, bundle: Bundle): void => {\n const addresses = valueAddresses(bundle);\n for (const [id, segment] of addresses.print) index.gameId.set(id, segment);\n for (const [segment, id] of addresses.accept) index.id.set(segment, id);\n for (const [gameId, candidates] of addresses.repeated) index.repeated.set(gameId, candidates);\n};\n\n/** One side's five stores (shared on the engine, per-flow on each flow). */\ninterface Partition {\n story: StateBag;\n box: Map<string, StateBag>;\n deck: Map<string, StateBag>;\n hand: Map<string, StateBag>;\n value: Map<string, StateBag>;\n}\n\ntype PartitionKind = keyof Partition;\n\n/** Everything a Flow shares with its Engine: the bundle-derived lookups\n * (immutable), the shared stores (replaced wholesale by loadGame/reset),\n * and the seams. One object, held by both classes - the two are one\n * machine in two lifetimes. */\ninterface Internals {\n bundle: Bundle;\n logCap?: number;\n cardsById: Map<string, CardEntry>;\n cardsByGameId: Map<string, CardEntry>;\n boxesByGameId: Map<string, Box<Expression>>;\n boxesById: Map<string, Box<Expression>>;\n handsById: Map<string, { hand: Hand<Expression>; box: Box<Expression> }>;\n handsByGameId: Map<string, { hand: Hand<Expression>; box: Box<Expression> }>;\n /** The owner segment of a property address, both ways round (4.4). */\n owners: OwnerIndexes;\n templatesById: Map<string, HandTemplate<Expression>>;\n groupsById: Map<string, { group: TagGroup; box: Box<Expression> }>;\n requiredGroups: Set<string>;\n nodeCache: WeakMap<Expression, ExprNode>;\n ladders: {\n world: Map<string, readonly string[]>;\n story: Map<string, readonly string[]>;\n box: Map<string, Map<string, readonly string[]>>;\n deck: Map<string, Map<string, readonly string[]>>;\n value: Map<string, Map<string, readonly string[]>>;\n hand: Map<string, Map<string, readonly string[]>>;\n };\n hasQualities: boolean;\n /** Does ANY deck or card in the bundle opt into shared scarcity? False for\n * the overwhelming majority of projects, and when it is false the two\n * claim-ledger walks in dealing are skipped entirely. Same idea as\n * `hasQualities` above: a bundle that does not use a feature must not pay\n * for it. */\n hasShared: boolean;\n /** The per-flow halves of every declaration list, precomputed once: each\n * new flow builds its bags from these. */\n flowDecls: DeclSet;\n /** The shared halves, the same way. Not used to build anything - the shared\n * bags are built straight from the bundle - but a load report has to say\n * what the shared side WOULD hold without building a bag, which is what\n * makes previewLoad pure. */\n sharedDecls: DeclSet;\n /** The shared stores, registered in the registry for the engine's life.\n * Reseeded in place by reset and by a load that carries values. */\n shared: Partition;\n /** The game's one registry (or the engine's own, when it is standalone). */\n registry: ScopeRegistry;\n /** True when the engine made the registry: `saveGame()` then carries its values. */\n ownsRegistry: boolean;\n /** True when the engine self-backed @world (standalone, no resolver bound). */\n selfWorld: boolean;\n /** Every OTHER scope in the registry, as an eval context sees it (instance\n * keys left out), rebuilt only when the registry's set of scopes moves. */\n registryView: () => { scopes: EvalContext[\"scopes\"]; qualities: EvalContext[\"qualities\"] };\n /** @world, read through the registry by name (the scope's own normalisation),\n * so a @world the game registered folded to lower case still answers the\n * names as authored. */\n worldResolver: ScopeResolver;\n /** The @world WRITE seam. `host` says the caller is the GAME's own surface -\n * setProperty, the coverage harness, the CLI's --set - which the shared\n * kernel lets past a `writable: false` (scoperegistry 0.6.0): that flag is\n * the story's promise, not the game's. The story's refusal is the\n * worldReadOnly table below, consulted before this seam is reached. A BOUND\n * resolver is opaque - it takes a name and a value and keeps whatever rule\n * the game has - so the flag only ever reaches the self-backed bag.\n * Undefined when @world cannot be written at all (a resolver bound with no\n * `set`). */\n worldSet?: (name: string, value: ScalarValue, host?: boolean) => void;\n /** @world names declared `writable: false`: the story's promise, kept at\n * runtime as the compiler keeps it at publish (Reboot.md 10). */\n worldReadOnly: Set<string>;\n /** `turn` is the box clock the event happened on, where the caller knows it\n * - the same stamp the flow's own log carries. Unity and Unreal passed it\n * from the start; JS and Godot dropped it, so their examiners printed \"[-]\"\n * on every deal, peek, evict and write line while the other two printed the\n * real turn. Four runtimes, two different run logs (2026-08-29). */\n emitEngine: (flow: string, event: TraceEvent, turn?: number) => void;\n engineTracing: () => boolean;\n}\n\nconst handDeclsOf = (internals: Internals, hand: Hand<Expression>): PropertyDecl[] => {\n if (hand.template !== undefined) {\n return internals.templatesById.get(hand.template)?.properties\n ?? internals.bundle.boxes.flatMap((b) => b.handTemplates).find((t) => t.id === hand.template)?.properties\n ?? [];\n }\n return hand.properties ?? [];\n};\n\n/**\n * One owned property's ADDRESS, owner segment and all: `box.village.mood`.\n *\n * The stores, the save envelope and the ladders stay keyed by internal id -\n * a save must survive a rename, which is the whole reason ids exist - so this\n * is the one place the two vocabularies meet, and it is a formatter, never a\n * lookup key. An owner the build no longer has (a save that outlived an edit)\n * keeps the id it arrived with: there is no gameId left to give it, which is\n * the rule a load report's evictions have always used.\n */\nconst addressOf = (internals: Internals, kind: OwnedScope, id: string): string =>\n `${kind}.${internals.owners[kind].gameId.get(id) ?? id}`;\n\n/**\n * Resolve a property address's owner segment to the internal id the stores are\n * keyed by. `legacy` says the caller used the pre-4.4 form - an internal id\n * where a gameId belongs - which resolves for THIS release and earns a\n * diagnostic; the next lockstep release refuses it, in every scope including\n * `value`, which had the one reprieve until it gained an address of its own.\n * `ambiguous` is a short-form value address two boxes answer to: the caller\n * REFUSES it, listing those candidates. Undefined when the segment names no\n * owner at all, which is the caller's \"no <kind> store\" error.\n */\ntype OwnerLookup = { id: string; legacy: boolean } | { ambiguous: string[] };\n\nconst resolveOwner = (internals: Internals, kind: OwnedScope, segment: string): OwnerLookup | undefined => {\n // Checked before the lookup, because the short form is deliberately NOT in\n // the accept map when it is ambiguous: silently picking the first tag in\n // bundle order is the bug this removes.\n const candidates = internals.owners[kind].repeated.get(segment);\n if (candidates !== undefined) return { ambiguous: candidates };\n const byGameId = internals.owners[kind].id.get(segment);\n if (byGameId !== undefined) return { id: byGameId, legacy: false };\n // A gameId that equals its id took the branch above, so anything reaching\n // here and known as an id is genuinely the old spelling.\n if (internals.owners[kind].gameId.has(segment)) return { id: segment, legacy: true };\n return undefined;\n};\n\n/** Resolve or throw: the two refusals every property address shares, in one\n * place, so the engine's surface and a flow's answer alike. */\nconst ownerOrThrow = (internals: Internals, kind: OwnedScope, segment: string, name: string): { id: string; legacy: boolean } => {\n const owner = resolveOwner(internals, kind, segment);\n if (owner === undefined) throw new Error(`no ${kind} store \"${segment}\"`);\n if (\"ambiguous\" in owner) throw new Error(ambiguousValueAddressMessage(segment, name, owner.ambiguous));\n return owner;\n};\n\n/** What a legacy address is told. It NAMES the address to move to, because\n * \"that form is deprecated\" without the replacement leaves a host grepping a\n * bundle for ids it never chose. */\nconst legacyAddressMessage = (internals: Internals, kind: OwnedScope, segment: string, name: string): string =>\n `\"${kind}.${segment}.${name}\" names the ${kind} by its internal id; write \"${addressOf(internals, kind, segment)}.${name}\". `\n + `The internal-id form is refused after the next release.`;\n\n/** Build one side of the partition from the bundle. The bags are KEYED by\n * internal id and ADDRESSED by gameId; see addressOf. */\nconst buildPartition = (internals: Internals, half: (scope: FlaggedScope, decls: PropertyDecl[]) => PropertyDecl[]): Partition => {\n const b = internals.bundle;\n const at = (kind: OwnedScope, id: string): string => `${addressOf(internals, kind, id)}.`;\n return {\n story: bagFromDecls(half(\"story\", b.story.properties), \"story.\"),\n box: new Map(b.boxes.map((box) => [box.id, bagFromDecls(half(\"box\", box.properties), at(\"box\", box.id))])),\n deck: new Map(b.boxes.flatMap((box) => box.decks.map(\n (deck): [string, StateBag] => [deck.id, bagFromDecls(half(\"deck\", deck.properties), at(\"deck\", deck.id))]))),\n // A template instance inherits the template's property declarations;\n // a standalone hand declares its own (schema 2.6).\n hand: new Map(b.boxes.flatMap((box) => box.hands.map(\n (hand): [string, StateBag] => [hand.id, bagFromDecls(half(\"hand\", handDeclsOf(internals, hand)), at(\"hand\", hand.id))]))),\n value: new Map(b.boxes.flatMap((box) => box.tagGroups.flatMap((group) => group.tags.map(\n (tag): [string, StateBag] => [tag.id, bagFromDecls(half(\"value\", tag.properties ?? []), at(\"value\", tag.id))])))),\n };\n};\n\nconst partitionValues = (p: Partition): PropsPartition => ({\n story: p.story.values,\n box: Object.fromEntries([...p.box].map(([id, bag]) => [id, bag.values])),\n deck: Object.fromEntries([...p.deck].map(([id, bag]) => [id, bag.values])),\n hand: Object.fromEntries([...p.hand].map(([id, bag]) => [id, bag.values])),\n value: Object.fromEntries([...p.value].map(([id, bag]) => [id, bag.values])),\n});\n\nconst loadPartition = (p: Partition, values: PropsPartition | undefined): void => {\n // Fresh defaults are already in the bags; the saved values land over\n // them: orphaned keys (deleted entities, re-flagged properties) drop;\n // newly declared properties keep defaults.\n p.story.load(values?.story ?? {});\n for (const kind of [\"box\", \"deck\", \"hand\", \"value\"] as const) {\n for (const [id, bag] of Object.entries(values?.[kind] ?? {})) {\n p[kind].get(id)?.load(bag);\n }\n }\n};\n\n// --- the load report (design/engine-server.md 4.9) ---------------------------\n//\n// One walk, two entry points. `previewLoad` runs it and returns the report;\n// `loadGame` runs it, returns the same report and then applies the CLEANED\n// blob the walk produced. Two implementations of \"what does this save cost\"\n// would drift the first time one of them was fixed, so there is one, and the\n// apply half consumes its output rather than repeating its decisions.\n\n/** The report under construction: unsorted, until finishReport orders it. */\ninterface ReportDraft {\n evicted: LoadEviction[];\n droppedCooldowns: { flow: string; card: string }[];\n droppedSpent: string[];\n droppedProperties: LoadProperty[];\n defaultedProperties: LoadProperty[];\n retypedProperties: LoadProperty[];\n}\n\nconst emptyDraft = (): ReportDraft => ({\n evicted: [], droppedCooldowns: [], droppedSpent: [],\n droppedProperties: [], defaultedProperties: [], retypedProperties: [],\n});\n\n/** The sort key separator: a UNIT SEPARATOR, as the play-history indexes use,\n * because it cannot occur in an id, a gameId or a property name. */\nconst SORT_SEP = \"\\u001f\";\n\nconst byKey = <T>(items: T[], key: (item: T) => string): T[] =>\n [...items].map((item) => ({ item, k: key(item) }))\n .sort((a, b) => (a.k < b.k ? -1 : a.k > b.k ? 1 : 0))\n .map((e) => e.item);\n\nconst propKey = (p: LoadProperty): string => `${p.flow ?? \"\"}${SORT_SEP}${p.path}`;\n\n/**\n * Does a saved value still fit its declaration?\n *\n * The type first, then the declaration's own vocabulary: an enum value or a\n * quality stage the edit struck out is still a string of the right type and\n * still no longer a legal value, and a condition comparing against the ladder\n * would answer nonsense about it. A declaration with no vocabulary (`values` /\n * `stages` absent) constrains nothing, so anything of the right type fits.\n */\nfunction valueFits(decl: PropertyDecl, value: ScalarValue): boolean {\n switch (decl.type) {\n case \"boolean\": return typeof value === \"boolean\";\n case \"number\": return typeof value === \"number\";\n case \"string\": return typeof value === \"string\";\n case \"enum\":\n return typeof value === \"string\" && (decl.values === undefined || decl.values.includes(value));\n case \"quality\":\n return typeof value === \"string\" && (decl.stages === undefined || decl.stages.includes(value));\n case \"flags\":\n return Array.isArray(value) && (decl.values === undefined || value.every((f) => decl.values!.includes(f)));\n default: return true;\n }\n}\n\n/** Walk one bag's worth of saved values against one bag's worth of\n * declarations: report the orphans, the newcomers and the misfits, and\n * return the values that survive. */\nfunction walkScope(\n decls: PropertyDecl[] | undefined,\n saved: PropertyBag | undefined,\n path: (name: string) => string,\n flow: string | undefined,\n draft: ReportDraft,\n): PropertyBag {\n const at = (name: string): LoadProperty =>\n ({ ...(flow !== undefined ? { flow } : {}), path: path(name) });\n const byName = new Map((decls ?? []).map((d) => [d.name, d]));\n const values = saved ?? {};\n const clean: PropertyBag = {};\n for (const [name, value] of Object.entries(values)) {\n const decl = byName.get(name);\n if (decl === undefined) { draft.droppedProperties.push(at(name)); continue; }\n if (!valueFits(decl, value)) { draft.retypedProperties.push(at(name)); continue; }\n clean[name] = value;\n }\n for (const decl of decls ?? []) {\n if (!(decl.name in values)) draft.defaultedProperties.push(at(decl.name));\n }\n return clean;\n}\n\n/** The same walk over all five scopes of one partition. An owner the save\n * carries and the build no longer has drops whole (its bag is gone, so its\n * values have nowhere to land); an owner the build has and the save lacks\n * keeps every default. */\nfunction walkPartition(\n internals: Internals,\n decls: DeclSet,\n values: PropsPartition | undefined,\n flow: string | undefined,\n draft: ReportDraft,\n): PropsPartition {\n const out: PropsPartition = {\n story: walkScope(decls.story, values?.story, (n) => `story.${n}`, flow, draft),\n box: {}, deck: {}, hand: {}, value: {},\n };\n for (const kind of [\"box\", \"deck\", \"hand\", \"value\"] as const) {\n const savedKind = values?.[kind] ?? {};\n const ids = [...new Set([...decls[kind].keys(), ...Object.keys(savedKind)])].sort();\n for (const id of ids) {\n // The report's `path` is exactly what listProperties() prints and what\n // setProperty takes: one grammar, so an operator reading a hot-swap\n // report can paste the address straight back in (4.4).\n const owner = addressOf(internals, kind, id);\n out[kind][id] = walkScope(decls[kind].get(id), savedKind[id],\n (n) => `${owner}.${n}`, flow, draft);\n }\n }\n return out;\n}\n\n/** Order the draft and answer the identity questions. `saved` is the content\n * block the save carries; for a single-flow restore there is none, so the\n * caller passes the bundle's own and no drift is reported. */\nfunction finishReport(bundle: BundleContent, saved: BundleContent, flows: string[], draft: ReportDraft): LoadReport {\n const drift = saved.version !== bundle.version || saved.hash !== bundle.hash;\n const evicted = byKey(draft.evicted, (e) => [e.flow, e.hand, e.card, e.reason].join(SORT_SEP));\n const droppedCooldowns = byKey(draft.droppedCooldowns, (c) => `${c.flow}${SORT_SEP}${c.card}`);\n const droppedSpent = [...draft.droppedSpent].sort();\n const droppedProperties = byKey(draft.droppedProperties, propKey);\n const defaultedProperties = byKey(draft.defaultedProperties, propKey);\n const retypedProperties = byKey(draft.retypedProperties, propKey);\n return {\n // `flows` is what the load restores, not something it had to change, so\n // it never makes a report inexact.\n exact: !drift && evicted.length === 0 && droppedCooldowns.length === 0 && droppedSpent.length === 0\n && droppedProperties.length === 0 && defaultedProperties.length === 0 && retypedProperties.length === 0,\n project: bundle.project,\n version: { saved: saved.version, bundle: bundle.version },\n hash: { saved: saved.hash, bundle: bundle.hash },\n flows,\n evicted, droppedCooldowns, droppedSpent,\n droppedProperties, defaultedProperties, retypedProperties,\n };\n}\n\n// --- the Engine ---------------------------------------------------------------\n\nexport class Engine {\n private readonly internals: Internals;\n private readonly seed: number;\n private readonly onReplacedFlow: EngineOptions[\"onReplacedFlow\"];\n private readonly flowsById = new Map<string, Flow>();\n private readonly engineTraceHandlers = new Set<EngineTraceHandler>();\n /** The host's @world binding, if the engine was built with one: it\n * outlives reset/loadGame (the host's container is the host's). The\n * self-backed resolver is rebuilt instead. */\n private readonly hostWorld?: ScopeResolver;\n\n /** The options this engine was built with: hotSwap builds its replacement from them. */\n private readonly creationOptions: EngineOptions;\n /** How to register each shared scope again, in registration order: a failed\n * hotSwap puts this engine back exactly as it was. */\n private readonly sharedMounts: Array<{ key: string; mount: () => void }> = [];\n\n constructor(bundle: Bundle, opts: EngineOptions = {}) {\n this.creationOptions = opts;\n this.seed = opts.seed ?? 0;\n this.onReplacedFlow = opts.onReplacedFlow;\n if (opts.world !== undefined) this.hostWorld = opts.world;\n const internals: Internals = {\n bundle,\n ...(opts.log ? { logCap: typeof opts.log === \"object\" ? (opts.log.cap ?? 1000) : 1000 } : {}),\n cardsById: new Map(), cardsByGameId: new Map(),\n boxesByGameId: new Map(), boxesById: new Map(),\n handsById: new Map(), handsByGameId: new Map(),\n owners: emptyOwnerIndexes(),\n templatesById: new Map(), groupsById: new Map(),\n requiredGroups: new Set(),\n nodeCache: new WeakMap(),\n ladders: { world: new Map(), story: new Map(), box: new Map(), deck: new Map(), value: new Map(), hand: new Map() },\n hasQualities: false,\n hasShared: false,\n flowDecls: { story: [], box: new Map(), deck: new Map(), hand: new Map(), value: new Map() },\n sharedDecls: { story: [], box: new Map(), deck: new Map(), hand: new Map(), value: new Map() },\n shared: undefined as unknown as Partition,\n registry: opts.registry ?? new ScopeRegistry(),\n ownsRegistry: opts.registry === undefined,\n selfWorld: false,\n registryView: () => view(),\n worldResolver: undefined as unknown as ScopeResolver,\n worldReadOnly: new Set<string>(),\n emitEngine: (flow, event, turn) => {\n if (this.internals.logCap !== undefined) {\n this.engineLog.push({ ...event, flow, seq: this.engineSeq++, ...(turn !== undefined ? { turn } : {}) });\n if (this.engineLog.length > this.internals.logCap) {\n this.engineLog.splice(0, this.engineLog.length - this.internals.logCap);\n }\n }\n for (const h of this.engineTraceHandlers) h(flow, event);\n },\n engineTracing: () => this.engineTraceHandlers.size > 0,\n };\n this.internals = internals;\n let viewRevision = -1;\n let viewCache: ReturnType<Internals[\"registryView\"]> = { scopes: {}, qualities: undefined };\n const view = (): ReturnType<Internals[\"registryView\"]> => {\n const reg = internals.registry;\n if (reg.revision !== viewRevision) {\n const ctx = reg.toEvalContext();\n const scopes: EvalContext[\"scopes\"] = {};\n // An instance key (`storylets/deck/x`, another engine's) is no expression token.\n for (const [k, v] of Object.entries(ctx.scopes)) if (!k.includes(\"/\")) scopes[k] = v;\n viewCache = { scopes, qualities: ctx.qualities };\n viewRevision = reg.revision;\n }\n return viewCache;\n };\n\n // The value scope's segments come off the whole bundle at once (a tag\n // gameId is only unique within its group), so they are built before the\n // walk rather than tag by tag inside it.\n indexValueOwners(internals.owners.value, bundle);\n\n for (const box of bundle.boxes) {\n internals.boxesById.set(box.id, box);\n internals.boxesByGameId.set(effectiveGameId(box), box);\n indexOwner(internals.owners.box, box);\n for (const group of box.tagGroups) {\n internals.groupsById.set(group.id, { group, box });\n if (group.required === true) internals.requiredGroups.add(group.id);\n }\n for (const deck of box.decks) {\n indexOwner(internals.owners.deck, deck);\n if (deck.shared === true) internals.hasShared = true;\n for (const card of deck.cards) {\n const entry = { card, deck, box };\n internals.cardsById.set(card.id, entry);\n internals.cardsByGameId.set(effectiveGameId(card), entry);\n if (card.shared === true) internals.hasShared = true;\n }\n }\n for (const template of box.handTemplates) {\n internals.templatesById.set(template.id, template);\n }\n for (const hand of box.hands) {\n internals.handsById.set(hand.id, { hand, box });\n internals.handsByGameId.set(effectiveGameId(hand), { hand, box });\n indexOwner(internals.owners.hand, hand);\n }\n }\n this.initLadders();\n\n // Both halves, precomputed once (a bundle's declarations never change):\n // each openFlow builds its bags from the per-flow half, and a load report\n // asks either half what it declares without building anything at all.\n const declSet = (half: (scope: FlaggedScope, decls: PropertyDecl[]) => PropertyDecl[]): DeclSet => ({\n story: half(\"story\", bundle.story.properties),\n box: new Map(bundle.boxes.map((box) => [box.id, half(\"box\", box.properties)])),\n deck: new Map(bundle.boxes.flatMap((box) => box.decks.map(\n (deck): [string, PropertyDecl[]] => [deck.id, half(\"deck\", deck.properties)]))),\n hand: new Map(bundle.boxes.flatMap((box) => box.hands.map(\n (hand): [string, PropertyDecl[]] => [hand.id, half(\"hand\", handDeclsOf(internals, hand))]))),\n value: new Map(bundle.boxes.flatMap((box) => box.tagGroups.flatMap((group) => group.tags.map(\n (tag): [string, PropertyDecl[]] => [tag.id, half(\"value\", tag.properties ?? [])])))),\n });\n internals.flowDecls = declSet(flowHalf);\n internals.sharedDecls = declSet(sharedHalf);\n\n this.initShared(this.hostWorld);\n }\n\n /** Build the shared stores, register them and @world, and set up the @world\n * seam. Once, for the engine's life: reset and loads reseed the bags in\n * place, so the registry never sees them come and go. */\n private initShared(hostWorld?: ScopeResolver): void {\n const internals = this.internals;\n const reg = internals.registry;\n const worldDecls = internals.bundle.world.properties as unknown as ScopeDeclaration[];\n internals.shared = buildPartition(internals, sharedHalf);\n internals.worldReadOnly = new Set(internals.bundle.world.properties.filter((d) => d.writable === false).map((d) => d.name));\n const registered: string[] = [];\n // Register now, and remember how, so a failed hotSwap can register again.\n const mount = (key: string, register: () => void): void => {\n register();\n registered.push(key);\n this.sharedMounts.push({ key, mount: register });\n };\n try {\n // `story` is this engine's token whether or not the bundle declares a shared\n // @story property: registering it is what makes a clash show at once.\n const story = internals.shared.story;\n mount(\"story\", () => { reg.mountOwned(\"story\", story, { owner: OWNER }); }); // claims values the game loaded first\n for (const kind of OWNED_SCOPES) {\n for (const [id, bag] of internals.shared[kind]) {\n if (bag.declarations().length === 0) continue; // holds nothing: not registered\n mount(sharedKey(kind, id), () => { reg.mountOwned(sharedKey(kind, id), bag, { owner: OWNER }); });\n }\n }\n if (hostWorld !== undefined) {\n // The game keeps these values: an external scope, never saved.\n mount(\"world\", () => { reg.defineForeign(\"world\", hostWorld, worldDecls, { normalise: identity, owner: OWNER }); });\n } else if (internals.ownsRegistry && !reg.has(\"world\")) {\n // Standalone: self-backed from the declared defaults, DECLARATIONS AND\n // ALL, as a property the registry stores and SAVES (only a resolver the\n // game binds is external). The bag keeps `writable: false` so an\n // examiner still reads it there, and the kernel lets a `{ host: true }`\n // write past it, which is what the game's own surface passes.\n reg.defineOwned(\"world\", worldDecls, { normalise: identity, pathPrefix: \"world.\", owner: OWNER });\n const worldBag = reg.ownedBag(\"world\");\n registered.push(\"world\");\n this.sharedMounts.push({ key: \"world\", mount: () => { reg.mountOwned(\"world\", worldBag, { owner: OWNER }); } });\n internals.selfWorld = true;\n }\n // Given the game's registry and no resolver, @world is the game's to\n // register: this engine registers nothing for it.\n } catch (e) {\n for (const k of registered) reg.remove(k, { keep: true }); // a clash leaves the game's registry as it was\n throw e;\n }\n internals.worldResolver = {\n get: (n) => reg.get(\"world\", n),\n set: (n, v) => { reg.set(\"world\", n, v); },\n };\n if (hostWorld !== undefined) {\n // A bound resolver is opaque: it keeps whatever rule the game has, so the\n // story's `writable: false` is kept by worldReadOnly before this seam.\n internals.worldSet = hostWorld.set !== undefined ? (n, v): void => { reg.set(\"world\", n, v, { host: true }); } : undefined;\n } else {\n internals.worldSet = (n, v, host): void => { reg.set(\"world\", n, v, host === true ? { host: true } : undefined); };\n }\n }\n\n /** Every shared bag back to its declared defaults, in place (the registry\n * keeps them registered), the self-backed @world included. */\n private reseedShared(): void {\n const { shared, sharedDecls, registry } = this.internals;\n shared.story.reseed(sharedDecls.story as unknown as ScopeDeclaration[]);\n for (const kind of OWNED_SCOPES) {\n for (const [id, bag] of shared[kind]) bag.reseed((sharedDecls[kind].get(id) ?? []) as unknown as ScopeDeclaration[]);\n }\n if (this.internals.selfWorld) {\n registry.reseedOwned(\"world\", this.internals.bundle.world.properties as unknown as ScopeDeclaration[]);\n }\n }\n\n /** Quality ladders by scope for the eval channel (design/quality.md):\n * world/story keyed by name; box/deck/value keyed by owner id then name.\n * Built once - a bundle's declarations never change. Ladders are\n * declaration-level, so the sharing flag does not touch them. */\n private initLadders(): void {\n const internals = this.internals;\n const grab = (decls: PropertyDecl[] | undefined): Map<string, readonly string[]> => {\n const m = new Map<string, readonly string[]>();\n for (const d of decls ?? []) if (d.type === \"quality\" && d.stages !== undefined) m.set(d.name, d.stages);\n return m;\n };\n const b = internals.bundle;\n internals.ladders.world = grab(b.world.properties);\n internals.ladders.story = grab(b.story.properties);\n for (const box of b.boxes) {\n internals.ladders.box.set(box.id, grab(box.properties));\n for (const deck of box.decks) internals.ladders.deck.set(deck.id, grab(deck.properties));\n for (const group of box.tagGroups) {\n for (const tag of group.tags) internals.ladders.value.set(tag.id, grab(tag.properties));\n }\n for (const hand of box.hands) internals.ladders.hand.set(hand.id, grab(handDeclsOf(internals, hand)));\n }\n const any = (m: Map<string, Map<string, readonly string[]>>): boolean =>\n [...m.values()].some((x) => x.size > 0);\n internals.hasQualities = internals.ladders.world.size > 0 || internals.ladders.story.size > 0\n || any(internals.ladders.box) || any(internals.ladders.deck)\n || any(internals.ladders.value) || any(internals.ladders.hand);\n }\n\n // --- flow management (Patter's surface, name for name) ----------------------\n\n /** Open (or REPLACE) the named flow. An existing id's flow is closed\n * first - re-opening a name is a reset of that name's whole per-flow\n * state; shared state is untouched. There is no default flow: \"main\" is\n * a caller convention, not an engine rule. */\n openFlow(id: string, opts: OpenFlowOptions = {}): Flow {\n return this.open(id, opts, false);\n }\n\n /** openFlow, and loadGame's rebuild. `claim` says the new flow's bags take\n * the values the registry holds for them (a load); a fresh open is a reset\n * of that name, so anything waiting for it is discarded first. */\n private open(id: string, opts: OpenFlowOptions, claim: boolean): Flow {\n this.assertExternalScopes();\n // The world's claims as they stand WITHOUT this name, taken before the\n // replace: a resume competes with the other flows, never with the flow it\n // is replacing (which is about to release everything it holds).\n const otherClaims = opts.restore !== undefined ? this.sharedClaimsExcept(id) : undefined;\n // Replacing an existing id KEEPS its place in the order. `close()` would\n // drop the key, and a JS Map re-inserts a deleted key at the END, so\n // openFlow(\"a\"); openFlow(\"b\"); openFlow(\"a\") listed [b, a] here and\n // [a, b] on all three ports - a different `flows()` order and, since\n // `saveGame` keys its flows in that order, a different `.storyletsave`\n // byte stream for the same run (2026-08-29). markClosed without dropFlow\n // is the difference: the old handle goes inert, the slot stays put.\n const existing = this.flowsById.get(id);\n if (existing) {\n // Say so BEFORE the old flow goes inert, while its board is still readable.\n const dealt = existing.heldCardIds().length;\n if (dealt > 0) this.onReplacedFlow?.(id, dealt);\n existing.markClosed();\n }\n if (!claim) this.internals.registry.discardParked(flowPrefix(id));\n const flow = new Flow(this, this.internals, id, opts.seed ?? this.seed);\n this.flowsById.set(id, flow);\n if (opts.restore !== undefined) {\n const draft = emptyDraft();\n // Cloned: a caller holding one blob may resume two flows from it, and\n // an aliased playLog would then grow in both.\n const clean = this.planFlowRestore(id, structuredClone(opts.restore), otherClaims, draft);\n flow.restore(clean);\n const content = this.internals.bundle.content;\n opts.onRestoreReport?.(finishReport(content, content, [id], draft));\n }\n return flow;\n }\n\n getFlow(id: string): Flow | undefined {\n return this.flowsById.get(id);\n }\n\n /** Every live flow, open order. */\n flows(): Flow[] {\n return [...this.flowsById.values()];\n }\n\n /** Close the named flow: its handle goes INERT (every verb throws). A\n * dropped-but-held flow must not keep writing shared state (Patter's\n * stale-handle lesson). Unknown ids are a quiet no-op, like closing a\n * closed door. */\n closeFlow(id: string): void {\n const flow = this.flowsById.get(id);\n if (!flow) return;\n this.flowsById.delete(id);\n flow.markClosed();\n }\n\n /** @internal - Flow.close() routes here so both doors agree. */\n dropFlow(id: string, flow: Flow): void {\n if (this.flowsById.get(id) === flow) this.flowsById.delete(id);\n }\n\n /** Close every flow and reseed the shared state to its defaults (the\n * self-backed @world included; a host-bound @world is the host's and is\n * not touched). */\n reset(): void {\n this.dropRun(false);\n this.reseedShared();\n // Values loaded for bags nobody has claimed yet are the old run's too: a\n // flow opened after the reset must not pick them up. Other engines' stay.\n this.internals.registry.discardParked(\"storylets/\");\n }\n\n /** End the run: clear the log, close every flow, forget spent cards. Each\n * flow's bags leave the registry; `keepFlows` names the flows whose values\n * are kept there for the flow that replaces them (a load into the game's\n * registry). */\n private dropRun(keepFlows: Set<string> | false): void {\n // The log is a run-lifetime utility and is not saved; a reset is a new run.\n // All three ports cleared it here and the reference did not, so `reset()`\n // (and `loadGame`) left the previous run's entries in place with `seq`\n // continuing across the boundary - while the same call on Godot, Unity or\n // Unreal returned an empty log (2026-08-29).\n this.engineLog = [];\n for (const [id, flow] of this.flowsById) {\n flow.releaseBags(keepFlows !== false && keepFlows.has(id));\n flow.markClosed();\n }\n this.flowsById.clear();\n this.spent.clear();\n }\n\n // --- shared scarcity (design/shared-scarcity.md) -----------------------------\n\n /** Cards a shared `redraw: \"never\"` has taken out of the world, by card id.\n * The claim ledger is DERIVED from live boards and so needs no storage;\n * this one is durable, so it rides the save's shared half. */\n private spent = new Set<string>();\n\n /** @internal */\n isTaken(cardId: string): boolean {\n return this.spent.has(cardId);\n }\n\n /** @internal */\n markTaken(cardId: string): void {\n this.spent.add(cardId);\n }\n\n // --- the run's log (design/shared-scarcity.md 8.2) ---------------------------\n\n /** Every flow's events in one ordered stream, each tagged with its flow.\n * Opt in with the same `log` option the flow logs use; capped the same way.\n *\n * This exists because a flow's own log cannot answer the question a run\n * raises: when a story action in ANOTHER flow moves shared state, your\n * flow's log says nothing and your value simply changes. Reading a run\n * needs one stream that says who did what, and merging the per-flow logs by\n * hand is a thing every host would otherwise have to write. */\n private engineLog: EngineLogEntry[] = [];\n private engineSeq = 0;\n\n log(): readonly EngineLogEntry[] {\n return this.engineLog;\n }\n\n clearLog(): void {\n this.engineLog = [];\n }\n\n /** @internal - shared claims across every LIVE flow, card id -> holders.\n * Derived, which is what makes closeFlow and the openFlow replace release\n * what a flow was holding: its board leaves the map with it. */\n sharedClaims(): Map<string, number> {\n const counts = new Map<string, number>();\n for (const flow of this.flowsById.values()) {\n for (const id of flow.heldCardIds()) counts.set(id, (counts.get(id) ?? 0) + 1);\n }\n return counts;\n }\n\n /** The same ledger with one name left out: what the REST of the world\n * holds, which is the question a resume under that name has to ask. */\n private sharedClaimsExcept(id: string): Map<string, number> {\n const counts = new Map<string, number>();\n for (const [flowId, flow] of this.flowsById) {\n if (flowId === id) continue;\n for (const cardId of flow.heldCardIds()) counts.set(cardId, (counts.get(cardId) ?? 0) + 1);\n }\n return counts;\n }\n\n // --- engine-level state access ----------------------------------------------\n\n /**\n * Read shared state by path: \"world.x\", \"story.gold\" (when shared),\n * \"box.village.heat\" (when shared) - the owner segment is its GAMEID\n * (design/engine-server.md 4.4). A ref that resolves PER-FLOW throws,\n * naming the fix - silently answering with some flow's copy (or a junk\n * default) was the bug Patter's engine.getProperty guard exists to stop.\n */\n getProperty(path: string): ScalarValue {\n const found = this.resolveShared(path);\n const value = found.kind === \"world\" ? this.internals.worldResolver.get(found.name)\n : found.kind === \"scope\" ? this.internals.registry.get(found.token, found.name)\n : found.bag.get(found.name);\n if (value === undefined) throw new Error(`no property at \"${path}\"`);\n return value;\n }\n\n setProperty(path: string, value: ScalarValue): void {\n const found = this.resolveShared(path);\n if (found.kind === \"world\") {\n if (!this.internals.worldSet) {\n throw new Error(`@world is read-only here: the host bound no write`);\n }\n this.internals.worldSet(found.name, value, true);\n return;\n }\n if (found.kind === \"scope\") {\n this.internals.registry.set(found.token, found.name, value, { host: true });\n return;\n }\n // A host write: silent under the firing rule (no subscriber feedback\n // loop), but visible to the bag's audit hook - and a HOST write, so a\n // `writable: false` does not refuse it. That flag is the story's promise\n // about its own outcomes; this is the game speaking, in any scope.\n found.bag.set(found.name, value, { silent: true, reason: \"host setProperty\", host: true });\n }\n\n private resolveShared(path: string):\n | { kind: \"world\"; name: string }\n | { kind: \"scope\"; token: string; name: string }\n | { kind: \"bag\"; bag: StateBag; name: string } {\n const parts = path.split(\".\");\n const perFlow = (): never => {\n throw new Error(`\"${path}\" is per-flow state - read it on a Flow, not the Engine`);\n };\n if (parts.length === 2 && parts[0] === \"world\") return { kind: \"world\", name: parts[1]! };\n // Another engine's game-wide scope (`patter.gold`): every engine reads every scope.\n if (parts.length === 2 && parts[0] !== \"story\" && this.internals.registry.has(parts[0]!)) {\n return { kind: \"scope\", token: parts[0]!, name: parts[1]! };\n }\n if (parts.length === 2 && parts[0] === \"story\") {\n const name = parts[1]!;\n if (this.internals.shared.story.get(name) !== undefined) return { kind: \"bag\", bag: this.internals.shared.story, name };\n if (this.internals.flowDecls.story.some((d) => d.name === name)) perFlow();\n throw new Error(`no property at \"${path}\"`);\n }\n if (parts.length === 3 && (parts[0] === \"box\" || parts[0] === \"deck\" || parts[0] === \"hand\" || parts[0] === \"value\")) {\n const kind = parts[0] as OwnedScope;\n const [, segment, name] = parts as unknown as [string, string, string];\n const owner = ownerOrThrow(this.internals, kind, segment, name);\n if (owner.legacy) this.diagnose(legacyAddressMessage(this.internals, kind, segment, name));\n const id = owner.id;\n const bag = this.internals.shared[kind].get(id);\n if (bag !== undefined && bag.get(name) !== undefined) return { kind: \"bag\", bag, name };\n if (this.internals.flowDecls[kind].get(id)?.some((d) => d.name === name)) perFlow();\n if (bag === undefined && !this.internals.flowDecls[kind].has(id)) throw new Error(`no ${kind} store \"${segment}\"`);\n throw new Error(`no property at \"${path}\"`);\n }\n throw new Error(`bad property path \"${path}\"`);\n }\n\n /** The engine's own surface has no flow, so an engine-level diagnostic\n * carries the empty flow id - the same way a LoadReport's shared half\n * carries no flow. It reaches the run log and the engine tap; there is\n * nowhere else for it to go, and it fires only on a legacy address. */\n private diagnose(message: string): void {\n this.internals.emitEngine(\"\", { type: \"diagnostic\", where: \"property address\", message });\n }\n\n /** Content that names another engine's scope (`@patter.visits`) runs only\n * where that engine is on this registry: without it every read would answer\n * false and every write fail, so the flow is refused as it opens, before\n * anything changes. By then a game has built all of its engines, whatever\n * order it built them in. The same message on every runtime. */\n private assertExternalScopes(): void {\n for (const token of this.internals.bundle.externalScopes ?? []) {\n if (!this.internals.registry.has(token)) {\n throw new Error(`this content names @${token}, which no engine on this registry registered: `\n + `give every engine the game's one registry`);\n }\n }\n }\n\n /** The shared surface as examiner rows: @world (read through the\n * resolver) then the shared partitions. Per-flow rows live on each Flow. */\n listProperties(): PropertyRow[] {\n const out: PropertyRow[] = [];\n for (const d of this.internals.bundle.world.properties) {\n const value = this.internals.worldResolver.get(d.name);\n out.push({\n path: `world.${d.name}`, name: d.name, type: d.type,\n value: value ?? d.default, default: d.default,\n ...(d.values !== undefined ? { values: d.values } : {}),\n ...(d.stages !== undefined ? { stages: d.stages } : {}),\n // @world is FOREIGN - a host resolver backs it - so writability is whether that\n // resolver can be written at all AND what the declaration says, which is the\n // shared registry's own rule for a foreign scope (its foreignWritable). The\n // `as PropertyView` cast this replaced was hiding the field's absence: the row\n // type has always required it, and these rows shipped without one.\n //\n // A row is where `writable: false` is meant to SHOW (Reboot.md 10): it tells a\n // state panel this is the game's value, not the story's. It does not stop the\n // panel editing it - the host's setProperty passes `{ host: true }`.\n writable: this.internals.worldSet !== undefined && !this.internals.worldReadOnly.has(d.name),\n });\n }\n // The bag composes its rows' addresses from its own pathPrefix, so the prefix here is\n // only the caller's label for the mount; the row arrives already addressed.\n const add = (_prefix: string, bag: StateBag): void => {\n for (const row of bag.rows()) out.push(row);\n };\n add(\"story\", this.internals.shared.story);\n for (const kind of OWNED_SCOPES) {\n for (const [id, bag] of this.internals.shared[kind]) add(addressOf(this.internals, kind, id), bag);\n }\n return out;\n }\n\n /** The SHARED kernel bags with their store path prefixes (the state\n * logger's mount surface). The @world container is the host's own bag -\n * the host mounts it itself. */\n listBags(): BagMount[] {\n const mounts: BagMount[] = [{ prefix: \"story\", bag: this.internals.shared.story }];\n for (const kind of [\"box\", \"deck\", \"hand\", \"value\"] as const) {\n for (const [id, bag] of this.internals.shared[kind]) mounts.push({ prefix: addressOf(this.internals, kind, id), bag });\n }\n return mounts;\n }\n\n /** Every flow's trace, one stream, each event tagged with its flow id. */\n subscribeTrace(handler: EngineTraceHandler): () => void {\n this.engineTraceHandlers.add(handler);\n return () => this.engineTraceHandlers.delete(handler);\n }\n\n // --- persistence (schema 4) -------------------------------------------------\n\n /**\n * Live bundle refresh: rebuild on an edited bundle with the whole run carried\n * over, and return the replacement with the report its load produced.\n *\n * Standalone, that is a save and a load into a new engine, and this one is left\n * untouched (discard it). With the game's registry the two cannot both hold the\n * same keys, so this engine is spent afterwards (its flows closed, the\n * replacement holding everything on the same registry): it carries its\n * own values into the snapshot, steps out of the registry, and the replacement\n * loads them the way a standalone save loads: so the report covers the\n * properties the edit dropped, defaulted, or retyped, and a dropped property\n * is dropped rather than kept. Values the game loaded that were still waiting\n * for a flow of this engine carry across as they were, and nothing belonging\n * to any other engine is touched. A save for another project is refused before\n * anything moves; if the rebuild fails for any other reason, this engine takes\n * its registrations back and is left exactly as it was.\n */\n hotSwap(bundle: Bundle, opts: EngineOptions = {}): { engine: Engine; report: LoadReport } {\n if (bundle.content.project !== this.internals.bundle.content.project) {\n throw new Error(`save is for project \"${this.internals.bundle.content.project}\", bundle is \"${bundle.content.project}\"`);\n }\n const options: EngineOptions = { ...this.creationOptions, ...opts };\n const snapshot = this.saveGame();\n const reg = this.internals.registry;\n if (this.internals.ownsRegistry) {\n // Its own registry: a save and a load into a new engine, as it always was,\n // and this engine is left untouched.\n const next = new Engine(bundle, { ...options, registry: undefined });\n return { engine: next, report: next.loadGame(snapshot) };\n }\n // This engine's own values, registered or still waiting for a flow.\n const mine: Record<string, Record<string, ScalarValue>> = {};\n for (const [key, values] of Object.entries(reg.save())) {\n if (key === \"story\" || key.startsWith(\"storylets/\")) mine[key] = values;\n }\n const registeredKeys = new Set([\n ...this.sharedMounts.map((m) => m.key),\n ...[...this.flowsById.values()].flatMap((f) => f.registeredKeys()),\n ]);\n const waiting = Object.fromEntries(Object.entries(mine).filter(([key]) => !registeredKeys.has(key)));\n // Step out of the registry. The bags keep their values, so stepping back in is exact.\n for (const { key } of this.sharedMounts) if (reg.has(key)) reg.remove(key);\n for (const flow of this.flowsById.values()) flow.releaseBags(false);\n let next: Engine | undefined;\n try {\n next = new Engine(bundle, { ...options, registry: reg });\n const report = next.loadGame({ ...snapshot, registry: mine });\n // Values that were waiting for a flow wait on, for the replacement's flow of that name.\n const stillWaiting = Object.fromEntries(Object.entries(waiting).filter(([key]) => !reg.has(key)));\n if (Object.keys(stillWaiting).length > 0) reg.load(stillWaiting, { keepParked: true });\n this.dropRun(false);\n return { engine: next, report };\n } catch (e) {\n // Back as it was. The replacement's registrations go; a constructor that\n // failed part way parked what it had claimed, so this engine's keys are\n // cleared of anything waiting, registered again, and its own values laid\n // back over them (the waiting ones parked again).\n next?.dropRun(false);\n for (const { key } of next?.sharedMounts ?? []) if (reg.has(key)) reg.remove(key);\n reg.discardParked(\"storylets/\");\n for (const { mount } of this.sharedMounts) mount();\n for (const flow of this.flowsById.values()) flow.mountBags();\n // `story` may have claimed what the failed replacement parked there: back to\n // its declarations, then this engine's own values over it.\n this.reseedShared();\n reg.load(mine, { keepParked: true });\n throw e;\n }\n }\n\n /** The whole engine's NON-property state, one envelope: the spent cards\n * once, then every live flow (board, clocks, cooldowns, PRNG, play log)\n * keyed by its id. The property values are the registry's: a standalone\n * engine (one that made its own registry) carries them here under\n * `registry`, self-backed @world included; a game that passed a registry\n * saves it once itself, beside each engine's envelope. */\n saveGame(): SaveEnvelope {\n return structuredClone({\n schema: SAVE_SCHEMA,\n content: this.internals.bundle.content,\n ...(this.internals.ownsRegistry ? { registry: this.internals.registry.save() } : {}),\n shared: { spent: [...this.spent].sort() },\n flows: Object.fromEntries([...this.flowsById].map(([id, flow]) => [id, flow.snapshot(false)])),\n });\n }\n\n /** ONE flow's blob, to park a visit that is walking away: the same shape\n * the envelope carries per flow, and the same shape `openFlow`'s `restore`\n * option takes back (design/engine-server.md 4.1). Saving the whole\n * envelope to park one of four hundred players is wrong in cost and in\n * meaning. Throws for a name that is not open - a closed flow has nothing\n * left to save. */\n saveFlow(id: string): FlowSave {\n const flow = this.flowsById.get(id);\n if (!flow) throw new Error(`unknown flow \"${id}\"`);\n // Parked whole, properties included: a parked flow's bags leave the\n // registry when it closes, so its values have to travel with it.\n return structuredClone(flow.snapshot(true));\n }\n\n /** What `loadGame(envelope)` would do that is not a plain restore, without\n * doing any of it (design/engine-server.md 4.9). Pure: nothing on this\n * engine moves. A project mismatch is refused here exactly as `loadGame`\n * refuses it - it is the one thing neither call will tolerate. */\n previewLoad(envelope: SaveEnvelope | SaveEnvelopeV1): LoadReport {\n this.assertSameProject(envelope);\n return this.planLoad(envelope).report;\n }\n\n /** What `openFlow(id, { restore: saved })` would do to a flow of that name,\n * without doing it: the same report shape, since a visit parked under one\n * build and resumed under the next raises the same questions. Pure. */\n previewFlowRestore(id: string, saved: FlowSave): LoadReport {\n const draft = emptyDraft();\n this.planFlowRestore(id, saved, this.sharedClaimsExcept(id), draft);\n const content = this.internals.bundle.content;\n return finishReport(content, content, [id], draft);\n }\n\n /** Restore: shared state once, then every flow REBUILT from its blob.\n * Handles held from before the load are closed and inert (Patter's\n * rule); take fresh ones from getFlow()/flows().\n *\n * Property values come from the registry. An envelope that carries them\n * (a standalone engine's, or a version 1 envelope) has them walked, cleaned,\n * and moved into the registry here, over fresh defaults. Otherwise the game\n * loads its registry itself, before or after this call: each flow's bags\n * are handed back to the registry with their values, and the restored\n * flows claim them. The report then covers only what this envelope holds;\n * the registry's own load rule applies to the values.\n *\n * Returns the report `previewLoad` would have given for this envelope: the\n * drift tolerance that makes a load forgiving is what hides its cost, so\n * the cost comes back with the load whether or not anybody looked first. */\n loadGame(envelope: SaveEnvelope | SaveEnvelopeV1): LoadReport {\n this.assertSameProject(envelope);\n this.assertExternalScopes();\n const plan = this.planLoad(structuredClone(envelope));\n const reg = this.internals.registry;\n if (plan.sections !== undefined) {\n // The envelope carries the values: every bag of this engine back to its\n // defaults, then the cleaned values over them.\n this.reset();\n // The engine's own registry takes the save wholesale. A game's registry may\n // hold values the game loaded for other engines, still waiting: add to\n // those, never replace them.\n if (this.internals.ownsRegistry) reg.load(plan.sections);\n else reg.load(plan.sections, { keepParked: true });\n } else {\n this.dropRun(new Set(plan.flows.map(([id]) => id)));\n }\n for (const id of plan.spent) this.spent.add(id);\n for (const [id, clean] of plan.flows) this.open(id, {}, true).restore(clean);\n return plan.report;\n }\n\n private assertSameProject(envelope: SaveEnvelope | SaveEnvelopeV1): void {\n if (envelope.content.project !== this.internals.bundle.content.project) {\n throw new Error(`save is for project \"${envelope.content.project}\", bundle is \"${this.internals.bundle.content.project}\"`);\n }\n }\n\n /** The whole-envelope walk: the report, and the cleaned state the apply\n * half writes. Nothing here touches the engine, which is what lets\n * previewLoad and loadGame share it. */\n private planLoad(envelope: SaveEnvelope | SaveEnvelopeV1): {\n report: LoadReport;\n /** The cleaned property values to move into the registry, when the\n * envelope carries any. */\n sections?: Sections;\n spent: string[];\n flows: [string, FlowSave][];\n } {\n const schema = (envelope as { schema?: unknown }).schema;\n if (schema !== SAVE_SCHEMA && schema !== SAVE_SCHEMA_V1) throw new Error(`unsupported save schema: ${String(schema)}`);\n const draft = emptyDraft();\n // Where the property values are, if this envelope has them: a version 1\n // envelope's partitions, or a standalone engine's registry sections.\n const flowIds = new Set(Object.keys(envelope.flows ?? {}));\n let moved: { shared: PropsPartition; flows: Map<string, PropsPartition>; rest: Sections } | undefined;\n if (envelope.schema === SAVE_SCHEMA_V1) {\n moved = {\n shared: envelope.shared?.props ?? emptyPartitionValues(),\n flows: new Map(Object.entries(envelope.flows ?? {}).map(([id, f]) => [id, f.props ?? emptyPartitionValues()])),\n rest: {},\n };\n } else if (envelope.registry !== undefined) {\n moved = partitionsFromSections(envelope.registry, flowIds);\n }\n const shared = moved !== undefined\n ? walkPartition(this.internals, this.internals.sharedDecls, moved.shared, undefined, draft)\n : undefined;\n const spent: string[] = [];\n for (const cardId of envelope.shared?.spent ?? []) {\n if (this.internals.cardsById.has(cardId)) spent.push(cardId);\n else draft.droppedSpent.push(cardId);\n }\n const flows: [string, FlowSave][] = [];\n const sections: Sections | undefined = moved !== undefined ? { ...moved.rest } : undefined;\n if (sections !== undefined && shared !== undefined) {\n sectionsOf(shared, (kind, id) => (kind === \"story\" ? \"story\" : sharedKey(kind, id!)), sections);\n }\n for (const [id, saved] of Object.entries(envelope.flows ?? {})) {\n const withProps: FlowSave = moved !== undefined\n ? { ...saved, props: moved.flows.get(id) ?? emptyPartitionValues() }\n : { ...saved };\n const clean = this.planFlowRestore(id, withProps, undefined, draft);\n if (sections !== undefined && clean.props !== undefined) {\n // The flow's values go into the registry, where its bags claim them; the\n // restored flow itself carries none.\n sectionsOf(clean.props, (kind, owner) => flowKey(id, kind, owner), sections);\n delete clean.props;\n }\n flows.push([id, clean]);\n }\n return {\n report: finishReport(this.internals.bundle.content, envelope.content, flows.map(([id]) => id), draft),\n ...(sections !== undefined ? { sections } : {}),\n spent, flows,\n };\n }\n\n /** One flow's walk. `otherClaims` is the rest of the world's shared ledger\n * and is present only for a SINGLE-flow restore into a live engine: a\n * whole-envelope load rebuilds every flow from one consistent moment, so\n * there is nobody else to compete with. */\n private planFlowRestore(\n id: string,\n saved: FlowSave,\n otherClaims: Map<string, number> | undefined,\n draft: ReportDraft,\n ): FlowSave {\n const internals = this.internals;\n // A flow blob without properties (a version 2 envelope's: the registry has\n // them) has nothing to walk.\n const props = saved.props !== undefined ? walkPartition(internals, internals.flowDecls, saved.props, id, draft) : undefined;\n\n const cooldowns: Record<string, number> = {};\n for (const [cardId, turn] of Object.entries(saved.cooldowns ?? {})) {\n if (internals.cardsById.has(cardId)) cooldowns[cardId] = turn;\n else draft.droppedCooldowns.push({ flow: id, card: cardId });\n }\n\n // A deleted entity has no gameId left, so it is named by the id the save\n // carries; everything the build still knows is named by its gameId.\n const cardName = (cardId: string): string => {\n const entry = internals.cardsById.get(cardId);\n return entry ? effectiveGameId(entry.card) : cardId;\n };\n const board: Record<string, string[]> = {};\n const restored = new Map<string, number>();\n for (const [handId, ids] of Object.entries(saved.board ?? {})) {\n const known = internals.handsById.get(handId);\n if (known === undefined) {\n for (const cardId of ids) {\n draft.evicted.push({ flow: id, hand: handId, card: cardName(cardId), reason: \"hand-vanished\" });\n }\n continue;\n }\n const hand = effectiveGameId(known.hand);\n const kept: string[] = [];\n for (const cardId of ids) {\n const entry = internals.cardsById.get(cardId);\n if (entry === undefined) {\n draft.evicted.push({ flow: id, hand, card: cardId, reason: \"vanished\" });\n continue;\n }\n if (otherClaims !== undefined && cardIsShared(entry.card, entry.deck.shared ?? false)) {\n const held = (otherClaims.get(cardId) ?? 0) + (restored.get(cardId) ?? 0);\n if (held >= sharedCap(entry.card)) {\n draft.evicted.push({ flow: id, hand, card: effectiveGameId(entry.card), reason: \"claimed-elsewhere\" });\n continue;\n }\n restored.set(cardId, (restored.get(cardId) ?? 0) + 1);\n }\n kept.push(cardId);\n }\n board[handId] = kept;\n }\n\n return {\n ...(props !== undefined ? { props } : {}),\n turns: saved.turns ?? {},\n prng: saved.prng,\n cooldowns,\n board,\n playLog: saved.playLog ?? [],\n };\n }\n}\n\n// --- the Flow -----------------------------------------------------------------\n\nexport class Flow {\n readonly id: string;\n private readonly engine: Engine;\n private readonly internals: Internals;\n private closed = false;\n\n private prng: Prng;\n /** Per-box turn counters, keyed by box id (schema 3.4) - per flow. */\n private turnCounts = new Map<string, number>();\n private cooldowns: Record<string, number> = {};\n /** The board: hand contents (card ids, dealt order), keyed by hand id. */\n private boardContents = new Map<string, string[]>();\n private playLog: PlayRecord[] = [];\n // --- play-history indexes -------------------------------------------------\n // The four play-history host functions used to SCAN playLog on every call,\n // and they are called once per candidate card per ask, so dealing was\n // O(candidates x playLog): a shipped game got measurably slower the longer\n // somebody played it, which is the failure mode nobody meets in testing.\n // Measured before the change, 2000 cards: a box with no history condition\n // held flat at 0.3ms while `count_played` went 0.8ms -> 27.9ms as the log\n // reached 4000 plays.\n //\n // These are a pure summary of `playLog`, maintained where it is appended and\n // rebuilt where it is replaced, so they cannot drift from it. They are NOT\n // saved: `playLog` is the record, this is a derivation, and rebuilding on\n // load keeps the save format untouched.\n //\n // The tag keys are the played card's OWN (groupId, tagId) pairs, which is\n // what makes the box-local rule survive: a group name resolves inside the\n // ASKING box, so a card in another box carries different ids and cannot\n // match, exactly as the per-record `inTag` check used to decide.\n private playCount = new Map<string, number>();\n private lastPlayOf = new Map<string, PlayRecord>();\n private tagPlayCount = new Map<string, number>();\n private lastPlayInTag = new Map<string, PlayRecord>();\n /** The per-flow property partitions (the not-shared halves), each bag\n * that declares something registered under this flow's keys. */\n private stores: Partition;\n private readonly registered: string[] = [];\n /** This flow's bags that declare something, under their registry keys. */\n private readonly bagKeys: Array<[string, StateBag]> = [];\n\n private traceHandlers = new Set<TraceHandler>();\n private logEntries: LogEntry[] = [];\n private logSeq = 0;\n\n /** Merged read view per scope, built once (bags are stable for the\n * flow's life): the flow's own bag first, the shared bag behind it.\n * Names are disjoint (shared XOR per-flow by declaration), so \"first\"\n * is routing, not shadowing. */\n private readonly storyReader: ScopeResolver;\n private readonly boxReaders = new Map<string, ScopeResolver>();\n private readonly deckReaders = new Map<string, ScopeResolver>();\n\n /** @internal - built by Engine.openFlow / Engine.loadGame only. */\n constructor(engine: Engine, internals: Internals, id: string, seed: number) {\n this.engine = engine;\n this.internals = internals;\n this.id = id;\n this.prng = makePrng(seed);\n this.stores = buildPartition(internals, flowHalf);\n // Register the bags: each claims whatever the registry holds for its key (a\n // load); openFlow discarded that first for a fresh flow.\n const put = (key: string, bag: StateBag): void => {\n if (bag.declarations().length === 0) return; // holds nothing: not registered\n this.bagKeys.push([key, bag]);\n };\n put(flowKey(id, \"story\"), this.stores.story);\n for (const kind of OWNED_SCOPES) for (const [owner, bag] of this.stores[kind]) put(flowKey(id, kind, owner), bag);\n this.mountBags();\n for (const box of internals.bundle.boxes) {\n this.turnCounts.set(box.id, 0);\n for (const hand of box.hands) this.boardContents.set(hand.id, []);\n }\n const pair = (own: StateBag | undefined, shared: StateBag | undefined): ScopeResolver => ({\n get: (n) => own?.get(n) ?? shared?.get(n),\n });\n // `internals.shared` is reassigned wholesale by loadGame/reset, but a\n // load rebuilds every Flow too, so a live flow's readers and the\n // shared partition are always the same generation.\n this.storyReader = pair(this.stores.story, internals.shared.story);\n for (const box of internals.bundle.boxes) {\n this.boxReaders.set(box.id, pair(this.stores.box.get(box.id), internals.shared.box.get(box.id)));\n for (const deck of box.decks) {\n this.deckReaders.set(deck.id, pair(this.stores.deck.get(deck.id), internals.shared.deck.get(deck.id)));\n }\n }\n }\n\n // --- lifetime ----------------------------------------------------------------\n\n get isClosed(): boolean {\n return this.closed;\n }\n\n /** Close this flow: the handle goes inert, every verb throws. */\n close(): void {\n if (this.closed) return;\n this.engine.dropFlow(this.id, this);\n this.markClosed();\n }\n\n /** @internal */\n markClosed(): void {\n this.releaseBags(false);\n this.closed = true;\n }\n\n /** @internal - take this flow's bags out of the registry; with `keep`, their\n * values wait there for the flow that replaces this one (a load into the\n * game's registry). Idempotent. */\n releaseBags(keep: boolean): void {\n for (const key of this.registered) this.internals.registry.remove(key, { keep });\n this.registered.length = 0;\n }\n\n /** @internal - the registry keys this flow holds right now. */\n registeredKeys(): string[] {\n return [...this.registered];\n }\n\n /** @internal - register this flow's bags (again): at construction, and when a\n * failed hotSwap hands them back. Each claims what the registry holds for it. */\n mountBags(): void {\n for (const [key, bag] of this.bagKeys) {\n this.internals.registry.mountOwned(key, bag, { owner: OWNER });\n this.registered.push(key);\n }\n }\n\n private assertOpen(): void {\n if (this.closed) throw new Error(`flow \"${this.id}\" is closed`);\n }\n\n /** A box's current turn (schema 3.4), on THIS flow's clock. */\n turn(boxRef: string): number {\n this.assertOpen();\n const box = this.internals.boxesByGameId.get(boxRef) ?? this.internals.boxesById.get(boxRef);\n if (!box) throw new Error(`unknown box \"${boxRef}\"`);\n return this.turnCounts.get(box.id) ?? 0;\n }\n\n /** Subscribe to this flow's deal/play trace (schema 5). Returns the\n * unsubscribe. With no subscribers anywhere the flow does no trace work. */\n subscribeTrace(handler: TraceHandler): () => void {\n this.traceHandlers.add(handler);\n return () => this.traceHandlers.delete(handler);\n }\n\n private get tracing(): boolean {\n return this.traceHandlers.size > 0 || this.internals.logCap !== undefined || this.internals.engineTracing();\n }\n\n private emit(event: TraceEvent, turn?: number): void {\n if (this.internals.logCap !== undefined) {\n this.logEntries.push({ ...event, seq: this.logSeq++, ...(turn !== undefined ? { turn } : {}) });\n if (this.logEntries.length > this.internals.logCap) this.logEntries.splice(0, this.logEntries.length - this.internals.logCap);\n }\n for (const handler of this.traceHandlers) handler(event);\n this.internals.emitEngine(this.id, event, turn);\n }\n\n /** The retained flow log (opt-in via the Engine's `log`), oldest first,\n * capped. The introspection seam for hosts and tools; the durable play\n * history in a save stays `playLog` (schema 4) - the log is a\n * flow-lifetime utility and is NOT saved. */\n log(): readonly LogEntry[] {\n return this.logEntries;\n }\n\n /** Empty the retained log; `seq` keeps counting, so ordering across a\n * clear stays meaningful. */\n clearLog(): void {\n this.logEntries = [];\n }\n\n // --- expression plumbing ----------------------------------------------------\n\n private node(expr: Expression): ExprNode {\n let node = this.internals.nodeCache.get(expr);\n if (!node) {\n node = deserialiseAst(expr.ast);\n this.internals.nodeCache.set(expr, node);\n }\n return node;\n }\n\n /** Tag group names are box-scoped: two boxes may name a group the same way\n * (schema 1 - boxes namespace their groups), so a name is only ever\n * resolved inside the box being asked, never bundle-wide. Ids are\n * project-unique and accepted here too, still confined to the box. */\n private groupInBox(box: Box<Expression>, ref: string): TagGroup | undefined {\n return box.tagGroups.find((g) => effectiveGameId(g) === ref)\n ?? box.tagGroups.find((g) => g.id === ref);\n }\n\n /** Fold one play into the indexes. O(the card's tags), not O(the log). */\n private indexPlay(record: PlayRecord): void {\n this.playCount.set(record.card, (this.playCount.get(record.card) ?? 0) + 1);\n this.lastPlayOf.set(record.card, record);\n const entry = this.internals.cardsByGameId.get(record.card);\n if (!entry) return;\n for (const [groupId, tagIds] of Object.entries(entry.card.tags ?? {})) {\n for (const tagId of tagIds) {\n const key = tagKey(groupId, tagId);\n this.tagPlayCount.set(key, (this.tagPlayCount.get(key) ?? 0) + 1);\n this.lastPlayInTag.set(key, record);\n }\n }\n }\n\n /** Rebuild the indexes from the log. Called wherever `playLog` is REPLACED\n * rather than appended to, which is `restore` alone. */\n private rebuildPlayIndex(): void {\n this.playCount.clear();\n this.lastPlayOf.clear();\n this.tagPlayCount.clear();\n this.lastPlayInTag.clear();\n for (const record of this.playLog) this.indexPlay(record);\n }\n\n /** `box` is the box whose ask is being evaluated: the play-history\n * functions take a bare group name, so it resolves there (a card's tags\n * reference its own box's group, which keeps the counts box-local).\n * History is THIS flow's: countPlayed answers \"have I done this\". */\n /** One host per box, built once.\n *\n * The closures below read `this.playCount`, `this.turnCounts` and the rest\n * LIVE, so a cached host answers with current state - which is what makes\n * caching safe rather than a snapshot bug. Unreal did this from the start\n * (`hostsByBox_`, built at flow construction) and the other three rebuilt a\n * host, and its closures, on every `evalCtx` call: once per deck per ask,\n * and once per surviving card in the eviction pass. Structural divergence\n * in one port AND the allocation the audit flagged, so the other three\n * copied it (2026-08-29). Lazy rather than eager, so a bundle's unvisited\n * boxes cost nothing. */\n private hostsByBox = new Map<string, StoryletsHost>();\n\n private host(box: Box<Expression>): StoryletsHost {\n const cached = this.hostsByBox.get(box.id);\n if (cached !== undefined) return cached;\n const made = this.makeHost(box);\n this.hostsByBox.set(box.id, made);\n return made;\n }\n\n private makeHost(box: Box<Expression>): StoryletsHost {\n /** A group NAME and tag name resolved in THIS box, as the index's key.\n * Resolved once per call now, where `inTag` used to resolve it again for\n * every record in the log. Undefined when either name is unknown here,\n * which is the old per-record `false` and answers \"never\". */\n const keyOf = (group: string, tag: string): string | undefined => {\n const found = this.groupInBox(box, group);\n const t = found?.tags.find((v) => v.gameId === tag);\n return found && t ? tagKey(found.id, t.id) : undefined;\n };\n /** Turns-since is measured on the played card's box's clock (3.4). */\n const since = (record: PlayRecord): number => {\n const entry = this.internals.cardsByGameId.get(record.card);\n if (!entry) return NEVER_PLAYED;\n return (this.turnCounts.get(entry.box.id) ?? 0) - record.turn;\n };\n return {\n nextRandom: () => this.prng.next(),\n countPlayed: (card) => this.playCount.get(card) ?? 0,\n turnsSincePlayed: (card) => {\n const last = this.lastPlayOf.get(card);\n return last ? since(last) : NEVER_PLAYED;\n },\n countPlayedIn: (group, tag) => {\n const key = keyOf(group, tag);\n return key === undefined ? 0 : this.tagPlayCount.get(key) ?? 0;\n },\n turnsSincePlayedIn: (group, tag) => {\n const key = keyOf(group, tag);\n const last = key === undefined ? undefined : this.lastPlayInTag.get(key);\n return last ? since(last) : NEVER_PLAYED;\n },\n };\n }\n\n /** The evaluation environment (schema 3.1/6.2): @box/@deck resolve to the\n * card under evaluation; in hand-condition contexts @deck is an empty bag,\n * so any reference is an eval error (missing-policy throw). Every scope\n * is the flow's MERGED view - its own copies over the shared values,\n * names disjoint - and @world reads through the engine's resolver. */\n private evalCtx(box: Box<Expression>, deck: Deck<Expression> | undefined, handEnv: HandEnv): EvalContext {\n const others = this.internals.registryView();\n return {\n scopes: {\n // Every other engine's game-wide scope first (every engine reads every\n // scope); this engine's own tokens are its merged views, over the top.\n ...others.scopes,\n world: this.internals.worldResolver,\n story: this.storyReader,\n box: this.boxReaders.get(box.id) ?? {},\n deck: deck ? this.deckReaders.get(deck.id) ?? {} : {},\n hand: handEnv.bag,\n },\n host: this.host(box) as unknown as Record<string, unknown>,\n // The quality channel, answering for THIS ask's box and deck. Only wired\n // when a quality exists, so a bundle without one evaluates byte-\n // identically to before the feature.\n ...(this.internals.hasQualities || others.qualities !== undefined ? {\n qualities: (scope: string, name: string): readonly string[] | undefined =>\n scope === \"world\" ? this.internals.ladders.world.get(name) ?? others.qualities?.(scope, name)\n : scope === \"story\" ? this.internals.ladders.story.get(name)\n : scope === \"box\" ? this.internals.ladders.box.get(box.id)?.get(name)\n : scope === \"deck\" && deck ? this.internals.ladders.deck.get(deck.id)?.get(name)\n // @hand is composed, so the ladder belongs to whatever supplied the\n // value THIS ask: the bound tag, or the asking hand. `sources` is\n // already the map that answers that, because write-back needs it.\n : scope === \"hand\" ? this.handLadder(handEnv, name)\n : others.qualities?.(scope, name),\n } : {}),\n };\n }\n\n /** The ladder behind one composed @hand name, or undefined when the name is\n * not a quality (or came from criteria, which are tag NAMES, never state). */\n private handLadder(handEnv: HandEnv, name: string): readonly string[] | undefined {\n const source = handEnv.sources.get(name);\n if (!source) return undefined;\n return source.kind === \"value\" ? this.internals.ladders.value.get(source.id)?.get(name)\n : source.kind === \"hand\" ? this.internals.ladders.hand.get(source.id)?.get(name)\n : undefined;\n }\n\n private eval(expr: Expression, ctx: EvalContext): ScalarValue {\n return evaluate(this.node(expr), ctx, storyletsDialect);\n }\n\n private passes(expr: Expression | undefined, ctx: EvalContext, where?: string): boolean {\n if (!expr) return true;\n try {\n return conditionPasses(this.eval(expr, ctx));\n } catch (e) {\n // An eval error is never a silent pass: the card/deck is unavailable\n // (schema 3.1), and the trace surfaces the diagnostic.\n if (this.tracing) {\n this.emit({ type: \"diagnostic\", where: where ?? \"condition\", message: e instanceof Error ? e.message : String(e) });\n }\n return false;\n }\n }\n\n // --- resolving asks (schema 2.6 + 3.6) -----------------------------------------\n\n private tagByGameId(group: TagGroup, gameId: string): Tag | undefined {\n return group.tags.find((t) => t.gameId === gameId);\n }\n\n /** A deal's ask: the hand's template bindings + chosen tags, or its rule's\n * bindings, plus the implicit home binding (schema 2.4). */\n private askForHand(hand: Hand<Expression>, box: Box<Expression>): AskDescriptor {\n const boundTags = new Map<string, string>();\n const askNames: Record<string, string> = {};\n let condition: Expression | undefined;\n if (hand.template !== undefined) {\n const template = this.internals.templatesById.get(hand.template);\n if (!template) throw new Error(`hand \"${effectiveGameId(hand)}\": unknown template \"${hand.template}\"`);\n for (const [groupId, tagId] of Object.entries(template.bindings ?? {})) {\n boundTags.set(groupId, tagId);\n }\n for (const [groupId, tagId] of Object.entries(hand.chosen ?? {})) {\n // A hole filled from a property rather than with a tag: resolve it\n // now, before tag composition (4.6, the hand that moves).\n if (isHoleRef(tagId)) {\n this.fillHoleFromProperty(hand, groupId, tagId, boundTags, askNames);\n continue;\n }\n boundTags.set(groupId, tagId);\n const found = this.internals.groupsById.get(groupId);\n const tag = found?.group.tags.find((t) => t.id === tagId);\n if (found && tag) askNames[effectiveGameId(found.group)] = effectiveGameId(tag);\n }\n condition = template.condition;\n } else {\n for (const [groupId, tagId] of Object.entries(hand.rule?.bindings ?? {})) {\n if (isHoleRef(tagId)) {\n this.fillHoleFromProperty(hand, groupId, tagId, boundTags, askNames);\n continue;\n }\n boundTags.set(groupId, tagId);\n // ...and name it, exactly as the template branch above does: a card\n // reading @hand.<group> must not care HOW the group got bound\n // (design/hand-typing.md, the residues).\n const found = this.internals.groupsById.get(groupId);\n const tag = found?.group.tags.find((t) => t.id === tagId);\n if (found && tag) askNames[effectiveGameId(found.group)] = effectiveGameId(tag);\n }\n condition = hand.rule?.condition;\n }\n boundTags.set(PLACE_GROUP, hand.id);\n this.bindStateGroups(box, boundTags, askNames);\n return { box, hand, ...(condition !== undefined ? { condition } : {}), boundTags, askNames };\n }\n\n /** A peek's ask: raw criteria ({group gameId: tag gameId}), bindings only,\n * no condition slot (schema 3.1; the boundary, Reboot 4). */\n private askForPeek(box: Box<Expression>, criteria: Record<string, string>): AskDescriptor {\n const boundTags = new Map<string, string>();\n const askNames: Record<string, string> = {};\n for (const [groupRef, tagRef] of Object.entries(criteria)) {\n if (groupRef === PLACE_GROUP) {\n const hand = this.internals.handsByGameId.get(tagRef) ?? this.internals.handsById.get(tagRef);\n if (!hand) throw new Error(`peek: unknown hand \"${tagRef}\" in home criteria`);\n boundTags.set(PLACE_GROUP, hand.hand.id);\n continue;\n }\n const found = this.groupInBox(box, groupRef);\n if (!found) {\n throw new Error(`peek: unknown tag group \"${groupRef}\" in box \"${effectiveGameId(box)}\"`);\n }\n const tag = this.tagByGameId(found, tagRef) ?? found.tags.find((t) => t.id === tagRef);\n if (!tag) throw new Error(`peek: unknown tag \"${tagRef}\" in group \"${effectiveGameId(found)}\"`);\n boundTags.set(found.id, tag.id);\n askNames[effectiveGameId(found)] = effectiveGameId(tag);\n }\n this.bindStateGroups(box, boundTags, askNames);\n return { box, boundTags, askNames };\n }\n\n /**\n * Fill one hole from the property its value names: the hand that moves\n * (design/engine-server.md 4.6).\n *\n * The semantics are `bindStateGroups`' below, word for word, applied per\n * HOLE instead of per group: resolved at ask time, and a value naming no tag\n * leaves the hole UNBOUND (a wildcard) with a diagnostic rather than dealing\n * a silently empty hand. What is added is the `@hand` scope - the asking\n * hand's OWN declared state, read here from the flow's merged view (the\n * shared half under the flow's own, so a `shared: true` declaration moves\n * the hole for every flow and a per-flow one moves it for this flow alone).\n *\n * Read BEFORE tag composition, which is the whole reason it is safe: the\n * @hand bag a card sees is built from the bound tags, so resolving a hole\n * from it would be circular. A hand's own declarations are not, so they are.\n */\n private fillHoleFromProperty(\n hand: Hand<Expression>, groupId: string, ref: string,\n boundTags: Map<string, string>, askNames: Record<string, string>,\n ): void {\n const found = this.internals.groupsById.get(groupId);\n const groupName = found ? effectiveGameId(found.group) : groupId;\n const where = `hand ${effectiveGameId(hand)}, tag group ${groupName}`;\n const parsed = parseHoleRef(ref);\n if (!parsed) {\n this.emit({ type: \"diagnostic\", where, message: `\"${ref}\" is not a @hand, @world or @story property reference` });\n return;\n }\n if (!found) {\n this.emit({ type: \"diagnostic\", where, message: `\"${ref}\" fills a tag group that is not in this box` });\n return;\n }\n let value: ScalarValue | undefined;\n if (parsed.scope === \"hand\") {\n value = this.valuesOf(\"hand\", hand.id)[parsed.name];\n } else {\n try {\n value = this.getProperty(`${parsed.scope}.${parsed.name}`);\n } catch {\n value = undefined;\n }\n }\n if (value === undefined) {\n this.emit({ type: \"diagnostic\", where, message: `\"${ref}\" names a property that is not declared` });\n return;\n }\n const wanted = typeof value === \"string\" ? value : String(value);\n const tag = found.group.tags.find((t) => effectiveGameId(t) === wanted);\n if (!tag) {\n this.emit({ type: \"diagnostic\", where, message: `${ref} is \"${wanted}\", which is not one of the tags of \"${groupName}\"` });\n return;\n }\n boundTags.set(groupId, tag.id);\n askNames[groupName] = effectiveGameId(tag);\n }\n\n /**\n * Bind every `boundBy` group in the box from the property it names.\n *\n * The gap this closes: only a hand could bind a group, and `deal` takes no\n * criteria, so an axis driven by state (an act, a chapter) had nowhere to\n * gate. Runs AFTER the hand's own bindings and never overwrites one: an\n * explicit binding is a deliberate act and beats a default.\n *\n * A value naming no tag in the group leaves the group UNBOUND rather than\n * matching nothing. Unbound is a wildcard, so the ask still deals; a silent\n * empty hand would look like content that does not exist, and the diagnostic\n * is what says otherwise.\n */\n private bindStateGroups(box: Box<Expression>, boundTags: Map<string, string>, askNames: Record<string, string>): void {\n for (const group of box.tagGroups) {\n if (group.boundBy === undefined || boundTags.has(group.id)) continue;\n const ref = /^@(world|story)\\.([a-z][a-z0-9_-]*)$/.exec(group.boundBy);\n if (!ref) {\n this.emit({ type: \"diagnostic\", where: `tag group ${effectiveGameId(group)}`, message: `boundBy \"${group.boundBy}\" is not a @world or @story property reference` });\n continue;\n }\n let value: ScalarValue | undefined;\n try {\n value = this.getProperty(`${ref[1]}.${ref[2]}`);\n } catch {\n this.emit({ type: \"diagnostic\", where: `tag group ${effectiveGameId(group)}`, message: `boundBy \"${group.boundBy}\" names a property that is not declared` });\n continue;\n }\n const wanted = typeof value === \"string\" ? value : String(value);\n const tag = group.tags.find((t) => effectiveGameId(t) === wanted);\n if (!tag) {\n this.emit({ type: \"diagnostic\", where: `tag group ${effectiveGameId(group)}`, message: `${group.boundBy} is \"${wanted}\", which is not one of its tags` });\n continue;\n }\n boundTags.set(group.id, tag.id);\n askNames[effectiveGameId(group)] = effectiveGameId(tag);\n }\n }\n\n // --- @hand composition (schema 3.6) -------------------------------------------\n\n /** A store's full value view for one owner: the shared half under the\n * flow's half. Names are disjoint, so the spread is routing, not\n * shadowing. */\n private valuesOf(kind: Exclude<PartitionKind, \"story\">, id: string): PropertyBag {\n return {\n ...(this.internals.shared[kind].get(id)?.values ?? {}),\n ...(this.stores[kind].get(id)?.values ?? {}),\n };\n }\n\n private buildHandEnv(ask: AskDescriptor): HandEnv {\n const bag: PropertyBag = {};\n const sources = new Map<string, HandSource>();\n\n // 1. Tag properties of every bound tag (home binds a hand, not a tag).\n for (const [groupId, tagId] of ask.boundTags) {\n if (groupId === PLACE_GROUP) continue;\n for (const [name, value] of Object.entries(this.valuesOf(\"value\", tagId))) {\n bag[name] = value;\n sources.set(name, { kind: \"value\", id: tagId });\n }\n }\n // 2. Hand properties, when the ask is a deal.\n if (ask.hand) {\n for (const [name, value] of Object.entries(this.valuesOf(\"hand\", ask.hand.id))) {\n bag[name] = value;\n sources.set(name, { kind: \"hand\", id: ask.hand.id });\n }\n }\n // 3. Chosen tags / criteria, by group name (the tag's gameId as value).\n for (const [name, value] of Object.entries(ask.askNames)) {\n bag[name] = value;\n sources.set(name, { kind: \"criteria\" });\n }\n return { bag, sources, boundTags: ask.boundTags };\n }\n\n // --- the ask (schema 3.1 + 3.2) ------------------------------------------------\n\n /** The claims ledger, derived from THIS flow's board: card id -> holding\n * hands (schema 3.5). Claims are per flow - another flow holding the\n * card is another playthrough, not a rival hand. */\n private claims(): Map<string, number> {\n const counts = new Map<string, number>();\n for (const contents of this.boardContents.values()) {\n for (const id of contents) counts.set(id, (counts.get(id) ?? 0) + 1);\n }\n return counts;\n }\n\n /** @internal - every card id on THIS flow's board, one entry per holding\n * hand. The engine sums these across live flows for the shared ledger. */\n heldCardIds(): string[] {\n return [...this.boardContents.values()].flat();\n }\n\n private copiesOf(card: Card<Expression>): number {\n return card.copies ?? 1;\n }\n\n /** The claims step (schema 3.1 step 6) for one card, as a verdict or null\n * for \"available\". Two caps apply to a shared card and they are different\n * statements, so they get different verdicts: `copies` is your own board\n * filling up, `sharedCopies` is somebody else already holding it, and a\n * participant told \"claimed\" about a card sitting on another person's\n * table would read it as an engine fault (design/shared-scarcity 9.3.1).\n *\n * `mine` counts this flow's holdings, `world` every live flow's. */\n private claimVerdict(\n card: Card<Expression>,\n shared: boolean,\n mine: Map<string, number>,\n world: Map<string, number>,\n ): \"claimed\" | \"claimed-elsewhere\" | null {\n const id = card.id;\n if ((mine.get(id) ?? 0) >= this.copiesOf(card)) return \"claimed\";\n if (shared && (world.get(id) ?? 0) >= sharedCap(card)) return \"claimed-elsewhere\";\n return null;\n }\n\n /** Tag matching (schema 3.1 step 3): for every bound group the card lists\n * the bound tag or omits the group (wildcard); the home group inverts -\n * a homed card requires a matching home binding (schema 2.4). */\n private tagsMatch(card: Card<Expression>, boundTags: Map<string, string>): boolean {\n const home = card.tags?.[PLACE_GROUP];\n if (home !== undefined && home.length > 0) {\n const bound = boundTags.get(PLACE_GROUP);\n if (bound === undefined || !home.includes(bound)) return false;\n }\n for (const [groupId, tagId] of boundTags) {\n if (groupId === PLACE_GROUP) continue;\n const tags = card.tags?.[groupId];\n if (tags === undefined) {\n // Omission is a wildcard unless the group says otherwise. A required\n // group inverts it, which is what `place` has always done per card.\n if (this.internals.requiredGroups.has(groupId)) return false;\n continue;\n }\n if (!tags.includes(tagId)) return false;\n }\n return true;\n }\n\n /** Run one ask: availability filter then ranking. `claimed` decides the\n * claims step (step 6) per card, returning the verdict that refused it or\n * null for available. `trace` (when a subscriber exists) collects the\n * per-card verdicts. */\n private runAsk(\n ask: AskDescriptor,\n claimed: (card: Card<Expression>, shared: boolean) => \"claimed\" | \"claimed-elsewhere\" | null,\n trace?: { id: string; verdict: TraceVerdict; priority?: number; specificity?: number }[],\n ): { ordered: CardEntry[]; handEnv: HandEnv } {\n const { box } = ask;\n const handEnv = this.buildHandEnv(ask);\n // Identity on the trace is by gameId (4.4), so the helper takes the CARD\n // rather than an id: every call site had one in hand, and taking the id\n // was the whole of how the two vocabularies got mixed.\n const verdict = (card: Card<Expression>, v: TraceVerdict): void => {\n trace?.push({ id: effectiveGameId(card), verdict: v });\n };\n\n // The hand's condition: ask-constant, evaluated once (schema 3.1 step 4).\n if (!this.passes(ask.condition, this.evalCtx(box, undefined, handEnv), `hand ${ask.hand ? effectiveGameId(ask.hand) : \"\"} condition`)) {\n return { ordered: [], handEnv };\n }\n\n // Deck gates: evaluated once per ask, in deck (id) order (schema 2.5).\n const gateOk = new Map<string, boolean>();\n for (const deck of box.decks) {\n gateOk.set(deck.id, this.passes(deck.condition, this.evalCtx(box, deck, handEnv), `deck ${deck.gameId} gate`));\n }\n\n const turn = this.turnCounts.get(box.id) ?? 0;\n const scored: { entry: CardEntry; priority: number; spec: number }[] = [];\n for (const deck of box.decks) {\n // ONE context per deck, not per card. It is built from box, deck and\n // handEnv, none of which vary inside this loop, and a condition is a\n // read-only gate (schema 3.1), so nothing can write through it and make\n // sharing visible. Rebuilding it per card cost an EvalContext, a scopes\n // map and five bag wrappers each time: about half the garbage a peek over\n // a large box produced (port-review-2026-08.md, measured).\n const deckCtx = this.evalCtx(box, deck, handEnv);\n const deckShared = deck.shared ?? false;\n for (const card of deck.cards) {\n const shared = cardIsShared(card, deckShared);\n if (!gateOk.get(deck.id)) {\n verdict(card, \"deck-gate\");\n continue;\n }\n // Taken out of the world by somebody's shared one-shot. Checked\n // before the flow's own clock, because \"cooldown\" would point the\n // reader at a turn counter that has nothing to do with it.\n if (shared && this.engine.isTaken(card.id)) {\n verdict(card, \"taken\");\n continue;\n }\n if ((this.cooldowns[card.id] ?? 0) > turn) {\n verdict(card, \"cooldown\");\n continue;\n }\n if (!this.tagsMatch(card, handEnv.boundTags)) {\n verdict(card, \"tags\");\n continue;\n }\n // The label is only read when an eval THROWS and only when tracing, so\n // building it per card was pure waste on the path that matters. Built\n // when tracing is on, where the cost is already accepted.\n if (card.condition && !this.passes(card.condition, deckCtx,\n this.tracing ? `card ${card.gameId} condition` : undefined)) {\n verdict(card, \"condition\");\n continue;\n }\n const refused = claimed(card, shared); // claims, last (schema 3.1 step 6)\n if (refused) {\n verdict(card, refused);\n continue;\n }\n\n let priority: number;\n if (typeof card.priority === \"number\") {\n priority = card.priority;\n } else {\n try {\n const v = this.eval(card.priority, deckCtx);\n if (typeof v !== \"number\") {\n verdict(card, \"priority\");\n continue;\n }\n priority = v;\n } catch (e) {\n if (this.tracing) {\n this.emit({ type: \"diagnostic\", where: `card ${card.gameId} priority`, message: e instanceof Error ? e.message : String(e) });\n }\n verdict(card, \"priority\");\n continue;\n }\n }\n let spec = 0;\n if (box.ranking.specificity && card.condition) {\n const node = this.node(card.condition);\n spec = matchedSpecificity(node, (n) => {\n try {\n return conditionPasses(evaluate(n, deckCtx, storyletsDialect));\n } catch {\n return false;\n }\n });\n }\n scored.push({ entry: { card, deck, box }, priority, spec });\n }\n }\n\n scored.sort((a, b) => b.priority - a.priority || b.spec - a.spec); // stable\n // Seeded shuffle of each maximal tie run; runs of 1 consume no draws.\n let i = 0;\n while (i < scored.length) {\n let j = i + 1;\n while (j < scored.length\n && scored[j]!.priority === scored[i]!.priority\n && scored[j]!.spec === scored[i]!.spec) j++;\n if (j - i > 1) {\n const run = scored.slice(i, j);\n shuffleInPlace(run, this.prng);\n // Written back element by element, as all three ports do. It used to be\n // `scored.splice(i, j - i, ...run)`, which SPREADS one argument per\n // element: with every card at the default priority 0 the tie run is the\n // whole list, and a box of 150 000 such cards threw `RangeError:\n // Maximum call stack size exceeded` rather than dealing. Far-fetched\n // for one box, but it was a crash where the ports had no limit, and the\n // reference is supposed to be the thing they are transliterated from.\n for (let k = 0; k < run.length; k++) scored[i + k] = run[k]!;\n }\n i = j;\n }\n for (const s of scored) {\n trace?.push({ id: effectiveGameId(s.entry.card), verdict: \"dealt\", priority: s.priority, specificity: s.spec });\n }\n return { ordered: scored.map((s) => s.entry), handEnv };\n }\n\n /** Flip eligible-but-not-taken trace entries to \"capped\". `taken` is keyed\n * by GAMEID, as the trace rows are (4.4): the two must move together or\n * every dealt card silently reads as capped. */\n private capTrace(\n trace: { id: string; verdict: TraceVerdict; priority?: number; specificity?: number }[],\n taken: ReadonlySet<string>,\n ): void {\n for (const entry of trace) {\n if (entry.verdict === \"dealt\" && !taken.has(entry.id)) entry.verdict = \"capped\";\n }\n }\n\n private view(entry: CardEntry): DealtCard {\n const { card } = entry;\n return {\n id: card.id,\n gameId: effectiveGameId(card),\n ...(card.title !== undefined ? { title: card.title } : {}),\n ...(card.purpose !== undefined ? { purpose: card.purpose } : {}),\n ...(card.fields !== undefined ? { fields: card.fields } : {}),\n };\n }\n\n private handCapacity(hand: Hand<Expression>): number {\n if (hand.slots !== undefined) return hand.slots;\n const declared = hand.template !== undefined\n ? this.internals.templatesById.get(hand.template)?.slots\n : hand.rule?.slots;\n return declared === undefined || declared === \"unbounded\" ? Infinity : declared;\n }\n\n private resolveHand(ref: string): { hand: Hand<Expression>; box: Box<Expression> } {\n const found = this.internals.handsByGameId.get(ref) ?? this.internals.handsById.get(ref);\n if (!found) throw new Error(`unknown hand \"${ref}\"`);\n return found;\n }\n\n // --- host surface (schema 5) ---------------------------------------------------\n\n /** Look at the top of the stock through raw tag criteria (schema 3.1):\n * claims respected, nothing registered, nothing left behind but the\n * trace line. You can never play a card you only peeked. */\n peek(boxRef: string, criteria: Record<string, string> = {}, n?: number): RankedList {\n this.assertOpen();\n const box = this.internals.boxesByGameId.get(boxRef) ?? this.internals.boxesById.get(boxRef);\n if (!box) throw new Error(`unknown box \"${boxRef}\"`);\n const ask = this.askForPeek(box, criteria);\n const claimCounts = this.claims();\n // Skipped outright when the bundle shares nothing, which is most bundles:\n // the ledger walks every live flow's whole board, and an empty map answers\n // every question the same way a computed one would.\n const worldClaims = this.internals.hasShared ? this.engine.sharedClaims() : new Map<string, number>();\n const trace = this.tracing ? [] : undefined;\n const { ordered } = this.runAsk(ask, (card, shared) => this.claimVerdict(card, shared, claimCounts, worldClaims), trace);\n // CLAMPED. `slice(0, -1)` drops the last card and returns the rest, so a\n // negative n answered with almost the whole list here while every port\n // returned nothing (2026-08-29).\n const listed = n === undefined ? ordered : ordered.slice(0, Math.max(n, 0));\n if (trace) {\n this.capTrace(trace, new Set(listed.map((e) => effectiveGameId(e.card))));\n this.emit({ type: \"peek\", box: effectiveGameId(box), criteria, cards: trace }, this.turnCounts.get(box.id) ?? 0);\n }\n return { box: effectiveGameId(box), cards: listed.map((e) => this.view(e)) };\n }\n\n /** Refresh one hand (schema 3.5); returns its new shape. */\n deal(handRef: string): DealtCard[] {\n this.assertOpen();\n const { hand } = this.resolveHand(handRef);\n return this.dealMany([handRef])[effectiveGameId(hand)] ?? [];\n }\n\n /** Re-deal several / all hands (schema 3.5): seeded hand-order shuffle\n * (fairness), evict, seed the ledger from survivors, fill in order.\n * Returns the dealt slice - the new contents of exactly the hands this\n * call dealt, keyed by hand gameId (board() stays the whole-board read). */\n dealMany(handRefs?: string[]): Record<string, DealtCard[]> {\n this.assertOpen();\n const dealt = (handRefs ?? [...this.internals.handsById.keys()].sort())\n .map((ref) => this.resolveHand(ref));\n shuffleInPlace(dealt, this.prng);\n\n // Eviction first: drop dealt cards no longer available to their hand\n // (minus the claims check against their own seat).\n for (const { hand, box } of dealt) {\n const ask = this.askForHand(hand, box);\n const handEnv = this.buildHandEnv(ask);\n const conditionOk = this.passes(ask.condition, this.evalCtx(box, undefined, handEnv));\n const gateOk = new Map<string, boolean>();\n for (const deck of box.decks) {\n gateOk.set(deck.id, this.passes(deck.condition, this.evalCtx(box, deck, handEnv)));\n }\n const turn = this.turnCounts.get(box.id) ?? 0;\n // Trace events fire after the state they report has landed (a handler\n // reading the board sees the eviction), so they are collected here and\n // emitted once the survivors are set.\n const evicted: { card: string; reason: Extract<TraceEvent, { type: \"evict\" }>[\"reason\"] }[] = [];\n // The card is named by gameId (4.4). A card the build no longer has -\n // the `vanished` branch below - has no gameId left, so it is named by\n // the id the board carries, which is the rule a load report has always\n // used for the same reason.\n const evict = (cardId: string, reason: Extract<TraceEvent, { type: \"evict\" }>[\"reason\"]): false => {\n const known = this.internals.cardsById.get(cardId);\n evicted.push({ card: known ? effectiveGameId(known.card) : cardId, reason });\n return false;\n };\n const survivors = (this.boardContents.get(hand.id) ?? []).filter((cardId) => {\n if (!conditionOk) return evict(cardId, \"hand-condition\");\n const entry = this.internals.cardsById.get(cardId);\n if (!entry) return evict(cardId, \"vanished\"); // edited content: dropped\n if (!gateOk.get(entry.deck.id)) return evict(cardId, \"deck-gate\");\n if ((this.cooldowns[cardId] ?? 0) > turn) return evict(cardId, \"cooldown\");\n if (!this.tagsMatch(entry.card, handEnv.boundTags)) return evict(cardId, \"tags\");\n if (!this.passes(entry.card.condition, this.evalCtx(box, entry.deck, handEnv), `card ${entry.card.gameId} condition`)) {\n return evict(cardId, \"condition\");\n }\n return true;\n });\n this.boardContents.set(hand.id, survivors);\n if (this.tracing) {\n for (const e of evicted) this.emit({ type: \"evict\", hand: effectiveGameId(hand), card: e.card, reason: e.reason }, turn);\n }\n }\n\n const claimCounts = this.claims();\n // The world ledger is taken once for the whole batch and kept in step with\n // the local one below, so two hands in the SAME deal cannot both take the\n // last shared copy. Skipped outright when the bundle shares nothing (most\n // bundles): an empty map answers every question the same way.\n const worldClaims = this.internals.hasShared ? this.engine.sharedClaims() : new Map<string, number>();\n for (const { hand, box } of dealt) {\n const contents = this.boardContents.get(hand.id) ?? [];\n const free = this.handCapacity(hand) - contents.length;\n if (free <= 0) continue;\n const ask = this.askForHand(hand, box);\n const own = new Set(contents);\n const trace = this.tracing ? [] : undefined;\n // At most once in any one hand; at most `copies` hands here, and at most\n // `sharedCopies` hands anywhere (schema 3.5, shared-scarcity 5).\n const { ordered } = this.runAsk(ask,\n (card, shared) => (own.has(card.id) ? \"claimed\" : this.claimVerdict(card, shared, claimCounts, worldClaims)), trace);\n const taking = ordered.slice(0, free);\n const added = taking.map((e) => e.card.id);\n this.boardContents.set(hand.id, [...contents, ...added]);\n for (const id of added) {\n claimCounts.set(id, (claimCounts.get(id) ?? 0) + 1);\n worldClaims.set(id, (worldClaims.get(id) ?? 0) + 1);\n }\n // Emitted after the hand is set: a handler reading board() sees the deal.\n if (trace) {\n this.capTrace(trace, new Set(taking.map((e) => effectiveGameId(e.card))));\n this.emit({ type: \"deal\", hand: effectiveGameId(hand), cards: trace }, this.turnCounts.get(box.id) ?? 0);\n }\n }\n\n return Object.fromEntries(dealt.map(({ hand }) => [\n effectiveGameId(hand),\n (this.boardContents.get(hand.id) ?? []).map((id) => this.view(this.internals.cardsById.get(id)!)),\n ]));\n }\n\n /** The board: current hand contents, in dealt order, keyed by hand gameId\n * (schema 5). Read it for what is out; peek the stock for what could\n * come.\n *\n * `boxRef` (a box gameId or id) narrows the read to that box's hands, in\n * the same shape and the same order: \"give me the barks hands\" is a\n * common host query, and boxes are how a game separates its storylet\n * systems, so the grouping belongs here rather than in every host. An\n * unknown box throws, as it does on turn() and peek(). */\n board(boxRef?: string): Record<string, DealtCard[]> {\n this.assertOpen();\n let keep: string | undefined;\n if (boxRef !== undefined) {\n const box = this.internals.boxesByGameId.get(boxRef) ?? this.internals.boxesById.get(boxRef);\n if (!box) throw new Error(`unknown box \"${boxRef}\"`);\n keep = box.id;\n }\n return Object.fromEntries([...this.boardContents.entries()]\n .filter(([handId]) => keep === undefined || this.internals.handsById.get(handId)!.box.id === keep)\n .map(([handId, ids]) => [\n effectiveGameId(this.internals.handsById.get(handId)!.hand),\n ids.map((id) => this.view(this.internals.cardsById.get(id)!)),\n ]));\n }\n\n /** Resolve a played/inspected card within a hand on the board. */\n private resolveDealt(cardId: string, handRef: string): { entry: CardEntry; ask: AskDescriptor } {\n const entry = this.internals.cardsById.get(cardId) ?? this.internals.cardsByGameId.get(cardId);\n if (!entry) throw new Error(`unknown card \"${cardId}\"`);\n const { hand, box } = this.resolveHand(handRef);\n if (!(this.boardContents.get(hand.id) ?? []).includes(entry.card.id)) {\n throw new Error(`card \"${effectiveGameId(entry.card)}\" is not dealt to hand \"${effectiveGameId(hand)}\"`);\n }\n return { entry, ask: this.askForHand(hand, box) };\n }\n\n /** Outcome availability, evaluated against CURRENT state on every ask\n * (schema 3.1/5) - never a deal-time snapshot. */\n outcomes(cardId: string, from: string): OutcomeView[] {\n this.assertOpen();\n const { entry, ask } = this.resolveDealt(cardId, from);\n const ctx = this.evalCtx(entry.box, entry.deck, this.buildHandEnv(ask));\n return entry.card.outcomes.map((o) => ({\n id: o.id,\n gameId: effectiveGameId(o),\n ...(o.title !== undefined ? { title: o.title } : {}),\n ...(o.purpose !== undefined ? { purpose: o.purpose } : {}),\n ...(o.fields !== undefined ? { fields: o.fields } : {}),\n available: this.passes(o.condition, ctx),\n }));\n }\n\n /** Apply an outcome (schema 3.7): the card must sit in a hand on the\n * board (you never play a card from inside the deck). Throws before any\n * mutation on a gated-shut outcome or a bad write target.\n *\n * A card with NO outcomes is played with none, named as \"\" (the\n * no-outcome-play brief, 2026-09-14): a masthead, a notice, a codex entry,\n * whose play means \"shown\". It is everything a play is except the writes:\n * the play log and the history functions count it, the box's turn moves by\n * the usual rule, the redraw rests it and it leaves its hand. \"\" is the one\n * spelling in all four runtimes, because a Blueprint pin cannot be absent.\n * Only the empty-for-empty case is new: \"\" on a card that has outcomes is\n * refused, and a named outcome on a card with none is refused as before. */\n play(cardId: string, outcomeGameId: string, from: string, opts: PlayOptions = {}): void {\n this.assertOpen();\n const { entry, ask } = this.resolveDealt(cardId, from);\n const bare = outcomeGameId === \"\";\n if (bare && entry.card.outcomes.length > 0) {\n throw new Error(`card \"${effectiveGameId(entry.card)}\" has outcomes (${entry.card.outcomes.map((o) => effectiveGameId(o)).join(\", \")}); name the one played`);\n }\n const outcome = bare ? undefined : entry.card.outcomes.find((o) => effectiveGameId(o) === outcomeGameId);\n if (!bare && !outcome) throw new Error(`card \"${effectiveGameId(entry.card)}\" has no outcome \"${outcomeGameId}\"`);\n\n const handEnv = this.buildHandEnv(ask);\n const ctx = this.evalCtx(entry.box, entry.deck, handEnv);\n if (outcome && !this.passes(outcome.condition, ctx)) {\n throw new Error(`outcome \"${outcomeGameId}\" on \"${effectiveGameId(entry.card)}\" is gated shut`);\n }\n\n // The played card's box's clock advances (schema 3.4); computed up\n // front so the play and its writes log as one action, one turn stamp.\n //\n // A TIMED box (design/engine-server.md 4.8) defaults to advancing\n // NOTHING: its clock is time, the host ticks it, and a play is not a\n // tick. A call that names `advanceTurns` still gets what it asked for,\n // in either kind of box, because the call says otherwise. This is the\n // whole of `turn`'s effect on the engine: the seconds are never read.\n const perPlay = entry.box.turn !== undefined ? 0 : this.internals.bundle.settings.playAdvancesTurns;\n const newTurn = (this.turnCounts.get(entry.box.id) ?? 0) + (opts.advanceTurns ?? perPlay);\n\n // Every right-hand side evaluates against PRE-play state, then all\n // writes land (schema 3.7).\n const writes: { target: string; value: ScalarValue }[] = [];\n for (const [target, expr] of Object.entries(outcome?.changes ?? {})) {\n writes.push({ target, value: this.eval(expr, ctx) });\n }\n for (const { target, value } of writes) {\n const { path, prev } = this.applyWrite(target, value, entry, handEnv);\n if (this.tracing) this.emit({ type: \"write\", target, path, value, ...(prev !== undefined ? { prev } : {}) }, newTurn);\n }\n\n const outcomeId = outcome ? effectiveGameId(outcome) : \"\";\n const record: PlayRecord = { card: effectiveGameId(entry.card), outcome: outcomeId, turn: newTurn };\n this.playLog.push(record);\n this.indexPlay(record);\n if (entry.card.redraw === \"never\") {\n // A shared one-shot leaves the world rather than this flow: the engine\n // holds it, so every flow is refused. A finite redraw deliberately does\n // NOT share, whatever the deck says - a cooldown is an absolute turn of\n // this flow's box clock, and there is no shared clock to compare it\n // against (design/shared-scarcity.md 9.3.2).\n if (cardIsShared(entry.card, entry.deck.shared ?? false)) this.engine.markTaken(entry.card.id);\n else this.cooldowns[entry.card.id] = Number.MAX_SAFE_INTEGER;\n } else if (typeof entry.card.redraw === \"number\") {\n this.cooldowns[entry.card.id] = newTurn + entry.card.redraw;\n }\n // The card leaves its hand, releasing its claim (schema 3.5/3.7).\n const handId = ask.hand!.id;\n this.boardContents.set(handId,\n (this.boardContents.get(handId) ?? []).filter((id) => id !== entry.card.id));\n this.turnCounts.set(entry.box.id, newTurn);\n // Emitted last: a handler reading the board and the clock sees the play.\n if (this.tracing) this.emit({ type: \"play\", card: effectiveGameId(entry.card), outcome: outcomeId, turn: newTurn }, newTurn);\n }\n\n /** One owned property's address, owner segment and all (4.4). */\n private address(kind: OwnedScope, id: string): string {\n return addressOf(this.internals, kind, id);\n }\n\n /** Land one change in whichever partition declares the name: the flow's\n * bag when the property is per-flow, the shared bag when it is shared -\n * the union/partition invariant made executable. */\n private landIn(kind: Exclude<PartitionKind, \"story\"> | \"story\", id: string | undefined, name: string, value: ScalarValue, path: string): { path: string; prev?: ScalarValue } {\n const own = kind === \"story\" ? this.stores.story : id !== undefined ? this.stores[kind].get(id) : undefined;\n const shared = kind === \"story\" ? this.internals.shared.story : id !== undefined ? this.internals.shared[kind].get(id) : undefined;\n const bag = own !== undefined && own.get(name) !== undefined ? own\n : shared !== undefined && shared.get(name) !== undefined ? shared\n : undefined;\n if (bag === undefined) throw new Error(`no property at \"${path}\"`);\n // An engine write: the bag's subscribers fire (the firing rule).\n const change = bag.set(name, value);\n return { path, ...(change.prev !== undefined ? { prev: change.prev } : {}) };\n }\n\n /** Land one change; returns the resolved store path (for the trace) and\n * the value it replaced (for the log's \"0 -> 1\" reading). */\n private applyWrite(target: string, value: ScalarValue, entry: CardEntry, handEnv: HandEnv): { path: string; prev?: ScalarValue } {\n const match = /^@([a-z]+)\\.([A-Za-z_][A-Za-z0-9_-]*)$/.exec(target);\n if (!match) throw new Error(`bad change target \"${target}\"`);\n const [, scope, name] = match as unknown as [string, string, string];\n switch (scope) {\n case \"world\": {\n const worldSet = this.internals.worldSet;\n if (!worldSet) throw new Error(`@world.${name} cannot be written: the host bound @world read-only`);\n // The story's own promise, kept HERE and only here, because here is where\n // the story does the writing: the table is consulted before the seam, so\n // an outcome never reaches the bag (which would let a host write past it)\n // nor a bound resolver (which cannot tell the two apart). The host's\n // setProperty is its own path and never asks. Patter's runtime refuses the\n // same write through the shared kernel, so both read one way.\n if (this.internals.worldReadOnly.has(name)) throw new Error(`'@world.${name}' is read-only (writable: false)`);\n const prev = this.internals.worldResolver.get(name);\n worldSet(name, value);\n return { path: `world.${name}`, ...(prev !== undefined ? { prev } : {}) };\n }\n case \"story\": return this.landIn(\"story\", undefined, name, value, `story.${name}`);\n case \"box\": return this.landIn(\"box\", entry.box.id, name, value, `${this.address(\"box\", entry.box.id)}.${name}`);\n case \"deck\": return this.landIn(\"deck\", entry.deck.id, name, value, `${this.address(\"deck\", entry.deck.id)}.${name}`);\n case \"hand\": {\n // Write-back routing (schema 3.6): the composed name remembers its\n // source store; writes to criteria/chosen-tag names are errors.\n const source = handEnv.sources.get(name);\n if (!source) throw new Error(`@hand.${name} is not composed in this ask`);\n if (source.kind === \"criteria\") throw new Error(`@hand.${name} is a chosen tag / criteria name and cannot be written`);\n return this.landIn(source.kind, source.id, name, value, `${this.address(source.kind, source.id)}.${name}`);\n }\n default: {\n // Another engine's game-wide scope (`@patter.x`): the family's shared\n // vocabulary lets a card write it, and the registry keeps that engine's\n // rules (a read-only property is refused). A story write, so no host flag.\n if (this.internals.registry.has(scope)) {\n const prev = this.internals.registry.get(scope, name);\n this.internals.registry.set(scope, name, value);\n return { path: `${scope}.${name}`, ...(prev !== undefined ? { prev } : {}) };\n }\n if (this.internals.bundle.externalScopes?.includes(scope)) {\n throw new Error(`@${scope}.${name} cannot be written: no engine on this registry registered @${scope}`);\n }\n throw new Error(`bad change target scope \"@${scope}\"`);\n }\n }\n }\n\n /** Advance one box's clock (schema 3.4): a turn is one draw-from-stock\n * session for that box, on THIS flow's clock. */\n advanceTurns(boxRef: string, n = 1): void {\n this.assertOpen();\n const box = this.internals.boxesByGameId.get(boxRef) ?? this.internals.boxesById.get(boxRef);\n if (!box) throw new Error(`unknown box \"${boxRef}\"`);\n const next = (this.turnCounts.get(box.id) ?? 0) + n;\n this.turnCounts.set(box.id, next);\n if (this.tracing) this.emit({ type: \"turns\", box: effectiveGameId(box), turn: next }, next);\n }\n\n // --- state access (host surface + test tooling) ---------------------------------\n\n /** Every box, bundle order: identity + this flow's clock (the enumeration\n * surface examiners key their turns sections on; parity member). */\n listBoxes(): BoxView[] {\n this.assertOpen();\n return this.internals.bundle.boxes.map((b) => ({\n id: b.id,\n gameId: effectiveGameId(b),\n ...(b.title !== undefined ? { title: b.title } : {}),\n turn: this.turnCounts.get(b.id) ?? 0,\n }));\n }\n\n /** THIS flow's kernel bags with their store path prefixes (the state\n * logger's mount surface; parity member). The shared bags are the\n * Engine's listBags; the flows are rebuilt by loadGame, so consumers\n * re-enumerate after a load. */\n listBags(): BagMount[] {\n this.assertOpen();\n const mounts: BagMount[] = [{ prefix: \"story\", bag: this.stores.story }];\n for (const kind of [\"box\", \"deck\", \"hand\", \"value\"] as const) {\n for (const [id, bag] of this.stores[kind]) mounts.push({ prefix: addressOf(this.internals, kind, id), bag });\n }\n return mounts;\n }\n\n /** The flow's FULL merged view as examiner rows (the property examiner /\n * editor surface, parity across all runtimes): @world read through the\n * resolver, then per scope the shared values and this flow's own.\n * Bundle order: world, story, then per-box / per-deck / per-hand /\n * per-tag stores. */\n listProperties(): PropertyRow[] {\n this.assertOpen();\n const out: PropertyRow[] = [];\n for (const d of this.internals.bundle.world.properties) {\n const value = this.internals.worldResolver.get(d.name);\n out.push({\n path: `world.${d.name}`, name: d.name, type: d.type,\n value: value ?? d.default, default: d.default,\n ...(d.values !== undefined ? { values: d.values } : {}),\n ...(d.stages !== undefined ? { stages: d.stages } : {}),\n // @world is FOREIGN - a host resolver backs it - so writability is whether that\n // resolver can be written at all AND what the declaration says, which is the\n // shared registry's own rule for a foreign scope (its foreignWritable). The\n // `as PropertyView` cast this replaced was hiding the field's absence: the row\n // type has always required it, and these rows shipped without one.\n //\n // A row is where `writable: false` is meant to SHOW (Reboot.md 10): it tells a\n // state panel this is the game's value, not the story's. It does not stop the\n // panel editing it - the host's setProperty passes `{ host: true }`.\n writable: this.internals.worldSet !== undefined && !this.internals.worldReadOnly.has(d.name),\n });\n }\n const add = (_prefix: string, shared: StateBag | undefined, own: StateBag | undefined): void => {\n for (const bag of [shared, own]) {\n if (bag === undefined) continue;\n for (const row of bag.rows()) out.push(row);\n }\n };\n add(\"story\", this.internals.shared.story, this.stores.story);\n for (const kind of OWNED_SCOPES) {\n const ids = new Set([...this.internals.shared[kind].keys(), ...this.stores[kind].keys()]);\n for (const id of ids) {\n add(addressOf(this.internals, kind, id), this.internals.shared[kind].get(id), this.stores[kind].get(id));\n }\n }\n return out;\n }\n\n /** Read by path: \"world.x\", \"story.gold\", \"value.docks.danger\",\n * \"box.village.heat\", \"deck.wares.n\", \"hand.the-elder.zone\" - the flow's\n * merged view, routed by the declaration's sharing.\n *\n * The owner segment is the entity's GAMEID, the name it is called by\n * everywhere else (4.4). Its internal id is accepted for this release and\n * earns a `diagnostic` naming the address to move to; the next lockstep\n * release refuses it. */\n getProperty(path: string): ScalarValue {\n this.assertOpen();\n const found = this.resolvePath(path);\n const value = found.kind === \"world\" ? this.internals.worldResolver.get(found.name)\n : found.kind === \"scope\" ? this.internals.registry.get(found.token, found.name)\n : found.own?.get(found.name) ?? found.shared?.get(found.name);\n if (value === undefined) throw new Error(`no property at \"${path}\"`);\n return value;\n }\n\n setProperty(path: string, value: ScalarValue): void {\n this.assertOpen();\n const found = this.resolvePath(path);\n if (found.kind === \"world\") {\n if (!this.internals.worldSet) throw new Error(`@world is read-only here: the host bound no write`);\n this.internals.worldSet(found.name, value, true);\n return;\n }\n if (found.kind === \"scope\") {\n this.internals.registry.set(found.token, found.name, value, { host: true });\n return;\n }\n const bag = found.own !== undefined && found.own.get(found.name) !== undefined ? found.own\n : found.shared !== undefined && found.shared.get(found.name) !== undefined ? found.shared\n : undefined;\n if (bag === undefined) throw new Error(`no property at \"${path}\"`);\n // A host write: silent under the firing rule (no subscriber feedback\n // loop), visible to the bag's audit hook, and flagged HOST so a\n // `writable: false` does not refuse the game its own value.\n bag.set(found.name, value, { silent: true, reason: \"host setProperty\", host: true });\n }\n\n private resolvePath(path: string):\n | { kind: \"world\"; name: string }\n | { kind: \"scope\"; token: string; name: string }\n | { kind: \"bag\"; own?: StateBag; shared?: StateBag; name: string } {\n const parts = path.split(\".\");\n if (parts.length === 2 && parts[0] === \"world\") return { kind: \"world\", name: parts[1]! };\n if (parts.length === 2 && parts[0] !== \"story\" && this.internals.registry.has(parts[0]!)) {\n return { kind: \"scope\", token: parts[0]!, name: parts[1]! };\n }\n if (parts.length === 2 && parts[0] === \"story\") {\n return { kind: \"bag\", own: this.stores.story, shared: this.internals.shared.story, name: parts[1]! };\n }\n if (parts.length === 3 && (parts[0] === \"box\" || parts[0] === \"deck\" || parts[0] === \"hand\" || parts[0] === \"value\")) {\n const kind = parts[0] as OwnedScope;\n const [, segment, name] = parts as unknown as [string, string, string];\n const owner = ownerOrThrow(this.internals, kind, segment, name);\n if (owner.legacy && this.tracing) {\n this.emit({ type: \"diagnostic\", where: \"property address\", message: legacyAddressMessage(this.internals, kind, segment, name) });\n }\n const own = this.stores[kind].get(owner.id);\n const shared = this.internals.shared[kind].get(owner.id);\n if (own === undefined && shared === undefined) throw new Error(`no ${kind} store \"${segment}\"`);\n return { kind: \"bag\", ...(own !== undefined ? { own } : {}), ...(shared !== undefined ? { shared } : {}), name };\n }\n throw new Error(`bad property path \"${path}\"`);\n }\n\n // --- persistence (schema 4) -------------------------------------------------\n\n /** @internal - this flow's blob: inside the engine's envelope without its\n * properties (the registry has them), or parked whole by saveFlow. */\n snapshot(withProps: boolean): FlowSave {\n return {\n ...(withProps ? { props: partitionValues(this.stores) } : {}),\n turns: Object.fromEntries(this.turnCounts),\n prng: this.prng.state(),\n cooldowns: this.cooldowns,\n board: Object.fromEntries(this.boardContents),\n playLog: this.playLog,\n };\n }\n\n /** @internal - restore a freshly opened flow from its blob (loadGame).\n * Orphaned keys (deleted entities) drop; new declarations keep defaults. */\n restore(saved: FlowSave): void {\n if (saved.props !== undefined) loadPartition(this.stores, saved.props);\n this.turnCounts = new Map(this.internals.bundle.boxes.map((b) => [b.id, 0]));\n for (const [boxId, turn] of Object.entries(saved.turns ?? {})) {\n if (this.turnCounts.has(boxId)) this.turnCounts.set(boxId, turn);\n }\n this.prng = makePrng(saved.prng);\n this.cooldowns = saved.cooldowns ?? {};\n this.playLog = saved.playLog ?? [];\n this.rebuildPlayIndex();\n this.boardContents = new Map(Object.entries(saved.board ?? {})\n .filter(([handId]) => this.internals.handsById.has(handId))\n .map(([handId, ids]) => [handId, ids.filter((id) => this.internals.cardsById.has(id))]));\n for (const handId of this.internals.handsById.keys()) {\n if (!this.boardContents.has(handId)) this.boardContents.set(handId, []);\n }\n }\n}\n","// ---------------------------------------------------------------------------\n// describeBundle - the bundle inspector's runtime half (design/engine-runtimes.md\n// section 2, piece 6).\n//\n// A BUNDLE-level API, deliberately NOT a session method: it answers the\n// integrator's question - \"I dropped a .storyletsc into my project, what may\n// my game code call?\" - from the imported asset alone, with no session, no\n// state and no game running. That makes the boundary rule (design 4) visible:\n// hands are what deal() takes, tag groups + tags are what peek() criteria are\n// drawn from, declared properties are what expressions read and a host may\n// set. Card lists are deliberately absent: cards are the engine's business,\n// counts are the orientation an integrator needs.\n//\n// Everything is in bundle order, so the description is deterministic and two\n// runtimes render the same rows in the same sequence. The property scopes are\n// the static twin of session.listProperties(): the same stores, in the same\n// order, before anything is instantiated (a hand instance carries its\n// template's declarations, exactly as the session's hand bags do).\n// ---------------------------------------------------------------------------\n\nimport { effectiveGameId, isHoleRef } from \"@storylet-studio/model\";\nimport type {\n Box, Bundle, Expression, Hand, PropertyDecl, PropertyType, ScalarValue,\n} from \"@storylet-studio/model\";\n\n/** What bundle this is: the staleness/identity triple plus the schema tag. */\nexport interface BundleIdentity {\n /** The bundle schema tag (\"storylets/bundle@0\"). */\n schema: string;\n /** content.project - the project name a save must agree with. */\n project: string;\n /** content.version - the authored bundle version. */\n version: string;\n /** content.hash - hash32 over the canonical source shards (schema 2.8). */\n hash: string;\n /** \"full\" | \"stripped\": whether authoring metadata (titles) survived. */\n metadata: string;\n}\n\n/** One hole this hand fills from a property rather than with a tag: the hand\n * MOVES when that property is written (design/engine-server.md 4.6). `group`\n * is the tag group's gameId, `from` the reference exactly as authored. */\nexport interface MovableHole {\n group: string;\n from: string;\n}\n\n/** One hand: the deal() surface. `gameId` is the name deal() is called with. */\nexport interface HandSummary {\n gameId: string;\n title?: string;\n /** The owning box's gameId (peek's first argument for the same stock). */\n box: string;\n /** The effective slot cap: the hand's override, else its template's or\n * rule's, else \"unbounded\". */\n slots: number | \"unbounded\";\n /** The hand template's gameId; absent for a standalone (inline-rule) hand. */\n template?: string;\n /**\n * The holes filled from a property, in bundle order. Absent when the hand\n * has none, which is the ordinary case.\n *\n * Reported because it is the one thing about a hand an integrator cannot see\n * from its name: a movable hole means writing that property MOVES the hand,\n * so it is the difference between a fixed kiosk and a performer who walks\n * about. `setProperty` is the whole verb; there is no other.\n */\n movable?: MovableHole[];\n}\n\n/** One tag group and its tags, by gameId: the peek() criteria surface (a\n * criteria entry is `{ [group gameId]: tag gameId }`). */\nexport interface TagGroupSummary {\n gameId: string;\n tags: string[];\n}\n\n/** One box: identity, its ranking policy, its tag groups, and counts. */\nexport interface BoxSummary {\n gameId: string;\n title?: string;\n /** The only per-box ranking policy (Reboot 2.2). */\n ranking: { specificity: boolean };\n /** Present on a TIMED box (design/engine-server.md 4.8): how long one of\n * its turns lasts. An integrator reading a bundle needs it to know which\n * boxes their host must tick, and how often. Absent is the ordinary box. */\n turn?: { seconds: number };\n /** How many cards in this box are DURABLE (design/engine-server.md 4.2):\n * their `redraw: \"never\"` spend outlives the run, and a server has to lift\n * and restore it. A count rather than a list, like every other number here:\n * an integrator needs to know whether this box has any such cards at all,\n * and which ones is the authoring tool's question. Absent when there are\n * none, which is the ordinary bundle. */\n durableCards?: number;\n tagGroups: TagGroupSummary[];\n counts: {\n decks: number;\n cards: number;\n hands: number;\n templates: number;\n tagGroups: number;\n };\n}\n\n/** One declared property: what expressions read and what a host may set. */\nexport interface PropertySummary {\n name: string;\n type: PropertyType;\n default: ScalarValue;\n /** Enum / flags options, where declared. */\n values?: string[];\n /** Declared DURABLE (design/engine-server.md 4.2): the value survives a run,\n * and a server lifts and restores it across one. The engine never reads it;\n * it is reported because it is the difference between a value an integrator\n * may reset and one somebody is going to expect back. Absent = run-scoped. */\n durable?: true;\n purpose?: string;\n}\n\n/** The scope a declaration block belongs to. `tag` declarations compose into\n * @hand for any ask that binds the tag (schema 3.6). */\nexport type PropertyScopeKind = \"world\" | \"story\" | \"box\" | \"deck\" | \"hand\" | \"tag\";\n\n/** One scope's declared properties. `owner` is the owning entity's gameId\n * (empty for world / story); `box` names its box; `group` names a tag's\n * group. */\nexport interface PropertyScopeSummary {\n scope: PropertyScopeKind;\n owner: string;\n box?: string;\n group?: string;\n properties: PropertySummary[];\n}\n\n/**\n * One map the bundle was asked to carry (design/graphical-views.md 2).\n *\n * Counts rather than the geometry itself, which is the same judgement the rest\n * of this file makes: an inspector answers \"what is in here\", and a host that\n * wants the polygons reads `bundle.maps` directly. Reported because a bundle\n * that silently carried a map would fail the promise this API exists for.\n */\nexport interface MapSummary {\n /** The owning box, by gameId. */\n box: string;\n /** The tag group this is a map of, by gameId. */\n group: string;\n zones: number;\n backgrounds: number;\n /** Placed hands standing on this map (design/engine-server.md 4.3): where the\n * kiosks are, in a bundle that carries geometry at all. */\n sites: number;\n}\n\n/** What a bundle offers a host, read from the asset alone. */\nexport interface BundleDescription {\n identity: BundleIdentity;\n /** Orientation, not inventory: no card lists (Reboot 2.1). */\n totals: {\n boxes: number;\n decks: number;\n cards: number;\n hands: number;\n templates: number;\n tagGroups: number;\n };\n boxes: BoxSummary[];\n /** Every hand in the bundle, box by box: the deal() surface. */\n hands: HandSummary[];\n /** world, story, then per box: the box, its decks, its hands, its tags.\n * Scopes that declare nothing are omitted (world and story always show,\n * so their absence reads as \"this bundle declares none\"). */\n properties: PropertyScopeSummary[];\n /** Maps carried as inert payload, when the build asked for them. Empty is\n * the normal state and means the bundle has no geometry in it. */\n maps: MapSummary[];\n}\n\nconst summarise = (decls: PropertyDecl[]): PropertySummary[] =>\n decls.map((d) => ({\n name: d.name,\n type: d.type,\n default: d.default,\n ...(d.values !== undefined ? { values: d.values } : {}),\n ...(d.durable === true ? { durable: true as const } : {}),\n ...(d.purpose !== undefined ? { purpose: d.purpose } : {}),\n }));\n\n/** How many cards in a box are durable: the card's own flag, else its deck's\n * (design/engine-server.md 4.2, the same inheritance `shared` has). */\nconst durableCardCount = (box: Box<Expression>): number =>\n box.decks.reduce((n, deck) =>\n n + deck.cards.filter((card) => (card.durable ?? deck.durable) === true).length, 0);\n\n/** A hand's declared @hand state: a template instance inherits its template's\n * declarations, a standalone hand declares its own (schema 2.6) - the same\n * rule the session's hand bags are built on. */\nconst handDecls = (hand: Hand<Expression>, box: Box<Expression>): PropertyDecl[] => {\n if (hand.template !== undefined) {\n return box.handTemplates.find((t) => t.id === hand.template)?.properties ?? [];\n }\n return hand.properties ?? [];\n};\n\n/** The hand's movable holes, in the bundle's own key order: every `chosen` /\n * rule-binding value that is a property reference rather than a tag (4.6).\n * A group id the bundle does not carry is skipped rather than reported under\n * its raw id: the description speaks gameIds throughout. */\nconst movableHoles = (hand: Hand<Expression>, box: Box<Expression>): MovableHole[] => {\n const filled = hand.template !== undefined ? hand.chosen : hand.rule?.bindings;\n const out: MovableHole[] = [];\n for (const [groupId, value] of Object.entries(filled ?? {})) {\n if (!isHoleRef(value)) continue;\n const group = box.tagGroups.find((g) => g.id === groupId);\n if (group === undefined) continue;\n out.push({ group: effectiveGameId(group), from: value });\n }\n return out;\n};\n\n/** The effective slot cap, resolved the way the session resolves capacity. */\nconst handSlots = (hand: Hand<Expression>, box: Box<Expression>): number | \"unbounded\" => {\n if (hand.slots !== undefined) return hand.slots;\n const declared = hand.template !== undefined\n ? box.handTemplates.find((t) => t.id === hand.template)?.slots\n : hand.rule?.slots;\n return declared === undefined ? \"unbounded\" : declared;\n};\n\n/** Describe a compiled bundle: the callable surface of an imported asset, no\n * session required (design/engine-runtimes.md 2, piece 6). Bundle order\n * throughout; the same shape every runtime returns. */\nexport function describeBundle(bundle: Bundle): BundleDescription {\n const boxes: BoxSummary[] = [];\n const hands: HandSummary[] = [];\n const properties: PropertyScopeSummary[] = [\n { scope: \"world\", owner: \"\", properties: summarise(bundle.world.properties) },\n { scope: \"story\", owner: \"\", properties: summarise(bundle.story.properties) },\n ];\n const totals = { boxes: 0, decks: 0, cards: 0, hands: 0, templates: 0, tagGroups: 0 };\n\n for (const box of bundle.boxes) {\n const boxGameId = effectiveGameId(box);\n const cards = box.decks.reduce((n, deck) => n + deck.cards.length, 0);\n boxes.push({\n gameId: boxGameId,\n ...(box.title !== undefined ? { title: box.title } : {}),\n ranking: { specificity: box.ranking.specificity },\n ...(box.turn !== undefined ? { turn: { seconds: box.turn.seconds } } : {}),\n ...(durableCardCount(box) > 0 ? { durableCards: durableCardCount(box) } : {}),\n tagGroups: box.tagGroups.map((group) => ({\n gameId: effectiveGameId(group),\n tags: group.tags.map((tag) => effectiveGameId(tag)),\n })),\n counts: {\n decks: box.decks.length,\n cards,\n hands: box.hands.length,\n templates: box.handTemplates.length,\n tagGroups: box.tagGroups.length,\n },\n });\n totals.boxes += 1;\n totals.decks += box.decks.length;\n totals.cards += cards;\n totals.hands += box.hands.length;\n totals.templates += box.handTemplates.length;\n totals.tagGroups += box.tagGroups.length;\n\n for (const hand of box.hands) {\n const template = hand.template !== undefined\n ? box.handTemplates.find((t) => t.id === hand.template)\n : undefined;\n const movable = movableHoles(hand, box);\n hands.push({\n gameId: effectiveGameId(hand),\n ...(hand.title !== undefined ? { title: hand.title } : {}),\n box: boxGameId,\n slots: handSlots(hand, box),\n ...(template !== undefined ? { template: effectiveGameId(template) } : {}),\n ...(movable.length > 0 ? { movable } : {}),\n });\n }\n\n // The property scopes, in the session's store order: box, decks, hands,\n // tags. Empty declaration blocks are dropped (nothing to read or set).\n const push = (scope: PropertyScopeKind, owner: string, decls: PropertyDecl[], group?: string): void => {\n if (decls.length === 0) return;\n properties.push({\n scope, owner, box: boxGameId, ...(group !== undefined ? { group } : {}),\n properties: summarise(decls),\n });\n };\n push(\"box\", boxGameId, box.properties);\n for (const deck of box.decks) push(\"deck\", effectiveGameId(deck), deck.properties);\n for (const hand of box.hands) push(\"hand\", effectiveGameId(hand), handDecls(hand, box));\n for (const group of box.tagGroups) {\n for (const tag of group.tags) {\n push(\"tag\", effectiveGameId(tag), tag.properties ?? [], effectiveGameId(group));\n }\n }\n }\n\n return {\n identity: {\n schema: bundle.schema,\n project: bundle.content.project,\n version: bundle.content.version,\n hash: bundle.content.hash,\n metadata: bundle.metadata,\n },\n totals,\n boxes,\n hands,\n properties,\n maps: (bundle.maps ?? []).map((map) => ({\n box: map.box,\n group: map.group,\n zones: map.zones.length,\n backgrounds: map.backgrounds?.length ?? 0,\n sites: map.sites?.length ?? 0,\n })),\n };\n}\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.<gameId>.x / deck.<gameId>.x / hand.<gameId>.x /\n// value.<tagGameId>.x, and value.<boxGameId>/<tagGameId>.x for a tag gameId\n// two boxes share (4.4)\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 - plus its turns / cooldowns / board. @world is not\n * here for the same reason it is not in a save envelope: the host owns that\n * container and mounts/saves it itself (createWorldContainer).\n *\n * Taken off the BAGS, which is what a save envelope is made of, rather than\n * off the envelope itself. The two used to be interchangeable; from 4.4 they\n * are not, because a property ADDRESS names its owner by gameId while the\n * envelope stays keyed by internal id (a save has to survive a rename). The\n * bags carry the address, so reading them is what keeps this snapshot and\n * the live logger's lines in ONE path space - which is the invariant the\n * whole diff rests on. */\nexport function snapshotState(engine: Engine, flow: Flow): StateSnapshot {\n const out: StateSnapshot = {};\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 for (const { bag } of [...engine.listBags(), ...flow.listBags()]) {\n for (const row of bag.rows()) {\n if (row.value !== undefined) out[row.path] = row.value as ScalarValue;\n }\n }\n Object.assign(out, extraState(engine.saveGame().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// Save-file plumbing over the .storyletsave file (storylets/savefile@1): the\n// HOST's file - the engine's envelope (storylets/save@2; @1 still read) plus,\n// 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, SAVE_SCHEMA_V1 } 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\n || (file.engine?.schema !== SAVE_SCHEMA && file.engine?.schema !== SAVE_SCHEMA_V1)) {\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 // A card played with none (\"\") has no outcome to name.\n case \"play\": return `${stamp}play ${e.card}${e.outcome === \"\" ? \"\" : ` -> ${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, plus\n * \"(durable)\" where the declaration says the value outlives a run\n * (design/engine-server.md 4.2). Nothing is added for the ordinary\n * run-scoped property: that is what a property is. */\nexport function formatPropertySummary(p: PropertySummary): string {\n const options = p.values !== undefined && p.values.length > 0 ? ` [${p.values.join(\", \")}]` : \"\";\n const durable = p.durable === true ? \" (durable)\" : \"\";\n return `${p.name}: ${p.type} = ${showVal(p.default)}${options}${durable}`;\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 // A movable hole is the one thing about a hand its name cannot say: write\n // that property and the hand moves (4.6).\n const moves = hand.movable === undefined ? \"\"\n : `, moves ${hand.movable.map((m) => `${m.group} from ${m.from}`).join(\" and \")}`;\n line(handsBody, `${hand.gameId}: box ${hand.box}, slots ${hand.slots}${template}${moves}`\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}, sites ${map.sites}`);\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 // A timed box says its unit here (design/engine-server.md 4.8), because\n // this is the line an integrator reads to find out what their host has to\n // tick. Nothing is added for an ordinary box: the answer \"a turn is a\n // play\" belongs in the docs, not on every line of every bundle.\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 + (box.turn !== undefined ? `, turn = ${box.turn.seconds}s` : \"\")\n // Only when there are any: a box whose cards all come back with the run\n // has nothing for a server to lift, and the zero would be noise.\n + (box.durableCards !== undefined ? `, durable cards ${box.durableCards}` : \"\"));\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), and since 4.4 that\n// holds for the trace event too: it is forwarded verbatim, and the runtime's\n// own ids are gameIds now, so the rule has no exception left.\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 through engine.hotSwap: a new\n// Engine over the new bundle, carrying the old one's run, on the same registry. 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 through the engine's own\n * `hotSwap`, returning the replacement. Never throws; a failure (unparseable\n * JSON, a bundle the runtime rejects, a different project) comes back as\n * `{ ok: false, error }` and the old engine is left as it was.\n *\n * Works whether the engine made its own registry or was given the game's: on\n * the game's registry the old engine hands its keys to the replacement, which a\n * plain save and load into a second engine cannot do (the two would clash).\n *\n * The engine remembers the options it was built with (seed, log, world,\n * registry), so `opts` is only for overriding one of them for the replacement.\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 // The engine's own hotSwap: on the game's registry the old engine has to hand\n // its keys over, which a plain save and load into a new engine cannot do.\n const { engine: next } = engine.hotSwap(bundle, opts);\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. Writing it\n * DIRECTLY is writing the kernel, so a `writable: false` declaration asks\n * the kernel's question: pass `{ host: true }` to say the game is speaking\n * (`bag.set(name, value, { host: true })`). Through `resolver` or an\n * engine's setProperty that is already answered. */\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.\n *\n * The container is the GAME's state, so it WRITES - even a declaration\n * carrying `writable: false`. That flag is the STORY's promise not to write\n * the value (Reboot.md 10), and the engine keeps it where the story writes: an\n * outcome is refused against the engine's read-only table before it ever\n * reaches this resolver. Enforcing it here as well refused the HOST too - the\n * clock the game must move, the harness driving the value it is testing\n * against - which is the opposite of what the flag says.\n *\n * So the declarations are seeded AS DECLARED, which is what an examiner over\n * this container should read, and the writes go through as HOST writes\n * (scoperegistry 0.6.0's `{ host: true }`). The resolver's `set` is the\n * engine's own doorway and passes the flag too: the engine has already sorted\n * story from host by then - a story write was refused earlier, a host write is\n * the only kind that arrives - and a resolver takes a name and a value with no\n * room to say which. A game wanting a rule of its own binds its own resolver\n * rather than this one; the ports' container (Unreal's UStoryletWorld) draws\n * the same line, with HostSet never refused and StorySet asking the game's own\n * read-only list. */\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, { host: true }); },\n },\n bag,\n values: () => bag.values,\n load: (values) => bag.load(values),\n };\n}\n"],"mappings":"gdAAA,IAAAA,GAAA,GAAAC,GAAAD,GAAA,YAAAE,GAAA,SAAAC,GAAA,oBAAAC,GAAA,eAAAC,GAAA,0BAAAC,GAAA,4BAAAC,EAAA,mBAAAC,GAAA,4BAAAC,GAAA,sBAAAF,GAAA,yBAAAG,GAAA,mBAAAC,GAAA,qBAAAC,GAAA,cAAAC,EAAA,yBAAAC,GAAA,mBAAAC,GAAA,0BAAAC,GAAA,qBAAAC,GAAA,cAAAC,GAAA,aAAAC,EAAA,cAAAC,GAAA,mBAAAC,GAAA,mBAAAC,EAAA,kBAAAC,KCwEO,SAASC,EAAeC,EAAyB,CACtD,OAAQA,EAAK,CAAC,EAAG,CACf,IAAK,IAAO,MAAO,CAAE,KAAM,OAAU,MAAOA,EAAK,CAAC,CAAE,EACpD,IAAK,IAAO,MAAO,CAAE,KAAM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AS,KAAK,MAAMF,CAAU,CAChC,MAAQ,CACN,MAAO,CAAE,GAAI,GAAO,MAAO,iCAAkC,CAC/D,CACA,GAAI,CAGF,GAAM,CAAE,OAAQG,CAAK,EAAIJ,EAAO,QAAQG,EAAQD,CAAI,EACpD,MAAO,CAAE,GAAI,GAAM,OAAQE,EAAM,OAAAD,CAAO,CAC1C,OAASE,EAAG,CACV,MAAO,CAAE,GAAI,GAAO,MAAOA,aAAa,MAAQA,EAAE,QAAU,OAAOA,CAAC,CAAE,CACxE,CACF,CCbO,SAASC,GAAqBC,EAAgC,CACnE,IAAMC,EAAM,IAAIC,EAASF,EAAO,MAAM,WAAY,CAAE,UAAYG,GAAMA,CAAE,CAAC,EACzE,MAAO,CACL,SAAU,CACR,IAAMA,GAAMF,EAAI,IAAIE,CAAC,EACrB,IAAK,CAACA,EAAWC,IAAmB,CAAEH,EAAI,IAAIE,EAAGC,EAAG,CAAE,KAAM,EAAK,CAAC,CAAG,CACvE,EACA,IAAAH,EACA,OAAQ,IAAMA,EAAI,OAClB,KAAOI,GAAWJ,EAAI,KAAKI,CAAM,CACnC,CACF","names":["browser_exports","__export","Engine","Flow","applyLiveBundle","boardFrame","createBundleInspector","createStateLogger","createLiveLink","createPropertyInspector","createWorldContainer","describeBundle","deserializeState","diffState","ensureInspectorStyle","formatLogEntry","formatPropertySummary","formatScopeLabel","loadState","makePrng","saveState","serializeState","shuffleInPlace","snapshotState","deserialiseAst","node","args","EvalError","message","evaluate","node","ctx","dialect","missingPolicy","rec","n","scope","val","arg","ladder","ladderOf","current","stageIndex","def","l","r","left","right","lLadder","rLadder","sameLadder","valueEquals","assertNumbers","a","b","x","y","i","op","value","toUint32","seed","modded","makePrng","s","shuffleInPlace","arr","prng","i","j","CHECK_FLAGS_COUNTING_CALL","node","DEFAULT_COUNTING_CALLS","matchedSpecificity","evalTruthy","opts","countingCalls","walk","want","l","r","rule","c","operands","holds","ENGINE_SCOPES","NEVER_PLAYED","host","h","stringArg","fn","args","i","v","EvalError","flagsArg","OWN_SCOPES","EXTERNAL_SCOPES","ENGINE_SCOPES","s","t","storyletsDialect","token","nextRandom","a","b","lo","hi","flags","arg","result","idx","card","dimension","value","gameIdify","text","effectiveGameId","entity","pinned","gameIdify","valueAddresses","bundle","tags","box","boxGameId","group","tag","gameId","forms","list","print","accept","repeated","candidates","ambiguous","ambiguousValueAddressMessage","segment","name","q","PLACE_GROUP","HOLE_REF","isHoleRef","value","parseHoleRef","m","SAVE_SCHEMA","SAVE_SCHEMA_V1","SAVEFILE_SCHEMA","diffState","prev","next","changes","paths","path","from","to","show","v","prefixOf","m","createStateLogger","adapter","opts","sink","line","label","emit","full","out","prefix","name","value","baseline","pushed","mounted","hook","bag","change","c","mount","mounts","i","diffed","PropertyBag","_PropertyBag","declarations","opts","n","d","name","defaultFor","value","change","audit","fn","rowFor","c","k","values","v","writable","pathPrefix","rowName","lowerCase","SAVE_FRAGMENT_VERSION","ScopeRegistry","token","bag","waiting","e","prefix","key","resolver","o","norm","decls","scope","out","owner","row","host","view","scopes","qualities","normOf","aliases","declsOf","m","properties","vals","blob","fragment","by","wants","tagKey","groupId","tagId","cardIsShared","card","deckShared","sharedCap","OWNER","identity","esc","id","unesc","sharedKey","kind","flowPrefix","flowId","flowKey","emptyPartitionValues","partitionsFromSections","sections","flowIds","shared","flows","rest","flowOf","escaped","p","key","values","m","sectionsOf","keyOf","out","bagFromDecls","decls","pathPrefix","PropertyBag","n","conditionPasses","v","SCOPE_DEFAULT_SHARED","isShared","scope","d","sharedHalf","flowHalf","OWNED_SCOPES","emptyOwnerIndexes","indexOwner","index","entity","gameId","effectiveGameId","indexValueOwners","bundle","addresses","valueAddresses","segment","candidates","handDeclsOf","internals","hand","b","addressOf","resolveOwner","byGameId","ownerOrThrow","name","owner","ambiguousValueAddressMessage","legacyAddressMessage","buildPartition","half","at","box","deck","group","tag","partitionValues","bag","loadPartition","emptyDraft","SORT_SEP","byKey","items","item","a","e","propKey","valueFits","decl","value","f","walkScope","saved","path","flow","draft","byName","clean","walkPartition","savedKind","ids","finishReport","drift","evicted","droppedCooldowns","droppedSpent","droppedProperties","defaultedProperties","retypedProperties","Engine","_Engine","opts","ScopeRegistry","view","event","turn","h","viewRevision","viewCache","reg","ctx","scopes","k","entry","template","declSet","hostWorld","worldDecls","registered","mount","register","story","worldBag","host","sharedDecls","registry","grab","any","x","claim","otherClaims","existing","dealt","Flow","content","keepFlows","cardId","counts","found","parts","perFlow","message","token","add","_prefix","row","mounts","handler","options","snapshot","next","mine","registeredKeys","waiting","report","stillWaiting","SAVE_SCHEMA","envelope","plan","schema","SAVE_SCHEMA_V1","moved","spent","withProps","props","cooldowns","cardName","board","restored","handId","known","kept","engine","seed","makePrng","put","pair","own","keep","boxRef","expr","node","deserialiseAst","ref","g","record","tagIds","cached","made","t","since","NEVER_PLAYED","last","handEnv","others","source","evaluate","storyletsDialect","where","boundTags","askNames","condition","isHoleRef","PLACE_GROUP","criteria","groupRef","tagRef","groupName","parsed","parseHoleRef","wanted","ask","sources","contents","world","home","bound","tags","claimed","trace","verdict","gateOk","scored","deckCtx","refused","priority","spec","matchedSpecificity","i","j","run","shuffleInPlace","s","taken","declared","claimCounts","worldClaims","ordered","listed","handRef","handRefs","conditionOk","evict","reason","survivors","free","taking","added","from","o","outcomeGameId","bare","outcome","perPlay","newTurn","writes","target","prev","outcomeId","change","match","worldSet","boxId","summarise","decls","d","durableCardCount","box","n","deck","card","handDecls","hand","movableHoles","filled","out","groupId","value","isHoleRef","group","g","effectiveGameId","handSlots","declared","t","describeBundle","bundle","boxes","hands","properties","totals","boxGameId","cards","tag","template","movable","push","scope","owner","map","snapshotState","engine","flow","out","bag","row","extraState","saved","boxId","turn","cardId","at","handId","cards","createStateLogger","opts","id","live","serializeState","engine","world","saveState","SAVEFILE_SCHEMA","loadState","file","SAVE_SCHEMA","SAVE_SCHEMA_V1","deserializeState","json","parsed","STYLE_ID","CSS","ensureInspectorStyle","style","eq","a","b","LOG_KINDS","LOG_KIND_LABELS","logKindOf","e","showVal","v","formatLogEntry","formatLogBody","flow","stamp","dealt","c","crit","g","t","listed","groupOf","path","parts","createPropertyInspector","engine","opts","liveFlow","live","el","head","h","saveBtn","blob","serializeState","url","filePicker","file","reader","deserializeState","refresh","loadBtn","filter","editors","groups","lastGroup","row","group","rowEl","buildRow","q","any","show","turnsHead","turnsBody","boardHead","boardBody","check","text","onChange","cls","label","box","buildLogPanel","which","caption","entriesOf","clear","empty","bar","body","kindOn","visibleLines","autoscroll","stampSeen","render","force","entries","lines","kind","on","copyBtn","clearBtn","flowLog","runLog","renderLog","line","parent","div","readLive","hand","cards","names","timer","pollMs","name","current","sync","commit","value","reset","widget","read","focused","w","input","select","o","s","readAll","showVal","v","formatPropertySummary","p","options","durable","formatScopeLabel","scope","group","line","parent","text","cls","div","fold","label","open","details","summary","body","createBundleInspector","bundle","opts","ensureInspectorStyle","description","describeBundle","el","head","h","identity","totals","ident","handsBody","hand","template","moves","m","tagsBody","box","propsBody","mapsBody","map","countsBody","DEFAULT_URL","BOARD_EVENTS","boardFrame","flow","id","hands","hand","cards","c","turns","box","createLiveLink","opts","url","Ctor","queue","sock","closed","build","engine","unsubscribe","announced","flush","m","post","frame","liveFlows","sendHello","flows","hello","f","first","b","postBoard","syncFlows","now","ids","onTrace","flowId","event","ev","msg","detach","next","applyLiveBundle","engine","bundleJson","opts","bundle","next","e","createWorldContainer","bundle","bag","PropertyBag","n","v","values"]}
|
|
1
|
+
{"version":3,"sources":["../src/browser.ts","../../../../expr/packages/expr/src/ast.ts","../../../../expr/packages/expr/src/evaluate.ts","../../../../expr/packages/expr/src/prng.ts","../../../../expr/packages/expr-specificity/src/index.ts","../../dialect/src/engine-scopes.ts","../../dialect/src/index.ts","../../model/src/index.ts","../../../../expr/packages/scoperegistry/src/state-logger.ts","../../../../expr/packages/scoperegistry/src/index.ts","../../runtime/src/engine.ts","../../runtime/src/describe.ts","../src/logger.ts","../src/save.ts","../src/inspector.ts","../src/bundle-inspector.ts","../src/live-link.ts","../src/refresh.ts","../src/world.ts"],"sourcesContent":["// The browser drop-in: ONE classic script, no build step, defining the\n// `StoryletEngine` global with the runtime AND these helpers on it, so a plain\n// page can build an engine, deal, play, and save and load the family's\n// .storyletsave text, all from two script tags (this and Patterplay's).\n//\n// Built by this package rather than the runtime because this is the one\n// package that depends on both: the runtime cannot bundle the helpers without\n// bundling itself twice. The export names of the two do not overlap (checked\n// 2026-09-04), so `export *` from each is exact.\nexport * from \"@storylet-studio/runtime\";\nexport * from \"./index.js\";\n","// ---------------------------------------------------------------------------\n// AST - the in-memory expression tree and its serialised tagged-tuple form.\n//\n// The in-memory `ExprNode` is a discriminated union (kind field). The published\n// `AstNode` is the compact tagged-tuple form that goes into a compiled bundle's\n// { src, ast } envelope - what a runtime walks, never parses.\n//\n// This module is dialect-agnostic: scope tokens and function names are plain\n// strings here; meaning is supplied by a Dialect (see dialect.ts).\n// ---------------------------------------------------------------------------\n\nexport type ScalarValue = boolean | number | string | string[];\n\nexport type BinaryOp =\n | \"==\" | \"!=\" | \">\" | \">=\" | \"<\" | \"<=\"\n | \"+\" | \"-\" | \"*\" | \"/\"\n | \"and\" | \"or\";\n\nexport type UnaryOp = \"not\" | \"neg\";\n\nexport type ExprNode =\n | { kind: \"bool\"; value: boolean }\n | { kind: \"number\"; value: number }\n | { kind: \"string\"; value: string }\n // All property references are scoped: bare `@name` is canonicalised to\n // `@<defaultScope>.name` at parse time. Names are lowercased at parse time.\n | { kind: \"scopedvar\"; scope: string; name: string }\n | { kind: \"call\"; name: string; args: ExprNode[] }\n | { kind: \"unary\"; op: UnaryOp; operand: ExprNode }\n | { kind: \"binary\"; op: BinaryOp; left: ExprNode; right: ExprNode }\n // Produced only by flag-delta function argument parsing (see Dialect\n // `flagDeltaArgs`) - not valid elsewhere.\n | { kind: \"flagdelta\"; sign: \"+\" | \"-\"; name: string };\n\n/**\n * Path into an ExprNode tree. Each segment names the field on the parent node,\n * with numeric indices for array elements (call args).\n * binary.left -> [\"left\"]\n * binary.right.args[0] -> [\"right\", \"args\", 0]\n * top-level node -> []\n */\nexport type AstPath = readonly (string | number)[];\n\n// ---------------------------------------------------------------------------\n// Published tagged-tuple form (JSON arrays, opcode at index 0).\n// ---------------------------------------------------------------------------\n\nexport type AstNode =\n | [\"b\", boolean]\n | [\"n\", number]\n | [\"s\", string]\n | [\"sv\", string, string]\n | [\"u\", UnaryOp, AstNode]\n | [\"bin\", BinaryOp, AstNode, AstNode]\n | [\"call\", string, ...AstNode[]]\n | [\"fd\", \"+\" | \"-\", string];\n\n/** In-memory ExprNode -> published tagged-tuple AstNode. */\nexport function serialiseAst(node: ExprNode): AstNode {\n switch (node.kind) {\n case \"bool\": return [\"b\", node.value];\n case \"number\": return [\"n\", node.value];\n case \"string\": return [\"s\", node.value];\n case \"scopedvar\": return [\"sv\", node.scope, node.name];\n case \"unary\": return [\"u\", node.op, serialiseAst(node.operand)];\n case \"binary\": return [\"bin\", node.op, serialiseAst(node.left), serialiseAst(node.right)];\n case \"call\": return [\"call\", node.name, ...node.args.map(serialiseAst)];\n case \"flagdelta\": return [\"fd\", node.sign, node.name];\n }\n}\n\n/** Published tagged-tuple AstNode -> in-memory ExprNode. */\nexport function deserialiseAst(node: AstNode): ExprNode {\n switch (node[0]) {\n case \"b\": return { kind: \"bool\", value: node[1] };\n case \"n\": return { kind: \"number\", value: node[1] };\n case \"s\": return { kind: \"string\", value: node[1] };\n case \"sv\": return { kind: \"scopedvar\", scope: node[1], name: node[2] };\n case \"u\": return { kind: \"unary\", op: node[1], operand: deserialiseAst(node[2]) };\n case \"bin\": return { kind: \"binary\", op: node[1], left: deserialiseAst(node[2]), right: deserialiseAst(node[3]) };\n case \"call\": {\n const args = (node.slice(2) as AstNode[]).map(deserialiseAst);\n return { kind: \"call\", name: node[1], args };\n }\n case \"fd\": return { kind: \"flagdelta\", sign: node[1], name: node[2] };\n }\n}\n","// ---------------------------------------------------------------------------\n// Evaluator - walk an ExprNode against an EvalContext, parameterised by Dialect.\n//\n// Operators (binary/unary), short-circuiting, and type-checking are generic.\n// Scope resolution uses the context's scope maps + the Dialect's per-scope\n// missing-property policy. Function calls dispatch to the Dialect's functions.\n//\n// Ported from @storylets/engine (storylets/packages/engine/src/expression.ts),\n// generalised by injecting scopes + functions from the Dialect.\n// ---------------------------------------------------------------------------\n\nimport type { ExprNode, ScalarValue } from \"./ast.js\";\nimport type { Dialect, EvalContext, ScopeResolver } from \"./dialect.js\";\n\nexport class EvalError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"EvalError\";\n }\n}\n\nexport function evaluate(node: ExprNode, ctx: EvalContext, dialect: Dialect): ScalarValue {\n // Per-scope missing-property policy, precomputed once per top-level evaluate.\n const missingPolicy = new Map<string, \"false\" | \"throw\">(\n dialect.scopes.map((s) => [s.token, s.missing ?? \"false\"])\n );\n\n const rec = (n: ExprNode): ScalarValue => {\n switch (n.kind) {\n case \"bool\": return n.value;\n case \"number\": return n.value;\n case \"string\": return n.value;\n\n case \"scopedvar\": {\n const scope = ctx.scopes[n.scope];\n if (scope === undefined) {\n // Scope context absent -> graceful false. (A scope the dialect knows\n // about but the context didn't populate, or an unknown scope.)\n return false;\n }\n // A scope is either a static bag or a host resolver ({ get }). Bag values\n // are always ScalarValue (never functions), so a `get` function reliably\n // distinguishes a resolver.\n const val = typeof (scope as ScopeResolver).get === \"function\"\n ? (scope as ScopeResolver).get(n.name)\n : (scope as Record<string, ScalarValue>)[n.name];\n if (val === undefined) {\n // Property not declared on the present scope. Policy decides: \"false\"\n // for back-compat scopes, \"throw\" for scopes where a missing key is a\n // bug publish-time validation should have caught.\n if (missingPolicy.get(n.scope) === \"throw\") {\n throw new EvalError(`@${n.scope}.${n.name} is not declared on the current ${n.scope}.`);\n }\n return false;\n }\n return val;\n }\n\n case \"call\": {\n // `advance` is the language's own, the first core built-in: the next\n // stage in the argument's ladder, saturating at the last. Core rather\n // than dialect because it IS the quality design's insertion mechanism\n // (an outcome that never names its destination routes through an\n // inserted stage automatically), and every dialect should say it the\n // same way. A dialect that defines its own `advance` wins, for\n // back-compat with any dialect that already had one.\n if (n.name === \"advance\" && !dialect.functions[n.name]) {\n const arg = n.args[0];\n if (n.args.length !== 1 || arg === undefined) {\n throw new EvalError(`advance() takes exactly 1 argument, got ${n.args.length}`);\n }\n const ladder = ladderOf(arg, ctx);\n if (ladder === undefined) {\n throw new EvalError(\"advance() needs a quality reference (@scope.name of a quality property)\");\n }\n const current = stageIndex(rec(arg), ladder, \"advance\");\n return ladder[Math.min(current + 1, ladder.length - 1)]!;\n }\n const def = dialect.functions[n.name];\n if (!def) throw new EvalError(`unknown function '${n.name}'`);\n return def.eval(n.args, { evaluate: rec, ctx });\n }\n\n case \"flagdelta\":\n throw new EvalError(\"flagdelta node is only valid as an argument to a flag-delta function\");\n\n case \"unary\": {\n if (n.op === \"not\") {\n const val = rec(n.operand);\n if (typeof val !== \"boolean\") throw new EvalError(`'not' requires a boolean operand, got ${typeof val}`);\n return !val;\n }\n // neg\n const val = rec(n.operand);\n if (typeof val !== \"number\") throw new EvalError(`unary '-' requires a numeric operand, got ${typeof val}`);\n return -val;\n }\n\n case \"binary\": {\n // Short-circuit operators first\n if (n.op === \"and\") {\n const l = rec(n.left);\n if (typeof l !== \"boolean\") throw new EvalError(`'and' requires boolean operands, left is ${typeof l}`);\n if (!l) return false;\n const r = rec(n.right);\n if (typeof r !== \"boolean\") throw new EvalError(`'and' requires boolean operands, right is ${typeof r}`);\n return r;\n }\n if (n.op === \"or\") {\n const l = rec(n.left);\n if (typeof l !== \"boolean\") throw new EvalError(`'or' requires boolean operands, left is ${typeof l}`);\n if (l) return true;\n const r = rec(n.right);\n if (typeof r !== \"boolean\") throw new EvalError(`'or' requires boolean operands, right is ${typeof r}`);\n return r;\n }\n\n const left = rec(n.left);\n const right = rec(n.right);\n\n // Quality: when either operand REFERENCES a quality (the node carries\n // the scope+name the channel resolves), ordering compares by ladder\n // position and arithmetic is refused. Everything else is untouched,\n // so a context with no channel behaves exactly as before.\n const lLadder = ladderOf(n.left, ctx);\n const rLadder = ladderOf(n.right, ctx);\n const ladder = lLadder ?? rLadder;\n if (ladder !== undefined) {\n if (lLadder && rLadder && !sameLadder(lLadder, rLadder)) {\n if (n.op === \">\" || n.op === \">=\" || n.op === \"<\" || n.op === \"<=\") {\n throw new EvalError(`'${n.op}' compares two different qualities, whose stage orders are unrelated`);\n }\n }\n switch (n.op) {\n case \">\": return stageIndex(left, ladder, \">\") > stageIndex(right, ladder, \">\");\n case \">=\": return stageIndex(left, ladder, \">=\") >= stageIndex(right, ladder, \">=\");\n case \"<\": return stageIndex(left, ladder, \"<\") < stageIndex(right, ladder, \"<\");\n case \"<=\": return stageIndex(left, ladder, \"<=\") <= stageIndex(right, ladder, \"<=\");\n case \"+\": case \"-\": case \"*\": case \"/\":\n throw new EvalError(`'${n.op}' cannot be applied to a quality - a stage is a position, not a number; use advance() to move it`);\n default: break; // == and != fall through to plain value equality\n }\n }\n\n switch (n.op) {\n case \"==\": return valueEquals(left, right);\n case \"!=\": return !valueEquals(left, right);\n case \">\": assertNumbers(left, right, \">\"); return (left as number) > (right as number);\n case \">=\": assertNumbers(left, right, \">=\"); return (left as number) >= (right as number);\n case \"<\": assertNumbers(left, right, \"<\"); return (left as number) < (right as number);\n case \"<=\": assertNumbers(left, right, \"<=\"); return (left as number) <= (right as number);\n case \"+\":\n if (typeof left === \"number\" && typeof right === \"number\") return left + right;\n if (typeof left === \"string\" && typeof right === \"string\") return left + right;\n throw new EvalError(`'+' requires two numbers or two strings, got ${typeof left} and ${typeof right}`);\n case \"-\": assertNumbers(left, right, \"-\"); return (left as number) - (right as number);\n case \"*\": assertNumbers(left, right, \"*\"); return (left as number) * (right as number);\n case \"/\":\n assertNumbers(left, right, \"/\");\n if ((right as number) === 0) throw new EvalError(\"division by zero\");\n return (left as number) / (right as number);\n }\n }\n }\n };\n\n return rec(node);\n}\n\n/**\n * Equality for `==` / `!=`. Primitives compare by value (JS `===`); arrays\n * (the flags value type) compare as SETS: same members, ORDER IRRELEVANT.\n *\n * Plain `===` on arrays would be reference equality - two distinct arrays with\n * the same contents would never be equal, and a fresh array (from a scope read\n * or a function result) would never equal another. Mixed array/non-array\n * operands are unequal, and never an error.\n *\n * Order was significant until 2026-09-01, and that was wrong: a flags value IS\n * a set, and its stored order is an artefact of the order somebody happened to\n * add things in. `set_flags(@f, +a)` then `+b` compared UNEQUAL to the same two\n * flags added the other way round, which is a difference no author can see and\n * none intends. The Storylet Engine papered over it by sorting in `set_flags`,\n * which only holds while every producer sorts: a bundle's declared default, or\n * a host handing a list in, does not.\n *\n * Compared as MULTISETS (sorted copies), so a duplicated flag still counts. A\n * well-formed flags value has no duplicates, but equality should not be the\n * thing that decides what happens if one appears.\n */\nfunction valueEquals(a: ScalarValue, b: ScalarValue): boolean {\n if (Array.isArray(a) || Array.isArray(b)) {\n if (!Array.isArray(a) || !Array.isArray(b)) return false;\n if (a.length !== b.length) return false;\n const x = [...a].sort();\n const y = [...b].sort();\n for (let i = 0; i < x.length; i++) if (x[i] !== y[i]) return false;\n return true;\n }\n return a === b;\n}\n\nfunction assertNumbers(l: ScalarValue, r: ScalarValue, op: string): void {\n if (typeof l !== \"number\" || typeof r !== \"number\") {\n throw new EvalError(`'${op}' requires numeric operands, got ${typeof l} and ${typeof r}`);\n }\n}\n\n// --- quality (design: storylets-new/design/quality.md) -----------------------\n\n/** The ladder behind an operand NODE, when the context's quality channel says\n * it references a quality. Values are plain strings; the node is what carries\n * the (scope, name) the channel needs. */\nfunction ladderOf(node: ExprNode, ctx: EvalContext): readonly string[] | undefined {\n if (node.kind !== \"scopedvar\" || ctx.qualities === undefined) return undefined;\n return ctx.qualities(node.scope, node.name);\n}\n\n/** Index of a stage in a ladder; an unknown stage is an error naming the\n * value, never a silent pass (a drifted save is exactly what lands here). */\nfunction stageIndex(value: ScalarValue, ladder: readonly string[], op: string): number {\n if (typeof value !== \"string\") {\n throw new EvalError(`'${op}' on a quality compares stages, got ${typeof value}`);\n }\n const i = ladder.indexOf(value);\n if (i < 0) throw new EvalError(`\"${value}\" is not a stage of this quality (stages: ${ladder.join(\", \")})`);\n return i;\n}\n\nconst sameLadder = (a: readonly string[], b: readonly string[]): boolean =>\n a.length === b.length && a.every((x, i) => x === b[i]);\n","// ---------------------------------------------------------------------------\n// mulberry32 - the contractual PRNG.\n//\n// A fixed, published algorithm that both product families need and neither\n// owns. It lived in `@storylet-studio/runtime` as prng.ts and inline in\n// `@patterkit/runtime`'s engine.ts, plus separately in three of Patterplay's\n// harnesses, plus a hand port in each of six native runtimes: thirteen copies\n// of forty lines. It belongs here, in the package both families already depend\n// on, for the same reason the evaluator does.\n//\n// All arithmetic is unsigned 32-bit, matching JavaScript's `>>> 0` and\n// Math.imul.\n// ---------------------------------------------------------------------------\n\nexport interface Prng {\n /** One draw in [0, 1); advances the state. */\n next(): number;\n /** The persisted state (a uint32; feed back into makePrng to restore). */\n state(): number;\n}\n\n/**\n * ECMA-262 7.1.6 ToUint32, which is what `seed >>> 0` means.\n *\n * Written out rather than spelled `seed >>> 0` because THIS is the obligation a\n * port in a language without JavaScript's shift semantics has to reproduce, and\n * the shorthand hides it. Patterplay's C++ port cast the seed straight to an\n * integer type, which is undefined behaviour outside that type's range and gave\n * two wrong answers before the parity corpus pinned them.\n */\nexport function toUint32(seed: number): number {\n if (Number.isNaN(seed) || !Number.isFinite(seed)) return 0;\n const modded = Math.trunc(seed) % 4294967296;\n return modded < 0 ? modded + 4294967296 : modded;\n}\n\n/**\n * Seed a generator. The state is UNSIGNED throughout (`>>> 0`, never `| 0`):\n * the two produce identical draws and differ only in the sign of the number a\n * save persists, and Patterplay shipped `| 0` for long enough that over half of\n * all its saves carried a negative state its own native ports could not read\n * back.\n */\nexport function makePrng(seed: number): Prng {\n let s = toUint32(seed);\n return {\n next(): number {\n s = (s + 0x6d2b79f5) >>> 0;\n let t = Math.imul(s ^ (s >>> 15), 1 | s);\n t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;\n return ((t ^ (t >>> 14)) >>> 0) / 4294967296;\n },\n state(): number {\n return s;\n },\n };\n}\n\n/** The contractual shuffle: Fisher-Yates, descending. Runs of one element\n * consume no draws (the loop never executes for length < 2). */\nexport function shuffleInPlace<T>(arr: T[], prng: Prng): void {\n for (let i = arr.length - 1; i > 0; i--) {\n const j = Math.floor(prng.next() * (i + 1));\n [arr[i], arr[j]] = [arr[j]!, arr[i]!];\n }\n}\n","// ---------------------------------------------------------------------------\n// @wildwinter/expr-specificity - public surface.\n//\n// Matched-constraint specificity: score how many atomic constraints in an\n// expression are actively holding it true against the current state. An\n// evaluation-aware walk (unlike a static clause count, an `or`'s score depends\n// on which branch is currently matching). Shared by Storylet Studio (storylet\n// draw priority) and Patter (dialogue best-match), which had independently\n// grown the same algorithm.\n//\n// Built on @wildwinter/expr's `ExprNode`. The host supplies truthiness via an\n// `evalTruthy` closure, so this package stays ignorant of the eval context,\n// the dialect, and the host's truthiness rule - each host keeps its own\n// behaviour while sharing one definition of the walk.\n// ---------------------------------------------------------------------------\n\nimport type { ExprNode } from \"@wildwinter/expr\";\n\n/** A call node, narrowed from the ExprNode union. */\ntype CallNode = Extract<ExprNode, { kind: \"call\" }>;\n\n/**\n * Evaluate an expression subtree to a boolean. Host-bound: the host closes over\n * its own evaluate + eval context + dialect and applies its own truthiness\n * coercion (Storylets' `conditionPasses`, Patter's `truthy`, etc.).\n */\nexport type EvalTruthy = (node: ExprNode) => boolean;\n\n/**\n * A call treated as a conjunction of constraints rather than a single atom, so\n * it contributes its operand count instead of 1. `check_flags` is the built-in\n * example (see {@link CHECK_FLAGS_COUNTING_CALL}).\n */\nexport interface CountingCall {\n /** The function name this rule applies to. */\n name: string;\n /** How many constraints the call contributes when it holds (at least 1). */\n count: (node: CallNode) => number;\n}\n\nexport interface MatchedSpecificityOptions {\n /**\n * Root polarity - the truth value the whole condition must have. Production\n * only ever scores conditions already known eligible, so this defaults to\n * `true` and rarely needs setting.\n */\n want?: boolean;\n /**\n * Calls scored by operand count rather than as a single atom. Defaults to\n * `[CHECK_FLAGS_COUNTING_CALL]`. Supply your own to add or replace rules.\n */\n countingCalls?: readonly CountingCall[];\n}\n\n/**\n * `check_flags(v, f1..fN)` counts as N constraints - an N-ary AND over the flag\n * operands - never fewer than 1. `args[0]` is the flags source, so the operand\n * count is `args.length - 1`.\n */\nexport const CHECK_FLAGS_COUNTING_CALL: CountingCall = {\n name: \"check_flags\",\n count: (node) => Math.max(1, node.args.length - 1),\n};\n\nconst DEFAULT_COUNTING_CALLS: readonly CountingCall[] = [CHECK_FLAGS_COUNTING_CALL];\n\n/**\n * Score how many atomic constraints in `node` are actively holding it true\n * against current state, via `evalTruthy`.\n *\n * The walk carries a polarity flag `want` (\"the truth value this subtree must\n * have for the whole to hold\"), applying De Morgan as it descends:\n * - atom: 1 if its truth matches `want`, else 0\n * - and: under `want`, both must hold -> sum; under `!want`, behaves as or\n * - or: under `want`, strongest branch -> max; under `!want`, behaves as and\n * - not: recurse with `want` flipped\n * - counting call (e.g. check_flags): its operand count when it must hold and\n * does, else the negated rules apply\n *\n * @example\n * // `@x == 5 and @y > 3` with both holding -> 2\n * matchedSpecificity(ast, node => conditionPasses(evaluate(node, ctx)))\n */\nexport function matchedSpecificity(\n node: ExprNode,\n evalTruthy: EvalTruthy,\n opts?: MatchedSpecificityOptions,\n): number {\n const countingCalls = opts?.countingCalls ?? DEFAULT_COUNTING_CALLS;\n return walk(node, opts?.want ?? true, evalTruthy, countingCalls);\n}\n\nfunction walk(\n node: ExprNode,\n want: boolean,\n evalTruthy: EvalTruthy,\n countingCalls: readonly CountingCall[],\n): number {\n if (node.kind === \"binary\" && (node.op === \"and\" || node.op === \"or\")) {\n const l = walk(node.left, want, evalTruthy, countingCalls);\n const r = walk(node.right, want, evalTruthy, countingCalls);\n // De Morgan: an `and` under negation behaves like an `or`, and vice versa.\n const behaveAsAnd = (node.op === \"and\") === want;\n if (behaveAsAnd) return l > 0 && r > 0 ? l + r : 0; // both must hold -> sum\n return Math.max(l, r); // either holds -> strongest branch\n }\n if (node.kind === \"unary\" && node.op === \"not\") {\n return walk(node.operand, !want, evalTruthy, countingCalls);\n }\n if (node.kind === \"call\") {\n const rule = countingCalls.find((c) => c.name === node.name);\n if (rule) {\n const operands = rule.count(node);\n const holds = evalTruthy(node);\n if (want) return holds ? operands : 0;\n return holds ? 0 : 1; // negated: De Morgan -> at least one operand fails -> 1\n }\n }\n // Any other node is an atom worth one constraint when its truth matches want.\n return evalTruthy(node) === want ? 1 : 0;\n}\n","// GENERATED - vendored from expr/family/engine-scopes.json by scripts/sync-conformance.mjs.\n// Do not edit here; edit the shared list and re-run the script.\n\n/** Every engine's game-wide scope token across the family. A compiler accepts every token here\n * that is not its own engine's, unchecked: the other engine owns those names and types. */\nexport interface EngineScope {\n token: string;\n engine: string;\n means: string;\n}\n\nexport const ENGINE_SCOPES: readonly EngineScope[] = [\n { token: \"patter\", engine: \"Patterplay\", means: \"Patter's shared globals\" },\n { token: \"story\", engine: \"Storylet Engine\", means: \"the Storylet Engine's shared @story properties\" },\n];\n","// ---------------------------------------------------------------------------\n// @storylet-studio/dialect - the storylets expression dialect.\n//\n// One dialect drives runtime eval AND publish-time validation (schema 6.1).\n// Five scopes, fixed (Reboot 3); bare `@name` is `@story.name` (schema 6.2,\n// resolved 2026-07-19). Function eval semantics carry from the old engine's\n// storylets-dialect.ts where the function survives (random, check_flags,\n// set_flags); the play-history functions are the new set pinned in schema 6.3.\n// ---------------------------------------------------------------------------\n\nimport { EvalError } from \"@wildwinter/expr\";\nimport { ENGINE_SCOPES } from \"./engine-scopes.js\";\nexport { ENGINE_SCOPES } from \"./engine-scopes.js\";\nexport type { EngineScope } from \"./engine-scopes.js\";\nimport type { Dialect, EvalHelpers, ExprNode, ScalarValue } from \"@wildwinter/expr\";\n\n/** turns_since_played / _in when the card / value has never been played. */\nexport const NEVER_PLAYED = 9999;\n\n/**\n * Host callbacks the dialect's functions read from `EvalContext.host`. The\n * runtime supplies these (its PRNG, its play log); the compiler validates\n * without them.\n */\nexport interface StoryletsHost {\n /** One PRNG draw in [0, 1) - the session mulberry32 (schema 3.3). */\n nextRandom(): number;\n /** Plays of the card (gameId) from the play log. */\n countPlayed(card: string): number;\n /** Turns since the card (gameId) last played; NEVER_PLAYED when never. */\n turnsSincePlayed(card: string): number;\n /** Plays of cards belonging to the dimension value (both by gameId). */\n countPlayedIn(dimension: string, value: string): number;\n /** As above; NEVER_PLAYED when never. */\n turnsSincePlayedIn(dimension: string, value: string): number;\n}\n\nconst host = (h: EvalHelpers): Partial<StoryletsHost> =>\n (h.ctx.host ?? {}) as Partial<StoryletsHost>;\n\nconst stringArg = (fn: string, args: ExprNode[], h: EvalHelpers, i: number): string => {\n const v = h.evaluate(args[i]!);\n if (typeof v !== \"string\" || v === \"\") {\n throw new EvalError(`${fn}() argument ${i + 1} must be a non-empty string`);\n }\n return v;\n};\n\n/** Resolve the first argument of check_flags / set_flags to a flag set. */\nconst flagsArg = (fn: string, args: ExprNode[], h: EvalHelpers): string[] => {\n if (args.length === 0) {\n throw new EvalError(`${fn}() requires at least one argument (the flags property)`);\n }\n const v = h.evaluate(args[0]!);\n if (Array.isArray(v)) return v as string[];\n // An unset flags property may surface as false; treat as the empty set\n // (carried from the old dialect). Anything else is a type error.\n if (v === false) return [];\n throw new EvalError(`${fn}() first argument must be a flags property`);\n};\n\n/** The Storylet Engine's own five scope tokens. */\nexport const OWN_SCOPES = [\"story\", \"world\", \"box\", \"deck\", \"hand\"] as const;\n\n/**\n * Other engines' game-wide scopes a card may name, from the family's shared list\n * (expr/family/engine-scopes.json): `@patter.gold` reads Patterplay's shared\n * globals in a game that runs both. On by default, with no project setting, so\n * combining the engines needs no wiring. The compiler lets these through\n * unchecked (the other engine owns its names and types), and the engine reports\n * at run time when the game has not registered one.\n */\nexport const EXTERNAL_SCOPES: readonly string[] = ENGINE_SCOPES\n .map((s) => s.token)\n .filter((t) => !(OWN_SCOPES as readonly string[]).includes(t));\n\nexport const storyletsDialect: Dialect = {\n // A missing property in a PRESENT scope is always an error: every property\n // is declared with a default, so absence means a publish bug, a drifted\n // save, or a foreign scope the host never fed (schema 6.2). The same holds\n // for another engine's scope: `@patter.glod` is a typo, and it says so the\n // first time the card is evaluated rather than quietly reading false.\n scopes: [\n ...OWN_SCOPES.map((token) => ({ token, missing: \"throw\" as const })),\n ...EXTERNAL_SCOPES.map((token) => ({ token, missing: \"throw\" as const })),\n ],\n defaultScope: \"story\",\n functions: {\n random: {\n minArgs: 2, maxArgs: 2, returnType: \"number\",\n eval(args: ExprNode[], h: EvalHelpers): ScalarValue {\n if (args.length !== 2) throw new EvalError(\"random(a, b) requires exactly 2 arguments\");\n const nextRandom = host(h).nextRandom;\n if (!nextRandom) throw new EvalError(\"random() called without a PRNG in context\");\n const a = h.evaluate(args[0]!);\n const b = h.evaluate(args[1]!);\n if (typeof a !== \"number\" || typeof b !== \"number\") {\n throw new EvalError(\"random(a, b) arguments must be numbers\");\n }\n if (!Number.isInteger(a) || !Number.isInteger(b)) {\n throw new EvalError(\"random(a, b) arguments must be integers\");\n }\n const lo = Math.min(a, b);\n const hi = Math.max(a, b);\n return Math.floor(nextRandom() * (hi - lo + 1)) + lo;\n },\n },\n check_flags: {\n minArgs: 1, returnType: \"boolean\", flagDeltaArgs: true,\n eval(args: ExprNode[], h: EvalHelpers): ScalarValue {\n const flags = flagsArg(\"check_flags\", args, h);\n for (let i = 1; i < args.length; i++) {\n const arg = args[i]!;\n if (arg.kind !== \"flagdelta\") {\n throw new EvalError(\"check_flags() flag args must be +flagName or -flagName\");\n }\n if (arg.sign === \"+\" ? !flags.includes(arg.name) : flags.includes(arg.name)) {\n return false;\n }\n }\n return true;\n },\n },\n set_flags: {\n minArgs: 1, returnType: \"flags\", flagDeltaArgs: true,\n eval(args: ExprNode[], h: EvalHelpers): ScalarValue {\n const result = [...flagsArg(\"set_flags\", args, h)];\n for (let i = 1; i < args.length; i++) {\n const arg = args[i]!;\n if (arg.kind !== \"flagdelta\") {\n throw new EvalError(\"set_flags() flag args must be +flagName or -flagName\");\n }\n if (arg.sign === \"+\") {\n if (!result.includes(arg.name)) result.push(arg.name);\n } else {\n const idx = result.indexOf(arg.name);\n if (idx >= 0) result.splice(idx, 1);\n }\n }\n // Sorted so a SAVE is deterministic: the same flags reached by different routes\n // serialise to the same bytes, which keeps save diffs and cross-runtime byte\n // comparisons stable. It is no longer what makes equality work - flags compare\n // as a SET since 2026-09-01 - so this is now about the stored form only, and\n // Patterplay not sorting is a difference that costs nothing.\n return result.sort();\n },\n },\n count_played: {\n minArgs: 1, maxArgs: 1, returnType: \"number\",\n eval(args: ExprNode[], h: EvalHelpers): ScalarValue {\n const card = stringArg(\"count_played\", args, h, 0);\n const fn = host(h).countPlayed;\n if (!fn) throw new EvalError(\"count_played() called without a play log in context\");\n return fn(card);\n },\n },\n turns_since_played: {\n minArgs: 1, maxArgs: 1, returnType: \"number\",\n eval(args: ExprNode[], h: EvalHelpers): ScalarValue {\n const card = stringArg(\"turns_since_played\", args, h, 0);\n const fn = host(h).turnsSincePlayed;\n if (!fn) throw new EvalError(\"turns_since_played() called without a play log in context\");\n return fn(card);\n },\n },\n count_played_in: {\n minArgs: 2, maxArgs: 2, returnType: \"number\",\n eval(args: ExprNode[], h: EvalHelpers): ScalarValue {\n const dimension = stringArg(\"count_played_in\", args, h, 0);\n const value = stringArg(\"count_played_in\", args, h, 1);\n const fn = host(h).countPlayedIn;\n if (!fn) throw new EvalError(\"count_played_in() called without a play log in context\");\n return fn(dimension, value);\n },\n },\n turns_since_played_in: {\n minArgs: 2, maxArgs: 2, returnType: \"number\",\n eval(args: ExprNode[], h: EvalHelpers): ScalarValue {\n const dimension = stringArg(\"turns_since_played_in\", args, h, 0);\n const value = stringArg(\"turns_since_played_in\", args, h, 1);\n const fn = host(h).turnsSincePlayedIn;\n if (!fn) throw new EvalError(\"turns_since_played_in() called without a play log in context\");\n return fn(dimension, value);\n },\n },\n },\n};\n\n/**\n * The dialect, also accepting the game-wide scopes `tokens` names: every token a game's\n * shared scopes folder declares (`game-scopes/`, patterkit design/shared-scopes.md), so a\n * game's own scope such as `@player` parses where the shared vocabulary alone would not. A\n * token the dialect already has keeps its place and its policy; each new one gets the policy\n * another engine's scope has, since whoever declared it owns its names. With nothing new to\n * add this is `storyletsDialect` itself, so a project with no shared folder compiles exactly\n * as before. For editing and publishing only: a runtime evaluates a compiled bundle, which\n * names its scopes already.\n */\nexport function storyletsDialectWith(tokens: readonly string[]): Dialect {\n const known = new Set(storyletsDialect.scopes.map((s) => s.token));\n const added = [...new Set(tokens)].filter((t) => !known.has(t));\n if (added.length === 0) return storyletsDialect;\n return {\n ...storyletsDialect,\n scopes: [...storyletsDialect.scopes, ...added.map((token) => ({ token, missing: \"throw\" as const }))],\n };\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 /**\n * The durability axis (design/engine-server.md 4.2), valid wherever `shared`\n * is valid and orthogonal to it: `shared` says whose value this is WITHIN a\n * run, `durable` says whether the value survives the run at all. A durable\n * shared property is the installation's memory (\"trolls defeated since we\n * opened\"); a durable per-flow one is the player's pocket (visits,\n * allegiance, what they earned).\n *\n * INERT TO THE RUNTIME. The engine partitions by `shared` alone and never\n * reads this. Durability is what the SERVER does at a run boundary: it reads\n * the declarations, lifts the durable values out of the partitions before the\n * world restarts, and writes them back into the fresh engine afterwards,\n * entirely through `getProperty` / `setProperty`.\n *\n * On a `@world` declaration the flag is a validation error, for the reason\n * `shared` is: @world is the game's own state, and how long the game keeps it\n * is the game's business.\n */\n durable?: boolean;\n purpose?: string;\n}\n\n/** A template field (box-defined), of the card template or of the outcome\n * fields. Data for the host; the engine never interprets fields and they are\n * 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// --- the value scope's owner segment (design/engine-server.md 4.4) -----------\n//\n// Every other owned scope names its owner with a gameId that is unique across\n// the bundle: box, deck, hand and card. A TAG's gameId is unique only within\n// its group, and a group's only within its box, so two boxes may each name a\n// tag \"docks\" - as ordinary as two boxes each having a \"zone\" group - and\n// `value.docks.danger` then names two stores.\n//\n// So the value scope's owner segment is box-qualified where it has to be:\n// `value.<boxGameId>/<tagGameId>.<name>`. The slash sits INSIDE the owner\n// segment, so the address still splits into three on the dot and no parser\n// changes shape. The qualified form is always accepted; the short form is\n// accepted while exactly one tag in the bundle carries that gameId, and\n// refused when more do, naming the qualified candidates. What a runtime\n// PRINTS - `listProperties`, a write on the trace, a load report, an\n// examiner - is the short form except where the gameId repeats.\n//\n// One definition, because the Board draws these addresses from the bundle\n// while the engine builds them from its own index, and an address the editor\n// shows that the engine will not take is the fault 4.4 was fixing.\n\n// A ZONE of the project map (design/project-map-contract.md 3.4) is the one\n// tag with no qualified form: it belongs to no box, so it prints and is\n// accepted as `value.<zoneGameId>.<name>` whichever boxes use it. Nothing can\n// make that ambiguous, because no box tag may share a zone's gameId (refused\n// by the compiler and again by the engine at load). A box-qualified form that\n// names a zone is REFUSED rather than accepted for old times' sake: there is\n// no old project to be kind to, and the qualified form would assert a box the\n// zone does not have.\n\n/** The answers a value address needs, all derived from the bundle. */\nexport interface ValueAddresses {\n /** Tag internal id -> the owner segment an address PRINTS for it. */\n print: Map<string, string>;\n /** Every owner segment a value address ACCEPTS -> the tag's internal id.\n * Holds the qualified form for every box tag, the short form only for a\n * gameId no other box tag shares, and the short form of every zone. */\n accept: Map<string, string>;\n /** A tag gameId more than one box uses -> its qualified forms, in bundle\n * order. Empty for the overwhelming majority of projects, and what a\n * refusal lists. Never holds a zone. */\n repeated: Map<string, string[]>;\n /** A box-qualified segment that names a project-map zone\n * (`\"box/quay\"`) -> the zone's own segment (`\"quay\"`), the one an\n * address must use instead. One entry per box and zone, so a refusal can\n * name the address that works without working it out again. Empty when\n * the bundle has no map. */\n zoneQualified: Map<string, string>;\n}\n\n/** The owner segment of every tag in the bundle, both ways round: the boxes'\n * tags, then the project map's zones. */\nexport function valueAddresses(bundle: {\n boxes: readonly { id: string; gameId?: string; title?: string; tagGroups: readonly TagGroup[] }[];\n map?: { group: TagGroup };\n}): ValueAddresses {\n const tags: { id: string; gameId: string; qualified: string }[] = [];\n for (const box of bundle.boxes) {\n const boxGameId = effectiveGameId(box);\n for (const group of box.tagGroups) {\n for (const tag of group.tags) {\n const gameId = effectiveGameId(tag);\n tags.push({ id: tag.id, gameId, qualified: `${boxGameId}/${gameId}` });\n }\n }\n }\n // Distinct qualified forms per gameId. Distinct rather than a count: two\n // groups in ONE box may also name a tag the same way, and a refusal that\n // offered the same address twice would be no help at all. Those two share\n // the qualified segment, and the first in bundle order answers to it, which\n // is what the short form did for everything before this rule.\n //\n // That last case is closing at the source rather than here (question 16,\n // ruled 2026-09-06): the compiler WARNS that a tag gameId must be unique\n // within its box, across all of that box's groups, and refuses it from the\n // next release. So this stays as the reading rule for a bundle built before\n // that, and a bundle built after it has no repeated qualified form to read.\n const forms = new Map<string, string[]>();\n for (const tag of tags) {\n const list = forms.get(tag.gameId) ?? [];\n if (!list.includes(tag.qualified)) list.push(tag.qualified);\n forms.set(tag.gameId, list);\n }\n const print = new Map<string, string>();\n const accept = new Map<string, string>();\n const repeated = new Map<string, string[]>();\n const zoneQualified = new Map<string, string>();\n for (const tag of tags) {\n const candidates = forms.get(tag.gameId) ?? [tag.qualified];\n const ambiguous = candidates.length > 1;\n print.set(tag.id, ambiguous ? tag.qualified : tag.gameId);\n if (!accept.has(tag.qualified)) accept.set(tag.qualified, tag.id);\n if (!ambiguous && !accept.has(tag.gameId)) accept.set(tag.gameId, tag.id);\n if (ambiguous) repeated.set(tag.gameId, candidates);\n }\n // The zones, after the box tags and never in `repeated`. A zone whose\n // gameId a box tag also uses is a bundle the engine refuses at load; should\n // one reach here anyway (the Board reads bundles the engine never loaded),\n // the box tag keeps the short form it already had and the zone does not\n // take it over silently.\n for (const tag of bundle.map?.group.tags ?? []) {\n const gameId = effectiveGameId(tag);\n print.set(tag.id, gameId);\n if (!accept.has(gameId)) accept.set(gameId, tag.id);\n for (const box of bundle.boxes) zoneQualified.set(`${effectiveGameId(box)}/${gameId}`, gameId);\n }\n return { print, accept, repeated, zoneQualified };\n}\n\n/** What a box-qualified address naming a project-map zone is told: why the\n * form is wrong, and the address that works (design/project-map-contract.md\n * 3.4). */\nexport function zoneQualifiedValueAddressMessage(segment: string, zone: string, name: string): string {\n return `\"value.${segment}.${name}\": \"${zone}\" is a zone of the project map, which belongs to no box; `\n + `write \"value.${zone}.${name}\"`;\n}\n\n/** What an ambiguous short-form value address is told: the candidates, in\n * full, because \"that names two tags\" without them leaves a host reading a\n * bundle it did not write to find out which boxes. */\nexport function ambiguousValueAddressMessage(\n segment: string, name: string, candidates: readonly string[],\n): string {\n const forms = candidates.map((q) => `\"value.${q}.${name}\"`);\n const list = forms.length <= 1 ? (forms[0] ?? \"\")\n : `${forms.slice(0, -1).join(\", \")} or ${forms[forms.length - 1]}`;\n return `\"value.${segment}.${name}\" names a tag in ${candidates.length} boxes; write ${list}`;\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/**\n * A count of a TIMED box's turns, said as time (design/engine-server.md 4.8):\n * `turnSpan(30, 60)` is \"30 min\", and `turnSpan(30, 60, true)` is \"30 minutes\".\n *\n * One definition, because the conversion appears wherever a designer might\n * otherwise have to do it in their head: the card editor's Redraw field, the\n * box page, the Board's advance buttons, and the coverage report's turn\n * budget. Two of those want the unit spelled out and two want it short, which\n * is the whole of `long`.\n */\nexport function turnSpan(turns: number, seconds: number, long = false): string {\n const total = Math.max(0, Math.round(turns * seconds));\n const say = (n: number, short: string, one: string, many: string): string =>\n long ? `${n} ${n === 1 ? one : many}` : `${n} ${short}`;\n if (total < 60) return long ? say(total, \"s\", \"second\", \"seconds\") : `${total}s`;\n if (total < 3600) {\n const minutes = total % 60 === 0 ? total / 60 : Math.round(total / 6) / 10;\n return say(minutes, \"min\", \"minute\", \"minutes\");\n }\n let hours = Math.floor(total / 3600);\n let rest = Math.round((total % 3600) / 60);\n if (rest === 60) { hours += 1; rest = 0; }\n const said = say(hours, \"hr\", \"hour\", \"hours\");\n return rest === 0 ? said : `${said} ${say(rest, \"min\", \"minute\", \"minutes\")}`;\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 /** Template data, as `Card.fields` is: field name -> value, declared by\n * the box's `outcomeFields`, validated at publish, and handed to the host\n * with the outcome. The engine never reads it: a press can say one line\n * (\"The notice is in your pocket\") without spending a card on it. */\n fields?: Record<string, ScalarValue>;\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 /** Does this card's `redraw: \"never\"` spend survive the run\n * (design/engine-server.md 4.2)? Absent takes the deck's flag, set here it\n * overrides the deck, exactly as `shared` does. `shared` decides who a\n * spend counts for WITHIN a run; this decides whether it outlives one.\n *\n * Only `\"never\"` crosses the run boundary, for the reason only `\"never\"`\n * crosses the flow boundary (shared-scarcity 9.3.2): a finite cooldown is\n * an absolute turn of a box clock, and the clock resets with the run. On\n * any other redraw the flag is a compile warning.\n *\n * INERT TO THE RUNTIME, like the declaration flag: the server lifts the\n * durable spends at run end (per-flow ones from the flow's `never`\n * cooldowns, shared ones from the engine's spent set) and puts them back\n * through `openFlow(id, { restore })` and `markTaken`. */\n durable?: boolean;\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 /** Every `redraw: \"never\"` card in this pile is spent for good, past the end\n * of the run, unless the card says otherwise (design/engine-server.md 4.2).\n * The container carries the flag for the reason `shared` is carried here:\n * a pile is what an author reaches for when a rule is true of all of it. */\n durable?: 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/** The scopes a movable hole may be filled from (design/engine-server.md 4.6):\n * the two `boundBy` already allows, plus `@hand` - the asking hand's OWN\n * declared property, resolved before tag composition so a movable hole can\n * never depend on the tags it is choosing. */\nexport type HoleRefScope = \"hand\" | \"story\" | \"world\";\n\n/** A parsed hole reference: `@hand.zone` -> `{ scope: \"hand\", name: \"zone\" }`. */\nexport interface HoleRef {\n scope: HoleRefScope;\n name: string;\n}\n\nconst HOLE_REF = /^@(hand|world|story)\\.([a-z][a-z0-9_-]*)$/;\n\n/**\n * Is this `chosen` / binding value MEANT as a property reference rather than a\n * tag id?\n *\n * The test is the leading `@` alone, deliberately: a value that starts with\n * one and does not parse is a mistyped reference, which the compiler should\n * name as such, not a tag id that happens to look odd. Tag ids never begin\n * with `@`.\n */\nexport const isHoleRef = (value: string): boolean => value.startsWith(\"@\");\n\n/** Parse a hole reference, or undefined when it is not one. The on-disk form\n * stays a plain string, so the canonical serialiser and the shard merge need\n * no change at all: a hole is still one group name against one value. */\nexport const parseHoleRef = (value: string): HoleRef | undefined => {\n const m = HOLE_REF.exec(value);\n return m === null ? undefined : { scope: m[1] as HoleRefScope, name: m[2]! };\n};\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. Literal tags only: what a\n * template FIXES is the same for every instance, and a hole that moves is\n * the instance's own business (`Hand.chosen`, 4.6). */\n bindings?: Record<string, string>;\n /** The holes: tag group ids each instance fills (one tag each, or one\n * property reference: 4.6). */\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 /**\n * Tag group id -> tag id, or a PROPERTY REFERENCE (`\"@hand.zone\"`,\n * `\"@story.where\"`, `\"@world.place\"`) the runtime resolves at ask time\n * (design/engine-server.md 4.6, the hand that moves). Still a plain string\n * on disk, so the canonical serialiser and the merge are untouched; what\n * widened is the meaning, and `parseHoleRef` is where it is read.\n *\n * `place` is never fillable this way: it is the hand's own name, not an axis.\n */\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 /**\n * Template instances: tag group id -> tag id, one per `chooses` hole.\n *\n * A value may instead be a PROPERTY REFERENCE (`\"@hand.zone\"`,\n * `\"@story.where\"`, `\"@world.place\"`), which makes the hole MOVABLE: the\n * runtime resolves the reference at ask time and binds the hole to the tag\n * the value names, so moving the Elder to the forest is `setProperty` and\n * nothing else (design/engine-server.md 4.6). Still a plain string on disk,\n * so the canonical serialiser and the shard merge need no change; read it\n * with `parseHoleRef`.\n */\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 /**\n * A TIMED box: its clock counts real time, one turn every `seconds` of the\n * run (design/engine-server.md 4.8). Absent is the ordinary box, whose turn\n * is a play.\n *\n * Two things follow, and only two. In the ENGINE, a play in this box\n * defaults to advancing nothing: `settings.playAdvancesTurns` does not\n * apply, so a designer cannot declare the convention and then forget to\n * switch play-advance off. Everywhere else it is what the tools SAY: the\n * host ticks the box (the runtime has no clock and gains none here), and a\n * card's `redraw: N` reads as N x `seconds`, which the editors, the bundle\n * inspectors and the coverage report spell out rather than leaving a\n * designer to know that 30 meant minutes.\n *\n * The number itself is inert to the runtime, which never reads it.\n */\n turn?: { seconds: number };\n /** The card template: what every card in this box carries. */\n fields: FieldDecl[];\n /** What every outcome in this box may carry, declared the same way.\n * Absent when the box declares none, so a bundle without them is byte for\n * byte what it was. */\n outcomeFields?: FieldDecl[];\n properties: PropertyDecl[];\n /**\n * The box has opted in to the PROJECT MAP (design/project-map-contract.md\n * 1.2, 2.2): its hands may bind the map's zone group and its cards may be\n * tagged with it, and it sees the group's name beside its own groups' names.\n * Absent is \"not on the map\", and a box that is not may not reference the\n * group at all: the engine refuses such a bundle at load.\n *\n * Opting in changes nothing about what the box deals FROM: a hand still\n * deals only from its own box's decks. What the boxes on the map share is\n * the zones' values (one bag per zone), never their cards or their history.\n */\n usesMap?: true;\n /** The box's OWN tag groups. The project map's group is never here, even in\n * a box that uses it: it is the bundle's, in `Bundle.map` (`groupsOfBox`\n * gives the two together). */\n tagGroups: TagGroup[];\n decks: Deck<E>[];\n handTemplates: HandTemplate<E>[];\n hands: Hand<E>[];\n}\n\n// --- the compiled bundle (.storyletsc) ---------------------------------------\n\n/**\n * The bundle schema this build of the format writes: @1 since the project map\n * (design/project-map-contract.md 2.4), the bundle that can carry `map` and\n * `Box.usesMap`.\n *\n * Every runtime READS @0 and @1 and refuses anything else, by name. Reading @0\n * is not a compatibility branch: an @0 bundle cannot carry a map, so it is the\n * same shape with less in it. The check exists so that from this release on a\n * runtime meeting a schema it does not know says so, rather than half-working\n * the way an @0 runtime does on a map bundle (tag matching is by id, so its\n * deals look right while every zone value is missing).\n */\nexport const BUNDLE_SCHEMA = \"storylets/bundle@1\";\n/** The schema before the project map, still read by every runtime. */\nexport const BUNDLE_SCHEMA_V0 = \"storylets/bundle@0\";\n/** Every bundle schema a runtime accepts. */\nexport const BUNDLE_SCHEMAS: readonly string[] = [BUNDLE_SCHEMA_V0, BUNDLE_SCHEMA];\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 * The play ladder (design/engine-server.md 4.10): how much of itself\n * Storyletter shows this project, in one setting with three rungs rather than\n * a set of toggles, because the features nest.\n *\n * solo one player, one flow: no sharing, no durability, no venue features\n * shared several players over one world: sharing appears\n * venue a production: nothing is hidden\n *\n * EDITOR-SIDE ONLY. It stays in the project shard beside `coverage` and\n * `export` and is never compiled: a solo project plays on the same Engine as a\n * venue one. Hidden is hidden rather than disabled, so going DOWN a rung is\n * refused when the project already contains what the rung would hide, and a\n * hand-edited shard above its rung is a compile warning.\n */\nexport type PlayRung = \"solo\" | \"shared\" | \"venue\";\n\n/** The default rung: a project shard that says nothing is a solo game. */\nexport const DEFAULT_PLAY_RUNG: PlayRung = \"solo\";\n\n/** The project shard's settings block: what the bundle carries, plus the\n * authoring-side play rung that it does not. */\nexport interface ProjectSettings extends BundleSettings {\n /** The play ladder rung (see `PlayRung`). Absent = \"solo\". */\n play?: PlayRung;\n}\n\n/**\n * The PROJECT MAP (design/project-map-contract.md 2.1): at most one per project,\n * above the boxes. Two halves, on purpose.\n *\n * `group` is SEMANTIC and always ships when the project declares a map: the zone\n * group, compiled exactly as a box's group is (the group's properties flattened\n * onto each tag), which opted-in boxes' hands bind and cards are tagged with BY\n * ID, as with any group. It is in no box's `tagGroups`. Each zone is one tag and\n * so one value bag, whichever boxes' hands are dealt to it.\n *\n * `geometry` is INERT PAYLOAD, as the per-box map block before it was: nothing\n * in the engine reads it, and it is absent unless the project asked for it\n * (`export.map`), so a shipping build carries no shapes. GAME IDS throughout,\n * because a host matches these against the names it passes to `peek`.\n *\n * SITES ARE CONTENT. Until 2026-09-05 they were deliberately left out: a site\n * was where an author parked a hand while working. That held for a game, where a\n * hand's zone is its only real-world meaning; it does not hold for a physical\n * experience (design/engine-server.md 4.3), where the position is where the kiosk\n * stands. They stay per box, because a hand belongs to one box.\n */\nexport interface ProjectMap {\n /** The zone group. The engine reads this. */\n group: TagGroup;\n /** Drawing data, only under `export.map`. The engine never reads it. */\n geometry?: {\n /** Drawn zones only, by tag gameId, in group order. A tag with no polygon\n * is not a place yet and is left out rather than shipped as an empty\n * shape. */\n zones: { tag: string; polygon: ViewPoint[] }[];\n /** Visible background pictures, back to front, as bundle-relative paths. */\n backgrounds?: BundleBackground[];\n /** Box gameId -> where that box's placed hands stand, sorted by hand\n * gameId so the bytes do not depend on authoring order. Only opted-in\n * boxes; a box with no site has no key, and no key at all when nothing\n * is placed. The zone a site sits in is NOT repeated: the hand's own\n * binding is what the runtime deals from. */\n sites?: Record<string, { hand: string; x: number; y: number }[]>;\n };\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/<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 | typeof BUNDLE_SCHEMA_V0;\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 /** The project map, when the project declares one (see `ProjectMap`). The\n * per-box `maps` array it replaces is gone, not kept as a one-element list:\n * zones are no longer a box's. */\n map?: ProjectMap;\n /** Other engines' game-wide scopes the content names (`patter`), sorted: the\n * family's shared vocabulary, let through unchecked by the compiler. The\n * engine reports when the game has not registered one. Absent when none. */\n externalScopes?: string[];\n}\n\n// --- reading the project map (design/project-map-contract.md 5, Q12) ---------\n//\n// The questions every reader of a bundle asks once a group may live outside the\n// box that uses it, answered once here beside `valueAddresses`, because the\n// engine, `describeBundle`, the Board and the server each looked a bound group up\n// in the hand's own box and silently lost the project one. Pure field access.\n\n/** The tag groups a box sees, by NAME as well as by id: its own groups, then the\n * project map's group when the box has opted in. The engine resolves a group\n * name in a box against exactly this list, own groups first (a bundle the\n * engine loads never has a box group sharing the project group's name, so the\n * order decides nothing; it is stated for determinism). */\nexport function groupsOfBox<E>(\n bundle: { map?: { group: TagGroup } },\n box: Pick<Box<E>, \"tagGroups\" | \"usesMap\">,\n): TagGroup[] {\n return box.usesMap === true && bundle.map !== undefined\n ? [...box.tagGroups, bundle.map.group]\n : box.tagGroups;\n}\n\n/** A tag group by internal id, wherever it lives: in a box (`box` set) or on the\n * project map (`box` absent). Ids are project-unique, so this is bundle-wide;\n * whether the box asking may USE the group is `groupsOfBox`'s question. */\nexport function groupById<E>(\n bundle: { boxes: readonly Box<E>[]; map?: { group: TagGroup } },\n id: string,\n): { group: TagGroup; box?: Box<E> } | undefined {\n for (const box of bundle.boxes) {\n const group = box.tagGroups.find((g) => g.id === id);\n if (group !== undefined) return { group, box };\n }\n return bundle.map?.group.id === id ? { group: bundle.map.group } : undefined;\n}\n\n/** Every tag group in the bundle, each once: the boxes' groups in bundle order,\n * then the project map's. What a walk over every value bag wants. */\nexport function allTagGroups<E>(bundle: { boxes: readonly Box<E>[]; map?: { group: TagGroup } }): TagGroup[] {\n const groups = bundle.boxes.flatMap((box) => box.tagGroups);\n return bundle.map !== undefined ? [...groups, bundle.map.group] : groups;\n}\n\n/** One declared owned property, as an address prints it. */\nexport interface PropertyAddress {\n /** The engine address, `<scope>.<owner segment>.<name>`, exactly as\n * `listProperties` prints it and `setProperty` accepts it. */\n path: string;\n scope: \"box\" | \"deck\" | \"hand\" | \"value\";\n /** The owner's internal id: what the stores and the save are keyed by. */\n owner: string;\n decl: PropertyDecl;\n}\n\n/**\n * Every declared box, deck, hand and tag property in the bundle, by the address\n * a runtime prints for it: boxes in bundle order (the box, its decks, its hands,\n * its tags), then the project map's zones, ONCE, whichever boxes use them. A hand\n * instance carries its template's declarations, as the engine's bags do.\n *\n * The owner segments are `valueAddresses`' for tags, so a zone prints\n * `value.<zone>.<name>` and a repeated box tag its qualified form.\n */\nexport function propertyAddresses(bundle: {\n boxes: readonly Box<unknown>[];\n map?: { group: TagGroup };\n}): PropertyAddress[] {\n const values = valueAddresses(bundle);\n const out: PropertyAddress[] = [];\n const push = (scope: PropertyAddress[\"scope\"], owner: string, segment: string, decls: readonly PropertyDecl[]): void => {\n for (const decl of decls) out.push({ path: `${scope}.${segment}.${decl.name}`, scope, owner, decl });\n };\n const tagsOf = (group: TagGroup): void => {\n for (const tag of group.tags) {\n push(\"value\", tag.id, values.print.get(tag.id) ?? effectiveGameId(tag), tag.properties ?? []);\n }\n };\n for (const box of bundle.boxes) {\n push(\"box\", box.id, effectiveGameId(box), box.properties);\n for (const deck of box.decks) push(\"deck\", deck.id, effectiveGameId(deck), deck.properties);\n for (const hand of box.hands) {\n const decls = hand.template !== undefined\n ? box.handTemplates.find((t) => t.id === hand.template)?.properties ?? []\n : hand.properties ?? [];\n push(\"hand\", hand.id, effectiveGameId(hand), decls);\n }\n for (const group of box.tagGroups) tagsOf(group);\n }\n if (bundle.map !== undefined) tagsOf(bundle.map.group);\n return out;\n}\n\n// --- the save envelope --------------------------------------------------------\n//\n// Version 2 (the one-registry model): property values are the game's\n// ScopeRegistry's, not the engine's. The envelope holds what is NOT a property\n// (boards, clocks, cooldowns, PRNGs, play logs, spent cards), plus, when the\n// engine made its own registry (a standalone game), that registry's values\n// under `registry`. A game that passed a registry saves it once itself.\n// Version 1 envelopes still load on every runtime: their property partitions\n// move into the registry under the keys below.\n//\n// Registry keys (identical on every runtime, since they are in the save):\n// `story` for the shared @story; `storylets/<kind>/<id>` for a shared box,\n// deck, hand, or value bag (kind is `box`, `deck`, `hand`, or `value`, id the\n// internal id); `storylets/flow/<flowId>/story` and\n// `storylets/flow/<flowId>/<kind>/<id>` for a flow's own. Ids escape `%` as\n// `%25` and `/` as `%2F`. A bag with no declared properties is not registered.\n// A self-backed @world (no resolver bound) is a stored property too, under\n// `world`.\n\nexport const SAVE_SCHEMA = \"storylets/save@2\";\n/** The version 1 envelope's schema tag, still read. */\nexport const SAVE_SCHEMA_V1 = \"storylets/save@1\";\n\nexport interface PlayRecord {\n /** Card and outcome by gameId (feeds the play-history functions). */\n card: string;\n /** \"\" for a card with no outcomes, played with none: the key is always\n * there, so a save's shape does not depend on the card. */\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), and the blob\n * `saveFlow` parks. */\nexport interface FlowSave {\n /** The per-flow property partitions. Carried by `saveFlow`, which parks one\n * flow whole; absent from a version 2 envelope's flows, whose properties\n * are the registry's. Present in every flow of a version 1 envelope. */\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 /** The shared property partitions: version 1 only. */\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 /** The engine's own registry's values, keyed by registry key: present only\n * when the engine made the registry itself (a standalone game). A game that\n * passed a registry saves it once, beside this envelope. */\n registry?: Record<string, PropertyBag>;\n shared: SharedSave;\n flows: Record<string, FlowSave>;\n}\n\n/** A version 1 envelope, from before the registry held the properties. Every\n * runtime still reads it: its partitions move into the registry as it loads. */\nexport interface SaveEnvelopeV1 {\n schema: typeof SAVE_SCHEMA_V1;\n content: BundleContent;\n shared: SharedSave & { props: PropsPartition };\n flows: Record<string, FlowSave & { props: PropsPartition }>;\n}\n\n// --- the load report (design/engine-server.md 4.9) ----------------------------\n//\n// `loadGame` is forgiving by design: a card the bundle no longer has drops off\n// the board, a property the save does not carry keeps its default, and a\n// version two builds newer loads without a word. That forgiveness is what makes\n// a save survive an edit, and it is also what hides the cost of a content\n// update from whoever is about to apply one. The report is the same walk,\n// itemised: `previewLoad` computes it and changes nothing, `loadGame` computes\n// it and applies it, and `previewFlowRestore` answers the same questions for\n// one flow (4.1's `openFlow(id, { restore })`).\n//\n// Card, hand and flow identities are GAME IDS: a report is host-facing and\n// internal ids mean nothing outside the project. The one exception is an\n// entity the edit DELETED - a vanished card, a vanished hand - which has no\n// gameId left to give, so the report carries the id the save itself carries.\n// There is nothing else to name it by.\n//\n// A property is named differently, and deliberately: by its ENGINE ADDRESS,\n// the string listProperties() prints and getProperty()/setProperty() accept.\n// A report entry is then something a host can act on rather than merely\n// print, and the runtimes have one property grammar instead of two.\n\n/** One card that a restore refused to put back on the board.\n *\n * `vanished` and `hand-vanished` are the edit's doing (the card, or the hand\n * it sat in, is no longer in the bundle). `claimed-elsewhere` is only ever a\n * single-flow restore into a LIVE engine: the card is shared, and the other\n * open flows already hold every copy the world has. */\nexport interface LoadEviction {\n flow: string;\n hand: string;\n card: string;\n reason: \"vanished\" | \"hand-vanished\" | \"claimed-elsewhere\";\n}\n\n/** One property the restore could not put back as it was. `flow` names the\n * flow whose half it belongs to; absent, it is the shared half.\n *\n * `path` is the engine's property address, spelled exactly as\n * `Flow.listProperties()` / `Engine.listProperties()` print it and exactly as\n * `getProperty` and `setProperty` accept it: `story.<name>` for the story\n * scope, `<scope>.<ownerGameId>.<name>` for the box, deck, hand and tag\n * scopes. No `@`, which belongs to the expression language and not to an\n * address.\n *\n * The owner segment is its GAMEID (design/engine-server.md 4.4), the name it\n * is called by everywhere else, so an operator reading a hot-swap report can\n * paste the address straight into `setProperty`. An owner the build no longer\n * has keeps the id the save carried: there is no gameId left to give it,\n * which is the rule the eviction list above has always used. */\nexport interface LoadProperty {\n flow?: string;\n path: string;\n}\n\n/** What a load or a flow restore would do that is not a plain restore\n * (design/engine-server.md 4.9). Arrays are sorted, so two runtimes given the\n * same save and bundle produce the same bytes; `flows` alone keeps the\n * envelope's own order, because a caller re-takes its handles in it. */\nexport interface LoadReport {\n /** No drift and nothing dropped, defaulted or retyped: the save goes back\n * exactly as it was. `flows` is not a divergence and does not count. */\n exact: boolean;\n project: string;\n /** Drift when the two differ; reported, never refused. */\n version: { saved: string; bundle: string };\n /** Drift when the two differ; reported, never refused. */\n hash: { saved: string; bundle: string };\n /** The flows this restores, in the order it restores them. */\n flows: string[];\n evicted: LoadEviction[];\n /** Cooldowns held for cards the bundle no longer has. */\n droppedCooldowns: { flow: string; card: string }[];\n /** Shared `redraw: \"never\"` entries for cards the bundle no longer has. */\n droppedSpent: string[];\n /** In the save, not declared any more. */\n droppedProperties: LoadProperty[];\n /** Declared, not in the save: it takes the declaration's default. */\n defaultedProperties: LoadProperty[];\n /** In the save, still declared, but the saved value no longer fits the\n * declaration (its type changed, or an enum value / quality stage was\n * edited away). It takes the declaration's default. */\n retypedProperties: LoadProperty[];\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 /** The engine's envelope: version 2 when written today, version 1 still read. */\n engine: SaveEnvelope | SaveEnvelopeV1;\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. One folder for the project, as\n * the source has (`<project>/assets/`), since the project map is the only thing\n * with pictures and there is one of it (design/project-map-contract.md 1.4).\n */\nexport const bundleAssetPath = (file: string): string => `assets/${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 AUTHOR's arrangement layer: the canvases, where cards sit on a deck's\n * node canvas and the furniture drawn round them. Its own shard because\n * positions churn (an afternoon of tidying a canvas touches every card) and\n * content does not, so a designer arranging and a writer editing never\n * collide on one file (design/graphical-views.md section 1.2). */\n view: \".storyletview\",\n /** The DESIGNER's map, in two places told apart by schema tag. At the\n * project root (`map.storyletmap`, `PROJECTMAP_SCHEMA`) it is the PROJECT\n * MAP: the zone group and the map's furniture, once for the project\n * (design/project-map-contract.md 1.1). In a box folder (`MAP_SCHEMA`) it is\n * that box's SITES: where its hands stand on the project map.\n *\n * Split out of the view shard on 2026-09-06 (design/engine-server.md 9.1\n * point 5) because the two halves stopped having one owner. A hand's\n * position ships in the bundle's `map.geometry` (4.3) and is where a venue's\n * kiosk stands, so it is SHAPE, which a server's author key may not change;\n * the canvases are the author's own working drawing and never leave the\n * project folder. One file could not be both. */\n map: \".storyletmap\",\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 /** An installation contract: what a VENUE depends on, one file per\n * installation in `contracts/` at the project root\n * (design/engine-server.md 4.11). Its own shard, and its own folder, for the\n * walkthrough's reason (Reboot 7.5, S4): a different owner, a different\n * change rate, and a merge that must never collide with the author's edits,\n * since the server always wins its own file. */\n contract: \".storyletcontract\",\n} as const;\n\n/** Where the installation contracts live, relative to the project root. The\n * directory is the registry, as it is for a box's decks: a contract exists\n * because its file exists. */\nexport const CONTRACTS_DIR = \"contracts\";\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\";\nexport const MAP_SCHEMA = \"storylets/map@0\";\n/** The project map shard's schema: the root `map.storyletmap`, beside the\n * project shard (design/project-map-contract.md 1.1). The same extension as a\n * box's map shard, told apart by this tag and by sitting at depth one. */\nexport const PROJECTMAP_SCHEMA = \"storylets/projectmap@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\";\nexport const CONTRACT_SCHEMA = \"storylets/contract@0\";\n\n/**\n * What one installation depends on, written by the venue's server and read by\n * `validate` (design/engine-server.md 4.11).\n *\n * NOT THE AUTHOR'S FILE. A venue is provisioned against names - the hands its\n * stations deal, the boxes its scheduler ticks, the properties its clocks drive,\n * the fields its crew read - and the server writes them out so the tools that\n * already gate a build can refuse a rename before it reaches the venue. A\n * project playing at two venues has two of these. The author never edits one,\n * and today, with no server built, a project either receives one or has none.\n *\n * NEVER COMPILED. It is project-side config like `coverage` and `export`: the\n * server does not need its own contract handed back, it needs the bundle to\n * still honour it.\n *\n * BY GAMEID throughout, because a gameId is the name that crosses the project's\n * border and an internal id is authoring identity.\n */\nexport interface ContractShard {\n schema: typeof CONTRACT_SCHEMA;\n /** The installation this contract speaks for. One file per installation, and\n * two files naming the same one is an error. */\n installation: string;\n /** Who wrote it, for a human reading the file (\"Storylet Server 0.1.0\"). */\n by?: string;\n /** The server's revision when it wrote this. */\n revision?: number;\n /** Hands a station is bound to, by gameId: they may not be renamed or\n * removed. */\n hands?: string[];\n /** Timed boxes the venue's scheduler ticks, by box gameId, with the turn unit\n * in SECONDS it was provisioned against. A box whose unit changed means every\n * rest on its cards changed meaning. */\n boxes?: Record<string, { turn: number }>;\n /** Property paths the venue reads or drives, in the engine's own address\n * grammar with no `@` (\"world.time_wall\", \"story.visits\"), which is how\n * `listProperties()` prints them. */\n properties?: ContractProperty[];\n /** Card-template field names the crew and the bridges read. */\n fields?: string[];\n /** Outcome field names they read, the same way: the after-line a station\n * shows when a press lands. What `fields` is to the card template, this is\n * to the box's `outcomeFields`. */\n outcomeFields?: string[];\n}\n\n/**\n * One contracted property.\n *\n * A bare path is the common form and the one the spec's example writes. The\n * object form adds the TYPE the venue was provisioned against, which is the only\n * way `validate` can catch the break that costs a producer most: a property that\n * still exists under the same name and now holds something else. A server that\n * knows the type should write the object form; a hand-written contract may say\n * only the path and get the existence check alone.\n */\nexport type ContractProperty = string | { path: string; type?: PropertyType };\n\n/** The path a contracted property names, whichever form it was written in. */\nexport const contractPropertyPath = (p: ContractProperty): string =>\n typeof p === \"string\" ? p : p.path;\n\n/** The type a contracted property was provisioned against, when it says. */\nexport const contractPropertyType = (p: ContractProperty): PropertyType | undefined =>\n typeof p === \"string\" ? undefined : p.type;\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 stand on the PROJECT map, and nothing else.\n * Carried by the MAP shard since 2026-09-06; `ViewShard.map` is the old\n * address, read for one release and never written.\n *\n * No furniture since the project map (design/project-map-contract.md 1.3): the\n * frames belong to the one map, in `ProjectMapShard`. A box map shard that\n * still carries `frames` is warned about and read for nothing until\n * `storyletengine format` moves them. */\nexport interface BoxMap {\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 AUTHOR's arrangement layer for one box: where cards sit on their decks'\n * canvases, and the furniture drawn round them.\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 /** The box's colour on the project map: its layer swatch, its pins and its\n * chips. A slot of the theme's 12-colour identity palette (0-11), not a hex\n * value, so it follows light, dark and the colour themes, as a Patter\n * writing status's `colour` does.\n *\n * STORED, not computed (the surfacing review's round-3 ruling): a box takes\n * the first slot no other box on the map uses when it joins, and keeps it\n * however the boxes are reordered, added or removed, until the author picks\n * another. Arrangement like everything else here, so it never reaches the\n * bundle. */\n colour?: number;\n /** @deprecated The box map's old address, kept for one release and READ ONLY.\n * A reader that meets it uses it when the box has no `MapShard`, and the\n * formatter moves it; nothing writes it any more. Removed after the next\n * release, at which point a map left here is simply lost. */\n map?: BoxMap;\n}\n\n/** The DESIGNER's map for one box: where its hands stand on the project map.\n *\n * Split out of the view shard on 2026-09-06 (design/engine-server.md 9.1 point\n * 5). The two halves had stopped sharing an owner: a hand's position ships in\n * the bundle's `map.geometry.sites` (4.3), which makes it the thing a venue\n * provisions its kiosks against, while a deck's canvas is a working drawing\n * that never leaves the folder. A server's author key may change the canvases\n * and not this.\n *\n * The map is NESTED under `map` rather than flattened to the top level, and\n * deliberately: the block's bytes are then exactly what the view shard held, so\n * the migration is a move of a value rather than a reshaping of it, the merge\n * strategy carries over word for word, and a reader that has to look in both\n * places is one expression (`box.map?.map ?? box.view?.map`).\n *\n * Source-only in the sense the view shard is not: `compileMaps` reads the\n * positions for the bundle's `map.geometry`, under `export.map`, for a box that\n * has opted in to the project map. */\nexport interface MapShard {\n schema: typeof MAP_SCHEMA;\n map: BoxMap;\n}\n\n/**\n * The PROJECT MAP's shard: the root `map.storyletmap` (design/project-map-contract.md\n * 1.1). At most one per project, above the boxes.\n *\n * `group` is the zone group, a `TagGroup` byte for byte the shape a box's tags\n * shard holds, so every reader of a group (the spatial marker, polygons,\n * backgrounds, group-level property declarations) carries over unchanged. It is\n * compiled exactly as a box's group is and ships as the bundle's `map.group`. A\n * box opts in with `usesMap` on its box shard; only an opted-in box's cards and\n * hands may reference it.\n *\n * `frames` is the map's furniture, moved here from every box's map shard:\n * arrangement, never compiled. Sites stay per box, in each box's own map shard,\n * because a hand belongs to one box.\n */\nexport interface ProjectMapShard extends CanvasFurniture {\n schema: typeof PROJECTMAP_SCHEMA;\n group: TagGroup;\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: ProjectSettings;\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 /**\n * Where the game's shared scopes folder is, relative to the folder holding this file\n * (`\"../../shared/game-scopes\"`). Authoring config, never compiled, and usually absent: the\n * tools find a `game-scopes/` folder by walking up from the project on their own, stopping at\n * the version-control root, so this is only for a folder that walk would not reach. A path\n * that doesn't exist is a project error. (patterkit design/shared-scopes.md.)\n */\n gameScopes?: string;\n /**\n * The Patter project this one is paired with: a `.patter` folder, relative to the folder\n * holding this file (`\"../story/the-hamlet.patter\"`). Authoring config, never compiled: the\n * engines still know nothing of each other (Reboot 10). With it, `validate` checks each card\n * against the scene of the same name in the Patter project's published bundle, and\n * Storyletter can open Patterpad at a card's scene. A folder that isn't there is a warning,\n * since a writer may hold the cards without the dialogue.\n */\n patter?: string;\n /**\n * The boxes the game performs through the paired Patter project, by box id: every card in them\n * plays the scene named after it. Authoring config, never compiled, and only meaningful beside\n * `patter`. With it, `validate` checks only these boxes and also reports a card with no scene;\n * Storyletter's Board plays their cards' scenes, and the playable export carries them.\n * Absent, every card that has a scene is checked and none is required to have one.\n */\n patterBoxes?: string[];\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 project's binary assets (the project\n * map's background images, in its root `assets/` folder)?\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 project map's GEOMETRY (zone shapes,\n * background pictures and each opted-in box's sites, `map.geometry`)? The\n * zone group itself always ships when there is a project map: the engine\n * reads it.\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 /** Declares a timed box (see `Box.turn`); compiled through unchanged. */\n turn?: { seconds: number };\n fields: FieldDecl[];\n /** The outcome fields (see `Box.outcomeFields`); a shard without the key\n * declares none. */\n outcomeFields?: FieldDecl[];\n properties: PropertyDecl[];\n /** The box has opted in to the PROJECT MAP (design/project-map-contract.md\n * 1.2): its hands may bind the map's zones and its cards may be tagged\n * with them. Absent is \"not on the map\"; never written false. Compiled\n * through to `Box.usesMap`. */\n usesMap?: true;\n };\n}\n\n/** The box's OWN tag groups: how its cards are filed. Never the project map's\n * zone group, which lives in the root map shard and which a box may not\n * declare a copy of (a spatial group here is a compile error naming\n * `storyletengine format`). */\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 /** Its `redraw: \"never\"` cards are spent past the run: see Deck.durable. */\n durable?: 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// 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 TO THE STORY; the HOST still writes it, by passing\n * `{ host: true }` (see `set`). Default is read/write. (`type`/`values` feed\n * validation.)\n *\n * The distinction is the whole point of the flag on a foreign scope, where the\n * value is the game's own: a flag carried in the story's bundle must not lock a\n * game out of its own state. Ruled 2026-09-05, after both products met it - the\n * Storylet Engine's venue clock and Patter's coverage driver were each blocked\n * from the one property they existed to move.\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 /** The author's note on what the property is for, which another tool's picker shows as a tip\n * (shared game scopes, scopes.ts). The registry itself ignores it. */\n purpose?: string;\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 /** A name as this bag keys it: its normalisation policy applied. The registry\n * uses it to key quality ladders and the validation schema the bag's own way,\n * so a case-significant (identity) bag is not quietly folded to lower case\n * one layer up. */\n normalise(name: string): string {\n return 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 unless the caller says it is the\n * HOST (`host: true`), for whom `writable: false` was never a rule - it is\n * the story's promise, not the game's. `silent` and `host` are separate on\n * purpose: one is about who hears the write, the other about who may make\n * it. Returns the change. */\n set(name: string, value: ScalarValue, opts?: { silent?: boolean; reason?: string; host?: boolean }): BagChange {\n const n = this.norm(name);\n if (!opts?.host && 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 owner?: string;\n}\ninterface ForeignScope {\n kind: \"foreign\";\n resolver: ScopeResolver;\n decls: Map<string, ScopeDeclaration>;\n scopeWritable: boolean;\n norm: (name: string) => string;\n owner?: string;\n}\ntype Entry = OwnedScope | ForeignScope;\n\nconst lowerCase = (name: string): string => name.toLowerCase();\n\n/** Options for an owned scope the registry builds (`defineOwned`). */\nexport interface OwnedScopeOptions {\n /** The address prefix its examiner rows carry, separator included. Defaults\n * to `<token>.`; the address grammar is the product's, not the registry's. */\n pathPrefix?: string;\n /** Name normalisation: lower case by default; a case-significant product\n * passes identity. */\n normalise?: (name: string) => string;\n /** Who registered it (an engine's name). Named in a clash error and carried\n * on examiner rows, so one examiner can group a combined game by engine. */\n owner?: string;\n}\n\n/** Options for a foreign scope (`defineForeign`). */\nexport interface ForeignScopeOptions {\n /** Scope-level read/write default for its declarations (default true). */\n writable?: boolean;\n /** Name normalisation for the names passed to the resolver: lower case by\n * default; a case-significant product passes identity. */\n normalise?: (name: string) => string;\n /** Who registered it. See `OwnedScopeOptions.owner`. */\n owner?: string;\n}\n\n/** Options for a context or schema built from the registry. */\nexport interface AliasOptions {\n /**\n * Expression token -> registered key. `{ scene: \"patter/flow-2/scene/tavern\" }`\n * makes `@scene` read that instance bag, for this context only.\n *\n * The registry learns nothing about what the token MEANS: which flow, which\n * scene, which deck is an engine's own idea, and the engine names the key per\n * evaluation. It has to be the registry's mechanism rather than the engine\n * patching the context afterwards, because quality ladders and validation are\n * looked up by token too, and an alias applies to all three alike.\n *\n * An alias to a key that is not registered throws: a condition evaluated\n * against a scope that is not there is an engine bug, not a graceful false.\n */\n aliases?: Record<string, string>;\n}\n\n/** Options for `remove`. */\nexport interface RemoveOptions {\n /** Park an owned scope's values, to be handed back when the same key is next\n * registered (a live reload rebuilding an engine). No effect on a foreign\n * scope, whose values were never the registry's. */\n keep?: boolean;\n}\n\n/** Options for `load`. */\nexport interface LoadOptions {\n /** Keep what earlier loads parked, adding this blob's unclaimed sections to\n * it (a section for the same key replaces the parked one). Without it, each\n * load replaces whatever an earlier load parked. For an engine moving an\n * older save's values into a registry the game has already loaded. */\n keepParked?: boolean;\n}\n\n/**\n * The versioned owned-state fragment.\n *\n * @deprecated Versioning belongs to the save that embeds the values, not to the\n * registry; no engine ever called this. Embed `save()` in your own versioned\n * save instead. Removed at the next breaking release.\n */\nexport interface OwnedStateFragment {\n version: number;\n scopes: Record<string, Record<string, ScalarValue>>;\n}\n\n/** @deprecated See `OwnedStateFragment`. Removed at the next breaking release. */\nexport const SAVE_FRAGMENT_VERSION = 1;\n\nexport class ScopeRegistry {\n private readonly scopes = new Map<string, Entry>();\n /** Values loaded for keys nobody has registered yet, waiting to be claimed. */\n private readonly parked = new Map<string, Record<string, ScalarValue>>();\n private rev = 0;\n\n /**\n * A counter that moves whenever a scope is registered or removed, and at no\n * other time: it starts at 0 and each registration or removal adds 1. Values\n * changing does not move it. A caller that caches a context built by\n * `toEvalContext()` rebuilds it when this moves, because the context's set of\n * scopes is fixed when it is built while the values it reads stay live.\n */\n get revision(): number {\n return this.rev;\n }\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 * The third argument may be the path prefix alone (the pre-0.7 form) or an\n * options object.\n */\n defineOwned(token: string, declarations: ScopeDeclaration[], opts?: string | OwnedScopeOptions): this {\n const o: OwnedScopeOptions = typeof opts === \"string\" ? { pathPrefix: opts } : opts ?? {};\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 const bag = new PropertyBag(declarations, {\n pathPrefix: o.pathPrefix ?? `${token}.`,\n ...(o.normalise ? { normalise: o.normalise } : {}),\n });\n return this.mountOwned(token, bag, o.owner !== undefined ? { owner: o.owner } : undefined);\n }\n\n /**\n * Attach an EXISTING bag as an owned scope: an engine (or a host) holds the\n * bag and this registry reads, writes, lists and saves it like its own.\n *\n * If values were loaded for this key before anyone registered it, the bag\n * claims them now: laid over its seeded defaults by the bag's own `load` rule.\n */\n mountOwned(token: string, bag: PropertyBag, opts?: { owner?: string }): this {\n this.assertFree(token, opts?.owner);\n this.scopes.set(token, { kind: \"owned\", bag, ...(opts?.owner !== undefined ? { owner: opts.owner } : {}) });\n this.rev++;\n const waiting = this.parked.get(token);\n if (waiting) {\n bag.load(waiting);\n this.parked.delete(token);\n }\n return this;\n }\n\n /**\n * Unregister a scope. With `{ keep: true }` an owned scope's values are parked\n * and handed back when the same key is next registered, which is how a live\n * reload hands an engine's state to its replacement. Throws on an unknown key.\n */\n remove(token: string, opts?: RemoveOptions): this {\n const e = this.scopes.get(token);\n if (!e) throw new Error(`unknown scope '@${token}'`);\n if (opts?.keep && e.kind === \"owned\") this.parked.set(token, e.bag.save());\n this.scopes.delete(token);\n this.rev++;\n return this;\n }\n\n /**\n * Drop parked values nobody claimed. Parked values are kept in the next save by\n * default, so nothing loaded is lost to a flow or deck that simply has not\n * reopened yet; a game that knows they are dead drops them here.\n *\n * With a `prefix`, only keys starting with it are dropped: an engine resetting\n * itself drops its own instance keys (`my-engine/`) and leaves every other\n * engine's alone.\n */\n discardParked(prefix?: string): this {\n if (prefix === undefined) this.parked.clear();\n else for (const key of [...this.parked.keys()]) if (key.startsWith(prefix)) this.parked.delete(key);\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 opts: boolean | ForeignScopeOptions = true,\n ): this {\n // A boolean is the pre-0.7 form: the scope-level writable default alone.\n const o: ForeignScopeOptions = typeof opts === \"boolean\" ? { writable: opts } : opts;\n this.assertFree(token, o.owner);\n const norm = o.normalise ?? lowerCase;\n const decls = new Map<string, ScopeDeclaration>();\n for (const d of declarations) decls.set(norm(d.name), d);\n this.scopes.set(token, {\n kind: \"foreign\", resolver, decls, scopeWritable: o.writable ?? true, norm,\n ...(o.owner !== undefined ? { owner: o.owner } : {}),\n });\n this.rev++;\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(e.norm(name));\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 scope.\n *\n * `writable: false` is the STORY's promise, so a story write is refused and\n * a HOST write is not: pass `{ host: true }` from a host's own surface (its\n * `setProperty`, its tooling, a coverage driver) and never from the path an\n * outcome or effect takes. A foreign scope whose resolver has no `set` is\n * refused for everyone, host included - that is not a rule to bypass, it is\n * a game that gave no way to write. */\n set(scope: string, name: string, value: ScalarValue, opts?: { host?: boolean }): 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, opts?.host ? { host: true } : undefined);\n } catch {\n throw new Error(`'@${scope}.${name}' is read-only`);\n }\n return;\n }\n const n = e.norm(name);\n if (!e.resolver.set) throw new Error(`'@${scope}.${name}' is read-only`);\n if (!opts?.host && !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; owner?: string } & PropertyRow)[] {\n const out: ({ scope: string; owner?: string } & PropertyRow)[] = [];\n for (const [token, e] of this.scopes) {\n const owner = e.owner !== undefined ? { owner: e.owner } : {};\n if (e.kind === \"owned\") {\n for (const row of e.bag.rows()) out.push({ scope: token, ...owner, ...row });\n } else {\n for (const [n, d] of e.decls) {\n out.push({\n scope: token, ...owner,\n ...rowFor(d, e.resolver.get(n), this.foreignWritable(e, n), n, `${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>, opts?: AliasOptions): EvalContext {\n const view = this.view(opts?.aliases);\n const scopes: EvalContext[\"scopes\"] = {};\n for (const [token, e] of view) scopes[token] = e.kind === \"owned\" ? e.bag.values : e.resolver;\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(view);\n return qualities.size === 0 ? { scopes, host } : {\n scopes, host,\n qualities: (scope, name) => {\n const e = view.get(scope);\n return e ? qualities.get(scope)?.get(normOf(e)(name)) : undefined;\n },\n };\n }\n\n /**\n * The scopes an expression sees: every registered key under its own token,\n * then each alias token pointing at its key's entry (an alias shadows a key of\n * the same name). Keys an engine uses for instance bags (`engine/flow-2/...`)\n * are not valid expression tokens, so they are present but unreachable.\n */\n private view(aliases?: Record<string, string>): Map<string, Entry> {\n const out = new Map(this.scopes);\n for (const [token, key] of Object.entries(aliases ?? {})) {\n const e = this.scopes.get(key);\n if (!e) throw new Error(`alias '@${token}' names '${key}', which is not registered`);\n out.set(token, e);\n }\n return out;\n }\n\n /** Every quality declaration's ladder, keyed scope token then name (the\n * scope's own normalisation). */\n private qualityLadders(view: Map<string, Entry>): Map<string, Map<string, readonly string[]>> {\n const out = new Map<string, Map<string, readonly string[]>>();\n for (const [token, e] of view) {\n for (const [n, d] of declsOf(e)) {\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(n, 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. Aliases\n * apply as they do to `toEvalContext`, so a condition written against `@scene`\n * validates against the instance bag the engine names.\n */\n toSchema(opts?: AliasOptions): ExpressionSchema {\n const properties = new Map<string, Map<string, { type: PropertyType; enumValues?: string[]; stages?: string[] }>>();\n for (const [token, e] of this.view(opts?.aliases)) {\n const decls = declsOf(e);\n if (decls.length === 0) continue;\n const m = new Map<string, { type: PropertyType; enumValues?: string[]; stages?: string[] }>();\n for (const [n, d] of decls) m.set(n, {\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 (foreign scopes are the game's, and the game\n * saves them), as bare bags keyed by token, plus any values still parked, so\n * a save taken before every engine has re-registered loses nothing. The\n * registry knows nothing about game saves: a game embeds this in its own. */\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 for (const [token, vals] of this.parked) out[token] = structuredClone(vals);\n return out;\n }\n\n /**\n * Restore from a `save` blob. An owned scope lays its section over its current\n * values (the bag's `load` rule). A section for a key nobody has registered\n * yet is PARKED and handed over when that key registers, so a game can load\n * its registry before its engines have reopened their flows or decks. A\n * section for a foreign scope is ignored: those values are the game's.\n *\n * A load replaces whatever was parked before it: it is a whole restore, and\n * residue from an earlier load must not leak into this one.\n *\n * Changed in 0.7.0: sections for unregistered keys used to be dropped.\n */\n load(blob: Record<string, Record<string, ScalarValue>>, opts?: LoadOptions): void {\n if (!opts?.keepParked) this.parked.clear();\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 else if (!e) this.parked.set(token, structuredClone(vals));\n }\n }\n\n /**\n * `save()` wrapped with a version stamp.\n *\n * @deprecated Versioning belongs to the save that embeds the values; no\n * engine ever called this. Embed `save()` in your own versioned save.\n * Removed at the next breaking release.\n */\n saveFragment(): OwnedStateFragment {\n return { version: SAVE_FRAGMENT_VERSION, scopes: this.save() };\n }\n\n /**\n * Restore from a versioned fragment; an unsupported version throws.\n *\n * @deprecated See `saveFragment`. Removed at the next breaking release.\n */\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 /**\n * A token is taken once. There is no reserved-token list: a clash surfaces\n * here, the moment a game combines its engines, which is the only moment\n * anyone knows which engines are present. With owners recorded the error says\n * whose token it already is.\n */\n private assertFree(token: string, owner?: string): void {\n const e = this.scopes.get(token);\n if (!e) return;\n const by = e.owner !== undefined ? ` by ${e.owner}` : \"\";\n const wants = owner !== undefined ? ` (wanted by ${owner})` : \"\";\n throw new Error(`scope '@${token}' is already registered${by}${wants}`);\n }\n}\n\n/** A scope entry's declarations, keyed by its own normalisation. */\nfunction declsOf(e: Entry): [string, ScopeDeclaration][] {\n if (e.kind === \"foreign\") return [...e.decls.entries()];\n return e.bag.declarations().map((d) => [e.bag.normalise(d.name), d]);\n}\n\n/** A scope entry's name normalisation. */\nfunction normOf(e: Entry): (name: string) => string {\n return e.kind === \"foreign\" ? e.norm : (n) => e.bag.normalise(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 reference runtime: an Engine is the world + flow manager, and ALL play\n// happens on a Flow handle (design/flows.md; the shape is Patter's, adopted\n// deliberately so a host driving both engines holds two objects with the\n// same grammar). The dealing semantics of design/storylets-schema.md\n// section 3 run per flow, implemented exactly and held to the conformance\n// corpus.\n//\n// The flow model, in one place:\n// - an Engine owns the bundle, every lookup built from it, the SHARED\n// property partitions and the @world resolver; a Flow owns its own\n// PRNG, per-box clocks, cooldowns, board, claims, play history and the\n// per-flow property partitions. Flows meet only through shared state.\n// - sharing is a per-property `shared` flag on the declaration (never a\n// scope token): @story defaults shared; box, deck, hand and tag\n// properties default per-flow. Every name is shared XOR per-flow, so a\n// read is a union of two bags and a write routes by name.\n// - every property bag lives in ONE ScopeRegistry per game (the\n// one-registry model): the game hands the engine its registry\n// (EngineOptions.registry) or the engine makes its own and acts as its\n// own game. The shared @story registers under `story`, every other bag\n// under a key starting `storylets/`, which no expression can name.\n// saveGame() carries what is NOT a property, plus the registry's values\n// only when the engine made the registry itself.\n// - @world is the game's: a resolver it binds (EngineOptions.world, never\n// saved), a scope it registers in its registry, or, for a standalone\n// engine, a self-backed bag the registry stores and saves.\n// - there is no default flow and no ambient current flow: openFlow(id) is\n// the only way in, an existing id is REPLACED (the old flow closes),\n// and a closed flow's handle is INERT - every verb throws (Patter's\n// stale-handle rule).\n// - engine.getProperty serves world.* and shared refs only; a ref that\n// resolves per-flow throws, naming the fix (Patter's teaching rule).\n// - the PROJECT MAP (design/project-map-contract.md 3) is one zone group\n// above the boxes, in `bundle.map.group` and in no box's `tagGroups`. A\n// box that opts in (`usesMap`) sees its name beside its own groups', so\n// its hands bind zones and its cards are tagged with them by id exactly\n// as with a box group. Each zone is ONE value bag, keyed by the tag's id\n// like any tag's, so a zone property is one value whichever box's hand\n// is dealt to it; the `shared` flag still decides per-flow against one\n// for the engine. What the boxes on a map do NOT share: a hand deals only\n// from its own box's decks, and play history stays the asking box's\n// (D7). A bundle that breaks the map's rules is refused at construction\n// (3.8) rather than half-played.\n//\n// Key dealing contracts, unchanged from round 2 (all per flow now):\n// - two verbs: deal(hand) claims, peek(box, criteria) just looks; you can\n// never play a card you only peeked (3.1, look/use rule)\n// - availability order: deck gate -> cooldown -> tags -> hand condition ->\n// card condition -> claims (3.1)\n// - claims are physical WITHIN a flow: a card sits in at most `copies`\n// hands of that flow's board at once, at most once in any one hand; the\n// ledger is derived from the board contents (3.5)\n// - a SHARED card (its deck's flag, or its own overriding it) is scarce\n// across flows too: at most `sharedCopies` hands anywhere, counted over\n// every live flow's board, and a shared `redraw: \"never\"` is spent for\n// everyone the first time anyone plays it. A finite redraw deliberately\n// stays per flow - a cooldown is an absolute turn of a per-flow clock, so\n// there is nothing shared to compare it against (design/shared-scarcity.md)\n// - the reserved home group inverts the wildcard: a homed card is\n// available only to an ask binding its home (2.4)\n// - ranking: priority desc -> specificity desc (box toggle) -> seeded\n// shuffle of each maximal tie run (3.2)\n// - one PRNG per flow: expression random(), tie shuffles and the batch\n// deal's hand-order shuffle all advance it; state lives in the save (3.3)\n// - each box has its own turn counter PER FLOW; cooldowns are absolute\n// next-eligible turns of the card's box's clock, set at play time from\n// the post-advance turn; \"never\" is MAX_SAFE_INTEGER, not Infinity (3.4)\n// - @hand composes bound-tag props -> hand props -> chosen tags/criteria\n// (by group name), later shadowing earlier; writes route back to their\n// source; criteria names cannot be written (3.6)\n// - outcome availability is never snapshotted: outcomes() and play()\n// evaluate gates against current state (3.1, 3.7)\n// - a trace event fires after the state it reports has landed, so a\n// handler reading the flow inside it sees the effect (the Live Link's\n// board snapshot depends on this; the shared fixture pins it)\n// ---------------------------------------------------------------------------\n\nimport { deserialiseAst, evaluate } from \"@wildwinter/expr\";\nimport type { EvalContext, ExprNode, ScalarValue, ScopeResolver } from \"@wildwinter/expr\";\nimport { matchedSpecificity } from \"@wildwinter/expr-specificity\";\nimport { storyletsDialect, NEVER_PLAYED } from \"@storylet-studio/dialect\";\n\n/** The play-history indexes' key for one (box, group, tag) triple.\n *\n * The BOX is in it because play history is box-specific (design/project-map-\n * contract.md 3.7, D7, ruled 2026-10-01): `count_played_in` asks about the\n * asking box's own plays. A box group was already box-unique, so its key never\n * needed the box; a project-map zone is one tag every opted-in box tags its\n * cards with, and without the box a play of a newspaper at the quay in one box\n * would count as an encounter at the quay in another.\n *\n * A UNIT SEPARATOR (U+001F) joins them: ids are letters, digits and\n * underscores, so a control character cannot occur in one and two different\n * triples can never collide into one key the way a \".\" or \":\" join could. NUL\n * would say the same thing and was the first choice, but GDScript will not\n * carry one in a string - it substitutes U+FFFD and warns on every parse - and\n * the four runtimes keep the same spelling. */\nconst tagKey = (boxId: string, groupId: string, tagId: string): string =>\n `${boxId}\\u001f${groupId}\\u001f${tagId}`;\n\nimport type { StoryletsHost } from \"@storylet-studio/dialect\";\nimport {\n BUNDLE_SCHEMAS, PLACE_GROUP, allTagGroups, ambiguousValueAddressMessage, effectiveGameId, groupsOfBox,\n isHoleRef, parseHoleRef, valueAddresses, zoneQualifiedValueAddressMessage,\n} from \"@storylet-studio/model\";\nimport type {\n Box, Bundle, BundleContent, Card, Deck, Expression, FlowSave, Hand, HandTemplate,\n LoadEviction, LoadProperty, LoadReport, PlayRecord, PropertyBag, PropertyDecl, PropsPartition,\n SaveEnvelope, SaveEnvelopeV1, Tag, TagGroup,\n} from \"@storylet-studio/model\";\nimport { SAVE_SCHEMA, SAVE_SCHEMA_V1 } from \"@storylet-studio/model\";\nimport { PropertyBag as StateBag, ScopeRegistry } from \"@wildwinter/scoperegistry\";\nimport type { PropertyRow, ScopeDeclaration } from \"@wildwinter/scoperegistry\";\nimport { makePrng, shuffleInPlace } from \"./prng.js\";\nimport type { Prng } from \"./prng.js\";\n\nexport interface EngineOptions {\n /** Default seed for each flow's PRNG; override per flow in openFlow\n * (cross-runtime determinism, schema 3.3). Default 0. */\n seed?: number;\n /** Retain each flow's event log for introspection - the game-engine seam\n * (schema 5): every trace event, sequence-stamped and turn-stamped where\n * the event has a box context. `true` keeps the default 1000 entries\n * (oldest dropped first). Off by default; subscribeTrace stays the\n * zero-retention stream. */\n log?: boolean | { cap?: number };\n /**\n * The host's resolver for @world - the values the game owns and the\n * story reads (and, where `set` is offered, writes). Engine-level, shared\n * by all flows, never saved: the game keeps these values. Omit it and a\n * standalone engine self-backs @world from the declared defaults, as a\n * property its registry stores and saves. A game running several engines\n * registers @world in its registry itself instead.\n */\n world?: ScopeResolver;\n /**\n * The game's registry: ONE per game, holding every engine's properties\n * except those the game keeps itself, saved once. Given one, the engine\n * registers its own scopes in it (@story under `story`, every other bag\n * under a key starting `storylets/`, and @world if `world` is passed),\n * reads every other scope from it, and `saveGame()` leaves the property\n * values to the game. @world is then the game's to register: owned if the\n * registry should store it, foreign if the game keeps it. Omit it and the\n * engine makes its own registry and acts as its own game: it self-backs\n * @world, and `saveGame()` carries the registry's values too.\n */\n registry?: ScopeRegistry;\n /**\n * Diagnostics hook (opt-in, dev tooling only): fired when `openFlow` REPLACES\n * a flow that still had cards dealt, with the flow id and how many. The\n * behaviour is unchanged - replacing is deliberate and the same in Patter -\n * this only makes it observable, because the case it catches is a host\n * calling `openFlow` straight after `loadGame` to \"re-take\" its handle and\n * silently discarding the hand the save just restored (`getFlow` is the\n * call). Zero cost when unset; leave it unset in shipped games.\n */\n onReplacedFlow?: (id: string, dealt: number) => void;\n}\n\nexport interface OpenFlowOptions {\n /** Seed for this flow's PRNG (defaults to the engine's `seed`). */\n seed?: number;\n /**\n * Open this flow AS IT WAS: a blob from `saveFlow`, applied to the freshly\n * opened (or replaced) flow before the handle comes back\n * (design/engine-server.md 4.1).\n *\n * An option on `openFlow` rather than a `Flow.restore` verb on purpose:\n * restoring INTO a running flow is the trap hosts keep falling into\n * (openFlow REPLACES), and \"open this flow as it was\" is one act. Drift is\n * tolerated exactly as `loadGame` tolerates it, with one addition, because\n * this restore lands in a LIVE engine: a shared card whose world copies are\n * all held by the OTHER open flows is not put back, and is reported as\n * `claimed-elsewhere`. Ask `previewFlowRestore` first to see that coming.\n */\n restore?: FlowSave;\n /** Handed the `restore`'s LoadReport as it happens - the same report\n * `previewFlowRestore` returns for the same blob. Ignored without\n * `restore`; the report has nowhere else to go, since `openFlow` returns\n * the handle. */\n onRestoreReport?: (report: LoadReport) => void;\n}\n\n/** A card view in a dealt hand or a peeked list. Carries NO outcome\n * availability - ask `outcomes()` for current truth (schema 5). */\nexport interface DealtCard {\n id: string;\n gameId: string;\n title?: string;\n purpose?: string;\n fields?: Record<string, ScalarValue>;\n}\n\nexport interface OutcomeView {\n id: string;\n gameId: string;\n title?: string;\n purpose?: string;\n /** The outcome's fields, exactly as the bundle carries them: game data\n * declared by the box's `outcomeFields`, never read by the engine. */\n fields?: Record<string, ScalarValue>;\n /** Evaluated against CURRENT state at the moment of the ask. */\n available: boolean;\n}\n\n/** What a peek returns: the top of the stock, looked at and put back.\n * The engine has no pick policy (Reboot 2.1). */\nexport interface RankedList {\n box: string;\n cards: DealtCard[];\n}\n\nexport interface PlayOptions {\n /** Turn advance override; default settings.playAdvancesTurns, or 0 when the\n * card's box is timed (design/engine-server.md 4.8). */\n advanceTurns?: number;\n}\n\n// --- the trace (schema 5): the deal/play log for tooling ----------------------\n\n/** Why a card did or did not make an ask, in availability order (schema 3.1). */\nexport type TraceVerdict =\n | \"dealt\" // in the hand / the returned list\n | \"capped\" // eligible, ranked below the size cap\n | \"cooldown\" // schema 3.1 step 1\n | \"deck-gate\" // step 2\n | \"tags\" // step 3 (incl. the home group's inverted default)\n | \"condition\" // steps 4-5 (a failing or erroring condition)\n | \"priority\" // a priority expression errored or was not a number\n | \"claimed\" // step 6: no free copy on YOUR board\n | \"claimed-elsewhere\" // step 6: another flow holds the world's copies\n | \"taken\"; // a shared redraw:never was spent, by anyone, for everyone\n\n/** One event on the deal/play log - \"why did Ambush at the ford get dealt\n * here?\" is answered by the ask event's per-card verdicts and keys. The\n * verb is the event type, so a peek is distinguishable from a deal when\n * reading a run back.\n *\n * IDENTITY IS BY GAMEID throughout (design/engine-server.md 4.4). It was\n * mixed until then: `deal.hand` and `peek.box` were gameIds while\n * `evict.hand`, `play.card` and every `cards[].id` were internal ids, so\n * every consumer outside the engine - the Board, the four examiners, the\n * Live Link, a wire a kiosk reads - mapped one to the other itself. */\nexport type TraceEvent =\n | {\n type: \"deal\";\n /** Hand gameId. */\n hand: string;\n /** `id` is the card's GAMEID (design/engine-server.md 4.4). */\n cards: { id: string; verdict: TraceVerdict; priority?: number; specificity?: number }[];\n }\n | {\n type: \"peek\";\n /** Box gameId. */\n box: string;\n criteria: Record<string, string>;\n /** `id` is the card's GAMEID (design/engine-server.md 4.4). */\n cards: { id: string; verdict: TraceVerdict; priority?: number; specificity?: number }[];\n }\n /** Hand and card gameIds. A card the build no longer has (`vanished`) has\n * no gameId left and is named by the id the board carried. */\n | { type: \"evict\"; hand: string; card: string; reason: TraceVerdict | \"hand-condition\" | \"vanished\" }\n /** Card and outcome gameIds; `outcome` is \"\" for a card with no outcomes,\n * played with none. */\n | { type: \"play\"; card: string; outcome: string; turn: number }\n /** One landed outcome change; `path` is the resolved store location, in the\n * address grammar `getProperty` takes - the owner segment is its gameId (a\n * routed @hand write shows where it actually went, schema 3.6). `prev`\n * is the value it replaced, so a log can read \"0 -> 1\". */\n | { type: \"write\"; target: string; path: string; value: ScalarValue; prev?: ScalarValue }\n /** An explicit clock advance via advanceTurns (schema 3.4); `turn` is the\n * box's new value. Plays stamp their own turn on the play event. */\n | { type: \"turns\"; box: string; turn: number }\n /** An expression eval error: never a silent pass (schema 3.1), always a\n * visible diagnostic. */\n | { type: \"diagnostic\"; where: string; message: string };\n\nexport type TraceHandler = (event: TraceEvent) => void;\n/** The engine-level tap: every flow's events, tagged with the flow id -\n * the tools' one stream. */\nexport type EngineTraceHandler = (flow: string, event: TraceEvent) => void;\n\n/** A retained log entry: the trace event plus its place in flow time.\n * `seq` orders the whole flow (monotonic; survives clearLog). `turn` is\n * the clock of the box the event happened in when it fired (peek: the box;\n * deal/evict: the hand's box; play and its writes: the played card's box,\n * stamped together with the play's own turn). Diagnostics carry no turn. */\nexport type LogEntry = TraceEvent & { seq: number; turn?: number };\n\n/** One entry on the ENGINE's log: the same event, plus the flow it happened\n * in. A run is several flows over shared state, so \"what happened in this\n * run\" is only answerable in one ordered stream, and only if each line says\n * who. The flow's own log stays flow-local and unchanged. */\nexport type EngineLogEntry = LogEntry & { flow: string };\n\n// --- internals ---------------------------------------------------------------\n\ninterface CardEntry {\n card: Card<Expression>;\n deck: Deck<Expression>;\n box: Box<Expression>;\n}\n\n/** Is this card scarce across flows (design/shared-scarcity.md)? The deck says\n * what the pile is for and the card may override it, the same inheritance a\n * property has with its scope default. Hoist the deck's flag out of a card\n * loop and pass the answer down: the ask runs this per card per deal. */\nconst cardIsShared = (card: Card<Expression>, deckShared: boolean): boolean =>\n card.shared ?? deckShared;\n\n/** How many hands ACROSS EVERY FLOW may hold this at once. Defaults to\n * `copies`, so the common case writes one number and only \"five in the world,\n * one to a customer\" needs both. Meaningless on an unshared card, and the\n * compiler warns when one sets it. */\nconst sharedCap = (card: Card<Expression>): number => card.sharedCopies ?? card.copies ?? 1;\n\ntype HandSource = { kind: \"value\"; id: string } | { kind: \"hand\"; id: string } | { kind: \"criteria\" };\n\n/** The composed @hand for one ask: the read bag, plus where each name\n * routes on write (schema 3.6). */\ninterface HandEnv {\n bag: PropertyBag;\n sources: Map<string, HandSource>;\n /** tag group id -> bound tag id (home included, its \"tag\" a hand id). */\n boundTags: Map<string, string>;\n}\n\n/** One ask, resolved: a deal (hand present, condition from its template or\n * rule) or a peek (criteria only, no condition - schema 3.1). */\ninterface AskDescriptor {\n box: Box<Expression>;\n hand?: Hand<Expression>;\n condition?: Expression;\n /** tag group id -> tag id, everything the ask binds (fixed + chosen +\n * criteria; for deals also home -> the hand's own id). */\n boundTags: Map<string, string>;\n /** Chosen tags / criteria surfaced into @hand by group gameId, the tag's\n * gameId as the value (schema 3.6). */\n askNames: Record<string, string>;\n}\n\n/** The owner label on everything this engine registers: named in a clash\n * error and carried on the registry's examiner rows. */\nconst OWNER = \"Storylet Engine\";\n\n/** Identity: storylets property names are case-significant as authored. */\nconst identity = (n: string): string => n;\n\n/** The registry keys this engine's bags live under. An id is escaped (`%` and\n * `/`) so no two keys can meet. Every runtime writes the same keys: they are\n * in the save. Owners are keyed by INTERNAL id, as the save always was, so a\n * save survives a rename. */\nconst esc = (id: string): string => id.replace(/%/g, \"%25\").replace(/\\//g, \"%2F\");\nconst unesc = (id: string): string => id.replace(/%2F/g, \"/\").replace(/%25/g, \"%\");\nconst sharedKey = (kind: OwnedScope, id: string): string => `storylets/${kind}/${esc(id)}`;\nconst flowPrefix = (flowId: string): string => `storylets/flow/${esc(flowId)}/`;\nconst flowKey = (flowId: string, kind: FlaggedScope, id?: string): string =>\n kind === \"story\" ? `${flowPrefix(flowId)}story` : `${flowPrefix(flowId)}${kind}/${esc(id!)}`;\n\n/** A registry section's values: registry key -> name -> value. */\ntype Sections = Record<string, PropertyBag>;\n\nconst emptyPartitionValues = (): PropsPartition => ({ story: {}, box: {}, deck: {}, hand: {}, value: {} });\n\n/** Sort a registry save's sections back into partitions, for the load walk:\n * the shared ones, each flow's (only the flows the save restores; the rest\n * are dropped), and everything that is not this engine's, passed through. */\nfunction partitionsFromSections(sections: Sections, flowIds: Set<string>): {\n shared: PropsPartition; flows: Map<string, PropsPartition>; rest: Sections;\n} {\n const shared = emptyPartitionValues();\n const flows = new Map<string, PropsPartition>();\n const rest: Sections = {};\n const flowOf = (escaped: string): PropsPartition | undefined => {\n const id = unesc(escaped);\n if (!flowIds.has(id)) return undefined;\n let p = flows.get(id);\n if (!p) { p = emptyPartitionValues(); flows.set(id, p); }\n return p;\n };\n for (const [key, values] of Object.entries(sections)) {\n let m: RegExpExecArray | null;\n if (key === \"story\") shared.story = values;\n else if ((m = /^storylets\\/(box|deck|hand|value)\\/([^/]+)$/.exec(key))) shared[m[1] as OwnedScope][unesc(m[2]!)] = values;\n else if ((m = /^storylets\\/flow\\/([^/]+)\\/story$/.exec(key))) { const p = flowOf(m[1]!); if (p) p.story = values; }\n else if ((m = /^storylets\\/flow\\/([^/]+)\\/(box|deck|hand|value)\\/([^/]+)$/.exec(key))) {\n const p = flowOf(m[1]!); if (p) p[m[2] as OwnedScope][unesc(m[3]!)] = values;\n } else if (!key.startsWith(\"storylets/\")) rest[key] = values;\n }\n return { shared, flows, rest };\n}\n\n/** A cleaned partition as registry sections, keyed the way its bags register.\n * Empty sections are left out: they would load nothing, and a section for a\n * bag that never registers would wait in the registry for ever. */\nfunction sectionsOf(p: PropsPartition, keyOf: (kind: FlaggedScope, id?: string) => string, out: Sections): void {\n if (Object.keys(p.story).length > 0) out[keyOf(\"story\")] = p.story;\n for (const kind of [\"box\", \"deck\", \"hand\", \"value\"] as const) {\n for (const [id, values] of Object.entries(p[kind])) if (Object.keys(values).length > 0) out[keyOf(kind, id)] = values;\n }\n}\n\n// Stores are shared-kernel bags (@wildwinter/scoperegistry, the properties\n// implementer Patter shares): identity normalisation because storylets\n// property names are case-significant as authored.\n// `pathPrefix` carries its own separator, so a bag composes its rows' addresses itself\n// (`story.gold`, `deck.tavern.drawn`) instead of every caller pasting a prefix onto a row.\nconst bagFromDecls = (decls: PropertyDecl[], pathPrefix: string): StateBag =>\n new StateBag(decls, { normalise: (n) => n, pathPrefix });\n\n// Truthiness for a bare condition. Booleans and numbers as you would expect;\n// a string passes when non-empty and a flag list when non-empty, matching\n// JavaScript's own coercion for those two.\n//\n// Until 2026-09-01 this admitted ONLY booleans and numbers, and Patterplay's\n// `truthy` admitted strings and lists as well. That was drift from writing the\n// two engines at different times, not a considered difference: the two share a\n// property registry, so the same value read from the same registry answered a\n// condition differently depending on which engine asked. expr-specificity calls\n// truthiness host-bound, and it is, but \"host-bound\" is licence for a host to\n// choose, not licence for two hosts in one family to disagree by accident.\nfunction conditionPasses(v: ScalarValue): boolean {\n if (typeof v === \"boolean\") return v;\n if (typeof v === \"number\") return v !== 0;\n if (typeof v === \"string\") return v !== \"\";\n return v.length > 0; // string[] (flags)\n}\n\n// PropertyView is gone. It was the shared PropertyRow plus a `path`, and `path` moved onto\n// that row on 2026-09-02 - so the name was a synonym, and a synonym for a shared type is how\n// the two families drifted in the first place: the same row called PropertyView here,\n// ScopePropertyRow next to it, PropertyRow in the kernel. listProperties() returns PropertyRow.\n\n/** One kernel bag with its store path prefix (story / box.<gameId> / deck.<gameId>\n * / hand.<gameId> / value.<gameId>): the state logger's mount surface\n * (design/engine-runtimes.md 3.4 - the logger builds on the PropertyBag\n * audit hook, so it needs the bags themselves, not just their rows).\n * The Engine lists the shared bags, a Flow its own; the @world container\n * is the host's bag and the host mounts it itself. loadGame() replaces\n * every bag, so re-enumerate after a load. */\nexport interface BagMount {\n prefix: string;\n bag: StateBag;\n}\n\n/** One box on the enumeration surface (examiners, hosts): identity plus\n * its clock (per flow). */\nexport interface BoxView {\n id: string;\n gameId: string;\n title?: string;\n turn: number;\n}\n\n/** The sharing default per scope (design/flows.md, the old system's rule):\n * @story is the playthrough family's globals, shared; the narrower scopes\n * are geographic, per-flow, so \"this flow's danger in the docks\" stays\n * expressible. A declaration's `shared` flag overrides. */\nconst SCOPE_DEFAULT_SHARED = { story: true, box: false, deck: false, hand: false, value: false } as const;\ntype FlaggedScope = keyof typeof SCOPE_DEFAULT_SHARED;\n\nconst isShared = (scope: FlaggedScope, d: PropertyDecl): boolean => d.shared ?? SCOPE_DEFAULT_SHARED[scope];\nconst sharedHalf = (scope: FlaggedScope, decls: PropertyDecl[]): PropertyDecl[] =>\n decls.filter((d) => isShared(scope, d));\nconst flowHalf = (scope: FlaggedScope, decls: PropertyDecl[]): PropertyDecl[] =>\n decls.filter((d) => !isShared(scope, d));\n\n/** One side's five declaration lists, keyed by owner id where the scope has\n * owners. The bags are built from these; so is the load report's answer to\n * \"what does this build declare that the save does not carry\". */\ninterface DeclSet {\n story: PropertyDecl[];\n box: Map<string, PropertyDecl[]>;\n deck: Map<string, PropertyDecl[]>;\n hand: Map<string, PropertyDecl[]>;\n value: Map<string, PropertyDecl[]>;\n}\n\n/** The four owned property scopes: the ones whose address carries an owner\n * segment. `story` has no owner and `world` is the host's. */\ntype OwnedScope = \"box\" | \"deck\" | \"hand\" | \"value\";\nconst OWNED_SCOPES = [\"box\", \"deck\", \"hand\", \"value\"] as const;\n\n/** The owner segment of a property address, both ways round\n * (design/engine-server.md 4.4).\n *\n * `gameId` is the segment the ADDRESS uses; `id` is the internal id everything\n * inside the engine is keyed by - the bags, the save envelope, the ladders.\n * Both maps are built in bundle order and a repeated gameId does NOT\n * overwrite the first.\n *\n * Box, deck, hand and card gameIds are unique bundle-wide, so for three of the\n * four scopes the segment is simply the gameId. A TAG's is unique only within\n * its group, and a group's only within its box, so two boxes may each name a\n * tag \"docks\": the value scope's segment is box-qualified,\n * `value.<boxGameId>/<tagGameId>.<name>`, wherever a gameId repeats, and the\n * short form is REFUSED there rather than resolved to the first in bundle\n * order. `valueAddresses` in the model is the one definition of that rule -\n * the Board draws these addresses from the bundle while the engine builds them\n * from this index, and the two have to agree - and `repeated` is what it\n * found, so a refusal can name the candidates.\n *\n * Two GROUPS in one box naming the same tag is the case the box qualifier\n * cannot separate, and it is closing at the source rather than here (question\n * 16, ruled 2026-09-06): the compiler warns that a tag gameId must be unique\n * within its box, and refuses it from the next release. Until then the first\n * in bundle order answers, as it always did.\n */\ninterface OwnerIndex {\n gameId: Map<string, string>; // internal id -> owner segment\n id: Map<string, string>; // owner segment -> internal id (first in bundle order wins)\n repeated: Map<string, string[]>; // an ambiguous short form -> the qualified candidates\n zoneQualified: Map<string, string>; // \"<box>/<zone>\" -> \"<zone>\", refused (value scope only)\n}\n\ntype OwnerIndexes = Record<OwnedScope, OwnerIndex>;\n\nconst emptyOwnerIndex = (): OwnerIndex =>\n ({ gameId: new Map(), id: new Map(), repeated: new Map(), zoneQualified: new Map() });\nconst emptyOwnerIndexes = (): OwnerIndexes => ({\n box: emptyOwnerIndex(), deck: emptyOwnerIndex(), hand: emptyOwnerIndex(), value: emptyOwnerIndex(),\n});\n\nconst indexOwner = (index: OwnerIndex, entity: { id: string; gameId?: string; title?: string }): void => {\n const gameId = effectiveGameId(entity);\n index.gameId.set(entity.id, gameId);\n if (!index.id.has(gameId)) index.id.set(gameId, entity.id);\n};\n\n/** The value scope's index, whole: the segments to print, the segments to\n * accept, the gameIds that need qualifying, and the box-qualified forms of\n * the project map's zones, which are refused. Built from the bundle rather\n * than tag by tag, because whether a tag's own gameId is enough is a question\n * about the OTHER boxes. */\nconst indexValueOwners = (index: OwnerIndex, bundle: Bundle): void => {\n const addresses = valueAddresses(bundle);\n for (const [id, segment] of addresses.print) index.gameId.set(id, segment);\n for (const [segment, id] of addresses.accept) index.id.set(segment, id);\n for (const [gameId, candidates] of addresses.repeated) index.repeated.set(gameId, candidates);\n for (const [segment, zone] of addresses.zoneQualified) index.zoneQualified.set(segment, zone);\n};\n\n/** One side's five stores (shared on the engine, per-flow on each flow). */\ninterface Partition {\n story: StateBag;\n box: Map<string, StateBag>;\n deck: Map<string, StateBag>;\n hand: Map<string, StateBag>;\n value: Map<string, StateBag>;\n}\n\ntype PartitionKind = keyof Partition;\n\n/** Everything a Flow shares with its Engine: the bundle-derived lookups\n * (immutable), the shared stores (replaced wholesale by loadGame/reset),\n * and the seams. One object, held by both classes - the two are one\n * machine in two lifetimes. */\ninterface Internals {\n bundle: Bundle;\n logCap?: number;\n cardsById: Map<string, CardEntry>;\n cardsByGameId: Map<string, CardEntry>;\n boxesByGameId: Map<string, Box<Expression>>;\n boxesById: Map<string, Box<Expression>>;\n handsById: Map<string, { hand: Hand<Expression>; box: Box<Expression> }>;\n handsByGameId: Map<string, { hand: Hand<Expression>; box: Box<Expression> }>;\n /** The owner segment of a property address, both ways round (4.4). */\n owners: OwnerIndexes;\n templatesById: Map<string, HandTemplate<Expression>>;\n /** Every group by internal id. `box` is absent for the project map's group,\n * which belongs to no box. */\n groupsById: Map<string, { group: TagGroup; box?: Box<Expression> }>;\n requiredGroups: Set<string>;\n nodeCache: WeakMap<Expression, ExprNode>;\n ladders: {\n world: Map<string, readonly string[]>;\n story: Map<string, readonly string[]>;\n box: Map<string, Map<string, readonly string[]>>;\n deck: Map<string, Map<string, readonly string[]>>;\n value: Map<string, Map<string, readonly string[]>>;\n hand: Map<string, Map<string, readonly string[]>>;\n };\n hasQualities: boolean;\n /** Does ANY deck or card in the bundle opt into shared scarcity? False for\n * the overwhelming majority of projects, and when it is false the two\n * claim-ledger walks in dealing are skipped entirely. Same idea as\n * `hasQualities` above: a bundle that does not use a feature must not pay\n * for it. */\n hasShared: boolean;\n /** The per-flow halves of every declaration list, precomputed once: each\n * new flow builds its bags from these. */\n flowDecls: DeclSet;\n /** The shared halves, the same way. Not used to build anything - the shared\n * bags are built straight from the bundle - but a load report has to say\n * what the shared side WOULD hold without building a bag, which is what\n * makes previewLoad pure. */\n sharedDecls: DeclSet;\n /** The shared stores, registered in the registry for the engine's life.\n * Reseeded in place by reset and by a load that carries values. */\n shared: Partition;\n /** The game's one registry (or the engine's own, when it is standalone). */\n registry: ScopeRegistry;\n /** True when the engine made the registry: `saveGame()` then carries its values. */\n ownsRegistry: boolean;\n /** True when the engine self-backed @world (standalone, no resolver bound). */\n selfWorld: boolean;\n /** Every OTHER scope in the registry, as an eval context sees it (instance\n * keys left out), rebuilt only when the registry's set of scopes moves. */\n registryView: () => { scopes: EvalContext[\"scopes\"]; qualities: EvalContext[\"qualities\"] };\n /** @world, read through the registry by name (the scope's own normalisation),\n * so a @world the game registered folded to lower case still answers the\n * names as authored. */\n worldResolver: ScopeResolver;\n /** The @world WRITE seam. `host` says the caller is the GAME's own surface -\n * setProperty, the coverage harness, the CLI's --set - which the shared\n * kernel lets past a `writable: false` (scoperegistry 0.6.0): that flag is\n * the story's promise, not the game's. The story's refusal is the\n * worldReadOnly table below, consulted before this seam is reached. A BOUND\n * resolver is opaque - it takes a name and a value and keeps whatever rule\n * the game has - so the flag only ever reaches the self-backed bag.\n * Undefined when @world cannot be written at all (a resolver bound with no\n * `set`). */\n worldSet?: (name: string, value: ScalarValue, host?: boolean) => void;\n /** @world names declared `writable: false`: the story's promise, kept at\n * runtime as the compiler keeps it at publish (Reboot.md 10). */\n worldReadOnly: Set<string>;\n /** `turn` is the box clock the event happened on, where the caller knows it\n * - the same stamp the flow's own log carries. Unity and Unreal passed it\n * from the start; JS and Godot dropped it, so their examiners printed \"[-]\"\n * on every deal, peek, evict and write line while the other two printed the\n * real turn. Four runtimes, two different run logs (2026-08-29). */\n emitEngine: (flow: string, event: TraceEvent, turn?: number) => void;\n engineTracing: () => boolean;\n}\n\nconst handDeclsOf = (internals: Internals, hand: Hand<Expression>): PropertyDecl[] => {\n if (hand.template !== undefined) {\n return internals.templatesById.get(hand.template)?.properties\n ?? internals.bundle.boxes.flatMap((b) => b.handTemplates).find((t) => t.id === hand.template)?.properties\n ?? [];\n }\n return hand.properties ?? [];\n};\n\n/**\n * One owned property's ADDRESS, owner segment and all: `box.village.mood`.\n *\n * The stores, the save envelope and the ladders stay keyed by internal id -\n * a save must survive a rename, which is the whole reason ids exist - so this\n * is the one place the two vocabularies meet, and it is a formatter, never a\n * lookup key. An owner the build no longer has (a save that outlived an edit)\n * keeps the id it arrived with: there is no gameId left to give it, which is\n * the rule a load report's evictions have always used.\n */\nconst addressOf = (internals: Internals, kind: OwnedScope, id: string): string =>\n `${kind}.${internals.owners[kind].gameId.get(id) ?? id}`;\n\n/**\n * Resolve a property address's owner segment to the internal id the stores are\n * keyed by. `legacy` says the caller used the pre-4.4 form - an internal id\n * where a gameId belongs - which resolves for THIS release and earns a\n * diagnostic; the next lockstep release refuses it, in every scope including\n * `value`, which had the one reprieve until it gained an address of its own.\n * `ambiguous` is a short-form value address two boxes answer to: the caller\n * REFUSES it, listing those candidates. Undefined when the segment names no\n * owner at all, which is the caller's \"no <kind> store\" error.\n */\ntype OwnerLookup = { id: string; legacy: boolean } | { ambiguous: string[] } | { zone: string };\n\nconst resolveOwner = (internals: Internals, kind: OwnedScope, segment: string): OwnerLookup | undefined => {\n // Checked before the lookup, because the short form is deliberately NOT in\n // the accept map when it is ambiguous: silently picking the first tag in\n // bundle order is the bug this removes.\n const candidates = internals.owners[kind].repeated.get(segment);\n if (candidates !== undefined) return { ambiguous: candidates };\n // A box-qualified form of a project-map zone: never accepted, because the\n // zone belongs to no box (design/project-map-contract.md 3.4).\n const zone = internals.owners[kind].zoneQualified.get(segment);\n if (zone !== undefined) return { zone };\n const byGameId = internals.owners[kind].id.get(segment);\n if (byGameId !== undefined) return { id: byGameId, legacy: false };\n // A gameId that equals its id took the branch above, so anything reaching\n // here and known as an id is genuinely the old spelling.\n if (internals.owners[kind].gameId.has(segment)) return { id: segment, legacy: true };\n return undefined;\n};\n\n/** Resolve or throw: the two refusals every property address shares, in one\n * place, so the engine's surface and a flow's answer alike. */\nconst ownerOrThrow = (internals: Internals, kind: OwnedScope, segment: string, name: string): { id: string; legacy: boolean } => {\n const owner = resolveOwner(internals, kind, segment);\n if (owner === undefined) throw new Error(`no ${kind} store \"${segment}\"`);\n if (\"ambiguous\" in owner) throw new Error(ambiguousValueAddressMessage(segment, name, owner.ambiguous));\n if (\"zone\" in owner) throw new Error(zoneQualifiedValueAddressMessage(segment, owner.zone, name));\n return owner;\n};\n\n/** What a legacy address is told. It NAMES the address to move to, because\n * \"that form is deprecated\" without the replacement leaves a host grepping a\n * bundle for ids it never chose. */\nconst legacyAddressMessage = (internals: Internals, kind: OwnedScope, segment: string, name: string): string =>\n `\"${kind}.${segment}.${name}\" names the ${kind} by its internal id; write \"${addressOf(internals, kind, segment)}.${name}\". `\n + `The internal-id form is refused after the next release.`;\n\n/** Build one side of the partition from the bundle. The bags are KEYED by\n * internal id and ADDRESSED by gameId; see addressOf. */\nconst buildPartition = (internals: Internals, half: (scope: FlaggedScope, decls: PropertyDecl[]) => PropertyDecl[]): Partition => {\n const b = internals.bundle;\n const at = (kind: OwnedScope, id: string): string => `${addressOf(internals, kind, id)}.`;\n return {\n story: bagFromDecls(half(\"story\", b.story.properties), \"story.\"),\n box: new Map(b.boxes.map((box) => [box.id, bagFromDecls(half(\"box\", box.properties), at(\"box\", box.id))])),\n deck: new Map(b.boxes.flatMap((box) => box.decks.map(\n (deck): [string, StateBag] => [deck.id, bagFromDecls(half(\"deck\", deck.properties), at(\"deck\", deck.id))]))),\n // A template instance inherits the template's property declarations;\n // a standalone hand declares its own (schema 2.6).\n hand: new Map(b.boxes.flatMap((box) => box.hands.map(\n (hand): [string, StateBag] => [hand.id, bagFromDecls(half(\"hand\", handDeclsOf(internals, hand)), at(\"hand\", hand.id))]))),\n // Every box's tags, then the project map's zones ONCE (design/project-\n // map-contract.md 3.3): a zone is one bag per partition, whichever boxes'\n // hands are dealt to it.\n value: new Map(allTagGroups(b).flatMap((group) => group.tags.map(\n (tag): [string, StateBag] => [tag.id, bagFromDecls(half(\"value\", tag.properties ?? []), at(\"value\", tag.id))]))),\n };\n};\n\nconst partitionValues = (p: Partition): PropsPartition => ({\n story: p.story.values,\n box: Object.fromEntries([...p.box].map(([id, bag]) => [id, bag.values])),\n deck: Object.fromEntries([...p.deck].map(([id, bag]) => [id, bag.values])),\n hand: Object.fromEntries([...p.hand].map(([id, bag]) => [id, bag.values])),\n value: Object.fromEntries([...p.value].map(([id, bag]) => [id, bag.values])),\n});\n\nconst loadPartition = (p: Partition, values: PropsPartition | undefined): void => {\n // Fresh defaults are already in the bags; the saved values land over\n // them: orphaned keys (deleted entities, re-flagged properties) drop;\n // newly declared properties keep defaults.\n p.story.load(values?.story ?? {});\n for (const kind of [\"box\", \"deck\", \"hand\", \"value\"] as const) {\n for (const [id, bag] of Object.entries(values?.[kind] ?? {})) {\n p[kind].get(id)?.load(bag);\n }\n }\n};\n\n// --- the load report (design/engine-server.md 4.9) ---------------------------\n//\n// One walk, two entry points. `previewLoad` runs it and returns the report;\n// `loadGame` runs it, returns the same report and then applies the CLEANED\n// blob the walk produced. Two implementations of \"what does this save cost\"\n// would drift the first time one of them was fixed, so there is one, and the\n// apply half consumes its output rather than repeating its decisions.\n\n/** The report under construction: unsorted, until finishReport orders it. */\ninterface ReportDraft {\n evicted: LoadEviction[];\n droppedCooldowns: { flow: string; card: string }[];\n droppedSpent: string[];\n droppedProperties: LoadProperty[];\n defaultedProperties: LoadProperty[];\n retypedProperties: LoadProperty[];\n}\n\nconst emptyDraft = (): ReportDraft => ({\n evicted: [], droppedCooldowns: [], droppedSpent: [],\n droppedProperties: [], defaultedProperties: [], retypedProperties: [],\n});\n\n/** The sort key separator: a UNIT SEPARATOR, as the play-history indexes use,\n * because it cannot occur in an id, a gameId or a property name. */\nconst SORT_SEP = \"\\u001f\";\n\nconst byKey = <T>(items: T[], key: (item: T) => string): T[] =>\n [...items].map((item) => ({ item, k: key(item) }))\n .sort((a, b) => (a.k < b.k ? -1 : a.k > b.k ? 1 : 0))\n .map((e) => e.item);\n\nconst propKey = (p: LoadProperty): string => `${p.flow ?? \"\"}${SORT_SEP}${p.path}`;\n\n/**\n * Does a saved value still fit its declaration?\n *\n * The type first, then the declaration's own vocabulary: an enum value or a\n * quality stage the edit struck out is still a string of the right type and\n * still no longer a legal value, and a condition comparing against the ladder\n * would answer nonsense about it. A declaration with no vocabulary (`values` /\n * `stages` absent) constrains nothing, so anything of the right type fits.\n */\nfunction valueFits(decl: PropertyDecl, value: ScalarValue): boolean {\n switch (decl.type) {\n case \"boolean\": return typeof value === \"boolean\";\n case \"number\": return typeof value === \"number\";\n case \"string\": return typeof value === \"string\";\n case \"enum\":\n return typeof value === \"string\" && (decl.values === undefined || decl.values.includes(value));\n case \"quality\":\n return typeof value === \"string\" && (decl.stages === undefined || decl.stages.includes(value));\n case \"flags\":\n return Array.isArray(value) && (decl.values === undefined || value.every((f) => decl.values!.includes(f)));\n default: return true;\n }\n}\n\n/** Walk one bag's worth of saved values against one bag's worth of\n * declarations: report the orphans, the newcomers and the misfits, and\n * return the values that survive. */\nfunction walkScope(\n decls: PropertyDecl[] | undefined,\n saved: PropertyBag | undefined,\n path: (name: string) => string,\n flow: string | undefined,\n draft: ReportDraft,\n): PropertyBag {\n const at = (name: string): LoadProperty =>\n ({ ...(flow !== undefined ? { flow } : {}), path: path(name) });\n const byName = new Map((decls ?? []).map((d) => [d.name, d]));\n const values = saved ?? {};\n const clean: PropertyBag = {};\n for (const [name, value] of Object.entries(values)) {\n const decl = byName.get(name);\n if (decl === undefined) { draft.droppedProperties.push(at(name)); continue; }\n if (!valueFits(decl, value)) { draft.retypedProperties.push(at(name)); continue; }\n clean[name] = value;\n }\n for (const decl of decls ?? []) {\n if (!(decl.name in values)) draft.defaultedProperties.push(at(decl.name));\n }\n return clean;\n}\n\n/** The same walk over all five scopes of one partition. An owner the save\n * carries and the build no longer has drops whole (its bag is gone, so its\n * values have nowhere to land); an owner the build has and the save lacks\n * keeps every default. */\nfunction walkPartition(\n internals: Internals,\n decls: DeclSet,\n values: PropsPartition | undefined,\n flow: string | undefined,\n draft: ReportDraft,\n): PropsPartition {\n const out: PropsPartition = {\n story: walkScope(decls.story, values?.story, (n) => `story.${n}`, flow, draft),\n box: {}, deck: {}, hand: {}, value: {},\n };\n for (const kind of [\"box\", \"deck\", \"hand\", \"value\"] as const) {\n const savedKind = values?.[kind] ?? {};\n const ids = [...new Set([...decls[kind].keys(), ...Object.keys(savedKind)])].sort();\n for (const id of ids) {\n // The report's `path` is exactly what listProperties() prints and what\n // setProperty takes: one grammar, so an operator reading a hot-swap\n // report can paste the address straight back in (4.4).\n const owner = addressOf(internals, kind, id);\n out[kind][id] = walkScope(decls[kind].get(id), savedKind[id],\n (n) => `${owner}.${n}`, flow, draft);\n }\n }\n return out;\n}\n\n/** Order the draft and answer the identity questions. `saved` is the content\n * block the save carries; for a single-flow restore there is none, so the\n * caller passes the bundle's own and no drift is reported. */\nfunction finishReport(bundle: BundleContent, saved: BundleContent, flows: string[], draft: ReportDraft): LoadReport {\n const drift = saved.version !== bundle.version || saved.hash !== bundle.hash;\n const evicted = byKey(draft.evicted, (e) => [e.flow, e.hand, e.card, e.reason].join(SORT_SEP));\n const droppedCooldowns = byKey(draft.droppedCooldowns, (c) => `${c.flow}${SORT_SEP}${c.card}`);\n const droppedSpent = [...draft.droppedSpent].sort();\n const droppedProperties = byKey(draft.droppedProperties, propKey);\n const defaultedProperties = byKey(draft.defaultedProperties, propKey);\n const retypedProperties = byKey(draft.retypedProperties, propKey);\n return {\n // `flows` is what the load restores, not something it had to change, so\n // it never makes a report inexact.\n exact: !drift && evicted.length === 0 && droppedCooldowns.length === 0 && droppedSpent.length === 0\n && droppedProperties.length === 0 && defaultedProperties.length === 0 && retypedProperties.length === 0,\n project: bundle.project,\n version: { saved: saved.version, bundle: bundle.version },\n hash: { saved: saved.hash, bundle: bundle.hash },\n flows,\n evicted, droppedCooldowns, droppedSpent,\n droppedProperties, defaultedProperties, retypedProperties,\n };\n}\n\n// --- the Engine ---------------------------------------------------------------\n\n/**\n * Refuse, at construction, a bundle this engine cannot read faithfully\n * (design/project-map-contract.md 3.8). Throws one error naming every problem\n * found, each naming the box and the group or tag at fault.\n *\n * The compiler refuses all of these first. The engine checks again because it\n * cannot tell a hand-built or stale bundle from a compiled one, and the\n * alternative is the silent half-working the server audit found twice: a hand\n * whose bound group is looked up in the wrong place comes back empty, and an\n * old runtime given a map bundle deals plausibly while every zone value is\n * missing. Only what would make the engine's OWN resolution ambiguous or wrong\n * is refused here; the compiler's bundle-wide group-name rule is stricter.\n */\nconst refuseUnreadableBundle = (bundle: Bundle): void => {\n // The schema tag (D4). Checked alone and first: a bundle of a schema this\n // runtime does not know may not have any of the shape the rest reads.\n const schema = (bundle as { schema?: unknown }).schema;\n if (typeof schema !== \"string\" || !BUNDLE_SCHEMAS.includes(schema)) {\n throw new Error(`unsupported bundle schema: ${String(schema)} (this runtime reads ${BUNDLE_SCHEMAS.join(\" and \")})`);\n }\n const problems: string[] = [];\n const map = bundle.map?.group;\n const mapName = map !== undefined ? effectiveGameId(map) : undefined;\n if (map !== undefined && mapName === PLACE_GROUP) {\n problems.push(`the project map's tag group is called \"${PLACE_GROUP}\", which is reserved for a box's own hands`);\n }\n // Every box tag gameId, for the zone-name rule: a zone's address has no\n // qualified form to fall back on (3.4), so any box tag sharing it anywhere\n // makes `value.<zone>.<name>` ambiguous.\n const boxTags = new Map<string, { box: string; group: string }>();\n for (const box of bundle.boxes) {\n for (const group of box.tagGroups) {\n for (const tag of group.tags) {\n const gameId = effectiveGameId(tag);\n if (!boxTags.has(gameId)) boxTags.set(gameId, { box: effectiveGameId(box), group: effectiveGameId(group) });\n }\n }\n }\n for (const tag of map?.tags ?? []) {\n const zone = effectiveGameId(tag);\n const clash = boxTags.get(zone);\n if (clash !== undefined) {\n problems.push(`the project map's zone \"${zone}\" has the name of tag \"${zone}\" in box \"${clash.box}\", group \"${clash.group}\", `\n + `so \"value.${zone}.<name>\" would name two things`);\n }\n }\n for (const box of bundle.boxes) {\n const boxName = effectiveGameId(box);\n if (box.usesMap === true) {\n if (map === undefined) {\n problems.push(`box \"${boxName}\" uses the project map, but the bundle has no map`);\n continue;\n }\n // One namespace in an opted-in box (3.1): a box group with the map's\n // name would make every name-based lookup there a coin toss.\n const twin = box.tagGroups.find((g) => effectiveGameId(g) === mapName);\n if (twin !== undefined) {\n problems.push(`box \"${boxName}\" uses the project map and declares its own tag group \"${mapName}\", the map's name`);\n }\n continue;\n }\n if (map === undefined) continue;\n // A box NOT on the map may not reference its group at all: every route a\n // reference takes, card tags, template bindings and holes, a hand's\n // chosen tags and a rule's bindings, by the group's id as written.\n const names = (where: string): void => {\n problems.push(`box \"${boxName}\" is not on the project map, but ${where} names the map's tag group \"${mapName}\"`);\n };\n for (const deck of box.decks) {\n for (const card of deck.cards) {\n if (card.tags?.[map.id] !== undefined) names(`card \"${effectiveGameId(card)}\"`);\n }\n }\n for (const template of box.handTemplates) {\n if (template.bindings?.[map.id] !== undefined || template.chooses?.includes(map.id) === true) {\n names(`hand template \"${effectiveGameId(template)}\"`);\n }\n }\n for (const hand of box.hands) {\n if (hand.chosen?.[map.id] !== undefined || hand.rule?.bindings?.[map.id] !== undefined) {\n names(`hand \"${effectiveGameId(hand)}\"`);\n }\n }\n }\n if (problems.length > 0) throw new Error(`bundle refused: ${problems.join(\"; \")}`);\n};\n\nexport class Engine {\n private readonly internals: Internals;\n private readonly seed: number;\n private readonly onReplacedFlow: EngineOptions[\"onReplacedFlow\"];\n private readonly flowsById = new Map<string, Flow>();\n private readonly engineTraceHandlers = new Set<EngineTraceHandler>();\n /** The host's @world binding, if the engine was built with one: it\n * outlives reset/loadGame (the host's container is the host's). The\n * self-backed resolver is rebuilt instead. */\n private readonly hostWorld?: ScopeResolver;\n\n /** The options this engine was built with: hotSwap builds its replacement from them. */\n private readonly creationOptions: EngineOptions;\n /** How to register each shared scope again, in registration order: a failed\n * hotSwap puts this engine back exactly as it was. */\n private readonly sharedMounts: Array<{ key: string; mount: () => void }> = [];\n\n constructor(bundle: Bundle, opts: EngineOptions = {}) {\n // First, before anything is indexed or registered: a bundle this engine\n // cannot read faithfully is refused whole (design/project-map-contract.md\n // 3.8), and a refusal must leave the game's registry untouched.\n refuseUnreadableBundle(bundle);\n this.creationOptions = opts;\n this.seed = opts.seed ?? 0;\n this.onReplacedFlow = opts.onReplacedFlow;\n if (opts.world !== undefined) this.hostWorld = opts.world;\n const internals: Internals = {\n bundle,\n ...(opts.log ? { logCap: typeof opts.log === \"object\" ? (opts.log.cap ?? 1000) : 1000 } : {}),\n cardsById: new Map(), cardsByGameId: new Map(),\n boxesByGameId: new Map(), boxesById: new Map(),\n handsById: new Map(), handsByGameId: new Map(),\n owners: emptyOwnerIndexes(),\n templatesById: new Map(), groupsById: new Map(),\n requiredGroups: new Set(),\n nodeCache: new WeakMap(),\n ladders: { world: new Map(), story: new Map(), box: new Map(), deck: new Map(), value: new Map(), hand: new Map() },\n hasQualities: false,\n hasShared: false,\n flowDecls: { story: [], box: new Map(), deck: new Map(), hand: new Map(), value: new Map() },\n sharedDecls: { story: [], box: new Map(), deck: new Map(), hand: new Map(), value: new Map() },\n shared: undefined as unknown as Partition,\n registry: opts.registry ?? new ScopeRegistry(),\n ownsRegistry: opts.registry === undefined,\n selfWorld: false,\n registryView: () => view(),\n worldResolver: undefined as unknown as ScopeResolver,\n worldReadOnly: new Set<string>(),\n emitEngine: (flow, event, turn) => {\n if (this.internals.logCap !== undefined) {\n this.engineLog.push({ ...event, flow, seq: this.engineSeq++, ...(turn !== undefined ? { turn } : {}) });\n if (this.engineLog.length > this.internals.logCap) {\n this.engineLog.splice(0, this.engineLog.length - this.internals.logCap);\n }\n }\n for (const h of this.engineTraceHandlers) h(flow, event);\n },\n engineTracing: () => this.engineTraceHandlers.size > 0,\n };\n this.internals = internals;\n let viewRevision = -1;\n let viewCache: ReturnType<Internals[\"registryView\"]> = { scopes: {}, qualities: undefined };\n const view = (): ReturnType<Internals[\"registryView\"]> => {\n const reg = internals.registry;\n if (reg.revision !== viewRevision) {\n const ctx = reg.toEvalContext();\n const scopes: EvalContext[\"scopes\"] = {};\n // An instance key (`storylets/deck/x`, another engine's) is no expression token.\n for (const [k, v] of Object.entries(ctx.scopes)) if (!k.includes(\"/\")) scopes[k] = v;\n viewCache = { scopes, qualities: ctx.qualities };\n viewRevision = reg.revision;\n }\n return viewCache;\n };\n\n // The value scope's segments come off the whole bundle at once (a tag\n // gameId is only unique within its group), so they are built before the\n // walk rather than tag by tag inside it.\n indexValueOwners(internals.owners.value, bundle);\n\n for (const box of bundle.boxes) {\n internals.boxesById.set(box.id, box);\n internals.boxesByGameId.set(effectiveGameId(box), box);\n indexOwner(internals.owners.box, box);\n for (const group of box.tagGroups) {\n internals.groupsById.set(group.id, { group, box });\n if (group.required === true) internals.requiredGroups.add(group.id);\n }\n for (const deck of box.decks) {\n indexOwner(internals.owners.deck, deck);\n if (deck.shared === true) internals.hasShared = true;\n for (const card of deck.cards) {\n const entry = { card, deck, box };\n internals.cardsById.set(card.id, entry);\n internals.cardsByGameId.set(effectiveGameId(card), entry);\n if (card.shared === true) internals.hasShared = true;\n }\n }\n for (const template of box.handTemplates) {\n internals.templatesById.set(template.id, template);\n }\n for (const hand of box.hands) {\n internals.handsById.set(hand.id, { hand, box });\n internals.handsByGameId.set(effectiveGameId(hand), { hand, box });\n indexOwner(internals.owners.hand, hand);\n }\n }\n // The project map's group: by id like any group, so a hand's binding, a\n // filled hole and tag matching need no logic of their own for it. Which\n // boxes may NAME it is `groupInBox`'s business (3.1); which may reference\n // it at all was settled by the refusal above.\n if (bundle.map !== undefined) {\n internals.groupsById.set(bundle.map.group.id, { group: bundle.map.group });\n if (bundle.map.group.required === true) internals.requiredGroups.add(bundle.map.group.id);\n }\n this.initLadders();\n\n // Both halves, precomputed once (a bundle's declarations never change):\n // each openFlow builds its bags from the per-flow half, and a load report\n // asks either half what it declares without building anything at all.\n const declSet = (half: (scope: FlaggedScope, decls: PropertyDecl[]) => PropertyDecl[]): DeclSet => ({\n story: half(\"story\", bundle.story.properties),\n box: new Map(bundle.boxes.map((box) => [box.id, half(\"box\", box.properties)])),\n deck: new Map(bundle.boxes.flatMap((box) => box.decks.map(\n (deck): [string, PropertyDecl[]] => [deck.id, half(\"deck\", deck.properties)]))),\n hand: new Map(bundle.boxes.flatMap((box) => box.hands.map(\n (hand): [string, PropertyDecl[]] => [hand.id, half(\"hand\", handDeclsOf(internals, hand))]))),\n value: new Map(allTagGroups(bundle).flatMap((group) => group.tags.map(\n (tag): [string, PropertyDecl[]] => [tag.id, half(\"value\", tag.properties ?? [])]))),\n });\n internals.flowDecls = declSet(flowHalf);\n internals.sharedDecls = declSet(sharedHalf);\n\n this.initShared(this.hostWorld);\n }\n\n /** Build the shared stores, register them and @world, and set up the @world\n * seam. Once, for the engine's life: reset and loads reseed the bags in\n * place, so the registry never sees them come and go. */\n private initShared(hostWorld?: ScopeResolver): void {\n const internals = this.internals;\n const reg = internals.registry;\n const worldDecls = internals.bundle.world.properties as unknown as ScopeDeclaration[];\n internals.shared = buildPartition(internals, sharedHalf);\n internals.worldReadOnly = new Set(internals.bundle.world.properties.filter((d) => d.writable === false).map((d) => d.name));\n const registered: string[] = [];\n // Register now, and remember how, so a failed hotSwap can register again.\n const mount = (key: string, register: () => void): void => {\n register();\n registered.push(key);\n this.sharedMounts.push({ key, mount: register });\n };\n try {\n // `story` is this engine's token whether or not the bundle declares a shared\n // @story property: registering it is what makes a clash show at once.\n const story = internals.shared.story;\n mount(\"story\", () => { reg.mountOwned(\"story\", story, { owner: OWNER }); }); // claims values the game loaded first\n for (const kind of OWNED_SCOPES) {\n for (const [id, bag] of internals.shared[kind]) {\n if (bag.declarations().length === 0) continue; // holds nothing: not registered\n mount(sharedKey(kind, id), () => { reg.mountOwned(sharedKey(kind, id), bag, { owner: OWNER }); });\n }\n }\n if (hostWorld !== undefined) {\n // The game keeps these values: an external scope, never saved.\n mount(\"world\", () => { reg.defineForeign(\"world\", hostWorld, worldDecls, { normalise: identity, owner: OWNER }); });\n } else if (internals.ownsRegistry && !reg.has(\"world\")) {\n // Standalone: self-backed from the declared defaults, DECLARATIONS AND\n // ALL, as a property the registry stores and SAVES (only a resolver the\n // game binds is external). The bag keeps `writable: false` so an\n // examiner still reads it there, and the kernel lets a `{ host: true }`\n // write past it, which is what the game's own surface passes.\n reg.defineOwned(\"world\", worldDecls, { normalise: identity, pathPrefix: \"world.\", owner: OWNER });\n const worldBag = reg.ownedBag(\"world\");\n registered.push(\"world\");\n this.sharedMounts.push({ key: \"world\", mount: () => { reg.mountOwned(\"world\", worldBag, { owner: OWNER }); } });\n internals.selfWorld = true;\n }\n // Given the game's registry and no resolver, @world is the game's to\n // register: this engine registers nothing for it.\n } catch (e) {\n for (const k of registered) reg.remove(k, { keep: true }); // a clash leaves the game's registry as it was\n throw e;\n }\n internals.worldResolver = {\n get: (n) => reg.get(\"world\", n),\n set: (n, v) => { reg.set(\"world\", n, v); },\n };\n if (hostWorld !== undefined) {\n // A bound resolver is opaque: it keeps whatever rule the game has, so the\n // story's `writable: false` is kept by worldReadOnly before this seam.\n internals.worldSet = hostWorld.set !== undefined ? (n, v): void => { reg.set(\"world\", n, v, { host: true }); } : undefined;\n } else {\n internals.worldSet = (n, v, host): void => { reg.set(\"world\", n, v, host === true ? { host: true } : undefined); };\n }\n }\n\n /** Every shared bag back to its declared defaults, in place (the registry\n * keeps them registered), the self-backed @world included. */\n private reseedShared(): void {\n const { shared, sharedDecls, registry } = this.internals;\n shared.story.reseed(sharedDecls.story as unknown as ScopeDeclaration[]);\n for (const kind of OWNED_SCOPES) {\n for (const [id, bag] of shared[kind]) bag.reseed((sharedDecls[kind].get(id) ?? []) as unknown as ScopeDeclaration[]);\n }\n if (this.internals.selfWorld) {\n registry.reseedOwned(\"world\", this.internals.bundle.world.properties as unknown as ScopeDeclaration[]);\n }\n }\n\n /** Quality ladders by scope for the eval channel (design/quality.md):\n * world/story keyed by name; box/deck/value keyed by owner id then name.\n * Built once - a bundle's declarations never change. Ladders are\n * declaration-level, so the sharing flag does not touch them. */\n private initLadders(): void {\n const internals = this.internals;\n const grab = (decls: PropertyDecl[] | undefined): Map<string, readonly string[]> => {\n const m = new Map<string, readonly string[]>();\n for (const d of decls ?? []) if (d.type === \"quality\" && d.stages !== undefined) m.set(d.name, d.stages);\n return m;\n };\n const b = internals.bundle;\n internals.ladders.world = grab(b.world.properties);\n internals.ladders.story = grab(b.story.properties);\n for (const box of b.boxes) {\n internals.ladders.box.set(box.id, grab(box.properties));\n for (const deck of box.decks) internals.ladders.deck.set(deck.id, grab(deck.properties));\n for (const group of box.tagGroups) {\n for (const tag of group.tags) internals.ladders.value.set(tag.id, grab(tag.properties));\n }\n for (const hand of box.hands) internals.ladders.hand.set(hand.id, grab(handDeclsOf(internals, hand)));\n }\n // The zones, once, keyed by tag id like every other tag (3.3).\n for (const tag of b.map?.group.tags ?? []) internals.ladders.value.set(tag.id, grab(tag.properties));\n const any = (m: Map<string, Map<string, readonly string[]>>): boolean =>\n [...m.values()].some((x) => x.size > 0);\n internals.hasQualities = internals.ladders.world.size > 0 || internals.ladders.story.size > 0\n || any(internals.ladders.box) || any(internals.ladders.deck)\n || any(internals.ladders.value) || any(internals.ladders.hand);\n }\n\n // --- flow management (Patter's surface, name for name) ----------------------\n\n /** Open (or REPLACE) the named flow. An existing id's flow is closed\n * first - re-opening a name is a reset of that name's whole per-flow\n * state; shared state is untouched. There is no default flow: \"main\" is\n * a caller convention, not an engine rule. */\n openFlow(id: string, opts: OpenFlowOptions = {}): Flow {\n return this.open(id, opts, false);\n }\n\n /** openFlow, and loadGame's rebuild. `claim` says the new flow's bags take\n * the values the registry holds for them (a load); a fresh open is a reset\n * of that name, so anything waiting for it is discarded first. */\n private open(id: string, opts: OpenFlowOptions, claim: boolean): Flow {\n this.assertExternalScopes();\n // The world's claims as they stand WITHOUT this name, taken before the\n // replace: a resume competes with the other flows, never with the flow it\n // is replacing (which is about to release everything it holds).\n const otherClaims = opts.restore !== undefined ? this.sharedClaimsExcept(id) : undefined;\n // Replacing an existing id KEEPS its place in the order. `close()` would\n // drop the key, and a JS Map re-inserts a deleted key at the END, so\n // openFlow(\"a\"); openFlow(\"b\"); openFlow(\"a\") listed [b, a] here and\n // [a, b] on all three ports - a different `flows()` order and, since\n // `saveGame` keys its flows in that order, a different `.storyletsave`\n // byte stream for the same run (2026-08-29). markClosed without dropFlow\n // is the difference: the old handle goes inert, the slot stays put. The\n // registry cannot keep a key's place the same way (the old flow's keys are\n // removed and the new flow's appended), so `saveGame` writes the registry\n // section in flow order itself: see `registrySection` (2026-10-01).\n const existing = this.flowsById.get(id);\n if (existing) {\n // Say so BEFORE the old flow goes inert, while its board is still readable.\n const dealt = existing.heldCardIds().length;\n if (dealt > 0) this.onReplacedFlow?.(id, dealt);\n existing.markClosed();\n }\n if (!claim) this.internals.registry.discardParked(flowPrefix(id));\n const flow = new Flow(this, this.internals, id, opts.seed ?? this.seed);\n this.flowsById.set(id, flow);\n if (opts.restore !== undefined) {\n const draft = emptyDraft();\n // Cloned: a caller holding one blob may resume two flows from it, and\n // an aliased playLog would then grow in both.\n const clean = this.planFlowRestore(id, structuredClone(opts.restore), otherClaims, draft);\n flow.restore(clean);\n const content = this.internals.bundle.content;\n opts.onRestoreReport?.(finishReport(content, content, [id], draft));\n }\n return flow;\n }\n\n getFlow(id: string): Flow | undefined {\n return this.flowsById.get(id);\n }\n\n /** Every live flow, open order. */\n flows(): Flow[] {\n return [...this.flowsById.values()];\n }\n\n /** Close the named flow: its handle goes INERT (every verb throws). A\n * dropped-but-held flow must not keep writing shared state (Patter's\n * stale-handle lesson). Unknown ids are a quiet no-op, like closing a\n * closed door. */\n closeFlow(id: string): void {\n const flow = this.flowsById.get(id);\n if (!flow) return;\n this.flowsById.delete(id);\n flow.markClosed();\n }\n\n /** @internal - Flow.close() routes here so both doors agree. */\n dropFlow(id: string, flow: Flow): void {\n if (this.flowsById.get(id) === flow) this.flowsById.delete(id);\n }\n\n /** Close every flow and reseed the shared state to its defaults (the\n * self-backed @world included; a host-bound @world is the host's and is\n * not touched). */\n reset(): void {\n this.dropRun(false);\n this.reseedShared();\n // Values loaded for bags nobody has claimed yet are the old run's too: a\n // flow opened after the reset must not pick them up. Other engines' stay.\n this.internals.registry.discardParked(\"storylets/\");\n }\n\n /** End the run: clear the log, close every flow, forget spent cards. Each\n * flow's bags leave the registry; `keepFlows` names the flows whose values\n * are kept there for the flow that replaces them (a load into the game's\n * registry). */\n private dropRun(keepFlows: Set<string> | false): void {\n // The log is a run-lifetime utility and is not saved; a reset is a new run.\n // All three ports cleared it here and the reference did not, so `reset()`\n // (and `loadGame`) left the previous run's entries in place with `seq`\n // continuing across the boundary - while the same call on Godot, Unity or\n // Unreal returned an empty log (2026-08-29).\n this.engineLog = [];\n for (const [id, flow] of this.flowsById) {\n flow.releaseBags(keepFlows !== false && keepFlows.has(id));\n flow.markClosed();\n }\n this.flowsById.clear();\n this.spent.clear();\n }\n\n // --- shared scarcity (design/shared-scarcity.md) -----------------------------\n\n /** Cards a shared `redraw: \"never\"` has taken out of the world, by card id.\n * The claim ledger is DERIVED from live boards and so needs no storage;\n * this one is durable, so it rides the save's shared half. */\n private spent = new Set<string>();\n\n /** @internal */\n isTaken(cardId: string): boolean {\n return this.spent.has(cardId);\n }\n\n /** @internal */\n markTaken(cardId: string): void {\n this.spent.add(cardId);\n }\n\n // --- the run's log (design/shared-scarcity.md 8.2) ---------------------------\n\n /** Every flow's events in one ordered stream, each tagged with its flow.\n * Opt in with the same `log` option the flow logs use; capped the same way.\n *\n * This exists because a flow's own log cannot answer the question a run\n * raises: when a story action in ANOTHER flow moves shared state, your\n * flow's log says nothing and your value simply changes. Reading a run\n * needs one stream that says who did what, and merging the per-flow logs by\n * hand is a thing every host would otherwise have to write. */\n private engineLog: EngineLogEntry[] = [];\n private engineSeq = 0;\n\n log(): readonly EngineLogEntry[] {\n return this.engineLog;\n }\n\n clearLog(): void {\n this.engineLog = [];\n }\n\n /** @internal - shared claims across every LIVE flow, card id -> holders.\n * Derived, which is what makes closeFlow and the openFlow replace release\n * what a flow was holding: its board leaves the map with it. */\n sharedClaims(): Map<string, number> {\n const counts = new Map<string, number>();\n for (const flow of this.flowsById.values()) {\n for (const id of flow.heldCardIds()) counts.set(id, (counts.get(id) ?? 0) + 1);\n }\n return counts;\n }\n\n /** The same ledger with one name left out: what the REST of the world\n * holds, which is the question a resume under that name has to ask. */\n private sharedClaimsExcept(id: string): Map<string, number> {\n const counts = new Map<string, number>();\n for (const [flowId, flow] of this.flowsById) {\n if (flowId === id) continue;\n for (const cardId of flow.heldCardIds()) counts.set(cardId, (counts.get(cardId) ?? 0) + 1);\n }\n return counts;\n }\n\n // --- engine-level state access ----------------------------------------------\n\n /**\n * Read shared state by path: \"world.x\", \"story.gold\" (when shared),\n * \"box.village.heat\" (when shared) - the owner segment is its GAMEID\n * (design/engine-server.md 4.4). A ref that resolves PER-FLOW throws,\n * naming the fix - silently answering with some flow's copy (or a junk\n * default) was the bug Patter's engine.getProperty guard exists to stop.\n */\n getProperty(path: string): ScalarValue {\n const found = this.resolveShared(path);\n const value = found.kind === \"world\" ? this.internals.worldResolver.get(found.name)\n : found.kind === \"scope\" ? this.internals.registry.get(found.token, found.name)\n : found.bag.get(found.name);\n if (value === undefined) throw new Error(`no property at \"${path}\"`);\n return value;\n }\n\n setProperty(path: string, value: ScalarValue): void {\n const found = this.resolveShared(path);\n if (found.kind === \"world\") {\n if (!this.internals.worldSet) {\n throw new Error(`@world is read-only here: the host bound no write`);\n }\n this.internals.worldSet(found.name, value, true);\n return;\n }\n if (found.kind === \"scope\") {\n this.internals.registry.set(found.token, found.name, value, { host: true });\n return;\n }\n // A host write: silent under the firing rule (no subscriber feedback\n // loop), but visible to the bag's audit hook - and a HOST write, so a\n // `writable: false` does not refuse it. That flag is the story's promise\n // about its own outcomes; this is the game speaking, in any scope.\n found.bag.set(found.name, value, { silent: true, reason: \"host setProperty\", host: true });\n }\n\n private resolveShared(path: string):\n | { kind: \"world\"; name: string }\n | { kind: \"scope\"; token: string; name: string }\n | { kind: \"bag\"; bag: StateBag; name: string } {\n const parts = path.split(\".\");\n const perFlow = (): never => {\n throw new Error(`\"${path}\" is per-flow state - read it on a Flow, not the Engine`);\n };\n if (parts.length === 2 && parts[0] === \"world\") return { kind: \"world\", name: parts[1]! };\n // Another engine's game-wide scope (`patter.gold`): every engine reads every scope.\n if (parts.length === 2 && parts[0] !== \"story\" && this.internals.registry.has(parts[0]!)) {\n return { kind: \"scope\", token: parts[0]!, name: parts[1]! };\n }\n if (parts.length === 2 && parts[0] === \"story\") {\n const name = parts[1]!;\n if (this.internals.shared.story.get(name) !== undefined) return { kind: \"bag\", bag: this.internals.shared.story, name };\n if (this.internals.flowDecls.story.some((d) => d.name === name)) perFlow();\n throw new Error(`no property at \"${path}\"`);\n }\n if (parts.length === 3 && (parts[0] === \"box\" || parts[0] === \"deck\" || parts[0] === \"hand\" || parts[0] === \"value\")) {\n const kind = parts[0] as OwnedScope;\n const [, segment, name] = parts as unknown as [string, string, string];\n const owner = ownerOrThrow(this.internals, kind, segment, name);\n if (owner.legacy) this.diagnose(legacyAddressMessage(this.internals, kind, segment, name));\n const id = owner.id;\n const bag = this.internals.shared[kind].get(id);\n if (bag !== undefined && bag.get(name) !== undefined) return { kind: \"bag\", bag, name };\n if (this.internals.flowDecls[kind].get(id)?.some((d) => d.name === name)) perFlow();\n if (bag === undefined && !this.internals.flowDecls[kind].has(id)) throw new Error(`no ${kind} store \"${segment}\"`);\n throw new Error(`no property at \"${path}\"`);\n }\n throw new Error(`bad property path \"${path}\"`);\n }\n\n /** The engine's own surface has no flow, so an engine-level diagnostic\n * carries the empty flow id - the same way a LoadReport's shared half\n * carries no flow. It reaches the run log and the engine tap; there is\n * nowhere else for it to go, and it fires only on a legacy address. */\n private diagnose(message: string): void {\n this.internals.emitEngine(\"\", { type: \"diagnostic\", where: \"property address\", message });\n }\n\n /** Content that names another engine's scope (`@patter.visits`) runs only\n * where that engine is on this registry: without it every read would answer\n * false and every write fail, so the flow is refused as it opens, before\n * anything changes. By then a game has built all of its engines, whatever\n * order it built them in. The same message on every runtime. */\n private assertExternalScopes(): void {\n for (const token of this.internals.bundle.externalScopes ?? []) {\n if (!this.internals.registry.has(token)) {\n throw new Error(`this content names @${token}, which no engine on this registry registered: `\n + `give every engine the game's one registry`);\n }\n }\n }\n\n /** The shared surface as examiner rows: @world (read through the\n * resolver) then the shared partitions. Per-flow rows live on each Flow. */\n listProperties(): PropertyRow[] {\n const out: PropertyRow[] = [];\n for (const d of this.internals.bundle.world.properties) {\n const value = this.internals.worldResolver.get(d.name);\n out.push({\n path: `world.${d.name}`, name: d.name, type: d.type,\n value: value ?? d.default, default: d.default,\n ...(d.values !== undefined ? { values: d.values } : {}),\n ...(d.stages !== undefined ? { stages: d.stages } : {}),\n // @world is FOREIGN - a host resolver backs it - so writability is whether that\n // resolver can be written at all AND what the declaration says, which is the\n // shared registry's own rule for a foreign scope (its foreignWritable). The\n // `as PropertyView` cast this replaced was hiding the field's absence: the row\n // type has always required it, and these rows shipped without one.\n //\n // A row is where `writable: false` is meant to SHOW (Reboot.md 10): it tells a\n // state panel this is the game's value, not the story's. It does not stop the\n // panel editing it - the host's setProperty passes `{ host: true }`.\n writable: this.internals.worldSet !== undefined && !this.internals.worldReadOnly.has(d.name),\n });\n }\n // The bag composes its rows' addresses from its own pathPrefix, so the prefix here is\n // only the caller's label for the mount; the row arrives already addressed.\n const add = (_prefix: string, bag: StateBag): void => {\n for (const row of bag.rows()) out.push(row);\n };\n add(\"story\", this.internals.shared.story);\n for (const kind of OWNED_SCOPES) {\n for (const [id, bag] of this.internals.shared[kind]) add(addressOf(this.internals, kind, id), bag);\n }\n return out;\n }\n\n /** The SHARED kernel bags with their store path prefixes (the state\n * logger's mount surface). The @world container is the host's own bag -\n * the host mounts it itself. */\n listBags(): BagMount[] {\n const mounts: BagMount[] = [{ prefix: \"story\", bag: this.internals.shared.story }];\n for (const kind of [\"box\", \"deck\", \"hand\", \"value\"] as const) {\n for (const [id, bag] of this.internals.shared[kind]) mounts.push({ prefix: addressOf(this.internals, kind, id), bag });\n }\n return mounts;\n }\n\n /** Every flow's trace, one stream, each event tagged with its flow id. */\n subscribeTrace(handler: EngineTraceHandler): () => void {\n this.engineTraceHandlers.add(handler);\n return () => this.engineTraceHandlers.delete(handler);\n }\n\n // --- persistence (schema 4) -------------------------------------------------\n\n /**\n * Live bundle refresh: rebuild on an edited bundle with the whole run carried\n * over, and return the replacement with the report its load produced.\n *\n * Standalone, that is a save and a load into a new engine, and this one is left\n * untouched (discard it). With the game's registry the two cannot both hold the\n * same keys, so this engine is spent afterwards (its flows closed, the\n * replacement holding everything on the same registry): it carries its\n * own values into the snapshot, steps out of the registry, and the replacement\n * loads them the way a standalone save loads: so the report covers the\n * properties the edit dropped, defaulted, or retyped, and a dropped property\n * is dropped rather than kept. Values the game loaded that were still waiting\n * for a flow of this engine carry across as they were, and nothing belonging\n * to any other engine is touched. A save for another project is refused before\n * anything moves; if the rebuild fails for any other reason, this engine takes\n * its registrations back and is left exactly as it was.\n */\n hotSwap(bundle: Bundle, opts: EngineOptions = {}): { engine: Engine; report: LoadReport } {\n if (bundle.content.project !== this.internals.bundle.content.project) {\n throw new Error(`save is for project \"${this.internals.bundle.content.project}\", bundle is \"${bundle.content.project}\"`);\n }\n const options: EngineOptions = { ...this.creationOptions, ...opts };\n const snapshot = this.saveGame();\n const reg = this.internals.registry;\n if (this.internals.ownsRegistry) {\n // Its own registry: a save and a load into a new engine, as it always was,\n // and this engine is left untouched.\n const next = new Engine(bundle, { ...options, registry: undefined });\n return { engine: next, report: next.loadGame(snapshot) };\n }\n // This engine's own values, registered or still waiting for a flow.\n const mine: Record<string, Record<string, ScalarValue>> = {};\n for (const [key, values] of Object.entries(reg.save())) {\n if (key === \"story\" || key.startsWith(\"storylets/\")) mine[key] = values;\n }\n const registeredKeys = new Set([\n ...this.sharedMounts.map((m) => m.key),\n ...[...this.flowsById.values()].flatMap((f) => f.registeredKeys()),\n ]);\n const waiting = Object.fromEntries(Object.entries(mine).filter(([key]) => !registeredKeys.has(key)));\n // Step out of the registry. The bags keep their values, so stepping back in is exact.\n for (const { key } of this.sharedMounts) if (reg.has(key)) reg.remove(key);\n for (const flow of this.flowsById.values()) flow.releaseBags(false);\n let next: Engine | undefined;\n try {\n next = new Engine(bundle, { ...options, registry: reg });\n const report = next.loadGame({ ...snapshot, registry: mine });\n // Values that were waiting for a flow wait on, for the replacement's flow of that name.\n const stillWaiting = Object.fromEntries(Object.entries(waiting).filter(([key]) => !reg.has(key)));\n if (Object.keys(stillWaiting).length > 0) reg.load(stillWaiting, { keepParked: true });\n this.dropRun(false);\n return { engine: next, report };\n } catch (e) {\n // Back as it was. The replacement's registrations go; a constructor that\n // failed part way parked what it had claimed, so this engine's keys are\n // cleared of anything waiting, registered again, and its own values laid\n // back over them (the waiting ones parked again).\n next?.dropRun(false);\n for (const { key } of next?.sharedMounts ?? []) if (reg.has(key)) reg.remove(key);\n reg.discardParked(\"storylets/\");\n for (const { mount } of this.sharedMounts) mount();\n for (const flow of this.flowsById.values()) flow.mountBags();\n // `story` may have claimed what the failed replacement parked there: back to\n // its declarations, then this engine's own values over it.\n this.reseedShared();\n reg.load(mine, { keepParked: true });\n throw e;\n }\n }\n\n /** The whole engine's NON-property state, one envelope: the spent cards\n * once, then every live flow (board, clocks, cooldowns, PRNG, play log)\n * keyed by its id. The property values are the registry's: a standalone\n * engine (one that made its own registry) carries them here under\n * `registry`, self-backed @world included; a game that passed a registry\n * saves it once itself, beside each engine's envelope. */\n saveGame(): SaveEnvelope {\n return structuredClone({\n schema: SAVE_SCHEMA,\n content: this.internals.bundle.content,\n ...(this.internals.ownsRegistry ? { registry: this.registrySection() } : {}),\n shared: { spent: [...this.spent].sort() },\n flows: Object.fromEntries([...this.flowsById].map(([id, flow]) => [id, flow.snapshot(false)])),\n });\n }\n\n /** The registry's values in CANONICAL order, the order a load rebuilds them\n * in: the engine-wide keys as the constructor registered them, then each\n * flow's keys in `flows()` order (each flow's own registration order), then\n * anything else the registry holds (values still waiting for a key), as the\n * registry lists it. The registry itself lists keys in registration order,\n * and a flow replaced in place (`open()` above keeps its slot in\n * `flowsById`) re-registers its keys at the END, so `openFlow(\"a\");\n * openFlow(\"b\"); openFlow(\"a\")` saved b's keys before a's while a load\n * rebuilt a's first: the same run, different `.storyletsave` bytes, and a\n * save loaded and saved again no longer equal to itself. It is the\n * 2026-08-29 rule carried into the section save@2 moved the per-flow values\n * to (2026-10-01). Order does not matter on READ (`partitionsFromSections`\n * sorts by key shape), so a save written in the old order loads as before. */\n private registrySection(): Sections {\n const all = this.internals.registry.save() as Sections;\n const out: Sections = {};\n const take = (key: string): void => {\n if (Object.prototype.hasOwnProperty.call(all, key) && !Object.prototype.hasOwnProperty.call(out, key)) out[key] = all[key]!;\n };\n for (const { key } of this.sharedMounts) take(key);\n for (const flow of this.flowsById.values()) for (const key of flow.registeredKeys()) take(key);\n for (const key of Object.keys(all)) take(key);\n return out;\n }\n\n /** ONE flow's blob, to park a visit that is walking away: the same shape\n * the envelope carries per flow, and the same shape `openFlow`'s `restore`\n * option takes back (design/engine-server.md 4.1). Saving the whole\n * envelope to park one of four hundred players is wrong in cost and in\n * meaning. Throws for a name that is not open - a closed flow has nothing\n * left to save. */\n saveFlow(id: string): FlowSave {\n const flow = this.flowsById.get(id);\n if (!flow) throw new Error(`unknown flow \"${id}\"`);\n // Parked whole, properties included: a parked flow's bags leave the\n // registry when it closes, so its values have to travel with it.\n return structuredClone(flow.snapshot(true));\n }\n\n /** What `loadGame(envelope)` would do that is not a plain restore, without\n * doing any of it (design/engine-server.md 4.9). Pure: nothing on this\n * engine moves. A project mismatch is refused here exactly as `loadGame`\n * refuses it - it is the one thing neither call will tolerate. */\n previewLoad(envelope: SaveEnvelope | SaveEnvelopeV1): LoadReport {\n this.assertSameProject(envelope);\n return this.planLoad(envelope).report;\n }\n\n /** What `openFlow(id, { restore: saved })` would do to a flow of that name,\n * without doing it: the same report shape, since a visit parked under one\n * build and resumed under the next raises the same questions. Pure. */\n previewFlowRestore(id: string, saved: FlowSave): LoadReport {\n const draft = emptyDraft();\n this.planFlowRestore(id, saved, this.sharedClaimsExcept(id), draft);\n const content = this.internals.bundle.content;\n return finishReport(content, content, [id], draft);\n }\n\n /** Restore: shared state once, then every flow REBUILT from its blob.\n * Handles held from before the load are closed and inert (Patter's\n * rule); take fresh ones from getFlow()/flows().\n *\n * Property values come from the registry. An envelope that carries them\n * (a standalone engine's, or a version 1 envelope) has them walked, cleaned,\n * and moved into the registry here, over fresh defaults. Otherwise the game\n * loads its registry itself, before or after this call: each flow's bags\n * are handed back to the registry with their values, and the restored\n * flows claim them. The report then covers only what this envelope holds;\n * the registry's own load rule applies to the values.\n *\n * Returns the report `previewLoad` would have given for this envelope: the\n * drift tolerance that makes a load forgiving is what hides its cost, so\n * the cost comes back with the load whether or not anybody looked first. */\n loadGame(envelope: SaveEnvelope | SaveEnvelopeV1): LoadReport {\n this.assertSameProject(envelope);\n this.assertExternalScopes();\n const plan = this.planLoad(structuredClone(envelope));\n const reg = this.internals.registry;\n if (plan.sections !== undefined) {\n // The envelope carries the values: every bag of this engine back to its\n // defaults, then the cleaned values over them.\n this.reset();\n // The engine's own registry takes the save wholesale. A game's registry may\n // hold values the game loaded for other engines, still waiting: add to\n // those, never replace them.\n if (this.internals.ownsRegistry) reg.load(plan.sections);\n else reg.load(plan.sections, { keepParked: true });\n } else {\n this.dropRun(new Set(plan.flows.map(([id]) => id)));\n }\n for (const id of plan.spent) this.spent.add(id);\n for (const [id, clean] of plan.flows) this.open(id, {}, true).restore(clean);\n return plan.report;\n }\n\n private assertSameProject(envelope: SaveEnvelope | SaveEnvelopeV1): void {\n if (envelope.content.project !== this.internals.bundle.content.project) {\n throw new Error(`save is for project \"${envelope.content.project}\", bundle is \"${this.internals.bundle.content.project}\"`);\n }\n }\n\n /** The whole-envelope walk: the report, and the cleaned state the apply\n * half writes. Nothing here touches the engine, which is what lets\n * previewLoad and loadGame share it. */\n private planLoad(envelope: SaveEnvelope | SaveEnvelopeV1): {\n report: LoadReport;\n /** The cleaned property values to move into the registry, when the\n * envelope carries any. */\n sections?: Sections;\n spent: string[];\n flows: [string, FlowSave][];\n } {\n const schema = (envelope as { schema?: unknown }).schema;\n if (schema !== SAVE_SCHEMA && schema !== SAVE_SCHEMA_V1) throw new Error(`unsupported save schema: ${String(schema)}`);\n const draft = emptyDraft();\n // Where the property values are, if this envelope has them: a version 1\n // envelope's partitions, or a standalone engine's registry sections.\n const flowIds = new Set(Object.keys(envelope.flows ?? {}));\n let moved: { shared: PropsPartition; flows: Map<string, PropsPartition>; rest: Sections } | undefined;\n if (envelope.schema === SAVE_SCHEMA_V1) {\n moved = {\n shared: envelope.shared?.props ?? emptyPartitionValues(),\n flows: new Map(Object.entries(envelope.flows ?? {}).map(([id, f]) => [id, f.props ?? emptyPartitionValues()])),\n rest: {},\n };\n } else if (envelope.registry !== undefined) {\n moved = partitionsFromSections(envelope.registry, flowIds);\n }\n const shared = moved !== undefined\n ? walkPartition(this.internals, this.internals.sharedDecls, moved.shared, undefined, draft)\n : undefined;\n const spent: string[] = [];\n for (const cardId of envelope.shared?.spent ?? []) {\n if (this.internals.cardsById.has(cardId)) spent.push(cardId);\n else draft.droppedSpent.push(cardId);\n }\n const flows: [string, FlowSave][] = [];\n const sections: Sections | undefined = moved !== undefined ? { ...moved.rest } : undefined;\n if (sections !== undefined && shared !== undefined) {\n sectionsOf(shared, (kind, id) => (kind === \"story\" ? \"story\" : sharedKey(kind, id!)), sections);\n }\n for (const [id, saved] of Object.entries(envelope.flows ?? {})) {\n const withProps: FlowSave = moved !== undefined\n ? { ...saved, props: moved.flows.get(id) ?? emptyPartitionValues() }\n : { ...saved };\n const clean = this.planFlowRestore(id, withProps, undefined, draft);\n if (sections !== undefined && clean.props !== undefined) {\n // The flow's values go into the registry, where its bags claim them; the\n // restored flow itself carries none.\n sectionsOf(clean.props, (kind, owner) => flowKey(id, kind, owner), sections);\n delete clean.props;\n }\n flows.push([id, clean]);\n }\n return {\n report: finishReport(this.internals.bundle.content, envelope.content, flows.map(([id]) => id), draft),\n ...(sections !== undefined ? { sections } : {}),\n spent, flows,\n };\n }\n\n /** One flow's walk. `otherClaims` is the rest of the world's shared ledger\n * and is present only for a SINGLE-flow restore into a live engine: a\n * whole-envelope load rebuilds every flow from one consistent moment, so\n * there is nobody else to compete with. */\n private planFlowRestore(\n id: string,\n saved: FlowSave,\n otherClaims: Map<string, number> | undefined,\n draft: ReportDraft,\n ): FlowSave {\n const internals = this.internals;\n // A flow blob without properties (a version 2 envelope's: the registry has\n // them) has nothing to walk.\n const props = saved.props !== undefined ? walkPartition(internals, internals.flowDecls, saved.props, id, draft) : undefined;\n\n const cooldowns: Record<string, number> = {};\n for (const [cardId, turn] of Object.entries(saved.cooldowns ?? {})) {\n if (internals.cardsById.has(cardId)) cooldowns[cardId] = turn;\n else draft.droppedCooldowns.push({ flow: id, card: cardId });\n }\n\n // A deleted entity has no gameId left, so it is named by the id the save\n // carries; everything the build still knows is named by its gameId.\n const cardName = (cardId: string): string => {\n const entry = internals.cardsById.get(cardId);\n return entry ? effectiveGameId(entry.card) : cardId;\n };\n const board: Record<string, string[]> = {};\n const restored = new Map<string, number>();\n for (const [handId, ids] of Object.entries(saved.board ?? {})) {\n const known = internals.handsById.get(handId);\n if (known === undefined) {\n for (const cardId of ids) {\n draft.evicted.push({ flow: id, hand: handId, card: cardName(cardId), reason: \"hand-vanished\" });\n }\n continue;\n }\n const hand = effectiveGameId(known.hand);\n const kept: string[] = [];\n for (const cardId of ids) {\n const entry = internals.cardsById.get(cardId);\n if (entry === undefined) {\n draft.evicted.push({ flow: id, hand, card: cardId, reason: \"vanished\" });\n continue;\n }\n if (otherClaims !== undefined && cardIsShared(entry.card, entry.deck.shared ?? false)) {\n const held = (otherClaims.get(cardId) ?? 0) + (restored.get(cardId) ?? 0);\n if (held >= sharedCap(entry.card)) {\n draft.evicted.push({ flow: id, hand, card: effectiveGameId(entry.card), reason: \"claimed-elsewhere\" });\n continue;\n }\n restored.set(cardId, (restored.get(cardId) ?? 0) + 1);\n }\n kept.push(cardId);\n }\n board[handId] = kept;\n }\n\n return {\n ...(props !== undefined ? { props } : {}),\n turns: saved.turns ?? {},\n prng: saved.prng,\n cooldowns,\n board,\n playLog: saved.playLog ?? [],\n };\n }\n}\n\n// --- the Flow -----------------------------------------------------------------\n\nexport class Flow {\n readonly id: string;\n private readonly engine: Engine;\n private readonly internals: Internals;\n private closed = false;\n\n private prng: Prng;\n /** Per-box turn counters, keyed by box id (schema 3.4) - per flow. */\n private turnCounts = new Map<string, number>();\n private cooldowns: Record<string, number> = {};\n /** The board: hand contents (card ids, dealt order), keyed by hand id. */\n private boardContents = new Map<string, string[]>();\n private playLog: PlayRecord[] = [];\n // --- play-history indexes -------------------------------------------------\n // The four play-history host functions used to SCAN playLog on every call,\n // and they are called once per candidate card per ask, so dealing was\n // O(candidates x playLog): a shipped game got measurably slower the longer\n // somebody played it, which is the failure mode nobody meets in testing.\n // Measured before the change, 2000 cards: a box with no history condition\n // held flat at 0.3ms while `count_played` went 0.8ms -> 27.9ms as the log\n // reached 4000 plays.\n //\n // These are a pure summary of `playLog`, maintained where it is appended and\n // rebuilt where it is replaced, so they cannot drift from it. They are NOT\n // saved: `playLog` is the record, this is a derivation, and rebuilding on\n // load keeps the save format untouched.\n //\n // The tag keys are the played card's OWN (groupId, tagId) pairs, which is\n // what makes the box-local rule survive: a group name resolves inside the\n // ASKING box, so a card in another box carries different ids and cannot\n // match, exactly as the per-record `inTag` check used to decide.\n private playCount = new Map<string, number>();\n private lastPlayOf = new Map<string, PlayRecord>();\n private tagPlayCount = new Map<string, number>();\n private lastPlayInTag = new Map<string, PlayRecord>();\n /** The per-flow property partitions (the not-shared halves), each bag\n * that declares something registered under this flow's keys. */\n private stores: Partition;\n private readonly registered: string[] = [];\n /** This flow's bags that declare something, under their registry keys. */\n private readonly bagKeys: Array<[string, StateBag]> = [];\n\n private traceHandlers = new Set<TraceHandler>();\n private logEntries: LogEntry[] = [];\n private logSeq = 0;\n\n /** Merged read view per scope, built once (bags are stable for the\n * flow's life): the flow's own bag first, the shared bag behind it.\n * Names are disjoint (shared XOR per-flow by declaration), so \"first\"\n * is routing, not shadowing. */\n private readonly storyReader: ScopeResolver;\n private readonly boxReaders = new Map<string, ScopeResolver>();\n private readonly deckReaders = new Map<string, ScopeResolver>();\n\n /** @internal - built by Engine.openFlow / Engine.loadGame only. */\n constructor(engine: Engine, internals: Internals, id: string, seed: number) {\n this.engine = engine;\n this.internals = internals;\n this.id = id;\n this.prng = makePrng(seed);\n this.stores = buildPartition(internals, flowHalf);\n // Register the bags: each claims whatever the registry holds for its key (a\n // load); openFlow discarded that first for a fresh flow.\n const put = (key: string, bag: StateBag): void => {\n if (bag.declarations().length === 0) return; // holds nothing: not registered\n this.bagKeys.push([key, bag]);\n };\n put(flowKey(id, \"story\"), this.stores.story);\n for (const kind of OWNED_SCOPES) for (const [owner, bag] of this.stores[kind]) put(flowKey(id, kind, owner), bag);\n this.mountBags();\n for (const box of internals.bundle.boxes) {\n this.turnCounts.set(box.id, 0);\n for (const hand of box.hands) this.boardContents.set(hand.id, []);\n }\n const pair = (own: StateBag | undefined, shared: StateBag | undefined): ScopeResolver => ({\n get: (n) => own?.get(n) ?? shared?.get(n),\n });\n // `internals.shared` is reassigned wholesale by loadGame/reset, but a\n // load rebuilds every Flow too, so a live flow's readers and the\n // shared partition are always the same generation.\n this.storyReader = pair(this.stores.story, internals.shared.story);\n for (const box of internals.bundle.boxes) {\n this.boxReaders.set(box.id, pair(this.stores.box.get(box.id), internals.shared.box.get(box.id)));\n for (const deck of box.decks) {\n this.deckReaders.set(deck.id, pair(this.stores.deck.get(deck.id), internals.shared.deck.get(deck.id)));\n }\n }\n }\n\n // --- lifetime ----------------------------------------------------------------\n\n get isClosed(): boolean {\n return this.closed;\n }\n\n /** Close this flow: the handle goes inert, every verb throws. */\n close(): void {\n if (this.closed) return;\n this.engine.dropFlow(this.id, this);\n this.markClosed();\n }\n\n /** @internal */\n markClosed(): void {\n this.releaseBags(false);\n this.closed = true;\n }\n\n /** @internal - take this flow's bags out of the registry; with `keep`, their\n * values wait there for the flow that replaces this one (a load into the\n * game's registry). Idempotent. */\n releaseBags(keep: boolean): void {\n for (const key of this.registered) this.internals.registry.remove(key, { keep });\n this.registered.length = 0;\n }\n\n /** @internal - the registry keys this flow holds right now. */\n registeredKeys(): string[] {\n return [...this.registered];\n }\n\n /** @internal - register this flow's bags (again): at construction, and when a\n * failed hotSwap hands them back. Each claims what the registry holds for it. */\n mountBags(): void {\n for (const [key, bag] of this.bagKeys) {\n this.internals.registry.mountOwned(key, bag, { owner: OWNER });\n this.registered.push(key);\n }\n }\n\n private assertOpen(): void {\n if (this.closed) throw new Error(`flow \"${this.id}\" is closed`);\n }\n\n /** A box's current turn (schema 3.4), on THIS flow's clock. */\n turn(boxRef: string): number {\n this.assertOpen();\n const box = this.internals.boxesByGameId.get(boxRef) ?? this.internals.boxesById.get(boxRef);\n if (!box) throw new Error(`unknown box \"${boxRef}\"`);\n return this.turnCounts.get(box.id) ?? 0;\n }\n\n /** Subscribe to this flow's deal/play trace (schema 5). Returns the\n * unsubscribe. With no subscribers anywhere the flow does no trace work. */\n subscribeTrace(handler: TraceHandler): () => void {\n this.traceHandlers.add(handler);\n return () => this.traceHandlers.delete(handler);\n }\n\n private get tracing(): boolean {\n return this.traceHandlers.size > 0 || this.internals.logCap !== undefined || this.internals.engineTracing();\n }\n\n private emit(event: TraceEvent, turn?: number): void {\n if (this.internals.logCap !== undefined) {\n this.logEntries.push({ ...event, seq: this.logSeq++, ...(turn !== undefined ? { turn } : {}) });\n if (this.logEntries.length > this.internals.logCap) this.logEntries.splice(0, this.logEntries.length - this.internals.logCap);\n }\n for (const handler of this.traceHandlers) handler(event);\n this.internals.emitEngine(this.id, event, turn);\n }\n\n /** The retained flow log (opt-in via the Engine's `log`), oldest first,\n * capped. The introspection seam for hosts and tools; the durable play\n * history in a save stays `playLog` (schema 4) - the log is a\n * flow-lifetime utility and is NOT saved. */\n log(): readonly LogEntry[] {\n return this.logEntries;\n }\n\n /** Empty the retained log; `seq` keeps counting, so ordering across a\n * clear stays meaningful. */\n clearLog(): void {\n this.logEntries = [];\n }\n\n // --- expression plumbing ----------------------------------------------------\n\n private node(expr: Expression): ExprNode {\n let node = this.internals.nodeCache.get(expr);\n if (!node) {\n node = deserialiseAst(expr.ast);\n this.internals.nodeCache.set(expr, node);\n }\n return node;\n }\n\n /** Tag group names are box-scoped: two boxes may name a group the same way\n * (schema 1 - boxes namespace their groups), so a name is only ever\n * resolved inside the box being asked, never bundle-wide. Ids are\n * project-unique and accepted here too, still confined to the box.\n *\n * A box on the project map sees ONE namespace: its own groups, then the\n * map's group (design/project-map-contract.md 3.1). A box that has not\n * opted in does not see the map's name at all, so a peek naming it there\n * is the ordinary unknown-group refusal. Own groups first is stated for\n * determinism only: a bundle that loads never has the two share a name. */\n private groupInBox(box: Box<Expression>, ref: string): TagGroup | undefined {\n const groups = groupsOfBox(this.internals.bundle, box);\n return groups.find((g) => effectiveGameId(g) === ref)\n ?? groups.find((g) => g.id === ref);\n }\n\n /** Fold one play into the indexes. O(the card's tags), not O(the log). */\n private indexPlay(record: PlayRecord): void {\n this.playCount.set(record.card, (this.playCount.get(record.card) ?? 0) + 1);\n this.lastPlayOf.set(record.card, record);\n const entry = this.internals.cardsByGameId.get(record.card);\n if (!entry) return;\n for (const [groupId, tagIds] of Object.entries(entry.card.tags ?? {})) {\n for (const tagId of tagIds) {\n // Keyed by the PLAYED card's box: history is box-specific (D7).\n const key = tagKey(entry.box.id, groupId, tagId);\n this.tagPlayCount.set(key, (this.tagPlayCount.get(key) ?? 0) + 1);\n this.lastPlayInTag.set(key, record);\n }\n }\n }\n\n /** Rebuild the indexes from the log. Called wherever `playLog` is REPLACED\n * rather than appended to, which is `restore` alone. */\n private rebuildPlayIndex(): void {\n this.playCount.clear();\n this.lastPlayOf.clear();\n this.tagPlayCount.clear();\n this.lastPlayInTag.clear();\n for (const record of this.playLog) this.indexPlay(record);\n }\n\n /** `box` is the box whose ask is being evaluated: the play-history\n * functions take a bare group name, so it resolves there, and they count\n * only that box's own plays (the box is in the index key). That was\n * automatic while every group was a box's; a project-map zone is shared,\n * and its history is still not (design/project-map-contract.md 3.7, D7).\n * History is THIS flow's: countPlayed answers \"have I done this\". */\n /** One host per box, built once.\n *\n * The closures below read `this.playCount`, `this.turnCounts` and the rest\n * LIVE, so a cached host answers with current state - which is what makes\n * caching safe rather than a snapshot bug. Unreal did this from the start\n * (`hostsByBox_`, built at flow construction) and the other three rebuilt a\n * host, and its closures, on every `evalCtx` call: once per deck per ask,\n * and once per surviving card in the eviction pass. Structural divergence\n * in one port AND the allocation the audit flagged, so the other three\n * copied it (2026-08-29). Lazy rather than eager, so a bundle's unvisited\n * boxes cost nothing. */\n private hostsByBox = new Map<string, StoryletsHost>();\n\n private host(box: Box<Expression>): StoryletsHost {\n const cached = this.hostsByBox.get(box.id);\n if (cached !== undefined) return cached;\n const made = this.makeHost(box);\n this.hostsByBox.set(box.id, made);\n return made;\n }\n\n private makeHost(box: Box<Expression>): StoryletsHost {\n /** A group NAME and tag name resolved in THIS box, as the index's key,\n * with this box in it: a zone's plays in another box are not this box's\n * history. Resolved once per call now, where `inTag` used to resolve it\n * again for every record in the log. Undefined when either name is\n * unknown here, which is the old per-record `false` and answers \"never\". */\n const keyOf = (group: string, tag: string): string | undefined => {\n const found = this.groupInBox(box, group);\n const t = found?.tags.find((v) => v.gameId === tag);\n return found && t ? tagKey(box.id, found.id, t.id) : undefined;\n };\n /** Turns-since is measured on the played card's box's clock (3.4). */\n const since = (record: PlayRecord): number => {\n const entry = this.internals.cardsByGameId.get(record.card);\n if (!entry) return NEVER_PLAYED;\n return (this.turnCounts.get(entry.box.id) ?? 0) - record.turn;\n };\n return {\n nextRandom: () => this.prng.next(),\n countPlayed: (card) => this.playCount.get(card) ?? 0,\n turnsSincePlayed: (card) => {\n const last = this.lastPlayOf.get(card);\n return last ? since(last) : NEVER_PLAYED;\n },\n countPlayedIn: (group, tag) => {\n const key = keyOf(group, tag);\n return key === undefined ? 0 : this.tagPlayCount.get(key) ?? 0;\n },\n turnsSincePlayedIn: (group, tag) => {\n const key = keyOf(group, tag);\n const last = key === undefined ? undefined : this.lastPlayInTag.get(key);\n return last ? since(last) : NEVER_PLAYED;\n },\n };\n }\n\n /** The evaluation environment (schema 3.1/6.2): @box/@deck resolve to the\n * card under evaluation; in hand-condition contexts @deck is an empty bag,\n * so any reference is an eval error (missing-policy throw). Every scope\n * is the flow's MERGED view - its own copies over the shared values,\n * names disjoint - and @world reads through the engine's resolver. */\n private evalCtx(box: Box<Expression>, deck: Deck<Expression> | undefined, handEnv: HandEnv): EvalContext {\n const others = this.internals.registryView();\n return {\n scopes: {\n // Every other engine's game-wide scope first (every engine reads every\n // scope); this engine's own tokens are its merged views, over the top.\n ...others.scopes,\n world: this.internals.worldResolver,\n story: this.storyReader,\n box: this.boxReaders.get(box.id) ?? {},\n deck: deck ? this.deckReaders.get(deck.id) ?? {} : {},\n hand: handEnv.bag,\n },\n host: this.host(box) as unknown as Record<string, unknown>,\n // The quality channel, answering for THIS ask's box and deck. Only wired\n // when a quality exists, so a bundle without one evaluates byte-\n // identically to before the feature.\n ...(this.internals.hasQualities || others.qualities !== undefined ? {\n qualities: (scope: string, name: string): readonly string[] | undefined =>\n scope === \"world\" ? this.internals.ladders.world.get(name) ?? others.qualities?.(scope, name)\n : scope === \"story\" ? this.internals.ladders.story.get(name)\n : scope === \"box\" ? this.internals.ladders.box.get(box.id)?.get(name)\n : scope === \"deck\" && deck ? this.internals.ladders.deck.get(deck.id)?.get(name)\n // @hand is composed, so the ladder belongs to whatever supplied the\n // value THIS ask: the bound tag, or the asking hand. `sources` is\n // already the map that answers that, because write-back needs it.\n : scope === \"hand\" ? this.handLadder(handEnv, name)\n : others.qualities?.(scope, name),\n } : {}),\n };\n }\n\n /** The ladder behind one composed @hand name, or undefined when the name is\n * not a quality (or came from criteria, which are tag NAMES, never state). */\n private handLadder(handEnv: HandEnv, name: string): readonly string[] | undefined {\n const source = handEnv.sources.get(name);\n if (!source) return undefined;\n return source.kind === \"value\" ? this.internals.ladders.value.get(source.id)?.get(name)\n : source.kind === \"hand\" ? this.internals.ladders.hand.get(source.id)?.get(name)\n : undefined;\n }\n\n private eval(expr: Expression, ctx: EvalContext): ScalarValue {\n return evaluate(this.node(expr), ctx, storyletsDialect);\n }\n\n private passes(expr: Expression | undefined, ctx: EvalContext, where?: string): boolean {\n if (!expr) return true;\n try {\n return conditionPasses(this.eval(expr, ctx));\n } catch (e) {\n // An eval error is never a silent pass: the card/deck is unavailable\n // (schema 3.1), and the trace surfaces the diagnostic.\n if (this.tracing) {\n this.emit({ type: \"diagnostic\", where: where ?? \"condition\", message: e instanceof Error ? e.message : String(e) });\n }\n return false;\n }\n }\n\n // --- resolving asks (schema 2.6 + 3.6) -----------------------------------------\n\n private tagByGameId(group: TagGroup, gameId: string): Tag | undefined {\n return group.tags.find((t) => t.gameId === gameId);\n }\n\n /** A deal's ask: the hand's template bindings + chosen tags, or its rule's\n * bindings, plus the implicit home binding (schema 2.4). */\n private askForHand(hand: Hand<Expression>, box: Box<Expression>): AskDescriptor {\n const boundTags = new Map<string, string>();\n const askNames: Record<string, string> = {};\n let condition: Expression | undefined;\n if (hand.template !== undefined) {\n const template = this.internals.templatesById.get(hand.template);\n if (!template) throw new Error(`hand \"${effectiveGameId(hand)}\": unknown template \"${hand.template}\"`);\n for (const [groupId, tagId] of Object.entries(template.bindings ?? {})) {\n boundTags.set(groupId, tagId);\n }\n for (const [groupId, tagId] of Object.entries(hand.chosen ?? {})) {\n // A hole filled from a property rather than with a tag: resolve it\n // now, before tag composition (4.6, the hand that moves).\n if (isHoleRef(tagId)) {\n this.fillHoleFromProperty(hand, groupId, tagId, boundTags, askNames);\n continue;\n }\n boundTags.set(groupId, tagId);\n const found = this.internals.groupsById.get(groupId);\n const tag = found?.group.tags.find((t) => t.id === tagId);\n if (found && tag) askNames[effectiveGameId(found.group)] = effectiveGameId(tag);\n }\n condition = template.condition;\n } else {\n for (const [groupId, tagId] of Object.entries(hand.rule?.bindings ?? {})) {\n if (isHoleRef(tagId)) {\n this.fillHoleFromProperty(hand, groupId, tagId, boundTags, askNames);\n continue;\n }\n boundTags.set(groupId, tagId);\n // ...and name it, exactly as the template branch above does: a card\n // reading @hand.<group> must not care HOW the group got bound\n // (design/hand-typing.md, the residues).\n const found = this.internals.groupsById.get(groupId);\n const tag = found?.group.tags.find((t) => t.id === tagId);\n if (found && tag) askNames[effectiveGameId(found.group)] = effectiveGameId(tag);\n }\n condition = hand.rule?.condition;\n }\n boundTags.set(PLACE_GROUP, hand.id);\n this.bindStateGroups(box, boundTags, askNames);\n return { box, hand, ...(condition !== undefined ? { condition } : {}), boundTags, askNames };\n }\n\n /** A peek's ask: raw criteria ({group gameId: tag gameId}), bindings only,\n * no condition slot (schema 3.1; the boundary, Reboot 4). */\n private askForPeek(box: Box<Expression>, criteria: Record<string, string>): AskDescriptor {\n const boundTags = new Map<string, string>();\n const askNames: Record<string, string> = {};\n for (const [groupRef, tagRef] of Object.entries(criteria)) {\n if (groupRef === PLACE_GROUP) {\n const hand = this.internals.handsByGameId.get(tagRef) ?? this.internals.handsById.get(tagRef);\n if (!hand) throw new Error(`peek: unknown hand \"${tagRef}\" in home criteria`);\n boundTags.set(PLACE_GROUP, hand.hand.id);\n continue;\n }\n const found = this.groupInBox(box, groupRef);\n if (!found) {\n throw new Error(`peek: unknown tag group \"${groupRef}\" in box \"${effectiveGameId(box)}\"`);\n }\n const tag = this.tagByGameId(found, tagRef) ?? found.tags.find((t) => t.id === tagRef);\n if (!tag) throw new Error(`peek: unknown tag \"${tagRef}\" in group \"${effectiveGameId(found)}\"`);\n boundTags.set(found.id, tag.id);\n askNames[effectiveGameId(found)] = effectiveGameId(tag);\n }\n this.bindStateGroups(box, boundTags, askNames);\n return { box, boundTags, askNames };\n }\n\n /**\n * Fill one hole from the property its value names: the hand that moves\n * (design/engine-server.md 4.6).\n *\n * The semantics are `bindStateGroups`' below, word for word, applied per\n * HOLE instead of per group: resolved at ask time, and a value naming no tag\n * leaves the hole UNBOUND (a wildcard) with a diagnostic rather than dealing\n * a silently empty hand. What is added is the `@hand` scope - the asking\n * hand's OWN declared state, read here from the flow's merged view (the\n * shared half under the flow's own, so a `shared: true` declaration moves\n * the hole for every flow and a per-flow one moves it for this flow alone).\n *\n * Read BEFORE tag composition, which is the whole reason it is safe: the\n * @hand bag a card sees is built from the bound tags, so resolving a hole\n * from it would be circular. A hand's own declarations are not, so they are.\n */\n private fillHoleFromProperty(\n hand: Hand<Expression>, groupId: string, ref: string,\n boundTags: Map<string, string>, askNames: Record<string, string>,\n ): void {\n const found = this.internals.groupsById.get(groupId);\n const groupName = found ? effectiveGameId(found.group) : groupId;\n const where = `hand ${effectiveGameId(hand)}, tag group ${groupName}`;\n const parsed = parseHoleRef(ref);\n if (!parsed) {\n this.emit({ type: \"diagnostic\", where, message: `\"${ref}\" is not a @hand, @world or @story property reference` });\n return;\n }\n if (!found) {\n this.emit({ type: \"diagnostic\", where, message: `\"${ref}\" fills a tag group that is not in this box` });\n return;\n }\n let value: ScalarValue | undefined;\n if (parsed.scope === \"hand\") {\n value = this.valuesOf(\"hand\", hand.id)[parsed.name];\n } else {\n try {\n value = this.getProperty(`${parsed.scope}.${parsed.name}`);\n } catch {\n value = undefined;\n }\n }\n if (value === undefined) {\n this.emit({ type: \"diagnostic\", where, message: `\"${ref}\" names a property that is not declared` });\n return;\n }\n const wanted = typeof value === \"string\" ? value : String(value);\n const tag = found.group.tags.find((t) => effectiveGameId(t) === wanted);\n if (!tag) {\n this.emit({ type: \"diagnostic\", where, message: `${ref} is \"${wanted}\", which is not one of the tags of \"${groupName}\"` });\n return;\n }\n boundTags.set(groupId, tag.id);\n askNames[groupName] = effectiveGameId(tag);\n }\n\n /**\n * Bind every `boundBy` group in the box from the property it names.\n *\n * The gap this closes: only a hand could bind a group, and `deal` takes no\n * criteria, so an axis driven by state (an act, a chapter) had nowhere to\n * gate. Runs AFTER the hand's own bindings and never overwrites one: an\n * explicit binding is a deliberate act and beats a default.\n *\n * A value naming no tag in the group leaves the group UNBOUND rather than\n * matching nothing. Unbound is a wildcard, so the ask still deals; a silent\n * empty hand would look like content that does not exist, and the diagnostic\n * is what says otherwise.\n */\n private bindStateGroups(box: Box<Expression>, boundTags: Map<string, string>, askNames: Record<string, string>): void {\n // The box's own groups and, when it is on the project map, the map's\n // group: a `boundBy` there binds in every opted-in box (3.2).\n for (const group of groupsOfBox(this.internals.bundle, box)) {\n if (group.boundBy === undefined || boundTags.has(group.id)) continue;\n const ref = /^@(world|story)\\.([a-z][a-z0-9_-]*)$/.exec(group.boundBy);\n if (!ref) {\n this.emit({ type: \"diagnostic\", where: `tag group ${effectiveGameId(group)}`, message: `boundBy \"${group.boundBy}\" is not a @world or @story property reference` });\n continue;\n }\n let value: ScalarValue | undefined;\n try {\n value = this.getProperty(`${ref[1]}.${ref[2]}`);\n } catch {\n this.emit({ type: \"diagnostic\", where: `tag group ${effectiveGameId(group)}`, message: `boundBy \"${group.boundBy}\" names a property that is not declared` });\n continue;\n }\n const wanted = typeof value === \"string\" ? value : String(value);\n const tag = group.tags.find((t) => effectiveGameId(t) === wanted);\n if (!tag) {\n this.emit({ type: \"diagnostic\", where: `tag group ${effectiveGameId(group)}`, message: `${group.boundBy} is \"${wanted}\", which is not one of its tags` });\n continue;\n }\n boundTags.set(group.id, tag.id);\n askNames[effectiveGameId(group)] = effectiveGameId(tag);\n }\n }\n\n // --- @hand composition (schema 3.6) -------------------------------------------\n\n /** A store's full value view for one owner: the shared half under the\n * flow's half. Names are disjoint, so the spread is routing, not\n * shadowing. */\n private valuesOf(kind: Exclude<PartitionKind, \"story\">, id: string): PropertyBag {\n return {\n ...(this.internals.shared[kind].get(id)?.values ?? {}),\n ...(this.stores[kind].get(id)?.values ?? {}),\n };\n }\n\n private buildHandEnv(ask: AskDescriptor): HandEnv {\n const bag: PropertyBag = {};\n const sources = new Map<string, HandSource>();\n\n // 1. Tag properties of every bound tag (home binds a hand, not a tag).\n for (const [groupId, tagId] of ask.boundTags) {\n if (groupId === PLACE_GROUP) continue;\n for (const [name, value] of Object.entries(this.valuesOf(\"value\", tagId))) {\n bag[name] = value;\n sources.set(name, { kind: \"value\", id: tagId });\n }\n }\n // 2. Hand properties, when the ask is a deal.\n if (ask.hand) {\n for (const [name, value] of Object.entries(this.valuesOf(\"hand\", ask.hand.id))) {\n bag[name] = value;\n sources.set(name, { kind: \"hand\", id: ask.hand.id });\n }\n }\n // 3. Chosen tags / criteria, by group name (the tag's gameId as value).\n for (const [name, value] of Object.entries(ask.askNames)) {\n bag[name] = value;\n sources.set(name, { kind: \"criteria\" });\n }\n return { bag, sources, boundTags: ask.boundTags };\n }\n\n // --- the ask (schema 3.1 + 3.2) ------------------------------------------------\n\n /** The claims ledger, derived from THIS flow's board: card id -> holding\n * hands (schema 3.5). Claims are per flow - another flow holding the\n * card is another playthrough, not a rival hand. */\n private claims(): Map<string, number> {\n const counts = new Map<string, number>();\n for (const contents of this.boardContents.values()) {\n for (const id of contents) counts.set(id, (counts.get(id) ?? 0) + 1);\n }\n return counts;\n }\n\n /** @internal - every card id on THIS flow's board, one entry per holding\n * hand. The engine sums these across live flows for the shared ledger. */\n heldCardIds(): string[] {\n return [...this.boardContents.values()].flat();\n }\n\n private copiesOf(card: Card<Expression>): number {\n return card.copies ?? 1;\n }\n\n /** The claims step (schema 3.1 step 6) for one card, as a verdict or null\n * for \"available\". Two caps apply to a shared card and they are different\n * statements, so they get different verdicts: `copies` is your own board\n * filling up, `sharedCopies` is somebody else already holding it, and a\n * participant told \"claimed\" about a card sitting on another person's\n * table would read it as an engine fault (design/shared-scarcity 9.3.1).\n *\n * `mine` counts this flow's holdings, `world` every live flow's. */\n private claimVerdict(\n card: Card<Expression>,\n shared: boolean,\n mine: Map<string, number>,\n world: Map<string, number>,\n ): \"claimed\" | \"claimed-elsewhere\" | null {\n const id = card.id;\n if ((mine.get(id) ?? 0) >= this.copiesOf(card)) return \"claimed\";\n if (shared && (world.get(id) ?? 0) >= sharedCap(card)) return \"claimed-elsewhere\";\n return null;\n }\n\n /** Tag matching (schema 3.1 step 3): for every bound group the card lists\n * the bound tag or omits the group (wildcard); the home group inverts -\n * a homed card requires a matching home binding (schema 2.4). */\n private tagsMatch(card: Card<Expression>, boundTags: Map<string, string>): boolean {\n const home = card.tags?.[PLACE_GROUP];\n if (home !== undefined && home.length > 0) {\n const bound = boundTags.get(PLACE_GROUP);\n if (bound === undefined || !home.includes(bound)) return false;\n }\n for (const [groupId, tagId] of boundTags) {\n if (groupId === PLACE_GROUP) continue;\n const tags = card.tags?.[groupId];\n if (tags === undefined) {\n // Omission is a wildcard unless the group says otherwise. A required\n // group inverts it, which is what `place` has always done per card.\n if (this.internals.requiredGroups.has(groupId)) return false;\n continue;\n }\n if (!tags.includes(tagId)) return false;\n }\n return true;\n }\n\n /** Run one ask: availability filter then ranking. `claimed` decides the\n * claims step (step 6) per card, returning the verdict that refused it or\n * null for available. `trace` (when a subscriber exists) collects the\n * per-card verdicts. */\n private runAsk(\n ask: AskDescriptor,\n claimed: (card: Card<Expression>, shared: boolean) => \"claimed\" | \"claimed-elsewhere\" | null,\n trace?: { id: string; verdict: TraceVerdict; priority?: number; specificity?: number }[],\n ): { ordered: CardEntry[]; handEnv: HandEnv } {\n const { box } = ask;\n const handEnv = this.buildHandEnv(ask);\n // Identity on the trace is by gameId (4.4), so the helper takes the CARD\n // rather than an id: every call site had one in hand, and taking the id\n // was the whole of how the two vocabularies got mixed.\n const verdict = (card: Card<Expression>, v: TraceVerdict): void => {\n trace?.push({ id: effectiveGameId(card), verdict: v });\n };\n\n // The hand's condition: ask-constant, evaluated once (schema 3.1 step 4).\n if (!this.passes(ask.condition, this.evalCtx(box, undefined, handEnv), `hand ${ask.hand ? effectiveGameId(ask.hand) : \"\"} condition`)) {\n return { ordered: [], handEnv };\n }\n\n // Deck gates: evaluated once per ask, in deck (id) order (schema 2.5).\n const gateOk = new Map<string, boolean>();\n for (const deck of box.decks) {\n gateOk.set(deck.id, this.passes(deck.condition, this.evalCtx(box, deck, handEnv), `deck ${deck.gameId} gate`));\n }\n\n const turn = this.turnCounts.get(box.id) ?? 0;\n const scored: { entry: CardEntry; priority: number; spec: number }[] = [];\n for (const deck of box.decks) {\n // ONE context per deck, not per card. It is built from box, deck and\n // handEnv, none of which vary inside this loop, and a condition is a\n // read-only gate (schema 3.1), so nothing can write through it and make\n // sharing visible. Rebuilding it per card cost an EvalContext, a scopes\n // map and five bag wrappers each time: about half the garbage a peek over\n // a large box produced (port-review-2026-08.md, measured).\n const deckCtx = this.evalCtx(box, deck, handEnv);\n const deckShared = deck.shared ?? false;\n for (const card of deck.cards) {\n const shared = cardIsShared(card, deckShared);\n if (!gateOk.get(deck.id)) {\n verdict(card, \"deck-gate\");\n continue;\n }\n // Taken out of the world by somebody's shared one-shot. Checked\n // before the flow's own clock, because \"cooldown\" would point the\n // reader at a turn counter that has nothing to do with it.\n if (shared && this.engine.isTaken(card.id)) {\n verdict(card, \"taken\");\n continue;\n }\n if ((this.cooldowns[card.id] ?? 0) > turn) {\n verdict(card, \"cooldown\");\n continue;\n }\n if (!this.tagsMatch(card, handEnv.boundTags)) {\n verdict(card, \"tags\");\n continue;\n }\n // The label is only read when an eval THROWS and only when tracing, so\n // building it per card was pure waste on the path that matters. Built\n // when tracing is on, where the cost is already accepted.\n if (card.condition && !this.passes(card.condition, deckCtx,\n this.tracing ? `card ${card.gameId} condition` : undefined)) {\n verdict(card, \"condition\");\n continue;\n }\n const refused = claimed(card, shared); // claims, last (schema 3.1 step 6)\n if (refused) {\n verdict(card, refused);\n continue;\n }\n\n let priority: number;\n if (typeof card.priority === \"number\") {\n priority = card.priority;\n } else {\n try {\n const v = this.eval(card.priority, deckCtx);\n if (typeof v !== \"number\") {\n verdict(card, \"priority\");\n continue;\n }\n priority = v;\n } catch (e) {\n if (this.tracing) {\n this.emit({ type: \"diagnostic\", where: `card ${card.gameId} priority`, message: e instanceof Error ? e.message : String(e) });\n }\n verdict(card, \"priority\");\n continue;\n }\n }\n let spec = 0;\n if (box.ranking.specificity && card.condition) {\n const node = this.node(card.condition);\n spec = matchedSpecificity(node, (n) => {\n try {\n return conditionPasses(evaluate(n, deckCtx, storyletsDialect));\n } catch {\n return false;\n }\n });\n }\n scored.push({ entry: { card, deck, box }, priority, spec });\n }\n }\n\n scored.sort((a, b) => b.priority - a.priority || b.spec - a.spec); // stable\n // Seeded shuffle of each maximal tie run; runs of 1 consume no draws.\n let i = 0;\n while (i < scored.length) {\n let j = i + 1;\n while (j < scored.length\n && scored[j]!.priority === scored[i]!.priority\n && scored[j]!.spec === scored[i]!.spec) j++;\n if (j - i > 1) {\n const run = scored.slice(i, j);\n shuffleInPlace(run, this.prng);\n // Written back element by element, as all three ports do. It used to be\n // `scored.splice(i, j - i, ...run)`, which SPREADS one argument per\n // element: with every card at the default priority 0 the tie run is the\n // whole list, and a box of 150 000 such cards threw `RangeError:\n // Maximum call stack size exceeded` rather than dealing. Far-fetched\n // for one box, but it was a crash where the ports had no limit, and the\n // reference is supposed to be the thing they are transliterated from.\n for (let k = 0; k < run.length; k++) scored[i + k] = run[k]!;\n }\n i = j;\n }\n for (const s of scored) {\n trace?.push({ id: effectiveGameId(s.entry.card), verdict: \"dealt\", priority: s.priority, specificity: s.spec });\n }\n return { ordered: scored.map((s) => s.entry), handEnv };\n }\n\n /** Flip eligible-but-not-taken trace entries to \"capped\". `taken` is keyed\n * by GAMEID, as the trace rows are (4.4): the two must move together or\n * every dealt card silently reads as capped. */\n private capTrace(\n trace: { id: string; verdict: TraceVerdict; priority?: number; specificity?: number }[],\n taken: ReadonlySet<string>,\n ): void {\n for (const entry of trace) {\n if (entry.verdict === \"dealt\" && !taken.has(entry.id)) entry.verdict = \"capped\";\n }\n }\n\n private view(entry: CardEntry): DealtCard {\n const { card } = entry;\n return {\n id: card.id,\n gameId: effectiveGameId(card),\n ...(card.title !== undefined ? { title: card.title } : {}),\n ...(card.purpose !== undefined ? { purpose: card.purpose } : {}),\n ...(card.fields !== undefined ? { fields: card.fields } : {}),\n };\n }\n\n private handCapacity(hand: Hand<Expression>): number {\n if (hand.slots !== undefined) return hand.slots;\n const declared = hand.template !== undefined\n ? this.internals.templatesById.get(hand.template)?.slots\n : hand.rule?.slots;\n return declared === undefined || declared === \"unbounded\" ? Infinity : declared;\n }\n\n private resolveHand(ref: string): { hand: Hand<Expression>; box: Box<Expression> } {\n const found = this.internals.handsByGameId.get(ref) ?? this.internals.handsById.get(ref);\n if (!found) throw new Error(`unknown hand \"${ref}\"`);\n return found;\n }\n\n // --- host surface (schema 5) ---------------------------------------------------\n\n /** Look at the top of the stock through raw tag criteria (schema 3.1):\n * claims respected, nothing registered, nothing left behind but the\n * trace line. You can never play a card you only peeked. */\n peek(boxRef: string, criteria: Record<string, string> = {}, n?: number): RankedList {\n this.assertOpen();\n const box = this.internals.boxesByGameId.get(boxRef) ?? this.internals.boxesById.get(boxRef);\n if (!box) throw new Error(`unknown box \"${boxRef}\"`);\n const ask = this.askForPeek(box, criteria);\n const claimCounts = this.claims();\n // Skipped outright when the bundle shares nothing, which is most bundles:\n // the ledger walks every live flow's whole board, and an empty map answers\n // every question the same way a computed one would.\n const worldClaims = this.internals.hasShared ? this.engine.sharedClaims() : new Map<string, number>();\n const trace = this.tracing ? [] : undefined;\n const { ordered } = this.runAsk(ask, (card, shared) => this.claimVerdict(card, shared, claimCounts, worldClaims), trace);\n // CLAMPED. `slice(0, -1)` drops the last card and returns the rest, so a\n // negative n answered with almost the whole list here while every port\n // returned nothing (2026-08-29).\n const listed = n === undefined ? ordered : ordered.slice(0, Math.max(n, 0));\n if (trace) {\n this.capTrace(trace, new Set(listed.map((e) => effectiveGameId(e.card))));\n this.emit({ type: \"peek\", box: effectiveGameId(box), criteria, cards: trace }, this.turnCounts.get(box.id) ?? 0);\n }\n return { box: effectiveGameId(box), cards: listed.map((e) => this.view(e)) };\n }\n\n /** Refresh one hand (schema 3.5); returns its new shape. */\n deal(handRef: string): DealtCard[] {\n this.assertOpen();\n const { hand } = this.resolveHand(handRef);\n return this.dealMany([handRef])[effectiveGameId(hand)] ?? [];\n }\n\n /** Re-deal several / all hands (schema 3.5): seeded hand-order shuffle\n * (fairness), evict, seed the ledger from survivors, fill in order.\n * Returns the dealt slice - the new contents of exactly the hands this\n * call dealt, keyed by hand gameId (board() stays the whole-board read). */\n dealMany(handRefs?: string[]): Record<string, DealtCard[]> {\n this.assertOpen();\n const dealt = (handRefs ?? [...this.internals.handsById.keys()].sort())\n .map((ref) => this.resolveHand(ref));\n shuffleInPlace(dealt, this.prng);\n\n // Eviction first: drop dealt cards no longer available to their hand\n // (minus the claims check against their own seat).\n for (const { hand, box } of dealt) {\n const ask = this.askForHand(hand, box);\n const handEnv = this.buildHandEnv(ask);\n const conditionOk = this.passes(ask.condition, this.evalCtx(box, undefined, handEnv));\n const gateOk = new Map<string, boolean>();\n for (const deck of box.decks) {\n gateOk.set(deck.id, this.passes(deck.condition, this.evalCtx(box, deck, handEnv)));\n }\n const turn = this.turnCounts.get(box.id) ?? 0;\n // Trace events fire after the state they report has landed (a handler\n // reading the board sees the eviction), so they are collected here and\n // emitted once the survivors are set.\n const evicted: { card: string; reason: Extract<TraceEvent, { type: \"evict\" }>[\"reason\"] }[] = [];\n // The card is named by gameId (4.4). A card the build no longer has -\n // the `vanished` branch below - has no gameId left, so it is named by\n // the id the board carries, which is the rule a load report has always\n // used for the same reason.\n const evict = (cardId: string, reason: Extract<TraceEvent, { type: \"evict\" }>[\"reason\"]): false => {\n const known = this.internals.cardsById.get(cardId);\n evicted.push({ card: known ? effectiveGameId(known.card) : cardId, reason });\n return false;\n };\n const survivors = (this.boardContents.get(hand.id) ?? []).filter((cardId) => {\n if (!conditionOk) return evict(cardId, \"hand-condition\");\n const entry = this.internals.cardsById.get(cardId);\n if (!entry) return evict(cardId, \"vanished\"); // edited content: dropped\n if (!gateOk.get(entry.deck.id)) return evict(cardId, \"deck-gate\");\n if ((this.cooldowns[cardId] ?? 0) > turn) return evict(cardId, \"cooldown\");\n if (!this.tagsMatch(entry.card, handEnv.boundTags)) return evict(cardId, \"tags\");\n if (!this.passes(entry.card.condition, this.evalCtx(box, entry.deck, handEnv), `card ${entry.card.gameId} condition`)) {\n return evict(cardId, \"condition\");\n }\n return true;\n });\n this.boardContents.set(hand.id, survivors);\n if (this.tracing) {\n for (const e of evicted) this.emit({ type: \"evict\", hand: effectiveGameId(hand), card: e.card, reason: e.reason }, turn);\n }\n }\n\n const claimCounts = this.claims();\n // The world ledger is taken once for the whole batch and kept in step with\n // the local one below, so two hands in the SAME deal cannot both take the\n // last shared copy. Skipped outright when the bundle shares nothing (most\n // bundles): an empty map answers every question the same way.\n const worldClaims = this.internals.hasShared ? this.engine.sharedClaims() : new Map<string, number>();\n for (const { hand, box } of dealt) {\n const contents = this.boardContents.get(hand.id) ?? [];\n const free = this.handCapacity(hand) - contents.length;\n if (free <= 0) continue;\n const ask = this.askForHand(hand, box);\n const own = new Set(contents);\n const trace = this.tracing ? [] : undefined;\n // At most once in any one hand; at most `copies` hands here, and at most\n // `sharedCopies` hands anywhere (schema 3.5, shared-scarcity 5).\n const { ordered } = this.runAsk(ask,\n (card, shared) => (own.has(card.id) ? \"claimed\" : this.claimVerdict(card, shared, claimCounts, worldClaims)), trace);\n const taking = ordered.slice(0, free);\n const added = taking.map((e) => e.card.id);\n this.boardContents.set(hand.id, [...contents, ...added]);\n for (const id of added) {\n claimCounts.set(id, (claimCounts.get(id) ?? 0) + 1);\n worldClaims.set(id, (worldClaims.get(id) ?? 0) + 1);\n }\n // Emitted after the hand is set: a handler reading board() sees the deal.\n if (trace) {\n this.capTrace(trace, new Set(taking.map((e) => effectiveGameId(e.card))));\n this.emit({ type: \"deal\", hand: effectiveGameId(hand), cards: trace }, this.turnCounts.get(box.id) ?? 0);\n }\n }\n\n return Object.fromEntries(dealt.map(({ hand }) => [\n effectiveGameId(hand),\n (this.boardContents.get(hand.id) ?? []).map((id) => this.view(this.internals.cardsById.get(id)!)),\n ]));\n }\n\n /** The board: current hand contents, in dealt order, keyed by hand gameId\n * (schema 5). Read it for what is out; peek the stock for what could\n * come.\n *\n * `boxRef` (a box gameId or id) narrows the read to that box's hands, in\n * the same shape and the same order: \"give me the barks hands\" is a\n * common host query, and boxes are how a game separates its storylet\n * systems, so the grouping belongs here rather than in every host. An\n * unknown box throws, as it does on turn() and peek(). */\n board(boxRef?: string): Record<string, DealtCard[]> {\n this.assertOpen();\n let keep: string | undefined;\n if (boxRef !== undefined) {\n const box = this.internals.boxesByGameId.get(boxRef) ?? this.internals.boxesById.get(boxRef);\n if (!box) throw new Error(`unknown box \"${boxRef}\"`);\n keep = box.id;\n }\n return Object.fromEntries([...this.boardContents.entries()]\n .filter(([handId]) => keep === undefined || this.internals.handsById.get(handId)!.box.id === keep)\n .map(([handId, ids]) => [\n effectiveGameId(this.internals.handsById.get(handId)!.hand),\n ids.map((id) => this.view(this.internals.cardsById.get(id)!)),\n ]));\n }\n\n /** Resolve a played/inspected card within a hand on the board. */\n private resolveDealt(cardId: string, handRef: string): { entry: CardEntry; ask: AskDescriptor } {\n const entry = this.internals.cardsById.get(cardId) ?? this.internals.cardsByGameId.get(cardId);\n if (!entry) throw new Error(`unknown card \"${cardId}\"`);\n const { hand, box } = this.resolveHand(handRef);\n if (!(this.boardContents.get(hand.id) ?? []).includes(entry.card.id)) {\n throw new Error(`card \"${effectiveGameId(entry.card)}\" is not dealt to hand \"${effectiveGameId(hand)}\"`);\n }\n return { entry, ask: this.askForHand(hand, box) };\n }\n\n /** Outcome availability, evaluated against CURRENT state on every ask\n * (schema 3.1/5) - never a deal-time snapshot. */\n outcomes(cardId: string, from: string): OutcomeView[] {\n this.assertOpen();\n const { entry, ask } = this.resolveDealt(cardId, from);\n const ctx = this.evalCtx(entry.box, entry.deck, this.buildHandEnv(ask));\n return entry.card.outcomes.map((o) => ({\n id: o.id,\n gameId: effectiveGameId(o),\n ...(o.title !== undefined ? { title: o.title } : {}),\n ...(o.purpose !== undefined ? { purpose: o.purpose } : {}),\n ...(o.fields !== undefined ? { fields: o.fields } : {}),\n available: this.passes(o.condition, ctx),\n }));\n }\n\n /** Apply an outcome (schema 3.7): the card must sit in a hand on the\n * board (you never play a card from inside the deck). Throws before any\n * mutation on a gated-shut outcome or a bad write target.\n *\n * A card with NO outcomes is played with none, named as \"\" (the\n * no-outcome-play brief, 2026-09-14): a masthead, a notice, a codex entry,\n * whose play means \"shown\". It is everything a play is except the writes:\n * the play log and the history functions count it, the box's turn moves by\n * the usual rule, the redraw rests it and it leaves its hand. \"\" is the one\n * spelling in all four runtimes, because a Blueprint pin cannot be absent.\n * Only the empty-for-empty case is new: \"\" on a card that has outcomes is\n * refused, and a named outcome on a card with none is refused as before. */\n play(cardId: string, outcomeGameId: string, from: string, opts: PlayOptions = {}): void {\n this.assertOpen();\n const { entry, ask } = this.resolveDealt(cardId, from);\n const bare = outcomeGameId === \"\";\n if (bare && entry.card.outcomes.length > 0) {\n throw new Error(`card \"${effectiveGameId(entry.card)}\" has outcomes (${entry.card.outcomes.map((o) => effectiveGameId(o)).join(\", \")}); name the one played`);\n }\n const outcome = bare ? undefined : entry.card.outcomes.find((o) => effectiveGameId(o) === outcomeGameId);\n if (!bare && !outcome) throw new Error(`card \"${effectiveGameId(entry.card)}\" has no outcome \"${outcomeGameId}\"`);\n\n const handEnv = this.buildHandEnv(ask);\n const ctx = this.evalCtx(entry.box, entry.deck, handEnv);\n if (outcome && !this.passes(outcome.condition, ctx)) {\n throw new Error(`outcome \"${outcomeGameId}\" on \"${effectiveGameId(entry.card)}\" is gated shut`);\n }\n\n // The played card's box's clock advances (schema 3.4); computed up\n // front so the play and its writes log as one action, one turn stamp.\n //\n // A TIMED box (design/engine-server.md 4.8) defaults to advancing\n // NOTHING: its clock is time, the host ticks it, and a play is not a\n // tick. A call that names `advanceTurns` still gets what it asked for,\n // in either kind of box, because the call says otherwise. This is the\n // whole of `turn`'s effect on the engine: the seconds are never read.\n const perPlay = entry.box.turn !== undefined ? 0 : this.internals.bundle.settings.playAdvancesTurns;\n const newTurn = (this.turnCounts.get(entry.box.id) ?? 0) + (opts.advanceTurns ?? perPlay);\n\n // Every right-hand side evaluates against PRE-play state, then all\n // writes land (schema 3.7).\n const writes: { target: string; value: ScalarValue }[] = [];\n for (const [target, expr] of Object.entries(outcome?.changes ?? {})) {\n writes.push({ target, value: this.eval(expr, ctx) });\n }\n for (const { target, value } of writes) {\n const { path, prev } = this.applyWrite(target, value, entry, handEnv);\n if (this.tracing) this.emit({ type: \"write\", target, path, value, ...(prev !== undefined ? { prev } : {}) }, newTurn);\n }\n\n const outcomeId = outcome ? effectiveGameId(outcome) : \"\";\n const record: PlayRecord = { card: effectiveGameId(entry.card), outcome: outcomeId, turn: newTurn };\n this.playLog.push(record);\n this.indexPlay(record);\n if (entry.card.redraw === \"never\") {\n // A shared one-shot leaves the world rather than this flow: the engine\n // holds it, so every flow is refused. A finite redraw deliberately does\n // NOT share, whatever the deck says - a cooldown is an absolute turn of\n // this flow's box clock, and there is no shared clock to compare it\n // against (design/shared-scarcity.md 9.3.2).\n if (cardIsShared(entry.card, entry.deck.shared ?? false)) this.engine.markTaken(entry.card.id);\n else this.cooldowns[entry.card.id] = Number.MAX_SAFE_INTEGER;\n } else if (typeof entry.card.redraw === \"number\") {\n this.cooldowns[entry.card.id] = newTurn + entry.card.redraw;\n }\n // The card leaves its hand, releasing its claim (schema 3.5/3.7).\n const handId = ask.hand!.id;\n this.boardContents.set(handId,\n (this.boardContents.get(handId) ?? []).filter((id) => id !== entry.card.id));\n this.turnCounts.set(entry.box.id, newTurn);\n // Emitted last: a handler reading the board and the clock sees the play.\n if (this.tracing) this.emit({ type: \"play\", card: effectiveGameId(entry.card), outcome: outcomeId, turn: newTurn }, newTurn);\n }\n\n /** One owned property's address, owner segment and all (4.4). */\n private address(kind: OwnedScope, id: string): string {\n return addressOf(this.internals, kind, id);\n }\n\n /** Land one change in whichever partition declares the name: the flow's\n * bag when the property is per-flow, the shared bag when it is shared -\n * the union/partition invariant made executable. */\n private landIn(kind: Exclude<PartitionKind, \"story\"> | \"story\", id: string | undefined, name: string, value: ScalarValue, path: string): { path: string; prev?: ScalarValue } {\n const own = kind === \"story\" ? this.stores.story : id !== undefined ? this.stores[kind].get(id) : undefined;\n const shared = kind === \"story\" ? this.internals.shared.story : id !== undefined ? this.internals.shared[kind].get(id) : undefined;\n const bag = own !== undefined && own.get(name) !== undefined ? own\n : shared !== undefined && shared.get(name) !== undefined ? shared\n : undefined;\n if (bag === undefined) throw new Error(`no property at \"${path}\"`);\n // An engine write: the bag's subscribers fire (the firing rule).\n const change = bag.set(name, value);\n return { path, ...(change.prev !== undefined ? { prev: change.prev } : {}) };\n }\n\n /** Land one change; returns the resolved store path (for the trace) and\n * the value it replaced (for the log's \"0 -> 1\" reading). */\n private applyWrite(target: string, value: ScalarValue, entry: CardEntry, handEnv: HandEnv): { path: string; prev?: ScalarValue } {\n const match = /^@([a-z]+)\\.([A-Za-z_][A-Za-z0-9_-]*)$/.exec(target);\n if (!match) throw new Error(`bad change target \"${target}\"`);\n const [, scope, name] = match as unknown as [string, string, string];\n switch (scope) {\n case \"world\": {\n const worldSet = this.internals.worldSet;\n if (!worldSet) throw new Error(`@world.${name} cannot be written: the host bound @world read-only`);\n // The story's own promise, kept HERE and only here, because here is where\n // the story does the writing: the table is consulted before the seam, so\n // an outcome never reaches the bag (which would let a host write past it)\n // nor a bound resolver (which cannot tell the two apart). The host's\n // setProperty is its own path and never asks. Patter's runtime refuses the\n // same write through the shared kernel, so both read one way.\n if (this.internals.worldReadOnly.has(name)) throw new Error(`'@world.${name}' is read-only (writable: false)`);\n const prev = this.internals.worldResolver.get(name);\n worldSet(name, value);\n return { path: `world.${name}`, ...(prev !== undefined ? { prev } : {}) };\n }\n case \"story\": return this.landIn(\"story\", undefined, name, value, `story.${name}`);\n case \"box\": return this.landIn(\"box\", entry.box.id, name, value, `${this.address(\"box\", entry.box.id)}.${name}`);\n case \"deck\": return this.landIn(\"deck\", entry.deck.id, name, value, `${this.address(\"deck\", entry.deck.id)}.${name}`);\n case \"hand\": {\n // Write-back routing (schema 3.6): the composed name remembers its\n // source store; writes to criteria/chosen-tag names are errors.\n const source = handEnv.sources.get(name);\n if (!source) throw new Error(`@hand.${name} is not composed in this ask`);\n if (source.kind === \"criteria\") throw new Error(`@hand.${name} is a chosen tag / criteria name and cannot be written`);\n return this.landIn(source.kind, source.id, name, value, `${this.address(source.kind, source.id)}.${name}`);\n }\n default: {\n // Another engine's game-wide scope (`@patter.x`): the family's shared\n // vocabulary lets a card write it, and the registry keeps that engine's\n // rules (a read-only property is refused). A story write, so no host flag.\n if (this.internals.registry.has(scope)) {\n const prev = this.internals.registry.get(scope, name);\n this.internals.registry.set(scope, name, value);\n return { path: `${scope}.${name}`, ...(prev !== undefined ? { prev } : {}) };\n }\n if (this.internals.bundle.externalScopes?.includes(scope)) {\n throw new Error(`@${scope}.${name} cannot be written: no engine on this registry registered @${scope}`);\n }\n throw new Error(`bad change target scope \"@${scope}\"`);\n }\n }\n }\n\n /** Advance one box's clock (schema 3.4): a turn is one draw-from-stock\n * session for that box, on THIS flow's clock. */\n advanceTurns(boxRef: string, n = 1): void {\n this.assertOpen();\n const box = this.internals.boxesByGameId.get(boxRef) ?? this.internals.boxesById.get(boxRef);\n if (!box) throw new Error(`unknown box \"${boxRef}\"`);\n const next = (this.turnCounts.get(box.id) ?? 0) + n;\n this.turnCounts.set(box.id, next);\n if (this.tracing) this.emit({ type: \"turns\", box: effectiveGameId(box), turn: next }, next);\n }\n\n // --- state access (host surface + test tooling) ---------------------------------\n\n /** Every box, bundle order: identity + this flow's clock (the enumeration\n * surface examiners key their turns sections on; parity member). */\n listBoxes(): BoxView[] {\n this.assertOpen();\n return this.internals.bundle.boxes.map((b) => ({\n id: b.id,\n gameId: effectiveGameId(b),\n ...(b.title !== undefined ? { title: b.title } : {}),\n turn: this.turnCounts.get(b.id) ?? 0,\n }));\n }\n\n /** THIS flow's kernel bags with their store path prefixes (the state\n * logger's mount surface; parity member). The shared bags are the\n * Engine's listBags; the flows are rebuilt by loadGame, so consumers\n * re-enumerate after a load. */\n listBags(): BagMount[] {\n this.assertOpen();\n const mounts: BagMount[] = [{ prefix: \"story\", bag: this.stores.story }];\n for (const kind of [\"box\", \"deck\", \"hand\", \"value\"] as const) {\n for (const [id, bag] of this.stores[kind]) mounts.push({ prefix: addressOf(this.internals, kind, id), bag });\n }\n return mounts;\n }\n\n /** The flow's FULL merged view as examiner rows (the property examiner /\n * editor surface, parity across all runtimes): @world read through the\n * resolver, then per scope the shared values and this flow's own.\n * Bundle order: world, story, then per-box / per-deck / per-hand /\n * per-tag stores. */\n listProperties(): PropertyRow[] {\n this.assertOpen();\n const out: PropertyRow[] = [];\n for (const d of this.internals.bundle.world.properties) {\n const value = this.internals.worldResolver.get(d.name);\n out.push({\n path: `world.${d.name}`, name: d.name, type: d.type,\n value: value ?? d.default, default: d.default,\n ...(d.values !== undefined ? { values: d.values } : {}),\n ...(d.stages !== undefined ? { stages: d.stages } : {}),\n // @world is FOREIGN - a host resolver backs it - so writability is whether that\n // resolver can be written at all AND what the declaration says, which is the\n // shared registry's own rule for a foreign scope (its foreignWritable). The\n // `as PropertyView` cast this replaced was hiding the field's absence: the row\n // type has always required it, and these rows shipped without one.\n //\n // A row is where `writable: false` is meant to SHOW (Reboot.md 10): it tells a\n // state panel this is the game's value, not the story's. It does not stop the\n // panel editing it - the host's setProperty passes `{ host: true }`.\n writable: this.internals.worldSet !== undefined && !this.internals.worldReadOnly.has(d.name),\n });\n }\n const add = (_prefix: string, shared: StateBag | undefined, own: StateBag | undefined): void => {\n for (const bag of [shared, own]) {\n if (bag === undefined) continue;\n for (const row of bag.rows()) out.push(row);\n }\n };\n add(\"story\", this.internals.shared.story, this.stores.story);\n for (const kind of OWNED_SCOPES) {\n const ids = new Set([...this.internals.shared[kind].keys(), ...this.stores[kind].keys()]);\n for (const id of ids) {\n add(addressOf(this.internals, kind, id), this.internals.shared[kind].get(id), this.stores[kind].get(id));\n }\n }\n return out;\n }\n\n /** Read by path: \"world.x\", \"story.gold\", \"value.docks.danger\",\n * \"box.village.heat\", \"deck.wares.n\", \"hand.the-elder.zone\" - the flow's\n * merged view, routed by the declaration's sharing.\n *\n * The owner segment is the entity's GAMEID, the name it is called by\n * everywhere else (4.4). Its internal id is accepted for this release and\n * earns a `diagnostic` naming the address to move to; the next lockstep\n * release refuses it. */\n getProperty(path: string): ScalarValue {\n this.assertOpen();\n const found = this.resolvePath(path);\n const value = found.kind === \"world\" ? this.internals.worldResolver.get(found.name)\n : found.kind === \"scope\" ? this.internals.registry.get(found.token, found.name)\n : found.own?.get(found.name) ?? found.shared?.get(found.name);\n if (value === undefined) throw new Error(`no property at \"${path}\"`);\n return value;\n }\n\n setProperty(path: string, value: ScalarValue): void {\n this.assertOpen();\n const found = this.resolvePath(path);\n if (found.kind === \"world\") {\n if (!this.internals.worldSet) throw new Error(`@world is read-only here: the host bound no write`);\n this.internals.worldSet(found.name, value, true);\n return;\n }\n if (found.kind === \"scope\") {\n this.internals.registry.set(found.token, found.name, value, { host: true });\n return;\n }\n const bag = found.own !== undefined && found.own.get(found.name) !== undefined ? found.own\n : found.shared !== undefined && found.shared.get(found.name) !== undefined ? found.shared\n : undefined;\n if (bag === undefined) throw new Error(`no property at \"${path}\"`);\n // A host write: silent under the firing rule (no subscriber feedback\n // loop), visible to the bag's audit hook, and flagged HOST so a\n // `writable: false` does not refuse the game its own value.\n bag.set(found.name, value, { silent: true, reason: \"host setProperty\", host: true });\n }\n\n private resolvePath(path: string):\n | { kind: \"world\"; name: string }\n | { kind: \"scope\"; token: string; name: string }\n | { kind: \"bag\"; own?: StateBag; shared?: StateBag; name: string } {\n const parts = path.split(\".\");\n if (parts.length === 2 && parts[0] === \"world\") return { kind: \"world\", name: parts[1]! };\n if (parts.length === 2 && parts[0] !== \"story\" && this.internals.registry.has(parts[0]!)) {\n return { kind: \"scope\", token: parts[0]!, name: parts[1]! };\n }\n if (parts.length === 2 && parts[0] === \"story\") {\n return { kind: \"bag\", own: this.stores.story, shared: this.internals.shared.story, name: parts[1]! };\n }\n if (parts.length === 3 && (parts[0] === \"box\" || parts[0] === \"deck\" || parts[0] === \"hand\" || parts[0] === \"value\")) {\n const kind = parts[0] as OwnedScope;\n const [, segment, name] = parts as unknown as [string, string, string];\n const owner = ownerOrThrow(this.internals, kind, segment, name);\n if (owner.legacy && this.tracing) {\n this.emit({ type: \"diagnostic\", where: \"property address\", message: legacyAddressMessage(this.internals, kind, segment, name) });\n }\n const own = this.stores[kind].get(owner.id);\n const shared = this.internals.shared[kind].get(owner.id);\n if (own === undefined && shared === undefined) throw new Error(`no ${kind} store \"${segment}\"`);\n return { kind: \"bag\", ...(own !== undefined ? { own } : {}), ...(shared !== undefined ? { shared } : {}), name };\n }\n throw new Error(`bad property path \"${path}\"`);\n }\n\n // --- persistence (schema 4) -------------------------------------------------\n\n /** @internal - this flow's blob: inside the engine's envelope without its\n * properties (the registry has them), or parked whole by saveFlow. */\n snapshot(withProps: boolean): FlowSave {\n return {\n ...(withProps ? { props: partitionValues(this.stores) } : {}),\n turns: Object.fromEntries(this.turnCounts),\n prng: this.prng.state(),\n cooldowns: this.cooldowns,\n board: Object.fromEntries(this.boardContents),\n playLog: this.playLog,\n };\n }\n\n /** @internal - restore a freshly opened flow from its blob (loadGame).\n * Orphaned keys (deleted entities) drop; new declarations keep defaults. */\n restore(saved: FlowSave): void {\n if (saved.props !== undefined) loadPartition(this.stores, saved.props);\n this.turnCounts = new Map(this.internals.bundle.boxes.map((b) => [b.id, 0]));\n for (const [boxId, turn] of Object.entries(saved.turns ?? {})) {\n if (this.turnCounts.has(boxId)) this.turnCounts.set(boxId, turn);\n }\n this.prng = makePrng(saved.prng);\n this.cooldowns = saved.cooldowns ?? {};\n this.playLog = saved.playLog ?? [];\n this.rebuildPlayIndex();\n this.boardContents = new Map(Object.entries(saved.board ?? {})\n .filter(([handId]) => this.internals.handsById.has(handId))\n .map(([handId, ids]) => [handId, ids.filter((id) => this.internals.cardsById.has(id))]));\n for (const handId of this.internals.handsById.keys()) {\n if (!this.boardContents.has(handId)) this.boardContents.set(handId, []);\n }\n }\n}\n","// ---------------------------------------------------------------------------\n// describeBundle - the bundle inspector's runtime half (design/engine-runtimes.md\n// section 2, piece 6).\n//\n// A BUNDLE-level API, deliberately NOT a session method: it answers the\n// integrator's question - \"I dropped a .storyletsc into my project, what may\n// my game code call?\" - from the imported asset alone, with no session, no\n// state and no game running. That makes the boundary rule (design 4) visible:\n// hands are what deal() takes, tag groups + tags are what peek() criteria are\n// drawn from, declared properties are what expressions read and a host may\n// set. Card lists are deliberately absent: cards are the engine's business,\n// counts are the orientation an integrator needs.\n//\n// Everything is in bundle order, so the description is deterministic and two\n// runtimes render the same rows in the same sequence. The property scopes are\n// the static twin of session.listProperties(): the same stores, in the same\n// order, before anything is instantiated (a hand instance carries its\n// template's declarations, exactly as the session's hand bags do).\n// ---------------------------------------------------------------------------\n\nimport { effectiveGameId, groupsOfBox, isHoleRef } from \"@storylet-studio/model\";\nimport type {\n Box, Bundle, Expression, Hand, PropertyDecl, PropertyType, ScalarValue,\n} from \"@storylet-studio/model\";\n\n/** What bundle this is: the staleness/identity triple plus the schema tag. */\nexport interface BundleIdentity {\n /** The bundle schema tag (\"storylets/bundle@1\", or \"@0\" from before the\n * project map). */\n schema: string;\n /** content.project - the project name a save must agree with. */\n project: string;\n /** content.version - the authored bundle version. */\n version: string;\n /** content.hash - hash32 over the canonical source shards (schema 2.8). */\n hash: string;\n /** \"full\" | \"stripped\": whether authoring metadata (titles) survived. */\n metadata: string;\n}\n\n/** One hole this hand fills from a property rather than with a tag: the hand\n * MOVES when that property is written (design/engine-server.md 4.6). `group`\n * is the tag group's gameId, `from` the reference exactly as authored. */\nexport interface MovableHole {\n group: string;\n from: string;\n}\n\n/** One hand: the deal() surface. `gameId` is the name deal() is called with. */\nexport interface HandSummary {\n gameId: string;\n title?: string;\n /** The owning box's gameId (peek's first argument for the same stock). */\n box: string;\n /** The effective slot cap: the hand's override, else its template's or\n * rule's, else \"unbounded\". */\n slots: number | \"unbounded\";\n /** The hand template's gameId; absent for a standalone (inline-rule) hand. */\n template?: string;\n /**\n * The holes filled from a property, in bundle order. Absent when the hand\n * has none, which is the ordinary case.\n *\n * Reported because it is the one thing about a hand an integrator cannot see\n * from its name: a movable hole means writing that property MOVES the hand,\n * so it is the difference between a fixed kiosk and a performer who walks\n * about. `setProperty` is the whole verb; there is no other.\n */\n movable?: MovableHole[];\n}\n\n/** One tag group and its tags, by gameId: the peek() criteria surface (a\n * criteria entry is `{ [group gameId]: tag gameId }`). */\nexport interface TagGroupSummary {\n gameId: string;\n tags: string[];\n}\n\n/** One box: identity, its ranking policy, its tag groups, and counts. */\nexport interface BoxSummary {\n gameId: string;\n title?: string;\n /** The box is on the project map (design/project-map-contract.md 3.7): it\n * may name the map's group in peek criteria beside its own `tagGroups`,\n * which list the box's OWN groups only. Absent is \"not on the map\". */\n usesMap?: true;\n /** The only per-box ranking policy (Reboot 2.2). */\n ranking: { specificity: boolean };\n /** Present on a TIMED box (design/engine-server.md 4.8): how long one of\n * its turns lasts. An integrator reading a bundle needs it to know which\n * boxes their host must tick, and how often. Absent is the ordinary box. */\n turn?: { seconds: number };\n /** How many cards in this box are DURABLE (design/engine-server.md 4.2):\n * their `redraw: \"never\"` spend outlives the run, and a server has to lift\n * and restore it. A count rather than a list, like every other number here:\n * an integrator needs to know whether this box has any such cards at all,\n * and which ones is the authoring tool's question. Absent when there are\n * none, which is the ordinary bundle. */\n durableCards?: number;\n tagGroups: TagGroupSummary[];\n counts: {\n decks: number;\n cards: number;\n hands: number;\n templates: number;\n tagGroups: number;\n };\n}\n\n/** One declared property: what expressions read and what a host may set. */\nexport interface PropertySummary {\n name: string;\n type: PropertyType;\n default: ScalarValue;\n /** Enum / flags options, where declared. */\n values?: string[];\n /** Declared DURABLE (design/engine-server.md 4.2): the value survives a run,\n * and a server lifts and restores it across one. The engine never reads it;\n * it is reported because it is the difference between a value an integrator\n * may reset and one somebody is going to expect back. Absent = run-scoped. */\n durable?: true;\n purpose?: string;\n}\n\n/** The scope a declaration block belongs to. `tag` declarations compose into\n * @hand for any ask that binds the tag (schema 3.6). */\nexport type PropertyScopeKind = \"world\" | \"story\" | \"box\" | \"deck\" | \"hand\" | \"tag\";\n\n/** One scope's declared properties. `owner` is the owning entity's gameId\n * (empty for world / story); `box` names its box; `group` names a tag's\n * group. A zone of the project map is a `tag` scope with `group` and NO\n * `box`: it belongs to none. */\nexport interface PropertyScopeSummary {\n scope: PropertyScopeKind;\n owner: string;\n box?: string;\n group?: string;\n properties: PropertySummary[];\n}\n\n/**\n * The project map (design/project-map-contract.md 3.7): its group, which boxes\n * are on it, and how much geometry the bundle carries.\n *\n * Counts rather than the geometry itself, which is the same judgement the rest\n * of this file makes: an inspector answers \"what is in here\", and a host that\n * wants the polygons reads `bundle.map.geometry` directly. The geometry counts\n * are zero when the build did not ask for geometry (`export.map`); the group is\n * there regardless, because hands and cards reference it.\n */\nexport interface MapSummary {\n /** The zone group's gameId: the name an opted-in box's peek criteria use. */\n group: string;\n /** Its tags (the zones), by gameId. */\n tags: string[];\n /** The opted-in boxes, by gameId, in bundle order. */\n boxes: string[];\n /** Drawn zones in the carried geometry. */\n zones: number;\n backgrounds: number;\n /** Box gameId -> placed hands standing on the map (design/engine-server.md\n * 4.3): where the kiosks are. Only boxes with a site have a key. */\n sites: Record<string, number>;\n}\n\n/** What a bundle offers a host, read from the asset alone. */\nexport interface BundleDescription {\n identity: BundleIdentity;\n /** Orientation, not inventory: no card lists (Reboot 2.1). */\n totals: {\n boxes: number;\n decks: number;\n cards: number;\n hands: number;\n templates: number;\n tagGroups: number;\n };\n boxes: BoxSummary[];\n /** Every hand in the bundle, box by box: the deal() surface. */\n hands: HandSummary[];\n /** world, story, then per box: the box, its decks, its hands, its tags;\n * then the project map's zones, once. Scopes that declare nothing are omitted (world and story always show,\n * so their absence reads as \"this bundle declares none\"). */\n properties: PropertyScopeSummary[];\n /** The project map, when the bundle has one. Absent is the bundle with no\n * map at all. */\n map?: MapSummary;\n}\n\nconst summarise = (decls: PropertyDecl[]): PropertySummary[] =>\n decls.map((d) => ({\n name: d.name,\n type: d.type,\n default: d.default,\n ...(d.values !== undefined ? { values: d.values } : {}),\n ...(d.durable === true ? { durable: true as const } : {}),\n ...(d.purpose !== undefined ? { purpose: d.purpose } : {}),\n }));\n\n/** How many cards in a box are durable: the card's own flag, else its deck's\n * (design/engine-server.md 4.2, the same inheritance `shared` has). */\nconst durableCardCount = (box: Box<Expression>): number =>\n box.decks.reduce((n, deck) =>\n n + deck.cards.filter((card) => (card.durable ?? deck.durable) === true).length, 0);\n\n/** A hand's declared @hand state: a template instance inherits its template's\n * declarations, a standalone hand declares its own (schema 2.6) - the same\n * rule the session's hand bags are built on. */\nconst handDecls = (hand: Hand<Expression>, box: Box<Expression>): PropertyDecl[] => {\n if (hand.template !== undefined) {\n return box.handTemplates.find((t) => t.id === hand.template)?.properties ?? [];\n }\n return hand.properties ?? [];\n};\n\n/** The hand's movable holes, in the bundle's own key order: every `chosen` /\n * rule-binding value that is a property reference rather than a tag (4.6).\n * The group is looked up where the engine looks it up: the box's own groups\n * and, for a box on the project map, the map's group, so the roaming\n * character whose hole names a zone is reported rather than lost (3.7). A\n * group id neither place holds is a bundle the engine refuses or cannot\n * bind, and is skipped rather than reported under its raw id: the\n * description speaks gameIds throughout. */\nconst movableHoles = (bundle: Bundle, hand: Hand<Expression>, box: Box<Expression>): MovableHole[] => {\n const filled = hand.template !== undefined ? hand.chosen : hand.rule?.bindings;\n const out: MovableHole[] = [];\n for (const [groupId, value] of Object.entries(filled ?? {})) {\n if (!isHoleRef(value)) continue;\n const group = groupsOfBox(bundle, box).find((g) => g.id === groupId);\n if (group === undefined) continue;\n out.push({ group: effectiveGameId(group), from: value });\n }\n return out;\n};\n\n/** The effective slot cap, resolved the way the session resolves capacity. */\nconst handSlots = (hand: Hand<Expression>, box: Box<Expression>): number | \"unbounded\" => {\n if (hand.slots !== undefined) return hand.slots;\n const declared = hand.template !== undefined\n ? box.handTemplates.find((t) => t.id === hand.template)?.slots\n : hand.rule?.slots;\n return declared === undefined ? \"unbounded\" : declared;\n};\n\n/** Describe a compiled bundle: the callable surface of an imported asset, no\n * session required (design/engine-runtimes.md 2, piece 6). Bundle order\n * throughout; the same shape every runtime returns. */\nexport function describeBundle(bundle: Bundle): BundleDescription {\n const boxes: BoxSummary[] = [];\n const hands: HandSummary[] = [];\n const properties: PropertyScopeSummary[] = [\n { scope: \"world\", owner: \"\", properties: summarise(bundle.world.properties) },\n { scope: \"story\", owner: \"\", properties: summarise(bundle.story.properties) },\n ];\n const totals = { boxes: 0, decks: 0, cards: 0, hands: 0, templates: 0, tagGroups: 0 };\n\n for (const box of bundle.boxes) {\n const boxGameId = effectiveGameId(box);\n const cards = box.decks.reduce((n, deck) => n + deck.cards.length, 0);\n boxes.push({\n gameId: boxGameId,\n ...(box.title !== undefined ? { title: box.title } : {}),\n ...(box.usesMap === true ? { usesMap: true as const } : {}),\n ranking: { specificity: box.ranking.specificity },\n ...(box.turn !== undefined ? { turn: { seconds: box.turn.seconds } } : {}),\n ...(durableCardCount(box) > 0 ? { durableCards: durableCardCount(box) } : {}),\n tagGroups: box.tagGroups.map((group) => ({\n gameId: effectiveGameId(group),\n tags: group.tags.map((tag) => effectiveGameId(tag)),\n })),\n counts: {\n decks: box.decks.length,\n cards,\n hands: box.hands.length,\n templates: box.handTemplates.length,\n tagGroups: box.tagGroups.length,\n },\n });\n totals.boxes += 1;\n totals.decks += box.decks.length;\n totals.cards += cards;\n totals.hands += box.hands.length;\n totals.templates += box.handTemplates.length;\n totals.tagGroups += box.tagGroups.length;\n\n for (const hand of box.hands) {\n const template = hand.template !== undefined\n ? box.handTemplates.find((t) => t.id === hand.template)\n : undefined;\n const movable = movableHoles(bundle, hand, box);\n hands.push({\n gameId: effectiveGameId(hand),\n ...(hand.title !== undefined ? { title: hand.title } : {}),\n box: boxGameId,\n slots: handSlots(hand, box),\n ...(template !== undefined ? { template: effectiveGameId(template) } : {}),\n ...(movable.length > 0 ? { movable } : {}),\n });\n }\n\n // The property scopes, in the session's store order: box, decks, hands,\n // tags. Empty declaration blocks are dropped (nothing to read or set).\n const push = (scope: PropertyScopeKind, owner: string, decls: PropertyDecl[], group?: string): void => {\n if (decls.length === 0) return;\n properties.push({\n scope, owner, box: boxGameId, ...(group !== undefined ? { group } : {}),\n properties: summarise(decls),\n });\n };\n push(\"box\", boxGameId, box.properties);\n for (const deck of box.decks) push(\"deck\", effectiveGameId(deck), deck.properties);\n for (const hand of box.hands) push(\"hand\", effectiveGameId(hand), handDecls(hand, box));\n for (const group of box.tagGroups) {\n for (const tag of group.tags) {\n push(\"tag\", effectiveGameId(tag), tag.properties ?? [], effectiveGameId(group));\n }\n }\n }\n\n // The project map's zones, ONCE and after every box, whichever boxes use\n // them: the same order the engine's value bags are built in. A `tag` scope\n // with no `box`, because a zone belongs to none.\n const map = bundle.map;\n if (map !== undefined) {\n const group = effectiveGameId(map.group);\n for (const tag of map.group.tags) {\n const decls = tag.properties ?? [];\n if (decls.length > 0) properties.push({ scope: \"tag\", owner: effectiveGameId(tag), group, properties: summarise(decls) });\n }\n totals.tagGroups += 1;\n }\n\n return {\n identity: {\n schema: bundle.schema,\n project: bundle.content.project,\n version: bundle.content.version,\n hash: bundle.content.hash,\n metadata: bundle.metadata,\n },\n totals,\n boxes,\n hands,\n properties,\n ...(map !== undefined ? {\n map: {\n group: effectiveGameId(map.group),\n tags: map.group.tags.map((tag) => effectiveGameId(tag)),\n boxes: bundle.boxes.filter((box) => box.usesMap === true).map((box) => effectiveGameId(box)),\n zones: map.geometry?.zones.length ?? 0,\n backgrounds: map.geometry?.backgrounds?.length ?? 0,\n sites: Object.fromEntries(Object.entries(map.geometry?.sites ?? {}).map(([box, sites]) => [box, sites.length])),\n },\n } : {}),\n };\n}\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.<gameId>.x / deck.<gameId>.x / hand.<gameId>.x /\n// value.<tagGameId>.x, and value.<boxGameId>/<tagGameId>.x for a tag gameId\n// two boxes share (4.4)\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 - plus its turns / cooldowns / board. @world is not\n * here for the same reason it is not in a save envelope: the host owns that\n * container and mounts/saves it itself (createWorldContainer).\n *\n * Taken off the BAGS, which is what a save envelope is made of, rather than\n * off the envelope itself. The two used to be interchangeable; from 4.4 they\n * are not, because a property ADDRESS names its owner by gameId while the\n * envelope stays keyed by internal id (a save has to survive a rename). The\n * bags carry the address, so reading them is what keeps this snapshot and\n * the live logger's lines in ONE path space - which is the invariant the\n * whole diff rests on. */\nexport function snapshotState(engine: Engine, flow: Flow): StateSnapshot {\n const out: StateSnapshot = {};\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 for (const { bag } of [...engine.listBags(), ...flow.listBags()]) {\n for (const row of bag.rows()) {\n if (row.value !== undefined) out[row.path] = row.value as ScalarValue;\n }\n }\n Object.assign(out, extraState(engine.saveGame().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// Save-file plumbing over the .storyletsave file (storylets/savefile@1): the\n// HOST's file - the engine's envelope (storylets/save@2; @1 still read) plus,\n// 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, SAVE_SCHEMA_V1 } 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\n || (file.engine?.schema !== SAVE_SCHEMA && file.engine?.schema !== SAVE_SCHEMA_V1)) {\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 // A card played with none (\"\") has no outcome to name.\n case \"play\": return `${stamp}play ${e.card}${e.outcome === \"\" ? \"\" : ` -> ${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, plus\n * \"(durable)\" where the declaration says the value outlives a run\n * (design/engine-server.md 4.2). Nothing is added for the ordinary\n * run-scoped property: that is what a property is. */\nexport function formatPropertySummary(p: PropertySummary): string {\n const options = p.values !== undefined && p.values.length > 0 ? ` [${p.values.join(\", \")}]` : \"\";\n const durable = p.durable === true ? \" (durable)\" : \"\";\n return `${p.name}: ${p.type} = ${showVal(p.default)}${options}${durable}`;\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 // A movable hole is the one thing about a hand its name cannot say: write\n // that property and the hand moves (4.6).\n const moves = hand.movable === undefined ? \"\"\n : `, moves ${hand.movable.map((m) => `${m.group} from ${m.from}`).join(\" and \")}`;\n line(handsBody, `${hand.gameId}: box ${hand.box}, slots ${hand.slots}${template}${moves}`\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 // --- the project map: which boxes are on it, and any geometry carried ---\n //\n // Only when there IS one. 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. The zones themselves are already under Properties and the opted-in\n // boxes' peek criteria; this says where they live and what the build carried\n // besides, since the geometry is inert and would otherwise go unmentioned.\n const map = description.map;\n if (map !== undefined) {\n const mapBody = fold(el, \"Project map\", open);\n mapBody.className = \"sl-maps\";\n line(mapBody, `${map.group}: ${map.tags.join(\", \")}`);\n line(mapBody, `boxes on the map: ${map.boxes.length > 0 ? map.boxes.join(\", \") : \"none\"}`);\n const sites = Object.entries(map.sites).map(([box, n]) => `${box} ${n}`).join(\", \");\n line(mapBody, `geometry carried (the engine ignores it): zones ${map.zones}, pictures ${map.backgrounds}`\n + `, hands ${sites === \"\" ? \"0\" : sites}`, \"sl-line sl-note\");\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 // A timed box says its unit here (design/engine-server.md 4.8), because\n // this is the line an integrator reads to find out what their host has to\n // tick. Nothing is added for an ordinary box: the answer \"a turn is a\n // play\" belongs in the docs, not on every line of every bundle.\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 + (box.turn !== undefined ? `, turn = ${box.turn.seconds}s` : \"\")\n // Only when there are any: a box whose cards all come back with the run\n // has nothing for a server to lift, and the zero would be noise.\n + (box.durableCards !== undefined ? `, durable cards ${box.durableCards}` : \"\"));\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), and since 4.4 that\n// holds for the trace event too: it is forwarded verbatim, and the runtime's\n// own ids are gameIds now, so the rule has no exception left.\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 through engine.hotSwap: a new\n// Engine over the new bundle, carrying the old one's run, on the same registry. 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 through the engine's own\n * `hotSwap`, returning the replacement. Never throws; a failure (unparseable\n * JSON, a bundle the runtime rejects, a different project) comes back as\n * `{ ok: false, error }` and the old engine is left as it was.\n *\n * Works whether the engine made its own registry or was given the game's: on\n * the game's registry the old engine hands its keys to the replacement, which a\n * plain save and load into a second engine cannot do (the two would clash).\n *\n * The engine remembers the options it was built with (seed, log, world,\n * registry), so `opts` is only for overriding one of them for the replacement.\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 // The engine's own hotSwap: on the game's registry the old engine has to hand\n // its keys over, which a plain save and load into a new engine cannot do.\n const { engine: next } = engine.hotSwap(bundle, opts);\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. Writing it\n * DIRECTLY is writing the kernel, so a `writable: false` declaration asks\n * the kernel's question: pass `{ host: true }` to say the game is speaking\n * (`bag.set(name, value, { host: true })`). Through `resolver` or an\n * engine's setProperty that is already answered. */\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.\n *\n * The container is the GAME's state, so it WRITES - even a declaration\n * carrying `writable: false`. That flag is the STORY's promise not to write\n * the value (Reboot.md 10), and the engine keeps it where the story writes: an\n * outcome is refused against the engine's read-only table before it ever\n * reaches this resolver. Enforcing it here as well refused the HOST too - the\n * clock the game must move, the harness driving the value it is testing\n * against - which is the opposite of what the flag says.\n *\n * So the declarations are seeded AS DECLARED, which is what an examiner over\n * this container should read, and the writes go through as HOST writes\n * (scoperegistry 0.6.0's `{ host: true }`). The resolver's `set` is the\n * engine's own doorway and passes the flag too: the engine has already sorted\n * story from host by then - a story write was refused earlier, a host write is\n * the only kind that arrives - and a resolver takes a name and a value with no\n * room to say which. A game wanting a rule of its own binds its own resolver\n * rather than this one; the ports' container (Unreal's UStoryletWorld) draws\n * the same line, with HostSet never refused and StorySet asking the game's own\n * read-only list. */\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, { host: true }); },\n },\n bag,\n values: () => bag.values,\n load: (values) => bag.load(values),\n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,KAAOI,GAAWJ,EAAI,KAAKI,CAAM,CACnC,CACF","names":["browser_exports","__export","Engine","Flow","applyLiveBundle","boardFrame","createBundleInspector","createStateLogger","createLiveLink","createPropertyInspector","createWorldContainer","describeBundle","deserializeState","diffState","ensureInspectorStyle","formatLogEntry","formatPropertySummary","formatScopeLabel","loadState","makePrng","saveState","serializeState","shuffleInPlace","snapshotState","deserialiseAst","node","args","EvalError","message","evaluate","node","ctx","dialect","missingPolicy","s","rec","n","scope","val","arg","ladder","ladderOf","current","stageIndex","def","l","r","left","right","lLadder","rLadder","sameLadder","valueEquals","assertNumbers","a","b","x","y","i","op","value","toUint32","seed","modded","makePrng","s","shuffleInPlace","arr","prng","i","j","CHECK_FLAGS_COUNTING_CALL","node","DEFAULT_COUNTING_CALLS","matchedSpecificity","evalTruthy","opts","countingCalls","walk","want","l","r","rule","c","operands","holds","ENGINE_SCOPES","NEVER_PLAYED","host","h","stringArg","fn","args","i","v","EvalError","flagsArg","OWN_SCOPES","EXTERNAL_SCOPES","ENGINE_SCOPES","t","storyletsDialect","token","nextRandom","a","b","lo","hi","flags","arg","result","idx","card","dimension","value","gameIdify","text","effectiveGameId","entity","pinned","gameIdify","valueAddresses","bundle","tags","box","boxGameId","group","tag","gameId","forms","list","print","accept","repeated","zoneQualified","candidates","ambiguous","zoneQualifiedValueAddressMessage","segment","zone","name","ambiguousValueAddressMessage","q","PLACE_GROUP","HOLE_REF","isHoleRef","value","parseHoleRef","m","BUNDLE_SCHEMA","BUNDLE_SCHEMA_V0","BUNDLE_SCHEMAS","groupsOfBox","bundle","box","allTagGroups","bundle","groups","box","SAVE_SCHEMA","SAVE_SCHEMA_V1","SAVEFILE_SCHEMA","diffState","prev","next","changes","paths","path","from","to","show","v","prefixOf","m","createStateLogger","adapter","opts","sink","line","label","emit","c","full","out","prefix","name","value","baseline","pushed","mounted","hook","bag","change","mount","mounts","i","diffed","PropertyBag","_PropertyBag","declarations","opts","n","d","name","defaultFor","value","change","audit","fn","rowFor","c","k","values","v","writable","pathPrefix","rowName","lowerCase","SAVE_FRAGMENT_VERSION","ScopeRegistry","token","o","bag","waiting","e","prefix","key","resolver","norm","decls","scope","out","owner","row","host","view","scopes","qualities","normOf","aliases","declsOf","m","properties","vals","blob","fragment","by","wants","tagKey","boxId","groupId","tagId","cardIsShared","card","deckShared","sharedCap","OWNER","identity","n","esc","id","unesc","sharedKey","kind","flowPrefix","flowId","flowKey","emptyPartitionValues","partitionsFromSections","sections","flowIds","shared","flows","rest","flowOf","escaped","p","key","values","m","sectionsOf","keyOf","out","bagFromDecls","decls","pathPrefix","PropertyBag","conditionPasses","v","SCOPE_DEFAULT_SHARED","isShared","scope","d","sharedHalf","flowHalf","OWNED_SCOPES","emptyOwnerIndex","emptyOwnerIndexes","indexOwner","index","entity","gameId","effectiveGameId","indexValueOwners","bundle","addresses","valueAddresses","segment","candidates","zone","handDeclsOf","internals","hand","b","addressOf","resolveOwner","byGameId","ownerOrThrow","name","owner","ambiguousValueAddressMessage","zoneQualifiedValueAddressMessage","legacyAddressMessage","buildPartition","half","at","box","deck","allTagGroups","group","tag","partitionValues","bag","loadPartition","emptyDraft","SORT_SEP","byKey","items","item","a","e","propKey","valueFits","decl","value","f","walkScope","saved","path","flow","draft","byName","clean","walkPartition","savedKind","ids","finishReport","drift","evicted","droppedCooldowns","c","droppedSpent","droppedProperties","defaultedProperties","retypedProperties","refuseUnreadableBundle","schema","BUNDLE_SCHEMAS","problems","map","mapName","PLACE_GROUP","boxTags","clash","boxName","g","names","where","template","Engine","_Engine","opts","ScopeRegistry","view","event","turn","h","viewRevision","viewCache","reg","ctx","scopes","k","entry","declSet","hostWorld","worldDecls","registered","mount","register","story","worldBag","host","sharedDecls","registry","grab","any","x","claim","otherClaims","existing","dealt","Flow","content","keepFlows","cardId","counts","found","parts","perFlow","message","token","add","_prefix","row","mounts","handler","options","snapshot","next","mine","registeredKeys","waiting","report","stillWaiting","SAVE_SCHEMA","all","take","envelope","plan","SAVE_SCHEMA_V1","moved","spent","withProps","props","cooldowns","cardName","board","restored","handId","known","kept","engine","seed","makePrng","put","pair","own","keep","boxRef","expr","node","deserialiseAst","ref","groups","groupsOfBox","record","tagIds","cached","made","t","since","NEVER_PLAYED","last","handEnv","others","source","evaluate","storyletsDialect","boundTags","askNames","condition","isHoleRef","criteria","groupRef","tagRef","groupName","parsed","parseHoleRef","wanted","ask","sources","contents","world","home","bound","tags","claimed","trace","verdict","gateOk","scored","deckCtx","refused","priority","spec","matchedSpecificity","i","j","run","shuffleInPlace","s","taken","declared","claimCounts","worldClaims","ordered","listed","handRef","handRefs","conditionOk","evict","reason","survivors","free","taking","added","from","o","outcomeGameId","bare","outcome","perPlay","newTurn","writes","target","prev","outcomeId","change","match","worldSet","summarise","decls","d","durableCardCount","box","n","deck","card","handDecls","hand","movableHoles","bundle","filled","out","groupId","value","isHoleRef","group","groupsOfBox","g","effectiveGameId","handSlots","declared","t","describeBundle","boxes","hands","properties","totals","boxGameId","cards","tag","template","movable","push","scope","owner","map","sites","snapshotState","engine","flow","out","bag","row","extraState","saved","boxId","turn","cardId","at","handId","cards","createStateLogger","opts","id","live","serializeState","engine","world","saveState","SAVEFILE_SCHEMA","loadState","file","SAVE_SCHEMA","SAVE_SCHEMA_V1","deserializeState","json","parsed","STYLE_ID","CSS","ensureInspectorStyle","style","eq","a","b","LOG_KINDS","LOG_KIND_LABELS","logKindOf","e","showVal","v","formatLogEntry","formatLogBody","flow","stamp","dealt","c","crit","g","t","listed","groupOf","path","parts","createPropertyInspector","engine","opts","liveFlow","live","el","head","h","saveBtn","blob","serializeState","url","filePicker","file","reader","deserializeState","refresh","loadBtn","filter","editors","groups","lastGroup","row","group","rowEl","buildRow","q","any","show","turnsHead","turnsBody","boardHead","boardBody","check","text","onChange","cls","label","box","buildLogPanel","which","caption","entriesOf","clear","empty","bar","body","kindOn","visibleLines","autoscroll","stampSeen","render","force","entries","lines","kind","on","copyBtn","clearBtn","flowLog","runLog","renderLog","line","parent","div","readLive","hand","cards","names","timer","pollMs","name","current","sync","commit","value","reset","widget","read","focused","w","input","select","o","s","readAll","showVal","v","formatPropertySummary","p","options","durable","formatScopeLabel","scope","group","line","parent","text","cls","div","fold","label","open","details","summary","body","createBundleInspector","bundle","opts","ensureInspectorStyle","description","describeBundle","el","head","h","identity","totals","ident","handsBody","hand","template","moves","m","tagsBody","box","propsBody","map","mapBody","sites","n","countsBody","DEFAULT_URL","BOARD_EVENTS","boardFrame","flow","id","hands","hand","cards","c","turns","box","createLiveLink","opts","url","Ctor","queue","sock","closed","build","engine","unsubscribe","announced","flush","m","post","frame","liveFlows","sendHello","flows","hello","f","first","b","postBoard","syncFlows","now","ids","onTrace","flowId","event","ev","msg","detach","next","applyLiveBundle","engine","bundleJson","opts","bundle","next","e","createWorldContainer","bundle","bag","PropertyBag","n","v","values"]}
|