libpetri 2.13.0 → 3.0.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/README.md +47 -136
- package/dist/{chunk-7VJ5CYUU.js → chunk-5W6SVYPD.js} +67 -19
- package/dist/chunk-5W6SVYPD.js.map +1 -0
- package/dist/{chunk-JVI5HFRX.js → chunk-VCDOKWVU.js} +2 -2
- package/dist/{chunk-E3ZWB645.js → chunk-YVIPJ6KM.js} +1 -1
- package/dist/chunk-YVIPJ6KM.js.map +1 -0
- package/dist/debug/index.d.ts +2 -2
- package/dist/debug/index.js +2 -2
- package/dist/doclet/index.d.ts +1 -1
- package/dist/doclet/index.js +3 -3
- package/dist/dot-exporter-3STXYK74.js +9 -0
- package/dist/{event-store-DKTenPbC.d.ts → event-store-Df_sAVQ_.d.ts} +1 -1
- package/dist/export/index.d.ts +1 -1
- package/dist/export/index.js +2 -2
- package/dist/index.d.ts +91 -38
- package/dist/index.js +368 -294
- package/dist/index.js.map +1 -1
- package/dist/{petri-net-C3LSY-vm.d.ts → petri-net-UQBBkvLl.d.ts} +24 -29
- package/dist/verification/index.d.ts +6 -5
- package/dist/verification/index.js +1 -1
- package/package.json +1 -1
- package/dist/chunk-7VJ5CYUU.js.map +0 -1
- package/dist/chunk-E3ZWB645.js.map +0 -1
- package/dist/dot-exporter-SHBYMMJ3.js +0 -9
- /package/dist/{chunk-JVI5HFRX.js.map → chunk-VCDOKWVU.js.map} +0 -0
- /package/dist/{dot-exporter-SHBYMMJ3.js.map → dot-exporter-3STXYK74.js.map} +0 -0
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/core/out.ts","../src/core/transition-action.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/analysis/dbm.ts","../src/verification/analysis/state-class.ts","../src/core/internal/output-action-check.ts","../src/verification/analysis/state-class-graph.ts","../src/verification/z3/counterexample-decoder.ts","../src/verification/z3/name-coloured-encoder.ts","../src/verification/analysis/name-fragment.ts","../src/verification/analysis/name-marking.ts","../src/verification/analysis/name-state-class.ts","../src/verification/analysis/name-state-class-graph.ts","../src/verification/nu-scg-verifier.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 './place.js';\nimport type { TransitionContext } from './transition-context.js';\n\n/**\n * The action executed when a transition fires.\n * Receives a TransitionContext providing filtered I/O and structure access.\n */\nexport type TransitionAction = (ctx: TransitionContext) => Promise<void>;\n\n// ==================== Built-in Actions ====================\n\n/**\n * Identity action: produces no outputs.\n * For transitions that only consume tokens without producing any.\n *\n * Returns a stable singleton reference (CORE-051), so {@link isPassthrough}\n * can recognise it.\n */\nexport function passthrough(): TransitionAction {\n return PASSTHROUGH;\n}\n\n/** @internal Stable passthrough action — see {@link passthrough}. */\nconst PASSTHROUGH: TransitionAction = async () => {};\n\n/**\n * Whether `action` is the built-in {@link passthrough} — i.e. provably produces\n * no output tokens. Identity-based, so a hand-written no-op is not claimed.\n *\n * @param action the action to test; `null` / `undefined` is not passthrough\n */\nexport function isPassthrough(action: TransitionAction | null | undefined): boolean {\n return action === PASSTHROUGH;\n}\n\n/**\n * Transform action: applies function to context, copies result to ALL output places.\n *\n * @example\n * ```ts\n * const action = transform(ctx => ctx.input(inputPlace).toUpperCase());\n * // Result is copied to every declared output place\n * ```\n */\nexport function transform(fn: (ctx: TransitionContext) => unknown): TransitionAction {\n return async (ctx) => {\n const result = fn(ctx);\n for (const outputPlace of ctx.outputPlaces()) {\n ctx.output(outputPlace, result);\n }\n };\n}\n\n/**\n * Fork action: copies single input token to all outputs.\n * Requires exactly one input place (derived from structure).\n */\nexport function fork(): TransitionAction {\n return transform((ctx) => {\n const inputPlaces = ctx.inputPlaces();\n if (inputPlaces.size !== 1) {\n throw new Error(`Fork requires exactly 1 input place, found ${inputPlaces.size}`);\n }\n const inputPlace = inputPlaces.values().next().value as Place<any>;\n return ctx.input(inputPlace);\n });\n}\n\n/**\n * Transform with explicit input place.\n */\nexport function transformFrom<I>(inputPlace: Place<I>, fn: (value: I) => unknown): TransitionAction {\n return transform((ctx) => fn(ctx.input(inputPlace)));\n}\n\n/**\n * Async transform: applies async function, copies result to all outputs.\n */\nexport function transformAsync(fn: (ctx: TransitionContext) => Promise<unknown>): TransitionAction {\n return async (ctx) => {\n const result = await fn(ctx);\n for (const outputPlace of ctx.outputPlaces()) {\n ctx.output(outputPlace, result);\n }\n };\n}\n\n/** Produce action: produces a single token with the given value to the specified place. */\nexport function produce<T>(place: Place<T>, value: T): TransitionAction {\n return async (ctx) => {\n ctx.output(place, value);\n };\n}\n\n/**\n * Wraps an action with timeout handling.\n * If the action completes within the timeout, normal completion.\n * If the timeout expires, the timeoutValue is produced to the timeoutPlace.\n *\n * @example\n * ```ts\n * const action = withTimeout(\n * async (ctx) => { ctx.output(resultPlace, await fetchData()); },\n * 5000,\n * timeoutPlace,\n * 'timed-out',\n * );\n * ```\n */\nexport function withTimeout<T>(\n action: TransitionAction,\n timeoutMs: number,\n timeoutPlace: Place<T>,\n timeoutValue: T,\n): TransitionAction {\n return (ctx) => {\n return new Promise<void>((resolve, reject) => {\n let completed = false;\n const timer = setTimeout(() => {\n if (!completed) {\n completed = true;\n ctx.output(timeoutPlace, timeoutValue);\n resolve();\n }\n }, timeoutMs);\n action(ctx).then(\n () => {\n if (!completed) {\n completed = true;\n clearTimeout(timer);\n resolve();\n }\n },\n (err) => {\n if (!completed) {\n completed = true;\n clearTimeout(timer);\n reject(err);\n }\n },\n );\n });\n };\n}\n","import type { Place } from '../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 =\n | DeadlockFree\n | MutualExclusion\n | PlaceBound\n | Unreachable\n | BranchPlaceBound\n | JoinedOrDeadLettered;\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/**\n * Branch / budget place bound: a ν-net budget or fork-branch place never\n * exceeds `bound` tokens — the bounded-budget decidability lever (NU-040).\n *\n * Encodes identically to {@link PlaceBound} (a linear-integer count bound), but\n * names the ν-net intent: the live correlation pool is bounded, keeping the\n * well-structured transition system finite. The matched-transition\n * over-approximation is sound for this safety bound — a `proven` verdict holds\n * for the real net, which fires strictly fewer joins than the over-approximation.\n */\nexport interface BranchPlaceBound {\n readonly type: 'branch-place-bound';\n readonly place: Place<any>;\n readonly bound: number;\n}\n\n/**\n * Joined-or-dead-lettered: every forked name is eventually joined or\n * dead-lettered, so no reachable *quiescent* (deadlocked) marking still holds a\n * token in `pending` (NU-040). Violated when a reachable marking is both\n * quiescent and has `pending >= 1` — a stranded correlation group.\n */\nexport interface JoinedOrDeadLettered {\n readonly type: 'joined-or-dead-lettered';\n readonly pending: 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/** Branch / budget place bound (NU-040). See {@link BranchPlaceBound}. */\nexport function branchPlaceBound(place: Place<any>, bound: number): BranchPlaceBound {\n return { type: 'branch-place-bound', place, bound };\n}\n\n/** Joined-or-dead-lettered at quiescence (NU-040). See {@link JoinedOrDeadLettered}. */\nexport function joinedOrDeadLettered(pending: Place<any>): JoinedOrDeadLettered {\n return { type: 'joined-or-dead-lettered', pending };\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 case 'branch-place-bound':\n return `Branch place bound (ν-budget): ${prop.place.name} <= ${prop.bound}`;\n case 'joined-or-dead-lettered':\n return `Joined-or-dead-lettered: ${prop.pending.name} = 0 at quiescence`;\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 * A P-semiflow generator row during Colom–Silva elimination: the running\n * transition signature `y·C` plus the non-negative place weight `y` that produced\n * it. A row survives an elimination step only when the current column of `y·C` is\n * zero, so after every transition is eliminated the surviving rows have `y·C = 0`.\n */\ninterface SemiflowRow {\n readonly sig: number[];\n readonly weight: number[];\n}\n\n/**\n * Computes minimal **P-semiflows** — non-negative place weightings `y` with\n * `y·C = 0` — via the Colom–Silva / Farkas method. Unlike {@link computePInvariants}\n * (a signed null-space basis), every returned `PInvariant.weights` is non-negative:\n * a genuine P-semiflow, with `constant = y·M0`. A non-negative conservation law\n * soundly **bounds** the token sum over its support: `Σ_{support} M(p) ≤ y·M0`. Used\n * to bound the number of simultaneously-live colours in the name-coloured encoder\n * (see `colourSlotBound`).\n *\n * Mirrors the Rust reference `compute_p_semiflows`.\n */\nexport function computePSemiflows(\n matrix: IncidenceMatrix,\n flatNet: FlatNet,\n initialMarking: MarkingState,\n): PInvariant[] {\n const np = matrix.numPlaces();\n const nt = matrix.numTransitions();\n if (np === 0) return [];\n\n const incidence = matrix.incidence(); // [t][p]\n\n // One generator row per place: signature = the place's column of C (over\n // transitions), weight = e_p. Eliminate one transition column at a time using only\n // non-negative combinations, so accumulated weights stay non-negative.\n let rows: SemiflowRow[] = [];\n for (let p = 0; p < np; p++) {\n const sig = new Array<number>(nt);\n for (let t = 0; t < nt; t++) sig[t] = incidence[t]![p]!;\n const weight = new Array<number>(np).fill(0);\n weight[p] = 1;\n rows.push({ sig, weight });\n }\n\n for (let t = 0; t < nt; t++) {\n const next: SemiflowRow[] = rows.filter((r) => r.sig[t] === 0);\n const pos = rows.filter((r) => r.sig[t]! > 0);\n const neg = rows.filter((r) => r.sig[t]! < 0);\n for (const rp of pos) {\n for (const rn of neg) {\n const cp = -rn.sig[t]!; // > 0\n const cn = rp.sig[t]!; // > 0\n // Checked combination: `number` is f64 and loses integer precision above 2^53,\n // so DROP this generator if any coefficient leaves the safe-integer range rather\n // than keep an imprecise (invalid) row. colourSlotBound then falls back to the\n // sound over-approximation — never an under-approximation.\n const sig = combineRow(cp, rp.sig, cn, rn.sig);\n const weight = combineRow(cp, rp.weight, cn, rn.weight);\n if (sig === null || weight === null) continue;\n reduceGcd(sig, weight);\n next.push({ sig, weight });\n }\n }\n rows = keepSupportMinimal(next);\n if (rows.length > 8192) rows.length = 8192; // safety backstop against blow-up\n }\n\n const semiflows: PInvariant[] = [];\n for (const { weight } of rows) {\n if (!weight.some((x) => x !== 0)) continue;\n const support = new Set<number>();\n let constant = 0;\n for (let p = 0; p < np; p++) {\n if (weight[p] !== 0) {\n support.add(p);\n constant += weight[p]! * initialMarking.tokens(flatNet.places[p]!);\n }\n }\n // Drop a semiflow whose `Σ weight·M0` left the safe-integer range — fewer covering\n // semiflows just means colourSlotBound falls back soundly.\n if (!Number.isSafeInteger(constant)) continue;\n semiflows.push(pInvariant(weight, constant, support));\n }\n return semiflows;\n}\n\n/**\n * Divides a generator row's signature and weight by the GCD of all their absolute\n * values (keeps the P-semiflow minimal and the integers small). Mutates in place.\n */\n/**\n * `cp*a + cn*b` componentwise, or null if any result leaves the safe-integer range\n * (`number` is f64 and loses integer precision above 2^53) — the caller then drops the\n * generator and the colour bound falls back soundly rather than using imprecise values.\n */\nfunction combineRow(\n cp: number,\n a: readonly number[],\n cn: number,\n b: readonly number[],\n): number[] | null {\n const out = new Array<number>(a.length);\n for (let i = 0; i < a.length; i++) {\n const v = cp * a[i]! + cn * b[i]!;\n if (!Number.isSafeInteger(v)) return null;\n out[i] = v;\n }\n return out;\n}\n\nfunction reduceGcd(sig: number[], weight: number[]): void {\n let g = 0;\n for (const v of sig) g = gcd(g, Math.abs(v));\n for (const v of weight) g = gcd(g, Math.abs(v));\n if (g > 1) {\n for (let i = 0; i < sig.length; i++) sig[i] = sig[i]! / g;\n for (let i = 0; i < weight.length; i++) weight[i] = weight[i]! / g;\n }\n}\n\n/**\n * Drops any row whose weight-support is a strict superset of another's — a\n * non-minimal combination only inflates the set (and can cause combinatorial\n * blow-up). Mirrors the Rust reference `keep_support_minimal`.\n */\nfunction keepSupportMinimal(rows: SemiflowRow[]): SemiflowRow[] {\n const supports: number[][] = rows.map((r) => {\n const s: number[] = [];\n for (let i = 0; i < r.weight.length; i++) if (r.weight[i] !== 0) s.push(i);\n return s;\n });\n const keep = new Array<boolean>(rows.length).fill(true);\n for (let i = 0; i < rows.length; i++) {\n if (!keep[i]) continue;\n for (let j = 0; j < rows.length; j++) {\n if (i === j || !keep[j]) continue;\n if (supports[j]!.length < supports[i]!.length && supports[j]!.every((p) => supports[i]!.includes(p))) {\n keep[i] = false;\n break;\n }\n }\n }\n return rows.filter((_, i) => keep[i]);\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 'branch-place-bound': {\n // ν-net budget lever (NU-040): a count bound, encoded identically to\n // place-bound. Sound under the matched-transition over-approximation —\n // the real net fires fewer joins, so it cannot exceed a bound the\n // over-approximation respects.\n const idx = flatNetIndexOf(flatNet, property.place);\n if (idx < 0) throw new Error(`BranchPlaceBound references unknown place: ${property.place.name}`);\n return mVars[idx]!.gt(property.bound);\n }\n\n case 'joined-or-dead-lettered': {\n // NU-040: a quiescent (deadlocked) marking that still holds a `pending`\n // token is a stranded correlation group. Reuse the deadlock predicate and\n // conjoin pending non-emptiness.\n const idx = flatNetIndexOf(flatNet, property.pending);\n if (idx < 0) return ctx.Bool.val(false); // unknown pending place: no violation\n const deadlock = encodeDeadlock(ctx, flatNet, mVars, P);\n return ctx.And(deadlock, mVars[idx]!.ge(1));\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","const EPSILON = 1e-9;\n\n/**\n * Difference Bound Matrix (DBM) for Time Petri Net state class analysis.\n *\n * Implements the Berthomieu-Diaz (1991) algorithm for computing firing domains\n * and their successors. Matrix bounds[i][j] = upper bound on (xi - xj).\n * Index 0 is the reference clock; index i+1 is the clock for transition i.\n */\nexport class DBM {\n private readonly bounds: Float64Array;\n private readonly dim: number;\n readonly clockNames: readonly string[];\n private readonly _empty: boolean;\n\n private constructor(bounds: Float64Array, dim: number, clockNames: readonly string[], empty: boolean) {\n this.bounds = bounds;\n this.dim = dim;\n this.clockNames = clockNames;\n this._empty = empty;\n }\n\n /** Creates an initial firing domain for enabled transitions. */\n static create(clockNames: readonly string[], lowerBounds: number[], upperBounds: number[]): DBM {\n const n = clockNames.length;\n const dim = n + 1;\n const bounds = makeMatrix(dim, Infinity);\n\n for (let i = 0; i < n; i++) {\n bounds[(0) * dim + (i + 1)] = -lowerBounds[i]!;\n bounds[(i + 1) * dim + (0)] = upperBounds[i]!;\n }\n\n return new DBM(bounds, dim, clockNames, false).canonicalize();\n }\n\n /** Creates an empty (unsatisfiable) zone. */\n static empty(clockNames: readonly string[]): DBM {\n const b = new Float64Array(1);\n b[0] = 0;\n return new DBM(b, 1, clockNames, true);\n }\n\n isEmpty(): boolean {\n return this._empty;\n }\n\n clockCount(): number {\n return this.clockNames.length;\n }\n\n private get(i: number, j: number): number {\n return this.bounds[i * this.dim + j]!;\n }\n\n /** Gets the lower bound (earliest firing time) for clock i. */\n getLowerBound(clockIndex: number): number {\n if (this._empty || clockIndex < 0 || clockIndex >= this.clockNames.length) return 0;\n const val = -this.get(0, clockIndex + 1);\n return val === 0 ? 0 : val; // normalize -0 to 0\n }\n\n /** Gets the upper bound (latest firing time / deadline) for clock i. */\n getUpperBound(clockIndex: number): number {\n if (this._empty || clockIndex < 0 || clockIndex >= this.clockNames.length) return Infinity;\n return this.get(clockIndex + 1, 0);\n }\n\n /** Checks if transition can fire (lower bound <= 0 after time passage). */\n canFire(clockIndex: number): boolean {\n return !this._empty && this.getLowerBound(clockIndex) <= EPSILON;\n }\n\n /**\n * Computes the successor firing domain after firing transition t_f.\n * Implements the 5-step Berthomieu-Diaz successor formula.\n */\n fireTransition(\n firedClock: number,\n newClockNames: readonly string[],\n newLowerBounds: number[],\n newUpperBounds: number[],\n persistentClocks: number[],\n ): DBM {\n if (this._empty) return this;\n\n const n = this.clockNames.length;\n if (firedClock < 0 || firedClock >= n) {\n throw new Error(`Invalid fired clock index: ${firedClock}`);\n }\n\n // Step 1: Intersect with \"t_f fires first\" constraint\n const constrained = new Float64Array(this.bounds);\n const dim = this.dim;\n const f = firedClock + 1;\n\n for (let i = 0; i < n; i++) {\n if (i !== firedClock) {\n const idx = i + 1;\n const pos = f * dim + idx;\n constrained[pos] = Math.min(constrained[pos]!, 0);\n }\n }\n\n // Step 2: Canonicalize\n if (!canonicalizeInPlace(constrained, dim)) {\n return DBM.empty([]);\n }\n\n // Steps 3 & 4: Substitution and Elimination\n const newN = persistentClocks.length + newClockNames.length;\n const newDim = newN + 1;\n const newBounds = makeMatrix(newDim, Infinity);\n\n // Copy persistent clocks with transformed bounds\n for (let pi = 0; pi < persistentClocks.length; pi++) {\n const oldIdx = persistentClocks[pi]! + 1;\n const newIdx = pi + 1;\n\n const upper = constrained[oldIdx * dim + f]!;\n const lower = Math.max(0, -constrained[f * dim + oldIdx]!);\n\n newBounds[0 * newDim + newIdx] = -lower;\n newBounds[newIdx * newDim + 0] = upper;\n\n // Inter-clock constraints between persistent transitions (preserved)\n for (let pj = 0; pj < persistentClocks.length; pj++) {\n const oldJ = persistentClocks[pj]! + 1;\n const newJ = pj + 1;\n newBounds[newIdx * newDim + newJ] = constrained[oldIdx * dim + oldJ]!;\n }\n }\n\n // Step 5: Add fresh intervals for newly enabled transitions\n const offset = persistentClocks.length;\n for (let k = 0; k < newClockNames.length; k++) {\n const idx = offset + k + 1;\n newBounds[0 * newDim + idx] = -newLowerBounds[k]!;\n newBounds[idx * newDim + 0] = newUpperBounds[k]!;\n }\n\n // Build new clock names\n const allNames: string[] = [];\n for (const idx of persistentClocks) {\n allNames.push(this.clockNames[idx]!);\n }\n allNames.push(...newClockNames);\n\n // Step 6: Final canonicalization\n return new DBM(newBounds, newDim, allNames, false).canonicalize();\n }\n\n /** Lets time pass: set all lower bounds to 0. */\n letTimePass(): DBM {\n if (this._empty) return this;\n\n const newBounds = new Float64Array(this.bounds);\n for (let i = 1; i < this.dim; i++) {\n newBounds[0 * this.dim + i] = 0;\n }\n\n return new DBM(newBounds, this.dim, this.clockNames, false).canonicalize();\n }\n\n private canonicalize(): DBM {\n if (this._empty) return this;\n\n const canon = new Float64Array(this.bounds);\n if (!canonicalizeInPlace(canon, this.dim)) {\n return DBM.empty(this.clockNames);\n }\n return new DBM(canon, this.dim, this.clockNames, false);\n }\n\n equals(other: DBM): boolean {\n if (this === other) return true;\n if (this._empty && other._empty) return true;\n if (this._empty || other._empty) return false;\n if (this.clockNames.length !== other.clockNames.length) return false;\n for (let i = 0; i < this.clockNames.length; i++) {\n if (this.clockNames[i] !== other.clockNames[i]) return false;\n }\n if (this.bounds.length !== other.bounds.length) return false;\n for (let i = 0; i < this.bounds.length; i++) {\n if (Math.abs(this.bounds[i]! - other.bounds[i]!) > EPSILON) return false;\n }\n return true;\n }\n\n toString(): string {\n if (this._empty) return 'DBM[empty]';\n const parts: string[] = [];\n for (let i = 0; i < this.clockNames.length; i++) {\n const lo = formatBound(this.getLowerBound(i));\n const hi = formatBound(this.getUpperBound(i));\n parts.push(`${this.clockNames[i]}:[${lo},${hi}]`);\n }\n return `DBM{${parts.join(', ')}}`;\n }\n}\n\nfunction makeMatrix(dim: number, fill: number): Float64Array {\n const m = new Float64Array(dim * dim).fill(fill);\n for (let i = 0; i < dim; i++) {\n m[i * dim + i] = 0;\n }\n return m;\n}\n\nfunction canonicalizeInPlace(dbm: Float64Array, dim: number): boolean {\n for (let k = 0; k < dim; k++) {\n for (let i = 0; i < dim; i++) {\n for (let j = 0; j < dim; j++) {\n const ik = dbm[i * dim + k]!;\n const kj = dbm[k * dim + j]!;\n if (ik < Infinity && kj < Infinity) {\n const via = ik + kj;\n if (via < dbm[i * dim + j]!) {\n dbm[i * dim + j] = via;\n }\n }\n }\n }\n }\n for (let i = 0; i < dim; i++) {\n if (dbm[i * dim + i]! < -EPSILON) return false;\n }\n return true;\n}\n\nfunction formatBound(b: number): string {\n if (b >= Infinity / 2) return '\\u221e';\n if (b === Math.trunc(b)) return String(b);\n return b.toFixed(3);\n}\n","import type { Transition } from '../../core/transition.js';\nimport type { MarkingState } from '../marking-state.js';\nimport type { DBM } from './dbm.js';\n\n/**\n * A State Class in Time Petri Net analysis.\n *\n * A state class is a pair (M, D) where M is a marking and D is a firing domain (DBM).\n * State classes provide a finite abstraction of the infinite state space of Time Petri Nets.\n */\nexport class StateClass {\n readonly marking: MarkingState;\n readonly firingDomain: DBM;\n readonly enabledTransitions: readonly Transition[];\n /**\n * Class-relative earliest-ready time (seconds) of each enabled transition,\n * parallel to `enabledTransitions`. Captured from the firing-domain DBM\n * (`getLowerBound(k)`) *before* `letTimePass()` zeroes the lower bounds, i.e.\n * the minimum time from class entry at which clock `k` may fire.\n *\n * Purely additive: base timed-reachability (marking + DBM zone, `equals`,\n * `classKey`) ignores it. Read only by the ν conflict-priority prune (NU-052,\n * `priorityDominated`), where comparing `readyEarliest[H] <= readyEarliest[L]`\n * decides whether the strictly higher-priority `H` becomes ready no later than\n * `L` and so pre-empts it.\n */\n readonly readyEarliest: readonly number[];\n\n constructor(\n marking: MarkingState,\n firingDomain: DBM,\n enabledTransitions: readonly Transition[],\n readyEarliest: readonly number[],\n ) {\n this.marking = marking;\n this.firingDomain = firingDomain;\n this.enabledTransitions = [...enabledTransitions];\n this.readyEarliest = [...readyEarliest];\n }\n\n isEmpty(): boolean {\n return this.firingDomain.isEmpty();\n }\n\n canFire(transition: Transition): boolean {\n const idx = this.enabledTransitions.indexOf(transition);\n if (idx < 0) return false;\n return this.firingDomain.getUpperBound(idx) >= 0;\n }\n\n transitionIndex(transition: Transition): number {\n return this.enabledTransitions.indexOf(transition);\n }\n\n equals(other: StateClass): boolean {\n if (this === other) return true;\n return this.marking.toString() === other.marking.toString()\n && this.firingDomain.equals(other.firingDomain);\n }\n\n toString(): string {\n return `StateClass{${this.marking}, ${this.firingDomain}}`;\n }\n}\n","import type { PetriNet } from '../petri-net.js';\nimport { isPassthrough } from '../transition-action.js';\n\n/**\n * CORE-043: a transition that declares an output spec must not carry the built-in\n * `passthrough()`. It produces no tokens, so output validation (IO-015) rejects every\n * firing and the declared output never arrives. Enforced when a net is compiled for\n * execution and when one is handed to verification, so verification cannot green-light a net that will not compile.\n */\nexport function requireOutputProducingActions(net: PetriNet): void {\n for (const t of net.transitions) {\n if (t.outputSpec !== null && isPassthrough(t.action)) {\n throw new Error(\n `Transition '${t.name}' declares an output spec but carries passthrough(), which ` +\n `produces no tokens. Every firing would fail output validation (IO-015) and ` +\n `the declared output would never arrive. Bind an action that produces it — ` +\n `fork() moves the input token across — or drop the output spec if the ` +\n `transition is meant to be a sink.`,\n );\n }\n }\n}\n","import type { Place } from '../../core/place.js';\nimport type { EnvironmentPlace } from '../../core/place.js';\nimport type { In } from '../../core/in.js';\nimport type { Transition } from '../../core/transition.js';\nimport type { PetriNet } from '../../core/petri-net.js';\nimport { earliest, latest } from '../../core/timing.js';\nimport { enumerateBranches } from '../../core/out.js';\nimport { MarkingState } from '../marking-state.js';\nimport { DBM } from './dbm.js';\nimport { StateClass } from './state-class.js';\nimport type { EnvironmentAnalysisMode } from './environment-analysis-mode.js';\nimport { ignore } from './environment-analysis-mode.js';\nimport { requireOutputProducingActions } from '../../core/internal/output-action-check.js';\n\n/** Edge that tracks which XOR branch was taken. */\nexport interface BranchEdge {\n readonly branchIndex: number;\n readonly target: StateClass;\n}\n\nexport interface VirtualTransition {\n readonly transition: Transition;\n readonly branchIndex: number;\n readonly outputPlaces: ReadonlySet<Place<any>>;\n}\n\n/**\n * State Class Graph for Time Petri Net analysis.\n *\n * Implements the Berthomieu-Diaz (1991) algorithm for computing the state class\n * graph of a bounded Time Petri Net.\n */\nexport class StateClassGraph {\n readonly net: PetriNet;\n readonly initialClass: StateClass;\n private readonly _stateClasses: StateClass[];\n private readonly _transitions: Map<StateClass, Map<Transition, BranchEdge[]>>;\n private readonly _successors: Map<StateClass, Set<StateClass>>;\n private readonly _predecessors: Map<StateClass, Set<StateClass>>;\n private readonly _complete: boolean;\n\n private constructor(\n net: PetriNet,\n initialClass: StateClass,\n stateClasses: StateClass[],\n transitions: Map<StateClass, Map<Transition, BranchEdge[]>>,\n complete: boolean,\n ) {\n this.net = net;\n this.initialClass = initialClass;\n this._stateClasses = stateClasses;\n this._transitions = transitions;\n this._complete = complete;\n\n // Build successor/predecessor maps\n this._successors = new Map();\n this._predecessors = new Map();\n for (const sc of stateClasses) {\n this._successors.set(sc, new Set());\n this._predecessors.set(sc, new Set());\n }\n for (const [from, tMap] of transitions) {\n for (const edges of tMap.values()) {\n for (const edge of edges) {\n this._successors.get(from)!.add(edge.target);\n this._predecessors.get(edge.target)!.add(from);\n }\n }\n }\n }\n\n /**\n * Builds the state class graph for a Time Petri Net.\n *\n * @throws Error if the net violates CORE-043 — analysis rejects the same nets execution rejects.\n */\n static build(\n net: PetriNet,\n initialMarking: MarkingState,\n maxClasses: number,\n environmentPlaces?: Set<EnvironmentPlace<any>>,\n environmentMode?: EnvironmentAnalysisMode,\n ): StateClassGraph {\n requireOutputProducingActions(net);\n\n const envMode = environmentMode ?? ignore();\n const envPlaces = new Set<Place<any>>();\n if (environmentPlaces) {\n for (const ep of environmentPlaces) {\n envPlaces.add(ep.place);\n }\n }\n\n const initialClass = initialStateClass(net, initialMarking, envPlaces, envMode);\n\n // BFS exploration\n const stateClasses: StateClass[] = [initialClass];\n const stateClassSet = new Set<string>([classKey(initialClass)]);\n const classMap = new Map<string, StateClass>([[classKey(initialClass), initialClass]]);\n const transitionMap = new Map<StateClass, Map<Transition, BranchEdge[]>>();\n transitionMap.set(initialClass, new Map());\n const queue: StateClass[] = [initialClass];\n let complete = true;\n\n while (queue.length > 0) {\n if (stateClasses.length >= maxClasses) {\n complete = false;\n break;\n }\n\n const current = queue.shift()!;\n\n for (const transition of current.enabledTransitions) {\n const virtualTransitions = expandTransition(transition);\n\n for (const vt of virtualTransitions) {\n const successor = computeSuccessor(net, current, vt, envPlaces, envMode);\n if (successor === null || successor.isEmpty()) continue;\n\n // Add edge with branch index\n const tEdges = transitionMap.get(current)!;\n if (!tEdges.has(transition)) tEdges.set(transition, []);\n tEdges.get(transition)!.push({ branchIndex: vt.branchIndex, target: successor });\n\n // Dedup state classes by key\n const key = classKey(successor);\n if (!stateClassSet.has(key)) {\n stateClassSet.add(key);\n classMap.set(key, successor);\n stateClasses.push(successor);\n transitionMap.set(successor, new Map());\n queue.push(successor);\n } else {\n // Rewrite edge target to existing canonical instance\n const canonical = classMap.get(key)!;\n if (canonical !== successor) {\n const edges = tEdges.get(transition)!;\n edges[edges.length - 1] = { branchIndex: vt.branchIndex, target: canonical };\n }\n }\n }\n }\n }\n\n return new StateClassGraph(net, initialClass, stateClasses, transitionMap, complete);\n }\n\n stateClasses(): readonly StateClass[] {\n return this._stateClasses;\n }\n\n size(): number {\n return this._stateClasses.length;\n }\n\n isComplete(): boolean {\n return this._complete;\n }\n\n successors(sc: StateClass): Set<StateClass> {\n return this._successors.get(sc) ?? new Set();\n }\n\n predecessors(sc: StateClass): Set<StateClass> {\n return this._predecessors.get(sc) ?? new Set();\n }\n\n /** Returns all outgoing transitions with their branch edges. */\n outgoingBranchEdges(sc: StateClass): Map<Transition, BranchEdge[]> {\n return this._transitions.get(sc) ?? new Map();\n }\n\n /** Returns the branch edges for a specific transition from a state class. */\n branchEdges(sc: StateClass, transition: Transition): BranchEdge[] {\n const map = this._transitions.get(sc);\n if (!map) return [];\n return map.get(transition) ?? [];\n }\n\n /** Returns all transitions that are enabled from a state class. */\n enabledTransitions(sc: StateClass): Set<Transition> {\n const map = this._transitions.get(sc);\n if (!map) return new Set();\n return new Set(map.keys());\n }\n\n /** Finds all state classes with a given marking. */\n classesWithMarking(marking: MarkingState): StateClass[] {\n const key = marking.toString();\n return this._stateClasses.filter(sc => sc.marking.toString() === key);\n }\n\n /** Checks if a marking is reachable. */\n isReachable(marking: MarkingState): boolean {\n const key = marking.toString();\n return this._stateClasses.some(sc => sc.marking.toString() === key);\n }\n\n /** Gets all reachable markings. */\n reachableMarkings(): Set<string> {\n const markings = new Set<string>();\n for (const sc of this._stateClasses) {\n markings.add(sc.marking.toString());\n }\n return markings;\n }\n\n /** Counts edges in the graph (each branch edge counts separately). */\n edgeCount(): number {\n let count = 0;\n for (const map of this._transitions.values()) {\n for (const edges of map.values()) {\n count += edges.length;\n }\n }\n return count;\n }\n\n toString(): string {\n return `StateClassGraph[classes=${this.size()}, edges=${this.edgeCount()}, complete=${this._complete}]`;\n }\n}\n\nfunction classKey(sc: StateClass): string {\n return `${sc.marking.toString()}|${sc.firingDomain.toString()}`;\n}\n\n/**\n * Builds the initial state class (enabled set + firing-domain DBM after letting\n * time pass). Shared by the plain SCG and the name-aware ν-partition SCG\n * (NU-050, Route B).\n */\nexport function initialStateClass(\n net: PetriNet,\n initialMarking: MarkingState,\n envPlaces: Set<Place<any>>,\n envMode: EnvironmentAnalysisMode,\n): StateClass {\n const enabledTransitions = findEnabledTransitions(net, initialMarking, envPlaces, envMode);\n const clockNames = enabledTransitions.map(t => t.name);\n const lowerBounds = enabledTransitions.map(t => earliest(t.timing) / 1000);\n const upperBounds = enabledTransitions.map(t => latest(t.timing) / 1000);\n const baseDBM = DBM.create(clockNames, lowerBounds, upperBounds);\n // Class-relative earliest-ready time of each enabled clock, captured BEFORE\n // letTimePass() zeroes the DBM lower bounds (NU-052 residual-earliest).\n const readyEarliest = enabledTransitions.map((_, k) => baseDBM.getLowerBound(k));\n const initialDBM = baseDBM.letTimePass();\n return new StateClass(initialMarking, initialDBM, enabledTransitions, readyEarliest);\n}\n\nexport function expandTransition(t: Transition): VirtualTransition[] {\n let branches: ReadonlyArray<ReadonlySet<Place<any>>>;\n\n if (t.outputSpec !== null) {\n branches = enumerateBranches(t.outputSpec);\n } else {\n branches = [new Set()];\n }\n\n return branches.map((outputPlaces, i) => ({\n transition: t,\n branchIndex: i,\n outputPlaces: outputPlaces as ReadonlySet<Place<any>>,\n }));\n}\n\nexport function computeSuccessor(\n net: PetriNet,\n current: StateClass,\n fired: VirtualTransition,\n environmentPlaces: Set<Place<any>>,\n environmentMode: EnvironmentAnalysisMode,\n): StateClass | null {\n const transition = fired.transition;\n\n // 1. Compute new marking\n const newMarking = fireTransition(current.marking, transition, fired.outputPlaces, environmentPlaces, environmentMode);\n\n // 2. Determine persistent and newly enabled transitions\n const newEnabledAll = findEnabledTransitions(net, newMarking, environmentPlaces, environmentMode);\n\n const persistent: Transition[] = [];\n const persistentIndices: number[] = [];\n for (let i = 0; i < current.enabledTransitions.length; i++) {\n const t = current.enabledTransitions[i]!;\n if (t !== transition && newEnabledAll.includes(t)) {\n persistent.push(t);\n persistentIndices.push(i);\n }\n }\n\n const newlyEnabled: Transition[] = [];\n for (const t of newEnabledAll) {\n if (!persistent.includes(t)) {\n newlyEnabled.push(t);\n }\n }\n\n // 3. Compute successor DBM\n const firedIdx = current.transitionIndex(transition);\n const newClockNames = newlyEnabled.map(t => t.name);\n const newLowerBounds = newlyEnabled.map(t => earliest(t.timing) / 1000);\n const newUpperBounds = newlyEnabled.map(t => latest(t.timing) / 1000);\n\n const firedDBM = current.firingDomain.fireTransition(\n firedIdx,\n newClockNames,\n newLowerBounds,\n newUpperBounds,\n persistentIndices,\n );\n\n // allEnabled order matches firedDBM's clock order (persistent-then-newly-enabled).\n // Capture the class-relative earliest-ready time of each clock BEFORE\n // letTimePass() zeroes the DBM lower bounds (NU-052 residual-earliest).\n const allEnabled = [...persistent, ...newlyEnabled];\n const readyEarliest = allEnabled.map((_, k) => firedDBM.getLowerBound(k));\n\n const newDBM = firedDBM.letTimePass();\n\n return new StateClass(newMarking, newDBM, allEnabled, readyEarliest);\n}\n\nfunction findEnabledTransitions(\n net: PetriNet,\n marking: MarkingState,\n environmentPlaces: Set<Place<any>>,\n environmentMode: EnvironmentAnalysisMode,\n): Transition[] {\n const enabled: Transition[] = [];\n for (const transition of net.transitions) {\n if (isEnabled(transition, marking, environmentPlaces, environmentMode)) {\n enabled.push(transition);\n }\n }\n return enabled;\n}\n\nfunction isEnabled(\n transition: Transition,\n marking: MarkingState,\n environmentPlaces: Set<Place<any>>,\n environmentMode: EnvironmentAnalysisMode,\n): boolean {\n for (const spec of transition.inputSpecs) {\n const required = inputRequiredCount(spec);\n if (!checkPlaceEnabled(spec.place, required, marking, environmentPlaces, environmentMode)) {\n return false;\n }\n }\n\n for (const arc of transition.reads) {\n if (!checkPlaceEnabled(arc.place, 1, marking, environmentPlaces, environmentMode)) {\n return false;\n }\n }\n\n for (const arc of transition.inhibitors) {\n if (marking.hasTokens(arc.place)) {\n return false;\n }\n }\n\n return true;\n}\n\nfunction inputRequiredCount(spec: In): number {\n switch (spec.type) {\n case 'one': return 1;\n case 'exactly': return spec.count;\n case 'all': return 1;\n case 'at-least': return spec.minimum;\n }\n}\n\nfunction inputConsumeCount(spec: In): number {\n switch (spec.type) {\n case 'one': return 1;\n case 'exactly': return spec.count;\n case 'all': return 1; // Analysis: consume minimum (1 token)\n case 'at-least': return spec.minimum;\n }\n}\n\nfunction checkPlaceEnabled(\n place: Place<any>,\n required: number,\n marking: MarkingState,\n environmentPlaces: Set<Place<any>>,\n environmentMode: EnvironmentAnalysisMode,\n): boolean {\n if (!environmentPlaces.has(place)) {\n return marking.tokens(place) >= required;\n }\n\n switch (environmentMode.type) {\n case 'always-available': return true;\n case 'bounded': return required <= environmentMode.maxTokens;\n case 'ignore': return marking.tokens(place) >= required;\n }\n}\n\nfunction fireTransition(\n marking: MarkingState,\n transition: Transition,\n outputPlaces: ReadonlySet<Place<any>>,\n environmentPlaces: Set<Place<any>>,\n environmentMode: EnvironmentAnalysisMode,\n): MarkingState {\n const builder = MarkingState.builder().copyFrom(marking);\n\n // Consume from inputs\n for (const spec of transition.inputSpecs) {\n const toConsume = inputConsumeCount(spec);\n consumeFromPlace(builder, spec.place, toConsume, environmentPlaces, environmentMode);\n }\n\n // Reset places\n for (const arc of transition.resets) {\n const current = marking.tokens(arc.place);\n if (current > 0) {\n builder.removeTokens(arc.place, current);\n }\n }\n\n // Produce to outputs\n for (const place of outputPlaces) {\n builder.addTokens(place, 1);\n }\n\n return builder.build();\n}\n\nfunction consumeFromPlace(\n builder: ReturnType<typeof MarkingState.builder>,\n place: Place<any>,\n count: number,\n environmentPlaces: Set<Place<any>>,\n environmentMode: EnvironmentAnalysisMode,\n): void {\n if (!environmentPlaces.has(place)) {\n builder.removeTokens(place, count);\n return;\n }\n if (environmentMode.type === 'ignore') {\n builder.removeTokens(place, count);\n }\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","/**\n * @module name-coloured-encoder\n *\n * Bounded **name-coloured** CHC encoding for ν-net join correlation\n * ([NU-050] #1, Route A — the EUF-style carve-out).\n *\n * The flat {@link module:smt-encoder} is a pure *counting* abstraction: a place\n * is one integer, and a matched (ν-join) transition is encoded name-blind — it\n * fires whenever the input *counts* allow, regardless of whether the consumed\n * tokens actually share a correlation name. That over-approximation is sound for\n * `proven` on reachability-safety bounds but can report a **spurious** `violated`\n * whose counterexample silently equates two *distinct* names.\n *\n * This encoder removes that imprecision for the bounded fragment. The\n * decidability lever ([NU-040]) is a bounded live-name count: a budget place gates\n * minting, and a non-negative **P-semiflow** weighting every coloured place bounds\n * the simultaneously-live names to a finite `k` (`Σ_{coloured} M ≤ y·M0`; see\n * {@link buildColouredPlan} / `colourSlotBound`). So names are modelled as a\n * **finite set of `k` colours**. Each coloured\n * place becomes `k` per-colour integer counts; a mint introduces a *globally\n * fresh* colour (one currently empty everywhere); a matched join consumes the\n * **same colour** from every correlated input. Within the budget bound the\n * encoding is *exact* — sound and complete — so no different-name counterexample\n * survives.\n *\n * **Supported fragment**: {@link buildColouredPlan} returns `null` (and the\n * verifier falls back to the sound over-approximation) unless the net is in the\n * budget-bounded coloured fragment:\n * - coloured places = the correlated inputs of every matched transition, plus (in\n * EXTENDED mode, [NU-051]) the declared carrier places;\n * - each coloured place is *produced only by* minting forks (count 1, no coloured\n * input, costs ≥1 budget token) or EXTENDED relays, and *consumed only by*\n * matched joins or EXTENDED coloured consumers — a relay threads one colour on, a\n * drain drops it, each consuming exactly one coloured input at count 1;\n * - the coloured place set is structurally token-bounded: some non-negative\n * P-semiflow weights every coloured place, so the simultaneously-live colour count\n * is bounded by that semiflow's initial value `k` (`Σ_{coloured} M ≤ y·M0`). A net\n * with no covering non-negative semiflow (an unbounded colour leak) falls back;\n * - coloured places start empty; no inhibitor/read/reset/consume-all arc touches a\n * coloured place.\n *\n * XOR output branches are supported ([NU-053], Part 3): each branch is a separate\n * flat row classified by its own incidence, with `matchSpec` read from its source.\n *\n * **Properties**: reachability-safety properties compare aggregate coloured place\n * counts. Quiescence properties (`deadlock-free`, `joined-or-dead-lettered`) use a\n * colour-aware deadlock predicate ([NU-053], Part 2): every transition is disabled\n * for every colour (a mint has no globally-fresh colour, a join no shared colour, a\n * consumer no resident colour) and the marking is not a sink state — mirroring the\n * flat {@link module:smt-encoder} deadlock with the same env-injection relaxation.\n *\n * Mirrors the Rust reference `name_coloured_encoder.rs` exactly; the difference\n * is that this builds z3-solver expressions rather than emitting SMT-LIB2 text.\n * Z3 types are partially untyped; the ctx/fp parameters use `any`.\n */\nimport type { Arith, Bool, FuncDecl } from 'z3-solver';\nimport type { PetriNet } from '../../core/petri-net.js';\nimport type { Place } from '../../core/place.js';\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 { FragmentMode } from '../analysis/name-fragment.js';\nimport type { EncodingResult } from './smt-encoder.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/** How a transition relates to the coloured (correlation-carrying) places. */\ntype Klass =\n | { readonly kind: 'mint'; readonly colouredOut: readonly number[] }\n | { readonly kind: 'join'; readonly colouredIn: readonly number[] }\n /**\n * EXTENDED coloured consumer ([NU-051]): a non-match transition that consumes\n * one same-coloured token from `inputCol` (count 1) and threads it into each\n * `colouredOut` (relay) or into none (drain — `colouredOut` empty).\n */\n | { readonly kind: 'consume'; readonly inputCol: number; readonly colouredOut: readonly number[] }\n | { readonly kind: 'untouched' };\n\n/** A validated plan for the name-coloured encoding of a budget-bounded ν-net. */\nexport interface ColouredPlan {\n /** Flat indices of the coloured places (ascending). */\n readonly coloured: readonly number[];\n /** Per flat place: whether it is coloured. */\n readonly isColoured: readonly boolean[];\n /** Colour bound — the number of simultaneously-live names (the P-semiflow slot bound). */\n readonly k: number;\n /** Classification, one entry per flat transition (XOR branches included). */\n readonly classes: readonly Klass[];\n}\n\n/**\n * Sound colour-slot bound `k`: a colour is live iff some coloured place holds it, so\n * `#live colours ≤ Σ_{coloured} M(p) ≤ y·M0` for any non-negative P-semiflow `y`\n * (`y·C = 0`, `y ≥ 0`) that weights every coloured place `≥ 1`. Returns the tightest\n * such `y·M0` (each `PInvariant.constant` is `y·M0`), or `null` when no covering\n * non-negative semiflow exists — the coloured set is then not structurally\n * token-bounded (a genuine unbounded colour leak) and the caller must fall back.\n *\n * Mirrors the Rust reference `colour_slot_bound`.\n */\nfunction colourSlotBound(coloured: readonly number[], semiflows: readonly PInvariant[]): number | null {\n const w = (inv: PInvariant, pid: number): number => inv.weights[pid] ?? 0;\n const isSemiflow = (inv: PInvariant): boolean => inv.weights.every((x) => x >= 0);\n\n // Tightest bound: a single non-negative P-semiflow weighting every coloured place.\n let single: number | null = null;\n for (const inv of semiflows) {\n if (isSemiflow(inv) && inv.constant >= 1 && coloured.every((pid) => w(inv, pid) >= 1)) {\n if (single === null || inv.constant < single) single = inv.constant;\n }\n }\n if (single !== null) return single;\n\n // Otherwise sum the non-negative semiflows that touch a coloured place — the sum is\n // itself a valid non-negative P-semiflow. If together they weight every coloured\n // place, `Σ y·M0` is a sound (looser) bound; if some coloured place stays at weight\n // 0 across all of them, no non-negative semiflow covers it, so the coloured set is\n // not structurally token-bounded → null (sound over-approximation).\n let sumConst = 0;\n const covered = new Array<boolean>(coloured.length).fill(false);\n for (const inv of semiflows) {\n if (!isSemiflow(inv)) continue;\n let touches = false;\n for (let i = 0; i < coloured.length; i++) {\n if (w(inv, coloured[i]!) >= 1) {\n covered[i] = true;\n touches = true;\n }\n }\n if (touches) sumConst += inv.constant;\n }\n if (covered.every((c) => c) && sumConst >= 1) return sumConst;\n return null;\n}\n\n/**\n * Detects whether `net` is in the supported budget-bounded coloured fragment\n * (mint→matched-join, plus the EXTENDED coloured consumers and carrier places of\n * [NU-051], with XOR-expanded output branches) and, if so, returns the plan for\n * {@link encodeColoured}. Returns `null` otherwise — the verifier then uses the\n * sound over-approximation.\n *\n * Each flat row carries a back-reference to its source transition\n * ({@link FlatTransition.source}); an XOR transition expands to one flat row per\n * output branch (no 1:1 net↔flat assumption), so we read `matchSpec` from the\n * source while classifying by the flat row's own incidence.\n *\n * `semiflows` are the net's non-negative P-semiflows ({@link computePSemiflows}); a\n * covering one sets the colour-slot bound `k` (see {@link colourSlotBound}).\n */\nexport function buildColouredPlan(\n net: PetriNet,\n flat: FlatNet,\n initial: MarkingState,\n budgetNames: ReadonlySet<string>,\n fragmentMode: FragmentMode,\n carrierPlaces: ReadonlySet<string>,\n semiflows: readonly PInvariant[],\n): ColouredPlan | null {\n const P = flat.places.length;\n\n // 1. Coloured places = every matched transition's correlated inputs, plus (in\n // EXTENDED mode) the declared carrier places that thread a fork-minted name\n // through intermediate places to a ν-join input ([NU-051]).\n const isColoured: boolean[] = new Array<boolean>(P).fill(false);\n for (const t of net.transitions) {\n const ms = t.matchSpec;\n if (ms) {\n for (const key of ms.keys) {\n const pid = flat.placeIndex.get(key.place.name);\n if (pid == null) return null;\n isColoured[pid] = true;\n }\n }\n }\n if (fragmentMode === 'extended') {\n for (const c of carrierPlaces) {\n const pid = flat.placeIndex.get(c);\n if (pid != null) isColoured[pid] = true;\n }\n }\n const coloured: number[] = [];\n for (let i = 0; i < P; i++) if (isColoured[i]) coloured.push(i);\n if (coloured.length === 0) return null;\n\n // Coloured places must start empty — no initial colour assignment is modelled.\n for (const pid of coloured) {\n if (initial.tokens(flat.places[pid]!) !== 0) return null;\n }\n\n // Colour-slot bound k: a colour is live iff some coloured place holds it, so\n // `#live colours ≤ Σ_{coloured} M(p) ≤ y·M0` for any non-negative P-semiflow `y`\n // weighting every coloured place `≥ 1`. `k` is the tightest such `y·M0`; any\n // `k ≥ #live` is sound — a larger k only costs O(k) columns, never\n // under-approximates, since a mint may take any free slot behind the freshness\n // guard. If no covering non-negative semiflow exists the coloured set is not\n // structurally token-bounded (a genuine unbounded colour leak), so fall back to the\n // sound over-approximation. This replaces the old budget-count `k` and both\n // structural discipline checks (atomic-rejoin + budget-Φ) below.\n const k = colourSlotBound(coloured, semiflows);\n if (k === null) return null;\n\n // Budget places gate minting: a mint must consume ≥1 budget token — that is what\n // makes it a fresh-name fork rather than an arbitrary coloured producer.\n const budgetIdx = new Set<number>();\n for (const n of budgetNames) {\n const i = flat.placeIndex.get(n);\n if (i != null) budgetIdx.add(i);\n }\n\n // No inhibitor/read/reset/consume-all arc may touch a coloured place.\n for (const ft of flat.transitions) {\n const touches =\n ft.inhibitorPlaces.some((i) => isColoured[i]) ||\n ft.readPlaces.some((i) => isColoured[i]) ||\n ft.resetPlaces.some((i) => isColoured[i]) ||\n ft.consumeAll.some((ca, i) => ca && isColoured[i]!);\n if (touches) return null;\n }\n\n // 2. Classify each flat row from its own incidence (matchSpec from its source).\n const classes: Klass[] = [];\n for (const ft of flat.transitions) {\n const colouredIn = coloured.filter((pid) => ft.preVector[pid]! > 0);\n const colouredOut = coloured.filter((pid) => ft.postVector[pid]! > 0);\n const ms = ft.source.matchSpec;\n\n if (ms) {\n // Matched join: consumes coloured inputs (count 1), produces none.\n if (colouredOut.length !== 0 || colouredIn.length === 0) return null;\n if (colouredIn.some((pid) => ft.preVector[pid]! !== 1)) return null;\n classes.push({ kind: 'join', colouredIn });\n } else if (colouredIn.length !== 0) {\n // EXTENDED coloured consumer (relay/drain, [NU-051]): a non-match transition\n // consuming a coloured place. Admitted only in EXTENDED mode, and only when it\n // consumes EXACTLY ONE coloured input at count EXACTLY ONE (higher counts would\n // over-count the name layer against the base marking's single token per place).\n // It relays the name into its coloured outputs (each at count 1) or drains it.\n if (fragmentMode !== 'extended') return null;\n if (colouredIn.length !== 1 || ft.preVector[colouredIn[0]!]! !== 1) return null;\n if (colouredOut.some((o) => ft.postVector[o]! !== 1)) return null;\n classes.push({ kind: 'consume', inputCol: colouredIn[0]!, colouredOut });\n } else if (colouredOut.length !== 0) {\n // Minting fork: produces coloured (count 1), consumes none, and must consume\n // ≥1 budget token — that is what makes it a fresh-name fork rather than an\n // arbitrary coloured producer. (Boundedness is decided by the colour-slot bound\n // above, not here.)\n if (colouredOut.some((o) => ft.postVector[o]! !== 1)) return null;\n let budgetConsumed = 0;\n for (const b of budgetIdx) budgetConsumed += ft.preVector[b]!;\n if (budgetConsumed < 1) return null;\n classes.push({ kind: 'mint', colouredOut });\n } else {\n // Touches no coloured place at all.\n classes.push({ kind: 'untouched' });\n }\n }\n\n return { coloured, isColoured, k, classes };\n}\n\n/**\n * Column layout over the coloured state vector: uncoloured place → one var,\n * coloured place → `k` per-colour vars. The current/next-marking variables are\n * named consts reused across every rule (each `ForAll` scopes its own binding).\n */\ninterface Layout {\n /** Column index of each uncoloured place (`-1` if coloured). */\n readonly colUnc: number[];\n /** Per coloured place: its `k` column indices (empty if uncoloured). */\n readonly colCol: number[][];\n /** Total column count. */\n readonly nCols: number;\n /** Current-marking vars, one per column. */\n readonly cur: Arith[];\n /** Next-marking vars, one per column. */\n readonly nxt: Arith[];\n}\n\nfunction buildLayout(ctx: Z3Context, plan: ColouredPlan, P: number): Layout {\n const colUnc: number[] = new Array<number>(P).fill(-1);\n const colCol: number[][] = Array.from({ length: P }, () => []);\n let nCols = 0;\n for (let i = 0; i < P; i++) {\n if (plan.isColoured[i]) {\n const idxs: number[] = [];\n for (let c = 0; c < plan.k; c++) idxs.push(nCols++);\n colCol[i] = idxs;\n } else {\n colUnc[i] = nCols++;\n }\n }\n const cur: Arith[] = [];\n const nxt: Arith[] = [];\n for (let col = 0; col < nCols; col++) {\n cur.push(ctx.Int.const(`c${col}`));\n nxt.push(ctx.Int.const(`cp${col}`));\n }\n return { colUnc, colCol, nCols, cur, nxt };\n}\n\n/** Contributes the enablement guards and the changed-column updates of a rule. */\ntype Fill = (enab: Bool[], upd: Map<number, Arith>) => void;\n\n/**\n * Encodes the supported ν-net as bounded name-coloured CHC for Z3 Spacer. Reuses\n * {@link EncodingResult}; with the query `(not Error)`, `sat` ⇒ PROVEN, `unsat` ⇒\n * VIOLATED (the Spacer convention shared with the flat encoder).\n *\n * Returns `null` when the property names a place that does not resolve in the net\n * (see {@link encodeViolation}); the verifier reports Unknown rather than certify a\n * vacuous PROVEN.\n */\nexport function encodeColoured(\n ctx: Z3Context,\n fp: Z3Fixedpoint,\n plan: ColouredPlan,\n flat: FlatNet,\n initial: MarkingState,\n property: SmtProperty,\n invariants: readonly PInvariant[],\n sinkPlaces: ReadonlySet<Place<any>> = new Set(),\n): EncodingResult | null {\n const P = flat.places.length;\n const k = plan.k;\n const lay = buildLayout(ctx, plan, P);\n\n const intSort = ctx.Int.sort();\n const boolSort = ctx.Bool.sort();\n const markingSorts: any[] = new Array(lay.nCols).fill(intSort);\n const reachable: FuncDecl = ctx.Function.declare('Reachable', ...markingSorts, boolSort);\n fp.registerRelation(reachable);\n const error: FuncDecl = ctx.Function.declare('Error', boolSort);\n fp.registerRelation(error);\n\n // Init: uncoloured places carry their initial count; coloured start empty.\n const initArgs: Arith[] = new Array(lay.nCols);\n for (let i = 0; i < P; i++) {\n if (plan.isColoured[i]) {\n for (let c = 0; c < k; c++) initArgs[lay.colCol[i]![c]!] = ctx.Int.val(0);\n } else {\n initArgs[lay.colUnc[i]!] = ctx.Int.val(initial.tokens(flat.places[i]!));\n }\n }\n fp.addRule((reachable as any).call(...initArgs) as Bool, 'init');\n\n // Transition rules.\n for (let ti = 0; ti < plan.classes.length; ti++) {\n const cls = plan.classes[ti]!;\n const ft = flat.transitions[ti]!;\n if (cls.kind === 'untouched') {\n addRule(ctx, fp, reachable, lay, plan, invariants, `${ft.name}_u`, (enab, upd) =>\n uncolouredIncidence(ctx, lay, plan, ft, enab, upd),\n );\n } else if (cls.kind === 'mint') {\n const colouredOut = cls.colouredOut;\n for (let c = 0; c < k; c++) {\n const cc = c;\n addRule(ctx, fp, reachable, lay, plan, invariants, `${ft.name}_mint_${cc}`, (enab, upd) => {\n uncolouredIncidence(ctx, lay, plan, ft, enab, upd);\n // Globally fresh colour: cc must be empty in every coloured place.\n for (const q of plan.coloured) enab.push(lay.cur[lay.colCol[q]![cc]!]!.eq(0));\n for (const o of colouredOut) {\n const col = lay.colCol[o]![cc]!;\n upd.set(col, lay.cur[col]!.add(1));\n }\n });\n }\n } else if (cls.kind === 'join') {\n const colouredIn = cls.colouredIn;\n for (let c = 0; c < k; c++) {\n const cc = c;\n addRule(ctx, fp, reachable, lay, plan, invariants, `${ft.name}_join_${cc}`, (enab, upd) => {\n uncolouredIncidence(ctx, lay, plan, ft, enab, upd);\n // Same colour cc present in every correlated input.\n for (const ip of colouredIn) {\n const col = lay.colCol[ip]![cc]!;\n enab.push(lay.cur[col]!.ge(1));\n upd.set(col, lay.cur[col]!.add(-1));\n }\n });\n }\n } else {\n // EXTENDED coloured consumer: one rule per colour — consume colour cc from\n // the single coloured input and thread it into each coloured output (relay),\n // or into none (drain).\n const inputCol = cls.inputCol;\n const colouredOut = cls.colouredOut;\n for (let c = 0; c < k; c++) {\n const cc = c;\n addRule(ctx, fp, reachable, lay, plan, invariants, `${ft.name}_consume_${cc}`, (enab, upd) => {\n uncolouredIncidence(ctx, lay, plan, ft, enab, upd);\n const icol = lay.colCol[inputCol]![cc]!;\n enab.push(lay.cur[icol]!.ge(1));\n upd.set(icol, lay.cur[icol]!.add(-1));\n for (const o of colouredOut) {\n const ocol = lay.colCol[o]![cc]!;\n upd.set(ocol, lay.cur[ocol]!.add(1));\n }\n });\n }\n }\n }\n\n // Error rule. `false` ⇒ the property names an unresolved place; refuse to build\n // a vacuously-provable encoding and let the verifier report Unknown.\n if (!addErrorRule(ctx, fp, reachable, error, lay, plan, flat, property, sinkPlaces)) {\n return null;\n }\n\n return {\n errorExpr: (error as any).call() as Bool,\n reachableDecl: reachable,\n };\n}\n\n/**\n * Builds one transition CHC rule. `fill` contributes the enablement guards and\n * the changed-column updates; every other column is copied unchanged, changed\n * columns get a non-negativity guard, and the (lifted) P-invariants constrain the\n * successor.\n */\nfunction addRule(\n ctx: Z3Context,\n fp: Z3Fixedpoint,\n reachable: FuncDecl,\n lay: Layout,\n plan: ColouredPlan,\n invariants: readonly PInvariant[],\n ruleName: string,\n fill: Fill,\n): void {\n const enab: Bool[] = [];\n const upd = new Map<number, Arith>();\n fill(enab, upd);\n\n const conds: Bool[] = [(reachable as any).call(...lay.cur) as Bool, ...enab];\n for (let col = 0; col < lay.nCols; col++) {\n const expr = upd.get(col);\n if (expr !== undefined) {\n conds.push(lay.nxt[col]!.eq(expr), lay.nxt[col]!.ge(0));\n } else {\n conds.push(lay.nxt[col]!.eq(lay.cur[col]!));\n }\n }\n for (const inv of invariants) {\n const eq = liftedInvariant(ctx, inv, plan, lay, lay.nxt);\n if (eq) conds.push(eq);\n }\n\n const body = ctx.And(...conds);\n const head = (reachable as any).call(...lay.nxt) as Bool;\n const qRule = ctx.ForAll([...lay.cur, ...lay.nxt], ctx.Implies(body, head));\n fp.addRule(qRule, ruleName);\n}\n\n/**\n * Pushes the enablement guards and column updates contributed by a transition's\n * **uncoloured** incidence (consume/produce on non-coloured places). Coloured\n * columns are handled by the caller (mint produces, join consumes). Mirrors the\n * Rust reference — no blanket current-marking non-negativity guard.\n */\nfunction uncolouredIncidence(\n ctx: Z3Context,\n lay: Layout,\n plan: ColouredPlan,\n ft: FlatTransition,\n enab: Bool[],\n upd: Map<number, Arith>,\n): void {\n const P = ft.preVector.length;\n for (let i = 0; i < P; i++) {\n if (plan.isColoured[i]) continue;\n const col = lay.colUnc[i]!;\n const pre = ft.preVector[i]!;\n if (pre > 0) enab.push(lay.cur[col]!.ge(pre));\n if (ft.resetPlaces.includes(i) || ft.consumeAll[i]) {\n upd.set(col, ctx.Int.val(ft.postVector[i]!));\n } else {\n const delta = ft.postVector[i]! - ft.preVector[i]!;\n if (delta !== 0) upd.set(col, lay.cur[col]!.add(delta));\n }\n }\n // Inhibitor / read arcs (all on uncoloured places — checked in buildColouredPlan).\n for (const pid of ft.inhibitorPlaces) enab.push(lay.cur[lay.colUnc[pid]!]!.eq(0));\n for (const pid of ft.readPlaces) enab.push(lay.cur[lay.colUnc[pid]!]!.ge(1));\n}\n\n/**\n * Aggregate token-count expression for a place over the given var-set: the single\n * uncoloured var, or the sum of its colours.\n */\nfunction aggregate(plan: ColouredPlan, lay: Layout, place: number, vars: readonly Arith[]): Arith {\n if (plan.isColoured[place]) {\n const cols = lay.colCol[place]!;\n let sum = vars[cols[0]!]!;\n for (let c = 1; c < cols.length; c++) sum = sum.add(vars[cols[c]!]!);\n return sum;\n }\n return vars[lay.colUnc[place]!]!;\n}\n\n/**\n * Lifts a flat P-invariant to the coloured layout: a coloured place's variable\n * becomes the sum of its colours (= its aggregate count), so the (true) flat\n * invariant constrains the coloured successor without excluding any reachable\n * state.\n */\nfunction liftedInvariant(\n ctx: Z3Context,\n inv: PInvariant,\n plan: ColouredPlan,\n lay: Layout,\n vars: readonly Arith[],\n): Bool | null {\n if (inv.support.size === 0) return null;\n let sum: Arith = ctx.Int.val(0);\n for (const i of inv.support) {\n const agg = aggregate(plan, lay, i, vars);\n const w = inv.weights[i]!;\n sum = sum.add(w === 1 ? agg : agg.mul(w));\n }\n return sum.eq(inv.constant);\n}\n\n/**\n * Encodes the error rule: a reachable marking that violates the property.\n * Returns `false` when the property names an unresolved place ({@link encodeViolation}\n * returned `null`); no rule is added and the caller reports Unknown rather than\n * certify a vacuous PROVEN.\n */\nfunction addErrorRule(\n ctx: Z3Context,\n fp: Z3Fixedpoint,\n reachable: FuncDecl,\n error: FuncDecl,\n lay: Layout,\n plan: ColouredPlan,\n flat: FlatNet,\n property: SmtProperty,\n sinkPlaces: ReadonlySet<Place<any>>,\n): boolean {\n const violation = encodeViolation(ctx, plan, lay, flat, property, lay.cur, sinkPlaces);\n if (violation === null) return false; // unresolved property place → signal Unknown\n const reachBody = (reachable as any).call(...lay.cur) as Bool;\n const body = ctx.And(reachBody, violation);\n const head = (error as any).call() as Bool;\n const qRule = ctx.ForAll([...lay.cur], ctx.Implies(body, head));\n fp.addRule(qRule, 'error');\n return true;\n}\n\n/**\n * Encodes the property-violation condition over the coloured current marking.\n * Reachability-safety properties compare aggregate place counts; quiescence\n * properties ([NU-053]) use the colour-aware deadlock predicate.\n *\n * Returns `null` when the property names a place that does not resolve in the\n * net (e.g. a typo'd bound/pending place). A `false` violation term there would\n * make the Error rule unsatisfiable and yield a **vacuous** PROVEN, silently\n * certifying a mis-named place; `null` propagates up so the verifier reports\n * Unknown instead.\n */\nfunction encodeViolation(\n ctx: Z3Context,\n plan: ColouredPlan,\n lay: Layout,\n flat: FlatNet,\n property: SmtProperty,\n cur: readonly Arith[],\n sinkPlaces: ReadonlySet<Place<any>>,\n): Bool | null {\n switch (property.type) {\n case 'place-bound':\n case 'branch-place-bound': {\n const idx = flatNetIndexOf(flat, property.place);\n if (idx < 0) return null;\n return aggregate(plan, lay, idx, cur).gt(property.bound);\n }\n case 'mutual-exclusion': {\n const i1 = flatNetIndexOf(flat, property.p1);\n const i2 = flatNetIndexOf(flat, property.p2);\n if (i1 < 0 || i2 < 0) return ctx.Bool.val(false);\n return ctx.And(aggregate(plan, lay, i1, cur).ge(1), aggregate(plan, lay, i2, cur).ge(1));\n }\n case 'unreachable': {\n const conds: Bool[] = [];\n for (const place of property.places) {\n const idx = flatNetIndexOf(flat, place);\n if (idx >= 0) conds.push(aggregate(plan, lay, idx, cur).ge(1));\n }\n if (conds.length === 0) return ctx.Bool.val(false);\n return conds.length === 1 ? conds[0]! : ctx.And(...conds);\n }\n case 'deadlock-free':\n return encodeColouredDeadlock(ctx, plan, lay, flat, sinkPlaces);\n case 'joined-or-dead-lettered': {\n const idx = flatNetIndexOf(flat, property.pending);\n if (idx < 0) return null;\n const deadlock = encodeColouredDeadlock(ctx, plan, lay, flat, sinkPlaces);\n return ctx.And(deadlock, aggregate(plan, lay, idx, cur).ge(1));\n }\n }\n}\n\n/** Conjunction of `xs` (empty ⇒ `true`), avoiding variadic-spread edge cases. */\nfunction andAll(ctx: Z3Context, xs: Bool[]): Bool {\n if (xs.length === 0) return ctx.Bool.val(true);\n let r = xs[0]!;\n for (let i = 1; i < xs.length; i++) r = ctx.And(r, xs[i]!);\n return r;\n}\n\n/** Disjunction of `xs` (empty ⇒ `false`). */\nfunction orAll(ctx: Z3Context, xs: Bool[]): Bool {\n if (xs.length === 0) return ctx.Bool.val(false);\n let r = xs[0]!;\n for (let i = 1; i < xs.length; i++) r = ctx.Or(r, xs[i]!);\n return r;\n}\n\n/** Maps injected environment-place index -> injection bound (null = unbounded). */\nfunction injectedEnvIndices(flat: FlatNet): Map<number, number | null> {\n const out = new Map<number, number | null>();\n for (const [name, bound] of flat.environmentInjection) {\n const idx = flat.placeIndex.get(name);\n if (idx != null) out.set(idx, bound);\n }\n return out;\n}\n\n/**\n * The uncoloured disable reasons for a flat row: marking-dependent clauses (any one\n * true ⇒ the transition's uncoloured part is unmet), plus a flag that it is\n * permanently disabled (an env cap below the demand means it can never fire).\n * Coloured places are excluded — their enablement is the per-class colour term.\n * Mirrors the flat {@link module:smt-encoder} deadlock with the same env relaxation.\n */\nfunction uncolouredDisable(\n ft: FlatTransition,\n lay: Layout,\n plan: ColouredPlan,\n envInj: Map<number, number | null>,\n): { reasons: Bool[]; permanentlyDisabled: boolean } {\n const reasons: Bool[] = [];\n let permanentlyDisabled = false;\n const P = ft.preVector.length;\n for (let i = 0; i < P; i++) {\n if (plan.isColoured[i] || ft.preVector[i]! === 0) continue;\n if (envInj.has(i)) {\n const bound = envInj.get(i)!;\n if (bound !== null && ft.preVector[i]! > bound) permanentlyDisabled = true;\n continue;\n }\n reasons.push(lay.cur[lay.colUnc[i]!]!.lt(ft.preVector[i]!));\n }\n for (const inh of ft.inhibitorPlaces) {\n reasons.push(lay.cur[lay.colUnc[inh]!]!.gt(0));\n }\n for (const rd of ft.readPlaces) {\n if (envInj.has(rd)) {\n const bound = envInj.get(rd)!;\n if (bound !== null && bound < 1) permanentlyDisabled = true;\n continue;\n }\n reasons.push(lay.cur[lay.colUnc[rd]!]!.lt(1));\n }\n return { reasons, permanentlyDisabled };\n}\n\n/**\n * The colour-specific \"disabled for every colour\" term for a class (`null` if the\n * class imposes no coloured enablement constraint). Combined by the caller with the\n * uncoloured disable reasons: the transition is disabled if EITHER holds.\n */\nfunction colouredDisabledTerm(ctx: Z3Context, cls: Klass, plan: ColouredPlan, lay: Layout): Bool | null {\n const k = plan.k;\n switch (cls.kind) {\n case 'untouched':\n return null;\n case 'mint': {\n // No globally-fresh colour: for every colour c, some coloured place holds c.\n const perColour: Bool[] = [];\n for (let c = 0; c < k; c++) {\n const present = plan.coloured.map((q) => lay.cur[lay.colCol[q]![c]!]!.ge(1));\n perColour.push(orAll(ctx, present));\n }\n return andAll(ctx, perColour);\n }\n case 'join': {\n // No colour is shared by all correlated inputs: for every colour c, some\n // input lacks c.\n const perColour: Bool[] = [];\n for (let c = 0; c < k; c++) {\n const missing = cls.colouredIn.map((i) => lay.cur[lay.colCol[i]![c]!]!.eq(0));\n perColour.push(orAll(ctx, missing));\n }\n return andAll(ctx, perColour);\n }\n case 'consume': {\n // No colour present at the single coloured input.\n const perColour: Bool[] = [];\n for (let c = 0; c < k; c++) {\n perColour.push(lay.cur[lay.colCol[cls.inputCol]![c]!]!.eq(0));\n }\n return andAll(ctx, perColour);\n }\n }\n}\n\n/**\n * Colour-aware deadlock predicate ([NU-053]): every transition is disabled (no\n * colour enables it) and the marking is not a sink state. Mirrors the flat\n * {@link module:smt-encoder}'s `encodeDeadlock` with the same env-injection\n * relaxation (VER-006), lifted to the coloured layout.\n */\nfunction encodeColouredDeadlock(\n ctx: Z3Context,\n plan: ColouredPlan,\n lay: Layout,\n flat: FlatNet,\n sinkPlaces: ReadonlySet<Place<any>>,\n): Bool {\n const envInj = injectedEnvIndices(flat);\n const disabledConditions: Bool[] = [];\n for (let ti = 0; ti < plan.classes.length; ti++) {\n const cls = plan.classes[ti]!;\n const ft = flat.transitions[ti]!;\n const { reasons, permanentlyDisabled } = uncolouredDisable(ft, lay, plan, envInj);\n if (permanentlyDisabled) {\n // The transition can never fire — it is always \"disabled\".\n disabledConditions.push(ctx.Bool.val(true));\n continue;\n }\n const term = colouredDisabledTerm(ctx, cls, plan, lay);\n if (term !== null) reasons.push(term);\n if (reasons.length === 0) {\n // Always enabled (possibly via injection) — no marking is a deadlock.\n return ctx.Bool.val(false);\n }\n disabledConditions.push(reasons.length === 1 ? reasons[0]! : orAll(ctx, reasons));\n }\n\n // Not a sink state: some non-sink place still holds a token (aggregate count).\n const sinkIndices = new Set<number>();\n for (const sink of sinkPlaces) {\n const idx = flatNetIndexOf(flat, sink);\n if (idx >= 0) sinkIndices.add(idx);\n }\n if (sinkIndices.size > 0) {\n const nonSink: Bool[] = [];\n for (let pid = 0; pid < flat.places.length; pid++) {\n if (sinkIndices.has(pid)) continue;\n nonSink.push(aggregate(plan, lay, pid, lay.cur).ge(1));\n }\n if (nonSink.length > 0) {\n disabledConditions.push(orAll(ctx, nonSink));\n }\n }\n\n return andAll(ctx, disabledConditions);\n}\n","/**\n * Name-correlation fragment classifier for the ν-aware state class graph\n * (NU-050, Route B). See the Rust/Java equivalents for the full contract.\n *\n * Identifies the coloured places (the correlated inputs of ν-joins) and the role\n * of each transition in the supported fragment. Returns `null` when the net is\n * not a ν-net or falls outside the admitted fragment (the caller falls back to\n * the SMT / Route A path).\n *\n * {@link FragmentMode.base} (default) admits the shipped mint → matched-join\n * fragment only: a non-match transition consuming a coloured place, or a join\n * re-minting into one, rejects the net. {@link FragmentMode.extended} (opt-in,\n * NU-051) additionally admits the coloured-consumer role ({@link Role} `consume`,\n * drain/relay) and unions user-declared *carrier* places into the coloured set\n * (fork-threaded co-mint). The one deliberate tightening shared by both modes is\n * the reset/read/inhibitor-on-coloured guard below.\n */\nimport type { PetriNet } from '../../core/petri-net.js';\nimport type { Transition } from '../../core/transition.js';\nimport { enumerateBranches } from '../../core/out.js';\n\n/**\n * Selects which coloured-place fragment {@link classify} admits. `base` (default)\n * reproduces the shipped mint → matched-join fragment exactly; `extended`\n * additionally admits the coloured-consumer (drain/relay) role and carrier\n * places (NU-051).\n */\nexport type FragmentMode = 'base' | 'extended';\n\nexport type Role =\n | { readonly type: 'ordinary' }\n | { readonly type: 'mint' }\n | { readonly type: 'join'; readonly colouredIn: ReadonlyArray<readonly [string, number]> }\n /**\n * Coloured consumer (drain/relay), EXTENDED only (NU-051). A non-match\n * transition that consumes **exactly one** coloured place at count **exactly\n * one**. It *relays* the consumed name-symbol into each coloured output of the\n * fired branch (threading `s`), or *drains* it (dead-letters `s`) when the\n * branch produces no coloured output. Because the consumed count is fixed at\n * one, the role carries only the input place name — no count, no list.\n *\n * Documented precondition (NU-051): the action MUST thread the consumed symbol\n * (relay) or drop it (drain); it MUST NOT mint a *fresh* name into a coloured\n * output while consuming a coloured token (a consume-and-remint transition is\n * out of contract — the name layer would thread `s` where the runtime mints\n * afresh).\n */\n | { readonly type: 'consume'; readonly colouredInput: string };\n\nexport interface NameFragment {\n readonly colouredOrder: readonly string[];\n isColoured(place: string): boolean;\n role(transition: string): Role;\n}\n\n/**\n * Classifies `net` under `mode`. Under {@link FragmentMode.extended} the declared\n * `carrierPlaces` (intermediate places carrying a fresh name from the minting\n * fork onward to a ν-join input) are unioned into the coloured set *before* role\n * assignment, so the existing mint co-mints one fresh name into all of them, and\n * non-match transitions may take the drain/relay `consume` role. Under\n * {@link FragmentMode.base} the `carrierPlaces` are ignored and any non-match\n * transition consuming a coloured place rejects the net (NU-051).\n *\n * Both modes reject a net where any coloured place carries a reset, read, or\n * inhibitor arc: those arcs would be silently misclassified ordinary and the\n * name layer would drift from the base marking (a soundness guard; rejection\n * just falls back to the sound over-approximation).\n */\nexport function classify(\n net: PetriNet,\n mode: FragmentMode,\n carrierPlaces: ReadonlySet<string>,\n): NameFragment | null {\n // 1. Coloured places = union of every match transition's correlated inputs,\n // plus (EXTENDED only) the declared carrier places.\n const coloured = new Set<string>();\n let anyMatch = false;\n for (const t of net.transitions) {\n if (t.matchSpec !== null) {\n anyMatch = true;\n for (const key of t.matchSpec.keys) coloured.add(key.place.name);\n }\n }\n if (!anyMatch || coloured.size === 0) return null;\n if (mode === 'extended') {\n for (const c of carrierPlaces) coloured.add(c);\n }\n\n // 1b. Soundness guard (BOTH modes): no coloured place may carry a reset, read,\n // or inhibitor arc on any transition. Checked after the coloured set is\n // finalized (a carrier could carry such an arc).\n for (const t of net.transitions) {\n if (\n t.resets.some(r => coloured.has(r.place.name)) ||\n t.reads.some(r => coloured.has(r.place.name)) ||\n t.inhibitors.some(i => coloured.has(i.place.name))\n ) {\n return null;\n }\n }\n\n const roles = new Map<string, Role>();\n for (const t of net.transitions) {\n const colouredInputs = t.inputSpecs.filter(s => coloured.has(s.place.name));\n const consumesColoured = colouredInputs.length > 0;\n let producesColoured = false;\n if (t.outputSpec !== null) {\n for (const branch of enumerateBranches(t.outputSpec)) {\n for (const p of branch) {\n if (coloured.has(p.name)) producesColoured = true;\n }\n }\n }\n\n let role: Role;\n if (t.matchSpec !== null) {\n if (producesColoured) return null; // re-mint onto a coloured place — out of fragment\n const colouredIn: Array<readonly [string, number]> = [];\n for (const key of t.matchSpec.keys) {\n const place = key.place.name;\n // One/Exactly consume a fixed count of the matched name (faithfully\n // modelled). All/AtLeast consume ALL matching tokens at runtime — the\n // fixed-count SCG step would under-consume — so drop to the over-approx.\n const required = fixedRequiredCount(t, place);\n if (required === null) return null;\n colouredIn.push([place, required] as const);\n }\n colouredIn.sort((a, b) => (a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : 0));\n role = { type: 'join', colouredIn };\n } else if (consumesColoured) {\n // A non-match transition consuming a coloured token.\n if (mode === 'base') return null; // BASE: unsupported — the name would be ambiguous.\n // EXTENDED: admitted as a drain/relay ONLY when it consumes exactly ONE\n // coloured place at count EXACTLY ONE (one or exactly{count:1}). More than\n // one coloured input, or any higher / all / at-least count, would over-count\n // the name layer relative to the base marking (which adds exactly one token\n // per output place) — reject to the sound over-approximation.\n if (colouredInputs.length !== 1) return null;\n const spec = colouredInputs[0]!;\n const countOne = spec.type === 'one' || (spec.type === 'exactly' && spec.count === 1);\n if (!countOne) return null;\n role = { type: 'consume', colouredInput: spec.place.name };\n } else if (producesColoured) {\n role = { type: 'mint' };\n } else {\n role = { type: 'ordinary' };\n }\n roles.set(t.name, role);\n }\n\n const colouredOrder = [...coloured].sort();\n return {\n colouredOrder,\n isColoured: (p) => coloured.has(p),\n role: (tn) => roles.get(tn) ?? { type: 'ordinary' },\n };\n}\n\n/**\n * The fixed per-firing consumption of the matched name for `t`'s input on\n * `placeName`, or `null` when the cardinality consumes ALL matching tokens\n * (all/at-least) or no such input exists — neither of which the fixed-count SCG\n * step can model faithfully.\n */\nfunction fixedRequiredCount(t: Transition, placeName: string): number | null {\n for (const spec of t.inputSpecs) {\n if (spec.place.name === placeName) {\n switch (spec.type) {\n case 'one': return 1;\n case 'exactly': return spec.count;\n case 'all': return null;\n case 'at-least': return null;\n }\n }\n }\n return null;\n}\n","/**\n * The abstract **name-partition** layer for the ν-aware state class graph\n * (NU-050, Route B).\n *\n * The plain {@link StateClassGraph} is name-blind: a marking is a per-place token\n * count, so a ν-join fires whenever the counts allow, ignoring whether the\n * consumed tokens share a correlation name. This carries, beside the count\n * marking, an abstract partition of the correlation tokens into name-symbols. A\n * `Sym` is an opaque identity only (NU-001) — the analyzer never evaluates the\n * runtime name projection. {@link NameMarking.canonicalKey} quotients markings\n * that differ only by a permutation of symbols (the raw ids never appear in a\n * key), keeping the graph finite when the live-name count is structurally\n * bounded. The key string format matches the Rust and Java implementations.\n */\n\nexport type Sym = number;\n\nexport class NameMarking {\n // place name -> (symbol -> count). Only coloured places appear; a place's\n // total here equals its count in the base MarkingState.\n private readonly perPlace: Map<string, Map<Sym, number>>;\n\n constructor(perPlace?: Map<string, Map<Sym, number>>) {\n this.perPlace = perPlace ?? new Map();\n }\n\n copy(): NameMarking {\n const p = new Map<string, Map<Sym, number>>();\n for (const [place, syms] of this.perPlace) {\n p.set(place, new Map(syms));\n }\n return new NameMarking(p);\n }\n\n add(place: string, sym: Sym, count: number): void {\n if (count === 0) return;\n let syms = this.perPlace.get(place);\n if (!syms) {\n syms = new Map();\n this.perPlace.set(place, syms);\n }\n syms.set(sym, (syms.get(sym) ?? 0) + count);\n }\n\n /** Removes `count` of `sym` from `place`; returns false (unchanged) if fewer present. */\n remove(place: string, sym: Sym, count: number): boolean {\n const syms = this.perPlace.get(place);\n if (!syms) return false;\n const have = syms.get(sym);\n if (have === undefined || have < count) return false;\n const left = have - count;\n if (left === 0) {\n syms.delete(sym);\n if (syms.size === 0) this.perPlace.delete(place);\n } else {\n syms.set(sym, left);\n }\n return true;\n }\n\n countOf(place: string, sym: Sym): number {\n return this.perPlace.get(place)?.get(sym) ?? 0;\n }\n\n symbolsIn(place: string): Sym[] {\n const syms = this.perPlace.get(place);\n return syms ? [...syms.keys()] : [];\n }\n\n private liveSymbols(): Sym[] {\n const all = new Set<Sym>();\n for (const syms of this.perPlace.values()) {\n for (const s of syms.keys()) all.add(s);\n }\n return [...all];\n }\n\n /**\n * Symmetry-canonical key over `colouredOrder` (the finiteness mechanism). Two\n * markings differing only by a permutation of symbols produce an identical key\n * (NU-001). Each symbol's signature is its count vector over `colouredOrder`;\n * symbols are ranked by (signature, raw id) and emitted per place as a\n * rank-multiset — a complete invariant of the symbol-permutation orbit.\n */\n canonicalKey(colouredOrder: readonly string[]): string {\n const signature = (s: Sym): number[] => colouredOrder.map(p => this.countOf(p, s));\n const ranked = this.liveSymbols().map(s => ({ sig: signature(s), sym: s }));\n ranked.sort((a, b) => {\n const c = compareNumberArrays(a.sig, b.sig);\n return c !== 0 ? c : a.sym - b.sym;\n });\n const rankOf = new Map<Sym, number>();\n ranked.forEach((r, i) => rankOf.set(r.sym, i));\n\n const parts = colouredOrder.map(p => {\n const syms = this.perPlace.get(p);\n const entries: Array<[number, number]> = [];\n if (syms) {\n for (const [s, c] of syms) entries.push([rankOf.get(s)!, c]);\n }\n entries.sort((a, b) => (a[0] !== b[0] ? a[0] - b[0] : a[1] - b[1]));\n const inner = entries.map(([r, c]) => `${r}x${c}`).join(',');\n return `${p}:{${inner}}`;\n });\n return parts.join('#');\n }\n}\n\nfunction compareNumberArrays(a: readonly number[], b: readonly number[]): number {\n const n = Math.min(a.length, b.length);\n for (let i = 0; i < n; i++) {\n if (a[i]! !== b[i]!) return a[i]! - b[i]!;\n }\n return a.length - b.length;\n}\n","import type { StateClass } from './state-class.js';\nimport type { NameMarking } from './name-marking.js';\n\n/**\n * A name-aware state class (NU-050, Route B): the base count + DBM\n * {@link StateClass} plus the abstract {@link NameMarking} partition layer. The\n * base class is reused verbatim, so the timing/zone dimension is untouched —\n * name×time composition is automatic. The dedup `key` is the base key\n * (marking + DBM zone) joined with the symmetry-canonical name-partition key.\n */\nexport class NameStateClass {\n readonly base: StateClass;\n readonly names: NameMarking;\n readonly key: string;\n\n constructor(base: StateClass, names: NameMarking, colouredOrder: readonly string[]) {\n this.base = base;\n this.names = names;\n this.key = `${base.marking.toString()}|${base.firingDomain.toString()}||${names.canonicalKey(colouredOrder)}`;\n }\n}\n","/**\n * The ν-aware (name-partition quotient) State Class Graph (NU-050, Route B).\n *\n * Mirrors {@link StateClassGraph} — same Berthomieu-Diaz BFS, same count + DBM\n * successor step (reused verbatim via {@link computeSuccessor}) — but each class\n * additionally carries the abstract {@link NameMarking} partition. A ν-join is\n * enabled only when one shared name is present at the required multiplicity in\n * every correlated input; a mint introduces a globally-fresh name-symbol; dedup\n * is by the symmetry-canonical key so states differing only by a permutation of\n * names collapse. If BFS closes within `maxClasses` the graph is the complete\n * reachable quotient (exact); otherwise it truncates and the verifier reports\n * `unknown` (ν-PN reachability is undecidable).\n */\nimport type { PetriNet } from '../../core/petri-net.js';\nimport type { Place } from '../../core/place.js';\nimport type { EnvironmentPlace } from '../../core/place.js';\nimport type { In } from '../../core/in.js';\nimport type { Transition } from '../../core/transition.js';\nimport type { MarkingState } from '../marking-state.js';\nimport type { EnvironmentAnalysisMode } from './environment-analysis-mode.js';\nimport { ignore } from './environment-analysis-mode.js';\nimport { initialStateClass, expandTransition, computeSuccessor } from './state-class-graph.js';\nimport { NameMarking, type Sym } from './name-marking.js';\nimport { NameStateClass } from './name-state-class.js';\nimport type { NameFragment, Role } from './name-fragment.js';\nimport type { PrioritySemantics } from './priority-semantics.js';\n\nexport interface NameEdge {\n readonly from: number;\n readonly to: number;\n readonly transitionName: string;\n}\n\nexport class NameStateClassGraph {\n readonly classes: NameStateClass[] = [];\n readonly edges: NameEdge[] = [];\n private readonly _successors: number[][] = [];\n private _complete = true;\n\n isComplete(): boolean {\n return this._complete;\n }\n\n classCount(): number {\n return this.classes.length;\n }\n\n successorsOf(idx: number): readonly number[] {\n return this._successors[idx]!;\n }\n\n /** The base count-marking of class `idx` (for property queries). */\n markingOf(idx: number): MarkingState {\n return this.classes[idx]!.base.marking;\n }\n\n static build(\n net: PetriNet,\n initialMarking: MarkingState,\n fragment: NameFragment,\n maxClasses: number,\n environmentPlaces?: Set<EnvironmentPlace<any>>,\n environmentMode?: EnvironmentAnalysisMode,\n prioritySemantics: PrioritySemantics = 'none',\n ): NameStateClassGraph {\n const envMode = environmentMode ?? ignore();\n const envPlaces = new Set<Place<any>>();\n if (environmentPlaces) {\n for (const ep of environmentPlaces) envPlaces.add(ep.place);\n }\n\n const graph = new NameStateClassGraph();\n const base0 = initialStateClass(net, initialMarking, envPlaces, envMode);\n // Coloured places start empty in the supported fragment (the verifier guards\n // this), so the initial name partition is empty.\n const initial = new NameStateClass(base0, new NameMarking(), fragment.colouredOrder);\n\n const indexOf = new Map<string, number>();\n graph.pushClass(initial, indexOf);\n\n const sym = { next: 0 as Sym };\n const queue: number[] = [0];\n\n while (queue.length > 0) {\n if (graph.classes.length >= maxClasses) {\n graph._complete = false;\n break;\n }\n const curIdx = queue.shift()!;\n const current = graph.classes[curIdx]!;\n\n // The enabled transitions of this class as objects — used by the\n // conflict-only priority prune below (NU-052).\n const enabled = current.base.enabledTransitions;\n for (let idxL = 0; idxL < enabled.length; idxL++) {\n const transition = enabled[idxL]!;\n // NU-052: under CONFLICT semantics, skip a firing the eager,\n // priority-ordered executor would never produce — a conflicting,\n // no-later-ready, strictly-higher-priority transition that actually fires\n // takes the contested token first. `idxL` is L's index in the enabled set\n // (parallel to `readyEarliest`).\n if (\n prioritySemantics === 'conflict' &&\n priorityDominated(\n transition,\n idxL,\n enabled,\n current.base.readyEarliest,\n current.base.marking,\n current.names,\n fragment,\n )\n ) {\n continue;\n }\n const role = fragment.role(transition.name);\n for (const vt of expandTransition(transition)) {\n const baseSucc = computeSuccessor(net, current.base, vt, envPlaces, envMode);\n if (baseSucc === null || baseSucc.isEmpty()) continue;\n const nameSuccs = nameSuccessors(role, current.names, vt.outputPlaces, fragment, sym);\n for (const nm of nameSuccs) {\n const succ = new NameStateClass(baseSucc, nm, fragment.colouredOrder);\n let toIdx = indexOf.get(succ.key);\n if (toIdx === undefined) {\n toIdx = graph.classes.length;\n graph.pushClass(succ, indexOf);\n queue.push(toIdx);\n }\n graph.addEdge(curIdx, toIdx, transition.name);\n }\n }\n }\n }\n return graph;\n }\n\n private pushClass(c: NameStateClass, indexOf: Map<string, number>): void {\n const idx = this.classes.length;\n this.classes.push(c);\n this._successors.push([]);\n indexOf.set(c.key, idx);\n }\n\n private addEdge(from: number, to: number, name: string): void {\n this.edges.push({ from, to, transitionName: name });\n this._successors[from]!.push(to);\n }\n}\n\n/** Float slack for the class-relative earliest-ready comparison (matches the DBM's own EPSILON). */\nconst READY_EPS = 1e-9;\n\n/**\n * True if a firing of `l` is pre-empted by conflict-only priority (NU-052): some\n * other enabled transition `h` has strictly higher priority, shares a consumed\n * input place with `l` **under real competition**, becomes ready no later than\n * `l`, and actually fires in this class (produces a name-successor). The executor\n * fires ready transitions in descending priority order within a pass, so `h` takes\n * the contested token and `l` cannot fire — the pruned firing is not\n * runtime-reachable.\n *\n * **Readiness (DBM residual-earliest).** The name-SCG carries a DBM, so a static\n * `earliest(h) <= earliest(l)` does NOT entail \"H ready no later than L\": their\n * class-relative enabling epochs can put H's clock behind L's. We compare the\n * class-relative earliest-ready times captured on the base class\n * (`StateClass.readyEarliest`, the DBM lower bounds before `letTimePass`): H\n * pre-empts L only when `readyEarliest[H] <= readyEarliest[L] + EPS`. This is\n * fully precise on the zone off-diagonal and subsumes the previously-shipped\n * `earliest 0` case (an immediate H has `readyEarliest[H] === 0 <=\n * readyEarliest[L]`), so no capability is lost.\n *\n * **Real competition (multiplicity).** Sharing a consumed place is not enough: if\n * the place holds enough tokens for H and L at once they do not compete, and\n * pruning L would be unsound — see {@link sharesConsumedInput}.\n *\n * The `willFire` guard is essential on a ν-net: a match (join) transition can be\n * base-enabled yet **name-disabled** (its inputs carry no shared name). Such a\n * join never consumes the contested token, so it must not pre-empt a conflicting\n * drain — otherwise a genuine straggler would strand.\n */\nfunction priorityDominated(\n l: Transition,\n idxL: number,\n enabled: readonly Transition[],\n readyEarliest: readonly number[],\n marking: MarkingState,\n names: NameMarking,\n fragment: NameFragment,\n): boolean {\n return enabled.some(\n (h, idxH) =>\n h !== l &&\n h.priority > l.priority &&\n readyEarliest[idxH]! <= readyEarliest[idxL]! + READY_EPS &&\n willFire(h, names, fragment) &&\n sharesConsumedInput(h, l, marking),\n );\n}\n\n/**\n * True if base-enabled `h` actually produces a name-successor from this class — a\n * join finds a shared enabling name and a consumer finds a resident symbol.\n * Ordinary and Mint always fire; only a name-disabled join (or an empty-input\n * consumer) does not, and such a transition must not pre-empt a conflicting firing.\n */\nfunction willFire(h: Transition, names: NameMarking, fragment: NameFragment): boolean {\n const role = fragment.role(h.name);\n switch (role.type) {\n case 'join':\n return enablingSymbols(names, role.colouredIn).length > 0;\n case 'consume':\n return names.symbolsIn(role.colouredInput).length > 0;\n case 'ordinary':\n case 'mint':\n return true;\n default: {\n // Exhaustiveness guard: a future Role member is a compile error here,\n // rather than silently defaulting to will-fire=true.\n const _exhaustive: never = role;\n return _exhaustive;\n }\n }\n}\n\n/**\n * True if `h` and `l` genuinely compete for a consumed token — they share a\n * consumed input place `p` whose token count in `marking` cannot satisfy both\n * demands at once (`count(p) < demand_h(p) + demand_l(p)`). Read and inhibitor\n * arcs are excluded ({@link Transition.inputPlaces} is consumed inputs only),\n * since they do not remove a token another transition competes for. Compared by\n * place name (name-based Place equality, MOD-024).\n *\n * The multiplicity clause is a soundness guard for the NU-052 prune: if the shared\n * place holds enough tokens for both, `h` does NOT rob `l`, so pruning `l` would\n * drop a runtime-reachable firing.\n */\nfunction sharesConsumedInput(h: Transition, l: Transition, marking: MarkingState): boolean {\n const lIns = new Set<string>();\n for (const p of l.inputPlaces()) lIns.add(p.name);\n for (const p of h.inputPlaces()) {\n if (lIns.has(p.name) && marking.tokens(p) < consumedDemand(h, p.name) + consumedDemand(l, p.name)) {\n return true;\n }\n }\n return false;\n}\n\n/**\n * Tokens `t` consumes from the named place on one firing (summed across its input\n * specs referencing that place — normally a single spec). Uses the enablement\n * required-count so `all`/`at-least` demand their minimum, matching the base SCG's\n * consumption model.\n */\nfunction consumedDemand(t: Transition, placeName: string): number {\n let demand = 0;\n for (const spec of t.inputSpecs) {\n if (spec.place.name === placeName) demand += inputRequiredCount(spec);\n }\n return demand;\n}\n\nfunction inputRequiredCount(spec: In): number {\n switch (spec.type) {\n case 'one': return 1;\n case 'exactly': return spec.count;\n case 'all': return 1;\n case 'at-least': return spec.minimum;\n }\n}\n\n/**\n * The coloured output place names of the fired branch (used by Mint to stamp a\n * fresh symbol, and by Consume to relay the consumed symbol).\n */\nfunction colouredOutputs(outputPlaces: ReadonlySet<Place<any>>, fragment: NameFragment): string[] {\n return [...outputPlaces].filter(p => fragment.isColoured(p.name)).map(p => p.name);\n}\n\n/**\n * Name-layer successors of one firing. Ordinary passes the layer through; Mint\n * stamps one globally-fresh symbol into the coloured outputs of this branch (one\n * symbol into several = same-mint siblings); Join yields one successor per\n * enabling symbol (none ⇒ the join is name-disabled); Consume (EXTENDED, NU-051)\n * yields one successor per resident symbol of the single coloured input (count 1,\n * so NONE is dropped), threading that symbol into every coloured output (relay)\n * or dropping it (drain, no coloured output).\n */\nfunction nameSuccessors(\n role: Role,\n names: NameMarking,\n outputPlaces: ReadonlySet<Place<any>>,\n fragment: NameFragment,\n sym: { next: Sym },\n): NameMarking[] {\n switch (role.type) {\n case 'ordinary':\n return [names.copy()];\n case 'mint': {\n const colouredOut = colouredOutputs(outputPlaces, fragment);\n const nm = names.copy();\n if (colouredOut.length > 0) {\n const fresh = sym.next++;\n for (const p of colouredOut) nm.add(p, fresh, 1);\n }\n return [nm];\n }\n case 'join': {\n const result: NameMarking[] = [];\n for (const s of enablingSymbols(names, role.colouredIn)) {\n const nm = names.copy();\n for (const [p, req] of role.colouredIn) nm.remove(p, s, req);\n result.push(nm);\n }\n return result;\n }\n case 'consume': {\n // Count is fixed at one, so every resident symbol satisfies the required\n // count — NO base-enabled firing is dropped. Emit EXACTLY ONE symbol per\n // coloured output (relay), keeping the name-layer total == base count.\n const colouredOut = colouredOutputs(outputPlaces, fragment);\n const result: NameMarking[] = [];\n for (const s of names.symbolsIn(role.colouredInput)) {\n const nm = names.copy();\n nm.remove(role.colouredInput, s, 1);\n for (const p of colouredOut) nm.add(p, s, 1);\n result.push(nm);\n }\n return result;\n }\n }\n}\n\n/**\n * Symbols that enable a join: present at the required multiplicity in EVERY\n * correlated input — the exactness core of NU-050 (a count-only check would\n * wrongly fire on two distinct names).\n */\nfunction enablingSymbols(names: NameMarking, colouredIn: ReadonlyArray<readonly [string, number]>): Sym[] {\n if (colouredIn.length === 0) return [];\n const [firstPlace, firstReq] = colouredIn[0]!;\n const result: Sym[] = [];\n for (const s of names.symbolsIn(firstPlace)) {\n if (names.countOf(firstPlace, s) < firstReq) continue;\n let ok = true;\n for (let i = 1; i < colouredIn.length; i++) {\n const [p, req] = colouredIn[i]!;\n if (names.countOf(p, s) < req) {\n ok = false;\n break;\n }\n }\n if (ok) result.push(s);\n }\n return result;\n}\n","/**\n * ν-net exact verification via the name-aware state-class-graph name-partition\n * quotient (NU-050, Route B). Bridges {@link NameStateClassGraph} to the\n * {@link SmtVerificationResult} verdict types.\n *\n * {@link verifyViaNameScg} returns `null` when the net is outside the supported\n * mint→matched-join fragment (the caller falls back to the SMT / Route A path);\n * otherwise an exact verdict when the symbolic graph closes, or `unknown` when it\n * truncates (the live correlation pool is unbounded).\n */\nimport type { PetriNet } from '../core/petri-net.js';\nimport type { Place } from '../core/place.js';\nimport type { EnvironmentPlace } from '../core/place.js';\nimport type { MarkingState } from './marking-state.js';\nimport type { EnvironmentAnalysisMode } from './analysis/environment-analysis-mode.js';\nimport { classify, type FragmentMode } from './analysis/name-fragment.js';\nimport type { PrioritySemantics } from './analysis/priority-semantics.js';\nimport { NameStateClassGraph } from './analysis/name-state-class-graph.js';\nimport type { SmtProperty } from './smt-property.js';\nimport type { Verdict } from './smt-verification-result.js';\n\nconst NOTE_EXACT =\n '\\nNote: ν-join correlation decided exactly via the state-class-graph name-partition ' +\n 'quotient — the symbolic graph closed, so the verdict is sound AND complete (no spurious ' +\n 'different-name counterexample; quiescence is name-aware), beyond the bounded-budget ' +\n 'fragment (NU-050, Route B).\\n';\n\nexport interface NuScgOutcome {\n readonly verdict: Verdict;\n readonly trace: MarkingState[];\n readonly transitions: string[];\n readonly note: string;\n readonly classCount: number;\n}\n\nexport function verifyViaNameScg(\n net: PetriNet,\n initial: MarkingState,\n property: SmtProperty,\n sinkPlaces: ReadonlySet<Place<any>>,\n environmentPlaces: Set<EnvironmentPlace<any>>,\n environmentMode: EnvironmentAnalysisMode,\n maxClasses: number,\n fragmentMode: FragmentMode,\n carrierPlaces: ReadonlySet<string>,\n prioritySemantics: PrioritySemantics,\n): NuScgOutcome | null {\n const fragment = classify(net, fragmentMode, carrierPlaces);\n if (fragment === null) return null;\n // We model no initial colour assignment, so coloured places must start empty.\n for (const p of initial.placesWithTokens()) {\n if (fragment.isColoured(p.name)) return null;\n }\n\n const scg = NameStateClassGraph.build(\n net, initial, fragment, maxClasses, environmentPlaces, environmentMode, prioritySemantics,\n );\n\n if (!scg.isComplete()) {\n return {\n verdict: {\n type: 'unknown',\n reason:\n `ν name-aware state-class graph truncated at ${maxClasses} classes — the live ` +\n 'correlation pool is not structurally bounded; reachability over unbounded fresh ' +\n 'names is undecidable (NU-050, Route B). Declare a budget place to bound the live ' +\n 'pool, or raise nuMaxClasses.',\n },\n trace: [],\n transitions: [],\n note: '',\n classCount: scg.classCount(),\n };\n }\n\n const violating = decide(scg, property, sinkPlaces);\n if (violating >= 0) {\n const [trace, transitions] = counterexamplePath(scg, violating);\n return { verdict: { type: 'violated' }, trace, transitions, note: NOTE_EXACT, classCount: scg.classCount() };\n }\n return {\n verdict: { type: 'proven', method: 'ν name-partition SCG (NU-050, Route B)', inductiveInvariant: null },\n trace: [],\n transitions: [],\n note: NOTE_EXACT,\n classCount: scg.classCount(),\n };\n}\n\n/** Returns a witnessing class index for a violation, or -1 if the property holds. */\nfunction decide(scg: NameStateClassGraph, property: SmtProperty, sinkPlaces: ReadonlySet<Place<any>>): number {\n const firstWhere = (pred: (i: number) => boolean): number => {\n for (let i = 0; i < scg.classCount(); i++) {\n if (pred(i)) return i;\n }\n return -1;\n };\n\n switch (property.type) {\n case 'place-bound':\n case 'branch-place-bound':\n return firstWhere(i => scg.markingOf(i).tokens(property.place) > property.bound);\n case 'unreachable':\n return firstWhere(i => {\n const m = scg.markingOf(i);\n for (const p of property.places) {\n if (!m.hasTokens(p)) return false;\n }\n return true;\n });\n case 'mutual-exclusion':\n return firstWhere(i => {\n const m = scg.markingOf(i);\n return m.hasTokens(property.p1) && m.hasTokens(property.p2);\n });\n case 'deadlock-free':\n return firstWhere(i => scg.successorsOf(i).length === 0 && !allTokensInSinks(scg.markingOf(i), sinkPlaces));\n case 'joined-or-dead-lettered':\n return firstWhere(i => scg.successorsOf(i).length === 0 && scg.markingOf(i).hasTokens(property.pending));\n }\n}\n\nfunction allTokensInSinks(m: MarkingState, sinks: ReadonlySet<Place<any>>): boolean {\n const sinkNames = new Set<string>();\n for (const s of sinks) sinkNames.add(s.name);\n for (const p of m.placesWithTokens()) {\n if (!sinkNames.has(p.name)) return false;\n }\n return true;\n}\n\n/** Shortest firing sequence from the initial class (0) to `target`. */\nfunction counterexamplePath(scg: NameStateClassGraph, target: number): [MarkingState[], string[]] {\n const n = scg.classCount();\n const parent = new Array<number>(n).fill(-1);\n const via = new Array<string>(n).fill('');\n const visited = new Array<boolean>(n).fill(false);\n visited[0] = true;\n const queue: number[] = [0];\n while (queue.length > 0) {\n const u = queue.shift()!;\n if (u === target) break;\n for (const e of scg.edges) {\n if (e.from === u && !visited[e.to]) {\n visited[e.to] = true;\n parent[e.to] = u;\n via[e.to] = e.transitionName;\n queue.push(e.to);\n }\n }\n }\n const chain: number[] = [];\n for (let cur = target; cur !== -1; cur = parent[cur]!) {\n chain.push(cur);\n }\n chain.reverse();\n const markings = chain.map(i => scg.markingOf(i));\n const transitions = chain.slice(1).map(i => via[i]!);\n return [markings, transitions];\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, computePSemiflows, 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 { buildColouredPlan, encodeColoured, type ColouredPlan } from './z3/name-coloured-encoder.js';\nimport { verifyViaNameScg } from './nu-scg-verifier.js';\nimport type { FragmentMode } from './analysis/name-fragment.js';\nimport type { PrioritySemantics } from './analysis/priority-semantics.js';\nimport { decode } from './z3/counterexample-decoder.js';\nimport { requireOutputProducingActions } from '../core/internal/output-action-check.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 readonly _budgetPlaces = new Set<string>();\n private _environmentMode: EnvironmentAnalysisMode = alwaysAvailable();\n private _timeoutMs: number = 60_000;\n private _nuMaxClasses: number = 100_000;\n private _fragmentMode: FragmentMode = 'base';\n private readonly _carrierPlaces = new Set<string>();\n private _prioritySemantics: PrioritySemantics = 'none';\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 /**\n * Declares ν-net budget places (NU-040): places whose token count bounds the\n * live correlation pool (they gate fresh-name minting). Declaring at least one\n * places the net in the decidable bounded fragment, so reachability-safety\n * properties over its ν-joins are verified (the matched transitions are\n * over-approximated). Without any budget place, a net that mints fresh names\n * is treated as unbounded and the verifier returns `unknown` (NU-050).\n */\n budgetPlaces(...places: Place<any>[]): this {\n for (const p of places) this._budgetPlaces.add(p.name);\n return this;\n }\n\n timeout(ms: number): this {\n this._timeoutMs = ms;\n return this;\n }\n\n /**\n * Sets the class-count cap for the ν-aware state-class-graph analysis (NU-050,\n * Route B). When the symbolic name-aware graph would exceed this, the analysis\n * truncates and the verdict is `unknown` (the live correlation pool is not\n * structurally bounded). Default 100_000.\n */\n nuMaxClasses(max: number): this {\n this._nuMaxClasses = max;\n return this;\n }\n\n /**\n * Selects the ν-net coloured-place fragment for Route B (NU-051). `base`\n * (default) admits the shipped mint → matched-join fragment only; `extended`\n * additionally admits the opt-in coloured-consumer (drain/relay) role and the\n * declared {@link carrierPlaces}. When `extended` is requested but the net\n * falls outside the coloured-consumer fragment, Route B declines and a short\n * note is appended to the report before falling back to the sound\n * over-approximation.\n */\n fragmentMode(mode: FragmentMode): this {\n this._fragmentMode = mode;\n return this;\n }\n\n /**\n * Declares ν-net *carrier* places (NU-051, EXTENDED only): intermediate places\n * that carry a fresh name from the minting fork onward to a ν-join input. Under\n * {@link fragmentMode} `extended` they are unioned into the coloured set so the\n * existing mint co-mints one fresh name into all of them; under `base` they are\n * ignored. Accumulating. Throws if a declared place is not in the net — a\n * mistyped carrier name would let two fork branches mint independent names, so\n * the join never becomes name-enabled and the verifier would otherwise report a\n * confident false deadlock; it must surface, never silently proceed.\n */\n carrierPlaces(...places: Place<any>[]): this {\n for (const p of places) {\n if (![...this.net.places].some(np => np.name === p.name)) {\n throw new Error(`declared carrier place '${p.name}' not in the net`);\n }\n this._carrierPlaces.add(p.name);\n }\n return this;\n }\n\n /**\n * Selects how the Route-B name-aware analyzer treats transition priority\n * (NU-052). Defaults to `'none'` (the priority-blind over-approximation).\n * `'conflict'` models the executor's conflict-only priority resolution, so a\n * lower-priority transition pre-empted by a conflicting, no-later-ready,\n * strictly-higher-priority one is not explored — removing spurious\n * dead-letter-drain stalls the eager, priority-ordered executor never produces.\n */\n prioritySemantics(semantics: PrioritySemantics): this {\n this._prioritySemantics = semantics;\n return this;\n }\n\n /**\n * Runs the verification pipeline.\n *\n * @throws Error if the net violates CORE-043 — verification rejects the same nets execution rejects.\n */\n async verify(): Promise<SmtVerificationResult> {\n requireOutputProducingActions(this.net);\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 // ν-net awareness (NU-040, NU-050). A transition with a match spec joins by\n // name equality; the untimed encoder over-approximates that (name equality\n // assumed satisfiable). Sound for reachability-safety bounds (proven holds —\n // the real net fires strictly fewer joins) but NOT for quiescence-based\n // properties, which name-blind firing distorts. `applyNuGuard` turns those\n // cases into unknown.\n const hasMatch = [...this.net.transitions].some(t => t.matchSpec !== null);\n const nuBounded = this._budgetPlaces.size > 0;\n\n // ν-net Route B (NU-050): the name-aware state-class-graph name-partition\n // quotient decides ν-join correlation EXACTLY — including name×time and\n // quiescence — without a budget. It \"fills the gaps\" the SMT / Route A path\n // cannot answer exactly: quiescence properties on a ν-net, and unbudgeted\n // reachability-safety. Budgeted, untimed reachability-safety in Route A's\n // fragment stays on Route A below (this trigger is false there). If the net is\n // outside the supported fragment, verifyViaNameScg returns null and we fall\n // through to the existing pipeline (which applies the sound unknown downgrade).\n if (hasMatch && (!isReachabilitySafety(this._property) || !nuBounded)) {\n const outcome = verifyViaNameScg(\n this.net, this._initialMarking, this._property, this._sinkPlaces,\n this._environmentPlaces, this._environmentMode, this._nuMaxClasses,\n this._fragmentMode, this._carrierPlaces, this._prioritySemantics,\n );\n // Route B truncating to unknown on a bounded quiescence ν-net is not the\n // final word: defer to the scalable Route A coloured IC3/PDR encoder\n // (NU-053) below instead of returning unknown here.\n const deferToRouteA =\n outcome !== null &&\n outcome.verdict.type === 'unknown' &&\n !isReachabilitySafety(this._property) &&\n nuBounded;\n if (outcome !== null && !deferToRouteA) {\n report.push('=== ν-net Route B: name-aware state-class graph (NU-050) ===');\n report.push(` Name-partition state classes: ${outcome.classCount}`);\n report.push(outcome.note);\n if (outcome.transitions.length > 0) {\n report.push(` Counterexample trace: ${outcome.trace.length} states, ${outcome.transitions.length} transitions`);\n }\n return buildResult(\n outcome.verdict, report.join('\\n'), [], [], outcome.trace, outcome.transitions,\n performance.now() - start,\n {\n places: [...this.net.places].length,\n transitions: [...this.net.transitions].length,\n invariantsFound: 0,\n structuralResult: 'n/a (ν name-partition SCG)',\n },\n );\n } else if (deferToRouteA) {\n report.push(\n 'ν-net Route B inconclusive (name-partition truncated); deferring to ' +\n 'Route A coloured IC3/PDR (NU-053).',\n );\n }\n // EXTENDED was requested but the net is outside the coloured-consumer\n // fragment (classify declined). Surface a short note instead of a silent\n // cliff, then verify via the sound over-approximation below (NU-051, §5\n // diagnosability).\n if (this._fragmentMode === 'extended' && !deferToRouteA) {\n report.push(\n 'ν-net Route B (EXTENDED) declined: net outside coloured-consumer fragment ' +\n '(a coloured place consumed count != 1 or by multiple inputs, carries a ' +\n 'reset/read/inhibitor arc, or a join re-mints a coloured place); verified via ' +\n 'sound over-approximation instead.',\n );\n }\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 !hasMatch &&\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 // P-semiflows (non-negative conservation laws) bound the simultaneously-live\n // colour count that sets the name-coloured encoder's slot count `k` (see\n // buildColouredPlan / colourSlotBound).\n const semiflows = computePSemiflows(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 // ν-net exact refinement (NU-050 #1, Route A). For a budget-bounded ν-net in\n // the supported fragment, encode names as a finite colour set (k = the declared\n // budget) with exact same-colour join matching, instead of the name-blind\n // over-approximation — this rules out spurious counterexamples that would equate\n // two distinct names. Reachability-safety AND quiescence (NU-053) properties are\n // both routed here; a net outside the fragment keeps the flat encoding.\n const colouredPlan: ColouredPlan | null =\n hasMatch && nuBounded\n ? buildColouredPlan(\n this.net, flatNet, this._initialMarking, this._budgetPlaces,\n this._fragmentMode, this._carrierPlaces, semiflows,\n )\n : null;\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 let encoding;\n if (colouredPlan != null) {\n report.push(\n ` ν-encoding: name-coloured (exact within budget k=${colouredPlan.k}; ` +\n `${colouredPlan.coloured.length} coloured place(s))`,\n );\n encoding = encodeColoured(runner.ctx, runner.fp, colouredPlan, flatNet, this._initialMarking, this._property, invariants, this._sinkPlaces);\n if (encoding == null) {\n // The property names a place that does not resolve in the net (e.g. a\n // typo'd bound/pending place). Emitting the encoding anyway would certify\n // a vacuous PROVEN; refuse and report Unknown so a mis-named place never\n // silently certifies.\n const reason =\n 'property names a place that does not resolve in the net; refusing to certify ' +\n '(the encoding would be vacuously proven)';\n report.push(' Status: UNKNOWN (unresolved property place)\\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 } else {\n encoding = encode(runner.ctx, runner.fp, flatNet, this._initialMarking, this._property, invariants, this._sinkPlaces);\n }\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 this.applyNuGuard(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 ), hasMatch, nuBounded, colouredPlan != null);\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 this.applyNuGuard(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 ), hasMatch, nuBounded, colouredPlan != null);\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 * ν-net soundness guard (NU-040, NU-050). Applied only when the net contains\n * match (ν-join) transitions, and only to a proven/violated verdict (an\n * existing unknown is left as-is).\n *\n * - Quiescence-based properties (deadlock / joined-or-dead-lettered): the\n * name-blind over-approximation over-fires joins, so it sees fewer quiescent\n * states and may miss a real stranded marking — downgraded to unknown\n * (exact quiescence reasoning is deferred to the SCG name-partition quotient).\n * - Reachability-safety with unbounded fresh names (no budget declared):\n * reachability over unbounded fresh names is undecidable — unknown.\n * - Bounded reachability-safety in the name-coloured fragment (`exact`): name\n * equality is encoded exactly via bounded name-colouring, so the verdict is\n * sound *and* complete within the budget — no spurious different-name\n * counterexample. The verdict is kept and the exact-path note is appended.\n * - Bounded reachability-safety outside that fragment: `proven` is sound; a\n * `violated` may be spurious — the verdict is kept and the over-approximation\n * caveat is appended to the report.\n */\n private applyNuGuard(\n result: SmtVerificationResult,\n hasMatch: boolean,\n nuBounded: boolean,\n exact: boolean,\n ): SmtVerificationResult {\n if (!hasMatch || result.verdict.type === 'unknown') return result;\n // Exact path FIRST (NU-050 #1 / NU-053, Route A): name equality is encoded\n // exactly via bounded name-colouring, so the verdict is sound AND complete\n // within the budget bound — no spurious different-name counterexample. This\n // holds for reachability-safety AND quiescence (deadlock / joined-or-dead-\n // lettered), so an exact coloured plan keeps its verdict for quiescence too;\n // the colour-aware deadlock encoding does not over-fire joins.\n if (exact) {\n const note =\n '\\nNote: ν-join name equality is encoded exactly via bounded name-colouring ' +\n '(k = budget); the verdict is sound and complete within the budget bound — no spurious ' +\n 'different-name counterexample (NU-050 #1 / NU-053).\\n';\n return { ...result, report: result.report + note };\n }\n if (!isReachabilitySafety(this._property)) {\n return downgradeToUnknown(\n result,\n 'ν-matching transitions present and the property depends on quiescence ' +\n '(deadlock / joined-or-dead-lettered); the name-blind over-approximation cannot ' +\n 'decide it soundly — deferred to the exact ν-analysis (NU-050)',\n );\n }\n if (!nuBounded) {\n return downgradeToUnknown(\n result,\n 'ν-matching transitions present with unbounded fresh names (no budget place declared ' +\n 'via budgetPlaces(...)); reachability over unbounded fresh names is undecidable ' +\n '(NU-040) — declare the budget place(s) that gate minting to verify within the ' +\n 'bounded fragment',\n );\n }\n // Bounded reachability-safety outside the name-coloured fragment: the matched\n // transitions are over-approximated, so a violated may be spurious.\n const note =\n \"\\nNote: matched (ν-join) transitions are over-approximated (name equality assumed \" +\n \"satisfiable). 'proven' is sound; a 'violated' counterexample may be spurious pending \" +\n 'the exact ν-analysis (NU-050).\\n';\n return { ...result, report: result.report + note };\n }\n}\n\n/**\n * Whether a property is a reachability-safety property — one whose violation is\n * a reachable bad marking. For these the matched-transition over-approximation\n * is sound for `proven`. Quiescence-based properties (deadlock,\n * joined-or-dead-lettered) are not: their violation involves the absence of\n * enabled transitions, which the name-blind over-approximation distorts (NU-050).\n */\nfunction isReachabilitySafety(property: SmtProperty): boolean {\n switch (property.type) {\n case 'place-bound':\n case 'branch-place-bound':\n case 'mutual-exclusion':\n case 'unreachable':\n return true;\n case 'deadlock-free':\n case 'joined-or-dead-lettered':\n return false;\n }\n}\n\nfunction downgradeToUnknown(result: SmtVerificationResult, reason: string): SmtVerificationResult {\n return {\n ...result,\n verdict: { type: 'unknown', reason },\n report: result.report + `\\nDowngraded to UNKNOWN: ${reason}\\n`,\n discoveredInvariants: [],\n counterexampleTrace: [],\n counterexampleTransitions: [],\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,IAAI,QAAQ,CAAC;AACpC;AAGO,SAAS,OAAO,UAAyB;AAC9C,MAAI,SAAS,SAAS,GAAG;AACvB,UAAM,IAAI,MAAM,kCAAkC;AAAA,EACpD;AACA,SAAO,EAAE,MAAM,OAAO,SAAS;AACjC;AAGO,SAAS,aAAa,QAA8B;AACzD,SAAO,IAAI,GAAG,OAAO,IAAI,QAAQ,CAAC;AACpC;AAGO,SAAS,SAAS,GAAyB;AAChD,SAAO,EAAE,MAAM,SAAS,OAAO,EAAE;AACnC;AAGO,SAA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