libpetri 2.7.0 → 2.7.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.js +3 -0
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
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/in.ts","../src/core/transition-action.ts","../src/core/transition-context.ts","../src/core/token-input.ts","../src/core/token-output.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/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 readonly guard?: (value: T) => boolean;\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>, guard?: (value: T) => boolean): ArcInput<T> {\n return guard !== undefined ? { type: 'input', place, guard } : { 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/** Checks if an input arc has a guard predicate. */\nexport function hasGuard(arc: ArcInput): boolean {\n return arc.guard !== undefined;\n}\n\n/** Checks if a token value matches an input arc's guard. */\nexport function matchesGuard<T>(arc: ArcInput<T>, value: T): boolean {\n if (arc.guard === undefined) return true;\n return arc.guard(value);\n}\n","import type { Place } from './place.js';\n\n/**\n * Input specification with cardinality and optional guard predicate.\n * CPN-compliant: cardinality determines how many tokens to consume,\n * guard filters which tokens are eligible.\n *\n * Inputs are always AND-joined (all must be satisfied to enable transition).\n * XOR on inputs is modeled via multiple transitions (conflict).\n */\nexport type In = InOne | InExactly | InAll | InAtLeast;\n\nexport interface InOne<T = any> {\n readonly type: 'one';\n readonly place: Place<T>;\n readonly guard?: (value: T) => boolean;\n}\n\nexport interface InExactly<T = any> {\n readonly type: 'exactly';\n readonly place: Place<T>;\n readonly count: number;\n readonly guard?: (value: T) => boolean;\n}\n\nexport interface InAll<T = any> {\n readonly type: 'all';\n readonly place: Place<T>;\n readonly guard?: (value: T) => boolean;\n}\n\nexport interface InAtLeast<T = any> {\n readonly type: 'at-least';\n readonly place: Place<T>;\n readonly minimum: number;\n readonly guard?: (value: T) => boolean;\n}\n\n// ==================== Factory Functions ====================\n\n/** Consume exactly 1 token (standard CPN semantics). Optional guard filters eligible tokens. */\nexport function one<T>(place: Place<T>, guard?: (value: T) => boolean): InOne<T> {\n return guard !== undefined ? { type: 'one', place, guard } : { type: 'one', place };\n}\n\n/** Consume exactly N tokens (batching). Optional guard filters eligible tokens. */\nexport function exactly<T>(count: number, place: Place<T>, guard?: (value: T) => boolean): InExactly<T> {\n if (count < 1) {\n throw new Error(`count must be >= 1, got: ${count}`);\n }\n return guard !== undefined ? { type: 'exactly', place, count, guard } : { type: 'exactly', place, count };\n}\n\n/** Consume all available tokens (must be 1+). Optional guard filters eligible tokens. */\nexport function all<T>(place: Place<T>, guard?: (value: T) => boolean): InAll<T> {\n return guard !== undefined ? { type: 'all', place, guard } : { type: 'all', place };\n}\n\n/** Wait for N+ tokens, consume all when enabled. Optional guard filters eligible tokens. */\nexport function atLeast<T>(minimum: number, place: Place<T>, guard?: (value: T) => boolean): InAtLeast<T> {\n if (minimum < 1) {\n throw new Error(`minimum must be >= 1, got: ${minimum}`);\n }\n return guard !== undefined\n ? { type: 'at-least', place, minimum, guard }\n : { type: 'at-least', place, minimum };\n}\n\n// ==================== Helper Functions ====================\n\n/** Returns the minimum number of tokens required to enable. */\nexport function requiredCount(spec: In): number {\n switch (spec.type) {\n case 'one': return 1;\n case 'exactly': return spec.count;\n case 'all': return 1;\n case 'at-least': return spec.minimum;\n }\n}\n\n/**\n * Returns the actual number of tokens to consume given the available count.\n * - One: always consumes 1\n * - Exactly: always consumes exactly count\n * - All: consumes all available\n * - AtLeast: consumes all available (when enabled, i.e., >= minimum)\n */\nexport function consumptionCount(spec: In, available: number): number {\n if (available < requiredCount(spec)) {\n throw new Error(\n `Cannot consume from '${spec.place.name}': available=${available}, required=${requiredCount(spec)}`\n );\n }\n switch (spec.type) {\n case 'one': return 1;\n case 'exactly': return spec.count;\n case 'all': return available;\n case 'at-least': return available;\n }\n}\n","import type { Place } from './place.js';\nimport type { TransitionContext } from './transition-context.js';\n\n/**\n * The action executed when a transition fires.\n * Receives a TransitionContext providing filtered I/O and structure access.\n */\nexport type TransitionAction = (ctx: TransitionContext) => Promise<void>;\n\n// ==================== Built-in Actions ====================\n\n/**\n * Identity action: produces no outputs.\n *\n * Returns a stable singleton reference (cached on first call). Reference\n * stability is relied on by {@link import('./internal/subnet-rewriter.js')\n * .composeActions} during channel composition (MOD-021) to short-circuit a\n * passthrough-on-both-sides merge to passthrough — saving a microtask hop\n * and matching the Java implementation's behaviour where both transitions'\n * default actions collapse to the builder's own passthrough default.\n */\nexport function passthrough(): TransitionAction {\n return PASSTHROUGH;\n}\n\n/** @internal Stable passthrough action — see {@link passthrough}. */\nconst PASSTHROUGH: TransitionAction = async () => {};\n\n/**\n * Transform action: applies function to context, copies result to ALL output places.\n *\n * @example\n * ```ts\n * const action = transform(ctx => ctx.input(inputPlace).toUpperCase());\n * // Result is copied to every declared output place\n * ```\n */\nexport function transform(fn: (ctx: TransitionContext) => unknown): TransitionAction {\n return async (ctx) => {\n const result = fn(ctx);\n for (const outputPlace of ctx.outputPlaces()) {\n ctx.output(outputPlace, result);\n }\n };\n}\n\n/**\n * Fork action: copies single input token to all outputs.\n * Requires exactly one input place (derived from structure).\n */\nexport function fork(): TransitionAction {\n return transform((ctx) => {\n const inputPlaces = ctx.inputPlaces();\n if (inputPlaces.size !== 1) {\n throw new Error(`Fork requires exactly 1 input place, found ${inputPlaces.size}`);\n }\n const inputPlace = inputPlaces.values().next().value as Place<any>;\n return ctx.input(inputPlace);\n });\n}\n\n/**\n * Transform with explicit input place.\n */\nexport function transformFrom<I>(inputPlace: Place<I>, fn: (value: I) => unknown): TransitionAction {\n return transform((ctx) => fn(ctx.input(inputPlace)));\n}\n\n/**\n * Async transform: applies async function, copies result to all outputs.\n */\nexport function transformAsync(fn: (ctx: TransitionContext) => Promise<unknown>): TransitionAction {\n return async (ctx) => {\n const result = await fn(ctx);\n for (const outputPlace of ctx.outputPlaces()) {\n ctx.output(outputPlace, result);\n }\n };\n}\n\n/** Produce action: produces a single token with the given value to the specified place. */\nexport function produce<T>(place: Place<T>, value: T): TransitionAction {\n return async (ctx) => {\n ctx.output(place, value);\n };\n}\n\n/**\n * Wraps an action with timeout handling.\n * If the action completes within the timeout, normal completion.\n * If the timeout expires, the timeoutValue is produced to the timeoutPlace.\n *\n * @example\n * ```ts\n * const action = withTimeout(\n * async (ctx) => { ctx.output(resultPlace, await fetchData()); },\n * 5000,\n * timeoutPlace,\n * 'timed-out',\n * );\n * ```\n */\nexport function withTimeout<T>(\n action: TransitionAction,\n timeoutMs: number,\n timeoutPlace: Place<T>,\n timeoutValue: T,\n): TransitionAction {\n return (ctx) => {\n return new Promise<void>((resolve, reject) => {\n let completed = false;\n const timer = setTimeout(() => {\n if (!completed) {\n completed = true;\n ctx.output(timeoutPlace, timeoutValue);\n resolve();\n }\n }, timeoutMs);\n action(ctx).then(\n () => {\n if (!completed) {\n completed = true;\n clearTimeout(timer);\n resolve();\n }\n },\n (err) => {\n if (!completed) {\n completed = true;\n clearTimeout(timer);\n reject(err);\n }\n },\n );\n });\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';\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 * 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 private readonly _rawOutput: 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\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._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._rawOutput.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._rawOutput.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 // ==================== 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 { 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 /** Add a value to an output place (creates token with current timestamp). */\n add<T>(place: Place<T>, value: T): 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 this._entries.push({ place, token });\n return this;\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 { ArcInhibitor, ArcRead, ArcReset } from './arc.js';\nimport type { In } from './in.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 * 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 ) {\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\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\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 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 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 );\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 { Timing } from '../timing.js';\nimport type { TransitionAction } from '../transition-action.js';\nimport { passthrough } 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: rebuilds `t` with the supplied `name` and arc places\n * rewritten through `remap`. Used by both {@link rewriteTransition} (which\n * prefixes the name) and {@link substitutePlaces} (which keeps the name\n * unchanged).\n */\nfunction rebuildWithName(\n t: Transition,\n name: string,\n remap: Map<string, Place<unknown>>,\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(...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 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`. Guards are\n * carried through by reference.\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), spec.guard);\n case 'exactly':\n return exactly(spec.count, resolve(spec.place, remap), spec.guard);\n case 'all':\n return all(resolve(spec.place, remap), spec.guard);\n case 'at-least':\n return atLeast(spec.minimum, resolve(spec.place, remap), spec.guard);\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. Duplicates (by structural key — same arc kind +\n * place name) are deduped so identical arcs to a shared place collapse.\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 (per [MOD-021]) — the message names the\n * channel and both timings 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 first so a conflict short-circuits before any building.\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\n const builder = Transition.builder(mergedName)\n .timing(mergedTiming)\n .priority(mergedPriority);\n if (mergedAction !== undefined) {\n builder.action(mergedAction);\n }\n\n // Inputs: union caller-first, then instance, dedup by (kind, place name,\n // count/minimum where applicable). Guard predicates are reference-compared\n // — two equal-shaped arcs with different guard closures are treated as\n // distinct (the safest default, matching Java's record-equality dedupe\n // when guards are absent and conservatively avoiding silent guard merges).\n const unionedInputs = unionArcs<In>(caller.inputSpecs, instance.inputSpecs, keyOfIn);\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 return builder.build();\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 passthrough}, so the `undefined` branches are defensive — they exist\n * so this helper is robust if upstream 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\n/**\n * Reference identity check against the singleton passthrough action.\n *\n * {@link passthrough} returns a stable cached reference, so identity\n * comparison reliably detects \"this is the no-op default action\". Used by\n * {@link composeActions} to collapse passthrough-on-both-sides to\n * passthrough — saving a microtask hop and matching the Java\n * implementation's behaviour where both transitions' default actions\n * collapse to the builder's own passthrough default.\n */\nconst PASSTHROUGH_REF = passthrough();\nfunction isPassthrough(action: TransitionAction): boolean {\n return action === PASSTHROUGH_REF;\n}\n\n/**\n * Structural key for an {@link In} arc. Encodes the discriminant + place\n * name + cardinality (where applicable). Guard predicates are NOT folded\n * into the key — two arcs of the same shape with different guard closures\n * are treated as distinct (the safe default).\n */\nfunction keyOfIn(arc: In): string {\n switch (arc.type) {\n case 'one':\n return arc.guard === undefined\n ? `one|${arc.place.name}`\n : `one|${arc.place.name}|g:${guardKey(arc.guard)}`;\n case 'exactly':\n return arc.guard === undefined\n ? `exactly|${arc.place.name}|${arc.count}`\n : `exactly|${arc.place.name}|${arc.count}|g:${guardKey(arc.guard)}`;\n case 'all':\n return arc.guard === undefined\n ? `all|${arc.place.name}`\n : `all|${arc.place.name}|g:${guardKey(arc.guard)}`;\n case 'at-least':\n return arc.guard === undefined\n ? `atLeast|${arc.place.name}|${arc.minimum}`\n : `atLeast|${arc.place.name}|${arc.minimum}|g:${guardKey(arc.guard)}`;\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 * Identity-only key for guard closures. Two distinct closure references\n * yield distinct keys; reusing the same closure across arcs collapses them.\n * We use a WeakMap so guard closures don't hold extra retention, and the\n * counter assigned per closure is stable across calls within one process.\n */\nconst GUARD_KEYS = new WeakMap<object, string>();\nlet guardKeyCounter = 0;\nfunction guardKey(g: object): string {\n let k = GUARD_KEYS.get(g);\n if (k === undefined) {\n k = String(++guardKeyCounter);\n GUARD_KEYS.set(g, k);\n }\n return k;\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 substitutePlaces}; 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 by {@link substitutePlaces} (a fresh\n * `Transition` instance); callers that care about identity preservation for\n * un-affected transitions should instead skip the rewrite entirely when\n * `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 * @param transitions the transitions to rewrite (non-null, may be empty)\n * @param fusionMap non-canonical name → canonical place remap (non-null)\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): Set<Transition> {\n const rewritten = new Set<Transition>();\n for (const t of transitions) {\n rewritten.add(substitutePlaces(t, fusionMap));\n }\n return rewritten;\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 * 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 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';\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(harness: VerificationHarness<P>): 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 // 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 const verifier = SmtVerifier.forNet(syntheticNet).property(property);\n if (envPlaces.length > 0) {\n verifier.environmentPlaces(...envPlaces);\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 bindActionsWithResolver(actionResolver: (name: string) => TransitionAction): 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.\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.\n const rewrittenTransitions = applyFusion(this._transitions, fusionMap);\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 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 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/** Anything that carries a place reference and an optional guard predicate. */\nexport interface GuardSpec<T = any> {\n readonly place: Place<T>;\n readonly guard?: (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 guard predicate.\n *\n * Performs a linear scan of the place's FIFO queue. If no guard is provided,\n * behaves like `removeFirst()`. If a guard is provided, skips non-matching\n * tokens and splices the first match out of the queue (O(n) worst case).\n */\n removeFirstMatching(spec: GuardSpec): Token<any> | null {\n const queue = this.tokens.get(spec.place.name);\n if (!queue || queue.length === 0) return null;\n if (!spec.guard) {\n return queue.shift()!;\n }\n for (let i = 0; i < queue.length; i++) {\n const token = queue[i]!;\n if (spec.guard(token.value)) {\n queue.splice(i, 1);\n return token;\n }\n }\n return null;\n }\n\n // ======================== Token Inspection ========================\n\n /** Check if any token matches a guard predicate. */\n hasMatchingToken(spec: GuardSpec): boolean {\n const queue = this.tokens.get(spec.place.name);\n if (!queue || queue.length === 0) return false;\n if (!spec.guard) return true;\n return queue.some(t => spec.guard!(t.value));\n }\n\n /**\n * Counts tokens in a place whose values satisfy the guard predicate.\n *\n * If no guard is provided, returns the total token count (O(1)).\n * With a guard, performs a linear scan over all tokens (O(n)).\n * Used by the executor for enablement checks on guarded `all`/`at-least` inputs.\n */\n countMatching(spec: GuardSpec): number {\n const queue = this.tokens.get(spec.place.name);\n if (!queue || queue.length === 0) return 0;\n if (!spec.guard) return queue.length;\n let count = 0;\n for (const t of queue) {\n if (spec.guard(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';\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 and guard flags\n private readonly _cardinalityChecks: (CardinalityCheck | null)[];\n private readonly _hasGuards: boolean[];\n\n private constructor(net: PetriNet) {\n this.net = 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._hasGuards = 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 const needs = new Uint32Array(this.wordCount);\n const inhibitors = new Uint32Array(this.wordCount);\n\n let needsCardinality = false;\n\n // Input specs\n for (const inSpec of t.inputSpecs) {\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 if (inSpec.guard) {\n this._hasGuards[tid] = 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 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 hasGuards(tid: number): boolean {\n return this._hasGuards[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 guard checks\n * are performed separately by the executor for transitions that pass this 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 * 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 { TransitionContext } from '../core/transition-context.js';\nimport { OutViolationError } from './out-violation-error.js';\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 * Recursively validates that a transition's output satisfies its declared Out spec.\n *\n * @returns the set of claimed place names, or null if not satisfied\n * @throws OutViolationError if a structural violation is detected (e.g. XOR with 0 or 2+ branches)\n */\nexport function validateOutSpec(\n tName: string,\n spec: Out,\n producedPlaceNames: Set<string>,\n): Set<string> | null {\n switch (spec.type) {\n case 'place':\n return producedPlaceNames.has(spec.place.name)\n ? new Set([spec.place.name])\n : null;\n\n case 'forward-input':\n return producedPlaceNames.has(spec.to.name)\n ? new Set([spec.to.name])\n : null;\n\n case 'and': {\n const claimed = new Set<string>();\n for (const child of spec.children) {\n const result = validateOutSpec(tName, child, producedPlaceNames);\n if (result === null) return null;\n for (const p of result) claimed.add(p);\n }\n return claimed;\n }\n\n case 'xor': {\n const satisfied: Set<string>[] = [];\n for (const child of spec.children) {\n const result = validateOutSpec(tName, child, producedPlaceNames);\n if (result !== null) satisfied.push(result);\n }\n if (satisfied.length === 0) {\n throw new OutViolationError(\n `'${tName}': XOR violation - no branch produced (exactly 1 required)`\n );\n }\n if (satisfied.length > 1) {\n throw new OutViolationError(\n `'${tName}': XOR violation - multiple branches produced`\n );\n }\n return satisfied[0]!;\n }\n\n case 'timeout':\n return validateOutSpec(tName, spec.child, producedPlaceNames);\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 the consumed input token to the output place.\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 */\nexport function produceTimeoutOutput(context: TransitionContext, timeoutChild: Out): void {\n switch (timeoutChild.type) {\n case 'place':\n context.output(timeoutChild.place, null);\n break;\n case 'forward-input': {\n const value = context.input(timeoutChild.from);\n context.output(timeoutChild.to, value);\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 } 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 } from './marking.js';\nimport { validateOutSpec, produceTimeoutOutput, DEADLINE_TOLERANCE_MS } from './executor-support.js';\nimport { OutViolationError } from './out-violation-error.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 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 markedPlaces: 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 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.markedPlaces = 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\n // ======================== Execution ========================\n\n async run(timeoutMs?: number): Promise<Marking> {\n if (timeoutMs !== undefined) {\n let timer: ReturnType<typeof setTimeout> | undefined;\n const timeoutPromise = new Promise<never>((_, reject) => {\n timer = setTimeout(() => reject(new Error('Execution timed out')), timeoutMs);\n });\n try {\n return await Promise.race([this.executeLoop(), timeoutPromise]);\n } finally {\n if (timer !== undefined) clearTimeout(timer);\n }\n }\n return this.executeLoop();\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.initializeMarkedBitmap();\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 initializeMarkedBitmap(): 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.markedPlaces, 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 markedPlaces mid-scan.\n const markingSnap = this.markingSnapBuffer;\n markingSnap.set(this.markedPlaces);\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 // Guard check: verify matching tokens exist for each guarded input\n if (this.compiled.hasGuards(tid)) {\n const t = this.compiled.transition(tid);\n for (const spec of t.inputSpecs) {\n if (!spec.guard) continue;\n const requiredCount = spec.type === 'one' ? 1\n : spec.type === 'exactly' ? spec.count\n : spec.type === 'at-least' ? spec.minimum\n : 1; // 'all' requires at least 1 matching\n if (this.marking.countMatching(spec) < requiredCount) 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 `markedPlaces` 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.markedPlaces)) {\n this.fireTransition(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.markedPlaces);\n for (const entry of ready) {\n const { tid } = entry;\n if (this.enabledFlags[tid] && this.canEnable(tid, freshSnap)) {\n this.fireTransition(tid);\n // Update snapshot after consuming tokens\n freshSnap.set(this.markedPlaces);\n } else {\n this.enabledFlags[tid] = 0;\n this.enabledTransitionCount--;\n this.enabledAtMs[tid] = -Infinity;\n }\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 and guard.\n // Note: for guarded 'all'/'at-least' inputs, countMatching() is called here AND in\n // canEnable() — a known O(2n) tradeoff. Token queues are typically ≤10 items, so\n // the simplicity of re-scanning outweighs caching complexity.\n for (const inSpec of t.inputSpecs) {\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 toConsume = inSpec.guard\n ? this.marking.countMatching(inSpec)\n : this.marking.tokenCount(inSpec.place);\n break;\n case 'at-least':\n toConsume = inSpec.guard\n ? this.marking.countMatching(inSpec)\n : this.marking.tokenCount(inSpec.place);\n break;\n }\n\n for (let i = 0; i < toConsume; i++) {\n const token = inSpec.guard\n ? this.marking.removeFirstMatching(inSpec)\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\n // Create action promise with optional timeout\n let actionPromise = t.action(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 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.markedPlaces, 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 result = validateOutSpec(t.name, t.outputSpec, produced);\n if (result === null) {\n throw new OutViolationError(\n `'${t.name}': output does not satisfy declared spec`\n );\n }\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 this.marking.addToken(entry.place, entry.token);\n produced.push(entry.token);\n const pid = this.compiled.placeId(entry.place);\n setBit(this.markedPlaces, pid);\n this.markDirty(pid);\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 this.marking.addToken(event.place, event.token);\n const pid = this.compiled.placeId(event.place);\n setBit(this.markedPlaces, pid);\n this.markDirty(pid);\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 // 2. External event wake-up\n promises.push(new Promise<void>(resolve => { this.wakeUpResolve = resolve; }));\n\n // 3. Timer for next delayed transition\n const timerMs = this.millisUntilNextTimedTransition();\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 private emitEvent(event: NetEvent): void {\n if (this.eventStoreEnabled) {\n this.eventStore.append(event);\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 /** 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 & Guards ====================\n readonly cardinalityChecks: readonly (CardinalityCheck | null)[];\n readonly hasGuards: 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 for (let tid = 0; tid < tc; tid++) {\n const t = compiled.transition(tid);\n consumeOps[tid] = compileConsumeProgram(t, compiled);\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 & Guards ====================\n const cardinalityChecks: (CardinalityCheck | null)[] = new Array(tc);\n const hasGuards: boolean[] = new Array(tc);\n for (let tid = 0; tid < tc; tid++) {\n cardinalityChecks[tid] = compiled.cardinalityCheck(tid);\n hasGuards[tid] = compiled.hasGuards(tid);\n }\n this.cardinalityChecks = cardinalityChecks;\n this.hasGuards = hasGuards;\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) !== 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) !== 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(t: Transition, compiled: CompiledNet): 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 for (const arc of t.resets) {\n const pid = compiled.placeId(arc.place);\n ops.push(RESET, pid);\n }\n\n return ops;\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 } 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, DEADLINE_TOLERANCE_MS } from './executor-support.js';\nimport { OutViolationError } from './out-violation-error.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\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 // ==================== 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.placeId(place);\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\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): Promise<Marking> {\n if (timeoutMs !== undefined) {\n let timer: ReturnType<typeof setTimeout> | undefined;\n const timeoutPromise = new Promise<never>((_, reject) => {\n timer = setTimeout(() => reject(new Error('Execution timed out')), timeoutMs);\n });\n try {\n return await Promise.race([this.executeLoop(), timeoutPromise]);\n } finally {\n if (timer !== undefined) clearTimeout(timer);\n }\n }\n return this.executeLoop();\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 // Guard check\n if (prog.hasGuards[tid]) {\n const t = prog.compiled.transition(tid);\n for (const spec of t.inputSpecs) {\n if (!spec.guard) continue;\n const required = spec.type === 'one' ? 1\n : spec.type === 'exactly' ? spec.count\n : spec.type === 'at-least' ? spec.minimum\n : 1;\n if (this.countMatching(prog.compiled.placeId(spec.place), spec.guard) < required) return false;\n }\n }\n\n return true;\n }\n\n private countMatching(pid: number, guard: (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 (guard(q[i]!.value)) matching++;\n }\n return matching;\n }\n\n private removeFirstMatching(pid: number, guard: (value: any) => boolean): Token<any> | null {\n const q = this.tokenQueues[pid]!;\n for (let i = 0; i < q.length; i++) {\n if (guard(q[i]!.value)) {\n return 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.fireTransition(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.fireTransition(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 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 if (prog.hasGuards[tid]) {\n this.fireTransitionGuarded(tid, t, inputs, consumed);\n } else {\n const ops = prog.consumeOps[tid]!;\n let pc = 0;\n while (pc < ops.length) {\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 case RESET: {\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 break;\n }\n }\n }\n }\n\n // Read arcs\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 // 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\n // Create action promise with optional timeout\n let actionPromise = t.action(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 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 private fireTransitionGuarded(_tid: number, t: Transition, inputs: TokenInput, consumed: Token<any>[]): void {\n const prog = this.program;\n\n for (const inSpec of t.inputSpecs) {\n const pid = prog.compiled.placeId(inSpec.place);\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 toConsume = inSpec.guard\n ? this.countMatching(pid, inSpec.guard)\n : this.tokenQueues[pid]!.length;\n break;\n case 'at-least':\n toConsume = inSpec.guard\n ? this.countMatching(pid, inSpec.guard)\n : this.tokenQueues[pid]!.length;\n break;\n }\n\n const guardFn = inSpec.guard;\n for (let i = 0; i < toConsume; i++) {\n const token = guardFn\n ? this.removeFirstMatching(pid, guardFn)\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 // 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 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 throw new OutViolationError(\n `'${t.name}': output does not satisfy declared spec`\n );\n }\n } else if (simplePid === -1) {\n const produced = outputs.placesWithTokens();\n const result = validateOutSpec(t.name, t.outputSpec, produced);\n if (result === null) {\n throw new OutViolationError(\n `'${t.name}': output does not satisfy declared spec`\n );\n }\n }\n }\n\n // Add output tokens to queues\n const produced: Token<any>[] = [];\n for (const entry of outputs.entries()) {\n const pid = prog.compiled.placeId(entry.place);\n this.tokenQueues[pid]!.push(entry.token);\n produced.push(entry.token);\n this.setMarkingBit(pid);\n this.markDirty(pid);\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 prog = this.program;\n const len = this.externalQueue.length;\n\n for (let i = 0; i < len; i++) {\n const event = this.externalQueue[i]!;\n try {\n const pid = prog.compiled.placeId(event.place);\n this.tokenQueues[pid]!.push(event.token);\n this.setMarkingBit(pid);\n this.markDirty(pid);\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 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 // External event wake-up\n promises.push(new Promise<void>(resolve => { this.wakeUpResolve = resolve; }));\n\n // Timer for next timed transition\n const timerMs = this.millisUntilNextTimedTransition();\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 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 this.eventStore.append(event);\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;;;ACaO,SAAS,SAAYA,QAAiB,OAA4C;AACvF,SAAO,UAAU,SAAY,EAAE,MAAM,SAAS,OAAAA,QAAO,MAAM,IAAI,EAAE,MAAM,SAAS,OAAAA,OAAM;AACxF;AAGO,SAAS,UAAaA,QAA+B;AAC1D,SAAO,EAAE,MAAM,UAAU,OAAAA,OAAM;AACjC;AAGO,SAAS,aAAgBA,QAAkC;AAChE,SAAO,EAAE,MAAM,aAAa,OAAAA,OAAM;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AAW;AAChB,SAAK,SAAS;AACd,SAAK,OAAO;AAAA,EACd;AAAA;AAAA,EAIQ,UAAU,OAAuB;AACvC,QAAI,KAAK,mBAAmB;AAC1B,WAAK,WAAW,OAAO,KAAK;AAAA,IAC9B;AAAA,EACF;AACF;AAEA,IAAME,mBAAN,cAA8B,MAAM;AAAA,EAClC,cAAc;AAAE,UAAM,gBAAgB;AAAG,SAAK,OAAO;AAAA,EAAmB;AAC1E;","names":["place","place","place","timeoutPlace","resolve","place","place","place","place","place","EMPTY_ALIAS","i","place","place","place","place","place","resolve","place","requiredCount","produced","place","resolve","TimeoutSentinel","produced"]}
|
|
1
|
+
{"version":3,"sources":["../src/core/token.ts","../src/core/place.ts","../src/core/arc.ts","../src/core/in.ts","../src/core/transition-action.ts","../src/core/transition-context.ts","../src/core/token-input.ts","../src/core/token-output.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/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 readonly guard?: (value: T) => boolean;\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>, guard?: (value: T) => boolean): ArcInput<T> {\n return guard !== undefined ? { type: 'input', place, guard } : { 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/** Checks if an input arc has a guard predicate. */\nexport function hasGuard(arc: ArcInput): boolean {\n return arc.guard !== undefined;\n}\n\n/** Checks if a token value matches an input arc's guard. */\nexport function matchesGuard<T>(arc: ArcInput<T>, value: T): boolean {\n if (arc.guard === undefined) return true;\n return arc.guard(value);\n}\n","import type { Place } from './place.js';\n\n/**\n * Input specification with cardinality and optional guard predicate.\n * CPN-compliant: cardinality determines how many tokens to consume,\n * guard filters which tokens are eligible.\n *\n * Inputs are always AND-joined (all must be satisfied to enable transition).\n * XOR on inputs is modeled via multiple transitions (conflict).\n */\nexport type In = InOne | InExactly | InAll | InAtLeast;\n\nexport interface InOne<T = any> {\n readonly type: 'one';\n readonly place: Place<T>;\n readonly guard?: (value: T) => boolean;\n}\n\nexport interface InExactly<T = any> {\n readonly type: 'exactly';\n readonly place: Place<T>;\n readonly count: number;\n readonly guard?: (value: T) => boolean;\n}\n\nexport interface InAll<T = any> {\n readonly type: 'all';\n readonly place: Place<T>;\n readonly guard?: (value: T) => boolean;\n}\n\nexport interface InAtLeast<T = any> {\n readonly type: 'at-least';\n readonly place: Place<T>;\n readonly minimum: number;\n readonly guard?: (value: T) => boolean;\n}\n\n// ==================== Factory Functions ====================\n\n/** Consume exactly 1 token (standard CPN semantics). Optional guard filters eligible tokens. */\nexport function one<T>(place: Place<T>, guard?: (value: T) => boolean): InOne<T> {\n return guard !== undefined ? { type: 'one', place, guard } : { type: 'one', place };\n}\n\n/** Consume exactly N tokens (batching). Optional guard filters eligible tokens. */\nexport function exactly<T>(count: number, place: Place<T>, guard?: (value: T) => boolean): InExactly<T> {\n if (count < 1) {\n throw new Error(`count must be >= 1, got: ${count}`);\n }\n return guard !== undefined ? { type: 'exactly', place, count, guard } : { type: 'exactly', place, count };\n}\n\n/** Consume all available tokens (must be 1+). Optional guard filters eligible tokens. */\nexport function all<T>(place: Place<T>, guard?: (value: T) => boolean): InAll<T> {\n return guard !== undefined ? { type: 'all', place, guard } : { type: 'all', place };\n}\n\n/** Wait for N+ tokens, consume all when enabled. Optional guard filters eligible tokens. */\nexport function atLeast<T>(minimum: number, place: Place<T>, guard?: (value: T) => boolean): InAtLeast<T> {\n if (minimum < 1) {\n throw new Error(`minimum must be >= 1, got: ${minimum}`);\n }\n return guard !== undefined\n ? { type: 'at-least', place, minimum, guard }\n : { type: 'at-least', place, minimum };\n}\n\n// ==================== Helper Functions ====================\n\n/** Returns the minimum number of tokens required to enable. */\nexport function requiredCount(spec: In): number {\n switch (spec.type) {\n case 'one': return 1;\n case 'exactly': return spec.count;\n case 'all': return 1;\n case 'at-least': return spec.minimum;\n }\n}\n\n/**\n * Returns the actual number of tokens to consume given the available count.\n * - One: always consumes 1\n * - Exactly: always consumes exactly count\n * - All: consumes all available\n * - AtLeast: consumes all available (when enabled, i.e., >= minimum)\n */\nexport function consumptionCount(spec: In, available: number): number {\n if (available < requiredCount(spec)) {\n throw new Error(\n `Cannot consume from '${spec.place.name}': available=${available}, required=${requiredCount(spec)}`\n );\n }\n switch (spec.type) {\n case 'one': return 1;\n case 'exactly': return spec.count;\n case 'all': return available;\n case 'at-least': return available;\n }\n}\n","import type { Place } from './place.js';\nimport type { TransitionContext } from './transition-context.js';\n\n/**\n * The action executed when a transition fires.\n * Receives a TransitionContext providing filtered I/O and structure access.\n */\nexport type TransitionAction = (ctx: TransitionContext) => Promise<void>;\n\n// ==================== Built-in Actions ====================\n\n/**\n * Identity action: produces no outputs.\n *\n * Returns a stable singleton reference (cached on first call). Reference\n * stability is relied on by {@link import('./internal/subnet-rewriter.js')\n * .composeActions} during channel composition (MOD-021) to short-circuit a\n * passthrough-on-both-sides merge to passthrough — saving a microtask hop\n * and matching the Java implementation's behaviour where both transitions'\n * default actions collapse to the builder's own passthrough default.\n */\nexport function passthrough(): TransitionAction {\n return PASSTHROUGH;\n}\n\n/** @internal Stable passthrough action — see {@link passthrough}. */\nconst PASSTHROUGH: TransitionAction = async () => {};\n\n/**\n * Transform action: applies function to context, copies result to ALL output places.\n *\n * @example\n * ```ts\n * const action = transform(ctx => ctx.input(inputPlace).toUpperCase());\n * // Result is copied to every declared output place\n * ```\n */\nexport function transform(fn: (ctx: TransitionContext) => unknown): TransitionAction {\n return async (ctx) => {\n const result = fn(ctx);\n for (const outputPlace of ctx.outputPlaces()) {\n ctx.output(outputPlace, result);\n }\n };\n}\n\n/**\n * Fork action: copies single input token to all outputs.\n * Requires exactly one input place (derived from structure).\n */\nexport function fork(): TransitionAction {\n return transform((ctx) => {\n const inputPlaces = ctx.inputPlaces();\n if (inputPlaces.size !== 1) {\n throw new Error(`Fork requires exactly 1 input place, found ${inputPlaces.size}`);\n }\n const inputPlace = inputPlaces.values().next().value as Place<any>;\n return ctx.input(inputPlace);\n });\n}\n\n/**\n * Transform with explicit input place.\n */\nexport function transformFrom<I>(inputPlace: Place<I>, fn: (value: I) => unknown): TransitionAction {\n return transform((ctx) => fn(ctx.input(inputPlace)));\n}\n\n/**\n * Async transform: applies async function, copies result to all outputs.\n */\nexport function transformAsync(fn: (ctx: TransitionContext) => Promise<unknown>): TransitionAction {\n return async (ctx) => {\n const result = await fn(ctx);\n for (const outputPlace of ctx.outputPlaces()) {\n ctx.output(outputPlace, result);\n }\n };\n}\n\n/** Produce action: produces a single token with the given value to the specified place. */\nexport function produce<T>(place: Place<T>, value: T): TransitionAction {\n return async (ctx) => {\n ctx.output(place, value);\n };\n}\n\n/**\n * Wraps an action with timeout handling.\n * If the action completes within the timeout, normal completion.\n * If the timeout expires, the timeoutValue is produced to the timeoutPlace.\n *\n * @example\n * ```ts\n * const action = withTimeout(\n * async (ctx) => { ctx.output(resultPlace, await fetchData()); },\n * 5000,\n * timeoutPlace,\n * 'timed-out',\n * );\n * ```\n */\nexport function withTimeout<T>(\n action: TransitionAction,\n timeoutMs: number,\n timeoutPlace: Place<T>,\n timeoutValue: T,\n): TransitionAction {\n return (ctx) => {\n return new Promise<void>((resolve, reject) => {\n let completed = false;\n const timer = setTimeout(() => {\n if (!completed) {\n completed = true;\n ctx.output(timeoutPlace, timeoutValue);\n resolve();\n }\n }, timeoutMs);\n action(ctx).then(\n () => {\n if (!completed) {\n completed = true;\n clearTimeout(timer);\n resolve();\n }\n },\n (err) => {\n if (!completed) {\n completed = true;\n clearTimeout(timer);\n reject(err);\n }\n },\n );\n });\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';\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 * 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 private readonly _rawOutput: 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\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._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._rawOutput.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._rawOutput.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 // ==================== 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 { 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 /** Add a value to an output place (creates token with current timestamp). */\n add<T>(place: Place<T>, value: T): 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 this._entries.push({ place, token });\n return this;\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 { ArcInhibitor, ArcRead, ArcReset } from './arc.js';\nimport type { In } from './in.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 * 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 ) {\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\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\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 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 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 );\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 { Timing } from '../timing.js';\nimport type { TransitionAction } from '../transition-action.js';\nimport { passthrough } 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: rebuilds `t` with the supplied `name` and arc places\n * rewritten through `remap`. Used by both {@link rewriteTransition} (which\n * prefixes the name) and {@link substitutePlaces} (which keeps the name\n * unchanged).\n */\nfunction rebuildWithName(\n t: Transition,\n name: string,\n remap: Map<string, Place<unknown>>,\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(...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 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`. Guards are\n * carried through by reference.\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), spec.guard);\n case 'exactly':\n return exactly(spec.count, resolve(spec.place, remap), spec.guard);\n case 'all':\n return all(resolve(spec.place, remap), spec.guard);\n case 'at-least':\n return atLeast(spec.minimum, resolve(spec.place, remap), spec.guard);\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. Duplicates (by structural key — same arc kind +\n * place name) are deduped so identical arcs to a shared place collapse.\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 (per [MOD-021]) — the message names the\n * channel and both timings 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 first so a conflict short-circuits before any building.\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\n const builder = Transition.builder(mergedName)\n .timing(mergedTiming)\n .priority(mergedPriority);\n if (mergedAction !== undefined) {\n builder.action(mergedAction);\n }\n\n // Inputs: union caller-first, then instance, dedup by (kind, place name,\n // count/minimum where applicable). Guard predicates are reference-compared\n // — two equal-shaped arcs with different guard closures are treated as\n // distinct (the safest default, matching Java's record-equality dedupe\n // when guards are absent and conservatively avoiding silent guard merges).\n const unionedInputs = unionArcs<In>(caller.inputSpecs, instance.inputSpecs, keyOfIn);\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 return builder.build();\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 passthrough}, so the `undefined` branches are defensive — they exist\n * so this helper is robust if upstream 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\n/**\n * Reference identity check against the singleton passthrough action.\n *\n * {@link passthrough} returns a stable cached reference, so identity\n * comparison reliably detects \"this is the no-op default action\". Used by\n * {@link composeActions} to collapse passthrough-on-both-sides to\n * passthrough — saving a microtask hop and matching the Java\n * implementation's behaviour where both transitions' default actions\n * collapse to the builder's own passthrough default.\n */\nconst PASSTHROUGH_REF = passthrough();\nfunction isPassthrough(action: TransitionAction): boolean {\n return action === PASSTHROUGH_REF;\n}\n\n/**\n * Structural key for an {@link In} arc. Encodes the discriminant + place\n * name + cardinality (where applicable). Guard predicates are NOT folded\n * into the key — two arcs of the same shape with different guard closures\n * are treated as distinct (the safe default).\n */\nfunction keyOfIn(arc: In): string {\n switch (arc.type) {\n case 'one':\n return arc.guard === undefined\n ? `one|${arc.place.name}`\n : `one|${arc.place.name}|g:${guardKey(arc.guard)}`;\n case 'exactly':\n return arc.guard === undefined\n ? `exactly|${arc.place.name}|${arc.count}`\n : `exactly|${arc.place.name}|${arc.count}|g:${guardKey(arc.guard)}`;\n case 'all':\n return arc.guard === undefined\n ? `all|${arc.place.name}`\n : `all|${arc.place.name}|g:${guardKey(arc.guard)}`;\n case 'at-least':\n return arc.guard === undefined\n ? `atLeast|${arc.place.name}|${arc.minimum}`\n : `atLeast|${arc.place.name}|${arc.minimum}|g:${guardKey(arc.guard)}`;\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 * Identity-only key for guard closures. Two distinct closure references\n * yield distinct keys; reusing the same closure across arcs collapses them.\n * We use a WeakMap so guard closures don't hold extra retention, and the\n * counter assigned per closure is stable across calls within one process.\n */\nconst GUARD_KEYS = new WeakMap<object, string>();\nlet guardKeyCounter = 0;\nfunction guardKey(g: object): string {\n let k = GUARD_KEYS.get(g);\n if (k === undefined) {\n k = String(++guardKeyCounter);\n GUARD_KEYS.set(g, k);\n }\n return k;\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 substitutePlaces}; 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 by {@link substitutePlaces} (a fresh\n * `Transition` instance); callers that care about identity preservation for\n * un-affected transitions should instead skip the rewrite entirely when\n * `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 * @param transitions the transitions to rewrite (non-null, may be empty)\n * @param fusionMap non-canonical name → canonical place remap (non-null)\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): Set<Transition> {\n const rewritten = new Set<Transition>();\n for (const t of transitions) {\n rewritten.add(substitutePlaces(t, fusionMap));\n }\n return rewritten;\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 * 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 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';\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(harness: VerificationHarness<P>): 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 // 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 const verifier = SmtVerifier.forNet(syntheticNet).property(property);\n if (envPlaces.length > 0) {\n verifier.environmentPlaces(...envPlaces);\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 bindActionsWithResolver(actionResolver: (name: string) => TransitionAction): 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.\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.\n const rewrittenTransitions = applyFusion(this._transitions, fusionMap);\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 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/** Anything that carries a place reference and an optional guard predicate. */\nexport interface GuardSpec<T = any> {\n readonly place: Place<T>;\n readonly guard?: (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 guard predicate.\n *\n * Performs a linear scan of the place's FIFO queue. If no guard is provided,\n * behaves like `removeFirst()`. If a guard is provided, skips non-matching\n * tokens and splices the first match out of the queue (O(n) worst case).\n */\n removeFirstMatching(spec: GuardSpec): Token<any> | null {\n const queue = this.tokens.get(spec.place.name);\n if (!queue || queue.length === 0) return null;\n if (!spec.guard) {\n return queue.shift()!;\n }\n for (let i = 0; i < queue.length; i++) {\n const token = queue[i]!;\n if (spec.guard(token.value)) {\n queue.splice(i, 1);\n return token;\n }\n }\n return null;\n }\n\n // ======================== Token Inspection ========================\n\n /** Check if any token matches a guard predicate. */\n hasMatchingToken(spec: GuardSpec): boolean {\n const queue = this.tokens.get(spec.place.name);\n if (!queue || queue.length === 0) return false;\n if (!spec.guard) return true;\n return queue.some(t => spec.guard!(t.value));\n }\n\n /**\n * Counts tokens in a place whose values satisfy the guard predicate.\n *\n * If no guard is provided, returns the total token count (O(1)).\n * With a guard, performs a linear scan over all tokens (O(n)).\n * Used by the executor for enablement checks on guarded `all`/`at-least` inputs.\n */\n countMatching(spec: GuardSpec): number {\n const queue = this.tokens.get(spec.place.name);\n if (!queue || queue.length === 0) return 0;\n if (!spec.guard) return queue.length;\n let count = 0;\n for (const t of queue) {\n if (spec.guard(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';\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 and guard flags\n private readonly _cardinalityChecks: (CardinalityCheck | null)[];\n private readonly _hasGuards: boolean[];\n\n private constructor(net: PetriNet) {\n this.net = 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._hasGuards = 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 const needs = new Uint32Array(this.wordCount);\n const inhibitors = new Uint32Array(this.wordCount);\n\n let needsCardinality = false;\n\n // Input specs\n for (const inSpec of t.inputSpecs) {\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 if (inSpec.guard) {\n this._hasGuards[tid] = 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 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 hasGuards(tid: number): boolean {\n return this._hasGuards[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 guard checks\n * are performed separately by the executor for transitions that pass this 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 * 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 { TransitionContext } from '../core/transition-context.js';\nimport { OutViolationError } from './out-violation-error.js';\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 * Recursively validates that a transition's output satisfies its declared Out spec.\n *\n * @returns the set of claimed place names, or null if not satisfied\n * @throws OutViolationError if a structural violation is detected (e.g. XOR with 0 or 2+ branches)\n */\nexport function validateOutSpec(\n tName: string,\n spec: Out,\n producedPlaceNames: Set<string>,\n): Set<string> | null {\n switch (spec.type) {\n case 'place':\n return producedPlaceNames.has(spec.place.name)\n ? new Set([spec.place.name])\n : null;\n\n case 'forward-input':\n return producedPlaceNames.has(spec.to.name)\n ? new Set([spec.to.name])\n : null;\n\n case 'and': {\n const claimed = new Set<string>();\n for (const child of spec.children) {\n const result = validateOutSpec(tName, child, producedPlaceNames);\n if (result === null) return null;\n for (const p of result) claimed.add(p);\n }\n return claimed;\n }\n\n case 'xor': {\n const satisfied: Set<string>[] = [];\n for (const child of spec.children) {\n const result = validateOutSpec(tName, child, producedPlaceNames);\n if (result !== null) satisfied.push(result);\n }\n if (satisfied.length === 0) {\n throw new OutViolationError(\n `'${tName}': XOR violation - no branch produced (exactly 1 required)`\n );\n }\n if (satisfied.length > 1) {\n throw new OutViolationError(\n `'${tName}': XOR violation - multiple branches produced`\n );\n }\n return satisfied[0]!;\n }\n\n case 'timeout':\n return validateOutSpec(tName, spec.child, producedPlaceNames);\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 the consumed input token to the output place.\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 */\nexport function produceTimeoutOutput(context: TransitionContext, timeoutChild: Out): void {\n switch (timeoutChild.type) {\n case 'place':\n context.output(timeoutChild.place, null);\n break;\n case 'forward-input': {\n const value = context.input(timeoutChild.from);\n context.output(timeoutChild.to, value);\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 } 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 } from './marking.js';\nimport { validateOutSpec, produceTimeoutOutput, DEADLINE_TOLERANCE_MS } from './executor-support.js';\nimport { OutViolationError } from './out-violation-error.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 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 markedPlaces: 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 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.markedPlaces = 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\n // ======================== Execution ========================\n\n async run(timeoutMs?: number): Promise<Marking> {\n if (timeoutMs !== undefined) {\n let timer: ReturnType<typeof setTimeout> | undefined;\n const timeoutPromise = new Promise<never>((_, reject) => {\n timer = setTimeout(() => reject(new Error('Execution timed out')), timeoutMs);\n });\n try {\n return await Promise.race([this.executeLoop(), timeoutPromise]);\n } finally {\n if (timer !== undefined) clearTimeout(timer);\n }\n }\n return this.executeLoop();\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.initializeMarkedBitmap();\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 initializeMarkedBitmap(): 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.markedPlaces, 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 markedPlaces mid-scan.\n const markingSnap = this.markingSnapBuffer;\n markingSnap.set(this.markedPlaces);\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 // Guard check: verify matching tokens exist for each guarded input\n if (this.compiled.hasGuards(tid)) {\n const t = this.compiled.transition(tid);\n for (const spec of t.inputSpecs) {\n if (!spec.guard) continue;\n const requiredCount = spec.type === 'one' ? 1\n : spec.type === 'exactly' ? spec.count\n : spec.type === 'at-least' ? spec.minimum\n : 1; // 'all' requires at least 1 matching\n if (this.marking.countMatching(spec) < requiredCount) 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 `markedPlaces` 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.markedPlaces)) {\n this.fireTransition(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.markedPlaces);\n for (const entry of ready) {\n const { tid } = entry;\n if (this.enabledFlags[tid] && this.canEnable(tid, freshSnap)) {\n this.fireTransition(tid);\n // Update snapshot after consuming tokens\n freshSnap.set(this.markedPlaces);\n } else {\n this.enabledFlags[tid] = 0;\n this.enabledTransitionCount--;\n this.enabledAtMs[tid] = -Infinity;\n }\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 and guard.\n // Note: for guarded 'all'/'at-least' inputs, countMatching() is called here AND in\n // canEnable() — a known O(2n) tradeoff. Token queues are typically ≤10 items, so\n // the simplicity of re-scanning outweighs caching complexity.\n for (const inSpec of t.inputSpecs) {\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 toConsume = inSpec.guard\n ? this.marking.countMatching(inSpec)\n : this.marking.tokenCount(inSpec.place);\n break;\n case 'at-least':\n toConsume = inSpec.guard\n ? this.marking.countMatching(inSpec)\n : this.marking.tokenCount(inSpec.place);\n break;\n }\n\n for (let i = 0; i < toConsume; i++) {\n const token = inSpec.guard\n ? this.marking.removeFirstMatching(inSpec)\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\n // Create action promise with optional timeout\n let actionPromise = t.action(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 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.markedPlaces, 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 result = validateOutSpec(t.name, t.outputSpec, produced);\n if (result === null) {\n throw new OutViolationError(\n `'${t.name}': output does not satisfy declared spec`\n );\n }\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 this.marking.addToken(entry.place, entry.token);\n produced.push(entry.token);\n const pid = this.compiled.placeId(entry.place);\n setBit(this.markedPlaces, pid);\n this.markDirty(pid);\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 this.marking.addToken(event.place, event.token);\n const pid = this.compiled.placeId(event.place);\n setBit(this.markedPlaces, pid);\n this.markDirty(pid);\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 // 2. External event wake-up\n promises.push(new Promise<void>(resolve => { this.wakeUpResolve = resolve; }));\n\n // 3. Timer for next delayed transition\n const timerMs = this.millisUntilNextTimedTransition();\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 private emitEvent(event: NetEvent): void {\n if (this.eventStoreEnabled) {\n this.eventStore.append(event);\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 /** 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 & Guards ====================\n readonly cardinalityChecks: readonly (CardinalityCheck | null)[];\n readonly hasGuards: 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 for (let tid = 0; tid < tc; tid++) {\n const t = compiled.transition(tid);\n consumeOps[tid] = compileConsumeProgram(t, compiled);\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 & Guards ====================\n const cardinalityChecks: (CardinalityCheck | null)[] = new Array(tc);\n const hasGuards: boolean[] = new Array(tc);\n for (let tid = 0; tid < tc; tid++) {\n cardinalityChecks[tid] = compiled.cardinalityCheck(tid);\n hasGuards[tid] = compiled.hasGuards(tid);\n }\n this.cardinalityChecks = cardinalityChecks;\n this.hasGuards = hasGuards;\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) !== 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) !== 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(t: Transition, compiled: CompiledNet): 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 for (const arc of t.resets) {\n const pid = compiled.placeId(arc.place);\n ops.push(RESET, pid);\n }\n\n return ops;\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 } 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, DEADLINE_TOLERANCE_MS } from './executor-support.js';\nimport { OutViolationError } from './out-violation-error.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\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 // ==================== 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.placeId(place);\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\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): Promise<Marking> {\n if (timeoutMs !== undefined) {\n let timer: ReturnType<typeof setTimeout> | undefined;\n const timeoutPromise = new Promise<never>((_, reject) => {\n timer = setTimeout(() => reject(new Error('Execution timed out')), timeoutMs);\n });\n try {\n return await Promise.race([this.executeLoop(), timeoutPromise]);\n } finally {\n if (timer !== undefined) clearTimeout(timer);\n }\n }\n return this.executeLoop();\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 // Guard check\n if (prog.hasGuards[tid]) {\n const t = prog.compiled.transition(tid);\n for (const spec of t.inputSpecs) {\n if (!spec.guard) continue;\n const required = spec.type === 'one' ? 1\n : spec.type === 'exactly' ? spec.count\n : spec.type === 'at-least' ? spec.minimum\n : 1;\n if (this.countMatching(prog.compiled.placeId(spec.place), spec.guard) < required) return false;\n }\n }\n\n return true;\n }\n\n private countMatching(pid: number, guard: (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 (guard(q[i]!.value)) matching++;\n }\n return matching;\n }\n\n private removeFirstMatching(pid: number, guard: (value: any) => boolean): Token<any> | null {\n const q = this.tokenQueues[pid]!;\n for (let i = 0; i < q.length; i++) {\n if (guard(q[i]!.value)) {\n return 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.fireTransition(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.fireTransition(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 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 if (prog.hasGuards[tid]) {\n this.fireTransitionGuarded(tid, t, inputs, consumed);\n } else {\n const ops = prog.consumeOps[tid]!;\n let pc = 0;\n while (pc < ops.length) {\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 case RESET: {\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 break;\n }\n }\n }\n }\n\n // Read arcs\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 // 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\n // Create action promise with optional timeout\n let actionPromise = t.action(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 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 private fireTransitionGuarded(_tid: number, t: Transition, inputs: TokenInput, consumed: Token<any>[]): void {\n const prog = this.program;\n\n for (const inSpec of t.inputSpecs) {\n const pid = prog.compiled.placeId(inSpec.place);\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 toConsume = inSpec.guard\n ? this.countMatching(pid, inSpec.guard)\n : this.tokenQueues[pid]!.length;\n break;\n case 'at-least':\n toConsume = inSpec.guard\n ? this.countMatching(pid, inSpec.guard)\n : this.tokenQueues[pid]!.length;\n break;\n }\n\n const guardFn = inSpec.guard;\n for (let i = 0; i < toConsume; i++) {\n const token = guardFn\n ? this.removeFirstMatching(pid, guardFn)\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 // 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 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 throw new OutViolationError(\n `'${t.name}': output does not satisfy declared spec`\n );\n }\n } else if (simplePid === -1) {\n const produced = outputs.placesWithTokens();\n const result = validateOutSpec(t.name, t.outputSpec, produced);\n if (result === null) {\n throw new OutViolationError(\n `'${t.name}': output does not satisfy declared spec`\n );\n }\n }\n }\n\n // Add output tokens to queues\n const produced: Token<any>[] = [];\n for (const entry of outputs.entries()) {\n const pid = prog.compiled.placeId(entry.place);\n this.tokenQueues[pid]!.push(entry.token);\n produced.push(entry.token);\n this.setMarkingBit(pid);\n this.markDirty(pid);\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 prog = this.program;\n const len = this.externalQueue.length;\n\n for (let i = 0; i < len; i++) {\n const event = this.externalQueue[i]!;\n try {\n const pid = prog.compiled.placeId(event.place);\n this.tokenQueues[pid]!.push(event.token);\n this.setMarkingBit(pid);\n this.markDirty(pid);\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 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 // External event wake-up\n promises.push(new Promise<void>(resolve => { this.wakeUpResolve = resolve; }));\n\n // Timer for next timed transition\n const timerMs = this.millisUntilNextTimedTransition();\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 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 this.eventStore.append(event);\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,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OAAO;AAC9C,YAAM,IAAI,KAAK,YAAY,GAAG;AAC9B,UAAI,EAAE,WAAW,EAAG;AACpB,WAAK,IAAI,KAAK,OAAO,GAAG,EAAG,MAAM,CAAC,GAAG,CAAC,CAAC;AAAA,IACzC;AACA,WAAO;AAAA,EACT;AAAA,EAEA,cAAuB;AACrB,WAAO,KAAK,2BAA2B,KAAK,KAAK,kBAAkB;AAAA,EACrE;AAAA,EAEA,cAAsB;AACpB,WAAO,KAAK,QAAQ,SAAS,EAAE;AAAA,EACjC;AAAA,EAEA,QAAc;AACZ,SAAK,WAAW;AAChB,SAAK,OAAO;AAAA,EACd;AAAA,EAEA,QAAc;AACZ,SAAK,WAAW;AAChB,SAAK,SAAS;AACd,SAAK,OAAO;AAAA,EACd;AAAA;AAAA,EAIQ,UAAU,OAAuB;AACvC,QAAI,KAAK,mBAAmB;AAC1B,WAAK,WAAW,OAAO,KAAK;AAAA,IAC9B;AAAA,EACF;AACF;AAEA,IAAME,mBAAN,cAA8B,MAAM;AAAA,EAClC,cAAc;AAAE,UAAM,gBAAgB;AAAG,SAAK,OAAO;AAAA,EAAmB;AAC1E;","names":["place","place","place","timeoutPlace","resolve","place","place","place","place","place","EMPTY_ALIAS","i","place","place","place","place","place","resolve","place","requiredCount","produced","place","resolve","TimeoutSentinel","produced"]}
|