libpetri 2.7.0 → 2.8.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/chunk-E3ZWB645.js +27 -0
- package/dist/chunk-E3ZWB645.js.map +1 -0
- package/dist/{chunk-ULX3OG6H.js → chunk-JVI5HFRX.js} +12 -6
- package/dist/chunk-JVI5HFRX.js.map +1 -0
- package/dist/chunk-M3KT7BFO.js +2773 -0
- package/dist/chunk-M3KT7BFO.js.map +1 -0
- package/dist/debug/index.d.ts +2 -2
- package/dist/debug/index.js +2 -1
- package/dist/debug/index.js.map +1 -1
- package/dist/doclet/index.d.ts +1 -1
- package/dist/doclet/index.js +3 -2
- package/dist/doclet/index.js.map +1 -1
- package/dist/dot-exporter-SHBYMMJ3.js +9 -0
- package/dist/{event-store-8XkpYUeU.d.ts → event-store-CAkN_ayv.d.ts} +1 -1
- package/dist/export/index.d.ts +1 -1
- package/dist/export/index.js +2 -1
- package/dist/index.d.ts +27 -4
- package/dist/index.js +280 -8
- package/dist/index.js.map +1 -1
- package/dist/{petri-net-D73-PO6d.d.ts → petri-net-B4wQwsUj.d.ts} +140 -3
- package/dist/verification/index.d.ts +40 -2
- package/dist/verification/index.js +9 -508
- package/dist/verification/index.js.map +1 -1
- package/package.json +1 -1
- package/dist/chunk-ETNHEAS6.js +0 -1458
- package/dist/chunk-ETNHEAS6.js.map +0 -1
- package/dist/chunk-ULX3OG6H.js.map +0 -1
- package/dist/dot-exporter-TYC6FUAD.js +0 -8
- /package/dist/{dot-exporter-TYC6FUAD.js.map → dot-exporter-SHBYMMJ3.js.map} +0 -0
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/core/out.ts","../src/verification/marking-state.ts","../src/verification/smt-property.ts","../src/verification/encoding/flat-transition.ts","../src/verification/analysis/environment-analysis-mode.ts","../src/verification/encoding/net-flattener.ts","../src/verification/encoding/incidence-matrix.ts","../src/verification/invariant/p-invariant.ts","../src/verification/invariant/p-invariant-computer.ts","../src/verification/invariant/structural-check.ts","../src/verification/z3/spacer-runner.ts","../src/verification/encoding/flat-net.ts","../src/verification/z3/smt-encoder.ts","../src/verification/z3/counterexample-decoder.ts","../src/verification/smt-verifier.ts","../src/verification/smt-verification-result.ts"],"sourcesContent":["import type { Place } from './place.js';\n\n/**\n * Output specification with explicit split semantics.\n * Supports composite structures (XOR of ANDs, AND of XORs, etc.)\n *\n * - And: ALL children must receive tokens\n * - Xor: EXACTLY ONE child receives token\n * - Place: Leaf node representing a single output place\n * - Timeout: Timeout branch that activates if action exceeds duration\n * - ForwardInput: Forward consumed input to output on timeout\n */\nexport type Out = OutAnd | OutXor | OutPlace | OutTimeout | OutForwardInput;\n\nexport interface OutAnd {\n readonly type: 'and';\n readonly children: readonly Out[];\n}\n\nexport interface OutXor {\n readonly type: 'xor';\n readonly children: readonly Out[];\n}\n\nexport interface OutPlace {\n readonly type: 'place';\n readonly place: Place<any>;\n}\n\nexport interface OutTimeout {\n readonly type: 'timeout';\n /** Timeout duration in milliseconds. */\n readonly afterMs: number;\n readonly child: Out;\n}\n\nexport interface OutForwardInput {\n readonly type: 'forward-input';\n readonly from: Place<any>;\n readonly to: Place<any>;\n}\n\n// ==================== Factory Functions ====================\n\n/**\n * AND-split: all children must receive tokens.\n *\n * @example\n * ```ts\n * // AND of XOR branches: one of (A,B) AND one of (C,D)\n * and(xorPlaces(placeA, placeB), xorPlaces(placeC, placeD))\n *\n * // AND with a fixed place + XOR branch\n * and(outPlace(always), xorPlaces(left, right))\n * ```\n */\nexport function and(...children: Out[]): OutAnd {\n if (children.length === 0) {\n throw new Error('AND requires at least 1 child');\n }\n return { type: 'and', children };\n}\n\n/** AND-split from places: all places must receive tokens. */\nexport function andPlaces(...places: Place<any>[]): OutAnd {\n return and(...places.map(outPlace));\n}\n\n/** XOR-split: exactly one child receives token. */\nexport function xor(...children: Out[]): OutXor {\n if (children.length < 2) {\n throw new Error('XOR requires at least 2 children');\n }\n return { type: 'xor', children };\n}\n\n/** XOR-split from places: exactly one place receives token. */\nexport function xorPlaces(...places: Place<any>[]): OutXor {\n return xor(...places.map(outPlace));\n}\n\n/** Leaf output spec for a single place. */\nexport function outPlace(p: Place<any>): OutPlace {\n return { type: 'place', place: p };\n}\n\n/** Timeout output: activates if action exceeds duration. */\nexport function timeout(afterMs: number, child: Out): OutTimeout {\n if (afterMs <= 0) {\n throw new Error(`Timeout must be positive: ${afterMs}`);\n }\n return { type: 'timeout', afterMs, child };\n}\n\n/** Timeout output pointing to a single place. */\nexport function timeoutPlace(afterMs: number, p: Place<any>): OutTimeout {\n return timeout(afterMs, outPlace(p));\n}\n\n/** Forward consumed input value to output place on timeout. */\nexport function forwardInput(from: Place<any>, to: Place<any>): OutForwardInput {\n return { type: 'forward-input', from, to };\n}\n\n// ==================== Helper Functions ====================\n\n/** Collects all leaf places from this output spec (flattened). */\nexport function allPlaces(out: Out): Set<Place<any>> {\n const result = new Set<Place<any>>();\n collectPlaces(out, result);\n return result;\n}\n\nfunction collectPlaces(out: Out, result: Set<Place<any>>): void {\n switch (out.type) {\n case 'place':\n result.add(out.place);\n break;\n case 'forward-input':\n result.add(out.to);\n break;\n case 'and':\n case 'xor':\n for (const child of out.children) {\n collectPlaces(child, result);\n }\n break;\n case 'timeout':\n collectPlaces(out.child, result);\n break;\n }\n}\n\n/**\n * Enumerates all possible output branches for structural analysis.\n *\n * - AND = single branch containing all child places (Cartesian product)\n * - XOR = one branch per alternative child\n * - Nested = Cartesian product for AND, union for XOR\n */\nexport function enumerateBranches(out: Out): ReadonlyArray<ReadonlySet<Place<any>>> {\n switch (out.type) {\n case 'place':\n return [new Set([out.place])];\n\n case 'forward-input':\n return [new Set<Place<any>>([out.to])];\n\n case 'and': {\n let result: Set<Place<any>>[] = [new Set()];\n for (const child of out.children) {\n result = crossProduct(result, enumerateBranches(child) as Set<Place<any>>[]);\n }\n return result;\n }\n\n case 'xor': {\n const result: Set<Place<any>>[] = [];\n for (const child of out.children) {\n result.push(...(enumerateBranches(child) as Set<Place<any>>[]));\n }\n return result;\n }\n\n case 'timeout':\n return enumerateBranches(out.child);\n }\n}\n\nfunction crossProduct(\n a: Set<Place<any>>[],\n b: ReadonlyArray<ReadonlySet<Place<any>>>,\n): Set<Place<any>>[] {\n const result: Set<Place<any>>[] = [];\n for (const setA of a) {\n for (const setB of b) {\n const merged = new Set<Place<any>>(setA);\n for (const p of setB) merged.add(p);\n result.push(merged);\n }\n }\n return result;\n}\n","import type { Place } from '../core/place.js';\n\n/** @internal Symbol key restricting construction to the builder and factory methods. */\nconst MARKING_STATE_KEY = Symbol('MarkingState.internal');\n\n/**\n * Immutable snapshot of a Petri net marking for state space analysis.\n *\n * Maps places (by name) to integer token counts. Only stores places with count > 0.\n * Used for invariant computation and structural verification, not runtime execution.\n */\nexport class MarkingState {\n private readonly tokenCounts: ReadonlyMap<string, number>;\n private readonly placesByName: ReadonlyMap<string, Place<any>>;\n\n /** @internal Use {@link MarkingState.builder} or {@link MarkingState.empty} to create instances. */\n constructor(key: symbol, tokenCounts: Map<string, number>, placesByName: Map<string, Place<any>>) {\n if (key !== MARKING_STATE_KEY) throw new Error('Use MarkingState.builder() to create instances');\n this.tokenCounts = tokenCounts;\n this.placesByName = placesByName;\n }\n\n /** Returns the token count for a place (0 if absent). */\n tokens(place: Place<any>): number {\n return this.tokenCounts.get(place.name) ?? 0;\n }\n\n /** Checks if a place has at least one token. */\n hasTokens(place: Place<any>): boolean {\n return this.tokens(place) > 0;\n }\n\n /** Checks if any of the given places has tokens. */\n hasTokensInAny(places: Iterable<Place<any>>): boolean {\n for (const p of places) {\n if (this.hasTokens(p)) return true;\n }\n return false;\n }\n\n /** Returns all places with tokens > 0. */\n placesWithTokens(): Place<any>[] {\n return [...this.placesByName.values()];\n }\n\n /** Returns the total number of tokens. */\n totalTokens(): number {\n let sum = 0;\n for (const count of this.tokenCounts.values()) sum += count;\n return sum;\n }\n\n /** Checks if no tokens exist anywhere. */\n isEmpty(): boolean {\n return this.tokenCounts.size === 0;\n }\n\n toString(): string {\n if (this.tokenCounts.size === 0) return '{}';\n const entries = [...this.tokenCounts.entries()]\n .sort(([a], [b]) => a.localeCompare(b))\n .map(([name, count]) => `${name}:${count}`);\n return `{${entries.join(', ')}}`;\n }\n\n static empty(): MarkingState {\n return new MarkingState(MARKING_STATE_KEY, new Map(), new Map());\n }\n\n static builder(): MarkingStateBuilder {\n return new MarkingStateBuilder();\n }\n}\n\nexport class MarkingStateBuilder {\n private readonly tokenCounts = new Map<string, number>();\n private readonly placesByName = new Map<string, Place<any>>();\n\n /** Sets the token count for a place. */\n tokens(place: Place<any>, count: number): this {\n if (count < 0) throw new Error(`Token count cannot be negative: ${count}`);\n if (count > 0) {\n this.tokenCounts.set(place.name, count);\n this.placesByName.set(place.name, place);\n } else {\n this.tokenCounts.delete(place.name);\n this.placesByName.delete(place.name);\n }\n return this;\n }\n\n /** Adds tokens to a place. */\n addTokens(place: Place<any>, count: number): this {\n if (count < 0) throw new Error(`Token count cannot be negative: ${count}`);\n if (count > 0) {\n const current = this.tokenCounts.get(place.name) ?? 0;\n this.tokenCounts.set(place.name, current + count);\n this.placesByName.set(place.name, place);\n }\n return this;\n }\n\n /** Removes tokens from a place. Throws if insufficient. */\n removeTokens(place: Place<any>, count: number): this {\n const current = this.tokenCounts.get(place.name) ?? 0;\n const newCount = current - count;\n if (newCount < 0) {\n throw new Error(\n `Cannot remove ${count} tokens from ${place.name} (has ${current})`,\n );\n }\n if (newCount === 0) {\n this.tokenCounts.delete(place.name);\n this.placesByName.delete(place.name);\n } else {\n this.tokenCounts.set(place.name, newCount);\n }\n return this;\n }\n\n /** Copies all token counts from another marking state. */\n copyFrom(other: MarkingState): this {\n for (const p of other.placesWithTokens()) {\n this.tokenCounts.set(p.name, other.tokens(p));\n this.placesByName.set(p.name, p);\n }\n return this;\n }\n\n build(): MarkingState {\n return new MarkingState(MARKING_STATE_KEY, new Map(this.tokenCounts), new Map(this.placesByName));\n }\n}\n","import type { Place } from '../core/place.js';\n\n/**\n * Safety properties that can be verified via IC3/PDR.\n *\n * Each property is encoded as an error condition: if a reachable state\n * violates the property, Spacer finds a counterexample. If no violation\n * is reachable, the property is proven.\n */\nexport type SmtProperty = DeadlockFree | MutualExclusion | PlaceBound | Unreachable;\n\n/** Deadlock-freedom: no reachable marking has all transitions disabled. */\nexport interface DeadlockFree {\n readonly type: 'deadlock-free';\n}\n\n/** Mutual exclusion: two places never have tokens simultaneously. */\nexport interface MutualExclusion {\n readonly type: 'mutual-exclusion';\n readonly p1: Place<any>;\n readonly p2: Place<any>;\n}\n\n/** Place bound: a place never exceeds a given token count. */\nexport interface PlaceBound {\n readonly type: 'place-bound';\n readonly place: Place<any>;\n readonly bound: number;\n}\n\n/** Unreachability: the given places never all have tokens simultaneously. */\nexport interface Unreachable {\n readonly type: 'unreachable';\n readonly places: ReadonlySet<Place<any>>;\n}\n\n// Factory functions\n\nexport function deadlockFree(): DeadlockFree {\n return { type: 'deadlock-free' };\n}\n\nexport function mutualExclusion(p1: Place<any>, p2: Place<any>): MutualExclusion {\n return { type: 'mutual-exclusion', p1, p2 };\n}\n\nexport function placeBound(place: Place<any>, bound: number): PlaceBound {\n return { type: 'place-bound', place, bound };\n}\n\nexport function unreachable(places: ReadonlySet<Place<any>>): Unreachable {\n return { type: 'unreachable', places: new Set(places) };\n}\n\n/** Human-readable description of a property. */\nexport function propertyDescription(prop: SmtProperty): string {\n switch (prop.type) {\n case 'deadlock-free':\n return 'Deadlock-freedom';\n case 'mutual-exclusion':\n return `Mutual exclusion of ${prop.p1.name} and ${prop.p2.name}`;\n case 'place-bound':\n return `Place ${prop.place.name} bounded by ${prop.bound}`;\n case 'unreachable':\n return `Unreachability of marking with tokens in {${[...prop.places].map(p => p.name).join(', ')}}`;\n }\n}\n","import type { Transition } from '../../core/transition.js';\n\n/**\n * A flattened transition with pre/post vectors for SMT encoding.\n *\n * Each Transition with XOR outputs is expanded into multiple FlatTransitions\n * (one per branch). Non-XOR transitions map 1:1.\n */\nexport interface FlatTransition {\n /** Display name (e.g. \"Search_b0\", \"Search_b1\"). */\n readonly name: string;\n /** The original transition. */\n readonly source: Transition;\n /** Which XOR branch (-1 if no XOR). */\n readonly branchIndex: number;\n /** Tokens consumed per place (indexed by place index). */\n readonly preVector: readonly number[];\n /** Tokens produced per place (indexed by place index). */\n readonly postVector: readonly number[];\n /** Place indices where inhibitor arcs block firing. */\n readonly inhibitorPlaces: readonly number[];\n /** Place indices requiring a token without consuming. */\n readonly readPlaces: readonly number[];\n /** Place indices set to 0 on firing. */\n readonly resetPlaces: readonly number[];\n /** True at index i means place i uses All/AtLeast semantics. */\n readonly consumeAll: readonly boolean[];\n}\n\nexport function flatTransition(\n name: string,\n source: Transition,\n branchIndex: number,\n preVector: number[],\n postVector: number[],\n inhibitorPlaces: number[],\n readPlaces: number[],\n resetPlaces: number[],\n consumeAll: boolean[],\n): FlatTransition {\n return {\n name,\n source,\n branchIndex,\n preVector,\n postVector,\n inhibitorPlaces,\n readPlaces,\n resetPlaces,\n consumeAll,\n };\n}\n","/**\n * Analysis mode for environment places in state class graph construction.\n */\nexport type EnvironmentAnalysisMode =\n | { readonly type: 'always-available' }\n | { readonly type: 'bounded'; readonly maxTokens: number }\n | { readonly type: 'ignore' };\n\n/** Assumes environment places always have sufficient tokens. */\nexport function alwaysAvailable(): EnvironmentAnalysisMode {\n return { type: 'always-available' };\n}\n\n/** Analyzes with a bounded number of tokens in environment places. */\nexport function bounded(maxTokens: number): EnvironmentAnalysisMode {\n if (maxTokens < 0) throw new Error('maxTokens must be non-negative');\n return { type: 'bounded', maxTokens };\n}\n\n/** Treats environment places as regular places (default). */\nexport function ignore(): EnvironmentAnalysisMode {\n return { type: 'ignore' };\n}\n","/**\n * @module net-flattener\n *\n * Flattens a PetriNet into integer-indexed pre/post vectors for SMT encoding.\n *\n * **XOR expansion**: Transitions with XOR output specs are expanded into multiple\n * flat transitions — one per deterministic branch. Each branch produces tokens to\n * exactly one XOR child's places. This converts non-deterministic output routing\n * into separate transitions that the SMT solver can reason about independently.\n *\n * **Vector construction**: For each flat transition, builds:\n * - `preVector[p]`: tokens consumed from place p (input cardinality)\n * - `postVector[p]`: tokens produced to place p (from the selected branch)\n * - `consumeAll[p]`: true for `all`/`at-least` inputs (consume everything)\n * - Index arrays for inhibitor, read, and reset arcs\n *\n * Places are sorted by name for stable, deterministic indexing across runs.\n */\nimport type { PetriNet } from '../../core/petri-net.js';\nimport type { Place, EnvironmentPlace } from '../../core/place.js';\nimport type { Out } from '../../core/out.js';\nimport type { FlatNet } from './flat-net.js';\nimport { flatTransition } from './flat-transition.js';\nimport { enumerateBranches, allPlaces as outAllPlaces } from '../../core/out.js';\nimport { type EnvironmentAnalysisMode, alwaysAvailable } from '../analysis/environment-analysis-mode.js';\n\n// The SMT path shares the single 3-mode EnvironmentAnalysisMode with the state\n// class graph (VER-006): AlwaysAvailable / Bounded(k) / Ignore. Re-exported here\n// for the encoding barrel so existing `libpetri/verification` consumers resolve it.\nexport { type EnvironmentAnalysisMode, alwaysAvailable, bounded, ignore } from '../analysis/environment-analysis-mode.js';\n\n/**\n * Flattens a PetriNet into a FlatNet suitable for SMT encoding.\n *\n * Flattening involves:\n * 1. Assigning each place a stable integer index (sorted by name)\n * 2. Expanding XOR outputs into separate flat transitions (one per branch)\n * 3. Building pre/post vectors from input/output specs\n * 4. Recording inhibitor, read, and reset arcs\n * 5. Setting environment bounds for bounded analysis mode\n */\nexport function flatten(\n net: PetriNet,\n environmentPlaces: Set<EnvironmentPlace<any>> = new Set(),\n environmentMode: EnvironmentAnalysisMode = alwaysAvailable(),\n): FlatNet {\n // 1. Collect ALL places\n const allPlacesSet = new Map<string, Place<any>>();\n for (const p of net.places) {\n allPlacesSet.set(p.name, p);\n }\n for (const t of net.transitions) {\n for (const inSpec of t.inputSpecs) {\n allPlacesSet.set(inSpec.place.name, inSpec.place);\n }\n if (t.outputSpec !== null) {\n for (const p of outAllPlaces(t.outputSpec)) {\n allPlacesSet.set(p.name, p);\n }\n }\n for (const arc of t.inhibitors) allPlacesSet.set(arc.place.name, arc.place);\n for (const arc of t.reads) allPlacesSet.set(arc.place.name, arc.place);\n for (const arc of t.resets) allPlacesSet.set(arc.place.name, arc.place);\n }\n\n // Sort by name for stable indexing\n const places = [...allPlacesSet.values()].sort((a, b) => a.name.localeCompare(b.name));\n\n const placeIndex = new Map<string, number>();\n for (let i = 0; i < places.length; i++) {\n placeIndex.set(places[i]!.name, i);\n }\n\n // 2. Compute environment bounds (legacy post-cap) and the injection map.\n // The injection map drives the encoder's env-injection rule and the\n // incidence-matrix injector columns; bounds remain a harmless extra cap.\n const environmentBounds = new Map<string, number>();\n const environmentInjection = new Map<string, number | null>();\n switch (environmentMode.type) {\n case 'always-available':\n for (const ep of environmentPlaces) {\n environmentInjection.set(ep.place.name, null);\n }\n break;\n case 'bounded':\n for (const ep of environmentPlaces) {\n environmentBounds.set(ep.place.name, environmentMode.maxTokens);\n environmentInjection.set(ep.place.name, environmentMode.maxTokens);\n }\n break;\n case 'ignore':\n // Not modeled: env places stay ordinary (frozen at their initial count).\n break;\n }\n\n // 3. Expand transitions\n const n = places.length;\n const flatTransitions = [];\n\n for (const transition of net.transitions) {\n const branches = enumerateOutputBranches(transition);\n\n for (let branchIdx = 0; branchIdx < branches.length; branchIdx++) {\n const branchPlaces = branches[branchIdx]!;\n const name = branches.length > 1\n ? `${transition.name}_b${branchIdx}`\n : transition.name;\n\n // Build pre-vector and consumeAll flags\n const preVector = new Array<number>(n).fill(0);\n const consumeAll = new Array<boolean>(n).fill(false);\n\n for (const inSpec of transition.inputSpecs) {\n const idx = placeIndex.get(inSpec.place.name);\n if (idx === undefined) continue;\n\n switch (inSpec.type) {\n case 'one':\n preVector[idx] = 1;\n break;\n case 'exactly':\n preVector[idx] = inSpec.count;\n break;\n case 'all':\n preVector[idx] = 1;\n consumeAll[idx] = true;\n break;\n case 'at-least':\n preVector[idx] = inSpec.minimum;\n consumeAll[idx] = true;\n break;\n }\n }\n\n // Build post-vector from branch output places\n const postVector = new Array<number>(n).fill(0);\n for (const p of branchPlaces) {\n const idx = placeIndex.get(p.name);\n if (idx !== undefined) {\n postVector[idx] = 1;\n }\n }\n\n // Inhibitor places\n const inhibitorPlaces = transition.inhibitors\n .map(arc => placeIndex.get(arc.place.name))\n .filter((idx): idx is number => idx !== undefined);\n\n // Read places\n const readPlaces = transition.reads\n .map(arc => placeIndex.get(arc.place.name))\n .filter((idx): idx is number => idx !== undefined);\n\n // Reset places\n const resetPlaces = transition.resets\n .map(arc => placeIndex.get(arc.place.name))\n .filter((idx): idx is number => idx !== undefined);\n\n flatTransitions.push(flatTransition(\n name,\n transition,\n branches.length > 1 ? branchIdx : -1,\n preVector,\n postVector,\n inhibitorPlaces,\n readPlaces,\n resetPlaces,\n consumeAll,\n ));\n }\n }\n\n return {\n places,\n placeIndex,\n transitions: flatTransitions,\n environmentBounds,\n environmentInjection,\n };\n}\n\nfunction enumerateOutputBranches(t: { outputSpec: Out | null }): ReadonlySet<Place<any>>[] {\n if (t.outputSpec !== null) {\n return enumerateBranches(t.outputSpec) as ReadonlySet<Place<any>>[];\n }\n // No outputs (sink transition)\n return [new Set()];\n}\n","import type { FlatNet } from './flat-net.js';\n\n/**\n * Incidence matrix for a flattened Petri net.\n *\n * The incidence matrix C is defined as C[t][p] = post[t][p] - pre[t][p].\n * It captures the net effect of each transition on each place.\n *\n * P-invariants are solutions to y^T * C = 0, found via null space\n * computation on C^T.\n */\nexport class IncidenceMatrix {\n private readonly _pre: readonly (readonly number[])[];\n private readonly _post: readonly (readonly number[])[];\n private readonly _incidence: readonly (readonly number[])[];\n private readonly _numTransitions: number;\n private readonly _numPlaces: number;\n\n private constructor(\n pre: number[][],\n post: number[][],\n incidence: number[][],\n numTransitions: number,\n numPlaces: number,\n ) {\n this._pre = pre;\n this._post = post;\n this._incidence = incidence;\n this._numTransitions = numTransitions;\n this._numPlaces = numPlaces;\n }\n\n /**\n * Computes the incidence matrix from a FlatNet.\n *\n * Environment-injected places (VER-006) each contribute one extra **injector\n * column** (a virtual transition that produces one token into that place and\n * consumes nothing). This makes P-invariant computation env-aware: a valid\n * invariant `y` must satisfy `y^T·C = 0` for the injector column too, forcing\n * `y[envPlace] = 0` and thereby discarding closed-net conservation laws (e.g.\n * `IN + OUT = const`) that would otherwise vacuously bound an injectable place.\n */\n static from(flatNet: FlatNet): IncidenceMatrix {\n const T = flatNet.transitions.length;\n const P = flatNet.places.length;\n\n const pre: number[][] = [];\n const post: number[][] = [];\n const incidence: number[][] = [];\n\n for (let t = 0; t < T; t++) {\n const ft = flatNet.transitions[t]!;\n const preRow = new Array<number>(P);\n const postRow = new Array<number>(P);\n const incRow = new Array<number>(P);\n\n for (let p = 0; p < P; p++) {\n preRow[p] = ft.preVector[p]!;\n postRow[p] = ft.postVector[p]!;\n incRow[p] = postRow[p]! - preRow[p]!;\n }\n\n pre.push(preRow);\n post.push(postRow);\n incidence.push(incRow);\n }\n\n // Injector columns (one per injected environment place): pre = 0, post = e_p.\n let injectorCount = 0;\n for (const name of flatNet.environmentInjection.keys()) {\n const idx = flatNet.placeIndex.get(name);\n if (idx == null) continue;\n const preRow = new Array<number>(P).fill(0);\n const postRow = new Array<number>(P).fill(0);\n const incRow = new Array<number>(P).fill(0);\n postRow[idx] = 1;\n incRow[idx] = 1;\n pre.push(preRow);\n post.push(postRow);\n incidence.push(incRow);\n injectorCount++;\n }\n\n return new IncidenceMatrix(pre, post, incidence, T + injectorCount, P);\n }\n\n /**\n * Returns C^T (transpose of incidence matrix), dimensions [P][T].\n * Used for P-invariant computation: null space of C^T gives P-invariants.\n */\n transposedIncidence(): number[][] {\n const ct: number[][] = [];\n for (let p = 0; p < this._numPlaces; p++) {\n const row = new Array<number>(this._numTransitions);\n for (let t = 0; t < this._numTransitions; t++) {\n row[t] = this._incidence[t]![p]!;\n }\n ct.push(row);\n }\n return ct;\n }\n\n /** Returns the pre-matrix (tokens consumed). T×P. */\n pre(): readonly (readonly number[])[] { return this._pre; }\n\n /** Returns the post-matrix (tokens produced). T×P. */\n post(): readonly (readonly number[])[] { return this._post; }\n\n /** Returns the incidence matrix C[t][p] = post - pre. T×P. */\n incidence(): readonly (readonly number[])[] { return this._incidence; }\n\n numTransitions(): number { return this._numTransitions; }\n numPlaces(): number { return this._numPlaces; }\n}\n","/**\n * A P-invariant (place invariant) of a Petri net.\n *\n * A P-invariant is a vector y such that y^T * C = 0, where C is the\n * incidence matrix. This means that for any reachable marking M:\n * sum(y_i * M_i) = constant, where constant = sum(y_i * M0_i).\n *\n * P-invariants provide structural bounds on places and are used as\n * strengthening lemmas for the IC3/PDR engine.\n */\nexport interface PInvariant {\n /** Weight vector (one entry per place index). */\n readonly weights: readonly number[];\n /** The invariant value sum(y_i * M0_i). */\n readonly constant: number;\n /** Set of place indices where weight != 0. */\n readonly support: ReadonlySet<number>;\n}\n\nexport function pInvariant(weights: number[], constant: number, support: Set<number>): PInvariant {\n return { weights, constant, support };\n}\n\nexport function pInvariantToString(inv: PInvariant): string {\n const parts: string[] = [];\n for (const i of inv.support) {\n if (inv.weights[i] !== 1) {\n parts.push(`${inv.weights[i]}*p${i}`);\n } else {\n parts.push(`p${i}`);\n }\n }\n return `PInvariant[${parts.join(' + ')} = ${inv.constant}]`;\n}\n","/**\n * @module p-invariant-computer\n *\n * Computes P-invariants of a Petri net via integer Gaussian elimination (Farkas' algorithm).\n *\n * **Algorithm**: A P-invariant is a non-negative integer vector y such that y^T · C = 0\n * (where C is the incidence matrix). This expresses a conservation law: the weighted\n * token sum Σ(y_i · M[i]) is constant across all reachable markings.\n *\n * **Farkas variant**: Constructs the augmented matrix [C^T | I_P] and row-reduces\n * the C^T portion to zero using integer elimination (no floating point). Rows where\n * the C^T part becomes all-zero yield invariant vectors from the identity part.\n * Row normalization by GCD keeps values small during elimination.\n *\n * **Integer Gaussian elimination**: Each elimination step multiplies rows by pivot\n * coefficients (a·row - b·pivotRow) to avoid fractions. This preserves integer\n * arithmetic throughout, critical for exact invariant computation.\n *\n * Invariants are used to strengthen SMT queries (added as constraints on M').\n */\nimport type { FlatNet } from '../encoding/flat-net.js';\nimport type { IncidenceMatrix } from '../encoding/incidence-matrix.js';\nimport type { MarkingState } from '../marking-state.js';\nimport type { PInvariant } from './p-invariant.js';\nimport { pInvariant } from './p-invariant.js';\n\n/**\n * Computes P-invariants of a Petri net via integer Gaussian elimination.\n *\n * P-invariants are non-negative integer vectors y where y^T * C = 0.\n * They express conservation laws: the weighted token sum is constant\n * across all reachable markings.\n *\n * Algorithm: compute the null space of C^T using integer row reduction\n * with an augmented identity matrix (Farkas' algorithm variant).\n */\nexport function computePInvariants(\n matrix: IncidenceMatrix,\n flatNet: FlatNet,\n initialMarking: MarkingState,\n): PInvariant[] {\n const P = matrix.numPlaces();\n const T = matrix.numTransitions();\n\n if (P === 0 || T === 0) return [];\n\n // We want to find y such that y^T * C = 0, i.e., C^T * y = 0\n // Start with augmented matrix [C^T | I_P]\n // Row-reduce C^T part to zero; the I_P part gives the invariant vectors.\n const ct = matrix.transposedIncidence(); // P × T\n\n // Augmented matrix: P rows, T + P columns\n // Use regular numbers (safe for nets with < ~50 places/transitions)\n const cols = T + P;\n const augmented: number[][] = [];\n for (let i = 0; i < P; i++) {\n const row = new Array<number>(cols).fill(0);\n for (let j = 0; j < T; j++) {\n row[j] = ct[i]![j]!;\n }\n row[T + i] = 1; // identity part\n augmented.push(row);\n }\n\n // Integer Gaussian elimination on the C^T part (columns 0..T-1)\n let pivotRow = 0;\n for (let col = 0; col < T && pivotRow < P; col++) {\n // Find pivot (non-zero entry in this column)\n let pivot = -1;\n for (let row = pivotRow; row < P; row++) {\n if (augmented[row]![col] !== 0) {\n pivot = row;\n break;\n }\n }\n if (pivot === -1) continue; // free variable\n\n // Swap pivot row\n if (pivot !== pivotRow) {\n const tmp = augmented[pivotRow]!;\n augmented[pivotRow] = augmented[pivot]!;\n augmented[pivot] = tmp;\n }\n\n // Eliminate this column in all other rows\n for (let row = 0; row < P; row++) {\n if (row === pivotRow || augmented[row]![col] === 0) continue;\n\n const a = augmented[pivotRow]![col]!;\n const b = augmented[row]![col]!;\n\n // row = a*row - b*pivotRow (keeps integers, eliminates col)\n for (let c = 0; c < cols; c++) {\n augmented[row]![c] = a * augmented[row]![c]! - b * augmented[pivotRow]![c]!;\n }\n\n // Normalize by GCD to keep values small\n normalizeRow(augmented[row]!, cols);\n }\n\n pivotRow++;\n }\n\n // Extract invariants: rows where C^T part is all zeros\n const invariants: PInvariant[] = [];\n for (let row = 0; row < P; row++) {\n let isZero = true;\n for (let col = 0; col < T; col++) {\n if (augmented[row]![col] !== 0) {\n isZero = false;\n break;\n }\n }\n if (!isZero) continue;\n\n // Extract the weight vector from the identity part\n const weights = new Array<number>(P);\n let allNonNegative = true;\n let hasPositive = false;\n\n for (let i = 0; i < P; i++) {\n weights[i] = augmented[row]![T + i]!;\n if (weights[i]! < 0) {\n allNonNegative = false;\n break;\n }\n if (weights[i]! > 0) hasPositive = true;\n }\n\n // We want semi-positive invariants (all weights >= 0, at least one > 0)\n if (!allNonNegative) {\n // Try negating\n let allNonPositive = true;\n for (let i = 0; i < P; i++) {\n if (augmented[row]![T + i]! > 0) {\n allNonPositive = false;\n break;\n }\n }\n if (allNonPositive) {\n for (let i = 0; i < P; i++) {\n weights[i] = -augmented[row]![T + i]!;\n }\n hasPositive = true;\n allNonNegative = true;\n }\n }\n\n if (!allNonNegative || !hasPositive) continue;\n\n // Normalize: divide by GCD of weights\n let g = 0;\n for (const w of weights) {\n if (w > 0) g = gcd(g, w);\n }\n if (g > 1) {\n for (let i = 0; i < P; i++) {\n weights[i] = weights[i]! / g;\n }\n }\n\n // Compute support and constant\n const support = new Set<number>();\n let constant = 0;\n for (let i = 0; i < P; i++) {\n if (weights[i] !== 0) {\n support.add(i);\n const place = flatNet.places[i]!;\n constant += weights[i]! * initialMarking.tokens(place);\n }\n }\n\n invariants.push(pInvariant(weights, constant, support));\n }\n\n return invariants;\n}\n\n/**\n * Checks if every place is covered by at least one P-invariant.\n * If true, the net is structurally bounded.\n */\nexport function isCoveredByInvariants(invariants: readonly PInvariant[], numPlaces: number): boolean {\n const covered = new Array<boolean>(numPlaces).fill(false);\n for (const inv of invariants) {\n for (const idx of inv.support) {\n if (idx < numPlaces) covered[idx] = true;\n }\n }\n return covered.every(c => c);\n}\n\nfunction normalizeRow(row: number[], cols: number): void {\n let g = 0;\n for (let c = 0; c < cols; c++) {\n if (row[c] !== 0) {\n g = gcd(g, Math.abs(row[c]!));\n }\n }\n if (g > 1) {\n for (let c = 0; c < cols; c++) {\n row[c] = row[c]! / g;\n }\n }\n}\n\nfunction gcd(a: number, b: number): number {\n while (b !== 0) {\n const t = b;\n b = a % b;\n a = t;\n }\n return a;\n}\n","/**\n * @module structural-check\n *\n * Structural deadlock pre-check using siphon/trap analysis (Commoner's theorem).\n *\n * **Commoner's theorem**: A Petri net is deadlock-free if every siphon contains\n * an initially marked trap.\n *\n * **Siphon**: A set of places S where every transition that outputs to S also\n * inputs from S. Key property: once all places in a siphon become empty,\n * they can never be re-marked. An empty siphon can cause deadlock.\n *\n * **Trap**: A set of places S where every transition that inputs from S also\n * outputs to S. Key property: once any place in a trap is marked,\n * the trap remains marked forever.\n *\n * **Algorithm**: For each place, compute the minimal siphon containing it via\n * fixed-point expansion. For each siphon, find the maximal trap within it\n * (fixed-point contraction). If every siphon contains an initially-marked\n * trap, deadlock-freedom is proven structurally — no SMT query needed.\n *\n * Limited to nets with ≤50 places to bound enumeration cost.\n */\nimport type { FlatNet } from '../encoding/flat-net.js';\nimport type { MarkingState } from '../marking-state.js';\n\nconst MAX_PLACES_FOR_SIPHON_ANALYSIS = 50;\n\n/**\n * Result of structural deadlock check using siphon/trap analysis.\n */\nexport type StructuralCheckResult =\n | { readonly type: 'no-potential-deadlock' }\n | { readonly type: 'potential-deadlock'; readonly siphon: ReadonlySet<number> }\n | { readonly type: 'inconclusive'; readonly reason: string };\n\n/**\n * Structural deadlock pre-check using siphon/trap analysis.\n *\n * Commoner's theorem: a Petri net is deadlock-free if every siphon\n * contains a marked trap.\n *\n * A siphon is a set of places S such that every transition with\n * an output in S also has an input in S. Once empty, a siphon stays empty.\n *\n * A trap is a set of places S such that every transition with\n * an input in S also has an output in S. Once marked, a trap stays marked.\n */\nexport function structuralCheck(flatNet: FlatNet, initialMarking: MarkingState): StructuralCheckResult {\n const P = flatNet.places.length;\n\n if (P === 0) {\n return { type: 'no-potential-deadlock' };\n }\n\n if (P > MAX_PLACES_FOR_SIPHON_ANALYSIS) {\n return { type: 'inconclusive', reason: `Net has ${P} places, siphon enumeration skipped` };\n }\n\n const siphons = findMinimalSiphons(flatNet);\n\n if (siphons.length === 0) {\n return { type: 'no-potential-deadlock' };\n }\n\n for (const siphon of siphons) {\n const trap = findMaximalTrapIn(flatNet, siphon);\n\n if (trap.size === 0 || !isMarked(trap, flatNet, initialMarking)) {\n return { type: 'potential-deadlock', siphon };\n }\n }\n\n return { type: 'no-potential-deadlock' };\n}\n\n/**\n * Finds minimal siphons by checking all non-empty subsets of deadlock-enabling places.\n * Uses a fixed-point approach: start from each place and grow the siphon.\n */\nexport function findMinimalSiphons(flatNet: FlatNet): ReadonlySet<number>[] {\n const P = flatNet.places.length;\n const siphons: Set<number>[] = [];\n\n // Pre-compute: for each place, which transitions have it as output?\n const placeAsOutput: number[][] = [];\n for (let p = 0; p < P; p++) {\n placeAsOutput.push([]);\n }\n\n for (let t = 0; t < flatNet.transitions.length; t++) {\n const ft = flatNet.transitions[t]!;\n for (let p = 0; p < P; p++) {\n if (ft.postVector[p]! > 0) {\n placeAsOutput[p]!.push(t);\n }\n }\n }\n\n for (let startPlace = 0; startPlace < P; startPlace++) {\n const siphon = computeSiphonContaining(startPlace, flatNet, placeAsOutput);\n if (siphon !== null && siphon.size > 0) {\n let isMinimal = true;\n const toRemove: number[] = [];\n for (let i = 0; i < siphons.length; i++) {\n const existing = siphons[i]!;\n if (setsEqual(existing, siphon)) {\n isMinimal = false;\n break;\n }\n if (isSubsetOf(existing, siphon)) {\n isMinimal = false;\n break;\n }\n if (isSubsetOf(siphon, existing)) {\n toRemove.push(i);\n }\n }\n for (let i = toRemove.length - 1; i >= 0; i--) {\n siphons.splice(toRemove[i]!, 1);\n }\n if (isMinimal) {\n siphons.push(siphon);\n }\n }\n }\n\n return siphons;\n}\n\nfunction computeSiphonContaining(\n startPlace: number,\n flatNet: FlatNet,\n placeAsOutput: number[][],\n): Set<number> | null {\n const siphon = new Set<number>();\n siphon.add(startPlace);\n\n let changed = true;\n while (changed) {\n changed = false;\n const snapshot = [...siphon];\n\n for (const p of snapshot) {\n for (const t of placeAsOutput[p]!) {\n const ft = flatNet.transitions[t]!;\n\n let hasInputInSiphon = false;\n for (let q = 0; q < flatNet.places.length; q++) {\n if (ft.preVector[q]! > 0 && siphon.has(q)) {\n hasInputInSiphon = true;\n break;\n }\n }\n\n if (!hasInputInSiphon) {\n let added = false;\n for (let q = 0; q < flatNet.places.length; q++) {\n if (ft.preVector[q]! > 0) {\n if (!siphon.has(q)) {\n siphon.add(q);\n changed = true;\n }\n added = true;\n break;\n }\n }\n if (!added) {\n return null;\n }\n }\n }\n }\n }\n\n return siphon;\n}\n\n/**\n * Finds the maximal trap within a given set of places.\n * Uses fixed-point: start with the full set and remove places that violate the trap condition.\n */\nexport function findMaximalTrapIn(flatNet: FlatNet, places: ReadonlySet<number>): ReadonlySet<number> {\n const trap = new Set(places);\n\n let changed = true;\n while (changed) {\n changed = false;\n const toRemove: number[] = [];\n\n for (const p of trap) {\n let satisfies = true;\n for (let t = 0; t < flatNet.transitions.length; t++) {\n const ft = flatNet.transitions[t]!;\n if (ft.preVector[p]! > 0) {\n let outputsToTrap = false;\n for (const q of trap) {\n if (ft.postVector[q]! > 0) {\n outputsToTrap = true;\n break;\n }\n }\n if (!outputsToTrap) {\n satisfies = false;\n break;\n }\n }\n }\n if (!satisfies) {\n toRemove.push(p);\n }\n }\n\n if (toRemove.length > 0) {\n for (const p of toRemove) trap.delete(p);\n changed = true;\n }\n }\n\n return trap;\n}\n\nfunction isMarked(placeIndices: ReadonlySet<number>, flatNet: FlatNet, marking: MarkingState): boolean {\n for (const idx of placeIndices) {\n const place = flatNet.places[idx]!;\n if (marking.tokens(place) > 0) return true;\n }\n return false;\n}\n\nfunction setsEqual(a: ReadonlySet<number>, b: ReadonlySet<number>): boolean {\n if (a.size !== b.size) return false;\n for (const v of a) {\n if (!b.has(v)) return false;\n }\n return true;\n}\n\nfunction isSubsetOf(sub: ReadonlySet<number>, sup: ReadonlySet<number>): boolean {\n if (sub.size > sup.size) return false;\n for (const v of sub) {\n if (!sup.has(v)) return false;\n }\n return true;\n}\n","import { init } from 'z3-solver';\nimport type { Bool, Expr, FuncDecl } from 'z3-solver';\n\n/**\n * Result of a Spacer query.\n */\nexport type QueryResult = QueryProven | QueryViolated | QueryUnknown;\n\n/** Property proven: no reachable error state (UNSAT). */\nexport interface QueryProven {\n readonly type: 'proven';\n readonly invariantFormula: string | null;\n readonly levelInvariants: readonly string[];\n}\n\n/** Counterexample found (SAT). The answer is the derivation tree. */\nexport interface QueryViolated {\n readonly type: 'violated';\n readonly answer: Expr | null;\n}\n\n/** Solver could not determine (timeout, resource limit). */\nexport interface QueryUnknown {\n readonly type: 'unknown';\n readonly reason: string;\n}\n\n/**\n * The Z3 context and helpers returned by SpacerRunner.create().\n * Exposes the context object for building expressions.\n */\nexport interface SpacerContext {\n /** The Z3 high-level context for building expressions. */\n readonly ctx: ReturnType<Awaited<ReturnType<typeof init>>['Context']>;\n /** The Z3 Fixedpoint solver instance (Spacer engine). Z3 types are complex; using any. */\n readonly fp: any;\n\n /** Queries whether the error state is reachable. */\n query(errorExpr: Bool, reachableDecl?: FuncDecl): Promise<QueryResult>;\n\n /** Releases Z3 resources. */\n dispose(): void;\n}\n\n// Use a type alias for the Z3 context to avoid the deep inference\ntype Z3Context = ReturnType<Awaited<ReturnType<typeof init>>['Context']>;\n\n/**\n * Creates a Spacer runner with the given timeout.\n *\n * Uses Z3's Spacer engine (CHC solver based on IC3/PDR) to prove or\n * disprove safety properties.\n */\nexport async function createSpacerRunner(timeoutMs: number): Promise<SpacerContext> {\n const { Context } = await init();\n const ctx = new Context('main') as Z3Context;\n const fp = new (ctx as any).Fixedpoint() as any;\n\n // Configure Spacer engine\n fp.set('engine', 'spacer');\n if (timeoutMs > 0) {\n fp.set('timeout', Math.min(timeoutMs, 2147483647));\n }\n\n async function query(errorExpr: Bool, reachableDecl?: FuncDecl): Promise<QueryResult> {\n try {\n const status = await fp.query(errorExpr);\n\n if (status === 'unsat') {\n let invariantFormula: string | null = null;\n const levelInvariants: string[] = [];\n\n try {\n const answer = fp.getAnswer();\n if (answer != null) {\n invariantFormula = answer.toString();\n }\n } catch {\n // Some configurations don't produce answers\n }\n\n if (reachableDecl != null) {\n try {\n const levels = fp.getNumLevels(reachableDecl);\n for (let i = 0; i < levels; i++) {\n const cover = fp.getCoverDelta(i, reachableDecl);\n if (cover != null && !(ctx as any).isTrue(cover)) {\n levelInvariants.push(`Level ${i}: ${cover.toString()}`);\n }\n }\n } catch {\n // Level queries may not be available\n }\n }\n\n return { type: 'proven', invariantFormula, levelInvariants };\n }\n\n if (status === 'sat') {\n let answer: Expr | null = null;\n try {\n answer = fp.getAnswer();\n } catch {\n // Some configurations don't produce answers\n }\n return { type: 'violated', answer };\n }\n\n // unknown\n return { type: 'unknown', reason: fp.getReasonUnknown() };\n } catch (e: any) {\n return { type: 'unknown', reason: `Z3 exception: ${e.message ?? e}` };\n }\n }\n\n function dispose(): void {\n try {\n fp.release();\n } catch {\n // ignore\n }\n }\n\n return {\n ctx,\n fp,\n query,\n dispose,\n } as SpacerContext;\n}\n","import type { Place } from '../../core/place.js';\nimport type { FlatTransition } from './flat-transition.js';\n\n/**\n * A flattened Petri net with indexed places and XOR-expanded transitions.\n *\n * Intermediate representation between the high-level PetriNet and Z3 CHC encoding.\n */\nexport interface FlatNet {\n /** Ordered list of places (index = position). */\n readonly places: readonly Place<any>[];\n /** Reverse lookup: place name -> index. */\n readonly placeIndex: ReadonlyMap<string, number>;\n /** XOR-expanded flat transitions. */\n readonly transitions: readonly FlatTransition[];\n /** For bounded environment places: place name -> max tokens. */\n readonly environmentBounds: ReadonlyMap<string, number>;\n /**\n * Environment places whose tokens the analysis MODELS as externally injected\n * (VER-006). Maps env place name -> injection bound: a number caps injection\n * (`Bounded(k)`), `null` means unbounded (`AlwaysAvailable`). Absent entries\n * (incl. `Ignore` mode) are not injected. The encoder emits one injection CHC\n * rule per entry and the incidence matrix gains one injector column per entry\n * so closed-net P-invariants over these places are correctly discarded.\n */\n readonly environmentInjection: ReadonlyMap<string, number | null>;\n}\n\nexport function flatNetPlaceCount(net: FlatNet): number {\n return net.places.length;\n}\n\nexport function flatNetTransitionCount(net: FlatNet): number {\n return net.transitions.length;\n}\n\nexport function flatNetIndexOf(net: FlatNet, place: Place<any>): number {\n return net.placeIndex.get(place.name) ?? -1;\n}\n","/**\n * @module smt-encoder\n *\n * Encodes a flattened Petri net as Constrained Horn Clauses (CHC) for Z3's Spacer engine.\n *\n * **CHC encoding strategy**: The net's state space is modeled as integer vectors\n * (one variable per place = token count). Three rule types:\n *\n * 1. **Init**: `Reachable(M0)` — the initial marking is reachable\n * 2. **Transition**: `Reachable(M') :- Reachable(M) ∧ enabled(M,t) ∧ fire(M,M',t)` —\n * one rule per flat transition (XOR branches are separate transitions)\n * 3. **Error**: `Error() :- Reachable(M) ∧ violation(M)` — safety property violation\n *\n * Transition rules include: non-negativity constraints on M', P-invariant strengthening\n * clauses, and environment bounds for bounded analysis.\n *\n * Z3 types are complex and partially untyped; the ctx/fp parameters use `any`.\n */\nimport type { Arith, Bool, FuncDecl } from 'z3-solver';\nimport type { FlatNet } from '../encoding/flat-net.js';\nimport type { FlatTransition } from '../encoding/flat-transition.js';\nimport type { MarkingState } from '../marking-state.js';\nimport type { SmtProperty } from '../smt-property.js';\nimport type { PInvariant } from '../invariant/p-invariant.js';\nimport type { Place } from '../../core/place.js';\nimport { flatNetIndexOf } from '../encoding/flat-net.js';\n\n/** Z3 high-level context. Typed as `any` because z3-solver's TS types are incomplete. */\ntype Z3Context = any;\n/** Z3 Fixedpoint solver instance. Typed as `any` because z3-solver's TS types are incomplete. */\ntype Z3Fixedpoint = any;\n\n/**\n * Result of CHC encoding.\n */\nexport interface EncodingResult {\n readonly errorExpr: Bool;\n readonly reachableDecl: FuncDecl;\n}\n\n/**\n * Encodes a flattened Petri net as Constrained Horn Clauses (CHC) for Z3's Spacer engine.\n *\n * CHC rules:\n * - Reachable(M0) — initial state is reachable\n * - Reachable(M') :- Reachable(M) AND enabled(M,t) AND fire(M,M',t) — transition rules\n * - Error() :- Reachable(M) AND property_violation(M) — safety property\n */\nexport function encode(\n ctx: Z3Context,\n fp: Z3Fixedpoint,\n flatNet: FlatNet,\n initialMarking: MarkingState,\n property: SmtProperty,\n invariants: readonly PInvariant[],\n sinkPlaces: ReadonlySet<Place<any>> = new Set(),\n): EncodingResult {\n const P = flatNet.places.length;\n const Int = ctx.Int;\n const Bool_ = ctx.Bool;\n\n // Create sorts array for function declaration\n const intSort = Int.sort();\n const boolSort = Bool_.sort();\n const markingSorts: any[] = new Array(P).fill(intSort);\n\n // Create the Reachable relation: (Int, Int, ...) -> Bool\n const reachable: FuncDecl = ctx.Function.declare('Reachable', ...markingSorts, boolSort);\n fp.registerRelation(reachable);\n\n // Create the Error relation: () -> Bool\n const error: FuncDecl = ctx.Function.declare('Error', boolSort);\n fp.registerRelation(error);\n\n // === Rule 1: Initial state ===\n // Reachable(m0_0, m0_1, ..., m0_{P-1})\n const m0Args: Arith[] = [];\n for (let i = 0; i < P; i++) {\n const tokens = initialMarking.tokens(flatNet.places[i]!);\n m0Args.push(Int.val(tokens));\n }\n const initFact = (reachable as any).call(...m0Args) as Bool;\n fp.addRule(initFact, 'init');\n\n // === Rule 2: Transition rules ===\n for (let t = 0; t < flatNet.transitions.length; t++) {\n const ft = flatNet.transitions[t]!;\n encodeTransitionRule(ctx, fp, reachable, ft, flatNet, invariants, P);\n }\n\n // === Rule 2b: Environment-injection rules (VER-006) ===\n // Per injected env place p: Reachable(M') :- Reachable(M) ∧ [M[p] < bound] ∧\n // M'[p] = M[p]+1 ∧ (∀q≠p) M'[q] = M[q]. Unbounded (AlwaysAvailable) omits the\n // guard so p can grow without limit. These are NOT flat transitions, so the\n // deadlock encoding (which iterates flatNet.transitions) never sees them and\n // deadlock-freedom does not become trivially true. P-invariants are NOT\n // conjoined here — injection deliberately breaks closed-net conservation.\n for (const [name, bound] of flatNet.environmentInjection) {\n const idx = flatNet.placeIndex.get(name);\n if (idx == null) continue;\n encodeInjectionRule(ctx, fp, reachable, idx, bound, P);\n }\n\n // === Rule 3: Error rule (property violation) ===\n encodeErrorRule(ctx, fp, reachable, error, flatNet, property, sinkPlaces, P);\n\n return {\n errorExpr: (error as any).call() as Bool,\n reachableDecl: reachable,\n };\n}\n\nfunction encodeTransitionRule(\n ctx: Z3Context,\n fp: Z3Fixedpoint,\n reachable: FuncDecl,\n ft: FlatTransition,\n flatNet: FlatNet,\n invariants: readonly PInvariant[],\n P: number,\n): void {\n const Int = ctx.Int;\n\n // Create named variables for current and next marking\n const mVars: Arith[] = [];\n const mPrimeVars: Arith[] = [];\n for (let i = 0; i < P; i++) {\n mVars.push(Int.const(`m${i}`));\n mPrimeVars.push(Int.const(`mp${i}`));\n }\n\n // Body: Reachable(M) AND enabled(M,t) AND fire(M,M',t) AND non-negativity(M') AND invariants(M') AND env bounds(M')\n const reachBody = (reachable as any).call(...mVars) as Bool;\n const enabled = encodeEnabled(ctx, ft, flatNet, mVars, P);\n const fireRelation = encodeFire(ctx, ft, flatNet, mVars, mPrimeVars, P);\n\n // Non-negativity of M'\n let nonNeg: Bool = ctx.Bool.val(true);\n for (let i = 0; i < P; i++) {\n nonNeg = ctx.And(nonNeg, mPrimeVars[i]!.ge(0));\n }\n\n // P-invariant constraints on M'\n const invConstraints = encodeInvariantConstraints(ctx, invariants, mPrimeVars, P);\n\n // Environment bounds on M'\n let envBounds: Bool = ctx.Bool.val(true);\n for (const [name, bound] of flatNet.environmentBounds) {\n const idx = flatNet.placeIndex.get(name);\n if (idx != null) {\n envBounds = ctx.And(envBounds, mPrimeVars[idx]!.le(bound));\n }\n }\n\n // Body conjunction\n const body = ctx.And(reachBody, enabled, fireRelation, nonNeg, invConstraints, envBounds);\n\n // Head: Reachable(M')\n const head = (reachable as any).call(...mPrimeVars) as Bool;\n\n // Rule: forall M, M'. body => head\n const allVars = [...mVars, ...mPrimeVars];\n const rule = ctx.Implies(body, head);\n const qRule = ctx.ForAll(allVars, rule);\n\n fp.addRule(qRule, `t_${ft.name}`);\n}\n\n/**\n * Encodes one environment-injection rule (VER-006): the external world adds a\n * token to environment place `idx`. `bound === null` ⇒ unbounded (AlwaysAvailable);\n * a number ⇒ guarded so the place never exceeds `bound` (Bounded). All other\n * columns are copied unchanged. No P-invariant strengthening (injection breaks\n * conservation by design); non-negativity is implied by `M[idx] ≥ 0 ⇒ M'[idx] ≥ 1`.\n */\nfunction encodeInjectionRule(\n ctx: Z3Context,\n fp: Z3Fixedpoint,\n reachable: FuncDecl,\n idx: number,\n bound: number | null,\n P: number,\n): void {\n const Int = ctx.Int;\n\n const mVars: Arith[] = [];\n const mPrimeVars: Arith[] = [];\n for (let i = 0; i < P; i++) {\n mVars.push(Int.const(`m${i}`));\n mPrimeVars.push(Int.const(`mp${i}`));\n }\n\n const reachBody = (reachable as any).call(...mVars) as Bool;\n\n let fire: Bool = ctx.Bool.val(true);\n for (let i = 0; i < P; i++) {\n if (i === idx) {\n fire = ctx.And(fire, mPrimeVars[i]!.eq(mVars[i]!.add(1)));\n } else {\n fire = ctx.And(fire, mPrimeVars[i]!.eq(mVars[i]!));\n }\n }\n\n // Bounded injection: only inject while still below the cap.\n const guard: Bool = bound === null ? ctx.Bool.val(true) : mVars[idx]!.lt(bound);\n\n const body = ctx.And(reachBody, guard, fire);\n const head = (reachable as any).call(...mPrimeVars) as Bool;\n const qRule = ctx.ForAll([...mVars, ...mPrimeVars], ctx.Implies(body, head));\n\n fp.addRule(qRule, `env_inject_${idx}`);\n}\n\n/** Maps injected environment-place index -> injection bound (null = unbounded). */\nfunction injectedEnvIndices(flatNet: FlatNet): Map<number, number | null> {\n const out = new Map<number, number | null>();\n for (const [name, bound] of flatNet.environmentInjection) {\n const idx = flatNet.placeIndex.get(name);\n if (idx != null) out.set(idx, bound);\n }\n return out;\n}\n\n/**\n * Encodes the enablement predicate for a flat transition.\n *\n * When `relaxEnv` is true (used only by the deadlock check), input/read\n * requirements on injectable environment places are treated as satisfiable by\n * external injection — `AlwaysAvailable` always satisfies them, `Bounded(k)`\n * satisfies them iff the required cardinality is ≤ k (a compile-time check on the\n * arc weight, not on the marking). This mirrors the state class graph's\n * always-available enablement (VER-006) so a reactive net merely *waiting for\n * input* is not reported as a deadlock; only a marking that no injection could\n * ever re-enable counts. Transition firing rules always use the strict form\n * (`relaxEnv` false) because firing genuinely consumes tokens.\n */\nfunction encodeEnabled(\n ctx: Z3Context,\n ft: FlatTransition,\n flatNet: FlatNet,\n mVars: Arith[],\n P: number,\n relaxEnv = false,\n): Bool {\n let result: Bool = ctx.Bool.val(true);\n const envInj = relaxEnv ? injectedEnvIndices(flatNet) : undefined;\n\n // Input requirements: M[p] >= pre[p] (relaxed for injectable env inputs).\n for (let p = 0; p < P; p++) {\n const pre = ft.preVector[p]!;\n if (pre <= 0) continue;\n if (envInj?.has(p)) {\n const bound = envInj.get(p)!;\n if (bound !== null && pre > bound) return ctx.Bool.val(false); // never enableable\n continue; // satisfiable by injection\n }\n result = ctx.And(result, mVars[p]!.ge(pre));\n }\n\n // Read arcs: M[p] >= 1 (relaxed for injectable env inputs).\n for (const p of ft.readPlaces) {\n if (envInj?.has(p)) {\n const bound = envInj.get(p)!;\n if (bound !== null && bound < 1) return ctx.Bool.val(false);\n continue;\n }\n result = ctx.And(result, mVars[p]!.ge(1));\n }\n\n // Inhibitor arcs: M[p] == 0\n for (const p of ft.inhibitorPlaces) {\n result = ctx.And(result, mVars[p]!.eq(0));\n }\n\n // Non-negativity of current marking\n for (let p = 0; p < P; p++) {\n result = ctx.And(result, mVars[p]!.ge(0));\n }\n\n return result;\n}\n\nfunction encodeFire(\n ctx: Z3Context,\n ft: FlatTransition,\n _flatNet: FlatNet,\n mVars: Arith[],\n mPrimeVars: Arith[],\n P: number,\n): Bool {\n let result: Bool = ctx.Bool.val(true);\n\n for (let p = 0; p < P; p++) {\n const isReset = ft.resetPlaces.includes(p);\n\n if (isReset || ft.consumeAll[p]) {\n // Reset/consumeAll: M'[p] = post[p]\n result = ctx.And(result, mPrimeVars[p]!.eq(ft.postVector[p]!));\n } else {\n // Standard: M'[p] = M[p] - pre[p] + post[p]\n const delta = ft.postVector[p]! - ft.preVector[p]!;\n if (delta === 0) {\n result = ctx.And(result, mPrimeVars[p]!.eq(mVars[p]!));\n } else {\n result = ctx.And(result, mPrimeVars[p]!.eq(mVars[p]!.add(delta)));\n }\n }\n }\n\n return result;\n}\n\nfunction encodeErrorRule(\n ctx: Z3Context,\n fp: Z3Fixedpoint,\n reachable: FuncDecl,\n error: FuncDecl,\n flatNet: FlatNet,\n property: SmtProperty,\n sinkPlaces: ReadonlySet<Place<any>>,\n P: number,\n): void {\n const Int = ctx.Int;\n\n // Create variables for the error rule\n const mVars: Arith[] = [];\n for (let i = 0; i < P; i++) {\n mVars.push(Int.const(`em${i}`));\n }\n\n const reachBody = (reachable as any).call(...mVars) as Bool;\n const violation = encodePropertyViolation(ctx, flatNet, property, sinkPlaces, mVars, P);\n\n const head = (error as any).call() as Bool;\n const body = ctx.And(reachBody, violation);\n const rule = ctx.Implies(body, head);\n const qRule = ctx.ForAll(mVars, rule);\n\n fp.addRule(qRule, `error_${property.type}`);\n}\n\nfunction encodePropertyViolation(\n ctx: Z3Context,\n flatNet: FlatNet,\n property: SmtProperty,\n sinkPlaces: ReadonlySet<Place<any>>,\n mVars: Arith[],\n P: number,\n): Bool {\n switch (property.type) {\n case 'deadlock-free': {\n const deadlock = encodeDeadlock(ctx, flatNet, mVars, P);\n if (sinkPlaces.size > 0) {\n // Deadlock is only a violation if NOT at any expected sink place\n let notAtSink: Bool = ctx.Bool.val(true);\n for (const sink of sinkPlaces) {\n const idx = flatNetIndexOf(flatNet, sink);\n if (idx >= 0) {\n notAtSink = ctx.And(notAtSink, mVars[idx]!.eq(0));\n }\n }\n return ctx.And(deadlock, notAtSink);\n }\n return deadlock;\n }\n\n case 'mutual-exclusion': {\n const idx1 = flatNetIndexOf(flatNet, property.p1);\n const idx2 = flatNetIndexOf(flatNet, property.p2);\n if (idx1 < 0) throw new Error(`MutualExclusion references unknown place: ${property.p1.name}`);\n if (idx2 < 0) throw new Error(`MutualExclusion references unknown place: ${property.p2.name}`);\n return ctx.And(mVars[idx1]!.ge(1), mVars[idx2]!.ge(1));\n }\n\n case 'place-bound': {\n const idx = flatNetIndexOf(flatNet, property.place);\n if (idx < 0) throw new Error(`PlaceBound references unknown place: ${property.place.name}`);\n return mVars[idx]!.gt(property.bound);\n }\n\n case 'unreachable': {\n let allMarked: Bool = ctx.Bool.val(true);\n for (const place of property.places) {\n const idx = flatNetIndexOf(flatNet, place);\n if (idx >= 0) {\n allMarked = ctx.And(allMarked, mVars[idx]!.ge(1));\n }\n }\n return allMarked;\n }\n }\n}\n\n/**\n * Encodes the deadlock condition: no transition is enabled. Environment inputs\n * are treated as injectable (`relaxEnv`), so a marking that an external injection\n * could re-enable is NOT a deadlock — only a genuinely stuck marking is (VER-006).\n */\nfunction encodeDeadlock(\n ctx: Z3Context,\n flatNet: FlatNet,\n mVars: Arith[],\n P: number,\n): Bool {\n let deadlock: Bool = ctx.Bool.val(true);\n\n for (const ft of flatNet.transitions) {\n const enabled = encodeEnabled(ctx, ft, flatNet, mVars, P, /* relaxEnv */ true);\n deadlock = ctx.And(deadlock, ctx.Not(enabled));\n }\n\n return deadlock;\n}\n\nfunction encodeInvariantConstraints(\n ctx: Z3Context,\n invariants: readonly PInvariant[],\n mVars: Arith[],\n P: number,\n): Bool {\n let result: Bool = ctx.Bool.val(true);\n\n for (const inv of invariants) {\n // sum(y_i * M[i]) == constant\n let sum: Arith = ctx.Int.val(0);\n for (const idx of inv.support) {\n if (idx < P) {\n sum = sum.add(mVars[idx]!.mul(inv.weights[idx]!));\n }\n }\n result = ctx.And(result, sum.eq(inv.constant));\n }\n\n return result;\n}\n","import type { Expr } from 'z3-solver';\nimport { MarkingState } from '../marking-state.js';\nimport type { FlatNet } from '../encoding/flat-net.js';\n\n/**\n * Result of counterexample decoding.\n */\nexport interface DecodedTrace {\n readonly trace: readonly MarkingState[];\n readonly transitions: readonly string[];\n}\n\n/**\n * Decodes Z3 Spacer counterexample answers into Petri net marking traces.\n *\n * When Spacer finds a counterexample (property violation), it produces\n * a derivation tree showing how the error state is reachable. This function\n * extracts the marking at each step to produce a human-readable trace.\n */\nexport function decode(ctx: any, answer: Expr | null, flatNet: FlatNet): DecodedTrace {\n const trace: MarkingState[] = [];\n const transitions: string[] = [];\n\n if (answer == null) {\n return { trace, transitions };\n }\n\n try {\n extractTrace(ctx, answer, flatNet, trace, transitions);\n } catch {\n // Z3 answer format varies; gracefully degrade\n }\n\n return { trace, transitions };\n}\n\n/**\n * Recursively traverses the Z3 proof tree to extract marking states.\n */\nfunction extractTrace(\n ctx: any,\n expr: any,\n flatNet: FlatNet,\n trace: MarkingState[],\n transitions: string[],\n): void {\n if (expr == null) return;\n\n // Check if this is a function application\n if (!ctx.isApp(expr)) return;\n\n let name: string;\n try {\n const decl = expr.decl();\n name = String(decl.name());\n } catch {\n return;\n }\n\n // Check if this is a Reachable application with integer arguments\n const P = flatNet.places.length;\n if (name === 'Reachable') {\n const numArgs = expr.numArgs();\n if (numArgs === P) {\n const marking = extractMarking(ctx, expr, flatNet);\n if (marking != null) {\n trace.push(marking);\n }\n }\n }\n\n // Recurse into children to find the derivation chain\n try {\n const numArgs = expr.numArgs();\n for (let i = 0; i < numArgs; i++) {\n const child = expr.arg(i);\n extractTrace(ctx, child, flatNet, trace, transitions);\n }\n } catch {\n // Not all expressions support arg()\n }\n\n // Try to extract transition name from rule application\n if (name.startsWith('t_')) {\n transitions.push(name.substring(2));\n }\n}\n\n/**\n * Extracts a MarkingState from a Reachable(...) application.\n */\nfunction extractMarking(ctx: any, reachableApp: any, flatNet: FlatNet): MarkingState | null {\n const P = flatNet.places.length;\n if (reachableApp.numArgs() !== P) return null;\n\n const builder = MarkingState.builder();\n for (let i = 0; i < P; i++) {\n const arg = reachableApp.arg(i);\n if (ctx.isIntVal(arg)) {\n const tokens = Number(arg.value());\n if (tokens > 0) {\n builder.tokens(flatNet.places[i]!, tokens);\n }\n } else {\n // Non-concrete value in counterexample\n return null;\n }\n }\n return builder.build();\n}\n","import type { PetriNet } from '../core/petri-net.js';\nimport type { EnvironmentPlace, Place } from '../core/place.js';\nimport { MarkingState, MarkingStateBuilder } from './marking-state.js';\nimport type { SmtProperty } from './smt-property.js';\nimport { deadlockFree, propertyDescription } from './smt-property.js';\nimport type { SmtVerificationResult, SmtStatistics, Verdict } from './smt-verification-result.js';\nimport type { PInvariant } from './invariant/p-invariant.js';\nimport type { FlatNet } from './encoding/flat-net.js';\nimport { flatten } from './encoding/net-flattener.js';\nimport { type EnvironmentAnalysisMode, alwaysAvailable } from './analysis/environment-analysis-mode.js';\nimport { IncidenceMatrix } from './encoding/incidence-matrix.js';\nimport { computePInvariants, isCoveredByInvariants } from './invariant/p-invariant-computer.js';\nimport { structuralCheck } from './invariant/structural-check.js';\nimport { createSpacerRunner } from './z3/spacer-runner.js';\nimport { encode } from './z3/smt-encoder.js';\nimport { decode } from './z3/counterexample-decoder.js';\n\n/**\n * IC3/PDR-based safety verifier for Petri nets using Z3's Spacer engine.\n *\n * Proves safety properties (especially deadlock-freedom) without\n * enumerating all reachable states. IC3 constructs inductive invariants\n * incrementally, which works well for bounded nets.\n *\n * Key design decisions:\n * - Operates on the marking projection (integer vectors) — no timing\n * - An untimed deadlock-freedom proof is stronger than needed\n * (timing can only restrict behavior)\n * - Guards are ignored — over-approximation is sound for safety properties\n * - If a counterexample is found, it may be spurious in timed/guarded\n * semantics — the report notes this\n *\n * Verification Pipeline:\n * 1. Flatten — expand XOR, index places, build pre/post vectors\n * 2. Structural pre-check — siphon/trap analysis (may prove early)\n * 3. P-invariants — compute conservation laws for strengthening\n * 4. SMT encode + query — IC3/PDR via Z3 Spacer\n * 5. Decode result — proof or counterexample trace\n */\nexport class SmtVerifier {\n private _initialMarking: MarkingState = MarkingState.empty();\n private _property: SmtProperty = deadlockFree();\n private readonly _environmentPlaces = new Set<EnvironmentPlace<any>>();\n private readonly _sinkPlaces = new Set<Place<any>>();\n private _environmentMode: EnvironmentAnalysisMode = alwaysAvailable();\n private _timeoutMs: number = 60_000;\n\n private constructor(private readonly net: PetriNet) {}\n\n static forNet(net: PetriNet): SmtVerifier {\n return new SmtVerifier(net);\n }\n\n initialMarking(marking: MarkingState): this;\n initialMarking(configurator: (builder: MarkingStateBuilder) => void): this;\n initialMarking(arg: MarkingState | ((builder: MarkingStateBuilder) => void)): this {\n if (arg instanceof MarkingState) {\n this._initialMarking = arg;\n } else {\n const builder = MarkingState.builder();\n arg(builder);\n this._initialMarking = builder.build();\n }\n return this;\n }\n\n property(property: SmtProperty): this {\n this._property = property;\n return this;\n }\n\n environmentPlaces(...places: EnvironmentPlace<any>[]): this {\n for (const p of places) this._environmentPlaces.add(p);\n return this;\n }\n\n environmentMode(mode: EnvironmentAnalysisMode): this {\n this._environmentMode = mode;\n return this;\n }\n\n /**\n * Declares expected sink (terminal) places for deadlock-freedom analysis.\n * Markings where any sink place has a token are not considered deadlocks.\n */\n sinkPlaces(...places: Place<any>[]): this {\n for (const p of places) this._sinkPlaces.add(p);\n return this;\n }\n\n timeout(ms: number): this {\n this._timeoutMs = ms;\n return this;\n }\n\n /**\n * Runs the verification pipeline.\n */\n async verify(): Promise<SmtVerificationResult> {\n const start = performance.now();\n const report: string[] = [];\n report.push('=== IC3/PDR SAFETY VERIFICATION ===\\n');\n report.push(`Net: ${this.net.name}`);\n const propDesc = this._sinkPlaces.size === 0\n ? propertyDescription(this._property)\n : `${propertyDescription(this._property)} (sinks: ${[...this._sinkPlaces].map(p => p.name).join(', ')})`;\n report.push(`Property: ${propDesc}`);\n report.push(`Timeout: ${(this._timeoutMs / 1000).toFixed(0)}s\\n`);\n\n // Phase 1: Flatten\n report.push('Phase 1: Flattening net...');\n const flatNet = flatten(this.net, this._environmentPlaces, this._environmentMode);\n report.push(` Places: ${flatNet.places.length}`);\n report.push(` Transitions (expanded): ${flatNet.transitions.length}`);\n if (flatNet.environmentBounds.size > 0) {\n report.push(` Environment bounds: ${flatNet.environmentBounds.size} places`);\n }\n report.push('');\n\n // Phase 2: Structural pre-check\n report.push('Phase 2: Structural pre-check (siphon/trap)...');\n const structResult = structuralCheck(flatNet, this._initialMarking);\n let structResultStr: string;\n switch (structResult.type) {\n case 'no-potential-deadlock':\n structResultStr = 'no potential deadlock';\n break;\n case 'potential-deadlock':\n structResultStr = `potential deadlock (siphon: {${[...structResult.siphon].join(',')}})`;\n break;\n case 'inconclusive':\n structResultStr = `inconclusive (${structResult.reason})`;\n break;\n }\n report.push(` Result: ${structResultStr}\\n`);\n\n // If structural check proves deadlock-freedom for DeadlockFree property\n // (only valid when no sink places — structural check doesn't account for sinks).\n // Skipped when environment places are registered: the siphon/trap analysis runs\n // on the closed net and is blind to env injection (VER-006), so its early proof\n // could be unsound — fall through to the (injection-aware) SMT encoding instead.\n if (\n this._property.type === 'deadlock-free' &&\n this._sinkPlaces.size === 0 &&\n structResult.type === 'no-potential-deadlock' &&\n this._environmentPlaces.size === 0\n ) {\n report.push('=== RESULT ===\\n');\n report.push('PROVEN (structural): Deadlock-freedom verified by Commoner\\'s theorem.');\n report.push(' All siphons contain initially marked traps.');\n return buildResult(\n { type: 'proven', method: 'structural', inductiveInvariant: null },\n report.join('\\n'), [], [], [], [],\n performance.now() - start,\n { places: flatNet.places.length, transitions: flatNet.transitions.length, invariantsFound: 0, structuralResult: structResultStr },\n );\n }\n\n // Phase 3: P-invariants\n report.push('Phase 3: Computing P-invariants...');\n const matrix = IncidenceMatrix.from(flatNet);\n const invariants = computePInvariants(matrix, flatNet, this._initialMarking);\n report.push(` Found: ${invariants.length} P-invariant(s)`);\n const structurallyBounded = isCoveredByInvariants(invariants, flatNet.places.length);\n report.push(` Structurally bounded: ${structurallyBounded ? 'YES' : 'NO'}`);\n for (const inv of invariants) {\n report.push(` ${formatInvariant(inv, flatNet)}`);\n }\n report.push('');\n\n // Phase 4: SMT encode + query via Spacer\n report.push('Phase 4: IC3/PDR verification via Z3 Spacer...');\n\n let runner;\n try {\n runner = await createSpacerRunner(this._timeoutMs);\n } catch (e: any) {\n report.push(` ERROR: ${e.message ?? e}\\n`);\n report.push('=== RESULT ===\\n');\n report.push(`UNKNOWN: Z3 initialization error: ${e.message ?? e}`);\n return buildResult(\n { type: 'unknown', reason: `Z3 init error: ${e.message ?? e}` },\n report.join('\\n'), invariants, [], [], [],\n performance.now() - start,\n { places: flatNet.places.length, transitions: flatNet.transitions.length, invariantsFound: invariants.length, structuralResult: structResultStr },\n );\n }\n\n try {\n const encoding = encode(runner.ctx, runner.fp, flatNet, this._initialMarking, this._property, invariants, this._sinkPlaces);\n const queryResult = await runner.query(encoding.errorExpr, encoding.reachableDecl);\n\n switch (queryResult.type) {\n case 'proven': {\n // Guard against silent vacuous proofs (VER-006): in `ignore` mode the\n // encoding does not model env injection, so env-gated transitions never\n // fire and ANY safety bound is trivially \"proven\". Refuse to certify —\n // downgrade to UNKNOWN with actionable guidance.\n if (this._environmentPlaces.size > 0 && this._environmentMode.type === 'ignore') {\n const reason =\n 'environment places present but not modeled (mode=ignore); a proof would be ' +\n 'vacuous — use alwaysAvailable() or bounded(k) to model external injection';\n report.push(` Status: UNSAT, but vacuous under ignore mode\\n`);\n report.push('=== RESULT ===\\n');\n report.push(`UNKNOWN: ${reason}`);\n return buildResult(\n { type: 'unknown', reason },\n report.join('\\n'), invariants, [], [], [],\n performance.now() - start,\n { places: flatNet.places.length, transitions: flatNet.transitions.length, invariantsFound: invariants.length, structuralResult: structResultStr },\n );\n }\n\n report.push(' Status: UNSAT (property holds)\\n');\n\n // Decode IC3-synthesized invariants with place name substitution\n const discoveredInvariants: string[] = [];\n if (queryResult.invariantFormula != null) {\n discoveredInvariants.push(substituteNames(queryResult.invariantFormula, flatNet));\n }\n for (const level of queryResult.levelInvariants) {\n discoveredInvariants.push(substituteNames(level, flatNet));\n }\n\n // Phase 5: Inductive invariant\n if (discoveredInvariants.length > 0) {\n report.push('Phase 5: Inductive invariant (discovered by IC3)');\n report.push(` Spacer synthesized: ${discoveredInvariants[0]}`);\n report.push(' This formula is INDUCTIVE: preserved by all transitions.');\n if (discoveredInvariants.length > 1) {\n report.push(' Per-level clauses:');\n for (let i = 1; i < discoveredInvariants.length; i++) {\n report.push(` ${discoveredInvariants[i]}`);\n }\n }\n report.push('');\n }\n\n report.push('=== RESULT ===\\n');\n report.push(`PROVEN (IC3/PDR): ${propDesc}`);\n report.push(' Z3 Spacer proved no reachable state violates the property.');\n report.push(' NOTE: Verification ignores timing constraints and JS guards.');\n report.push(' An untimed proof is STRONGER than a timed one (timing only restricts behavior).');\n\n return buildResult(\n {\n type: 'proven',\n method: 'IC3/PDR',\n inductiveInvariant: queryResult.invariantFormula != null\n ? substituteNames(queryResult.invariantFormula, flatNet)\n : null,\n },\n report.join('\\n'), invariants, discoveredInvariants, [], [],\n performance.now() - start,\n { places: flatNet.places.length, transitions: flatNet.transitions.length, invariantsFound: invariants.length, structuralResult: structResultStr },\n );\n }\n\n case 'violated': {\n report.push(' Status: SAT (counterexample found)\\n');\n\n const decoded = decode(runner.ctx, queryResult.answer, flatNet);\n\n report.push('=== RESULT ===\\n');\n report.push(`VIOLATED: ${propDesc}`);\n if (decoded.trace.length > 0) {\n report.push(` Counterexample trace (${decoded.trace.length} states):`);\n for (let i = 0; i < decoded.trace.length; i++) {\n report.push(` ${i}: ${decoded.trace[i]}`);\n }\n }\n if (decoded.transitions.length > 0) {\n report.push(` Firing sequence: ${decoded.transitions.join(' -> ')}`);\n }\n report.push('\\n WARNING: This counterexample is in UNTIMED semantics.');\n report.push(' It may be spurious if timing constraints prevent this sequence.');\n report.push(' JS guards are also ignored in this analysis.');\n\n return buildResult(\n { type: 'violated' },\n report.join('\\n'), invariants, [], decoded.trace as MarkingState[], decoded.transitions as string[],\n performance.now() - start,\n { places: flatNet.places.length, transitions: flatNet.transitions.length, invariantsFound: invariants.length, structuralResult: structResultStr },\n );\n }\n\n case 'unknown': {\n report.push(` Status: UNKNOWN (${queryResult.reason})\\n`);\n report.push('=== RESULT ===\\n');\n report.push(`UNKNOWN: Could not determine ${propDesc}`);\n report.push(` Reason: ${queryResult.reason}`);\n\n return buildResult(\n { type: 'unknown', reason: queryResult.reason },\n report.join('\\n'), invariants, [], [], [],\n performance.now() - start,\n { places: flatNet.places.length, transitions: flatNet.transitions.length, invariantsFound: invariants.length, structuralResult: structResultStr },\n );\n }\n }\n } catch (e: any) {\n report.push(` ERROR: ${e.message ?? e}\\n`);\n report.push('=== RESULT ===\\n');\n report.push(`UNKNOWN: Z3 solver error: ${e.message ?? e}`);\n\n return buildResult(\n { type: 'unknown', reason: `Z3 error: ${e.message ?? e}` },\n report.join('\\n'), invariants, [], [], [],\n performance.now() - start,\n { places: flatNet.places.length, transitions: flatNet.transitions.length, invariantsFound: invariants.length, structuralResult: structResultStr },\n );\n } finally {\n runner.dispose();\n }\n }\n}\n\n/**\n * Substitutes Z3 variable names (m0, m1, ...) with place names in a formula string.\n */\nfunction substituteNames(formula: string, flatNet: FlatNet): string {\n // Replace from highest index first to avoid m1 matching inside m10\n for (let i = flatNet.places.length - 1; i >= 0; i--) {\n formula = formula.replace(new RegExp(`\\\\bm${i}\\\\b`, 'g'), flatNet.places[i]!.name);\n }\n return formula;\n}\n\nfunction formatInvariant(inv: PInvariant, flatNet: FlatNet): string {\n const parts: string[] = [];\n for (const idx of inv.support) {\n if (inv.weights[idx] !== 1) {\n parts.push(`${inv.weights[idx]}*${flatNet.places[idx]!.name}`);\n } else {\n parts.push(flatNet.places[idx]!.name);\n }\n }\n return `${parts.join(' + ')} = ${inv.constant}`;\n}\n\nfunction buildResult(\n verdict: Verdict,\n report: string,\n invariants: readonly PInvariant[],\n discoveredInvariants: readonly string[],\n trace: readonly MarkingState[],\n transitions: readonly string[],\n elapsedMs: number,\n statistics: SmtStatistics,\n): SmtVerificationResult {\n return { verdict, report, invariants, discoveredInvariants, counterexampleTrace: trace, counterexampleTransitions: transitions, elapsedMs, statistics };\n}\n","import type { MarkingState } from './marking-state.js';\nimport type { PInvariant } from './invariant/p-invariant.js';\n\n/**\n * Verification verdict.\n */\nexport type Verdict = Proven | Violated | Unknown;\n\n/** Property proven safe. No reachable state violates it. */\nexport interface Proven {\n readonly type: 'proven';\n readonly method: string;\n readonly inductiveInvariant: string | null;\n}\n\n/** Property violated. A counterexample trace is available. */\nexport interface Violated {\n readonly type: 'violated';\n}\n\n/** Could not determine. */\nexport interface Unknown {\n readonly type: 'unknown';\n readonly reason: string;\n}\n\n/**\n * Solver statistics.\n */\nexport interface SmtStatistics {\n readonly places: number;\n readonly transitions: number;\n readonly invariantsFound: number;\n readonly structuralResult: string;\n}\n\n/**\n * Result of SMT-based verification.\n */\nexport interface SmtVerificationResult {\n readonly verdict: Verdict;\n readonly report: string;\n readonly invariants: readonly PInvariant[];\n readonly discoveredInvariants: readonly string[];\n readonly counterexampleTrace: readonly MarkingState[];\n readonly counterexampleTransitions: readonly string[];\n readonly elapsedMs: number;\n readonly statistics: SmtStatistics;\n}\n\nexport function isProven(result: SmtVerificationResult): boolean {\n return result.verdict.type === 'proven';\n}\n\nexport function isViolated(result: SmtVerificationResult): boolean {\n return result.verdict.type === 'violated';\n}\n"],"mappings":";AAwDO,SAAS,OAAO,UAAyB;AAC9C,MAAI,SAAS,WAAW,GAAG;AACzB,UAAM,IAAI,MAAM,+BAA+B;AAAA,EACjD;AACA,SAAO,EAAE,MAAM,OAAO,SAAS;AACjC;AAGO,SAAS,aAAa,QAA8B;AACzD,SAAO,IAAI,GAAG,OAAO,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Q,YAAY,sBAAsB,qBAAqB,OAAO,2BAA2B,aAAa,WAAW,WAAW;AACxJ;;;AC7SO,SAAS,SAAS,QAAwC;AAC/D,SAAO,OAAO,QAAQ,SAAS;AACjC;AAEO,SAAS,WAAW,QAAwC;AACjE,SAAO,OAAO,QAAQ,SAAS;AACjC;","names":[]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/export/styles.ts","../src/export/subnet-prefixes.ts","../src/export/cluster-builder.ts","../src/export/petri-net-mapper.ts","../src/export/dot-renderer.ts","../src/export/dot-exporter.ts"],"sourcesContent":["// GENERATED from spec/petri-net-styles.json — do not edit manually.\n// Regenerate with: scripts/generate-styles.sh\n\n/**\n * Style loader for Petri net visualization.\n *\n * Reads the shared style definition from `spec/petri-net-styles.json` and\n * exposes typed accessors for node and edge visual properties.\n *\n * @module export/styles\n */\n\nimport type { NodeShape, EdgeLineStyle, ArrowHead } from './graph.js';\n\n// ======================== Style Types ========================\n\nexport interface NodeVisual {\n readonly shape: NodeShape;\n readonly fill: string;\n readonly stroke: string;\n readonly penwidth: number;\n readonly style?: string;\n readonly height?: number;\n readonly width?: number;\n}\n\nexport interface EdgeVisual {\n readonly color: string;\n readonly style: EdgeLineStyle;\n readonly arrowhead: ArrowHead;\n readonly penwidth?: number;\n}\n\nexport interface FontStyle {\n readonly family: string;\n readonly nodeSize: number;\n readonly edgeSize: number;\n}\n\nexport interface GraphStyle {\n readonly nodesep: number;\n readonly ranksep: number;\n readonly forcelabels: boolean;\n readonly overlap: boolean;\n readonly outputorder: string;\n}\n\n// ======================== Inline Style Data ========================\n\n// Inlined from spec/petri-net-styles.json to avoid runtime JSON import issues.\n// Keep in sync with the spec file.\n\nconst NODE_STYLES: Record<NodeCategory, NodeVisual> = {\n place: { shape: 'circle', fill: '#FFFFFF', stroke: '#333333', penwidth: 1.5, width: 0.35 },\n start: { shape: 'circle', fill: '#d4edda', stroke: '#28a745', penwidth: 2.0, width: 0.35 },\n end: { shape: 'doublecircle', fill: '#cce5ff', stroke: '#004085', penwidth: 2.0, width: 0.35 },\n environment: { shape: 'circle', fill: '#f8d7da', stroke: '#721c24', penwidth: 2.0, style: 'dashed', width: 0.35 },\n transition: { shape: 'box', fill: '#fff3cd', stroke: '#856404', penwidth: 1.0, height: 0.4, width: 0.8 },\n 'xor-junction': { shape: 'diamond', fill: '#FFFFFF', stroke: '#333333', penwidth: 1.0, height: 0.3, width: 0.3 },\n 'and-junction': { shape: 'diamond', fill: '#FFFFFF', stroke: '#333333', penwidth: 1.0, height: 0.3, width: 0.3 },\n 'interface-port':{ shape: 'circle', fill: '#e7f1ff', stroke: '#1d4ed8', penwidth: 2.0, style: 'dashed', width: 0.35 },\n 'sync-channel': { shape: 'box', fill: '#f3e8ff', stroke: '#6d28d9', penwidth: 1.5, height: 0.4, width: 0.8 },\n};\n\nconst EDGE_STYLES: Record<EdgeCategory, EdgeVisual> = {\n input: { color: '#333333', style: 'solid', arrowhead: 'normal' },\n output: { color: '#333333', style: 'solid', arrowhead: 'normal' },\n inhibitor: { color: '#dc3545', style: 'solid', arrowhead: 'odot' },\n read: { color: '#6c757d', style: 'dashed', arrowhead: 'normal' },\n reset: { color: '#fd7e14', style: 'bold', arrowhead: 'normal', penwidth: 2.0 },\n 'reset-output': { color: '#fd7e14', style: 'bold', arrowhead: 'normal', penwidth: 2.0 },\n};\n\nexport const FONT: FontStyle = { family: 'Helvetica,Arial,sans-serif', nodeSize: 12, edgeSize: 10 };\n\nexport const GRAPH: GraphStyle = { nodesep: 0.5, ranksep: 0.75, forcelabels: true, overlap: false, outputorder: 'edgesfirst' };\n\n// ======================== Public API ========================\n\nexport type NodeCategory = 'place' | 'start' | 'end' | 'environment' | 'transition' | 'xor-junction' | 'and-junction' | 'interface-port' | 'sync-channel';\nexport type EdgeCategory = 'input' | 'output' | 'inhibitor' | 'read' | 'reset' | 'reset-output';\n\n/** Returns the visual style for the given node category. */\nexport function nodeStyle(category: NodeCategory): NodeVisual {\n return NODE_STYLES[category];\n}\n\n/** Returns the visual style for the given edge/arc type. */\nexport function edgeStyle(arcType: EdgeCategory): EdgeVisual {\n return EDGE_STYLES[arcType];\n}\n","/**\n * Prefix-derivation helpers for subnet-instance-aware export and debug\n * tooling, per `spec/11-modular-composition.md` **MOD-040** (export\n * grouping) and **MOD-041** (debug protocol subnet instances).\n *\n * The `\"/\"` character is the prefix separator established by **MOD-010**:\n * a node named `\"outer/inner/leaf\"` belongs to the cluster tree\n * `outer -> outer/inner`, with `\"leaf\"` as the un-prefixed final segment.\n *\n * This module is observability-only — it never inspects {@link\n * import('../core/subnet-def').SubnetDef} or {@link\n * import('../core/instance').Instance} objects, only the resulting\n * prefixed names that survived composition. That keeps consumers (DOT\n * exporter, debug protocol handler) decoupled from the modular-composition\n * layer per **MOD-023**.\n *\n * @module export/subnet-prefixes\n */\n\n/**\n * Returns the instance prefix carried by the given node name, or `undefined`\n * when the name has no `/` (i.e. is not part of any composed subnet\n * instance).\n *\n * The prefix is the substring up to (but not including) the **last** `/`\n * — so `\"producer1/internal\"` returns `\"producer1\"` and\n * `\"outer/inner/leaf\"` returns `\"outer/inner\"`. The bare segment after the\n * last `/` is the original (un-prefixed) place or transition name.\n *\n * @param nodeName the prefixed-or-flat node name\n * @returns the prefix, or `undefined` for flat names\n */\nexport function instancePrefixOf(nodeName: string | null | undefined): string | undefined {\n if (nodeName == null) return undefined;\n const idx = nodeName.lastIndexOf('/');\n if (idx <= 0) return undefined;\n return nodeName.substring(0, idx);\n}\n\n/**\n * Returns the parent prefix of a given prefix, or `undefined` if the prefix\n * is top-level (single segment, no `/`).\n *\n * Used by the debug protocol's {@code SubnetInstance.parentPrefix} field\n * per **MOD-041** for nested instances.\n *\n * @param prefix an instance prefix string (e.g. `\"outer/inner\"`)\n * @returns the parent prefix (e.g. `\"outer\"`), or `undefined` for top-level\n */\nexport function parentOf(prefix: string | null | undefined): string | undefined {\n if (prefix == null || prefix.length === 0) return undefined;\n const idx = prefix.lastIndexOf('/');\n if (idx <= 0) return undefined;\n return prefix.substring(0, idx);\n}\n\n/**\n * Returns the last (leaf) segment of a prefix, used as the cluster label per\n * **MOD-040**. For top-level prefixes the input itself is returned unchanged.\n *\n * @param prefix an instance prefix string\n * @returns the trailing segment after the last `/` (or the input when there\n * is no `/`)\n */\nexport function leafSegment(prefix: string | null | undefined): string | null | undefined {\n if (prefix == null || prefix.length === 0) return prefix;\n const idx = prefix.lastIndexOf('/');\n return idx < 0 ? prefix : prefix.substring(idx + 1);\n}\n","/**\n * Builds nested `subgraph cluster_*` blocks for DOT export per\n * `spec/11-modular-composition.md` **MOD-040** and `spec/09-export.md`\n * **EXP-016**.\n *\n * Given a flat list of nodes and edges plus a `nodeId -> prefix` map\n * produced during mapping (see {@link import('./petri-net-mapper.js').mapToGraph}),\n * this partitioner:\n *\n * 1. Walks every distinct prefix to produce the cluster tree (nested\n * {@link Subgraph} entries).\n * 2. Routes each node into the deepest cluster whose prefix equals the\n * node's prefix; nodes without a prefix stay at the top level.\n * 3. Routes each edge into the deepest cluster that contains **both**\n * endpoints; edges crossing cluster boundaries (or with at least one\n * top-level endpoint) stay at the top level so Graphviz routes them\n * correctly without truncating cluster boxes.\n * 4. Applies a default cluster style (rounded, dashed, light fill) when\n * none is provided — readable defaults sufficient until task #9 layers\n * the doclet styling on top.\n *\n * This partitioner is structural-only: it does not consult any\n * {@link import('../core/subnet-def').SubnetDef} or {@link\n * import('../core/instance').Instance} — it operates exclusively on the\n * flattened post-composition node names per **MOD-023**.\n *\n * @module export/cluster-builder\n */\n\nimport type { GraphEdge, GraphNode, Subgraph } from './graph.js';\nimport { sanitize } from './petri-net-mapper.js';\nimport { parentOf } from './subnet-prefixes.js';\n\n/** Result of partitioning nodes/edges into a clustered hierarchy. */\nexport interface Partition {\n readonly topLevelNodes: readonly GraphNode[];\n readonly topLevelEdges: readonly GraphEdge[];\n readonly topLevelSubgraphs: readonly Subgraph[];\n}\n\n/**\n * Default cluster styling (per [EXP-016] visual contract). These values\n * mirror the `cluster.subnet-cluster` entry in\n * `spec/petri-net-styles.json` so cross-language output stays\n * byte-equivalent.\n */\nexport const DEFAULT_CLUSTER_ATTRS: Readonly<Record<string, string>> = {\n style: 'rounded,dashed',\n bgcolor: '#FAFAFA',\n penwidth: '1.5',\n};\n\ninterface MutableCluster {\n readonly prefix: string;\n readonly nodes: GraphNode[];\n readonly edges: GraphEdge[];\n readonly childPrefixes: string[];\n}\n\n/**\n * Partitions nodes and edges into a cluster hierarchy. Mutates neither input\n * collection.\n *\n * @param nodes all nodes (places, transitions, junctions)\n * @param edges all edges\n * @param nodeIdToPrefix per-node instance prefix; absent entries stay\n * top-level\n * @returns the partitioned cluster hierarchy\n */\nexport function partition(\n nodes: readonly GraphNode[],\n edges: readonly GraphEdge[],\n nodeIdToPrefix: ReadonlyMap<string, string>,\n): Partition {\n // Fast path: no prefixes => no clusters. Preserves byte-equal output for\n // flat (non-composed) nets.\n if (nodeIdToPrefix.size === 0) {\n return {\n topLevelNodes: [...nodes],\n topLevelEdges: [...edges],\n topLevelSubgraphs: [],\n };\n }\n\n // Step 1: walk every prefix to produce the cluster tree shape. We need\n // every internal prefix node, not just leaf prefixes — e.g. a node\n // \"outer/inner/leaf\" requires both \"outer\" and \"outer/inner\" to exist as\n // cluster blocks per [EXP-016] / [MOD-013].\n //\n // We use a Map for insertion-order iteration (deterministic per [EXP-014]).\n const prefixOrder = new Map<string, true>();\n for (const prefix of nodeIdToPrefix.values()) {\n registerPrefixChain(prefix, prefixOrder);\n }\n\n // prefix -> (mutable nodes, mutable edges, mutable child prefixes)\n const prefixState = new Map<string, MutableCluster>();\n for (const prefix of prefixOrder.keys()) {\n prefixState.set(prefix, { prefix, nodes: [], edges: [], childPrefixes: [] });\n }\n // Wire parent -> child relationships.\n for (const prefix of prefixState.keys()) {\n const parent = parentOf(prefix);\n if (parent !== undefined) {\n prefixState.get(parent)!.childPrefixes.push(prefix);\n }\n }\n\n // Step 2: route nodes into their deepest cluster.\n const topLevelNodes: GraphNode[] = [];\n for (const node of nodes) {\n const prefix = nodeIdToPrefix.get(node.id);\n if (prefix === undefined) {\n topLevelNodes.push(node);\n } else {\n prefixState.get(prefix)!.nodes.push(node);\n }\n }\n\n // Step 3: route edges into the deepest cluster containing both endpoints.\n // Cross-cluster edges stay at top-level so Graphviz draws them between\n // cluster boxes rather than inside one.\n const topLevelEdges: GraphEdge[] = [];\n for (const edge of edges) {\n const fromPrefix = nodeIdToPrefix.get(edge.from);\n const toPrefix = nodeIdToPrefix.get(edge.to);\n const common = deepestCommonPrefix(fromPrefix, toPrefix);\n if (common === undefined) {\n topLevelEdges.push(edge);\n } else {\n prefixState.get(common)!.edges.push(edge);\n }\n }\n\n // Step 3.5: synthesize ghost edges for 1-hop cluster_X → orphan → cluster_Y\n // paths so Graphviz (with compound=true) can constrain the two clusters'\n // relative layout. Ghost edges are style=invis — they carry layout weight\n // only; the visible flow still goes through the orphan via the real edges.\n // Per spec EXP-017.\n for (const ghost of synthesizeGhostEdges(nodes, edges, nodeIdToPrefix)) {\n topLevelEdges.push(ghost);\n }\n\n // Step 4: assemble Subgraph records bottom-up so children are built before\n // they're consumed by parents.\n const built = new Map<string, Subgraph>();\n // Reverse the insertion order: parents were inserted before children in\n // registerPrefixChain so iterating reversed produces a deepest-first order.\n const iterationOrder = [...prefixState.keys()].reverse();\n for (const prefix of iterationOrder) {\n const state = prefixState.get(prefix)!;\n const children: Subgraph[] = [];\n for (const childPrefix of state.childPrefixes) {\n const child = built.get(childPrefix);\n if (child !== undefined) {\n children.push(child);\n }\n }\n // Children were built deepest-first, so they're reversed relative to\n // their original insertion order. Restore the original order.\n children.reverse();\n\n const subgraph: Subgraph = {\n id: sanitize(prefix),\n label: prefix,\n nodes: [...state.nodes],\n edges: [...state.edges],\n subgraphs: children,\n attrs: DEFAULT_CLUSTER_ATTRS,\n };\n built.set(prefix, subgraph);\n }\n\n // Top-level subgraphs are those whose prefix has no parent.\n const topLevelSubgraphs: Subgraph[] = [];\n for (const prefix of prefixState.keys()) {\n if (parentOf(prefix) === undefined) {\n topLevelSubgraphs.push(built.get(prefix)!);\n }\n }\n\n return {\n topLevelNodes,\n topLevelEdges,\n topLevelSubgraphs,\n };\n}\n\n/**\n * Walks a prefix root-to-leaf, registering every intermediate prefix in\n * `accumulator` (no-op when already present). Ensures parents are inserted\n * before children.\n */\nfunction registerPrefixChain(prefix: string | undefined, accumulator: Map<string, true>): void {\n if (prefix == null || prefix.length === 0) return;\n const segments = prefix.split('/');\n let built = '';\n for (const seg of segments) {\n if (built.length > 0) built += '/';\n built += seg;\n if (!accumulator.has(built)) {\n accumulator.set(built, true);\n }\n }\n}\n\n/**\n * Synthesizes one invisible ghost edge per ordered (cluster_X, cluster_Y)\n * pair that is bridged by at least one top-level orphan node via a 1-hop\n * path (i.e. some edge X-node → orphan and some edge orphan → Y-node). The\n * ghost edge carries `style=invis, ltail=cluster_<sanitizedX>,\n * lhead=cluster_<sanitizedY>` so Graphviz (with `compound=true`) treats it\n * as a real cluster-to-cluster layout constraint without producing any\n * visible artifact. Per spec EXP-017.\n *\n * Determinism: walks orphans in `nodes` order, walks each orphan's\n * incoming/outgoing edges in `edges` order. First-witness wins for anchor\n * node selection. This matches the iteration discipline in the Java/Rust\n * mirrors so cross-language byte-parity holds.\n */\nfunction synthesizeGhostEdges(\n nodes: readonly GraphNode[],\n edges: readonly GraphEdge[],\n nodeIdToPrefix: ReadonlyMap<string, string>,\n): GraphEdge[] {\n // Index edges by their orphan endpoint. An orphan is any node whose id is\n // not in nodeIdToPrefix.\n const incomingByOrphan = new Map<string, GraphEdge[]>();\n const outgoingByOrphan = new Map<string, GraphEdge[]>();\n for (const edge of edges) {\n const fromHasPrefix = nodeIdToPrefix.has(edge.from);\n const toHasPrefix = nodeIdToPrefix.has(edge.to);\n if (fromHasPrefix && !toHasPrefix) {\n let list = incomingByOrphan.get(edge.to);\n if (list === undefined) {\n list = [];\n incomingByOrphan.set(edge.to, list);\n }\n list.push(edge);\n }\n if (!fromHasPrefix && toHasPrefix) {\n let list = outgoingByOrphan.get(edge.from);\n if (list === undefined) {\n list = [];\n outgoingByOrphan.set(edge.from, list);\n }\n list.push(edge);\n }\n }\n\n // Walk orphans in nodes order. For each (clusterX_prefix, clusterY_prefix)\n // ordered pair with X !== Y, record the first witness anchor pair.\n // Map<\"X\\0Y\", { from, to, x, y }> — using an insertion-ordered Map for\n // deterministic emission order.\n const ghosts = new Map<string, { from: string; to: string; x: string; y: string }>();\n for (const node of nodes) {\n if (nodeIdToPrefix.has(node.id)) continue;\n const incoming = incomingByOrphan.get(node.id);\n const outgoing = outgoingByOrphan.get(node.id);\n if (incoming === undefined || outgoing === undefined) continue;\n for (const eIn of incoming) {\n const x = nodeIdToPrefix.get(eIn.from)!;\n for (const eOut of outgoing) {\n const y = nodeIdToPrefix.get(eOut.to)!;\n if (x === y) continue;\n const key = `${x}\\0${y}`;\n if (!ghosts.has(key)) {\n ghosts.set(key, { from: eIn.from, to: eOut.to, x, y });\n }\n }\n }\n }\n\n const result: GraphEdge[] = [];\n for (const { from, to, x, y } of ghosts.values()) {\n result.push({\n from,\n to,\n color: '#000000',\n style: 'invis',\n arrowhead: 'none',\n arcType: 'ghost',\n attrs: {\n ltail: 'cluster_' + sanitize(x),\n lhead: 'cluster_' + sanitize(y),\n },\n });\n }\n return result;\n}\n\n/**\n * Returns the deepest prefix that is a (non-strict) ancestor of both sides,\n * or `undefined` when there is no shared cluster (top-level routing).\n */\nfunction deepestCommonPrefix(a: string | undefined, b: string | undefined): string | undefined {\n if (a === undefined || b === undefined) return undefined;\n if (a === b) return a;\n\n const aSegs = a.split('/');\n const bSegs = b.split('/');\n let built = '';\n let matched = 0;\n const min = Math.min(aSegs.length, bSegs.length);\n for (let i = 0; i < min; i++) {\n if (aSegs[i] !== bSegs[i]) break;\n if (matched > 0) built += '/';\n built += aSegs[i];\n matched++;\n }\n return matched === 0 ? undefined : built;\n}\n","/**\n * Maps a PetriNet definition to a format-agnostic Graph.\n *\n * Petri net semantics live here. The mapper applies the visualization rules\n * specified in spec/09-export.md (EXP-012, EXP-013, EXP-014):\n *\n * - XOR / AND output groups with ≥2 children become synthetic junction nodes\n * (diamond for XOR, square for AND).\n * - Output + reset arcs to the same place collapse into a single edge styled\n * as the reset-output category and labelled \"reset+out\".\n * - Junction IDs use the form j_<transition>__<kind>_<idx>, where idx is a\n * depth-first pre-order counter starting at 0.\n *\n * @module export/petri-net-mapper\n */\n\nimport type { PetriNet } from '../core/petri-net.js';\nimport type { Transition } from '../core/transition.js';\nimport type { Out } from '../core/out.js';\nimport { earliest, latest, hasDeadline } from '../core/timing.js';\nimport type { Graph, GraphNode, GraphEdge, RankDir } from './graph.js';\nimport { nodeStyle, edgeStyle, FONT, GRAPH } from './styles.js';\nimport type { NodeCategory } from './styles.js';\nimport { partition } from './cluster-builder.js';\nimport { instancePrefixOf } from './subnet-prefixes.js';\n\n// ======================== Configuration ========================\n\n/**\n * Selects how DOT export groups nodes into `subgraph cluster_*` blocks (per\n * **MOD-040** / **EXP-016**).\n *\n * - `'auto'` — use subnet-membership metadata (per MOD-026) when the net\n * carries any; otherwise fall back to instance-prefix name detection.\n * Default.\n * - `'metadata'` — strictly cluster from subnet-membership metadata; a node\n * with no metadata entry — including a prefix-named instance node — is not\n * clustered. Use `'auto'` to also cluster prefix-named nodes.\n * - `'prefix'` — always cluster from instance-prefix name segments; ignore\n * metadata.\n * - `'none'` — emit no clusters; every node renders at the top level.\n */\nexport type ClusterSource = 'auto' | 'metadata' | 'prefix' | 'none';\n\nexport interface DotConfig {\n readonly direction: RankDir;\n readonly showTypes: boolean;\n readonly showIntervals: boolean;\n readonly showPriority: boolean;\n readonly environmentPlaces?: ReadonlySet<string>;\n /**\n * How to group nodes into `subgraph cluster_*` blocks (per MOD-040 /\n * EXP-016). Additive; defaults to `'auto'` when omitted.\n */\n readonly clusterSource?: ClusterSource;\n}\n\nexport const DEFAULT_DOT_CONFIG: DotConfig = {\n direction: 'TB',\n showTypes: true,\n showIntervals: true,\n showPriority: true,\n};\n\n// ======================== Public API ========================\n\n/** Sanitizes a name for use as a graph node ID. */\nexport function sanitize(name: string): string {\n return name.replace(/[^a-zA-Z0-9_]/g, '_');\n}\n\n/** Maps a PetriNet to a format-agnostic Graph. */\nexport function mapToGraph(net: PetriNet, config: DotConfig = DEFAULT_DOT_CONFIG): Graph {\n const places = analyzePlaces(net);\n const envNames = config.environmentPlaces ?? new Set<string>();\n\n const nodes: GraphNode[] = [];\n const edges: GraphEdge[] = [];\n\n // Track each emitted node's cluster key (per [MOD-040]) so we can partition\n // into subgraph clusters at the end. Nodes with no cluster key are absent\n // from this map and stay at the top level.\n const nodeIdToPrefix = new Map<string, string>();\n\n // MOD-040 / EXP-016: 'auto' uses subnet-membership metadata (MOD-026) when\n // present and falls back to instance-prefix detection; 'metadata' is strict\n // (metadata only, no fallback); 'prefix' ignores metadata; 'none' suppresses\n // clustering. Flat and prefix-instantiated nets stay byte-identical under\n // 'auto'.\n const membership = net.subnetMembership;\n const clusterSource: ClusterSource = config.clusterSource ?? 'auto';\n\n // Place nodes\n for (const [name, info] of places) {\n const category = placeCategory(info, envNames.has(name));\n const style = nodeStyle(category);\n const nodeId = 'p_' + sanitize(name);\n nodes.push({\n id: nodeId,\n label: '',\n shape: style.shape,\n fill: style.fill,\n stroke: style.stroke,\n penwidth: style.penwidth,\n semanticId: name,\n style: style.style,\n width: style.width,\n attrs: { xlabel: name, fixedsize: 'true' },\n });\n const key = clusterKeyOf(name, clusterSource, membership);\n if (key !== undefined) {\n nodeIdToPrefix.set(nodeId, key);\n }\n }\n\n // Transition nodes\n for (const t of net.transitions) {\n const style = nodeStyle('transition');\n const tid = 't_' + sanitize(t.name);\n nodes.push({\n id: tid,\n label: transitionLabel(t, config),\n shape: style.shape,\n fill: style.fill,\n stroke: style.stroke,\n penwidth: style.penwidth,\n semanticId: t.name,\n height: style.height,\n width: style.width,\n });\n const key = clusterKeyOf(t.name, clusterSource, membership);\n if (key !== undefined) {\n nodeIdToPrefix.set(tid, key);\n }\n }\n\n // Edges (and junction nodes)\n for (const t of net.transitions) {\n const tid = 't_' + sanitize(t.name);\n const tSanitized = sanitize(t.name);\n // Junctions inherit their parent transition's cluster key — tracked here\n // so the partition step routes them correctly.\n const tPrefix = clusterKeyOf(t.name, clusterSource, membership);\n const resetPlaces = new Set(t.resets.map(r => r.place.name));\n const combined = new Set<string>();\n\n // Input arcs from inputSpecs\n for (const spec of t.inputSpecs) {\n const pid = 'p_' + sanitize(spec.place.name);\n const inputStyle = edgeStyle('input');\n let label: string | undefined;\n switch (spec.type) {\n case 'exactly':\n label = `×${spec.count}`;\n break;\n case 'all':\n label = '*';\n break;\n case 'at-least':\n label = `≥${spec.minimum}`;\n break;\n }\n edges.push({\n from: pid,\n to: tid,\n label,\n color: inputStyle.color,\n style: inputStyle.style,\n arrowhead: inputStyle.arrowhead,\n arcType: 'input',\n });\n }\n\n // Output arcs from outputSpec — emits junction nodes + edges, marks combined places.\n if (t.outputSpec !== null) {\n const ctx: EmitCtx = {\n tSanitized,\n resetPlaces,\n combined,\n nodes,\n edges,\n counter: 0,\n transitionPrefix: tPrefix,\n nodeIdToPrefix,\n };\n emitOutput(t.outputSpec, tid, null, ctx);\n }\n\n // Inhibitor arcs\n for (const inh of t.inhibitors) {\n const pid = 'p_' + sanitize(inh.place.name);\n const inhStyle = edgeStyle('inhibitor');\n edges.push({\n from: pid,\n to: tid,\n color: inhStyle.color,\n style: inhStyle.style,\n arrowhead: inhStyle.arrowhead,\n arcType: 'inhibitor',\n });\n }\n\n // Read arcs\n for (const r of t.reads) {\n const pid = 'p_' + sanitize(r.place.name);\n const readStyle = edgeStyle('read');\n edges.push({\n from: pid,\n to: tid,\n label: 'read',\n color: readStyle.color,\n style: readStyle.style,\n arrowhead: readStyle.arrowhead,\n arcType: 'read',\n });\n }\n\n // Standalone reset arcs (only those not already combined with an output)\n for (const rst of t.resets) {\n if (!combined.has(rst.place.name)) {\n const pid = 'p_' + sanitize(rst.place.name);\n const resetStyle = edgeStyle('reset');\n edges.push({\n from: tid,\n to: pid,\n label: 'reset',\n color: resetStyle.color,\n style: resetStyle.style,\n arrowhead: resetStyle.arrowhead,\n penwidth: resetStyle.penwidth,\n arcType: 'reset',\n });\n }\n }\n }\n\n // Partition nodes/edges into subgraph clusters per [MOD-040] / [EXP-016].\n // When there are no prefixed names this is a structural no-op and the\n // resulting Graph is byte-identical to the pre-cluster output.\n const partitioned = partition(nodes, edges, nodeIdToPrefix);\n\n return {\n id: sanitize(net.name),\n rankdir: config.direction,\n nodes: partitioned.topLevelNodes,\n edges: partitioned.topLevelEdges,\n subgraphs: partitioned.topLevelSubgraphs,\n graphAttrs: {\n nodesep: String(GRAPH.nodesep),\n ranksep: String(GRAPH.ranksep),\n forcelabels: String(GRAPH.forcelabels),\n overlap: String(GRAPH.overlap),\n fontname: FONT.family,\n outputorder: GRAPH.outputorder,\n compound: 'true',\n },\n nodeDefaults: {\n fontname: FONT.family,\n fontsize: String(FONT.nodeSize),\n },\n edgeDefaults: {\n fontname: FONT.family,\n fontsize: String(FONT.edgeSize),\n },\n };\n}\n\n// ======================== Place Analysis ========================\n\ninterface PlaceInfo {\n hasIncoming: boolean;\n hasOutgoing: boolean;\n}\n\nfunction analyzePlaces(net: PetriNet): Map<string, PlaceInfo> {\n const map = new Map<string, PlaceInfo>();\n\n function ensure(name: string): PlaceInfo {\n let info = map.get(name);\n if (!info) {\n info = { hasIncoming: false, hasOutgoing: false };\n map.set(name, info);\n }\n return info;\n }\n\n for (const t of net.transitions) {\n for (const spec of t.inputSpecs) {\n ensure(spec.place.name).hasOutgoing = true;\n }\n if (t.outputSpec !== null) {\n for (const p of t.outputPlaces()) {\n ensure(p.name).hasIncoming = true;\n }\n }\n for (const inh of t.inhibitors) {\n ensure(inh.place.name);\n }\n for (const r of t.reads) {\n ensure(r.place.name).hasOutgoing = true;\n }\n for (const rst of t.resets) {\n ensure(rst.place.name);\n }\n }\n\n return map;\n}\n\nfunction placeCategory(info: PlaceInfo, isEnvironment: boolean): NodeCategory {\n if (isEnvironment) return 'environment';\n if (!info.hasIncoming) return 'start';\n if (!info.hasOutgoing) return 'end';\n return 'place';\n}\n\n// ======================== Helpers ========================\n\n/**\n * Resolves the cluster key for a node (place or transition) per **MOD-040** /\n * **EXP-016**:\n *\n * - `'auto'` — the owning subnet name from membership metadata (MOD-026),\n * falling back to instance-prefix detection for any node without an entry,\n * so mixed direct + instance composition keeps both cluster kinds.\n * - `'metadata'` — strictly the owning subnet name; a node with no metadata\n * entry is not clustered.\n * - `'prefix'` — strictly the instance-prefix segment; metadata is ignored.\n * - `'none'` — never clustered.\n *\n * @param nodeName the semantic node name (place or transition)\n * @param source the configured cluster source\n * @param membership the net's subnet-membership map (MOD-026)\n * @returns the cluster key, or `undefined` when the node is not clustered\n */\nfunction clusterKeyOf(\n nodeName: string,\n source: ClusterSource,\n membership: ReadonlyMap<string, string>,\n): string | undefined {\n switch (source) {\n case 'none':\n return undefined;\n case 'prefix':\n return instancePrefixOf(nodeName);\n case 'metadata':\n return membership.get(nodeName);\n case 'auto':\n return membership.get(nodeName) ?? instancePrefixOf(nodeName);\n default: {\n // Exhaustiveness guard: a future ClusterSource member is a compile error.\n const _exhaustive: never = source;\n return _exhaustive;\n }\n }\n}\n\nfunction transitionLabel(t: Transition, config: DotConfig): string {\n const parts = [t.name];\n\n if (config.showIntervals) {\n const e = earliest(t.timing);\n const l = latest(t.timing);\n const max = hasDeadline(t.timing) ? String(l) : '∞';\n parts.push(`[${e}, ${max}]ms`);\n }\n\n if (config.showPriority && t.priority !== 0) {\n parts.push(`prio=${t.priority}`);\n }\n\n return parts.join(' ');\n}\n\n/**\n * Mutable per-transition state threaded through the recursive Out-tree walk.\n *\n * `counter` starts at 0 and increments once per emitted junction (depth-first\n * pre-order). `combined` accumulates place names where a reset+output combination\n * short-circuited the standalone reset edge.\n */\ninterface EmitCtx {\n readonly tSanitized: string;\n readonly resetPlaces: ReadonlySet<string>;\n readonly combined: Set<string>;\n readonly nodes: GraphNode[];\n readonly edges: GraphEdge[];\n counter: number;\n /**\n * Instance prefix (e.g. \"b1\" or \"outer/inner\") of the parent transition —\n * junction nodes inherit this so they live inside the right cluster per\n * [MOD-040]. Undefined for transitions that are not part of any composed\n * instance.\n */\n readonly transitionPrefix: string | undefined;\n /**\n * Shared map populated during mapping; junction emitters add their own\n * entries under transitionPrefix.\n */\n readonly nodeIdToPrefix: Map<string, string>;\n}\n\n/**\n * Emits output edges for an Out tree, inserting junction nodes for XOR/AND\n * groups with ≥2 children. Combined reset+output edges replace plain output\n * edges when a leaf place is also in `ctx.resetPlaces`.\n *\n * @param out current Out subtree\n * @param parentId id of the parent node (transition or junction)\n * @param branchLabel label to apply to the edge entering this Out (timeout/XOR-branch label)\n * @param ctx per-transition junction context (counter, reset set, accumulators)\n */\nfunction emitOutput(out: Out, parentId: string, branchLabel: string | null, ctx: EmitCtx): void {\n switch (out.type) {\n case 'place': {\n const pid = 'p_' + sanitize(out.place.name);\n pushLeafEdge(parentId, pid, out.place.name, branchLabel, ctx, false);\n return;\n }\n\n case 'forward-input': {\n const pid = 'p_' + sanitize(out.to.name);\n const fwdLabel = (branchLabel ? branchLabel + ' ' : '') + '⟵' + out.from.name;\n // ForwardInput is dashed; reset+out combination overrides if applicable.\n pushLeafEdge(parentId, pid, out.to.name, fwdLabel, ctx, true);\n return;\n }\n\n case 'and':\n case 'xor': {\n // Single-child groups collapse: pass through.\n if (out.children.length < 2) {\n if (out.children.length === 1) {\n emitOutput(out.children[0]!, parentId, branchLabel, ctx);\n }\n return;\n }\n\n // Insert junction node — diamond gateway with heavy ✕ / ✚ glyph as discriminator.\n const kind = out.type;\n const idx = ctx.counter++;\n const junctionId = `j_${ctx.tSanitized}__${kind}_${idx}`;\n const category: NodeCategory = kind === 'xor' ? 'xor-junction' : 'and-junction';\n const jStyle = nodeStyle(category);\n ctx.nodes.push({\n id: junctionId,\n label: kind === 'xor' ? '✕' : '✚',\n shape: jStyle.shape,\n fill: jStyle.fill,\n stroke: jStyle.stroke,\n penwidth: jStyle.penwidth,\n semanticId: junctionId,\n height: jStyle.height,\n width: jStyle.width,\n attrs: { fixedsize: 'true', fontsize: '14' },\n });\n // Junctions belong to their parent transition's cluster per [MOD-040].\n if (ctx.transitionPrefix !== undefined) {\n ctx.nodeIdToPrefix.set(junctionId, ctx.transitionPrefix);\n }\n\n // Edge parent → junction (carries any inherited branch/timeout label).\n const outStyle = edgeStyle('output');\n ctx.edges.push({\n from: parentId,\n to: junctionId,\n label: branchLabel ?? undefined,\n color: outStyle.color,\n style: outStyle.style,\n arrowhead: outStyle.arrowhead,\n arcType: 'output',\n });\n\n // Recurse children: XOR junction propagates per-branch labels; AND junction does not.\n for (const child of out.children) {\n const childLabel = kind === 'xor' ? inferBranchLabel(child) : null;\n emitOutput(child, junctionId, childLabel, ctx);\n }\n return;\n }\n\n case 'timeout': {\n // Override any inherited branchLabel: the timeout label fully describes\n // this branch (the XOR pre-inference resolves to the same string).\n const timeoutLabel = `⏱${out.afterMs}ms`;\n emitOutput(out.child, parentId, timeoutLabel, ctx);\n return;\n }\n }\n}\n\nfunction pushLeafEdge(\n fromId: string,\n toId: string,\n placeName: string,\n branchLabel: string | null,\n ctx: EmitCtx,\n isForwardInput: boolean,\n): void {\n if (ctx.resetPlaces.has(placeName)) {\n ctx.combined.add(placeName);\n const ro = edgeStyle('reset-output');\n ctx.edges.push({\n from: fromId,\n to: toId,\n label: 'reset+out',\n color: ro.color,\n style: ro.style,\n arrowhead: ro.arrowhead,\n penwidth: ro.penwidth,\n arcType: 'reset-output',\n });\n return;\n }\n\n const out = edgeStyle('output');\n ctx.edges.push({\n from: fromId,\n to: toId,\n label: branchLabel ?? undefined,\n color: out.color,\n style: isForwardInput ? 'dashed' : out.style,\n arrowhead: out.arrowhead,\n arcType: 'output',\n });\n}\n\nfunction inferBranchLabel(out: Out): string | null {\n switch (out.type) {\n case 'place': return out.place.name;\n case 'timeout': return `⏱${out.afterMs}ms`;\n case 'forward-input': return out.to.name;\n case 'and':\n case 'xor':\n return null;\n }\n}\n","/**\n * Renders a Graph to DOT (Graphviz) string.\n *\n * Pure function with zero Petri net knowledge. Operates solely on the\n * format-agnostic Graph model.\n *\n * @module export/dot-renderer\n */\n\nimport type { Graph, GraphNode, GraphEdge, Subgraph } from './graph.js';\n\n// ======================== Public API ========================\n\n/** Renders a Graph to a DOT string suitable for Graphviz. */\nexport function renderDot(graph: Graph): string {\n const lines: string[] = [];\n\n lines.push(`digraph ${quoteId(graph.id)} {`);\n\n // Graph attributes\n lines.push(` rankdir=${graph.rankdir};`);\n for (const [key, value] of Object.entries(graph.graphAttrs)) {\n lines.push(` ${key}=${quoteAttr(value)};`);\n }\n\n // Node defaults\n if (Object.keys(graph.nodeDefaults).length > 0) {\n lines.push(` node [${formatAttrs(graph.nodeDefaults)}];`);\n }\n\n // Edge defaults\n if (Object.keys(graph.edgeDefaults).length > 0) {\n lines.push(` edge [${formatAttrs(graph.edgeDefaults)}];`);\n }\n\n lines.push('');\n\n // Subgraphs\n for (const sg of graph.subgraphs) {\n lines.push(...renderSubgraph(sg, ' '));\n lines.push('');\n }\n\n // Nodes\n for (const node of graph.nodes) {\n lines.push(` ${renderNode(node)}`);\n }\n\n if (graph.nodes.length > 0) {\n lines.push('');\n }\n\n // Edges\n for (const edge of graph.edges) {\n lines.push(` ${renderEdge(edge)}`);\n }\n\n lines.push('}');\n\n return lines.join('\\n');\n}\n\n// ======================== Internal Rendering ========================\n\nfunction renderNode(node: GraphNode): string {\n const attrs: Record<string, string> = {\n label: node.label,\n shape: node.shape,\n style: node.style ? `\"filled,${node.style}\"` : 'filled',\n fillcolor: node.fill,\n color: node.stroke,\n penwidth: String(node.penwidth),\n };\n\n if (node.height !== undefined) {\n attrs['height'] = String(node.height);\n }\n if (node.width !== undefined) {\n attrs['width'] = String(node.width);\n }\n\n // Merge extra attrs\n if (node.attrs) {\n for (const [key, value] of Object.entries(node.attrs)) {\n attrs[key] = value;\n }\n }\n\n return `${quoteId(node.id)} [${formatNodeAttrs(attrs)}];`;\n}\n\nfunction renderEdge(edge: GraphEdge): string {\n const attrs: Record<string, string> = {\n color: edge.color,\n style: edge.style,\n arrowhead: edge.arrowhead,\n };\n\n if (edge.label !== undefined) {\n attrs['label'] = edge.label;\n }\n if (edge.penwidth !== undefined) {\n attrs['penwidth'] = String(edge.penwidth);\n }\n\n // Merge extra attrs\n if (edge.attrs) {\n for (const [key, value] of Object.entries(edge.attrs)) {\n attrs[key] = value;\n }\n }\n\n return `${quoteId(edge.from)} -> ${quoteId(edge.to)} [${formatNodeAttrs(attrs)}];`;\n}\n\nfunction renderSubgraph(sg: Subgraph, indent: string): string[] {\n const lines: string[] = [];\n lines.push(`${indent}subgraph ${quoteId('cluster_' + sg.id)} {`);\n\n if (sg.label !== undefined) {\n lines.push(`${indent} label=${quoteAttr(sg.label)};`);\n }\n\n if (sg.attrs) {\n for (const [key, value] of Object.entries(sg.attrs)) {\n lines.push(`${indent} ${key}=${quoteAttr(value)};`);\n }\n }\n\n for (const node of sg.nodes) {\n lines.push(`${indent} ${renderNode(node)}`);\n }\n\n // Nested clusters per EXP-016 / MOD-040.\n if (sg.subgraphs) {\n for (const nested of sg.subgraphs) {\n lines.push(...renderSubgraph(nested, indent + ' '));\n }\n }\n\n // Intra-cluster edges (both endpoints inside this cluster) — placed inside\n // the cluster so Graphviz routes them correctly. Cross-cluster edges live\n // on the top-level Graph.edges list.\n if (sg.edges) {\n for (const e of sg.edges) {\n lines.push(`${indent} ${renderEdge(e)}`);\n }\n }\n\n lines.push(`${indent}}`);\n return lines;\n}\n\n// ======================== DOT Quoting ========================\n\n/** Quotes a DOT identifier. Always quotes to be safe with special chars. */\nfunction quoteId(id: string): string {\n // DOT keywords that must be quoted\n if (/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(id) && !isDotKeyword(id)) {\n return id;\n }\n return `\"${escapeDot(id)}\"`;\n}\n\n/** Quotes a DOT attribute value. */\nfunction quoteAttr(value: string): string {\n // Numbers don't need quoting\n if (/^-?\\d+(\\.\\d+)?$/.test(value)) {\n return value;\n }\n return `\"${escapeDot(value)}\"`;\n}\n\n/** Escapes special characters for DOT strings. */\nfunction escapeDot(s: string): string {\n return s.replace(/\\\\/g, '\\\\\\\\').replace(/\"/g, '\\\\\"');\n}\n\n/**\n * Formats node/edge attributes where certain values (like style with commas)\n * need special handling.\n */\nfunction formatNodeAttrs(attrs: Record<string, string>): string {\n return Object.entries(attrs)\n .map(([key, value]) => {\n // Style values that are already pre-quoted (contain the quote char)\n if (value.startsWith('\"') && value.endsWith('\"')) {\n return `${key}=${value}`;\n }\n return `${key}=${quoteAttr(value)}`;\n })\n .join(', ');\n}\n\n/** Formats simple key=value attributes. */\nfunction formatAttrs(attrs: Readonly<Record<string, string>>): string {\n return Object.entries(attrs)\n .map(([key, value]) => `${key}=${quoteAttr(value)}`)\n .join(', ');\n}\n\n/** DOT language keywords that must be quoted when used as identifiers. */\nfunction isDotKeyword(id: string): boolean {\n const lower = id.toLowerCase();\n return lower === 'graph' || lower === 'digraph' || lower === 'subgraph'\n || lower === 'node' || lower === 'edge' || lower === 'strict';\n}\n","/**\n * Convenience function for exporting a PetriNet to DOT format.\n *\n * @module export/dot-exporter\n */\n\nimport type { PetriNet } from '../core/petri-net.js';\nimport type { DotConfig } from './petri-net-mapper.js';\nimport { mapToGraph } from './petri-net-mapper.js';\nimport { renderDot } from './dot-renderer.js';\n\n/**\n * Exports a PetriNet to DOT (Graphviz) format.\n *\n * @param net the Petri net to export\n * @param config optional export configuration\n * @returns DOT string suitable for rendering with Graphviz\n */\nexport function dotExport(net: PetriNet, config?: DotConfig): string {\n return renderDot(mapToGraph(net, config));\n}\n"],"mappings":";;;;;;;AAoDA,IAAM,cAAgD;AAAA,EACpD,OAAiB,EAAE,OAAO,UAAW,MAAM,WAAW,QAAQ,WAAW,UAAU,KAAK,OAAO,KAAK;AAAA,EACpG,OAAiB,EAAE,OAAO,UAAW,MAAM,WAAW,QAAQ,WAAW,UAAU,GAAK,OAAO,KAAK;AAAA,EACpG,KA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