libpetri 5.0.0 → 5.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{chunk-4HMFNYTH.js → chunk-BPGE7GZR.js} +2 -2
- package/dist/{chunk-75KEJQGC.js → chunk-EL4E6LVO.js} +1002 -205
- package/dist/chunk-EL4E6LVO.js.map +1 -0
- package/dist/debug/index.d.ts +2 -2
- package/dist/doclet/index.d.ts +1 -1
- package/dist/doclet/resources/petrinet-diagrams.js +4892 -4896
- package/dist/{event-store-hlH3-bzJ.d.ts → event-store-CUyHiIH7.d.ts} +1 -1
- package/dist/export/index.d.ts +1 -1
- package/dist/index.d.ts +23 -4
- package/dist/index.js +69 -4
- package/dist/index.js.map +1 -1
- package/dist/{petri-net-CH7UvjOW.d.ts → petri-net-6G5r1Wwb.d.ts} +59 -2
- package/dist/render-dom/index.js +1 -1
- package/dist/verification/index.d.ts +435 -14
- package/dist/verification/index.js +31 -1
- package/dist/verification/index.js.map +1 -1
- package/dist/viewer/index.js +1 -1
- package/dist/viewer/viewer.iife.js +4892 -4896
- package/package.json +5 -5
- package/dist/chunk-75KEJQGC.js.map +0 -1
- /package/dist/{chunk-4HMFNYTH.js.map → chunk-BPGE7GZR.js.map} +0 -0
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/core/token.ts","../src/core/place.ts","../src/core/arc.ts","../src/core/name.ts","../src/core/token-output.ts","../src/core/transition-context.ts","../src/core/token-input.ts","../src/core/transition.ts","../src/core/interface.ts","../src/core/instance.ts","../src/core/internal/subnet-rewriter.ts","../src/verification/verification-harness.ts","../src/core/subnet-def.ts","../src/core/compose-bindings.ts","../src/core/fusion-set.ts","../src/core/petri-net.ts","../src/core/subnet.ts","../src/runtime/marking.ts","../src/runtime/compiled-net.ts","../src/event/event-store.ts","../src/runtime/match-engine.ts","../src/runtime/out-violation-error.ts","../src/runtime/executor-support.ts","../src/runtime/bitmap-net-executor.ts","../src/runtime/precompiled-net.ts","../src/runtime/precompiled-net-executor.ts"],"sourcesContent":["/**\n * An immutable token carrying a typed value through the Petri net.\n *\n * Tokens flow from place to place as transitions fire, carrying typed\n * payloads that represent the state of a computation or workflow.\n */\nexport interface Token<T> {\n readonly value: T;\n /** Epoch milliseconds when the token was created. */\n readonly createdAt: number;\n /**\n * JSON-friendly projection of the token value, populated by\n * {@link SessionArchiveReader} when hydrating a v3 archive so replay\n * consumers see the same structured shape the writer emitted. Live tokens\n * (produced by {@link tokenOf} / {@link tokenAt}) leave this `undefined`;\n * the runtime ignores it. See [EVT-025](../../../spec/08-events-observability.md)\n * AC5. (libpetri 1.8.0+)\n */\n readonly structured?: unknown;\n}\n\n/** Cached singleton unit token. */\nconst UNIT_TOKEN: Token<null> = Object.freeze({\n value: null,\n createdAt: 0,\n});\n\n/** Creates a token with the given value and current timestamp. */\nexport function tokenOf<T>(value: T): Token<T> {\n return { value, createdAt: Date.now() };\n}\n\n/**\n * Returns a unit token (marker with no meaningful value).\n * Used for pure control flow where presence matters but data doesn't.\n * Returns a cached singleton whose `value` is `null`.\n */\nexport function unitToken(): Token<null> {\n return UNIT_TOKEN;\n}\n\n/** Creates a token with a specific timestamp (for testing/replay). */\nexport function tokenAt<T>(value: T, createdAt: number): Token<T> {\n return { value, createdAt };\n}\n\n/** Checks if this is the singleton unit token. */\nexport function isUnit(token: Token<unknown>): boolean {\n return token === UNIT_TOKEN;\n}\n","/**\n * A typed place in the Petri Net that holds tokens of a specific type.\n *\n * Places are the \"state containers\" of a Petri net. They hold tokens that\n * represent data or resources flowing through the net.\n *\n * Places use name-based equality (matching Java record semantics).\n * Internally use `Map<string, ...>` keyed by `place.name` for O(1) lookups.\n */\nexport interface Place<T> {\n readonly name: string;\n /** Phantom field to carry the type parameter. Never set at runtime. */\n readonly _phantom?: T;\n}\n\n/**\n * An environment place that accepts external token injection.\n * Wraps a regular Place and marks it for external event injection.\n */\nexport interface EnvironmentPlace<T> {\n readonly place: Place<T>;\n}\n\n/** Creates a typed place. */\nexport function place<T>(name: string): Place<T> {\n return { name };\n}\n\n/** Creates an environment place (external event injection point). */\nexport function environmentPlace<T>(name: string): EnvironmentPlace<T> {\n return { place: place<T>(name) };\n}\n","import type { Place } from './place.js';\n\n/**\n * Arc types connecting places to transitions in the Petri net.\n *\n * | Arc Type | Requires Token? | Consumes? | Effect |\n * |-----------|-----------------|-----------|--------------------------|\n * | Input | Yes | Yes | Token consumed on fire |\n * | Output | No | No | Token produced on complete|\n * | Inhibitor | No (blocks) | No | Disables transition |\n * | Read | Yes | No | Token remains |\n * | Reset | No | Yes (all) | All tokens removed |\n */\nexport type Arc = ArcInput | ArcOutput | ArcInhibitor | ArcRead | ArcReset;\n\nexport interface ArcInput<T = any> {\n readonly type: 'input';\n readonly place: Place<T>;\n}\n\nexport interface ArcOutput<T = any> {\n readonly type: 'output';\n readonly place: Place<T>;\n}\n\nexport interface ArcInhibitor<T = any> {\n readonly type: 'inhibitor';\n readonly place: Place<T>;\n}\n\nexport interface ArcRead<T = any> {\n readonly type: 'read';\n readonly place: Place<T>;\n}\n\nexport interface ArcReset<T = any> {\n readonly type: 'reset';\n readonly place: Place<T>;\n}\n\n// ==================== Factory Functions ====================\n\n/** Input arc: consumes token from place when transition fires. */\nexport function inputArc<T>(place: Place<T>): ArcInput<T> {\n return { type: 'input', place };\n}\n\n/** Output arc: produces token to place when transition fires. */\nexport function outputArc<T>(place: Place<T>): ArcOutput<T> {\n return { type: 'output', place };\n}\n\n/** Inhibitor arc: blocks transition if place has tokens. */\nexport function inhibitorArc<T>(place: Place<T>): ArcInhibitor<T> {\n return { type: 'inhibitor', place };\n}\n\n/** Read arc: requires token without consuming. */\nexport function readArc<T>(place: Place<T>): ArcRead<T> {\n return { type: 'read', place };\n}\n\n/** Reset arc: removes all tokens from place when firing. */\nexport function resetArc<T>(place: Place<T>): ArcReset<T> {\n return { type: 'reset', place };\n}\n\n/** Returns the place this arc connects to. */\nexport function arcPlace(arc: Arc): Place<any> {\n return arc.place;\n}\n","/**\n * ν-net token identities ([[NameId]]).\n *\n * A {@link NameId} is an **opaque correlation identity** carried by a token so\n * that a fork can mint a fresh name and a later join can re-merge exactly the\n * siblings that share it (see {@link import('./match-spec.js').MatchSpec}). The\n * only operation defined on names is **equality** (`===`); names also have a\n * lexicographic order used purely for the deterministic match tie-break\n * (NU-020).\n *\n * Identity is a *projection* of the token payload, not a field on\n * {@link import('./token.js').Token}: a `MatchSpec` declares the\n * `value → NameId` key, and the fork mints a fresh name into the payload via\n * `ctx.freshName()`. This keeps `Token` (and the event/archive formats)\n * unchanged while still giving the analyzer a name-symmetric uninterpreted sort\n * to reason about (spec NU-001).\n */\n\n/** An opaque correlation identity for ν-net fork/join (a branded string). */\nexport type NameId = string & { readonly __nameIdBrand: unique symbol };\n\n/** Creates a {@link NameId} from a string. */\nexport function nameId(value: string): NameId {\n return value as NameId;\n}\n","import type { Place } from './place.js';\nimport type { Token } from './token.js';\nimport { tokenOf } from './token.js';\n\n/**\n * An output entry: place + token pair.\n */\nexport interface OutputEntry {\n readonly place: Place<any>;\n readonly token: Token<any>;\n}\n\n/**\n * Collects output tokens produced by a transition action.\n */\nexport class TokenOutput {\n private readonly _entries: OutputEntry[] = [];\n\n /**\n * Once true, further writes are dropped instead of appended. Set by the executor\n * (via {@link import('./transition-context.js').TransitionContext.detachForTimeout})\n * when a firing times out, so the action it has stopped waiting for can no longer\n * reach the marking. Irreversible.\n */\n private detached = false;\n\n /** Add a value to an output place (creates token with current timestamp). */\n add<T>(place: Place<T>, value: T): this {\n if (this.detached) return this;\n this._entries.push({ place, token: tokenOf(value) });\n return this;\n }\n\n /** Add a pre-existing token to an output place. */\n addToken<T>(place: Place<T>, token: Token<T>): this {\n if (this.detached) return this;\n this._entries.push({ place, token });\n return this;\n }\n\n /**\n * @internal Severs this collector: subsequent {@link add}/{@link addToken} calls are\n * dropped. Executor machinery invoked when a firing times out — never call from an action.\n */\n detach(): void {\n this.detached = true;\n }\n\n /** Returns all collected outputs. */\n entries(): readonly OutputEntry[] {\n return this._entries;\n }\n\n /** Check if any outputs were produced. */\n isEmpty(): boolean {\n return this._entries.length === 0;\n }\n\n /** Returns the set of place names that received tokens. */\n placesWithTokens(): Set<string> {\n const result = new Set<string>();\n for (const entry of this._entries) {\n result.add(entry.place.name);\n }\n return result;\n }\n}\n","import type { Place } from './place.js';\nimport type { Token } from './token.js';\nimport type { TokenInput } from './token-input.js';\nimport { TokenOutput } from './token-output.js';\nimport { type NameId, nameId } from './name.js';\n\n/** Callback for emitting log messages from transition actions. */\nexport type LogFn = (level: string, message: string, error?: Error) => void;\n\n/** @internal Shared empty correspondence for the common (identity) case. */\nconst EMPTY_ALIAS: ReadonlyMap<string, Place<any>> = new Map();\n\n/**\n * @internal Process-global fallback counter for {@link TransitionContext.freshName}\n * when no executor-installed minter is present (e.g. a context built directly in\n * a unit test). Guarantees uniqueness; the executor installs a deterministic\n * per-run minter for replay-stable names.\n */\nlet GLOBAL_FRESH_NAME_COUNTER = 0;\n\n/**\n * Context provided to transition actions.\n *\n * Provides filtered access based on structure:\n * - Input places (consumed tokens)\n * - Read places (context tokens, not consumed)\n * - Output places (where to produce tokens)\n *\n * Enforces the structure contract — actions can only access places\n * declared in the transition's structure.\n */\nexport class TransitionContext {\n private readonly rawInput: TokenInput;\n /**\n * What the executor harvests. Identical to {@link writeTarget} until\n * {@link detachForTimeout} replaces it with a fresh collector the action cannot reach.\n */\n private _rawOutput: TokenOutput;\n /**\n * What the action writes to. Never reassigned, so an action already inside\n * `output(...)` cannot be redirected mid-write; severance happens by detaching this\n * collector, not by swapping it.\n */\n private readonly writeTarget: TokenOutput;\n private readonly allowedInputs: Set<string>;\n private readonly allowedReads: Set<string>;\n private readonly allowedOutputs: Set<string>;\n private readonly _inputPlaces: ReadonlySet<Place<any>>;\n private readonly _readPlaces: ReadonlySet<Place<any>>;\n private readonly _outputPlaces: ReadonlySet<Place<any>>;\n private readonly _transitionName: string;\n private readonly executionCtx: Map<string, unknown>;\n private readonly _logFn?: LogFn;\n private readonly placeAlias: ReadonlyMap<string, Place<any>>;\n private _freshNameSupplier?: () => NameId;\n\n constructor(\n transitionName: string,\n rawInput: TokenInput,\n rawOutput: TokenOutput,\n inputPlaces: ReadonlySet<Place<any>>,\n readPlaces: ReadonlySet<Place<any>>,\n outputPlaces: ReadonlySet<Place<any>>,\n executionContext?: Map<string, unknown>,\n logFn?: LogFn,\n placeAlias?: ReadonlyMap<string, Place<any>>,\n ) {\n this._transitionName = transitionName;\n this.rawInput = rawInput;\n this._rawOutput = rawOutput;\n this.writeTarget = rawOutput;\n this._inputPlaces = inputPlaces;\n this._readPlaces = readPlaces;\n this._outputPlaces = outputPlaces;\n const ai = new Set<string>();\n for (const p of inputPlaces) ai.add(p.name);\n this.allowedInputs = ai;\n const ar = new Set<string>();\n for (const p of readPlaces) ar.add(p.name);\n this.allowedReads = ar;\n const ao = new Set<string>();\n for (const p of outputPlaces) ao.add(p.name);\n this.allowedOutputs = ao;\n this.executionCtx = executionContext ?? new Map();\n this._logFn = logFn;\n this.placeAlias = placeAlias ?? EMPTY_ALIAS;\n }\n\n /**\n * Resolves a place key through the transition's declared→actual place\n * correspondence (per **MOD-031**). For a hand-written or directly-composed\n * transition the correspondence is the identity, so this returns `place`\n * unchanged; after instancing / port binding it maps a *declared* place\n * constant the action hardcodes to the *actual* composed place. The result\n * feeds both the declared-set check and the token-store access (both keyed by\n * `place.name`), so `inputPlaces()`/`outputPlaces()` discovery is unaffected.\n */\n private resolve<T>(place: Place<T>): Place<T> {\n const actual = this.placeAlias.get(place.name);\n return actual !== undefined ? (actual as Place<T>) : place;\n }\n\n // ==================== Input Access (consumed) ====================\n\n /** Get single consumed input value. Throws if place not declared or multiple tokens. */\n input<T>(place: Place<T>): T {\n const actual = this.resolve(place);\n this.requireInput(actual);\n const values = this.rawInput.values(actual);\n if (values.length !== 1) {\n throw new Error(\n `Place '${actual.name}' consumed ${values.length} tokens, use inputs() for batched access`\n );\n }\n return values[0]!;\n }\n\n /** Get all consumed input values for a place. */\n inputs<T>(place: Place<T>): readonly T[] {\n const actual = this.resolve(place);\n this.requireInput(actual);\n return this.rawInput.values(actual);\n }\n\n /** Get consumed input token with metadata. */\n inputToken<T>(place: Place<T>): Token<T> {\n const actual = this.resolve(place);\n this.requireInput(actual);\n return this.rawInput.get(actual);\n }\n\n /** Returns declared input places (consumed). */\n inputPlaces(): ReadonlySet<Place<any>> {\n return this._inputPlaces;\n }\n\n private requireInput(place: Place<any>): void {\n if (!this.allowedInputs.has(place.name)) {\n throw new Error(\n `Place '${place.name}' not in declared inputs: [${[...this.allowedInputs].join(', ')}]`\n );\n }\n }\n\n // ==================== Read Access (not consumed) ====================\n\n /** Get read-only context value. Throws if place not declared as read. */\n read<T>(place: Place<T>): T {\n const actual = this.resolve(place);\n this.requireRead(actual);\n return this.rawInput.value(actual);\n }\n\n /** Get all read-only context values for a place. */\n reads<T>(place: Place<T>): readonly T[] {\n const actual = this.resolve(place);\n this.requireRead(actual);\n return this.rawInput.values(actual);\n }\n\n /** Returns declared read places (context, not consumed). */\n readPlaces(): ReadonlySet<Place<any>> {\n return this._readPlaces;\n }\n\n private requireRead(place: Place<any>): void {\n if (!this.allowedReads.has(place.name)) {\n throw new Error(\n `Place '${place.name}' not in declared reads: [${[...this.allowedReads].join(', ')}]`\n );\n }\n }\n\n // ==================== Output Access ====================\n\n /**\n * Add one or more output values to the same place in a single call.\n *\n * Validates the place once, then appends each value to the output\n * collector. Calling with zero values is a no-op.\n *\n * @example\n * ctx.output(outPlace, 'a', 'b', 'c');\n * ctx.output(outPlace, ...someArray);\n *\n * @throws if place not declared as output.\n */\n output<T>(place: Place<T>, ...values: T[]): this {\n const actual = this.resolve(place);\n this.requireOutput(actual);\n for (const value of values) {\n this.writeTarget.add(actual, value);\n }\n return this;\n }\n\n /**\n * Add one or more pre-built output tokens to the same place in a single call.\n *\n * Validates the place once, then appends each token. Calling with zero\n * tokens is a no-op.\n *\n * @throws if place not declared as output.\n */\n outputToken<T>(place: Place<T>, ...tokens: Token<T>[]): this {\n const actual = this.resolve(place);\n this.requireOutput(actual);\n for (const token of tokens) {\n this.writeTarget.addToken(actual, token);\n }\n return this;\n }\n\n /** Returns declared output places. */\n outputPlaces(): ReadonlySet<Place<any>> {\n return this._outputPlaces;\n }\n\n private requireOutput(place: Place<any>): void {\n if (!this.allowedOutputs.has(place.name)) {\n throw new Error(\n `Place '${place.name}' not in declared outputs: [${[...this.allowedOutputs].join(', ')}]`\n );\n }\n }\n\n /**\n * Severs the action's output from the marking, for use when a firing times out.\n *\n * After this call the action's `output(...)` writes are dropped, and the executor\n * harvests a fresh collector the action holds no reference to. Anything the action\n * wrote *before* the timeout is discarded with it: a partial result merged with the\n * timeout branch would violate the transition's own output spec.\n *\n * This is the only isolation available — libpetri does not own the promise the action\n * runs on, so it cannot stop the work, only stop the result from landing.\n *\n * @internal Executor machinery — must be called by the executor, never by an action.\n */\n detachForTimeout(): void {\n this.writeTarget.detach();\n this._rawOutput = new TokenOutput();\n }\n\n /**\n * Produces into the executor's harvest collector rather than the action's write target.\n *\n * Identical to {@link output} before {@link detachForTimeout}; after it, this is the\n * only route that still reaches the marking. Used by the executor to deposit the\n * timeout branch.\n *\n * @internal Executor machinery — must be called by the executor, never by an action.\n */\n outputToHarvest<T>(place: Place<T>, value: T): this {\n const actual = this.resolve(place);\n this.requireOutput(actual);\n this._rawOutput.add(actual, value);\n return this;\n }\n\n // ==================== ν-name minting (NU-010) ====================\n\n /**\n * @internal Installs the ν-name minter. Wired by the executor at firing time\n * so names minted by {@link freshName} are monotonic across the run and\n * instance-prefixed (spec NU-010, NU-030).\n */\n setFreshNameSupplier(supplier: () => NameId): void {\n this._freshNameSupplier = supplier;\n }\n\n /**\n * Mints a fresh ν-name (the ν-binder primitive — spec NU-010).\n *\n * An action calls this on the fork side to create a correlation id, then\n * writes it into the sibling output payloads; a later join correlates those\n * siblings via a {@link import('./match-spec.js').MatchSpec}. Uses the\n * executor-installed minter when present; otherwise falls back to a\n * process-global counter prefixed by the transition name.\n */\n freshName(): NameId {\n if (this._freshNameSupplier) return this._freshNameSupplier();\n return nameId(`${this._transitionName}#${GLOBAL_FRESH_NAME_COUNTER++}`);\n }\n\n // ==================== Structure Info ====================\n\n /** Returns the transition name. */\n transitionName(): string {\n return this._transitionName;\n }\n\n // ==================== Execution Context ====================\n\n /** Retrieves an execution context object by key. */\n executionContext<T>(key: string): T | undefined {\n return this.executionCtx.get(key) as T | undefined;\n }\n\n /** Checks if an execution context object of the given key is present. */\n hasExecutionContext(key: string): boolean {\n return this.executionCtx.has(key);\n }\n\n // ==================== Logging ====================\n\n /** Emits a structured log message into the event store. */\n log(level: string, message: string, error?: Error): void {\n this._logFn?.(level, message, error);\n }\n\n // ==================== Internal ====================\n\n /** @internal Used by BitmapNetExecutor to collect outputs after action completion. */\n rawOutput(): TokenOutput {\n return this._rawOutput;\n }\n}\n","import type { Place } from './place.js';\nimport type { Token } from './token.js';\n\n/**\n * Consumed input tokens bound to their source places.\n *\n * Passed to TransitionAction as the `input` parameter, providing\n * type-safe read access to tokens consumed from input places.\n */\nexport class TokenInput {\n private readonly tokens = new Map<string, Token<any>[]>();\n\n /** Add a token (used by executor when firing transition). */\n add<T>(place: Place<T>, token: Token<T>): this {\n const existing = this.tokens.get(place.name);\n if (existing) {\n existing.push(token);\n } else {\n this.tokens.set(place.name, [token]);\n }\n return this;\n }\n\n /** Get all tokens for a place. */\n getAll<T>(place: Place<T>): readonly Token<T>[] {\n return (this.tokens.get(place.name) ?? []) as Token<T>[];\n }\n\n /** Get the first token for a place. Throws if no tokens. */\n get<T>(place: Place<T>): Token<T> {\n const list = this.tokens.get(place.name);\n if (!list || list.length === 0) {\n throw new Error(`No token for place: ${place.name}`);\n }\n return list[0] as Token<T>;\n }\n\n /** Get the first token's value for a place. Throws if no tokens. */\n value<T>(place: Place<T>): T {\n return this.get(place).value;\n }\n\n /** Get all token values for a place. */\n values<T>(place: Place<T>): readonly T[] {\n return this.getAll(place).map(t => t.value);\n }\n\n /** Get token count for a place. */\n count(place: Place<any>): number {\n return this.getAll(place).length;\n }\n\n /** Check if any tokens exist for a place. */\n has(place: Place<any>): boolean {\n return this.count(place) > 0;\n }\n}\n","import type { Place } from './place.js';\nimport type { ArcInhibitor, ArcRead, ArcReset } from './arc.js';\nimport type { In } from './in.js';\nimport type { MatchSpec } from './match-spec.js';\nimport type { Out, OutTimeout } from './out.js';\nimport type { Timing } from './timing.js';\nimport type { TransitionAction } from './transition-action.js';\nimport { passthrough } from './transition-action.js';\nimport { immediate } from './timing.js';\nimport { allPlaces } from './out.js';\n\n/** @internal Symbol key restricting construction to the builder. */\nconst TRANSITION_KEY = Symbol('Transition.internal');\n\n/** @internal Shared empty correspondence for the common (identity) case. */\nconst EMPTY_PLACE_ALIAS: ReadonlyMap<string, Place<any>> = new Map();\n\n/**\n * A transition in the Time Petri Net that transforms tokens.\n *\n * Transitions use identity-based equality (===) — each instance is unique\n * regardless of name. The name is purely a label for display/debugging/export.\n */\nexport class Transition {\n readonly name: string;\n readonly inputSpecs: readonly In[];\n readonly outputSpec: Out | null;\n readonly inhibitors: readonly ArcInhibitor[];\n readonly reads: readonly ArcRead[];\n readonly resets: readonly ArcReset[];\n readonly timing: Timing;\n readonly actionTimeout: OutTimeout | null;\n readonly action: TransitionAction;\n readonly priority: number;\n\n /**\n * ν-net join correlation: a subset of `inputSpecs` that must be correlated by\n * name equality on firing (spec NU-020). `null` for ordinary transitions.\n */\n readonly matchSpec: MatchSpec | null;\n\n /**\n * Per-transition **declared → actual** place correspondence (per\n * **MOD-031**), keyed by the author-original declared place **name** →\n * actual composed place. Empty for a hand-written or directly-composed\n * ([MOD-025]) transition (identity). Populated by the subnet rewriter after\n * instantiation ([MOD-010]) / port binding ([MOD-020]) so an action that\n * hardcodes a declared place constant resolves to the composed place via\n * {@link import('./transition-context.js').TransitionContext}. Consumed only\n * by the action-facing context I/O — never by enablement, firing, the\n * verifier, the exporter, or events (so [MOD-023] is unaffected).\n */\n readonly placeAlias: ReadonlyMap<string, Place<any>>;\n\n private readonly _inputPlaces: ReadonlySet<Place<any>>;\n private readonly _readPlaces: ReadonlySet<Place<any>>;\n private readonly _outputPlaces: ReadonlySet<Place<any>>;\n\n /** @internal Use {@link Transition.builder} to create instances. */\n constructor(\n key: symbol,\n name: string,\n inputSpecs: readonly In[],\n outputSpec: Out | null,\n inhibitors: readonly ArcInhibitor[],\n reads: readonly ArcRead[],\n resets: readonly ArcReset[],\n timing: Timing,\n action: TransitionAction,\n priority: number,\n placeAlias: ReadonlyMap<string, Place<any>> = EMPTY_PLACE_ALIAS,\n matchSpec: MatchSpec | null = null,\n ) {\n if (key !== TRANSITION_KEY) throw new Error('Use Transition.builder() to create instances');\n this.name = name;\n this.inputSpecs = inputSpecs;\n this.outputSpec = outputSpec;\n this.inhibitors = inhibitors;\n this.reads = reads;\n this.resets = resets;\n this.timing = timing;\n this.actionTimeout = findTimeout(outputSpec);\n this.action = action;\n this.priority = priority;\n this.placeAlias = placeAlias.size === 0 ? EMPTY_PLACE_ALIAS : placeAlias;\n this.matchSpec = matchSpec;\n\n // Precompute place sets\n const inputPlaces = new Set<Place<any>>();\n for (const spec of inputSpecs) {\n inputPlaces.add(spec.place);\n }\n this._inputPlaces = inputPlaces;\n\n const readPlaces = new Set<Place<any>>();\n for (const r of reads) {\n readPlaces.add(r.place);\n }\n this._readPlaces = readPlaces;\n\n const outputPlaces = new Set<Place<any>>();\n if (outputSpec !== null) {\n for (const p of allPlaces(outputSpec)) {\n outputPlaces.add(p);\n }\n }\n this._outputPlaces = outputPlaces;\n }\n\n /** Returns set of input places — consumed tokens. */\n inputPlaces(): ReadonlySet<Place<any>> {\n return this._inputPlaces;\n }\n\n /** Returns set of read places — context tokens, not consumed. */\n readPlaces(): ReadonlySet<Place<any>> {\n return this._readPlaces;\n }\n\n /** Returns set of output places — where tokens are produced. */\n outputPlaces(): ReadonlySet<Place<any>> {\n return this._outputPlaces;\n }\n\n /** Returns true if this transition has an action timeout. */\n hasActionTimeout(): boolean {\n return this.actionTimeout !== null;\n }\n\n toString(): string {\n return `Transition[${this.name}]`;\n }\n\n static builder(name: string): TransitionBuilder {\n return new TransitionBuilder(name);\n }\n}\n\nexport class TransitionBuilder {\n private readonly _name: string;\n private readonly _inputSpecs: In[] = [];\n private _outputSpec: Out | null = null;\n private readonly _inhibitors: ArcInhibitor[] = [];\n private readonly _reads: ArcRead[] = [];\n private readonly _resets: ArcReset[] = [];\n private _timing: Timing = immediate();\n private _action: TransitionAction = passthrough();\n private _priority = 0;\n private _placeAlias: ReadonlyMap<string, Place<any>> = EMPTY_PLACE_ALIAS;\n private _matchSpec: MatchSpec | null = null;\n\n constructor(name: string) {\n this._name = name;\n }\n\n /** Add input specifications with cardinality. */\n inputs(...specs: In[]): this {\n this._inputSpecs.push(...specs);\n return this;\n }\n\n /** Set the output specification (composite AND/XOR structure). */\n outputs(spec: Out): this {\n this._outputSpec = spec;\n return this;\n }\n\n /** Add inhibitor arc. */\n inhibitor(place: Place<any>): this {\n this._inhibitors.push({ type: 'inhibitor', place });\n return this;\n }\n\n /** Add inhibitor arcs. */\n inhibitors(...places: Place<any>[]): this {\n for (const p of places) {\n this._inhibitors.push({ type: 'inhibitor', place: p });\n }\n return this;\n }\n\n /** Add read arc. */\n read(place: Place<any>): this {\n this._reads.push({ type: 'read', place });\n return this;\n }\n\n /** Add read arcs. */\n reads(...places: Place<any>[]): this {\n for (const p of places) {\n this._reads.push({ type: 'read', place: p });\n }\n return this;\n }\n\n /** Add reset arc. */\n reset(place: Place<any>): this {\n this._resets.push({ type: 'reset', place });\n return this;\n }\n\n /** Add reset arcs. */\n resets(...places: Place<any>[]): this {\n for (const p of places) {\n this._resets.push({ type: 'reset', place: p });\n }\n return this;\n }\n\n /** Set timing specification. */\n timing(timing: Timing): this {\n this._timing = timing;\n return this;\n }\n\n /** Set the transition action. */\n action(action: TransitionAction): this {\n this._action = action;\n return this;\n }\n\n /** Set the priority (higher fires first). */\n priority(priority: number): this {\n this._priority = priority;\n return this;\n }\n\n /**\n * Sets the ν-net join correlation spec: the named input places must be\n * correlated by name equality on firing (spec NU-020). Every place referenced\n * by the spec must also be declared as an input.\n */\n match(spec: MatchSpec): this {\n this._matchSpec = spec;\n return this;\n }\n\n /**\n * Sets the per-transition declared→actual place correspondence (per\n * **MOD-031**). Populated by the subnet rewriter during the compose-time\n * rewrite; not normally called by hand-written nets, whose correspondence is\n * the identity (empty map).\n */\n placeAlias(alias: ReadonlyMap<string, Place<any>>): this {\n this._placeAlias = alias;\n return this;\n }\n\n build(): Transition {\n // Validate ForwardInput references\n if (this._outputSpec !== null) {\n const inputPlaceNames = new Set(this._inputSpecs.map(s => s.place.name));\n for (const fi of findForwardInputs(this._outputSpec)) {\n if (!inputPlaceNames.has(fi.from.name)) {\n throw new Error(\n `Transition '${this._name}': ForwardInput references non-input place '${fi.from.name}'`\n );\n }\n }\n }\n\n // Validate MatchSpec correlates only declared input places (NU-020).\n if (this._matchSpec !== null) {\n const inputPlaceNames = new Set(this._inputSpecs.map(s => s.place.name));\n for (const k of this._matchSpec.keys) {\n if (!inputPlaceNames.has(k.place.name)) {\n throw new Error(\n `Transition '${this._name}': MatchSpec correlates non-input place '${k.place.name}'`\n );\n }\n }\n }\n\n return new Transition(\n TRANSITION_KEY,\n this._name,\n [...this._inputSpecs],\n this._outputSpec,\n [...this._inhibitors],\n [...this._reads],\n [...this._resets],\n this._timing,\n this._action,\n this._priority,\n this._placeAlias,\n this._matchSpec,\n );\n }\n}\n\n/** Recursively searches the output spec for a Timeout node. */\nfunction findTimeout(out: Out | null): OutTimeout | null {\n if (out === null) return null;\n switch (out.type) {\n case 'timeout': return out;\n case 'and':\n case 'xor':\n for (const child of out.children) {\n const found = findTimeout(child);\n if (found !== null) return found;\n }\n return null;\n case 'place':\n case 'forward-input':\n return null;\n }\n}\n\n/** Recursively finds all ForwardInput nodes in the output spec. */\nfunction findForwardInputs(out: Out): Array<{ from: Place<any>; to: Place<any> }> {\n switch (out.type) {\n case 'forward-input':\n return [{ from: out.from, to: out.to }];\n case 'and':\n case 'xor':\n return out.children.flatMap(findForwardInputs);\n case 'timeout':\n return findForwardInputs(out.child);\n case 'place':\n return [];\n }\n}\n","import type { Place } from './place.js';\nimport type { Transition } from './transition.js';\n\n/**\n * Advisory direction metadata for an interface place.\n *\n * Per **MOD-004**, direction is metadata only — it does NOT constrain arc flow\n * at runtime. Token movement is governed by arcs declared per CORE-030..CORE-035.\n */\nexport type PortDirection = 'input' | 'output' | 'inout';\n\n/**\n * A typed interface place exposed for composition, per **MOD-003**.\n *\n * Direction is advisory metadata only (per **MOD-004**); the underlying\n * `Place<T>` reference is what is rewired at compose time.\n */\nexport interface Port<T = unknown> {\n /** Port name, unique within the {@link Interface}. */\n readonly name: string;\n /** Direction (advisory). */\n readonly direction: PortDirection;\n /** The body place exposed by this port. */\n readonly place: Place<T>;\n}\n\n/**\n * An interface transition exposed for synchronous fusion with a caller-side\n * transition, per **MOD-005**.\n *\n * The only present variant in this scaffolding is the synchronous channel.\n * The interface is left structurally open for future channel kinds without\n * breaking existing pattern matches on `name`/`transition`.\n */\nexport interface Channel {\n /** Channel name, unique within the channel namespace. */\n readonly name: string;\n /** The body transition exposed by this channel. */\n readonly transition: Transition;\n}\n\n/** @internal Symbol key restricting construction to the builder. */\nconst INTERFACE_KEY = Symbol('Interface.internal');\n\n/**\n * Immutable declaration of a subnet's **interface**: the set of {@link Port}\n * (interface places) and {@link Channel} (interface transitions) exposed for\n * composition with an enclosing net.\n *\n * Specified by `spec/11-modular-composition.md` requirements **MOD-003**\n * (port declaration) and **MOD-005** (channel declaration). Validation rules\n * per **MOD-006** are enforced by `SubnetDef.builder()` at subnet build\n * time; this class itself enforces only port/channel name uniqueness within\n * its respective namespaces (used both by `SubnetDef` and by hand-built\n * interfaces fed into `SubnetDef.fromNet`).\n */\nexport class Interface {\n readonly ports: ReadonlyMap<string, Port<unknown>>;\n readonly channels: ReadonlyMap<string, Channel>;\n\n /** @internal Use {@link Interface.builder} to create instances. */\n constructor(\n key: symbol,\n ports: ReadonlyMap<string, Port<unknown>>,\n channels: ReadonlyMap<string, Channel>,\n ) {\n if (key !== INTERFACE_KEY) throw new Error('Use Interface.builder() to create instances');\n this.ports = ports;\n this.channels = channels;\n }\n\n /** Looks up a port by name. Returns undefined when absent. */\n port<T = unknown>(name: string): Port<T> | undefined {\n return this.ports.get(name) as Port<T> | undefined;\n }\n\n /** Looks up a channel by name. Returns undefined when absent. */\n channel(name: string): Channel | undefined {\n return this.channels.get(name);\n }\n\n /**\n * Looks up a port by name and returns its underlying place, narrowed to\n * `Place<T>`. Returns undefined when the port does not exist.\n *\n * Note: TypeScript erases generics at runtime, so unlike Java's\n * `portPlaceAs(name, Class<T>)` this method cannot verify the token type at\n * runtime — the caller is trusted to supply the correct `T`. Per **MOD-022**,\n * type compatibility is enforced at compile time only in TypeScript.\n */\n placeAs<T>(name: string): Place<T> | undefined {\n const p = this.ports.get(name);\n if (p === undefined) return undefined;\n return p.place as Place<T>;\n }\n\n static builder(): InterfaceBuilder {\n return new InterfaceBuilder();\n }\n}\n\nexport class InterfaceBuilder {\n private readonly _ports = new Map<string, Port<unknown>>();\n private readonly _channels = new Map<string, Channel>();\n\n /** Add a pre-built port (rejects duplicate names). */\n port(port: Port<unknown>): this {\n if (this._ports.has(port.name)) {\n throw new Error(`Duplicate port name: '${port.name}'`);\n }\n this._ports.set(port.name, port);\n return this;\n }\n\n /** Add an input port (advisory direction). */\n inputPort<T>(name: string, place: Place<T>): this {\n return this.port({ name, direction: 'input', place: place as Place<unknown> });\n }\n\n /** Add an output port (advisory direction). */\n outputPort<T>(name: string, place: Place<T>): this {\n return this.port({ name, direction: 'output', place: place as Place<unknown> });\n }\n\n /** Add an in-out port (advisory direction). */\n inoutPort<T>(name: string, place: Place<T>): this {\n return this.port({ name, direction: 'inout', place: place as Place<unknown> });\n }\n\n /** Add a pre-built channel (rejects duplicate names). */\n channel(channel: Channel): this;\n /** Declare a synchronous channel by name + transition (rejects duplicate names). */\n channel(name: string, transition: Transition): this;\n channel(channelOrName: Channel | string, transition?: Transition): this {\n const ch: Channel = typeof channelOrName === 'string'\n ? { name: channelOrName, transition: transition! }\n : channelOrName;\n if (this._channels.has(ch.name)) {\n throw new Error(`Duplicate channel name: '${ch.name}'`);\n }\n this._channels.set(ch.name, ch);\n return this;\n }\n\n /** @internal Bulk-add ports already validated by the caller. */\n portsAll(ports: Iterable<Port<unknown>>): this {\n for (const p of ports) this.port(p);\n return this;\n }\n\n /** @internal Bulk-add channels already validated by the caller. */\n channelsAll(channels: Iterable<Channel>): this {\n for (const c of channels) this.channel(c);\n return this;\n }\n\n build(): Interface {\n // Freeze maps by handing them off as ReadonlyMap. Defensive copies guard\n // against post-build mutation through retained builder references.\n return new Interface(\n INTERFACE_KEY,\n new Map(this._ports),\n new Map(this._channels),\n );\n }\n}\n","import type { PetriNet } from './petri-net.js';\nimport type { Place } from './place.js';\nimport type { SubnetDef } from './subnet-def.js';\nimport type { SubnetInstance } from './subnet-instance.js';\nimport type { Transition } from './transition.js';\nimport type { TransitionAction } from './transition-action.js';\n\n/**\n * @internal Symbol key restricting construction to {@link SubnetDef.instantiate}\n * and the (future) `subnet-rewriter` module. Exported via the package-internal\n * factory {@link __createInstance} so the rewriter can construct Instances\n * without exposing the constructor publicly.\n */\nconst INSTANCE_KEY = Symbol('Instance.internal');\n\n/**\n * A typed module instance produced by {@link SubnetDef.instantiate}, per\n * `spec/11-modular-composition.md` requirements **MOD-010** (creation),\n * **MOD-011** (typed handle map), **MOD-012** (per-instance state isolation),\n * and **MOD-030** (action binding).\n *\n * An instance carries:\n * - The {@link prefix} used to rename body elements (per [MOD-010] separator `\"/\"`);\n * - A reference to the originating {@link SubnetDef};\n * - The renamed body — a structurally valid `PetriNet` per [CORE-040];\n * - Typed lookup handles for ports and channels keyed by their **original**\n * (pre-prefix) names;\n * - The `params` value supplied at instantiation.\n *\n * **Scaffolding status**: this class ships in scaffolding form. The\n * {@link bindActions} method throws `Error(\"not implemented\")` until the\n * `instantiate` rename pass lands in the next task. Direct accessors are\n * wired up so downstream code can take dependencies on the API shape today.\n *\n * @typeParam P parameter type (use `void` for unparameterised subnets)\n */\nexport class Instance<P = void> {\n readonly prefix: string;\n readonly def: SubnetDef<P>;\n readonly renamedBody: PetriNet;\n readonly portHandles: ReadonlyMap<string, Place<unknown>>;\n readonly channelHandles: ReadonlyMap<string, Transition>;\n readonly params: P;\n\n /**\n * @internal Use {@link SubnetDef.instantiate} (or the internal factory\n * {@link __createInstance}) to create instances.\n */\n constructor(\n key: symbol,\n prefix: string,\n def: SubnetDef<P>,\n renamedBody: PetriNet,\n portHandles: ReadonlyMap<string, Place<unknown>>,\n channelHandles: ReadonlyMap<string, Transition>,\n params: P,\n ) {\n if (key !== INSTANCE_KEY) {\n throw new Error('Use SubnetDef.instantiate() to create Instance values');\n }\n this.prefix = prefix;\n this.def = def;\n this.renamedBody = renamedBody;\n this.portHandles = portHandles;\n this.channelHandles = channelHandles;\n this.params = params;\n }\n\n /**\n * Returns the renamed {@link Place} corresponding to the named port.\n *\n * The port name is the **original** (pre-prefix) name as declared in the\n * subnet's `Interface`. Per **MOD-022**, TypeScript enforces token-type\n * compatibility at compile time only; this method does not validate `T`\n * at runtime. A missing name raises an `Error`.\n *\n * @throws when the port name is unknown\n */\n port<T>(name: string): Place<T> {\n const p = this.portHandles.get(name);\n if (p === undefined) {\n throw new Error(`No port named '${name}' in instance '${this.prefix}'`);\n }\n return p as Place<T>;\n }\n\n /**\n * Returns the renamed {@link Transition} corresponding to the named channel.\n *\n * @throws when the channel name is unknown\n */\n channel(name: string): Transition {\n const t = this.channelHandles.get(name);\n if (t === undefined) {\n throw new Error(`No channel named '${name}' in instance '${this.prefix}'`);\n }\n return t;\n }\n\n /**\n * Returns the debug-UI descriptor for this instance per **MOD-041**.\n */\n descriptor(): SubnetInstance {\n const transitions: string[] = [];\n for (const t of this.renamedBody.transitions) transitions.push(t.name);\n const exposedPlaces: string[] = [];\n for (const p of this.portHandles.values()) exposedPlaces.push(p.name);\n return {\n prefix: this.prefix,\n defName: this.def.name,\n transitions,\n exposedPlaces,\n params: this.params,\n parentPrefix: null,\n };\n }\n\n /**\n * Produces a derived instance whose specified transitions (named by their\n * **original**, pre-prefix names) carry the supplied actions per **MOD-030**.\n *\n * For each entry `[originalName, action]`, the renamed body is searched for\n * the transition whose name equals `prefix + \"/\" + originalName`. The\n * resulting instance shares the original `def`, `prefix`, `params`, and\n * port/channel handle topology — only the renamed body is rebuilt with new\n * actions. Per **MOD-030**, calling `bindActions` on one instance does NOT\n * affect the actions held by other instances of the same `def`.\n *\n * Unrecognised original names raise an `Error` so typos surface eagerly.\n */\n bindActions(actionsByOriginalName: Record<string, TransitionAction>): Instance<P> {\n // Build a Map<prefixedName, TransitionAction> for the resolver.\n // Validate every supplied original name against the renamed body's\n // transition set to surface typos eagerly.\n const prefixedByName = new Map<string, TransitionAction>();\n const renamedNames = new Set<string>();\n for (const t of this.renamedBody.transitions) {\n renamedNames.add(t.name);\n }\n\n for (const originalName of Object.keys(actionsByOriginalName)) {\n const prefixed = this.prefix + '/' + originalName;\n if (!renamedNames.has(prefixed)) {\n throw new Error(\n `Instance.bindActions: no transition '${originalName}' (resolved as ` +\n `'${prefixed}') in instance '${this.prefix}' of subnet '${this.def.name}'`,\n );\n }\n prefixedByName.set(prefixed, actionsByOriginalName[originalName]!);\n }\n\n // Use the existing PetriNet.bindActionsWithResolver — it preserves the\n // existing action when the resolver returns it (see petri-net.ts), so\n // unaffected transitions land in the new net by reference (sharing per\n // MOD-030).\n const reboundBody = this.renamedBody.bindActionsWithResolver((name) => {\n const action = prefixedByName.get(name);\n if (action !== undefined) return action;\n // Return the existing action so PetriNet.bindActionsWithResolver\n // short-circuits the rebuild for unaffected transitions.\n for (const t of this.renamedBody.transitions) {\n if (t.name === name) return t.action;\n }\n // Unreachable — the resolver is only called for transitions in this.renamedBody.\n /* istanbul ignore next */\n throw new Error(`Instance.bindActions: resolver invoked with unknown name '${name}'`);\n });\n\n // Rebuild the channel handles against the rebound body so callers see\n // the post-rebind transition (with its new action) when they ask for a\n // channel by name.\n const reboundChannelHandles = new Map<string, Transition>();\n if (this.channelHandles.size > 0) {\n const byName = new Map<string, Transition>();\n for (const t of reboundBody.transitions) {\n byName.set(t.name, t);\n }\n for (const [name, oldT] of this.channelHandles) {\n const refreshed = byName.get(oldT.name);\n if (refreshed === undefined) {\n /* istanbul ignore next */\n throw new Error(\n `Instance.bindActions: channel '${name}' transition '${oldT.name}' not found in rebound body`,\n );\n }\n reboundChannelHandles.set(name, refreshed);\n }\n }\n\n return __createInstance<P>(\n this.prefix,\n this.def,\n reboundBody,\n this.portHandles,\n reboundChannelHandles,\n this.params,\n );\n }\n}\n\n/**\n * @internal Package-internal factory used by {@link SubnetDef.instantiate}\n * and the (future) `subnet-rewriter` module to construct {@link Instance}\n * values without re-exporting the Symbol-guarded constructor key publicly.\n *\n * NOT part of the public API surface — do NOT re-export from `core/index.ts`.\n */\nexport function __createInstance<P>(\n prefix: string,\n def: SubnetDef<P>,\n renamedBody: PetriNet,\n portHandles: ReadonlyMap<string, Place<unknown>>,\n channelHandles: ReadonlyMap<string, Transition>,\n params: P,\n): Instance<P> {\n return new Instance<P>(\n INSTANCE_KEY,\n prefix,\n def,\n renamedBody,\n portHandles,\n channelHandles,\n params,\n );\n}\n","/**\n * @internal\n *\n * Package-internal utility encapsulating the structural rewrite primitive used\n * by {@link SubnetDef.instantiate} and (later) `PetriNetBuilder.compose(...)`\n * per **MOD-020**.\n *\n * The rewrite is purely structural: every place reference in every arc is\n * replaced according to a supplied `Map<string, Place<unknown>>` keyed by\n * **original place name** (TypeScript Place identity is name-based per\n * `runtime/compiled-net.ts`'s `Map<string, number>`). Every transition is\n * rebuilt with rewritten arcs, preserving timing, priority, and action by\n * reference per **MOD-030**.\n *\n * ## Design — one engine, multiple callers\n *\n * The {@link renameNet} entry point is specialised to the rename pass: it\n * allocates fresh prefixed places via the `place(name)` factory, records the\n * old-to-new mapping in caller-supplied `Map`s (so callers can build\n * port/channel handle maps), and emits a renamed `PetriNet`. The arc-rewrite\n * helpers ({@link rewriteIn}, {@link rewriteOut}, etc.) are factored out so\n * the future `compose(...)` caller can substitute port-place mappings against\n * an arbitrary remap without renaming everything.\n *\n * ## Performance — V8 hidden-class stability\n *\n * - Places are constructed exclusively via the existing `place<T>(name)`\n * factory (from `core/place.ts`) so V8 can settle a single hidden class for\n * all `Place` allocations. We never synthesize `{name: ...}` literals\n * inline.\n * - Arcs are constructed via the existing `inputArc`, `inhibitorArc`,\n * `readArc`, `resetArc`, `outPlace`, `forwardInput`, `timeout` factories;\n * `In` shapes go through `one`, `exactly`, `all`, `atLeast`.\n * - The recursive `Out.And` / `Out.Xor` reconstruction uses pre-sized\n * `Array<Out>` plus a `for` loop (parallel to the Java perf reasoning about\n * `Stream` overhead — see `SubnetRewriter.rewriteOut`). `Array.prototype.map`\n * is avoided on this hot path.\n * - The `inputs(...)` rest-parameter into `TransitionBuilder.inputs` does\n * create a shallow array copy internally; this matches Java's\n * `Arc.In[t.inputSpecs().size()]` allocation and is the minimum allocation\n * needed to land arcs in the builder's defensive copy.\n *\n * Specified by `spec/11-modular-composition.md` MOD-010, MOD-011, MOD-012,\n * MOD-013, MOD-020, MOD-030.\n */\n\nimport type { Place } from '../place.js';\nimport { place } from '../place.js';\nimport type { ArcInhibitor, ArcRead, ArcReset } from '../arc.js';\nimport type { In } from '../in.js';\nimport { one, exactly, all, atLeast } from '../in.js';\nimport type { Out } from '../out.js';\nimport { and, outPlace, forwardInput, timeout, allPlaces } from '../out.js';\nimport { PetriNet } from '../petri-net.js';\nimport { Transition } from '../transition.js';\nimport type { MatchSpec } from '../match-spec.js';\nimport type { Timing } from '../timing.js';\nimport type { TransitionAction } from '../transition-action.js';\nimport { isPassthrough } from '../transition-action.js';\n\n// ============================================================\n// Public entry points\n// ============================================================\n\n/**\n * Returns a renamed copy of `orig`: same generic token type at the type\n * level, with `prefix + \"/\" + orig.name` as the new name. Goes through the\n * `place<T>(name)` factory for V8 hidden-class stability.\n */\nexport function renamePlace<T>(orig: Place<T>, prefix: string): Place<T> {\n return place<T>(prefix + '/' + orig.name);\n}\n\n/**\n * Renames every place and transition of `body`, prefixing each name with\n * `prefix + \"/\"`.\n *\n * **Side effects**: fills the two supplied maps so the caller can resolve\n * original-place / original-transition references against the rewritten\n * equivalents:\n *\n * - `placeRemap` — original place **name** → renamed place\n * - `transitionRemap` — original transition **name** → renamed transition\n *\n * Both maps are cleared on entry, then populated in iteration order.\n *\n * Note: the maps are keyed by name strings (not Place / Transition object\n * identity) because TypeScript Place identity is name-based per\n * `runtime/compiled-net.ts` (`Map<string, number>`). This matches how the\n * compiled net dedupes places.\n *\n * @param body the subnet body to rewrite\n * @param prefix the rename prefix\n * @param placeRemap caller-allocated map filled with old-name → new place\n * @param transitionRemap caller-allocated map filled with old-name → new transition\n * @returns a fresh `PetriNet` whose name is `prefix + \"/\" + body.name` and\n * whose places/transitions are renamed copies\n */\nexport function renameNet(\n body: PetriNet,\n prefix: string,\n placeRemap: Map<string, Place<unknown>>,\n transitionRemap: Map<string, Transition>,\n): PetriNet {\n placeRemap.clear();\n transitionRemap.clear();\n\n // Pass 1: rename every place. We must do this before transitions so arc\n // rewriting can resolve every place reference unambiguously.\n for (const orig of body.places) {\n placeRemap.set(orig.name, renamePlace(orig as Place<unknown>, prefix));\n }\n\n // Pass 2: rebuild every transition with arcs rewritten via placeRemap.\n const builder = PetriNet.builder(prefix + '/' + body.name);\n\n // Add places explicitly: some may not be referenced by any transition arc,\n // but were declared on the body — preserve that membership.\n for (const renamedPlace of placeRemap.values()) {\n builder.place(renamedPlace);\n }\n\n for (const t of body.transitions) {\n const renamed = rewriteTransition(t, prefix, placeRemap);\n transitionRemap.set(t.name, renamed);\n builder.transition(renamed);\n }\n\n return builder.build();\n}\n\n/**\n * Rebuilds `t` with name `prefix + \"/\" + t.name` and every arc rewritten\n * through `placeRemap`. Timing, priority, and action are carried through by\n * reference (action sharing per **MOD-030**).\n *\n * If a place referenced by an arc is not present in `placeRemap` (keyed by\n * original name), the arc retains the original place — partial remaps are\n * valid (used by the future `compose(...)` caller).\n */\nexport function rewriteTransition(\n t: Transition,\n prefix: string,\n placeRemap: Map<string, Place<unknown>>,\n): Transition {\n return rebuildWithName(t, prefix + '/' + t.name, placeRemap);\n}\n\n/**\n * Rebuilds `t` with the **same** name, substituting every arc place reference\n * through `remap`. Timing, priority, and action are carried through by\n * reference (action sharing per **MOD-030**).\n *\n * This is the rewrite primitive used by `PetriNetBuilder.compose(...)` (task\n * #12) when merging an instance's renamed body into an enclosing net: the\n * transition's prefixed name is already unique within the host (per\n * [MOD-010]), so no further renaming is needed — only port-place references\n * are substituted with the caller's places.\n *\n * If a place referenced by an arc is not present in `remap`, the arc retains\n * the original place — partial remaps are valid.\n */\nexport function substitutePlaces(\n t: Transition,\n remap: Map<string, Place<unknown>>,\n): Transition {\n return rebuildWithName(t, t.name, remap);\n}\n\n// ============================================================\n// Shared transition-rebuild implementation\n// ============================================================\n\n/**\n * Shared implementation — the single transition-rebuild site: rebuilds `t` with\n * the supplied `name` and arc places rewritten through `remap`. Used by\n * {@link rewriteTransition} (which prefixes the name), {@link substitutePlaces}\n * (which keeps the name), and {@link applyFusion} (which additionally passes\n * `normalizeInputs` to reconcile arcs the remap made collide).\n *\n * The action timeout is not a builder field: {@link Transition} derives it from\n * the output spec, which {@link rewriteOut} carries through — including the\n * `timeout` node itself (IO-013 / EXEC-022).\n */\nfunction rebuildWithName(\n t: Transition,\n name: string,\n remap: Map<string, Place<unknown>>,\n normalizeInputs?: (inputs: readonly In[]) => readonly In[],\n): Transition {\n const builder = Transition.builder(name)\n .timing(t.timing)\n .priority(t.priority)\n .action(t.action);\n\n // Build the declared→actual place correspondence (MOD-031) from the same\n // `remap` the arcs are rewritten through, chaining any pre-existing alias so\n // nested instantiation ([MOD-013]) resolves declared → final composed place.\n const alias = buildPlaceAlias(t, remap);\n if (alias.size > 0) {\n builder.placeAlias(alias);\n }\n\n if (t.inputSpecs.length > 0) {\n // Pre-size for V8 hidden-class stability; for-loop over Stream.map.\n const rewrittenInputs = new Array<In>(t.inputSpecs.length);\n for (let i = 0; i < t.inputSpecs.length; i++) {\n rewrittenInputs[i] = rewriteIn(t.inputSpecs[i]!, remap);\n }\n builder.inputs(...(normalizeInputs !== undefined\n ? normalizeInputs(rewrittenInputs)\n : rewrittenInputs));\n }\n\n if (t.outputSpec !== null) {\n builder.outputs(rewriteOut(t.outputSpec, remap));\n }\n\n for (let i = 0; i < t.inhibitors.length; i++) {\n builder.inhibitor(rewriteInhibitor(t.inhibitors[i]!, remap).place);\n }\n for (let i = 0; i < t.reads.length; i++) {\n builder.read(rewriteRead(t.reads[i]!, remap).place);\n }\n for (let i = 0; i < t.resets.length; i++) {\n builder.reset(rewriteReset(t.resets[i]!, remap).place);\n }\n\n // Carry the ν-net join correlation forward, following place renames so a\n // composed join still correlates the right (renamed) inputs (NU-020/-030).\n if (t.matchSpec !== null) {\n builder.match({\n keys: t.matchSpec.keys.map(k => ({\n place: remap.get(k.place.name) ?? k.place,\n key: k.key,\n })),\n });\n }\n\n return builder.build();\n}\n\n// ============================================================\n// Declared→actual place correspondence (MOD-031)\n// ============================================================\n\n/**\n * Builds the per-transition **declared → actual** place correspondence (per\n * **MOD-031**) for a transition being rewritten through `remap`, keyed by the\n * author-original declared place **name** → actual composed place. Mirrors the\n * Rust `build_local_name_map` / Java `buildPlaceAlias` algorithm so all three\n * implementations agree.\n *\n * **Chained path** — when `t` already carries a non-empty alias (from an\n * earlier rewrite pass: nested instantiation [MOD-013], or\n * instantiate-then-compose), each `declaredName → prev` entry is carried\n * forward as `declaredName → (remap.get(prev.name) ?? prev)`; identity results\n * are dropped. The arcs are deliberately **not** walked in this case — their\n * places are intermediate-pass names, not author-original, so recording them\n * would leak intermediate keys the user never declared.\n *\n * **First-pass path** — when `t` carries no alias, every arc place maps to its\n * remapped place keyed by the author-original name; identity entries are\n * skipped. The ForwardInput `from` is captured via the input walk and its `to`\n * via {@link allPlaces}.\n */\nfunction buildPlaceAlias(\n t: Transition,\n remap: Map<string, Place<unknown>>,\n): ReadonlyMap<string, Place<unknown>> {\n const prev = t.placeAlias;\n if (remap.size === 0 && prev.size === 0) {\n return EMPTY_ALIAS;\n }\n\n const alias = new Map<string, Place<unknown>>();\n\n if (prev.size > 0) {\n for (const [declaredName, prevActual] of prev) {\n const replaced = remap.get(prevActual.name);\n const finalActual = replaced !== undefined ? replaced : prevActual;\n if (finalActual.name !== declaredName) {\n alias.set(declaredName, finalActual);\n }\n }\n return alias;\n }\n\n const record = (p: Place<unknown>): void => {\n if (alias.has(p.name)) return;\n const replaced = remap.get(p.name);\n if (replaced !== undefined && replaced.name !== p.name) {\n alias.set(p.name, replaced);\n }\n };\n for (const spec of t.inputSpecs) record(spec.place as Place<unknown>);\n for (const rd of t.reads) record(rd.place as Place<unknown>);\n for (const inh of t.inhibitors) record(inh.place as Place<unknown>);\n for (const rs of t.resets) record(rs.place as Place<unknown>);\n if (t.outputSpec !== null) {\n for (const p of allPlaces(t.outputSpec)) record(p as Place<unknown>);\n }\n return alias;\n}\n\n/** @internal Shared empty correspondence for the no-op rewrite case. */\nconst EMPTY_ALIAS: ReadonlyMap<string, Place<unknown>> = new Map();\n\n// ============================================================\n// Arc rewrite helpers (exhaustive switches — no default)\n// ============================================================\n\n/**\n * Rewrites an {@link In} via the place remap. Exhaustive `switch` over the\n * discriminated union variants `one`, `exactly`, `all`, `at-least`.\n */\nexport function rewriteIn(spec: In, remap: Map<string, Place<unknown>>): In {\n switch (spec.type) {\n case 'one':\n return one(resolve(spec.place, remap));\n case 'exactly':\n return exactly(spec.count, resolve(spec.place, remap));\n case 'all':\n return all(resolve(spec.place, remap));\n case 'at-least':\n return atLeast(spec.minimum, resolve(spec.place, remap));\n }\n}\n\n/**\n * Rewrites an {@link Out} via the place remap. Exhaustive recursive `switch`\n * over the discriminated union variants `place`, `forward-input`, `and`, `xor`,\n * `timeout`.\n *\n * `and` / `xor` traversal uses explicit pre-sized `Array<Out>` + indexed\n * `for` (no `Array.prototype.map`) per the perf notes on this module.\n */\nexport function rewriteOut(out: Out, remap: Map<string, Place<unknown>>): Out {\n switch (out.type) {\n case 'place':\n return outPlace(resolve(out.place, remap));\n\n case 'forward-input':\n return forwardInput(resolve(out.from, remap), resolve(out.to, remap));\n\n case 'and': {\n const children = out.children;\n const rewritten = new Array<Out>(children.length);\n for (let i = 0; i < children.length; i++) {\n rewritten[i] = rewriteOut(children[i]!, remap);\n }\n // Reconstruct via the same shape the `and(...)` factory produces. We\n // skip the factory's variadic spread on this hot path; the resulting\n // shape is identical.\n return { type: 'and', children: rewritten };\n }\n\n case 'xor': {\n const children = out.children;\n const rewritten = new Array<Out>(children.length);\n for (let i = 0; i < children.length; i++) {\n rewritten[i] = rewriteOut(children[i]!, remap);\n }\n return { type: 'xor', children: rewritten };\n }\n\n case 'timeout':\n return timeout(out.afterMs, rewriteOut(out.child, remap));\n }\n}\n\n/** Rewrites an {@link ArcInhibitor} via the place remap. */\nexport function rewriteInhibitor(\n inh: ArcInhibitor,\n remap: Map<string, Place<unknown>>,\n): ArcInhibitor {\n return { type: 'inhibitor', place: resolve(inh.place, remap) };\n}\n\n/** Rewrites an {@link ArcRead} via the place remap. */\nexport function rewriteRead(\n rd: ArcRead,\n remap: Map<string, Place<unknown>>,\n): ArcRead {\n return { type: 'read', place: resolve(rd.place, remap) };\n}\n\n/** Rewrites an {@link ArcReset} via the place remap. */\nexport function rewriteReset(\n rs: ArcReset,\n remap: Map<string, Place<unknown>>,\n): ArcReset {\n return { type: 'reset', place: resolve(rs.place, remap) };\n}\n\n// ============================================================\n// Resolution helper\n// ============================================================\n\n/**\n * Looks up `p` in `remap` by `p.name`; returns the original if absent\n * (partial-remap semantics for the future `compose` caller).\n *\n * The unchecked cast is safe at runtime: TypeScript erases generics, and the\n * remap is populated by {@link renamePlace}, which preserves the token type\n * by construction (the renamed Place carries the same `T` at the type level\n * via the `place<T>(name)` factory). Future callers that put non-rename\n * mappings in must preserve the same invariant.\n */\nfunction resolve<T>(p: Place<T>, remap: Map<string, Place<unknown>>): Place<T> {\n const replaced = remap.get(p.name);\n return replaced !== undefined ? (replaced as Place<T>) : p;\n}\n\n// ============================================================\n// Channel composition: transition merge (MOD-021)\n// ============================================================\n\n/**\n * Merges a caller-side transition with an instance-side (renamed) channel\n * transition into a single {@link Transition} per **MOD-021**.\n *\n * ## Merge semantics\n *\n * - **Identity / name** — caller-wins. The merged transition's name is\n * `mergedName` (typically `caller.name`), so the merged transition remains\n * discoverable from caller-side code paths.\n * - **Arcs** — input/inhibitor/read/reset arcs are unioned: caller-side first,\n * then instance-side. Same-place input arcs are reconciled per MOD-021\n * rules (a)-(d) via {@link normalizeInputArcs} (additive where summable,\n * rejected otherwise); identical inhibitor/read/reset arcs collapse by\n * structural key.\n * - **Output spec** — if both sides carry an output spec, they are wrapped\n * under a single new outer `OutAnd(caller, instance)` so both sides' outputs\n * fire on a successful merged firing. If only one side has an output spec,\n * that one wins. If neither side has one, the merged transition has none.\n * `OutAnd` permits heterogeneous children (recursive trees), so wrapping a\n * possibly-`OutAnd` child under a new outer `OutAnd` is structurally legal.\n * - **Timing** — see {@link mergeTimings}. Caller wins when one side is\n * `Immediate`; equal non-`Immediate` timings collapse; conflicting\n * non-`Immediate` timings throw.\n * - **Priority** — see {@link pickPriority}. Caller-side wins (policy, not a\n * bug).\n * - **Action** — see {@link composeActions}. Sequential composition: caller-\n * side action runs first, then on its completion the instance-side action\n * runs against the same {@link import('../transition-context.js').TransitionContext}.\n * The runtime sees one transition firing per [CORE-021] / [EXEC-001].\n *\n * @throws when timings conflict or same-place input arcs have no additive\n * merge (per [MOD-021]) — the message names the channel and both\n * conflicting values so users can resolve it explicitly.\n */\nexport function mergeTransitions(\n caller: Transition,\n instance: Transition,\n mergedName: string,\n): Transition {\n if (mergedName === undefined || mergedName === null || mergedName.length === 0) {\n throw new Error('mergeTransitions: mergedName must be a non-empty string');\n }\n\n // Resolve timing / match / alias first so any conflict short-circuits before\n // building. The ν-net match and MOD-031 alias are carried as-is: both sides\n // already reference final host places at merge time (upstream substitutePlaces\n // remapped them, match included), so no further remap here.\n const mergedTiming = mergeTimings(caller.timing, instance.timing, mergedName);\n const mergedPriority = pickPriority(caller.priority, instance.priority);\n const mergedAction = composeActions(caller.action, instance.action);\n const mergedMatch = mergeMatchSpecs(caller.matchSpec, instance.matchSpec, mergedName);\n const mergedAlias = mergePlaceAlias(caller.placeAlias, instance.placeAlias, mergedName);\n\n const builder = Transition.builder(mergedName)\n .timing(mergedTiming)\n .priority(mergedPriority);\n if (mergedAction !== undefined) {\n builder.action(mergedAction);\n }\n\n // MOD-021 rule (d): different arc-kind sets on one place across the two\n // sides cannot be merged (identical sets pair up under rules (a)/(b)).\n rejectCrossSideKindConflicts(caller, instance, mergedName);\n\n // Inputs: union caller-first, then instance; same-place collisions merge\n // additively or reject per MOD-021 rules (a)-(d).\n const unionedInputs = normalizeInputArcs(\n [...caller.inputSpecs, ...instance.inputSpecs],\n () => `Channel composition '${mergedName}'`,\n );\n if (unionedInputs.length > 0) {\n builder.inputs(...unionedInputs);\n }\n\n // Outputs: wrap both sides under OutAnd; one-sided wins; none -> none.\n const mergedOutput = mergeOutputs(caller.outputSpec, instance.outputSpec);\n if (mergedOutput !== null) {\n builder.outputs(mergedOutput);\n }\n\n // Inhibitors / reads / resets: arc-record union (caller first, then instance).\n for (const inh of unionArcs<ArcInhibitor>(\n caller.inhibitors,\n instance.inhibitors,\n keyOfInhibitor,\n )) {\n builder.inhibitor(inh.place);\n }\n for (const rd of unionArcs<ArcRead>(caller.reads, instance.reads, keyOfRead)) {\n builder.read(rd.place);\n }\n for (const rs of unionArcs<ArcReset>(caller.resets, instance.resets, keyOfReset)) {\n builder.reset(rs.place);\n }\n\n // Apply the ν-net match (NU-060) and the MOD-031 declared→actual place map\n // (both resolved above, before any building, so a conflict on either\n // short-circuits with no wasted arc-union work).\n if (mergedMatch !== null) {\n builder.match(mergedMatch);\n }\n if (mergedAlias.size > 0) {\n builder.placeAlias(mergedAlias);\n }\n\n return builder.build();\n}\n\n/**\n * Carries the ν-net join correlation ({@link MatchSpec}) through a channel merge\n * per **NU-060**. One-sided → that side's match survives; both-null → none; both\n * non-null → the merge is rejected, because two independent name correlations\n * cannot be silently fused into one transition and NU-060 forbids dropping a\n * match. The surviving match is returned as-is: both transitions already\n * reference final host places at merge time, so no place remap is applied here\n * (unlike {@link rebuildWithName}).\n */\nfunction mergeMatchSpecs(\n caller: MatchSpec | null,\n instance: MatchSpec | null,\n channelName: string,\n): MatchSpec | null {\n if (caller === null) return instance;\n if (instance === null) return caller;\n throw new Error(\n `Channel composition '${channelName}': both the caller-side and instance-side ` +\n `transition carry a ν-net match — refusing to fuse two independent correlations ` +\n `into one transition (NU-060). Resolve explicitly by keeping the match on a single side.`,\n );\n}\n\n/**\n * Unions the two sides' MOD-031 declared→actual place correspondences for a\n * channel merge. Both actions run within the single merged firing, so each\n * side's declared-place resolution must survive. Disjoint keys union; an entry\n * present on both sides with the same actual collapses; a genuine conflict (same\n * declared place bound to two different actual places, compared by place name)\n * is rejected naming the declared place.\n */\nfunction mergePlaceAlias(\n caller: ReadonlyMap<string, Place<any>>,\n instance: ReadonlyMap<string, Place<any>>,\n channelName: string,\n): ReadonlyMap<string, Place<any>> {\n if (caller.size === 0) return instance;\n if (instance.size === 0) return caller;\n const merged = new Map<string, Place<any>>(caller);\n for (const [declared, actual] of instance) {\n const existing = merged.get(declared);\n if (existing !== undefined && existing.name !== actual.name) {\n throw new Error(\n `Channel composition '${channelName}': conflicting declared→actual place alias ` +\n `for declared place '${declared}' — caller-side maps to '${existing.name}', ` +\n `instance-side to '${actual.name}' (MOD-031). Resolve explicitly.`,\n );\n }\n merged.set(declared, actual);\n }\n return merged;\n}\n\n/**\n * Merges two timings per **MOD-021**:\n *\n * - Both `Immediate` -> `Immediate`.\n * - One `Immediate` -> the other side wins.\n * - Both non-`Immediate` and equal (by structural inspection of the timing\n * variant fields) -> that value collapses.\n * - Otherwise the conflict is rejected with an `Error` naming the channel\n * and both timings — the user must resolve it explicitly.\n */\nexport function mergeTimings(caller: Timing, instance: Timing, channelName: string): Timing {\n if (caller.type === 'immediate' && instance.type === 'immediate') {\n return { type: 'immediate' };\n }\n if (caller.type === 'immediate') return instance;\n if (instance.type === 'immediate') return caller;\n if (timingsEqual(caller, instance)) return caller;\n throw new Error(\n `Channel composition '${channelName}': conflicting non-Immediate timings — ` +\n `caller-side ${describeTiming(caller)} vs instance-side ${describeTiming(instance)}. ` +\n `Resolve explicitly by aligning the timings on either side (MOD-021).`,\n );\n}\n\n/**\n * Caller-side priority wins per **MOD-021**. Documented as policy: the\n * instance-side priority is ignored, not blended.\n */\nexport function pickPriority(callerPriority: number, _instancePriority: number): number {\n return callerPriority;\n}\n\n/**\n * Composes two transition actions sequentially: the caller-side action runs\n * first, then on its resolution the instance-side action runs against the same\n * {@link import('../transition-context.js').TransitionContext}. The combined\n * action surfaces a single `Promise<void>` so the executor sees one\n * transition firing per [CORE-021] / [EXEC-001].\n *\n * Null / passthrough handling:\n * - If both sides are `undefined` or both are `passthrough`, returns\n * `undefined` so {@link mergeTransitions} leaves the builder's default\n * passthrough action in place.\n * - If exactly one side is `undefined` / passthrough, the other side is\n * returned by reference (no extra wrapping).\n * - Otherwise returns a fresh sequential composition.\n *\n * Note: the production {@link Transition.builder} defaults action to\n * {@link import('../transition-action.js').passthrough}, so the `undefined`\n * branches are defensive — they exist so this helper is robust if upstream\n * surfaces a literal `undefined` action.\n */\nexport function composeActions(\n caller: TransitionAction | undefined,\n instance: TransitionAction | undefined,\n): TransitionAction | undefined {\n const callerIsPassthrough = caller === undefined || isPassthrough(caller);\n const instanceIsPassthrough = instance === undefined || isPassthrough(instance);\n\n if (callerIsPassthrough && instanceIsPassthrough) return undefined;\n if (callerIsPassthrough) return instance;\n if (instanceIsPassthrough) return caller;\n return async (ctx) => {\n await caller!(ctx);\n await instance!(ctx);\n };\n}\n\n/**\n * Combines two output specs per the merge contract: if both are present,\n * wrap them under a single {@link import('../out.js').OutAnd}; otherwise\n * return the non-null side (or `null` if both are missing).\n *\n * Exported (via the surrounding module's re-export surface) for unit testing\n * and for parity with the Java internal helper.\n */\nexport function mergeOutputs(caller: Out | null, instance: Out | null): Out | null {\n if (caller === null && instance === null) return null;\n if (caller === null) return instance;\n if (instance === null) return caller;\n return and(caller, instance);\n}\n\n/**\n * Returns the union of two arc lists, caller-first then instance, with\n * duplicates removed by structural key. Order is preserved within each\n * source list. Used for input, inhibitor, read, and reset arcs.\n *\n * Implementation: `Map<string, A>` preserves insertion order and dedupes by\n * the supplied key function. TypeScript arc records are POJOs — there is no\n * built-in structural equality, so callers must supply a key derived from\n * the discriminating fields (kind + place name + cardinality where\n * applicable).\n */\nexport function unionArcs<A>(\n caller: readonly A[],\n instance: readonly A[],\n keyOf: (arc: A) => string,\n): A[] {\n if (caller.length === 0 && instance.length === 0) return [];\n // Pre-size for V8 hidden-class stability; Map preserves insertion order\n // and dedupes by string key, mirroring Java's LinkedHashSet semantics.\n const seen = new Map<string, A>();\n for (let i = 0; i < caller.length; i++) {\n const arc = caller[i]!;\n const key = keyOf(arc);\n if (!seen.has(key)) seen.set(key, arc);\n }\n for (let i = 0; i < instance.length; i++) {\n const arc = instance[i]!;\n const key = keyOf(arc);\n if (!seen.has(key)) seen.set(key, arc);\n }\n const result = new Array<A>(seen.size);\n let i = 0;\n for (const arc of seen.values()) result[i++] = arc;\n return result;\n}\n\n// ============================================================\n// Internal helpers (timings, arc keys, action introspection)\n// ============================================================\n\n/**\n * Structural equality for two non-`Immediate` timings. Used by\n * {@link mergeTimings} to collapse equal timings into a single value\n * (mirrors Java's `record.equals`).\n */\nfunction timingsEqual(a: Timing, b: Timing): boolean {\n if (a.type !== b.type) return false;\n switch (a.type) {\n case 'immediate':\n return true;\n case 'deadline':\n return a.byMs === (b as typeof a).byMs;\n case 'delayed':\n return a.afterMs === (b as typeof a).afterMs;\n case 'window': {\n const w = b as typeof a;\n return a.earliestMs === w.earliestMs && a.latestMs === w.latestMs;\n }\n case 'exact':\n return a.atMs === (b as typeof a).atMs;\n }\n}\n\n/** Human-readable timing description for the conflict-diagnostic message. */\nfunction describeTiming(t: Timing): string {\n switch (t.type) {\n case 'immediate':\n return 'Immediate';\n case 'deadline':\n return `Deadline(byMs=${t.byMs})`;\n case 'delayed':\n return `Delayed(afterMs=${t.afterMs})`;\n case 'window':\n return `Window(earliestMs=${t.earliestMs}, latestMs=${t.latestMs})`;\n case 'exact':\n return `Exact(atMs=${t.atMs})`;\n }\n}\n\nfunction keyOfInhibitor(arc: ArcInhibitor): string {\n return `inh|${arc.place.name}`;\n}\nfunction keyOfRead(arc: ArcRead): string {\n return `read|${arc.place.name}`;\n}\nfunction keyOfReset(arc: ArcReset): string {\n return `reset|${arc.place.name}`;\n}\n\n// ============================================================\n// Input-arc normalization at composition seams (MOD-021 (a)-(d))\n// ============================================================\n\n/**\n * Normalizes an input-arc list per **MOD-021**'s arc-deduplication rules:\n * arcs on distinct places pass through in order; same-place arcs merge per\n * {@link mergeInPair} (additive where summable, rejected otherwise).\n *\n * `seamOf(placeName)` supplies the diagnostic prefix naming the seam that\n * caused the collision (fusion set per [MOD-061], or channel composition).\n * Collision-free lists are returned by reference — no rebuild.\n */\nexport function normalizeInputArcs(\n arcs: readonly In[],\n seamOf: (placeName: string) => string,\n): readonly In[] {\n if (arcs.length < 2) return arcs;\n const byPlace = new Map<string, In>();\n let collided = false;\n for (let i = 0; i < arcs.length; i++) {\n const arc = arcs[i]!;\n const name = arc.place.name;\n const prior = byPlace.get(name);\n if (prior === undefined) {\n byPlace.set(name, arc);\n } else {\n collided = true;\n byPlace.set(name, mergeInPair(prior, arc, seamOf(name)));\n }\n }\n if (!collided) return arcs;\n const result = new Array<In>(byPlace.size);\n let i = 0;\n for (const arc of byPlace.values()) result[i++] = arc;\n return result;\n}\n\n/**\n * Merges two same-place input arcs per the canonical [MOD-021] merge table:\n * `one`/`exactly` weights sum, `atLeast` pairs keep the stricter minimum,\n * `all`+`all` collapses. Any other pairing is rejected per rule (c).\n */\nfunction mergeInPair(a: In, b: In, seam: string): In {\n if (a.type === 'all' && b.type === 'all') return a;\n if (a.type === 'at-least' && b.type === 'at-least') {\n return a.minimum >= b.minimum ? a : b;\n }\n const countA = summableCount(a);\n const countB = summableCount(b);\n if (countA !== -1 && countB !== -1) {\n return exactly(countA + countB, a.place);\n }\n throw new Error(\n `${seam}: input arcs ${describeIn(a)} and ${describeIn(b)} collide on place ` +\n `'${a.place.name}' and have no additive merge (MOD-021 rule (c)). Use a ` +\n `single arc with exactly(n) / atLeast(n).`,\n );\n}\n\n/** Summable consumption weight of `one`/`exactly`; -1 for `all`/`at-least`. */\nfunction summableCount(arc: In): number {\n switch (arc.type) {\n case 'one':\n return 1;\n case 'exactly':\n return arc.count;\n default:\n return -1;\n }\n}\n\n/**\n * Cardinality-only rendering for the collision diagnostic — the place name\n * already appears once in the sentence.\n */\nfunction describeIn(arc: In): string {\n switch (arc.type) {\n case 'one':\n return 'one()';\n case 'exactly':\n return `exactly(${arc.count})`;\n case 'all':\n return 'all()';\n case 'at-least':\n return `atLeast(${arc.minimum})`;\n }\n}\n\n/**\n * Rejects a channel merge where the two sides put different arc-kind sets on\n * the same place — e.g. the caller consumes `P` while the instance resets `P`\n * (MOD-021 rule (d)). Identical kind sets pair up under rules (a)/(b), and\n * same-side kind mixes (read+reset on one place, EXEC-013) stay authorable.\n * Output specs are excluded: caller-consumes / instance-produces on one place\n * is the normal channel wiring pattern (outputs union via `OutAnd`).\n */\nfunction rejectCrossSideKindConflicts(\n caller: Transition,\n instance: Transition,\n mergedName: string,\n): void {\n const callerKinds = arcKindsByPlace(caller);\n if (callerKinds.size === 0) return;\n for (const [place, instanceSet] of arcKindsByPlace(instance)) {\n const callerSet = callerKinds.get(place);\n if (callerSet !== undefined && !sameKindSet(callerSet, instanceSet)) {\n throw new Error(\n `Channel composition '${mergedName}': conflicting arc kinds on place ` +\n `'${place}' — caller-side ${describeKinds(callerSet)} vs instance-side ` +\n `${describeKinds(instanceSet)}. Different arc types on one place ` +\n `cannot be merged (MOD-021 rule (d)). Resolve explicitly.`,\n );\n }\n }\n}\n\n/** Groups a transition's input/inhibitor/read/reset arcs into place name → kind set. */\nfunction arcKindsByPlace(t: Transition): Map<string, Set<string>> {\n const kinds = new Map<string, Set<string>>();\n const add = (name: string, kind: string): void => {\n let set = kinds.get(name);\n if (set === undefined) {\n set = new Set();\n kinds.set(name, set);\n }\n set.add(kind);\n };\n for (const s of t.inputSpecs) add(s.place.name, 'input');\n for (const a of t.inhibitors) add(a.place.name, 'inhibitor');\n for (const a of t.reads) add(a.place.name, 'read');\n for (const a of t.resets) add(a.place.name, 'reset');\n return kinds;\n}\n\n/** Renders an arc-kind set as `[input, read]` — sorted, so all three languages match. */\nfunction describeKinds(kinds: ReadonlySet<string>): string {\n return `[${[...kinds].sort().join(', ')}]`;\n}\n\nfunction sameKindSet(a: ReadonlySet<string>, b: ReadonlySet<string>): boolean {\n if (a.size !== b.size) return false;\n for (const k of a) if (!b.has(k)) return false;\n return true;\n}\n\n// ============================================================\n// Fusion: bulk place substitution across a transition set (MOD-061)\n// ============================================================\n\n/**\n * Applies a fusion remap to every transition in `transitions`, substituting\n * non-canonical → canonical place references in each transition's arcs.\n * Returns a fresh insertion-ordered `Set<Transition>`; the input collection\n * is not mutated.\n *\n * This is the loop wrapper around {@link rebuildWithName}; it exists so\n * callers — notably `PetriNetBuilder.build()` during fusion resolution per\n * **MOD-061** — do not duplicate the per-transition dispatch. Transitions\n * whose arcs do not reference any key of `fusionMap` pass through unchanged\n * in shape but are still rebuilt (a fresh `Transition` instance); callers that\n * care about identity preservation for un-affected transitions should instead\n * skip the rewrite entirely when `fusionMap.size === 0`.\n *\n * The remap is keyed by **non-canonical place name** → **canonical place**\n * (matching the `Map<string, Place<unknown>>` key convention used throughout\n * this module — TypeScript Place identity is name-based per\n * `runtime/compiled-net.ts`).\n *\n * When the substitution makes two input arcs of one transition collide on the\n * canonical place, they are reconciled per [MOD-021] via\n * {@link normalizeInputArcs} (additive where summable, rejected otherwise) so\n * a fused net still compiles under the CORE-030 duplicate-input rejection.\n *\n * @param transitions the transitions to rewrite (non-null, may be empty)\n * @param fusionMap non-canonical name → canonical place remap (non-null)\n * @param seamOf canonical place name → diagnostic seam prefix (the\n * owning fusion set) for collision rejections\n * @returns a fresh, insertion-ordered set of rewritten transitions\n */\nexport function applyFusion(\n transitions: Iterable<Transition>,\n fusionMap: Map<string, Place<unknown>>,\n seamOf: (canonicalPlaceName: string) => string,\n): Set<Transition> {\n // Normalization rides the rebuild rather than rebuilding a second time;\n // normalizeInputArcs returns collision-free lists by reference.\n const normalizeInputs = (inputs: readonly In[]): readonly In[] =>\n normalizeInputArcs(inputs, seamOf);\n const rewritten = new Set<Transition>();\n for (const t of transitions) {\n // Only transitions the fusion actually rewrites get the merge pass: a\n // pre-existing duplicate on an untouched place stays a CORE-030 compile\n // rejection rather than being silently summed away.\n rewritten.add(rebuildWithName(t, t.name, fusionMap,\n fusionTouchesInputs(t, fusionMap) ? normalizeInputs : undefined));\n }\n return rewritten;\n}\n\n/** True when any input arc of `t` references a fused (non-canonical) place. */\nfunction fusionTouchesInputs(t: Transition, fusionMap: Map<string, Place<unknown>>): boolean {\n if (fusionMap.size === 0) return false;\n for (let i = 0; i < t.inputSpecs.length; i++) {\n if (fusionMap.has(t.inputSpecs[i]!.place.name)) return true;\n }\n return false;\n}\n","import type { PetriNet } from '../core/petri-net.js';\nimport type { Token } from '../core/token.js';\nimport type { SmtProperty } from './smt-property.js';\nimport type { SmtVerificationResult } from './smt-verification-result.js';\nimport { isProven, isViolated } from './smt-verification-result.js';\n\n/**\n * Token-source supplier used by the verification harness to seed a synthetic\n * environment place for a given input port, per\n * `spec/11-modular-composition.md` requirement **MOD-051** AC #3.\n *\n * The supplier's presence is what bounds the input behavior in the synthetic\n * harness; it is invoked once at synthetic-net construction time so that\n * supplier-side errors surface eagerly, not at verification time. The\n * concrete token value is not consumed by the verifier itself (which operates\n * on the integer marking projection per [VER-004]); it merely materialises\n * the seed token type and surfaces user errors.\n */\nexport type TokenSupplier = () => Token<unknown>;\n\n/**\n * Harness driving local property verification of a subnet definition per\n * `spec/11-modular-composition.md` requirement **MOD-051**.\n *\n * The harness is a value carrier consumed by\n * {@link import('../core/subnet-def.js').SubnetDef.verify}. It supplies the\n * three pieces of information needed to wrap a subnet in a synthetic\n * enclosing net for verification:\n *\n * 1. A {@link params} value of the subnet's parameter type.\n * 2. A {@link portInputGenerators} map from **input port name** (original /\n * pre-prefix) to a {@link TokenSupplier}. The supplier's presence is what\n * bounds the input behavior in the synthetic harness; the supplier is\n * invoked at synthetic-net construction time when the harness wires up the\n * {@link import('../core/place.js').EnvironmentPlace} associated with the\n * port.\n * 3. A set of {@link properties} to check (per [VER-002] /\n * {@link SmtProperty}).\n *\n * Each entry in {@link portInputGenerators} MUST correspond to an input or\n * in-out port declared on the subnet's interface. Output-only ports never\n * appear in the generator map; instead, the harness wires them to a synthetic\n * observation place visible to the verifier.\n *\n * The map and property collection accept either the canonical\n * `Map`/`ReadonlySet` form or a plain `Record`/`readonly array` for ergonomic\n * inline construction; `SubnetDef.verify` normalises both.\n *\n * @typeParam P parameter type carried through to the subnet under test\n */\nexport interface VerificationHarness<P = void> {\n /**\n * Parameter value supplied to\n * {@link import('../core/subnet-def.js').SubnetDef.instantiate} for the\n * system-under-test instance. Use `undefined` (or `null`) for `P = void`.\n */\n readonly params: P;\n\n /**\n * Map (or `Record`) from **input port name** to a {@link TokenSupplier} that\n * seeds the synthetic environment place for that port. Output-only ports\n * MUST NOT appear; in-out ports MUST appear (mirrors the Java harness).\n */\n readonly portInputGenerators:\n | ReadonlyMap<string, TokenSupplier>\n | Readonly<Record<string, TokenSupplier>>;\n\n /**\n * Safety properties to check on the synthetic enclosing net per\n * {@link SmtProperty}. An empty collection is permitted but yields an empty\n * {@link VerificationResult.perProperty}.\n */\n readonly properties: ReadonlySet<SmtProperty> | readonly SmtProperty[];\n\n}\n\n/**\n * Aggregated outcome of a\n * {@link import('../core/subnet-def.js').SubnetDef.verify} invocation per\n * `spec/11-modular-composition.md` requirement **MOD-051**.\n *\n * The verifier is invoked once per {@link SmtProperty} declared in the\n * harness; each invocation produces an {@link SmtVerificationResult}. This\n * record carries the per-property results plus the synthetic enclosing net\n * that was constructed for verification (useful for diagnostic output and\n * tooling to render the harness wiring).\n */\nexport interface VerificationResult {\n /**\n * The synthetic enclosing net assembled by `SubnetDef.verify(...)`: the\n * renamed body of the subnet under test, with each input port bound to a\n * synthetic environment place and each output port bound to a synthetic\n * observation place.\n */\n readonly syntheticNet: PetriNet;\n\n /**\n * Per-property verification results, in the iteration order of the\n * harness's {@link VerificationHarness.properties} collection.\n */\n readonly perProperty: ReadonlyMap<SmtProperty, SmtVerificationResult>;\n\n /**\n * Returns true when every property in the harness was proven safe.\n * An empty harness (no properties) returns `true` vacuously.\n */\n allProven(): boolean;\n\n /**\n * Returns true when at least one property was violated (counter-example\n * found).\n */\n anyViolated(): boolean;\n}\n\n/**\n * @internal Builds a {@link VerificationResult} value from the per-property\n * map and synthetic net. The resulting object is structurally immutable; the\n * `perProperty` map is wrapped in a defensive copy so callers cannot mutate\n * the verifier's view through retained map references.\n */\nexport function buildVerificationResult(\n syntheticNet: PetriNet,\n perProperty: ReadonlyMap<SmtProperty, SmtVerificationResult>,\n): VerificationResult {\n const frozen = new Map(perProperty);\n return {\n syntheticNet,\n perProperty: frozen,\n allProven(): boolean {\n for (const r of frozen.values()) {\n if (!isProven(r)) return false;\n }\n return true;\n },\n anyViolated(): boolean {\n for (const r of frozen.values()) {\n if (isViolated(r)) return true;\n }\n return false;\n },\n };\n}\n\n/**\n * @internal Normalises {@link VerificationHarness.portInputGenerators} to a\n * canonical `Map<string, TokenSupplier>` regardless of whether the caller\n * supplied a `Map` or a `Record`. Iteration order is preserved.\n */\nexport function normaliseGenerators(\n generators: VerificationHarness<unknown>['portInputGenerators'],\n): Map<string, TokenSupplier> {\n if (generators instanceof Map) return new Map(generators);\n return new Map(Object.entries(generators));\n}\n\n/**\n * @internal Normalises {@link VerificationHarness.properties} to an array of\n * {@link SmtProperty} regardless of whether the caller supplied a `Set` or an\n * array. Iteration order is preserved.\n */\nexport function normaliseProperties(\n properties: VerificationHarness<unknown>['properties'],\n): SmtProperty[] {\n if (Array.isArray(properties)) return [...properties];\n return [...(properties as ReadonlySet<SmtProperty>)];\n}\n","import type { PetriNet } from './petri-net.js';\nimport type { Transition } from './transition.js';\nimport type { Place } from './place.js';\nimport { environmentPlace, place as makePlace, type EnvironmentPlace } from './place.js';\nimport { Interface, type Channel, type Port } from './interface.js';\nimport type { Instance } from './instance.js';\nimport { __createInstance } from './instance.js';\nimport { PetriNet as PetriNetClass } from './petri-net.js';\nimport { renameNet } from './internal/subnet-rewriter.js';\nimport { SmtVerifier } from '../verification/smt-verifier.js';\nimport { alwaysAvailable } from '../verification/analysis/environment-analysis-mode.js';\nimport type { EnvironmentAnalysisMode } from '../verification/analysis/environment-analysis-mode.js';\nimport type { SmtProperty } from '../verification/smt-property.js';\nimport type { SmtVerificationResult } from '../verification/smt-verification-result.js';\nimport {\n buildVerificationResult,\n normaliseGenerators,\n normaliseProperties,\n type VerificationHarness,\n type VerificationResult,\n type TokenSupplier,\n} from '../verification/verification-harness.js';\nimport { requireOutputProducingActions } from './internal/output-action-check.js';\n\n// Re-export the real harness types from the verification module for callers\n// that import from `core/subnet-def.js`. The previous task-#10 placeholder\n// shape is removed; the surface is now backed by `verification/verification-harness.ts`.\nexport type { VerificationHarness, VerificationResult, TokenSupplier };\n\n/** @internal Symbol key restricting construction to {@link SubnetDef.builder} and {@link SubnetDef.fromNet}. */\nconst SUBNET_DEF_KEY = Symbol('SubnetDef.internal');\n\n/**\n * An open Petri net fragment paired with a declared {@link Interface}, per\n * `spec/11-modular-composition.md` requirement **MOD-001**.\n *\n * A subnet definition is the reusable unit of composition. It carries:\n * - A {@link name} (used as the originating-def label in `SubnetInstance` per [MOD-041]);\n * - A {@link body} — a structurally complete `PetriNet` per [CORE-040];\n * - An {@link iface} — the set of exposed ports and channels per [MOD-003] / [MOD-005].\n *\n * `SubnetDef` is the open variant of the {@link Subnet} discriminated union\n * defined in `subnet.ts` per **MOD-002**.\n *\n * The {@link SubnetDef.fromNet} retrofit factory per **MOD-014** wraps an\n * existing closed `PetriNet` plus an `Interface` into an unparameterised\n * `SubnetDef<void>`, applying the same per-element validation as the\n * builder's `build()`.\n *\n * @typeParam P parameter type carried through to `Instance.params`\n * (use `void` for unparameterised subnets)\n */\nexport class SubnetDef<P = void> {\n readonly name: string;\n readonly body: PetriNet;\n readonly iface: Interface;\n\n /** @internal Use {@link SubnetDef.builder} or {@link SubnetDef.fromNet} to create instances. */\n constructor(key: symbol, name: string, body: PetriNet, iface: Interface) {\n if (key !== SUBNET_DEF_KEY) {\n throw new Error('Use SubnetDef.builder() or SubnetDef.fromNet() to create instances');\n }\n this.name = name;\n this.body = body;\n this.iface = iface;\n }\n\n /**\n * Produces a renamed module instance per **MOD-010**, **MOD-011**, **MOD-012**,\n * and **MOD-030**.\n *\n * The rename pass walks every place and transition of the body net,\n * substituting each name with `prefix + \"/\" + originalName`, and rebuilds\n * every arc with rewritten place references. Transition timing, priority,\n * and action are carried through by reference (action sharing per\n * [MOD-030]). The renamed body is itself a structurally valid `PetriNet`\n * per [CORE-040]; per-instance state isolation per [MOD-012] is a\n * structural consequence of distinct prefixed names.\n *\n * ## Prefix validation\n *\n * The `\"/\"` character is reserved as the prefix separator (per [MOD-010]).\n * User-supplied prefixes MUST NOT contain `\"/\"`; nested instantiation is\n * performed by the future `PetriNetBuilder.compose(...)` mechanism (per\n * [MOD-013]). A prefix containing `\"/\"` raises an `Error`.\n *\n * @param prefix the rename prefix (non-empty, must not contain `\"/\"`)\n * @param params the parameter value carried through to `Instance.params`\n * (may be omitted when `P` is `void`)\n * @throws when `prefix` is empty or contains `\"/\"`\n */\n instantiate(prefix: string, params?: P): Instance<P> {\n validatePrefix(prefix);\n\n // Allocate the two remap maps. The rewriter fills them as side effects so\n // we can resolve interface place/transition references afterward. Maps\n // are keyed by ORIGINAL name strings (TypeScript Place identity is\n // name-based per `runtime/compiled-net.ts`).\n const placeRemap = new Map<string, Place<unknown>>();\n const transitionRemap = new Map<string, Transition>();\n\n const renamedBody = renameNet(this.body, prefix, placeRemap, transitionRemap);\n\n // Resolve port handles: original-port-name -> renamed body place.\n const portHandles = new Map<string, Place<unknown>>();\n for (const port of this.iface.ports.values()) {\n const renamed = placeRemap.get(port.place.name);\n if (renamed === undefined) {\n // Defensive: should be impossible because MOD-006 validation at\n // SubnetDef.builder.build() guarantees port.place is in the body.\n throw new Error(\n `Port '${port.name}' references place '${port.place.name}' that was not found ` +\n `in the renamed body. This indicates a SubnetDef invariant violation.`,\n );\n }\n portHandles.set(port.name, renamed);\n }\n\n // Resolve channel handles: original-channel-name -> renamed body transition.\n const channelHandles = new Map<string, Transition>();\n for (const channel of this.iface.channels.values()) {\n const renamed = transitionRemap.get(channel.transition.name);\n if (renamed === undefined) {\n throw new Error(\n `Channel '${channel.name}' references transition '${channel.transition.name}' that was not found ` +\n `in the renamed body. This indicates a SubnetDef invariant violation.`,\n );\n }\n channelHandles.set(channel.name, renamed);\n }\n\n return __createInstance<P>(\n prefix,\n this,\n renamedBody,\n portHandles,\n channelHandles,\n params as P,\n );\n }\n\n /**\n * Verifies safety properties of this subnet definition **in isolation** per\n * **MOD-051**, by wrapping it in a synthetic enclosing net where each input\n * port is fed by an {@link EnvironmentPlace} (token-source per the harness\n * generator) and each output port is observed via a synthetic place. The\n * standard {@link SmtVerifier} (per [MOD-050]) is invoked once per property\n * declared in the harness; the resulting per-property outcomes are\n * aggregated into a {@link VerificationResult}.\n *\n * ## Synthetic-net construction\n *\n * The synthetic enclosing net is built by:\n * 1. Instantiating this `SubnetDef` with the prefix `\"sut\"` (system-under-test)\n * and `harness.params`.\n * 2. For each input or in-out port on the interface, looking up the\n * harness generator by port name, allocating a synthetic\n * {@link Place}`<unknown>` of the same conceptual token type as the\n * port, wrapping it in an {@link EnvironmentPlace}, and binding the\n * port to that synthetic place via\n * {@link import('./petri-net.js').PetriNetBuilder.compose}. The supplier\n * is invoked once at construction time to materialize the seed token —\n * its presence is what bounds the input behavior under analysis. **If\n * the harness map is missing a generator for a required input or in-out\n * port, an `Error` is thrown.**\n * 3. For each output or in-out port, allocating a synthetic observation\n * {@link Place}`<unknown>` and binding the port to it via the same\n * `compose(...)` call. The verifier inspects this place's reachability\n * / marking through the standard property APIs ({@link SmtProperty}).\n * 4. Building the resulting flat {@link PetriNet} per [MOD-023] (the\n * verifier is composition-unaware per [MOD-050]).\n *\n * ## Per-property invocation\n *\n * Each {@link SmtProperty} in the harness is verified independently against\n * the same synthetic net. The synthetic environment places are passed\n * through to the verifier so that places driven by the harness generators\n * are treated under the verifier's environment-analysis semantics rather\n * than as ordinary sink places.\n *\n * @param harness the verification harness — supplies parameters, input-port\n * token generators, and the property set\n * @returns a {@link VerificationResult} aggregating per-property\n * {@link SmtVerificationResult}s\n * @throws when an input or in-out port is missing a harness generator\n */\n async verify(\n harness: VerificationHarness<P>,\n /**\n * How injection into the synthetic environment places is modeled (VER-006,\n * MOD-051 AC3).\n *\n * The synthetic net has environment places by construction, so this decides what a\n * verdict means. The default over-approximates: a `proven` under\n * `alwaysAvailable()` holds for any environment. Pass `bounded(k)` to prove a\n * property that holds only when the environment injects at most `k` tokens.\n * `ignore()` is accepted but cannot yield `proven` — VER-006 refuses to certify a\n * proof that holds only because injection was never modeled.\n */\n environmentMode: EnvironmentAnalysisMode = alwaysAvailable(),\n ): Promise<VerificationResult> {\n if (harness === null || harness === undefined) {\n throw new Error('SubnetDef.verify: harness must not be null/undefined');\n }\n\n // Step 1: instantiate this SubnetDef under the \"sut\" prefix. Uses an\n // underscore in the synthetic enclosing net's name to avoid colliding\n // with the \"/\" prefix separator (matches Java).\n const sut = this.instantiate('sut', harness.params);\n\n // Normalise the harness's generator map / property collection up front so\n // we can check membership and iterate deterministically below.\n const generators = normaliseGenerators(harness.portInputGenerators);\n const properties = normaliseProperties(harness.properties);\n\n // Step 2: allocate synthetic harness places per port direction. Track\n // the environment places (one per input/inout port) for the SmtVerifier\n // so the verifier knows to treat their underlying places as boundary\n // places rather than ordinary internals.\n const envPlaces: EnvironmentPlace<unknown>[] = [];\n const portMappings = new Map<string, Place<unknown>>();\n\n for (const port of this.iface.ports.values()) {\n const portName = port.name;\n\n switch (port.direction) {\n case 'input': {\n const generator = generators.get(portName);\n if (generator === undefined) {\n throw new Error(\n `verify: harness is missing an input generator for port '${portName}' ` +\n `on subnet '${this.name}' (MOD-051)`,\n );\n }\n // Touch the supplier to surface user-supplied errors at synthetic-\n // net construction time rather than at verification time. Mirrors\n // Java's Objects.requireNonNull(generator.get(), ...).\n const seed = generator();\n if (seed === null || seed === undefined) {\n throw new Error(\n `verify: input generator for port '${portName}' on subnet ` +\n `'${this.name}' produced null/undefined`,\n );\n }\n const synth = makePlace<unknown>(`harness_in_${portName}`);\n envPlaces.push(environmentPlace<unknown>(synth.name));\n portMappings.set(portName, synth);\n break;\n }\n case 'output': {\n const synth = makePlace<unknown>(`harness_out_${portName}`);\n portMappings.set(portName, synth);\n break;\n }\n case 'inout': {\n const generator = generators.get(portName);\n if (generator === undefined) {\n throw new Error(\n `verify: harness is missing an input generator for in-out port ` +\n `'${portName}' on subnet '${this.name}' (MOD-051)`,\n );\n }\n const seed = generator();\n if (seed === null || seed === undefined) {\n throw new Error(\n `verify: input generator for in-out port '${portName}' on subnet ` +\n `'${this.name}' produced null/undefined`,\n );\n }\n const synth = makePlace<unknown>(`harness_io_${portName}`);\n envPlaces.push(environmentPlace<unknown>(synth.name));\n portMappings.set(portName, synth);\n break;\n }\n }\n }\n\n // Step 3: build the synthetic enclosing net. Channels declared on the\n // interface (but not bound here) flow through as ordinary renamed\n // transitions per MOD-021. The `verify_` prefix uses an underscore (not\n // `/`) so the enclosing-net name does not collide with the prefix\n // separator reserved by [MOD-010].\n const syntheticNet = PetriNetClass.builder('verify_' + this.name)\n .compose(sut as Instance<unknown>, portMappings)\n .build();\n\n // CORE-043, checked here rather than left to SmtVerifier so an empty property set\n // cannot skip it.\n requireOutputProducingActions(syntheticNet);\n\n // Step 4: invoke the SmtVerifier once per property and aggregate\n // results. Iteration order matches the harness's property collection\n // for deterministic per-property reporting.\n const perProperty = new Map<SmtProperty, SmtVerificationResult>();\n for (const property of properties) {\n // Set explicitly rather than inherited: the synthetic env places are the\n // harness's own, so how injection is modelled is the harness's call\n // ([MOD-051] AC3), not the verifier default's. Under ignore() [VER-006]\n // downgrades every proof about a net with env places to Unknown, so a\n // subnet with an input port could never be proven.\n const verifier = SmtVerifier.forNet(syntheticNet).property(property);\n if (envPlaces.length > 0) {\n verifier.environmentPlaces(...envPlaces);\n verifier.environmentMode(environmentMode);\n }\n const result = await verifier.verify();\n perProperty.set(property, result);\n }\n\n return buildVerificationResult(syntheticNet, perProperty);\n }\n\n // ============================================================\n // Static factories\n // ============================================================\n\n static builder<P = void>(name: string): SubnetDefBuilder<P> {\n return new SubnetDefBuilder<P>(name);\n }\n\n /**\n * Retrofit utility per **MOD-014**: wraps an existing closed {@link PetriNet}\n * plus an {@link Interface} into an unparameterised `SubnetDef<void>`.\n *\n * Validation per **MOD-014** / **MOD-006** is enforced before the result is\n * constructed:\n * - Every port's underlying `Place` must be present in `net.places`.\n * - Every channel's underlying `Transition` must be present in `net.transitions`.\n * - Port and channel name uniqueness is re-validated defensively (the\n * `Interface` builder already enforces this; hand-built `Interface`\n * values bypass that path).\n *\n * The resulting subnet definition is unparameterised (parameter type is `void`).\n *\n * @throws when a port place is not in `net.places`, a channel transition is\n * not in `net.transitions`, or port/channel names are not unique.\n */\n static fromNet(net: PetriNet, iface: Interface): SubnetDef<void> {\n const bodyPlaces = net.places;\n const bodyTransitions = net.transitions;\n\n // Re-validate port-name uniqueness (defence in depth — InterfaceBuilder\n // enforces it for the builder route, but a hand-built `Interface`\n // bypasses that path; SubnetDef.fromNet is the documented retrofit\n // entry point so we re-check here to keep failures crisp). Note: do NOT\n // use `Set#add`'s return value — `Set#add` returns the Set itself\n // (truthy) and cannot signal \"already present\"; check with `has` first.\n const seenPortNames = new Set<string>();\n for (const port of iface.ports.values()) {\n if (seenPortNames.has(port.name)) {\n throw new Error(\n `fromNet: duplicate port name '${port.name}' on interface for net '${net.name}' (MOD-006)`,\n );\n }\n seenPortNames.add(port.name);\n if (!bodyPlaces.has(port.place as Place<unknown>)) {\n throw new Error(\n `fromNet: port '${port.name}' references place '${port.place.name}' which is not in net '${net.name}' (MOD-014/MOD-006)`,\n );\n }\n }\n\n // Re-validate channel-name uniqueness and transition membership.\n const seenChannelNames = new Set<string>();\n for (const channel of iface.channels.values()) {\n if (seenChannelNames.has(channel.name)) {\n throw new Error(\n `fromNet: duplicate channel name '${channel.name}' on interface for net '${net.name}' (MOD-006)`,\n );\n }\n seenChannelNames.add(channel.name);\n if (!bodyTransitions.has(channel.transition)) {\n throw new Error(\n `fromNet: channel '${channel.name}' references transition '${channel.transition.name}' which is not in net '${net.name}' (MOD-014/MOD-006)`,\n );\n }\n }\n\n return new SubnetDef<void>(SUBNET_DEF_KEY, net.name, net, iface);\n }\n}\n\n/**\n * Fluent builder for {@link SubnetDef}.\n *\n * Validation per **MOD-006** is enforced at {@link build}:\n * - Every port's underlying place must be in the body net.\n * - Every channel's underlying transition must be in the body net.\n * - Port names must be unique within the port namespace.\n * - Channel names must be unique within the channel namespace.\n */\nexport class SubnetDefBuilder<P = void> {\n private readonly _name: string;\n private readonly _bodyBuilder: ReturnType<typeof PetriNetClass.builder>;\n private readonly _ports: Port<unknown>[] = [];\n private readonly _channels: Channel[] = [];\n\n constructor(name: string) {\n this._name = name;\n this._bodyBuilder = PetriNetClass.builder(name);\n }\n\n // -------- body construction (delegates to PetriNet.Builder) --------\n\n transition(transition: Transition): this {\n this._bodyBuilder.transition(transition);\n return this;\n }\n\n transitions(...transitions: Transition[]): this {\n this._bodyBuilder.transitions(...transitions);\n return this;\n }\n\n place<T>(place: Place<T>): this {\n this._bodyBuilder.place(place);\n return this;\n }\n\n // -------- interface declarations --------\n\n inputPort<T>(name: string, place: Place<T>): this {\n this._ports.push({ name, direction: 'input', place: place as Place<unknown> });\n return this;\n }\n\n outputPort<T>(name: string, place: Place<T>): this {\n this._ports.push({ name, direction: 'output', place: place as Place<unknown> });\n return this;\n }\n\n inoutPort<T>(name: string, place: Place<T>): this {\n this._ports.push({ name, direction: 'inout', place: place as Place<unknown> });\n return this;\n }\n\n channel(name: string, transition: Transition): this {\n this._channels.push({ name, transition });\n return this;\n }\n\n // -------- build & validate (MOD-006) --------\n\n build(): SubnetDef<P> {\n const built = this._bodyBuilder.build();\n const bodyPlaces = built.places;\n const bodyTransitions = built.transitions;\n\n // 1. Validate port-name uniqueness (MOD-006). Note: do NOT use\n // `Set#add`'s return value — it returns the Set itself (truthy) and\n // cannot signal \"already present\"; check with `has` first.\n const portNames = new Set<string>();\n for (const port of this._ports) {\n if (portNames.has(port.name)) {\n throw new Error(`Subnet '${this._name}': duplicate port name '${port.name}'`);\n }\n portNames.add(port.name);\n // 2. Validate port place membership (MOD-006).\n if (!bodyPlaces.has(port.place as Place<unknown>)) {\n throw new Error(\n `Subnet '${this._name}': port '${port.name}' references place '${port.place.name}' which is not in the body`,\n );\n }\n }\n\n // 3. Validate channel-name uniqueness and transition membership (MOD-006).\n const channelNames = new Set<string>();\n for (const channel of this._channels) {\n if (channelNames.has(channel.name)) {\n throw new Error(`Subnet '${this._name}': duplicate channel name '${channel.name}'`);\n }\n channelNames.add(channel.name);\n if (!bodyTransitions.has(channel.transition)) {\n throw new Error(\n `Subnet '${this._name}': channel '${channel.name}' references transition '${channel.transition.name}' which is not in the body`,\n );\n }\n }\n\n const ifaceBuilder = Interface.builder();\n ifaceBuilder.portsAll(this._ports);\n ifaceBuilder.channelsAll(this._channels);\n const iface = ifaceBuilder.build();\n\n return new SubnetDef<P>(SUBNET_DEF_KEY, this._name, built, iface);\n }\n}\n\n/**\n * @internal Validates the prefix supplied to {@link SubnetDef.instantiate}\n * per **MOD-010**:\n * - non-empty;\n * - no `\"/\"` (reserved as the prefix separator; nested instantiation is\n * performed by `PetriNetBuilder.compose(...)` per [MOD-013]).\n *\n * Throws an `Error` with a descriptive message on failure.\n */\nfunction validatePrefix(prefix: string): void {\n if (typeof prefix !== 'string' || prefix.length === 0) {\n throw new Error('SubnetDef.instantiate: prefix must be a non-empty string');\n }\n if (prefix.indexOf('/') >= 0) {\n throw new Error(\n `SubnetDef.instantiate: prefix must not contain '/' (reserved as the prefix ` +\n `separator per MOD-010); use compose(...) for nested instantiation. Got: '${prefix}'`,\n );\n }\n}\n","import type { Place } from './place.js';\nimport type { Transition } from './transition.js';\n\n/**\n * @internal Symbol key restricting construction to\n * {@link PetriNetBuilder.compose}. Bindings are produced by the host builder\n * and supplied to the caller's callback — direct construction is not part of\n * the public API.\n */\nconst COMPOSE_BINDINGS_KEY = Symbol('ComposeBindings.internal');\n\n/**\n * Typed binding builder for {@link PetriNetBuilder.compose}, per\n * `spec/11-modular-composition.md` requirements **MOD-020** (composition\n * operation) and **MOD-022** (type compatibility).\n *\n * `ComposeBindings` is a write-only collector: callers register port and\n * channel bindings against an instance's interface, and the host builder\n * consumes the recorded mappings as it merges the instance into the\n * enclosing net.\n *\n * ## Port bindings (MOD-020, MOD-022)\n *\n * {@link bindPort} merges an interface port with a caller-side place. The\n * port name is the **original** (pre-prefix) name declared in the subnet's\n * `Interface`; the caller place takes the port's slot in the resulting net.\n * Token-type compatibility is enforced at compile time only in TypeScript\n * (per [MOD-022]) — the typed `bindPort<T>` signature is the safety\n * mechanism. TypeScript erases generics at runtime, so a misuse via `as`\n * casts is structurally undetectable.\n *\n * ## Channel bindings (MOD-021)\n *\n * {@link bindChannel} records a synchronous channel binding: at compose time\n * the named instance-side interface transition is **merged** with the\n * supplied caller-side {@link Transition} into one transition in the\n * resulting flat net. Channel composition is implemented in task #13; until\n * then `compose(...)` raises an `Error` when any channel binding is present.\n *\n * ## Identity\n *\n * Instances are produced by {@link PetriNetBuilder.compose} and supplied to\n * the caller's callback. The constructor is symbol-guarded to prevent\n * direct construction.\n */\nexport class ComposeBindings {\n private readonly _portBindings = new Map<string, Place<unknown>>();\n private readonly _channelBindings = new Map<string, Transition>();\n\n /**\n * @internal Use {@link PetriNetBuilder.compose} — instances are produced\n * by the host builder and supplied to the caller's callback.\n */\n constructor(key: symbol) {\n if (key !== COMPOSE_BINDINGS_KEY) {\n throw new Error(\n 'Use PetriNetBuilder.compose(instance, b => ...) — ComposeBindings is not directly constructible',\n );\n }\n }\n\n /**\n * Binds the named interface port to the given caller place per **MOD-020**.\n *\n * The port name is the **original** (pre-prefix) name declared in the\n * subnet's `Interface`. The typed `<T>` parameter ensures the caller\n * place's token type matches the interface port's token type at compile\n * time per [MOD-022]; TypeScript does not validate the type at runtime\n * because generics are erased.\n *\n * @throws when `portName` is already bound on this builder\n */\n bindPort<T>(portName: string, callerPlace: Place<T>): this {\n if (this._portBindings.has(portName)) {\n throw new Error(`Port '${portName}' is already bound`);\n }\n this._portBindings.set(portName, callerPlace as Place<unknown>);\n return this;\n }\n\n /**\n * Records a synchronous channel binding per **MOD-021**: at compose time,\n * the instance-side renamed channel transition is merged with\n * `callerTransition` into a single transition in the resulting flat net.\n *\n * **Status**: channel composition is implemented in task #13. Recording a\n * channel binding here is permitted, but `compose(...)` currently raises\n * an `Error` when any channel binding is present.\n *\n * @throws when `channelName` is already bound on this builder\n */\n bindChannel(channelName: string, callerTransition: Transition): this {\n if (this._channelBindings.has(channelName)) {\n throw new Error(`Channel '${channelName}' is already bound`);\n }\n this._channelBindings.set(channelName, callerTransition);\n return this;\n }\n\n /** Returns an unmodifiable view of the recorded port bindings. */\n portBindings(): ReadonlyMap<string, Place<unknown>> {\n return this._portBindings;\n }\n\n /** Returns an unmodifiable view of the recorded channel bindings. */\n channelBindings(): ReadonlyMap<string, Transition> {\n return this._channelBindings;\n }\n}\n\n/**\n * @internal Package-internal factory used by {@link PetriNetBuilder.compose}\n * to construct {@link ComposeBindings} values without re-exporting the\n * Symbol-guarded constructor key publicly.\n *\n * NOT part of the public API surface — do NOT re-export from `core/index.ts`.\n */\nexport function __createComposeBindings(): ComposeBindings {\n return new ComposeBindings(COMPOSE_BINDINGS_KEY);\n}\n","import type { Place } from './place.js';\n\n/** @internal Symbol key restricting construction to {@link FusionSet.builder} and {@link FusionSet.of}. */\nconst FUSION_SET_KEY = Symbol('FusionSet.internal');\n\n/**\n * A declaration that N typed places are to be treated as a single canonical\n * place in the resulting flat {@link import('./petri-net.js').PetriNet}, per\n * `spec/11-modular-composition.md` requirements **MOD-060** (fusion set\n * declaration) and **MOD-061** (fusion resolution at build).\n *\n * Fusion is **orthogonal to subnet composition**: composition merges places\n * via port-binding (one instance port place ↔ one caller place per binding);\n * fusion merges N places at once via N-ary equivalence, applied **after** all\n * `compose(...)` calls have flattened subnet instances into the enclosing\n * {@link import('./petri-net.js').PetriNetBuilder}. Fusion is the mechanism\n * for modeling shared cross-instance state — e.g., a global rate limiter\n * shared by three instances of a leaky-bucket subnet — without expressing the\n * shared resource as an interface port on every subnet.\n *\n * ## Canonical member\n *\n * The **first declared member** is the canonical place; the others are\n * non-canonical and get substituted away at\n * {@link import('./petri-net.js').PetriNetBuilder.build} time. The canonical\n * member's name and identity survive into the resulting flat net;\n * non-canonical members do not appear in the built net's place set.\n *\n * ## Token-type homogeneity (MOD-060)\n *\n * All members of a fusion set MUST share the same token type. **In\n * TypeScript** this is enforced at **compile time only** (via the typed\n * `<T>` parameter on {@link FusionSetBuilder.member} and the typed varargs of\n * {@link FusionSet.of}); per the TS-specific MOD-022 clause, no runtime\n * `tokenType` introspection exists because Place carries only a phantom\n * generic. The Java implementation enforces the same invariant at runtime.\n *\n * ## Single-member sets\n *\n * A fusion set with a single member is degenerate but allowed: it is a no-op\n * at fusion-resolution time (the canonical member maps to itself, no\n * substitution occurs). This matches the structural semantics of an N-ary\n * equivalence with N=1.\n *\n * ## Identity\n *\n * `FusionSet` is immutable after construction. The {@link members} array is\n * frozen; iteration order is the declaration order, with the first element\n * guaranteed to be the canonical member.\n *\n * @see import('./petri-net.js').PetriNetBuilder.fuse\n */\nexport class FusionSet {\n readonly name: string;\n readonly members: readonly Place<unknown>[];\n\n /** @internal Use {@link FusionSet.builder} or {@link FusionSet.of} to create instances. */\n constructor(key: symbol, name: string, members: readonly Place<unknown>[]) {\n if (key !== FUSION_SET_KEY) {\n throw new Error('Use FusionSet.builder() or FusionSet.of() to create instances');\n }\n this.name = name;\n this.members = members;\n }\n\n /**\n * Returns the canonical member — by convention, the first declared member.\n * The canonical place's identity survives into the resulting flat net.\n */\n get canonical(): Place<unknown> {\n return this.members[0]!;\n }\n\n /**\n * Returns all members **except** the canonical member, in declaration order.\n * These are the places that get substituted away at\n * {@link import('./petri-net.js').PetriNetBuilder.build} time.\n *\n * For a single-member (degenerate) set, returns an empty array.\n */\n nonCanonical(): readonly Place<unknown>[] {\n if (this.members.length <= 1) return [];\n return this.members.slice(1);\n }\n\n toString(): string {\n return `FusionSet[${this.name}, canonical=${this.canonical.name}, members=${this.members.length}]`;\n }\n\n // ============================================================\n // Static factories\n // ============================================================\n\n /** Returns a fresh {@link FusionSetBuilder} with the given human-readable name. */\n static builder(name: string): FusionSetBuilder {\n return new FusionSetBuilder(name);\n }\n\n /**\n * Convenience factory: builds a fusion set whose first member is `first`\n * (the canonical) and whose remaining members are `rest`, all sharing the\n * type `<T>`.\n *\n * The varargs form ensures static-type homogeneity at the call site (the\n * TypeScript compiler checks every `rest` entry is a `Place<T>`).\n */\n static of<T>(name: string, first: Place<T>, ...rest: Place<T>[]): FusionSet {\n const members: Place<unknown>[] = [first as Place<unknown>];\n for (const p of rest) members.push(p as Place<unknown>);\n return new FusionSet(FUSION_SET_KEY, name, Object.freeze(members));\n }\n}\n\n/**\n * Fluent builder for {@link FusionSet}.\n *\n * Members are appended in call order; the first member becomes the canonical\n * place. The typed `<T>` parameter on {@link member} is for compile-time\n * guidance only — TypeScript erases generics at runtime, so no homogeneity\n * check happens here.\n */\nexport class FusionSetBuilder {\n private readonly _name: string;\n private readonly _members: Place<unknown>[] = [];\n\n constructor(name: string) {\n if (typeof name !== 'string' || name.length === 0) {\n throw new Error('FusionSet.builder: name must be a non-empty string');\n }\n this._name = name;\n }\n\n /**\n * Appends a member to the fusion set. The first member becomes the canonical\n * place per the convention documented on {@link FusionSet}.\n *\n * The `<T>` parameter is for compile-time guidance only: callers writing\n * typed code at the same call site benefit from the compiler checking\n * `Place<T>` at each member.\n */\n member<T>(place: Place<T>): this {\n if (place === undefined || place === null) {\n throw new Error(`FusionSet '${this._name}': member place must not be null`);\n }\n this._members.push(place as Place<unknown>);\n return this;\n }\n\n /**\n * Builds the immutable {@link FusionSet}. Validates that the set has at\n * least one member; the empty set is rejected as malformed per **MOD-060**.\n * Single-member sets are accepted as a structurally degenerate no-op.\n */\n build(): FusionSet {\n if (this._members.length === 0) {\n throw new Error(\n `FusionSet '${this._name}': must have at least one member (MOD-060)`,\n );\n }\n return new FusionSet(FUSION_SET_KEY, this._name, Object.freeze(this._members.slice()));\n }\n}\n\n/**\n * @internal Re-exported symbol key so the {@link FusionSet} test harness can\n * verify the symbol-guard. NOT part of the public API surface.\n */\nexport const __FUSION_SET_KEY_FOR_TEST = FUSION_SET_KEY;\n","import type { Place } from './place.js';\nimport type { TransitionAction } from './transition-action.js';\nimport { passthrough } from './transition-action.js';\nimport { Transition } from './transition.js';\nimport type { Instance } from './instance.js';\nimport { SubnetDef } from './subnet-def.js';\nimport { ComposeBindings, __createComposeBindings } from './compose-bindings.js';\nimport { applyFusion, mergeTransitions, substitutePlaces } from './internal/subnet-rewriter.js';\nimport { FusionSet, FusionSetBuilder } from './fusion-set.js';\n\n/** @internal Symbol key restricting construction to the builder and bindActions. */\nconst PETRI_NET_KEY = Symbol('PetriNet.internal');\n\n/**\n * Immutable definition of a Time Petri Net structure.\n *\n * A PetriNet is a reusable definition that can be executed multiple times\n * with different initial markings. Places are auto-collected from transitions.\n */\nexport class PetriNet {\n readonly name: string;\n readonly places: ReadonlySet<Place<any>>;\n readonly transitions: ReadonlySet<Transition>;\n\n /**\n * Subnet-membership metadata per **MOD-026**: maps each node name (place or\n * transition) contributed by exactly one directly-composed subnet to that\n * subnet's name. Shared places contributed by two or more subnets, and every\n * node of a net not built via {@link PetriNetBuilder.compose}`(SubnetDef)`,\n * are absent. Never null — an empty map when there is no metadata. The DOT\n * exporter renders `subgraph cluster_*` blocks from this map.\n *\n * V8 `Map` is insertion-ordered, preserving compose order so cluster\n * subgraphs render deterministically (cross-language byte-parity).\n */\n readonly subnetMembership: ReadonlyMap<string, string>;\n\n /** @internal Use {@link PetriNet.builder} to create instances. */\n constructor(\n key: symbol,\n name: string,\n places: ReadonlySet<Place<any>>,\n transitions: ReadonlySet<Transition>,\n subnetMembership: ReadonlyMap<string, string> = new Map(),\n ) {\n if (key !== PETRI_NET_KEY) throw new Error('Use PetriNet.builder() to create instances');\n this.name = name;\n this.places = places;\n this.transitions = transitions;\n this.subnetMembership = subnetMembership;\n }\n\n /**\n * Creates a new PetriNet with actions bound to transitions by name.\n * Unbound transitions keep passthrough action.\n */\n bindActions(actionBindings: Map<string, TransitionAction> | Record<string, TransitionAction>): PetriNet {\n const bindings = actionBindings instanceof Map\n ? actionBindings\n : new Map(Object.entries(actionBindings));\n\n return this.bindActionsWithResolver(\n (name) => bindings.get(name) ?? passthrough(),\n );\n }\n\n /**\n * Creates a new PetriNet with actions bound via a resolver function.\n *\n * The resolver is called once per transition with its name. Returning `null`\n * defers that transition — it keeps whatever action it already carries — which\n * is what makes staged binding (**MOD-024** AC7) work.\n */\n bindActionsWithResolver(actionResolver: (name: string) => TransitionAction | null): PetriNet {\n const boundTransitions = new Set<Transition>();\n for (const t of this.transitions) {\n const action = actionResolver(t.name);\n if (action !== null && action !== t.action) {\n boundTransitions.add(rebuildWithAction(t, action));\n } else {\n boundTransitions.add(t);\n }\n }\n // MOD-026: bindActions rebuilds transitions but preserves their names, so\n // name-keyed membership metadata survives a session bind unchanged.\n return new PetriNet(PETRI_NET_KEY, this.name, this.places, boundTransitions,\n this.subnetMembership);\n }\n\n static builder(name: string): PetriNetBuilder {\n return new PetriNetBuilder(name);\n }\n}\n\nexport class PetriNetBuilder {\n private readonly _name: string;\n private readonly _places = new Set<Place<any>>();\n private readonly _transitions = new Set<Transition>();\n private readonly _fusionSets: FusionSet[] = [];\n // MOD-026: node name -> set of subnet names that contributed it via\n // compose(SubnetDef), in first-contribution order. Resolved to single-owner\n // membership at build(). V8 Map/Set iterate in insertion order, preserving\n // compose order for cross-language byte-parity.\n private readonly _subnetContributions = new Map<string, Set<string>>();\n\n constructor(name: string) {\n this._name = name;\n }\n\n /** Add an explicit place. */\n place(place: Place<any>): this {\n this._places.add(place);\n return this;\n }\n\n /** Add explicit places. */\n places(...places: Place<any>[]): this {\n for (const p of places) this._places.add(p);\n return this;\n }\n\n /** Add a transition (auto-collects places from arcs). */\n transition(transition: Transition): this {\n this._transitions.add(transition);\n for (const spec of transition.inputSpecs) {\n this._places.add(spec.place);\n }\n for (const p of transition.outputPlaces()) {\n this._places.add(p);\n }\n for (const inh of transition.inhibitors) {\n this._places.add(inh.place);\n }\n for (const r of transition.reads) {\n this._places.add(r.place);\n }\n for (const r of transition.resets) {\n this._places.add(r.place);\n }\n return this;\n }\n\n /** Add transitions (auto-collects places from arcs). */\n transitions(...transitions: Transition[]): this {\n for (const t of transitions) this.transition(t);\n return this;\n }\n\n /**\n * Composes a subnet {@link Instance} into this builder per **MOD-020**\n * (composition operation), **MOD-021** (channel composition), **MOD-022**\n * (type compatibility), and **MOD-023** (composition produces a flat net).\n *\n * Two overloads are supported:\n *\n * 1. **Map / Record overload** — the runtime-checked form. Pass a\n * `Map<string, Place<unknown>>` or a `Record<string, Place<unknown>>`\n * keyed by the subnet's **original** (pre-prefix) port names. No\n * channel bindings are recorded by this overload.\n *\n * 2. **Callback overload** — the typed form. Pass a callback receiving a\n * fresh {@link ComposeBindings}; register port bindings via\n * `bindings.bindPort<T>(name, place)` so TypeScript checks each\n * binding's token type at compile time per [MOD-022]. Synchronous\n * channels may be merged with caller-side transitions via\n * `bindings.bindChannel(name, t)` per [MOD-021].\n *\n * For each port binding `(portName -> callerPlace)`, the instance's\n * renamed port place is substituted with the caller place at every arc\n * in the instance's renamed body via the `subnet-rewriter` module.\n * Internal (non-port) places of the instance flow through with their\n * prefixed names. Composition is **eager** — the rewrite happens here,\n * not at `build()` (per [MOD-020] AC #5).\n *\n * For each channel binding `(channelName -> callerTransition)`, the\n * instance's renamed channel transition and the caller-side transition\n * are merged into one transition in the resulting flat net per [MOD-021].\n * If the caller-side transition has not been added to this builder yet,\n * it is added implicitly during the merge step.\n *\n * @throws when a port name is unknown on the instance's interface, when a\n * channel name is unknown on the interface, or when caller- and\n * instance-side transition timings conflict (per [MOD-021]).\n */\n compose(instance: Instance<unknown>): this;\n compose(\n instance: Instance<unknown>,\n portMappings: ReadonlyMap<string, Place<unknown>> | Record<string, Place<unknown>>,\n ): this;\n compose(\n instance: Instance<unknown>,\n bind: (b: ComposeBindings) => void,\n ): this;\n compose(def: SubnetDef<unknown>): this;\n compose(\n instanceOrDef: Instance<unknown> | SubnetDef<unknown>,\n arg?:\n | ReadonlyMap<string, Place<unknown>>\n | Record<string, Place<unknown>>\n | ((b: ComposeBindings) => void),\n ): this {\n if (instanceOrDef instanceof SubnetDef) {\n return this.composeDirect(instanceOrDef);\n }\n const instance = instanceOrDef;\n if (arg === undefined) {\n return this.composeAuto(instance);\n }\n if (typeof arg === 'function') {\n const bindings = __createComposeBindings();\n arg(bindings);\n return this.composeInternal(instance, bindings.portBindings(), bindings.channelBindings());\n }\n\n const portMappings: ReadonlyMap<string, Place<unknown>> =\n arg instanceof Map ? arg : new Map(Object.entries(arg));\n return this.composeInternal(instance, portMappings, new Map());\n }\n\n /**\n * Composes a subnet {@link SubnetDef} **directly** into this builder per\n * **MOD-025** — **without instantiation**, and without the prefix-renaming\n * of {@link SubnetDef.instantiate}.\n *\n * Every body place and transition is added under its **original**\n * (un-prefixed) name. Places merge into this builder by name: a body place\n * whose name equals an enclosing-net place *is* that place in the composed\n * flat net. This is the mode for wiring a subnet in as a single shared copy.\n *\n * Direct composition is **order-independent**: composing the same set of\n * subnets in any order yields the same flat net, because merging is by\n * place name and not by a probe of the builder's place set at call time —\n * contrast the no-interface body-inference branch of {@link composeAuto}\n * (MOD-024), which is order-sensitive.\n *\n * For multiple *independent* copies — each with isolated per-instance state\n * per [MOD-012] — use {@link SubnetDef.instantiate} + the `compose(instance)`\n * overload instead.\n *\n * Rejections: a body transition whose name already exists in this builder\n * (use `instantiate(prefix)` for independent copies); a subnet whose\n * interface declares any channel (direct composition does not bind\n * channels — use `instantiate` + the channel-binding `compose` overload).\n *\n * Token-type conflicts on a same-named place cannot be detected: TS\n * {@link Place} equality is name-only at runtime (the documented carve-out,\n * same as MOD-024).\n *\n * @throws when the subnet declares channels, or a body transition name\n * collides with a transition already in this builder.\n */\n private composeDirect(def: SubnetDef<unknown>): this {\n const iface = def.iface;\n\n // MOD-025: direct composition does not bind channels.\n if (iface.channels.size > 0) {\n const channelNames: string[] = [];\n for (const c of iface.channels.values()) channelNames.push(c.name);\n channelNames.sort();\n throw new Error(\n `compose(SubnetDef): subnet '${def.name}' declares channels ` +\n `[${channelNames.join(', ')}]; direct composition does not bind channels.` +\n ` Use def.instantiate(prefix) + compose(instance, bind => bind.bindChannel(...)).`,\n );\n }\n\n const body = def.body;\n\n // MOD-025: a body transition whose name already exists here is almost\n // always a mistake — instantiate(prefix) is the multi-copy path.\n const hostTransitionNames = new Set<string>();\n for (const t of this._transitions) hostTransitionNames.add(t.name);\n for (const t of body.transitions) {\n if (hostTransitionNames.has(t.name)) {\n throw new Error(\n `compose(SubnetDef): transition '${t.name}' from subnet '${def.name}' ` +\n `collides with a transition already in net '${this._name}'. Direct ` +\n `composition merges by name; for independent copies use ` +\n `def.instantiate(prefix) + compose(instance).`,\n );\n }\n }\n\n // Canonicalize place references. TS `Set<Place>` dedups by reference, so\n // a body place value-equal-by-name to a host place must be funnelled\n // through the single host reference (same intent as composeAuto). Body\n // places with a new name are canonical as themselves; arcs referencing\n // them are left untouched by substitutePlaces.\n const hostByName = new Map<string, Place<unknown>>();\n for (const p of this._places) hostByName.set(p.name, p);\n\n // MOD-026: record which subnet each node came from so cluster-aware DOT\n // export can reconstruct subgraphs without prefix names. The subnet name\n // is sanitised of '/' so it never triggers spurious nested-cluster\n // splitting in the exporter.\n const subnetName = def.name.replace(/\\//g, '_');\n\n const mergeMap = new Map<string, Place<unknown>>();\n for (const p of body.places) {\n const host = hostByName.get(p.name);\n this.place(host ?? p);\n if (host !== undefined) mergeMap.set(p.name, host);\n this.recordContribution(p.name, subnetName);\n }\n for (const t of body.transitions) {\n this.transition(substitutePlaces(t, mergeMap));\n this.recordContribution(t.name, subnetName);\n }\n return this;\n }\n\n /** @internal MOD-026: records a node as contributed by the named subnet. */\n private recordContribution(nodeName: string, subnetName: string): void {\n let owners = this._subnetContributions.get(nodeName);\n if (owners === undefined) {\n owners = new Set<string>();\n this._subnetContributions.set(nodeName, owners);\n }\n owners.add(subnetName);\n }\n\n /**\n * Identity-default auto-compose per **MOD-024**.\n *\n * Each declared interface port auto-binds to its own `port.place` — the\n * Place the SubnetDef builder declared via `.inputPort(name, hostPlace)`\n * (or `outputPort` / `inoutPort`). If the host builder already declares\n * the equal place, the two merge; if not, the place arrives implicitly\n * via the rewritten transitions' arcs (same flow as explicit `bindPort`).\n *\n * If the subnet declares no interface ports at all, body places are\n * checked against this builder's place set **by name** (matching the\n * existing TS Place equality semantics; see [CORE-002] note in\n * `spec/11-modular-composition.md` MOD-024). Body places that don't match\n * stay private under their prefixed names per [MOD-010].\n *\n * Channels are NOT auto-bound — transition identity is too delicate for\n * inference. If the subnet declares any channel, this overload throws.\n */\n private composeAuto(instance: Instance<unknown>): this {\n const iface = instance.def.iface;\n\n if (iface.channels.size > 0) {\n const channelNames: string[] = [];\n for (const c of iface.channels.values()) channelNames.push(c.name);\n channelNames.sort();\n throw new Error(\n `compose(Instance): subnet '${instance.def.name}' ` +\n `(instance prefix '${instance.prefix}') declares channels [${channelNames.join(', ')}]` +\n `; auto-compose does not bind channels.` +\n ` Use compose(instance, bind => bind.bindChannel(...)) with explicit channel bindings.`,\n );\n }\n\n // Pre-index host places by name. The TS `_places: Set<Place>` dedupes\n // by reference (Place is an interface with only `name`), so when the\n // host pre-declared a Place object that is value-equal-by-name but a\n // different reference from the SubnetDef port's carried place, we\n // prefer the host reference: arc rewriting funnels through it and the\n // port's own Place object never enters `_places`. Same intent as\n // Rust's `place_index.get(&probe).cloned().unwrap_or(probe)` and\n // Java's record-equality `places.contains(probe)` in this branch.\n const hostByName = new Map<string, Place<unknown>>();\n for (const p of this._places) hostByName.set(p.name, p);\n\n if (iface.ports.size > 0) {\n // Explicit interface: each declared port auto-binds to its own\n // declared place. The SubnetDef's inputPort/outputPort/inoutPort\n // statement IS the host wiring — trust it. When a host place with\n // the same name already exists, use the host reference so the\n // merged net has a single Place per name.\n const portMappings = new Map<string, Place<unknown>>();\n for (const port of iface.ports.values()) {\n const hostMatch = hostByName.get(port.place.name);\n portMappings.set(port.name, hostMatch ?? port.place);\n }\n return this.composeInternal(instance, portMappings, new Map());\n }\n\n // No declared interface — infer the merge set from body places that\n // also exist on the host builder (matched by name). Build the\n // renamed-name -> host-place map directly and apply the composition.\n\n const mergeMap = new Map<string, Place<unknown>>();\n const prefix = instance.prefix + '/';\n for (const renamed of instance.renamedBody.places) {\n if (!renamed.name.startsWith(prefix)) continue;\n const originalName = renamed.name.substring(prefix.length);\n const hostMatch = hostByName.get(originalName);\n if (hostMatch !== undefined) {\n mergeMap.set(renamed.name, hostMatch);\n }\n }\n return this.applyComposition(instance, mergeMap, new Map());\n }\n\n /**\n * @internal Shared compose implementation: validates port and channel\n * bindings, builds the place-substitution map, walks every renamed-body\n * transition through {@link substitutePlaces}, applies channel merges per\n * [MOD-021], and adds the resulting transitions to this builder.\n *\n * ## Channel-merge flow ([MOD-021])\n *\n * 1. Collect rewritten instance transitions into a working `Map<string,\n * Transition>` keyed by prefixed transition name (deferred — not yet\n * added to the builder's transition set).\n * 2. For each channel binding, resolve the renamed instance-side\n * transition through `instance.channel(channelName)`, then look up its\n * rewritten counterpart in the working map by name.\n * 3. Replace the working-map entry with a {@link mergeTransitions} result\n * that fuses caller-side + instance-side; remove the rewritten\n * instance-side entry. Also replace (or add) the caller-side\n * transition in this builder's transition set with the same merged\n * result, indexed under the caller's name slot.\n * 4. Add the surviving (un-merged) entries to this builder.\n *\n * The deferral matters: writing the rewritten instance transitions to the\n * builder eagerly would force a second \"remove-then-replace\" pass to\n * apply the channel merges, complicating the place-collection invariants.\n * Collecting first and merging second keeps the builder's transition set\n * finalized exactly once.\n *\n * Keying the working map by prefixed transition name (rather than by\n * Transition reference) is also robust against a prior\n * {@link Instance.bindActions} call that may have rebuilt the renamed-body\n * transitions, breaking identity equality between the body and the\n * channel-handle map — but the prefixed names remain stable.\n */\n private composeInternal(\n instance: Instance<unknown>,\n portMappings: ReadonlyMap<string, Place<unknown>>,\n channelBindings: ReadonlyMap<string, Transition>,\n ): this {\n const iface = instance.def.iface;\n\n // Build mergeMap: keyed by RENAMED instance-side place name -> caller\n // place. The subnet-rewriter resolves arc-place references by name\n // (matching TS Place identity model: name-based equality per\n // runtime/compiled-net.ts), so we key by the renamed name.\n const mergeMap = new Map<string, Place<unknown>>();\n\n for (const [portName, callerPlace] of portMappings) {\n const port = iface.port(portName);\n if (port === undefined) {\n const knownPorts: string[] = [];\n for (const p of iface.ports.values()) knownPorts.push(p.name);\n throw new Error(\n `compose: no port named '${portName}' on subnet '${instance.def.name}' ` +\n `(instance prefix '${instance.prefix}'). Known ports: [${knownPorts.join(', ')}]`,\n );\n }\n\n // Resolve the renamed instance-side place via the typed accessor;\n // this gives us the rewritten Place<unknown> in the instance body.\n const ifacePlace = instance.port<unknown>(portName);\n mergeMap.set(ifacePlace.name, callerPlace);\n }\n\n return this.applyComposition(instance, mergeMap, channelBindings);\n }\n\n /**\n * Shared post-mergeMap pipeline: rewrites renamed-body transitions\n * through `mergeMap`, applies channel merges per **MOD-021**, and adds\n * the surviving transitions to the builder.\n *\n * Used by both the explicit-binding path (`composeInternal`) and the\n * auto-compose path (`composeAuto` per **MOD-024**). The two paths differ\n * only in how the (renamed Place name → host Place) `mergeMap` is built.\n */\n private applyComposition(\n instance: Instance<unknown>,\n mergeMap: Map<string, Place<unknown>>,\n channelBindings: ReadonlyMap<string, Transition>,\n ): this {\n const iface = instance.def.iface;\n\n // Step 1: Stage rewritten instance transitions in a working map keyed\n // by prefixed transition name. The substitutePlaces primitive keeps\n // the prefixed transition name unchanged (per MOD-010 — prefixed names\n // are already unique within the host) and rewrites only the arc place\n // references.\n const rewrittenByName = new Map<string, Transition>();\n for (const t of instance.renamedBody.transitions) {\n rewrittenByName.set(t.name, substitutePlaces(t, mergeMap));\n }\n\n // Step 2: Apply channel merges. For each binding, locate the rewritten\n // instance-side transition by name, fuse it with the caller-side\n // transition, and replace the working-map entry. Also replace the\n // caller-side transition in this builder's transition set with the\n // merged result (or add it if the caller did not pre-add it).\n for (const [channelName, callerTrans] of channelBindings) {\n // Resolve the renamed instance-side channel transition. instance.channel\n // throws on unknown name; we re-wrap with a more contextual message.\n let instanceRenamedChannel: Transition;\n try {\n instanceRenamedChannel = instance.channel(channelName);\n } catch (cause) {\n const knownChannels: string[] = [];\n for (const c of iface.channels.values()) knownChannels.push(c.name);\n const err = new Error(\n `compose: no channel named '${channelName}' on subnet '${instance.def.name}' ` +\n `(instance prefix '${instance.prefix}'). Known channels: [${knownChannels.join(', ')}]`,\n );\n // Preserve cause chain for diagnostics (Node 16.9+ supports the\n // standard Error cause option).\n (err as Error & { cause?: unknown }).cause = cause;\n throw err;\n }\n\n // Look up the rewritten (port-substituted) version of the renamed\n // channel transition by name.\n const rewrittenInstanceChannel = rewrittenByName.get(instanceRenamedChannel.name);\n if (rewrittenInstanceChannel === undefined) {\n // Defensive: SubnetDef.builder validation guarantees the channel's\n // transition is a member of the renamed body.\n /* istanbul ignore next */\n throw new Error(\n `compose: channel '${channelName}' resolved to a transition ` +\n `'${instanceRenamedChannel.name}' that is not present in the renamed body. ` +\n `This indicates a SubnetDef invariant violation.`,\n );\n }\n\n // Build the merged transition (caller-wins identity per MOD-021).\n const merged = mergeTransitions(callerTrans, rewrittenInstanceChannel, callerTrans.name);\n\n // Step 2a: Remove the rewritten instance-side transition from the\n // working map (it merges away — only the merged result remains under\n // the caller's transition slot in the builder).\n rewrittenByName.delete(instanceRenamedChannel.name);\n\n // Step 2b: Replace the caller-side transition (if present) in this\n // builder's transition set with the merged result. If the caller did\n // not pre-add it, simply add the merged transition — the user's\n // intent to use callerTrans is captured via the binding itself.\n this._transitions.delete(callerTrans);\n this.transition(merged);\n }\n\n // Step 3: Add the surviving (un-merged) rewritten transitions to the\n // builder. transition() auto-collects places — internal (non-merged)\n // renamed places are added under their prefixed names; caller places\n // already in the builder's place set get deduped via Place name.\n for (const rewritten of rewrittenByName.values()) {\n this.transition(rewritten);\n }\n\n return this;\n }\n\n /**\n * Registers one or more {@link FusionSet} declarations on this builder, per\n * **MOD-060** (fusion set declaration) and **MOD-061** (fusion resolution\n * at build).\n *\n * Fusion is **orthogonal to subnet composition**: fuse sets are accumulated\n * here and applied during {@link build} **after** all `compose(...)` calls\n * have flattened subnet instances into the builder's transition set.\n * Registration order is irrelevant to semantics — `fuse(set)` BEFORE\n * `compose(...)` and `fuse(set)` AFTER `compose(...)` both apply at the\n * same point in the build pipeline.\n *\n * ## Validation\n *\n * Cross-set overlap (a place appearing in two fusion sets) is detected at\n * {@link build} and reported as an `Error` naming the offending place and\n * both sets.\n *\n * Two overloads are supported:\n *\n * 1. **Spread overload** — pass one or more pre-built {@link FusionSet}\n * values (e.g., from `FusionSet.of(...)` or\n * `FusionSet.builder(...).build()`).\n * 2. **Sugar overload** — pass a callback receiving a fresh\n * {@link FusionSetBuilder} named after the enclosing net; register\n * members via `b.member(place)`. Equivalent to\n * `FusionSet.builder('<netName>-fusion').<callback>.build()` followed by\n * `fuse(...)` on the result.\n */\n fuse(...sets: FusionSet[]): this;\n fuse(declarer: (b: FusionSetBuilder) => void): this;\n fuse(...args: [(b: FusionSetBuilder) => void] | FusionSet[]): this {\n if (args.length === 1 && typeof args[0] === 'function') {\n const declarer = args[0] as (b: FusionSetBuilder) => void;\n const fb = FusionSet.builder(this._name + '-fusion');\n declarer(fb);\n this._fusionSets.push(fb.build());\n return this;\n }\n for (const s of args as FusionSet[]) {\n if (s === undefined || s === null) {\n throw new Error('fuse: fusion set must not be null');\n }\n this._fusionSets.push(s);\n }\n return this;\n }\n\n /**\n * Builds the immutable {@link PetriNet}, applying fusion resolution (per\n * **MOD-061**) AFTER all transition/composition accumulation:\n *\n * 1. Detect overlapping fusion sets — a single place declared in two sets\n * is rejected with an `Error`.\n * 2. Build the `non-canonical → canonical` substitution map across all\n * sets, keyed by non-canonical place name (matching the rewriter's\n * Map<string, Place<unknown>> convention — TypeScript Place identity is\n * name-based per `runtime/compiled-net.ts`).\n * 3. Walk every transition through {@link applyFusion} to rewrite arc place\n * references; input arcs colliding on a canonical place merge per\n * [MOD-021] (additive where summable, rejected otherwise).\n * 4. Re-derive the place set from the rewritten transitions plus any\n * caller-declared standalone places, dropping non-canonical members.\n * Caller-declared standalone places that happen to be non-canonical\n * members are also dropped.\n *\n * If no fusion sets were registered, the build is the trivial\n * `new PetriNet(...)` — the fusion machinery has no per-build cost when\n * unused.\n *\n * @throws when two fusion sets share a place\n */\n build(): PetriNet {\n const membership = this.resolveSubnetMembership();\n if (this._fusionSets.length === 0) {\n return new PetriNet(PETRI_NET_KEY, this._name, this._places, this._transitions,\n membership);\n }\n return this.buildWithFusion(membership);\n }\n\n /**\n * @internal Resolves the per-compose contributions recorded by\n * `composeDirect` into the final node-name → subnet-name membership map per\n * **MOD-026**. A node contributed by exactly one subnet maps to that subnet;\n * a place contributed by two or more subnets is a shared rendezvous place\n * and is omitted (it renders top-level, outside any cluster). Returns an\n * empty map — the common case — when no subnet was composed directly.\n */\n private resolveSubnetMembership(): Map<string, string> {\n const resolved = new Map<string, string>();\n for (const [nodeName, owners] of this._subnetContributions) {\n if (owners.size === 1) {\n resolved.set(nodeName, owners.values().next().value as string);\n }\n }\n return resolved;\n }\n\n /**\n * @internal Drops membership entries for places removed by fusion: a\n * non-canonical fused member no longer exists in the net, so its\n * `node-name → subnet` entry would dangle. The surviving canonical place\n * keeps its own entry. Per **MOD-026**.\n */\n private static filterFusedMembership(\n membership: Map<string, string>,\n nonCanonicalNames: ReadonlySet<string>,\n ): Map<string, string> {\n if (membership.size === 0 || nonCanonicalNames.size === 0) {\n return membership;\n }\n const filtered = new Map<string, string>();\n for (const [key, value] of membership) {\n if (!nonCanonicalNames.has(key)) {\n filtered.set(key, value);\n }\n }\n return filtered;\n }\n\n /**\n * @internal Fusion-resolution pass per **MOD-061**. Split out from\n * {@link build} so the no-fusion fast path stays trivial.\n */\n private buildWithFusion(membership: Map<string, string>): PetriNet {\n // Step 1: detect overlap. The same place name MUST NOT appear in more\n // than one fusion set (TypeScript Place identity is name-based per\n // `runtime/compiled-net.ts`).\n const ownership = new Map<string, FusionSet>();\n for (const set of this._fusionSets) {\n for (const member of set.members) {\n const prior = ownership.get(member.name);\n if (prior !== undefined && prior !== set) {\n throw new Error(\n `Fusion overlap: place '${member.name}' appears in two fusion sets ` +\n `('${prior.name}' and '${set.name}'). A place may appear in at most ` +\n `one fusion set (MOD-060).`,\n );\n }\n ownership.set(member.name, set);\n }\n }\n\n // Step 2: build the non-canonical-name → canonical-place substitution\n // map. Single-member sets contribute nothing (no non-canonical members),\n // so the map is naturally empty for the degenerate case.\n const fusionMap = new Map<string, Place<unknown>>();\n const nonCanonicalNames = new Set<string>();\n for (const set of this._fusionSets) {\n const canonical = set.canonical;\n for (const nc of set.nonCanonical()) {\n fusionMap.set(nc.name, canonical);\n nonCanonicalNames.add(nc.name);\n }\n }\n\n // Step 3: rewrite every transition's arcs through the fusion map.\n // applyFusion always returns a fresh set; if fusionMap is empty (single-\n // member-only sets) the rewrite is structurally a no-op but still rebuilds\n // Transition records — no observable difference. Input-arc collisions on a\n // canonical place merge per MOD-021, naming the owning fusion set on\n // rejection.\n const rewrittenTransitions = applyFusion(this._transitions, fusionMap, (canonicalName) => {\n const owner = ownership.get(canonicalName);\n return `Fusion set '${owner !== undefined ? owner.name : canonicalName}'`;\n });\n\n // Step 4: re-derive the place set. Strategy: start from the current\n // place set, drop every non-canonical member (they are gone from the\n // net), then union in the places auto-discovered from the rewritten\n // transitions. This preserves caller-declared standalone places that are\n // unrelated to fusion, drops any standalone declarations of non-canonical\n // members, and ensures canonical places end up present even if a caller\n // never declared them standalone.\n const rebuiltPlaces = new Set<Place<any>>();\n for (const p of this._places) {\n if (!nonCanonicalNames.has(p.name)) {\n rebuiltPlaces.add(p);\n }\n }\n for (const t of rewrittenTransitions) {\n for (const spec of t.inputSpecs) rebuiltPlaces.add(spec.place);\n for (const p of t.outputPlaces()) rebuiltPlaces.add(p);\n for (const inh of t.inhibitors) rebuiltPlaces.add(inh.place);\n for (const r of t.reads) rebuiltPlaces.add(r.place);\n for (const r of t.resets) rebuiltPlaces.add(r.place);\n }\n\n return new PetriNet(PETRI_NET_KEY, this._name, rebuiltPlaces, rewrittenTransitions,\n PetriNetBuilder.filterFusedMembership(membership, nonCanonicalNames));\n }\n}\n\n/** Creates a new transition with a different action while preserving all arc specs. */\nfunction rebuildWithAction(t: Transition, action: TransitionAction): Transition {\n const builder = Transition.builder(t.name)\n .timing(t.timing)\n .priority(t.priority)\n .action(action);\n\n // MOD-031: carry the declared→actual place correspondence forward so an action\n // bound after instantiate/compose ([CORE-042]) still resolves its hardcoded\n // declared places. Empty for hand-written / directly-composed transitions.\n if (t.placeAlias.size > 0) {\n builder.placeAlias(t.placeAlias);\n }\n\n if (t.inputSpecs.length > 0) {\n builder.inputs(...t.inputSpecs);\n }\n if (t.outputSpec !== null) {\n builder.outputs(t.outputSpec);\n }\n\n for (const inh of t.inhibitors) {\n builder.inhibitor(inh.place);\n }\n for (const r of t.reads) {\n builder.read(r.place);\n }\n for (const r of t.resets) {\n builder.reset(r.place);\n }\n\n // NU-030: carry the ν-net join correlation forward. bindActions only attaches\n // an action — it does not rename places — so the matchSpec's input-place\n // references are still valid and it is carried as-is (no remap, unlike the\n // compose/rename rebuildWithName). Dropping it here would silently revert a\n // correlated join-by-id to a plain FIFO AND join at runtime.\n if (t.matchSpec !== null) {\n builder.match(t.matchSpec);\n }\n\n return builder.build();\n}\n","import type { PetriNet } from './petri-net.js';\nimport type { SubnetDef } from './subnet-def.js';\n\n/**\n * Discriminated sum-type abstraction over Petri nets, distinguishing **closed**\n * (runnable) nets from **open** (composable) subnet fragments per\n * `spec/11-modular-composition.md` requirement **MOD-002**.\n *\n * This abstraction is the bridge between the existing flat {@link PetriNet}\n * world and the modular composition extension. Code that wishes to accept\n * \"any net\" types its parameter as `Subnet`; code that needs a runnable net\n * continues to take {@link PetriNet} (or `Subnet` narrowed to `'closed'`);\n * code that needs an open fragment takes {@link SubnetDef} (or `Subnet`\n * narrowed to `'open'`). Misuse is rejected at compile time wherever\n * TypeScript's structural typing permits.\n *\n * Use the literal `kind` field for exhaustive pattern matching:\n *\n * ```ts\n * function classify(s: Subnet): string {\n * switch (s.kind) {\n * case 'closed': return `closed:${s.net.name}`;\n * case 'open': return `open:${s.def.name}`;\n * }\n * }\n * ```\n */\nexport type Subnet =\n | { readonly kind: 'closed'; readonly net: PetriNet }\n | { readonly kind: 'open'; readonly def: SubnetDef<unknown> };\n\n/** Wraps a {@link PetriNet} as a closed (runnable) {@link Subnet}. */\nexport function closedSubnet(net: PetriNet): Subnet {\n return { kind: 'closed', net };\n}\n\n/** Wraps a {@link SubnetDef} as an open (composable) {@link Subnet}. */\nexport function openSubnet(def: SubnetDef<unknown>): Subnet {\n return { kind: 'open', def };\n}\n","/**\n * @module marking\n *\n * Mutable token state (marking) of a running Petri net.\n *\n * Tokens per place are stored in FIFO arrays (push to end, shift from front).\n * Not thread-safe — all mutation occurs from the single-threaded orchestrator.\n *\n * For typical nets (≤10 tokens per place), Array.shift() is faster than a deque\n * due to cache locality. Only optimize if profiling shows a bottleneck.\n */\nimport type { Place } from '../core/place.js';\nimport type { Token } from '../core/token.js';\n\nconst EMPTY_TOKENS: readonly Token<any>[] = Object.freeze([]);\n\n/**\n * A place reference plus an optional per-token predicate.\n *\n * Used by the ν-net join path (NU-020/NU-021) to select the tokens whose\n * projected correlation name equals the chosen binding. This is *not* an input\n * guard (IO-006, removed) — input specifications are purely structural; the\n * predicate here is always derived from name correlation.\n */\nexport interface PredicateSpec<T = any> {\n readonly place: Place<T>;\n readonly predicate?: (value: T) => boolean;\n}\n\n/**\n * Mutable marking (token state) of a Petri Net during execution.\n *\n * Tokens in each place are maintained in FIFO order (array: push to end, shift from front).\n * Not thread-safe — all access must be from the orchestrator.\n */\nexport class Marking {\n /** Place name -> FIFO queue of tokens. */\n private readonly tokens = new Map<string, Token<any>[]>();\n /** Place name -> Place reference (for inspection). */\n private readonly placeRefs = new Map<string, Place<any>>();\n\n static empty(): Marking {\n return new Marking();\n }\n\n static from(initial: Map<Place<any>, Token<any>[]>): Marking {\n const m = new Marking();\n for (const [place, tokens] of initial) {\n m.placeRefs.set(place.name, place);\n m.tokens.set(place.name, [...tokens]);\n }\n return m;\n }\n\n // ======================== Token Addition ========================\n\n addToken<T>(place: Place<T>, token: Token<T>): void {\n this.placeRefs.set(place.name, place);\n const queue = this.tokens.get(place.name);\n if (queue) {\n queue.push(token);\n } else {\n this.tokens.set(place.name, [token]);\n }\n }\n\n // ======================== Token Removal ========================\n\n /** Removes and returns the oldest token. Returns null if empty. */\n removeFirst<T>(place: Place<T>): Token<T> | null {\n const queue = this.tokens.get(place.name);\n if (!queue || queue.length === 0) return null;\n return queue.shift() as Token<T>;\n }\n\n /** Removes and returns all tokens from a place. */\n removeAll<T>(place: Place<T>): Token<T>[] {\n const queue = this.tokens.get(place.name);\n if (!queue || queue.length === 0) return [];\n const result = [...queue] as Token<T>[];\n queue.length = 0;\n return result;\n }\n\n /**\n * Removes and returns the first token whose value satisfies the predicate.\n *\n * Performs a linear scan of the place's FIFO queue. If no predicate is\n * provided, behaves like `removeFirst()`. Otherwise skips non-matching\n * tokens and splices the first match out of the queue (O(n) worst case).\n */\n removeFirstMatching(spec: PredicateSpec): Token<any> | null {\n const queue = this.tokens.get(spec.place.name);\n if (!queue || queue.length === 0) return null;\n if (!spec.predicate) {\n return queue.shift()!;\n }\n for (let i = 0; i < queue.length; i++) {\n const token = queue[i]!;\n if (spec.predicate(token.value)) {\n // Head removal (the common ν-net case — the matched token is the oldest,\n // hence at the front with distinct timestamps) uses the V8-optimized\n // shift() rather than an O(n) splice, keeping a draining join linear.\n if (i === 0) queue.shift();\n else queue.splice(i, 1);\n return token;\n }\n }\n return null;\n }\n\n // ======================== Token Inspection ========================\n\n /** Check if any token satisfies the predicate. */\n hasMatchingToken(spec: PredicateSpec): boolean {\n const queue = this.tokens.get(spec.place.name);\n if (!queue || queue.length === 0) return false;\n if (!spec.predicate) return true;\n return queue.some(t => spec.predicate!(t.value));\n }\n\n /**\n * Counts tokens in a place whose values satisfy the predicate.\n *\n * If no predicate is provided, returns the total token count (O(1)).\n * With a predicate, performs a linear scan over all tokens (O(n)).\n * Used by the executor to size a ν-net correlated `all`/`at-least` consume.\n */\n countMatching(spec: PredicateSpec): number {\n const queue = this.tokens.get(spec.place.name);\n if (!queue || queue.length === 0) return 0;\n if (!spec.predicate) return queue.length;\n let count = 0;\n for (const t of queue) {\n if (spec.predicate(t.value)) count++;\n }\n return count;\n }\n\n /**\n * Returns tokens in a place. **Returns a live reference** to the internal\n * array — callers must not mutate it. Copy with `[...peekTokens(p)]` if\n * mutation or snapshot semantics are needed.\n */\n peekTokens<T>(place: Place<T>): readonly Token<T>[] {\n return (this.tokens.get(place.name) ?? EMPTY_TOKENS) as readonly Token<T>[];\n }\n\n /** Returns the oldest token without removing it. */\n peekFirst<T>(place: Place<T>): Token<T> | null {\n const queue = this.tokens.get(place.name);\n return queue && queue.length > 0 ? queue[0] as Token<T> : null;\n }\n\n /** Checks if a place has any tokens. */\n hasTokens(place: Place<any>): boolean {\n const queue = this.tokens.get(place.name);\n return queue !== undefined && queue.length > 0;\n }\n\n /** Returns the number of tokens in a place. */\n tokenCount(place: Place<any>): number {\n const queue = this.tokens.get(place.name);\n return queue ? queue.length : 0;\n }\n\n // ======================== Debugging ========================\n\n toString(): string {\n const parts: string[] = [];\n for (const [name, queue] of this.tokens) {\n if (queue.length > 0) {\n parts.push(`${name}: ${queue.length}`);\n }\n }\n return `Marking{${parts.join(', ')}}`;\n }\n}\n","/**\n * @module compiled-net\n *\n * Integer-indexed, precomputed representation of a PetriNet for bitmap-based execution.\n *\n * **Precomputation strategy**: At compile time, all places and transitions are assigned\n * stable integer IDs. Input/inhibitor arcs are converted to Uint32Array bitmasks (one per\n * transition), enabling O(W) enablement checks via bitwise AND where W = ceil(numPlaces/32).\n *\n * **Why bitmaps**: JS bitwise operators work natively on 32-bit integers. Using Uint32Array\n * with 32-bit words (WORD_SHIFT=5) avoids BigInt overhead while keeping enablement checks\n * branch-free and cache-friendly. For a typical 50-place net, W=2 words per mask.\n *\n * **Reverse index**: A place-to-transitions mapping enables the dirty set pattern —\n * when a place's marking changes, only affected transitions are re-evaluated.\n */\nimport type { PetriNet } from '../core/petri-net.js';\nimport type { Place } from '../core/place.js';\nimport type { Transition } from '../core/transition.js';\nimport { requiredCount } from '../core/in.js';\nimport { allPlaces } from '../core/out.js';\nimport { requireOutputProducingActions } from '../core/internal/output-action-check.js';\n\n/** 32-bit words for JS bitwise ops. */\nexport const WORD_SHIFT = 5;\nexport const BIT_MASK = 31;\n\nexport interface CardinalityCheck {\n readonly placeIds: readonly number[];\n readonly requiredCounts: readonly number[];\n}\n\n/**\n * Integer-indexed, precomputed representation of a PetriNet for bitmap-based execution.\n *\n * Uses Uint32Array masks with 32-bit words (JS bitwise ops work on 32-bit ints natively).\n */\nexport class CompiledNet {\n readonly net: PetriNet;\n readonly placeCount: number;\n readonly transitionCount: number;\n readonly wordCount: number;\n\n // ID mappings\n private readonly _placesById: Place<any>[];\n private readonly _transitionsById: Transition[];\n private readonly _placeIndex: Map<string, number>;\n private readonly _transitionIndex: Map<Transition, number>;\n\n // Precomputed masks per transition\n private readonly _needsMask: Uint32Array[];\n private readonly _inhibitorMask: Uint32Array[];\n\n // Reverse index: place -> affected transition IDs\n private readonly _placeToTransitions: number[][];\n\n // Consumption place IDs per transition (input + reset places)\n private readonly _consumptionPlaceIds: number[][];\n\n // Cardinality flags\n private readonly _cardinalityChecks: (CardinalityCheck | null)[];\n // ν-net join flag: the transition carries a MatchSpec (NU-020). Precomputed\n // so the hot enablement loop can skip the match check on non-ν transitions\n // (zero-cost gating).\n private readonly _hasMatch: boolean[];\n\n private constructor(net: PetriNet) {\n this.net = net;\n\n // CORE-043: reconcile declared structure against bound behaviour before anything else.\n requireOutputProducingActions(net);\n\n // Collect all places\n const allPlacesSet = new Map<string, Place<any>>();\n for (const t of net.transitions) {\n for (const spec of t.inputSpecs) allPlacesSet.set(spec.place.name, spec.place);\n for (const r of t.reads) allPlacesSet.set(r.place.name, r.place);\n for (const inh of t.inhibitors) allPlacesSet.set(inh.place.name, inh.place);\n for (const rst of t.resets) allPlacesSet.set(rst.place.name, rst.place);\n if (t.outputSpec !== null) {\n for (const p of allPlaces(t.outputSpec)) allPlacesSet.set(p.name, p);\n }\n }\n for (const p of net.places) allPlacesSet.set(p.name, p);\n\n this.placeCount = allPlacesSet.size;\n this.wordCount = (this.placeCount + BIT_MASK) >>> WORD_SHIFT;\n\n // Assign place IDs\n this._placesById = [...allPlacesSet.values()];\n this._placeIndex = new Map();\n for (let i = 0; i < this._placesById.length; i++) {\n this._placeIndex.set(this._placesById[i]!.name, i);\n }\n\n // Assign transition IDs\n this._transitionsById = [...net.transitions];\n this.transitionCount = this._transitionsById.length;\n this._transitionIndex = new Map();\n for (let i = 0; i < this._transitionsById.length; i++) {\n this._transitionIndex.set(this._transitionsById[i]!, i);\n }\n\n // Precompute masks\n this._needsMask = new Array(this.transitionCount);\n this._inhibitorMask = new Array(this.transitionCount);\n this._consumptionPlaceIds = new Array(this.transitionCount);\n this._cardinalityChecks = new Array(this.transitionCount).fill(null);\n this._hasMatch = new Array(this.transitionCount).fill(false);\n\n const placeToTransitionsList: number[][] = new Array(this.placeCount);\n for (let i = 0; i < this.placeCount; i++) {\n placeToTransitionsList[i] = [];\n }\n\n for (let tid = 0; tid < this.transitionCount; tid++) {\n const t = this._transitionsById[tid]!;\n this._hasMatch[tid] = t.matchSpec !== null;\n const needs = new Uint32Array(this.wordCount);\n const inhibitors = new Uint32Array(this.wordCount);\n\n let needsCardinality = false;\n\n // Input specs\n // CORE-030: the Transition builder stays permissive; the duplicate-input\n // rejection lives here so both executors share it.\n const seenInputPlaces = new Set<string>();\n for (const inSpec of t.inputSpecs) {\n if (seenInputPlaces.has(inSpec.place.name)) {\n throw new Error(\n `Transition '${t.name}' declares two input arcs on place '${inSpec.place.name}'. `\n + 'Duplicate input places have no coherent consumption semantics and are rejected '\n + 'at compile time (CORE-030). Use a single arc with exactly(n) / atLeast(n) instead.'\n );\n }\n seenInputPlaces.add(inSpec.place.name);\n const pid = this._placeIndex.get(inSpec.place.name)!;\n setBit(needs, pid);\n placeToTransitionsList[pid]!.push(tid);\n\n if (inSpec.type !== 'one') {\n needsCardinality = true;\n }\n }\n\n // Build cardinality check if needed\n if (needsCardinality) {\n const pids: number[] = [];\n const reqs: number[] = [];\n for (const inSpec of t.inputSpecs) {\n pids.push(this._placeIndex.get(inSpec.place.name)!);\n reqs.push(requiredCount(inSpec));\n }\n this._cardinalityChecks[tid] = { placeIds: pids, requiredCounts: reqs };\n }\n\n // Read arcs\n for (const arc of t.reads) {\n const pid = this._placeIndex.get(arc.place.name)!;\n setBit(needs, pid);\n placeToTransitionsList[pid]!.push(tid);\n }\n\n // Inhibitor arcs\n for (const arc of t.inhibitors) {\n const pid = this._placeIndex.get(arc.place.name)!;\n setBit(inhibitors, pid);\n placeToTransitionsList[pid]!.push(tid);\n }\n\n // Reset arcs (add to affected transitions)\n for (const arc of t.resets) {\n const pid = this._placeIndex.get(arc.place.name)!;\n placeToTransitionsList[pid]!.push(tid);\n }\n\n // Consumption place IDs (input + reset, deduplicated)\n const consumptionSet = new Set<number>();\n for (const spec of t.inputSpecs) consumptionSet.add(this._placeIndex.get(spec.place.name)!);\n for (const arc of t.resets) consumptionSet.add(this._placeIndex.get(arc.place.name)!);\n this._consumptionPlaceIds[tid] = [...consumptionSet];\n\n this._needsMask[tid] = needs;\n this._inhibitorMask[tid] = inhibitors;\n }\n\n // Build reverse index: deduplicate transition IDs per place\n this._placeToTransitions = new Array(this.placeCount);\n for (let pid = 0; pid < this.placeCount; pid++) {\n this._placeToTransitions[pid] = [...new Set(placeToTransitionsList[pid]!)];\n }\n }\n\n static compile(net: PetriNet): CompiledNet {\n return new CompiledNet(net);\n }\n\n // ==================== Accessors ====================\n\n place(pid: number): Place<any> { return this._placesById[pid]!; }\n transition(tid: number): Transition { return this._transitionsById[tid]!; }\n\n placeId(place: Place<any>): number {\n const id = this._placeIndex.get(place.name);\n if (id === undefined) throw new Error(`Unknown place: ${place.name}`);\n return id;\n }\n\n /**\n * Non-throwing variant of {@link placeId}: `undefined` when the compiled net\n * does not know the place. Lets callers retain tokens on undeclared places\n * (CORE-072) instead of rejecting or dropping them.\n */\n tryPlaceId(place: Place<any>): number | undefined {\n return this._placeIndex.get(place.name);\n }\n\n transitionId(t: Transition): number {\n const id = this._transitionIndex.get(t);\n if (id === undefined) throw new Error(`Unknown transition: ${t.name}`);\n return id;\n }\n\n affectedTransitions(pid: number): readonly number[] {\n return this._placeToTransitions[pid]!;\n }\n\n consumptionPlaceIds(tid: number): readonly number[] {\n return this._consumptionPlaceIds[tid]!;\n }\n\n cardinalityCheck(tid: number): CardinalityCheck | null {\n return this._cardinalityChecks[tid]!;\n }\n\n hasMatch(tid: number): boolean {\n return this._hasMatch[tid]!;\n }\n\n // ==================== Enablement Check ====================\n\n /**\n * Two-phase bitmap enablement check for a transition:\n * 1. **Presence check**: verifies all required places (inputs + reads) have tokens\n * via `containsAll(snapshot, needsMask)`.\n * 2. **Inhibitor check**: verifies no inhibitor places have tokens\n * via `!intersects(snapshot, inhibitorMask)`.\n *\n * This is a necessary but not sufficient condition — cardinality and ν-net match\n * checks are performed separately by the executor for transitions that pass this\n * fast path.\n */\n canEnableBitmap(tid: number, markingSnapshot: Uint32Array): boolean {\n // All needed places present?\n if (!containsAll(markingSnapshot, this._needsMask[tid]!)) return false;\n // No inhibitors active?\n if (intersects(markingSnapshot, this._inhibitorMask[tid]!)) return false;\n return true;\n }\n}\n\n// ==================== Bitmap Helpers ====================\n\nexport function setBit(arr: Uint32Array, bit: number): void {\n arr[bit >>> WORD_SHIFT]! |= (1 << (bit & BIT_MASK));\n}\n\nexport function clearBit(arr: Uint32Array, bit: number): void {\n arr[bit >>> WORD_SHIFT]! &= ~(1 << (bit & BIT_MASK));\n}\n\nexport function testBit(arr: Uint32Array, bit: number): boolean {\n return (arr[bit >>> WORD_SHIFT]! & (1 << (bit & BIT_MASK))) !== 0;\n}\n\n/** Checks if all bits in mask are set in snapshot. */\nexport function containsAll(snapshot: Uint32Array, mask: Uint32Array): boolean {\n for (let i = 0; i < mask.length; i++) {\n const m = mask[i]!;\n if (m === 0) continue;\n const s = i < snapshot.length ? snapshot[i]! : 0;\n // Use >>> 0 to coerce the bitwise AND result to unsigned. Without this,\n // when bit 31 (the sign bit) is set, (s & m) returns a negative signed\n // int32 while m (from Uint32Array) is unsigned, causing a false mismatch.\n if (((s & m) >>> 0) !== m) return false;\n }\n return true;\n}\n\n/** Checks if any bit in mask is set in snapshot. */\nexport function intersects(snapshot: Uint32Array, mask: Uint32Array): boolean {\n for (let i = 0; i < mask.length; i++) {\n const m = mask[i]!;\n if (m === 0) continue;\n if (i < snapshot.length && (snapshot[i]! & m) !== 0) return true;\n }\n return false;\n}\n\n","import type { NetEvent } from './net-event.js';\nimport { eventTransitionName, isFailureEvent } from './net-event.js';\n\n/**\n * Storage for events emitted during Petri net execution.\n */\nexport interface EventStore {\n /** Appends an event to the store. */\n append(event: NetEvent): void;\n\n /** Returns all events in chronological order. */\n events(): readonly NetEvent[];\n\n /** Whether this store is enabled (false = skip event creation). */\n isEnabled(): boolean;\n\n /** Number of events captured. */\n size(): number;\n\n /** Whether no events have been captured. */\n isEmpty(): boolean;\n}\n\n// ==================== Query Helpers ====================\n\n/** Returns events matching a predicate. */\nexport function filterEvents(store: EventStore, predicate: (e: NetEvent) => boolean): NetEvent[] {\n return store.events().filter(predicate);\n}\n\n/** Returns events of a specific type. */\nexport function eventsOfType<T extends NetEvent['type']>(\n store: EventStore,\n type: T,\n): Extract<NetEvent, { type: T }>[] {\n return store.events().filter(e => e.type === type) as Extract<NetEvent, { type: T }>[];\n}\n\n/** Returns all events for a specific transition. */\nexport function transitionEvents(store: EventStore, transitionName: string): NetEvent[] {\n return store.events().filter(e => eventTransitionName(e) === transitionName);\n}\n\n/** Returns all failure events. */\nexport function failures(store: EventStore): NetEvent[] {\n return store.events().filter(isFailureEvent);\n}\n\n// ==================== InMemoryEventStore ====================\n\nexport class InMemoryEventStore implements EventStore {\n private readonly _events: NetEvent[] = [];\n\n append(event: NetEvent): void {\n this._events.push(event);\n }\n\n events(): readonly NetEvent[] {\n return this._events;\n }\n\n isEnabled(): boolean {\n return true;\n }\n\n size(): number {\n return this._events.length;\n }\n\n isEmpty(): boolean {\n return this._events.length === 0;\n }\n\n /** Clears all stored events. */\n clear(): void {\n this._events.length = 0;\n }\n}\n\n// ==================== NoopEventStore ====================\n\nconst EMPTY: readonly NetEvent[] = Object.freeze([]);\n\nclass NoopEventStoreImpl implements EventStore {\n append(_event: NetEvent): void {\n // No-op\n }\n\n events(): readonly NetEvent[] {\n return EMPTY;\n }\n\n isEnabled(): boolean {\n return false;\n }\n\n size(): number {\n return 0;\n }\n\n isEmpty(): boolean {\n return true;\n }\n}\n\nconst NOOP_INSTANCE = new NoopEventStoreImpl();\n\n/** Returns a no-op event store that discards all events. */\nexport function noopEventStore(): EventStore {\n return NOOP_INSTANCE;\n}\n\n/** Creates a new in-memory event store. */\nexport function inMemoryEventStore(): InMemoryEventStore {\n return new InMemoryEventStore();\n}\n","/**\n * @module match-engine\n *\n * ν-net binding selection — the canonical name-correlation algorithm shared by\n * both executor backends (spec NU-020).\n *\n * A transition carrying a {@link import('../core/match-spec.js').MatchSpec} is\n * enabled only when there is a single name present in every correlated input\n * with its required token count. The two executors differ only in how they read\n * tokens (`Marking` FIFO queues vs the precompiled per-place arrays); the\n * *selection* — which name satisfies the join, and the deterministic tie-break —\n * lives here so it is identical across backends and matches the Rust/Java ports.\n */\nimport type { Token } from '../core/token.js';\nimport type { Place } from '../core/place.js';\nimport type { Transition } from '../core/transition.js';\nimport type { NameId } from '../core/name.js';\nimport type { KeyFn } from '../core/match-spec.js';\n\n/** Per-correlated-input statistic for one name: count + oldest timestamp (ms). */\nexport interface NameStat {\n count: number;\n minCreatedAt: number;\n}\n\n/**\n * Selects the satisfying correlation name across all correlated inputs, or\n * `null` when no single name is present in every input with at least its\n * required count.\n *\n * Determinism (NU-020): among satisfying names, pick the one whose oldest\n * matched token (minimum `createdAt` across the correlated inputs) is earliest;\n * break remaining ties by {@link NameId} order. Byte-identical to the Rust\n * `select_match_name` and the Java `selectMatchName`.\n *\n * The `NameId` tie-break uses JS string `<` (UTF-16 code-unit order). This is\n * byte-identical to the Java (`String.compareTo`) and Rust (UTF-8 code-point)\n * ports for ASCII/BMP names — which covers every executor-minted name\n * (`\"{transition}#{n}\"`). For supplementary-plane code points in user-supplied\n * correlation keys, Rust's UTF-8 order can differ from this UTF-16 order; NU-001\n * requires only per-implementation consistency, which holds.\n */\nexport function selectMatchName(\n perPlace: ReadonlyArray<Map<NameId, NameStat>>,\n requireds: readonly number[],\n): NameId | null {\n if (perPlace.length === 0) return null;\n // Seed candidate names from the smallest index; result is seed-independent.\n let seed = 0;\n for (let i = 1; i < perPlace.length; i++) {\n if (perPlace[i]!.size < perPlace[seed]!.size) seed = i;\n }\n\n let bestName: NameId | null = null;\n let bestTs = 0;\n for (const [name, stat] of perPlace[seed]!) {\n if (stat.count < requireds[seed]!) continue;\n let repTs = Number.MAX_SAFE_INTEGER;\n let satisfied = true;\n for (let j = 0; j < perPlace.length; j++) {\n const s = perPlace[j]!.get(name);\n if (s === undefined || s.count < requireds[j]!) {\n satisfied = false;\n break;\n }\n repTs = Math.min(repTs, s.minCreatedAt);\n }\n if (!satisfied) continue;\n const take = bestName === null || repTs < bestTs || (repTs === bestTs && name < bestName);\n if (take) {\n bestName = name;\n bestTs = repTs;\n }\n }\n return bestName;\n}\n\n/**\n * Builds a `name → {count, minCreatedAt}` index over the given tokens. Tokens\n * whose projected name is `undefined`/`null` are skipped — they carry no\n * correlation name and can never participate in a match (NU-021).\n */\nexport function buildNameIndex(\n tokens: readonly Token<any>[],\n key: KeyFn,\n): Map<NameId, NameStat> {\n const index = new Map<NameId, NameStat>();\n for (const token of tokens) {\n const name = key(token.value);\n if (name === undefined || name === null) continue;\n const ts = token.createdAt;\n const prev = index.get(name);\n if (prev) {\n prev.count++;\n if (ts < prev.minCreatedAt) prev.minCreatedAt = ts;\n } else {\n index.set(name, { count: 1, minCreatedAt: ts });\n }\n }\n return index;\n}\n\n/**\n * Required token count for `placeName` from the transition's input spec\n * (1 for one/all, n for exactly(n), m for at-least(m)).\n */\nexport function requiredFor(t: Transition, placeName: string): number {\n for (const inSpec of t.inputSpecs) {\n if (inSpec.place.name === placeName) {\n if (inSpec.type === 'exactly') return inSpec.count;\n if (inSpec.type === 'at-least') return inSpec.minimum;\n return 1;\n }\n }\n return 1;\n}\n\n/**\n * Finds the correlation name satisfying `t`'s `MatchSpec`, or `null` if the join\n * is not enabled (NU-020). `getTokens` abstracts the token source so both\n * executors share this code (Marking queues vs precompiled per-place arrays).\n */\nexport function findBinding(\n t: Transition,\n getTokens: (place: Place<any>) => readonly Token<any>[],\n): NameId | null {\n const ms = t.matchSpec;\n if (!ms) return null;\n const perPlace: Map<NameId, NameStat>[] = [];\n const requireds: number[] = [];\n for (const k of ms.keys) {\n perPlace.push(buildNameIndex(getTokens(k.place), k.key));\n requireds.push(requiredFor(t, k.place.name));\n }\n return selectMatchName(perPlace, requireds);\n}\n\n// ==================== Incremental matcher (NU-020 performance) ====================\n//\n// `selectMatchName` rebuilds a full name index over every token on each call, so\n// draining N ready correlation groups costs O(N²). `IncrementalMatcher` maintains\n// the per-input name index (a FIFO min-queue of timestamps per name) plus a\n// lazy-deletion min-heap of ready names ordered by the same `(oldest_ts, name)`\n// key, so `add`/`consume` are O(log n) and `best()` is an O(1) read. Used only\n// for `one`/`exactly` correlated inputs that are consumed by no other transition\n// (so the cache can't desync); otherwise the executor falls back to\n// `selectMatchName`. Ported byte-identically from the Rust `IncrementalMatcher`.\n\n/**\n * FIFO queue of timestamps with O(1)-amortized min-query (two-stack method).\n * Mirrors the executor's FIFO-within-name removal (`popFront` drops the\n * earliest-inserted token) while answering \"oldest remaining timestamp\". A plain\n * min-heap would diverge from FIFO order when timestamps are not insertion-ordered.\n */\nclass MinQueue {\n private readonly inStack: number[] = [];\n private readonly inMin: number[] = [];\n private readonly outStack: number[] = [];\n private readonly outMin: number[] = [];\n\n get size(): number {\n return this.inStack.length + this.outStack.length;\n }\n\n pushBack(v: number): void {\n this.inStack.push(v);\n const top = this.inMin.length;\n this.inMin.push(top ? Math.min(this.inMin[top - 1]!, v) : v);\n }\n\n popFront(): void {\n if (this.outStack.length === 0) {\n while (this.inStack.length) {\n const v = this.inStack.pop()!;\n this.inMin.pop();\n this.outStack.push(v);\n const top = this.outMin.length;\n this.outMin.push(top ? Math.min(this.outMin[top - 1]!, v) : v);\n }\n }\n this.outStack.pop();\n this.outMin.pop();\n }\n\n min(): number {\n const a = this.inMin.length ? this.inMin[this.inMin.length - 1]! : Infinity;\n const b = this.outMin.length ? this.outMin[this.outMin.length - 1]! : Infinity;\n return a < b ? a : b;\n }\n}\n\ninterface ReadyEntry {\n ts: number;\n name: NameId;\n}\n\n/** Binary min-heap of ready names keyed by `(ts, name)` — the `select_match_name` order. */\nclass ReadyHeap {\n private readonly a: ReadyEntry[] = [];\n\n get size(): number {\n return this.a.length;\n }\n\n peek(): ReadyEntry | undefined {\n return this.a[0];\n }\n\n private less(x: ReadyEntry, y: ReadyEntry): boolean {\n return x.ts < y.ts || (x.ts === y.ts && x.name < y.name);\n }\n\n push(e: ReadyEntry): void {\n const a = this.a;\n a.push(e);\n let i = a.length - 1;\n while (i > 0) {\n const p = (i - 1) >> 1;\n if (this.less(a[i]!, a[p]!)) {\n const tmp = a[i]!;\n a[i] = a[p]!;\n a[p] = tmp;\n i = p;\n } else break;\n }\n }\n\n pop(): void {\n const a = this.a;\n const last = a.pop()!;\n if (a.length === 0) return;\n a[0] = last;\n let i = 0;\n const n = a.length;\n for (;;) {\n const l = 2 * i + 1;\n const r = 2 * i + 2;\n let m = i;\n if (l < n && this.less(a[l]!, a[m]!)) m = l;\n if (r < n && this.less(a[r]!, a[m]!)) m = r;\n if (m === i) break;\n const tmp = a[i]!;\n a[i] = a[m]!;\n a[m] = tmp;\n i = m;\n }\n }\n}\n\n/**\n * Incremental equivalent of {@link selectMatchName} for `one`/`exactly`\n * correlated inputs (fixed consume count). {@link best} is an O(1) read and, for\n * any sequence of `add`/`consume`, returns exactly the name `selectMatchName`\n * would — verified by `incremental-matcher.test.ts`.\n *\n * While ready names are pushed in non-decreasing `(rep_ts, name)` order — the\n * canonical fork/join (siblings carry the fork's monotonic timestamp) or any\n * time-ordered seed — a plain FIFO (index-based deque, never `shift()`) is a\n * valid min-PQ, so `add`/`consume` are amortized O(1). The first out-of-order\n * push migrates the deque into the lazy-deletion {@link ReadyHeap} (`heaped`),\n * thereafter O(log n) — the proven fallback. The fast path is re-entered whenever\n * the structure fully empties.\n */\nexport class IncrementalMatcher {\n private readonly ts: Array<Map<NameId, MinQueue>>;\n /** Monotonic fast path: ascending `(rep_ts, name)`; `fifo[fifoHead]` (after\n * `cleanTop`) is the min. Active while `!heaped`. Advance `fifoHead` instead of\n * `shift()` (O(1)); reset when the head catches the length. */\n private readonly fifo: ReadyEntry[] = [];\n private fifoHead = 0;\n /** Largest entry appended to `fifo` in the current monotonic run. */\n private maxPushed: ReadyEntry | null = null;\n /** Once an out-of-order push migrates `fifo` into `heap`. */\n private heaped = false;\n private readonly heap = new ReadyHeap();\n private readonly ready = new Map<NameId, number>();\n\n constructor(private readonly requireds: readonly number[]) {\n this.ts = requireds.map(() => new Map<NameId, MinQueue>());\n }\n\n /** Add one token carrying `name` at `createdAt` to input `i`. */\n add(i: number, name: NameId, createdAt: number): void {\n let q = this.ts[i]!.get(name);\n if (!q) {\n q = new MinQueue();\n this.ts[i]!.set(name, q);\n }\n q.pushBack(createdAt);\n this.refresh(name);\n this.cleanTop();\n }\n\n /** Remove the `required` earliest-inserted tokens of `name` from every input (NU-020). */\n consume(name: NameId): void {\n for (let i = 0; i < this.requireds.length; i++) {\n const q = this.ts[i]!.get(name);\n if (q) {\n for (let r = 0; r < this.requireds[i]!; r++) q.popFront();\n if (q.size === 0) this.ts[i]!.delete(name);\n }\n }\n this.refresh(name);\n this.cleanTop();\n }\n\n /** The name `selectMatchName` would pick, or `null`. O(1) read. */\n best(): NameId | null {\n if (this.heaped) {\n const top = this.heap.peek();\n return top ? top.name : null;\n }\n return this.fifoHead < this.fifo.length ? this.fifo[this.fifoHead]!.name : null;\n }\n\n /**\n * Route a ready name's `(rep, name)` to the active structure: append to the\n * FIFO in O(1) while pushes stay non-decreasing; on the first inversion,\n * migrate the FIFO into the heap and stay heap-backed.\n */\n private pushReady(rep: number, name: NameId): void {\n const entry: ReadyEntry = { ts: rep, name };\n if (this.heaped) {\n this.heap.push(entry);\n return;\n }\n const max = this.maxPushed;\n const monotonic = max === null || rep > max.ts || (rep === max.ts && name >= max.name);\n if (monotonic) {\n this.maxPushed = entry;\n this.fifo.push(entry);\n } else {\n this.heaped = true;\n for (let i = this.fifoHead; i < this.fifo.length; i++) this.heap.push(this.fifo[i]!);\n this.fifo.length = 0;\n this.fifoHead = 0;\n this.heap.push(entry);\n }\n }\n\n private repTs(name: NameId): number | null {\n let rep = Infinity;\n for (let i = 0; i < this.requireds.length; i++) {\n const q = this.ts[i]!.get(name);\n if (!q || q.size < this.requireds[i]!) return null;\n const m = q.min();\n if (m < rep) rep = m;\n }\n return rep;\n }\n\n private refresh(name: NameId): void {\n const rep = this.repTs(name);\n if (rep !== null) {\n if (this.ready.get(name) !== rep) {\n this.ready.set(name, rep);\n this.pushReady(rep, name);\n }\n } else {\n this.ready.delete(name);\n }\n }\n\n private cleanTop(): void {\n if (this.heaped) {\n for (;;) {\n const top = this.heap.peek();\n if (top && this.ready.get(top.name) !== top.ts) this.heap.pop();\n else break;\n }\n if (this.heap.size === 0) {\n this.heaped = false;\n this.maxPushed = null;\n }\n } else {\n while (this.fifoHead < this.fifo.length) {\n const top = this.fifo[this.fifoHead]!;\n if (this.ready.get(top.name) !== top.ts) this.fifoHead++;\n else break;\n }\n if (this.fifoHead >= this.fifo.length) {\n // fully drained: reset the backing array + start a fresh monotonic run\n this.fifo.length = 0;\n this.fifoHead = 0;\n this.maxPushed = null;\n }\n }\n }\n\n /** Test-only: has the matcher fallen back from the FIFO fast path to the heap? */\n isHeaped(): boolean {\n return this.heaped;\n }\n}\n","/**\n * Error thrown when a transition's output doesn't satisfy its declared Out spec.\n */\nexport class OutViolationError extends Error {\n constructor(message: string) {\n super(message);\n this.name = 'OutViolationError';\n }\n}\n","/**\n * @module executor-support\n *\n * Output validation and timeout production for the Petri net executor.\n *\n * **Output validation algorithm**: Recursively walks the declared Out spec tree,\n * checking that the action's produced tokens match the structure:\n * - Place/ForwardInput: place must be in the produced set\n * - AND: all children must be satisfied (conjunction)\n * - XOR: exactly 1 child must be satisfied (throws OutViolationError for 0 or 2+)\n * - Timeout: delegates to child spec\n *\n * Returns the set of \"claimed\" place names on success, or null if unsatisfied.\n *\n * **Timeout production**: When an action exceeds its timeout, produces default\n * tokens to the timeout branch's output places, enabling the net to continue.\n */\nimport type { Out } from '../core/out.js';\nimport type { Transition } from '../core/transition.js';\nimport type { TransitionContext } from '../core/transition-context.js';\nimport { OutViolationError } from './out-violation-error.js';\n\n/**\n * Invokes a transition action, converting a synchronous throw or a non-Promise\n * return into a rejected promise.\n *\n * Actions are invoked inline on the orchestrator loop, so an action that throws\n * before returning its promise (an undeclared-place access, a bad closure) would\n * otherwise unwind out of the firing loop and take the whole executor with it.\n * Routing it through a rejected promise makes it flow the same contained path as an\n * asynchronously-reported failure. A `null`/non-thenable return (a mis-typed action\n * that forgot `async`) is likewise rejected rather than silently treated as complete.\n */\nexport function executeAction(t: Transition, context: TransitionContext): Promise<void> {\n try {\n const stage = t.action(context) as unknown;\n if (stage == null || typeof (stage as { then?: unknown }).then !== 'function') {\n return Promise.reject(new Error(\n `'${t.name}': action returned null/non-thenable instead of a Promise`));\n }\n return Promise.resolve(stage as Promise<void>);\n } catch (err) {\n return Promise.reject(err);\n }\n}\n\n/**\n * Swallows a failure thrown by a user {@link import('../event/event-store.js').EventStore}\n * from `append`, logging it once.\n *\n * An event emission is observation, not control flow: a store that throws must not\n * unwind the orchestrator loop or escape a failure handler. Each executor wraps its\n * single `emitEvent` choke point in a try/catch that routes here.\n *\n * @param when short description of what was being emitted, for the log message\n * @param err the throwable the store raised\n */\nexport function swallowEventStoreFailure(when: string, err: unknown): void {\n console.warn(\n `libpetri: EventStore.append threw while emitting ${when}; the event is dropped`, err);\n}\n\n/**\n * Default deadline-enforcement tolerance, in milliseconds.\n *\n * A transition with a hard deadline (`deadline()` / `window()`) is force-disabled only once its\n * elapsed time exceeds `latest + DEADLINE_TOLERANCE_MS`, absorbing timer-resolution and scheduling\n * jitter (TIME-013). Shared by both executors and matched by the Java and Rust runtimes so\n * deadline enforcement behaves identically across languages. Configurable per executor via the\n * `deadlineToleranceMs` option.\n *\n * `exact()` timing is enforced *softly* — an exact transition fires at the first opportunity at/after\n * its target time and is never force-disabled, so this tolerance does not gate its firing (TIME-006).\n */\nexport const DEADLINE_TOLERANCE_MS = 5;\n\n/**\n * [IO-015] output validation as an **exact-explanation search**.\n *\n * An *assignment* picks exactly one child at each `xor` it reaches; subtrees under\n * an unselected child are never evaluated. Each assignment claims a set of places,\n * and validation succeeds iff **exactly one** assignment's claim *equals* the\n * produced set.\n *\n * Returns that claim on success and throws `OutViolationError` otherwise — whether\n * nothing explains the write or two or more branches do.\n *\n * Equality — rather than \"every obligation was satisfied\" — is what makes a token\n * written to a declared place outside the selected branch a violation instead of a\n * silent deposit. It also removes the need for a subsumption tie-break:\n * `xor(and(A,B,C), and(A,B))` with A, B, C produced has exactly one *exact* claim.\n *\n * Being a search rather than an eager walk is what makes `and` genuinely unordered\n * ([IO-015] AC8): the old version short-circuited on its first unsatisfied child and\n * let an inner `xor` throw before an enclosing one could try a sibling, so the same\n * write set could pass or fail depending on declaration order.\n */\nexport function validateOutSpec(\n tName: string,\n spec: Out,\n producedPlaceNames: Set<string>,\n): Set<string> {\n // Equality is tested against the produced places the spec could name at all.\n // A token produced to a place the spec never mentions is [CORE-072]'s business\n // — retained and reported, not an [IO-015] violation — so it must not make the\n // claim sets unmatchable.\n const named = specNames(spec);\n let relevant = 0;\n for (const name of producedPlaceNames) {\n if (named.has(name)) relevant++;\n }\n\n const exact: Set<string>[] = [];\n for (const claim of claimsWithin(spec, producedPlaceNames)) {\n // Every claim is a subset of the produced set by construction (a leaf only\n // claims a place that was produced), so equal size means equal set.\n if (claim.size === relevant) {\n exact.push(claim);\n if (exact.length > 1) break;\n }\n }\n const wrote = [...producedPlaceNames].filter(n => named.has(n)).sort();\n if (exact.length === 0) {\n throw new OutViolationError(\n `'${tName}': output does not match the declared spec - produced {${wrote.join(', ')}}, ` +\n `which no single branch of the spec claims exactly`\n );\n }\n if (exact.length > 1) {\n throw new OutViolationError(\n `'${tName}': ambiguous output - {${wrote.join(', ')}} is claimed by more than one branch`\n );\n }\n return exact[0]!;\n}\n\n/**\n * Collapses identical claims, keeping at most two of each.\n *\n * Validation only needs to distinguish \"no assignment\", \"exactly one\" and \"more\n * than one\", so a third assignment claiming an already-seen set carries no\n * information. Without this the `and` join is O(2^k) in the number of `xor`\n * children — 21us at k=8, seconds at k=20, on a path that runs every firing.\n * With it the working set is bounded by the number of DISTINCT claim subsets,\n * which is at most 2^|produced|; the produced set is what the action actually\n * wrote, and is small.\n */\nfunction capMultiplicity(claims: Set<string>[]): Set<string>[] {\n if (claims.length < 3) return claims;\n const seen = new Map<string, number>();\n const out: Set<string>[] = [];\n for (const claim of claims) {\n const key = [...claim].sort().join('\\u0000');\n const n = seen.get(key) ?? 0;\n if (n >= 2) continue;\n seen.set(key, n + 1);\n out.push(claim);\n }\n return out;\n}\n\n/** Every place named anywhere in the spec tree, memoised per spec object. */\nconst specNamesCache = new WeakMap<object, Set<string>>();\nfunction specNames(spec: Out): Set<string> {\n const hit = specNamesCache.get(spec as object);\n if (hit !== undefined) return hit;\n const names = new Set<string>();\n const walk = (node: Out): void => {\n switch (node.type) {\n case 'place': names.add(node.place.name); break;\n case 'forward-input': names.add(node.to.name); break;\n case 'timeout': walk(node.child); break;\n case 'xor':\n case 'and': for (const c of node.children) walk(c); break;\n }\n };\n walk(spec);\n specNamesCache.set(spec as object, names);\n return names;\n}\n\n/**\n * Claims of every assignment whose claim is a subset of `produced`.\n *\n * The subset restriction is the pruning that keeps this linear in practice: a leaf\n * naming a place that was not produced yields nothing, so a `xor` branch dies as soon\n * as it claims something unwritten, and an `and` dies with any unsatisfiable child.\n * Branching survives only where several `xor` children are simultaneously consistent\n * with what was produced — the ambiguous case, which is rejected anyway.\n */\nfunction claimsWithin(spec: Out, produced: Set<string>): Set<string>[] {\n switch (spec.type) {\n case 'place':\n return produced.has(spec.place.name) ? [new Set([spec.place.name])] : [];\n\n case 'forward-input':\n return produced.has(spec.to.name) ? [new Set([spec.to.name])] : [];\n\n case 'timeout':\n return claimsWithin(spec.child, produced);\n\n case 'xor': {\n const out: Set<string>[] = [];\n for (const child of spec.children) {\n for (const claim of claimsWithin(child, produced)) out.push(claim);\n }\n return capMultiplicity(out);\n }\n\n case 'and': {\n // Unordered: the children are a set of obligations, so this is a join over\n // their claim sets and the result cannot depend on their declaration order.\n let acc: Set<string>[] = [new Set()];\n for (const child of spec.children) {\n const childClaims = claimsWithin(child, produced);\n if (childClaims.length === 0) return []; // no assignment can satisfy this AND\n const next: Set<string>[] = [];\n for (const partial of acc) {\n for (const claim of childClaims) {\n const merged = new Set(partial);\n for (const name of claim) merged.add(name);\n next.push(merged);\n }\n }\n acc = capMultiplicity(next);\n }\n return acc;\n }\n }\n}\n\n/**\n * Produces default tokens to the timeout branch's output places when an action\n * exceeds its timeout. Walks the Out spec tree recursively:\n *\n * - **Place**: produces `null` (the timeout sentinel value).\n * - **ForwardInput**: forwards *all* tokens consumed from the `from` place to the\n * output place, in consumption order — one output token per consumed token, so a\n * batched input spec (`all()` / `exactly(n)`) conserves its tokens on timeout.\n * - **AND**: recurses into all children (all branches get tokens).\n * - **XOR**: disallowed — timeout cannot choose a branch non-deterministically.\n * - **Timeout**: disallowed — nested timeouts would create ambiguous recovery paths.\n *\n * Writes through {@link TransitionContext.outputToHarvest} rather than `output(...)`:\n * by this point the context has been detached, so the ordinary write target is closed\n * and only the harvest collector still reaches the marking.\n */\nexport function produceTimeoutOutput(context: TransitionContext, timeoutChild: Out): void {\n switch (timeoutChild.type) {\n case 'place':\n context.outputToHarvest(timeoutChild.place, null);\n break;\n case 'forward-input': {\n // Forward *every* token consumed from `from`, not just the first: a batched\n // input spec (`all()`, `exactly(n)`, `atLeast(n)`) consumes N tokens, and\n // re-emitting only one would silently destroy N-1 of them on the retry path.\n // `inputs()` is the batched accessor and preserves consumption (FIFO) order;\n // the singular `input()` throws outright when the place yielded != 1 token.\n for (const value of context.inputs(timeoutChild.from)) {\n context.outputToHarvest(timeoutChild.to, value);\n }\n break;\n }\n case 'and':\n for (const child of timeoutChild.children) {\n produceTimeoutOutput(context, child);\n }\n break;\n case 'xor':\n throw new Error('XOR not allowed in timeout child');\n case 'timeout':\n throw new Error('Nested Timeout not allowed');\n }\n}\n","/**\n * @module bitmap-net-executor\n *\n * Async bitmap-based executor for Typed Coloured Time Petri Nets.\n *\n * **Execution loop phases** (per cycle):\n * 1. Process completed transitions — collect outputs, validate against Out specs\n * 2. Process external events — inject tokens from EnvironmentPlaces\n * 3. Update dirty transitions — re-evaluate enablement for transitions whose\n * input/inhibitor/read places changed (bitmap-based dirty set tracking)\n * 4. Fire ready transitions — sorted by priority (desc) then FIFO enablement time\n * 5. Await work — sleep until an action completes, a timer fires, or an external event arrives\n *\n * **Concurrency model**: Single-threaded JS event loop. No locks or CAS needed.\n * Multiple transitions execute concurrently via Promises (actions return Promise<void>).\n * Only the orchestrator mutates marking state — actions communicate via TokenOutput.\n *\n * **Bitmap strategy**: Places are tracked as bits in Uint32Array words. Enablement\n * checks use bitwise AND/OR for O(W) where W = ceil(numPlaces/32). A dirty set\n * bitmap tracks which transitions need re-evaluation, avoiding O(T) scans per cycle.\n *\n * @see CompiledNet for the precomputed bitmap masks and reverse indices\n */\nimport type { PetriNet } from '../core/petri-net.js';\nimport type { Place, EnvironmentPlace } from '../core/place.js';\nimport type { Token } from '../core/token.js';\nimport type { Transition } from '../core/transition.js';\nimport type { EventStore } from '../event/event-store.js';\nimport type { NetEvent } from '../event/net-event.js';\nimport type { PetriNetExecutor, RunTimeoutPolicy } from './petri-net-executor.js';\nimport { tokenOf } from '../core/token.js';\nimport { TokenInput } from '../core/token-input.js';\nimport { TokenOutput } from '../core/token-output.js';\nimport { TransitionContext } from '../core/transition-context.js';\nimport { noopEventStore } from '../event/event-store.js';\nimport { CompiledNet, WORD_SHIFT, BIT_MASK, setBit, clearBit } from './compiled-net.js';\nimport { Marking, type PredicateSpec } from './marking.js';\nimport { findBinding, IncrementalMatcher } from './match-engine.js';\nimport { keyForPlace } from '../core/match-spec.js';\nimport { nameId } from '../core/name.js';\nimport { validateOutSpec, produceTimeoutOutput, executeAction, swallowEventStoreFailure, DEADLINE_TOLERANCE_MS } from './executor-support.js';\nimport { earliest as timingEarliest, latest as timingLatest, hasDeadline as timingHasDeadline } from '../core/timing.js';\n\n/** Tolerance for JS timer jitter (setTimeout resolution ~1-4ms). */\n// Tolerance for deadline enforcement to account for Node.js event loop timer jitter.\ninterface InFlightTransition {\n promise: Promise<void>;\n context: TransitionContext;\n consumed: Token<any>[];\n startMs: number;\n resolve: () => void;\n error?: unknown;\n}\n\ninterface ExternalEvent<T = any> {\n place: Place<T>;\n token: Token<T>;\n resolve: (value: boolean) => void;\n reject: (err: Error) => void;\n}\n\nexport interface BitmapNetExecutorOptions {\n eventStore?: EventStore;\n environmentPlaces?: Set<EnvironmentPlace<any>>;\n /** Provides execution context data for each transition firing. */\n executionContextProvider?: (transitionName: string, consumed: Token<any>[]) => Map<string, unknown>;\n /**\n * Grace band (ms) beyond a hard deadline (`deadline()` / `window()`) before a transition is\n * force-disabled with a `transition-timed-out` event (TIME-013). Defaults to {@link DEADLINE_TOLERANCE_MS}\n * (5ms); `0` gives strict enforcement. Must be non-negative. Does not affect `exact()` transitions,\n * which are enforced softly (TIME-006).\n */\n deadlineToleranceMs?: number;\n}\n\n/**\n * Async bitmap-based executor for Coloured Time Petri Nets.\n *\n * Single-threaded JS model: no CAS needed, direct array writes.\n * Actions return Promise<void> — multiple in-flight actions are naturally concurrent.\n *\n * @remarks\n * **Deadline enforcement**: Transitions with finite deadlines (`deadline`, `window`, `exact`)\n * are checked in `enforceDeadlines()`, called from the main loop only when `hasAnyDeadlines`\n * is true (precomputed at construction). If a transition has been enabled longer than\n * `latest(timing)`, it is forcibly disabled and a `TransitionTimedOut` event is emitted.\n * The `awaitWork()` timer also schedules wake-ups for approaching deadlines, not just\n * earliest firing times.\n *\n * **Constructor precomputation**: `hasAnyDeadlines`, `allImmediate`/`allSamePriority`,\n * and `eventStoreEnabled` are computed once to avoid per-cycle overhead. Safe because\n * `isEnabled()` is constant and timing/priority are immutable on Transition.\n */\nexport class BitmapNetExecutor implements PetriNetExecutor {\n private readonly compiled: CompiledNet;\n private readonly marking: Marking;\n /** Monotonic source for ν-name minting (ctx.freshName(), NU-010). */\n private freshNameCounter = 0;\n /**\n * ν-net incremental match caches (NU-020): per matched transition, an\n * {@link IncrementalMatcher} kept in lockstep with the marking when the\n * transition is fast-path eligible (every correlated input is `one`/`exactly`,\n * consumed by no other transition, never reset), else `null` → fall back to\n * the O(n) rebuild {@link findBinding}. Turns a draining matched join from\n * O(n²) into O(n log n). Mirrors the precompiled executor and the Rust backends.\n */\n private matchCaches: (IncrementalMatcher | null)[] = [];\n private placeMatchTargets: Array<Array<[number, number]>> = [];\n private readonly eventStore: EventStore;\n private readonly environmentPlaces: Set<string>;\n private readonly hasEnvironmentPlaces: boolean;\n private readonly executionContextProvider?: (transitionName: string, consumed: Token<any>[]) => Map<string, unknown>;\n private readonly startMs: number;\n private readonly hasAnyDeadlines: boolean;\n private readonly allImmediate: boolean;\n private readonly allSamePriority: boolean;\n private readonly eventStoreEnabled: boolean;\n\n // Bitmaps (Uint32Array, direct writes)\n private readonly markingBitmap: Uint32Array;\n private readonly dirtySet: Uint32Array;\n private readonly markingSnapBuffer: Uint32Array;\n private readonly dirtySnapBuffer: Uint32Array;\n private readonly firingSnapBuffer: Uint32Array;\n\n // Orchestrator state\n private readonly enabledAtMs: Float64Array;\n private readonly inFlightFlags: Uint8Array;\n private readonly enabledFlags: Uint8Array;\n /** Precomputed: 1 if transition has a finite deadline, 0 otherwise. */\n private readonly hasDeadlineFlags: Uint8Array;\n /** Precomputed: 1 for exact() transitions — enforced softly, never force-disabled (TIME-006). */\n private readonly isExactFlags: Uint8Array;\n /** Grace band (ms) before a hard deadline force-disables (TIME-013). */\n private readonly deadlineToleranceMs: number;\n private enabledTransitionCount = 0;\n\n // In-flight tracking\n private readonly inFlight = new Map<Transition, InFlightTransition>();\n private readonly inFlightPromises: Promise<void>[] = [];\n private readonly awaitPromises: Promise<void>[] = [];\n\n // Queues\n private readonly completionQueue: Transition[] = [];\n private readonly externalQueue: ExternalEvent[] = [];\n\n // Wake-up mechanism\n private wakeUpResolve: (() => void) | null = null;\n\n // Pre-allocated buffer for fireReadyTransitions() to avoid per-cycle allocation\n private readonly readyBuffer: { tid: number; priority: number; enabledAtMs: number }[] = [];\n\n // Pending reset places for clock-restart detection\n private readonly pendingResetPlaces = new Set<string>();\n /**\n * Undeclared place names already reported (CORE-072 AC4). Keyed by name — TS\n * Place identity is name-based — so a hot loop warns once, not per token.\n */\n private readonly warnedUnknownPlaces = new Set<string>();\n private readonly transitionInputPlaceNames: Map<Transition, Set<string>>;\n\n private running = false;\n private draining = false;\n private closed = false;\n\n constructor(\n net: PetriNet,\n initialTokens: Map<Place<any>, Token<any>[]>,\n options: BitmapNetExecutorOptions = {},\n ) {\n this.compiled = CompiledNet.compile(net);\n this.marking = Marking.from(initialTokens);\n this.eventStore = options.eventStore ?? noopEventStore();\n this.environmentPlaces = new Set(\n [...(options.environmentPlaces ?? [])].map(ep => ep.place.name)\n );\n this.hasEnvironmentPlaces = this.environmentPlaces.size > 0;\n this.executionContextProvider = options.executionContextProvider;\n this.deadlineToleranceMs = options.deadlineToleranceMs ?? DEADLINE_TOLERANCE_MS;\n if (this.deadlineToleranceMs < 0) {\n throw new Error(`Deadline tolerance must be non-negative: ${this.deadlineToleranceMs}`);\n }\n this.startMs = performance.now();\n\n const wordCount = this.compiled.wordCount;\n this.markingBitmap = new Uint32Array(wordCount);\n this.markingSnapBuffer = new Uint32Array(wordCount);\n this.firingSnapBuffer = new Uint32Array(wordCount);\n const dirtyWords = (this.compiled.transitionCount + BIT_MASK) >>> WORD_SHIFT;\n this.dirtySet = new Uint32Array(dirtyWords);\n this.dirtySnapBuffer = new Uint32Array(dirtyWords);\n\n this.enabledAtMs = new Float64Array(this.compiled.transitionCount);\n this.enabledAtMs.fill(-Infinity);\n this.inFlightFlags = new Uint8Array(this.compiled.transitionCount);\n this.enabledFlags = new Uint8Array(this.compiled.transitionCount);\n this.hasDeadlineFlags = new Uint8Array(this.compiled.transitionCount);\n this.isExactFlags = new Uint8Array(this.compiled.transitionCount);\n let anyDeadlines = false;\n let allImm = true;\n let samePrio = true;\n const firstPriority = this.compiled.transitionCount > 0\n ? this.compiled.transition(0).priority : 0;\n for (let tid = 0; tid < this.compiled.transitionCount; tid++) {\n const t = this.compiled.transition(tid);\n if (timingHasDeadline(t.timing)) {\n this.hasDeadlineFlags[tid] = 1;\n anyDeadlines = true;\n }\n if (t.timing.type === 'exact') this.isExactFlags[tid] = 1;\n if (t.timing.type !== 'immediate') allImm = false;\n if (t.priority !== firstPriority) samePrio = false;\n }\n this.hasAnyDeadlines = anyDeadlines;\n this.allImmediate = allImm;\n this.allSamePriority = samePrio;\n this.eventStoreEnabled = this.eventStore.isEnabled();\n\n // Precompute input place names per transition\n this.transitionInputPlaceNames = new Map();\n for (const t of net.transitions) {\n const names = new Set<string>();\n for (const spec of t.inputSpecs) names.add(spec.place.name);\n this.transitionInputPlaceNames.set(t, names);\n }\n\n // CORE-072: the Marking keeps tokens on places the net never declared;\n // report each such place once, matching the precompiled backend's seam.\n for (const [place, tokens] of initialTokens) {\n if (tokens.length > 0 && this.compiled.tryPlaceId(place) === undefined) {\n this.warnUnknownPlace(place, '');\n }\n }\n\n this.initMatchCaches();\n }\n\n /**\n * Builds the ν-net incremental match caches (NU-020). A matched join is\n * fast-path eligible only when every correlated input is `one`/`exactly`, is\n * consumed by no other transition, and is never reset — so the cache can never\n * desync from the marking. Mirrors the precompiled executor.\n */\n private initMatchCaches(): void {\n const compiled = this.compiled;\n const tc = compiled.transitionCount;\n const pc = compiled.placeCount;\n this.matchCaches = new Array(tc).fill(null);\n this.placeMatchTargets = Array.from({ length: pc }, () => []);\n\n let anyMatch = false;\n for (let tid = 0; tid < tc; tid++) {\n if (compiled.hasMatch(tid)) { anyMatch = true; break; }\n }\n if (!anyMatch) return;\n\n const inputConsumers: number[][] = Array.from({ length: pc }, () => []);\n const resetTarget: boolean[] = new Array(pc).fill(false);\n for (let tid = 0; tid < tc; tid++) {\n const t = compiled.transition(tid);\n for (const spec of t.inputSpecs) inputConsumers[compiled.placeId(spec.place)]!.push(tid);\n for (const arc of t.resets) resetTarget[compiled.placeId(arc.place)] = true;\n }\n\n for (let tid = 0; tid < tc; tid++) {\n if (!compiled.hasMatch(tid)) continue;\n const t = compiled.transition(tid);\n const ms = t.matchSpec;\n if (!ms) continue;\n\n const requireds: number[] = [];\n let eligible = true;\n for (const mk of ms.keys) {\n const pid = compiled.placeId(mk.place);\n const spec = t.inputSpecs.find(s => s.place.name === mk.place.name);\n let required: number;\n if (spec?.type === 'one') required = 1;\n else if (spec?.type === 'exactly') required = spec.count;\n else { eligible = false; break; }\n const cons = inputConsumers[pid]!;\n if (resetTarget[pid] || cons.length !== 1 || cons[0] !== tid) { eligible = false; break; }\n requireds.push(required);\n }\n if (!eligible) continue;\n\n const matcher = new IncrementalMatcher(requireds);\n for (let keyIdx = 0; keyIdx < ms.keys.length; keyIdx++) {\n const mk = ms.keys[keyIdx]!;\n const pid = compiled.placeId(mk.place);\n for (const token of this.marking.peekTokens(mk.place)) {\n const name = mk.key(token.value);\n if (name !== undefined && name !== null) matcher.add(keyIdx, name, token.createdAt);\n }\n this.placeMatchTargets[pid]!.push([tid, keyIdx]);\n }\n this.matchCaches[tid] = matcher;\n }\n }\n\n /** Mirror a token added to correlated input `pid` into every fast-path matcher. */\n private cacheAddToken(pid: number, token: Token<any>): void {\n const targets = this.placeMatchTargets[pid];\n if (targets === undefined || targets.length === 0) return;\n const compiled = this.compiled;\n for (const [tid, keyIdx] of targets) {\n const cache = this.matchCaches[tid];\n if (cache == null) continue;\n const t = compiled.transition(tid);\n const mk = t.matchSpec!.keys[keyIdx]!;\n const name = mk.key(token.value);\n if (name !== undefined && name !== null) cache.add(keyIdx, name, token.createdAt);\n }\n }\n\n // ======================== Execution ========================\n\n async run(timeoutMs?: number, onTimeout: RunTimeoutPolicy = 'abandon'): Promise<Marking> {\n if (timeoutMs === undefined) return this.executeLoop();\n\n let timer: ReturnType<typeof setTimeout> | undefined;\n let timedOut = false;\n const timeoutPromise = new Promise<never>((_, reject) => {\n timer = setTimeout(() => {\n timedOut = true;\n reject(new Error('Execution timed out'));\n }, timeoutMs);\n });\n // Held rather than inlined into the race: Promise.race walks away from the\n // loser, it does not cancel it, so the loop needs handling of its own.\n const loop = this.executeLoop();\n try {\n return await Promise.race([loop, timeoutPromise]);\n } finally {\n if (timer !== undefined) clearTimeout(timer);\n if (timedOut) {\n if (onTimeout === 'close') this.close();\n // Nobody is left to observe the abandoned loop's outcome.\n loop.catch(() => {});\n }\n }\n }\n\n private async executeLoop(): Promise<Marking> {\n this.running = true;\n this.emitEvent({\n type: 'execution-started',\n timestamp: Date.now(),\n netName: this.compiled.net.name,\n executionId: this.executionId(),\n });\n\n this.initializeMarkingBitmap();\n this.markAllDirty();\n\n this.emitEvent({\n type: 'marking-snapshot',\n timestamp: Date.now(),\n marking: this.snapshotMarking(),\n });\n\n while (this.running) {\n this.processCompletedTransitions();\n this.processExternalEvents();\n this.updateDirtyTransitions();\n // Single timestamp for this loop iteration: ensures deadline enforcement and\n // firing readiness checks use the same time reference, preventing races where\n // a transition passes the deadline check but is disabled before the fire check.\n const cycleNowMs = performance.now();\n // Deadline enforcement: separate pass over ALL enabled transitions (not just dirty\n // ones), since deadlines tick independently of place changes. Gated by\n // hasAnyDeadlines (O(0) skip for pure immediate nets).\n if (this.hasAnyDeadlines) this.enforceDeadlines(cycleNowMs);\n\n if (this.shouldTerminate()) break;\n\n this.fireReadyTransitions(cycleNowMs);\n // Skip awaitWork() when firing produced dirty bits (e.g., token consumption\n // disabled a conflicting transition). Bounded: without microtask yield no new\n // completions arrive, so the loop converges in at most one extra pass.\n if (this.hasDirtyBits()) continue;\n await this.awaitWork();\n }\n\n this.running = false;\n this.drainPendingExternalEvents();\n\n this.emitEvent({\n type: 'marking-snapshot',\n timestamp: Date.now(),\n marking: this.snapshotMarking(),\n });\n\n this.emitEvent({\n type: 'execution-completed',\n timestamp: Date.now(),\n netName: this.compiled.net.name,\n executionId: this.executionId(),\n totalDurationMs: performance.now() - this.startMs,\n });\n\n return this.marking;\n }\n\n // ======================== Environment Place API ========================\n\n async inject<T>(envPlace: EnvironmentPlace<T>, token: Token<T>): Promise<boolean> {\n if (!this.environmentPlaces.has(envPlace.place.name)) {\n throw new Error(`Place ${envPlace.place.name} is not registered as an environment place`);\n }\n if (this.closed || this.draining) return false;\n\n return new Promise<boolean>((resolve, reject) => {\n this.externalQueue.push({\n place: envPlace.place,\n token,\n resolve,\n reject,\n });\n this.wakeUp();\n });\n }\n\n /** Convenience: inject a raw value (creates token with current timestamp). */\n async injectValue<T>(envPlace: EnvironmentPlace<T>, value: T): Promise<boolean> {\n return this.inject(envPlace, tokenOf(value));\n }\n\n // ======================== Initialize ========================\n\n private initializeMarkingBitmap(): void {\n for (let pid = 0; pid < this.compiled.placeCount; pid++) {\n const place = this.compiled.place(pid);\n if (this.marking.hasTokens(place)) {\n setBit(this.markingBitmap, pid);\n }\n }\n }\n\n private markAllDirty(): void {\n const tc = this.compiled.transitionCount;\n const dirtyWords = this.dirtySet.length;\n for (let w = 0; w < dirtyWords - 1; w++) {\n this.dirtySet[w] = 0xFFFFFFFF;\n }\n if (dirtyWords > 0) {\n const lastWordBits = tc & BIT_MASK;\n this.dirtySet[dirtyWords - 1] = lastWordBits === 0 ? 0xFFFFFFFF : (1 << lastWordBits) - 1;\n }\n }\n\n private shouldTerminate(): boolean {\n if (this.closed) {\n // ENV-013: immediate close — wait for in-flight actions to complete\n return this.inFlight.size === 0 && this.completionQueue.length === 0;\n }\n if (this.hasEnvironmentPlaces) {\n return this.draining\n && this.enabledTransitionCount === 0\n && this.inFlight.size === 0\n && this.completionQueue.length === 0;\n }\n return this.enabledTransitionCount === 0\n && this.inFlight.size === 0\n && this.completionQueue.length === 0;\n }\n\n // ======================== Dirty Set Transitions ========================\n\n private updateDirtyTransitions(): void {\n const nowMs = performance.now();\n\n // Snapshot the marking bitmap into pre-allocated buffer.\n // We need a consistent snapshot because enablement checks read multiple words,\n // and concurrent completions/injections could modify markingBitmap mid-scan.\n const markingSnap = this.markingSnapBuffer;\n markingSnap.set(this.markingBitmap);\n\n // Snapshot-and-clear the dirty set in one pass. New dirty bits set during\n // re-evaluation (e.g., by cascading enablement) are captured in the next cycle.\n const dirtyWords = this.dirtySet.length;\n const dirtySnap = this.dirtySnapBuffer;\n for (let w = 0; w < dirtyWords; w++) {\n dirtySnap[w] = this.dirtySet[w]!;\n this.dirtySet[w] = 0;\n }\n\n // Iterate over set bits using the numberOfTrailingZeros trick.\n for (let w = 0; w < dirtyWords; w++) {\n let word = dirtySnap[w]!;\n while (word !== 0) {\n // Extract lowest set bit index: `word & -word` isolates the lowest set bit,\n // `Math.clz32()` counts leading zeros (0-31), XOR 31 converts to trailing zeros.\n const bit = Math.clz32(word & -word) ^ 31;\n const tid = (w << WORD_SHIFT) | bit;\n word &= word - 1; // clear lowest set bit (Kernighan's trick)\n\n if (tid >= this.compiled.transitionCount) break;\n if (this.inFlightFlags[tid]) continue;\n\n const wasEnabled = this.enabledFlags[tid] !== 0;\n const canNow = this.canEnable(tid, markingSnap);\n\n if (canNow && !wasEnabled) {\n this.enabledFlags[tid] = 1;\n this.enabledTransitionCount++;\n this.enabledAtMs[tid] = nowMs;\n this.emitEvent({\n type: 'transition-enabled',\n timestamp: Date.now(),\n transitionName: this.compiled.transition(tid).name,\n });\n } else if (!canNow && wasEnabled) {\n this.enabledFlags[tid] = 0;\n this.enabledTransitionCount--;\n this.enabledAtMs[tid] = -Infinity;\n } else if (canNow && wasEnabled && this.hasInputFromResetPlace(this.compiled.transition(tid))) {\n this.enabledAtMs[tid] = nowMs;\n this.emitEvent({\n type: 'transition-clock-restarted',\n timestamp: Date.now(),\n transitionName: this.compiled.transition(tid).name,\n });\n }\n }\n }\n\n this.pendingResetPlaces.clear();\n }\n\n /**\n * Checks all enabled transitions with finite deadlines. If a transition has been\n * enabled longer than `latest(timing)`, it is forcibly disabled and a\n * `TransitionTimedOut` event is emitted. Classical TPN semantics require transitions\n * to either fire within their window or become disabled.\n *\n * A 1ms tolerance is applied to account for timer jitter and microtask scheduling\n * delays. Without this, exact-timed transitions (where earliest == latest) would\n * almost always be disabled before they can fire.\n */\n private enforceDeadlines(nowMs: number): void {\n for (let tid = 0; tid < this.compiled.transitionCount; tid++) {\n if (!this.hasDeadlineFlags[tid]) continue; // O(1) skip for non-deadline transitions\n // exact() is enforced softly — it fires at the first opportunity at/after its target and is\n // never force-disabled (TIME-006). Only hard deadlines (deadline()/window()) are reaped here.\n if (this.isExactFlags[tid]) continue;\n if (!this.enabledFlags[tid] || this.inFlightFlags[tid]) continue;\n const t = this.compiled.transition(tid);\n\n const elapsed = nowMs - this.enabledAtMs[tid]!;\n const latestMs = timingLatest(t.timing);\n if (elapsed > latestMs + this.deadlineToleranceMs) {\n this.enabledFlags[tid] = 0;\n this.enabledTransitionCount--;\n this.emitEvent({\n type: 'transition-timed-out',\n timestamp: Date.now(),\n transitionName: t.name,\n deadlineMs: latestMs,\n actualDurationMs: elapsed,\n });\n this.enabledAtMs[tid] = -Infinity;\n }\n }\n }\n\n private canEnable(tid: number, markingSnap: Uint32Array): boolean {\n if (!this.compiled.canEnableBitmap(tid, markingSnap)) return false;\n\n // Cardinality check\n const cardCheck = this.compiled.cardinalityCheck(tid);\n if (cardCheck !== null) {\n for (let i = 0; i < cardCheck.placeIds.length; i++) {\n const pid = cardCheck.placeIds[i]!;\n const required = cardCheck.requiredCounts[i]!;\n const place = this.compiled.place(pid);\n if (this.marking.tokenCount(place) < required) return false;\n }\n }\n\n // ν-net join: a correlation name must satisfy every matched input (NU-020).\n // Fast-path transitions read the maintained matcher (O(1)); the rest rebuild\n // the index (O(n)).\n if (this.compiled.hasMatch(tid)) {\n const cache = this.matchCaches[tid];\n const noBinding = cache != null\n ? cache.best() === null\n : findBinding(this.compiled.transition(tid), p => this.marking.peekTokens(p)) === null;\n if (noBinding) {\n return false;\n }\n }\n\n return true;\n }\n\n private hasInputFromResetPlace(t: Transition): boolean {\n if (this.pendingResetPlaces.size === 0) return false;\n const inputNames = this.transitionInputPlaceNames.get(t);\n if (!inputNames) return false;\n for (const name of this.pendingResetPlaces) {\n if (inputNames.has(name)) return true;\n }\n return false;\n }\n\n // ======================== Firing ========================\n\n private fireReadyTransitions(nowMs: number): void {\n if (this.allImmediate && this.allSamePriority) {\n this.fireReadyImmediate();\n return;\n }\n this.fireReadyGeneral(nowMs);\n }\n\n /**\n * Fast path for nets where all transitions are immediate and same priority.\n * Skips timing checks, sorting, and snapshot buffer — just scan and fire.\n *\n * Uses live `markingBitmap` instead of a snapshot. Safe because\n * `updateBitmapAfterConsumption()` synchronously updates the bitmap before the next\n * iteration. For equal-priority immediate transitions, tid scan order satisfies\n * FIFO-by-enablement-time (all enabled in the same cycle).\n */\n private fireReadyImmediate(): void {\n for (let tid = 0; tid < this.compiled.transitionCount; tid++) {\n if (!this.enabledFlags[tid] || this.inFlightFlags[tid]) continue;\n if (this.canEnable(tid, this.markingBitmap)) {\n this.fireTransitionContained(tid);\n } else {\n this.enabledFlags[tid] = 0;\n this.enabledTransitionCount--;\n this.enabledAtMs[tid] = -Infinity;\n }\n }\n }\n\n private fireReadyGeneral(nowMs: number): void {\n\n // Collect ready transitions into pre-allocated buffer to reduce GC pressure\n const ready = this.readyBuffer;\n ready.length = 0;\n for (let tid = 0; tid < this.compiled.transitionCount; tid++) {\n if (!this.enabledFlags[tid] || this.inFlightFlags[tid]) continue;\n const t = this.compiled.transition(tid);\n const enabledMs = this.enabledAtMs[tid]!;\n const elapsedMs = nowMs - enabledMs;\n const earliestMs = timingEarliest(t.timing);\n if (earliestMs <= elapsedMs) {\n ready.push({ tid, priority: t.priority, enabledAtMs: enabledMs });\n }\n }\n if (ready.length === 0) return;\n\n // Sort: higher priority first, then earlier enablement (FIFO).\n // This defines the deterministic scheduling contract for conflict resolution.\n // We re-sort each cycle rather than maintaining a sorted invariant because\n // enablement times change on clock-restarts (reset arcs), which would require\n // expensive re-insertion. Sorting ≤T entries per cycle is fast enough.\n ready.sort((a, b) => {\n const prioCmp = b.priority - a.priority;\n if (prioCmp !== 0) return prioCmp;\n return a.enabledAtMs - b.enabledAtMs;\n });\n\n // Take a fresh snapshot for re-checking (reuse pre-allocated buffer)\n const freshSnap = this.firingSnapBuffer;\n freshSnap.set(this.markingBitmap);\n for (const entry of ready) {\n const { tid } = entry;\n if (this.enabledFlags[tid] && this.canEnable(tid, freshSnap)) {\n this.fireTransitionContained(tid);\n // Update snapshot after consuming tokens\n freshSnap.set(this.markingBitmap);\n } else {\n this.enabledFlags[tid] = 0;\n this.enabledTransitionCount--;\n this.enabledAtMs[tid] = -Infinity;\n }\n }\n }\n\n /**\n * Fires a transition, containing any synchronous throw to that one firing so it fails\n * only that transition, not the whole run.\n *\n * Without this boundary an unchecked throw raised while a transition fires — a hostile\n * EventStore.append on a token-removed or transition-started emit, or an error thrown while\n * consuming the matched tokens — unwinds out of the orchestrator loop and kills the executor.\n * The transition is instead failed and marked dirty for re-evaluation, the same treatment an\n * asynchronously-reported failure gets. Enablement-phase throws (a key function that\n * throws inside canEnable, before the firing) run outside this boundary and are not contained\n * here.\n *\n * fireTransition removes tokens from the marking before it reconciles the presence\n * bitmap, so a throw inside that window would leave bits asserting tokens that are gone;\n * the recovery re-runs updateBitmapAfterConsumption against the real marking.\n *\n * Unlike the Java runtime there is no VirtualMachineError/LinkageError analogue on the JS\n * side, so every throw is contained here — there is deliberately no fatal-rethrow escape\n * hatch.\n */\n private fireTransitionContained(tid: number): void {\n try {\n this.fireTransition(tid);\n } catch (e) {\n const t = this.compiled.transition(tid);\n if (this.enabledFlags[tid]) {\n this.enabledFlags[tid] = 0;\n this.enabledTransitionCount--;\n this.enabledAtMs[tid] = -Infinity;\n }\n if (this.inFlight.delete(t)) {\n this.inFlightFlags[tid] = 0;\n }\n this.updateBitmapAfterConsumption(tid);\n // Drop the ν fast-path matcher: fireTransition mirrors the matched consume into it\n // before the tokens physically leave the marking, so a throw in that window desyncs\n // it. Nulling it forces the next canEnable/fire to rebuild the binding via findBinding.\n this.matchCaches[tid] = null;\n const err = e instanceof Error ? e : new Error(String(e));\n this.emitEvent({\n type: 'transition-failed',\n timestamp: Date.now(),\n transitionName: t.name,\n errorMessage: err.message,\n exceptionType: err.name,\n stack: err.stack,\n });\n this.markTransitionDirty(tid);\n }\n }\n\n private fireTransition(tid: number): void {\n const t = this.compiled.transition(tid);\n const inputs = new TokenInput();\n const consumed: Token<any>[] = [];\n\n // Consume tokens based on input specs with cardinality.\n // ν-net join: resolve the correlation name once; correlated inputs consume\n // the name-matched tokens (name equality — NU-021).\n const ms = t.matchSpec;\n const cache = ms ? this.matchCaches[tid] : null;\n const chosen = ms\n ? (cache != null ? cache.best() : findBinding(t, p => this.marking.peekTokens(p)))\n : null;\n // Mirror the matched consume into the fast-path matcher (the only path by\n // which tokens leave this join's correlated inputs) before the marking changes.\n if (cache != null && chosen !== null) cache.consume(chosen);\n\n for (const inSpec of t.inputSpecs) {\n const keyFn = ms ? keyForPlace(ms, inSpec.place.name) : undefined;\n // Name-equality predicate when correlated; otherwise a plain FIFO consume.\n let spec: PredicateSpec;\n if (keyFn && chosen !== null) {\n spec = {\n place: inSpec.place,\n predicate: (v: any) => keyFn(v) === chosen,\n };\n } else {\n spec = inSpec;\n }\n\n let toConsume: number;\n switch (inSpec.type) {\n case 'one': toConsume = 1; break;\n case 'exactly': toConsume = inSpec.count; break;\n case 'all':\n case 'at-least':\n toConsume = spec.predicate\n ? this.marking.countMatching(spec)\n : this.marking.tokenCount(inSpec.place);\n break;\n }\n\n for (let i = 0; i < toConsume; i++) {\n const token = spec.predicate\n ? this.marking.removeFirstMatching(spec)\n : this.marking.removeFirst(inSpec.place);\n if (token === null) break;\n consumed.push(token);\n inputs.add(inSpec.place, token);\n this.emitEvent({\n type: 'token-removed',\n timestamp: Date.now(),\n placeName: inSpec.place.name,\n token,\n });\n }\n }\n\n // Read arcs (peek, don't consume)\n for (const arc of t.reads) {\n const token = this.marking.peekFirst(arc.place);\n if (token !== null) {\n inputs.add(arc.place, token);\n }\n }\n\n // Reset arcs\n for (const arc of t.resets) {\n const removed = this.marking.removeAll(arc.place);\n this.pendingResetPlaces.add(arc.place.name);\n for (const token of removed) {\n consumed.push(token);\n this.emitEvent({\n type: 'token-removed',\n timestamp: Date.now(),\n placeName: arc.place.name,\n token,\n });\n }\n }\n\n // Update bitmap for consumed/reset places\n this.updateBitmapAfterConsumption(tid);\n\n this.emitEvent({\n type: 'transition-started',\n timestamp: Date.now(),\n transitionName: t.name,\n consumedTokens: consumed,\n });\n\n const execCtx = this.executionContextProvider?.(t.name, consumed);\n const logFn = (level: string, message: string, error?: Error) => {\n this.emitEvent({\n type: 'log-message',\n timestamp: Date.now(),\n transitionName: t.name,\n logger: t.name,\n level,\n message,\n error: error?.name ?? null,\n errorMessage: error?.message ?? null,\n });\n };\n const context = new TransitionContext(\n t.name, inputs, new TokenOutput(),\n t.inputPlaces(), t.readPlaces(), t.outputPlaces(),\n execCtx,\n logFn,\n t.placeAlias,\n );\n const freshNameBase = t.name;\n context.setFreshNameSupplier(() => nameId(`${freshNameBase}#${this.freshNameCounter++}`));\n\n // Create action promise with optional timeout. executeAction converts a synchronous\n // throw or a null/non-thenable return into a rejected promise, so a misbehaving action\n // flows the contained failure path instead of unwinding the orchestrator loop.\n let actionPromise = executeAction(t, context);\n\n if (t.hasActionTimeout()) {\n const timeoutSpec = t.actionTimeout;\n if (timeoutSpec === null) throw new Error(`Expected actionTimeout on ${t.name}`);\n const timeoutMs = timeoutSpec.afterMs;\n actionPromise = Promise.race([\n actionPromise,\n new Promise<void>((_, reject) =>\n setTimeout(() => reject(new TimeoutSentinel()), timeoutMs)\n ),\n ]).catch((err) => {\n if (err instanceof TimeoutSentinel) {\n // Sever first, then produce: the abandoned action may still be writing to this\n // context, and its pre-timeout writes must not merge with the timeout branch.\n context.detachForTimeout();\n produceTimeoutOutput(context, timeoutSpec.child);\n this.emitEvent({\n type: 'action-timed-out',\n timestamp: Date.now(),\n transitionName: t.name,\n timeoutMs,\n });\n return;\n }\n throw err;\n });\n }\n\n // On completion, push to completionQueue\n let resolveInFlight!: () => void;\n const completionPromise = new Promise<void>(r => { resolveInFlight = r; });\n\n const flight: InFlightTransition = {\n promise: completionPromise,\n context,\n consumed,\n startMs: performance.now(),\n resolve: resolveInFlight,\n };\n\n actionPromise.then(\n () => {\n this.completionQueue.push(t);\n this.wakeUp();\n resolveInFlight();\n },\n (err) => {\n flight.error = err;\n this.completionQueue.push(t);\n this.wakeUp();\n resolveInFlight();\n },\n );\n\n this.inFlight.set(t, flight);\n this.inFlightFlags[tid] = 1;\n this.enabledFlags[tid] = 0;\n this.enabledTransitionCount--;\n this.enabledAtMs[tid] = -Infinity;\n }\n\n private updateBitmapAfterConsumption(tid: number): void {\n const pids = this.compiled.consumptionPlaceIds(tid);\n for (const pid of pids) {\n const place = this.compiled.place(pid);\n if (!this.marking.hasTokens(place)) {\n clearBit(this.markingBitmap, pid);\n }\n this.markDirty(pid);\n }\n }\n\n // ======================== Completion Processing ========================\n\n private processCompletedTransitions(): void {\n if (this.completionQueue.length === 0) return;\n // In-place iteration is safe: processing is synchronous and .push() only\n // happens from microtasks which cannot interleave within this loop.\n const len = this.completionQueue.length;\n for (let i = 0; i < len; i++) {\n const t = this.completionQueue[i]!;\n const flight = this.inFlight.get(t);\n if (!flight) continue;\n this.inFlight.delete(t);\n\n const tid = this.compiled.transitionId(t);\n this.inFlightFlags[tid] = 0;\n\n if (flight.error) {\n const err = flight.error instanceof Error\n ? flight.error\n : new Error(String(flight.error));\n this.emitEvent({\n type: 'transition-failed',\n timestamp: Date.now(),\n transitionName: t.name,\n errorMessage: err.message,\n exceptionType: err.name,\n stack: err.stack,\n });\n this.markTransitionDirty(tid);\n continue;\n }\n\n try {\n const outputs = flight.context.rawOutput();\n\n // Validate output against spec\n if (t.outputSpec !== null) {\n validateOutSpec(t.name, t.outputSpec, outputs.placesWithTokens());\n }\n\n // Single pass: add tokens to marking, update bitmap, and emit events\n const produced: Token<any>[] = [];\n for (const entry of outputs.entries()) {\n const pid = this.compiled.tryPlaceId(entry.place);\n this.marking.addToken(entry.place, entry.token);\n produced.push(entry.token);\n if (pid !== undefined) {\n this.cacheAddToken(pid, entry.token);\n setBit(this.markingBitmap, pid);\n this.markDirty(pid);\n } else {\n // Unknown place — retained in the Marking (CORE-072 AC3), no bits to update.\n this.warnUnknownPlace(entry.place, t.name);\n }\n this.emitEvent({\n type: 'token-added',\n timestamp: Date.now(),\n placeName: entry.place.name,\n token: entry.token,\n });\n }\n this.markTransitionDirty(tid);\n\n this.emitEvent({\n type: 'transition-completed',\n timestamp: Date.now(),\n transitionName: t.name,\n producedTokens: produced,\n durationMs: performance.now() - flight.startMs,\n });\n } catch (e) {\n const err = e instanceof Error ? e : new Error(String(e));\n this.emitEvent({\n type: 'transition-failed',\n timestamp: Date.now(),\n transitionName: t.name,\n errorMessage: err.message,\n exceptionType: err.name,\n stack: err.stack,\n });\n this.markTransitionDirty(tid);\n }\n }\n this.completionQueue.length = 0;\n }\n\n // ======================== External Events ========================\n\n private processExternalEvents(): void {\n if (this.externalQueue.length === 0) return;\n if (this.closed) return; // ENV-013: leave queued events for drainPendingExternalEvents()\n // In-place iteration is safe: processing is synchronous and .push() only\n // happens from microtasks which cannot interleave within this loop.\n const len = this.externalQueue.length;\n for (let i = 0; i < len; i++) {\n const event = this.externalQueue[i]!;\n try {\n const pid = this.compiled.tryPlaceId(event.place);\n this.marking.addToken(event.place, event.token);\n if (pid !== undefined) {\n this.cacheAddToken(pid, event.token);\n setBit(this.markingBitmap, pid);\n this.markDirty(pid);\n } else {\n // Unknown place — retained in the Marking (CORE-072 AC3), no bits to update.\n this.warnUnknownPlace(event.place, '');\n }\n\n this.emitEvent({\n type: 'token-added',\n timestamp: Date.now(),\n placeName: event.place.name,\n token: event.token,\n });\n event.resolve(true);\n } catch (e) {\n event.reject(e instanceof Error ? e : new Error(String(e)));\n }\n }\n this.externalQueue.length = 0;\n }\n\n private drainPendingExternalEvents(): void {\n while (this.externalQueue.length > 0) {\n this.externalQueue.shift()!.resolve(false);\n }\n }\n\n // ======================== Await Work ========================\n\n /**\n * Suspends the executor until work is available. Composes up to 3 promise sources\n * into a single Promise.race: (1) any in-flight action completing, (2) external\n * event injection via wakeUp(), (3) timer for the next delayed transition's earliest\n * firing time. This avoids busy-waiting while remaining responsive to all event types.\n *\n * **Microtask flush**: Before building Promise.race, yields via `await Promise.resolve()`\n * to drain the microtask queue. Sync actions complete via `.then()` microtask; this\n * yield lets those fire, avoiding ~5 allocations when work is already available.\n * After the yield, re-checks queues and `this.closed` for close-during-yield safety.\n */\n private async awaitWork(): Promise<void> {\n // When closed, ignore external queue — processExternalEvents() won't consume it,\n // and drainPendingExternalEvents() handles it after the loop exits.\n if (this.completionQueue.length > 0 || (!this.closed && this.externalQueue.length > 0)) return;\n\n // Flush microtask queue: sync actions complete via .then() which schedules a\n // microtask. A single await here lets those fire before we build a full\n // Promise.race (~5 allocations). For async workloads this adds ~0.05us.\n await Promise.resolve();\n if (this.completionQueue.length > 0 || (!this.closed && this.externalQueue.length > 0)) return;\n // ENV-013: when closed with no in-flight, exit immediately for shouldTerminate()\n if (this.closed && this.inFlight.size === 0) return;\n\n const promises = this.awaitPromises;\n promises.length = 0;\n\n // 1. Any in-flight action completing (reuse array to avoid 2 intermediate allocations)\n if (this.inFlight.size > 0) {\n const arr = this.inFlightPromises;\n arr.length = 0;\n for (const f of this.inFlight.values()) arr.push(f.promise);\n promises.push(Promise.race(arr));\n }\n\n // When closed, only wait for in-flight completions — skip event/timer promises\n if (!this.closed) {\n // Zero means a timing boundary is already due: an earliest firing time has\n // been reached, or a deadline needs enforcing. There is nothing to wait for,\n // and with no action in flight the race below would hold only the external\n // wake-up promise — which a net with no environment places has nobody to\n // resolve, so the loop would sleep until its run budget expired. Return and\n // let the next cycle act on the boundary. Rust reaches the same outcome via\n // sleep(0); Java returns early on `millisUntilNextTimedTransition() <= 0`.\n const timerMs = this.millisUntilNextTimedTransition();\n if (timerMs === 0 && promises.length === 0) return;\n\n // 2. External event wake-up\n promises.push(new Promise<void>(resolve => { this.wakeUpResolve = resolve; }));\n\n // 3. Timer for next delayed transition\n if (timerMs > 0 && timerMs < Infinity) {\n promises.push(new Promise<void>(r => setTimeout(r, timerMs)));\n }\n }\n\n if (promises.length > 0) {\n await Promise.race(promises);\n }\n this.wakeUpResolve = null;\n }\n\n private millisUntilNextTimedTransition(): number {\n const nowMs = performance.now();\n let minWaitMs = Infinity;\n\n for (let tid = 0; tid < this.compiled.transitionCount; tid++) {\n if (!this.enabledFlags[tid]) continue;\n const t = this.compiled.transition(tid);\n const enabledMs = this.enabledAtMs[tid]!;\n const elapsedMs = nowMs - enabledMs;\n\n // Time until earliest firing\n const earliestMs = timingEarliest(t.timing);\n const remainingEarliest = earliestMs - elapsedMs;\n if (remainingEarliest <= 0) return 0;\n minWaitMs = Math.min(minWaitMs, remainingEarliest);\n\n // Time until deadline expiry (must wake up to enforce deadline)\n if (timingHasDeadline(t.timing)) {\n const latestMs = timingLatest(t.timing);\n const remainingDeadline = latestMs - elapsedMs;\n if (remainingDeadline <= 0) return 0;\n minWaitMs = Math.min(minWaitMs, remainingDeadline);\n }\n }\n return minWaitMs;\n }\n\n private wakeUp(): void {\n this.wakeUpResolve?.();\n }\n\n // ======================== Dirty Set Helpers ========================\n\n /** Returns true if any transition needs re-evaluation. O(W) where W = ceil(transitions/32). */\n private hasDirtyBits(): boolean {\n for (let w = 0; w < this.dirtySet.length; w++) {\n if (this.dirtySet[w] !== 0) return true;\n }\n return false;\n }\n\n private markDirty(pid: number): void {\n const tids = this.compiled.affectedTransitions(pid);\n for (const tid of tids) {\n this.markTransitionDirty(tid);\n }\n }\n\n private markTransitionDirty(tid: number): void {\n this.dirtySet[tid >>> WORD_SHIFT]! |= (1 << (tid & BIT_MASK));\n }\n\n // ======================== State Inspection ========================\n\n getMarking(): Marking { return this.marking; }\n\n /** Builds a snapshot of the current marking for event emission. */\n private snapshotMarking(): ReadonlyMap<string, readonly Token<any>[]> {\n const snap = new Map<string, readonly Token<any>[]>();\n for (let pid = 0; pid < this.compiled.placeCount; pid++) {\n const p = this.compiled.place(pid);\n const tokens = this.marking.peekTokens(p);\n if (tokens.length > 0) {\n snap.set(p.name, [...tokens]);\n }\n }\n return snap;\n }\n\n isQuiescent(): boolean {\n return this.enabledTransitionCount === 0 && this.inFlight.size === 0;\n }\n\n executionId(): string {\n return this.startMs.toString(16);\n }\n\n drain(): void {\n this.draining = true;\n this.wakeUp();\n }\n\n close(): void {\n this.draining = true;\n this.closed = true;\n this.wakeUp();\n }\n\n // ======================== Event Emission ========================\n\n /**\n * Reports an undeclared place once (CORE-072 AC4, emitted as the EVT-013\n * log-message event). `transitionName` is the producer, empty at the\n * initial-marking and injection seams. Retention never depends on this.\n */\n private warnUnknownPlace(place: Place<any>, transitionName: string): void {\n if (this.warnedUnknownPlaces.has(place.name)) return;\n this.warnedUnknownPlaces.add(place.name);\n this.emitEvent({\n type: 'log-message',\n timestamp: Date.now(),\n transitionName,\n logger: 'libpetri.runtime',\n level: 'WARN',\n message: `unknown place '${place.name}': tokens are retained in the marking but inert `\n + '(the net declares no arc on it)',\n error: null,\n errorMessage: null,\n });\n }\n\n private emitEvent(event: NetEvent): void {\n if (this.eventStoreEnabled) {\n // A user EventStore.append that throws is observation failing, not control flow:\n // swallow it so a hostile store cannot unwind the orchestrator loop. One choke\n // point covers every emit site.\n try {\n this.eventStore.append(event);\n } catch (err) {\n swallowEventStoreFailure(event.type, err);\n }\n }\n }\n}\n\n/** Internal sentinel for timeout detection. */\nclass TimeoutSentinel extends Error {\n constructor() { super('action timeout'); this.name = 'TimeoutSentinel'; }\n}\n","/**\n * @module precompiled-net\n *\n * Flat-array precompiled representation of a PetriNet for high-performance execution.\n *\n * **Design**: Compiles from a `CompiledNet`, converting all per-transition data into\n * flat typed arrays indexed by transition ID (tid) or place ID (pid). Eliminates Map\n * lookups and object traversals from the hot path.\n *\n * **Sparse enablement**: Each transition's needs/inhibitor masks are classified as\n * empty (-2), single-word (>=0), or multi-word (-1). Single-word masks avoid inner\n * loops entirely; multi-word uses precomputed sparse indices to skip zero words.\n *\n * **Opcode programs**: Input consumption is compiled to compact opcode sequences\n * (CONSUME_ONE, CONSUME_N, CONSUME_ALL, CONSUME_ATLEAST, RESET) that the executor\n * dispatches without inspecting In spec objects.\n *\n * @see CompiledNet for the base bitmap representation\n * @see PrecompiledNetExecutor for the executor that uses this representation\n */\nimport type { PetriNet } from '../core/petri-net.js';\nimport type { Place } from '../core/place.js';\nimport type { Transition } from '../core/transition.js';\nimport type { Out } from '../core/out.js';\nimport { CompiledNet, WORD_SHIFT, BIT_MASK } from './compiled-net.js';\nimport type { CardinalityCheck } from './compiled-net.js';\nimport { earliest as timingEarliest, latest as timingLatest, hasDeadline as timingHasDeadline } from '../core/timing.js';\n\n// ==================== Opcodes ====================\n\n/** Consume exactly 1 token from place. Next word: pid. */\nexport const CONSUME_ONE = 0;\n/** Consume exactly N tokens. Next words: pid, count. */\nexport const CONSUME_N = 1;\n/** Consume all tokens. Next word: pid. */\nexport const CONSUME_ALL = 2;\n/** Consume at-least N tokens (consumes all). Next words: pid, minimum. */\nexport const CONSUME_ATLEAST = 3;\n/** Reset (clear all tokens). Next word: pid. */\nexport const RESET = 4;\n\n/** Sparse mask classification: no bits set. */\nconst SPARSE_EMPTY = -2;\n/** Sparse mask classification: bits span multiple words. */\nconst SPARSE_MULTI = -1;\n\n/**\n * Immutable precompiled representation of a Petri net.\n *\n * All data is stored in flat typed arrays indexed by tid/pid for cache-friendly,\n * branch-free access on the hot path. Compiled once, reused across executions.\n */\nexport class PrecompiledNet {\n // ==================== Identity ====================\n readonly compiled: CompiledNet;\n readonly placeCount: number;\n readonly transitionCount: number;\n readonly wordCount: number;\n\n // ==================== Place Cache ====================\n /** Places indexed by pid — avoids compiled.place(pid) indirection on hot path. */\n readonly places: readonly Place<any>[];\n\n // ==================== Opcode Programs ====================\n /** Per-transition consume opcode sequences. */\n readonly consumeOps: readonly (readonly number[])[];\n /**\n * Per-transition index into {@link consumeOps} where the RESET tail begins; the\n * executor peeks read arcs at this boundary so reads observe the post-input,\n * pre-reset marking (EXEC-013 AC4).\n */\n readonly resetOpsStart: Uint32Array;\n /** Per-transition read-arc place IDs. */\n readonly readOps: readonly (readonly number[])[];\n\n // ==================== Enablement Masks ====================\n readonly needsMask: readonly Uint32Array[];\n readonly inhibitorMask: readonly Uint32Array[];\n\n // ==================== Sparse Enablement (PERF-042) ====================\n readonly needsSingleWordIndex: Int8Array;\n readonly needsSingleWordMask: Uint32Array;\n readonly needsSparseIndices: readonly (readonly number[])[];\n readonly needsSparseMasks: readonly (readonly number[])[];\n\n readonly inhibitorSingleWordIndex: Int8Array;\n readonly inhibitorSingleWordMask: Uint32Array;\n readonly inhibitorSparseIndices: readonly (readonly number[])[];\n readonly inhibitorSparseMasks: readonly (readonly number[])[];\n\n // ==================== Timing (CONC-024) ====================\n readonly earliestMs: Float64Array;\n readonly latestMs: Float64Array;\n readonly hasDeadline: Uint8Array;\n /**\n * 1 for `exact()` transitions. Exact transitions fire at the first opportunity at/after their\n * target time (delayed-style liveness) and are never force-disabled by deadline enforcement —\n * their upper bound is observed, not enforced. See TIME-006.\n */\n readonly isExact: Uint8Array;\n\n // ==================== Priority (CONC-023) ====================\n readonly priorities: Int32Array;\n readonly transitionToPriorityIndex: Uint32Array;\n readonly priorityLevels: readonly number[];\n readonly distinctPriorityCount: number;\n\n // ==================== Output Fast Path ====================\n /** -2=no spec, -1=complex, >=0=single output place ID. */\n readonly simpleOutputPlaceId: Int32Array;\n\n // ==================== Input Precomputation ====================\n readonly inputPlaceCount: Uint32Array;\n readonly inputPlaceMaskWords: readonly Uint32Array[];\n\n // ==================== Reverse Index ====================\n readonly placeToTransitions: readonly (readonly number[])[];\n readonly consumptionPlaceIds: readonly (readonly number[])[];\n\n // ==================== Cardinality ====================\n readonly cardinalityChecks: readonly (CardinalityCheck | null)[];\n // ν-net join flag (NU-020): gates the match-binding check off the hot\n // enablement path for non-ν transitions.\n readonly hasMatch: readonly boolean[];\n\n // ==================== Global Flags ====================\n readonly allImmediate: boolean;\n readonly allSamePriority: boolean;\n readonly anyDeadlines: boolean;\n\n private constructor(compiled: CompiledNet) {\n this.compiled = compiled;\n this.placeCount = compiled.placeCount;\n this.transitionCount = compiled.transitionCount;\n this.wordCount = compiled.wordCount;\n\n const tc = compiled.transitionCount;\n const wc = compiled.wordCount;\n\n // Cache place references\n const places: Place<any>[] = new Array(this.placeCount);\n for (let pid = 0; pid < this.placeCount; pid++) {\n places[pid] = compiled.place(pid);\n }\n this.places = places;\n\n // Copy masks from CompiledNet\n const needsMask: Uint32Array[] = new Array(tc);\n const inhibitorMask: Uint32Array[] = new Array(tc);\n for (let tid = 0; tid < tc; tid++) {\n // Access via canEnableBitmap internals — copy the mask arrays\n // We need to extract them; use the CompiledNet's accessor pattern\n needsMask[tid] = new Uint32Array(wc);\n inhibitorMask[tid] = new Uint32Array(wc);\n }\n\n // Build needs/inhibitor masks by probing CompiledNet\n // We reconstruct from transition arc specs since CompiledNet doesn't expose raw masks\n for (let tid = 0; tid < tc; tid++) {\n const t = compiled.transition(tid);\n const needs = needsMask[tid]!;\n const inhibitors = inhibitorMask[tid]!;\n\n for (const inSpec of t.inputSpecs) {\n const pid = compiled.placeId(inSpec.place);\n needs[pid >>> WORD_SHIFT]! |= (1 << (pid & BIT_MASK));\n }\n for (const arc of t.reads) {\n const pid = compiled.placeId(arc.place);\n needs[pid >>> WORD_SHIFT]! |= (1 << (pid & BIT_MASK));\n }\n for (const arc of t.inhibitors) {\n const pid = compiled.placeId(arc.place);\n inhibitors[pid >>> WORD_SHIFT]! |= (1 << (pid & BIT_MASK));\n }\n }\n this.needsMask = needsMask;\n this.inhibitorMask = inhibitorMask;\n\n // ==================== Sparse Enablement ====================\n this.needsSingleWordIndex = new Int8Array(tc);\n this.needsSingleWordMask = new Uint32Array(tc);\n const needsSparseIndices: number[][] = new Array(tc);\n const needsSparseMasks: number[][] = new Array(tc);\n\n this.inhibitorSingleWordIndex = new Int8Array(tc);\n this.inhibitorSingleWordMask = new Uint32Array(tc);\n const inhibitorSparseIndices: number[][] = new Array(tc);\n const inhibitorSparseMasks: number[][] = new Array(tc);\n\n for (let tid = 0; tid < tc; tid++) {\n compileSparse(needsMask[tid]!, wc,\n this.needsSingleWordIndex, this.needsSingleWordMask,\n needsSparseIndices, needsSparseMasks, tid);\n compileSparse(inhibitorMask[tid]!, wc,\n this.inhibitorSingleWordIndex, this.inhibitorSingleWordMask,\n inhibitorSparseIndices, inhibitorSparseMasks, tid);\n }\n this.needsSparseIndices = needsSparseIndices;\n this.needsSparseMasks = needsSparseMasks;\n this.inhibitorSparseIndices = inhibitorSparseIndices;\n this.inhibitorSparseMasks = inhibitorSparseMasks;\n\n // ==================== Opcode Programs ====================\n const consumeOps: number[][] = new Array(tc);\n const readOps: number[][] = new Array(tc);\n this.resetOpsStart = new Uint32Array(tc);\n for (let tid = 0; tid < tc; tid++) {\n const t = compiled.transition(tid);\n const program = compileConsumeProgram(t, compiled);\n consumeOps[tid] = program.ops;\n this.resetOpsStart[tid] = program.resetOpsStart;\n readOps[tid] = compileReadProgram(t, compiled);\n }\n this.consumeOps = consumeOps;\n this.readOps = readOps;\n\n // ==================== Reverse Index & Consumption ====================\n const placeToTransitions: number[][] = new Array(this.placeCount);\n const consumptionPlaceIds: number[][] = new Array(tc);\n for (let pid = 0; pid < this.placeCount; pid++) {\n placeToTransitions[pid] = [...compiled.affectedTransitions(pid)];\n }\n for (let tid = 0; tid < tc; tid++) {\n consumptionPlaceIds[tid] = [...compiled.consumptionPlaceIds(tid)];\n }\n this.placeToTransitions = placeToTransitions;\n this.consumptionPlaceIds = consumptionPlaceIds;\n\n // ==================== Cardinality ====================\n const cardinalityChecks: (CardinalityCheck | null)[] = new Array(tc);\n const hasMatch: boolean[] = new Array(tc);\n for (let tid = 0; tid < tc; tid++) {\n cardinalityChecks[tid] = compiled.cardinalityCheck(tid);\n hasMatch[tid] = compiled.hasMatch(tid);\n }\n this.cardinalityChecks = cardinalityChecks;\n this.hasMatch = hasMatch;\n\n // ==================== Timing ====================\n this.earliestMs = new Float64Array(tc);\n this.latestMs = new Float64Array(tc);\n this.hasDeadline = new Uint8Array(tc);\n this.isExact = new Uint8Array(tc);\n let anyDeadlines = false;\n let allImm = true;\n\n for (let tid = 0; tid < tc; tid++) {\n const t = compiled.transition(tid);\n this.earliestMs[tid] = timingEarliest(t.timing);\n this.latestMs[tid] = timingLatest(t.timing);\n if (timingHasDeadline(t.timing)) {\n this.hasDeadline[tid] = 1;\n anyDeadlines = true;\n }\n if (t.timing.type === 'exact') this.isExact[tid] = 1;\n if (t.timing.type !== 'immediate') allImm = false;\n }\n this.anyDeadlines = anyDeadlines;\n this.allImmediate = allImm;\n\n // ==================== Priority ====================\n this.priorities = new Int32Array(tc);\n const prioritySet = new Set<number>();\n const firstPriority = tc > 0 ? compiled.transition(0).priority : 0;\n let samePrio = true;\n\n for (let tid = 0; tid < tc; tid++) {\n const p = compiled.transition(tid).priority;\n this.priorities[tid] = p;\n prioritySet.add(p);\n if (p !== firstPriority) samePrio = false;\n }\n this.allSamePriority = samePrio;\n\n // Sort priorities descending\n const levels = [...prioritySet].sort((a, b) => b - a);\n this.priorityLevels = levels;\n this.distinctPriorityCount = levels.length;\n\n // Map tid -> priority queue index\n this.transitionToPriorityIndex = new Uint32Array(tc);\n const levelIndex = new Map<number, number>();\n for (let i = 0; i < levels.length; i++) {\n levelIndex.set(levels[i]!, i);\n }\n for (let tid = 0; tid < tc; tid++) {\n this.transitionToPriorityIndex[tid] = levelIndex.get(this.priorities[tid]!)!;\n }\n\n // ==================== Output Fast Path ====================\n this.simpleOutputPlaceId = new Int32Array(tc);\n for (let tid = 0; tid < tc; tid++) {\n const t = compiled.transition(tid);\n if (t.outputSpec === null) {\n this.simpleOutputPlaceId[tid] = -2; // no spec\n } else {\n const simplePid = simpleOutputPlace(t.outputSpec, compiled);\n this.simpleOutputPlaceId[tid] = simplePid;\n }\n }\n\n // ==================== Input Precomputation ====================\n this.inputPlaceCount = new Uint32Array(tc);\n const inputPlaceMaskWords: Uint32Array[] = new Array(tc);\n for (let tid = 0; tid < tc; tid++) {\n const t = compiled.transition(tid);\n this.inputPlaceCount[tid] = t.inputSpecs.length + t.reads.length;\n const mask = new Uint32Array(wc);\n for (const spec of t.inputSpecs) {\n const pid = compiled.placeId(spec.place);\n mask[pid >>> WORD_SHIFT]! |= (1 << (pid & BIT_MASK));\n }\n inputPlaceMaskWords[tid] = mask;\n }\n this.inputPlaceMaskWords = inputPlaceMaskWords;\n }\n\n // ==================== Factory Methods ====================\n\n static compile(net: PetriNet): PrecompiledNet {\n return new PrecompiledNet(CompiledNet.compile(net));\n }\n\n static compileFrom(compiled: CompiledNet): PrecompiledNet {\n return new PrecompiledNet(compiled);\n }\n\n // ==================== Sparse Enablement Check ====================\n\n /**\n * Three-case sparse enablement check:\n * 1. Empty mask (needsSingleWordIndex == -2): always passes\n * 2. Single-word mask (>=0): one comparison\n * 3. Multi-word mask (-1): iterate precomputed sparse indices\n */\n canEnableSparse(tid: number, snapshot: Uint32Array): boolean {\n // Check needs mask\n const needsIdx = this.needsSingleWordIndex[tid]!;\n if (needsIdx === SPARSE_EMPTY) {\n // No needs — passes\n } else if (needsIdx >= 0) {\n // Single word\n const m = this.needsSingleWordMask[tid]!;\n if (((snapshot[needsIdx]! & m) >>> 0) !== m) return false;\n } else {\n // Multi-word sparse\n const indices = this.needsSparseIndices[tid]!;\n const masks = this.needsSparseMasks[tid]!;\n for (let i = 0; i < indices.length; i++) {\n const m = masks[i]!;\n if (((snapshot[indices[i]!]! & m) >>> 0) !== m) return false;\n }\n }\n\n // Check inhibitor mask\n const inhIdx = this.inhibitorSingleWordIndex[tid]!;\n if (inhIdx === SPARSE_EMPTY) {\n return true; // No inhibitors\n } else if (inhIdx >= 0) {\n return (snapshot[inhIdx]! & this.inhibitorSingleWordMask[tid]!) === 0;\n } else {\n const indices = this.inhibitorSparseIndices[tid]!;\n const masks = this.inhibitorSparseMasks[tid]!;\n for (let i = 0; i < indices.length; i++) {\n if ((snapshot[indices[i]!]! & masks[i]!) !== 0) return false;\n }\n return true;\n }\n }\n}\n\n// ==================== Compilation Helpers ====================\n\nfunction compileSparse(\n mask: Uint32Array,\n wordCount: number,\n singleWordIndex: Int8Array,\n singleWordMask: Uint32Array,\n sparseIndices: number[][],\n sparseMasks: number[][],\n tid: number,\n): void {\n let nonZeroCount = 0;\n let lastNonZeroWord = -1;\n\n for (let w = 0; w < wordCount; w++) {\n if (mask[w] !== 0) {\n nonZeroCount++;\n lastNonZeroWord = w;\n }\n }\n\n if (nonZeroCount === 0) {\n singleWordIndex[tid] = SPARSE_EMPTY;\n singleWordMask[tid] = 0;\n sparseIndices[tid] = [];\n sparseMasks[tid] = [];\n } else if (nonZeroCount === 1) {\n singleWordIndex[tid] = lastNonZeroWord;\n singleWordMask[tid] = mask[lastNonZeroWord]!;\n sparseIndices[tid] = [];\n sparseMasks[tid] = [];\n } else {\n singleWordIndex[tid] = SPARSE_MULTI;\n singleWordMask[tid] = 0;\n const idx: number[] = [];\n const msk: number[] = [];\n for (let w = 0; w < wordCount; w++) {\n if (mask[w] !== 0) {\n idx.push(w);\n msk.push(mask[w]!);\n }\n }\n sparseIndices[tid] = idx;\n sparseMasks[tid] = msk;\n }\n}\n\nfunction compileConsumeProgram(\n t: Transition,\n compiled: CompiledNet,\n): { ops: number[]; resetOpsStart: number } {\n const ops: number[] = [];\n\n for (const spec of t.inputSpecs) {\n const pid = compiled.placeId(spec.place);\n switch (spec.type) {\n case 'one':\n ops.push(CONSUME_ONE, pid);\n break;\n case 'exactly':\n ops.push(CONSUME_N, pid, spec.count);\n break;\n case 'all':\n ops.push(CONSUME_ALL, pid);\n break;\n case 'at-least':\n ops.push(CONSUME_ATLEAST, pid, spec.minimum);\n break;\n }\n }\n\n // RESET opcodes are compiled after all input opcodes; the boundary lets the\n // executor peek read arcs before resets drain (EXEC-013).\n const resetOpsStart = ops.length;\n for (const arc of t.resets) {\n const pid = compiled.placeId(arc.place);\n ops.push(RESET, pid);\n }\n\n return { ops, resetOpsStart };\n}\n\nfunction compileReadProgram(t: Transition, compiled: CompiledNet): number[] {\n const pids: number[] = [];\n for (const arc of t.reads) {\n pids.push(compiled.placeId(arc.place));\n }\n return pids;\n}\n\nfunction simpleOutputPlace(spec: Out, compiled: CompiledNet): number {\n if (spec.type === 'place') {\n return compiled.placeId(spec.place);\n }\n return -1; // complex\n}\n","/**\n * @module precompiled-net-executor\n *\n * High-performance executor for Typed Coloured Time Petri Nets.\n *\n * **Architecture**: Uses `PrecompiledNet` for all transition/place data, replacing\n * Map lookups and object traversals with typed-array indexing. Token storage uses\n * simple per-place arrays, leveraging V8's optimized small-array shift/push.\n *\n * **Execution loop**: Same 5-phase structure as `BitmapNetExecutor`:\n * 1. Process completed transitions — drain completionQueue, validate outputs\n * 2. Process external events — inject tokens from EnvironmentPlaces\n * 3. Update dirty transitions — sparse enablement via `canEnableSparse()`\n * 4. Enforce deadlines — gated by `anyDeadlines` flag\n * 5. Fire ready transitions — opcode dispatch or priority-queue path\n *\n * **Key optimizations over BitmapNetExecutor**:\n * - Opcode-based consumption (switch on int vs object dispatch)\n * - Cached place references (avoids compiled.place(pid) indirection)\n * - Sparse enablement masks (skip zero words)\n * - Lazy Marking sync (arrays are sole source of truth during execution)\n * - Flat-array in-flight tracking (no Map overhead)\n *\n * @see PrecompiledNet for the precompiled data representation\n * @see BitmapNetExecutor for the reference implementation\n */\nimport type { PetriNet } from '../core/petri-net.js';\nimport type { Place, EnvironmentPlace } from '../core/place.js';\nimport type { Token } from '../core/token.js';\nimport type { Transition } from '../core/transition.js';\nimport type { EventStore } from '../event/event-store.js';\nimport type { NetEvent } from '../event/net-event.js';\nimport type { PetriNetExecutor, RunTimeoutPolicy } from './petri-net-executor.js';\nimport { tokenOf } from '../core/token.js';\nimport { TokenInput } from '../core/token-input.js';\nimport { TokenOutput } from '../core/token-output.js';\nimport { TransitionContext } from '../core/transition-context.js';\nimport { noopEventStore } from '../event/event-store.js';\nimport { WORD_SHIFT, BIT_MASK } from './compiled-net.js';\nimport { Marking } from './marking.js';\nimport { PrecompiledNet, CONSUME_ONE, CONSUME_N, CONSUME_ALL, CONSUME_ATLEAST, RESET } from './precompiled-net.js';\nimport { validateOutSpec, produceTimeoutOutput, executeAction, swallowEventStoreFailure, DEADLINE_TOLERANCE_MS } from './executor-support.js';\nimport { OutViolationError } from './out-violation-error.js';\nimport { findBinding, IncrementalMatcher } from './match-engine.js';\nimport { keyForPlace } from '../core/match-spec.js';\nimport { nameId, type NameId } from '../core/name.js';\n\n// ==================== Types ====================\n\ninterface ExternalEvent<T = any> {\n place: Place<T>;\n token: Token<T>;\n resolve: (value: boolean) => void;\n reject: (err: Error) => void;\n}\n\n/** Retained tokens for one undeclared place, keyed by name (CORE-072). */\ninterface UnknownPlaceTokens {\n place: Place<any>;\n tokens: Token<any>[];\n}\n\nexport interface PrecompiledNetExecutorOptions {\n eventStore?: EventStore;\n environmentPlaces?: Set<EnvironmentPlace<any>>;\n executionContextProvider?: (transitionName: string, consumed: Token<any>[]) => Map<string, unknown>;\n /** Skip output spec validation for trusted actions (CONC-026). */\n skipOutputValidation?: boolean;\n /** Reuse a precompiled program (avoids recompilation). */\n program?: PrecompiledNet;\n /**\n * Grace band (ms) beyond a hard deadline (`deadline()` / `window()`) before a transition is\n * force-disabled with a `transition-timed-out` event (TIME-013). Defaults to {@link DEADLINE_TOLERANCE_MS}\n * (5ms); `0` gives strict enforcement. Must be non-negative. Does not affect `exact()` transitions,\n * which are enforced softly (TIME-006).\n */\n deadlineToleranceMs?: number;\n}\n\n/**\n * High-performance executor using `PrecompiledNet`.\n *\n * Implements `PetriNetExecutor` with the same semantics as `BitmapNetExecutor`\n * but with flat-array optimizations for lower per-transition overhead.\n */\nexport class PrecompiledNetExecutor implements PetriNetExecutor {\n private readonly program: PrecompiledNet;\n private readonly eventStore: EventStore;\n private readonly environmentPlaces: Set<string>;\n private readonly hasEnvironmentPlaces: boolean;\n private readonly executionContextProvider?: (transitionName: string, consumed: Token<any>[]) => Map<string, unknown>;\n private readonly skipOutputValidation: boolean;\n private readonly deadlineToleranceMs: number;\n private readonly startMs: number;\n private readonly eventStoreEnabled: boolean;\n\n // ==================== Token Storage ====================\n /** Per-place token arrays, indexed by pid. */\n private readonly tokenQueues: Token<any>[][];\n /**\n * Tokens on places the compiled net does not know (CORE-072 AC3). Retained —\n * never dropped — and merged into the materialized marking, matching the\n * BitmapNetExecutor reference, whose Marking keeps them naturally. Keyed by\n * place NAME (TS Place identity is name-based), carrying the Place so\n * materializing a Marking has one to hand.\n */\n private readonly unknownPlaceTokens = new Map<string, UnknownPlaceTokens>();\n /** Monotonic source for ν-name minting (ctx.freshName(), NU-010). */\n private freshNameCounter = 0;\n /**\n * Per-transition ν-name minter cache, indexed by tid (built lazily). Each\n * supplier is created once and reused across firings, so installing it on a\n * per-fire context is a field assignment rather than a per-fire closure\n * allocation — keeping the fire path lean for non-ν transitions. Every\n * transition gets one (forks mint but carry no MatchSpec, so gating on\n * `hasMatch` would wrongly starve them).\n */\n private readonly freshNameSuppliers: (() => NameId)[] = [];\n\n // ==================== ν-net incremental match caches (NU-020) ====================\n /**\n * Per matched transition: an {@link IncrementalMatcher} kept in lockstep with\n * the token queues when the transition is fast-path eligible (every correlated\n * input is `one`/`exactly`, consumed by no other transition, and never reset),\n * else `null` → fall back to the O(n) rebuild {@link findBinding}. This turns a\n * draining matched join from O(n²) into O(n log n).\n */\n private matchCaches: (IncrementalMatcher | null)[] = [];\n /** Per place (by pid): the `[tid, keyIndex]` of every fast-path correlated input it feeds. */\n private placeMatchTargets: Array<Array<[number, number]>> = [];\n\n // ==================== Marking Bitmap ====================\n private readonly markingBitmap: Uint32Array;\n\n // ==================== Transition State ====================\n private readonly dirtyBitmap: Uint32Array;\n private readonly dirtyScanBuffer: Uint32Array;\n private readonly enabledAtMs: Float64Array;\n private readonly inFlightFlags: Uint8Array;\n private readonly enabledFlags: Uint8Array;\n private readonly transitionWords: number;\n\n // ==================== Enabled Count ====================\n private enabledTransitionCount = 0;\n\n // ==================== In-Flight Tracking ====================\n private readonly inFlightPromises: (Promise<void> | null)[];\n private readonly inFlightContexts: (TransitionContext | null)[];\n private readonly inFlightConsumed: (Token<any>[] | null)[];\n private readonly inFlightStartMs: Float64Array;\n private readonly inFlightResolves: ((() => void) | null)[];\n private readonly inFlightErrors: (unknown | null)[];\n private inFlightCount = 0;\n\n // ==================== Reset-Clock Detection ====================\n private readonly pendingResetWords: Uint32Array;\n private hasPendingResets = false;\n\n // ==================== Queues ====================\n private readonly completionQueue: number[] = [];\n private readonly externalQueue: ExternalEvent[] = [];\n private wakeUpResolve: (() => void) | null = null;\n\n // ==================== Reusable Buffers ====================\n private readonly markingSnapBuffer: Uint32Array;\n private readonly firingSnapBuffer: Uint32Array;\n private readonly awaitPromises: Promise<void>[] = [];\n private readonly racePromises: Promise<void>[] = [];\n\n // Pre-allocated buffer for fireReadyGeneral()\n private readonly readyBuffer: { tid: number; priority: number; enabledAtMs: number }[] = [];\n\n // ==================== Lifecycle ====================\n private running = false;\n private draining = false;\n private closed = false;\n\n // ==================== Lazy Marking ====================\n private marking: Marking | null = null;\n\n constructor(\n net: PetriNet,\n initialTokens: Map<Place<any>, Token<any>[]>,\n options: PrecompiledNetExecutorOptions = {},\n ) {\n this.program = options.program ?? PrecompiledNet.compile(net);\n this.eventStore = options.eventStore ?? noopEventStore();\n this.environmentPlaces = new Set(\n [...(options.environmentPlaces ?? [])].map(ep => ep.place.name)\n );\n this.hasEnvironmentPlaces = this.environmentPlaces.size > 0;\n this.executionContextProvider = options.executionContextProvider;\n this.skipOutputValidation = options.skipOutputValidation ?? false;\n this.deadlineToleranceMs = options.deadlineToleranceMs ?? DEADLINE_TOLERANCE_MS;\n if (this.deadlineToleranceMs < 0) {\n throw new Error(`Deadline tolerance must be non-negative: ${this.deadlineToleranceMs}`);\n }\n this.startMs = performance.now();\n this.eventStoreEnabled = this.eventStore.isEnabled();\n\n const prog = this.program;\n const pc = prog.placeCount;\n const tc = prog.transitionCount;\n const wc = prog.wordCount;\n\n // ==================== Token Queues ====================\n this.tokenQueues = new Array(pc);\n for (let pid = 0; pid < pc; pid++) {\n this.tokenQueues[pid] = [];\n }\n\n // Load initial tokens\n for (const [place, tokens] of initialTokens) {\n const pid = prog.compiled.tryPlaceId(place);\n if (pid === undefined) {\n // CORE-072: undeclared place — retain the tokens in a side store so\n // they reappear in the observable marking.\n for (let i = 0; i < tokens.length; i++) {\n this.retainUnknownToken(place, tokens[i]!, '');\n }\n continue;\n }\n const q = this.tokenQueues[pid]!;\n for (const token of tokens) {\n q.push(token);\n }\n }\n\n // ==================== Marking Bitmap ====================\n this.markingBitmap = new Uint32Array(wc);\n\n // ==================== Transition State ====================\n this.transitionWords = (tc + BIT_MASK) >>> WORD_SHIFT;\n this.dirtyBitmap = new Uint32Array(this.transitionWords);\n this.dirtyScanBuffer = new Uint32Array(this.transitionWords);\n this.enabledAtMs = new Float64Array(tc);\n this.enabledAtMs.fill(-Infinity);\n this.inFlightFlags = new Uint8Array(tc);\n this.enabledFlags = new Uint8Array(tc);\n\n // ==================== In-Flight Arrays ====================\n this.inFlightPromises = new Array(tc).fill(null);\n this.inFlightContexts = new Array(tc).fill(null);\n this.inFlightConsumed = new Array(tc).fill(null);\n this.inFlightStartMs = new Float64Array(tc);\n this.inFlightResolves = new Array(tc).fill(null);\n this.inFlightErrors = new Array(tc).fill(null);\n\n // ==================== Reset Detection ====================\n this.pendingResetWords = new Uint32Array(wc);\n\n // ==================== Snapshot Buffers ====================\n this.markingSnapBuffer = new Uint32Array(wc);\n this.firingSnapBuffer = new Uint32Array(wc);\n\n this.initMatchCaches();\n }\n\n /**\n * Builds the ν-net incremental match caches (NU-020). A matched join is\n * fast-path eligible only when every correlated input is `one`/`exactly`, is\n * consumed by no other transition, and is never reset — so tokens enter a\n * correlated input only via produce/inject (mirrored by `add`) and leave only\n * via this join's matched consume (mirrored by `consume`), and the cache can\n * never desync. Mirrors the Rust backends.\n */\n private initMatchCaches(): void {\n const prog = this.program;\n const tc = prog.transitionCount;\n const pc = prog.placeCount;\n this.matchCaches = new Array(tc).fill(null);\n this.placeMatchTargets = Array.from({ length: pc }, () => []);\n\n let anyMatch = false;\n for (let tid = 0; tid < tc; tid++) {\n if (prog.hasMatch[tid]) { anyMatch = true; break; }\n }\n if (!anyMatch) return;\n\n // Which transitions consume (input) or reset each place.\n const inputConsumers: number[][] = Array.from({ length: pc }, () => []);\n const resetTarget: boolean[] = new Array(pc).fill(false);\n for (let tid = 0; tid < tc; tid++) {\n const t = prog.compiled.transition(tid);\n for (const spec of t.inputSpecs) inputConsumers[prog.compiled.placeId(spec.place)]!.push(tid);\n for (const arc of t.resets) resetTarget[prog.compiled.placeId(arc.place)] = true;\n }\n\n for (let tid = 0; tid < tc; tid++) {\n if (!prog.hasMatch[tid]) continue;\n const t = prog.compiled.transition(tid);\n const ms = t.matchSpec;\n if (!ms) continue;\n\n const requireds: number[] = [];\n let eligible = true;\n for (const mk of ms.keys) {\n const pid = prog.compiled.placeId(mk.place);\n const spec = t.inputSpecs.find(s => s.place.name === mk.place.name);\n let required: number;\n if (spec?.type === 'one') required = 1;\n else if (spec?.type === 'exactly') required = spec.count;\n else { eligible = false; break; } // at-least/all: variable consume → fall back\n const cons = inputConsumers[pid]!;\n if (resetTarget[pid] || cons.length !== 1 || cons[0] !== tid) { eligible = false; break; }\n requireds.push(required);\n }\n if (!eligible) continue;\n\n const matcher = new IncrementalMatcher(requireds);\n for (let keyIdx = 0; keyIdx < ms.keys.length; keyIdx++) {\n const mk = ms.keys[keyIdx]!;\n const pid = prog.compiled.placeId(mk.place);\n for (const token of this.tokenQueues[pid]!) {\n const name = mk.key(token.value);\n if (name !== undefined && name !== null) matcher.add(keyIdx, name, token.createdAt);\n }\n this.placeMatchTargets[pid]!.push([tid, keyIdx]);\n }\n this.matchCaches[tid] = matcher;\n }\n }\n\n /** Mirror a token added to correlated input `pid` into every fast-path matcher. */\n private cacheAddToken(pid: number, token: Token<any>): void {\n const targets = this.placeMatchTargets[pid];\n if (targets === undefined || targets.length === 0) return;\n const prog = this.program;\n for (const [tid, keyIdx] of targets) {\n const cache = this.matchCaches[tid];\n if (cache == null) continue;\n const t = prog.compiled.transition(tid);\n const mk = t.matchSpec!.keys[keyIdx]!;\n const name = mk.key(token.value);\n if (name !== undefined && name !== null) cache.add(keyIdx, name, token.createdAt);\n }\n }\n\n // ======================== Bitmap Helpers ========================\n\n private markTransitionDirty(tid: number): void {\n this.dirtyBitmap[tid >>> WORD_SHIFT]! |= (1 << (tid & BIT_MASK));\n }\n\n private markDirty(pid: number): void {\n const tids = this.program.placeToTransitions[pid]!;\n for (let i = 0; i < tids.length; i++) {\n this.markTransitionDirty(tids[i]!);\n }\n }\n\n private setMarkingBit(pid: number): void {\n this.markingBitmap[pid >>> WORD_SHIFT]! |= (1 << (pid & BIT_MASK));\n }\n\n private clearMarkingBit(pid: number): void {\n this.markingBitmap[pid >>> WORD_SHIFT]! &= ~(1 << (pid & BIT_MASK));\n }\n\n // ======================== Execution ========================\n\n async run(timeoutMs?: number, onTimeout: RunTimeoutPolicy = 'abandon'): Promise<Marking> {\n if (timeoutMs === undefined) return this.executeLoop();\n\n let timer: ReturnType<typeof setTimeout> | undefined;\n let timedOut = false;\n const timeoutPromise = new Promise<never>((_, reject) => {\n timer = setTimeout(() => {\n timedOut = true;\n reject(new Error('Execution timed out'));\n }, timeoutMs);\n });\n // Held rather than inlined into the race: Promise.race walks away from the\n // loser, it does not cancel it, so the loop needs handling of its own.\n const loop = this.executeLoop();\n try {\n return await Promise.race([loop, timeoutPromise]);\n } finally {\n if (timer !== undefined) clearTimeout(timer);\n if (timedOut) {\n if (onTimeout === 'close') this.close();\n // Nobody is left to observe the abandoned loop's outcome.\n loop.catch(() => {});\n }\n }\n }\n\n private async executeLoop(): Promise<Marking> {\n this.running = true;\n const prog = this.program;\n\n this.emitEvent({\n type: 'execution-started',\n timestamp: Date.now(),\n netName: prog.compiled.net.name,\n executionId: this.executionId(),\n });\n\n this.initializeMarkingBitmap();\n this.markAllDirty();\n\n this.emitEvent({\n type: 'marking-snapshot',\n timestamp: Date.now(),\n marking: this.snapshotMarking(),\n });\n\n while (this.running) {\n this.processCompletedTransitions();\n this.processExternalEvents();\n this.updateDirtyTransitions();\n\n const cycleNowMs = performance.now();\n if (prog.anyDeadlines) this.enforceDeadlines(cycleNowMs);\n\n if (this.shouldTerminate()) break;\n\n this.fireReadyTransitions(cycleNowMs);\n if (this.hasDirtyBits()) continue;\n await this.awaitWork();\n }\n\n this.running = false;\n this.drainPendingExternalEvents();\n\n this.emitEvent({\n type: 'marking-snapshot',\n timestamp: Date.now(),\n marking: this.snapshotMarking(),\n });\n\n this.emitEvent({\n type: 'execution-completed',\n timestamp: Date.now(),\n netName: prog.compiled.net.name,\n executionId: this.executionId(),\n totalDurationMs: performance.now() - this.startMs,\n });\n\n return this.syncMarkingFromQueues();\n }\n\n // ======================== Environment Place API ========================\n\n async inject<T>(envPlace: EnvironmentPlace<T>, token: Token<T>): Promise<boolean> {\n if (!this.environmentPlaces.has(envPlace.place.name)) {\n throw new Error(`Place ${envPlace.place.name} is not registered as an environment place`);\n }\n if (this.closed || this.draining) return false;\n\n return new Promise<boolean>((resolve, reject) => {\n this.externalQueue.push({\n place: envPlace.place,\n token,\n resolve,\n reject,\n });\n this.wakeUp();\n });\n }\n\n async injectValue<T>(envPlace: EnvironmentPlace<T>, value: T): Promise<boolean> {\n return this.inject(envPlace, tokenOf(value));\n }\n\n // ======================== Initialize ========================\n\n private initializeMarkingBitmap(): void {\n for (let pid = 0; pid < this.program.placeCount; pid++) {\n if (this.tokenQueues[pid]!.length > 0) {\n this.setMarkingBit(pid);\n }\n }\n }\n\n private markAllDirty(): void {\n const tw = this.transitionWords;\n const tc = this.program.transitionCount;\n for (let w = 0; w < tw - 1; w++) {\n this.dirtyBitmap[w] = 0xFFFFFFFF;\n }\n if (tw > 0) {\n const lastBits = tc & BIT_MASK;\n this.dirtyBitmap[tw - 1] = lastBits === 0 ? 0xFFFFFFFF : (1 << lastBits) - 1;\n }\n }\n\n private shouldTerminate(): boolean {\n if (this.closed) {\n // ENV-013: immediate close — wait for in-flight actions to complete\n return this.inFlightCount === 0 && this.completionQueue.length === 0;\n }\n if (this.hasEnvironmentPlaces) {\n return this.draining\n && this.enabledTransitionCount === 0\n && this.inFlightCount === 0\n && this.completionQueue.length === 0;\n }\n return this.enabledTransitionCount === 0\n && this.inFlightCount === 0\n && this.completionQueue.length === 0;\n }\n\n // ======================== Dirty Set Processing ========================\n\n private updateDirtyTransitions(): void {\n const nowMs = performance.now();\n const prog = this.program;\n const tc = prog.transitionCount;\n\n // Snapshot marking bitmap\n const markingSnap = this.markingSnapBuffer;\n markingSnap.set(this.markingBitmap);\n\n // Snapshot-and-clear dirty set\n const tw = this.transitionWords;\n const dirtySnap = this.dirtyScanBuffer;\n for (let w = 0; w < tw; w++) {\n dirtySnap[w] = this.dirtyBitmap[w]!;\n this.dirtyBitmap[w] = 0;\n }\n\n // Iterate dirty transitions using Kernighan's bit trick\n for (let w = 0; w < tw; w++) {\n let word = dirtySnap[w]!;\n if (word === 0) continue;\n dirtySnap[w] = 0; // clear for next cycle\n while (word !== 0) {\n const bit = Math.clz32(word & -word) ^ 31;\n const tid = (w << WORD_SHIFT) | bit;\n word &= word - 1;\n\n if (tid >= tc) break;\n if (this.inFlightFlags[tid]) continue;\n\n const wasEnabled = this.enabledFlags[tid] !== 0;\n const canNow = this.canEnable(tid, markingSnap);\n\n if (canNow && !wasEnabled) {\n this.enabledFlags[tid] = 1;\n this.enabledTransitionCount++;\n this.enabledAtMs[tid] = nowMs;\n this.emitEvent({\n type: 'transition-enabled',\n timestamp: Date.now(),\n transitionName: prog.compiled.transition(tid).name,\n });\n } else if (!canNow && wasEnabled) {\n this.enabledFlags[tid] = 0;\n this.enabledTransitionCount--;\n this.enabledAtMs[tid] = -Infinity;\n } else if (canNow && wasEnabled && this.hasInputFromResetPlace(tid)) {\n this.enabledAtMs[tid] = nowMs;\n this.emitEvent({\n type: 'transition-clock-restarted',\n timestamp: Date.now(),\n transitionName: prog.compiled.transition(tid).name,\n });\n }\n }\n }\n\n if (this.hasPendingResets) {\n this.pendingResetWords.fill(0);\n this.hasPendingResets = false;\n }\n }\n\n private enforceDeadlines(nowMs: number): void {\n const prog = this.program;\n const tc = prog.transitionCount;\n\n for (let tid = 0; tid < tc; tid++) {\n if (!prog.hasDeadline[tid]) continue;\n // exact() is enforced softly — it fires at the first opportunity at/after its target and is\n // never force-disabled (TIME-006). Only hard deadlines (deadline()/window()) are reaped here.\n if (prog.isExact[tid]) continue;\n if (!this.enabledFlags[tid] || this.inFlightFlags[tid]) continue;\n\n const elapsed = nowMs - this.enabledAtMs[tid]!;\n const latestMs = prog.latestMs[tid]!;\n if (elapsed > latestMs + this.deadlineToleranceMs) {\n this.enabledFlags[tid] = 0;\n this.enabledTransitionCount--;\n this.enabledAtMs[tid] = -Infinity;\n this.emitEvent({\n type: 'transition-timed-out',\n timestamp: Date.now(),\n transitionName: prog.compiled.transition(tid).name,\n deadlineMs: latestMs,\n actualDurationMs: elapsed,\n });\n }\n }\n }\n\n private canEnable(tid: number, markingSnap: Uint32Array): boolean {\n const prog = this.program;\n\n // Sparse bitmap check\n if (!prog.canEnableSparse(tid, markingSnap)) return false;\n\n // Cardinality check\n const cardCheck = prog.cardinalityChecks[tid] ?? null;\n if (cardCheck !== null) {\n for (let i = 0; i < cardCheck.placeIds.length; i++) {\n const pid = cardCheck.placeIds[i]!;\n if (this.tokenQueues[pid]!.length < cardCheck.requiredCounts[i]!) return false;\n }\n }\n\n // ν-net join: a correlation name must satisfy every matched input (NU-020).\n // Gated on the precomputed `hasMatch` flag so non-ν transitions never fetch\n // the Transition object on this hot path (zero-cost gating, mirroring\n // Rust's `has_match(tid)`).\n if (prog.hasMatch[tid]) {\n const cache = this.matchCaches[tid];\n const noBinding = cache != null\n ? cache.best() === null\n : findBinding(prog.compiled.transition(tid), p => this.tokenQueues[prog.compiled.placeId(p)]!) === null;\n if (noBinding) {\n return false;\n }\n }\n\n return true;\n }\n\n private countMatching(pid: number, predicate: (value: any) => boolean): number {\n const q = this.tokenQueues[pid]!;\n let matching = 0;\n for (let i = 0; i < q.length; i++) {\n if (predicate(q[i]!.value)) matching++;\n }\n return matching;\n }\n\n private removeFirstMatching(pid: number, predicate: (value: any) => boolean): Token<any> | null {\n const q = this.tokenQueues[pid]!;\n for (let i = 0; i < q.length; i++) {\n if (predicate(q[i]!.value)) {\n // Head removal (the common ν-net case — the matched token is the oldest,\n // hence at the front when timestamps are distinct) uses the V8-optimized\n // shift() rather than an O(n) splice, keeping a draining join linear.\n return i === 0 ? q.shift()! : q.splice(i, 1)[0]!;\n }\n }\n return null;\n }\n\n private hasInputFromResetPlace(tid: number): boolean {\n if (!this.hasPendingResets) return false;\n const inputMask = this.program.inputPlaceMaskWords[tid]!;\n for (let w = 0; w < inputMask.length; w++) {\n if ((inputMask[w]! & this.pendingResetWords[w]!) !== 0) return true;\n }\n return false;\n }\n\n // ======================== Firing ========================\n\n private fireReadyTransitions(nowMs: number): void {\n if (this.program.allImmediate && this.program.allSamePriority) {\n this.fireReadyImmediate();\n return;\n }\n this.fireReadyGeneral(nowMs);\n }\n\n /**\n * Fast path for nets where all transitions are immediate and same priority.\n * Simple linear scan matching BitmapNetExecutor's pattern.\n */\n private fireReadyImmediate(): void {\n const tc = this.program.transitionCount;\n\n for (let tid = 0; tid < tc; tid++) {\n if (!this.enabledFlags[tid] || this.inFlightFlags[tid]) continue;\n if (this.canEnable(tid, this.markingBitmap)) {\n this.fireTransitionContained(tid);\n } else {\n this.enabledFlags[tid] = 0;\n this.enabledTransitionCount--;\n this.enabledAtMs[tid] = -Infinity;\n }\n }\n }\n\n private fireReadyGeneral(nowMs: number): void {\n const prog = this.program;\n const tc = prog.transitionCount;\n\n // Collect ready transitions into pre-allocated buffer\n const ready = this.readyBuffer;\n ready.length = 0;\n for (let tid = 0; tid < tc; tid++) {\n if (!this.enabledFlags[tid] || this.inFlightFlags[tid]) continue;\n const elapsedMs = nowMs - this.enabledAtMs[tid]!;\n if (prog.earliestMs[tid]! <= elapsedMs) {\n ready.push({ tid, priority: prog.priorities[tid]!, enabledAtMs: this.enabledAtMs[tid]! });\n }\n }\n if (ready.length === 0) return;\n\n // Sort: higher priority first, then earlier enablement (FIFO)\n ready.sort((a, b) => {\n const prioCmp = b.priority - a.priority;\n if (prioCmp !== 0) return prioCmp;\n return a.enabledAtMs - b.enabledAtMs;\n });\n\n // Take a fresh snapshot for re-checking\n const freshSnap = this.firingSnapBuffer;\n freshSnap.set(this.markingBitmap);\n for (const entry of ready) {\n const { tid } = entry;\n if (this.enabledFlags[tid] && this.canEnable(tid, freshSnap)) {\n this.fireTransitionContained(tid);\n freshSnap.set(this.markingBitmap);\n } else {\n this.enabledFlags[tid] = 0;\n this.enabledTransitionCount--;\n this.enabledAtMs[tid] = -Infinity;\n }\n }\n }\n\n /**\n * Fires a transition, containing any synchronous throw to that one firing so it fails\n * only that transition, not the whole run.\n *\n * Without this boundary an unchecked throw raised while a transition fires — a hostile\n * EventStore.append on a token-removed or transition-started emit, or an error thrown while\n * consuming the matched tokens — unwinds out of the orchestrator loop and kills the executor.\n * The transition is instead failed and marked dirty for re-evaluation, the same treatment an\n * asynchronously-reported failure gets. Enablement-phase throws (a key function that\n * throws inside canEnable, before the firing) run outside this boundary and are not contained\n * here.\n *\n * fireTransition drains tokens from the queues before it reconciles the presence bitmap,\n * so a throw inside that window would leave bits asserting tokens that are gone; the\n * recovery re-runs updateBitmapAfterConsumption against the true queue lengths.\n *\n * Unlike the Java runtime there is no VirtualMachineError/LinkageError analogue on\n * the JS side, so every throw is contained here — there is deliberately no\n * fatal-rethrow escape hatch.\n */\n private fireTransitionContained(tid: number): void {\n try {\n this.fireTransition(tid);\n } catch (e) {\n const t = this.program.compiled.transition(tid);\n if (this.enabledFlags[tid]) {\n this.enabledFlags[tid] = 0;\n this.enabledTransitionCount--;\n this.enabledAtMs[tid] = -Infinity;\n }\n if (this.inFlightFlags[tid]) {\n this.inFlightPromises[tid] = null;\n this.inFlightContexts[tid] = null;\n this.inFlightConsumed[tid] = null;\n this.inFlightResolves[tid] = null;\n this.inFlightErrors[tid] = null;\n this.inFlightFlags[tid] = 0;\n this.inFlightCount--;\n }\n this.updateBitmapAfterConsumption(tid);\n // Drop the ν fast-path matcher: fireTransition mirrors the matched consume into it\n // before the tokens leave the queues, so a throw in that window desyncs it. Nulling\n // it forces the next canEnable/fire to rebuild the binding via findBinding.\n this.matchCaches[tid] = null;\n const err = e instanceof Error ? e : new Error(String(e));\n this.emitEvent({\n type: 'transition-failed',\n timestamp: Date.now(),\n transitionName: t.name,\n errorMessage: err.message,\n exceptionType: err.name,\n stack: err.stack,\n });\n this.markTransitionDirty(tid);\n }\n }\n\n private fireTransition(tid: number): void {\n const prog = this.program;\n const t = prog.compiled.transition(tid);\n const consumed: Token<any>[] = [];\n const inputs = new TokenInput();\n\n // ==================== Opcode Dispatch ====================\n // In-firing order: inputs → read peeks → resets, split at\n // PrecompiledNet.resetOpsStart (EXEC-013 AC4).\n if (t.matchSpec) {\n // ν-net join (NU-020): bypass the opcode fast path, consume name-matched\n // tokens. Read arcs are peeked inside, at the same input/reset boundary.\n this.fireTransitionMatched(tid, t, inputs, consumed);\n } else {\n const ops = prog.consumeOps[tid]!;\n const resetOpsStart = prog.resetOpsStart[tid]!;\n let pc = 0;\n while (pc < resetOpsStart) {\n const opcode = ops[pc++]!;\n switch (opcode) {\n case CONSUME_ONE: {\n const pid = ops[pc++]!;\n const token = this.tokenQueues[pid]!.shift()!;\n consumed.push(token);\n inputs.add(prog.places[pid]!, token);\n this.emitEvent({\n type: 'token-removed',\n timestamp: Date.now(),\n placeName: prog.places[pid]!.name,\n token,\n });\n break;\n }\n case CONSUME_N: {\n const pid = ops[pc++]!;\n const count = ops[pc++]!;\n const place = prog.places[pid]!;\n for (let i = 0; i < count; i++) {\n const token = this.tokenQueues[pid]!.shift()!;\n consumed.push(token);\n inputs.add(place, token);\n this.emitEvent({\n type: 'token-removed',\n timestamp: Date.now(),\n placeName: place.name,\n token,\n });\n }\n break;\n }\n case CONSUME_ALL: {\n const pid = ops[pc++]!;\n const place = prog.places[pid]!;\n const q = this.tokenQueues[pid]!;\n const count = q.length;\n for (let i = 0; i < count; i++) {\n const token = q.shift()!;\n consumed.push(token);\n inputs.add(place, token);\n this.emitEvent({\n type: 'token-removed',\n timestamp: Date.now(),\n placeName: place.name,\n token,\n });\n }\n break;\n }\n case CONSUME_ATLEAST: {\n const pid = ops[pc++]!;\n pc++; // skip minimum (already validated in canEnable)\n const place = prog.places[pid]!;\n const q = this.tokenQueues[pid]!;\n const count = q.length;\n for (let i = 0; i < count; i++) {\n const token = q.shift()!;\n consumed.push(token);\n inputs.add(place, token);\n this.emitEvent({\n type: 'token-removed',\n timestamp: Date.now(),\n placeName: place.name,\n token,\n });\n }\n break;\n }\n default:\n throw new Error(`Unknown opcode: ${opcode}`);\n }\n }\n\n // Read arcs (peek, don't consume) — before resets drain (EXEC-013)\n this.peekReadArcs(tid, inputs);\n\n // RESET opcodes: [resetOpsStart, ops.length)\n while (pc < ops.length) {\n const opcode = ops[pc++]!;\n if (opcode !== RESET) {\n throw new Error(`Unknown opcode: ${opcode} (expected RESET past resetOpsStart)`);\n }\n const pid = ops[pc++]!;\n const place = prog.places[pid]!;\n const tokens = this.tokenQueues[pid]!.splice(0);\n this.pendingResetWords[pid >>> WORD_SHIFT]! |= (1 << (pid & BIT_MASK));\n this.hasPendingResets = true;\n for (const token of tokens) {\n consumed.push(token);\n this.emitEvent({\n type: 'token-removed',\n timestamp: Date.now(),\n placeName: place.name,\n token,\n });\n }\n }\n }\n\n // Update bitmap after consumption\n this.updateBitmapAfterConsumption(tid);\n\n this.emitEvent({\n type: 'transition-started',\n timestamp: Date.now(),\n transitionName: t.name,\n consumedTokens: consumed,\n });\n\n const execCtx = this.executionContextProvider?.(t.name, consumed);\n const logFn = (level: string, message: string, error?: Error) => {\n this.emitEvent({\n type: 'log-message',\n timestamp: Date.now(),\n transitionName: t.name,\n logger: t.name,\n level,\n message,\n error: error?.name ?? null,\n errorMessage: error?.message ?? null,\n });\n };\n const context = new TransitionContext(\n t.name, inputs, new TokenOutput(),\n t.inputPlaces(), t.readPlaces(), t.outputPlaces(),\n execCtx,\n logFn,\n t.placeAlias,\n );\n let freshNameSupplier = this.freshNameSuppliers[tid];\n if (freshNameSupplier === undefined) {\n const base = t.name;\n freshNameSupplier = () => nameId(`${base}#${this.freshNameCounter++}`);\n this.freshNameSuppliers[tid] = freshNameSupplier;\n }\n context.setFreshNameSupplier(freshNameSupplier);\n\n // Create action promise with optional timeout. executeAction converts a synchronous\n // throw or a null/non-thenable return into a rejected promise, so a misbehaving action\n // flows the contained failure path instead of unwinding the orchestrator loop.\n let actionPromise = executeAction(t, context);\n\n if (t.hasActionTimeout()) {\n const timeoutSpec = t.actionTimeout;\n if (timeoutSpec === null) throw new Error(`Expected actionTimeout on ${t.name}`);\n const timeoutMs = timeoutSpec.afterMs;\n actionPromise = Promise.race([\n actionPromise,\n new Promise<void>((_, reject) =>\n setTimeout(() => reject(new TimeoutSentinel()), timeoutMs)\n ),\n ]).catch((err) => {\n if (err instanceof TimeoutSentinel) {\n // Sever first, then produce: the abandoned action may still be writing to this\n // context, and its pre-timeout writes must not merge with the timeout branch.\n context.detachForTimeout();\n produceTimeoutOutput(context, timeoutSpec.child);\n this.emitEvent({\n type: 'action-timed-out',\n timestamp: Date.now(),\n transitionName: t.name,\n timeoutMs,\n });\n return;\n }\n throw err;\n });\n }\n\n // Track in-flight\n let resolveInFlight!: () => void;\n const completionPromise = new Promise<void>(r => { resolveInFlight = r; });\n\n this.inFlightPromises[tid] = completionPromise;\n this.inFlightContexts[tid] = context;\n this.inFlightConsumed[tid] = consumed;\n this.inFlightStartMs[tid] = performance.now();\n this.inFlightResolves[tid] = resolveInFlight;\n this.inFlightErrors[tid] = null;\n\n actionPromise.then(\n () => {\n this.completionQueue.push(tid);\n this.wakeUp();\n resolveInFlight();\n },\n (err) => {\n this.inFlightErrors[tid] = err;\n this.completionQueue.push(tid);\n this.wakeUp();\n resolveInFlight();\n },\n );\n\n this.inFlightFlags[tid] = 1;\n this.inFlightCount++;\n this.enabledFlags[tid] = 0;\n this.enabledTransitionCount--;\n this.enabledAtMs[tid] = -Infinity;\n }\n\n /**\n * Consumes the name-matched tokens for a ν-net join (NU-020): correlated\n * inputs take tokens whose projected name equals the chosen binding (NU-021);\n * other inputs consume FIFO. Reset arcs are honoured as on the opcode path.\n */\n private fireTransitionMatched(tid: number, t: Transition, inputs: TokenInput, consumed: Token<any>[]): void {\n const prog = this.program;\n const ms = t.matchSpec!;\n const cache = this.matchCaches[tid];\n const chosen = cache != null\n ? cache.best()\n : findBinding(t, p => this.tokenQueues[prog.compiled.placeId(p)]!);\n // Mirror the matched consume into the fast-path matcher (the only path by\n // which tokens leave this join's correlated inputs) before the token queues\n // change, keeping it in lockstep.\n if (cache != null && chosen !== null) cache.consume(chosen);\n\n for (const inSpec of t.inputSpecs) {\n const pid = prog.compiled.placeId(inSpec.place);\n const keyFn = keyForPlace(ms, inSpec.place.name);\n const pred: ((value: any) => boolean) | undefined =\n (keyFn && chosen !== null)\n ? (v: any) => keyFn(v) === chosen\n : undefined;\n\n let toConsume: number;\n switch (inSpec.type) {\n case 'one': toConsume = 1; break;\n case 'exactly': toConsume = inSpec.count; break;\n case 'all':\n case 'at-least':\n toConsume = pred ? this.countMatching(pid, pred) : this.tokenQueues[pid]!.length;\n break;\n }\n\n for (let i = 0; i < toConsume; i++) {\n const token = pred\n ? this.removeFirstMatching(pid, pred)\n : this.tokenQueues[pid]!.shift() ?? null;\n if (token === null) break;\n consumed.push(token);\n inputs.add(inSpec.place, token);\n this.emitEvent({\n type: 'token-removed',\n timestamp: Date.now(),\n placeName: inSpec.place.name,\n token,\n });\n }\n }\n\n // Read arcs (peek, don't consume) — before resets drain (EXEC-013)\n this.peekReadArcs(tid, inputs);\n\n // Reset arcs\n for (const arc of t.resets) {\n const pid = prog.compiled.placeId(arc.place);\n const tokens = this.tokenQueues[pid]!.splice(0);\n this.pendingResetWords[pid >>> WORD_SHIFT]! |= (1 << (pid & BIT_MASK));\n this.hasPendingResets = true;\n for (const token of tokens) {\n consumed.push(token);\n this.emitEvent({\n type: 'token-removed',\n timestamp: Date.now(),\n placeName: arc.place.name,\n token,\n });\n }\n }\n }\n\n /**\n * Peeks each read-arc place's front token into the context inputs. Called at\n * the input/reset boundary of a firing (EXEC-013): after input consumption,\n * before reset draining — so read(p)+reset(p) observes the pre-reset token.\n */\n private peekReadArcs(tid: number, inputs: TokenInput): void {\n const prog = this.program;\n const readPids = prog.readOps[tid]!;\n for (let i = 0; i < readPids.length; i++) {\n const pid = readPids[i]!;\n const q = this.tokenQueues[pid]!;\n if (q.length > 0) {\n inputs.add(prog.places[pid]!, q[0]!);\n }\n }\n }\n\n private updateBitmapAfterConsumption(tid: number): void {\n const pids = this.program.consumptionPlaceIds[tid]!;\n for (let i = 0; i < pids.length; i++) {\n const pid = pids[i]!;\n if (this.tokenQueues[pid]!.length === 0) {\n this.clearMarkingBit(pid);\n }\n this.markDirty(pid);\n }\n }\n\n // ======================== Completion Processing ========================\n\n private processCompletedTransitions(): void {\n if (this.completionQueue.length === 0) return;\n const prog = this.program;\n const len = this.completionQueue.length;\n\n for (let i = 0; i < len; i++) {\n const tid = this.completionQueue[i]!;\n const context = this.inFlightContexts[tid]!;\n const error = this.inFlightErrors[tid];\n const startMs = this.inFlightStartMs[tid]!;\n const t = prog.compiled.transition(tid);\n\n // Clear in-flight state\n this.inFlightFlags[tid] = 0;\n this.inFlightPromises[tid] = null;\n this.inFlightContexts[tid] = null;\n this.inFlightConsumed[tid] = null;\n this.inFlightResolves[tid] = null;\n this.inFlightErrors[tid] = null;\n this.inFlightCount--;\n\n if (error) {\n const err = error instanceof Error ? error : new Error(String(error));\n this.emitEvent({\n type: 'transition-failed',\n timestamp: Date.now(),\n transitionName: t.name,\n errorMessage: err.message,\n exceptionType: err.name,\n stack: err.stack,\n });\n this.markTransitionDirty(tid);\n continue;\n }\n\n try {\n const outputs = context.rawOutput();\n\n // Validate output\n if (!this.skipOutputValidation && t.outputSpec !== null) {\n const simplePid = prog.simpleOutputPlaceId[tid]!;\n if (simplePid >= 0) {\n const produced = outputs.placesWithTokens();\n if (!produced.has(prog.places[simplePid]!.name)) {\n // Same wording the general path emits: for a bare `Out.Place` the\n // spec names one place, so on failure nothing it names was written\n // and the exact-explanation verdict is identical to this check.\n throw new OutViolationError(\n `'${t.name}': output does not match the declared spec - produced {}, ` +\n `which no single branch of the spec claims exactly`\n );\n }\n } else if (simplePid === -1) {\n validateOutSpec(t.name, t.outputSpec, outputs.placesWithTokens());\n }\n }\n\n // Add output tokens to queues\n const produced: Token<any>[] = [];\n for (const entry of outputs.entries()) {\n this.produceToken(entry.place, entry.token, t.name);\n produced.push(entry.token);\n this.emitEvent({\n type: 'token-added',\n timestamp: Date.now(),\n placeName: entry.place.name,\n token: entry.token,\n });\n }\n this.markTransitionDirty(tid);\n\n this.emitEvent({\n type: 'transition-completed',\n timestamp: Date.now(),\n transitionName: t.name,\n producedTokens: produced,\n durationMs: performance.now() - startMs,\n });\n } catch (e) {\n const err = e instanceof Error ? e : new Error(String(e));\n this.emitEvent({\n type: 'transition-failed',\n timestamp: Date.now(),\n transitionName: t.name,\n errorMessage: err.message,\n exceptionType: err.name,\n stack: err.stack,\n });\n this.markTransitionDirty(tid);\n }\n }\n this.completionQueue.length = 0;\n }\n\n // ======================== External Events ========================\n\n private processExternalEvents(): void {\n if (this.externalQueue.length === 0) return;\n if (this.closed) return; // ENV-013: leave queued events for drainPendingExternalEvents()\n const len = this.externalQueue.length;\n\n for (let i = 0; i < len; i++) {\n const event = this.externalQueue[i]!;\n try {\n this.produceToken(event.place, event.token, '');\n\n this.emitEvent({\n type: 'token-added',\n timestamp: Date.now(),\n placeName: event.place.name,\n token: event.token,\n });\n event.resolve(true);\n } catch (e) {\n event.reject(e instanceof Error ? e : new Error(String(e)));\n }\n }\n this.externalQueue.length = 0;\n }\n\n /**\n * Adds a produced or injected token: queue/bitmap/dirty for compiled places,\n * or the retention side map when the program does not know it (CORE-072 AC3).\n * `transitionName` is the producer, empty at the injection seam.\n */\n private produceToken(place: Place<any>, token: Token<any>, transitionName: string): void {\n const pid = this.program.compiled.tryPlaceId(place);\n if (pid === undefined) {\n this.retainUnknownToken(place, token, transitionName);\n return;\n }\n this.cacheAddToken(pid, token);\n this.tokenQueues[pid]!.push(token);\n this.setMarkingBit(pid);\n this.markDirty(pid);\n }\n\n /**\n * Retains a token on an undeclared place (CORE-072 AC3) and reports the place\n * once — the first insert is the only one that creates a map entry, so a hot\n * loop cannot flood (AC4, emitted as the EVT-013 log-message event).\n */\n private retainUnknownToken(place: Place<any>, token: Token<any>, transitionName: string): void {\n const retained = this.unknownPlaceTokens.get(place.name);\n if (retained !== undefined) {\n retained.tokens.push(token);\n return;\n }\n this.unknownPlaceTokens.set(place.name, { place, tokens: [token] });\n this.emitEvent({\n type: 'log-message',\n timestamp: Date.now(),\n transitionName,\n logger: 'libpetri.runtime',\n level: 'WARN',\n message: `unknown place '${place.name}': tokens are retained in the marking but inert `\n + '(the net declares no arc on it)',\n error: null,\n errorMessage: null,\n });\n }\n\n private drainPendingExternalEvents(): void {\n while (this.externalQueue.length > 0) {\n this.externalQueue.shift()!.resolve(false);\n }\n }\n\n // ======================== Await Work ========================\n\n private async awaitWork(): Promise<void> {\n // When closed, ignore external queue — processExternalEvents() won't consume it,\n // and drainPendingExternalEvents() handles it after the loop exits.\n if (this.completionQueue.length > 0 || (!this.closed && this.externalQueue.length > 0)) return;\n\n await Promise.resolve();\n if (this.completionQueue.length > 0 || (!this.closed && this.externalQueue.length > 0)) return;\n // ENV-013: when closed with no in-flight, exit immediately for shouldTerminate()\n if (this.closed && this.inFlightCount === 0) return;\n\n const promises = this.awaitPromises;\n promises.length = 0;\n\n // In-flight completion\n if (this.inFlightCount > 0) {\n const arr = this.racePromises;\n arr.length = 0;\n for (let tid = 0; tid < this.program.transitionCount; tid++) {\n if (this.inFlightPromises[tid] !== null) {\n arr.push(this.inFlightPromises[tid]!);\n }\n }\n if (arr.length > 0) {\n promises.push(Promise.race(arr));\n }\n }\n\n // When closed, only wait for in-flight completions — skip event/timer promises\n if (!this.closed) {\n // Zero means a timing boundary is already due: an earliest firing time has\n // been reached, or a deadline needs enforcing. There is nothing to wait for,\n // and with no action in flight the race below would hold only the external\n // wake-up promise — which a net with no environment places has nobody to\n // resolve, so the loop would sleep until its run budget expired. Return and\n // let the next cycle act on the boundary. Rust reaches the same outcome via\n // sleep(0); Java returns early on `millisUntilNextTimedTransition() <= 0`.\n const timerMs = this.millisUntilNextTimedTransition();\n if (timerMs === 0 && promises.length === 0) return;\n\n // External event wake-up\n promises.push(new Promise<void>(resolve => { this.wakeUpResolve = resolve; }));\n\n // Timer for next timed transition\n if (timerMs > 0 && timerMs < Infinity) {\n promises.push(new Promise<void>(r => setTimeout(r, timerMs)));\n }\n }\n\n if (promises.length > 0) {\n await Promise.race(promises);\n }\n this.wakeUpResolve = null;\n }\n\n private millisUntilNextTimedTransition(): number {\n const nowMs = performance.now();\n const prog = this.program;\n const tc = prog.transitionCount;\n let minWaitMs = Infinity;\n\n for (let tid = 0; tid < tc; tid++) {\n if (!this.enabledFlags[tid]) continue;\n\n const enabledMs = this.enabledAtMs[tid]!;\n const elapsedMs = nowMs - enabledMs;\n\n const eMs = prog.earliestMs[tid]!;\n const remainingEarliest = eMs - elapsedMs;\n if (remainingEarliest <= 0) return 0;\n minWaitMs = Math.min(minWaitMs, remainingEarliest);\n\n if (prog.hasDeadline[tid]) {\n const lMs = prog.latestMs[tid]!;\n const remainingDeadline = lMs - elapsedMs;\n if (remainingDeadline <= 0) return 0;\n minWaitMs = Math.min(minWaitMs, remainingDeadline);\n }\n }\n return minWaitMs;\n }\n\n private wakeUp(): void {\n this.wakeUpResolve?.();\n }\n\n // ======================== Dirty Set Helpers ========================\n\n private hasDirtyBits(): boolean {\n for (let w = 0; w < this.transitionWords; w++) {\n if (this.dirtyBitmap[w] !== 0) return true;\n }\n return false;\n }\n\n // ======================== Lazy Marking Sync ========================\n\n private syncMarkingFromQueues(): Marking {\n const prog = this.program;\n const m = Marking.empty();\n for (let pid = 0; pid < prog.placeCount; pid++) {\n const q = this.tokenQueues[pid]!;\n if (q.length === 0) continue;\n const place = prog.places[pid]!;\n for (let i = 0; i < q.length; i++) {\n m.addToken(place, q[i]!);\n }\n }\n // CORE-072: merge retained tokens on undeclared places into the observable\n // marking (empty map for well-formed inputs — no hot-path cost).\n for (const { place, tokens } of this.unknownPlaceTokens.values()) {\n for (const token of tokens) {\n m.addToken(place, token);\n }\n }\n this.marking = m;\n return m;\n }\n\n // ======================== State Inspection ========================\n\n getMarking(): Marking {\n return this.marking ?? this.syncMarkingFromQueues();\n }\n\n private snapshotMarking(): ReadonlyMap<string, readonly Token<any>[]> {\n const prog = this.program;\n const snap = new Map<string, readonly Token<any>[]>();\n for (let pid = 0; pid < prog.placeCount; pid++) {\n const q = this.tokenQueues[pid]!;\n if (q.length === 0) continue;\n snap.set(prog.places[pid]!.name, [...q]);\n }\n return snap;\n }\n\n isQuiescent(): boolean {\n return this.enabledTransitionCount === 0 && this.inFlightCount === 0;\n }\n\n executionId(): string {\n return this.startMs.toString(16);\n }\n\n drain(): void {\n this.draining = true;\n this.wakeUp();\n }\n\n close(): void {\n this.draining = true;\n this.closed = true;\n this.wakeUp();\n }\n\n // ======================== Event Emission ========================\n\n private emitEvent(event: NetEvent): void {\n if (this.eventStoreEnabled) {\n // A user EventStore.append that throws is observation failing, not control flow:\n // swallow it so a hostile store cannot unwind the orchestrator loop. One choke\n // point covers every emit site.\n try {\n this.eventStore.append(event);\n } catch (err) {\n swallowEventStoreFailure(event.type, err);\n }\n }\n }\n}\n\n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mBAAmB;AAI1B,UAAI;AACF,aAAK,WAAW,OAAO,KAAK;AAAA,MAC9B,SAAS,KAAK;AACZ,iCAAyB,MAAM,MAAM,GAAG;AAAA,MAC1C;AAAA,IACF;AAAA,EACF;AACF;AAEA,IAAME,mBAAN,cAA8B,MAAM;AAAA,EAClC,cAAc;AAAE,UAAM,gBAAgB;AAAG,SAAK,OAAO;AAAA,EAAmB;AAC1E;","names":["place","place","place","place","matchSpec","place","place","EMPTY_ALIAS","i","place","place","place","place","place","place","exact","place","resolve","place","resolve","TimeoutSentinel","produced"]}
|
|
1
|
+
{"version":3,"sources":["../src/core/token.ts","../src/core/place.ts","../src/core/arc.ts","../src/core/name.ts","../src/core/token-output.ts","../src/core/transition-context.ts","../src/core/token-input.ts","../src/core/transition.ts","../src/core/interface.ts","../src/core/instance.ts","../src/core/internal/subnet-rewriter.ts","../src/verification/verification-harness.ts","../src/core/subnet-def.ts","../src/core/compose-bindings.ts","../src/core/fusion-set.ts","../src/core/petri-net.ts","../src/core/subnet.ts","../src/runtime/marking.ts","../src/runtime/compiled-net.ts","../src/event/event-store.ts","../src/runtime/match-engine.ts","../src/runtime/out-violation-error.ts","../src/runtime/executor-support.ts","../src/runtime/bitmap-net-executor.ts","../src/runtime/precompiled-net.ts","../src/runtime/precompiled-net-executor.ts"],"sourcesContent":["/**\n * An immutable token carrying a typed value through the Petri net.\n *\n * Tokens flow from place to place as transitions fire, carrying typed\n * payloads that represent the state of a computation or workflow.\n */\nexport interface Token<T> {\n readonly value: T;\n /** Epoch milliseconds when the token was created. */\n readonly createdAt: number;\n /**\n * JSON-friendly projection of the token value, populated by\n * {@link SessionArchiveReader} when hydrating a v3 archive so replay\n * consumers see the same structured shape the writer emitted. Live tokens\n * (produced by {@link tokenOf} / {@link tokenAt}) leave this `undefined`;\n * the runtime ignores it. See [EVT-025](../../../spec/08-events-observability.md)\n * AC5. (libpetri 1.8.0+)\n */\n readonly structured?: unknown;\n}\n\n/** Cached singleton unit token. */\nconst UNIT_TOKEN: Token<null> = Object.freeze({\n value: null,\n createdAt: 0,\n});\n\n/** Creates a token with the given value and current timestamp. */\nexport function tokenOf<T>(value: T): Token<T> {\n return { value, createdAt: Date.now() };\n}\n\n/**\n * Returns a unit token (marker with no meaningful value).\n * Used for pure control flow where presence matters but data doesn't.\n * Returns a cached singleton whose `value` is `null`.\n */\nexport function unitToken(): Token<null> {\n return UNIT_TOKEN;\n}\n\n/** Creates a token with a specific timestamp (for testing/replay). */\nexport function tokenAt<T>(value: T, createdAt: number): Token<T> {\n return { value, createdAt };\n}\n\n/** Checks if this is the singleton unit token. */\nexport function isUnit(token: Token<unknown>): boolean {\n return token === UNIT_TOKEN;\n}\n","/**\n * A typed place in the Petri Net that holds tokens of a specific type.\n *\n * Places are the \"state containers\" of a Petri net. They hold tokens that\n * represent data or resources flowing through the net.\n *\n * Places use name-based equality (matching Java record semantics).\n * Internally use `Map<string, ...>` keyed by `place.name` for O(1) lookups.\n */\nexport interface Place<T> {\n readonly name: string;\n /** Phantom field to carry the type parameter. Never set at runtime. */\n readonly _phantom?: T;\n}\n\n/**\n * An environment place that accepts external token injection.\n * Wraps a regular Place and marks it for external event injection.\n */\nexport interface EnvironmentPlace<T> {\n readonly place: Place<T>;\n}\n\n/** Creates a typed place. */\nexport function place<T>(name: string): Place<T> {\n return { name };\n}\n\n/** Creates an environment place (external event injection point). */\nexport function environmentPlace<T>(name: string): EnvironmentPlace<T> {\n return { place: place<T>(name) };\n}\n","import type { Place } from './place.js';\n\n/**\n * Arc types connecting places to transitions in the Petri net.\n *\n * | Arc Type | Requires Token? | Consumes? | Effect |\n * |-----------|-----------------|-----------|--------------------------|\n * | Input | Yes | Yes | Token consumed on fire |\n * | Output | No | No | Token produced on complete|\n * | Inhibitor | No (blocks) | No | Disables transition |\n * | Read | Yes | No | Token remains |\n * | Reset | No | Yes (all) | All tokens removed |\n */\nexport type Arc = ArcInput | ArcOutput | ArcInhibitor | ArcRead | ArcReset;\n\nexport interface ArcInput<T = any> {\n readonly type: 'input';\n readonly place: Place<T>;\n}\n\nexport interface ArcOutput<T = any> {\n readonly type: 'output';\n readonly place: Place<T>;\n}\n\nexport interface ArcInhibitor<T = any> {\n readonly type: 'inhibitor';\n readonly place: Place<T>;\n}\n\nexport interface ArcRead<T = any> {\n readonly type: 'read';\n readonly place: Place<T>;\n}\n\nexport interface ArcReset<T = any> {\n readonly type: 'reset';\n readonly place: Place<T>;\n}\n\n// ==================== Factory Functions ====================\n\n/** Input arc: consumes token from place when transition fires. */\nexport function inputArc<T>(place: Place<T>): ArcInput<T> {\n return { type: 'input', place };\n}\n\n/** Output arc: produces token to place when transition fires. */\nexport function outputArc<T>(place: Place<T>): ArcOutput<T> {\n return { type: 'output', place };\n}\n\n/** Inhibitor arc: blocks transition if place has tokens. */\nexport function inhibitorArc<T>(place: Place<T>): ArcInhibitor<T> {\n return { type: 'inhibitor', place };\n}\n\n/** Read arc: requires token without consuming. */\nexport function readArc<T>(place: Place<T>): ArcRead<T> {\n return { type: 'read', place };\n}\n\n/** Reset arc: removes all tokens from place when firing. */\nexport function resetArc<T>(place: Place<T>): ArcReset<T> {\n return { type: 'reset', place };\n}\n\n/** Returns the place this arc connects to. */\nexport function arcPlace(arc: Arc): Place<any> {\n return arc.place;\n}\n","/**\n * ν-net token identities ([[NameId]]).\n *\n * A {@link NameId} is an **opaque correlation identity** carried by a token so\n * that a fork can mint a fresh name and a later join can re-merge exactly the\n * siblings that share it (see {@link import('./match-spec.js').MatchSpec}). The\n * only operation defined on names is **equality** (`===`); names also have a\n * lexicographic order used purely for the deterministic match tie-break\n * (NU-020).\n *\n * Identity is a *projection* of the token payload, not a field on\n * {@link import('./token.js').Token}: a `MatchSpec` declares the\n * `value → NameId` key, and the fork mints a fresh name into the payload via\n * `ctx.freshName()`. This keeps `Token` (and the event/archive formats)\n * unchanged while still giving the analyzer a name-symmetric uninterpreted sort\n * to reason about (spec NU-001).\n */\n\n/** An opaque correlation identity for ν-net fork/join (a branded string). */\nexport type NameId = string & { readonly __nameIdBrand: unique symbol };\n\n/** Creates a {@link NameId} from a string. */\nexport function nameId(value: string): NameId {\n return value as NameId;\n}\n","import type { Place } from './place.js';\nimport type { Token } from './token.js';\nimport { tokenOf } from './token.js';\n\n/**\n * An output entry: place + token pair.\n */\nexport interface OutputEntry {\n readonly place: Place<any>;\n readonly token: Token<any>;\n}\n\n/**\n * Collects output tokens produced by a transition action.\n */\nexport class TokenOutput {\n private readonly _entries: OutputEntry[] = [];\n\n /**\n * Once true, further writes are dropped instead of appended. Set by the executor\n * (via {@link import('./transition-context.js').TransitionContext.detachForTimeout})\n * when a firing times out, so the action it has stopped waiting for can no longer\n * reach the marking. Irreversible.\n */\n private detached = false;\n\n /** Add a value to an output place (creates token with current timestamp). */\n add<T>(place: Place<T>, value: T): this {\n if (this.detached) return this;\n this._entries.push({ place, token: tokenOf(value) });\n return this;\n }\n\n /** Add a pre-existing token to an output place. */\n addToken<T>(place: Place<T>, token: Token<T>): this {\n if (this.detached) return this;\n this._entries.push({ place, token });\n return this;\n }\n\n /**\n * @internal Severs this collector: subsequent {@link add}/{@link addToken} calls are\n * dropped. Executor machinery invoked when a firing times out — never call from an action.\n */\n detach(): void {\n this.detached = true;\n }\n\n /** Returns all collected outputs. */\n entries(): readonly OutputEntry[] {\n return this._entries;\n }\n\n /** Check if any outputs were produced. */\n isEmpty(): boolean {\n return this._entries.length === 0;\n }\n\n /** Returns the set of place names that received tokens. */\n placesWithTokens(): Set<string> {\n const result = new Set<string>();\n for (const entry of this._entries) {\n result.add(entry.place.name);\n }\n return result;\n }\n}\n","import type { Place } from './place.js';\nimport type { Token } from './token.js';\nimport type { TokenInput } from './token-input.js';\nimport { TokenOutput } from './token-output.js';\nimport { type NameId, nameId } from './name.js';\n\n/** Callback for emitting log messages from transition actions. */\nexport type LogFn = (level: string, message: string, error?: Error) => void;\n\n/** @internal Shared empty correspondence for the common (identity) case. */\nconst EMPTY_ALIAS: ReadonlyMap<string, Place<any>> = new Map();\n\n/**\n * @internal Process-global fallback counter for {@link TransitionContext.freshName}\n * when no executor-installed minter is present (e.g. a context built directly in\n * a unit test). Guarantees uniqueness; the executor installs a deterministic\n * per-run minter for replay-stable names.\n */\nlet GLOBAL_FRESH_NAME_COUNTER = 0;\n\n/**\n * Context provided to transition actions.\n *\n * Provides filtered access based on structure:\n * - Input places (consumed tokens)\n * - Read places (context tokens, not consumed)\n * - Output places (where to produce tokens)\n *\n * Enforces the structure contract — actions can only access places\n * declared in the transition's structure.\n */\nexport class TransitionContext {\n private readonly rawInput: TokenInput;\n /**\n * What the executor harvests. Identical to {@link writeTarget} until\n * {@link detachForTimeout} replaces it with a fresh collector the action cannot reach.\n */\n private _rawOutput: TokenOutput;\n /**\n * What the action writes to. Never reassigned, so an action already inside\n * `output(...)` cannot be redirected mid-write; severance happens by detaching this\n * collector, not by swapping it.\n */\n private readonly writeTarget: TokenOutput;\n private readonly allowedInputs: Set<string>;\n private readonly allowedReads: Set<string>;\n private readonly allowedOutputs: Set<string>;\n private readonly _inputPlaces: ReadonlySet<Place<any>>;\n private readonly _readPlaces: ReadonlySet<Place<any>>;\n private readonly _outputPlaces: ReadonlySet<Place<any>>;\n private readonly _transitionName: string;\n private readonly executionCtx: Map<string, unknown>;\n private readonly _logFn?: LogFn;\n private readonly placeAlias: ReadonlyMap<string, Place<any>>;\n private _freshNameSupplier?: () => NameId;\n\n constructor(\n transitionName: string,\n rawInput: TokenInput,\n rawOutput: TokenOutput,\n inputPlaces: ReadonlySet<Place<any>>,\n readPlaces: ReadonlySet<Place<any>>,\n outputPlaces: ReadonlySet<Place<any>>,\n executionContext?: Map<string, unknown>,\n logFn?: LogFn,\n placeAlias?: ReadonlyMap<string, Place<any>>,\n ) {\n this._transitionName = transitionName;\n this.rawInput = rawInput;\n this._rawOutput = rawOutput;\n this.writeTarget = rawOutput;\n this._inputPlaces = inputPlaces;\n this._readPlaces = readPlaces;\n this._outputPlaces = outputPlaces;\n const ai = new Set<string>();\n for (const p of inputPlaces) ai.add(p.name);\n this.allowedInputs = ai;\n const ar = new Set<string>();\n for (const p of readPlaces) ar.add(p.name);\n this.allowedReads = ar;\n const ao = new Set<string>();\n for (const p of outputPlaces) ao.add(p.name);\n this.allowedOutputs = ao;\n this.executionCtx = executionContext ?? new Map();\n this._logFn = logFn;\n this.placeAlias = placeAlias ?? EMPTY_ALIAS;\n }\n\n /**\n * Resolves a place key through the transition's declared→actual place\n * correspondence (per **MOD-031**). For a hand-written or directly-composed\n * transition the correspondence is the identity, so this returns `place`\n * unchanged; after instancing / port binding it maps a *declared* place\n * constant the action hardcodes to the *actual* composed place. The result\n * feeds both the declared-set check and the token-store access (both keyed by\n * `place.name`), so `inputPlaces()`/`outputPlaces()` discovery is unaffected.\n */\n private resolve<T>(place: Place<T>): Place<T> {\n const actual = this.placeAlias.get(place.name);\n return actual !== undefined ? (actual as Place<T>) : place;\n }\n\n // ==================== Input Access (consumed) ====================\n\n /** Get single consumed input value. Throws if place not declared or multiple tokens. */\n input<T>(place: Place<T>): T {\n const actual = this.resolve(place);\n this.requireInput(actual);\n const values = this.rawInput.values(actual);\n if (values.length !== 1) {\n throw new Error(\n `Place '${actual.name}' consumed ${values.length} tokens, use inputs() for batched access`\n );\n }\n return values[0]!;\n }\n\n /** Get all consumed input values for a place. */\n inputs<T>(place: Place<T>): readonly T[] {\n const actual = this.resolve(place);\n this.requireInput(actual);\n return this.rawInput.values(actual);\n }\n\n /** Get consumed input token with metadata. */\n inputToken<T>(place: Place<T>): Token<T> {\n const actual = this.resolve(place);\n this.requireInput(actual);\n return this.rawInput.get(actual);\n }\n\n /** Returns declared input places (consumed). */\n inputPlaces(): ReadonlySet<Place<any>> {\n return this._inputPlaces;\n }\n\n private requireInput(place: Place<any>): void {\n if (!this.allowedInputs.has(place.name)) {\n throw new Error(\n `Place '${place.name}' not in declared inputs: [${[...this.allowedInputs].join(', ')}]`\n );\n }\n }\n\n // ==================== Read Access (not consumed) ====================\n\n /** Get read-only context value. Throws if place not declared as read. */\n read<T>(place: Place<T>): T {\n const actual = this.resolve(place);\n this.requireRead(actual);\n return this.rawInput.value(actual);\n }\n\n /** Get all read-only context values for a place. */\n reads<T>(place: Place<T>): readonly T[] {\n const actual = this.resolve(place);\n this.requireRead(actual);\n return this.rawInput.values(actual);\n }\n\n /** Returns declared read places (context, not consumed). */\n readPlaces(): ReadonlySet<Place<any>> {\n return this._readPlaces;\n }\n\n private requireRead(place: Place<any>): void {\n if (!this.allowedReads.has(place.name)) {\n throw new Error(\n `Place '${place.name}' not in declared reads: [${[...this.allowedReads].join(', ')}]`\n );\n }\n }\n\n // ==================== Output Access ====================\n\n /**\n * Add one or more output values to the same place in a single call.\n *\n * Validates the place once, then appends each value to the output\n * collector. Calling with zero values is a no-op.\n *\n * @example\n * ctx.output(outPlace, 'a', 'b', 'c');\n * ctx.output(outPlace, ...someArray);\n *\n * @throws if place not declared as output.\n */\n output<T>(place: Place<T>, ...values: T[]): this {\n const actual = this.resolve(place);\n this.requireOutput(actual);\n for (const value of values) {\n this.writeTarget.add(actual, value);\n }\n return this;\n }\n\n /**\n * Add one or more pre-built output tokens to the same place in a single call.\n *\n * Validates the place once, then appends each token. Calling with zero\n * tokens is a no-op.\n *\n * @throws if place not declared as output.\n */\n outputToken<T>(place: Place<T>, ...tokens: Token<T>[]): this {\n const actual = this.resolve(place);\n this.requireOutput(actual);\n for (const token of tokens) {\n this.writeTarget.addToken(actual, token);\n }\n return this;\n }\n\n /** Returns declared output places. */\n outputPlaces(): ReadonlySet<Place<any>> {\n return this._outputPlaces;\n }\n\n private requireOutput(place: Place<any>): void {\n if (!this.allowedOutputs.has(place.name)) {\n throw new Error(\n `Place '${place.name}' not in declared outputs: [${[...this.allowedOutputs].join(', ')}]`\n );\n }\n }\n\n /**\n * Severs the action's output from the marking, for use when a firing times out.\n *\n * After this call the action's `output(...)` writes are dropped, and the executor\n * harvests a fresh collector the action holds no reference to. Anything the action\n * wrote *before* the timeout is discarded with it: a partial result merged with the\n * timeout branch would violate the transition's own output spec.\n *\n * This is the only isolation available — libpetri does not own the promise the action\n * runs on, so it cannot stop the work, only stop the result from landing.\n *\n * @internal Executor machinery — must be called by the executor, never by an action.\n */\n detachForTimeout(): void {\n this.writeTarget.detach();\n this._rawOutput = new TokenOutput();\n }\n\n /**\n * Produces into the executor's harvest collector rather than the action's write target.\n *\n * Identical to {@link output} before {@link detachForTimeout}; after it, this is the\n * only route that still reaches the marking. Used by the executor to deposit the\n * timeout branch.\n *\n * @internal Executor machinery — must be called by the executor, never by an action.\n */\n outputToHarvest<T>(place: Place<T>, value: T): this {\n const actual = this.resolve(place);\n this.requireOutput(actual);\n this._rawOutput.add(actual, value);\n return this;\n }\n\n // ==================== ν-name minting (NU-010) ====================\n\n /**\n * @internal Installs the ν-name minter. Wired by the executor at firing time\n * so names minted by {@link freshName} are monotonic across the run and\n * instance-prefixed (spec NU-010, NU-030).\n */\n setFreshNameSupplier(supplier: () => NameId): void {\n this._freshNameSupplier = supplier;\n }\n\n /**\n * Mints a fresh ν-name (the ν-binder primitive — spec NU-010).\n *\n * An action calls this on the fork side to create a correlation id, then\n * writes it into the sibling output payloads; a later join correlates those\n * siblings via a {@link import('./match-spec.js').MatchSpec}. Uses the\n * executor-installed minter when present; otherwise falls back to a\n * process-global counter prefixed by the transition name.\n */\n freshName(): NameId {\n if (this._freshNameSupplier) return this._freshNameSupplier();\n return nameId(`${this._transitionName}#${GLOBAL_FRESH_NAME_COUNTER++}`);\n }\n\n // ==================== Structure Info ====================\n\n /** Returns the transition name. */\n transitionName(): string {\n return this._transitionName;\n }\n\n // ==================== Execution Context ====================\n\n /** Retrieves an execution context object by key. */\n executionContext<T>(key: string): T | undefined {\n return this.executionCtx.get(key) as T | undefined;\n }\n\n /** Checks if an execution context object of the given key is present. */\n hasExecutionContext(key: string): boolean {\n return this.executionCtx.has(key);\n }\n\n // ==================== Logging ====================\n\n /** Emits a structured log message into the event store. */\n log(level: string, message: string, error?: Error): void {\n this._logFn?.(level, message, error);\n }\n\n // ==================== Internal ====================\n\n /** @internal Used by BitmapNetExecutor to collect outputs after action completion. */\n rawOutput(): TokenOutput {\n return this._rawOutput;\n }\n}\n","import type { Place } from './place.js';\nimport type { Token } from './token.js';\n\n/**\n * Consumed input tokens bound to their source places.\n *\n * Passed to TransitionAction as the `input` parameter, providing\n * type-safe read access to tokens consumed from input places.\n */\nexport class TokenInput {\n private readonly tokens = new Map<string, Token<any>[]>();\n\n /** Add a token (used by executor when firing transition). */\n add<T>(place: Place<T>, token: Token<T>): this {\n const existing = this.tokens.get(place.name);\n if (existing) {\n existing.push(token);\n } else {\n this.tokens.set(place.name, [token]);\n }\n return this;\n }\n\n /** Get all tokens for a place. */\n getAll<T>(place: Place<T>): readonly Token<T>[] {\n return (this.tokens.get(place.name) ?? []) as Token<T>[];\n }\n\n /** Get the first token for a place. Throws if no tokens. */\n get<T>(place: Place<T>): Token<T> {\n const list = this.tokens.get(place.name);\n if (!list || list.length === 0) {\n throw new Error(`No token for place: ${place.name}`);\n }\n return list[0] as Token<T>;\n }\n\n /** Get the first token's value for a place. Throws if no tokens. */\n value<T>(place: Place<T>): T {\n return this.get(place).value;\n }\n\n /** Get all token values for a place. */\n values<T>(place: Place<T>): readonly T[] {\n return this.getAll(place).map(t => t.value);\n }\n\n /** Get token count for a place. */\n count(place: Place<any>): number {\n return this.getAll(place).length;\n }\n\n /** Check if any tokens exist for a place. */\n has(place: Place<any>): boolean {\n return this.count(place) > 0;\n }\n}\n","import type { Place } from './place.js';\nimport type { ArcInhibitor, ArcRead, ArcReset } from './arc.js';\nimport type { In } from './in.js';\nimport type { MatchSpec } from './match-spec.js';\nimport type { Out, OutTimeout } from './out.js';\nimport type { Timing } from './timing.js';\nimport type { TransitionAction } from './transition-action.js';\nimport { passthrough } from './transition-action.js';\nimport { immediate } from './timing.js';\nimport { allPlaces } from './out.js';\n\n/** @internal Symbol key restricting construction to the builder. */\nconst TRANSITION_KEY = Symbol('Transition.internal');\n\n/** @internal Shared empty correspondence for the common (identity) case. */\nconst EMPTY_PLACE_ALIAS: ReadonlyMap<string, Place<any>> = new Map();\n\n/**\n * A transition in the Time Petri Net that transforms tokens.\n *\n * Transitions use identity-based equality (===) — each instance is unique\n * regardless of name. The name is purely a label for display/debugging/export.\n */\nexport class Transition {\n readonly name: string;\n readonly inputSpecs: readonly In[];\n readonly outputSpec: Out | null;\n readonly inhibitors: readonly ArcInhibitor[];\n readonly reads: readonly ArcRead[];\n readonly resets: readonly ArcReset[];\n readonly timing: Timing;\n readonly actionTimeout: OutTimeout | null;\n readonly action: TransitionAction;\n readonly priority: number;\n\n /**\n * ν-net join correlation: a subset of `inputSpecs` that must be correlated by\n * name equality on firing (spec NU-020). `null` for ordinary transitions.\n */\n readonly matchSpec: MatchSpec | null;\n\n /**\n * Per-transition **declared → actual** place correspondence (per\n * **MOD-031**), keyed by the author-original declared place **name** →\n * actual composed place. Empty for a hand-written or directly-composed\n * ([MOD-025]) transition (identity). Populated by the subnet rewriter after\n * instantiation ([MOD-010]) / port binding ([MOD-020]) so an action that\n * hardcodes a declared place constant resolves to the composed place via\n * {@link import('./transition-context.js').TransitionContext}. Consumed only\n * by the action-facing context I/O — never by enablement, firing, the\n * verifier, the exporter, or events (so [MOD-023] is unaffected).\n */\n readonly placeAlias: ReadonlyMap<string, Place<any>>;\n\n private readonly _inputPlaces: ReadonlySet<Place<any>>;\n private readonly _readPlaces: ReadonlySet<Place<any>>;\n private readonly _outputPlaces: ReadonlySet<Place<any>>;\n\n /** @internal Use {@link Transition.builder} to create instances. */\n constructor(\n key: symbol,\n name: string,\n inputSpecs: readonly In[],\n outputSpec: Out | null,\n inhibitors: readonly ArcInhibitor[],\n reads: readonly ArcRead[],\n resets: readonly ArcReset[],\n timing: Timing,\n action: TransitionAction,\n priority: number,\n placeAlias: ReadonlyMap<string, Place<any>> = EMPTY_PLACE_ALIAS,\n matchSpec: MatchSpec | null = null,\n ) {\n if (key !== TRANSITION_KEY) throw new Error('Use Transition.builder() to create instances');\n this.name = name;\n this.inputSpecs = inputSpecs;\n this.outputSpec = outputSpec;\n this.inhibitors = inhibitors;\n this.reads = reads;\n this.resets = resets;\n this.timing = timing;\n this.actionTimeout = findTimeout(outputSpec);\n this.action = action;\n this.priority = priority;\n this.placeAlias = placeAlias.size === 0 ? EMPTY_PLACE_ALIAS : placeAlias;\n this.matchSpec = matchSpec;\n\n // Precompute place sets\n const inputPlaces = new Set<Place<any>>();\n for (const spec of inputSpecs) {\n inputPlaces.add(spec.place);\n }\n this._inputPlaces = inputPlaces;\n\n const readPlaces = new Set<Place<any>>();\n for (const r of reads) {\n readPlaces.add(r.place);\n }\n this._readPlaces = readPlaces;\n\n const outputPlaces = new Set<Place<any>>();\n if (outputSpec !== null) {\n for (const p of allPlaces(outputSpec)) {\n outputPlaces.add(p);\n }\n }\n this._outputPlaces = outputPlaces;\n }\n\n /** Returns set of input places — consumed tokens. */\n inputPlaces(): ReadonlySet<Place<any>> {\n return this._inputPlaces;\n }\n\n /** Returns set of read places — context tokens, not consumed. */\n readPlaces(): ReadonlySet<Place<any>> {\n return this._readPlaces;\n }\n\n /** Returns set of output places — where tokens are produced. */\n outputPlaces(): ReadonlySet<Place<any>> {\n return this._outputPlaces;\n }\n\n /** Returns true if this transition has an action timeout. */\n hasActionTimeout(): boolean {\n return this.actionTimeout !== null;\n }\n\n toString(): string {\n return `Transition[${this.name}]`;\n }\n\n static builder(name: string): TransitionBuilder {\n return new TransitionBuilder(name);\n }\n}\n\nexport class TransitionBuilder {\n private readonly _name: string;\n private readonly _inputSpecs: In[] = [];\n private _outputSpec: Out | null = null;\n private readonly _inhibitors: ArcInhibitor[] = [];\n private readonly _reads: ArcRead[] = [];\n private readonly _resets: ArcReset[] = [];\n private _timing: Timing = immediate();\n private _action: TransitionAction = passthrough();\n private _priority = 0;\n private _placeAlias: ReadonlyMap<string, Place<any>> = EMPTY_PLACE_ALIAS;\n private _matchSpec: MatchSpec | null = null;\n\n constructor(name: string) {\n this._name = name;\n }\n\n /** Add input specifications with cardinality. */\n inputs(...specs: In[]): this {\n this._inputSpecs.push(...specs);\n return this;\n }\n\n /** Set the output specification (composite AND/XOR structure). */\n outputs(spec: Out): this {\n this._outputSpec = spec;\n return this;\n }\n\n /** Add inhibitor arc. */\n inhibitor(place: Place<any>): this {\n this._inhibitors.push({ type: 'inhibitor', place });\n return this;\n }\n\n /** Add inhibitor arcs. */\n inhibitors(...places: Place<any>[]): this {\n for (const p of places) {\n this._inhibitors.push({ type: 'inhibitor', place: p });\n }\n return this;\n }\n\n /** Add read arc. */\n read(place: Place<any>): this {\n this._reads.push({ type: 'read', place });\n return this;\n }\n\n /** Add read arcs. */\n reads(...places: Place<any>[]): this {\n for (const p of places) {\n this._reads.push({ type: 'read', place: p });\n }\n return this;\n }\n\n /** Add reset arc. */\n reset(place: Place<any>): this {\n this._resets.push({ type: 'reset', place });\n return this;\n }\n\n /** Add reset arcs. */\n resets(...places: Place<any>[]): this {\n for (const p of places) {\n this._resets.push({ type: 'reset', place: p });\n }\n return this;\n }\n\n /** Set timing specification. */\n timing(timing: Timing): this {\n this._timing = timing;\n return this;\n }\n\n /** Set the transition action. */\n action(action: TransitionAction): this {\n this._action = action;\n return this;\n }\n\n /** Set the priority (higher fires first). */\n priority(priority: number): this {\n this._priority = priority;\n return this;\n }\n\n /**\n * Sets the ν-net join correlation spec: the named input places must be\n * correlated by name equality on firing (spec NU-020). Every place referenced\n * by the spec must also be declared as an input.\n */\n match(spec: MatchSpec): this {\n this._matchSpec = spec;\n return this;\n }\n\n /**\n * Sets the per-transition declared→actual place correspondence (per\n * **MOD-031**). Populated by the subnet rewriter during the compose-time\n * rewrite; not normally called by hand-written nets, whose correspondence is\n * the identity (empty map).\n */\n placeAlias(alias: ReadonlyMap<string, Place<any>>): this {\n this._placeAlias = alias;\n return this;\n }\n\n build(): Transition {\n // Validate ForwardInput references\n if (this._outputSpec !== null) {\n const inputPlaceNames = new Set(this._inputSpecs.map(s => s.place.name));\n for (const fi of findForwardInputs(this._outputSpec)) {\n if (!inputPlaceNames.has(fi.from.name)) {\n throw new Error(\n `Transition '${this._name}': ForwardInput references non-input place '${fi.from.name}'`\n );\n }\n }\n }\n\n // Validate MatchSpec correlates only declared input places (NU-020).\n if (this._matchSpec !== null) {\n const inputPlaceNames = new Set(this._inputSpecs.map(s => s.place.name));\n for (const k of this._matchSpec.keys) {\n if (!inputPlaceNames.has(k.place.name)) {\n throw new Error(\n `Transition '${this._name}': MatchSpec correlates non-input place '${k.place.name}'`\n );\n }\n }\n }\n\n return new Transition(\n TRANSITION_KEY,\n this._name,\n [...this._inputSpecs],\n this._outputSpec,\n [...this._inhibitors],\n [...this._reads],\n [...this._resets],\n this._timing,\n this._action,\n this._priority,\n this._placeAlias,\n this._matchSpec,\n );\n }\n}\n\n/** Recursively searches the output spec for a Timeout node. */\nfunction findTimeout(out: Out | null): OutTimeout | null {\n if (out === null) return null;\n switch (out.type) {\n case 'timeout': return out;\n case 'and':\n case 'xor':\n for (const child of out.children) {\n const found = findTimeout(child);\n if (found !== null) return found;\n }\n return null;\n case 'place':\n case 'forward-input':\n return null;\n }\n}\n\n/** Recursively finds all ForwardInput nodes in the output spec. */\nfunction findForwardInputs(out: Out): Array<{ from: Place<any>; to: Place<any> }> {\n switch (out.type) {\n case 'forward-input':\n return [{ from: out.from, to: out.to }];\n case 'and':\n case 'xor':\n return out.children.flatMap(findForwardInputs);\n case 'timeout':\n return findForwardInputs(out.child);\n case 'place':\n return [];\n }\n}\n","import type { Place } from './place.js';\nimport type { Transition } from './transition.js';\n\n/**\n * Advisory direction metadata for an interface place.\n *\n * Per **MOD-004**, direction is metadata only — it does NOT constrain arc flow\n * at runtime. Token movement is governed by arcs declared per CORE-030..CORE-035.\n */\nexport type PortDirection = 'input' | 'output' | 'inout';\n\n/**\n * A typed interface place exposed for composition, per **MOD-003**.\n *\n * Direction is advisory metadata only (per **MOD-004**); the underlying\n * `Place<T>` reference is what is rewired at compose time.\n */\nexport interface Port<T = unknown> {\n /** Port name, unique within the {@link Interface}. */\n readonly name: string;\n /** Direction (advisory). */\n readonly direction: PortDirection;\n /** The body place exposed by this port. */\n readonly place: Place<T>;\n}\n\n/**\n * An interface transition exposed for synchronous fusion with a caller-side\n * transition, per **MOD-005**.\n *\n * The only present variant in this scaffolding is the synchronous channel.\n * The interface is left structurally open for future channel kinds without\n * breaking existing pattern matches on `name`/`transition`.\n */\nexport interface Channel {\n /** Channel name, unique within the channel namespace. */\n readonly name: string;\n /** The body transition exposed by this channel. */\n readonly transition: Transition;\n}\n\n/** @internal Symbol key restricting construction to the builder. */\nconst INTERFACE_KEY = Symbol('Interface.internal');\n\n/**\n * Immutable declaration of a subnet's **interface**: the set of {@link Port}\n * (interface places) and {@link Channel} (interface transitions) exposed for\n * composition with an enclosing net.\n *\n * Specified by `spec/11-modular-composition.md` requirements **MOD-003**\n * (port declaration) and **MOD-005** (channel declaration). Validation rules\n * per **MOD-006** are enforced by `SubnetDef.builder()` at subnet build\n * time; this class itself enforces only port/channel name uniqueness within\n * its respective namespaces (used both by `SubnetDef` and by hand-built\n * interfaces fed into `SubnetDef.fromNet`).\n */\nexport class Interface {\n readonly ports: ReadonlyMap<string, Port<unknown>>;\n readonly channels: ReadonlyMap<string, Channel>;\n\n /** @internal Use {@link Interface.builder} to create instances. */\n constructor(\n key: symbol,\n ports: ReadonlyMap<string, Port<unknown>>,\n channels: ReadonlyMap<string, Channel>,\n ) {\n if (key !== INTERFACE_KEY) throw new Error('Use Interface.builder() to create instances');\n this.ports = ports;\n this.channels = channels;\n }\n\n /** Looks up a port by name. Returns undefined when absent. */\n port<T = unknown>(name: string): Port<T> | undefined {\n return this.ports.get(name) as Port<T> | undefined;\n }\n\n /** Looks up a channel by name. Returns undefined when absent. */\n channel(name: string): Channel | undefined {\n return this.channels.get(name);\n }\n\n /**\n * Looks up a port by name and returns its underlying place, narrowed to\n * `Place<T>`. Returns undefined when the port does not exist.\n *\n * Note: TypeScript erases generics at runtime, so unlike Java's\n * `portPlaceAs(name, Class<T>)` this method cannot verify the token type at\n * runtime — the caller is trusted to supply the correct `T`. Per **MOD-022**,\n * type compatibility is enforced at compile time only in TypeScript.\n */\n placeAs<T>(name: string): Place<T> | undefined {\n const p = this.ports.get(name);\n if (p === undefined) return undefined;\n return p.place as Place<T>;\n }\n\n static builder(): InterfaceBuilder {\n return new InterfaceBuilder();\n }\n}\n\nexport class InterfaceBuilder {\n private readonly _ports = new Map<string, Port<unknown>>();\n private readonly _channels = new Map<string, Channel>();\n\n /** Add a pre-built port (rejects duplicate names). */\n port(port: Port<unknown>): this {\n if (this._ports.has(port.name)) {\n throw new Error(`Duplicate port name: '${port.name}'`);\n }\n this._ports.set(port.name, port);\n return this;\n }\n\n /** Add an input port (advisory direction). */\n inputPort<T>(name: string, place: Place<T>): this {\n return this.port({ name, direction: 'input', place: place as Place<unknown> });\n }\n\n /** Add an output port (advisory direction). */\n outputPort<T>(name: string, place: Place<T>): this {\n return this.port({ name, direction: 'output', place: place as Place<unknown> });\n }\n\n /** Add an in-out port (advisory direction). */\n inoutPort<T>(name: string, place: Place<T>): this {\n return this.port({ name, direction: 'inout', place: place as Place<unknown> });\n }\n\n /** Add a pre-built channel (rejects duplicate names). */\n channel(channel: Channel): this;\n /** Declare a synchronous channel by name + transition (rejects duplicate names). */\n channel(name: string, transition: Transition): this;\n channel(channelOrName: Channel | string, transition?: Transition): this {\n const ch: Channel = typeof channelOrName === 'string'\n ? { name: channelOrName, transition: transition! }\n : channelOrName;\n if (this._channels.has(ch.name)) {\n throw new Error(`Duplicate channel name: '${ch.name}'`);\n }\n this._channels.set(ch.name, ch);\n return this;\n }\n\n /** @internal Bulk-add ports already validated by the caller. */\n portsAll(ports: Iterable<Port<unknown>>): this {\n for (const p of ports) this.port(p);\n return this;\n }\n\n /** @internal Bulk-add channels already validated by the caller. */\n channelsAll(channels: Iterable<Channel>): this {\n for (const c of channels) this.channel(c);\n return this;\n }\n\n build(): Interface {\n // Freeze maps by handing them off as ReadonlyMap. Defensive copies guard\n // against post-build mutation through retained builder references.\n return new Interface(\n INTERFACE_KEY,\n new Map(this._ports),\n new Map(this._channels),\n );\n }\n}\n","import type { PetriNet } from './petri-net.js';\nimport type { Place } from './place.js';\nimport type { SubnetDef } from './subnet-def.js';\nimport type { SubnetInstance } from './subnet-instance.js';\nimport type { Transition } from './transition.js';\nimport type { TransitionAction } from './transition-action.js';\n\n/**\n * @internal Symbol key restricting construction to {@link SubnetDef.instantiate}\n * and the (future) `subnet-rewriter` module. Exported via the package-internal\n * factory {@link __createInstance} so the rewriter can construct Instances\n * without exposing the constructor publicly.\n */\nconst INSTANCE_KEY = Symbol('Instance.internal');\n\n/**\n * A typed module instance produced by {@link SubnetDef.instantiate}, per\n * `spec/11-modular-composition.md` requirements **MOD-010** (creation),\n * **MOD-011** (typed handle map), **MOD-012** (per-instance state isolation),\n * and **MOD-030** (action binding).\n *\n * An instance carries:\n * - The {@link prefix} used to rename body elements (per [MOD-010] separator `\"/\"`);\n * - A reference to the originating {@link SubnetDef};\n * - The renamed body — a structurally valid `PetriNet` per [CORE-040];\n * - Typed lookup handles for ports and channels keyed by their **original**\n * (pre-prefix) names;\n * - The `params` value supplied at instantiation.\n *\n * **Scaffolding status**: this class ships in scaffolding form. The\n * {@link bindActions} method throws `Error(\"not implemented\")` until the\n * `instantiate` rename pass lands in the next task. Direct accessors are\n * wired up so downstream code can take dependencies on the API shape today.\n *\n * @typeParam P parameter type (use `void` for unparameterised subnets)\n */\nexport class Instance<P = void> {\n readonly prefix: string;\n readonly def: SubnetDef<P>;\n readonly renamedBody: PetriNet;\n readonly portHandles: ReadonlyMap<string, Place<unknown>>;\n readonly channelHandles: ReadonlyMap<string, Transition>;\n readonly params: P;\n\n /**\n * @internal Use {@link SubnetDef.instantiate} (or the internal factory\n * {@link __createInstance}) to create instances.\n */\n constructor(\n key: symbol,\n prefix: string,\n def: SubnetDef<P>,\n renamedBody: PetriNet,\n portHandles: ReadonlyMap<string, Place<unknown>>,\n channelHandles: ReadonlyMap<string, Transition>,\n params: P,\n ) {\n if (key !== INSTANCE_KEY) {\n throw new Error('Use SubnetDef.instantiate() to create Instance values');\n }\n this.prefix = prefix;\n this.def = def;\n this.renamedBody = renamedBody;\n this.portHandles = portHandles;\n this.channelHandles = channelHandles;\n this.params = params;\n }\n\n /**\n * Returns the renamed {@link Place} corresponding to the named port.\n *\n * The port name is the **original** (pre-prefix) name as declared in the\n * subnet's `Interface`. Per **MOD-022**, TypeScript enforces token-type\n * compatibility at compile time only; this method does not validate `T`\n * at runtime. A missing name raises an `Error`.\n *\n * @throws when the port name is unknown\n */\n port<T>(name: string): Place<T> {\n const p = this.portHandles.get(name);\n if (p === undefined) {\n throw new Error(`No port named '${name}' in instance '${this.prefix}'`);\n }\n return p as Place<T>;\n }\n\n /**\n * Returns the renamed {@link Transition} corresponding to the named channel.\n *\n * @throws when the channel name is unknown\n */\n channel(name: string): Transition {\n const t = this.channelHandles.get(name);\n if (t === undefined) {\n throw new Error(`No channel named '${name}' in instance '${this.prefix}'`);\n }\n return t;\n }\n\n /**\n * Returns the debug-UI descriptor for this instance per **MOD-041**.\n */\n descriptor(): SubnetInstance {\n const transitions: string[] = [];\n for (const t of this.renamedBody.transitions) transitions.push(t.name);\n const exposedPlaces: string[] = [];\n for (const p of this.portHandles.values()) exposedPlaces.push(p.name);\n return {\n prefix: this.prefix,\n defName: this.def.name,\n transitions,\n exposedPlaces,\n params: this.params,\n parentPrefix: null,\n };\n }\n\n /**\n * Produces a derived instance whose specified transitions (named by their\n * **original**, pre-prefix names) carry the supplied actions per **MOD-030**.\n *\n * For each entry `[originalName, action]`, the renamed body is searched for\n * the transition whose name equals `prefix + \"/\" + originalName`. The\n * resulting instance shares the original `def`, `prefix`, `params`, and\n * port/channel handle topology — only the renamed body is rebuilt with new\n * actions. Per **MOD-030**, calling `bindActions` on one instance does NOT\n * affect the actions held by other instances of the same `def`.\n *\n * Unrecognised original names raise an `Error` so typos surface eagerly.\n */\n bindActions(actionsByOriginalName: Record<string, TransitionAction>): Instance<P> {\n // Build a Map<prefixedName, TransitionAction> for the resolver.\n // Validate every supplied original name against the renamed body's\n // transition set to surface typos eagerly.\n const prefixedByName = new Map<string, TransitionAction>();\n const renamedNames = new Set<string>();\n for (const t of this.renamedBody.transitions) {\n renamedNames.add(t.name);\n }\n\n for (const originalName of Object.keys(actionsByOriginalName)) {\n const prefixed = this.prefix + '/' + originalName;\n if (!renamedNames.has(prefixed)) {\n throw new Error(\n `Instance.bindActions: no transition '${originalName}' (resolved as ` +\n `'${prefixed}') in instance '${this.prefix}' of subnet '${this.def.name}'`,\n );\n }\n prefixedByName.set(prefixed, actionsByOriginalName[originalName]!);\n }\n\n // Use the existing PetriNet.bindActionsWithResolver — it preserves the\n // existing action when the resolver returns it (see petri-net.ts), so\n // unaffected transitions land in the new net by reference (sharing per\n // MOD-030).\n const reboundBody = this.renamedBody.bindActionsWithResolver((name) => {\n const action = prefixedByName.get(name);\n if (action !== undefined) return action;\n // Return the existing action so PetriNet.bindActionsWithResolver\n // short-circuits the rebuild for unaffected transitions.\n for (const t of this.renamedBody.transitions) {\n if (t.name === name) return t.action;\n }\n // Unreachable — the resolver is only called for transitions in this.renamedBody.\n /* istanbul ignore next */\n throw new Error(`Instance.bindActions: resolver invoked with unknown name '${name}'`);\n });\n\n // Rebuild the channel handles against the rebound body so callers see\n // the post-rebind transition (with its new action) when they ask for a\n // channel by name.\n const reboundChannelHandles = new Map<string, Transition>();\n if (this.channelHandles.size > 0) {\n const byName = new Map<string, Transition>();\n for (const t of reboundBody.transitions) {\n byName.set(t.name, t);\n }\n for (const [name, oldT] of this.channelHandles) {\n const refreshed = byName.get(oldT.name);\n if (refreshed === undefined) {\n /* istanbul ignore next */\n throw new Error(\n `Instance.bindActions: channel '${name}' transition '${oldT.name}' not found in rebound body`,\n );\n }\n reboundChannelHandles.set(name, refreshed);\n }\n }\n\n return __createInstance<P>(\n this.prefix,\n this.def,\n reboundBody,\n this.portHandles,\n reboundChannelHandles,\n this.params,\n );\n }\n}\n\n/**\n * @internal Package-internal factory used by {@link SubnetDef.instantiate}\n * and the (future) `subnet-rewriter` module to construct {@link Instance}\n * values without re-exporting the Symbol-guarded constructor key publicly.\n *\n * NOT part of the public API surface — do NOT re-export from `core/index.ts`.\n */\nexport function __createInstance<P>(\n prefix: string,\n def: SubnetDef<P>,\n renamedBody: PetriNet,\n portHandles: ReadonlyMap<string, Place<unknown>>,\n channelHandles: ReadonlyMap<string, Transition>,\n params: P,\n): Instance<P> {\n return new Instance<P>(\n INSTANCE_KEY,\n prefix,\n def,\n renamedBody,\n portHandles,\n channelHandles,\n params,\n );\n}\n","/**\n * @internal\n *\n * Package-internal utility encapsulating the structural rewrite primitive used\n * by {@link SubnetDef.instantiate} and (later) `PetriNetBuilder.compose(...)`\n * per **MOD-020**.\n *\n * The rewrite is purely structural: every place reference in every arc is\n * replaced according to a supplied `Map<string, Place<unknown>>` keyed by\n * **original place name** (TypeScript Place identity is name-based per\n * `runtime/compiled-net.ts`'s `Map<string, number>`). Every transition is\n * rebuilt with rewritten arcs, preserving timing, priority, and action by\n * reference per **MOD-030**.\n *\n * ## Design — one engine, multiple callers\n *\n * The {@link renameNet} entry point is specialised to the rename pass: it\n * allocates fresh prefixed places via the `place(name)` factory, records the\n * old-to-new mapping in caller-supplied `Map`s (so callers can build\n * port/channel handle maps), and emits a renamed `PetriNet`. The arc-rewrite\n * helpers ({@link rewriteIn}, {@link rewriteOut}, etc.) are factored out so\n * the future `compose(...)` caller can substitute port-place mappings against\n * an arbitrary remap without renaming everything.\n *\n * ## Performance — V8 hidden-class stability\n *\n * - Places are constructed exclusively via the existing `place<T>(name)`\n * factory (from `core/place.ts`) so V8 can settle a single hidden class for\n * all `Place` allocations. We never synthesize `{name: ...}` literals\n * inline.\n * - Arcs are constructed via the existing `inputArc`, `inhibitorArc`,\n * `readArc`, `resetArc`, `outPlace`, `forwardInput`, `timeout` factories;\n * `In` shapes go through `one`, `exactly`, `all`, `atLeast`.\n * - The recursive `Out.And` / `Out.Xor` reconstruction uses pre-sized\n * `Array<Out>` plus a `for` loop (parallel to the Java perf reasoning about\n * `Stream` overhead — see `SubnetRewriter.rewriteOut`). `Array.prototype.map`\n * is avoided on this hot path.\n * - The `inputs(...)` rest-parameter into `TransitionBuilder.inputs` does\n * create a shallow array copy internally; this matches Java's\n * `Arc.In[t.inputSpecs().size()]` allocation and is the minimum allocation\n * needed to land arcs in the builder's defensive copy.\n *\n * Specified by `spec/11-modular-composition.md` MOD-010, MOD-011, MOD-012,\n * MOD-013, MOD-020, MOD-030.\n */\n\nimport type { Place } from '../place.js';\nimport { place } from '../place.js';\nimport type { ArcInhibitor, ArcRead, ArcReset } from '../arc.js';\nimport type { In } from '../in.js';\nimport { one, exactly, all, atLeast } from '../in.js';\nimport type { Out } from '../out.js';\nimport { and, outPlace, forwardInput, timeout, allPlaces } from '../out.js';\nimport { PetriNet } from '../petri-net.js';\nimport { Transition } from '../transition.js';\nimport type { MatchSpec } from '../match-spec.js';\nimport type { Timing } from '../timing.js';\nimport type { TransitionAction } from '../transition-action.js';\nimport { isPassthrough } from '../transition-action.js';\n\n// ============================================================\n// Public entry points\n// ============================================================\n\n/**\n * Returns a renamed copy of `orig`: same generic token type at the type\n * level, with `prefix + \"/\" + orig.name` as the new name. Goes through the\n * `place<T>(name)` factory for V8 hidden-class stability.\n */\nexport function renamePlace<T>(orig: Place<T>, prefix: string): Place<T> {\n return place<T>(prefix + '/' + orig.name);\n}\n\n/**\n * Renames every place and transition of `body`, prefixing each name with\n * `prefix + \"/\"`.\n *\n * **Side effects**: fills the two supplied maps so the caller can resolve\n * original-place / original-transition references against the rewritten\n * equivalents:\n *\n * - `placeRemap` — original place **name** → renamed place\n * - `transitionRemap` — original transition **name** → renamed transition\n *\n * Both maps are cleared on entry, then populated in iteration order.\n *\n * Note: the maps are keyed by name strings (not Place / Transition object\n * identity) because TypeScript Place identity is name-based per\n * `runtime/compiled-net.ts` (`Map<string, number>`). This matches how the\n * compiled net dedupes places.\n *\n * @param body the subnet body to rewrite\n * @param prefix the rename prefix\n * @param placeRemap caller-allocated map filled with old-name → new place\n * @param transitionRemap caller-allocated map filled with old-name → new transition\n * @returns a fresh `PetriNet` whose name is `prefix + \"/\" + body.name` and\n * whose places/transitions are renamed copies\n */\nexport function renameNet(\n body: PetriNet,\n prefix: string,\n placeRemap: Map<string, Place<unknown>>,\n transitionRemap: Map<string, Transition>,\n): PetriNet {\n placeRemap.clear();\n transitionRemap.clear();\n\n // Pass 1: rename every place. We must do this before transitions so arc\n // rewriting can resolve every place reference unambiguously.\n for (const orig of body.places) {\n placeRemap.set(orig.name, renamePlace(orig as Place<unknown>, prefix));\n }\n\n // Pass 2: rebuild every transition with arcs rewritten via placeRemap.\n const builder = PetriNet.builder(prefix + '/' + body.name);\n\n // Add places explicitly: some may not be referenced by any transition arc,\n // but were declared on the body — preserve that membership.\n for (const renamedPlace of placeRemap.values()) {\n builder.place(renamedPlace);\n }\n\n for (const t of body.transitions) {\n const renamed = rewriteTransition(t, prefix, placeRemap);\n transitionRemap.set(t.name, renamed);\n builder.transition(renamed);\n }\n\n return builder.build();\n}\n\n/**\n * Rebuilds `t` with name `prefix + \"/\" + t.name` and every arc rewritten\n * through `placeRemap`. Timing, priority, and action are carried through by\n * reference (action sharing per **MOD-030**).\n *\n * If a place referenced by an arc is not present in `placeRemap` (keyed by\n * original name), the arc retains the original place — partial remaps are\n * valid (used by the future `compose(...)` caller).\n */\nexport function rewriteTransition(\n t: Transition,\n prefix: string,\n placeRemap: Map<string, Place<unknown>>,\n): Transition {\n return rebuildWithName(t, prefix + '/' + t.name, placeRemap);\n}\n\n/**\n * Rebuilds `t` with the **same** name, substituting every arc place reference\n * through `remap`. Timing, priority, and action are carried through by\n * reference (action sharing per **MOD-030**).\n *\n * This is the rewrite primitive used by `PetriNetBuilder.compose(...)` (task\n * #12) when merging an instance's renamed body into an enclosing net: the\n * transition's prefixed name is already unique within the host (per\n * [MOD-010]), so no further renaming is needed — only port-place references\n * are substituted with the caller's places.\n *\n * If a place referenced by an arc is not present in `remap`, the arc retains\n * the original place — partial remaps are valid.\n */\nexport function substitutePlaces(\n t: Transition,\n remap: Map<string, Place<unknown>>,\n): Transition {\n return rebuildWithName(t, t.name, remap);\n}\n\n// ============================================================\n// Shared transition-rebuild implementation\n// ============================================================\n\n/**\n * Shared implementation — the single transition-rebuild site: rebuilds `t` with\n * the supplied `name` and arc places rewritten through `remap`. Used by\n * {@link rewriteTransition} (which prefixes the name), {@link substitutePlaces}\n * (which keeps the name), and {@link applyFusion} (which additionally passes\n * `normalizeInputs` to reconcile arcs the remap made collide).\n *\n * The action timeout is not a builder field: {@link Transition} derives it from\n * the output spec, which {@link rewriteOut} carries through — including the\n * `timeout` node itself (IO-013 / EXEC-022).\n */\nfunction rebuildWithName(\n t: Transition,\n name: string,\n remap: Map<string, Place<unknown>>,\n normalizeInputs?: (inputs: readonly In[]) => readonly In[],\n): Transition {\n const builder = Transition.builder(name)\n .timing(t.timing)\n .priority(t.priority)\n .action(t.action);\n\n // Build the declared→actual place correspondence (MOD-031) from the same\n // `remap` the arcs are rewritten through, chaining any pre-existing alias so\n // nested instantiation ([MOD-013]) resolves declared → final composed place.\n const alias = buildPlaceAlias(t, remap);\n if (alias.size > 0) {\n builder.placeAlias(alias);\n }\n\n if (t.inputSpecs.length > 0) {\n // Pre-size for V8 hidden-class stability; for-loop over Stream.map.\n const rewrittenInputs = new Array<In>(t.inputSpecs.length);\n for (let i = 0; i < t.inputSpecs.length; i++) {\n rewrittenInputs[i] = rewriteIn(t.inputSpecs[i]!, remap);\n }\n builder.inputs(...(normalizeInputs !== undefined\n ? normalizeInputs(rewrittenInputs)\n : rewrittenInputs));\n }\n\n if (t.outputSpec !== null) {\n builder.outputs(rewriteOut(t.outputSpec, remap));\n }\n\n for (let i = 0; i < t.inhibitors.length; i++) {\n builder.inhibitor(rewriteInhibitor(t.inhibitors[i]!, remap).place);\n }\n for (let i = 0; i < t.reads.length; i++) {\n builder.read(rewriteRead(t.reads[i]!, remap).place);\n }\n for (let i = 0; i < t.resets.length; i++) {\n builder.reset(rewriteReset(t.resets[i]!, remap).place);\n }\n\n // Carry the ν-net join correlation forward, following place renames so a\n // composed join still correlates the right (renamed) inputs (NU-020/-030).\n if (t.matchSpec !== null) {\n builder.match({\n keys: t.matchSpec.keys.map(k => ({\n place: remap.get(k.place.name) ?? k.place,\n key: k.key,\n })),\n });\n }\n\n return builder.build();\n}\n\n// ============================================================\n// Declared→actual place correspondence (MOD-031)\n// ============================================================\n\n/**\n * Builds the per-transition **declared → actual** place correspondence (per\n * **MOD-031**) for a transition being rewritten through `remap`, keyed by the\n * author-original declared place **name** → actual composed place. Mirrors the\n * Rust `build_local_name_map` / Java `buildPlaceAlias` algorithm so all three\n * implementations agree.\n *\n * **Chained path** — when `t` already carries a non-empty alias (from an\n * earlier rewrite pass: nested instantiation [MOD-013], or\n * instantiate-then-compose), each `declaredName → prev` entry is carried\n * forward as `declaredName → (remap.get(prev.name) ?? prev)`; identity results\n * are dropped. The arcs are deliberately **not** walked in this case — their\n * places are intermediate-pass names, not author-original, so recording them\n * would leak intermediate keys the user never declared.\n *\n * **First-pass path** — when `t` carries no alias, every arc place maps to its\n * remapped place keyed by the author-original name; identity entries are\n * skipped. The ForwardInput `from` is captured via the input walk and its `to`\n * via {@link allPlaces}.\n */\nfunction buildPlaceAlias(\n t: Transition,\n remap: Map<string, Place<unknown>>,\n): ReadonlyMap<string, Place<unknown>> {\n const prev = t.placeAlias;\n if (remap.size === 0 && prev.size === 0) {\n return EMPTY_ALIAS;\n }\n\n const alias = new Map<string, Place<unknown>>();\n\n if (prev.size > 0) {\n for (const [declaredName, prevActual] of prev) {\n const replaced = remap.get(prevActual.name);\n const finalActual = replaced !== undefined ? replaced : prevActual;\n if (finalActual.name !== declaredName) {\n alias.set(declaredName, finalActual);\n }\n }\n return alias;\n }\n\n const record = (p: Place<unknown>): void => {\n if (alias.has(p.name)) return;\n const replaced = remap.get(p.name);\n if (replaced !== undefined && replaced.name !== p.name) {\n alias.set(p.name, replaced);\n }\n };\n for (const spec of t.inputSpecs) record(spec.place as Place<unknown>);\n for (const rd of t.reads) record(rd.place as Place<unknown>);\n for (const inh of t.inhibitors) record(inh.place as Place<unknown>);\n for (const rs of t.resets) record(rs.place as Place<unknown>);\n if (t.outputSpec !== null) {\n for (const p of allPlaces(t.outputSpec)) record(p as Place<unknown>);\n }\n return alias;\n}\n\n/** @internal Shared empty correspondence for the no-op rewrite case. */\nconst EMPTY_ALIAS: ReadonlyMap<string, Place<unknown>> = new Map();\n\n// ============================================================\n// Arc rewrite helpers (exhaustive switches — no default)\n// ============================================================\n\n/**\n * Rewrites an {@link In} via the place remap. Exhaustive `switch` over the\n * discriminated union variants `one`, `exactly`, `all`, `at-least`.\n */\nexport function rewriteIn(spec: In, remap: Map<string, Place<unknown>>): In {\n switch (spec.type) {\n case 'one':\n return one(resolve(spec.place, remap));\n case 'exactly':\n return exactly(spec.count, resolve(spec.place, remap));\n case 'all':\n return all(resolve(spec.place, remap));\n case 'at-least':\n return atLeast(spec.minimum, resolve(spec.place, remap));\n }\n}\n\n/**\n * Rewrites an {@link Out} via the place remap. Exhaustive recursive `switch`\n * over the discriminated union variants `place`, `forward-input`, `and`, `xor`,\n * `timeout`.\n *\n * `and` / `xor` traversal uses explicit pre-sized `Array<Out>` + indexed\n * `for` (no `Array.prototype.map`) per the perf notes on this module.\n */\nexport function rewriteOut(out: Out, remap: Map<string, Place<unknown>>): Out {\n switch (out.type) {\n case 'place':\n return outPlace(resolve(out.place, remap));\n\n case 'forward-input':\n return forwardInput(resolve(out.from, remap), resolve(out.to, remap));\n\n case 'and': {\n const children = out.children;\n const rewritten = new Array<Out>(children.length);\n for (let i = 0; i < children.length; i++) {\n rewritten[i] = rewriteOut(children[i]!, remap);\n }\n // Reconstruct via the same shape the `and(...)` factory produces. We\n // skip the factory's variadic spread on this hot path; the resulting\n // shape is identical.\n return { type: 'and', children: rewritten };\n }\n\n case 'xor': {\n const children = out.children;\n const rewritten = new Array<Out>(children.length);\n for (let i = 0; i < children.length; i++) {\n rewritten[i] = rewriteOut(children[i]!, remap);\n }\n return { type: 'xor', children: rewritten };\n }\n\n case 'timeout':\n return timeout(out.afterMs, rewriteOut(out.child, remap));\n }\n}\n\n/** Rewrites an {@link ArcInhibitor} via the place remap. */\nexport function rewriteInhibitor(\n inh: ArcInhibitor,\n remap: Map<string, Place<unknown>>,\n): ArcInhibitor {\n return { type: 'inhibitor', place: resolve(inh.place, remap) };\n}\n\n/** Rewrites an {@link ArcRead} via the place remap. */\nexport function rewriteRead(\n rd: ArcRead,\n remap: Map<string, Place<unknown>>,\n): ArcRead {\n return { type: 'read', place: resolve(rd.place, remap) };\n}\n\n/** Rewrites an {@link ArcReset} via the place remap. */\nexport function rewriteReset(\n rs: ArcReset,\n remap: Map<string, Place<unknown>>,\n): ArcReset {\n return { type: 'reset', place: resolve(rs.place, remap) };\n}\n\n// ============================================================\n// Resolution helper\n// ============================================================\n\n/**\n * Looks up `p` in `remap` by `p.name`; returns the original if absent\n * (partial-remap semantics for the future `compose` caller).\n *\n * The unchecked cast is safe at runtime: TypeScript erases generics, and the\n * remap is populated by {@link renamePlace}, which preserves the token type\n * by construction (the renamed Place carries the same `T` at the type level\n * via the `place<T>(name)` factory). Future callers that put non-rename\n * mappings in must preserve the same invariant.\n */\nfunction resolve<T>(p: Place<T>, remap: Map<string, Place<unknown>>): Place<T> {\n const replaced = remap.get(p.name);\n return replaced !== undefined ? (replaced as Place<T>) : p;\n}\n\n// ============================================================\n// Channel composition: transition merge (MOD-021)\n// ============================================================\n\n/**\n * Merges a caller-side transition with an instance-side (renamed) channel\n * transition into a single {@link Transition} per **MOD-021**.\n *\n * ## Merge semantics\n *\n * - **Identity / name** — caller-wins. The merged transition's name is\n * `mergedName` (typically `caller.name`), so the merged transition remains\n * discoverable from caller-side code paths.\n * - **Arcs** — input/inhibitor/read/reset arcs are unioned: caller-side first,\n * then instance-side. Same-place input arcs are reconciled per MOD-021\n * rules (a)-(d) via {@link normalizeInputArcs} (additive where summable,\n * rejected otherwise); identical inhibitor/read/reset arcs collapse by\n * structural key.\n * - **Output spec** — if both sides carry an output spec, they are wrapped\n * under a single new outer `OutAnd(caller, instance)` so both sides' outputs\n * fire on a successful merged firing. If only one side has an output spec,\n * that one wins. If neither side has one, the merged transition has none.\n * `OutAnd` permits heterogeneous children (recursive trees), so wrapping a\n * possibly-`OutAnd` child under a new outer `OutAnd` is structurally legal.\n * - **Timing** — see {@link mergeTimings}. Caller wins when one side is\n * `Immediate`; equal non-`Immediate` timings collapse; conflicting\n * non-`Immediate` timings throw.\n * - **Priority** — see {@link pickPriority}. Caller-side wins (policy, not a\n * bug).\n * - **Action** — see {@link composeActions}. Sequential composition: caller-\n * side action runs first, then on its completion the instance-side action\n * runs against the same {@link import('../transition-context.js').TransitionContext}.\n * The runtime sees one transition firing per [CORE-021] / [EXEC-001].\n *\n * @throws when timings conflict or same-place input arcs have no additive\n * merge (per [MOD-021]) — the message names the channel and both\n * conflicting values so users can resolve it explicitly.\n */\nexport function mergeTransitions(\n caller: Transition,\n instance: Transition,\n mergedName: string,\n): Transition {\n if (mergedName === undefined || mergedName === null || mergedName.length === 0) {\n throw new Error('mergeTransitions: mergedName must be a non-empty string');\n }\n\n // Resolve timing / match / alias first so any conflict short-circuits before\n // building. The ν-net match and MOD-031 alias are carried as-is: both sides\n // already reference final host places at merge time (upstream substitutePlaces\n // remapped them, match included), so no further remap here.\n const mergedTiming = mergeTimings(caller.timing, instance.timing, mergedName);\n const mergedPriority = pickPriority(caller.priority, instance.priority);\n const mergedAction = composeActions(caller.action, instance.action);\n const mergedMatch = mergeMatchSpecs(caller.matchSpec, instance.matchSpec, mergedName);\n const mergedAlias = mergePlaceAlias(caller.placeAlias, instance.placeAlias, mergedName);\n\n const builder = Transition.builder(mergedName)\n .timing(mergedTiming)\n .priority(mergedPriority);\n if (mergedAction !== undefined) {\n builder.action(mergedAction);\n }\n\n // MOD-021 rule (d): different arc-kind sets on one place across the two\n // sides cannot be merged (identical sets pair up under rules (a)/(b)).\n rejectCrossSideKindConflicts(caller, instance, mergedName);\n\n // Inputs: union caller-first, then instance; same-place collisions merge\n // additively or reject per MOD-021 rules (a)-(d).\n const unionedInputs = normalizeInputArcs(\n [...caller.inputSpecs, ...instance.inputSpecs],\n () => `Channel composition '${mergedName}'`,\n );\n if (unionedInputs.length > 0) {\n builder.inputs(...unionedInputs);\n }\n\n // Outputs: wrap both sides under OutAnd; one-sided wins; none -> none.\n const mergedOutput = mergeOutputs(caller.outputSpec, instance.outputSpec);\n if (mergedOutput !== null) {\n builder.outputs(mergedOutput);\n }\n\n // Inhibitors / reads / resets: arc-record union (caller first, then instance).\n for (const inh of unionArcs<ArcInhibitor>(\n caller.inhibitors,\n instance.inhibitors,\n keyOfInhibitor,\n )) {\n builder.inhibitor(inh.place);\n }\n for (const rd of unionArcs<ArcRead>(caller.reads, instance.reads, keyOfRead)) {\n builder.read(rd.place);\n }\n for (const rs of unionArcs<ArcReset>(caller.resets, instance.resets, keyOfReset)) {\n builder.reset(rs.place);\n }\n\n // Apply the ν-net match (NU-060) and the MOD-031 declared→actual place map\n // (both resolved above, before any building, so a conflict on either\n // short-circuits with no wasted arc-union work).\n if (mergedMatch !== null) {\n builder.match(mergedMatch);\n }\n if (mergedAlias.size > 0) {\n builder.placeAlias(mergedAlias);\n }\n\n return builder.build();\n}\n\n/**\n * Carries the ν-net join correlation ({@link MatchSpec}) through a channel merge\n * per **NU-060**. One-sided → that side's match survives; both-null → none; both\n * non-null → the merge is rejected, because two independent name correlations\n * cannot be silently fused into one transition and NU-060 forbids dropping a\n * match. The surviving match is returned as-is: both transitions already\n * reference final host places at merge time, so no place remap is applied here\n * (unlike {@link rebuildWithName}).\n */\nfunction mergeMatchSpecs(\n caller: MatchSpec | null,\n instance: MatchSpec | null,\n channelName: string,\n): MatchSpec | null {\n if (caller === null) return instance;\n if (instance === null) return caller;\n throw new Error(\n `Channel composition '${channelName}': both the caller-side and instance-side ` +\n `transition carry a ν-net match — refusing to fuse two independent correlations ` +\n `into one transition (NU-060). Resolve explicitly by keeping the match on a single side.`,\n );\n}\n\n/**\n * Unions the two sides' MOD-031 declared→actual place correspondences for a\n * channel merge. Both actions run within the single merged firing, so each\n * side's declared-place resolution must survive. Disjoint keys union; an entry\n * present on both sides with the same actual collapses; a genuine conflict (same\n * declared place bound to two different actual places, compared by place name)\n * is rejected naming the declared place.\n */\nfunction mergePlaceAlias(\n caller: ReadonlyMap<string, Place<any>>,\n instance: ReadonlyMap<string, Place<any>>,\n channelName: string,\n): ReadonlyMap<string, Place<any>> {\n if (caller.size === 0) return instance;\n if (instance.size === 0) return caller;\n const merged = new Map<string, Place<any>>(caller);\n for (const [declared, actual] of instance) {\n const existing = merged.get(declared);\n if (existing !== undefined && existing.name !== actual.name) {\n throw new Error(\n `Channel composition '${channelName}': conflicting declared→actual place alias ` +\n `for declared place '${declared}' — caller-side maps to '${existing.name}', ` +\n `instance-side to '${actual.name}' (MOD-031). Resolve explicitly.`,\n );\n }\n merged.set(declared, actual);\n }\n return merged;\n}\n\n/**\n * Merges two timings per **MOD-021**:\n *\n * - Both `Immediate` -> `Immediate`.\n * - One `Immediate` -> the other side wins.\n * - Both non-`Immediate` and equal (by structural inspection of the timing\n * variant fields) -> that value collapses.\n * - Otherwise the conflict is rejected with an `Error` naming the channel\n * and both timings — the user must resolve it explicitly.\n */\nexport function mergeTimings(caller: Timing, instance: Timing, channelName: string): Timing {\n if (caller.type === 'immediate' && instance.type === 'immediate') {\n return { type: 'immediate' };\n }\n if (caller.type === 'immediate') return instance;\n if (instance.type === 'immediate') return caller;\n if (timingsEqual(caller, instance)) return caller;\n throw new Error(\n `Channel composition '${channelName}': conflicting non-Immediate timings — ` +\n `caller-side ${describeTiming(caller)} vs instance-side ${describeTiming(instance)}. ` +\n `Resolve explicitly by aligning the timings on either side (MOD-021).`,\n );\n}\n\n/**\n * Caller-side priority wins per **MOD-021**. Documented as policy: the\n * instance-side priority is ignored, not blended.\n */\nexport function pickPriority(callerPriority: number, _instancePriority: number): number {\n return callerPriority;\n}\n\n/**\n * Composes two transition actions sequentially: the caller-side action runs\n * first, then on its resolution the instance-side action runs against the same\n * {@link import('../transition-context.js').TransitionContext}. The combined\n * action surfaces a single `Promise<void>` so the executor sees one\n * transition firing per [CORE-021] / [EXEC-001].\n *\n * Null / passthrough handling:\n * - If both sides are `undefined` or both are `passthrough`, returns\n * `undefined` so {@link mergeTransitions} leaves the builder's default\n * passthrough action in place.\n * - If exactly one side is `undefined` / passthrough, the other side is\n * returned by reference (no extra wrapping).\n * - Otherwise returns a fresh sequential composition.\n *\n * Note: the production {@link Transition.builder} defaults action to\n * {@link import('../transition-action.js').passthrough}, so the `undefined`\n * branches are defensive — they exist so this helper is robust if upstream\n * surfaces a literal `undefined` action.\n */\nexport function composeActions(\n caller: TransitionAction | undefined,\n instance: TransitionAction | undefined,\n): TransitionAction | undefined {\n const callerIsPassthrough = caller === undefined || isPassthrough(caller);\n const instanceIsPassthrough = instance === undefined || isPassthrough(instance);\n\n if (callerIsPassthrough && instanceIsPassthrough) return undefined;\n if (callerIsPassthrough) return instance;\n if (instanceIsPassthrough) return caller;\n return async (ctx) => {\n await caller!(ctx);\n await instance!(ctx);\n };\n}\n\n/**\n * Combines two output specs per the merge contract: if both are present,\n * wrap them under a single {@link import('../out.js').OutAnd}; otherwise\n * return the non-null side (or `null` if both are missing).\n *\n * Exported (via the surrounding module's re-export surface) for unit testing\n * and for parity with the Java internal helper.\n */\nexport function mergeOutputs(caller: Out | null, instance: Out | null): Out | null {\n if (caller === null && instance === null) return null;\n if (caller === null) return instance;\n if (instance === null) return caller;\n return and(caller, instance);\n}\n\n/**\n * Returns the union of two arc lists, caller-first then instance, with\n * duplicates removed by structural key. Order is preserved within each\n * source list. Used for input, inhibitor, read, and reset arcs.\n *\n * Implementation: `Map<string, A>` preserves insertion order and dedupes by\n * the supplied key function. TypeScript arc records are POJOs — there is no\n * built-in structural equality, so callers must supply a key derived from\n * the discriminating fields (kind + place name + cardinality where\n * applicable).\n */\nexport function unionArcs<A>(\n caller: readonly A[],\n instance: readonly A[],\n keyOf: (arc: A) => string,\n): A[] {\n if (caller.length === 0 && instance.length === 0) return [];\n // Pre-size for V8 hidden-class stability; Map preserves insertion order\n // and dedupes by string key, mirroring Java's LinkedHashSet semantics.\n const seen = new Map<string, A>();\n for (let i = 0; i < caller.length; i++) {\n const arc = caller[i]!;\n const key = keyOf(arc);\n if (!seen.has(key)) seen.set(key, arc);\n }\n for (let i = 0; i < instance.length; i++) {\n const arc = instance[i]!;\n const key = keyOf(arc);\n if (!seen.has(key)) seen.set(key, arc);\n }\n const result = new Array<A>(seen.size);\n let i = 0;\n for (const arc of seen.values()) result[i++] = arc;\n return result;\n}\n\n// ============================================================\n// Internal helpers (timings, arc keys, action introspection)\n// ============================================================\n\n/**\n * Structural equality for two non-`Immediate` timings. Used by\n * {@link mergeTimings} to collapse equal timings into a single value\n * (mirrors Java's `record.equals`).\n */\nfunction timingsEqual(a: Timing, b: Timing): boolean {\n if (a.type !== b.type) return false;\n switch (a.type) {\n case 'immediate':\n return true;\n case 'deadline':\n return a.byMs === (b as typeof a).byMs;\n case 'delayed':\n return a.afterMs === (b as typeof a).afterMs;\n case 'window': {\n const w = b as typeof a;\n return a.earliestMs === w.earliestMs && a.latestMs === w.latestMs;\n }\n case 'exact':\n return a.atMs === (b as typeof a).atMs;\n }\n}\n\n/** Human-readable timing description for the conflict-diagnostic message. */\nfunction describeTiming(t: Timing): string {\n switch (t.type) {\n case 'immediate':\n return 'Immediate';\n case 'deadline':\n return `Deadline(byMs=${t.byMs})`;\n case 'delayed':\n return `Delayed(afterMs=${t.afterMs})`;\n case 'window':\n return `Window(earliestMs=${t.earliestMs}, latestMs=${t.latestMs})`;\n case 'exact':\n return `Exact(atMs=${t.atMs})`;\n }\n}\n\nfunction keyOfInhibitor(arc: ArcInhibitor): string {\n return `inh|${arc.place.name}`;\n}\nfunction keyOfRead(arc: ArcRead): string {\n return `read|${arc.place.name}`;\n}\nfunction keyOfReset(arc: ArcReset): string {\n return `reset|${arc.place.name}`;\n}\n\n// ============================================================\n// Input-arc normalization at composition seams (MOD-021 (a)-(d))\n// ============================================================\n\n/**\n * Normalizes an input-arc list per **MOD-021**'s arc-deduplication rules:\n * arcs on distinct places pass through in order; same-place arcs merge per\n * {@link mergeInPair} (additive where summable, rejected otherwise).\n *\n * `seamOf(placeName)` supplies the diagnostic prefix naming the seam that\n * caused the collision (fusion set per [MOD-061], or channel composition).\n * Collision-free lists are returned by reference — no rebuild.\n */\nexport function normalizeInputArcs(\n arcs: readonly In[],\n seamOf: (placeName: string) => string,\n): readonly In[] {\n if (arcs.length < 2) return arcs;\n const byPlace = new Map<string, In>();\n let collided = false;\n for (let i = 0; i < arcs.length; i++) {\n const arc = arcs[i]!;\n const name = arc.place.name;\n const prior = byPlace.get(name);\n if (prior === undefined) {\n byPlace.set(name, arc);\n } else {\n collided = true;\n byPlace.set(name, mergeInPair(prior, arc, seamOf(name)));\n }\n }\n if (!collided) return arcs;\n const result = new Array<In>(byPlace.size);\n let i = 0;\n for (const arc of byPlace.values()) result[i++] = arc;\n return result;\n}\n\n/**\n * Merges two same-place input arcs per the canonical [MOD-021] merge table:\n * `one`/`exactly` weights sum, `atLeast` pairs keep the stricter minimum,\n * `all`+`all` collapses. Any other pairing is rejected per rule (c).\n */\nfunction mergeInPair(a: In, b: In, seam: string): In {\n if (a.type === 'all' && b.type === 'all') return a;\n if (a.type === 'at-least' && b.type === 'at-least') {\n return a.minimum >= b.minimum ? a : b;\n }\n const countA = summableCount(a);\n const countB = summableCount(b);\n if (countA !== -1 && countB !== -1) {\n return exactly(countA + countB, a.place);\n }\n throw new Error(\n `${seam}: input arcs ${describeIn(a)} and ${describeIn(b)} collide on place ` +\n `'${a.place.name}' and have no additive merge (MOD-021 rule (c)). Use a ` +\n `single arc with exactly(n) / atLeast(n).`,\n );\n}\n\n/** Summable consumption weight of `one`/`exactly`; -1 for `all`/`at-least`. */\nfunction summableCount(arc: In): number {\n switch (arc.type) {\n case 'one':\n return 1;\n case 'exactly':\n return arc.count;\n default:\n return -1;\n }\n}\n\n/**\n * Cardinality-only rendering for the collision diagnostic — the place name\n * already appears once in the sentence.\n */\nfunction describeIn(arc: In): string {\n switch (arc.type) {\n case 'one':\n return 'one()';\n case 'exactly':\n return `exactly(${arc.count})`;\n case 'all':\n return 'all()';\n case 'at-least':\n return `atLeast(${arc.minimum})`;\n }\n}\n\n/**\n * Rejects a channel merge where the two sides put different arc-kind sets on\n * the same place — e.g. the caller consumes `P` while the instance resets `P`\n * (MOD-021 rule (d)). Identical kind sets pair up under rules (a)/(b), and\n * same-side kind mixes (read+reset on one place, EXEC-013) stay authorable.\n * Output specs are excluded: caller-consumes / instance-produces on one place\n * is the normal channel wiring pattern (outputs union via `OutAnd`).\n */\nfunction rejectCrossSideKindConflicts(\n caller: Transition,\n instance: Transition,\n mergedName: string,\n): void {\n const callerKinds = arcKindsByPlace(caller);\n if (callerKinds.size === 0) return;\n for (const [place, instanceSet] of arcKindsByPlace(instance)) {\n const callerSet = callerKinds.get(place);\n if (callerSet !== undefined && !sameKindSet(callerSet, instanceSet)) {\n throw new Error(\n `Channel composition '${mergedName}': conflicting arc kinds on place ` +\n `'${place}' — caller-side ${describeKinds(callerSet)} vs instance-side ` +\n `${describeKinds(instanceSet)}. Different arc types on one place ` +\n `cannot be merged (MOD-021 rule (d)). Resolve explicitly.`,\n );\n }\n }\n}\n\n/** Groups a transition's input/inhibitor/read/reset arcs into place name → kind set. */\nfunction arcKindsByPlace(t: Transition): Map<string, Set<string>> {\n const kinds = new Map<string, Set<string>>();\n const add = (name: string, kind: string): void => {\n let set = kinds.get(name);\n if (set === undefined) {\n set = new Set();\n kinds.set(name, set);\n }\n set.add(kind);\n };\n for (const s of t.inputSpecs) add(s.place.name, 'input');\n for (const a of t.inhibitors) add(a.place.name, 'inhibitor');\n for (const a of t.reads) add(a.place.name, 'read');\n for (const a of t.resets) add(a.place.name, 'reset');\n return kinds;\n}\n\n/** Renders an arc-kind set as `[input, read]` — sorted, so all three languages match. */\nfunction describeKinds(kinds: ReadonlySet<string>): string {\n return `[${[...kinds].sort().join(', ')}]`;\n}\n\nfunction sameKindSet(a: ReadonlySet<string>, b: ReadonlySet<string>): boolean {\n if (a.size !== b.size) return false;\n for (const k of a) if (!b.has(k)) return false;\n return true;\n}\n\n// ============================================================\n// Fusion: bulk place substitution across a transition set (MOD-061)\n// ============================================================\n\n/**\n * Applies a fusion remap to every transition in `transitions`, substituting\n * non-canonical → canonical place references in each transition's arcs.\n * Returns a fresh insertion-ordered `Set<Transition>`; the input collection\n * is not mutated.\n *\n * This is the loop wrapper around {@link rebuildWithName}; it exists so\n * callers — notably `PetriNetBuilder.build()` during fusion resolution per\n * **MOD-061** — do not duplicate the per-transition dispatch. Transitions\n * whose arcs do not reference any key of `fusionMap` pass through unchanged\n * in shape but are still rebuilt (a fresh `Transition` instance); callers that\n * care about identity preservation for un-affected transitions should instead\n * skip the rewrite entirely when `fusionMap.size === 0`.\n *\n * The remap is keyed by **non-canonical place name** → **canonical place**\n * (matching the `Map<string, Place<unknown>>` key convention used throughout\n * this module — TypeScript Place identity is name-based per\n * `runtime/compiled-net.ts`).\n *\n * When the substitution makes two input arcs of one transition collide on the\n * canonical place, they are reconciled per [MOD-021] via\n * {@link normalizeInputArcs} (additive where summable, rejected otherwise) so\n * a fused net still compiles under the CORE-030 duplicate-input rejection.\n *\n * @param transitions the transitions to rewrite (non-null, may be empty)\n * @param fusionMap non-canonical name → canonical place remap (non-null)\n * @param seamOf canonical place name → diagnostic seam prefix (the\n * owning fusion set) for collision rejections\n * @returns a fresh, insertion-ordered set of rewritten transitions\n */\nexport function applyFusion(\n transitions: Iterable<Transition>,\n fusionMap: Map<string, Place<unknown>>,\n seamOf: (canonicalPlaceName: string) => string,\n): Set<Transition> {\n // Normalization rides the rebuild rather than rebuilding a second time;\n // normalizeInputArcs returns collision-free lists by reference.\n const normalizeInputs = (inputs: readonly In[]): readonly In[] =>\n normalizeInputArcs(inputs, seamOf);\n const rewritten = new Set<Transition>();\n for (const t of transitions) {\n // Only transitions the fusion actually rewrites get the merge pass: a\n // pre-existing duplicate on an untouched place stays a CORE-030 compile\n // rejection rather than being silently summed away.\n rewritten.add(rebuildWithName(t, t.name, fusionMap,\n fusionTouchesInputs(t, fusionMap) ? normalizeInputs : undefined));\n }\n return rewritten;\n}\n\n/** True when any input arc of `t` references a fused (non-canonical) place. */\nfunction fusionTouchesInputs(t: Transition, fusionMap: Map<string, Place<unknown>>): boolean {\n if (fusionMap.size === 0) return false;\n for (let i = 0; i < t.inputSpecs.length; i++) {\n if (fusionMap.has(t.inputSpecs[i]!.place.name)) return true;\n }\n return false;\n}\n","import type { PetriNet } from '../core/petri-net.js';\nimport type { Token } from '../core/token.js';\nimport type { SmtProperty } from './smt-property.js';\nimport type { SmtVerificationResult } from './smt-verification-result.js';\nimport { isProven, isViolated } from './smt-verification-result.js';\n\n/**\n * Token-source supplier used by the verification harness to seed a synthetic\n * environment place for a given input port, per\n * `spec/11-modular-composition.md` requirement **MOD-051** AC #3.\n *\n * The supplier's presence is what bounds the input behavior in the synthetic\n * harness; it is invoked once at synthetic-net construction time so that\n * supplier-side errors surface eagerly, not at verification time. The\n * concrete token value is not consumed by the verifier itself (which operates\n * on the integer marking projection per [VER-004]); it merely materialises\n * the seed token type and surfaces user errors.\n */\nexport type TokenSupplier = () => Token<unknown>;\n\n/**\n * Harness driving local property verification of a subnet definition per\n * `spec/11-modular-composition.md` requirement **MOD-051**.\n *\n * The harness is a value carrier consumed by\n * {@link import('../core/subnet-def.js').SubnetDef.verify}. It supplies the\n * three pieces of information needed to wrap a subnet in a synthetic\n * enclosing net for verification:\n *\n * 1. A {@link params} value of the subnet's parameter type.\n * 2. A {@link portInputGenerators} map from **input port name** (original /\n * pre-prefix) to a {@link TokenSupplier}. The supplier's presence is what\n * bounds the input behavior in the synthetic harness; the supplier is\n * invoked at synthetic-net construction time when the harness wires up the\n * {@link import('../core/place.js').EnvironmentPlace} associated with the\n * port.\n * 3. A set of {@link properties} to check (per [VER-002] /\n * {@link SmtProperty}).\n *\n * Each entry in {@link portInputGenerators} MUST correspond to an input or\n * in-out port declared on the subnet's interface. Output-only ports never\n * appear in the generator map; instead, the harness wires them to a synthetic\n * observation place visible to the verifier.\n *\n * The map and property collection accept either the canonical\n * `Map`/`ReadonlySet` form or a plain `Record`/`readonly array` for ergonomic\n * inline construction; `SubnetDef.verify` normalises both.\n *\n * @typeParam P parameter type carried through to the subnet under test\n */\nexport interface VerificationHarness<P = void> {\n /**\n * Parameter value supplied to\n * {@link import('../core/subnet-def.js').SubnetDef.instantiate} for the\n * system-under-test instance. Use `undefined` (or `null`) for `P = void`.\n */\n readonly params: P;\n\n /**\n * Map (or `Record`) from **input port name** to a {@link TokenSupplier} that\n * seeds the synthetic environment place for that port. Output-only ports\n * MUST NOT appear; in-out ports MUST appear (mirrors the Java harness).\n */\n readonly portInputGenerators:\n | ReadonlyMap<string, TokenSupplier>\n | Readonly<Record<string, TokenSupplier>>;\n\n /**\n * Safety properties to check on the synthetic enclosing net per\n * {@link SmtProperty}. An empty collection is permitted but yields an empty\n * {@link VerificationResult.perProperty}.\n */\n readonly properties: ReadonlySet<SmtProperty> | readonly SmtProperty[];\n\n}\n\n/**\n * Aggregated outcome of a\n * {@link import('../core/subnet-def.js').SubnetDef.verify} invocation per\n * `spec/11-modular-composition.md` requirement **MOD-051**.\n *\n * The verifier is invoked once per {@link SmtProperty} declared in the\n * harness; each invocation produces an {@link SmtVerificationResult}. This\n * record carries the per-property results plus the synthetic enclosing net\n * that was constructed for verification (useful for diagnostic output and\n * tooling to render the harness wiring).\n */\nexport interface VerificationResult {\n /**\n * The synthetic enclosing net assembled by `SubnetDef.verify(...)`: the\n * renamed body of the subnet under test, with each input port bound to a\n * synthetic environment place and each output port bound to a synthetic\n * observation place.\n */\n readonly syntheticNet: PetriNet;\n\n /**\n * Per-property verification results, in the iteration order of the\n * harness's {@link VerificationHarness.properties} collection.\n */\n readonly perProperty: ReadonlyMap<SmtProperty, SmtVerificationResult>;\n\n /**\n * Returns true when every property in the harness was proven safe.\n * An empty harness (no properties) returns `true` vacuously.\n */\n allProven(): boolean;\n\n /**\n * Returns true when at least one property was violated (counter-example\n * found).\n */\n anyViolated(): boolean;\n}\n\n/**\n * @internal Builds a {@link VerificationResult} value from the per-property\n * map and synthetic net. The resulting object is structurally immutable; the\n * `perProperty` map is wrapped in a defensive copy so callers cannot mutate\n * the verifier's view through retained map references.\n */\nexport function buildVerificationResult(\n syntheticNet: PetriNet,\n perProperty: ReadonlyMap<SmtProperty, SmtVerificationResult>,\n): VerificationResult {\n const frozen = new Map(perProperty);\n return {\n syntheticNet,\n perProperty: frozen,\n allProven(): boolean {\n for (const r of frozen.values()) {\n if (!isProven(r)) return false;\n }\n return true;\n },\n anyViolated(): boolean {\n for (const r of frozen.values()) {\n if (isViolated(r)) return true;\n }\n return false;\n },\n };\n}\n\n/**\n * @internal Normalises {@link VerificationHarness.portInputGenerators} to a\n * canonical `Map<string, TokenSupplier>` regardless of whether the caller\n * supplied a `Map` or a `Record`. Iteration order is preserved.\n */\nexport function normaliseGenerators(\n generators: VerificationHarness<unknown>['portInputGenerators'],\n): Map<string, TokenSupplier> {\n if (generators instanceof Map) return new Map(generators);\n return new Map(Object.entries(generators));\n}\n\n/**\n * @internal Normalises {@link VerificationHarness.properties} to an array of\n * {@link SmtProperty} regardless of whether the caller supplied a `Set` or an\n * array. Iteration order is preserved.\n */\nexport function normaliseProperties(\n properties: VerificationHarness<unknown>['properties'],\n): SmtProperty[] {\n if (Array.isArray(properties)) return [...properties];\n return [...(properties as ReadonlySet<SmtProperty>)];\n}\n","import type { PetriNet } from './petri-net.js';\nimport type { Transition } from './transition.js';\nimport type { Place } from './place.js';\nimport { environmentPlace, place as makePlace, type EnvironmentPlace } from './place.js';\nimport { Interface, type Channel, type Port } from './interface.js';\nimport type { Instance } from './instance.js';\nimport { __createInstance } from './instance.js';\nimport { PetriNet as PetriNetClass } from './petri-net.js';\nimport { renameNet } from './internal/subnet-rewriter.js';\nimport { SmtVerifier } from '../verification/smt-verifier.js';\nimport { alwaysAvailable } from '../verification/analysis/environment-analysis-mode.js';\nimport type { EnvironmentAnalysisMode } from '../verification/analysis/environment-analysis-mode.js';\nimport type { SmtProperty } from '../verification/smt-property.js';\nimport type { SmtVerificationResult } from '../verification/smt-verification-result.js';\nimport {\n buildVerificationResult,\n normaliseGenerators,\n normaliseProperties,\n type VerificationHarness,\n type VerificationResult,\n type TokenSupplier,\n} from '../verification/verification-harness.js';\nimport { requireOutputProducingActions } from './internal/output-action-check.js';\n\n// Re-export the real harness types from the verification module for callers\n// that import from `core/subnet-def.js`. The previous task-#10 placeholder\n// shape is removed; the surface is now backed by `verification/verification-harness.ts`.\nexport type { VerificationHarness, VerificationResult, TokenSupplier };\n\n/** @internal Symbol key restricting construction to {@link SubnetDef.builder} and {@link SubnetDef.fromNet}. */\nconst SUBNET_DEF_KEY = Symbol('SubnetDef.internal');\n\n/**\n * An open Petri net fragment paired with a declared {@link Interface}, per\n * `spec/11-modular-composition.md` requirement **MOD-001**.\n *\n * A subnet definition is the reusable unit of composition. It carries:\n * - A {@link name} (used as the originating-def label in `SubnetInstance` per [MOD-041]);\n * - A {@link body} — a structurally complete `PetriNet` per [CORE-040];\n * - An {@link iface} — the set of exposed ports and channels per [MOD-003] / [MOD-005].\n *\n * `SubnetDef` is the open variant of the {@link Subnet} discriminated union\n * defined in `subnet.ts` per **MOD-002**.\n *\n * The {@link SubnetDef.fromNet} retrofit factory per **MOD-014** wraps an\n * existing closed `PetriNet` plus an `Interface` into an unparameterised\n * `SubnetDef<void>`, applying the same per-element validation as the\n * builder's `build()`.\n *\n * @typeParam P parameter type carried through to `Instance.params`\n * (use `void` for unparameterised subnets)\n */\nexport class SubnetDef<P = void> {\n readonly name: string;\n readonly body: PetriNet;\n readonly iface: Interface;\n\n /** @internal Use {@link SubnetDef.builder} or {@link SubnetDef.fromNet} to create instances. */\n constructor(key: symbol, name: string, body: PetriNet, iface: Interface) {\n if (key !== SUBNET_DEF_KEY) {\n throw new Error('Use SubnetDef.builder() or SubnetDef.fromNet() to create instances');\n }\n this.name = name;\n this.body = body;\n this.iface = iface;\n }\n\n /**\n * Produces a renamed module instance per **MOD-010**, **MOD-011**, **MOD-012**,\n * and **MOD-030**.\n *\n * The rename pass walks every place and transition of the body net,\n * substituting each name with `prefix + \"/\" + originalName`, and rebuilds\n * every arc with rewritten place references. Transition timing, priority,\n * and action are carried through by reference (action sharing per\n * [MOD-030]). The renamed body is itself a structurally valid `PetriNet`\n * per [CORE-040]; per-instance state isolation per [MOD-012] is a\n * structural consequence of distinct prefixed names.\n *\n * ## Prefix validation\n *\n * The `\"/\"` character is reserved as the prefix separator (per [MOD-010]).\n * User-supplied prefixes MUST NOT contain `\"/\"`; nested instantiation is\n * performed by the future `PetriNetBuilder.compose(...)` mechanism (per\n * [MOD-013]). A prefix containing `\"/\"` raises an `Error`.\n *\n * @param prefix the rename prefix (non-empty, must not contain `\"/\"`)\n * @param params the parameter value carried through to `Instance.params`\n * (may be omitted when `P` is `void`)\n * @throws when `prefix` is empty or contains `\"/\"`\n */\n instantiate(prefix: string, params?: P): Instance<P> {\n validatePrefix(prefix);\n\n // Allocate the two remap maps. The rewriter fills them as side effects so\n // we can resolve interface place/transition references afterward. Maps\n // are keyed by ORIGINAL name strings (TypeScript Place identity is\n // name-based per `runtime/compiled-net.ts`).\n const placeRemap = new Map<string, Place<unknown>>();\n const transitionRemap = new Map<string, Transition>();\n\n const renamedBody = renameNet(this.body, prefix, placeRemap, transitionRemap);\n\n // Resolve port handles: original-port-name -> renamed body place.\n const portHandles = new Map<string, Place<unknown>>();\n for (const port of this.iface.ports.values()) {\n const renamed = placeRemap.get(port.place.name);\n if (renamed === undefined) {\n // Defensive: should be impossible because MOD-006 validation at\n // SubnetDef.builder.build() guarantees port.place is in the body.\n throw new Error(\n `Port '${port.name}' references place '${port.place.name}' that was not found ` +\n `in the renamed body. This indicates a SubnetDef invariant violation.`,\n );\n }\n portHandles.set(port.name, renamed);\n }\n\n // Resolve channel handles: original-channel-name -> renamed body transition.\n const channelHandles = new Map<string, Transition>();\n for (const channel of this.iface.channels.values()) {\n const renamed = transitionRemap.get(channel.transition.name);\n if (renamed === undefined) {\n throw new Error(\n `Channel '${channel.name}' references transition '${channel.transition.name}' that was not found ` +\n `in the renamed body. This indicates a SubnetDef invariant violation.`,\n );\n }\n channelHandles.set(channel.name, renamed);\n }\n\n return __createInstance<P>(\n prefix,\n this,\n renamedBody,\n portHandles,\n channelHandles,\n params as P,\n );\n }\n\n /**\n * Verifies safety properties of this subnet definition **in isolation** per\n * **MOD-051**, by wrapping it in a synthetic enclosing net where each input\n * port is fed by an {@link EnvironmentPlace} (token-source per the harness\n * generator) and each output port is observed via a synthetic place. The\n * standard {@link SmtVerifier} (per [MOD-050]) is invoked once per property\n * declared in the harness; the resulting per-property outcomes are\n * aggregated into a {@link VerificationResult}.\n *\n * ## Synthetic-net construction\n *\n * The synthetic enclosing net is built by:\n * 1. Instantiating this `SubnetDef` with the prefix `\"sut\"` (system-under-test)\n * and `harness.params`.\n * 2. For each input or in-out port on the interface, looking up the\n * harness generator by port name, allocating a synthetic\n * {@link Place}`<unknown>` of the same conceptual token type as the\n * port, wrapping it in an {@link EnvironmentPlace}, and binding the\n * port to that synthetic place via\n * {@link import('./petri-net.js').PetriNetBuilder.compose}. The supplier\n * is invoked once at construction time to materialize the seed token —\n * its presence is what bounds the input behavior under analysis. **If\n * the harness map is missing a generator for a required input or in-out\n * port, an `Error` is thrown.**\n * 3. For each output or in-out port, allocating a synthetic observation\n * {@link Place}`<unknown>` and binding the port to it via the same\n * `compose(...)` call. The verifier inspects this place's reachability\n * / marking through the standard property APIs ({@link SmtProperty}).\n * 4. Building the resulting flat {@link PetriNet} per [MOD-023] (the\n * verifier is composition-unaware per [MOD-050]).\n *\n * ## Per-property invocation\n *\n * Each {@link SmtProperty} in the harness is verified independently against\n * the same synthetic net. The synthetic environment places are passed\n * through to the verifier so that places driven by the harness generators\n * are treated under the verifier's environment-analysis semantics rather\n * than as ordinary sink places.\n *\n * @param harness the verification harness — supplies parameters, input-port\n * token generators, and the property set\n * @returns a {@link VerificationResult} aggregating per-property\n * {@link SmtVerificationResult}s\n * @throws when an input or in-out port is missing a harness generator\n */\n async verify(\n harness: VerificationHarness<P>,\n /**\n * How injection into the synthetic environment places is modeled (VER-006,\n * MOD-051 AC3).\n *\n * The synthetic net has environment places by construction, so this decides what a\n * verdict means. The default over-approximates: a `proven` under\n * `alwaysAvailable()` holds for any environment. Pass `bounded(k)` to prove a\n * property that holds only when the environment injects at most `k` tokens.\n * `ignore()` is accepted but cannot yield `proven` — VER-006 refuses to certify a\n * proof that holds only because injection was never modeled.\n */\n environmentMode: EnvironmentAnalysisMode = alwaysAvailable(),\n ): Promise<VerificationResult> {\n if (harness === null || harness === undefined) {\n throw new Error('SubnetDef.verify: harness must not be null/undefined');\n }\n\n // Step 1: instantiate this SubnetDef under the \"sut\" prefix. Uses an\n // underscore in the synthetic enclosing net's name to avoid colliding\n // with the \"/\" prefix separator (matches Java).\n const sut = this.instantiate('sut', harness.params);\n\n // Normalise the harness's generator map / property collection up front so\n // we can check membership and iterate deterministically below.\n const generators = normaliseGenerators(harness.portInputGenerators);\n const properties = normaliseProperties(harness.properties);\n\n // Step 2: allocate synthetic harness places per port direction. Track\n // the environment places (one per input/inout port) for the SmtVerifier\n // so the verifier knows to treat their underlying places as boundary\n // places rather than ordinary internals.\n const envPlaces: EnvironmentPlace<unknown>[] = [];\n const portMappings = new Map<string, Place<unknown>>();\n\n for (const port of this.iface.ports.values()) {\n const portName = port.name;\n\n switch (port.direction) {\n case 'input': {\n const generator = generators.get(portName);\n if (generator === undefined) {\n throw new Error(\n `verify: harness is missing an input generator for port '${portName}' ` +\n `on subnet '${this.name}' (MOD-051)`,\n );\n }\n // Touch the supplier to surface user-supplied errors at synthetic-\n // net construction time rather than at verification time. Mirrors\n // Java's Objects.requireNonNull(generator.get(), ...).\n const seed = generator();\n if (seed === null || seed === undefined) {\n throw new Error(\n `verify: input generator for port '${portName}' on subnet ` +\n `'${this.name}' produced null/undefined`,\n );\n }\n const synth = makePlace<unknown>(`harness_in_${portName}`);\n envPlaces.push(environmentPlace<unknown>(synth.name));\n portMappings.set(portName, synth);\n break;\n }\n case 'output': {\n const synth = makePlace<unknown>(`harness_out_${portName}`);\n portMappings.set(portName, synth);\n break;\n }\n case 'inout': {\n const generator = generators.get(portName);\n if (generator === undefined) {\n throw new Error(\n `verify: harness is missing an input generator for in-out port ` +\n `'${portName}' on subnet '${this.name}' (MOD-051)`,\n );\n }\n const seed = generator();\n if (seed === null || seed === undefined) {\n throw new Error(\n `verify: input generator for in-out port '${portName}' on subnet ` +\n `'${this.name}' produced null/undefined`,\n );\n }\n const synth = makePlace<unknown>(`harness_io_${portName}`);\n envPlaces.push(environmentPlace<unknown>(synth.name));\n portMappings.set(portName, synth);\n break;\n }\n }\n }\n\n // Step 3: build the synthetic enclosing net. Channels declared on the\n // interface (but not bound here) flow through as ordinary renamed\n // transitions per MOD-021. The `verify_` prefix uses an underscore (not\n // `/`) so the enclosing-net name does not collide with the prefix\n // separator reserved by [MOD-010].\n const syntheticNet = PetriNetClass.builder('verify_' + this.name)\n .compose(sut as Instance<unknown>, portMappings)\n .build();\n\n // CORE-043, checked here rather than left to SmtVerifier so an empty property set\n // cannot skip it.\n requireOutputProducingActions(syntheticNet);\n\n // Step 4: invoke the SmtVerifier once per property and aggregate\n // results. Iteration order matches the harness's property collection\n // for deterministic per-property reporting.\n const perProperty = new Map<SmtProperty, SmtVerificationResult>();\n for (const property of properties) {\n // Set explicitly rather than inherited: the synthetic env places are the\n // harness's own, so how injection is modelled is the harness's call\n // ([MOD-051] AC3), not the verifier default's. Under ignore() [VER-006]\n // downgrades every proof about a net with env places to Unknown, so a\n // subnet with an input port could never be proven.\n const verifier = SmtVerifier.forNet(syntheticNet).property(property);\n if (envPlaces.length > 0) {\n verifier.environmentPlaces(...envPlaces);\n verifier.environmentMode(environmentMode);\n }\n const result = await verifier.verify();\n perProperty.set(property, result);\n }\n\n return buildVerificationResult(syntheticNet, perProperty);\n }\n\n // ============================================================\n // Static factories\n // ============================================================\n\n static builder<P = void>(name: string): SubnetDefBuilder<P> {\n return new SubnetDefBuilder<P>(name);\n }\n\n /**\n * Retrofit utility per **MOD-014**: wraps an existing closed {@link PetriNet}\n * plus an {@link Interface} into an unparameterised `SubnetDef<void>`.\n *\n * Validation per **MOD-014** / **MOD-006** is enforced before the result is\n * constructed:\n * - Every port's underlying `Place` must be present in `net.places`.\n * - Every channel's underlying `Transition` must be present in `net.transitions`.\n * - Port and channel name uniqueness is re-validated defensively (the\n * `Interface` builder already enforces this; hand-built `Interface`\n * values bypass that path).\n *\n * The resulting subnet definition is unparameterised (parameter type is `void`).\n *\n * @throws when a port place is not in `net.places`, a channel transition is\n * not in `net.transitions`, or port/channel names are not unique.\n */\n static fromNet(net: PetriNet, iface: Interface): SubnetDef<void> {\n const bodyPlaces = net.places;\n const bodyTransitions = net.transitions;\n\n // Re-validate port-name uniqueness (defence in depth — InterfaceBuilder\n // enforces it for the builder route, but a hand-built `Interface`\n // bypasses that path; SubnetDef.fromNet is the documented retrofit\n // entry point so we re-check here to keep failures crisp). Note: do NOT\n // use `Set#add`'s return value — `Set#add` returns the Set itself\n // (truthy) and cannot signal \"already present\"; check with `has` first.\n const seenPortNames = new Set<string>();\n for (const port of iface.ports.values()) {\n if (seenPortNames.has(port.name)) {\n throw new Error(\n `fromNet: duplicate port name '${port.name}' on interface for net '${net.name}' (MOD-006)`,\n );\n }\n seenPortNames.add(port.name);\n if (!bodyPlaces.has(port.place as Place<unknown>)) {\n throw new Error(\n `fromNet: port '${port.name}' references place '${port.place.name}' which is not in net '${net.name}' (MOD-014/MOD-006)`,\n );\n }\n }\n\n // Re-validate channel-name uniqueness and transition membership.\n const seenChannelNames = new Set<string>();\n for (const channel of iface.channels.values()) {\n if (seenChannelNames.has(channel.name)) {\n throw new Error(\n `fromNet: duplicate channel name '${channel.name}' on interface for net '${net.name}' (MOD-006)`,\n );\n }\n seenChannelNames.add(channel.name);\n if (!bodyTransitions.has(channel.transition)) {\n throw new Error(\n `fromNet: channel '${channel.name}' references transition '${channel.transition.name}' which is not in net '${net.name}' (MOD-014/MOD-006)`,\n );\n }\n }\n\n return new SubnetDef<void>(SUBNET_DEF_KEY, net.name, net, iface);\n }\n}\n\n/**\n * Fluent builder for {@link SubnetDef}.\n *\n * Validation per **MOD-006** is enforced at {@link build}:\n * - Every port's underlying place must be in the body net.\n * - Every channel's underlying transition must be in the body net.\n * - Port names must be unique within the port namespace.\n * - Channel names must be unique within the channel namespace.\n */\nexport class SubnetDefBuilder<P = void> {\n private readonly _name: string;\n private readonly _bodyBuilder: ReturnType<typeof PetriNetClass.builder>;\n private readonly _ports: Port<unknown>[] = [];\n private readonly _channels: Channel[] = [];\n\n constructor(name: string) {\n this._name = name;\n this._bodyBuilder = PetriNetClass.builder(name);\n }\n\n // -------- body construction (delegates to PetriNet.Builder) --------\n\n transition(transition: Transition): this {\n this._bodyBuilder.transition(transition);\n return this;\n }\n\n transitions(...transitions: Transition[]): this {\n this._bodyBuilder.transitions(...transitions);\n return this;\n }\n\n place<T>(place: Place<T>): this {\n this._bodyBuilder.place(place);\n return this;\n }\n\n // -------- interface declarations --------\n\n inputPort<T>(name: string, place: Place<T>): this {\n this._ports.push({ name, direction: 'input', place: place as Place<unknown> });\n return this;\n }\n\n outputPort<T>(name: string, place: Place<T>): this {\n this._ports.push({ name, direction: 'output', place: place as Place<unknown> });\n return this;\n }\n\n inoutPort<T>(name: string, place: Place<T>): this {\n this._ports.push({ name, direction: 'inout', place: place as Place<unknown> });\n return this;\n }\n\n channel(name: string, transition: Transition): this {\n this._channels.push({ name, transition });\n return this;\n }\n\n // -------- build & validate (MOD-006) --------\n\n build(): SubnetDef<P> {\n const built = this._bodyBuilder.build();\n const bodyPlaces = built.places;\n const bodyTransitions = built.transitions;\n\n // 1. Validate port-name uniqueness (MOD-006). Note: do NOT use\n // `Set#add`'s return value — it returns the Set itself (truthy) and\n // cannot signal \"already present\"; check with `has` first.\n const portNames = new Set<string>();\n for (const port of this._ports) {\n if (portNames.has(port.name)) {\n throw new Error(`Subnet '${this._name}': duplicate port name '${port.name}'`);\n }\n portNames.add(port.name);\n // 2. Validate port place membership (MOD-006).\n if (!bodyPlaces.has(port.place as Place<unknown>)) {\n throw new Error(\n `Subnet '${this._name}': port '${port.name}' references place '${port.place.name}' which is not in the body`,\n );\n }\n }\n\n // 3. Validate channel-name uniqueness and transition membership (MOD-006).\n const channelNames = new Set<string>();\n for (const channel of this._channels) {\n if (channelNames.has(channel.name)) {\n throw new Error(`Subnet '${this._name}': duplicate channel name '${channel.name}'`);\n }\n channelNames.add(channel.name);\n if (!bodyTransitions.has(channel.transition)) {\n throw new Error(\n `Subnet '${this._name}': channel '${channel.name}' references transition '${channel.transition.name}' which is not in the body`,\n );\n }\n }\n\n const ifaceBuilder = Interface.builder();\n ifaceBuilder.portsAll(this._ports);\n ifaceBuilder.channelsAll(this._channels);\n const iface = ifaceBuilder.build();\n\n return new SubnetDef<P>(SUBNET_DEF_KEY, this._name, built, iface);\n }\n}\n\n/**\n * @internal Validates the prefix supplied to {@link SubnetDef.instantiate}\n * per **MOD-010**:\n * - non-empty;\n * - no `\"/\"` (reserved as the prefix separator; nested instantiation is\n * performed by `PetriNetBuilder.compose(...)` per [MOD-013]).\n *\n * Throws an `Error` with a descriptive message on failure.\n */\nfunction validatePrefix(prefix: string): void {\n if (typeof prefix !== 'string' || prefix.length === 0) {\n throw new Error('SubnetDef.instantiate: prefix must be a non-empty string');\n }\n if (prefix.indexOf('/') >= 0) {\n throw new Error(\n `SubnetDef.instantiate: prefix must not contain '/' (reserved as the prefix ` +\n `separator per MOD-010); use compose(...) for nested instantiation. Got: '${prefix}'`,\n );\n }\n}\n","import type { Place } from './place.js';\nimport type { Transition } from './transition.js';\n\n/**\n * @internal Symbol key restricting construction to\n * {@link PetriNetBuilder.compose}. Bindings are produced by the host builder\n * and supplied to the caller's callback — direct construction is not part of\n * the public API.\n */\nconst COMPOSE_BINDINGS_KEY = Symbol('ComposeBindings.internal');\n\n/**\n * Typed binding builder for {@link PetriNetBuilder.compose}, per\n * `spec/11-modular-composition.md` requirements **MOD-020** (composition\n * operation) and **MOD-022** (type compatibility).\n *\n * `ComposeBindings` is a write-only collector: callers register port and\n * channel bindings against an instance's interface, and the host builder\n * consumes the recorded mappings as it merges the instance into the\n * enclosing net.\n *\n * ## Port bindings (MOD-020, MOD-022)\n *\n * {@link bindPort} merges an interface port with a caller-side place. The\n * port name is the **original** (pre-prefix) name declared in the subnet's\n * `Interface`; the caller place takes the port's slot in the resulting net.\n * Token-type compatibility is enforced at compile time only in TypeScript\n * (per [MOD-022]) — the typed `bindPort<T>` signature is the safety\n * mechanism. TypeScript erases generics at runtime, so a misuse via `as`\n * casts is structurally undetectable.\n *\n * ## Channel bindings (MOD-021)\n *\n * {@link bindChannel} records a synchronous channel binding: at compose time\n * the named instance-side interface transition is **merged** with the\n * supplied caller-side {@link Transition} into one transition in the\n * resulting flat net. Channel composition is implemented in task #13; until\n * then `compose(...)` raises an `Error` when any channel binding is present.\n *\n * ## Identity\n *\n * Instances are produced by {@link PetriNetBuilder.compose} and supplied to\n * the caller's callback. The constructor is symbol-guarded to prevent\n * direct construction.\n */\nexport class ComposeBindings {\n private readonly _portBindings = new Map<string, Place<unknown>>();\n private readonly _channelBindings = new Map<string, Transition>();\n\n /**\n * @internal Use {@link PetriNetBuilder.compose} — instances are produced\n * by the host builder and supplied to the caller's callback.\n */\n constructor(key: symbol) {\n if (key !== COMPOSE_BINDINGS_KEY) {\n throw new Error(\n 'Use PetriNetBuilder.compose(instance, b => ...) — ComposeBindings is not directly constructible',\n );\n }\n }\n\n /**\n * Binds the named interface port to the given caller place per **MOD-020**.\n *\n * The port name is the **original** (pre-prefix) name declared in the\n * subnet's `Interface`. The typed `<T>` parameter ensures the caller\n * place's token type matches the interface port's token type at compile\n * time per [MOD-022]; TypeScript does not validate the type at runtime\n * because generics are erased.\n *\n * @throws when `portName` is already bound on this builder\n */\n bindPort<T>(portName: string, callerPlace: Place<T>): this {\n if (this._portBindings.has(portName)) {\n throw new Error(`Port '${portName}' is already bound`);\n }\n this._portBindings.set(portName, callerPlace as Place<unknown>);\n return this;\n }\n\n /**\n * Records a synchronous channel binding per **MOD-021**: at compose time,\n * the instance-side renamed channel transition is merged with\n * `callerTransition` into a single transition in the resulting flat net.\n *\n * **Status**: channel composition is implemented in task #13. Recording a\n * channel binding here is permitted, but `compose(...)` currently raises\n * an `Error` when any channel binding is present.\n *\n * @throws when `channelName` is already bound on this builder\n */\n bindChannel(channelName: string, callerTransition: Transition): this {\n if (this._channelBindings.has(channelName)) {\n throw new Error(`Channel '${channelName}' is already bound`);\n }\n this._channelBindings.set(channelName, callerTransition);\n return this;\n }\n\n /** Returns an unmodifiable view of the recorded port bindings. */\n portBindings(): ReadonlyMap<string, Place<unknown>> {\n return this._portBindings;\n }\n\n /** Returns an unmodifiable view of the recorded channel bindings. */\n channelBindings(): ReadonlyMap<string, Transition> {\n return this._channelBindings;\n }\n}\n\n/**\n * @internal Package-internal factory used by {@link PetriNetBuilder.compose}\n * to construct {@link ComposeBindings} values without re-exporting the\n * Symbol-guarded constructor key publicly.\n *\n * NOT part of the public API surface — do NOT re-export from `core/index.ts`.\n */\nexport function __createComposeBindings(): ComposeBindings {\n return new ComposeBindings(COMPOSE_BINDINGS_KEY);\n}\n","import type { Place } from './place.js';\n\n/** @internal Symbol key restricting construction to {@link FusionSet.builder} and {@link FusionSet.of}. */\nconst FUSION_SET_KEY = Symbol('FusionSet.internal');\n\n/**\n * A declaration that N typed places are to be treated as a single canonical\n * place in the resulting flat {@link import('./petri-net.js').PetriNet}, per\n * `spec/11-modular-composition.md` requirements **MOD-060** (fusion set\n * declaration) and **MOD-061** (fusion resolution at build).\n *\n * Fusion is **orthogonal to subnet composition**: composition merges places\n * via port-binding (one instance port place ↔ one caller place per binding);\n * fusion merges N places at once via N-ary equivalence, applied **after** all\n * `compose(...)` calls have flattened subnet instances into the enclosing\n * {@link import('./petri-net.js').PetriNetBuilder}. Fusion is the mechanism\n * for modeling shared cross-instance state — e.g., a global rate limiter\n * shared by three instances of a leaky-bucket subnet — without expressing the\n * shared resource as an interface port on every subnet.\n *\n * ## Canonical member\n *\n * The **first declared member** is the canonical place; the others are\n * non-canonical and get substituted away at\n * {@link import('./petri-net.js').PetriNetBuilder.build} time. The canonical\n * member's name and identity survive into the resulting flat net;\n * non-canonical members do not appear in the built net's place set.\n *\n * ## Token-type homogeneity (MOD-060)\n *\n * All members of a fusion set MUST share the same token type. **In\n * TypeScript** this is enforced at **compile time only** (via the typed\n * `<T>` parameter on {@link FusionSetBuilder.member} and the typed varargs of\n * {@link FusionSet.of}); per the TS-specific MOD-022 clause, no runtime\n * `tokenType` introspection exists because Place carries only a phantom\n * generic. The Java implementation enforces the same invariant at runtime.\n *\n * ## Single-member sets\n *\n * A fusion set with a single member is degenerate but allowed: it is a no-op\n * at fusion-resolution time (the canonical member maps to itself, no\n * substitution occurs). This matches the structural semantics of an N-ary\n * equivalence with N=1.\n *\n * ## Identity\n *\n * `FusionSet` is immutable after construction. The {@link members} array is\n * frozen; iteration order is the declaration order, with the first element\n * guaranteed to be the canonical member.\n *\n * @see import('./petri-net.js').PetriNetBuilder.fuse\n */\nexport class FusionSet {\n readonly name: string;\n readonly members: readonly Place<unknown>[];\n\n /** @internal Use {@link FusionSet.builder} or {@link FusionSet.of} to create instances. */\n constructor(key: symbol, name: string, members: readonly Place<unknown>[]) {\n if (key !== FUSION_SET_KEY) {\n throw new Error('Use FusionSet.builder() or FusionSet.of() to create instances');\n }\n this.name = name;\n this.members = members;\n }\n\n /**\n * Returns the canonical member — by convention, the first declared member.\n * The canonical place's identity survives into the resulting flat net.\n */\n get canonical(): Place<unknown> {\n return this.members[0]!;\n }\n\n /**\n * Returns all members **except** the canonical member, in declaration order.\n * These are the places that get substituted away at\n * {@link import('./petri-net.js').PetriNetBuilder.build} time.\n *\n * For a single-member (degenerate) set, returns an empty array.\n */\n nonCanonical(): readonly Place<unknown>[] {\n if (this.members.length <= 1) return [];\n return this.members.slice(1);\n }\n\n toString(): string {\n return `FusionSet[${this.name}, canonical=${this.canonical.name}, members=${this.members.length}]`;\n }\n\n // ============================================================\n // Static factories\n // ============================================================\n\n /** Returns a fresh {@link FusionSetBuilder} with the given human-readable name. */\n static builder(name: string): FusionSetBuilder {\n return new FusionSetBuilder(name);\n }\n\n /**\n * Convenience factory: builds a fusion set whose first member is `first`\n * (the canonical) and whose remaining members are `rest`, all sharing the\n * type `<T>`.\n *\n * The varargs form ensures static-type homogeneity at the call site (the\n * TypeScript compiler checks every `rest` entry is a `Place<T>`).\n */\n static of<T>(name: string, first: Place<T>, ...rest: Place<T>[]): FusionSet {\n const members: Place<unknown>[] = [first as Place<unknown>];\n for (const p of rest) members.push(p as Place<unknown>);\n return new FusionSet(FUSION_SET_KEY, name, Object.freeze(members));\n }\n}\n\n/**\n * Fluent builder for {@link FusionSet}.\n *\n * Members are appended in call order; the first member becomes the canonical\n * place. The typed `<T>` parameter on {@link member} is for compile-time\n * guidance only — TypeScript erases generics at runtime, so no homogeneity\n * check happens here.\n */\nexport class FusionSetBuilder {\n private readonly _name: string;\n private readonly _members: Place<unknown>[] = [];\n\n constructor(name: string) {\n if (typeof name !== 'string' || name.length === 0) {\n throw new Error('FusionSet.builder: name must be a non-empty string');\n }\n this._name = name;\n }\n\n /**\n * Appends a member to the fusion set. The first member becomes the canonical\n * place per the convention documented on {@link FusionSet}.\n *\n * The `<T>` parameter is for compile-time guidance only: callers writing\n * typed code at the same call site benefit from the compiler checking\n * `Place<T>` at each member.\n */\n member<T>(place: Place<T>): this {\n if (place === undefined || place === null) {\n throw new Error(`FusionSet '${this._name}': member place must not be null`);\n }\n this._members.push(place as Place<unknown>);\n return this;\n }\n\n /**\n * Builds the immutable {@link FusionSet}. Validates that the set has at\n * least one member; the empty set is rejected as malformed per **MOD-060**.\n * Single-member sets are accepted as a structurally degenerate no-op.\n */\n build(): FusionSet {\n if (this._members.length === 0) {\n throw new Error(\n `FusionSet '${this._name}': must have at least one member (MOD-060)`,\n );\n }\n return new FusionSet(FUSION_SET_KEY, this._name, Object.freeze(this._members.slice()));\n }\n}\n\n/**\n * @internal Re-exported symbol key so the {@link FusionSet} test harness can\n * verify the symbol-guard. NOT part of the public API surface.\n */\nexport const __FUSION_SET_KEY_FOR_TEST = FUSION_SET_KEY;\n","import type { Place } from './place.js';\nimport type { TransitionAction } from './transition-action.js';\nimport { passthrough } from './transition-action.js';\nimport { Transition } from './transition.js';\nimport type { Instance } from './instance.js';\nimport { SubnetDef } from './subnet-def.js';\nimport { ComposeBindings, __createComposeBindings } from './compose-bindings.js';\nimport { applyFusion, mergeTransitions, substitutePlaces } from './internal/subnet-rewriter.js';\nimport { FusionSet, FusionSetBuilder } from './fusion-set.js';\n\n/** @internal Symbol key restricting construction to the builder and bindActions. */\nconst PETRI_NET_KEY = Symbol('PetriNet.internal');\n\n/**\n * Immutable definition of a Time Petri Net structure.\n *\n * A PetriNet is a reusable definition that can be executed multiple times\n * with different initial markings. Places are auto-collected from transitions.\n */\nexport class PetriNet {\n readonly name: string;\n readonly places: ReadonlySet<Place<any>>;\n readonly transitions: ReadonlySet<Transition>;\n\n /**\n * Subnet-membership metadata per **MOD-026**: maps each node name (place or\n * transition) contributed by exactly one directly-composed subnet to that\n * subnet's name. Shared places contributed by two or more subnets, and every\n * node of a net not built via {@link PetriNetBuilder.compose}`(SubnetDef)`,\n * are absent. Never null — an empty map when there is no metadata. The DOT\n * exporter renders `subgraph cluster_*` blocks from this map.\n *\n * V8 `Map` is insertion-ordered, preserving compose order so cluster\n * subgraphs render deterministically (cross-language byte-parity).\n */\n readonly subnetMembership: ReadonlyMap<string, string>;\n\n /** @internal Use {@link PetriNet.builder} to create instances. */\n constructor(\n key: symbol,\n name: string,\n places: ReadonlySet<Place<any>>,\n transitions: ReadonlySet<Transition>,\n subnetMembership: ReadonlyMap<string, string> = new Map(),\n ) {\n if (key !== PETRI_NET_KEY) throw new Error('Use PetriNet.builder() to create instances');\n this.name = name;\n this.places = places;\n this.transitions = transitions;\n this.subnetMembership = subnetMembership;\n }\n\n /**\n * Creates a new PetriNet with actions bound to transitions by name.\n * Unbound transitions keep passthrough action.\n */\n bindActions(actionBindings: Map<string, TransitionAction> | Record<string, TransitionAction>): PetriNet {\n const bindings = actionBindings instanceof Map\n ? actionBindings\n : new Map(Object.entries(actionBindings));\n\n return this.bindActionsWithResolver(\n (name) => bindings.get(name) ?? passthrough(),\n );\n }\n\n /**\n * Creates a new PetriNet with actions bound via a resolver function.\n *\n * The resolver is called once per transition with its name. Returning `null`\n * defers that transition — it keeps whatever action it already carries — which\n * is what makes staged binding (**MOD-024** AC7) work.\n */\n bindActionsWithResolver(actionResolver: (name: string) => TransitionAction | null): PetriNet {\n const boundTransitions = new Set<Transition>();\n for (const t of this.transitions) {\n const action = actionResolver(t.name);\n if (action !== null && action !== t.action) {\n boundTransitions.add(rebuildWithAction(t, action));\n } else {\n boundTransitions.add(t);\n }\n }\n // MOD-026: bindActions rebuilds transitions but preserves their names, so\n // name-keyed membership metadata survives a session bind unchanged.\n return new PetriNet(PETRI_NET_KEY, this.name, this.places, boundTransitions,\n this.subnetMembership);\n }\n\n static builder(name: string): PetriNetBuilder {\n return new PetriNetBuilder(name);\n }\n}\n\nexport class PetriNetBuilder {\n private readonly _name: string;\n private readonly _places = new Set<Place<any>>();\n private readonly _transitions = new Set<Transition>();\n private readonly _fusionSets: FusionSet[] = [];\n // MOD-026: node name -> set of subnet names that contributed it via\n // compose(SubnetDef), in first-contribution order. Resolved to single-owner\n // membership at build(). V8 Map/Set iterate in insertion order, preserving\n // compose order for cross-language byte-parity.\n private readonly _subnetContributions = new Map<string, Set<string>>();\n\n constructor(name: string) {\n this._name = name;\n }\n\n /** Add an explicit place. */\n place(place: Place<any>): this {\n this._places.add(place);\n return this;\n }\n\n /** Add explicit places. */\n places(...places: Place<any>[]): this {\n for (const p of places) this._places.add(p);\n return this;\n }\n\n /** Add a transition (auto-collects places from arcs). */\n transition(transition: Transition): this {\n this._transitions.add(transition);\n for (const spec of transition.inputSpecs) {\n this._places.add(spec.place);\n }\n for (const p of transition.outputPlaces()) {\n this._places.add(p);\n }\n for (const inh of transition.inhibitors) {\n this._places.add(inh.place);\n }\n for (const r of transition.reads) {\n this._places.add(r.place);\n }\n for (const r of transition.resets) {\n this._places.add(r.place);\n }\n return this;\n }\n\n /** Add transitions (auto-collects places from arcs). */\n transitions(...transitions: Transition[]): this {\n for (const t of transitions) this.transition(t);\n return this;\n }\n\n /**\n * Composes a subnet {@link Instance} into this builder per **MOD-020**\n * (composition operation), **MOD-021** (channel composition), **MOD-022**\n * (type compatibility), and **MOD-023** (composition produces a flat net).\n *\n * Two overloads are supported:\n *\n * 1. **Map / Record overload** — the runtime-checked form. Pass a\n * `Map<string, Place<unknown>>` or a `Record<string, Place<unknown>>`\n * keyed by the subnet's **original** (pre-prefix) port names. No\n * channel bindings are recorded by this overload.\n *\n * 2. **Callback overload** — the typed form. Pass a callback receiving a\n * fresh {@link ComposeBindings}; register port bindings via\n * `bindings.bindPort<T>(name, place)` so TypeScript checks each\n * binding's token type at compile time per [MOD-022]. Synchronous\n * channels may be merged with caller-side transitions via\n * `bindings.bindChannel(name, t)` per [MOD-021].\n *\n * For each port binding `(portName -> callerPlace)`, the instance's\n * renamed port place is substituted with the caller place at every arc\n * in the instance's renamed body via the `subnet-rewriter` module.\n * Internal (non-port) places of the instance flow through with their\n * prefixed names. Composition is **eager** — the rewrite happens here,\n * not at `build()` (per [MOD-020] AC #5).\n *\n * For each channel binding `(channelName -> callerTransition)`, the\n * instance's renamed channel transition and the caller-side transition\n * are merged into one transition in the resulting flat net per [MOD-021].\n * If the caller-side transition has not been added to this builder yet,\n * it is added implicitly during the merge step.\n *\n * @throws when a port name is unknown on the instance's interface, when a\n * channel name is unknown on the interface, or when caller- and\n * instance-side transition timings conflict (per [MOD-021]).\n */\n compose(instance: Instance<unknown>): this;\n compose(\n instance: Instance<unknown>,\n portMappings: ReadonlyMap<string, Place<unknown>> | Record<string, Place<unknown>>,\n ): this;\n compose(\n instance: Instance<unknown>,\n bind: (b: ComposeBindings) => void,\n ): this;\n compose(def: SubnetDef<unknown>): this;\n compose(\n instanceOrDef: Instance<unknown> | SubnetDef<unknown>,\n arg?:\n | ReadonlyMap<string, Place<unknown>>\n | Record<string, Place<unknown>>\n | ((b: ComposeBindings) => void),\n ): this {\n if (instanceOrDef instanceof SubnetDef) {\n return this.composeDirect(instanceOrDef);\n }\n const instance = instanceOrDef;\n if (arg === undefined) {\n return this.composeAuto(instance);\n }\n if (typeof arg === 'function') {\n const bindings = __createComposeBindings();\n arg(bindings);\n return this.composeInternal(instance, bindings.portBindings(), bindings.channelBindings());\n }\n\n const portMappings: ReadonlyMap<string, Place<unknown>> =\n arg instanceof Map ? arg : new Map(Object.entries(arg));\n return this.composeInternal(instance, portMappings, new Map());\n }\n\n /**\n * Composes a subnet {@link SubnetDef} **directly** into this builder per\n * **MOD-025** — **without instantiation**, and without the prefix-renaming\n * of {@link SubnetDef.instantiate}.\n *\n * Every body place and transition is added under its **original**\n * (un-prefixed) name. Places merge into this builder by name: a body place\n * whose name equals an enclosing-net place *is* that place in the composed\n * flat net. This is the mode for wiring a subnet in as a single shared copy.\n *\n * Direct composition is **order-independent**: composing the same set of\n * subnets in any order yields the same flat net, because merging is by\n * place name and not by a probe of the builder's place set at call time —\n * contrast the no-interface body-inference branch of {@link composeAuto}\n * (MOD-024), which is order-sensitive.\n *\n * For multiple *independent* copies — each with isolated per-instance state\n * per [MOD-012] — use {@link SubnetDef.instantiate} + the `compose(instance)`\n * overload instead.\n *\n * Rejections: a body transition whose name already exists in this builder\n * (use `instantiate(prefix)` for independent copies); a subnet whose\n * interface declares any channel (direct composition does not bind\n * channels — use `instantiate` + the channel-binding `compose` overload).\n *\n * Token-type conflicts on a same-named place cannot be detected: TS\n * {@link Place} equality is name-only at runtime (the documented carve-out,\n * same as MOD-024).\n *\n * @throws when the subnet declares channels, or a body transition name\n * collides with a transition already in this builder.\n */\n private composeDirect(def: SubnetDef<unknown>): this {\n const iface = def.iface;\n\n // MOD-025: direct composition does not bind channels.\n if (iface.channels.size > 0) {\n const channelNames: string[] = [];\n for (const c of iface.channels.values()) channelNames.push(c.name);\n channelNames.sort();\n throw new Error(\n `compose(SubnetDef): subnet '${def.name}' declares channels ` +\n `[${channelNames.join(', ')}]; direct composition does not bind channels.` +\n ` Use def.instantiate(prefix) + compose(instance, bind => bind.bindChannel(...)).`,\n );\n }\n\n const body = def.body;\n\n // MOD-025: a body transition whose name already exists here is almost\n // always a mistake — instantiate(prefix) is the multi-copy path.\n const hostTransitionNames = new Set<string>();\n for (const t of this._transitions) hostTransitionNames.add(t.name);\n for (const t of body.transitions) {\n if (hostTransitionNames.has(t.name)) {\n throw new Error(\n `compose(SubnetDef): transition '${t.name}' from subnet '${def.name}' ` +\n `collides with a transition already in net '${this._name}'. Direct ` +\n `composition merges by name; for independent copies use ` +\n `def.instantiate(prefix) + compose(instance).`,\n );\n }\n }\n\n // Canonicalize place references. TS `Set<Place>` dedups by reference, so\n // a body place value-equal-by-name to a host place must be funnelled\n // through the single host reference (same intent as composeAuto). Body\n // places with a new name are canonical as themselves; arcs referencing\n // them are left untouched by substitutePlaces.\n const hostByName = new Map<string, Place<unknown>>();\n for (const p of this._places) hostByName.set(p.name, p);\n\n // MOD-026: record which subnet each node came from so cluster-aware DOT\n // export can reconstruct subgraphs without prefix names. The subnet name\n // is sanitised of '/' so it never triggers spurious nested-cluster\n // splitting in the exporter.\n const subnetName = def.name.replace(/\\//g, '_');\n\n const mergeMap = new Map<string, Place<unknown>>();\n for (const p of body.places) {\n const host = hostByName.get(p.name);\n this.place(host ?? p);\n if (host !== undefined) mergeMap.set(p.name, host);\n this.recordContribution(p.name, subnetName);\n }\n for (const t of body.transitions) {\n this.transition(substitutePlaces(t, mergeMap));\n this.recordContribution(t.name, subnetName);\n }\n return this;\n }\n\n /** @internal MOD-026: records a node as contributed by the named subnet. */\n private recordContribution(nodeName: string, subnetName: string): void {\n let owners = this._subnetContributions.get(nodeName);\n if (owners === undefined) {\n owners = new Set<string>();\n this._subnetContributions.set(nodeName, owners);\n }\n owners.add(subnetName);\n }\n\n /**\n * Identity-default auto-compose per **MOD-024**.\n *\n * Each declared interface port auto-binds to its own `port.place` — the\n * Place the SubnetDef builder declared via `.inputPort(name, hostPlace)`\n * (or `outputPort` / `inoutPort`). If the host builder already declares\n * the equal place, the two merge; if not, the place arrives implicitly\n * via the rewritten transitions' arcs (same flow as explicit `bindPort`).\n *\n * If the subnet declares no interface ports at all, body places are\n * checked against this builder's place set **by name** (matching the\n * existing TS Place equality semantics; see [CORE-002] note in\n * `spec/11-modular-composition.md` MOD-024). Body places that don't match\n * stay private under their prefixed names per [MOD-010].\n *\n * Channels are NOT auto-bound — transition identity is too delicate for\n * inference. If the subnet declares any channel, this overload throws.\n */\n private composeAuto(instance: Instance<unknown>): this {\n const iface = instance.def.iface;\n\n if (iface.channels.size > 0) {\n const channelNames: string[] = [];\n for (const c of iface.channels.values()) channelNames.push(c.name);\n channelNames.sort();\n throw new Error(\n `compose(Instance): subnet '${instance.def.name}' ` +\n `(instance prefix '${instance.prefix}') declares channels [${channelNames.join(', ')}]` +\n `; auto-compose does not bind channels.` +\n ` Use compose(instance, bind => bind.bindChannel(...)) with explicit channel bindings.`,\n );\n }\n\n // Pre-index host places by name. The TS `_places: Set<Place>` dedupes\n // by reference (Place is an interface with only `name`), so when the\n // host pre-declared a Place object that is value-equal-by-name but a\n // different reference from the SubnetDef port's carried place, we\n // prefer the host reference: arc rewriting funnels through it and the\n // port's own Place object never enters `_places`. Same intent as\n // Rust's `place_index.get(&probe).cloned().unwrap_or(probe)` and\n // Java's record-equality `places.contains(probe)` in this branch.\n const hostByName = new Map<string, Place<unknown>>();\n for (const p of this._places) hostByName.set(p.name, p);\n\n if (iface.ports.size > 0) {\n // Explicit interface: each declared port auto-binds to its own\n // declared place. The SubnetDef's inputPort/outputPort/inoutPort\n // statement IS the host wiring — trust it. When a host place with\n // the same name already exists, use the host reference so the\n // merged net has a single Place per name.\n const portMappings = new Map<string, Place<unknown>>();\n for (const port of iface.ports.values()) {\n const hostMatch = hostByName.get(port.place.name);\n portMappings.set(port.name, hostMatch ?? port.place);\n }\n return this.composeInternal(instance, portMappings, new Map());\n }\n\n // No declared interface — infer the merge set from body places that\n // also exist on the host builder (matched by name). Build the\n // renamed-name -> host-place map directly and apply the composition.\n\n const mergeMap = new Map<string, Place<unknown>>();\n const prefix = instance.prefix + '/';\n for (const renamed of instance.renamedBody.places) {\n if (!renamed.name.startsWith(prefix)) continue;\n const originalName = renamed.name.substring(prefix.length);\n const hostMatch = hostByName.get(originalName);\n if (hostMatch !== undefined) {\n mergeMap.set(renamed.name, hostMatch);\n }\n }\n return this.applyComposition(instance, mergeMap, new Map());\n }\n\n /**\n * @internal Shared compose implementation: validates port and channel\n * bindings, builds the place-substitution map, walks every renamed-body\n * transition through {@link substitutePlaces}, applies channel merges per\n * [MOD-021], and adds the resulting transitions to this builder.\n *\n * ## Channel-merge flow ([MOD-021])\n *\n * 1. Collect rewritten instance transitions into a working `Map<string,\n * Transition>` keyed by prefixed transition name (deferred — not yet\n * added to the builder's transition set).\n * 2. For each channel binding, resolve the renamed instance-side\n * transition through `instance.channel(channelName)`, then look up its\n * rewritten counterpart in the working map by name.\n * 3. Replace the working-map entry with a {@link mergeTransitions} result\n * that fuses caller-side + instance-side; remove the rewritten\n * instance-side entry. Also replace (or add) the caller-side\n * transition in this builder's transition set with the same merged\n * result, indexed under the caller's name slot.\n * 4. Add the surviving (un-merged) entries to this builder.\n *\n * The deferral matters: writing the rewritten instance transitions to the\n * builder eagerly would force a second \"remove-then-replace\" pass to\n * apply the channel merges, complicating the place-collection invariants.\n * Collecting first and merging second keeps the builder's transition set\n * finalized exactly once.\n *\n * Keying the working map by prefixed transition name (rather than by\n * Transition reference) is also robust against a prior\n * {@link Instance.bindActions} call that may have rebuilt the renamed-body\n * transitions, breaking identity equality between the body and the\n * channel-handle map — but the prefixed names remain stable.\n */\n private composeInternal(\n instance: Instance<unknown>,\n portMappings: ReadonlyMap<string, Place<unknown>>,\n channelBindings: ReadonlyMap<string, Transition>,\n ): this {\n const iface = instance.def.iface;\n\n // Build mergeMap: keyed by RENAMED instance-side place name -> caller\n // place. The subnet-rewriter resolves arc-place references by name\n // (matching TS Place identity model: name-based equality per\n // runtime/compiled-net.ts), so we key by the renamed name.\n const mergeMap = new Map<string, Place<unknown>>();\n\n for (const [portName, callerPlace] of portMappings) {\n const port = iface.port(portName);\n if (port === undefined) {\n const knownPorts: string[] = [];\n for (const p of iface.ports.values()) knownPorts.push(p.name);\n throw new Error(\n `compose: no port named '${portName}' on subnet '${instance.def.name}' ` +\n `(instance prefix '${instance.prefix}'). Known ports: [${knownPorts.join(', ')}]`,\n );\n }\n\n // Resolve the renamed instance-side place via the typed accessor;\n // this gives us the rewritten Place<unknown> in the instance body.\n const ifacePlace = instance.port<unknown>(portName);\n mergeMap.set(ifacePlace.name, callerPlace);\n }\n\n return this.applyComposition(instance, mergeMap, channelBindings);\n }\n\n /**\n * Shared post-mergeMap pipeline: rewrites renamed-body transitions\n * through `mergeMap`, applies channel merges per **MOD-021**, and adds\n * the surviving transitions to the builder.\n *\n * Used by both the explicit-binding path (`composeInternal`) and the\n * auto-compose path (`composeAuto` per **MOD-024**). The two paths differ\n * only in how the (renamed Place name → host Place) `mergeMap` is built.\n */\n private applyComposition(\n instance: Instance<unknown>,\n mergeMap: Map<string, Place<unknown>>,\n channelBindings: ReadonlyMap<string, Transition>,\n ): this {\n const iface = instance.def.iface;\n\n // Step 1: Stage rewritten instance transitions in a working map keyed\n // by prefixed transition name. The substitutePlaces primitive keeps\n // the prefixed transition name unchanged (per MOD-010 — prefixed names\n // are already unique within the host) and rewrites only the arc place\n // references.\n const rewrittenByName = new Map<string, Transition>();\n for (const t of instance.renamedBody.transitions) {\n rewrittenByName.set(t.name, substitutePlaces(t, mergeMap));\n }\n\n // Step 2: Apply channel merges. For each binding, locate the rewritten\n // instance-side transition by name, fuse it with the caller-side\n // transition, and replace the working-map entry. Also replace the\n // caller-side transition in this builder's transition set with the\n // merged result (or add it if the caller did not pre-add it).\n for (const [channelName, callerTrans] of channelBindings) {\n // Resolve the renamed instance-side channel transition. instance.channel\n // throws on unknown name; we re-wrap with a more contextual message.\n let instanceRenamedChannel: Transition;\n try {\n instanceRenamedChannel = instance.channel(channelName);\n } catch (cause) {\n const knownChannels: string[] = [];\n for (const c of iface.channels.values()) knownChannels.push(c.name);\n const err = new Error(\n `compose: no channel named '${channelName}' on subnet '${instance.def.name}' ` +\n `(instance prefix '${instance.prefix}'). Known channels: [${knownChannels.join(', ')}]`,\n );\n // Preserve cause chain for diagnostics (Node 16.9+ supports the\n // standard Error cause option).\n (err as Error & { cause?: unknown }).cause = cause;\n throw err;\n }\n\n // Look up the rewritten (port-substituted) version of the renamed\n // channel transition by name.\n const rewrittenInstanceChannel = rewrittenByName.get(instanceRenamedChannel.name);\n if (rewrittenInstanceChannel === undefined) {\n // Defensive: SubnetDef.builder validation guarantees the channel's\n // transition is a member of the renamed body.\n /* istanbul ignore next */\n throw new Error(\n `compose: channel '${channelName}' resolved to a transition ` +\n `'${instanceRenamedChannel.name}' that is not present in the renamed body. ` +\n `This indicates a SubnetDef invariant violation.`,\n );\n }\n\n // Build the merged transition (caller-wins identity per MOD-021).\n const merged = mergeTransitions(callerTrans, rewrittenInstanceChannel, callerTrans.name);\n\n // Step 2a: Remove the rewritten instance-side transition from the\n // working map (it merges away — only the merged result remains under\n // the caller's transition slot in the builder).\n rewrittenByName.delete(instanceRenamedChannel.name);\n\n // Step 2b: Replace the caller-side transition (if present) in this\n // builder's transition set with the merged result. If the caller did\n // not pre-add it, simply add the merged transition — the user's\n // intent to use callerTrans is captured via the binding itself.\n this._transitions.delete(callerTrans);\n this.transition(merged);\n }\n\n // Step 3: Add the surviving (un-merged) rewritten transitions to the\n // builder. transition() auto-collects places — internal (non-merged)\n // renamed places are added under their prefixed names; caller places\n // already in the builder's place set get deduped via Place name.\n for (const rewritten of rewrittenByName.values()) {\n this.transition(rewritten);\n }\n\n return this;\n }\n\n /**\n * Registers one or more {@link FusionSet} declarations on this builder, per\n * **MOD-060** (fusion set declaration) and **MOD-061** (fusion resolution\n * at build).\n *\n * Fusion is **orthogonal to subnet composition**: fuse sets are accumulated\n * here and applied during {@link build} **after** all `compose(...)` calls\n * have flattened subnet instances into the builder's transition set.\n * Registration order is irrelevant to semantics — `fuse(set)` BEFORE\n * `compose(...)` and `fuse(set)` AFTER `compose(...)` both apply at the\n * same point in the build pipeline.\n *\n * ## Validation\n *\n * Cross-set overlap (a place appearing in two fusion sets) is detected at\n * {@link build} and reported as an `Error` naming the offending place and\n * both sets.\n *\n * Two overloads are supported:\n *\n * 1. **Spread overload** — pass one or more pre-built {@link FusionSet}\n * values (e.g., from `FusionSet.of(...)` or\n * `FusionSet.builder(...).build()`).\n * 2. **Sugar overload** — pass a callback receiving a fresh\n * {@link FusionSetBuilder} named after the enclosing net; register\n * members via `b.member(place)`. Equivalent to\n * `FusionSet.builder('<netName>-fusion').<callback>.build()` followed by\n * `fuse(...)` on the result.\n */\n fuse(...sets: FusionSet[]): this;\n fuse(declarer: (b: FusionSetBuilder) => void): this;\n fuse(...args: [(b: FusionSetBuilder) => void] | FusionSet[]): this {\n if (args.length === 1 && typeof args[0] === 'function') {\n const declarer = args[0] as (b: FusionSetBuilder) => void;\n const fb = FusionSet.builder(this._name + '-fusion');\n declarer(fb);\n this._fusionSets.push(fb.build());\n return this;\n }\n for (const s of args as FusionSet[]) {\n if (s === undefined || s === null) {\n throw new Error('fuse: fusion set must not be null');\n }\n this._fusionSets.push(s);\n }\n return this;\n }\n\n /**\n * Builds the immutable {@link PetriNet}, applying fusion resolution (per\n * **MOD-061**) AFTER all transition/composition accumulation:\n *\n * 1. Detect overlapping fusion sets — a single place declared in two sets\n * is rejected with an `Error`.\n * 2. Build the `non-canonical → canonical` substitution map across all\n * sets, keyed by non-canonical place name (matching the rewriter's\n * Map<string, Place<unknown>> convention — TypeScript Place identity is\n * name-based per `runtime/compiled-net.ts`).\n * 3. Walk every transition through {@link applyFusion} to rewrite arc place\n * references; input arcs colliding on a canonical place merge per\n * [MOD-021] (additive where summable, rejected otherwise).\n * 4. Re-derive the place set from the rewritten transitions plus any\n * caller-declared standalone places, dropping non-canonical members.\n * Caller-declared standalone places that happen to be non-canonical\n * members are also dropped.\n *\n * If no fusion sets were registered, the build is the trivial\n * `new PetriNet(...)` — the fusion machinery has no per-build cost when\n * unused.\n *\n * @throws when two fusion sets share a place\n */\n build(): PetriNet {\n const membership = this.resolveSubnetMembership();\n if (this._fusionSets.length === 0) {\n return new PetriNet(PETRI_NET_KEY, this._name, this._places, this._transitions,\n membership);\n }\n return this.buildWithFusion(membership);\n }\n\n /**\n * @internal Resolves the per-compose contributions recorded by\n * `composeDirect` into the final node-name → subnet-name membership map per\n * **MOD-026**. A node contributed by exactly one subnet maps to that subnet;\n * a place contributed by two or more subnets is a shared rendezvous place\n * and is omitted (it renders top-level, outside any cluster). Returns an\n * empty map — the common case — when no subnet was composed directly.\n */\n private resolveSubnetMembership(): Map<string, string> {\n const resolved = new Map<string, string>();\n for (const [nodeName, owners] of this._subnetContributions) {\n if (owners.size === 1) {\n resolved.set(nodeName, owners.values().next().value as string);\n }\n }\n return resolved;\n }\n\n /**\n * @internal Drops membership entries for places removed by fusion: a\n * non-canonical fused member no longer exists in the net, so its\n * `node-name → subnet` entry would dangle. The surviving canonical place\n * keeps its own entry. Per **MOD-026**.\n */\n private static filterFusedMembership(\n membership: Map<string, string>,\n nonCanonicalNames: ReadonlySet<string>,\n ): Map<string, string> {\n if (membership.size === 0 || nonCanonicalNames.size === 0) {\n return membership;\n }\n const filtered = new Map<string, string>();\n for (const [key, value] of membership) {\n if (!nonCanonicalNames.has(key)) {\n filtered.set(key, value);\n }\n }\n return filtered;\n }\n\n /**\n * @internal Fusion-resolution pass per **MOD-061**. Split out from\n * {@link build} so the no-fusion fast path stays trivial.\n */\n private buildWithFusion(membership: Map<string, string>): PetriNet {\n // Step 1: detect overlap. The same place name MUST NOT appear in more\n // than one fusion set (TypeScript Place identity is name-based per\n // `runtime/compiled-net.ts`).\n const ownership = new Map<string, FusionSet>();\n for (const set of this._fusionSets) {\n for (const member of set.members) {\n const prior = ownership.get(member.name);\n if (prior !== undefined && prior !== set) {\n throw new Error(\n `Fusion overlap: place '${member.name}' appears in two fusion sets ` +\n `('${prior.name}' and '${set.name}'). A place may appear in at most ` +\n `one fusion set (MOD-060).`,\n );\n }\n ownership.set(member.name, set);\n }\n }\n\n // Step 2: build the non-canonical-name → canonical-place substitution\n // map. Single-member sets contribute nothing (no non-canonical members),\n // so the map is naturally empty for the degenerate case.\n const fusionMap = new Map<string, Place<unknown>>();\n const nonCanonicalNames = new Set<string>();\n for (const set of this._fusionSets) {\n const canonical = set.canonical;\n for (const nc of set.nonCanonical()) {\n fusionMap.set(nc.name, canonical);\n nonCanonicalNames.add(nc.name);\n }\n }\n\n // Step 3: rewrite every transition's arcs through the fusion map.\n // applyFusion always returns a fresh set; if fusionMap is empty (single-\n // member-only sets) the rewrite is structurally a no-op but still rebuilds\n // Transition records — no observable difference. Input-arc collisions on a\n // canonical place merge per MOD-021, naming the owning fusion set on\n // rejection.\n const rewrittenTransitions = applyFusion(this._transitions, fusionMap, (canonicalName) => {\n const owner = ownership.get(canonicalName);\n return `Fusion set '${owner !== undefined ? owner.name : canonicalName}'`;\n });\n\n // Step 4: re-derive the place set. Strategy: start from the current\n // place set, drop every non-canonical member (they are gone from the\n // net), then union in the places auto-discovered from the rewritten\n // transitions. This preserves caller-declared standalone places that are\n // unrelated to fusion, drops any standalone declarations of non-canonical\n // members, and ensures canonical places end up present even if a caller\n // never declared them standalone.\n const rebuiltPlaces = new Set<Place<any>>();\n for (const p of this._places) {\n if (!nonCanonicalNames.has(p.name)) {\n rebuiltPlaces.add(p);\n }\n }\n for (const t of rewrittenTransitions) {\n for (const spec of t.inputSpecs) rebuiltPlaces.add(spec.place);\n for (const p of t.outputPlaces()) rebuiltPlaces.add(p);\n for (const inh of t.inhibitors) rebuiltPlaces.add(inh.place);\n for (const r of t.reads) rebuiltPlaces.add(r.place);\n for (const r of t.resets) rebuiltPlaces.add(r.place);\n }\n\n return new PetriNet(PETRI_NET_KEY, this._name, rebuiltPlaces, rewrittenTransitions,\n PetriNetBuilder.filterFusedMembership(membership, nonCanonicalNames));\n }\n}\n\n/** Creates a new transition with a different action while preserving all arc specs. */\nfunction rebuildWithAction(t: Transition, action: TransitionAction): Transition {\n const builder = Transition.builder(t.name)\n .timing(t.timing)\n .priority(t.priority)\n .action(action);\n\n // MOD-031: carry the declared→actual place correspondence forward so an action\n // bound after instantiate/compose ([CORE-042]) still resolves its hardcoded\n // declared places. Empty for hand-written / directly-composed transitions.\n if (t.placeAlias.size > 0) {\n builder.placeAlias(t.placeAlias);\n }\n\n if (t.inputSpecs.length > 0) {\n builder.inputs(...t.inputSpecs);\n }\n if (t.outputSpec !== null) {\n builder.outputs(t.outputSpec);\n }\n\n for (const inh of t.inhibitors) {\n builder.inhibitor(inh.place);\n }\n for (const r of t.reads) {\n builder.read(r.place);\n }\n for (const r of t.resets) {\n builder.reset(r.place);\n }\n\n // NU-030: carry the ν-net join correlation forward. bindActions only attaches\n // an action — it does not rename places — so the matchSpec's input-place\n // references are still valid and it is carried as-is (no remap, unlike the\n // compose/rename rebuildWithName). Dropping it here would silently revert a\n // correlated join-by-id to a plain FIFO AND join at runtime.\n if (t.matchSpec !== null) {\n builder.match(t.matchSpec);\n }\n\n return builder.build();\n}\n","import type { PetriNet } from './petri-net.js';\nimport type { SubnetDef } from './subnet-def.js';\n\n/**\n * Discriminated sum-type abstraction over Petri nets, distinguishing **closed**\n * (runnable) nets from **open** (composable) subnet fragments per\n * `spec/11-modular-composition.md` requirement **MOD-002**.\n *\n * This abstraction is the bridge between the existing flat {@link PetriNet}\n * world and the modular composition extension. Code that wishes to accept\n * \"any net\" types its parameter as `Subnet`; code that needs a runnable net\n * continues to take {@link PetriNet} (or `Subnet` narrowed to `'closed'`);\n * code that needs an open fragment takes {@link SubnetDef} (or `Subnet`\n * narrowed to `'open'`). Misuse is rejected at compile time wherever\n * TypeScript's structural typing permits.\n *\n * Use the literal `kind` field for exhaustive pattern matching:\n *\n * ```ts\n * function classify(s: Subnet): string {\n * switch (s.kind) {\n * case 'closed': return `closed:${s.net.name}`;\n * case 'open': return `open:${s.def.name}`;\n * }\n * }\n * ```\n */\nexport type Subnet =\n | { readonly kind: 'closed'; readonly net: PetriNet }\n | { readonly kind: 'open'; readonly def: SubnetDef<unknown> };\n\n/** Wraps a {@link PetriNet} as a closed (runnable) {@link Subnet}. */\nexport function closedSubnet(net: PetriNet): Subnet {\n return { kind: 'closed', net };\n}\n\n/** Wraps a {@link SubnetDef} as an open (composable) {@link Subnet}. */\nexport function openSubnet(def: SubnetDef<unknown>): Subnet {\n return { kind: 'open', def };\n}\n","/**\n * @module marking\n *\n * Mutable token state (marking) of a running Petri net.\n *\n * Tokens per place are stored in FIFO arrays (push to end, shift from front).\n * Not thread-safe — all mutation occurs from the single-threaded orchestrator.\n *\n * For typical nets (≤10 tokens per place), Array.shift() is faster than a deque\n * due to cache locality. Only optimize if profiling shows a bottleneck.\n */\nimport type { Place } from '../core/place.js';\nimport type { Token } from '../core/token.js';\n\nconst EMPTY_TOKENS: readonly Token<any>[] = Object.freeze([]);\n\n/**\n * A place reference plus an optional per-token predicate.\n *\n * Used by the ν-net join path (NU-020/NU-021) to select the tokens whose\n * projected correlation name equals the chosen binding. This is *not* an input\n * guard (IO-006, removed) — input specifications are purely structural; the\n * predicate here is always derived from name correlation.\n */\nexport interface PredicateSpec<T = any> {\n readonly place: Place<T>;\n readonly predicate?: (value: T) => boolean;\n}\n\n/**\n * Mutable marking (token state) of a Petri Net during execution.\n *\n * Tokens in each place are maintained in FIFO order (array: push to end, shift from front).\n * Not thread-safe — all access must be from the orchestrator.\n */\nexport class Marking {\n /** Place name -> FIFO queue of tokens. */\n private readonly tokens = new Map<string, Token<any>[]>();\n /** Place name -> Place reference (for inspection). */\n private readonly placeRefs = new Map<string, Place<any>>();\n\n static empty(): Marking {\n return new Marking();\n }\n\n static from(initial: Map<Place<any>, Token<any>[]>): Marking {\n const m = new Marking();\n for (const [place, tokens] of initial) {\n m.placeRefs.set(place.name, place);\n m.tokens.set(place.name, [...tokens]);\n }\n return m;\n }\n\n // ======================== Token Addition ========================\n\n addToken<T>(place: Place<T>, token: Token<T>): void {\n this.placeRefs.set(place.name, place);\n const queue = this.tokens.get(place.name);\n if (queue) {\n queue.push(token);\n } else {\n this.tokens.set(place.name, [token]);\n }\n }\n\n // ======================== Token Removal ========================\n\n /** Removes and returns the oldest token. Returns null if empty. */\n removeFirst<T>(place: Place<T>): Token<T> | null {\n const queue = this.tokens.get(place.name);\n if (!queue || queue.length === 0) return null;\n return queue.shift() as Token<T>;\n }\n\n /** Removes and returns all tokens from a place. */\n removeAll<T>(place: Place<T>): Token<T>[] {\n const queue = this.tokens.get(place.name);\n if (!queue || queue.length === 0) return [];\n const result = [...queue] as Token<T>[];\n queue.length = 0;\n return result;\n }\n\n /**\n * Removes and returns the first token whose value satisfies the predicate.\n *\n * Performs a linear scan of the place's FIFO queue. If no predicate is\n * provided, behaves like `removeFirst()`. Otherwise skips non-matching\n * tokens and splices the first match out of the queue (O(n) worst case).\n */\n removeFirstMatching(spec: PredicateSpec): Token<any> | null {\n const queue = this.tokens.get(spec.place.name);\n if (!queue || queue.length === 0) return null;\n if (!spec.predicate) {\n return queue.shift()!;\n }\n for (let i = 0; i < queue.length; i++) {\n const token = queue[i]!;\n if (spec.predicate(token.value)) {\n // Head removal (the common ν-net case — the matched token is the oldest,\n // hence at the front with distinct timestamps) uses the V8-optimized\n // shift() rather than an O(n) splice, keeping a draining join linear.\n if (i === 0) queue.shift();\n else queue.splice(i, 1);\n return token;\n }\n }\n return null;\n }\n\n // ======================== Token Inspection ========================\n\n /** Check if any token satisfies the predicate. */\n hasMatchingToken(spec: PredicateSpec): boolean {\n const queue = this.tokens.get(spec.place.name);\n if (!queue || queue.length === 0) return false;\n if (!spec.predicate) return true;\n return queue.some(t => spec.predicate!(t.value));\n }\n\n /**\n * Counts tokens in a place whose values satisfy the predicate.\n *\n * If no predicate is provided, returns the total token count (O(1)).\n * With a predicate, performs a linear scan over all tokens (O(n)).\n * Used by the executor to size a ν-net correlated `all`/`at-least` consume.\n */\n countMatching(spec: PredicateSpec): number {\n const queue = this.tokens.get(spec.place.name);\n if (!queue || queue.length === 0) return 0;\n if (!spec.predicate) return queue.length;\n let count = 0;\n for (const t of queue) {\n if (spec.predicate(t.value)) count++;\n }\n return count;\n }\n\n /**\n * Returns tokens in a place. **Returns a live reference** to the internal\n * array — callers must not mutate it. Copy with `[...peekTokens(p)]` if\n * mutation or snapshot semantics are needed.\n */\n peekTokens<T>(place: Place<T>): readonly Token<T>[] {\n return (this.tokens.get(place.name) ?? EMPTY_TOKENS) as readonly Token<T>[];\n }\n\n /** Returns the oldest token without removing it. */\n peekFirst<T>(place: Place<T>): Token<T> | null {\n const queue = this.tokens.get(place.name);\n return queue && queue.length > 0 ? queue[0] as Token<T> : null;\n }\n\n /** Checks if a place has any tokens. */\n hasTokens(place: Place<any>): boolean {\n const queue = this.tokens.get(place.name);\n return queue !== undefined && queue.length > 0;\n }\n\n /** Returns the number of tokens in a place. */\n tokenCount(place: Place<any>): number {\n const queue = this.tokens.get(place.name);\n return queue ? queue.length : 0;\n }\n\n // ======================== Debugging ========================\n\n toString(): string {\n const parts: string[] = [];\n for (const [name, queue] of this.tokens) {\n if (queue.length > 0) {\n parts.push(`${name}: ${queue.length}`);\n }\n }\n return `Marking{${parts.join(', ')}}`;\n }\n}\n","/**\n * @module compiled-net\n *\n * Integer-indexed, precomputed representation of a PetriNet for bitmap-based execution.\n *\n * **Precomputation strategy**: At compile time, all places and transitions are assigned\n * stable integer IDs. Input/inhibitor arcs are converted to Uint32Array bitmasks (one per\n * transition), enabling O(W) enablement checks via bitwise AND where W = ceil(numPlaces/32).\n *\n * **Why bitmaps**: JS bitwise operators work natively on 32-bit integers. Using Uint32Array\n * with 32-bit words (WORD_SHIFT=5) avoids BigInt overhead while keeping enablement checks\n * branch-free and cache-friendly. For a typical 50-place net, W=2 words per mask.\n *\n * **Reverse index**: A place-to-transitions mapping enables the dirty set pattern —\n * when a place's marking changes, only affected transitions are re-evaluated.\n */\nimport type { PetriNet } from '../core/petri-net.js';\nimport type { Place } from '../core/place.js';\nimport type { Transition } from '../core/transition.js';\nimport { requiredCount } from '../core/in.js';\nimport { allPlaces } from '../core/out.js';\nimport { requireOutputProducingActions } from '../core/internal/output-action-check.js';\n\n/** 32-bit words for JS bitwise ops. */\nexport const WORD_SHIFT = 5;\nexport const BIT_MASK = 31;\n\nexport interface CardinalityCheck {\n readonly placeIds: readonly number[];\n readonly requiredCounts: readonly number[];\n}\n\n/**\n * Integer-indexed, precomputed representation of a PetriNet for bitmap-based execution.\n *\n * Uses Uint32Array masks with 32-bit words (JS bitwise ops work on 32-bit ints natively).\n */\nexport class CompiledNet {\n readonly net: PetriNet;\n readonly placeCount: number;\n readonly transitionCount: number;\n readonly wordCount: number;\n\n // ID mappings\n private readonly _placesById: Place<any>[];\n private readonly _transitionsById: Transition[];\n private readonly _placeIndex: Map<string, number>;\n private readonly _transitionIndex: Map<Transition, number>;\n\n // Precomputed masks per transition\n private readonly _needsMask: Uint32Array[];\n private readonly _inhibitorMask: Uint32Array[];\n\n // Reverse index: place -> affected transition IDs\n private readonly _placeToTransitions: number[][];\n\n // Consumption place IDs per transition (input + reset places)\n private readonly _consumptionPlaceIds: number[][];\n\n // Cardinality flags\n private readonly _cardinalityChecks: (CardinalityCheck | null)[];\n // ν-net join flag: the transition carries a MatchSpec (NU-020). Precomputed\n // so the hot enablement loop can skip the match check on non-ν transitions\n // (zero-cost gating).\n private readonly _hasMatch: boolean[];\n\n private constructor(net: PetriNet) {\n this.net = net;\n\n // CORE-043: reconcile declared structure against bound behaviour before anything else.\n requireOutputProducingActions(net);\n\n // Collect all places\n const allPlacesSet = new Map<string, Place<any>>();\n for (const t of net.transitions) {\n for (const spec of t.inputSpecs) allPlacesSet.set(spec.place.name, spec.place);\n for (const r of t.reads) allPlacesSet.set(r.place.name, r.place);\n for (const inh of t.inhibitors) allPlacesSet.set(inh.place.name, inh.place);\n for (const rst of t.resets) allPlacesSet.set(rst.place.name, rst.place);\n if (t.outputSpec !== null) {\n for (const p of allPlaces(t.outputSpec)) allPlacesSet.set(p.name, p);\n }\n }\n for (const p of net.places) allPlacesSet.set(p.name, p);\n\n this.placeCount = allPlacesSet.size;\n this.wordCount = (this.placeCount + BIT_MASK) >>> WORD_SHIFT;\n\n // Assign place IDs\n this._placesById = [...allPlacesSet.values()];\n this._placeIndex = new Map();\n for (let i = 0; i < this._placesById.length; i++) {\n this._placeIndex.set(this._placesById[i]!.name, i);\n }\n\n // Assign transition IDs\n this._transitionsById = [...net.transitions];\n this.transitionCount = this._transitionsById.length;\n this._transitionIndex = new Map();\n for (let i = 0; i < this._transitionsById.length; i++) {\n this._transitionIndex.set(this._transitionsById[i]!, i);\n }\n\n // Precompute masks\n this._needsMask = new Array(this.transitionCount);\n this._inhibitorMask = new Array(this.transitionCount);\n this._consumptionPlaceIds = new Array(this.transitionCount);\n this._cardinalityChecks = new Array(this.transitionCount).fill(null);\n this._hasMatch = new Array(this.transitionCount).fill(false);\n\n const placeToTransitionsList: number[][] = new Array(this.placeCount);\n for (let i = 0; i < this.placeCount; i++) {\n placeToTransitionsList[i] = [];\n }\n\n for (let tid = 0; tid < this.transitionCount; tid++) {\n const t = this._transitionsById[tid]!;\n this._hasMatch[tid] = t.matchSpec !== null;\n const needs = new Uint32Array(this.wordCount);\n const inhibitors = new Uint32Array(this.wordCount);\n\n let needsCardinality = false;\n\n // Input specs\n // CORE-030: the Transition builder stays permissive; the duplicate-input\n // rejection lives here so both executors share it.\n const seenInputPlaces = new Set<string>();\n for (const inSpec of t.inputSpecs) {\n if (seenInputPlaces.has(inSpec.place.name)) {\n throw new Error(\n `Transition '${t.name}' declares two input arcs on place '${inSpec.place.name}'. `\n + 'Duplicate input places have no coherent consumption semantics and are rejected '\n + 'at compile time (CORE-030). Use a single arc with exactly(n) / atLeast(n) instead.'\n );\n }\n seenInputPlaces.add(inSpec.place.name);\n const pid = this._placeIndex.get(inSpec.place.name)!;\n setBit(needs, pid);\n placeToTransitionsList[pid]!.push(tid);\n\n if (inSpec.type !== 'one') {\n needsCardinality = true;\n }\n }\n\n // Build cardinality check if needed\n if (needsCardinality) {\n const pids: number[] = [];\n const reqs: number[] = [];\n for (const inSpec of t.inputSpecs) {\n pids.push(this._placeIndex.get(inSpec.place.name)!);\n reqs.push(requiredCount(inSpec));\n }\n this._cardinalityChecks[tid] = { placeIds: pids, requiredCounts: reqs };\n }\n\n // Read arcs\n for (const arc of t.reads) {\n const pid = this._placeIndex.get(arc.place.name)!;\n setBit(needs, pid);\n placeToTransitionsList[pid]!.push(tid);\n }\n\n // Inhibitor arcs\n for (const arc of t.inhibitors) {\n const pid = this._placeIndex.get(arc.place.name)!;\n setBit(inhibitors, pid);\n placeToTransitionsList[pid]!.push(tid);\n }\n\n // Reset arcs (add to affected transitions)\n for (const arc of t.resets) {\n const pid = this._placeIndex.get(arc.place.name)!;\n placeToTransitionsList[pid]!.push(tid);\n }\n\n // Consumption place IDs (input + reset, deduplicated)\n const consumptionSet = new Set<number>();\n for (const spec of t.inputSpecs) consumptionSet.add(this._placeIndex.get(spec.place.name)!);\n for (const arc of t.resets) consumptionSet.add(this._placeIndex.get(arc.place.name)!);\n this._consumptionPlaceIds[tid] = [...consumptionSet];\n\n this._needsMask[tid] = needs;\n this._inhibitorMask[tid] = inhibitors;\n }\n\n // Build reverse index: deduplicate transition IDs per place\n this._placeToTransitions = new Array(this.placeCount);\n for (let pid = 0; pid < this.placeCount; pid++) {\n this._placeToTransitions[pid] = [...new Set(placeToTransitionsList[pid]!)];\n }\n }\n\n static compile(net: PetriNet): CompiledNet {\n return new CompiledNet(net);\n }\n\n // ==================== Accessors ====================\n\n place(pid: number): Place<any> { return this._placesById[pid]!; }\n transition(tid: number): Transition { return this._transitionsById[tid]!; }\n\n placeId(place: Place<any>): number {\n const id = this._placeIndex.get(place.name);\n if (id === undefined) throw new Error(`Unknown place: ${place.name}`);\n return id;\n }\n\n /**\n * Non-throwing variant of {@link placeId}: `undefined` when the compiled net\n * does not know the place. Lets callers retain tokens on undeclared places\n * (CORE-072) instead of rejecting or dropping them.\n */\n tryPlaceId(place: Place<any>): number | undefined {\n return this._placeIndex.get(place.name);\n }\n\n transitionId(t: Transition): number {\n const id = this._transitionIndex.get(t);\n if (id === undefined) throw new Error(`Unknown transition: ${t.name}`);\n return id;\n }\n\n affectedTransitions(pid: number): readonly number[] {\n return this._placeToTransitions[pid]!;\n }\n\n consumptionPlaceIds(tid: number): readonly number[] {\n return this._consumptionPlaceIds[tid]!;\n }\n\n cardinalityCheck(tid: number): CardinalityCheck | null {\n return this._cardinalityChecks[tid]!;\n }\n\n hasMatch(tid: number): boolean {\n return this._hasMatch[tid]!;\n }\n\n // ==================== Enablement Check ====================\n\n /**\n * Two-phase bitmap enablement check for a transition:\n * 1. **Presence check**: verifies all required places (inputs + reads) have tokens\n * via `containsAll(snapshot, needsMask)`.\n * 2. **Inhibitor check**: verifies no inhibitor places have tokens\n * via `!intersects(snapshot, inhibitorMask)`.\n *\n * This is a necessary but not sufficient condition — cardinality and ν-net match\n * checks are performed separately by the executor for transitions that pass this\n * fast path.\n */\n canEnableBitmap(tid: number, markingSnapshot: Uint32Array): boolean {\n // All needed places present?\n if (!containsAll(markingSnapshot, this._needsMask[tid]!)) return false;\n // No inhibitors active?\n if (intersects(markingSnapshot, this._inhibitorMask[tid]!)) return false;\n return true;\n }\n}\n\n// ==================== Bitmap Helpers ====================\n\nexport function setBit(arr: Uint32Array, bit: number): void {\n arr[bit >>> WORD_SHIFT]! |= (1 << (bit & BIT_MASK));\n}\n\nexport function clearBit(arr: Uint32Array, bit: number): void {\n arr[bit >>> WORD_SHIFT]! &= ~(1 << (bit & BIT_MASK));\n}\n\nexport function testBit(arr: Uint32Array, bit: number): boolean {\n return (arr[bit >>> WORD_SHIFT]! & (1 << (bit & BIT_MASK))) !== 0;\n}\n\n/** Checks if all bits in mask are set in snapshot. */\nexport function containsAll(snapshot: Uint32Array, mask: Uint32Array): boolean {\n for (let i = 0; i < mask.length; i++) {\n const m = mask[i]!;\n if (m === 0) continue;\n const s = i < snapshot.length ? snapshot[i]! : 0;\n // Use >>> 0 to coerce the bitwise AND result to unsigned. Without this,\n // when bit 31 (the sign bit) is set, (s & m) returns a negative signed\n // int32 while m (from Uint32Array) is unsigned, causing a false mismatch.\n if (((s & m) >>> 0) !== m) return false;\n }\n return true;\n}\n\n/** Checks if any bit in mask is set in snapshot. */\nexport function intersects(snapshot: Uint32Array, mask: Uint32Array): boolean {\n for (let i = 0; i < mask.length; i++) {\n const m = mask[i]!;\n if (m === 0) continue;\n if (i < snapshot.length && (snapshot[i]! & m) !== 0) return true;\n }\n return false;\n}\n\n","import type { NetEvent } from './net-event.js';\nimport { eventTransitionName, isFailureEvent } from './net-event.js';\n\n/**\n * Storage for events emitted during Petri net execution.\n */\nexport interface EventStore {\n /** Appends an event to the store. */\n append(event: NetEvent): void;\n\n /** Returns all events in chronological order. */\n events(): readonly NetEvent[];\n\n /** Whether this store is enabled (false = skip event creation). */\n isEnabled(): boolean;\n\n /** Number of events captured. */\n size(): number;\n\n /** Whether no events have been captured. */\n isEmpty(): boolean;\n}\n\n// ==================== Query Helpers ====================\n\n/** Returns events matching a predicate. */\nexport function filterEvents(store: EventStore, predicate: (e: NetEvent) => boolean): NetEvent[] {\n return store.events().filter(predicate);\n}\n\n/** Returns events of a specific type. */\nexport function eventsOfType<T extends NetEvent['type']>(\n store: EventStore,\n type: T,\n): Extract<NetEvent, { type: T }>[] {\n return store.events().filter(e => e.type === type) as Extract<NetEvent, { type: T }>[];\n}\n\n/** Returns all events for a specific transition. */\nexport function transitionEvents(store: EventStore, transitionName: string): NetEvent[] {\n return store.events().filter(e => eventTransitionName(e) === transitionName);\n}\n\n/** Returns all failure events. */\nexport function failures(store: EventStore): NetEvent[] {\n return store.events().filter(isFailureEvent);\n}\n\n// ==================== InMemoryEventStore ====================\n\nexport class InMemoryEventStore implements EventStore {\n private readonly _events: NetEvent[] = [];\n\n append(event: NetEvent): void {\n this._events.push(event);\n }\n\n events(): readonly NetEvent[] {\n return this._events;\n }\n\n isEnabled(): boolean {\n return true;\n }\n\n size(): number {\n return this._events.length;\n }\n\n isEmpty(): boolean {\n return this._events.length === 0;\n }\n\n /** Clears all stored events. */\n clear(): void {\n this._events.length = 0;\n }\n}\n\n// ==================== NoopEventStore ====================\n\nconst EMPTY: readonly NetEvent[] = Object.freeze([]);\n\nclass NoopEventStoreImpl implements EventStore {\n append(_event: NetEvent): void {\n // No-op\n }\n\n events(): readonly NetEvent[] {\n return EMPTY;\n }\n\n isEnabled(): boolean {\n return false;\n }\n\n size(): number {\n return 0;\n }\n\n isEmpty(): boolean {\n return true;\n }\n}\n\nconst NOOP_INSTANCE = new NoopEventStoreImpl();\n\n/** Returns a no-op event store that discards all events. */\nexport function noopEventStore(): EventStore {\n return NOOP_INSTANCE;\n}\n\n/** Creates a new in-memory event store. */\nexport function inMemoryEventStore(): InMemoryEventStore {\n return new InMemoryEventStore();\n}\n","/**\n * @module match-engine\n *\n * ν-net binding selection — the canonical name-correlation algorithm shared by\n * both executor backends (spec NU-020).\n *\n * A transition carrying a {@link import('../core/match-spec.js').MatchSpec} is\n * enabled only when there is a single name present in every correlated input\n * with its required token count. The two executors differ only in how they read\n * tokens (`Marking` FIFO queues vs the precompiled per-place arrays); the\n * *selection* — which name satisfies the join, and the deterministic tie-break —\n * lives here so it is identical across backends and matches the Rust/Java ports.\n */\nimport type { Token } from '../core/token.js';\nimport type { Place } from '../core/place.js';\nimport type { Transition } from '../core/transition.js';\nimport type { NameId } from '../core/name.js';\nimport type { KeyFn } from '../core/match-spec.js';\n\n/** Per-correlated-input statistic for one name: count + oldest timestamp (ms). */\nexport interface NameStat {\n count: number;\n minCreatedAt: number;\n}\n\n/**\n * Selects the satisfying correlation name across all correlated inputs, or\n * `null` when no single name is present in every input with at least its\n * required count.\n *\n * Determinism (NU-020): among satisfying names, pick the one whose oldest\n * matched token (minimum `createdAt` across the correlated inputs) is earliest;\n * break remaining ties by {@link NameId} order. Byte-identical to the Rust\n * `select_match_name` and the Java `selectMatchName`.\n *\n * The `NameId` tie-break uses JS string `<` (UTF-16 code-unit order). This is\n * byte-identical to the Java (`String.compareTo`) and Rust (UTF-8 code-point)\n * ports for ASCII/BMP names — which covers every executor-minted name\n * (`\"{transition}#{n}\"`). For supplementary-plane code points in user-supplied\n * correlation keys, Rust's UTF-8 order can differ from this UTF-16 order; NU-001\n * requires only per-implementation consistency, which holds.\n */\nexport function selectMatchName(\n perPlace: ReadonlyArray<Map<NameId, NameStat>>,\n requireds: readonly number[],\n): NameId | null {\n if (perPlace.length === 0) return null;\n // Seed candidate names from the smallest index; result is seed-independent.\n let seed = 0;\n for (let i = 1; i < perPlace.length; i++) {\n if (perPlace[i]!.size < perPlace[seed]!.size) seed = i;\n }\n\n let bestName: NameId | null = null;\n let bestTs = 0;\n for (const [name, stat] of perPlace[seed]!) {\n if (stat.count < requireds[seed]!) continue;\n let repTs = Number.MAX_SAFE_INTEGER;\n let satisfied = true;\n for (let j = 0; j < perPlace.length; j++) {\n const s = perPlace[j]!.get(name);\n if (s === undefined || s.count < requireds[j]!) {\n satisfied = false;\n break;\n }\n repTs = Math.min(repTs, s.minCreatedAt);\n }\n if (!satisfied) continue;\n const take = bestName === null || repTs < bestTs || (repTs === bestTs && name < bestName);\n if (take) {\n bestName = name;\n bestTs = repTs;\n }\n }\n return bestName;\n}\n\n/**\n * Builds a `name → {count, minCreatedAt}` index over the given tokens. Tokens\n * whose projected name is `undefined`/`null` are skipped — they carry no\n * correlation name and can never participate in a match (NU-021).\n */\nexport function buildNameIndex(\n tokens: readonly Token<any>[],\n key: KeyFn,\n): Map<NameId, NameStat> {\n const index = new Map<NameId, NameStat>();\n for (const token of tokens) {\n const name = key(token.value);\n if (name === undefined || name === null) continue;\n const ts = token.createdAt;\n const prev = index.get(name);\n if (prev) {\n prev.count++;\n if (ts < prev.minCreatedAt) prev.minCreatedAt = ts;\n } else {\n index.set(name, { count: 1, minCreatedAt: ts });\n }\n }\n return index;\n}\n\n/**\n * Required token count for `placeName` from the transition's input spec\n * (1 for one/all, n for exactly(n), m for at-least(m)).\n */\nexport function requiredFor(t: Transition, placeName: string): number {\n for (const inSpec of t.inputSpecs) {\n if (inSpec.place.name === placeName) {\n if (inSpec.type === 'exactly') return inSpec.count;\n if (inSpec.type === 'at-least') return inSpec.minimum;\n return 1;\n }\n }\n return 1;\n}\n\n/**\n * Finds the correlation name satisfying `t`'s `MatchSpec`, or `null` if the join\n * is not enabled (NU-020). `getTokens` abstracts the token source so both\n * executors share this code (Marking queues vs precompiled per-place arrays).\n */\nexport function findBinding(\n t: Transition,\n getTokens: (place: Place<any>) => readonly Token<any>[],\n): NameId | null {\n const ms = t.matchSpec;\n if (!ms) return null;\n const perPlace: Map<NameId, NameStat>[] = [];\n const requireds: number[] = [];\n for (const k of ms.keys) {\n perPlace.push(buildNameIndex(getTokens(k.place), k.key));\n requireds.push(requiredFor(t, k.place.name));\n }\n return selectMatchName(perPlace, requireds);\n}\n\n// ==================== Incremental matcher (NU-020 performance) ====================\n//\n// `selectMatchName` rebuilds a full name index over every token on each call, so\n// draining N ready correlation groups costs O(N²). `IncrementalMatcher` maintains\n// the per-input name index (a FIFO min-queue of timestamps per name) plus a\n// lazy-deletion min-heap of ready names ordered by the same `(oldest_ts, name)`\n// key, so `add`/`consume` are O(log n) and `best()` is an O(1) read. Used only\n// for `one`/`exactly` correlated inputs that are consumed by no other transition\n// (so the cache can't desync); otherwise the executor falls back to\n// `selectMatchName`. Ported byte-identically from the Rust `IncrementalMatcher`.\n\n/**\n * FIFO queue of timestamps with O(1)-amortized min-query (two-stack method).\n * Mirrors the executor's FIFO-within-name removal (`popFront` drops the\n * earliest-inserted token) while answering \"oldest remaining timestamp\". A plain\n * min-heap would diverge from FIFO order when timestamps are not insertion-ordered.\n */\nclass MinQueue {\n private readonly inStack: number[] = [];\n private readonly inMin: number[] = [];\n private readonly outStack: number[] = [];\n private readonly outMin: number[] = [];\n\n get size(): number {\n return this.inStack.length + this.outStack.length;\n }\n\n pushBack(v: number): void {\n this.inStack.push(v);\n const top = this.inMin.length;\n this.inMin.push(top ? Math.min(this.inMin[top - 1]!, v) : v);\n }\n\n popFront(): void {\n if (this.outStack.length === 0) {\n while (this.inStack.length) {\n const v = this.inStack.pop()!;\n this.inMin.pop();\n this.outStack.push(v);\n const top = this.outMin.length;\n this.outMin.push(top ? Math.min(this.outMin[top - 1]!, v) : v);\n }\n }\n this.outStack.pop();\n this.outMin.pop();\n }\n\n min(): number {\n const a = this.inMin.length ? this.inMin[this.inMin.length - 1]! : Infinity;\n const b = this.outMin.length ? this.outMin[this.outMin.length - 1]! : Infinity;\n return a < b ? a : b;\n }\n}\n\ninterface ReadyEntry {\n ts: number;\n name: NameId;\n}\n\n/** Binary min-heap of ready names keyed by `(ts, name)` — the `select_match_name` order. */\nclass ReadyHeap {\n private readonly a: ReadyEntry[] = [];\n\n get size(): number {\n return this.a.length;\n }\n\n peek(): ReadyEntry | undefined {\n return this.a[0];\n }\n\n private less(x: ReadyEntry, y: ReadyEntry): boolean {\n return x.ts < y.ts || (x.ts === y.ts && x.name < y.name);\n }\n\n push(e: ReadyEntry): void {\n const a = this.a;\n a.push(e);\n let i = a.length - 1;\n while (i > 0) {\n const p = (i - 1) >> 1;\n if (this.less(a[i]!, a[p]!)) {\n const tmp = a[i]!;\n a[i] = a[p]!;\n a[p] = tmp;\n i = p;\n } else break;\n }\n }\n\n pop(): void {\n const a = this.a;\n const last = a.pop()!;\n if (a.length === 0) return;\n a[0] = last;\n let i = 0;\n const n = a.length;\n for (;;) {\n const l = 2 * i + 1;\n const r = 2 * i + 2;\n let m = i;\n if (l < n && this.less(a[l]!, a[m]!)) m = l;\n if (r < n && this.less(a[r]!, a[m]!)) m = r;\n if (m === i) break;\n const tmp = a[i]!;\n a[i] = a[m]!;\n a[m] = tmp;\n i = m;\n }\n }\n}\n\n/**\n * Incremental equivalent of {@link selectMatchName} for `one`/`exactly`\n * correlated inputs (fixed consume count). {@link best} is an O(1) read and, for\n * any sequence of `add`/`consume`, returns exactly the name `selectMatchName`\n * would — verified by `incremental-matcher.test.ts`.\n *\n * While ready names are pushed in non-decreasing `(rep_ts, name)` order — the\n * canonical fork/join (siblings carry the fork's monotonic timestamp) or any\n * time-ordered seed — a plain FIFO (index-based deque, never `shift()`) is a\n * valid min-PQ, so `add`/`consume` are amortized O(1). The first out-of-order\n * push migrates the deque into the lazy-deletion {@link ReadyHeap} (`heaped`),\n * thereafter O(log n) — the proven fallback. The fast path is re-entered whenever\n * the structure fully empties.\n */\nexport class IncrementalMatcher {\n private readonly ts: Array<Map<NameId, MinQueue>>;\n /** Monotonic fast path: ascending `(rep_ts, name)`; `fifo[fifoHead]` (after\n * `cleanTop`) is the min. Active while `!heaped`. Advance `fifoHead` instead of\n * `shift()` (O(1)); reset when the head catches the length. */\n private readonly fifo: ReadyEntry[] = [];\n private fifoHead = 0;\n /** Largest entry appended to `fifo` in the current monotonic run. */\n private maxPushed: ReadyEntry | null = null;\n /** Once an out-of-order push migrates `fifo` into `heap`. */\n private heaped = false;\n private readonly heap = new ReadyHeap();\n private readonly ready = new Map<NameId, number>();\n\n constructor(private readonly requireds: readonly number[]) {\n this.ts = requireds.map(() => new Map<NameId, MinQueue>());\n }\n\n /** Add one token carrying `name` at `createdAt` to input `i`. */\n add(i: number, name: NameId, createdAt: number): void {\n let q = this.ts[i]!.get(name);\n if (!q) {\n q = new MinQueue();\n this.ts[i]!.set(name, q);\n }\n q.pushBack(createdAt);\n this.refresh(name);\n this.cleanTop();\n }\n\n /** Remove the `required` earliest-inserted tokens of `name` from every input (NU-020). */\n consume(name: NameId): void {\n for (let i = 0; i < this.requireds.length; i++) {\n const q = this.ts[i]!.get(name);\n if (q) {\n for (let r = 0; r < this.requireds[i]!; r++) q.popFront();\n if (q.size === 0) this.ts[i]!.delete(name);\n }\n }\n this.refresh(name);\n this.cleanTop();\n }\n\n /** The name `selectMatchName` would pick, or `null`. O(1) read. */\n best(): NameId | null {\n if (this.heaped) {\n const top = this.heap.peek();\n return top ? top.name : null;\n }\n return this.fifoHead < this.fifo.length ? this.fifo[this.fifoHead]!.name : null;\n }\n\n /**\n * Route a ready name's `(rep, name)` to the active structure: append to the\n * FIFO in O(1) while pushes stay non-decreasing; on the first inversion,\n * migrate the FIFO into the heap and stay heap-backed.\n */\n private pushReady(rep: number, name: NameId): void {\n const entry: ReadyEntry = { ts: rep, name };\n if (this.heaped) {\n this.heap.push(entry);\n return;\n }\n const max = this.maxPushed;\n const monotonic = max === null || rep > max.ts || (rep === max.ts && name >= max.name);\n if (monotonic) {\n this.maxPushed = entry;\n this.fifo.push(entry);\n } else {\n this.heaped = true;\n for (let i = this.fifoHead; i < this.fifo.length; i++) this.heap.push(this.fifo[i]!);\n this.fifo.length = 0;\n this.fifoHead = 0;\n this.heap.push(entry);\n }\n }\n\n private repTs(name: NameId): number | null {\n let rep = Infinity;\n for (let i = 0; i < this.requireds.length; i++) {\n const q = this.ts[i]!.get(name);\n if (!q || q.size < this.requireds[i]!) return null;\n const m = q.min();\n if (m < rep) rep = m;\n }\n return rep;\n }\n\n private refresh(name: NameId): void {\n const rep = this.repTs(name);\n if (rep !== null) {\n if (this.ready.get(name) !== rep) {\n this.ready.set(name, rep);\n this.pushReady(rep, name);\n }\n } else {\n this.ready.delete(name);\n }\n }\n\n private cleanTop(): void {\n if (this.heaped) {\n for (;;) {\n const top = this.heap.peek();\n if (top && this.ready.get(top.name) !== top.ts) this.heap.pop();\n else break;\n }\n if (this.heap.size === 0) {\n this.heaped = false;\n this.maxPushed = null;\n }\n } else {\n while (this.fifoHead < this.fifo.length) {\n const top = this.fifo[this.fifoHead]!;\n if (this.ready.get(top.name) !== top.ts) this.fifoHead++;\n else break;\n }\n if (this.fifoHead >= this.fifo.length) {\n // fully drained: reset the backing array + start a fresh monotonic run\n this.fifo.length = 0;\n this.fifoHead = 0;\n this.maxPushed = null;\n }\n }\n }\n\n /** Test-only: has the matcher fallen back from the FIFO fast path to the heap? */\n isHeaped(): boolean {\n return this.heaped;\n }\n}\n","/**\n * Error thrown when a transition's output doesn't satisfy its declared Out spec.\n */\nexport class OutViolationError extends Error {\n constructor(message: string) {\n super(message);\n this.name = 'OutViolationError';\n }\n}\n","/**\n * @module executor-support\n *\n * Output validation and timeout production for the Petri net executor.\n *\n * **Output validation algorithm**: Recursively walks the declared Out spec tree,\n * checking that the action's produced tokens match the structure:\n * - Place/ForwardInput: place must be in the produced set\n * - AND: all children must be satisfied (conjunction)\n * - XOR: exactly 1 child must be satisfied (throws OutViolationError for 0 or 2+)\n * - Timeout: delegates to child spec\n *\n * Returns the set of \"claimed\" place names on success, or null if unsatisfied.\n *\n * **Timeout production**: When an action exceeds its timeout, produces default\n * tokens to the timeout branch's output places, enabling the net to continue.\n */\nimport type { Out } from '../core/out.js';\nimport type { Transition } from '../core/transition.js';\nimport type { TransitionContext } from '../core/transition-context.js';\nimport { OutViolationError } from './out-violation-error.js';\n\n/**\n * Invokes a transition action, converting a synchronous throw or a non-Promise\n * return into a rejected promise.\n *\n * Actions are invoked inline on the orchestrator loop, so an action that throws\n * before returning its promise (an undeclared-place access, a bad closure) would\n * otherwise unwind out of the firing loop and take the whole executor with it.\n * Routing it through a rejected promise makes it flow the same contained path as an\n * asynchronously-reported failure. A `null`/non-thenable return (a mis-typed action\n * that forgot `async`) is likewise rejected rather than silently treated as complete.\n */\nexport function executeAction(t: Transition, context: TransitionContext): Promise<void> {\n try {\n const stage = t.action(context) as unknown;\n if (stage == null || typeof (stage as { then?: unknown }).then !== 'function') {\n return Promise.reject(new Error(\n `'${t.name}': action returned null/non-thenable instead of a Promise`));\n }\n return Promise.resolve(stage as Promise<void>);\n } catch (err) {\n return Promise.reject(err);\n }\n}\n\n/**\n * Swallows a failure thrown by a user {@link import('../event/event-store.js').EventStore}\n * from `append`, logging it once.\n *\n * An event emission is observation, not control flow: a store that throws must not\n * unwind the orchestrator loop or escape a failure handler. Each executor wraps its\n * single `emitEvent` choke point in a try/catch that routes here.\n *\n * @param when short description of what was being emitted, for the log message\n * @param err the throwable the store raised\n */\nexport function swallowEventStoreFailure(when: string, err: unknown): void {\n console.warn(\n `libpetri: EventStore.append threw while emitting ${when}; the event is dropped`, err);\n}\n\n/**\n * Default deadline-enforcement tolerance, in milliseconds.\n *\n * A transition with a hard deadline (`deadline()` / `window()`) is force-disabled only once its\n * elapsed time exceeds `latest + DEADLINE_TOLERANCE_MS`, absorbing timer-resolution and scheduling\n * jitter (TIME-013). Shared by both executors and matched by the Java and Rust runtimes so\n * deadline enforcement behaves identically across languages. Configurable per executor via the\n * `deadlineToleranceMs` option.\n *\n * `exact()` timing is enforced *softly* — an exact transition fires at the first opportunity at/after\n * its target time and is never force-disabled, so this tolerance does not gate its firing (TIME-006).\n */\nexport const DEADLINE_TOLERANCE_MS = 5;\n\n/**\n * [IO-015] output validation as an **exact-explanation search**.\n *\n * An *assignment* picks exactly one child at each `xor` it reaches; subtrees under\n * an unselected child are never evaluated. Each assignment claims a set of places,\n * and validation succeeds iff **exactly one** assignment's claim *equals* the\n * produced set.\n *\n * Returns that claim on success and throws `OutViolationError` otherwise — whether\n * nothing explains the write or two or more branches do.\n *\n * Equality — rather than \"every obligation was satisfied\" — is what makes a token\n * written to a declared place outside the selected branch a violation instead of a\n * silent deposit. It also removes the need for a subsumption tie-break:\n * `xor(and(A,B,C), and(A,B))` with A, B, C produced has exactly one *exact* claim.\n *\n * Being a search rather than an eager walk is what makes `and` genuinely unordered\n * ([IO-015] AC8): the old version short-circuited on its first unsatisfied child and\n * let an inner `xor` throw before an enclosing one could try a sibling, so the same\n * write set could pass or fail depending on declaration order.\n */\nexport function validateOutSpec(\n tName: string,\n spec: Out,\n producedPlaceNames: Set<string>,\n): Set<string> {\n // Equality is tested against the produced places the spec could name at all.\n // A token produced to a place the spec never mentions is [CORE-072]'s business\n // — retained and reported, not an [IO-015] violation — so it must not make the\n // claim sets unmatchable.\n const named = specNames(spec);\n let relevant = 0;\n for (const name of producedPlaceNames) {\n if (named.has(name)) relevant++;\n }\n\n const exact: Set<string>[] = [];\n for (const claim of claimsWithin(spec, producedPlaceNames)) {\n // Every claim is a subset of the produced set by construction (a leaf only\n // claims a place that was produced), so equal size means equal set.\n if (claim.size === relevant) {\n exact.push(claim);\n if (exact.length > 1) break;\n }\n }\n const wrote = [...producedPlaceNames].filter(n => named.has(n)).sort();\n if (exact.length === 0) {\n throw new OutViolationError(\n `'${tName}': output does not match the declared spec - produced {${wrote.join(', ')}}, ` +\n `which no single branch of the spec claims exactly`\n );\n }\n if (exact.length > 1) {\n throw new OutViolationError(\n `'${tName}': ambiguous output - {${wrote.join(', ')}} is claimed by more than one branch`\n );\n }\n return exact[0]!;\n}\n\n/**\n * Collapses identical claims, keeping at most two of each.\n *\n * Validation only needs to distinguish \"no assignment\", \"exactly one\" and \"more\n * than one\", so a third assignment claiming an already-seen set carries no\n * information. Without this the `and` join is O(2^k) in the number of `xor`\n * children — 21us at k=8, seconds at k=20, on a path that runs every firing.\n * With it the working set is bounded by the number of DISTINCT claim subsets,\n * which is at most 2^|produced|; the produced set is what the action actually\n * wrote, and is small.\n */\nfunction capMultiplicity(claims: Set<string>[]): Set<string>[] {\n if (claims.length < 3) return claims;\n const seen = new Map<string, number>();\n const out: Set<string>[] = [];\n for (const claim of claims) {\n const key = [...claim].sort().join('\\u0000');\n const n = seen.get(key) ?? 0;\n if (n >= 2) continue;\n seen.set(key, n + 1);\n out.push(claim);\n }\n return out;\n}\n\n/** Every place named anywhere in the spec tree, memoised per spec object. */\nconst specNamesCache = new WeakMap<object, Set<string>>();\nfunction specNames(spec: Out): Set<string> {\n const hit = specNamesCache.get(spec as object);\n if (hit !== undefined) return hit;\n const names = new Set<string>();\n const walk = (node: Out): void => {\n switch (node.type) {\n case 'place': names.add(node.place.name); break;\n case 'forward-input': names.add(node.to.name); break;\n case 'timeout': walk(node.child); break;\n case 'xor':\n case 'and': for (const c of node.children) walk(c); break;\n }\n };\n walk(spec);\n specNamesCache.set(spec as object, names);\n return names;\n}\n\n/**\n * Claims of every assignment whose claim is a subset of `produced`.\n *\n * The subset restriction is the pruning that keeps this linear in practice: a leaf\n * naming a place that was not produced yields nothing, so a `xor` branch dies as soon\n * as it claims something unwritten, and an `and` dies with any unsatisfiable child.\n * Branching survives only where several `xor` children are simultaneously consistent\n * with what was produced — the ambiguous case, which is rejected anyway.\n */\nfunction claimsWithin(spec: Out, produced: Set<string>): Set<string>[] {\n switch (spec.type) {\n case 'place':\n return produced.has(spec.place.name) ? [new Set([spec.place.name])] : [];\n\n case 'forward-input':\n return produced.has(spec.to.name) ? [new Set([spec.to.name])] : [];\n\n case 'timeout':\n return claimsWithin(spec.child, produced);\n\n case 'xor': {\n const out: Set<string>[] = [];\n for (const child of spec.children) {\n for (const claim of claimsWithin(child, produced)) out.push(claim);\n }\n return capMultiplicity(out);\n }\n\n case 'and': {\n // Unordered: the children are a set of obligations, so this is a join over\n // their claim sets and the result cannot depend on their declaration order.\n let acc: Set<string>[] = [new Set()];\n for (const child of spec.children) {\n const childClaims = claimsWithin(child, produced);\n if (childClaims.length === 0) return []; // no assignment can satisfy this AND\n const next: Set<string>[] = [];\n for (const partial of acc) {\n for (const claim of childClaims) {\n const merged = new Set(partial);\n for (const name of claim) merged.add(name);\n next.push(merged);\n }\n }\n acc = capMultiplicity(next);\n }\n return acc;\n }\n }\n}\n\n/**\n * Produces default tokens to the timeout branch's output places when an action\n * exceeds its timeout. Walks the Out spec tree recursively:\n *\n * - **Place**: produces `null` (the timeout sentinel value).\n * - **ForwardInput**: forwards *all* tokens consumed from the `from` place to the\n * output place, in consumption order — one output token per consumed token, so a\n * batched input spec (`all()` / `exactly(n)`) conserves its tokens on timeout.\n * - **AND**: recurses into all children (all branches get tokens).\n * - **XOR**: disallowed — timeout cannot choose a branch non-deterministically.\n * - **Timeout**: disallowed — nested timeouts would create ambiguous recovery paths.\n *\n * Writes through {@link TransitionContext.outputToHarvest} rather than `output(...)`:\n * by this point the context has been detached, so the ordinary write target is closed\n * and only the harvest collector still reaches the marking.\n */\nexport function produceTimeoutOutput(context: TransitionContext, timeoutChild: Out): void {\n switch (timeoutChild.type) {\n case 'place':\n context.outputToHarvest(timeoutChild.place, null);\n break;\n case 'forward-input': {\n // Forward *every* token consumed from `from`, not just the first: a batched\n // input spec (`all()`, `exactly(n)`, `atLeast(n)`) consumes N tokens, and\n // re-emitting only one would silently destroy N-1 of them on the retry path.\n // `inputs()` is the batched accessor and preserves consumption (FIFO) order;\n // the singular `input()` throws outright when the place yielded != 1 token.\n for (const value of context.inputs(timeoutChild.from)) {\n context.outputToHarvest(timeoutChild.to, value);\n }\n break;\n }\n case 'and':\n for (const child of timeoutChild.children) {\n produceTimeoutOutput(context, child);\n }\n break;\n case 'xor':\n throw new Error('XOR not allowed in timeout child');\n case 'timeout':\n throw new Error('Nested Timeout not allowed');\n }\n}\n","/**\n * @module bitmap-net-executor\n *\n * Async bitmap-based executor for Typed Coloured Time Petri Nets.\n *\n * **Execution loop phases** (per cycle):\n * 1. Process completed transitions — collect outputs, validate against Out specs\n * 2. Process external events — inject tokens from EnvironmentPlaces\n * 3. Update dirty transitions — re-evaluate enablement for transitions whose\n * input/inhibitor/read places changed (bitmap-based dirty set tracking)\n * 4. Fire ready transitions — sorted by priority (desc) then FIFO enablement time\n * 5. Await work — sleep until an action completes, a timer fires, or an external event arrives\n *\n * **Concurrency model**: Single-threaded JS event loop. No locks or CAS needed.\n * Multiple transitions execute concurrently via Promises (actions return Promise<void>).\n * Only the orchestrator mutates marking state — actions communicate via TokenOutput.\n *\n * **Bitmap strategy**: Places are tracked as bits in Uint32Array words. Enablement\n * checks use bitwise AND/OR for O(W) where W = ceil(numPlaces/32). A dirty set\n * bitmap tracks which transitions need re-evaluation, avoiding O(T) scans per cycle.\n *\n * @see CompiledNet for the precomputed bitmap masks and reverse indices\n */\nimport type { PetriNet } from '../core/petri-net.js';\nimport type { Place, EnvironmentPlace } from '../core/place.js';\nimport type { Token } from '../core/token.js';\nimport type { Transition } from '../core/transition.js';\nimport type { EventStore } from '../event/event-store.js';\nimport type { NetEvent } from '../event/net-event.js';\nimport type { PetriNetExecutor, RunTimeoutPolicy } from './petri-net-executor.js';\nimport { tokenOf } from '../core/token.js';\nimport { TokenInput } from '../core/token-input.js';\nimport { TokenOutput } from '../core/token-output.js';\nimport { TransitionContext } from '../core/transition-context.js';\nimport { noopEventStore } from '../event/event-store.js';\nimport { CompiledNet, WORD_SHIFT, BIT_MASK, setBit, clearBit } from './compiled-net.js';\nimport { Marking, type PredicateSpec } from './marking.js';\nimport { findBinding, IncrementalMatcher } from './match-engine.js';\nimport { keyForPlace } from '../core/match-spec.js';\nimport { nameId } from '../core/name.js';\nimport { validateOutSpec, produceTimeoutOutput, executeAction, swallowEventStoreFailure, DEADLINE_TOLERANCE_MS } from './executor-support.js';\nimport { earliest as timingEarliest, latest as timingLatest, hasDeadline as timingHasDeadline } from '../core/timing.js';\n\n/** Tolerance for JS timer jitter (setTimeout resolution ~1-4ms). */\n// Tolerance for deadline enforcement to account for Node.js event loop timer jitter.\ninterface InFlightTransition {\n promise: Promise<void>;\n context: TransitionContext;\n consumed: Token<any>[];\n startMs: number;\n resolve: () => void;\n error?: unknown;\n}\n\ninterface ExternalEvent<T = any> {\n place: Place<T>;\n token: Token<T>;\n resolve: (value: boolean) => void;\n reject: (err: Error) => void;\n}\n\nexport interface BitmapNetExecutorOptions {\n eventStore?: EventStore;\n environmentPlaces?: Set<EnvironmentPlace<any>>;\n /** Provides execution context data for each transition firing. */\n executionContextProvider?: (transitionName: string, consumed: Token<any>[]) => Map<string, unknown>;\n /**\n * Grace band (ms) beyond a hard deadline (`deadline()` / `window()`) before a transition is\n * force-disabled with a `transition-timed-out` event (TIME-013). Defaults to {@link DEADLINE_TOLERANCE_MS}\n * (5ms); `0` gives strict enforcement. Must be non-negative. Does not affect `exact()` transitions,\n * which are enforced softly (TIME-006).\n */\n deadlineToleranceMs?: number;\n}\n\n/**\n * Async bitmap-based executor for Coloured Time Petri Nets.\n *\n * Single-threaded JS model: no CAS needed, direct array writes.\n * Actions return Promise<void> — multiple in-flight actions are naturally concurrent.\n *\n * @remarks\n * **Deadline enforcement**: Transitions with finite deadlines (`deadline`, `window`, `exact`)\n * are checked in `enforceDeadlines()`, called from the main loop only when `hasAnyDeadlines`\n * is true (precomputed at construction). If a transition has been enabled longer than\n * `latest(timing)`, it is forcibly disabled and a `TransitionTimedOut` event is emitted.\n * The `awaitWork()` timer also schedules wake-ups for approaching deadlines, not just\n * earliest firing times.\n *\n * **Constructor precomputation**: `hasAnyDeadlines`, `allImmediate`/`allSamePriority`,\n * and `eventStoreEnabled` are computed once to avoid per-cycle overhead. Safe because\n * `isEnabled()` is constant and timing/priority are immutable on Transition.\n */\nexport class BitmapNetExecutor implements PetriNetExecutor {\n private readonly compiled: CompiledNet;\n private readonly marking: Marking;\n /** Monotonic source for ν-name minting (ctx.freshName(), NU-010). */\n private freshNameCounter = 0;\n /**\n * ν-net incremental match caches (NU-020): per matched transition, an\n * {@link IncrementalMatcher} kept in lockstep with the marking when the\n * transition is fast-path eligible (every correlated input is `one`/`exactly`,\n * consumed by no other transition, never reset), else `null` → fall back to\n * the O(n) rebuild {@link findBinding}. Turns a draining matched join from\n * O(n²) into O(n log n). Mirrors the precompiled executor and the Rust backends.\n */\n private matchCaches: (IncrementalMatcher | null)[] = [];\n private placeMatchTargets: Array<Array<[number, number]>> = [];\n private readonly eventStore: EventStore;\n private readonly environmentPlaces: Set<string>;\n private readonly hasEnvironmentPlaces: boolean;\n private readonly executionContextProvider?: (transitionName: string, consumed: Token<any>[]) => Map<string, unknown>;\n private readonly startMs: number;\n private readonly hasAnyDeadlines: boolean;\n private readonly allImmediate: boolean;\n private readonly allSamePriority: boolean;\n private readonly eventStoreEnabled: boolean;\n\n // Bitmaps (Uint32Array, direct writes)\n private readonly markingBitmap: Uint32Array;\n private readonly dirtySet: Uint32Array;\n private readonly markingSnapBuffer: Uint32Array;\n private readonly dirtySnapBuffer: Uint32Array;\n private readonly firingSnapBuffer: Uint32Array;\n\n // Orchestrator state\n private readonly enabledAtMs: Float64Array;\n private readonly inFlightFlags: Uint8Array;\n private readonly enabledFlags: Uint8Array;\n /** Precomputed: 1 if transition has a finite deadline, 0 otherwise. */\n private readonly hasDeadlineFlags: Uint8Array;\n /** Precomputed: 1 for exact() transitions — enforced softly, never force-disabled (TIME-006). */\n private readonly isExactFlags: Uint8Array;\n /** Grace band (ms) before a hard deadline force-disables (TIME-013). */\n private readonly deadlineToleranceMs: number;\n private enabledTransitionCount = 0;\n\n // In-flight tracking\n private readonly inFlight = new Map<Transition, InFlightTransition>();\n private readonly inFlightPromises: Promise<void>[] = [];\n private readonly awaitPromises: Promise<void>[] = [];\n\n // Queues\n private readonly completionQueue: Transition[] = [];\n private readonly externalQueue: ExternalEvent[] = [];\n\n // Wake-up mechanism\n private wakeUpResolve: (() => void) | null = null;\n\n // Pre-allocated buffer for fireReadyTransitions() to avoid per-cycle allocation\n private readonly readyBuffer: { tid: number; priority: number; enabledAtMs: number }[] = [];\n\n // Pending reset places for clock-restart detection\n private readonly pendingResetPlaces = new Set<string>();\n /**\n * Undeclared place names already reported (CORE-072 AC4). Keyed by name — TS\n * Place identity is name-based — so a hot loop warns once, not per token.\n */\n private readonly warnedUnknownPlaces = new Set<string>();\n /** Transitions already warned for writing several tokens to a place their spec names once (IO-016 AC4). */\n private readonly warnedMultiplicity = new Set<string>();\n private readonly transitionInputPlaceNames: Map<Transition, Set<string>>;\n\n private running = false;\n private draining = false;\n private closed = false;\n\n constructor(\n net: PetriNet,\n initialTokens: Map<Place<any>, Token<any>[]>,\n options: BitmapNetExecutorOptions = {},\n ) {\n this.compiled = CompiledNet.compile(net);\n this.marking = Marking.from(initialTokens);\n this.eventStore = options.eventStore ?? noopEventStore();\n this.environmentPlaces = new Set(\n [...(options.environmentPlaces ?? [])].map(ep => ep.place.name)\n );\n this.hasEnvironmentPlaces = this.environmentPlaces.size > 0;\n this.executionContextProvider = options.executionContextProvider;\n this.deadlineToleranceMs = options.deadlineToleranceMs ?? DEADLINE_TOLERANCE_MS;\n if (this.deadlineToleranceMs < 0) {\n throw new Error(`Deadline tolerance must be non-negative: ${this.deadlineToleranceMs}`);\n }\n this.startMs = performance.now();\n\n const wordCount = this.compiled.wordCount;\n this.markingBitmap = new Uint32Array(wordCount);\n this.markingSnapBuffer = new Uint32Array(wordCount);\n this.firingSnapBuffer = new Uint32Array(wordCount);\n const dirtyWords = (this.compiled.transitionCount + BIT_MASK) >>> WORD_SHIFT;\n this.dirtySet = new Uint32Array(dirtyWords);\n this.dirtySnapBuffer = new Uint32Array(dirtyWords);\n\n this.enabledAtMs = new Float64Array(this.compiled.transitionCount);\n this.enabledAtMs.fill(-Infinity);\n this.inFlightFlags = new Uint8Array(this.compiled.transitionCount);\n this.enabledFlags = new Uint8Array(this.compiled.transitionCount);\n this.hasDeadlineFlags = new Uint8Array(this.compiled.transitionCount);\n this.isExactFlags = new Uint8Array(this.compiled.transitionCount);\n let anyDeadlines = false;\n let allImm = true;\n let samePrio = true;\n const firstPriority = this.compiled.transitionCount > 0\n ? this.compiled.transition(0).priority : 0;\n for (let tid = 0; tid < this.compiled.transitionCount; tid++) {\n const t = this.compiled.transition(tid);\n if (timingHasDeadline(t.timing)) {\n this.hasDeadlineFlags[tid] = 1;\n anyDeadlines = true;\n }\n if (t.timing.type === 'exact') this.isExactFlags[tid] = 1;\n if (t.timing.type !== 'immediate') allImm = false;\n if (t.priority !== firstPriority) samePrio = false;\n }\n this.hasAnyDeadlines = anyDeadlines;\n this.allImmediate = allImm;\n this.allSamePriority = samePrio;\n this.eventStoreEnabled = this.eventStore.isEnabled();\n\n // Precompute input place names per transition\n this.transitionInputPlaceNames = new Map();\n for (const t of net.transitions) {\n const names = new Set<string>();\n for (const spec of t.inputSpecs) names.add(spec.place.name);\n this.transitionInputPlaceNames.set(t, names);\n }\n\n // CORE-072: the Marking keeps tokens on places the net never declared;\n // report each such place once, matching the precompiled backend's seam.\n for (const [place, tokens] of initialTokens) {\n if (tokens.length > 0 && this.compiled.tryPlaceId(place) === undefined) {\n this.warnUnknownPlace(place, '');\n }\n }\n\n this.initMatchCaches();\n }\n\n /**\n * Builds the ν-net incremental match caches (NU-020). A matched join is\n * fast-path eligible only when every correlated input is `one`/`exactly`, is\n * consumed by no other transition, and is never reset — so the cache can never\n * desync from the marking. Mirrors the precompiled executor.\n */\n private initMatchCaches(): void {\n const compiled = this.compiled;\n const tc = compiled.transitionCount;\n const pc = compiled.placeCount;\n this.matchCaches = new Array(tc).fill(null);\n this.placeMatchTargets = Array.from({ length: pc }, () => []);\n\n let anyMatch = false;\n for (let tid = 0; tid < tc; tid++) {\n if (compiled.hasMatch(tid)) { anyMatch = true; break; }\n }\n if (!anyMatch) return;\n\n const inputConsumers: number[][] = Array.from({ length: pc }, () => []);\n const resetTarget: boolean[] = new Array(pc).fill(false);\n for (let tid = 0; tid < tc; tid++) {\n const t = compiled.transition(tid);\n for (const spec of t.inputSpecs) inputConsumers[compiled.placeId(spec.place)]!.push(tid);\n for (const arc of t.resets) resetTarget[compiled.placeId(arc.place)] = true;\n }\n\n for (let tid = 0; tid < tc; tid++) {\n if (!compiled.hasMatch(tid)) continue;\n const t = compiled.transition(tid);\n const ms = t.matchSpec;\n if (!ms) continue;\n\n const requireds: number[] = [];\n let eligible = true;\n for (const mk of ms.keys) {\n const pid = compiled.placeId(mk.place);\n const spec = t.inputSpecs.find(s => s.place.name === mk.place.name);\n let required: number;\n if (spec?.type === 'one') required = 1;\n else if (spec?.type === 'exactly') required = spec.count;\n else { eligible = false; break; }\n const cons = inputConsumers[pid]!;\n if (resetTarget[pid] || cons.length !== 1 || cons[0] !== tid) { eligible = false; break; }\n requireds.push(required);\n }\n if (!eligible) continue;\n\n const matcher = new IncrementalMatcher(requireds);\n for (let keyIdx = 0; keyIdx < ms.keys.length; keyIdx++) {\n const mk = ms.keys[keyIdx]!;\n const pid = compiled.placeId(mk.place);\n for (const token of this.marking.peekTokens(mk.place)) {\n const name = mk.key(token.value);\n if (name !== undefined && name !== null) matcher.add(keyIdx, name, token.createdAt);\n }\n this.placeMatchTargets[pid]!.push([tid, keyIdx]);\n }\n this.matchCaches[tid] = matcher;\n }\n }\n\n /** Mirror a token added to correlated input `pid` into every fast-path matcher. */\n private cacheAddToken(pid: number, token: Token<any>): void {\n const targets = this.placeMatchTargets[pid];\n if (targets === undefined || targets.length === 0) return;\n const compiled = this.compiled;\n for (const [tid, keyIdx] of targets) {\n const cache = this.matchCaches[tid];\n if (cache == null) continue;\n const t = compiled.transition(tid);\n const mk = t.matchSpec!.keys[keyIdx]!;\n const name = mk.key(token.value);\n if (name !== undefined && name !== null) cache.add(keyIdx, name, token.createdAt);\n }\n }\n\n // ======================== Execution ========================\n\n async run(timeoutMs?: number, onTimeout: RunTimeoutPolicy = 'abandon'): Promise<Marking> {\n if (timeoutMs === undefined) return this.executeLoop();\n\n let timer: ReturnType<typeof setTimeout> | undefined;\n let timedOut = false;\n const timeoutPromise = new Promise<never>((_, reject) => {\n timer = setTimeout(() => {\n timedOut = true;\n reject(new Error('Execution timed out'));\n }, timeoutMs);\n });\n // Held rather than inlined into the race: Promise.race walks away from the\n // loser, it does not cancel it, so the loop needs handling of its own.\n const loop = this.executeLoop();\n try {\n return await Promise.race([loop, timeoutPromise]);\n } finally {\n if (timer !== undefined) clearTimeout(timer);\n if (timedOut) {\n if (onTimeout === 'close') this.close();\n // Nobody is left to observe the abandoned loop's outcome.\n loop.catch(() => {});\n }\n }\n }\n\n private async executeLoop(): Promise<Marking> {\n this.running = true;\n this.emitEvent({\n type: 'execution-started',\n timestamp: Date.now(),\n netName: this.compiled.net.name,\n executionId: this.executionId(),\n });\n\n this.initializeMarkingBitmap();\n this.markAllDirty();\n\n this.emitEvent({\n type: 'marking-snapshot',\n timestamp: Date.now(),\n marking: this.snapshotMarking(),\n });\n\n while (this.running) {\n this.processCompletedTransitions();\n this.processExternalEvents();\n this.updateDirtyTransitions();\n // Single timestamp for this loop iteration: ensures deadline enforcement and\n // firing readiness checks use the same time reference, preventing races where\n // a transition passes the deadline check but is disabled before the fire check.\n const cycleNowMs = performance.now();\n // Deadline enforcement: separate pass over ALL enabled transitions (not just dirty\n // ones), since deadlines tick independently of place changes. Gated by\n // hasAnyDeadlines (O(0) skip for pure immediate nets).\n if (this.hasAnyDeadlines) this.enforceDeadlines(cycleNowMs);\n\n if (this.shouldTerminate()) break;\n\n this.fireReadyTransitions(cycleNowMs);\n // Skip awaitWork() when firing produced dirty bits (e.g., token consumption\n // disabled a conflicting transition). Bounded: without microtask yield no new\n // completions arrive, so the loop converges in at most one extra pass.\n if (this.hasDirtyBits()) continue;\n await this.awaitWork();\n }\n\n this.running = false;\n this.drainPendingExternalEvents();\n\n this.emitEvent({\n type: 'marking-snapshot',\n timestamp: Date.now(),\n marking: this.snapshotMarking(),\n });\n\n this.emitEvent({\n type: 'execution-completed',\n timestamp: Date.now(),\n netName: this.compiled.net.name,\n executionId: this.executionId(),\n totalDurationMs: performance.now() - this.startMs,\n });\n\n return this.marking;\n }\n\n // ======================== Environment Place API ========================\n\n async inject<T>(envPlace: EnvironmentPlace<T>, token: Token<T>): Promise<boolean> {\n if (!this.environmentPlaces.has(envPlace.place.name)) {\n throw new Error(`Place ${envPlace.place.name} is not registered as an environment place`);\n }\n if (this.closed || this.draining) return false;\n\n return new Promise<boolean>((resolve, reject) => {\n this.externalQueue.push({\n place: envPlace.place,\n token,\n resolve,\n reject,\n });\n this.wakeUp();\n });\n }\n\n /** Convenience: inject a raw value (creates token with current timestamp). */\n async injectValue<T>(envPlace: EnvironmentPlace<T>, value: T): Promise<boolean> {\n return this.inject(envPlace, tokenOf(value));\n }\n\n // ======================== Initialize ========================\n\n private initializeMarkingBitmap(): void {\n for (let pid = 0; pid < this.compiled.placeCount; pid++) {\n const place = this.compiled.place(pid);\n if (this.marking.hasTokens(place)) {\n setBit(this.markingBitmap, pid);\n }\n }\n }\n\n private markAllDirty(): void {\n const tc = this.compiled.transitionCount;\n const dirtyWords = this.dirtySet.length;\n for (let w = 0; w < dirtyWords - 1; w++) {\n this.dirtySet[w] = 0xFFFFFFFF;\n }\n if (dirtyWords > 0) {\n const lastWordBits = tc & BIT_MASK;\n this.dirtySet[dirtyWords - 1] = lastWordBits === 0 ? 0xFFFFFFFF : (1 << lastWordBits) - 1;\n }\n }\n\n private shouldTerminate(): boolean {\n if (this.closed) {\n // ENV-013: immediate close — wait for in-flight actions to complete\n return this.inFlight.size === 0 && this.completionQueue.length === 0;\n }\n if (this.hasEnvironmentPlaces) {\n return this.draining\n && this.enabledTransitionCount === 0\n && this.inFlight.size === 0\n && this.completionQueue.length === 0;\n }\n return this.enabledTransitionCount === 0\n && this.inFlight.size === 0\n && this.completionQueue.length === 0;\n }\n\n // ======================== Dirty Set Transitions ========================\n\n private updateDirtyTransitions(): void {\n const nowMs = performance.now();\n\n // Snapshot the marking bitmap into pre-allocated buffer.\n // We need a consistent snapshot because enablement checks read multiple words,\n // and concurrent completions/injections could modify markingBitmap mid-scan.\n const markingSnap = this.markingSnapBuffer;\n markingSnap.set(this.markingBitmap);\n\n // Snapshot-and-clear the dirty set in one pass. New dirty bits set during\n // re-evaluation (e.g., by cascading enablement) are captured in the next cycle.\n const dirtyWords = this.dirtySet.length;\n const dirtySnap = this.dirtySnapBuffer;\n for (let w = 0; w < dirtyWords; w++) {\n dirtySnap[w] = this.dirtySet[w]!;\n this.dirtySet[w] = 0;\n }\n\n // Iterate over set bits using the numberOfTrailingZeros trick.\n for (let w = 0; w < dirtyWords; w++) {\n let word = dirtySnap[w]!;\n while (word !== 0) {\n // Extract lowest set bit index: `word & -word` isolates the lowest set bit,\n // `Math.clz32()` counts leading zeros (0-31), XOR 31 converts to trailing zeros.\n const bit = Math.clz32(word & -word) ^ 31;\n const tid = (w << WORD_SHIFT) | bit;\n word &= word - 1; // clear lowest set bit (Kernighan's trick)\n\n if (tid >= this.compiled.transitionCount) break;\n if (this.inFlightFlags[tid]) continue;\n\n const wasEnabled = this.enabledFlags[tid] !== 0;\n const canNow = this.canEnable(tid, markingSnap);\n\n if (canNow && !wasEnabled) {\n this.enabledFlags[tid] = 1;\n this.enabledTransitionCount++;\n this.enabledAtMs[tid] = nowMs;\n this.emitEvent({\n type: 'transition-enabled',\n timestamp: Date.now(),\n transitionName: this.compiled.transition(tid).name,\n });\n } else if (!canNow && wasEnabled) {\n this.enabledFlags[tid] = 0;\n this.enabledTransitionCount--;\n this.enabledAtMs[tid] = -Infinity;\n } else if (canNow && wasEnabled && this.hasInputFromResetPlace(this.compiled.transition(tid))) {\n this.enabledAtMs[tid] = nowMs;\n this.emitEvent({\n type: 'transition-clock-restarted',\n timestamp: Date.now(),\n transitionName: this.compiled.transition(tid).name,\n });\n }\n }\n }\n\n this.pendingResetPlaces.clear();\n }\n\n /**\n * Checks all enabled transitions with finite deadlines. If a transition has been\n * enabled longer than `latest(timing)`, it is forcibly disabled and a\n * `TransitionTimedOut` event is emitted. Classical TPN semantics require transitions\n * to either fire within their window or become disabled.\n *\n * A 1ms tolerance is applied to account for timer jitter and microtask scheduling\n * delays. Without this, exact-timed transitions (where earliest == latest) would\n * almost always be disabled before they can fire.\n */\n private enforceDeadlines(nowMs: number): void {\n for (let tid = 0; tid < this.compiled.transitionCount; tid++) {\n if (!this.hasDeadlineFlags[tid]) continue; // O(1) skip for non-deadline transitions\n // exact() is enforced softly — it fires at the first opportunity at/after its target and is\n // never force-disabled (TIME-006). Only hard deadlines (deadline()/window()) are reaped here.\n if (this.isExactFlags[tid]) continue;\n if (!this.enabledFlags[tid] || this.inFlightFlags[tid]) continue;\n const t = this.compiled.transition(tid);\n\n const elapsed = nowMs - this.enabledAtMs[tid]!;\n const latestMs = timingLatest(t.timing);\n if (elapsed > latestMs + this.deadlineToleranceMs) {\n this.enabledFlags[tid] = 0;\n this.enabledTransitionCount--;\n this.emitEvent({\n type: 'transition-timed-out',\n timestamp: Date.now(),\n transitionName: t.name,\n deadlineMs: latestMs,\n actualDurationMs: elapsed,\n });\n this.enabledAtMs[tid] = -Infinity;\n }\n }\n }\n\n private canEnable(tid: number, markingSnap: Uint32Array): boolean {\n if (!this.compiled.canEnableBitmap(tid, markingSnap)) return false;\n\n // Cardinality check\n const cardCheck = this.compiled.cardinalityCheck(tid);\n if (cardCheck !== null) {\n for (let i = 0; i < cardCheck.placeIds.length; i++) {\n const pid = cardCheck.placeIds[i]!;\n const required = cardCheck.requiredCounts[i]!;\n const place = this.compiled.place(pid);\n if (this.marking.tokenCount(place) < required) return false;\n }\n }\n\n // ν-net join: a correlation name must satisfy every matched input (NU-020).\n // Fast-path transitions read the maintained matcher (O(1)); the rest rebuild\n // the index (O(n)).\n if (this.compiled.hasMatch(tid)) {\n const cache = this.matchCaches[tid];\n const noBinding = cache != null\n ? cache.best() === null\n : findBinding(this.compiled.transition(tid), p => this.marking.peekTokens(p)) === null;\n if (noBinding) {\n return false;\n }\n }\n\n return true;\n }\n\n private hasInputFromResetPlace(t: Transition): boolean {\n if (this.pendingResetPlaces.size === 0) return false;\n const inputNames = this.transitionInputPlaceNames.get(t);\n if (!inputNames) return false;\n for (const name of this.pendingResetPlaces) {\n if (inputNames.has(name)) return true;\n }\n return false;\n }\n\n // ======================== Firing ========================\n\n private fireReadyTransitions(nowMs: number): void {\n if (this.allImmediate && this.allSamePriority) {\n this.fireReadyImmediate();\n return;\n }\n this.fireReadyGeneral(nowMs);\n }\n\n /**\n * Fast path for nets where all transitions are immediate and same priority.\n * Skips timing checks, sorting, and snapshot buffer — just scan and fire.\n *\n * Uses live `markingBitmap` instead of a snapshot. Safe because\n * `updateBitmapAfterConsumption()` synchronously updates the bitmap before the next\n * iteration. For equal-priority immediate transitions, tid scan order satisfies\n * FIFO-by-enablement-time (all enabled in the same cycle).\n */\n private fireReadyImmediate(): void {\n for (let tid = 0; tid < this.compiled.transitionCount; tid++) {\n if (!this.enabledFlags[tid] || this.inFlightFlags[tid]) continue;\n if (this.canEnable(tid, this.markingBitmap)) {\n this.fireTransitionContained(tid);\n } else {\n this.enabledFlags[tid] = 0;\n this.enabledTransitionCount--;\n this.enabledAtMs[tid] = -Infinity;\n }\n }\n }\n\n private fireReadyGeneral(nowMs: number): void {\n\n // Collect ready transitions into pre-allocated buffer to reduce GC pressure\n const ready = this.readyBuffer;\n ready.length = 0;\n for (let tid = 0; tid < this.compiled.transitionCount; tid++) {\n if (!this.enabledFlags[tid] || this.inFlightFlags[tid]) continue;\n const t = this.compiled.transition(tid);\n const enabledMs = this.enabledAtMs[tid]!;\n const elapsedMs = nowMs - enabledMs;\n const earliestMs = timingEarliest(t.timing);\n if (earliestMs <= elapsedMs) {\n ready.push({ tid, priority: t.priority, enabledAtMs: enabledMs });\n }\n }\n if (ready.length === 0) return;\n\n // Sort: higher priority first, then earlier enablement (FIFO).\n // This defines the deterministic scheduling contract for conflict resolution.\n // We re-sort each cycle rather than maintaining a sorted invariant because\n // enablement times change on clock-restarts (reset arcs), which would require\n // expensive re-insertion. Sorting ≤T entries per cycle is fast enough.\n ready.sort((a, b) => {\n const prioCmp = b.priority - a.priority;\n if (prioCmp !== 0) return prioCmp;\n return a.enabledAtMs - b.enabledAtMs;\n });\n\n // Take a fresh snapshot for re-checking (reuse pre-allocated buffer)\n const freshSnap = this.firingSnapBuffer;\n freshSnap.set(this.markingBitmap);\n for (const entry of ready) {\n const { tid } = entry;\n if (this.enabledFlags[tid] && this.canEnable(tid, freshSnap)) {\n this.fireTransitionContained(tid);\n // Update snapshot after consuming tokens\n freshSnap.set(this.markingBitmap);\n } else {\n this.enabledFlags[tid] = 0;\n this.enabledTransitionCount--;\n this.enabledAtMs[tid] = -Infinity;\n }\n }\n }\n\n /**\n * Fires a transition, containing any synchronous throw to that one firing so it fails\n * only that transition, not the whole run.\n *\n * Without this boundary an unchecked throw raised while a transition fires — a hostile\n * EventStore.append on a token-removed or transition-started emit, or an error thrown while\n * consuming the matched tokens — unwinds out of the orchestrator loop and kills the executor.\n * The transition is instead failed and marked dirty for re-evaluation, the same treatment an\n * asynchronously-reported failure gets. Enablement-phase throws (a key function that\n * throws inside canEnable, before the firing) run outside this boundary and are not contained\n * here.\n *\n * fireTransition removes tokens from the marking before it reconciles the presence\n * bitmap, so a throw inside that window would leave bits asserting tokens that are gone;\n * the recovery re-runs updateBitmapAfterConsumption against the real marking.\n *\n * Unlike the Java runtime there is no VirtualMachineError/LinkageError analogue on the JS\n * side, so every throw is contained here — there is deliberately no fatal-rethrow escape\n * hatch.\n */\n private fireTransitionContained(tid: number): void {\n try {\n this.fireTransition(tid);\n } catch (e) {\n const t = this.compiled.transition(tid);\n if (this.enabledFlags[tid]) {\n this.enabledFlags[tid] = 0;\n this.enabledTransitionCount--;\n this.enabledAtMs[tid] = -Infinity;\n }\n if (this.inFlight.delete(t)) {\n this.inFlightFlags[tid] = 0;\n }\n this.updateBitmapAfterConsumption(tid);\n // Drop the ν fast-path matcher: fireTransition mirrors the matched consume into it\n // before the tokens physically leave the marking, so a throw in that window desyncs\n // it. Nulling it forces the next canEnable/fire to rebuild the binding via findBinding.\n this.matchCaches[tid] = null;\n const err = e instanceof Error ? e : new Error(String(e));\n this.emitEvent({\n type: 'transition-failed',\n timestamp: Date.now(),\n transitionName: t.name,\n errorMessage: err.message,\n exceptionType: err.name,\n stack: err.stack,\n });\n this.markTransitionDirty(tid);\n }\n }\n\n private fireTransition(tid: number): void {\n const t = this.compiled.transition(tid);\n const inputs = new TokenInput();\n const consumed: Token<any>[] = [];\n\n // Consume tokens based on input specs with cardinality.\n // ν-net join: resolve the correlation name once; correlated inputs consume\n // the name-matched tokens (name equality — NU-021).\n const ms = t.matchSpec;\n const cache = ms ? this.matchCaches[tid] : null;\n const chosen = ms\n ? (cache != null ? cache.best() : findBinding(t, p => this.marking.peekTokens(p)))\n : null;\n // Mirror the matched consume into the fast-path matcher (the only path by\n // which tokens leave this join's correlated inputs) before the marking changes.\n if (cache != null && chosen !== null) cache.consume(chosen);\n\n for (const inSpec of t.inputSpecs) {\n const keyFn = ms ? keyForPlace(ms, inSpec.place.name) : undefined;\n // Name-equality predicate when correlated; otherwise a plain FIFO consume.\n let spec: PredicateSpec;\n if (keyFn && chosen !== null) {\n spec = {\n place: inSpec.place,\n predicate: (v: any) => keyFn(v) === chosen,\n };\n } else {\n spec = inSpec;\n }\n\n let toConsume: number;\n switch (inSpec.type) {\n case 'one': toConsume = 1; break;\n case 'exactly': toConsume = inSpec.count; break;\n case 'all':\n case 'at-least':\n toConsume = spec.predicate\n ? this.marking.countMatching(spec)\n : this.marking.tokenCount(inSpec.place);\n break;\n }\n\n for (let i = 0; i < toConsume; i++) {\n const token = spec.predicate\n ? this.marking.removeFirstMatching(spec)\n : this.marking.removeFirst(inSpec.place);\n if (token === null) break;\n consumed.push(token);\n inputs.add(inSpec.place, token);\n this.emitEvent({\n type: 'token-removed',\n timestamp: Date.now(),\n placeName: inSpec.place.name,\n token,\n });\n }\n }\n\n // Read arcs (peek, don't consume)\n for (const arc of t.reads) {\n const token = this.marking.peekFirst(arc.place);\n if (token !== null) {\n inputs.add(arc.place, token);\n }\n }\n\n // Reset arcs\n for (const arc of t.resets) {\n const removed = this.marking.removeAll(arc.place);\n this.pendingResetPlaces.add(arc.place.name);\n for (const token of removed) {\n consumed.push(token);\n this.emitEvent({\n type: 'token-removed',\n timestamp: Date.now(),\n placeName: arc.place.name,\n token,\n });\n }\n }\n\n // Update bitmap for consumed/reset places\n this.updateBitmapAfterConsumption(tid);\n\n this.emitEvent({\n type: 'transition-started',\n timestamp: Date.now(),\n transitionName: t.name,\n consumedTokens: consumed,\n });\n\n const execCtx = this.executionContextProvider?.(t.name, consumed);\n const logFn = (level: string, message: string, error?: Error) => {\n this.emitEvent({\n type: 'log-message',\n timestamp: Date.now(),\n transitionName: t.name,\n logger: t.name,\n level,\n message,\n error: error?.name ?? null,\n errorMessage: error?.message ?? null,\n });\n };\n const context = new TransitionContext(\n t.name, inputs, new TokenOutput(),\n t.inputPlaces(), t.readPlaces(), t.outputPlaces(),\n execCtx,\n logFn,\n t.placeAlias,\n );\n const freshNameBase = t.name;\n context.setFreshNameSupplier(() => nameId(`${freshNameBase}#${this.freshNameCounter++}`));\n\n // Create action promise with optional timeout. executeAction converts a synchronous\n // throw or a null/non-thenable return into a rejected promise, so a misbehaving action\n // flows the contained failure path instead of unwinding the orchestrator loop.\n let actionPromise = executeAction(t, context);\n\n if (t.hasActionTimeout()) {\n const timeoutSpec = t.actionTimeout;\n if (timeoutSpec === null) throw new Error(`Expected actionTimeout on ${t.name}`);\n const timeoutMs = timeoutSpec.afterMs;\n actionPromise = Promise.race([\n actionPromise,\n new Promise<void>((_, reject) =>\n setTimeout(() => reject(new TimeoutSentinel()), timeoutMs)\n ),\n ]).catch((err) => {\n if (err instanceof TimeoutSentinel) {\n // Sever first, then produce: the abandoned action may still be writing to this\n // context, and its pre-timeout writes must not merge with the timeout branch.\n context.detachForTimeout();\n produceTimeoutOutput(context, timeoutSpec.child);\n this.emitEvent({\n type: 'action-timed-out',\n timestamp: Date.now(),\n transitionName: t.name,\n timeoutMs,\n });\n return;\n }\n throw err;\n });\n }\n\n // On completion, push to completionQueue\n let resolveInFlight!: () => void;\n const completionPromise = new Promise<void>(r => { resolveInFlight = r; });\n\n const flight: InFlightTransition = {\n promise: completionPromise,\n context,\n consumed,\n startMs: performance.now(),\n resolve: resolveInFlight,\n };\n\n actionPromise.then(\n () => {\n this.completionQueue.push(t);\n this.wakeUp();\n resolveInFlight();\n },\n (err) => {\n flight.error = err;\n this.completionQueue.push(t);\n this.wakeUp();\n resolveInFlight();\n },\n );\n\n this.inFlight.set(t, flight);\n this.inFlightFlags[tid] = 1;\n this.enabledFlags[tid] = 0;\n this.enabledTransitionCount--;\n this.enabledAtMs[tid] = -Infinity;\n }\n\n private updateBitmapAfterConsumption(tid: number): void {\n const pids = this.compiled.consumptionPlaceIds(tid);\n for (const pid of pids) {\n const place = this.compiled.place(pid);\n if (!this.marking.hasTokens(place)) {\n clearBit(this.markingBitmap, pid);\n }\n this.markDirty(pid);\n }\n }\n\n // ======================== Completion Processing ========================\n\n private processCompletedTransitions(): void {\n if (this.completionQueue.length === 0) return;\n // In-place iteration is safe: processing is synchronous and .push() only\n // happens from microtasks which cannot interleave within this loop.\n const len = this.completionQueue.length;\n for (let i = 0; i < len; i++) {\n const t = this.completionQueue[i]!;\n const flight = this.inFlight.get(t);\n if (!flight) continue;\n this.inFlight.delete(t);\n\n const tid = this.compiled.transitionId(t);\n this.inFlightFlags[tid] = 0;\n\n if (flight.error) {\n const err = flight.error instanceof Error\n ? flight.error\n : new Error(String(flight.error));\n this.emitEvent({\n type: 'transition-failed',\n timestamp: Date.now(),\n transitionName: t.name,\n errorMessage: err.message,\n exceptionType: err.name,\n stack: err.stack,\n });\n this.markTransitionDirty(tid);\n continue;\n }\n\n try {\n const outputs = flight.context.rawOutput();\n\n // Validate output against spec\n if (t.outputSpec !== null) {\n const produced = outputs.placesWithTokens();\n const claim = validateOutSpec(t.name, t.outputSpec, produced);\n // IO-016 AC4: a spec names a place once; several tokens into a named place\n // pass validation (IO-015 reads the produced SET) but exceed what every\n // branch-enumerating analysis models. Cheap test first: a repeat exists\n // iff there are more entries than distinct places.\n if (outputs.entries().length > produced.size) this.warnMultiplicity(t.name, outputs, claim);\n }\n\n // Single pass: add tokens to marking, update bitmap, and emit events\n const produced: Token<any>[] = [];\n for (const entry of outputs.entries()) {\n const pid = this.compiled.tryPlaceId(entry.place);\n this.marking.addToken(entry.place, entry.token);\n produced.push(entry.token);\n if (pid !== undefined) {\n this.cacheAddToken(pid, entry.token);\n setBit(this.markingBitmap, pid);\n this.markDirty(pid);\n } else {\n // Unknown place — retained in the Marking (CORE-072 AC3), no bits to update.\n this.warnUnknownPlace(entry.place, t.name);\n }\n this.emitEvent({\n type: 'token-added',\n timestamp: Date.now(),\n placeName: entry.place.name,\n token: entry.token,\n });\n }\n this.markTransitionDirty(tid);\n\n this.emitEvent({\n type: 'transition-completed',\n timestamp: Date.now(),\n transitionName: t.name,\n producedTokens: produced,\n durationMs: performance.now() - flight.startMs,\n });\n } catch (e) {\n const err = e instanceof Error ? e : new Error(String(e));\n this.emitEvent({\n type: 'transition-failed',\n timestamp: Date.now(),\n transitionName: t.name,\n errorMessage: err.message,\n exceptionType: err.name,\n stack: err.stack,\n });\n this.markTransitionDirty(tid);\n }\n }\n this.completionQueue.length = 0;\n }\n\n // ======================== External Events ========================\n\n private processExternalEvents(): void {\n if (this.externalQueue.length === 0) return;\n if (this.closed) return; // ENV-013: leave queued events for drainPendingExternalEvents()\n // In-place iteration is safe: processing is synchronous and .push() only\n // happens from microtasks which cannot interleave within this loop.\n const len = this.externalQueue.length;\n for (let i = 0; i < len; i++) {\n const event = this.externalQueue[i]!;\n try {\n const pid = this.compiled.tryPlaceId(event.place);\n this.marking.addToken(event.place, event.token);\n if (pid !== undefined) {\n this.cacheAddToken(pid, event.token);\n setBit(this.markingBitmap, pid);\n this.markDirty(pid);\n } else {\n // Unknown place — retained in the Marking (CORE-072 AC3), no bits to update.\n this.warnUnknownPlace(event.place, '');\n }\n\n this.emitEvent({\n type: 'token-added',\n timestamp: Date.now(),\n placeName: event.place.name,\n token: event.token,\n });\n event.resolve(true);\n } catch (e) {\n event.reject(e instanceof Error ? e : new Error(String(e)));\n }\n }\n this.externalQueue.length = 0;\n }\n\n private drainPendingExternalEvents(): void {\n while (this.externalQueue.length > 0) {\n this.externalQueue.shift()!.resolve(false);\n }\n }\n\n // ======================== Await Work ========================\n\n /**\n * Suspends the executor until work is available. Composes up to 3 promise sources\n * into a single Promise.race: (1) any in-flight action completing, (2) external\n * event injection via wakeUp(), (3) timer for the next delayed transition's earliest\n * firing time. This avoids busy-waiting while remaining responsive to all event types.\n *\n * **Microtask flush**: Before building Promise.race, yields via `await Promise.resolve()`\n * to drain the microtask queue. Sync actions complete via `.then()` microtask; this\n * yield lets those fire, avoiding ~5 allocations when work is already available.\n * After the yield, re-checks queues and `this.closed` for close-during-yield safety.\n */\n private async awaitWork(): Promise<void> {\n // When closed, ignore external queue — processExternalEvents() won't consume it,\n // and drainPendingExternalEvents() handles it after the loop exits.\n if (this.completionQueue.length > 0 || (!this.closed && this.externalQueue.length > 0)) return;\n\n // Flush microtask queue: sync actions complete via .then() which schedules a\n // microtask. A single await here lets those fire before we build a full\n // Promise.race (~5 allocations). For async workloads this adds ~0.05us.\n await Promise.resolve();\n if (this.completionQueue.length > 0 || (!this.closed && this.externalQueue.length > 0)) return;\n // ENV-013: when closed with no in-flight, exit immediately for shouldTerminate()\n if (this.closed && this.inFlight.size === 0) return;\n\n const promises = this.awaitPromises;\n promises.length = 0;\n\n // 1. Any in-flight action completing (reuse array to avoid 2 intermediate allocations)\n if (this.inFlight.size > 0) {\n const arr = this.inFlightPromises;\n arr.length = 0;\n for (const f of this.inFlight.values()) arr.push(f.promise);\n promises.push(Promise.race(arr));\n }\n\n // When closed, only wait for in-flight completions — skip event/timer promises\n if (!this.closed) {\n // Zero means a timing boundary is already due: an earliest firing time has\n // been reached, or a deadline needs enforcing. There is nothing to wait for,\n // and with no action in flight the race below would hold only the external\n // wake-up promise — which a net with no environment places has nobody to\n // resolve, so the loop would sleep until its run budget expired. Return and\n // let the next cycle act on the boundary. Rust reaches the same outcome via\n // sleep(0); Java returns early on `millisUntilNextTimedTransition() <= 0`.\n const timerMs = this.millisUntilNextTimedTransition();\n if (timerMs === 0 && promises.length === 0) return;\n\n // 2. External event wake-up\n promises.push(new Promise<void>(resolve => { this.wakeUpResolve = resolve; }));\n\n // 3. Timer for next delayed transition\n if (timerMs > 0 && timerMs < Infinity) {\n promises.push(new Promise<void>(r => setTimeout(r, timerMs)));\n }\n }\n\n if (promises.length > 0) {\n await Promise.race(promises);\n }\n this.wakeUpResolve = null;\n }\n\n private millisUntilNextTimedTransition(): number {\n const nowMs = performance.now();\n let minWaitMs = Infinity;\n\n for (let tid = 0; tid < this.compiled.transitionCount; tid++) {\n if (!this.enabledFlags[tid]) continue;\n const t = this.compiled.transition(tid);\n const enabledMs = this.enabledAtMs[tid]!;\n const elapsedMs = nowMs - enabledMs;\n\n // Time until earliest firing\n const earliestMs = timingEarliest(t.timing);\n const remainingEarliest = earliestMs - elapsedMs;\n if (remainingEarliest <= 0) return 0;\n minWaitMs = Math.min(minWaitMs, remainingEarliest);\n\n // Time until deadline expiry (must wake up to enforce deadline)\n if (timingHasDeadline(t.timing)) {\n const latestMs = timingLatest(t.timing);\n const remainingDeadline = latestMs - elapsedMs;\n if (remainingDeadline <= 0) return 0;\n minWaitMs = Math.min(minWaitMs, remainingDeadline);\n }\n }\n return minWaitMs;\n }\n\n private wakeUp(): void {\n this.wakeUpResolve?.();\n }\n\n // ======================== Dirty Set Helpers ========================\n\n /** Returns true if any transition needs re-evaluation. O(W) where W = ceil(transitions/32). */\n private hasDirtyBits(): boolean {\n for (let w = 0; w < this.dirtySet.length; w++) {\n if (this.dirtySet[w] !== 0) return true;\n }\n return false;\n }\n\n private markDirty(pid: number): void {\n const tids = this.compiled.affectedTransitions(pid);\n for (const tid of tids) {\n this.markTransitionDirty(tid);\n }\n }\n\n private markTransitionDirty(tid: number): void {\n this.dirtySet[tid >>> WORD_SHIFT]! |= (1 << (tid & BIT_MASK));\n }\n\n // ======================== State Inspection ========================\n\n getMarking(): Marking { return this.marking; }\n\n /** Builds a snapshot of the current marking for event emission. */\n private snapshotMarking(): ReadonlyMap<string, readonly Token<any>[]> {\n const snap = new Map<string, readonly Token<any>[]>();\n for (let pid = 0; pid < this.compiled.placeCount; pid++) {\n const p = this.compiled.place(pid);\n const tokens = this.marking.peekTokens(p);\n if (tokens.length > 0) {\n snap.set(p.name, [...tokens]);\n }\n }\n return snap;\n }\n\n isQuiescent(): boolean {\n return this.enabledTransitionCount === 0 && this.inFlight.size === 0;\n }\n\n executionId(): string {\n return this.startMs.toString(16);\n }\n\n drain(): void {\n this.draining = true;\n this.wakeUp();\n }\n\n close(): void {\n this.draining = true;\n this.closed = true;\n this.wakeUp();\n }\n\n // ======================== Event Emission ========================\n\n /**\n * Reports an undeclared place once (CORE-072 AC4, emitted as the EVT-013\n * log-message event). `transitionName` is the producer, empty at the\n * initial-marking and injection seams. Retention never depends on this.\n */\n private warnUnknownPlace(place: Place<any>, transitionName: string): void {\n if (this.warnedUnknownPlaces.has(place.name)) return;\n this.warnedUnknownPlaces.add(place.name);\n this.emitEvent({\n type: 'log-message',\n timestamp: Date.now(),\n transitionName,\n logger: 'libpetri.runtime',\n level: 'WARN',\n message: `unknown place '${place.name}': tokens are retained in the marking but inert `\n + '(the net declares no arc on it)',\n error: null,\n errorMessage: null,\n });\n }\n\n /**\n * Reports, once per transition, a firing that wrote more than one token to a place\n * its output spec names once (IO-016 AC4), as the EVT-013 log-message event. The\n * tokens are deposited regardless: the diagnostic makes the under-approximation\n * every branch-enumerating analysis makes of this transition visible.\n */\n private warnMultiplicity(transitionName: string, outputs: TokenOutput, claim: ReadonlySet<string>): void {\n if (this.warnedMultiplicity.has(transitionName)) return;\n const counts = new Map<string, number>();\n for (const entry of outputs.entries()) {\n if (claim.has(entry.place.name)) counts.set(entry.place.name, (counts.get(entry.place.name) ?? 0) + 1);\n }\n const repeated: string[] = [];\n for (const [name, n] of counts) if (n > 1) repeated.push(`${name}: ${n}`);\n if (repeated.length === 0) return;\n this.warnedMultiplicity.add(transitionName);\n this.emitEvent({\n type: 'log-message',\n timestamp: Date.now(),\n transitionName,\n logger: 'libpetri.runtime',\n level: 'WARN',\n message: `'${transitionName}': wrote more than one token to a place its output spec names once `\n + `(${repeated.join(', ')}); branch-enumerating analyses model one token per named place, `\n + 'so this firing exceeds what they explore (IO-016)',\n error: null,\n errorMessage: null,\n });\n }\n\n private emitEvent(event: NetEvent): void {\n if (this.eventStoreEnabled) {\n // A user EventStore.append that throws is observation failing, not control flow:\n // swallow it so a hostile store cannot unwind the orchestrator loop. One choke\n // point covers every emit site.\n try {\n this.eventStore.append(event);\n } catch (err) {\n swallowEventStoreFailure(event.type, err);\n }\n }\n }\n}\n\n/** Internal sentinel for timeout detection. */\nclass TimeoutSentinel extends Error {\n constructor() { super('action timeout'); this.name = 'TimeoutSentinel'; }\n}\n","/**\n * @module precompiled-net\n *\n * Flat-array precompiled representation of a PetriNet for high-performance execution.\n *\n * **Design**: Compiles from a `CompiledNet`, converting all per-transition data into\n * flat typed arrays indexed by transition ID (tid) or place ID (pid). Eliminates Map\n * lookups and object traversals from the hot path.\n *\n * **Sparse enablement**: Each transition's needs/inhibitor masks are classified as\n * empty (-2), single-word (>=0), or multi-word (-1). Single-word masks avoid inner\n * loops entirely; multi-word uses precomputed sparse indices to skip zero words.\n *\n * **Opcode programs**: Input consumption is compiled to compact opcode sequences\n * (CONSUME_ONE, CONSUME_N, CONSUME_ALL, CONSUME_ATLEAST, RESET) that the executor\n * dispatches without inspecting In spec objects.\n *\n * @see CompiledNet for the base bitmap representation\n * @see PrecompiledNetExecutor for the executor that uses this representation\n */\nimport type { PetriNet } from '../core/petri-net.js';\nimport type { Place } from '../core/place.js';\nimport type { Transition } from '../core/transition.js';\nimport type { Out } from '../core/out.js';\nimport { CompiledNet, WORD_SHIFT, BIT_MASK } from './compiled-net.js';\nimport type { CardinalityCheck } from './compiled-net.js';\nimport { earliest as timingEarliest, latest as timingLatest, hasDeadline as timingHasDeadline } from '../core/timing.js';\n\n// ==================== Opcodes ====================\n\n/** Consume exactly 1 token from place. Next word: pid. */\nexport const CONSUME_ONE = 0;\n/** Consume exactly N tokens. Next words: pid, count. */\nexport const CONSUME_N = 1;\n/** Consume all tokens. Next word: pid. */\nexport const CONSUME_ALL = 2;\n/** Consume at-least N tokens (consumes all). Next words: pid, minimum. */\nexport const CONSUME_ATLEAST = 3;\n/** Reset (clear all tokens). Next word: pid. */\nexport const RESET = 4;\n\n/** Sparse mask classification: no bits set. */\nconst SPARSE_EMPTY = -2;\n/** Sparse mask classification: bits span multiple words. */\nconst SPARSE_MULTI = -1;\n\n/**\n * Immutable precompiled representation of a Petri net.\n *\n * All data is stored in flat typed arrays indexed by tid/pid for cache-friendly,\n * branch-free access on the hot path. Compiled once, reused across executions.\n */\nexport class PrecompiledNet {\n // ==================== Identity ====================\n readonly compiled: CompiledNet;\n readonly placeCount: number;\n readonly transitionCount: number;\n readonly wordCount: number;\n\n // ==================== Place Cache ====================\n /** Places indexed by pid — avoids compiled.place(pid) indirection on hot path. */\n readonly places: readonly Place<any>[];\n\n // ==================== Opcode Programs ====================\n /** Per-transition consume opcode sequences. */\n readonly consumeOps: readonly (readonly number[])[];\n /**\n * Per-transition index into {@link consumeOps} where the RESET tail begins; the\n * executor peeks read arcs at this boundary so reads observe the post-input,\n * pre-reset marking (EXEC-013 AC4).\n */\n readonly resetOpsStart: Uint32Array;\n /** Per-transition read-arc place IDs. */\n readonly readOps: readonly (readonly number[])[];\n\n // ==================== Enablement Masks ====================\n readonly needsMask: readonly Uint32Array[];\n readonly inhibitorMask: readonly Uint32Array[];\n\n // ==================== Sparse Enablement (PERF-042) ====================\n readonly needsSingleWordIndex: Int8Array;\n readonly needsSingleWordMask: Uint32Array;\n readonly needsSparseIndices: readonly (readonly number[])[];\n readonly needsSparseMasks: readonly (readonly number[])[];\n\n readonly inhibitorSingleWordIndex: Int8Array;\n readonly inhibitorSingleWordMask: Uint32Array;\n readonly inhibitorSparseIndices: readonly (readonly number[])[];\n readonly inhibitorSparseMasks: readonly (readonly number[])[];\n\n // ==================== Timing (CONC-024) ====================\n readonly earliestMs: Float64Array;\n readonly latestMs: Float64Array;\n readonly hasDeadline: Uint8Array;\n /**\n * 1 for `exact()` transitions. Exact transitions fire at the first opportunity at/after their\n * target time (delayed-style liveness) and are never force-disabled by deadline enforcement —\n * their upper bound is observed, not enforced. See TIME-006.\n */\n readonly isExact: Uint8Array;\n\n // ==================== Priority (CONC-023) ====================\n readonly priorities: Int32Array;\n readonly transitionToPriorityIndex: Uint32Array;\n readonly priorityLevels: readonly number[];\n readonly distinctPriorityCount: number;\n\n // ==================== Output Fast Path ====================\n /** -2=no spec, -1=complex, >=0=single output place ID. */\n readonly simpleOutputPlaceId: Int32Array;\n\n // ==================== Input Precomputation ====================\n readonly inputPlaceCount: Uint32Array;\n readonly inputPlaceMaskWords: readonly Uint32Array[];\n\n // ==================== Reverse Index ====================\n readonly placeToTransitions: readonly (readonly number[])[];\n readonly consumptionPlaceIds: readonly (readonly number[])[];\n\n // ==================== Cardinality ====================\n readonly cardinalityChecks: readonly (CardinalityCheck | null)[];\n // ν-net join flag (NU-020): gates the match-binding check off the hot\n // enablement path for non-ν transitions.\n readonly hasMatch: readonly boolean[];\n\n // ==================== Global Flags ====================\n readonly allImmediate: boolean;\n readonly allSamePriority: boolean;\n readonly anyDeadlines: boolean;\n\n private constructor(compiled: CompiledNet) {\n this.compiled = compiled;\n this.placeCount = compiled.placeCount;\n this.transitionCount = compiled.transitionCount;\n this.wordCount = compiled.wordCount;\n\n const tc = compiled.transitionCount;\n const wc = compiled.wordCount;\n\n // Cache place references\n const places: Place<any>[] = new Array(this.placeCount);\n for (let pid = 0; pid < this.placeCount; pid++) {\n places[pid] = compiled.place(pid);\n }\n this.places = places;\n\n // Copy masks from CompiledNet\n const needsMask: Uint32Array[] = new Array(tc);\n const inhibitorMask: Uint32Array[] = new Array(tc);\n for (let tid = 0; tid < tc; tid++) {\n // Access via canEnableBitmap internals — copy the mask arrays\n // We need to extract them; use the CompiledNet's accessor pattern\n needsMask[tid] = new Uint32Array(wc);\n inhibitorMask[tid] = new Uint32Array(wc);\n }\n\n // Build needs/inhibitor masks by probing CompiledNet\n // We reconstruct from transition arc specs since CompiledNet doesn't expose raw masks\n for (let tid = 0; tid < tc; tid++) {\n const t = compiled.transition(tid);\n const needs = needsMask[tid]!;\n const inhibitors = inhibitorMask[tid]!;\n\n for (const inSpec of t.inputSpecs) {\n const pid = compiled.placeId(inSpec.place);\n needs[pid >>> WORD_SHIFT]! |= (1 << (pid & BIT_MASK));\n }\n for (const arc of t.reads) {\n const pid = compiled.placeId(arc.place);\n needs[pid >>> WORD_SHIFT]! |= (1 << (pid & BIT_MASK));\n }\n for (const arc of t.inhibitors) {\n const pid = compiled.placeId(arc.place);\n inhibitors[pid >>> WORD_SHIFT]! |= (1 << (pid & BIT_MASK));\n }\n }\n this.needsMask = needsMask;\n this.inhibitorMask = inhibitorMask;\n\n // ==================== Sparse Enablement ====================\n this.needsSingleWordIndex = new Int8Array(tc);\n this.needsSingleWordMask = new Uint32Array(tc);\n const needsSparseIndices: number[][] = new Array(tc);\n const needsSparseMasks: number[][] = new Array(tc);\n\n this.inhibitorSingleWordIndex = new Int8Array(tc);\n this.inhibitorSingleWordMask = new Uint32Array(tc);\n const inhibitorSparseIndices: number[][] = new Array(tc);\n const inhibitorSparseMasks: number[][] = new Array(tc);\n\n for (let tid = 0; tid < tc; tid++) {\n compileSparse(needsMask[tid]!, wc,\n this.needsSingleWordIndex, this.needsSingleWordMask,\n needsSparseIndices, needsSparseMasks, tid);\n compileSparse(inhibitorMask[tid]!, wc,\n this.inhibitorSingleWordIndex, this.inhibitorSingleWordMask,\n inhibitorSparseIndices, inhibitorSparseMasks, tid);\n }\n this.needsSparseIndices = needsSparseIndices;\n this.needsSparseMasks = needsSparseMasks;\n this.inhibitorSparseIndices = inhibitorSparseIndices;\n this.inhibitorSparseMasks = inhibitorSparseMasks;\n\n // ==================== Opcode Programs ====================\n const consumeOps: number[][] = new Array(tc);\n const readOps: number[][] = new Array(tc);\n this.resetOpsStart = new Uint32Array(tc);\n for (let tid = 0; tid < tc; tid++) {\n const t = compiled.transition(tid);\n const program = compileConsumeProgram(t, compiled);\n consumeOps[tid] = program.ops;\n this.resetOpsStart[tid] = program.resetOpsStart;\n readOps[tid] = compileReadProgram(t, compiled);\n }\n this.consumeOps = consumeOps;\n this.readOps = readOps;\n\n // ==================== Reverse Index & Consumption ====================\n const placeToTransitions: number[][] = new Array(this.placeCount);\n const consumptionPlaceIds: number[][] = new Array(tc);\n for (let pid = 0; pid < this.placeCount; pid++) {\n placeToTransitions[pid] = [...compiled.affectedTransitions(pid)];\n }\n for (let tid = 0; tid < tc; tid++) {\n consumptionPlaceIds[tid] = [...compiled.consumptionPlaceIds(tid)];\n }\n this.placeToTransitions = placeToTransitions;\n this.consumptionPlaceIds = consumptionPlaceIds;\n\n // ==================== Cardinality ====================\n const cardinalityChecks: (CardinalityCheck | null)[] = new Array(tc);\n const hasMatch: boolean[] = new Array(tc);\n for (let tid = 0; tid < tc; tid++) {\n cardinalityChecks[tid] = compiled.cardinalityCheck(tid);\n hasMatch[tid] = compiled.hasMatch(tid);\n }\n this.cardinalityChecks = cardinalityChecks;\n this.hasMatch = hasMatch;\n\n // ==================== Timing ====================\n this.earliestMs = new Float64Array(tc);\n this.latestMs = new Float64Array(tc);\n this.hasDeadline = new Uint8Array(tc);\n this.isExact = new Uint8Array(tc);\n let anyDeadlines = false;\n let allImm = true;\n\n for (let tid = 0; tid < tc; tid++) {\n const t = compiled.transition(tid);\n this.earliestMs[tid] = timingEarliest(t.timing);\n this.latestMs[tid] = timingLatest(t.timing);\n if (timingHasDeadline(t.timing)) {\n this.hasDeadline[tid] = 1;\n anyDeadlines = true;\n }\n if (t.timing.type === 'exact') this.isExact[tid] = 1;\n if (t.timing.type !== 'immediate') allImm = false;\n }\n this.anyDeadlines = anyDeadlines;\n this.allImmediate = allImm;\n\n // ==================== Priority ====================\n this.priorities = new Int32Array(tc);\n const prioritySet = new Set<number>();\n const firstPriority = tc > 0 ? compiled.transition(0).priority : 0;\n let samePrio = true;\n\n for (let tid = 0; tid < tc; tid++) {\n const p = compiled.transition(tid).priority;\n this.priorities[tid] = p;\n prioritySet.add(p);\n if (p !== firstPriority) samePrio = false;\n }\n this.allSamePriority = samePrio;\n\n // Sort priorities descending\n const levels = [...prioritySet].sort((a, b) => b - a);\n this.priorityLevels = levels;\n this.distinctPriorityCount = levels.length;\n\n // Map tid -> priority queue index\n this.transitionToPriorityIndex = new Uint32Array(tc);\n const levelIndex = new Map<number, number>();\n for (let i = 0; i < levels.length; i++) {\n levelIndex.set(levels[i]!, i);\n }\n for (let tid = 0; tid < tc; tid++) {\n this.transitionToPriorityIndex[tid] = levelIndex.get(this.priorities[tid]!)!;\n }\n\n // ==================== Output Fast Path ====================\n this.simpleOutputPlaceId = new Int32Array(tc);\n for (let tid = 0; tid < tc; tid++) {\n const t = compiled.transition(tid);\n if (t.outputSpec === null) {\n this.simpleOutputPlaceId[tid] = -2; // no spec\n } else {\n const simplePid = simpleOutputPlace(t.outputSpec, compiled);\n this.simpleOutputPlaceId[tid] = simplePid;\n }\n }\n\n // ==================== Input Precomputation ====================\n this.inputPlaceCount = new Uint32Array(tc);\n const inputPlaceMaskWords: Uint32Array[] = new Array(tc);\n for (let tid = 0; tid < tc; tid++) {\n const t = compiled.transition(tid);\n this.inputPlaceCount[tid] = t.inputSpecs.length + t.reads.length;\n const mask = new Uint32Array(wc);\n for (const spec of t.inputSpecs) {\n const pid = compiled.placeId(spec.place);\n mask[pid >>> WORD_SHIFT]! |= (1 << (pid & BIT_MASK));\n }\n inputPlaceMaskWords[tid] = mask;\n }\n this.inputPlaceMaskWords = inputPlaceMaskWords;\n }\n\n // ==================== Factory Methods ====================\n\n static compile(net: PetriNet): PrecompiledNet {\n return new PrecompiledNet(CompiledNet.compile(net));\n }\n\n static compileFrom(compiled: CompiledNet): PrecompiledNet {\n return new PrecompiledNet(compiled);\n }\n\n // ==================== Sparse Enablement Check ====================\n\n /**\n * Three-case sparse enablement check:\n * 1. Empty mask (needsSingleWordIndex == -2): always passes\n * 2. Single-word mask (>=0): one comparison\n * 3. Multi-word mask (-1): iterate precomputed sparse indices\n */\n canEnableSparse(tid: number, snapshot: Uint32Array): boolean {\n // Check needs mask\n const needsIdx = this.needsSingleWordIndex[tid]!;\n if (needsIdx === SPARSE_EMPTY) {\n // No needs — passes\n } else if (needsIdx >= 0) {\n // Single word\n const m = this.needsSingleWordMask[tid]!;\n if (((snapshot[needsIdx]! & m) >>> 0) !== m) return false;\n } else {\n // Multi-word sparse\n const indices = this.needsSparseIndices[tid]!;\n const masks = this.needsSparseMasks[tid]!;\n for (let i = 0; i < indices.length; i++) {\n const m = masks[i]!;\n if (((snapshot[indices[i]!]! & m) >>> 0) !== m) return false;\n }\n }\n\n // Check inhibitor mask\n const inhIdx = this.inhibitorSingleWordIndex[tid]!;\n if (inhIdx === SPARSE_EMPTY) {\n return true; // No inhibitors\n } else if (inhIdx >= 0) {\n return (snapshot[inhIdx]! & this.inhibitorSingleWordMask[tid]!) === 0;\n } else {\n const indices = this.inhibitorSparseIndices[tid]!;\n const masks = this.inhibitorSparseMasks[tid]!;\n for (let i = 0; i < indices.length; i++) {\n if ((snapshot[indices[i]!]! & masks[i]!) !== 0) return false;\n }\n return true;\n }\n }\n}\n\n// ==================== Compilation Helpers ====================\n\nfunction compileSparse(\n mask: Uint32Array,\n wordCount: number,\n singleWordIndex: Int8Array,\n singleWordMask: Uint32Array,\n sparseIndices: number[][],\n sparseMasks: number[][],\n tid: number,\n): void {\n let nonZeroCount = 0;\n let lastNonZeroWord = -1;\n\n for (let w = 0; w < wordCount; w++) {\n if (mask[w] !== 0) {\n nonZeroCount++;\n lastNonZeroWord = w;\n }\n }\n\n if (nonZeroCount === 0) {\n singleWordIndex[tid] = SPARSE_EMPTY;\n singleWordMask[tid] = 0;\n sparseIndices[tid] = [];\n sparseMasks[tid] = [];\n } else if (nonZeroCount === 1) {\n singleWordIndex[tid] = lastNonZeroWord;\n singleWordMask[tid] = mask[lastNonZeroWord]!;\n sparseIndices[tid] = [];\n sparseMasks[tid] = [];\n } else {\n singleWordIndex[tid] = SPARSE_MULTI;\n singleWordMask[tid] = 0;\n const idx: number[] = [];\n const msk: number[] = [];\n for (let w = 0; w < wordCount; w++) {\n if (mask[w] !== 0) {\n idx.push(w);\n msk.push(mask[w]!);\n }\n }\n sparseIndices[tid] = idx;\n sparseMasks[tid] = msk;\n }\n}\n\nfunction compileConsumeProgram(\n t: Transition,\n compiled: CompiledNet,\n): { ops: number[]; resetOpsStart: number } {\n const ops: number[] = [];\n\n for (const spec of t.inputSpecs) {\n const pid = compiled.placeId(spec.place);\n switch (spec.type) {\n case 'one':\n ops.push(CONSUME_ONE, pid);\n break;\n case 'exactly':\n ops.push(CONSUME_N, pid, spec.count);\n break;\n case 'all':\n ops.push(CONSUME_ALL, pid);\n break;\n case 'at-least':\n ops.push(CONSUME_ATLEAST, pid, spec.minimum);\n break;\n }\n }\n\n // RESET opcodes are compiled after all input opcodes; the boundary lets the\n // executor peek read arcs before resets drain (EXEC-013).\n const resetOpsStart = ops.length;\n for (const arc of t.resets) {\n const pid = compiled.placeId(arc.place);\n ops.push(RESET, pid);\n }\n\n return { ops, resetOpsStart };\n}\n\nfunction compileReadProgram(t: Transition, compiled: CompiledNet): number[] {\n const pids: number[] = [];\n for (const arc of t.reads) {\n pids.push(compiled.placeId(arc.place));\n }\n return pids;\n}\n\nfunction simpleOutputPlace(spec: Out, compiled: CompiledNet): number {\n if (spec.type === 'place') {\n return compiled.placeId(spec.place);\n }\n return -1; // complex\n}\n","/**\n * @module precompiled-net-executor\n *\n * High-performance executor for Typed Coloured Time Petri Nets.\n *\n * **Architecture**: Uses `PrecompiledNet` for all transition/place data, replacing\n * Map lookups and object traversals with typed-array indexing. Token storage uses\n * simple per-place arrays, leveraging V8's optimized small-array shift/push.\n *\n * **Execution loop**: Same 5-phase structure as `BitmapNetExecutor`:\n * 1. Process completed transitions — drain completionQueue, validate outputs\n * 2. Process external events — inject tokens from EnvironmentPlaces\n * 3. Update dirty transitions — sparse enablement via `canEnableSparse()`\n * 4. Enforce deadlines — gated by `anyDeadlines` flag\n * 5. Fire ready transitions — opcode dispatch or priority-queue path\n *\n * **Key optimizations over BitmapNetExecutor**:\n * - Opcode-based consumption (switch on int vs object dispatch)\n * - Cached place references (avoids compiled.place(pid) indirection)\n * - Sparse enablement masks (skip zero words)\n * - Lazy Marking sync (arrays are sole source of truth during execution)\n * - Flat-array in-flight tracking (no Map overhead)\n *\n * @see PrecompiledNet for the precompiled data representation\n * @see BitmapNetExecutor for the reference implementation\n */\nimport type { PetriNet } from '../core/petri-net.js';\nimport type { Place, EnvironmentPlace } from '../core/place.js';\nimport type { Token } from '../core/token.js';\nimport type { Transition } from '../core/transition.js';\nimport type { EventStore } from '../event/event-store.js';\nimport type { NetEvent } from '../event/net-event.js';\nimport type { PetriNetExecutor, RunTimeoutPolicy } from './petri-net-executor.js';\nimport { tokenOf } from '../core/token.js';\nimport { TokenInput } from '../core/token-input.js';\nimport { TokenOutput } from '../core/token-output.js';\nimport { TransitionContext } from '../core/transition-context.js';\nimport { noopEventStore } from '../event/event-store.js';\nimport { WORD_SHIFT, BIT_MASK } from './compiled-net.js';\nimport { Marking } from './marking.js';\nimport { PrecompiledNet, CONSUME_ONE, CONSUME_N, CONSUME_ALL, CONSUME_ATLEAST, RESET } from './precompiled-net.js';\nimport { validateOutSpec, produceTimeoutOutput, executeAction, swallowEventStoreFailure, DEADLINE_TOLERANCE_MS } from './executor-support.js';\nimport { OutViolationError } from './out-violation-error.js';\nimport { findBinding, IncrementalMatcher } from './match-engine.js';\nimport { keyForPlace } from '../core/match-spec.js';\nimport { nameId, type NameId } from '../core/name.js';\n\n// ==================== Types ====================\n\ninterface ExternalEvent<T = any> {\n place: Place<T>;\n token: Token<T>;\n resolve: (value: boolean) => void;\n reject: (err: Error) => void;\n}\n\n/** Retained tokens for one undeclared place, keyed by name (CORE-072). */\ninterface UnknownPlaceTokens {\n place: Place<any>;\n tokens: Token<any>[];\n}\n\nexport interface PrecompiledNetExecutorOptions {\n eventStore?: EventStore;\n environmentPlaces?: Set<EnvironmentPlace<any>>;\n executionContextProvider?: (transitionName: string, consumed: Token<any>[]) => Map<string, unknown>;\n /** Skip output spec validation for trusted actions (CONC-026). */\n skipOutputValidation?: boolean;\n /** Reuse a precompiled program (avoids recompilation). */\n program?: PrecompiledNet;\n /**\n * Grace band (ms) beyond a hard deadline (`deadline()` / `window()`) before a transition is\n * force-disabled with a `transition-timed-out` event (TIME-013). Defaults to {@link DEADLINE_TOLERANCE_MS}\n * (5ms); `0` gives strict enforcement. Must be non-negative. Does not affect `exact()` transitions,\n * which are enforced softly (TIME-006).\n */\n deadlineToleranceMs?: number;\n}\n\n/**\n * High-performance executor using `PrecompiledNet`.\n *\n * Implements `PetriNetExecutor` with the same semantics as `BitmapNetExecutor`\n * but with flat-array optimizations for lower per-transition overhead.\n */\nexport class PrecompiledNetExecutor implements PetriNetExecutor {\n private readonly program: PrecompiledNet;\n private readonly eventStore: EventStore;\n private readonly environmentPlaces: Set<string>;\n private readonly hasEnvironmentPlaces: boolean;\n private readonly executionContextProvider?: (transitionName: string, consumed: Token<any>[]) => Map<string, unknown>;\n private readonly skipOutputValidation: boolean;\n private readonly deadlineToleranceMs: number;\n private readonly startMs: number;\n private readonly eventStoreEnabled: boolean;\n\n // ==================== Token Storage ====================\n /** Per-place token arrays, indexed by pid. */\n private readonly tokenQueues: Token<any>[][];\n /**\n * Tokens on places the compiled net does not know (CORE-072 AC3). Retained —\n * never dropped — and merged into the materialized marking, matching the\n * BitmapNetExecutor reference, whose Marking keeps them naturally. Keyed by\n * place NAME (TS Place identity is name-based), carrying the Place so\n * materializing a Marking has one to hand.\n */\n private readonly unknownPlaceTokens = new Map<string, UnknownPlaceTokens>();\n /** Transitions already warned for writing several tokens to a place their spec names once (IO-016 AC4). */\n private readonly warnedMultiplicity = new Set<string>();\n /** Monotonic source for ν-name minting (ctx.freshName(), NU-010). */\n private freshNameCounter = 0;\n /**\n * Per-transition ν-name minter cache, indexed by tid (built lazily). Each\n * supplier is created once and reused across firings, so installing it on a\n * per-fire context is a field assignment rather than a per-fire closure\n * allocation — keeping the fire path lean for non-ν transitions. Every\n * transition gets one (forks mint but carry no MatchSpec, so gating on\n * `hasMatch` would wrongly starve them).\n */\n private readonly freshNameSuppliers: (() => NameId)[] = [];\n\n // ==================== ν-net incremental match caches (NU-020) ====================\n /**\n * Per matched transition: an {@link IncrementalMatcher} kept in lockstep with\n * the token queues when the transition is fast-path eligible (every correlated\n * input is `one`/`exactly`, consumed by no other transition, and never reset),\n * else `null` → fall back to the O(n) rebuild {@link findBinding}. This turns a\n * draining matched join from O(n²) into O(n log n).\n */\n private matchCaches: (IncrementalMatcher | null)[] = [];\n /** Per place (by pid): the `[tid, keyIndex]` of every fast-path correlated input it feeds. */\n private placeMatchTargets: Array<Array<[number, number]>> = [];\n\n // ==================== Marking Bitmap ====================\n private readonly markingBitmap: Uint32Array;\n\n // ==================== Transition State ====================\n private readonly dirtyBitmap: Uint32Array;\n private readonly dirtyScanBuffer: Uint32Array;\n private readonly enabledAtMs: Float64Array;\n private readonly inFlightFlags: Uint8Array;\n private readonly enabledFlags: Uint8Array;\n private readonly transitionWords: number;\n\n // ==================== Enabled Count ====================\n private enabledTransitionCount = 0;\n\n // ==================== In-Flight Tracking ====================\n private readonly inFlightPromises: (Promise<void> | null)[];\n private readonly inFlightContexts: (TransitionContext | null)[];\n private readonly inFlightConsumed: (Token<any>[] | null)[];\n private readonly inFlightStartMs: Float64Array;\n private readonly inFlightResolves: ((() => void) | null)[];\n private readonly inFlightErrors: (unknown | null)[];\n private inFlightCount = 0;\n\n // ==================== Reset-Clock Detection ====================\n private readonly pendingResetWords: Uint32Array;\n private hasPendingResets = false;\n\n // ==================== Queues ====================\n private readonly completionQueue: number[] = [];\n private readonly externalQueue: ExternalEvent[] = [];\n private wakeUpResolve: (() => void) | null = null;\n\n // ==================== Reusable Buffers ====================\n private readonly markingSnapBuffer: Uint32Array;\n private readonly firingSnapBuffer: Uint32Array;\n private readonly awaitPromises: Promise<void>[] = [];\n private readonly racePromises: Promise<void>[] = [];\n\n // Pre-allocated buffer for fireReadyGeneral()\n private readonly readyBuffer: { tid: number; priority: number; enabledAtMs: number }[] = [];\n\n // ==================== Lifecycle ====================\n private running = false;\n private draining = false;\n private closed = false;\n\n // ==================== Lazy Marking ====================\n private marking: Marking | null = null;\n\n constructor(\n net: PetriNet,\n initialTokens: Map<Place<any>, Token<any>[]>,\n options: PrecompiledNetExecutorOptions = {},\n ) {\n this.program = options.program ?? PrecompiledNet.compile(net);\n this.eventStore = options.eventStore ?? noopEventStore();\n this.environmentPlaces = new Set(\n [...(options.environmentPlaces ?? [])].map(ep => ep.place.name)\n );\n this.hasEnvironmentPlaces = this.environmentPlaces.size > 0;\n this.executionContextProvider = options.executionContextProvider;\n this.skipOutputValidation = options.skipOutputValidation ?? false;\n this.deadlineToleranceMs = options.deadlineToleranceMs ?? DEADLINE_TOLERANCE_MS;\n if (this.deadlineToleranceMs < 0) {\n throw new Error(`Deadline tolerance must be non-negative: ${this.deadlineToleranceMs}`);\n }\n this.startMs = performance.now();\n this.eventStoreEnabled = this.eventStore.isEnabled();\n\n const prog = this.program;\n const pc = prog.placeCount;\n const tc = prog.transitionCount;\n const wc = prog.wordCount;\n\n // ==================== Token Queues ====================\n this.tokenQueues = new Array(pc);\n for (let pid = 0; pid < pc; pid++) {\n this.tokenQueues[pid] = [];\n }\n\n // Load initial tokens\n for (const [place, tokens] of initialTokens) {\n const pid = prog.compiled.tryPlaceId(place);\n if (pid === undefined) {\n // CORE-072: undeclared place — retain the tokens in a side store so\n // they reappear in the observable marking.\n for (let i = 0; i < tokens.length; i++) {\n this.retainUnknownToken(place, tokens[i]!, '');\n }\n continue;\n }\n const q = this.tokenQueues[pid]!;\n for (const token of tokens) {\n q.push(token);\n }\n }\n\n // ==================== Marking Bitmap ====================\n this.markingBitmap = new Uint32Array(wc);\n\n // ==================== Transition State ====================\n this.transitionWords = (tc + BIT_MASK) >>> WORD_SHIFT;\n this.dirtyBitmap = new Uint32Array(this.transitionWords);\n this.dirtyScanBuffer = new Uint32Array(this.transitionWords);\n this.enabledAtMs = new Float64Array(tc);\n this.enabledAtMs.fill(-Infinity);\n this.inFlightFlags = new Uint8Array(tc);\n this.enabledFlags = new Uint8Array(tc);\n\n // ==================== In-Flight Arrays ====================\n this.inFlightPromises = new Array(tc).fill(null);\n this.inFlightContexts = new Array(tc).fill(null);\n this.inFlightConsumed = new Array(tc).fill(null);\n this.inFlightStartMs = new Float64Array(tc);\n this.inFlightResolves = new Array(tc).fill(null);\n this.inFlightErrors = new Array(tc).fill(null);\n\n // ==================== Reset Detection ====================\n this.pendingResetWords = new Uint32Array(wc);\n\n // ==================== Snapshot Buffers ====================\n this.markingSnapBuffer = new Uint32Array(wc);\n this.firingSnapBuffer = new Uint32Array(wc);\n\n this.initMatchCaches();\n }\n\n /**\n * Builds the ν-net incremental match caches (NU-020). A matched join is\n * fast-path eligible only when every correlated input is `one`/`exactly`, is\n * consumed by no other transition, and is never reset — so tokens enter a\n * correlated input only via produce/inject (mirrored by `add`) and leave only\n * via this join's matched consume (mirrored by `consume`), and the cache can\n * never desync. Mirrors the Rust backends.\n */\n private initMatchCaches(): void {\n const prog = this.program;\n const tc = prog.transitionCount;\n const pc = prog.placeCount;\n this.matchCaches = new Array(tc).fill(null);\n this.placeMatchTargets = Array.from({ length: pc }, () => []);\n\n let anyMatch = false;\n for (let tid = 0; tid < tc; tid++) {\n if (prog.hasMatch[tid]) { anyMatch = true; break; }\n }\n if (!anyMatch) return;\n\n // Which transitions consume (input) or reset each place.\n const inputConsumers: number[][] = Array.from({ length: pc }, () => []);\n const resetTarget: boolean[] = new Array(pc).fill(false);\n for (let tid = 0; tid < tc; tid++) {\n const t = prog.compiled.transition(tid);\n for (const spec of t.inputSpecs) inputConsumers[prog.compiled.placeId(spec.place)]!.push(tid);\n for (const arc of t.resets) resetTarget[prog.compiled.placeId(arc.place)] = true;\n }\n\n for (let tid = 0; tid < tc; tid++) {\n if (!prog.hasMatch[tid]) continue;\n const t = prog.compiled.transition(tid);\n const ms = t.matchSpec;\n if (!ms) continue;\n\n const requireds: number[] = [];\n let eligible = true;\n for (const mk of ms.keys) {\n const pid = prog.compiled.placeId(mk.place);\n const spec = t.inputSpecs.find(s => s.place.name === mk.place.name);\n let required: number;\n if (spec?.type === 'one') required = 1;\n else if (spec?.type === 'exactly') required = spec.count;\n else { eligible = false; break; } // at-least/all: variable consume → fall back\n const cons = inputConsumers[pid]!;\n if (resetTarget[pid] || cons.length !== 1 || cons[0] !== tid) { eligible = false; break; }\n requireds.push(required);\n }\n if (!eligible) continue;\n\n const matcher = new IncrementalMatcher(requireds);\n for (let keyIdx = 0; keyIdx < ms.keys.length; keyIdx++) {\n const mk = ms.keys[keyIdx]!;\n const pid = prog.compiled.placeId(mk.place);\n for (const token of this.tokenQueues[pid]!) {\n const name = mk.key(token.value);\n if (name !== undefined && name !== null) matcher.add(keyIdx, name, token.createdAt);\n }\n this.placeMatchTargets[pid]!.push([tid, keyIdx]);\n }\n this.matchCaches[tid] = matcher;\n }\n }\n\n /** Mirror a token added to correlated input `pid` into every fast-path matcher. */\n private cacheAddToken(pid: number, token: Token<any>): void {\n const targets = this.placeMatchTargets[pid];\n if (targets === undefined || targets.length === 0) return;\n const prog = this.program;\n for (const [tid, keyIdx] of targets) {\n const cache = this.matchCaches[tid];\n if (cache == null) continue;\n const t = prog.compiled.transition(tid);\n const mk = t.matchSpec!.keys[keyIdx]!;\n const name = mk.key(token.value);\n if (name !== undefined && name !== null) cache.add(keyIdx, name, token.createdAt);\n }\n }\n\n // ======================== Bitmap Helpers ========================\n\n private markTransitionDirty(tid: number): void {\n this.dirtyBitmap[tid >>> WORD_SHIFT]! |= (1 << (tid & BIT_MASK));\n }\n\n private markDirty(pid: number): void {\n const tids = this.program.placeToTransitions[pid]!;\n for (let i = 0; i < tids.length; i++) {\n this.markTransitionDirty(tids[i]!);\n }\n }\n\n private setMarkingBit(pid: number): void {\n this.markingBitmap[pid >>> WORD_SHIFT]! |= (1 << (pid & BIT_MASK));\n }\n\n private clearMarkingBit(pid: number): void {\n this.markingBitmap[pid >>> WORD_SHIFT]! &= ~(1 << (pid & BIT_MASK));\n }\n\n // ======================== Execution ========================\n\n async run(timeoutMs?: number, onTimeout: RunTimeoutPolicy = 'abandon'): Promise<Marking> {\n if (timeoutMs === undefined) return this.executeLoop();\n\n let timer: ReturnType<typeof setTimeout> | undefined;\n let timedOut = false;\n const timeoutPromise = new Promise<never>((_, reject) => {\n timer = setTimeout(() => {\n timedOut = true;\n reject(new Error('Execution timed out'));\n }, timeoutMs);\n });\n // Held rather than inlined into the race: Promise.race walks away from the\n // loser, it does not cancel it, so the loop needs handling of its own.\n const loop = this.executeLoop();\n try {\n return await Promise.race([loop, timeoutPromise]);\n } finally {\n if (timer !== undefined) clearTimeout(timer);\n if (timedOut) {\n if (onTimeout === 'close') this.close();\n // Nobody is left to observe the abandoned loop's outcome.\n loop.catch(() => {});\n }\n }\n }\n\n private async executeLoop(): Promise<Marking> {\n this.running = true;\n const prog = this.program;\n\n this.emitEvent({\n type: 'execution-started',\n timestamp: Date.now(),\n netName: prog.compiled.net.name,\n executionId: this.executionId(),\n });\n\n this.initializeMarkingBitmap();\n this.markAllDirty();\n\n this.emitEvent({\n type: 'marking-snapshot',\n timestamp: Date.now(),\n marking: this.snapshotMarking(),\n });\n\n while (this.running) {\n this.processCompletedTransitions();\n this.processExternalEvents();\n this.updateDirtyTransitions();\n\n const cycleNowMs = performance.now();\n if (prog.anyDeadlines) this.enforceDeadlines(cycleNowMs);\n\n if (this.shouldTerminate()) break;\n\n this.fireReadyTransitions(cycleNowMs);\n if (this.hasDirtyBits()) continue;\n await this.awaitWork();\n }\n\n this.running = false;\n this.drainPendingExternalEvents();\n\n this.emitEvent({\n type: 'marking-snapshot',\n timestamp: Date.now(),\n marking: this.snapshotMarking(),\n });\n\n this.emitEvent({\n type: 'execution-completed',\n timestamp: Date.now(),\n netName: prog.compiled.net.name,\n executionId: this.executionId(),\n totalDurationMs: performance.now() - this.startMs,\n });\n\n return this.syncMarkingFromQueues();\n }\n\n // ======================== Environment Place API ========================\n\n async inject<T>(envPlace: EnvironmentPlace<T>, token: Token<T>): Promise<boolean> {\n if (!this.environmentPlaces.has(envPlace.place.name)) {\n throw new Error(`Place ${envPlace.place.name} is not registered as an environment place`);\n }\n if (this.closed || this.draining) return false;\n\n return new Promise<boolean>((resolve, reject) => {\n this.externalQueue.push({\n place: envPlace.place,\n token,\n resolve,\n reject,\n });\n this.wakeUp();\n });\n }\n\n async injectValue<T>(envPlace: EnvironmentPlace<T>, value: T): Promise<boolean> {\n return this.inject(envPlace, tokenOf(value));\n }\n\n // ======================== Initialize ========================\n\n private initializeMarkingBitmap(): void {\n for (let pid = 0; pid < this.program.placeCount; pid++) {\n if (this.tokenQueues[pid]!.length > 0) {\n this.setMarkingBit(pid);\n }\n }\n }\n\n private markAllDirty(): void {\n const tw = this.transitionWords;\n const tc = this.program.transitionCount;\n for (let w = 0; w < tw - 1; w++) {\n this.dirtyBitmap[w] = 0xFFFFFFFF;\n }\n if (tw > 0) {\n const lastBits = tc & BIT_MASK;\n this.dirtyBitmap[tw - 1] = lastBits === 0 ? 0xFFFFFFFF : (1 << lastBits) - 1;\n }\n }\n\n private shouldTerminate(): boolean {\n if (this.closed) {\n // ENV-013: immediate close — wait for in-flight actions to complete\n return this.inFlightCount === 0 && this.completionQueue.length === 0;\n }\n if (this.hasEnvironmentPlaces) {\n return this.draining\n && this.enabledTransitionCount === 0\n && this.inFlightCount === 0\n && this.completionQueue.length === 0;\n }\n return this.enabledTransitionCount === 0\n && this.inFlightCount === 0\n && this.completionQueue.length === 0;\n }\n\n // ======================== Dirty Set Processing ========================\n\n private updateDirtyTransitions(): void {\n const nowMs = performance.now();\n const prog = this.program;\n const tc = prog.transitionCount;\n\n // Snapshot marking bitmap\n const markingSnap = this.markingSnapBuffer;\n markingSnap.set(this.markingBitmap);\n\n // Snapshot-and-clear dirty set\n const tw = this.transitionWords;\n const dirtySnap = this.dirtyScanBuffer;\n for (let w = 0; w < tw; w++) {\n dirtySnap[w] = this.dirtyBitmap[w]!;\n this.dirtyBitmap[w] = 0;\n }\n\n // Iterate dirty transitions using Kernighan's bit trick\n for (let w = 0; w < tw; w++) {\n let word = dirtySnap[w]!;\n if (word === 0) continue;\n dirtySnap[w] = 0; // clear for next cycle\n while (word !== 0) {\n const bit = Math.clz32(word & -word) ^ 31;\n const tid = (w << WORD_SHIFT) | bit;\n word &= word - 1;\n\n if (tid >= tc) break;\n if (this.inFlightFlags[tid]) continue;\n\n const wasEnabled = this.enabledFlags[tid] !== 0;\n const canNow = this.canEnable(tid, markingSnap);\n\n if (canNow && !wasEnabled) {\n this.enabledFlags[tid] = 1;\n this.enabledTransitionCount++;\n this.enabledAtMs[tid] = nowMs;\n this.emitEvent({\n type: 'transition-enabled',\n timestamp: Date.now(),\n transitionName: prog.compiled.transition(tid).name,\n });\n } else if (!canNow && wasEnabled) {\n this.enabledFlags[tid] = 0;\n this.enabledTransitionCount--;\n this.enabledAtMs[tid] = -Infinity;\n } else if (canNow && wasEnabled && this.hasInputFromResetPlace(tid)) {\n this.enabledAtMs[tid] = nowMs;\n this.emitEvent({\n type: 'transition-clock-restarted',\n timestamp: Date.now(),\n transitionName: prog.compiled.transition(tid).name,\n });\n }\n }\n }\n\n if (this.hasPendingResets) {\n this.pendingResetWords.fill(0);\n this.hasPendingResets = false;\n }\n }\n\n private enforceDeadlines(nowMs: number): void {\n const prog = this.program;\n const tc = prog.transitionCount;\n\n for (let tid = 0; tid < tc; tid++) {\n if (!prog.hasDeadline[tid]) continue;\n // exact() is enforced softly — it fires at the first opportunity at/after its target and is\n // never force-disabled (TIME-006). Only hard deadlines (deadline()/window()) are reaped here.\n if (prog.isExact[tid]) continue;\n if (!this.enabledFlags[tid] || this.inFlightFlags[tid]) continue;\n\n const elapsed = nowMs - this.enabledAtMs[tid]!;\n const latestMs = prog.latestMs[tid]!;\n if (elapsed > latestMs + this.deadlineToleranceMs) {\n this.enabledFlags[tid] = 0;\n this.enabledTransitionCount--;\n this.enabledAtMs[tid] = -Infinity;\n this.emitEvent({\n type: 'transition-timed-out',\n timestamp: Date.now(),\n transitionName: prog.compiled.transition(tid).name,\n deadlineMs: latestMs,\n actualDurationMs: elapsed,\n });\n }\n }\n }\n\n private canEnable(tid: number, markingSnap: Uint32Array): boolean {\n const prog = this.program;\n\n // Sparse bitmap check\n if (!prog.canEnableSparse(tid, markingSnap)) return false;\n\n // Cardinality check\n const cardCheck = prog.cardinalityChecks[tid] ?? null;\n if (cardCheck !== null) {\n for (let i = 0; i < cardCheck.placeIds.length; i++) {\n const pid = cardCheck.placeIds[i]!;\n if (this.tokenQueues[pid]!.length < cardCheck.requiredCounts[i]!) return false;\n }\n }\n\n // ν-net join: a correlation name must satisfy every matched input (NU-020).\n // Gated on the precomputed `hasMatch` flag so non-ν transitions never fetch\n // the Transition object on this hot path (zero-cost gating, mirroring\n // Rust's `has_match(tid)`).\n if (prog.hasMatch[tid]) {\n const cache = this.matchCaches[tid];\n const noBinding = cache != null\n ? cache.best() === null\n : findBinding(prog.compiled.transition(tid), p => this.tokenQueues[prog.compiled.placeId(p)]!) === null;\n if (noBinding) {\n return false;\n }\n }\n\n return true;\n }\n\n private countMatching(pid: number, predicate: (value: any) => boolean): number {\n const q = this.tokenQueues[pid]!;\n let matching = 0;\n for (let i = 0; i < q.length; i++) {\n if (predicate(q[i]!.value)) matching++;\n }\n return matching;\n }\n\n private removeFirstMatching(pid: number, predicate: (value: any) => boolean): Token<any> | null {\n const q = this.tokenQueues[pid]!;\n for (let i = 0; i < q.length; i++) {\n if (predicate(q[i]!.value)) {\n // Head removal (the common ν-net case — the matched token is the oldest,\n // hence at the front when timestamps are distinct) uses the V8-optimized\n // shift() rather than an O(n) splice, keeping a draining join linear.\n return i === 0 ? q.shift()! : q.splice(i, 1)[0]!;\n }\n }\n return null;\n }\n\n private hasInputFromResetPlace(tid: number): boolean {\n if (!this.hasPendingResets) return false;\n const inputMask = this.program.inputPlaceMaskWords[tid]!;\n for (let w = 0; w < inputMask.length; w++) {\n if ((inputMask[w]! & this.pendingResetWords[w]!) !== 0) return true;\n }\n return false;\n }\n\n // ======================== Firing ========================\n\n private fireReadyTransitions(nowMs: number): void {\n if (this.program.allImmediate && this.program.allSamePriority) {\n this.fireReadyImmediate();\n return;\n }\n this.fireReadyGeneral(nowMs);\n }\n\n /**\n * Fast path for nets where all transitions are immediate and same priority.\n * Simple linear scan matching BitmapNetExecutor's pattern.\n */\n private fireReadyImmediate(): void {\n const tc = this.program.transitionCount;\n\n for (let tid = 0; tid < tc; tid++) {\n if (!this.enabledFlags[tid] || this.inFlightFlags[tid]) continue;\n if (this.canEnable(tid, this.markingBitmap)) {\n this.fireTransitionContained(tid);\n } else {\n this.enabledFlags[tid] = 0;\n this.enabledTransitionCount--;\n this.enabledAtMs[tid] = -Infinity;\n }\n }\n }\n\n private fireReadyGeneral(nowMs: number): void {\n const prog = this.program;\n const tc = prog.transitionCount;\n\n // Collect ready transitions into pre-allocated buffer\n const ready = this.readyBuffer;\n ready.length = 0;\n for (let tid = 0; tid < tc; tid++) {\n if (!this.enabledFlags[tid] || this.inFlightFlags[tid]) continue;\n const elapsedMs = nowMs - this.enabledAtMs[tid]!;\n if (prog.earliestMs[tid]! <= elapsedMs) {\n ready.push({ tid, priority: prog.priorities[tid]!, enabledAtMs: this.enabledAtMs[tid]! });\n }\n }\n if (ready.length === 0) return;\n\n // Sort: higher priority first, then earlier enablement (FIFO)\n ready.sort((a, b) => {\n const prioCmp = b.priority - a.priority;\n if (prioCmp !== 0) return prioCmp;\n return a.enabledAtMs - b.enabledAtMs;\n });\n\n // Take a fresh snapshot for re-checking\n const freshSnap = this.firingSnapBuffer;\n freshSnap.set(this.markingBitmap);\n for (const entry of ready) {\n const { tid } = entry;\n if (this.enabledFlags[tid] && this.canEnable(tid, freshSnap)) {\n this.fireTransitionContained(tid);\n freshSnap.set(this.markingBitmap);\n } else {\n this.enabledFlags[tid] = 0;\n this.enabledTransitionCount--;\n this.enabledAtMs[tid] = -Infinity;\n }\n }\n }\n\n /**\n * Fires a transition, containing any synchronous throw to that one firing so it fails\n * only that transition, not the whole run.\n *\n * Without this boundary an unchecked throw raised while a transition fires — a hostile\n * EventStore.append on a token-removed or transition-started emit, or an error thrown while\n * consuming the matched tokens — unwinds out of the orchestrator loop and kills the executor.\n * The transition is instead failed and marked dirty for re-evaluation, the same treatment an\n * asynchronously-reported failure gets. Enablement-phase throws (a key function that\n * throws inside canEnable, before the firing) run outside this boundary and are not contained\n * here.\n *\n * fireTransition drains tokens from the queues before it reconciles the presence bitmap,\n * so a throw inside that window would leave bits asserting tokens that are gone; the\n * recovery re-runs updateBitmapAfterConsumption against the true queue lengths.\n *\n * Unlike the Java runtime there is no VirtualMachineError/LinkageError analogue on\n * the JS side, so every throw is contained here — there is deliberately no\n * fatal-rethrow escape hatch.\n */\n private fireTransitionContained(tid: number): void {\n try {\n this.fireTransition(tid);\n } catch (e) {\n const t = this.program.compiled.transition(tid);\n if (this.enabledFlags[tid]) {\n this.enabledFlags[tid] = 0;\n this.enabledTransitionCount--;\n this.enabledAtMs[tid] = -Infinity;\n }\n if (this.inFlightFlags[tid]) {\n this.inFlightPromises[tid] = null;\n this.inFlightContexts[tid] = null;\n this.inFlightConsumed[tid] = null;\n this.inFlightResolves[tid] = null;\n this.inFlightErrors[tid] = null;\n this.inFlightFlags[tid] = 0;\n this.inFlightCount--;\n }\n this.updateBitmapAfterConsumption(tid);\n // Drop the ν fast-path matcher: fireTransition mirrors the matched consume into it\n // before the tokens leave the queues, so a throw in that window desyncs it. Nulling\n // it forces the next canEnable/fire to rebuild the binding via findBinding.\n this.matchCaches[tid] = null;\n const err = e instanceof Error ? e : new Error(String(e));\n this.emitEvent({\n type: 'transition-failed',\n timestamp: Date.now(),\n transitionName: t.name,\n errorMessage: err.message,\n exceptionType: err.name,\n stack: err.stack,\n });\n this.markTransitionDirty(tid);\n }\n }\n\n private fireTransition(tid: number): void {\n const prog = this.program;\n const t = prog.compiled.transition(tid);\n const consumed: Token<any>[] = [];\n const inputs = new TokenInput();\n\n // ==================== Opcode Dispatch ====================\n // In-firing order: inputs → read peeks → resets, split at\n // PrecompiledNet.resetOpsStart (EXEC-013 AC4).\n if (t.matchSpec) {\n // ν-net join (NU-020): bypass the opcode fast path, consume name-matched\n // tokens. Read arcs are peeked inside, at the same input/reset boundary.\n this.fireTransitionMatched(tid, t, inputs, consumed);\n } else {\n const ops = prog.consumeOps[tid]!;\n const resetOpsStart = prog.resetOpsStart[tid]!;\n let pc = 0;\n while (pc < resetOpsStart) {\n const opcode = ops[pc++]!;\n switch (opcode) {\n case CONSUME_ONE: {\n const pid = ops[pc++]!;\n const token = this.tokenQueues[pid]!.shift()!;\n consumed.push(token);\n inputs.add(prog.places[pid]!, token);\n this.emitEvent({\n type: 'token-removed',\n timestamp: Date.now(),\n placeName: prog.places[pid]!.name,\n token,\n });\n break;\n }\n case CONSUME_N: {\n const pid = ops[pc++]!;\n const count = ops[pc++]!;\n const place = prog.places[pid]!;\n for (let i = 0; i < count; i++) {\n const token = this.tokenQueues[pid]!.shift()!;\n consumed.push(token);\n inputs.add(place, token);\n this.emitEvent({\n type: 'token-removed',\n timestamp: Date.now(),\n placeName: place.name,\n token,\n });\n }\n break;\n }\n case CONSUME_ALL: {\n const pid = ops[pc++]!;\n const place = prog.places[pid]!;\n const q = this.tokenQueues[pid]!;\n const count = q.length;\n for (let i = 0; i < count; i++) {\n const token = q.shift()!;\n consumed.push(token);\n inputs.add(place, token);\n this.emitEvent({\n type: 'token-removed',\n timestamp: Date.now(),\n placeName: place.name,\n token,\n });\n }\n break;\n }\n case CONSUME_ATLEAST: {\n const pid = ops[pc++]!;\n pc++; // skip minimum (already validated in canEnable)\n const place = prog.places[pid]!;\n const q = this.tokenQueues[pid]!;\n const count = q.length;\n for (let i = 0; i < count; i++) {\n const token = q.shift()!;\n consumed.push(token);\n inputs.add(place, token);\n this.emitEvent({\n type: 'token-removed',\n timestamp: Date.now(),\n placeName: place.name,\n token,\n });\n }\n break;\n }\n default:\n throw new Error(`Unknown opcode: ${opcode}`);\n }\n }\n\n // Read arcs (peek, don't consume) — before resets drain (EXEC-013)\n this.peekReadArcs(tid, inputs);\n\n // RESET opcodes: [resetOpsStart, ops.length)\n while (pc < ops.length) {\n const opcode = ops[pc++]!;\n if (opcode !== RESET) {\n throw new Error(`Unknown opcode: ${opcode} (expected RESET past resetOpsStart)`);\n }\n const pid = ops[pc++]!;\n const place = prog.places[pid]!;\n const tokens = this.tokenQueues[pid]!.splice(0);\n this.pendingResetWords[pid >>> WORD_SHIFT]! |= (1 << (pid & BIT_MASK));\n this.hasPendingResets = true;\n for (const token of tokens) {\n consumed.push(token);\n this.emitEvent({\n type: 'token-removed',\n timestamp: Date.now(),\n placeName: place.name,\n token,\n });\n }\n }\n }\n\n // Update bitmap after consumption\n this.updateBitmapAfterConsumption(tid);\n\n this.emitEvent({\n type: 'transition-started',\n timestamp: Date.now(),\n transitionName: t.name,\n consumedTokens: consumed,\n });\n\n const execCtx = this.executionContextProvider?.(t.name, consumed);\n const logFn = (level: string, message: string, error?: Error) => {\n this.emitEvent({\n type: 'log-message',\n timestamp: Date.now(),\n transitionName: t.name,\n logger: t.name,\n level,\n message,\n error: error?.name ?? null,\n errorMessage: error?.message ?? null,\n });\n };\n const context = new TransitionContext(\n t.name, inputs, new TokenOutput(),\n t.inputPlaces(), t.readPlaces(), t.outputPlaces(),\n execCtx,\n logFn,\n t.placeAlias,\n );\n let freshNameSupplier = this.freshNameSuppliers[tid];\n if (freshNameSupplier === undefined) {\n const base = t.name;\n freshNameSupplier = () => nameId(`${base}#${this.freshNameCounter++}`);\n this.freshNameSuppliers[tid] = freshNameSupplier;\n }\n context.setFreshNameSupplier(freshNameSupplier);\n\n // Create action promise with optional timeout. executeAction converts a synchronous\n // throw or a null/non-thenable return into a rejected promise, so a misbehaving action\n // flows the contained failure path instead of unwinding the orchestrator loop.\n let actionPromise = executeAction(t, context);\n\n if (t.hasActionTimeout()) {\n const timeoutSpec = t.actionTimeout;\n if (timeoutSpec === null) throw new Error(`Expected actionTimeout on ${t.name}`);\n const timeoutMs = timeoutSpec.afterMs;\n actionPromise = Promise.race([\n actionPromise,\n new Promise<void>((_, reject) =>\n setTimeout(() => reject(new TimeoutSentinel()), timeoutMs)\n ),\n ]).catch((err) => {\n if (err instanceof TimeoutSentinel) {\n // Sever first, then produce: the abandoned action may still be writing to this\n // context, and its pre-timeout writes must not merge with the timeout branch.\n context.detachForTimeout();\n produceTimeoutOutput(context, timeoutSpec.child);\n this.emitEvent({\n type: 'action-timed-out',\n timestamp: Date.now(),\n transitionName: t.name,\n timeoutMs,\n });\n return;\n }\n throw err;\n });\n }\n\n // Track in-flight\n let resolveInFlight!: () => void;\n const completionPromise = new Promise<void>(r => { resolveInFlight = r; });\n\n this.inFlightPromises[tid] = completionPromise;\n this.inFlightContexts[tid] = context;\n this.inFlightConsumed[tid] = consumed;\n this.inFlightStartMs[tid] = performance.now();\n this.inFlightResolves[tid] = resolveInFlight;\n this.inFlightErrors[tid] = null;\n\n actionPromise.then(\n () => {\n this.completionQueue.push(tid);\n this.wakeUp();\n resolveInFlight();\n },\n (err) => {\n this.inFlightErrors[tid] = err;\n this.completionQueue.push(tid);\n this.wakeUp();\n resolveInFlight();\n },\n );\n\n this.inFlightFlags[tid] = 1;\n this.inFlightCount++;\n this.enabledFlags[tid] = 0;\n this.enabledTransitionCount--;\n this.enabledAtMs[tid] = -Infinity;\n }\n\n /**\n * Consumes the name-matched tokens for a ν-net join (NU-020): correlated\n * inputs take tokens whose projected name equals the chosen binding (NU-021);\n * other inputs consume FIFO. Reset arcs are honoured as on the opcode path.\n */\n private fireTransitionMatched(tid: number, t: Transition, inputs: TokenInput, consumed: Token<any>[]): void {\n const prog = this.program;\n const ms = t.matchSpec!;\n const cache = this.matchCaches[tid];\n const chosen = cache != null\n ? cache.best()\n : findBinding(t, p => this.tokenQueues[prog.compiled.placeId(p)]!);\n // Mirror the matched consume into the fast-path matcher (the only path by\n // which tokens leave this join's correlated inputs) before the token queues\n // change, keeping it in lockstep.\n if (cache != null && chosen !== null) cache.consume(chosen);\n\n for (const inSpec of t.inputSpecs) {\n const pid = prog.compiled.placeId(inSpec.place);\n const keyFn = keyForPlace(ms, inSpec.place.name);\n const pred: ((value: any) => boolean) | undefined =\n (keyFn && chosen !== null)\n ? (v: any) => keyFn(v) === chosen\n : undefined;\n\n let toConsume: number;\n switch (inSpec.type) {\n case 'one': toConsume = 1; break;\n case 'exactly': toConsume = inSpec.count; break;\n case 'all':\n case 'at-least':\n toConsume = pred ? this.countMatching(pid, pred) : this.tokenQueues[pid]!.length;\n break;\n }\n\n for (let i = 0; i < toConsume; i++) {\n const token = pred\n ? this.removeFirstMatching(pid, pred)\n : this.tokenQueues[pid]!.shift() ?? null;\n if (token === null) break;\n consumed.push(token);\n inputs.add(inSpec.place, token);\n this.emitEvent({\n type: 'token-removed',\n timestamp: Date.now(),\n placeName: inSpec.place.name,\n token,\n });\n }\n }\n\n // Read arcs (peek, don't consume) — before resets drain (EXEC-013)\n this.peekReadArcs(tid, inputs);\n\n // Reset arcs\n for (const arc of t.resets) {\n const pid = prog.compiled.placeId(arc.place);\n const tokens = this.tokenQueues[pid]!.splice(0);\n this.pendingResetWords[pid >>> WORD_SHIFT]! |= (1 << (pid & BIT_MASK));\n this.hasPendingResets = true;\n for (const token of tokens) {\n consumed.push(token);\n this.emitEvent({\n type: 'token-removed',\n timestamp: Date.now(),\n placeName: arc.place.name,\n token,\n });\n }\n }\n }\n\n /**\n * Peeks each read-arc place's front token into the context inputs. Called at\n * the input/reset boundary of a firing (EXEC-013): after input consumption,\n * before reset draining — so read(p)+reset(p) observes the pre-reset token.\n */\n private peekReadArcs(tid: number, inputs: TokenInput): void {\n const prog = this.program;\n const readPids = prog.readOps[tid]!;\n for (let i = 0; i < readPids.length; i++) {\n const pid = readPids[i]!;\n const q = this.tokenQueues[pid]!;\n if (q.length > 0) {\n inputs.add(prog.places[pid]!, q[0]!);\n }\n }\n }\n\n private updateBitmapAfterConsumption(tid: number): void {\n const pids = this.program.consumptionPlaceIds[tid]!;\n for (let i = 0; i < pids.length; i++) {\n const pid = pids[i]!;\n if (this.tokenQueues[pid]!.length === 0) {\n this.clearMarkingBit(pid);\n }\n this.markDirty(pid);\n }\n }\n\n // ======================== Completion Processing ========================\n\n private processCompletedTransitions(): void {\n if (this.completionQueue.length === 0) return;\n const prog = this.program;\n const len = this.completionQueue.length;\n\n for (let i = 0; i < len; i++) {\n const tid = this.completionQueue[i]!;\n const context = this.inFlightContexts[tid]!;\n const error = this.inFlightErrors[tid];\n const startMs = this.inFlightStartMs[tid]!;\n const t = prog.compiled.transition(tid);\n\n // Clear in-flight state\n this.inFlightFlags[tid] = 0;\n this.inFlightPromises[tid] = null;\n this.inFlightContexts[tid] = null;\n this.inFlightConsumed[tid] = null;\n this.inFlightResolves[tid] = null;\n this.inFlightErrors[tid] = null;\n this.inFlightCount--;\n\n if (error) {\n const err = error instanceof Error ? error : new Error(String(error));\n this.emitEvent({\n type: 'transition-failed',\n timestamp: Date.now(),\n transitionName: t.name,\n errorMessage: err.message,\n exceptionType: err.name,\n stack: err.stack,\n });\n this.markTransitionDirty(tid);\n continue;\n }\n\n try {\n const outputs = context.rawOutput();\n\n // Validate output\n if (!this.skipOutputValidation && t.outputSpec !== null) {\n const simplePid = prog.simpleOutputPlaceId[tid]!;\n if (simplePid >= 0) {\n const produced = outputs.placesWithTokens();\n const named = prog.places[simplePid]!.name;\n if (!produced.has(named)) {\n // Same wording the general path emits: for a bare `Out.Place` the\n // spec names one place, so on failure nothing it names was written\n // and the exact-explanation verdict is identical to this check.\n throw new OutViolationError(\n `'${t.name}': output does not match the declared spec - produced {}, ` +\n `which no single branch of the spec claims exactly`\n );\n }\n // IO-016 AC4 (see the general path below); the claim is the one named place.\n if (outputs.entries().length > produced.size) this.warnMultiplicity(t.name, outputs, new Set([named]));\n } else if (simplePid === -1) {\n const produced = outputs.placesWithTokens();\n const claim = validateOutSpec(t.name, t.outputSpec, produced);\n // IO-016 AC4: a spec names a place once; several tokens into a named place\n // pass validation (IO-015 reads the produced SET) but exceed what every\n // branch-enumerating analysis models. Cheap test first: a repeat exists\n // iff there are more entries than distinct places.\n if (outputs.entries().length > produced.size) this.warnMultiplicity(t.name, outputs, claim);\n }\n }\n\n // Add output tokens to queues\n const produced: Token<any>[] = [];\n for (const entry of outputs.entries()) {\n this.produceToken(entry.place, entry.token, t.name);\n produced.push(entry.token);\n this.emitEvent({\n type: 'token-added',\n timestamp: Date.now(),\n placeName: entry.place.name,\n token: entry.token,\n });\n }\n this.markTransitionDirty(tid);\n\n this.emitEvent({\n type: 'transition-completed',\n timestamp: Date.now(),\n transitionName: t.name,\n producedTokens: produced,\n durationMs: performance.now() - startMs,\n });\n } catch (e) {\n const err = e instanceof Error ? e : new Error(String(e));\n this.emitEvent({\n type: 'transition-failed',\n timestamp: Date.now(),\n transitionName: t.name,\n errorMessage: err.message,\n exceptionType: err.name,\n stack: err.stack,\n });\n this.markTransitionDirty(tid);\n }\n }\n this.completionQueue.length = 0;\n }\n\n // ======================== External Events ========================\n\n private processExternalEvents(): void {\n if (this.externalQueue.length === 0) return;\n if (this.closed) return; // ENV-013: leave queued events for drainPendingExternalEvents()\n const len = this.externalQueue.length;\n\n for (let i = 0; i < len; i++) {\n const event = this.externalQueue[i]!;\n try {\n this.produceToken(event.place, event.token, '');\n\n this.emitEvent({\n type: 'token-added',\n timestamp: Date.now(),\n placeName: event.place.name,\n token: event.token,\n });\n event.resolve(true);\n } catch (e) {\n event.reject(e instanceof Error ? e : new Error(String(e)));\n }\n }\n this.externalQueue.length = 0;\n }\n\n /**\n * Adds a produced or injected token: queue/bitmap/dirty for compiled places,\n * or the retention side map when the program does not know it (CORE-072 AC3).\n * `transitionName` is the producer, empty at the injection seam.\n */\n private produceToken(place: Place<any>, token: Token<any>, transitionName: string): void {\n const pid = this.program.compiled.tryPlaceId(place);\n if (pid === undefined) {\n this.retainUnknownToken(place, token, transitionName);\n return;\n }\n this.cacheAddToken(pid, token);\n this.tokenQueues[pid]!.push(token);\n this.setMarkingBit(pid);\n this.markDirty(pid);\n }\n\n /**\n * Retains a token on an undeclared place (CORE-072 AC3) and reports the place\n * once — the first insert is the only one that creates a map entry, so a hot\n * loop cannot flood (AC4, emitted as the EVT-013 log-message event).\n */\n private retainUnknownToken(place: Place<any>, token: Token<any>, transitionName: string): void {\n const retained = this.unknownPlaceTokens.get(place.name);\n if (retained !== undefined) {\n retained.tokens.push(token);\n return;\n }\n this.unknownPlaceTokens.set(place.name, { place, tokens: [token] });\n this.emitEvent({\n type: 'log-message',\n timestamp: Date.now(),\n transitionName,\n logger: 'libpetri.runtime',\n level: 'WARN',\n message: `unknown place '${place.name}': tokens are retained in the marking but inert `\n + '(the net declares no arc on it)',\n error: null,\n errorMessage: null,\n });\n }\n\n private drainPendingExternalEvents(): void {\n while (this.externalQueue.length > 0) {\n this.externalQueue.shift()!.resolve(false);\n }\n }\n\n // ======================== Await Work ========================\n\n private async awaitWork(): Promise<void> {\n // When closed, ignore external queue — processExternalEvents() won't consume it,\n // and drainPendingExternalEvents() handles it after the loop exits.\n if (this.completionQueue.length > 0 || (!this.closed && this.externalQueue.length > 0)) return;\n\n await Promise.resolve();\n if (this.completionQueue.length > 0 || (!this.closed && this.externalQueue.length > 0)) return;\n // ENV-013: when closed with no in-flight, exit immediately for shouldTerminate()\n if (this.closed && this.inFlightCount === 0) return;\n\n const promises = this.awaitPromises;\n promises.length = 0;\n\n // In-flight completion\n if (this.inFlightCount > 0) {\n const arr = this.racePromises;\n arr.length = 0;\n for (let tid = 0; tid < this.program.transitionCount; tid++) {\n if (this.inFlightPromises[tid] !== null) {\n arr.push(this.inFlightPromises[tid]!);\n }\n }\n if (arr.length > 0) {\n promises.push(Promise.race(arr));\n }\n }\n\n // When closed, only wait for in-flight completions — skip event/timer promises\n if (!this.closed) {\n // Zero means a timing boundary is already due: an earliest firing time has\n // been reached, or a deadline needs enforcing. There is nothing to wait for,\n // and with no action in flight the race below would hold only the external\n // wake-up promise — which a net with no environment places has nobody to\n // resolve, so the loop would sleep until its run budget expired. Return and\n // let the next cycle act on the boundary. Rust reaches the same outcome via\n // sleep(0); Java returns early on `millisUntilNextTimedTransition() <= 0`.\n const timerMs = this.millisUntilNextTimedTransition();\n if (timerMs === 0 && promises.length === 0) return;\n\n // External event wake-up\n promises.push(new Promise<void>(resolve => { this.wakeUpResolve = resolve; }));\n\n // Timer for next timed transition\n if (timerMs > 0 && timerMs < Infinity) {\n promises.push(new Promise<void>(r => setTimeout(r, timerMs)));\n }\n }\n\n if (promises.length > 0) {\n await Promise.race(promises);\n }\n this.wakeUpResolve = null;\n }\n\n private millisUntilNextTimedTransition(): number {\n const nowMs = performance.now();\n const prog = this.program;\n const tc = prog.transitionCount;\n let minWaitMs = Infinity;\n\n for (let tid = 0; tid < tc; tid++) {\n if (!this.enabledFlags[tid]) continue;\n\n const enabledMs = this.enabledAtMs[tid]!;\n const elapsedMs = nowMs - enabledMs;\n\n const eMs = prog.earliestMs[tid]!;\n const remainingEarliest = eMs - elapsedMs;\n if (remainingEarliest <= 0) return 0;\n minWaitMs = Math.min(minWaitMs, remainingEarliest);\n\n if (prog.hasDeadline[tid]) {\n const lMs = prog.latestMs[tid]!;\n const remainingDeadline = lMs - elapsedMs;\n if (remainingDeadline <= 0) return 0;\n minWaitMs = Math.min(minWaitMs, remainingDeadline);\n }\n }\n return minWaitMs;\n }\n\n private wakeUp(): void {\n this.wakeUpResolve?.();\n }\n\n // ======================== Dirty Set Helpers ========================\n\n private hasDirtyBits(): boolean {\n for (let w = 0; w < this.transitionWords; w++) {\n if (this.dirtyBitmap[w] !== 0) return true;\n }\n return false;\n }\n\n // ======================== Lazy Marking Sync ========================\n\n private syncMarkingFromQueues(): Marking {\n const prog = this.program;\n const m = Marking.empty();\n for (let pid = 0; pid < prog.placeCount; pid++) {\n const q = this.tokenQueues[pid]!;\n if (q.length === 0) continue;\n const place = prog.places[pid]!;\n for (let i = 0; i < q.length; i++) {\n m.addToken(place, q[i]!);\n }\n }\n // CORE-072: merge retained tokens on undeclared places into the observable\n // marking (empty map for well-formed inputs — no hot-path cost).\n for (const { place, tokens } of this.unknownPlaceTokens.values()) {\n for (const token of tokens) {\n m.addToken(place, token);\n }\n }\n this.marking = m;\n return m;\n }\n\n // ======================== State Inspection ========================\n\n getMarking(): Marking {\n return this.marking ?? this.syncMarkingFromQueues();\n }\n\n private snapshotMarking(): ReadonlyMap<string, readonly Token<any>[]> {\n const prog = this.program;\n const snap = new Map<string, readonly Token<any>[]>();\n for (let pid = 0; pid < prog.placeCount; pid++) {\n const q = this.tokenQueues[pid]!;\n if (q.length === 0) continue;\n snap.set(prog.places[pid]!.name, [...q]);\n }\n return snap;\n }\n\n isQuiescent(): boolean {\n return this.enabledTransitionCount === 0 && this.inFlightCount === 0;\n }\n\n executionId(): string {\n return this.startMs.toString(16);\n }\n\n drain(): void {\n this.draining = true;\n this.wakeUp();\n }\n\n close(): void {\n this.draining = true;\n this.closed = true;\n this.wakeUp();\n }\n\n // ======================== Event Emission ========================\n\n /**\n * Reports, once per transition, a firing that wrote more than one token to a place\n * its output spec names once (IO-016 AC4), as the EVT-013 log-message event. The\n * tokens are deposited regardless: the diagnostic makes the under-approximation\n * every branch-enumerating analysis makes of this transition visible. Mirrors the\n * bitmap executor word for word.\n */\n private warnMultiplicity(transitionName: string, outputs: TokenOutput, claim: ReadonlySet<string>): void {\n if (this.warnedMultiplicity.has(transitionName)) return;\n const counts = new Map<string, number>();\n for (const entry of outputs.entries()) {\n if (claim.has(entry.place.name)) counts.set(entry.place.name, (counts.get(entry.place.name) ?? 0) + 1);\n }\n const repeated: string[] = [];\n for (const [name, n] of counts) if (n > 1) repeated.push(`${name}: ${n}`);\n if (repeated.length === 0) return;\n this.warnedMultiplicity.add(transitionName);\n this.emitEvent({\n type: 'log-message',\n timestamp: Date.now(),\n transitionName,\n logger: 'libpetri.runtime',\n level: 'WARN',\n message: `'${transitionName}': wrote more than one token to a place its output spec names once `\n + `(${repeated.join(', ')}); branch-enumerating analyses model one token per named place, `\n + 'so this firing exceeds what they explore (IO-016)',\n error: null,\n errorMessage: null,\n });\n }\n\n private emitEvent(event: NetEvent): void {\n if (this.eventStoreEnabled) {\n // A user EventStore.append that throws is observation failing, not control flow:\n // swallow it so a hostile store cannot unwind the orchestrator loop. One choke\n // point covers every emit site.\n try {\n this.eventStore.append(event);\n } catch (err) {\n swallowEventStoreFailure(event.type, err);\n }\n }\n }\n}\n\nclass TimeoutSentinel extends Error {\n constructor() { super('action timeout'); this.name = 'TimeoutSentinel'; }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAsBA,IAAM,aAA0B,OAAO,OAAO;AAAA,EAC5C,OAAO;AAAA,EACP,WAAW;AACb,CAAC;AAGM,SAAS,QAAW,OAAoB;AAC7C,SAAO,EAAE,OAAO,WAAW,KAAK,IAAI,EAAE;AACxC;AAOO,SAAS,YAAyB;AACvC,SAAO;AACT;AAGO,SAAS,QAAW,OAAU,WAA6B;AAChE,SAAO,EAAE,OAAO,UAAU;AAC5B;AAGO,SAAS,OAAO,OAAgC;AACrD,SAAO,UAAU;AACnB;;;ACzBO,SAAS,MAAS,MAAwB;AAC/C,SAAO,EAAE,KAAK;AAChB;AAGO,SAAS,iBAAoB,MAAmC;AACrE,SAAO,EAAE,OAAO,MAAS,IAAI,EAAE;AACjC;;;ACYO,SAAS,SAAYA,QAA8B;AACxD,SAAO,EAAE,MAAM,SAAS,OAAAA,OAAM;AAChC;AAGO,SAAS,UAAaA,QAA+B;AAC1D,SAAO,EAAE,MAAM,UAAU,OAAAA,OAAM;AACjC;AAGO,SAAS,aAAgBA,QAAkC;AAChE,SAAO,EAAE,MAAM,aAAa,OAAAA,OAAM;AACpC;AAGO,SAAS,QAAWA,QAA6B;AACtD,SAAO,EAAE,MAAM,QAAQ,OAAAA,OAAM;AAC/B;AAGO,SAAS,SAAYA,QAA8B;AACxD,SAAO,EAAE,MAAM,SAAS,OAAAA,OAAM;AAChC;AAGO,SAAS,SAAS,KAAsB;AAC7C,SAAO,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AAK,OAAO;AAAA,EAAmB;AAC1E;","names":["place","place","place","place","matchSpec","place","place","EMPTY_ALIAS","i","place","place","place","place","place","place","exact","place","resolve","produced","place","resolve","TimeoutSentinel","produced"]}
|