libpetri 5.1.0 → 6.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.
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/core/place.ts","../src/core/in.ts","../src/core/out.ts","../src/core/transition-action.ts","../src/core/transition.ts","../src/core/interface.ts","../src/core/instance.ts","../src/verification/programming-error.ts","../src/core/internal/code-point-order.ts","../src/verification/marking-state.ts","../src/verification/count-clause.ts","../src/verification/smt-property.ts","../src/verification/rest-set.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/z3-process.ts","../src/verification/z3/smt-text.ts","../src/verification/z3/spacer-runner.ts","../src/verification/z3/smt-encoder.ts","../src/verification/z3/certificate-checker.ts","../src/verification/z3/linear-bound.ts","../src/verification/encoding/flat-net.ts","../src/verification/z3/abstract-replayer.ts","../src/verification/graph-decision.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/scg-verifier.ts","../src/verification/z3/counterexample-decoder.ts","../src/verification/z3/state-equation-query.ts","../src/verification/z3/trap-refinement.ts","../src/verification/z3/invariant-synthesis.ts","../src/verification/z3/parikh-search.ts","../src/verification/z3/state-equation-phase.ts","../src/verification/z3/bounded-run.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","../src/core/compose-bindings.ts","../src/core/internal/subnet-rewriter.ts","../src/core/fusion-set.ts","../src/core/petri-net.ts","../src/verification/verification-harness.ts","../src/core/subnet-def.ts"],"sourcesContent":["/**\n * A typed place in the Petri Net that holds tokens of a specific type.\n *\n * Places are the \"state containers\" of a Petri net. They hold tokens that\n * represent data or resources flowing through the net.\n *\n * Places use name-based equality (matching Java record semantics).\n * Internally use `Map<string, ...>` keyed by `place.name` for O(1) lookups.\n */\nexport interface Place<T> {\n readonly name: string;\n /** Phantom field to carry the type parameter. Never set at runtime. */\n readonly _phantom?: T;\n}\n\n/**\n * An environment place that accepts external token injection.\n * Wraps a regular Place and marks it for external event injection.\n */\nexport interface EnvironmentPlace<T> {\n readonly place: Place<T>;\n}\n\n/** Creates a typed place. */\nexport function place<T>(name: string): Place<T> {\n return { name };\n}\n\n/** Creates an environment place (external event injection point). */\nexport function environmentPlace<T>(name: string): EnvironmentPlace<T> {\n return { place: place<T>(name) };\n}\n","import type { Place } from './place.js';\n\n/**\n * Input specification with cardinality. Purely structural (IO-006): cardinality\n * determines how many tokens to consume; there is no per-token predicate.\n *\n * Conditional token selection is modeled with multiple conflicting transitions\n * and XOR-on-input semantics rather than a predicate coupled to the enablement\n * check.\n *\n * Inputs are always AND-joined (all must be satisfied to enable transition).\n * XOR on inputs is modeled via multiple transitions (conflict).\n */\nexport type In = InOne | InExactly | InAll | InAtLeast;\n\nexport interface InOne<T = any> {\n readonly type: 'one';\n readonly place: Place<T>;\n}\n\nexport interface InExactly<T = any> {\n readonly type: 'exactly';\n readonly place: Place<T>;\n readonly count: number;\n}\n\nexport interface InAll<T = any> {\n readonly type: 'all';\n readonly place: Place<T>;\n}\n\nexport interface InAtLeast<T = any> {\n readonly type: 'at-least';\n readonly place: Place<T>;\n readonly minimum: number;\n}\n\n// ==================== Factory Functions ====================\n\n/** Consume exactly 1 token (standard CPN semantics). */\nexport function one<T>(place: Place<T>): InOne<T> {\n return { type: 'one', place };\n}\n\n/** Consume exactly N tokens (batching). */\nexport function exactly<T>(count: number, place: Place<T>): InExactly<T> {\n if (count < 1) {\n throw new Error(`count must be >= 1, got: ${count}`);\n }\n return { type: 'exactly', place, count };\n}\n\n/** Consume all available tokens (must be 1+). */\nexport function all<T>(place: Place<T>): InAll<T> {\n return { type: 'all', place };\n}\n\n/** Wait for N+ tokens, consume all when enabled. */\nexport function atLeast<T>(minimum: number, place: Place<T>): InAtLeast<T> {\n if (minimum < 1) {\n throw new Error(`minimum must be >= 1, got: ${minimum}`);\n }\n return { type: 'at-least', place, minimum };\n}\n\n// ==================== Helper Functions ====================\n\n/** Returns the minimum number of tokens required to enable. */\nexport function requiredCount(spec: In): number {\n switch (spec.type) {\n case 'one': return 1;\n case 'exactly': return spec.count;\n case 'all': return 1;\n case 'at-least': return spec.minimum;\n }\n}\n\n/**\n * Returns the actual number of tokens to consume given the available count.\n * - One: always consumes 1\n * - Exactly: always consumes exactly count\n * - All: consumes all available\n * - AtLeast: consumes all available (when enabled, i.e., >= minimum)\n */\nexport function consumptionCount(spec: In, available: number): number {\n if (available < requiredCount(spec)) {\n throw new Error(\n `Cannot consume from '${spec.place.name}': available=${available}, required=${requiredCount(spec)}`\n );\n }\n switch (spec.type) {\n case 'one': return 1;\n case 'exactly': return spec.count;\n case 'all': return available;\n case 'at-least': return available;\n }\n}\n","import type { Place } from './place.js';\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 *\n * A spec names **places, not counts**. Validation ([IO-015]) compares the SET of\n * places an action wrote against the branches' claims, so an action that deposits\n * several tokens into one named place is accepted — and every analysis that\n * enumerates branches ({@link enumerateBranches}: the state-class graph, the SMT\n * encoding, the ν fragment check) models exactly one token per named place. Such a\n * firing therefore does more than the analyses explore, in the direction that can\n * make a `proven` false. The executors report it once per transition as a `WARN`\n * log-message ([IO-016]); a net meant to be verified should produce one token per\n * named place and express multiplicity in its topology.\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 ([IO-016]).\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 *\n * A branch is a **set** of places: it says which places receive a token, not how\n * many tokens each receives. Analyses built on it (the state-class graph's virtual\n * transitions, the flattener's post vectors, the ν fragment check) deposit one token\n * per place of the chosen branch. An action that writes `n > 1` tokens to a place\n * its branch names once is accepted by [IO-015] but is outside what those analyses\n * explore — a sound under-approximation for safety only when it never happens, which\n * is why the executors warn about it ([IO-016] AC4).\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 './place.js';\nimport type { ArcInhibitor, ArcRead, ArcReset } from './arc.js';\nimport type { In } from './in.js';\nimport type { MatchSpec } from './match-spec.js';\nimport type { Out, OutTimeout } from './out.js';\nimport type { Timing } from './timing.js';\nimport type { TransitionAction } from './transition-action.js';\nimport { passthrough } from './transition-action.js';\nimport { immediate } from './timing.js';\nimport { allPlaces } from './out.js';\n\n/** @internal Symbol key restricting construction to the builder. */\nconst TRANSITION_KEY = Symbol('Transition.internal');\n\n/** @internal Shared empty correspondence for the common (identity) case. */\nconst EMPTY_PLACE_ALIAS: ReadonlyMap<string, Place<any>> = new Map();\n\n/**\n * A transition in the Time Petri Net that transforms tokens.\n *\n * Transitions use identity-based equality (===) — each instance is unique\n * regardless of name. The name is purely a label for display/debugging/export.\n */\nexport class Transition {\n readonly name: string;\n readonly inputSpecs: readonly In[];\n readonly outputSpec: Out | null;\n readonly inhibitors: readonly ArcInhibitor[];\n readonly reads: readonly ArcRead[];\n readonly resets: readonly ArcReset[];\n readonly timing: Timing;\n readonly actionTimeout: OutTimeout | null;\n readonly action: TransitionAction;\n readonly priority: number;\n\n /**\n * ν-net join correlation: a subset of `inputSpecs` that must be correlated by\n * name equality on firing (spec NU-020). `null` for ordinary transitions.\n */\n readonly matchSpec: MatchSpec | null;\n\n /**\n * Per-transition **declared → actual** place correspondence (per\n * **MOD-031**), keyed by the author-original declared place **name** →\n * actual composed place. Empty for a hand-written or directly-composed\n * ([MOD-025]) transition (identity). Populated by the subnet rewriter after\n * instantiation ([MOD-010]) / port binding ([MOD-020]) so an action that\n * hardcodes a declared place constant resolves to the composed place via\n * {@link import('./transition-context.js').TransitionContext}. Consumed only\n * by the action-facing context I/O — never by enablement, firing, the\n * verifier, the exporter, or events (so [MOD-023] is unaffected).\n */\n readonly placeAlias: ReadonlyMap<string, Place<any>>;\n\n private readonly _inputPlaces: ReadonlySet<Place<any>>;\n private readonly _readPlaces: ReadonlySet<Place<any>>;\n private readonly _outputPlaces: ReadonlySet<Place<any>>;\n\n /** @internal Use {@link Transition.builder} to create instances. */\n constructor(\n key: symbol,\n name: string,\n inputSpecs: readonly In[],\n outputSpec: Out | null,\n inhibitors: readonly ArcInhibitor[],\n reads: readonly ArcRead[],\n resets: readonly ArcReset[],\n timing: Timing,\n action: TransitionAction,\n priority: number,\n placeAlias: ReadonlyMap<string, Place<any>> = EMPTY_PLACE_ALIAS,\n matchSpec: MatchSpec | null = null,\n ) {\n if (key !== TRANSITION_KEY) throw new Error('Use Transition.builder() to create instances');\n this.name = name;\n this.inputSpecs = inputSpecs;\n this.outputSpec = outputSpec;\n this.inhibitors = inhibitors;\n this.reads = reads;\n this.resets = resets;\n this.timing = timing;\n this.actionTimeout = findTimeout(outputSpec);\n this.action = action;\n this.priority = priority;\n this.placeAlias = placeAlias.size === 0 ? EMPTY_PLACE_ALIAS : placeAlias;\n this.matchSpec = matchSpec;\n\n // Precompute place sets\n const inputPlaces = new Set<Place<any>>();\n for (const spec of inputSpecs) {\n inputPlaces.add(spec.place);\n }\n this._inputPlaces = inputPlaces;\n\n const readPlaces = new Set<Place<any>>();\n for (const r of reads) {\n readPlaces.add(r.place);\n }\n this._readPlaces = readPlaces;\n\n const outputPlaces = new Set<Place<any>>();\n if (outputSpec !== null) {\n for (const p of allPlaces(outputSpec)) {\n outputPlaces.add(p);\n }\n }\n this._outputPlaces = outputPlaces;\n }\n\n /** Returns set of input places — consumed tokens. */\n inputPlaces(): ReadonlySet<Place<any>> {\n return this._inputPlaces;\n }\n\n /** Returns set of read places — context tokens, not consumed. */\n readPlaces(): ReadonlySet<Place<any>> {\n return this._readPlaces;\n }\n\n /** Returns set of output places — where tokens are produced. */\n outputPlaces(): ReadonlySet<Place<any>> {\n return this._outputPlaces;\n }\n\n /** Returns true if this transition has an action timeout. */\n hasActionTimeout(): boolean {\n return this.actionTimeout !== null;\n }\n\n toString(): string {\n return `Transition[${this.name}]`;\n }\n\n static builder(name: string): TransitionBuilder {\n return new TransitionBuilder(name);\n }\n}\n\nexport class TransitionBuilder {\n private readonly _name: string;\n private readonly _inputSpecs: In[] = [];\n private _outputSpec: Out | null = null;\n private readonly _inhibitors: ArcInhibitor[] = [];\n private readonly _reads: ArcRead[] = [];\n private readonly _resets: ArcReset[] = [];\n private _timing: Timing = immediate();\n private _action: TransitionAction = passthrough();\n private _priority = 0;\n private _placeAlias: ReadonlyMap<string, Place<any>> = EMPTY_PLACE_ALIAS;\n private _matchSpec: MatchSpec | null = null;\n\n constructor(name: string) {\n this._name = name;\n }\n\n /** Add input specifications with cardinality. */\n inputs(...specs: In[]): this {\n this._inputSpecs.push(...specs);\n return this;\n }\n\n /** Set the output specification (composite AND/XOR structure). */\n outputs(spec: Out): this {\n this._outputSpec = spec;\n return this;\n }\n\n /** Add inhibitor arc. */\n inhibitor(place: Place<any>): this {\n this._inhibitors.push({ type: 'inhibitor', place });\n return this;\n }\n\n /** Add inhibitor arcs. */\n inhibitors(...places: Place<any>[]): this {\n for (const p of places) {\n this._inhibitors.push({ type: 'inhibitor', place: p });\n }\n return this;\n }\n\n /** Add read arc. */\n read(place: Place<any>): this {\n this._reads.push({ type: 'read', place });\n return this;\n }\n\n /** Add read arcs. */\n reads(...places: Place<any>[]): this {\n for (const p of places) {\n this._reads.push({ type: 'read', place: p });\n }\n return this;\n }\n\n /** Add reset arc. */\n reset(place: Place<any>): this {\n this._resets.push({ type: 'reset', place });\n return this;\n }\n\n /** Add reset arcs. */\n resets(...places: Place<any>[]): this {\n for (const p of places) {\n this._resets.push({ type: 'reset', place: p });\n }\n return this;\n }\n\n /** Set timing specification. */\n timing(timing: Timing): this {\n this._timing = timing;\n return this;\n }\n\n /** Set the transition action. */\n action(action: TransitionAction): this {\n this._action = action;\n return this;\n }\n\n /** Set the priority (higher fires first). */\n priority(priority: number): this {\n this._priority = priority;\n return this;\n }\n\n /**\n * Sets the ν-net join correlation spec: the named input places must be\n * correlated by name equality on firing (spec NU-020). Every place referenced\n * by the spec must also be declared as an input.\n */\n match(spec: MatchSpec): this {\n this._matchSpec = spec;\n return this;\n }\n\n /**\n * Sets the per-transition declared→actual place correspondence (per\n * **MOD-031**). Populated by the subnet rewriter during the compose-time\n * rewrite; not normally called by hand-written nets, whose correspondence is\n * the identity (empty map).\n */\n placeAlias(alias: ReadonlyMap<string, Place<any>>): this {\n this._placeAlias = alias;\n return this;\n }\n\n build(): Transition {\n // Validate ForwardInput references\n if (this._outputSpec !== null) {\n const inputPlaceNames = new Set(this._inputSpecs.map(s => s.place.name));\n for (const fi of findForwardInputs(this._outputSpec)) {\n if (!inputPlaceNames.has(fi.from.name)) {\n throw new Error(\n `Transition '${this._name}': ForwardInput references non-input place '${fi.from.name}'`\n );\n }\n }\n }\n\n // Validate MatchSpec correlates only declared input places (NU-020).\n if (this._matchSpec !== null) {\n const inputPlaceNames = new Set(this._inputSpecs.map(s => s.place.name));\n for (const k of this._matchSpec.keys) {\n if (!inputPlaceNames.has(k.place.name)) {\n throw new Error(\n `Transition '${this._name}': MatchSpec correlates non-input place '${k.place.name}'`\n );\n }\n }\n }\n\n return new Transition(\n TRANSITION_KEY,\n this._name,\n [...this._inputSpecs],\n this._outputSpec,\n [...this._inhibitors],\n [...this._reads],\n [...this._resets],\n this._timing,\n this._action,\n this._priority,\n this._placeAlias,\n this._matchSpec,\n );\n }\n}\n\n/** Recursively searches the output spec for a Timeout node. */\nfunction findTimeout(out: Out | null): OutTimeout | null {\n if (out === null) return null;\n switch (out.type) {\n case 'timeout': return out;\n case 'and':\n case 'xor':\n for (const child of out.children) {\n const found = findTimeout(child);\n if (found !== null) return found;\n }\n return null;\n case 'place':\n case 'forward-input':\n return null;\n }\n}\n\n/** Recursively finds all ForwardInput nodes in the output spec. */\nfunction findForwardInputs(out: Out): Array<{ from: Place<any>; to: Place<any> }> {\n switch (out.type) {\n case 'forward-input':\n return [{ from: out.from, to: out.to }];\n case 'and':\n case 'xor':\n return out.children.flatMap(findForwardInputs);\n case 'timeout':\n return findForwardInputs(out.child);\n case 'place':\n return [];\n }\n}\n","import type { Place } from './place.js';\nimport type { Transition } from './transition.js';\n\n/**\n * Advisory direction metadata for an interface place.\n *\n * Per **MOD-004**, direction is metadata only — it does NOT constrain arc flow\n * at runtime. Token movement is governed by arcs declared per CORE-030..CORE-035.\n */\nexport type PortDirection = 'input' | 'output' | 'inout';\n\n/**\n * A typed interface place exposed for composition, per **MOD-003**.\n *\n * Direction is advisory metadata only (per **MOD-004**); the underlying\n * `Place<T>` reference is what is rewired at compose time.\n */\nexport interface Port<T = unknown> {\n /** Port name, unique within the {@link Interface}. */\n readonly name: string;\n /** Direction (advisory). */\n readonly direction: PortDirection;\n /** The body place exposed by this port. */\n readonly place: Place<T>;\n}\n\n/**\n * An interface transition exposed for synchronous fusion with a caller-side\n * transition, per **MOD-005**.\n *\n * The only present variant in this scaffolding is the synchronous channel.\n * The interface is left structurally open for future channel kinds without\n * breaking existing pattern matches on `name`/`transition`.\n */\nexport interface Channel {\n /** Channel name, unique within the channel namespace. */\n readonly name: string;\n /** The body transition exposed by this channel. */\n readonly transition: Transition;\n}\n\n/** @internal Symbol key restricting construction to the builder. */\nconst INTERFACE_KEY = Symbol('Interface.internal');\n\n/**\n * Immutable declaration of a subnet's **interface**: the set of {@link Port}\n * (interface places) and {@link Channel} (interface transitions) exposed for\n * composition with an enclosing net.\n *\n * Specified by `spec/11-modular-composition.md` requirements **MOD-003**\n * (port declaration) and **MOD-005** (channel declaration). Validation rules\n * per **MOD-006** are enforced by `SubnetDef.builder()` at subnet build\n * time; this class itself enforces only port/channel name uniqueness within\n * its respective namespaces (used both by `SubnetDef` and by hand-built\n * interfaces fed into `SubnetDef.fromNet`).\n */\nexport class Interface {\n readonly ports: ReadonlyMap<string, Port<unknown>>;\n readonly channels: ReadonlyMap<string, Channel>;\n\n /** @internal Use {@link Interface.builder} to create instances. */\n constructor(\n key: symbol,\n ports: ReadonlyMap<string, Port<unknown>>,\n channels: ReadonlyMap<string, Channel>,\n ) {\n if (key !== INTERFACE_KEY) throw new Error('Use Interface.builder() to create instances');\n this.ports = ports;\n this.channels = channels;\n }\n\n /** Looks up a port by name. Returns undefined when absent. */\n port<T = unknown>(name: string): Port<T> | undefined {\n return this.ports.get(name) as Port<T> | undefined;\n }\n\n /** Looks up a channel by name. Returns undefined when absent. */\n channel(name: string): Channel | undefined {\n return this.channels.get(name);\n }\n\n /**\n * Looks up a port by name and returns its underlying place, narrowed to\n * `Place<T>`. Returns undefined when the port does not exist.\n *\n * Note: TypeScript erases generics at runtime, so unlike Java's\n * `portPlaceAs(name, Class<T>)` this method cannot verify the token type at\n * runtime — the caller is trusted to supply the correct `T`. Per **MOD-022**,\n * type compatibility is enforced at compile time only in TypeScript.\n */\n placeAs<T>(name: string): Place<T> | undefined {\n const p = this.ports.get(name);\n if (p === undefined) return undefined;\n return p.place as Place<T>;\n }\n\n static builder(): InterfaceBuilder {\n return new InterfaceBuilder();\n }\n}\n\nexport class InterfaceBuilder {\n private readonly _ports = new Map<string, Port<unknown>>();\n private readonly _channels = new Map<string, Channel>();\n\n /** Add a pre-built port (rejects duplicate names). */\n port(port: Port<unknown>): this {\n if (this._ports.has(port.name)) {\n throw new Error(`Duplicate port name: '${port.name}'`);\n }\n this._ports.set(port.name, port);\n return this;\n }\n\n /** Add an input port (advisory direction). */\n inputPort<T>(name: string, place: Place<T>): this {\n return this.port({ name, direction: 'input', place: place as Place<unknown> });\n }\n\n /** Add an output port (advisory direction). */\n outputPort<T>(name: string, place: Place<T>): this {\n return this.port({ name, direction: 'output', place: place as Place<unknown> });\n }\n\n /** Add an in-out port (advisory direction). */\n inoutPort<T>(name: string, place: Place<T>): this {\n return this.port({ name, direction: 'inout', place: place as Place<unknown> });\n }\n\n /** Add a pre-built channel (rejects duplicate names). */\n channel(channel: Channel): this;\n /** Declare a synchronous channel by name + transition (rejects duplicate names). */\n channel(name: string, transition: Transition): this;\n channel(channelOrName: Channel | string, transition?: Transition): this {\n const ch: Channel = typeof channelOrName === 'string'\n ? { name: channelOrName, transition: transition! }\n : channelOrName;\n if (this._channels.has(ch.name)) {\n throw new Error(`Duplicate channel name: '${ch.name}'`);\n }\n this._channels.set(ch.name, ch);\n return this;\n }\n\n /** @internal Bulk-add ports already validated by the caller. */\n portsAll(ports: Iterable<Port<unknown>>): this {\n for (const p of ports) this.port(p);\n return this;\n }\n\n /** @internal Bulk-add channels already validated by the caller. */\n channelsAll(channels: Iterable<Channel>): this {\n for (const c of channels) this.channel(c);\n return this;\n }\n\n build(): Interface {\n // Freeze maps by handing them off as ReadonlyMap. Defensive copies guard\n // against post-build mutation through retained builder references.\n return new Interface(\n INTERFACE_KEY,\n new Map(this._ports),\n new Map(this._channels),\n );\n }\n}\n","import type { PetriNet } from './petri-net.js';\nimport type { Place } from './place.js';\nimport type { SubnetDef } from './subnet-def.js';\nimport type { SubnetInstance } from './subnet-instance.js';\nimport type { Transition } from './transition.js';\nimport type { TransitionAction } from './transition-action.js';\n\n/**\n * @internal Symbol key restricting construction to {@link SubnetDef.instantiate}\n * and the (future) `subnet-rewriter` module. Exported via the package-internal\n * factory {@link __createInstance} so the rewriter can construct Instances\n * without exposing the constructor publicly.\n */\nconst INSTANCE_KEY = Symbol('Instance.internal');\n\n/**\n * A typed module instance produced by {@link SubnetDef.instantiate}, per\n * `spec/11-modular-composition.md` requirements **MOD-010** (creation),\n * **MOD-011** (typed handle map), **MOD-012** (per-instance state isolation),\n * and **MOD-030** (action binding).\n *\n * An instance carries:\n * - The {@link prefix} used to rename body elements (per [MOD-010] separator `\"/\"`);\n * - A reference to the originating {@link SubnetDef};\n * - The renamed body — a structurally valid `PetriNet` per [CORE-040];\n * - Typed lookup handles for ports and channels keyed by their **original**\n * (pre-prefix) names;\n * - The `params` value supplied at instantiation.\n *\n * **Scaffolding status**: this class ships in scaffolding form. The\n * {@link bindActions} method throws `Error(\"not implemented\")` until the\n * `instantiate` rename pass lands in the next task. Direct accessors are\n * wired up so downstream code can take dependencies on the API shape today.\n *\n * @typeParam P parameter type (use `void` for unparameterised subnets)\n */\nexport class Instance<P = void> {\n readonly prefix: string;\n readonly def: SubnetDef<P>;\n readonly renamedBody: PetriNet;\n readonly portHandles: ReadonlyMap<string, Place<unknown>>;\n readonly channelHandles: ReadonlyMap<string, Transition>;\n readonly params: P;\n\n /**\n * @internal Use {@link SubnetDef.instantiate} (or the internal factory\n * {@link __createInstance}) to create instances.\n */\n constructor(\n key: symbol,\n prefix: string,\n def: SubnetDef<P>,\n renamedBody: PetriNet,\n portHandles: ReadonlyMap<string, Place<unknown>>,\n channelHandles: ReadonlyMap<string, Transition>,\n params: P,\n ) {\n if (key !== INSTANCE_KEY) {\n throw new Error('Use SubnetDef.instantiate() to create Instance values');\n }\n this.prefix = prefix;\n this.def = def;\n this.renamedBody = renamedBody;\n this.portHandles = portHandles;\n this.channelHandles = channelHandles;\n this.params = params;\n }\n\n /**\n * Returns the renamed {@link Place} corresponding to the named port.\n *\n * The port name is the **original** (pre-prefix) name as declared in the\n * subnet's `Interface`. Per **MOD-022**, TypeScript enforces token-type\n * compatibility at compile time only; this method does not validate `T`\n * at runtime. A missing name raises an `Error`.\n *\n * @throws when the port name is unknown\n */\n port<T>(name: string): Place<T> {\n const p = this.portHandles.get(name);\n if (p === undefined) {\n throw new Error(`No port named '${name}' in instance '${this.prefix}'`);\n }\n return p as Place<T>;\n }\n\n /**\n * Returns the renamed {@link Transition} corresponding to the named channel.\n *\n * @throws when the channel name is unknown\n */\n channel(name: string): Transition {\n const t = this.channelHandles.get(name);\n if (t === undefined) {\n throw new Error(`No channel named '${name}' in instance '${this.prefix}'`);\n }\n return t;\n }\n\n /**\n * Returns the debug-UI descriptor for this instance per **MOD-041**.\n */\n descriptor(): SubnetInstance {\n const transitions: string[] = [];\n for (const t of this.renamedBody.transitions) transitions.push(t.name);\n const exposedPlaces: string[] = [];\n for (const p of this.portHandles.values()) exposedPlaces.push(p.name);\n return {\n prefix: this.prefix,\n defName: this.def.name,\n transitions,\n exposedPlaces,\n params: this.params,\n parentPrefix: null,\n };\n }\n\n /**\n * Produces a derived instance whose specified transitions (named by their\n * **original**, pre-prefix names) carry the supplied actions per **MOD-030**.\n *\n * For each entry `[originalName, action]`, the renamed body is searched for\n * the transition whose name equals `prefix + \"/\" + originalName`. The\n * resulting instance shares the original `def`, `prefix`, `params`, and\n * port/channel handle topology — only the renamed body is rebuilt with new\n * actions. Per **MOD-030**, calling `bindActions` on one instance does NOT\n * affect the actions held by other instances of the same `def`.\n *\n * Unrecognised original names raise an `Error` so typos surface eagerly.\n */\n bindActions(actionsByOriginalName: Record<string, TransitionAction>): Instance<P> {\n // Build a Map<prefixedName, TransitionAction> for the resolver.\n // Validate every supplied original name against the renamed body's\n // transition set to surface typos eagerly.\n const prefixedByName = new Map<string, TransitionAction>();\n const renamedNames = new Set<string>();\n for (const t of this.renamedBody.transitions) {\n renamedNames.add(t.name);\n }\n\n for (const originalName of Object.keys(actionsByOriginalName)) {\n const prefixed = this.prefix + '/' + originalName;\n if (!renamedNames.has(prefixed)) {\n throw new Error(\n `Instance.bindActions: no transition '${originalName}' (resolved as ` +\n `'${prefixed}') in instance '${this.prefix}' of subnet '${this.def.name}'`,\n );\n }\n prefixedByName.set(prefixed, actionsByOriginalName[originalName]!);\n }\n\n // Use the existing PetriNet.bindActionsWithResolver — it preserves the\n // existing action when the resolver returns it (see petri-net.ts), so\n // unaffected transitions land in the new net by reference (sharing per\n // MOD-030).\n const reboundBody = this.renamedBody.bindActionsWithResolver((name) => {\n const action = prefixedByName.get(name);\n if (action !== undefined) return action;\n // Return the existing action so PetriNet.bindActionsWithResolver\n // short-circuits the rebuild for unaffected transitions.\n for (const t of this.renamedBody.transitions) {\n if (t.name === name) return t.action;\n }\n // Unreachable — the resolver is only called for transitions in this.renamedBody.\n /* istanbul ignore next */\n throw new Error(`Instance.bindActions: resolver invoked with unknown name '${name}'`);\n });\n\n // Rebuild the channel handles against the rebound body so callers see\n // the post-rebind transition (with its new action) when they ask for a\n // channel by name.\n const reboundChannelHandles = new Map<string, Transition>();\n if (this.channelHandles.size > 0) {\n const byName = new Map<string, Transition>();\n for (const t of reboundBody.transitions) {\n byName.set(t.name, t);\n }\n for (const [name, oldT] of this.channelHandles) {\n const refreshed = byName.get(oldT.name);\n if (refreshed === undefined) {\n /* istanbul ignore next */\n throw new Error(\n `Instance.bindActions: channel '${name}' transition '${oldT.name}' not found in rebound body`,\n );\n }\n reboundChannelHandles.set(name, refreshed);\n }\n }\n\n return __createInstance<P>(\n this.prefix,\n this.def,\n reboundBody,\n this.portHandles,\n reboundChannelHandles,\n this.params,\n );\n }\n}\n\n/**\n * @internal Package-internal factory used by {@link SubnetDef.instantiate}\n * and the (future) `subnet-rewriter` module to construct {@link Instance}\n * values without re-exporting the Symbol-guarded constructor key publicly.\n *\n * NOT part of the public API surface — do NOT re-export from `core/index.ts`.\n */\nexport function __createInstance<P>(\n prefix: string,\n def: SubnetDef<P>,\n renamedBody: PetriNet,\n portHandles: ReadonlyMap<string, Place<unknown>>,\n channelHandles: ReadonlyMap<string, Transition>,\n params: P,\n): Instance<P> {\n return new Instance<P>(\n INSTANCE_KEY,\n prefix,\n def,\n renamedBody,\n portHandles,\n channelHandles,\n params,\n );\n}\n","/**\n * @module programming-error\n *\n * Telling a verification failure apart from a bug.\n *\n * The pipeline is full of `catch` blocks that turn a failure into `Unknown`, or\n * into a weaker but still well-formed result. Every one of them was written for a\n * real condition — the solver died, the transport timed out, the replay search ran\n * out of budget — and every one of them quietly acquires a second meaning: *any*\n * defect in the code it guards. Once both arrive as the same verdict they cannot\n * be told apart, and a bug becomes a permanently plausible weaker answer instead\n * of a loud failure. That is the most expensive failure shape this verifier has:\n * a report that looks right and proves less.\n *\n * So the taxonomy is explicit. A `TypeError` or `ReferenceError` is never a\n * verdict — it is a defect in libpetri or in a caller's net, and it propagates. A\n * `RangeError` *is* a verdict: a stack overflow on a deep net is the capacity\n * limit `Unknown` exists to report. Everything else — a dead solver, a bad reply,\n * an exhausted budget — is the condition the catch was written for and passes\n * through untouched.\n */\n\n/**\n * Re-throws `e` when it is a programming defect rather than a verification\n * outcome. Call it first in any `catch` that degrades a result.\n */\nexport function rethrowIfProgrammingError(e: unknown): void {\n if (e instanceof TypeError || e instanceof ReferenceError) throw e;\n}\n","/** A UTF-16 unit at which code-unit and code-point order can disagree. */\nconst HIGH_UNIT = /[\\uD800-\\uFFFF]/;\n\n/**\n * Orders two strings by Unicode code point: negative when `a` sorts first, zero when equal,\n * positive otherwise.\n *\n * Every name order that reaches a report, witness trace, violation list or flat index uses\n * this, so a net prints and encodes the same on every host and in every implementation\n * ([VER-013], [VER-022]). `localeCompare` follows the host locale; `<` compares UTF-16 code\n * units, which puts a supplementary character (a surrogate pair from 0xD800) before one in\n * U+E000–U+FFFF. Rust's `str` order is code-point order; Java's `String` needs this fix too.\n *\n * ICU's fix-up (`uprv_strCompare`): only the first differing pair of units decides, and unit\n * and code-point order disagree only when both are ≥ 0xD800. For that pair, units ≥ 0xE000\n * move down by 0x800 and surrogates up by 0x2000. Exact for well-formed strings; a lone\n * surrogate, which no Rust `str` holds, sorts with the supplementary characters.\n *\n * Unless both strings hold a unit ≥ 0xD800 the engine's native comparison is the answer.\n * That fast path matters: a marking's `toString` in the class key and the canonical clock\n * order run it for every successor the state-class graph builds, and a JavaScript unit loop\n * made graph builds over long shared name prefixes up to a sixth slower.\n *\n * O(min(|a|, |b|)) unit comparisons, no allocation. The path check is O(1) for a string V8\n * stores one byte per unit, and a native scan otherwise.\n */\nexport function compareCodePoints(a: string, b: string): number {\n if (!HIGH_UNIT.test(a) || !HIGH_UNIT.test(b)) return a < b ? -1 : a > b ? 1 : 0;\n const n = a.length < b.length ? a.length : b.length;\n for (let i = 0; i < n; i++) {\n let x = a.charCodeAt(i);\n let y = b.charCodeAt(i);\n if (x !== y) {\n if (x >= 0xd800 && y >= 0xd800) {\n x += x >= 0xe000 ? -0x800 : 0x2000;\n y += y >= 0xe000 ? -0x800 : 0x2000;\n }\n return x - y;\n }\n }\n return a.length - b.length;\n}\n","import type { Place } from '../core/place.js';\nimport { compareCodePoints } from '../core/internal/code-point-order.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 /**\n * The marking as `{name:count, ...}`, places in code-point order of their names, so reports\n * and witness traces print the same on every host ([VER-013], [VER-022]).\n */\n toString(): string {\n if (this.tokenCounts.size === 0) return '{}';\n const entries = [...this.tokenCounts.entries()]\n .sort(([a], [b]) => compareCodePoints(a, 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","/**\n * @module count-clause\n *\n * A token count across places, shared by [VER-002]'s `QuiescentCount` and the open-net\n * contract of [VER-022]: how it is counted, which bound a marking breaks, and how it reads\n * in a report. Internal: `verification/index.ts` does not re-export this module.\n */\nimport type { Place } from '../core/place.js';\nimport type { MarkingState } from './marking-state.js';\n\n/** `exactly 1`, `at most 1`, `at least 2`, `between 1 and 3`, `any number`. */\nexport function countPhrase(min: number, max: number): string {\n if (min === max) return `exactly ${min}`;\n if (max === Infinity) return min === 0 ? 'any number' : `at least ${min}`;\n if (min === 0) return `at most ${max}`;\n return `between ${min} and ${max}`;\n}\n\n/** `exactly 1 across {a, b}`: the one phrasing of a count clause, for reports and both open-net routes. */\nexport function countAcross(min: number, max: number, places: Iterable<Place<any>>): string {\n return `${countPhrase(min, max)} across {${[...places].map(p => p.name).join(', ')}}`;\n}\n\n/** The tokens `m` holds across `places`, each place counted once. */\nexport function tokensAcross(m: MarkingState, places: Iterable<Place<any>>): number {\n const seen = new Set<string>();\n let count = 0;\n for (const p of places) {\n if (seen.has(p.name)) continue;\n seen.add(p.name);\n count += m.tokens(p);\n }\n return count;\n}\n\n/**\n * Which bound of a count `m` breaks: `upper` above `max` across `places`, `lower` below `min`\n * while no `waivedBy` place is marked, else `null`. Shared by [VER-002]'s `QuiescentCount` on\n * the graph routes and by the open-net contract of [VER-022].\n */\nexport function countViolation(\n m: MarkingState,\n places: Iterable<Place<any>>,\n min: number,\n max: number,\n waivedBy: Iterable<Place<any>>,\n): 'lower' | 'upper' | null {\n const count = tokensAcross(m, places);\n if (count > max) return 'upper';\n if (count < min && !m.hasTokensInAny(waivedBy)) return 'lower';\n return null;\n}\n","import type { Place } from '../core/place.js';\nimport { countAcross } from './count-clause.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 | TerminatesAtSink\n | MutualExclusion\n | PlaceBound\n | Unreachable\n | BranchPlaceBound\n | JoinedOrDeadLettered\n | QuiescentCount;\n\n/**\n * Deadlock-freedom: no reachable quiescent marking strands a token (VER-002).\n *\n * Violated when a reachable marking is quiescent (every transition disabled) and\n * holds a token in a place that is not a declared sink. The empty marking strands\n * nothing and never violates. This is workflow-net proper completion; for the\n * weaker \"did the net reach a terminal at all\", see {@link TerminatesAtSink},\n * which inverts on the empty marking.\n */\nexport interface DeadlockFree {\n readonly type: 'deadlock-free';\n}\n\n/**\n * Termination at a declared sink: every reachable quiescent marking has at least\n * one declared sink marked (VER-002).\n *\n * Violated when a reachable marking is quiescent and no declared sink holds a\n * token. Says nothing about tokens left elsewhere. Meaningful only with at least\n * one sink declared; with none, every quiescent marking violates vacuously.\n */\nexport interface TerminatesAtSink {\n readonly type: 'terminates-at-sink';\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/**\n * A token count at quiescence (VER-002): every reachable quiescent marking holds between\n * `min` and `max` tokens across `places` (`max` may be `Infinity`). The lower bound is\n * waived while any `waivedBy` place is marked, the upper never: a halted run ([VER-014])\n * need not refund its budget, but never holds more than there is.\n */\nexport interface QuiescentCount {\n readonly type: 'quiescent-count';\n readonly places: readonly Place<any>[];\n readonly min: number;\n readonly max: number;\n readonly waivedBy: readonly Place<any>[];\n}\n\n// Factory functions\n\nexport function deadlockFree(): DeadlockFree {\n return { type: 'deadlock-free' };\n}\n\n/** Quiescence reaches a declared sink (VER-002). See {@link TerminatesAtSink}. */\nexport function terminatesAtSink(): TerminatesAtSink {\n return { type: 'terminates-at-sink' };\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/**\n * A token count at quiescence (VER-002). See {@link QuiescentCount}.\n *\n * ```ts\n * quiescentCount([budget], k, k, [halt]) // the budget is back at k whenever the net comes to rest, unless it halted\n * ```\n */\nexport function quiescentCount(\n places: Iterable<Place<any>>,\n min: number,\n max: number,\n waivedBy: Iterable<Place<any>> = [],\n): QuiescentCount {\n if (!Number.isInteger(min) || min < 0 || !(max === Infinity || Number.isInteger(max)) || max < min) {\n throw new Error(`quiescentCount needs whole bounds with 0 <= min <= max, got ${min}..${max}`);\n }\n return { type: 'quiescent-count', places: [...places], min, max, waivedBy: [...waivedBy] };\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 'terminates-at-sink':\n return 'Terminates at a declared sink';\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 case 'quiescent-count': {\n const count = `Quiescent count: ${countAcross(prop.min, prop.max, prop.places)}`;\n return prop.waivedBy.length === 0\n ? count\n : `${count}; lower bound waived while {${prop.waivedBy.map(p => p.name).join(', ')}} is marked`;\n }\n }\n}\n","/**\n * @module rest-set\n *\n * Where a token may come to rest without being stranded (VER-002, VER-014).\n *\n * `DeadlockFree` is violated by a quiescent marking that holds a token outside the\n * places where resting is permitted. The permitted set has two layers:\n *\n * - the **declared sinks** (`SmtVerifier.sinkPlaces`), where a token may always rest;\n * - the **conditional sinks** (`SmtVerifier.sinkPlacesWhen(marker, …)`), where a\n * token may rest only while `marker` holds a token. A marked marker is a\n * *designed terminal* — a halted or paused run — and the marker itself is at rest\n * whenever it is marked.\n *\n * Declarations union: a token in `p` is excused when `p` is a declared sink, when\n * `p` is a marker, or when some conditional set naming `p` has its marker marked.\n * Every route that decides `DeadlockFree` — the flat and name-coloured CHC encoders,\n * the abstract counterexample replay and the Route B name-partition graph — reads\n * this one module, so the predicate cannot drift between them (VER-002 AC7).\n *\n * `TerminatesAtSink` is untouched by conditional declarations: it asks whether a\n * declared sink was reached and reads only the unconditional set.\n */\nimport type { Place } from '../core/place.js';\nimport type { FlatNet } from './encoding/flat-net.js';\nimport type { MarkingState } from './marking-state.js';\n\n/** Places where a token may rest while `marker` holds a token. */\nexport interface ConditionalSinks {\n readonly marker: Place<any>;\n readonly places: ReadonlySet<Place<any>>;\n}\n\n/**\n * Per flat place, how a token resting there is excused: `null` when it never counts\n * as stranded (a declared sink, or a marker), otherwise the ascending flat indices of\n * the markers whose presence excuses it — empty when nothing does, so a token there\n * is stranded whenever the marking is quiescent.\n *\n * Places and markers that do not resolve in the flat net contribute nothing, as an\n * unresolved sink does: a mistyped marker makes the property stricter, never laxer.\n */\nexport function strandingExcuses(\n flatNet: FlatNet,\n sinkPlaces: ReadonlySet<Place<any>>,\n conditional: readonly ConditionalSinks[],\n): (readonly number[] | null)[] {\n const P = flatNet.places.length;\n const excuses: (number[] | null)[] = new Array(P);\n for (let pid = 0; pid < P; pid++) excuses[pid] = [];\n for (const sink of sinkPlaces) {\n const pid = flatNet.placeIndex.get(sink.name);\n if (pid != null) excuses[pid] = null;\n }\n for (const { marker, places } of conditional) {\n const mid = flatNet.placeIndex.get(marker.name);\n if (mid == null) continue;\n excuses[mid] = null;\n for (const place of places) {\n const pid = flatNet.placeIndex.get(place.name);\n if (pid == null) continue;\n const list = excuses[pid];\n if (list != null && !list.includes(mid)) list.push(mid);\n }\n }\n for (const list of excuses) if (list != null) list.sort((a, b) => a - b);\n return excuses;\n}\n\n/**\n * Whether `m` holds a token that is stranded — outside every place where resting is\n * permitted in `m`. The graph-route form of {@link strandingExcuses}.\n */\nexport function strandsToken(\n m: MarkingState,\n sinkPlaces: ReadonlySet<Place<any>>,\n conditional: readonly ConditionalSinks[],\n): boolean {\n const resting = restingNames(m, sinkPlaces, conditional);\n for (const p of m.placesWithTokens()) {\n if (!resting.has(p.name)) return true;\n }\n return false;\n}\n\n/**\n * The places of `m` holding a stranded token, in `m`'s own order: empty exactly when\n * {@link strandsToken} is false. [VER-022] names them in its violations.\n */\nexport function strandedPlaces(\n m: MarkingState,\n sinkPlaces: ReadonlySet<Place<any>>,\n conditional: readonly ConditionalSinks[],\n): Place<any>[] {\n const resting = restingNames(m, sinkPlaces, conditional);\n return m.placesWithTokens().filter(p => !resting.has(p.name));\n}\n\n/** The names of the places where a token may rest in `m`: sinks, markers, and the places of every marked marker. */\nfunction restingNames(\n m: MarkingState,\n sinkPlaces: ReadonlySet<Place<any>>,\n conditional: readonly ConditionalSinks[],\n): Set<string> {\n const resting = new Set<string>();\n for (const s of sinkPlaces) resting.add(s.name);\n for (const { marker, places } of conditional) {\n resting.add(marker.name);\n if (m.hasTokens(marker)) {\n for (const p of places) resting.add(p.name);\n }\n }\n return resting;\n}\n\n/**\n * The declarations as the report prints them after the property description:\n * `sinks: a, b; when h: c, d; when p`, or `null` when nothing is declared.\n * Declaration order throughout, so the four implementations render the same text.\n */\nexport function describeSinks(\n sinkPlaces: ReadonlySet<Place<any>>,\n conditional: readonly ConditionalSinks[],\n): string | null {\n const parts: string[] = [];\n if (sinkPlaces.size > 0) parts.push(`sinks: ${[...sinkPlaces].map(p => p.name).join(', ')}`);\n for (const { marker, places } of conditional) {\n const names = [...places].map(p => p.name);\n parts.push(names.length === 0 ? `when ${marker.name}` : `when ${marker.name}: ${names.join(', ')}`);\n }\n return parts.length === 0 ? null : parts.join('; ');\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. */\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, in Unicode code-point order, for stable indexing across\n * runs, hosts and implementations.\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 { compareCodePoints } from '../../core/internal/code-point-order.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. Unicode code-point order (not the host's\n // locale, and not UTF-16 code units), so the index agrees with the Rust and Java\n // flatteners on every name and the emitted scripts stay byte-identical (VER-013).\n const places = [...allPlacesSet.values()].sort((a, b) => compareCodePoints(a.name, 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. The elimination above\n // runs in f64 `number`, so a row whose identity part left the safe-integer\n // range carries ROUNDED weights, not exact ones. Emit such a row raw — no\n // sign normalisation, no GCD reduction, which would otherwise launder e.g.\n // (2^54, 2^54) into a plausible-looking (1, 1) — and let\n // validateInvariantsExact drop it by name with the overflow reason.\n if (!rowIsExact(augmented[row]!, T, P)) {\n invariants.push(rawInvariant(augmented[row]!, T, P, flatNet, initialMarking));\n continue;\n }\n\n // A signed null-space basis, exactly as the Rust reference computes it\n // (VER-013 script parity): a mixed-sign row is a conservation law like any\n // other and passes the same exact gate; a semi-negative row is the same law\n // negated. Non-negativity is only required of the P-semiflows that bound the\n // colour slots (computePSemiflows), never of the strengthening laws. Rows were\n // GCD-normalised during the elimination, so no renormalisation here.\n const weights = new Array<number>(P);\n let hasPositive = false;\n let hasNegative = false;\n for (let i = 0; i < P; i++) {\n weights[i] = augmented[row]![T + i]!;\n if (weights[i]! > 0) hasPositive = true;\n if (weights[i]! < 0) hasNegative = true;\n }\n if (!hasPositive && !hasNegative) continue;\n if (!hasPositive) {\n for (let i = 0; i < P; i++) weights[i] = -weights[i]!;\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/** True when every weight in the identity part of `row` is an exact integer. */\nfunction rowIsExact(row: readonly number[], T: number, P: number): boolean {\n for (let i = 0; i < P; i++) {\n if (!Number.isSafeInteger(row[T + i]!)) return false;\n }\n return true;\n}\n\n/** The identity part of `row` verbatim, so the exact re-check sees what f64 produced. */\nfunction rawInvariant(\n row: readonly number[],\n T: number,\n P: number,\n flatNet: FlatNet,\n initialMarking: MarkingState,\n): PInvariant {\n const weights = new Array<number>(P);\n const support = new Set<number>();\n let constant = 0;\n for (let i = 0; i < P; i++) {\n weights[i] = row[T + i]!;\n if (weights[i] !== 0) {\n support.add(i);\n constant += weights[i]! * initialMarking.tokens(flatNet.places[i]!);\n }\n }\n return pInvariant(weights, constant, support);\n}\n\n/** An invariant rejected by {@link validateInvariantsExact}, with the reason it failed. */\nexport interface DroppedInvariant {\n readonly invariant: PInvariant;\n readonly reason: string;\n}\n\n/** Result of {@link validateInvariantsExact}: exact-verified invariants plus the rejects. */\nexport interface InvariantValidationResult {\n readonly valid: readonly PInvariant[];\n readonly dropped: readonly DroppedInvariant[];\n}\n\n/**\n * Re-verifies each computed P-invariant **exactly** (BigInt) and drops any that fails.\n *\n * {@link computePInvariants} runs its integer Gaussian elimination in f64 `number`\n * with no overflow guard, and the encoder conjoins each invariant into the CHC\n * transition-rule *body*: a numerically wrong invariant therefore removes reachable\n * successors and can certify a false `Proven`. This pass must run between\n * computation and use, so nothing imprecise ever reaches the encoder — mirroring\n * the defensive style of {@link computePSemiflows}, which drops rows rather than\n * keep imprecise ones.\n *\n * Checks per invariant `y`:\n * - every weight and the constant is a safe integer (`Number.isSafeInteger`),\n * - **H1 linearity**: `y` is zero on every place with non-linear consumption —\n * see below,\n * - `y·C = 0` exactly, per transition column of the incidence matrix (BigInt),\n * - the stored constant equals the exactly recomputed `y·M0`.\n *\n * `flatNet` and `initialMarking` are REQUIRED: they were once optional, and\n * omitting them silently disabled the H1 guard and the constant re-check —\n * i.e. the call had a configuration in which it certified unsound invariants.\n *\n * **H1 linearity guard** (`lean/Libpetri/Strengthening.lean`,\n * `consume_all_hypothesis_is_necessary`): the incidence matrix *linearizes*\n * consumption — its column is `post − pre` with `pre = requiredCount`, so it says\n * nothing about consume-all or reset semantics, where the encoder's fire relation\n * sets `m'_i = post[i]` and erases however many tokens the place actually held.\n * `y·C = 0` is therefore necessary but NOT sufficient: an invariant weighting such\n * a place can pass the exact gate yet be false on the real net, and conjoined into\n * the CHC rule bodies it prunes genuine successors (false PROVEN). Per the Lean\n * theorem's H1 hypothesis, any invariant with a nonzero weight on a place that is,\n * for any flat transition, a consume-all input place (`all` **and** `at-least` —\n * `atLeast(n)` waits for n but then consumes ALL available, see\n * `consumptionCount` in `core/in.ts`; the linear cardinalities are\n * `one`/`exactly(n)`) or a reset place is dropped here. Env-injectable places need\n * no guard of their own: their injector columns ({@link IncidenceMatrix.from})\n * already force `y = 0` there through the `y·C = 0` check — Strengthening.lean's\n * H3′ sufficiency result (`invariant_strengthening_sound_inj`).\n *\n * Dropping a *valid* conservation law only weakens the encoder's strengthening\n * lemmas (sound); keeping an invalid one is what must never happen.\n */\nexport function validateInvariantsExact(\n matrix: IncidenceMatrix,\n invariants: readonly PInvariant[],\n flatNet: FlatNet,\n initialMarking: MarkingState,\n): InvariantValidationResult {\n const nonlinear = nonlinearPlaces(flatNet);\n const valid: PInvariant[] = [];\n const dropped: DroppedInvariant[] = [];\n for (const inv of invariants) {\n const reason = exactCheckFailure(matrix, inv, nonlinear, flatNet, initialMarking);\n if (reason === null) {\n valid.push(inv);\n } else {\n dropped.push({ invariant: inv, reason });\n }\n }\n return { valid, dropped };\n}\n\n/**\n * Place indices with non-linear consumption on some flat transition — the\n * reset/consume-all arms of H1. The matrix may carry extra injector columns beyond\n * `flatNet.transitions`; injections are linear (`+e_p`) and need no entry here.\n */\nexport function nonlinearPlaces(flatNet: FlatNet): ReadonlySet<number> {\n const nonlinear = new Set<number>();\n for (const ft of flatNet.transitions) {\n for (let p = 0; p < ft.consumeAll.length; p++) {\n if (ft.consumeAll[p]) nonlinear.add(p);\n }\n for (const p of ft.resetPlaces) nonlinear.add(p);\n }\n return nonlinear;\n}\n\n/** Returns why `inv` fails the exact re-check, or null when it passes. */\nfunction exactCheckFailure(\n matrix: IncidenceMatrix,\n inv: PInvariant,\n nonlinear: ReadonlySet<number>,\n flatNet: FlatNet,\n initialMarking: MarkingState,\n): string | null {\n const P = matrix.numPlaces();\n const T = matrix.numTransitions();\n\n if (inv.weights.length !== P) {\n return `weight vector has ${inv.weights.length} entries, expected ${P}`;\n }\n for (let p = 0; p < P; p++) {\n if (!Number.isSafeInteger(inv.weights[p]!)) {\n return (\n `weight overflow at place '${placeName(flatNet, p)}' ` +\n `(exact value outside this implementation's integer extraction range)`\n );\n }\n }\n if (!Number.isSafeInteger(inv.constant)) {\n return `constant ${inv.constant} is outside the safe-integer range`;\n }\n\n // H1 linearity guard (see the {@link validateInvariantsExact} doc): a nonzero\n // weight on a consume-all or reset place makes the linearized column a lie about\n // the real firing, so the y·C = 0 check below would not certify conservation.\n for (let p = 0; p < inv.weights.length; p++) {\n if (inv.weights[p] !== 0 && nonlinear.has(p)) {\n return (\n `support intersects consume-all/reset place '${placeName(flatNet, p)}' ` +\n `(non-linear consumption; see Strengthening.lean H1)`\n );\n }\n }\n\n // y·C = 0, re-derived in BigInt from the incidence matrix (immune to f64 rounding).\n const y: bigint[] = inv.weights.map((w) => BigInt(w));\n const incidence = matrix.incidence(); // [t][p]\n for (let t = 0; t < T; t++) {\n const row = incidence[t]!;\n let dot = 0n;\n for (let p = 0; p < P; p++) {\n if (y[p] === 0n) continue;\n if (!Number.isSafeInteger(row[p]!)) {\n return `incidence entry ${row[p]} at [t=${t}][p=${p}] is outside the safe-integer range`;\n }\n dot += y[p]! * BigInt(row[p]!);\n }\n if (dot !== 0n) {\n return `y*C is ${dot} (not 0) at ${columnName(flatNet, t)}`;\n }\n }\n\n // Constant = y·M0, recomputed exactly.\n let exact = 0n;\n for (let p = 0; p < P; p++) {\n if (y[p] === 0n) continue;\n const tokens = initialMarking.tokens(flatNet.places[p]!);\n if (!Number.isSafeInteger(tokens)) {\n return `initial marking of place ${p} (${tokens}) is outside the safe-integer range`;\n }\n exact += y[p]! * BigInt(tokens);\n }\n if (exact !== BigInt(inv.constant)) {\n return `constant ${inv.constant} does not match exact y*M0 = ${exact}`;\n }\n\n return null;\n}\n\n/** Place name for a flat place index (falls back to `#idx` off the end). */\nfunction placeName(flatNet: FlatNet, p: number): string {\n return flatNet.places[p]?.name ?? `#${p}`;\n}\n\n/**\n * Name of incidence column `t`. Columns past `flatNet.transitions` are the\n * per-env-place injector columns {@link IncidenceMatrix.from} appends.\n */\nfunction columnName(flatNet: FlatNet, t: number): string {\n const ft = flatNet.transitions[t];\n return ft != null\n ? `transition '${ft.name}'`\n : `env-injector column ${t - flatNet.transitions.length}`;\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 */\n/** Same conservation law: identical weight vector and constant. */\nfunction sameInvariant(a: PInvariant, b: PInvariant): boolean {\n if (a.constant !== b.constant || a.weights.length !== b.weights.length) return false;\n for (let i = 0; i < a.weights.length; i++) {\n if (a.weights[i] !== b.weights[i]) return false;\n }\n return true;\n}\n\n/**\n * VER-007 — the semiflow union. Appends every gate-validated P-semiflow that is not\n * already a basis row (same weights, same constant) to `invariants`, returning the\n * strengthened list and how many rows were added.\n *\n * The null-space basis is one basis of many: elimination hands back mixed-sign rows\n * and rows that fold a reset place into a chain whose other combinations avoid it,\n * both lost to the exact gate — on a reset-heavy net every law of the chains those\n * arcs touch, leaving IC3 to rediscover conservation it cannot within any practical\n * budget. The Farkas rows ({@link computePSemiflows}) are the minimal laws of the\n * net. Conjoining them alongside the basis is pure strengthening (`Semiflow.lean`,\n * `semiflow_union_sound`) **provided both lists passed the same exact gate**\n * (`semiflow_gate_is_necessary`) — the caller's obligation; this only merges.\n */\nexport function strengthenWithSemiflows(\n invariants: readonly PInvariant[],\n semiflows: readonly PInvariant[],\n): { readonly invariants: readonly PInvariant[]; readonly added: number } {\n const strengthened = [...invariants];\n let added = 0;\n for (const sf of semiflows) {\n if (!strengthened.some((inv) => sameInvariant(inv, sf))) {\n strengthened.push(sf);\n added++;\n }\n }\n return { invariants: strengthened, added };\n}\n\n/**\n * Survivor cap per elimination round — the historical backstop against blow-up.\n * Rows past it are dropped, so on a branchy net the semiflows that survive are an\n * arbitrary truncation of the minimal set rather than all of it ([VER-007]).\n */\nconst MAX_SEMIFLOW_ROWS = 8192;\n\n/**\n * Candidate cap per elimination round, applied while the `pos x neg` combinations\n * are being built. Generous relative to {@link MAX_SEMIFLOW_ROWS} so that any net\n * whose enumeration completes today is unaffected; it exists to stop a net whose\n * candidate set is exponential from exhausting the heap before the filter runs.\n */\nconst MAX_SEMIFLOW_CANDIDATES = 65_536;\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 // Bound the CANDIDATE set, not merely the survivors. `pos x neg` is the term\n // that explodes — on branchy nets it is quadratic in a row count that is\n // already exponential in the branching — and materialising it before the\n // filter is what exhausts the heap, which aborts the process rather than\n // failing a verdict. The ceiling is well above `MAX_SEMIFLOW_ROWS` so that\n // every net small enough to finish keeps exactly the rows it had.\n outer:\n for (const rp of pos) {\n for (const rn of neg) {\n if (next.length >= MAX_SEMIFLOW_CANDIDATES) break outer;\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 > MAX_SEMIFLOW_ROWS) rows.length = MAX_SEMIFLOW_ROWS;\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 * `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\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 */\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 *\n * Kept row `i` is exactly one with no row `j` such that `|supp(j)| < |supp(i)|`\n * and `supp(j) ⊆ supp(i)`. (The obvious sequential reading — skipping a `j` that\n * has itself been dropped — computes the same set: if `j` was dropped there is a\n * `k` with `supp(k) ⊂ supp(j) ⊆ supp(i)` and `|supp(k)| < |supp(i)|`, so `k`\n * drops `i` in `j`'s place.) The set is therefore order-free, which is what lets\n * this run as a bitset sweep in ascending support size rather than the quadratic\n * scan of member lists it replaces: supports become machine words, a subset test\n * is a handful of AND operations, and candidates are compared only against\n * strictly smaller ones. Same rows, same order, on a net where the old form was\n * the dominant cost of the whole pipeline.\n */\nfunction keepSupportMinimal(rows: SemiflowRow[]): SemiflowRow[] {\n const n = rows.length;\n if (n < 2) return rows;\n const words = ((rows[0]!.weight.length + 31) >>> 5) || 1;\n const bits = new Uint32Array(n * words);\n const sizes = new Int32Array(n);\n for (let i = 0; i < n; i++) {\n const w = rows[i]!.weight;\n let size = 0;\n for (let p = 0; p < w.length; p++) {\n if (w[p] !== 0) {\n const idx = i * words + (p >>> 5);\n bits[idx] = bits[idx]! | (1 << (p & 31));\n size++;\n }\n }\n sizes[i] = size;\n }\n // Ascending support size: a row can only be dropped by a strictly smaller one,\n // so every possible dropper precedes it here and the inner loop can stop early.\n const order = new Int32Array(n);\n for (let i = 0; i < n; i++) order[i] = i;\n order.sort((a, b) => sizes[a]! - sizes[b]!);\n\n const keep = new Array<boolean>(n).fill(true);\n for (let oi = 0; oi < n; oi++) {\n const i = order[oi]!;\n const base = i * words;\n for (let oj = 0; oj < oi; oj++) {\n const j = order[oj]!;\n if (sizes[j]! >= sizes[i]!) break; // sorted: no strictly smaller row remains\n const jbase = j * words;\n let subset = true;\n for (let w = 0; w < words; w++) {\n const jb = bits[jbase + w]!;\n if ((jb & ~bits[base + w]!) !== 0) { subset = false; break; }\n }\n if (subset) { keep[i] = false; break; }\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 // Only a non-negative law bounds its support; a mixed-sign law (which the signed\n // null-space basis now carries) says nothing about boundedness.\n if (inv.weights.some((w) => w < 0)) continue;\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/**\n * The invariants in canonical order (VER-013): by ascending support, then weights,\n * then constant, each compared lexicographically. The same order the Rust and Java\n * verifiers apply, so the strengthened scripts are byte-identical.\n */\nexport function canonicalInvariantOrder(invariants: readonly PInvariant[]): PInvariant[] {\n const lex = (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 const support = (inv: PInvariant): number[] => [...inv.support].sort((x, y) => x - y);\n return [...invariants].sort(\n (a, b) => lex(support(a), support(b)) || lex(a.weights, b.weights) || a.constant - b.constant,\n );\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","/**\n * @module z3-process\n *\n * The z3 process transport (VER-013).\n *\n * Every SMT query is one `z3` process: the SMT-LIB2 script goes to its stdin in a\n * single write, stdin is closed so the solver sees end-of-file, and both output\n * streams are collected while a wall-clock watchdog waits. The child is killed on\n * every exit path, so a wedged solver can never outlive the query that started it,\n * and no solver state survives between queries, so concurrent verifiers in one\n * process are independent. The solve runs in another process, so the event loop\n * stays free while it works.\n *\n * The executable is `z3` on `PATH` unless {@link Z3_ENV} names another one. It is\n * probed once per verification with `--version` and refused below\n * {@link MIN_Z3_VERSION}; a missing or too-old binary surfaces as an `unknown`\n * verdict whose reason names the command and the environment variable, never as a\n * rejection out of `verify()`. Setting {@link DUMP_ENV} to a directory writes every\n * script and reply there (`NNN-<phase>.smt2`, `.out`, and `.err` when stderr is not\n * empty), which is how a solver reply is reproduced outside the pipeline.\n *\n * Timeouts are per invocation: `-t:<ms>` asks z3 to answer `unknown` after the soft\n * budget, `-T:<s>` (the budget plus {@link GRACE_MS}, rounded up) makes z3 print\n * `timeout` and exit on its own, and the watchdog at the budget plus twice the grace\n * kills whatever ignored both. The Java, TypeScript and Rust transports pass\n * byte-identical argument lists and classify replies identically.\n */\nimport { spawn, spawnSync } from 'node:child_process';\nimport { rethrowIfProgrammingError } from '../programming-error.js';\nimport { existsSync, mkdirSync, statSync, writeFileSync } from 'node:fs';\nimport * as path from 'node:path';\nimport { errorLine, timeoutLine } from './smt-text.js';\n\n/** Environment variable naming the z3 executable (default: `z3` on `PATH`). */\nexport const Z3_ENV = 'LIBPETRI_Z3';\n/** Environment variable naming a directory that receives every script and reply. */\nexport const DUMP_ENV = 'LIBPETRI_SMT_DUMP';\n/** Slack between the soft budget and the hard backstops, in milliseconds. */\nexport const GRACE_MS = 1_000;\n/** How long the `--version` probe may take before it counts as unavailable. */\nconst VERSION_PROBE_MS = 5_000;\n\n/** A z3 release version, ordered numerically. */\nexport interface Z3Version {\n readonly major: number;\n readonly minor: number;\n readonly patch: number;\n}\n\n/**\n * Oldest z3 the transport accepts: `-t`/`-T`, Spacer as `fp.engine`, and the\n * `(get-model)` / `(get-proof)` printers the decoders read are stable from here.\n */\nexport const MIN_Z3_VERSION: Z3Version = { major: 4, minor: 8, patch: 0 };\n\n/** Parses the version out of a `z3 --version` reply (`Z3 version 4.16.0 - 64 bit`). */\nexport function parseZ3Version(text: string): Z3Version | null {\n const m = /Z3 version (\\d+)\\.(\\d+)(?:\\.(\\d+))?/.exec(text);\n if (m == null) return null;\n return { major: Number(m[1]), minor: Number(m[2]), patch: m[3] == null ? 0 : Number(m[3]) };\n}\n\nexport function formatZ3Version(v: Z3Version): string {\n return `${v.major}.${v.minor}.${v.patch}`;\n}\n\nexport function compareZ3Version(a: Z3Version, b: Z3Version): number {\n return a.major - b.major || a.minor - b.minor || a.patch - b.patch;\n}\n\n/** A resolved z3 executable: where it is and which version answered the probe. */\nexport interface Z3Solver {\n /** The executable as resolved (a path, or a bare name on `PATH`). */\n readonly program: string;\n /** The version the probe reported. */\n readonly version: Z3Version;\n /** Where scripts and replies are written, or `null` for no dump. */\n readonly dumpDir: string | null;\n}\n\n/** No usable z3 resolved; the message is the `unknown` reason the verifier reports. */\nexport class Z3Unavailable extends Error {\n constructor(message: string) {\n super(message);\n this.name = 'Z3Unavailable';\n }\n}\n\n/** The process could not be started; the message is the `unknown` reason. */\nexport class Z3ProcessError extends Error {\n constructor(message: string) {\n super(message);\n this.name = 'Z3ProcessError';\n }\n}\n\n/** How a z3 process ended. */\nexport type Z3Exit =\n | { readonly kind: 'exited'; readonly code: number | null }\n | { readonly kind: 'killed' };\n\n/** The raw reply of one z3 run. */\nexport interface Z3Reply {\n readonly stdout: string;\n readonly stderr: string;\n readonly exit: Z3Exit;\n}\n\n/** True when the process exited with status 0. */\nexport function replySucceeded(reply: Z3Reply): boolean {\n return reply.exit.kind === 'exited' && reply.exit.code === 0;\n}\n\n/** The standard argument list: `-smt2 -in -t:<ms> -T:<s>`. */\nexport function argsFor(timeoutMs: number): string[] {\n return ['-smt2', '-in', `-t:${timeoutMs}`, `-T:${hardTimeoutSecs(timeoutMs)}`];\n}\n\n/** The `-T:` backstop in whole seconds: the soft budget plus the grace, rounded up. */\nexport function hardTimeoutSecs(timeoutMs: number): number {\n return Math.max(1, Math.ceil((timeoutMs + GRACE_MS) / 1000));\n}\n\n/** When the watchdog kills the process: the soft budget plus twice the grace. */\nexport function watchdogMs(timeoutMs: number): number {\n return timeoutMs + 2 * GRACE_MS;\n}\n\n/** The soft budget in milliseconds: at least one, so `-t:0` never means \"forever\". */\nexport function timeoutBudget(timeoutMs: number): number {\n return Math.max(1, Math.floor(Number.isFinite(timeoutMs) ? timeoutMs : 1));\n}\n\n/**\n * Why a reply carries no `(check-sat)` answer, in the order the transport contract\n * fixes: the `-T` backstop, the watchdog, an `(error …)` on either stream, anything\n * on stderr, and finally the unexpected stdout itself.\n */\nexport function failureReason(reply: Z3Reply, timeoutMs: number): string {\n if (timeoutLine(reply.stdout)) {\n return `z3 hard timeout after ${hardTimeoutSecs(timeoutMs)}s`;\n }\n if (reply.exit.kind === 'killed') {\n return `z3 did not exit within ${watchdogMs(timeoutMs)} ms and was killed`;\n }\n const err = errorLine(reply.stdout) ?? errorLine(reply.stderr);\n if (err != null) return `Z3 error: ${err}`;\n const stderr = reply.stderr.trim();\n if (stderr !== '') return `Z3 error: ${stderr}`;\n return `Unexpected Z3 output: ${reply.stdout.trim()}`;\n}\n\n/**\n * Where `program` resolves to: the path itself when it names a file, else the first\n * executable of that name on `PATH` (`.exe` tried on Windows); `null` when nothing\n * resolves.\n */\nexport function locateZ3(program: string, env: NodeJS.ProcessEnv = process.env): string | null {\n const isFile = (p: string): boolean => {\n try {\n return existsSync(p) && statSync(p).isFile();\n } catch (e) {\n // A filesystem refusal means \"not a usable file\"; a defect here would make a\n // solver that IS installed look absent, and \"your z3 isn't set up\" is a story\n // users believe, so it is the most convincingly disguised failure this module\n // can produce. It must not be one.\n rethrowIfProgrammingError(e);\n return false;\n }\n };\n if (program.includes('/') || program.includes(path.sep) || path.isAbsolute(program)) {\n return isFile(program) ? program : null;\n }\n const searchPath = env['PATH'] ?? '';\n const windows = process.platform === 'win32';\n for (const dir of searchPath.split(path.delimiter)) {\n if (dir === '') continue;\n const candidate = path.join(dir, program);\n if (isFile(candidate)) return candidate;\n if (windows && isFile(candidate + '.exe')) return candidate + '.exe';\n }\n return null;\n}\n\n/** Resolves a specific executable (tests point this at a stub). No dump directory. */\nexport function z3SolverAt(program: string, env: NodeJS.ProcessEnv = process.env): Z3Solver {\n const located = locateZ3(program, env);\n if (located == null) {\n throw new Z3Unavailable(\n `z3 binary not found: ${program}; install z3 >= ${formatZ3Version(MIN_Z3_VERSION)} or set ${Z3_ENV}`,\n );\n }\n const probe = spawnSync(located, ['--version'], {\n encoding: 'utf8',\n timeout: VERSION_PROBE_MS,\n stdio: ['ignore', 'pipe', 'pipe'],\n });\n if (probe.error != null) {\n if ((probe.error as NodeJS.ErrnoException).code === 'ETIMEDOUT') {\n throw new Z3Unavailable(`${program} --version did not answer within ${VERSION_PROBE_MS} ms`);\n }\n throw new Z3Unavailable(`failed to spawn ${program}: ${probe.error.message}`);\n }\n const version = parseZ3Version(probe.stdout ?? '');\n if (version == null) {\n const line = `${probe.stdout ?? ''}\\n${probe.stderr ?? ''}`\n .split('\\n')\n .map((l) => l.trim())\n .find((l) => l !== '') ?? '';\n throw new Z3Unavailable(`z3 --version did not report a version: ${line}`);\n }\n if (compareZ3Version(version, MIN_Z3_VERSION) < 0) {\n throw new Z3Unavailable(\n `z3 ${formatZ3Version(version)} is older than the minimum ${formatZ3Version(MIN_Z3_VERSION)}`,\n );\n }\n return { program: located, version, dumpDir: null };\n}\n\n/**\n * Resolves the executable named by {@link Z3_ENV}, or `z3` on `PATH`, probes its\n * version, and reads {@link DUMP_ENV}. Throws {@link Z3Unavailable}.\n */\nexport function resolveZ3(env: NodeJS.ProcessEnv = process.env): Z3Solver {\n const configured = env[Z3_ENV];\n const program = configured == null || configured.trim() === '' ? 'z3' : configured;\n const dump = env[DUMP_ENV];\n const solver = z3SolverAt(program, env);\n return { ...solver, dumpDir: dump == null || dump.trim() === '' ? null : dump };\n}\n\n/**\n * True if a usable `z3` executable resolves: `LIBPETRI_Z3` if set, else `z3` on\n * `PATH`, at or above {@link MIN_Z3_VERSION}. Without one every SMT path returns\n * `unknown`; the test suites use this to skip loudly rather than fail.\n */\nexport function z3Available(env: NodeJS.ProcessEnv = process.env): boolean {\n try {\n resolveZ3(env);\n return true;\n } catch (e) {\n // Same disguise as `locateZ3`, and worse in one way: the suites skip on a\n // `false` here, so a defect would take every solver-backed test out of the run\n // while the run stayed green. Only a genuine absence may answer `false`.\n rethrowIfProgrammingError(e);\n return false;\n }\n}\n\n/** Process-wide counter for dump file names (not solver state). */\nlet dumpCounter = 0;\n\nfunction dumpSlot(solver: Z3Solver, phase: string, script: string): string | null {\n if (solver.dumpDir == null) return null;\n dumpCounter += 1;\n try {\n mkdirSync(solver.dumpDir, { recursive: true });\n const base = path.join(solver.dumpDir, `${String(dumpCounter).padStart(3, '0')}-${phase}`);\n writeFileSync(`${base}.smt2`, script);\n return base;\n } catch {\n // Deliberately exempt from the programming-error rule, unlike the two above:\n // a dump is a diagnostic that no verdict depends on, so nothing it does can\n // make a report weaker or a solver look absent. Failing a verification because\n // a debug directory was unwritable would be the worse trade.\n return null;\n }\n}\n\nfunction dumpWrite(file: string, text: string): void {\n try {\n writeFileSync(file, text);\n } catch {\n // Ignored for the reason given in `dumpSlot`: the dump is a diagnostic, never\n // the pipeline.\n }\n}\n\n/**\n * Runs one script through one z3 process and resolves with the raw reply. `phase`\n * names the dump files; `extraArgs` follow the standard argument list. The only\n * rejection is a failed spawn: a solver that printed nothing, errored, timed out or\n * was killed still comes back as a reply for the caller to classify\n * ({@link failureReason}).\n */\nexport function runZ3Text(\n solver: Z3Solver,\n script: string,\n phase: string,\n timeoutMs: number,\n extraArgs: readonly string[] = [],\n): Promise<Z3Reply> {\n const budget = timeoutBudget(timeoutMs);\n const base = dumpSlot(solver, phase, script);\n return new Promise<Z3Reply>((resolve, reject) => {\n const child = spawn(solver.program, [...argsFor(budget), ...extraArgs], {\n stdio: ['pipe', 'pipe', 'pipe'],\n });\n const out: Buffer[] = [];\n const err: Buffer[] = [];\n let killed = false;\n let settled = false;\n child.stdout!.on('data', (chunk: Buffer) => out.push(chunk));\n child.stderr!.on('data', (chunk: Buffer) => err.push(chunk));\n // A solver that exited early (parse error, `-T` expiry) closes the pipe under\n // us; that is not a failure of the transport, the reply says what happened.\n child.stdin!.on('error', () => {});\n const watchdog = setTimeout(() => {\n killed = true;\n child.kill('SIGKILL');\n }, watchdogMs(budget));\n child.on('error', (e) => {\n if (settled) return;\n settled = true;\n clearTimeout(watchdog);\n reject(new Z3ProcessError(`failed to spawn ${solver.program}: ${e.message}`));\n });\n child.on('close', (code) => {\n if (settled) return;\n settled = true;\n clearTimeout(watchdog);\n const reply: Z3Reply = {\n stdout: Buffer.concat(out).toString('utf8'),\n stderr: Buffer.concat(err).toString('utf8'),\n exit: killed ? { kind: 'killed' } : { kind: 'exited', code },\n };\n if (base != null) {\n dumpWrite(`${base}.out`, reply.stdout);\n if (reply.stderr.trim() !== '') dumpWrite(`${base}.err`, reply.stderr);\n }\n resolve(reply);\n });\n // The whole script in one write, then EOF.\n child.stdin!.end(script);\n });\n}\n","/**\n * @module smt-text\n *\n * Text-level helpers shared by the transport, the Spacer runner, the certificate\n * check and the counterexample decoder (VER-013). Byte-for-byte mirrors of the Rust\n * `z3_process` / `smt_verifier` helpers and the Java `SmtText` class.\n */\n\n/**\n * The first trimmed stdout line that is a `(check-sat)` answer, or `null`. The answer\n * is a LINE anywhere in the reply, not the first bytes: a build is free to print a\n * warning first, and a HORN script that asks for both a proof and a model always gets\n * one `(error …)` line back.\n */\nexport function classifyFirstLine(stdout: string): 'sat' | 'unsat' | 'unknown' | null {\n for (const raw of stdout.split('\\n')) {\n const line = raw.trim();\n if (line === 'sat' || line === 'unsat' || line === 'unknown') return line;\n }\n return null;\n}\n\n/** True when z3's `-T` backstop fired: it prints the single line `timeout`. */\nexport function timeoutLine(stdout: string): boolean {\n return stdout.split('\\n').some((l) => l.trim() === 'timeout');\n}\n\n/** The first `(error …)` line in a z3 stream, trimmed; `null` if none. */\nexport function errorLine(text: string): string | null {\n for (const raw of text.split('\\n')) {\n const line = raw.trim();\n if (line.startsWith('(error')) return line;\n }\n return null;\n}\n\n/**\n * Returns the index one past the `)` matching the `(` at `start`, or `-1` when the\n * expression is unbalanced. Paren counting skips string literals (`\"…\"`, with `\"\"`\n * escapes) and quoted symbols (`|…|`).\n */\nexport function sexprEnd(s: string, start: number): number {\n let depth = 0;\n let inString = false;\n let inSymbol = false;\n for (let i = start; i < s.length; i++) {\n const c = s[i]!;\n if (inString) {\n if (c === '\"') inString = false;\n } else if (inSymbol) {\n if (c === '|') inSymbol = false;\n } else if (c === '\"') {\n inString = true;\n } else if (c === '|') {\n inSymbol = true;\n } else if (c === '(') {\n depth++;\n } else if (c === ')') {\n depth--;\n if (depth === 0) return i + 1;\n }\n }\n return -1;\n}\n\n/**\n * Every complete `(define-fun …)` s-expression in `output`, in order. A truncated\n * (unbalanced) definition is dropped rather than half-captured.\n */\nexport function extractDefineFuns(output: string): string[] {\n const defs: string[] = [];\n let from = 0;\n for (;;) {\n const pos = output.indexOf('(define-fun', from);\n if (pos < 0) break;\n const end = sexprEnd(output, pos);\n if (end < 0) break;\n defs.push(output.slice(pos, end));\n from = end;\n }\n return defs;\n}\n\n/**\n * The inductive invariant of a `sat` reply: every `(define-fun …)` of the\n * `(get-model)` block joined with newlines, or `null` when no model was printed.\n */\nexport function extractInvariant(output: string): string | null {\n const defs = extractDefineFuns(output);\n return defs.length === 0 ? null : defs.join('\\n');\n}\n","/**\n * @module spacer-runner\n *\n * Runs Z3 Spacer on a HORN script through one `z3` process (VER-013) and\n * classifies the reply in verdict terms.\n *\n * HORN/Spacer convention (shared with the Rust and Java verifiers and corroborated\n * by the certificate check): with the query `(assert (not Error))`, z3 prints `sat`\n * when the property is PROVEN (an inductive invariant excluding every violating\n * state exists) and `unsat` when it is VIOLATED (no such invariant; the refutation\n * proof carries the counterexample states).\n */\nimport { failureReason, runZ3Text, timeoutBudget, type Z3Solver } from './z3-process.js';\nimport { rethrowIfProgrammingError } from '../programming-error.js';\nimport { classifyFirstLine, extractInvariant } from './smt-text.js';\n\n/** Result of a Spacer query. */\nexport type QueryResult = QueryProven | QueryViolated | QueryUnknown;\n\n/** Property proven (z3 `sat`). */\nexport interface QueryProven {\n readonly type: 'proven';\n /**\n * The `(define-fun …)` block of the model, verbatim (the certificate the\n * certificate checker re-validates), or `null` when no model printed.\n */\n readonly invariantFormula: string | null;\n}\n\n/** Property violated (z3 `unsat`). */\nexport interface QueryViolated {\n readonly type: 'violated';\n /** The raw solver reply; the refutation proof in it is decoded by the counterexample decoder. */\n readonly answer: string;\n}\n\n/** Solver could not determine (timeout, resource limit, transport failure). */\nexport interface QueryUnknown {\n readonly type: 'unknown';\n readonly reason: string;\n}\n\n/**\n * Runs `smt2` with `fp.engine=spacer`. `phase` names the dump files (`horn` or\n * `horn-coloured`).\n */\nexport async function runZ3Spacer(\n solver: Z3Solver,\n timeoutMs: number,\n smt2: string,\n phase: string,\n): Promise<QueryResult> {\n let reply;\n try {\n reply = await runZ3Text(solver, smt2, phase, timeoutMs, ['fp.engine=spacer']);\n } catch (e: any) {\n rethrowIfProgrammingError(e);\n return { type: 'unknown', reason: String(e?.message ?? e) };\n }\n const stdout = reply.stdout.trim();\n\n // The verdict is a LINE anywhere in the reply, never its first bytes: the script\n // asks for both (get-proof) and (get-model), one of which answers `(error …)` on\n // either branch, and a build is free to print a warning first.\n switch (classifyFirstLine(stdout)) {\n // unsat => no inductive invariant excludes the bad state => VIOLATED.\n case 'unsat':\n return { type: 'violated', answer: stdout };\n // sat => an inductive invariant exists => PROVEN.\n case 'sat':\n return { type: 'proven', invariantFormula: extractInvariant(stdout) };\n case 'unknown':\n return { type: 'unknown', reason: 'Z3 answered unknown' };\n default:\n // No verdict at all: the `-T` backstop, the watchdog, an `(error …)` on\n // either stream, in that order (VER-013).\n return { type: 'unknown', reason: failureReason(reply, timeoutBudget(timeoutMs)) };\n }\n}\n","/**\n * @module smt-encoder\n *\n * Encodes a flattened Petri net as Constrained Horn Clauses (CHC) in SMT-LIB2 text\n * for Z3's Spacer engine (VER-013).\n *\n * The net's state space is modeled as integer vectors (one variable per place = token\n * count). Three rule types:\n *\n * 1. **Init**: `(assert (Reachable M0))` — the initial marking is reachable\n * 2. **Transition**: `Reachable(M') :- Reachable(M) ∧ enabled(M,t) ∧ fire(M,M',t) ∧\n * M' ≥ 0 ∧ invariants(M') ∧ env-bounds(M')` — one rule per flat transition, plus\n * one env-injection rule per injected environment place (VER-006)\n * 3. **Error**: `Error :- Reachable(M) ∧ violation(M)`; `(assert (not Error))`, so\n * `sat` is PROVEN and `unsat` is VIOLATED\n *\n * With the state equation (VER-016, {@link encodeNet}) the state is `(M, n)` — one\n * firing counter per flat transition — and every transition rule also conjoins\n * `M' = M0 + C·n'`, which hands Spacer every linear consequence of the marking\n * equation (the inequality conservation laws it cannot invent) at no enumeration cost.\n *\n * The emitted script is byte-identical to the Rust reference (`smt_encoder.rs`) and\n * the Java port for the same input: places in code-point order of their names, the\n * property's places, sinks, env bounds and injections in place-index order,\n * invariants in the order the verifier canonicalised.\n */\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 { strandingExcuses, type ConditionalSinks } from '../rest-set.js';\nimport { nonlinearPlaces } from '../invariant/p-invariant-computer.js';\n\n/** An encoded SMT-LIB2 script. */\nexport interface SmtEncoding {\n /** The script text. */\n readonly smt2: string;\n /** The number of flat places (the leading arguments of `Reachable` in the flat encoding). */\n readonly placeCount: number;\n /**\n * The number of firing counters that follow the places in `Reachable` (VER-016):\n * one per flat transition when the state equation is encoded, else 0.\n */\n readonly counterCount: number;\n}\n\n/** Options of {@link encodeNet}. */\nexport interface EncodeOptions {\n /** Declared sink places (VER-002). */\n readonly sinkPlaces?: ReadonlySet<Place<any>>;\n /** Emit `:produce-proofs` and `(get-proof)` so an `unsat` reply carries the refutation the replay decodes. */\n readonly produceProofs?: boolean;\n /** Conditional sinks (VER-014); read by `deadlock-free` only. */\n readonly conditionalSinks?: readonly ConditionalSinks[];\n /**\n * Carry one firing counter per flat transition and conjoin the marking equation\n * `M' = M0 + C·n'` (VER-016) into every rule body. Off by default (scripts stay\n * byte-identical).\n */\n readonly stateEquation?: boolean;\n}\n\n/** An injected environment place: its flat index and its cap (`null` = unbounded). */\nexport interface Injection {\n readonly pid: number;\n readonly bound: number | null;\n}\n\n/**\n * Encodes the net and property as a HORN script.\n *\n * @param produceProofs emit `:produce-proofs` and `(get-proof)` so an `unsat` reply\n * carries the refutation the replay decodes\n * @param conditionalSinks places where a token may rest while a marker is marked\n * (VER-014); read by `deadlock-free` only\n */\nexport function encode(\n flatNet: FlatNet,\n initialMarking: MarkingState,\n property: SmtProperty,\n invariants: readonly PInvariant[],\n sinkPlaces: ReadonlySet<Place<any>> = new Set(),\n produceProofs = false,\n conditionalSinks: readonly ConditionalSinks[] = [],\n): SmtEncoding {\n return encodeNet(flatNet, initialMarking, property, invariants, { sinkPlaces, produceProofs, conditionalSinks });\n}\n\n/**\n * {@link encode} with named options. With `stateEquation` (VER-016) the state carries\n * one firing counter per flat transition after the places: `Reachable(M, n)`, the\n * initial fact has `n = 0`, transition `k`'s rule increments `n_k` and copies the\n * others, an injection rule copies them all, and every transition rule's body\n * conjoins `m'_p = M0_p + Σ_t C[p][t]·n'_t` for each place whose column is exact\n * (no consume-all / reset arc, not injected) together with `n' ≥ 0`. The error rule\n * quantifies the counters and constrains only the marking.\n */\nexport function encodeNet(\n flatNet: FlatNet,\n initialMarking: MarkingState,\n property: SmtProperty,\n invariants: readonly PInvariant[],\n options: EncodeOptions = {},\n): SmtEncoding {\n const sinkPlaces = options.sinkPlaces ?? new Set<Place<any>>();\n const produceProofs = options.produceProofs ?? false;\n const conditionalSinks = options.conditionalSinks ?? [];\n const P = flatNet.places.length;\n const T = options.stateEquation ? flatNet.transitions.length : 0;\n const lines: string[] = [];\n const envInject = resolveEnvInjection(flatNet);\n\n if (produceProofs) lines.push('(set-option :produce-proofs true)');\n lines.push('(set-logic HORN)');\n lines.push('');\n\n lines.push(`(declare-fun Reachable (${ints(P + T).join(' ')}) Bool)`);\n lines.push('(declare-fun Error () Bool)');\n lines.push('');\n\n const mVars = vars(P, '');\n const mpVars = vars(P, 'p');\n const nVars = counterVars(T, '');\n const npVars = counterVars(T, 'p');\n\n const m0: string[] = [];\n for (let i = 0; i < P; i++) m0.push(String(initialMarking.tokens(flatNet.places[i]!)));\n for (let k = 0; k < T; k++) m0.push('0');\n lines.push(`(assert (Reachable ${m0.join(' ')}))`);\n lines.push('');\n\n const equation = T > 0 ? stateEquationConditions(flatNet, initialMarking, npVars) : [];\n for (let k = 0; k < flatNet.transitions.length; k++) {\n const ft = flatNet.transitions[k]!;\n const strengthening = [...invariantConditions(invariants, mpVars)];\n if (T > 0) strengthening.push(...counterConditions(k, nVars, npVars), ...equation);\n lines.push(encodeTransitionRule(flatNet, ft, mVars, mpVars, nVars, npVars, strengthening));\n }\n // Environment-injection rules (VER-006): NOT flat transitions, so the deadlock\n // encoding never sees them; no P-invariant strengthening, injection breaks\n // conservation on purpose. The counters are carried unchanged (VER-016).\n for (const inj of envInject) {\n lines.push(encodeInjectionRule(P, inj.pid, inj.bound, mVars, mpVars, nVars, npVars));\n }\n lines.push('');\n\n lines.push(encodeErrorRule(flatNet, property, mVars, nVars, sinkPlaces, envInject, conditionalSinks));\n lines.push('');\n\n // Under HORN/Spacer this is SAT when an inductive invariant excludes every\n // violating state (PROVEN) and UNSAT when none exists (VIOLATED).\n lines.push('(assert (not Error))');\n lines.push('(check-sat)');\n if (produceProofs) lines.push('(get-proof)');\n lines.push('(get-model)');\n\n return { smt2: lines.join('\\n'), placeCount: P, counterCount: T };\n}\n\n/** The injected environment places in place-index order. */\nexport function resolveEnvInjection(flatNet: FlatNet): Injection[] {\n const out: Injection[] = [];\n for (const [name, bound] of flatNet.environmentInjection) {\n const pid = flatNet.placeIndex.get(name);\n if (pid != null) out.push({ pid, bound });\n }\n out.sort((a, b) => a.pid - b.pid);\n return out;\n}\n\n/** The bounded environment places (legacy post-cap) in place-index order. */\nfunction envBounds(flatNet: FlatNet): Array<[number, number]> {\n const out: Array<[number, number]> = [];\n for (const [name, max] of flatNet.environmentBounds) {\n const pid = flatNet.placeIndex.get(name);\n if (pid != null) out.push([pid, max]);\n }\n out.sort((a, b) => a[0] - b[0]);\n return out;\n}\n\nfunction ints(n: number): string[] {\n return new Array<string>(n).fill('Int');\n}\n\nfunction vars(P: number, suffix: string): string[] {\n const out: string[] = [];\n for (let i = 0; i < P; i++) out.push(`m${i}${suffix}`);\n return out;\n}\n\n/** `n0..n{T-1}` (`suffix` = `'p'` for the primed counters), empty when `T` is 0. */\nfunction counterVars(T: number, suffix: string): string[] {\n const out: string[] = [];\n for (let k = 0; k < T; k++) out.push(`n${k}${suffix}`);\n return out;\n}\n\nfunction quantified(names: readonly string[]): string {\n return names.map((v) => `(${v} Int)`).join(' ');\n}\n\n// === State equation (VER-016) ===\n\n/**\n * The places whose column of the incidence matrix is exact in every step: no\n * consume-all / reset arc on them (H1) and not injected (H3').\n *\n * Only these carry an *equality* row. A place a consume-all or reset arc clears carries\n * the upper-bound row of {@link stateEquationConditions} instead ([VER-016] AC2), and an\n * injected place carries none.\n */\nexport function equationPlaces(flatNet: FlatNet): number[] {\n const excluded = new Set<number>(nonlinearPlaces(flatNet));\n for (const inj of resolveEnvInjection(flatNet)) excluded.add(inj.pid);\n const out: number[] = [];\n for (let p = 0; p < flatNet.places.length; p++) if (!excluded.has(p)) out.push(p);\n return out;\n}\n\n/**\n * The counter update of transition `fired` (`-1` for an injection step, which fires\n * no counted transition): `n'_k = n_k + 1` for the fired one, `n'_j = n_j` for the\n * rest, then `n' ≥ 0`.\n */\nexport function counterConditions(fired: number, nVars: readonly string[], npVars: readonly string[]): string[] {\n const conditions: string[] = [];\n for (let k = 0; k < nVars.length; k++) {\n conditions.push(k === fired ? `(= ${npVars[k]} (+ ${nVars[k]} 1))` : `(= ${npVars[k]} ${nVars[k]})`);\n }\n for (let k = 0; k < npVars.length; k++) conditions.push(`(>= ${npVars[k]} 0)`);\n return conditions;\n}\n\n/**\n * The marking equation over the given marking and counter variables, in place order, terms\n * in transition order: `m_p = M0_p + Σ_t C[p][t]·n_t` for every place of\n * {@link equationPlaces}, and `m_p ≤ …` for a place a consume-all or reset arc clears. A\n * clearing firing removes at least its arc weight, so the upper bound stays inductive over\n * `(M, n)`: the step needs `m_p ≥ pre`, which gives `post ≤ M0_p + C_p·n'`. An injected\n * place carries no row.\n */\nexport function stateEquationConditions(\n flatNet: FlatNet,\n initialMarking: MarkingState,\n nVars: readonly string[],\n mVars: readonly string[] = vars(flatNet.places.length, 'p'),\n): string[] {\n const conditions: string[] = [];\n const cleared = nonlinearPlaces(flatNet);\n const injected = new Set(resolveEnvInjection(flatNet).map((inj) => inj.pid));\n for (let p = 0; p < flatNet.places.length; p++) {\n if (injected.has(p)) continue;\n const terms: string[] = [];\n for (let t = 0; t < flatNet.transitions.length; t++) {\n const ft = flatNet.transitions[t]!;\n const c = ft.postVector[p]! - ft.preVector[p]!;\n if (c === 0) continue;\n terms.push(intTerm(c, nVars[t]!));\n }\n const m0 = initialMarking.tokens(flatNet.places[p]!);\n const rhs = terms.length === 0 ? `${m0}` : `(+ ${m0} ${terms.join(' ')})`;\n conditions.push(`(${cleared.has(p) ? '<=' : '='} ${mVars[p]} ${rhs})`);\n }\n return conditions;\n}\n\n// === Shared condition emitters ===\n//\n// Emitted by BOTH the CHC rule encoding and the plain-SMT step relation\n// (encodeStepRelationSmt2) the certificate check uses, so the two cannot drift.\n\n/**\n * Enablement + firing + non-negativity conjuncts for one flat transition:\n * `enabled(M, t)`, `fire(M, M', t)`, `M' >= 0`. Excludes the `Reachable` body atom,\n * the P-invariant strengthening and the env bounds.\n */\nfunction firingConditions(\n flatNet: FlatNet,\n ft: FlatTransition,\n mVars: readonly string[],\n mpVars: readonly string[],\n): string[] {\n const P = flatNet.places.length;\n const conditions: string[] = [];\n for (let i = 0; i < P; i++) {\n if (ft.preVector[i]! > 0) conditions.push(`(>= ${mVars[i]} ${ft.preVector[i]})`);\n }\n for (const inh of ft.inhibitorPlaces) conditions.push(`(= ${mVars[inh]} 0)`);\n for (const rd of ft.readPlaces) conditions.push(`(>= ${mVars[rd]} 1)`);\n for (let i = 0; i < P; i++) {\n if (ft.resetPlaces.includes(i) || ft.consumeAll[i]) {\n // Reset / consume-all: clear then add post.\n conditions.push(`(= ${mpVars[i]} ${ft.postVector[i]})`);\n } else {\n const delta = ft.postVector[i]! - ft.preVector[i]!;\n if (delta > 0) conditions.push(`(= ${mpVars[i]} (+ ${mVars[i]} ${delta}))`);\n else if (delta < 0) conditions.push(`(= ${mpVars[i]} (- ${mVars[i]} ${-delta}))`);\n else conditions.push(`(= ${mpVars[i]} ${mVars[i]})`);\n }\n }\n for (let i = 0; i < P; i++) conditions.push(`(>= ${mpVars[i]} 0)`);\n return conditions;\n}\n\n/**\n * P-invariant conjuncts over the given marking variables. The step relation never\n * emits these: the certificate check keeps its relation UNSTRENGTHENED and conjoins\n * them into the candidate instead, where the VCs re-prove them.\n */\nexport function invariantConditions(invariants: readonly PInvariant[], names: readonly string[]): string[] {\n const conditions: string[] = [];\n for (const inv of invariants) {\n const terms = [...inv.support].sort((a, b) => a - b).map((i) => `(* ${inv.weights[i]} ${names[i]})`);\n if (terms.length === 0) continue;\n const sum = terms.length === 1 ? terms[0]! : `(+ ${terms.join(' ')})`;\n conditions.push(`(= ${sum} ${inv.constant})`);\n }\n return conditions;\n}\n\n/** Environment post-cap conjuncts on the next marking (legacy Bounded mode). */\nfunction envBoundConditions(flatNet: FlatNet, mpVars: readonly string[]): string[] {\n return envBounds(flatNet).map(([pid, max]) => `(<= ${mpVars[pid]} ${max})`);\n}\n\n/**\n * Guard + column-update conjuncts for one env-injection step (VER-006):\n * `[m_pid < bound]`, `m'_pid = m_pid + 1`, all other columns copied.\n */\nfunction injectionConditions(\n P: number,\n pid: number,\n bound: number | null,\n mVars: readonly string[],\n mpVars: readonly string[],\n): string[] {\n const conditions: string[] = [];\n if (bound != null) conditions.push(`(< ${mVars[pid]} ${bound})`);\n for (let i = 0; i < P; i++) {\n if (i === pid) conditions.push(`(= ${mpVars[i]} (+ ${mVars[i]} 1))`);\n else conditions.push(`(= ${mpVars[i]} ${mVars[i]})`);\n }\n return conditions;\n}\n\nfunction encodeTransitionRule(\n flatNet: FlatNet,\n ft: FlatTransition,\n mVars: readonly string[],\n mpVars: readonly string[],\n nVars: readonly string[],\n npVars: readonly string[],\n strengthening: readonly string[],\n): string {\n const conditions = [`(Reachable ${[...mVars, ...nVars].join(' ')})`];\n conditions.push(...firingConditions(flatNet, ft, mVars, mpVars));\n conditions.push(...strengthening);\n conditions.push(...envBoundConditions(flatNet, mpVars));\n const body = `(and ${conditions.join('\\n ')})`;\n const quantifiedVars = quantified([...mVars, ...mpVars, ...nVars, ...npVars]);\n return `(assert (forall (${quantifiedVars})\\n (=> ${body}\\n (Reachable ${[...mpVars, ...npVars].join(' ')}))))`;\n}\n\nfunction encodeInjectionRule(\n P: number,\n pid: number,\n bound: number | null,\n mVars: readonly string[],\n mpVars: readonly string[],\n nVars: readonly string[],\n npVars: readonly string[],\n): string {\n const conditions = [`(Reachable ${[...mVars, ...nVars].join(' ')})`];\n conditions.push(...injectionConditions(P, pid, bound, mVars, mpVars));\n if (nVars.length > 0) conditions.push(...counterConditions(-1, nVars, npVars));\n const body = `(and ${conditions.join('\\n ')})`;\n const quantifiedVars = quantified([...mVars, ...mpVars, ...nVars, ...npVars]);\n return `(assert (forall (${quantifiedVars})\\n (=> ${body}\\n (Reachable ${[...mpVars, ...npVars].join(' ')}))))`;\n}\n\n/**\n * Joins conjuncts into one formula (`true` when empty, the bare conjunct when\n * singleton, since SMT-LIB `and` wants at least two arguments).\n */\nexport function conjoin(conditions: readonly string[]): string {\n if (conditions.length === 0) return 'true';\n if (conditions.length === 1) return conditions[0]!;\n return `(and ${conditions.join(' ')})`;\n}\n\n/** `c·v`: `v` for 1, `(- v)` for −1, otherwise `(* c v)` with a negative `c` written `(- k)`. */\nexport function intTerm(c: number | bigint, v: string): string {\n if (c === 1 || c === 1n) return v;\n if (c === -1 || c === -1n) return `(- ${v})`;\n return c > 0 ? `(* ${c} ${v})` : `(* (- ${-c}) ${v})`;\n}\n\n/** `Σ terms`: `zero` when empty, the bare term when singleton, otherwise `(+ …)`. */\nexport function sumTerms(terms: readonly string[], zero = '0'): string {\n return terms.length === 0 ? zero : terms.length === 1 ? terms[0]! : `(+ ${terms.join(' ')})`;\n}\n\n/**\n * The net's one-step relation `T(M, M')` as one plain SMT-LIB2 formula over the free\n * variables `m0..` / `m0p..`: the disjunction of every flat transition firing and\n * every env-injection step (VER-006). This is the UNSTRENGTHENED relation the\n * certificate check validates against: it shares the condition emitters with the CHC\n * path but omits the P-invariant conjuncts, so a certificate poisoned by a wrong\n * invariant cannot re-certify itself.\n */\nexport function encodeStepRelationSmt2(flatNet: FlatNet, stateEquation = false): string {\n const P = flatNet.places.length;\n const T = stateEquation ? flatNet.transitions.length : 0;\n const mVars = vars(P, '');\n const mpVars = vars(P, 'p');\n const nVars = counterVars(T, '');\n const npVars = counterVars(T, 'p');\n const disjuncts: string[] = [];\n for (let k = 0; k < flatNet.transitions.length; k++) {\n const ft = flatNet.transitions[k]!;\n const conditions = firingConditions(flatNet, ft, mVars, mpVars);\n // The counters move with the step (VER-016); the marking equation itself is\n // strengthening and stays out — the candidate carries it and the VCs re-prove it.\n if (T > 0) conditions.push(...counterConditions(k, nVars, npVars));\n conditions.push(...envBoundConditions(flatNet, mpVars));\n disjuncts.push(conjoin(conditions));\n }\n for (const inj of resolveEnvInjection(flatNet)) {\n const conditions = injectionConditions(P, inj.pid, inj.bound, mVars, mpVars);\n if (T > 0) conditions.push(...counterConditions(-1, nVars, npVars));\n disjuncts.push(conjoin(conditions));\n }\n if (disjuncts.length === 0) return 'false';\n if (disjuncts.length === 1) return disjuncts[0]!;\n return `(or ${disjuncts.join('\\n ')})`;\n}\n\nfunction encodeErrorRule(\n flatNet: FlatNet,\n property: SmtProperty,\n mVars: readonly string[],\n nVars: readonly string[],\n sinkPlaces: ReadonlySet<Place<any>>,\n envInject: readonly Injection[],\n conditionalSinks: readonly ConditionalSinks[],\n): string {\n const violation = encodePropertyViolation(flatNet, property, mVars, sinkPlaces, envInject, conditionalSinks);\n const state = [...mVars, ...nVars];\n return `(assert (forall (${quantified(state)})\\n (=> (and (Reachable ${state.join(' ')}) ${violation})\\n Error)))`;\n}\n\n/** The flat indices of the given places that resolve, ascending and deduplicated. */\nexport function indexOrdered(flatNet: FlatNet, places: Iterable<Place<any>>): number[] {\n const idx = new Set<number>();\n for (const place of places) {\n const i = flatNet.placeIndex.get(place.name);\n if (i != null) idx.add(i);\n }\n return [...idx].sort((a, b) => a - b);\n}\n\n/**\n * The property-violation condition `Bad(M)` over `mVars`. Also used by the\n * certificate check's safety VC, which must test against exactly the violation the\n * error rule encodes. A place the net does not declare contributes nothing; the\n * verifier refuses such a property before encoding.\n */\nexport function encodePropertyViolation(\n flatNet: FlatNet,\n property: SmtProperty,\n mVars: readonly string[],\n sinkPlaces: ReadonlySet<Place<any>>,\n envInject: readonly Injection[],\n conditionalSinks: readonly ConditionalSinks[] = [],\n): string {\n switch (property.type) {\n // DeadlockFree (VER-002): a quiescent marking that STRANDS a token — holds one\n // in a place where resting is not permitted. The empty marking strands nothing\n // and is therefore not a violation (AC4). A conditional sink (VER-014) is\n // stranded only while every marker that would excuse it is unmarked.\n case 'deadlock-free': {\n const conditions = encodeQuiescent(flatNet, mVars, envInject);\n if (conditions == null) return 'false';\n const stranded = strandedConditions(strandingExcuses(flatNet, sinkPlaces, conditionalSinks), mVars);\n // Every place is a declared sink: nothing can ever be stranded.\n if (stranded.length === 0) return 'false';\n conditions.push(`(or ${stranded.join(' ')})`);\n return joinConditions(conditions);\n }\n // TerminatesAtSink (VER-002): a quiescent marking that reached NO declared sink.\n // This is the predicate DeadlockFree carried before the VER-002 split, unchanged.\n case 'terminates-at-sink': {\n const conditions = encodeQuiescent(flatNet, mVars, envInject);\n if (conditions == null) return 'false';\n for (const pid of indexOrdered(flatNet, sinkPlaces)) {\n conditions.push(`(= ${mVars[pid]} 0)`);\n }\n return joinConditions(conditions);\n }\n case 'mutual-exclusion': {\n const conditions = indexOrdered(flatNet, [property.p1, property.p2]).map((i) => `(>= ${mVars[i]} 1)`);\n return conditions.length === 0 ? 'false' : `(and ${conditions.join(' ')})`;\n }\n case 'place-bound':\n case 'branch-place-bound': {\n // BranchPlaceBound is the ν-net budget lever (NU-040): a count bound, encoded\n // like PlaceBound.\n const pid = flatNet.placeIndex.get(property.place.name);\n return pid == null ? 'false' : `(> ${mVars[pid]} ${property.bound})`;\n }\n case 'unreachable': {\n const conditions = indexOrdered(flatNet, property.places).map((i) => `(>= ${mVars[i]} 1)`);\n return conditions.length === 0 ? 'false' : `(and ${conditions.join(' ')})`;\n }\n // JoinedOrDeadLettered (NU-040 AC4): a quiescent state that still holds a\n // `pending` token is a stranded correlation group. Carries NO sink clause — a\n // declared sink must not excuse a stranded group.\n case 'joined-or-dead-lettered': {\n const pid = flatNet.placeIndex.get(property.pending.name);\n // Unknown pending place name: no state can violate.\n if (pid == null) return 'false';\n const conditions = encodeQuiescent(flatNet, mVars, envInject);\n if (conditions == null) return 'false';\n conditions.push(`(>= ${mVars[pid]} 1)`);\n return joinConditions(conditions);\n }\n // QuiescentCount (VER-002): a quiescent marking whose count across the places is\n // below `min` with every waiver empty, or above `max`.\n case 'quiescent-count': {\n const bad = countViolationCondition(\n indexOrdered(flatNet, property.places).map((i) => mVars[i]!),\n indexOrdered(flatNet, property.waivedBy).map((i) => mVars[i]!),\n property.min,\n property.max,\n );\n if (bad == null) return 'false';\n const conditions = encodeQuiescent(flatNet, mVars, envInject);\n if (conditions == null) return 'false';\n conditions.push(bad);\n return joinConditions(conditions);\n }\n }\n}\n\n/**\n * The count clause of a `QuiescentCount` over rendered counts and waivers, each in\n * place-index order: `(and (< Σ min) (= w 0) …)` when `min > 0`, `(> Σ max)` when `max` is\n * finite, their `or` when both apply, `null` when neither does. Shared with the\n * name-coloured encoder; mirrored by the abstract replayer's `satisfiesBad`.\n */\nexport function countViolationCondition(\n counts: readonly string[],\n waivers: readonly string[],\n min: number,\n max: number,\n): string | null {\n const sum = sumTerms(counts);\n const parts: string[] = [];\n if (min > 0) {\n const below = `(< ${sum} ${min})`;\n parts.push(waivers.length === 0 ? below : `(and ${below} ${waivers.map((w) => `(= ${w} 0)`).join(' ')})`);\n }\n if (max !== Infinity) parts.push(`(> ${sum} ${max})`);\n if (parts.length === 0) return null;\n return parts.length === 1 ? parts[0]! : `(or ${parts.join(' ')})`;\n}\n\n/**\n * One \"a token is stranded here\" disjunct per place where resting is not always\n * permitted: `(>= m 1)`, conjoined with `(= marker 0)` for every marker whose\n * presence would excuse it (VER-014), markers in place-index order. Shared with the\n * name-coloured encoder through `counts`, which renders a place's count term.\n */\nexport function strandedConditions(\n excuses: readonly (readonly number[] | null)[],\n counts: readonly string[],\n): string[] {\n const stranded: string[] = [];\n for (let pid = 0; pid < excuses.length; pid++) {\n const markers = excuses[pid];\n if (markers == null) continue;\n if (markers.length === 0) {\n stranded.push(`(>= ${counts[pid]} 1)`);\n } else {\n stranded.push(`(and (>= ${counts[pid]} 1) ${markers.map(k => `(= ${counts[k]} 0)`).join(' ')})`);\n }\n }\n return stranded;\n}\n\n/**\n * Joins violation conjuncts into the final `Bad(M)` term. An empty conjunction is\n * vacuously true — a net with no transitions is quiescent everywhere.\n */\nfunction joinConditions(conditions: readonly string[]): string {\n return conditions.length === 0 ? 'true' : `(and ${conditions.join('\\n ')})`;\n}\n\n/**\n * Quiescence: every transition is disabled.\n *\n * Shared core of the three quiescence-sensitive properties (VER-002 DeadlockFree\n * and TerminatesAtSink, NU-040 JoinedOrDeadLettered). Each conjoins its own clause\n * on top and none is encoded here, so a change to one predicate cannot silently\n * move the others — which is exactly how the sink clause leaked into\n * JoinedOrDeadLettered before NU-040 AC4.\n *\n * Returns `null` when some transition is enabled in every marking: no quiescent\n * marking exists, so every property built on this is unviolatable.\n *\n * Environment inputs are treated as injectable (VER-006): an input/read on an\n * injectable env place is NOT a reason the transition is disabled (AlwaysAvailable\n * always satisfies it, Bounded(k) iff the demand is at most k), so a reactive net\n * merely waiting for input is not reported as quiescent; only a genuinely stuck\n * marking is.\n */\nfunction encodeQuiescent(\n flatNet: FlatNet,\n mVars: readonly string[],\n envInject: readonly Injection[],\n): string[] | null {\n const envBound = new Map<number, number | null>();\n for (const inj of envInject) envBound.set(inj.pid, inj.bound);\n const disabledConditions: string[] = [];\n for (const ft of flatNet.transitions) {\n const disableReasons: string[] = [];\n let permanentlyDisabled = false;\n for (let i = 0; i < flatNet.places.length; i++) {\n if (ft.preVector[i]! > 0) {\n if (envBound.has(i)) {\n const k = envBound.get(i)!;\n if (k != null && ft.preVector[i]! > k) permanentlyDisabled = true;\n continue;\n }\n disableReasons.push(`(< ${mVars[i]} ${ft.preVector[i]})`);\n }\n }\n for (const inh of ft.inhibitorPlaces) disableReasons.push(`(> ${mVars[inh]} 0)`);\n for (const rd of ft.readPlaces) {\n if (envBound.has(rd)) {\n const k = envBound.get(rd)!;\n if (k != null && k < 1) permanentlyDisabled = true;\n continue;\n }\n disableReasons.push(`(< ${mVars[rd]} 1)`);\n }\n if (permanentlyDisabled) {\n disabledConditions.push('true');\n continue;\n }\n // Transition is always enabled (possibly via injection) — never quiescent.\n if (disableReasons.length === 0) return null;\n disabledConditions.push(`(or ${disableReasons.join(' ')})`);\n }\n return disabledConditions;\n}\n\n/**\n * Whether NO marking of this net can be quiescent, because some transition is\n * enabled in every marking — an environment-gated one whose input injection can\n * always satisfy ([VER-006]).\n *\n * Every quiescence property is then unviolatable and comes back `proven` for a\n * reason that has nothing to do with the net's own behaviour: an open net with an\n * always-available source never comes to rest, so \"no reachable quiescent marking\n * strands a token\" is vacuously true. The verdict is correct and says nothing, and\n * a caller reading it as \"this workflow completes properly\" is misreading it, so\n * the verifier says so in the report.\n */\nexport function quiescenceUnreachable(flatNet: FlatNet, envInject: readonly Injection[]): boolean {\n return encodeQuiescent(flatNet, vars(flatNet.places.length, ''), envInject) === null;\n}\n\n/** Env-injectable bound map, index to cap (`null` = unbounded), for the coloured encoder. */\nexport function injectionMap(flatNet: FlatNet): Map<number, number | null> {\n const out = new Map<number, number | null>();\n for (const inj of resolveEnvInjection(flatNet)) out.set(inj.pid, inj.bound);\n return out;\n}\n","/**\n * @module certificate-checker\n *\n * Independent certificate check for IC3/PDR proofs.\n *\n * When Z3 Spacer answers `sat` on the CHC encoding ({@link module:smt-encoder}), the\n * model it prints interprets `Reachable` as an inductive invariant, the proof\n * certificate. This module re-verifies that certificate with plain (non-HORN) SMT\n * queries in a SECOND z3 run, so a `proven` verdict no longer rests on the empirical\n * HORN sat ⇒ proven mapping alone, nor on the correctness of the P-invariant\n * strengthening: the three verification conditions below are discharged against the\n * UNSTRENGTHENED step relation ({@link encodeStepRelationSmt2}).\n *\n * The candidate invariant is `R' := R ∧ Inv`, where `R` is the pasted `Reachable`\n * interpretation and `Inv` the validated P-invariant equalities the CHC encoding\n * strengthened its rule bodies with: a Spacer model is only guaranteed inductive\n * *relative to* that strengthening, so the conjuncts ride along in the candidate, but\n * the RELATION stays unstrengthened, which means VC1/VC2 re-prove each conjunct's\n * initiation and inductiveness from scratch. A wrong P-invariant cannot weaken this\n * check: it fails init or consecution instead.\n *\n * 1. **VC1 (init)**: `¬R'(M₀)` is UNSAT.\n * 2. **VC2 (consecution)**: `M ≥ 0 ∧ R'(M) ∧ T(M,M') ∧ ¬R'(M')` is UNSAT.\n * 3. **VC3 (safety)**: `M ≥ 0 ∧ R'(M) ∧ Bad(M)` is UNSAT.\n *\n * The `M ≥ 0` conjunct is the state domain: markings are token counts, so the VCs\n * range over ℕ^P; without it a certificate inductive over ℕ^P is refuted by a negative\n * predecessor in ℤ^P.\n *\n * The certificate is the `(define-fun …)` block of the `(get-model)` reply, pasted\n * verbatim: auxiliary definitions stay alongside `Reachable`, so every name resolves\n * in the fresh script. The three VCs run under `(push)`/`(pop)` in ONE script; the\n * emitted text is byte-identical to the Rust reference (`certificate_check.rs`) and\n * the Java port.\n *\n * Outcomes are split the way the caller must treat them: `failed` names the first VC\n * that was not UNSAT (with the solver status and, for SAT, a witness marking),\n * `unavailable` means the check could not run at all (missing or malformed\n * certificate, solver spawn failure, errored assert). Both withhold PROVEN; neither\n * throws.\n */\nimport type { FlatNet } from '../encoding/flat-net.js';\nimport { rethrowIfProgrammingError } from '../programming-error.js';\nimport type { MarkingState } from '../marking-state.js';\nimport type { SmtProperty } from '../smt-property.js';\nimport type { ConditionalSinks } from '../rest-set.js';\nimport type { PInvariant } from '../invariant/p-invariant.js';\nimport type { Place } from '../../core/place.js';\nimport {\n conjoin, encodePropertyViolation, encodeStepRelationSmt2, invariantConditions, resolveEnvInjection, stateEquationConditions } from './smt-encoder.js';\nimport { errorLine, sexprEnd, timeoutLine } from './smt-text.js';\nimport {\n hardTimeoutSecs, replySucceeded, runZ3Text, timeoutBudget, watchdogMs, type Z3Solver,\n} from './z3-process.js';\n\n/** Label of a validity condition, as it appears in the downgrade reason. */\nexport type CertificateVc = 'initiation (VC1)' | 'consecution (VC2)' | 'safety (VC3)';\n\nconst VC_LABELS: readonly CertificateVc[] = ['initiation (VC1)', 'consecution (VC2)', 'safety (VC3)'];\n\n/**\n * Outcome of the certificate check.\n *\n * `passed` — all three validity conditions are UNSAT; the proven verdict is certified\n * independently of the Fixedpoint engine.\n * `failed` — a validity condition was not UNSAT; `detail` carries the solver status\n * and, when the solver produced a model, a witness marking.\n * `unavailable` — the check could not run (missing/malformed certificate, solver\n * failure), so no VC is implicated.\n *\n * The caller must withhold PROVEN on `failed` and `unavailable` alike.\n */\nexport type CertificateCheckOutcome =\n | { readonly type: 'passed'; readonly invariant: string }\n | {\n readonly type: 'failed';\n readonly vc: CertificateVc;\n readonly detail: string;\n readonly invariant: string;\n }\n | { readonly type: 'unavailable'; readonly reason: string; readonly invariant: string | null };\n\n/**\n * Re-verifies an extracted proof certificate against the unstrengthened step relation.\n *\n * @param certificate the `(define-fun …)` block extracted verbatim from the Spacer\n * model (`null` when the solver printed none)\n * @param flatNet the flat net the CHC query was encoded from\n * @param initialMarking the verified initial marking (VC1)\n * @param property the verified property (VC3)\n * @param invariants the exactly-validated P-invariants the CHC bodies were\n * strengthened with; conjoined into the CANDIDATE certificate and re-proven by the\n * three VCs (never conjoined into the step relation)\n * @param sinkPlaces declared sink places (deadlock-freedom VC3)\n * @param solver the resolved z3 executable\n * @param timeoutMs per-invocation solver budget in milliseconds\n * @param conditionalSinks conditional sink declarations (VER-014, deadlock-freedom VC3)\n */\nexport async function checkCertificate(\n certificate: string | null,\n flatNet: FlatNet,\n initialMarking: MarkingState,\n property: SmtProperty,\n invariants: readonly PInvariant[],\n sinkPlaces: ReadonlySet<Place<any>>,\n solver: Z3Solver,\n timeoutMs: number,\n conditionalSinks: readonly ConditionalSinks[] = [],\n stateEquation = false,\n): Promise<CertificateCheckOutcome> {\n if (certificate == null) {\n return {\n type: 'unavailable',\n reason: 'no inductive invariant (define-fun block) could be extracted from the z3 model',\n invariant: null,\n };\n }\n const shape = shapeFailure(flatNet, invariants);\n if (shape != null) return { type: 'unavailable', reason: shape, invariant: certificate };\n if (!certificate.includes('(define-fun Reachable ') && !certificate.includes('(define-fun |Reachable| ')) {\n return { type: 'unavailable', reason: 'certificate does not define Reachable', invariant: certificate };\n }\n\n const vcs = buildVerificationConditions(certificate, flatNet, initialMarking, property, sinkPlaces, invariants, conditionalSinks, stateEquation);\n let results: string[];\n try {\n results = await runVcScript(script(vcs), timeoutMs, solver);\n } catch (e: any) {\n rethrowIfProgrammingError(e);\n return { type: 'unavailable', reason: String(e?.message ?? e), invariant: certificate };\n }\n for (let i = 0; i < results.length; i++) {\n if (results[i] !== 'unsat') {\n const detail = await detailFor(vcs, i, results[i]!, flatNet, timeoutMs, solver);\n return { type: 'failed', vc: VC_LABELS[i]!, detail, invariant: certificate };\n }\n }\n return { type: 'passed', invariant: certificate };\n}\n\n/**\n * The certificate-check script for the given inputs, exactly as\n * {@link checkCertificate} would send it (VER-013 script parity): what the\n * cross-language golden tests diff.\n */\nexport function vcScript(\n certificate: string,\n flatNet: FlatNet,\n initialMarking: MarkingState,\n property: SmtProperty,\n sinkPlaces: ReadonlySet<Place<any>>,\n invariants: readonly PInvariant[],\n conditionalSinks: readonly ConditionalSinks[] = [],\n stateEquation = false,\n): string {\n return script(buildVerificationConditions(certificate, flatNet, initialMarking, property, sinkPlaces, invariants, conditionalSinks, stateEquation));\n}\n\n/** Why the net and invariants cannot be indexed safely, or `null`. */\nfunction shapeFailure(flatNet: FlatNet, invariants: readonly PInvariant[]): string | null {\n const P = flatNet.places.length;\n for (const inv of invariants) {\n if (inv.weights.length !== P) {\n return `P-invariant has ${inv.weights.length} weights for a ${P}-place net`;\n }\n for (const pid of inv.support) {\n if (pid >= P || pid < 0) return `P-invariant support names place index ${pid} in a ${P}-place net`;\n }\n }\n return null;\n}\n\n/** A VC run that could not be trusted; the message is the reason. */\nclass VcFailure extends Error {}\n\n/**\n * Runs one plain-SMT script and returns the three positional `(check-sat)` answers.\n * Both output channels are inspected: an `(error …)` on EITHER stream means an assert\n * was dropped, which would silently make a VC vacuous; a `timeout` line, a watchdog\n * kill and a non-success exit mean the run did not complete. Only a clean\n * three-answer stdout counts.\n */\nasync function runVcScript(text: string, timeoutMs: number, solver: Z3Solver): Promise<string[]> {\n const reply = await runZ3Text(solver, text, 'certificate', timeoutMs, []);\n const budget = timeoutBudget(timeoutMs);\n const err = errorLine(reply.stderr);\n if (err != null) throw new VcFailure(`z3 reported an error on stderr: ${err}`);\n if (timeoutLine(reply.stdout)) {\n throw new VcFailure(`z3 hard timeout after ${hardTimeoutSecs(budget)}s while checking the certificate`);\n }\n if (reply.exit.kind === 'killed') {\n throw new VcFailure(`z3 did not exit within ${watchdogMs(budget)} ms while checking the certificate and was killed`);\n }\n const results = parseVcResults(reply.stdout);\n if (!replySucceeded(reply)) {\n const status = reply.exit.kind === 'exited' ? `exit status: ${reply.exit.code}` : 'the watchdog kill';\n throw new VcFailure(`z3 exited with ${status} after answering [${results.join(', ')}]`);\n }\n return results;\n}\n\n/**\n * Parses the three positional `(check-sat)` answers. Any `(error …)` line fails the\n * check outright (an errored assert silently vanishes from the query, which could\n * leave a VC vacuous); a `timeout` line is z3's `-T` backstop, not a fourth answer.\n */\nexport function parseVcResults(stdout: string): string[] {\n const err = errorLine(stdout);\n if (err != null) throw new VcFailure(`z3 error while checking the certificate: ${err}`);\n if (timeoutLine(stdout)) throw new VcFailure('z3 hard timeout while checking the certificate');\n const results = stdout\n .split('\\n')\n .map((l) => l.trim())\n .filter((l) => l === 'sat' || l === 'unsat' || l === 'unknown');\n if (results.length !== 3) {\n throw new VcFailure(`expected 3 VC answers from z3, got ${results.length}: [${results.join(', ')}]`);\n }\n return results;\n}\n\n/** The assembled VC script, kept in parts so one VC can be re-run alone. */\ninterface VerificationConditions {\n readonly prelude: readonly string[];\n /** The asserts of each VC, in `VC_LABELS` order. */\n readonly asserts: readonly (readonly string[])[];\n}\n\nfunction buildVerificationConditions(\n certificate: string,\n flatNet: FlatNet,\n initialMarking: MarkingState,\n property: SmtProperty,\n sinkPlaces: ReadonlySet<Place<any>>,\n invariants: readonly PInvariant[],\n conditionalSinks: readonly ConditionalSinks[],\n stateEquation: boolean,\n): VerificationConditions {\n const P = flatNet.places.length;\n // With the state equation (VER-016) the certificate ranges over the places AND\n // one firing counter per flat transition; the candidate then carries the marking\n // equation and `n >= 0` alongside the P-invariants, and the VCs re-prove them\n // against the raw step relation, whose only counter knowledge is the increment.\n const T = stateEquation ? flatNet.transitions.length : 0;\n const mVars: string[] = [];\n const mpVars: string[] = [];\n for (let i = 0; i < P; i++) {\n mVars.push(`m${i}`);\n mpVars.push(`m${i}p`);\n }\n const nVars: string[] = [];\n const npVars: string[] = [];\n for (let k = 0; k < T; k++) {\n nVars.push(`n${k}`);\n npVars.push(`n${k}p`);\n }\n const candidateOf = (m: readonly string[], n: readonly string[]): string => {\n const parts = [`(Reachable ${[...m, ...n].join(' ')})`, ...invariantConditions(invariants, m)];\n if (T > 0) {\n for (const v of n) parts.push(`(>= ${v} 0)`);\n parts.push(...stateEquationConditions(flatNet, initialMarking, n, m));\n }\n return conjoin(parts);\n };\n\n const prelude: string[] = [\n '; IC3/PDR certificate check (plain SMT-LIB2, not HORN):',\n '; each VC below must be unsat for the certificate to stand.',\n certificate,\n '',\n ];\n for (const v of mVars) prelude.push(`(declare-const ${v} Int)`);\n for (const v of mpVars) prelude.push(`(declare-const ${v} Int)`);\n for (const v of nVars) prelude.push(`(declare-const ${v} Int)`);\n for (const v of npVars) prelude.push(`(declare-const ${v} Int)`);\n\n // VC1 (init): the initial marking (and zero counters) satisfies the candidate invariant.\n const m0: string[] = [];\n for (let i = 0; i < P; i++) m0.push(String(initialMarking.tokens(flatNet.places[i]!)));\n const n0: string[] = new Array<string>(T).fill('0');\n const vc1 = [`(assert (not ${candidateOf(m0, n0)}))`];\n\n // The system lives in N^P, not Z^P.\n const nonNegative = [...mVars, ...nVars].map((v) => `(assert (>= ${v} 0))`);\n\n // VC2 (consecution): closed under the unstrengthened step relation.\n const step = encodeStepRelationSmt2(flatNet, stateEquation);\n const vc2 = [\n ...nonNegative,\n `(assert ${candidateOf(mVars, nVars)})`,\n `(assert ${step})`,\n `(assert (not ${candidateOf(mpVars, npVars)}))`,\n ];\n\n // VC3 (safety): excludes every property-violating state, exactly the violation\n // the CHC error rule encodes.\n const bad = encodePropertyViolation(flatNet, property, mVars, sinkPlaces, resolveEnvInjection(flatNet), conditionalSinks);\n const vc3 = [...nonNegative, `(assert ${candidateOf(mVars, nVars)})`, `(assert ${bad})`];\n\n return { prelude, asserts: [vc1, vc2, vc3] };\n}\n\n/** The full script: the prelude, then the three VCs under push/pop. */\nfunction script(vcs: VerificationConditions): string {\n const lines = [...vcs.prelude];\n for (let i = 0; i < vcs.asserts.length; i++) {\n lines.push('');\n lines.push(`; VC${i + 1} ${VC_LABELS[i]}`);\n lines.push('(push)');\n lines.push(...vcs.asserts[i]!);\n lines.push('(check-sat)');\n lines.push('(pop)');\n }\n return lines.join('\\n');\n}\n\n/**\n * Describes VC `i`'s non-`unsat` answer for the downgrade reason, by re-running that\n * VC alone with model/reason extraction enabled. Best effort: without it the answer is\n * still named.\n */\nasync function detailFor(\n vcs: VerificationConditions,\n i: number,\n answer: string,\n flatNet: FlatNet,\n timeoutMs: number,\n solver: Z3Solver,\n): Promise<string> {\n const lines = ['(set-option :produce-models true)', ...vcs.prelude, ...vcs.asserts[i]!, '(check-sat)'];\n lines.push(answer === 'sat' ? '(get-model)' : '(get-info :reason-unknown)');\n let reply = '';\n try {\n reply = (await runZ3Text(solver, lines.join('\\n'), 'certificate-detail', timeoutMs, [])).stdout;\n } catch {\n reply = '';\n }\n if (answer === 'sat') {\n const w = witness(reply, flatNet);\n return w == null ? 'solver returned SATISFIABLE' : `solver returned SATISFIABLE (witness: ${w})`;\n }\n const r = reasonUnknown(reply);\n return r == null ? 'solver returned UNKNOWN' : `solver returned UNKNOWN (${r})`;\n}\n\n/**\n * Reads the current-marking assignment out of a `(get-model)` reply as `p0=2, p1=1`\n * (place names, index order); `null` when no `m_i` was defined.\n */\nexport function witness(model: string, flatNet: FlatNet): string | null {\n const parts: string[] = [];\n for (let i = 0; i < flatNet.places.length; i++) {\n const needle = `(define-fun m${i} () Int`;\n const at = model.indexOf(needle);\n if (at < 0) continue;\n const rest = model.slice(at + needle.length).trimStart();\n let value: string;\n if (rest.startsWith('(')) {\n const end = sexprEnd(rest, 0);\n if (end < 0) continue;\n // A negative literal prints as `(- 1)`; flatten it back to `-1`.\n value = rest.slice(1, end - 1).trim().split(/\\s+/).join('');\n } else {\n let end = 0;\n while (end < rest.length && !/\\s/.test(rest[end]!) && rest[end] !== ')') end++;\n if (end === 0) continue;\n value = rest.slice(0, end);\n }\n parts.push(`${flatNet.places[i]!.name}=${value}`);\n }\n return parts.length === 0 ? null : parts.join(', ');\n}\n\n/** Reads z3's `(get-info :reason-unknown)` reply, e.g. `timeout`. */\nexport function reasonUnknown(reply: string): string | null {\n const at = reply.indexOf(':reason-unknown');\n if (at < 0) return null;\n const rest = reply.slice(at + ':reason-unknown'.length).trimStart();\n const end = rest.indexOf(')');\n if (end < 0) return null;\n let reason = rest.slice(0, end).trim();\n if (reason.startsWith('\"') && reason.endsWith('\"') && reason.length >= 2) reason = reason.slice(1, -1);\n reason = reason.trim();\n return reason === '' ? null : reason;\n}\n\n/**\n * The candidate invariant applied to a variable (or literal) vector:\n * `R'(vars) = (Reachable vars) ∧ Inv(vars)`.\n */\n\n","/**\n * @module linear-bound\n *\n * The linear state-equation bound (VER-015): a structural proof of a\n * reachability-safety property that needs no fixpoint search.\n *\n * Every reachable marking of the abstract net satisfies `M = M0 + C·σ` for some\n * firing count vector `σ ≥ 0`, so for any weighting `y ≥ 0` with `y·C ≤ 0` on every\n * transition, `y·M ≤ y·M0` holds along every run — a **decreasing** conservation\n * law, where the P-invariants of [VER-005] are the *equalities* `y·C = 0`. The\n * violation of a reachability-safety property is a lower demand on some places\n * (`m_p ≥ 1` for each place of an `unreachable`, `m_p ≥ k+1` for a `placeBound`);\n * if some `y` makes that demand exceed `y·M0`, no reachable marking meets it and the\n * property is proven.\n *\n * Finding `y` is one linear query in `QF_LIA`, answered by the same `z3` transport\n * as everything else ([VER-013]); the answer is then re-checked in exact integer\n * arithmetic (`y ≥ 0`, `y·C ≤ 0` per transition, `y·d ≥ y·M0 + 1`), so the proof\n * rests on the check, not on the solver. It closes exactly the class of proofs IC3\n * misses on pipeline-shaped nets: an ordering argument (\"both join slots armed means\n * every upstream stage has run, so no halt is still possible\") is a weighted count\n * bound, which Spacer's lemma generalisation does not invent over fifty variables\n * but a linear solver finds in milliseconds.\n *\n * Soundness needs the same guards as the equality laws: zero weight on every\n * consume-all / reset place (H1 — the fire relation is not linear there) and on\n * every injected environment place (H3' — injection breaks conservation).\n */\nimport type { FlatNet } from '../encoding/flat-net.js';\nimport type { MarkingState } from '../marking-state.js';\nimport type { SmtProperty } from '../smt-property.js';\nimport { nonlinearPlaces } from '../invariant/p-invariant-computer.js';\nimport { intTerm, resolveEnvInjection, sumTerms } from './smt-encoder.js';\nimport { extractDefineFuns } from './smt-text.js';\n\n/** One linear bound `Σ weights[p]·m_p ≤ constant`, with the demand it separates. */\nexport interface LinearBound {\n /** `y`, one entry per flat place, all non-negative. */\n readonly weights: readonly bigint[];\n /** `y·M0`. */\n readonly constant: bigint;\n /** `y·d`, what the violating markings need at least; strictly above `constant`. */\n readonly demandValue: bigint;\n}\n\n/**\n * The violation's demand: flat place index → the least count a violating marking\n * holds there. `null` when the property is not a reachability-safety property, or\n * names no place the net resolves (the verifier refuses those before this runs).\n */\nexport function violationDemand(flatNet: FlatNet, property: SmtProperty): Map<number, number> | null {\n const demand = new Map<number, number>();\n switch (property.type) {\n case 'unreachable':\n for (const p of property.places) {\n const pid = flatNet.placeIndex.get(p.name);\n if (pid != null) demand.set(pid, 1);\n }\n break;\n case 'mutual-exclusion': {\n for (const p of [property.p1, property.p2]) {\n const pid = flatNet.placeIndex.get(p.name);\n if (pid != null) demand.set(pid, 1);\n }\n break;\n }\n case 'place-bound':\n case 'branch-place-bound': {\n const pid = flatNet.placeIndex.get(property.place.name);\n if (pid != null) demand.set(pid, property.bound + 1);\n break;\n }\n case 'deadlock-free':\n case 'terminates-at-sink':\n case 'joined-or-dead-lettered':\n case 'quiescent-count':\n return null;\n }\n return demand.size === 0 ? null : demand;\n}\n\n/** The places whose weight is pinned to zero: H1 (consume-all / reset) and H3' (injected). */\nexport function zeroWeightPlaces(flatNet: FlatNet): Set<number> {\n const zero = new Set<number>(nonlinearPlaces(flatNet));\n for (const inj of resolveEnvInjection(flatNet)) zero.add(inj.pid);\n return zero;\n}\n\n/**\n * The `QF_LIA` script asking for a separating `y`, or `null` when the property has\n * no linear demand. Byte-identical across the four implementations: places in flat\n * index order, one row per flat transition in net order, `(- k)` for a negative\n * literal, a lone term unwrapped.\n */\nexport function encodeLinearBound(flatNet: FlatNet, initialMarking: MarkingState, property: SmtProperty): string | null {\n const demand = violationDemand(flatNet, property);\n if (demand == null) return null;\n const P = flatNet.places.length;\n const zero = zeroWeightPlaces(flatNet);\n const lines: string[] = [];\n lines.push('; Linear state-equation bound (VER-015): y >= 0 with y.C <= 0 on every');\n lines.push('; transition gives y.M <= y.M0 for every reachable M; sat = the violating');\n lines.push(\"; markings' demand exceeds that bound, so none is reachable.\");\n lines.push('(set-logic QF_LIA)');\n for (let p = 0; p < P; p++) lines.push(`(declare-const y${p} Int)`);\n for (let p = 0; p < P; p++) lines.push(`(assert (>= y${p} 0))`);\n for (const p of [...zero].sort((a, b) => a - b)) lines.push(`(assert (= y${p} 0))`);\n for (const ft of flatNet.transitions) {\n const terms: string[] = [];\n for (let p = 0; p < P; p++) {\n const c = ft.postVector[p]! - ft.preVector[p]!;\n if (c !== 0) terms.push(intTerm(c, `y${p}`));\n }\n if (terms.length > 0) lines.push(`(assert (<= ${sumTerms(terms)} 0))`);\n }\n const demandTerms: string[] = [];\n for (const p of [...demand.keys()].sort((a, b) => a - b)) demandTerms.push(intTerm(demand.get(p)!, `y${p}`));\n const initTerms: string[] = ['1'];\n for (let p = 0; p < P; p++) {\n const m0 = initialMarking.tokens(flatNet.places[p]!);\n if (m0 > 0) initTerms.push(intTerm(m0, `y${p}`));\n }\n lines.push(`(assert (>= ${sumTerms(demandTerms)} ${sumTerms(initTerms)}))`);\n lines.push('(check-sat)');\n lines.push('(get-model)');\n return lines.join('\\n');\n}\n\n/**\n * The weighting in a `sat` reply's model: `y_p` per flat place, zero where the model\n * is silent. `null` when the reply defines no `y`.\n */\nexport function decodeLinearBound(stdout: string, placeCount: number): bigint[] | null {\n const y = new Array<bigint>(placeCount).fill(0n);\n let seen = false;\n for (const def of extractDefineFuns(stdout)) {\n const m = /^\\(define-fun\\s+y(\\d+)\\s+\\(\\)\\s+Int\\s+(\\(-\\s*(\\d+)\\s*\\)|(\\d+))\\s*\\)$/s.exec(def.trim());\n if (m == null) continue;\n const pid = Number(m[1]);\n if (pid >= placeCount) continue;\n y[pid] = m[3] != null ? -BigInt(m[3]) : BigInt(m[4]!);\n seen = true;\n }\n return seen ? y : null;\n}\n\n/**\n * Re-proves the bound in exact integer arithmetic: `y ≥ 0`, zero on every H1/H3'\n * place, `y·C ≤ 0` on every flat transition, and `y·d ≥ y·M0 + 1`. Returns the bound\n * when every check passes and `null` otherwise — the verifier then continues to the\n * fixpoint query rather than trust the solver's model.\n */\nexport function checkLinearBoundExact(\n flatNet: FlatNet,\n initialMarking: MarkingState,\n property: SmtProperty,\n y: readonly bigint[],\n): LinearBound | null {\n const demand = violationDemand(flatNet, property);\n if (demand == null) return null;\n const P = flatNet.places.length;\n if (y.length !== P) return null;\n const zero = zeroWeightPlaces(flatNet);\n for (let p = 0; p < P; p++) {\n if (y[p]! < 0n) return null;\n if (zero.has(p) && y[p]! !== 0n) return null;\n }\n for (const ft of flatNet.transitions) {\n let delta = 0n;\n for (let p = 0; p < P; p++) {\n if (y[p]! === 0n) continue;\n delta += y[p]! * BigInt(ft.postVector[p]! - ft.preVector[p]!);\n }\n if (delta > 0n) return null;\n }\n let constant = 0n;\n for (let p = 0; p < P; p++) {\n if (y[p]! !== 0n) constant += y[p]! * BigInt(initialMarking.tokens(flatNet.places[p]!));\n }\n let demandValue = 0n;\n for (const [p, d] of demand) demandValue += y[p]! * BigInt(d);\n if (demandValue < constant + 1n) return null;\n return { weights: y, constant, demandValue };\n}\n\n/** `2*a + b <= 2` — the bound as the report prints it. */\nexport function formatLinearBound(flatNet: FlatNet, bound: LinearBound): string {\n const parts: string[] = [];\n for (let p = 0; p < bound.weights.length; p++) {\n const w = bound.weights[p]!;\n if (w === 0n) continue;\n parts.push(w === 1n ? flatNet.places[p]!.name : `${w}*${flatNet.places[p]!.name}`);\n }\n return `${parts.length === 0 ? '0' : parts.join(' + ')} <= ${bound.constant}`;\n}\n\n/** `ready_0 + ready_1 + _halt >= 3` — the violation's weighted demand as the report prints it. */\nexport function formatLinearDemand(flatNet: FlatNet, property: SmtProperty, bound: LinearBound): string {\n const demand = violationDemand(flatNet, property) ?? new Map<number, number>();\n const parts: string[] = [];\n for (const p of [...demand.keys()].sort((a, b) => a - b)) {\n const w = bound.weights[p]! * BigInt(demand.get(p)!);\n if (w === 0n) continue;\n parts.push(w === 1n ? flatNet.places[p]!.name : `${w}*${flatNet.places[p]!.name}`);\n }\n return `${parts.length === 0 ? '0' : parts.join(' + ')} >= ${bound.demandValue}`;\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 abstract-replayer\n *\n * Pure TS-side replayer for Spacer counterexamples over the ABSTRACT\n * (untimed, value-blind) count-vector semantics — the exact semantics the CHC\n * encoder emits and the Lean development verifies:\n *\n * - {@link enabledA} mirrors `lean/Libpetri/Basic.lean` `enabledA` and the\n * encoder's `encodeEnabled` arm (smt-encoder.ts): every input place holds at\n * least `pre[p]` tokens, every inhibited place is empty, every read place is\n * non-empty.\n * - {@link fireA} mirrors `Basic.lean` `fireA` and the encoder's `encodeFire`\n * arm: a reset or consume-all (`All`/`AtLeast`) place jumps to `post[p]`;\n * every other place moves by `M[p] - pre[p] + post[p]`.\n * - {@link successors} mirrors one disjunct of `encodeStepRelation`: a firing\n * is a successor only when its `M'` also respects `environmentBounds` (the\n * `envBounds(M')` conjunct every transition disjunct carries), and one\n * injection per modeled environment place whose guard admits it.\n * - {@link injectA} mirrors `encodeInjectionFire`/`encodeInjectionGuard`\n * (VER-006): one environment injection adds one token to the env place,\n * gated by `M[p] < k` for `Bounded(k)` and unguarded for `AlwaysAvailable`.\n * - {@link satisfiesBad} mirrors `encodePropertyViolation` — including the\n * relax-env deadlock enablement and the declared-sink exemption — as a\n * direct TS evaluator, so confirming a counterexample never needs a Z3 call.\n *\n * Because the abstraction over-approximates the concrete timed/valued net\n * (VER-004), a decoded counterexample can be spurious. This module therefore\n * only ever REPORTS an outcome ({@link ReplayOutcome}) — nothing here is\n * allowed to certify by crashing, and only the `no-chain` outcome (a fully\n * explored search that found no chain) is strong enough to withdraw a verdict.\n */\nimport type { FlatNet } from '../encoding/flat-net.js';\nimport type { FlatTransition } from '../encoding/flat-transition.js';\nimport type { SmtProperty } from '../smt-property.js';\nimport type { Place } from '../../core/place.js';\nimport { strandingExcuses, type ConditionalSinks } from '../rest-set.js';\nimport { MarkingState } from '../marking-state.js';\nimport { flatNetIndexOf } from '../encoding/flat-net.js';\n\n/** An abstract marking: token count per flat place index. */\nexport type AbstractState = readonly number[];\n\n/** One abstract step in a replayed chain. */\nexport type ReplayStep =\n | { readonly kind: 'fire'; readonly transition: string }\n | { readonly kind: 'inject'; readonly place: string };\n\n/** Display name for a step: the flat transition name, or `inject(<place>)`. */\nexport function stepName(step: ReplayStep): string {\n return step.kind === 'fire' ? step.transition : `inject(${step.place})`;\n}\n\n/** Canonical key for an abstract state (place counts joined by comma). */\nexport function stateKey(state: AbstractState): string {\n return state.join(',');\n}\n\n/** Projects a MarkingState onto the flat place indexing as a count vector. */\nexport function vectorize(marking: MarkingState, flatNet: FlatNet): number[] {\n return flatNet.places.map(p => marking.tokens(p));\n}\n\n/** Rebuilds a MarkingState from a count vector (inverse of {@link vectorize}). */\nexport function toMarkingState(state: AbstractState, flatNet: FlatNet): MarkingState {\n const builder = MarkingState.builder();\n for (let i = 0; i < flatNet.places.length; i++) {\n if (state[i]! > 0) builder.tokens(flatNet.places[i]!, state[i]!);\n }\n return builder.build();\n}\n\n/**\n * Abstract enablement (`Basic.lean` `enabledA`; encoder `encodeEnabled` with\n * `relaxEnv = false`): `M[p] >= pre[p]` per input, `M[p] = 0` per inhibitor,\n * `M[p] >= 1` per read. The encoder's non-negativity conjunct is invariant\n * here (states start in ℕ^P and every step preserves it), so it is not\n * re-checked.\n */\nexport function enabledA(state: AbstractState, ft: FlatTransition): boolean {\n const P = state.length;\n for (let p = 0; p < P; p++) {\n if (ft.preVector[p]! > 0 && state[p]! < ft.preVector[p]!) return false;\n }\n for (const p of ft.readPlaces) {\n if (state[p]! < 1) return false;\n }\n for (const p of ft.inhibitorPlaces) {\n if (state[p]! !== 0) return false;\n }\n return true;\n}\n\n/**\n * The abstract fire relation (`Basic.lean` `fireA`; encoder `encodeFire`):\n *\n * - reset place → `M'[p] = post[p]`\n * - consume-all place → `M'[p] = post[p]` (All/AtLeast drain the place)\n * - otherwise → `M'[p] = M[p] - pre[p] + post[p]`\n */\nexport function fireA(state: AbstractState, ft: FlatTransition): number[] {\n return fireIndexed(state, ft, new Set(ft.resetPlaces));\n}\n\n/** {@link fireA} with the transition's reset places already indexed. */\nfunction fireIndexed(\n state: AbstractState,\n ft: FlatTransition,\n resets: ReadonlySet<number>,\n): number[] {\n const P = state.length;\n const next = new Array<number>(P);\n for (let p = 0; p < P; p++) {\n if (resets.has(p) || ft.consumeAll[p]) {\n next[p] = ft.postVector[p]!;\n } else {\n next[p] = state[p]! - ft.preVector[p]! + ft.postVector[p]!;\n }\n }\n return next;\n}\n\n/**\n * One environment injection (encoder `encodeInjectionFire`): adds one token at\n * `idx`, all other places unchanged. Callers gate on the bound (VER-006).\n */\nexport function injectA(state: AbstractState, idx: number): number[] {\n const next = [...state];\n next[idx] = next[idx]! + 1;\n return next;\n}\n\n/** A successor state together with the step that produced it. */\nexport interface Successor {\n readonly state: number[];\n readonly step: ReplayStep;\n}\n\n/**\n * Per-replay indexes over a flat net, built once and reused by every expansion:\n * reset places per transition, the injection map, and the environment post-caps\n * every transition disjunct of the step relation carries.\n */\ninterface ReplayIndex {\n readonly flatNet: FlatNet;\n /** `resetSets[t]` — reset place indices of `flatNet.transitions[t]`. */\n readonly resetSets: readonly ReadonlySet<number>[];\n /** Injected env place index -> injection bound (`null` = unbounded). */\n readonly envInj: ReadonlyMap<number, number | null>;\n /** `environmentBounds` as `[place index, cap]` pairs: `M'[idx] <= cap`. */\n readonly envCaps: readonly (readonly [number, number])[];\n}\n\nfunction buildIndex(flatNet: FlatNet): ReplayIndex {\n const resetSets = flatNet.transitions.map(ft => new Set(ft.resetPlaces));\n const envInj = new Map<number, number | null>();\n for (const [name, bound] of flatNet.environmentInjection) {\n const idx = flatNet.placeIndex.get(name);\n if (idx != null) envInj.set(idx, bound);\n }\n return { flatNet, resetSets, envInj, envCaps: environmentCaps(flatNet) };\n}\n\n/** `environmentBounds` as `[place index, cap]` pairs (`M'[idx] <= cap`), in the net's own order. */\nexport function environmentCaps(flatNet: FlatNet): [number, number][] {\n const caps: [number, number][] = [];\n for (const [name, cap] of flatNet.environmentBounds) {\n const idx = flatNet.placeIndex.get(name);\n if (idx != null) caps.push([idx, cap]);\n }\n return caps;\n}\n\n/** The `envBounds(M')` conjunct of every transition disjunct (smt-encoder.ts). */\nfunction withinEnvBounds(index: ReplayIndex, state: AbstractState): boolean {\n for (const [idx, cap] of index.envCaps) {\n if (state[idx]! > cap) return false;\n }\n return true;\n}\n\n/**\n * All abstract successors of a state under the UNSTRENGTHENED step relation:\n * every enabled flat transition whose successor also respects the environment\n * post-caps, plus one injection per modeled environment place whose guard\n * admits it (`M[p] < k` for `Bounded(k)`, always for `AlwaysAvailable`).\n */\nexport function successors(state: AbstractState, flatNet: FlatNet): Successor[] {\n return successorsIndexed(buildIndex(flatNet), state);\n}\n\nfunction successorsIndexed(index: ReplayIndex, state: AbstractState): Successor[] {\n const out: Successor[] = [];\n const transitions = index.flatNet.transitions;\n for (let t = 0; t < transitions.length; t++) {\n const ft = transitions[t]!;\n if (!enabledA(state, ft)) continue;\n const next = fireIndexed(state, ft, index.resetSets[t]!);\n // The encoder conjoins envBounds(M') into every transition disjunct: a\n // firing that would push an environment place over its cap is NOT a step of\n // the encoded system, and chaining through one would confirm a trace the\n // CHC system cannot produce.\n if (!withinEnvBounds(index, next)) continue;\n out.push({ state: next, step: { kind: 'fire', transition: ft.name } });\n }\n for (const [name, bound] of index.flatNet.environmentInjection) {\n const idx = index.flatNet.placeIndex.get(name);\n if (idx == null) continue;\n if (bound === null || state[idx]! < bound) {\n out.push({ state: injectA(state, idx), step: { kind: 'inject', place: name } });\n }\n }\n return out;\n}\n\n/**\n * Relax-env enablement (encoder `encodeEnabled` with `relaxEnv = true`), used\n * only inside the deadlock predicate: input/read requirements on injectable\n * environment places are satisfiable by external injection — `AlwaysAvailable`\n * always, `Bounded(k)` iff the required cardinality is ≤ k.\n */\nfunction enabledRelaxEnv(\n state: AbstractState,\n ft: FlatTransition,\n envInj: ReadonlyMap<number, number | null>,\n): boolean {\n const P = state.length;\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 false; // never enableable\n continue; // satisfiable by injection\n }\n if (state[p]! < pre) return false;\n }\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 false;\n continue;\n }\n if (state[p]! < 1) return false;\n }\n for (const p of ft.inhibitorPlaces) {\n if (state[p]! !== 0) return false;\n }\n return true;\n}\n\n/**\n * Quiescence predicate (encoder `encodeQuiescent`): no flat transition is enabled\n * under relax-env semantics — a marking an external injection could re-enable is\n * NOT quiescent (VER-006).\n *\n * Carries no sink handling: each property in {@link satisfiesBad} conjoins its own\n * clause, exactly as the encoder does.\n */\nfunction isQuiescent(index: ReplayIndex, state: AbstractState): boolean {\n for (const ft of index.flatNet.transitions) {\n if (enabledRelaxEnv(state, ft, index.envInj)) return false;\n }\n return true;\n}\n\n/**\n * The flat indices of `places` that resolve, mirroring the encoder's `indexOrdered`. A\n * place the net does not declare is dropped, which makes a property stricter, never laxer.\n */\nfunction resolvedIndices(flatNet: FlatNet, places: Iterable<Place<any>>): Set<number> {\n const idx = new Set<number>();\n for (const place of places) {\n const i = flatNetIndexOf(flatNet, place);\n if (i >= 0) idx.add(i);\n }\n return idx;\n}\n\n/**\n * TS evaluator of the property-violation predicate `Bad(M)` — the direct\n * mirror of the encoder's `encodePropertyViolation`, arm for arm: shared\n * quiescence plus each property's own clause (VER-002 DeadlockFree strands a\n * token outside the sinks, TerminatesAtSink marks no sink, NU-040\n * JoinedOrDeadLettered has no sink clause at all), and the \"unresolved place\"\n * edge cases (unknown pending → never violated; unresolved unreachable places\n * are skipped, exactly as the encoder skips them).\n */\nexport function satisfiesBad(\n state: AbstractState,\n flatNet: FlatNet,\n property: SmtProperty,\n sinkPlaces: ReadonlySet<Place<any>>,\n conditionalSinks: readonly ConditionalSinks[] = [],\n): boolean {\n return satisfiesBadIndexed(buildIndex(flatNet), state, property, sinkPlaces, conditionalSinks);\n}\n\n/**\n * {@link satisfiesBad} with the net indexed once, for a search that tests many\n * states (the state-equation phase's witness search, VER-018).\n */\nexport function violationPredicate(\n flatNet: FlatNet,\n property: SmtProperty,\n sinkPlaces: ReadonlySet<Place<any>>,\n conditionalSinks: readonly ConditionalSinks[] = [],\n): (state: AbstractState) => boolean {\n const index = buildIndex(flatNet);\n return (state) => satisfiesBadIndexed(index, state, property, sinkPlaces, conditionalSinks);\n}\n\nfunction satisfiesBadIndexed(\n index: ReplayIndex,\n state: AbstractState,\n property: SmtProperty,\n sinkPlaces: ReadonlySet<Place<any>>,\n conditionalSinks: readonly ConditionalSinks[],\n): boolean {\n const flatNet = index.flatNet;\n switch (property.type) {\n // DeadlockFree (VER-002): quiescent AND some marked place is not where resting\n // is permitted — a conditional sink (VER-014) counts only while every marker\n // that would excuse it is unmarked. Mirrors the encoder's `stranded` disjunction.\n case 'deadlock-free': {\n if (!isQuiescent(index, state)) return false;\n const excuses = strandingExcuses(flatNet, sinkPlaces, conditionalSinks);\n for (let pid = 0; pid < flatNet.places.length; pid++) {\n const markers = excuses[pid];\n if (markers == null || state[pid]! < 1) continue;\n if (markers.every(k => state[k] === 0)) return true;\n }\n return false;\n }\n // TerminatesAtSink (VER-002): quiescent AND no declared sink marked.\n case 'terminates-at-sink': {\n if (!isQuiescent(index, state)) return false;\n for (const pid of resolvedIndices(flatNet, sinkPlaces)) {\n if (state[pid]! !== 0) return false;\n }\n return true;\n }\n case 'mutual-exclusion': {\n const idx1 = flatNetIndexOf(flatNet, property.p1);\n const idx2 = flatNetIndexOf(flatNet, property.p2);\n if (idx1 < 0 || idx2 < 0) return false; // encoder would have thrown before replay\n return state[idx1]! >= 1 && state[idx2]! >= 1;\n }\n case 'place-bound':\n case 'branch-place-bound': {\n const idx = flatNetIndexOf(flatNet, property.place);\n if (idx < 0) return false; // encoder would have thrown before replay\n return state[idx]! > property.bound;\n }\n // JoinedOrDeadLettered (NU-040 AC4): quiescent AND `pending` marked. No sink\n // clause — a marked sink must not excuse a stranded group.\n case 'joined-or-dead-lettered': {\n const idx = flatNetIndexOf(flatNet, property.pending);\n if (idx < 0) return false; // mirror: unknown pending place is never a violation\n return isQuiescent(index, state) && state[idx]! >= 1;\n }\n case 'unreachable': {\n let resolved = 0;\n for (const p of property.places) {\n const idx = flatNetIndexOf(flatNet, p);\n if (idx < 0) continue; // unresolved places skipped (encoder parity)\n resolved++;\n if (state[idx]! < 1) return false;\n }\n // With nothing resolved the conjunction would be vacuously true and EVERY\n // marking would violate — replay would then \"confirm\" at M0.\n return resolved > 0;\n }\n // QuiescentCount (VER-002): quiescent AND the count across the resolved places, each\n // once, is above `max` or below `min` with every resolved waiver empty. Mirrors\n // `countViolationCondition`, whose `min > 0` / finite-`max` guards only decide whether\n // a clause is emitted.\n case 'quiescent-count': {\n if (!isQuiescent(index, state)) return false;\n let count = 0;\n for (const i of resolvedIndices(flatNet, property.places)) count += state[i]!;\n if (count > property.max) return true;\n if (count < property.min) {\n for (const k of resolvedIndices(flatNet, property.waivedBy)) if (state[k]! !== 0) return false;\n return true;\n }\n return false;\n }\n }\n}\n\n/** Options for {@link replayCounterexample}. */\nexport interface ReplayOptions {\n /** Max abstract steps searched between decoded anchors (default 3). */\n readonly segmentBudget?: number;\n /**\n * Max search nodes ADMITTED to the whole search (default 10_000).\n *\n * A node is admitted when it survives the segment budget and the domination\n * check; dominated successors are never admitted and never counted. The root\n * (`M₀`) counts as the first admitted node, and the search stops as soon as\n * `nodeBudget` nodes have been admitted and another one is due — the same\n * `>=`-before-admission rule the Rust and Java replayers apply, so the same\n * nominal budget means the same effective search depth in all of them.\n */\n readonly nodeBudget?: number;\n}\n\n/**\n * Outcome of an abstract replay attempt.\n *\n * `confirmed` — a genuine abstract chain `M₀ → … → Bad` was found.\n * `no-chain` — the search ran to completion without truncation and no chain\n * exists: the counterexample is spurious or the decoder mis-read the\n * derivation, and ONLY this outcome may withdraw a `violated` verdict.\n * `exhausted` — the search was cut short (node or segment budget, or `M₀` was\n * not among the decoded states), so nothing was proved either way.\n */\nexport type ReplayOutcome =\n | {\n readonly kind: 'confirmed';\n /** The replayed chain in FIRING order, `M₀ … M_bad` inclusive. */\n readonly states: readonly AbstractState[];\n /** One step per consecutive pair of {@link states}. */\n readonly steps: readonly ReplayStep[];\n readonly nodesExplored: number;\n }\n | { readonly kind: 'no-chain'; readonly nodesExplored: number }\n | { readonly kind: 'exhausted'; readonly reason: string; readonly nodesExplored: number };\n\n/** One BFS node; the chain is recovered by walking `parent` back to the root. */\ninterface SearchNode {\n readonly state: AbstractState;\n /** The step that produced {@link state}; null at the root (`M₀`). */\n readonly step: ReplayStep | null;\n /** Index of the predecessor node, or -1 at the root. */\n readonly parent: number;\n /** Steps taken since the last decoded anchor (0 at an anchor). */\n readonly segment: number;\n}\n\n/**\n * Attempts to re-execute a decoded (order-free) counterexample state set in\n * the abstract semantics.\n *\n * The decoder collects Spacer's `Reachable` applications in derivation\n * TRAVERSAL order, which is not firing order; this search recovers a firing\n * order or reports that none exists. It is a single global breadth-first\n * search from `initial` over {@link successors}, where each node carries the\n * number of steps taken since the last decoded state (`segment`, reset to 0\n * whenever a decoded state is reached) and a node is expanded only while that\n * counter is below `segmentBudget`. A state is re-entered only when reached\n * with a strictly smaller segment counter (domination by `(state, segment)`),\n * and the whole search shares one `nodeBudget` counting nodes ADMITTED to the\n * search — non-dominated states only, the root included (see\n * {@link ReplayOptions.nodeBudget}).\n */\nexport function replayCounterexample(\n flatNet: FlatNet,\n initial: AbstractState,\n decodedStates: readonly AbstractState[],\n property: SmtProperty,\n sinkPlaces: ReadonlySet<Place<any>>,\n options: ReplayOptions = {},\n conditionalSinks: readonly ConditionalSinks[] = [],\n): ReplayOutcome {\n const segmentBudget = options.segmentBudget ?? 3;\n const nodeBudget = options.nodeBudget ?? 10_000;\n\n const anchors = new Set<string>();\n for (const s of decodedStates) anchors.add(stateKey(s));\n\n if (anchors.size === 0) {\n return { kind: 'exhausted', reason: 'no decoded states to replay', nodesExplored: 0 };\n }\n\n const initKey = stateKey(initial);\n if (!anchors.has(initKey)) {\n // Not evidence against the counterexample — the decoder simply did not\n // recover the init fact, so there is no anchored search to run.\n return {\n kind: 'exhausted',\n reason: 'the initial marking is not among the decoded states',\n nodesExplored: 0,\n };\n }\n\n const index = buildIndex(flatNet);\n if (satisfiesBadIndexed(index, initial, property, sinkPlaces, conditionalSinks)) {\n return { kind: 'confirmed', states: [initial], steps: [], nodesExplored: 1 };\n }\n\n const nodes: SearchNode[] = [{ state: initial, step: null, parent: -1, segment: 0 }];\n const bestSegment = new Map<string, number>([[initKey, 0]]);\n const queue: number[] = [0];\n let truncated = false;\n\n for (let head = 0; head < queue.length; head++) {\n const idx = queue[head]!;\n const node = nodes[idx]!;\n if (node.segment >= segmentBudget) {\n truncated = true; // the segment budget, not the state space, stopped us here\n continue;\n }\n for (const succ of successorsIndexed(index, node.state)) {\n const key = stateKey(succ.state);\n const segment = anchors.has(key) ? 0 : node.segment + 1;\n const prior = bestSegment.get(key);\n if (prior !== undefined && prior <= segment) continue; // dominated\n bestSegment.set(key, segment);\n\n // Checked BEFORE admission and with `>=`, so at most `nodeBudget` nodes\n // ever enter the search (the root among them) — same rule, same effective\n // depth, as the Rust and Java replayers.\n if (nodes.length >= nodeBudget) {\n return {\n kind: 'exhausted',\n reason: `search budget exhausted (${nodeBudget} nodes) before reaching a violating state`,\n nodesExplored: nodes.length,\n };\n }\n nodes.push({ state: succ.state, step: succ.step, parent: idx, segment });\n const childIdx = nodes.length - 1;\n if (satisfiesBadIndexed(index, succ.state, property, sinkPlaces, conditionalSinks)) {\n const chain = reconstruct(nodes, childIdx);\n return { kind: 'confirmed', ...chain, nodesExplored: nodes.length };\n }\n queue.push(childIdx);\n }\n }\n\n if (truncated) {\n return {\n kind: 'exhausted',\n reason:\n `no violating state within ${segmentBudget} abstract step(s) of a decoded state ` +\n `(${bestSegment.size} state(s) explored)`,\n nodesExplored: nodes.length,\n };\n }\n return { kind: 'no-chain', nodesExplored: nodes.length };\n}\n\n/** Walks `parent` links back to the root, yielding the chain in firing order. */\nfunction reconstruct(\n nodes: readonly SearchNode[],\n last: number,\n): { states: readonly AbstractState[]; steps: readonly ReplayStep[] } {\n const states: AbstractState[] = [];\n const steps: ReplayStep[] = [];\n for (let i = last; i >= 0; i = nodes[i]!.parent) {\n const node = nodes[i]!;\n states.push(node.state);\n if (node.step != null) steps.push(node.step);\n }\n states.reverse();\n steps.reverse();\n return { states, steps };\n}\n","/**\n * @module graph-decision\n *\n * The property predicate both state-class-graph routes decide, in one place.\n *\n * Two routes enumerate a finite graph of classes and read a verdict off it: the\n * ν name-partition quotient of [VER-012] (`nu-scg-verifier`) and the plain\n * bounded enumeration of [VER-017] (`scg-verifier`). They explore different\n * graphs, but the question they ask of a class is identical, and [VER-002] AC7\n * requires every route to decide the *same* predicate. Stating it once is what\n * keeps that true: when the sink clause last lived in two copies, one of them\n * drifted (NU-040 AC4).\n */\nimport type { Place } from '../core/place.js';\nimport { countViolation } from './count-clause.js';\nimport type { MarkingState } from './marking-state.js';\nimport type { SmtProperty } from './smt-property.js';\nimport { strandsToken, type ConditionalSinks } from './rest-set.js';\n\n/** A finite graph of classes, indexed `0 .. count - 1`, class 0 the initial one. */\nexport interface ClassView {\n readonly count: number;\n /** The marking of class `i`. */\n markingOf(i: number): MarkingState;\n /** Whether class `i` has no successor — the graph's quiescence. */\n isQuiescent(i: number): boolean;\n}\n\n/**\n * The index of the first class witnessing a violation, or `-1` when the property\n * holds across the whole graph.\n *\n * Quiescence-based properties read `isQuiescent`; reachability-safety properties\n * read the marking alone. `DeadlockFree` uses the shared rest set of [VER-014],\n * so a conditional sink excuses a token exactly as it does in the encoders.\n */\nexport function decideOverClasses(\n view: ClassView,\n property: SmtProperty,\n sinkPlaces: ReadonlySet<Place<any>>,\n conditionalSinks: readonly ConditionalSinks[] = [],\n): number {\n const firstWhere = (pred: (i: number) => boolean): number => {\n for (let i = 0; i < view.count; 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 => view.markingOf(i).tokens(property.place) > property.bound);\n case 'unreachable':\n return firstWhere(i => {\n const m = view.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 = view.markingOf(i);\n return m.hasTokens(property.p1) && m.hasTokens(property.p2);\n });\n // DeadlockFree (VER-002): a quiescent class that strands a token — some marked\n // place is not where resting is permitted, the conditional sinks of VER-014\n // included. The empty marking strands nothing (AC4).\n case 'deadlock-free':\n return firstWhere(i => view.isQuiescent(i) && strandsToken(view.markingOf(i), sinkPlaces, conditionalSinks));\n // TerminatesAtSink (VER-002): a quiescent class that marks NO declared sink.\n // Inverts with DeadlockFree on the empty marking, by design.\n case 'terminates-at-sink':\n return firstWhere(i => view.isQuiescent(i) && !anySinkMarked(view.markingOf(i), sinkPlaces));\n // JoinedOrDeadLettered (NU-040 AC4): a quiescent class still holding a pending\n // token. No sink clause.\n case 'joined-or-dead-lettered':\n return firstWhere(i => view.isQuiescent(i) && view.markingOf(i).hasTokens(property.pending));\n // QuiescentCount (VER-002): a quiescent class whose count across the places is below\n // the lower bound with no waiver marked, or above the upper bound.\n case 'quiescent-count':\n return firstWhere(i => view.isQuiescent(i)\n && countViolation(view.markingOf(i), property.places, property.min, property.max, property.waivedBy) !== null);\n }\n}\n\n/** Whether any declared sink place holds a token in `m` ([VER-002]). */\nfunction anySinkMarked(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 true;\n }\n return false;\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 /**\n * The same zone with its clocks reordered: clock `k` of the result is clock\n * `order[k]` of this DBM. `order` must be a permutation of `0..clockCount()-1`.\n *\n * The state-class graph applies this to put every class's clocks in the one\n * canonical order (VER-010), so two arrivals at the same marking and zone whose\n * transitions became enabled in a different sequence share a key instead of\n * being counted as two classes. The reference row and column stay put; the\n * matrix is copied once, O(dim²) against the O(dim³) canonicalisation every\n * successor already pays.\n */\n permuted(order: readonly number[]): DBM {\n if (this._empty) return this;\n const n = this.clockNames.length;\n const dim = this.dim;\n const out = new Float64Array(dim * dim);\n out[0] = 0;\n const names: string[] = new Array<string>(n);\n for (let i = 0; i < n; i++) {\n const oi = order[i]! + 1;\n names[i] = this.clockNames[order[i]!]!;\n out[(i + 1) * dim] = this.bounds[oi * dim]!;\n out[i + 1] = this.bounds[oi]!;\n for (let j = 0; j < n; j++) {\n out[(i + 1) * dim + (j + 1)] = this.bounds[oi * dim + (order[j]! + 1)]!;\n }\n }\n return new DBM(out, dim, names, false);\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 /**\n * The zone's identity for state-class dedup: the clock names and the FULL\n * canonical matrix, every difference bound included.\n *\n * {@link toString} prints only the per-clock projections `[lo, hi]`, and two\n * zones can agree on every projection while disagreeing on a difference\n * constraint `θi - θj <= c` — the class where one transition must fire no later\n * than another versus the class where either may go first. Keying on the\n * projections merges those, and since the graph explores only the first\n * arrival's successors, a marking reachable only from the second is lost: a\n * false `proven`. This key is what {@link equals} compares, rendered.\n */\n zoneKey(): string {\n if (this._empty) return 'DBM[empty]';\n const parts: string[] = [this.clockNames.join(',')];\n for (let i = 0; i < this.bounds.length; i++) parts.push(formatBound(this.bounds[i]!));\n return parts.join('|');\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 { consumptionCount } from '../../core/in.js';\nimport type { Transition } from '../../core/transition.js';\nimport type { PetriNet } from '../../core/petri-net.js';\nimport { earliest, immediate, latest, type Timing } 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';\nimport { compareCodePoints } from '../../core/internal/code-point-order.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/** Options for {@link StateClassGraph.build}. */\nexport interface StateClassGraphOptions {\n /**\n * Explore the **untimed** reachable set ([VER-004]): every clock gets `immediate()`'s\n * `[0, ∞)`, so any enabled transition may fire next and the graph holds exactly the\n * markings the untimed encoders reason about. No effect on an all-immediate net.\n */\n readonly untimed?: boolean;\n}\n\nconst IMMEDIATE: Timing = immediate();\n\n/** The timing a clock is given: the transition's own, or `immediate()` when exploring untimed. */\nfunction clockTiming(t: Transition, untimed: boolean): Timing {\n return untimed ? IMMEDIATE : t.timing;\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 options: StateClassGraphOptions = {},\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 const untimed = options.untimed === true;\n\n const initialClass = initialStateClass(net, initialMarking, envPlaces, envMode, untimed);\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, untimed);\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\n/**\n * The dedup key of a class: its marking and the full zone ({@link DBM.zoneKey}).\n *\n * Clocks are in canonical order by construction ({@link canonicalOrder}), so the\n * sequence in which transitions became enabled is not part of a class's identity —\n * it used to be, and on a workflow-shaped untimed net (every zone `[0, ∞)`) that\n * counted one marking once per interleaving of its enabling path: a measured\n * 1.5× class inflation, one marking held by fourteen classes.\n */\nfunction classKey(sc: StateClass): string {\n return `${sc.marking.toString()}|${sc.firingDomain.zoneKey()}`;\n}\n\n/**\n * The canonical clock order of an enabled set: ascending by transition name in code-point\n * order ([VER-013]), ties keeping their incoming order. Returns the permutation as indices\n * into `transitions`, or `null`, without allocating, when already in order.\n *\n * Observable: successors are explored in this order, which picks the shallowest witness a\n * report prints.\n */\nexport function canonicalOrder(transitions: readonly Transition[]): number[] | null {\n let sorted = true;\n for (let i = 1; i < transitions.length; i++) {\n if (compareCodePoints(transitions[i]!.name, transitions[i - 1]!.name) < 0) {\n sorted = false;\n break;\n }\n }\n if (sorted) return null;\n const order: number[] = new Array<number>(transitions.length);\n for (let i = 0; i < order.length; i++) order[i] = i;\n order.sort((a, b) => compareCodePoints(transitions[a]!.name, transitions[b]!.name) || a - b);\n return order;\n}\n\nfunction permute<T>(items: readonly T[], order: readonly number[]): T[] {\n const out: T[] = new Array<T>(items.length);\n for (let i = 0; i < order.length; i++) out[i] = items[order[i]!]!;\n return out;\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 untimed = false,\n): StateClass {\n const found = findEnabledTransitions(net, initialMarking, envPlaces, envMode);\n const order = canonicalOrder(found);\n const enabledTransitions = order === null ? found : permute(found, order);\n const clockNames = enabledTransitions.map(t => t.name);\n const lowerBounds = enabledTransitions.map(t => earliest(clockTiming(t, untimed)) / 1000);\n const upperBounds = enabledTransitions.map(t => latest(clockTiming(t, untimed)) / 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 untimed = false,\n): StateClass | null {\n const transition = fired.transition;\n\n // 1. Fire in two halves: the intermediate marking M - Pre(t) (inputs consumed, resets\n // drained, nothing produced yet), then the new marking.\n const intermediate = consumeInputs(current.marking, transition, environmentPlaces, environmentMode);\n const newMarking = produceOutputs(intermediate, fired.outputPlaces);\n\n // 2. Determine persistent and newly enabled transitions. A clock persists only when its\n // transition is not the fired one and stays enabled across the whole firing: in this\n // class, in the intermediate marking and in the new marking. A transition the firing\n // disables and re-enables (its token taken and put back, or a reset place refilled by\n // the outputs) is newly enabled with a fresh interval, as the executors restart its\n // clock (TIME-012). Surplus tokens keep it enabled throughout, so it stays persistent.\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 (\n t !== transition\n && newEnabledAll.includes(t)\n && isEnabled(t, intermediate, environmentPlaces, environmentMode)\n ) {\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(clockTiming(t, untimed)) / 1000);\n const newUpperBounds = newlyEnabled.map(t => latest(clockTiming(t, untimed)) / 1000);\n\n let firedDBM = current.firingDomain.fireTransition(\n firedIdx,\n newClockNames,\n newLowerBounds,\n newUpperBounds,\n persistentIndices,\n );\n\n // fireTransition lays the clocks out persistent-then-newly-enabled, which is\n // path-dependent; put them in canonical order so the class key is (VER-010).\n // The enabled list and the earliest-ready times below are permuted with them,\n // so index k means the same clock in all three.\n let allEnabled: Transition[] = [...persistent, ...newlyEnabled];\n const order = canonicalOrder(allEnabled);\n if (order !== null) {\n allEnabled = permute(allEnabled, order);\n firedDBM = firedDBM.permuted(order);\n }\n\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 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\n/**\n * Number of tokens this transition removes from `spec.place` when it fires,\n * given the `available` count currently in that place.\n *\n * Delegates to {@link consumptionCount} — the canonical IO-007 definition in\n * `core/in.ts`. The executors do not call it: `BitmapNetExecutor` fuses the\n * same rule into its consume loop (`bitmap-net-executor.ts:788`) and\n * `PrecompiledNetExecutor` compiles it to a CONSUME_ALL / CONSUME_ATLEAST\n * opcode resolved at run time (`precompiled-net.ts:440`). Three encodings of\n * one rule, which must stay in agreement.\n *\n * The analysis MUST NOT add a fourth: a divergent local definition here is\n * exactly what produced a verifier soundness bug (`all` was modelled as\n * consuming 1).\n *\n * `all` and `at-least` are **draining** arcs. The executor removes *every*\n * available token, not merely the minimum needed to enable. Do not\n * \"simplify\" this back to a constant. Modelling a minimum leaves residual\n * tokens the real net never holds; those phantom tokens keep inhibitor arcs\n * on the drained place unsatisfied, so successor state classes are never\n * generated and a genuinely reachable marking is reported unreachable. Since\n * `nu-scg-verifier` derives a `proven` verdict from this graph, that is a\n * false `Proven` — an unsound result, not merely an imprecise one.\n *\n * Note the deliberate asymmetry with {@link inputRequiredCount}\n * (`all` => 1, `at-least` => minimum): *enablement* tests the minimum,\n * *consumption* takes everything. Both are correct, for different questions.\n */\nfunction inputConsumeCount(spec: In, available: number): number {\n return consumptionCount(spec, available);\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\n/**\n * The first half of a firing: inputs consumed and reset places drained, nothing produced\n * yet. The result is the intermediate marking M - Pre(t) of Berthomieu and Diaz, on which\n * clock persistence is decided (TIME-012); {@link produceOutputs} completes the firing.\n */\nfunction consumeInputs(\n marking: MarkingState,\n transition: Transition,\n environmentPlaces: Set<Place<any>>,\n environmentMode: EnvironmentAnalysisMode,\n): MarkingState {\n const builder = MarkingState.builder().copyFrom(marking);\n\n // Consume from inputs. `all`/`at-least` drain the place, so the consumed\n // amount depends on what is actually there — read the current marking.\n for (const spec of transition.inputSpecs) {\n const available = marking.tokens(spec.place);\n if (available < inputRequiredCount(spec)) {\n // Only reachable for environment places under the always-available /\n // bounded modes, where enablement deliberately ignores the concrete\n // marking. consumeFromPlace is a no-op for those, so nothing to remove.\n continue;\n }\n const toConsume = inputConsumeCount(spec, available);\n consumeFromPlace(builder, spec.place, toConsume, environmentPlaces, environmentMode);\n }\n\n // Reset places: clear whatever is LEFT after the input loop, not what the\n // pre-firing marking held. Reading the original count overdraws whenever the\n // reset place is also an input — the inputs already took their share — and\n // `removeTokens` throws on the overdraw rather than mis-computing, so the whole\n // route died on a net both executors run happily. Setting the count states the\n // reset directly and cannot overdraw; it is also what the flat encoder emits\n // (`m'_p = postVector[p]` for a reset place, `firingConditions`), so the two\n // agree by construction. Outputs are produced after this, by produceOutputs,\n // so a place that is both reset and an output target ends at its post count\n // ([EXEC-013] AC4: consume, then read, then drain).\n for (const arc of transition.resets) {\n builder.tokens(arc.place, 0);\n }\n\n return builder.build();\n}\n\n/** The second half of a firing: one token into each output place of the fired branch. */\nfunction produceOutputs(\n intermediate: MarkingState,\n outputPlaces: ReadonlySet<Place<any>>,\n): MarkingState {\n const builder = MarkingState.builder().copyFrom(intermediate);\n for (const place of outputPlaces) {\n builder.addTokens(place, 1);\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","/**\n * @module scg-verifier\n *\n * Bounded state-space enumeration ([VER-017]): decide a property by building the\n * state-class graph and reading the verdict off it, when the graph closes within\n * a class budget.\n *\n * IC3/PDR is built for state spaces that are wide and shallow. A workflow net is\n * the opposite — narrow and deep: a forty-node pipeline has under two thousand\n * reachable classes, but its diameter is the length of the pipeline, so the\n * fixpoint engine needs a frame per stage and its cost climbs with the cube of\n * the length. Enumerating the same net is linear in the state space and finishes\n * in milliseconds. Measured on a forty-node chain (370 places): 410 s on the\n * fixpoint path, 0.11 s here.\n *\n * The route is exact when the graph closes — sound *and* complete, so a\n * `violated` is a real firing sequence rather than a possibly-spurious\n * over-approximation, and a `proven` is never the `unknown` a fixpoint search\n * runs out of time for.\n *\n * It applies only to an **untimed** net — every transition `immediate` — and that\n * restriction is what makes the verdict interchangeable with the encoders'. The\n * state-class graph carries firing domains, so on a timed net it would explore\n * only the runs the timing admits and its `proven` would be the weaker timed\n * claim; [VER-004] is explicit that the untimed proof is the stronger one, and a\n * route must not quietly hand back a weaker claim than the one it replaced. On an\n * untimed net no domain excludes anything, the graph explores exactly the untimed\n * reachable set, and the two routes decide the same predicate over the same\n * abstraction — enumeration simply decides it where the search may not.\n *\n * When the graph does not close within the budget the route declines and the\n * caller runs the SMT pipeline unchanged: enumeration never turns a verdict into\n * `unknown` that the solver could have decided.\n */\nimport type { PetriNet } from '../core/petri-net.js';\nimport type { Place } from '../core/place.js';\nimport type { MarkingState } from './marking-state.js';\nimport type { SmtProperty } from './smt-property.js';\nimport type { Verdict } from './smt-verification-result.js';\nimport type { ConditionalSinks } from './rest-set.js';\nimport { decideOverClasses } from './graph-decision.js';\nimport { StateClassGraph } from './analysis/state-class-graph.js';\nimport type { StateClass } from './analysis/state-class.js';\n\n/**\n * Whether every transition is `immediate`, so the state-class graph explores the\n * untimed reachable set exactly and its verdict is the encoders' claim rather\n * than the weaker timed one. See this module's header.\n */\nexport function isUntimed(net: PetriNet): boolean {\n for (const t of net.transitions) {\n if (t.timing.type !== 'immediate') return false;\n }\n return true;\n}\n\n/** The note a decided verdict carries into the report. */\nexport const NOTE_ENUMERATED =\n '\\nNote: decided by bounded state-space enumeration — the state-class graph closed, so the ' +\n 'verdict is sound AND complete: a `violated` is a real firing sequence, not a possibly-' +\n 'spurious over-approximation. The net is untimed, so this is the same claim the encoders ' +\n 'make (VER-017).\\n';\n\n/** Outcome of the enumeration route. */\nexport type ScgOutcome =\n /** The graph closed and decided the property. */\n | {\n readonly kind: 'decided';\n readonly verdict: Verdict;\n readonly trace: MarkingState[];\n readonly transitions: string[];\n readonly classCount: number;\n }\n /** The graph hit the class budget; the caller falls through to the SMT pipeline. */\n | { readonly kind: 'truncated'; readonly classCount: number };\n\n/**\n * Decides `property` by enumeration, or reports truncation.\n *\n * @param maxClasses the class budget; `<= 0` disables the route (the caller then\n * never calls this).\n */\nexport function verifyViaStateClassGraph(\n net: PetriNet,\n initial: MarkingState,\n property: SmtProperty,\n sinkPlaces: ReadonlySet<Place<any>>,\n maxClasses: number,\n conditionalSinks: readonly ConditionalSinks[] = [],\n): ScgOutcome {\n const graph = StateClassGraph.build(net, initial, maxClasses);\n const classes = graph.stateClasses();\n if (!graph.isComplete()) return { kind: 'truncated', classCount: classes.length };\n\n const violating = decideOverClasses(\n {\n count: classes.length,\n markingOf: i => classes[i]!.marking,\n isQuiescent: i => graph.successors(classes[i]!).size === 0,\n },\n property,\n sinkPlaces,\n conditionalSinks,\n );\n\n if (violating >= 0) {\n const [trace, transitions] = counterexamplePath(graph, classes[violating]!);\n return { kind: 'decided', verdict: { type: 'violated' }, trace, transitions, classCount: classes.length };\n }\n return {\n kind: 'decided',\n verdict: { type: 'proven', method: 'state-space enumeration (VER-017)', inductiveInvariant: null },\n trace: [],\n transitions: [],\n classCount: classes.length,\n };\n}\n\n/** Shortest firing sequence from the initial class to `target`, as markings and transition names. */\nfunction counterexamplePath(graph: StateClassGraph, target: StateClass): [MarkingState[], string[]] {\n const parent = new Map<StateClass, StateClass>();\n const via = new Map<StateClass, string>();\n const seen = new Set<StateClass>([graph.initialClass]);\n const queue: StateClass[] = [graph.initialClass];\n while (queue.length > 0) {\n const current = queue.shift()!;\n if (current === target) break;\n for (const [transition, edges] of graph.outgoingBranchEdges(current)) {\n for (const edge of edges) {\n if (seen.has(edge.target)) continue;\n seen.add(edge.target);\n parent.set(edge.target, current);\n via.set(edge.target, transition.name);\n queue.push(edge.target);\n }\n }\n }\n const chain: StateClass[] = [];\n for (let cur: StateClass | undefined = target; cur != null; cur = parent.get(cur)) {\n chain.push(cur);\n }\n chain.reverse();\n return [chain.map(sc => sc.marking), chain.slice(1).map(sc => via.get(sc)!)];\n}\n","/**\n * @module counterexample-decoder\n *\n * Decodes z3's refutation output into replayable counterexample material.\n *\n * There is exactly one decoder: {@link decodeStateSet}, which collects the ground\n * `Reachable` facts of a `:produce-proofs` refutation into a SET. The ordered trace\n * a caller sees is reconstructed from that set by the abstract replayer; the proof\n * printer's traversal order is not a firing order and was never safe to read as one.\n *\n * Applications with non-ground arguments (rule bodies quantify `Reachable` over\n * variables) or the wrong arity are skipped; a malformed proof simply yields a\n * smaller (possibly empty) set, never a throw. Byte-for-byte mirror of the Rust\n * `counterexample::decode_state_set`.\n */\nimport { MarkingState } from '../marking-state.js';\nimport type { FlatNet } from '../encoding/flat-net.js';\nimport { sexprEnd } from './smt-text.js';\n\n/** Result of counterexample decoding. */\nexport interface DecodedTrace {\n /**\n * The ground `Reachable` markings of the proof as an order-free set (text order\n * preserved for display), what the abstract replayer chains into a firing order.\n */\n readonly states: ReadonlySet<MarkingState>;\n /** Why nothing was decoded; `null` when `states` is non-empty. */\n readonly note: string | null;\n}\n\n/** Decodes the states of a z3 reply; a note says so when none were found. */\nexport function decode(answer: string, flatNet: FlatNet, counterCount = 0): DecodedTrace {\n const states = decodeStateSet(answer, flatNet, counterCount);\n return { states, note: states.size === 0 ? 'no ground Reachable states in the z3 proof' : null };\n}\n\n/**\n * Collects the ground `Reachable(...)` applications from a z3 refutation proof into\n * a state set, in text order.\n */\nexport function decodeStateSet(answer: string, flatNet: FlatNet, counterCount = 0): ReadonlySet<MarkingState> {\n const byKey = new Map<string, MarkingState>();\n const P = flatNet.places.length;\n // With the state equation (VER-016) a fact carries `counterCount` firing counters\n // after the places; the marking is the leading P arguments.\n for (const head of ['(Reachable', '(|Reachable|']) {\n let from = 0;\n for (;;) {\n const start = answer.indexOf(head, from);\n if (start < 0) break;\n from = start + head.length;\n // Word boundary: \"(Reachable\" must not match \"(ReachableFoo …\".\n if (head === '(Reachable') {\n const next = answer[from];\n if (next == null || !(/\\s/.test(next) || next === ')')) continue;\n }\n const end = sexprEnd(answer, start);\n if (end < 0) break;\n const inner = answer.slice(start + head.length, end - 1);\n const args = parseGroundIntArgs(inner);\n if (args != null && args.length === P + counterCount) {\n const marking = toMarking(counterCount === 0 ? args : args.slice(0, P), flatNet);\n const key = marking.toString();\n if (!byKey.has(key)) byKey.set(key, marking);\n }\n }\n }\n return new Set(byKey.values());\n}\n\nfunction toMarking(args: readonly number[], flatNet: FlatNet): MarkingState {\n const builder = MarkingState.builder();\n for (let i = 0; i < args.length; i++) {\n if (args[i]! > 0) builder.tokens(flatNet.places[i]!, args[i]!);\n }\n return builder.build();\n}\n\n/**\n * Parses an application's argument text into integers, accepting only GROUND\n * arguments: bare integer literals (`3`, `-1`) and the SMT-LIB negation form\n * `(- 3)`. Any other token (a bound variable, a nested expression) makes the\n * application non-ground: returns `null`.\n */\nexport function parseGroundIntArgs(inner: string): number[] | null {\n const args: number[] = [];\n let rest = inner.trimStart();\n while (rest !== '') {\n if (rest.startsWith('(')) {\n const stripped = rest.slice(1);\n const close = stripped.indexOf(')');\n if (close < 0) return null;\n const body = stripped.slice(0, close);\n if (body.includes('(')) return null;\n const trimmed = body.trim();\n if (!trimmed.startsWith('-')) return null;\n const n = parseInt64(trimmed.slice(1).trim());\n if (n == null) return null;\n args.push(-n);\n rest = stripped.slice(close + 1).trimStart();\n } else {\n let tokenEnd = rest.length;\n for (let i = 0; i < rest.length; i++) {\n const c = rest[i]!;\n if (/\\s/.test(c) || c === '(' || c === ')') {\n tokenEnd = i;\n break;\n }\n }\n const n = parseInt64(rest.slice(0, tokenEnd));\n if (n == null) return null;\n args.push(n);\n rest = rest.slice(tokenEnd).trimStart();\n }\n }\n return args;\n}\n\nfunction parseInt64(token: string): number | null {\n return /^-?\\d+$/.test(token) ? Number(token) : null;\n}\n","/**\n * @module state-equation-query\n *\n * The query of the state-equation phase (VER-018): one `QF_LIA` script asking\n * whether a marking the **marking equation** admits can violate the property.\n *\n * Every marking the untimed net reaches satisfies the rows of\n * {@link stateEquationConditions} for the firing counts `n ≥ 0` of the run that\n * reached it ([VER-016]): `m_p = M0_p + C_p·n` on a place whose column is exact, and\n * `m_p ≤ M0_p + C_p·n` on a place a consume-all or reset arc clears, since every\n * clearing firing removes at least its arc weight. `unsat` therefore proves the\n * property. A `sat` model is a *candidate*: a marking the equation admits, which the\n * net need not reach. The phase refines it away with inequalities every reachable\n * marking satisfies ({@link MarkingInequality}) and asks again.\n *\n * What the phase proves is `SE(M, n) ∧ ⋀ refinements(M)`, an inductive invariant\n * over the places and the firing counters. {@link refinementCertificate} renders it\n * as the `Reachable` interpretation the [VER-016] certificate check takes, which\n * re-proves initiation, consecution and safety against the raw step relation.\n */\nimport type { FlatNet } from '../encoding/flat-net.js';\nimport type { MarkingState } from '../marking-state.js';\nimport type { SmtProperty } from '../smt-property.js';\nimport type { ConditionalSinks } from '../rest-set.js';\nimport type { Place } from '../../core/place.js';\nimport {\n encodePropertyViolation, intTerm, resolveEnvInjection, stateEquationConditions, sumTerms,\n} from './smt-encoder.js';\nimport { extractDefineFuns } from './smt-text.js';\n\n/**\n * A linear inequality `Σ_p weights[p]·m_p ≤ constant` that every reachable marking\n * satisfies: an initially marked trap (`Σ_{q∈Q} m_q ≥ 1`, stored as weights `-1` and\n * constant `-1`), an inductive inequality, or one inductive relative to the marking\n * equation.\n */\nexport interface MarkingInequality {\n readonly weights: readonly bigint[];\n readonly constant: bigint;\n readonly origin: 'trap' | 'inductive' | 'relative';\n}\n\n/** A `sat` model of the query: a marking the equation admits and the firing counts it takes. */\nexport interface Candidate {\n readonly marking: readonly number[];\n readonly counts: readonly number[];\n}\n\n/**\n * The query: `m, n ≥ 0`, the marking equation, the refinements, and the property's\n * violation exactly as the HORN error rule encodes it.\n */\nexport function encodeStateEquationQuery(\n flatNet: FlatNet,\n initialMarking: MarkingState,\n property: SmtProperty,\n sinkPlaces: ReadonlySet<Place<any>>,\n conditionalSinks: readonly ConditionalSinks[],\n refinements: readonly MarkingInequality[],\n): string {\n const mVars = flatNet.places.map((_, i) => `m${i}`);\n const nVars = flatNet.transitions.map((_, k) => `n${k}`);\n const lines = [\n '; State-equation phase (VER-018): every reachable marking satisfies the marking',\n '; equation for the firing counts of its run (an upper bound on a place a',\n '; consume-all or reset arc clears); unsat = no such marking violates the property.',\n '(set-logic QF_LIA)',\n ];\n for (const v of [...mVars, ...nVars]) lines.push(`(declare-const ${v} Int)`);\n for (const v of [...mVars, ...nVars]) lines.push(`(assert (>= ${v} 0))`);\n for (const c of stateEquationConditions(flatNet, initialMarking, nVars, mVars)) lines.push(`(assert ${c})`);\n for (const r of refinements) lines.push(`(assert ${inequalityTerm(r, mVars)})`);\n const bad = encodePropertyViolation(\n flatNet, property, mVars, sinkPlaces, resolveEnvInjection(flatNet), conditionalSinks,\n );\n lines.push(`(assert ${bad})`);\n lines.push('(check-sat)');\n lines.push('(get-model)');\n return lines.join('\\n');\n}\n\n/** The candidate in a `sat` reply's model; `null` when the model defines no marking or counter. */\nexport function decodeCandidate(stdout: string, placeCount: number, transitionCount: number): Candidate | null {\n const marking = new Array<number>(placeCount).fill(0);\n const counts = new Array<number>(transitionCount).fill(0);\n let seen = false;\n for (const def of extractDefineFuns(stdout)) {\n const m = /^\\(define-fun\\s+([mn])(\\d+)\\s+\\(\\)\\s+Int\\s+(\\(-\\s*(\\d+)\\s*\\)|(\\d+))\\s*\\)$/s.exec(def.trim());\n if (m == null) continue;\n const index = Number(m[2]);\n const value = m[4] != null ? -Number(m[4]) : Number(m[5]);\n if (!Number.isSafeInteger(value)) return null;\n if (m[1] === 'm' && index < placeCount) marking[index] = value;\n else if (m[1] === 'n' && index < transitionCount) counts[index] = value;\n else continue;\n seen = true;\n }\n return seen ? { marking, counts } : null;\n}\n\n/** Whether the inequality holds at a marking, in exact integer arithmetic. */\nexport function holdsAt(inequality: MarkingInequality, marking: readonly number[]): boolean {\n let sum = 0n;\n for (let p = 0; p < inequality.weights.length; p++) {\n const w = inequality.weights[p]!;\n if (w !== 0n) sum += w * BigInt(marking[p] ?? 0);\n }\n return sum <= inequality.constant;\n}\n\n/**\n * The inequality as an SMT-LIB term over `vars`: `(<= Σ w·v c)`, or, when no weight\n * is positive, the same bound read the other way round — a trap is `(>= (+ v3 v5) 1)`.\n */\nfunction inequalityTerm(inequality: MarkingInequality, vars: readonly string[]): string {\n const flip = inequality.weights.every((w) => w <= 0n);\n const terms: string[] = [];\n for (let p = 0; p < inequality.weights.length; p++) {\n const w = flip ? -inequality.weights[p]! : inequality.weights[p]!;\n if (w !== 0n) terms.push(intTerm(w, vars[p]!));\n }\n const lhs = sumTerms(terms);\n return flip\n ? `(>= ${lhs} ${literal(-inequality.constant)})`\n : `(<= ${lhs} ${literal(inequality.constant)})`;\n}\n\n/**\n * The phase's proof as the `Reachable` interpretation the [VER-016] certificate check\n * takes: `(define-fun Reachable ((x!0 Int) …) Bool …)` over the places and one firing\n * counter per flat transition. The check conjoins the marking equation itself, so the\n * body carries only the refinements, and is `true` when none was needed.\n */\nexport function refinementCertificate(\n placeCount: number,\n transitionCount: number,\n refinements: readonly MarkingInequality[],\n): string {\n const params: string[] = [];\n for (let i = 0; i < placeCount + transitionCount; i++) params.push(`(x!${i} Int)`);\n const vars: string[] = [];\n for (let i = 0; i < placeCount; i++) vars.push(`x!${i}`);\n const terms = refinements.map((r) => inequalityTerm(r, vars));\n const body = terms.length === 0 ? 'true' : terms.length === 1 ? terms[0]! : `(and ${terms.join('\\n ')})`;\n return `(define-fun Reachable (${params.join(' ')}) Bool\\n ${body})`;\n}\n\n/** `Merge/hasdata <= Merge/ready_0 + Merge/ready_1`; a trap reads `a + b >= 1`. */\nexport function formatInequality(flatNet: FlatNet, inequality: MarkingInequality): string {\n const named = (p: number, w: bigint): string =>\n w === 1n ? flatNet.places[p]!.name : `${w}*${flatNet.places[p]!.name}`;\n const left: string[] = [];\n const right: string[] = [];\n inequality.weights.forEach((w, p) => {\n if (w > 0n) left.push(named(p, w));\n else if (w < 0n) right.push(named(p, -w));\n });\n if (left.length === 0) return `${right.length === 0 ? '0' : right.join(' + ')} >= ${-inequality.constant}`;\n // `a <= b` reads better than `a <= 0 + b`, so a zero constant is dropped once the\n // right-hand side has a term of its own.\n const dropZero = inequality.constant === 0n && right.length > 0;\n const rhs = dropZero ? right : [String(inequality.constant), ...right];\n return `${left.join(' + ')} <= ${rhs.join(' + ')}`;\n}\n\nfunction literal(c: bigint): string {\n return c < 0n ? `(- ${-c})` : String(c);\n}\n","/**\n * @module trap-refinement\n *\n * Trap refinement for the state-equation phase (VER-018), after Esparza,\n * Ledesma-Garza, Majumdar, Meyer and Niksic, \"An SMT-based approach to coverability\n * analysis\" (CAV 2014).\n *\n * A **trap** is a set of places `Q` such that every transition that removes a token\n * from `Q` also puts one into `Q`. A trap marked at `M0` stays marked in every\n * reachable marking, so a candidate that leaves an initially marked trap empty is not\n * reachable, and `Σ_{q∈Q} m_q ≥ 1` refutes it.\n *\n * \"Removes a token\" is generalised to the arcs the ordinary definition does not know:\n * a consume-all input or a reset arc on a place of `Q` removes tokens from `Q` whatever\n * its weight, so that transition must also put one into `Q`. Read and inhibitor arcs\n * remove nothing, and environment injection only adds tokens. No solver is involved.\n */\nimport type { FlatNet } from '../encoding/flat-net.js';\nimport type { FlatTransition } from '../encoding/flat-transition.js';\nimport type { MarkingInequality } from './state-equation-query.js';\n\n/**\n * An initially marked trap the candidate leaves empty, as the inequality\n * `Σ_{q∈Q} m_q ≥ 1`, or `null` when there is none. The trap is shrunk to a locally\n * minimal one: a smaller trap is a stronger constraint on the next candidate.\n */\nexport function refutingTrap(\n flatNet: FlatNet,\n initial: readonly number[],\n candidate: readonly number[],\n): MarkingInequality | null {\n const drains = flatNet.transitions.map(drainedPlaces);\n const feeds = flatNet.transitions.map(fedPlaces);\n const empty = new Set<number>();\n for (let p = 0; p < candidate.length; p++) if (candidate[p] === 0) empty.add(p);\n let trap = maximalTrap(empty, drains, feeds);\n if (!markedIn(trap, initial)) return null;\n for (const p of [...trap].sort((a, b) => a - b)) {\n // A snapshot of the trap we started from, while `trap` shrinks underneath: a place an\n // earlier round already dropped is no longer a candidate for dropping.\n if (!trap.has(p)) continue;\n const without = new Set(trap);\n without.delete(p);\n const smaller = maximalTrap(without, drains, feeds);\n if (markedIn(smaller, initial)) trap = smaller;\n }\n const weights = new Array<bigint>(flatNet.places.length).fill(0n);\n for (const p of trap) weights[p] = -1n;\n return { weights, constant: -1n, origin: 'trap' };\n}\n\n/**\n * The largest trap inside `within` (possibly empty): repeatedly drop the places a\n * transition drains when it feeds nothing back into what is left. Traps are closed\n * under union, so the result contains every trap inside `within`.\n */\nfunction maximalTrap(\n within: ReadonlySet<number>,\n drains: readonly (readonly number[])[],\n feeds: readonly (readonly number[])[],\n): Set<number> {\n const trap = new Set(within);\n let changed = true;\n while (changed) {\n changed = false;\n for (let t = 0; t < drains.length; t++) {\n if (!drains[t]!.some((p) => trap.has(p))) continue;\n if (feeds[t]!.some((p) => trap.has(p))) continue;\n for (const p of drains[t]!) if (trap.delete(p)) changed = true;\n }\n }\n return trap;\n}\n\n/** The places a firing of `ft` can take tokens from: its inputs, consume-all places and reset places. */\nfunction drainedPlaces(ft: FlatTransition): number[] {\n const out = new Set<number>(ft.resetPlaces);\n for (let p = 0; p < ft.preVector.length; p++) {\n if (ft.preVector[p]! > 0 || ft.consumeAll[p]) out.add(p);\n }\n return [...out].sort((a, b) => a - b);\n}\n\n/** The places a firing of `ft` puts at least one token into. */\nfunction fedPlaces(ft: FlatTransition): number[] {\n const out: number[] = [];\n for (let p = 0; p < ft.postVector.length; p++) if (ft.postVector[p]! > 0) out.push(p);\n return out;\n}\n\nfunction markedIn(places: ReadonlySet<number>, marking: readonly number[]): boolean {\n for (const p of places) if (marking[p]! > 0) return true;\n return false;\n}\n","/**\n * @module invariant-synthesis\n *\n * Inductive-inequality refinement for the state-equation phase (VER-018).\n *\n * The marking equation knows how often each transition fired, never in what order,\n * and it ignores the guards that impose the order. The typical spurious candidate on\n * a workflow net is a join that *skipped* — a transition inhibited by `hasdata` —\n * after the data token arrived: every count balances, and only the inhibitor rules\n * the run out. A trap cannot say that either. This refinement looks for one linear\n * inequality `a·M ≤ b` that\n *\n * 1. holds at `M0`,\n * 2. is kept by every step of the **exact** step relation — input weights, read and\n * inhibitor guards, consume-all and reset clearing included, which is where it\n * gets its power over the equation — and\n * 3. excludes the candidate: `a·M* ≥ b + 1`.\n *\n * For the join above that is `hasdata ≤ ready_0 + ready_1`: arrivals raise both\n * sides together, `skip` fires only when `hasdata` is empty, and `start` clears it.\n *\n * Condition 2 is the Farkas form of consecution (Colón, Sankaranarayanan and Sipma,\n * \"Linear invariant generation using non-linear constraint solving\", CAV 2003) with\n * the invariant's own multiplier restricted to `λ_t ∈ {0, 1}` per transition, which\n * keeps the query linear. Write `l_p = max(pre_p, 1 if p is read)` for the guard's\n * lower bound; an inhibited place is exactly `0` before the step.\n *\n * - `λ_t = 1`, the step keeps the bound: `a·M' − a·M ≤ 0` for every enabled `M`. A\n * place `t` does not clear contributes its column `C_p`; a place it clears\n * contributes `post_p − M_p ≤ post_p − l_p`, provided `a_p ≥ 0` (on an inhibited\n * cleared place `M_p = 0`, so `post_p` and no sign condition).\n * - `λ_t = 0`, the guard restores the bound on its own: `a_p ≤ 0` on every place `t`\n * neither clears nor inhibits, so `a·M'` is largest at `M = l`, and that value is\n * `≤ b`.\n *\n * An environment injection must keep the bound (`a_p ≤ 0` on an injected place). The\n * query is one `QF_LIA` script with integer weights in `[−bound, bound]`.\n *\n * The weights {@link encodeInductiveInequality} returns are re-checked in exact integer\n * arithmetic ({@link checkInductiveExact}) before they are used. Those of\n * {@link encodeRelativeInequality} are not, and cannot be: that bound holds only relative\n * to the marking equation, so the exact re-check would reject it. It rests on the\n * certificate check, which re-proves the whole refinement against the raw step relation\n * before any verdict rests on it.\n */\nimport type { FlatNet } from '../encoding/flat-net.js';\nimport type { FlatTransition } from '../encoding/flat-transition.js';\nimport { nonlinearPlaces } from '../invariant/p-invariant-computer.js';\nimport { conjoin, intTerm, resolveEnvInjection, sumTerms } from './smt-encoder.js';\nimport { extractDefineFuns } from './smt-text.js';\nimport type { MarkingInequality } from './state-equation-query.js';\n\n/** The default magnitude bound on the weights the query may choose. */\nexport const DEFAULT_WEIGHT_BOUND = 8;\n\n/** The two ways a transition can keep `a·M ≤ b`, as coefficient rows over the places. */\ninterface StepShape {\n /** `λ = 1`: `a_p ≥ 0` on these places, and `Σ keep[p]·a_p ≤ 0`. */\n readonly keepNonNegative: readonly number[];\n readonly keep: readonly number[];\n /** `λ = 0`: `a_p ≤ 0` on every place outside `restoreFree`, and `Σ restore[p]·a_p ≤ b`. */\n readonly restoreFree: readonly number[];\n readonly restore: readonly number[];\n}\n\n/** The shape of `ft`, or `null` when it can never fire (it inhibits a place it needs). */\nfunction stepShape(ft: FlatTransition, placeCount: number): StepShape | null {\n const inhibited = new Set(ft.inhibitorPlaces);\n const read = new Set(ft.readPlaces);\n const resets = new Set(ft.resetPlaces);\n for (const p of inhibited) if (ft.preVector[p]! > 0 || read.has(p)) return null;\n const keep = new Array<number>(placeCount).fill(0);\n const restore = new Array<number>(placeCount).fill(0);\n const keepNonNegative: number[] = [];\n const restoreFree: number[] = [];\n for (let p = 0; p < placeCount; p++) {\n const pre = ft.preVector[p]!;\n const post = ft.postVector[p]!;\n const lower = Math.max(pre, read.has(p) ? 1 : 0);\n if (resets.has(p) || ft.consumeAll[p]) {\n if (inhibited.has(p)) {\n keep[p] = post;\n } else {\n keep[p] = post - lower;\n keepNonNegative.push(p);\n }\n restore[p] = post;\n restoreFree.push(p);\n } else if (inhibited.has(p)) {\n keep[p] = post - pre;\n restore[p] = post - pre;\n restoreFree.push(p);\n } else {\n keep[p] = post - pre;\n restore[p] = post - pre + lower;\n }\n }\n return { keepNonNegative, keep, restoreFree, restore };\n}\n\n/**\n * The `QF_LIA` script asking for weights `a` and bound `b` meeting conditions 1–3 of the\n * module description for `candidate`. `u_p ≥ max(a_p, 0)`, so a transition's `λ = 0` sign\n * condition is the one equation `Σ_p u_p = Σ_{p free} u_p`.\n */\nexport function encodeInductiveInequality(\n flatNet: FlatNet,\n initial: readonly number[],\n candidate: readonly number[],\n weightBound: number = DEFAULT_WEIGHT_BOUND,\n): string {\n const P = flatNet.places.length;\n const a = (p: number): string => `a${p}`;\n const u = (p: number): string => `u${p}`;\n const lines = [\n '; Inductive-inequality refinement (VER-018): a.M <= b holding at M0, kept by every',\n '; step of the exact step relation (guards and clearing included), and excluding',\n '; the candidate marking.',\n '(set-logic QF_LIA)',\n ];\n const w = (p: number): string => `w${p}`;\n for (let p = 0; p < P; p++) lines.push(`(declare-const ${a(p)} Int)`);\n for (let p = 0; p < P; p++) lines.push(`(declare-const ${u(p)} Int)`);\n for (let p = 0; p < P; p++) lines.push(`(declare-const ${w(p)} Int)`);\n lines.push('(declare-const b Int)');\n lines.push('(declare-const upos Int)');\n for (let p = 0; p < P; p++) {\n lines.push(`(assert (and (>= ${a(p)} (- ${weightBound})) (<= ${a(p)} ${weightBound})))`);\n lines.push(`(assert (and (>= ${u(p)} 0) (>= ${u(p)} ${a(p)})))`);\n lines.push(`(assert (and (>= ${w(p)} 0) (>= ${w(p)} (- ${a(p)}))))`);\n }\n lines.push(`(assert (= upos ${sumTerms([...Array(P).keys()].map(u))}))`);\n lines.push(`(assert (<= ${linear(initial, a)} b))`);\n lines.push(`(assert (>= ${linear(candidate, a)} (+ b 1)))`);\n for (const ft of flatNet.transitions) {\n const shape = stepShape(ft, P);\n if (shape == null) continue;\n const keeps = [...shape.keepNonNegative.map((p) => `(>= ${a(p)} 0)`), `(<= ${linear(shape.keep, a)} 0)`];\n const restores = [`(= upos ${sumTerms(shape.restoreFree.map(u))})`, `(<= ${linear(shape.restore, a)} b)`];\n lines.push(`(assert (or ${conjoin(keeps)} ${conjoin(restores)}))`);\n }\n for (const inj of resolveEnvInjection(flatNet)) lines.push(`(assert (<= ${a(inj.pid)} 0))`);\n // The sparsest inequality reads as the structural fact and excludes more candidates.\n lines.push(`(minimize ${sumTerms([...Array(P).keys()].flatMap((p) => [u(p), w(p)]))})`);\n lines.push('(check-sat)');\n lines.push('(get-model)');\n return lines.join('\\n');\n}\n\n/**\n * The query of {@link encodeInductiveInequality} with the marking equation as a\n * premise of every step: the inequality need only be kept by steps from markings the\n * equation admits. A bound like `q + 3·out ≤ 3` on a queue that is bundled once a\n * signal arrives needs it — `produce` keeps the bound only because `q ≤ 2` whenever\n * `budget ≥ 1`, and that is the equation's `q + budget ≤ 3`.\n *\n * By Farkas, the premise contributes to transition `t`'s consecution one linear\n * consequence of the equation: a weighting `η^t` with `η^t·C_j ≤ 0` on every column\n * `j`, non-negative on a place whose row is an upper bound and absent on an injected\n * place, so that `η^t·M ≤ η^t·M0` holds wherever the equation does. With\n * `κ_t = Σ_{p not cleared} a_p·C_p + Σ_{p cleared} a_p·post_p` the two cases read:\n *\n * - `λ_t = 1`: `η^t_p ≥ 0` on a place `t` neither clears nor inhibits, `a_p + η^t_p ≥ 0`\n * on a place it clears, and `κ_t ≤ −η^t·M0 + Σ_{p not inhibited} ν_p·l_p`, with\n * `ν_p = η^t_p` (`a_p + η^t_p` on a cleared place).\n * - `λ_t = 0`: `a_p ≤ η^t_p` on a place `t` neither clears nor inhibits, `η^t_p ≥ 0` on\n * a place it clears, and `κ_t − b ≤ −η^t·M0 + Σ ν_p·l_p`, with `ν_p = η^t_p − a_p`\n * (`η^t_p` on a cleared place).\n *\n * With `η^t = 0` these are the conditions of {@link encodeInductiveInequality}. The\n * query carries one weighting per transition, so the phase asks it only when that\n * one found nothing. The weightings are real; the inequality's weights stay integers.\n * The certificate check re-proves the result as part of `SE ∧ refinements`.\n */\nexport function encodeRelativeInequality(\n flatNet: FlatNet,\n initial: readonly number[],\n candidate: readonly number[],\n weightBound: number = DEFAULT_WEIGHT_BOUND,\n): string {\n const P = flatNet.places.length;\n const T = flatNet.transitions.length;\n const upper = nonlinearPlaces(flatNet);\n const injected = new Set(resolveEnvInjection(flatNet).map((inj) => inj.pid));\n const rows = [...Array(P).keys()].filter((p) => !injected.has(p));\n const ra = (p: number): string => `(to_real a${p})`;\n const lines = [\n '; Inductive-inequality refinement relative to the marking equation (VER-018):',\n '; a.M <= b holding at M0, kept by every step from a marking the equation admits',\n '; (one Farkas weighting e<t>_<p> of the equation per transition), and excluding',\n '; the candidate marking.',\n '(set-logic QF_LIRA)',\n ];\n for (let p = 0; p < P; p++) lines.push(`(declare-const a${p} Int)`);\n for (let p = 0; p < P; p++) lines.push(`(declare-const u${p} Int)`);\n for (let p = 0; p < P; p++) lines.push(`(declare-const w${p} Int)`);\n lines.push('(declare-const b Int)');\n for (let p = 0; p < P; p++) {\n lines.push(`(assert (and (>= a${p} (- ${weightBound})) (<= a${p} ${weightBound})))`);\n lines.push(`(assert (and (>= u${p} 0) (>= u${p} a${p})))`);\n lines.push(`(assert (and (>= w${p} 0) (>= w${p} (- a${p}))))`);\n }\n lines.push(`(assert (<= ${linear(initial, (p) => `a${p}`)} b))`);\n lines.push(`(assert (>= ${linear(candidate, (p) => `a${p}`)} (+ b 1)))`);\n for (const p of injected) lines.push(`(assert (<= a${p} 0))`);\n for (let t = 0; t < T; t++) {\n const parts = stepParts(flatNet.transitions[t]!, P);\n if (parts == null) continue;\n const e = (p: number): string => `e${t}_${p}`;\n for (const p of rows) lines.push(`(declare-const ${e(p)} Real)`);\n for (const p of rows) if (upper.has(p)) lines.push(`(assert (>= ${e(p)} 0))`);\n for (const col of flatNet.transitions) {\n const terms: string[] = [];\n for (const p of rows) {\n const c = col.postVector[p]! - col.preVector[p]!;\n if (c !== 0) terms.push(scaled(c, e(p)));\n }\n if (terms.length > 0) lines.push(`(assert (<= ${sumTerms(terms)} 0.0))`);\n }\n // κ_t over the weights, and −η·M0.\n const kappa: string[] = [];\n for (let p = 0; p < P; p++) {\n const c = parts.cleared[p] ? parts.post[p]! : parts.delta[p]!;\n if (c !== 0) kappa.push(scaled(c, ra(p)));\n }\n const etaM0: string[] = [];\n for (const p of rows) if (initial[p]! !== 0) etaM0.push(scaled(-initial[p]!, e(p)));\n const keep: string[] = [];\n const keepRhs = [...etaM0];\n const restore: string[] = [];\n const restoreRhs = [...etaM0];\n for (let p = 0; p < P; p++) {\n if (parts.inhibited[p]) continue;\n const l = parts.lower[p]!;\n const eta = injected.has(p) ? '0.0' : e(p);\n if (parts.cleared[p]) {\n keep.push(`(>= (+ ${ra(p)} ${eta}) 0.0)`);\n restore.push(`(>= ${eta} 0.0)`);\n if (l !== 0) {\n keepRhs.push(scaled(l, `(+ ${ra(p)} ${eta})`));\n restoreRhs.push(scaled(l, eta));\n }\n } else {\n keep.push(`(>= ${eta} 0.0)`);\n restore.push(`(<= ${ra(p)} ${eta})`);\n if (l !== 0) {\n keepRhs.push(scaled(l, eta));\n restoreRhs.push(scaled(l, `(- ${eta} ${ra(p)})`));\n }\n }\n }\n keep.push(`(<= ${sumTerms(kappa, '0.0')} ${sumTerms(keepRhs, '0.0')})`);\n restore.push(`(<= (- ${sumTerms(kappa, '0.0')} (to_real b)) ${sumTerms(restoreRhs, '0.0')})`);\n lines.push(`(assert (or ${conjoin(keep)} ${conjoin(restore)}))`);\n }\n lines.push(`(minimize ${sumTerms([...Array(P).keys()].flatMap((p) => [`u${p}`, `w${p}`]))})`);\n lines.push('(check-sat)');\n lines.push('(get-model)');\n return lines.join('\\n');\n}\n\n/** The arcs of `ft` per place, or `null` when it can never fire (it inhibits a place it needs). */\nfunction stepParts(\n ft: FlatTransition,\n placeCount: number,\n): { cleared: boolean[]; inhibited: boolean[]; lower: number[]; delta: number[]; post: number[] } | null {\n const inhibited = new Array<boolean>(placeCount).fill(false);\n for (const p of ft.inhibitorPlaces) inhibited[p] = true;\n const read = new Set(ft.readPlaces);\n for (let p = 0; p < placeCount; p++) if (inhibited[p] && (ft.preVector[p]! > 0 || read.has(p))) return null;\n const resets = new Set(ft.resetPlaces);\n const cleared: boolean[] = [];\n const lower: number[] = [];\n const delta: number[] = [];\n const post: number[] = [];\n for (let p = 0; p < placeCount; p++) {\n cleared.push(resets.has(p) || ft.consumeAll[p] === true);\n lower.push(Math.max(ft.preVector[p]!, read.has(p) ? 1 : 0));\n delta.push(ft.postVector[p]! - ft.preVector[p]!);\n post.push(ft.postVector[p]!);\n }\n return { cleared, inhibited, lower, delta, post };\n}\n\n/** `c·x` for a real-valued `x`, `c` an integer. */\nfunction scaled(c: number, x: string): string {\n if (c === 1) return x;\n if (c === -1) return `(- ${x})`;\n return c > 0 ? `(* ${c}.0 ${x})` : `(* (- ${-c}.0) ${x})`;\n}\n\n/** The inequality in a `sat` reply's model; `null` when the model defines no weight or no bound. */\nexport function decodeInductiveInequality(stdout: string, placeCount: number): MarkingInequality | null {\n const weights = new Array<bigint>(placeCount).fill(0n);\n let constant: bigint | null = null;\n for (const def of extractDefineFuns(stdout)) {\n const m = /^\\(define-fun\\s+(a(\\d+)|b)\\s+\\(\\)\\s+Int\\s+(\\(-\\s*(\\d+)\\s*\\)|(\\d+))\\s*\\)$/s.exec(def.trim());\n if (m == null) continue;\n const value = m[4] != null ? -BigInt(m[4]) : BigInt(m[5]!);\n if (m[1] === 'b') constant = value;\n else if (Number(m[2]) < placeCount) weights[Number(m[2])] = value;\n }\n return constant == null ? null : { weights, constant, origin: 'inductive' };\n}\n\n/**\n * Re-proves conditions 1 and 2 of the module description in exact integer\n * arithmetic: the inequality holds at `M0`, every injected place has a weight `≤ 0`,\n * and every transition that can fire either keeps the bound (`λ = 1`) or restores it\n * from its guard (`λ = 0`). Condition 3 is not needed for soundness.\n */\nexport function checkInductiveExact(\n flatNet: FlatNet,\n initial: readonly number[],\n inequality: MarkingInequality,\n): boolean {\n const { weights, constant } = inequality;\n const P = flatNet.places.length;\n if (weights.length !== P) return false;\n if (dot(weights, initial) > constant) return false;\n for (const inj of resolveEnvInjection(flatNet)) if (weights[inj.pid]! > 0n) return false;\n for (const ft of flatNet.transitions) {\n const shape = stepShape(ft, P);\n if (shape == null) continue;\n if (shape.keepNonNegative.every((p) => weights[p]! >= 0n) && dot(weights, shape.keep) <= 0n) continue;\n const free = new Set(shape.restoreFree);\n const signs = weights.every((w, p) => w <= 0n || free.has(p));\n if (!signs || dot(weights, shape.restore) > constant) return false;\n }\n return true;\n}\n\nfunction dot(weights: readonly bigint[], values: readonly number[]): bigint {\n let s = 0n;\n for (let p = 0; p < weights.length; p++) {\n if (weights[p] !== 0n && values[p] !== 0) s += weights[p]! * BigInt(values[p]!);\n }\n return s;\n}\n\n/** `Σ coeffs[p]·var(p)` over the non-zero coefficients, `0` when there are none. */\nfunction linear(coeffs: readonly number[], v: (p: number) => string): string {\n const terms: string[] = [];\n for (let p = 0; p < coeffs.length; p++) {\n const c = coeffs[p]!;\n if (c === 0) continue;\n terms.push(intTerm(c, v(p)));\n }\n return sumTerms(terms);\n}\n","/**\n * @module parikh-search\n *\n * The witness search of the state-equation phase (VER-018): breadth-first from `M0` under\n * the exact abstract semantics ({@link enabledA} / {@link fireA}), firing each flat\n * transition at most as often as a candidate's counts allow, stopping at the first\n * violating marking. The counts bound the depth by their sum (Blondin, Haase and\n * Offtermatt, TACAS 2021).\n *\n * `found` is a real firing sequence, so its violation is confirmed. `none` means no run\n * within the counts reaches a violation. `exhausted` says nothing either way.\n *\n * Injection is not a counted firing and is never searched. `found` still stands: a run\n * without injection is a run of the net, and `Bad(M)` judges quiescence with relax-env\n * enablement. `none` does not, since an injected token could enable an unsearched run, so\n * under injection a completed search reports `exhausted`.\n */\nimport type { FlatNet } from '../encoding/flat-net.js';\nimport { enabledA, environmentCaps, fireA, type AbstractState } from './abstract-replayer.js';\n\n/** Outcome of {@link searchWithinCounts}. */\nexport type WitnessOutcome =\n | {\n readonly kind: 'found';\n /** The markings of the run, `M0 … M_bad` inclusive. */\n readonly states: readonly AbstractState[];\n /** The flat transitions fired, one per consecutive pair of {@link states}. */\n readonly steps: readonly string[];\n readonly nodes: number;\n }\n | { readonly kind: 'none'; readonly nodes: number }\n | { readonly kind: 'exhausted'; readonly reason: string; readonly nodes: number };\n\ninterface SearchNode {\n readonly state: AbstractState;\n readonly remaining: readonly number[];\n readonly parent: number;\n readonly transition: number;\n}\n\n/**\n * Searches the runs from `initial` that fire each transition `t` at most `counts[t]` times\n * for one that reaches a marking `isBad` accepts. A node is a marking with its unspent\n * counts, so two runs meeting there share a future and the second is dropped.\n */\nexport function searchWithinCounts(\n flatNet: FlatNet,\n initial: AbstractState,\n counts: readonly number[],\n isBad: (state: AbstractState) => boolean,\n nodeBudget = 100_000,\n): WitnessOutcome {\n const caps = environmentCaps(flatNet);\n const nodes: SearchNode[] = [{ state: initial, remaining: counts, parent: -1, transition: -1 }];\n if (isBad(initial)) return { kind: 'found', states: [initial], steps: [], nodes: 1 };\n const seen = new Set<string>([key(initial, counts)]);\n const transitions = flatNet.transitions;\n for (let head = 0; head < nodes.length; head++) {\n const node = nodes[head]!;\n for (let t = 0; t < transitions.length; t++) {\n if (node.remaining[t]! <= 0) continue;\n const ft = transitions[t]!;\n if (!enabledA(node.state, ft)) continue;\n const next = fireA(node.state, ft);\n if (caps.some(([idx, cap]) => next[idx]! > cap)) continue;\n const remaining = [...node.remaining];\n remaining[t]!--;\n const k = key(next, remaining);\n if (seen.has(k)) continue;\n if (nodes.length >= nodeBudget) {\n return { kind: 'exhausted', reason: `search budget exhausted (${nodeBudget} nodes)`, nodes: nodes.length };\n }\n seen.add(k);\n nodes.push({ state: next, remaining, parent: head, transition: t });\n if (isBad(next)) return { kind: 'found', ...reconstruct(nodes, nodes.length - 1, flatNet), nodes: nodes.length };\n }\n }\n // Out of counted runs, not budget: `none` only when injection cannot extend a run.\n return flatNet.environmentInjection.size > 0\n ? { kind: 'exhausted', reason: 'environment injection is not searched', nodes: nodes.length }\n : { kind: 'none', nodes: nodes.length };\n}\n\nfunction key(state: AbstractState, remaining: readonly number[]): string {\n return `${state.join(',')}|${remaining.join(',')}`;\n}\n\nfunction reconstruct(\n nodes: readonly SearchNode[],\n last: number,\n flatNet: FlatNet,\n): { states: AbstractState[]; steps: string[] } {\n const states: AbstractState[] = [];\n const steps: string[] = [];\n for (let i = last; i >= 0; i = nodes[i]!.parent) {\n const node = nodes[i]!;\n states.push(node.state);\n if (node.transition >= 0) steps.push(flatNet.transitions[node.transition]!.name);\n }\n states.reverse();\n steps.reverse();\n return { states, steps };\n}\n","/**\n * @module state-equation-phase\n *\n * The refinement loop of the state-equation phase (VER-018).\n *\n * One `QF_LIA` query asks whether a marking the marking equation admits violates the\n * property ({@link encodeStateEquationQuery}); `unsat` proves it. Each `sat` candidate is\n * settled cheapest first:\n *\n * 1. **Witness**: a run from `M0` within the candidate's counts that reaches a violation\n * ({@link searchWithinCounts}), the counterexample.\n * 2. **Trap**: an initially marked trap the candidate empties ({@link refutingTrap}).\n * 3. **Inductive inequality**: `a·M ≤ b` kept by the exact step relation and excluding the\n * candidate ({@link encodeInductiveInequality}), re-checked exactly. Failing that, one\n * inductive only relative to the marking equation ({@link encodeRelativeInequality}),\n * which no exact re-check can accept; the certificate check re-proves it.\n *\n * Every refinement holds in every reachable marking, so a later `unsat` is still a proof\n * and the refinements are its certificate. Otherwise the phase is inconclusive and the\n * verifier continues as without it: it adds verdicts, never removes them.\n */\nimport type { FlatNet } from '../encoding/flat-net.js';\nimport type { MarkingState } from '../marking-state.js';\nimport type { SmtProperty } from '../smt-property.js';\nimport type { ConditionalSinks } from '../rest-set.js';\nimport type { Place } from '../../core/place.js';\nimport { rethrowIfProgrammingError } from '../programming-error.js';\nimport { classifyFirstLine } from './smt-text.js';\nimport { vectorize, violationPredicate, type AbstractState } from './abstract-replayer.js';\nimport {\n decodeCandidate, encodeStateEquationQuery, holdsAt, type Candidate, type MarkingInequality,\n} from './state-equation-query.js';\nimport { refutingTrap } from './trap-refinement.js';\nimport {\n DEFAULT_WEIGHT_BOUND, checkInductiveExact, decodeInductiveInequality, encodeInductiveInequality,\n encodeRelativeInequality,\n} from './invariant-synthesis.js';\nimport { searchWithinCounts } from './parikh-search.js';\n\n/** The solver phase a script belongs to (`LIBPETRI_SMT_DUMP` file names, VER-013). */\nexport type StateEquationScriptPhase = 'state-equation' | 'invariant';\n\n/**\n * Runs one script through the solver within `timeoutMs` and resolves with its stdout.\n * Rejects when the transport failed or the reply carries no verdict line, with the\n * reason as the message.\n */\nexport type StateEquationSolver = (script: string, phase: StateEquationScriptPhase, timeoutMs: number) => Promise<string>;\n\n/** Options of {@link runStateEquationPhase}. */\nexport interface StateEquationPhaseOptions {\n /** The most refinements the phase adds before it gives up (default 32). */\n readonly maxRefinements?: number;\n /** The magnitude bound on an inductive inequality's weights (default {@link DEFAULT_WEIGHT_BOUND}). */\n readonly weightBound?: number;\n /** The node budget of each witness search (default 100 000). */\n readonly witnessNodes?: number;\n /** Wall-clock budget for the whole phase in milliseconds; each query gets what is left (default 60 000). */\n readonly budgetMs?: number;\n}\n\n/** Outcome of {@link runStateEquationPhase}. */\nexport type StateEquationOutcome =\n | {\n readonly kind: 'proven';\n /** The refinements the final `unsat` used, in the order they were added. */\n readonly refinements: readonly MarkingInequality[];\n /** Solver queries sent, both dump phases counted. */\n readonly queries: number;\n }\n | {\n readonly kind: 'violated';\n readonly states: readonly AbstractState[];\n readonly steps: readonly string[];\n readonly refinements: readonly MarkingInequality[];\n readonly queries: number;\n }\n | {\n readonly kind: 'inconclusive';\n readonly reason: string;\n readonly refinements: readonly MarkingInequality[];\n readonly queries: number;\n /** The candidate the phase stopped on, when it stopped holding one. */\n readonly candidate: Candidate | null;\n };\n\n/**\n * Runs the phase on the flat path. The caller runs the certificate check on a\n * `proven` outcome before reporting it ({@link refinementCertificate}).\n */\nexport async function runStateEquationPhase(\n flatNet: FlatNet,\n initialMarking: MarkingState,\n property: SmtProperty,\n sinkPlaces: ReadonlySet<Place<any>>,\n conditionalSinks: readonly ConditionalSinks[],\n run: StateEquationSolver,\n options: StateEquationPhaseOptions = {},\n): Promise<StateEquationOutcome> {\n const maxRefinements = options.maxRefinements ?? 32;\n const witnessNodes = options.witnessNodes ?? 100_000;\n const budgetMs = options.budgetMs ?? 60_000;\n const deadline = performance.now() + budgetMs;\n const P = flatNet.places.length;\n const T = flatNet.transitions.length;\n const initial: AbstractState = vectorize(initialMarking, flatNet);\n // A bound like `N·out + q ≤ N` weighs a flag by the capacity of the queue it guards,\n // so the default bound grows with the tokens the net starts with.\n const weightBound = options.weightBound ?? Math.max(DEFAULT_WEIGHT_BOUND, initial.reduce((s, v) => s + v, 0));\n const isBad = violationPredicate(flatNet, property, sinkPlaces, conditionalSinks);\n const refinements: MarkingInequality[] = [];\n let queries = 0;\n const inconclusive = (reason: string, candidate: Candidate | null = null): StateEquationOutcome =>\n ({ kind: 'inconclusive', reason, refinements, queries, candidate });\n\n const ask = async (script: string, phase: StateEquationScriptPhase): Promise<string | Error> => {\n const left = Math.floor(deadline - performance.now());\n if (left <= 0) return new Error(`time budget of ${budgetMs} ms exhausted`);\n queries++;\n try {\n return await run(script, phase, left);\n } catch (e: any) {\n rethrowIfProgrammingError(e);\n return new Error(String(e?.message ?? e));\n }\n };\n\n /** The inequality a synthesis query found, `null` when it proved there is none, or why it failed. */\n async function synthesize(script: string): Promise<MarkingInequality | null | Error> {\n const reply = await ask(script, 'invariant');\n if (reply instanceof Error) return reply;\n switch (classifyFirstLine(reply)) {\n case 'sat':\n return decodeInductiveInequality(reply, P) ?? new Error('the inductive-inequality model could not be decoded');\n case 'unsat':\n return null;\n default:\n return new Error('the inductive-inequality query answered unknown');\n }\n }\n\n /**\n * The refinement that excludes `candidate`, cheapest first: a trap, then an inequality\n * inductive on its own, then one inductive only relative to the marking equation. The\n * `Error` is the reason the phase cannot go on, not a failure of the net.\n */\n async function refine(candidate: Candidate): Promise<MarkingInequality | Error> {\n const trap = refutingTrap(flatNet, initial, candidate.marking);\n if (trap != null) return trap;\n\n // An inequality inductive on its own is cheaper to find and re-checked exactly;\n // one inductive relative to the equation is asked for only when there is none.\n const inductive = await synthesize(encodeInductiveInequality(flatNet, initial, candidate.marking, weightBound));\n if (inductive instanceof Error) return inductive;\n if (inductive != null) {\n if (!checkInductiveExact(flatNet, initial, inductive) || holdsAt(inductive, candidate.marking)) {\n return new Error('an inductive inequality failed the exact re-check');\n }\n return inductive;\n }\n\n const relative = await synthesize(encodeRelativeInequality(flatNet, initial, candidate.marking, weightBound));\n if (relative instanceof Error) return relative;\n if (relative == null) {\n return new Error(`no trap and no inductive inequality with weights within ±${weightBound} excludes the candidate`);\n }\n if (holdsAt(relative, candidate.marking)) {\n return new Error('an inductive inequality does not exclude its candidate');\n }\n // decodeInductiveInequality labels every model 'inductive'; the report must tell this one apart.\n return { ...relative, origin: 'relative' };\n }\n\n for (;;) {\n const query = encodeStateEquationQuery(flatNet, initialMarking, property, sinkPlaces, conditionalSinks, refinements);\n const reply = await ask(query, 'state-equation');\n if (reply instanceof Error) return inconclusive(reply.message);\n const answer = classifyFirstLine(reply);\n if (answer === 'unsat') return { kind: 'proven', refinements, queries };\n // `null` cannot reach here: the StateEquationSolver contract rejects a reply with no verdict line.\n if (answer !== 'sat') return inconclusive('the state-equation query answered unknown');\n const candidate = decodeCandidate(reply, P, T);\n if (candidate == null) return inconclusive('the state-equation model could not be decoded');\n\n const witness = searchWithinCounts(flatNet, initial, candidate.counts, isBad, witnessNodes);\n if (witness.kind === 'found') {\n return { kind: 'violated', states: witness.states, steps: witness.steps, refinements, queries };\n }\n if (refinements.length >= maxRefinements) {\n return inconclusive(`refinement budget exhausted (${maxRefinements} refinements)`, candidate);\n }\n\n const refinement = await refine(candidate);\n if (refinement instanceof Error) return inconclusive(refinement.message, candidate);\n refinements.push(refinement);\n }\n}\n\n/** `a=1, b=1 after t0 x1, t2 x1` — a candidate as the report prints it. */\nexport function describeCandidate(flatNet: FlatNet, candidate: Candidate): string {\n const marked = candidate.marking\n .map((v, p) => (v === 0 ? null : `${flatNet.places[p]!.name}=${v}`))\n .filter((s): s is string => s != null);\n const fired = candidate.counts\n .map((v, t) => (v === 0 ? null : `${flatNet.transitions[t]!.name} x${v}`))\n .filter((s): s is string => s != null);\n return `${marked.length === 0 ? '{}' : marked.join(', ')} after ${fired.length === 0 ? 'no firing' : fired.join(', ')}`;\n}\n","/**\n * @module bounded-run\n *\n * The firing-bound phase (VER-019). When every firing strictly lowers a weighted\n * token count, every run is short, and a bounded model check to that length decides\n * the property exactly — consume-all and reset clearing, inhibitor and read guards\n * included. A net whose runs are not bounded this way is reported as such and left\n * to the fixpoint query: a bound is both the runtime cap and the width of the claim.\n *\n * **Ranking.** Weights `r ≥ 0` with `r·C_t ≤ −1` for every flat transition `t` that\n * can fire. A clearing arc removes at least its weight, so the column `C_t = post −\n * pre` bounds its effect from above. `r·M` then drops by at least one per firing and\n * never goes below zero, so a run from `M0` has at most `K = r·M0` firings. One\n * `QF_LIA` query minimising `r·M0`, re-checked in exact integer arithmetic\n * ({@link checkRankingExact}). When none exists, Farkas gives `y ≥ 0, y ≠ 0` with\n * `C·y ≥ 0`: firing counts the marking equation lets repeat forever\n * ({@link encodeRepeatableVectorQuery}), whose support the report names.\n *\n * **Bounded model check.** One `QF_LIA` script unrolls `d` steps of the exact step\n * relation from `M0` — step `i` fires the transition its selector `s_i` names, or\n * idles, and once idle stays idle — and asks for a violation at the last marking\n * ({@link encodeBoundedRun}). Idling makes \"at most `d` firings\" one query. `sat` is\n * a run, decoded and replayed firing by firing before it is believed\n * ({@link replayRun}); `unsat` at `d = K` covers every run of the net.\n */\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 { ConditionalSinks } from '../rest-set.js';\nimport type { Place } from '../../core/place.js';\nimport { rethrowIfProgrammingError } from '../programming-error.js';\nimport {\n conjoin, encodePropertyViolation, intTerm, resolveEnvInjection, sumTerms,\n} from './smt-encoder.js';\nimport { classifyFirstLine, extractDefineFuns } from './smt-text.js';\nimport {\n enabledA, environmentCaps, fireA, vectorize, violationPredicate, type AbstractState,\n} from './abstract-replayer.js';\n\n/** A ranking and the firing bound it gives: `weights·C_t ≤ −1` on every transition that can fire. */\nexport interface FiringBound {\n /** `r`, one entry per flat place, all non-negative. */\n readonly weights: readonly bigint[];\n /** `K = r·M0`: no run from `M0` has more firings. */\n readonly bound: bigint;\n}\n\n/** Whether `ft` can ever fire: it does not inhibit a place it needs. */\nfunction canFire(ft: FlatTransition): boolean {\n for (const p of ft.inhibitorPlaces) {\n if (ft.preVector[p]! > 0 || ft.readPlaces.includes(p)) return false;\n }\n return true;\n}\n\n/** The `QF_LIA` script asking for the ranking with the least `r·M0`. */\nexport function encodeRankingQuery(flatNet: FlatNet, initial: readonly number[]): string {\n const P = flatNet.places.length;\n const lines = [\n '; Firing bound (VER-019): weights r >= 0 that every firing lowers by at least one',\n '; (r.C_t <= -1, a clearing arc counted at its weight); every run from M0 then has',\n '; at most r.M0 firings. sat with the least r.M0.',\n '(set-logic QF_LIA)',\n ];\n for (let p = 0; p < P; p++) lines.push(`(declare-const r${p} Int)`);\n for (let p = 0; p < P; p++) lines.push(`(assert (>= r${p} 0))`);\n for (const ft of flatNet.transitions) {\n if (!canFire(ft)) continue;\n const terms: string[] = [];\n for (let p = 0; p < P; p++) {\n const c = ft.postVector[p]! - ft.preVector[p]!;\n if (c !== 0) terms.push(intTerm(c, `r${p}`));\n }\n lines.push(`(assert (<= ${sumTerms(terms)} (- 1)))`);\n }\n const objective: string[] = [];\n for (let p = 0; p < P; p++) if (initial[p]! !== 0) objective.push(intTerm(initial[p]!, `r${p}`));\n lines.push(`(minimize ${sumTerms(objective)})`);\n lines.push('(check-sat)');\n lines.push('(get-model)');\n return lines.join('\\n');\n}\n\n/** The ranking in a `sat` reply's model; `null` when it defines no weight. */\nexport function decodeRanking(stdout: string, placeCount: number): bigint[] | null {\n const weights = new Array<bigint>(placeCount).fill(0n);\n let seen = false;\n for (const [name, value] of intDefinitions(stdout)) {\n const m = /^r(\\d+)$/.exec(name);\n if (m == null || Number(m[1]) >= placeCount) continue;\n weights[Number(m[1])] = value;\n seen = true;\n }\n return seen ? weights : null;\n}\n\n/**\n * Re-checks a ranking in exact integer arithmetic: `r ≥ 0` and `r·C_t ≤ −1` on every\n * flat transition that can fire. Returns the firing bound, or `null` when a check fails.\n */\nexport function checkRankingExact(\n flatNet: FlatNet,\n initial: readonly number[],\n weights: readonly bigint[],\n): FiringBound | null {\n const P = flatNet.places.length;\n if (weights.length !== P || weights.some((w) => w < 0n)) return null;\n for (const ft of flatNet.transitions) {\n if (!canFire(ft)) continue;\n let delta = 0n;\n for (let p = 0; p < P; p++) delta += weights[p]! * BigInt(ft.postVector[p]! - ft.preVector[p]!);\n if (delta > -1n) return null;\n }\n let bound = 0n;\n for (let p = 0; p < P; p++) bound += weights[p]! * BigInt(initial[p]!);\n return { weights, bound };\n}\n\n/**\n * The `QF_LIA` script asking for the Farkas alternative of a ranking: firing counts\n * `y ≥ 0`, not all zero, with `C·y ≥ 0` on every place — counts the marking equation\n * lets repeat forever. The fewest firings.\n */\nexport function encodeRepeatableVectorQuery(flatNet: FlatNet): string {\n const P = flatNet.places.length;\n const live = flatNet.transitions.map((ft, t) => (canFire(ft) ? t : -1)).filter((t) => t >= 0);\n const lines = [\n '; No firing bound (VER-019): firing counts y >= 0, not all zero, with C.y >= 0 on',\n '; every place, so the marking equation lets them repeat forever.',\n '(set-logic QF_LIA)',\n ];\n for (const t of live) lines.push(`(declare-const y${t} Int)`);\n for (const t of live) lines.push(`(assert (>= y${t} 0))`);\n lines.push(`(assert (>= ${sumTerms(live.map((t) => `y${t}`))} 1))`);\n for (let p = 0; p < P; p++) {\n const terms: string[] = [];\n for (const t of live) {\n const ft = flatNet.transitions[t]!;\n const c = ft.postVector[p]! - ft.preVector[p]!;\n if (c !== 0) terms.push(intTerm(c, `y${t}`));\n }\n if (terms.length > 0) lines.push(`(assert (>= ${sumTerms(terms)} 0))`);\n }\n lines.push(`(minimize ${sumTerms(live.map((t) => `y${t}`))})`);\n lines.push('(check-sat)');\n lines.push('(get-model)');\n return lines.join('\\n');\n}\n\n/** The transitions a repeatable vector fires, in net order; `null` when the model defines none. */\nexport function decodeRepeatableVector(stdout: string, transitionCount: number): number[] | null {\n const support: number[] = [];\n for (const [name, value] of intDefinitions(stdout)) {\n const m = /^y(\\d+)$/.exec(name);\n if (m != null && Number(m[1]) < transitionCount && value > 0n) support.push(Number(m[1]));\n }\n support.sort((a, b) => a - b);\n return support.length === 0 ? null : support;\n}\n\n/** Outcome of {@link findFiringBound}. */\nexport type RankingSearch =\n | { readonly kind: 'bound'; readonly bound: FiringBound }\n /** No ranking; `repeatable` is a repeatable firing vector's support, `null` when none was named. */\n | { readonly kind: 'unbounded'; readonly repeatable: readonly number[] | null }\n /** The ranking query answered `unknown`. */\n | { readonly kind: 'unknown' }\n /** The ranking the model gave failed {@link checkRankingExact}. */\n | { readonly kind: 'rejected' }\n /** `ask` failed with `reason`. */\n | { readonly kind: 'failed'; readonly reason: string };\n\n/**\n * The ranking query, re-checked exactly, and when it is `unsat` the repeatable-vector query.\n * Shared by the VER-019 phase and the open-net termination check of [VER-022]. `ask` resolves\n * with a reply that carries a verdict line, or with the `Error` that stopped it.\n */\nexport async function findFiringBound(\n flatNet: FlatNet,\n initial: readonly number[],\n ask: (script: string) => Promise<string | Error>,\n): Promise<RankingSearch> {\n const ranking = await ask(encodeRankingQuery(flatNet, initial));\n if (ranking instanceof Error) return { kind: 'failed', reason: ranking.message };\n switch (classifyFirstLine(ranking)) {\n case 'sat': {\n const weights = decodeRanking(ranking, flatNet.places.length);\n const bound = weights == null ? null : checkRankingExact(flatNet, initial, weights);\n return bound == null ? { kind: 'rejected' } : { kind: 'bound', bound };\n }\n case 'unsat': {\n const vector = await ask(encodeRepeatableVectorQuery(flatNet));\n const repeatable = vector instanceof Error || classifyFirstLine(vector) !== 'sat'\n ? null\n : decodeRepeatableVector(vector, flatNet.transitions.length);\n return { kind: 'unbounded', repeatable };\n }\n default:\n return { kind: 'unknown' };\n }\n}\n\n/**\n * The bounded model check: `depth` steps from `initial`, selector `s_i ∈ [0, T]` per\n * step (`T` idles), the exact guard and update of the selected transition, the\n * environment post-caps, and the property's violation at the last marking.\n */\nexport function encodeBoundedRun(\n flatNet: FlatNet,\n initial: readonly number[],\n property: SmtProperty,\n sinkPlaces: ReadonlySet<Place<any>>,\n conditionalSinks: readonly ConditionalSinks[],\n depth: number,\n): string {\n const P = flatNet.places.length;\n const T = flatNet.transitions.length;\n const m = (i: number, p: number): string => (i === 0 ? String(initial[p]!) : `m${i}_${p}`);\n // The encoder's `envBounds(M')` conjunct. Vacuous while `runFiringBoundPhase` refuses\n // injection, since only the `bounded` mode fills `environmentBounds`, and it injects.\n const caps = environmentCaps(flatNet);\n // Per place, the transitions that change it, last first: the `ite` chain nests inward from the last.\n const nesting: number[][] = Array.from({ length: P }, () => []);\n for (let t = T - 1; t >= 0; t--) {\n const ft = flatNet.transitions[t]!;\n for (let p = 0; p < P; p++) {\n if (clears(ft, p) || ft.postVector[p]! !== ft.preVector[p]!) nesting[p]!.push(t);\n }\n }\n const lines = [\n `; Bounded run (VER-019): ${depth} steps of the exact step relation from M0, idle`,\n '; only at the end; sat = a run to a violating marking.',\n '(set-logic QF_LIA)',\n ];\n for (let i = 0; i < depth; i++) lines.push(`(declare-const s${i} Int)`);\n for (let i = 1; i <= depth; i++) for (let p = 0; p < P; p++) lines.push(`(declare-const ${m(i, p)} Int)`);\n for (let i = 0; i < depth; i++) {\n lines.push(`(assert (and (>= s${i} 0) (<= s${i} ${T})))`);\n if (i + 1 < depth) lines.push(`(assert (=> (= s${i} ${T}) (= s${i + 1} ${T})))`);\n flatNet.transitions.forEach((ft, t) => {\n const guard = guardConditions(ft, (p) => m(i, p));\n lines.push(`(assert (=> (= s${i} ${t}) ${conjoin(guard)}))`);\n });\n for (let p = 0; p < P; p++) {\n let value = m(i, p);\n for (const t of nesting[p]!) {\n const ft = flatNet.transitions[t]!;\n const next = clears(ft, p) ? String(ft.postVector[p]!) : shifted(m(i, p), ft.postVector[p]! - ft.preVector[p]!);\n value = `(ite (= s${i} ${t}) ${next} ${value})`;\n }\n lines.push(`(assert (= ${m(i + 1, p)} ${value}))`);\n }\n for (const [p, cap] of caps) lines.push(`(assert (<= ${m(i + 1, p)} ${cap}))`);\n }\n const last: string[] = [];\n for (let p = 0; p < P; p++) last.push(m(depth, p));\n lines.push(`(assert ${encodePropertyViolation(flatNet, property, last, sinkPlaces, resolveEnvInjection(flatNet), conditionalSinks)})`);\n lines.push('(check-sat)');\n lines.push('(get-model)');\n return lines.join('\\n');\n}\n\n/** The transitions a `sat` bounded run fires, in order, up to the first idle step; `null` without selectors. */\nexport function decodeBoundedRun(stdout: string, transitionCount: number, depth: number): number[] | null {\n const selectors = new Array<number>(depth).fill(transitionCount);\n let seen = depth === 0;\n for (const [name, value] of intDefinitions(stdout)) {\n const m = /^s(\\d+)$/.exec(name);\n if (m == null || Number(m[1]) >= depth) continue;\n selectors[Number(m[1])] = Number(value);\n seen = true;\n }\n if (!seen) return null;\n const firings: number[] = [];\n for (const s of selectors) {\n if (s < 0 || s >= transitionCount) break;\n firings.push(s);\n }\n return firings;\n}\n\n/**\n * Replays a firing sequence from `initial` under the exact abstract semantics and\n * returns its markings and step names when every firing is enabled, respects the\n * environment post-caps, and the last marking violates the property; `null` otherwise.\n */\nexport function replayRun(\n flatNet: FlatNet,\n initial: AbstractState,\n firings: readonly number[],\n isBad: (state: AbstractState) => boolean,\n): { states: AbstractState[]; steps: string[] } | null {\n const caps = environmentCaps(flatNet);\n const states: AbstractState[] = [initial];\n const steps: string[] = [];\n let state = initial;\n for (const t of firings) {\n const ft = flatNet.transitions[t]!;\n if (!enabledA(state, ft)) return null;\n state = fireA(state, ft);\n if (caps.some(([idx, cap]) => state[idx]! > cap)) return null;\n states.push(state);\n steps.push(ft.name);\n }\n return isBad(state) ? { states, steps } : null;\n}\n\n/** `2*budget + q + s` — the ranking as the report prints it. */\nexport function formatRanking(flatNet: FlatNet, bound: FiringBound): string {\n const parts: string[] = [];\n bound.weights.forEach((w, p) => {\n if (w !== 0n) parts.push(w === 1n ? flatNet.places[p]!.name : `${w}*${flatNet.places[p]!.name}`);\n });\n return parts.length === 0 ? '0' : parts.join(' + ');\n}\n\n/** One depth of the bounded model check and what it answered. */\nexport interface DepthStep {\n readonly depth: number;\n readonly answer: 'sat' | 'unsat';\n}\n\n/** Outcome of {@link runFiringBoundPhase}. */\nexport type FiringBoundOutcome =\n | { readonly kind: 'proven'; readonly bound: FiringBound; readonly depths: readonly DepthStep[] }\n | {\n readonly kind: 'violated';\n readonly bound: FiringBound;\n readonly depths: readonly DepthStep[];\n readonly states: readonly AbstractState[];\n readonly steps: readonly string[];\n }\n /** No ranking exists; `repeatable` names the flat transitions a repeatable firing vector uses. */\n | { readonly kind: 'unbounded'; readonly repeatable: readonly number[] | null }\n | {\n readonly kind: 'inconclusive';\n readonly reason: string;\n readonly bound: FiringBound | null;\n readonly depths: readonly DepthStep[];\n };\n\n/** Runs one script within `timeoutMs`; rejects with the reason when the reply carries no verdict. */\nexport type FiringBoundSolver = (script: string, phase: 'ranking' | 'bmc', timeoutMs: number) => Promise<string>;\n\n/**\n * Runs the phase: {@link findFiringBound}, then the bounded model check at depths 8, 16,\n * 32, … up to the bound. A violating run is replayed before it is reported; `unsat` at the\n * bound is a proof. Builds its violation predicate from the same arguments as\n * `runStateEquationPhase`, so the two phases cannot disagree on it.\n */\nexport async function runFiringBoundPhase(\n flatNet: FlatNet,\n initialMarking: MarkingState,\n property: SmtProperty,\n sinkPlaces: ReadonlySet<Place<any>>,\n conditionalSinks: readonly ConditionalSinks[],\n run: FiringBoundSolver,\n options: { readonly budgetMs?: number; readonly maxDepth?: number } = {},\n): Promise<FiringBoundOutcome> {\n const budgetMs = options.budgetMs ?? 60_000;\n const maxDepth = options.maxDepth ?? 512;\n const deadline = performance.now() + budgetMs;\n const initial: AbstractState = vectorize(initialMarking, flatNet);\n const isBad = violationPredicate(flatNet, property, sinkPlaces, conditionalSinks);\n const depths: DepthStep[] = [];\n if (flatNet.environmentInjection.size > 0) {\n return { kind: 'inconclusive', reason: 'environment injection has no firing bound', bound: null, depths };\n }\n const ask = async (script: string, phase: 'ranking' | 'bmc'): Promise<string | Error> => {\n const left = Math.floor(deadline - performance.now());\n if (left <= 0) return new Error(`time budget of ${budgetMs} ms exhausted`);\n try {\n return await run(script, phase, left);\n } catch (e: any) {\n rethrowIfProgrammingError(e);\n return new Error(String(e?.message ?? e));\n }\n };\n\n const ranking = await findFiringBound(flatNet, initial, (script) => ask(script, 'ranking'));\n switch (ranking.kind) {\n case 'failed':\n return { kind: 'inconclusive', reason: ranking.reason, bound: null, depths };\n case 'unbounded':\n return { kind: 'unbounded', repeatable: ranking.repeatable };\n case 'unknown':\n return { kind: 'inconclusive', reason: 'the ranking query answered unknown', bound: null, depths };\n case 'rejected':\n return { kind: 'inconclusive', reason: 'the ranking failed the exact re-check', bound: null, depths };\n }\n const { bound } = ranking;\n if (bound.bound > BigInt(Number.MAX_SAFE_INTEGER)) {\n return { kind: 'inconclusive', reason: `firing bound ${bound.bound} is too large`, bound, depths };\n }\n const K = Number(bound.bound);\n let depth = Math.min(8, K, maxDepth);\n for (;;) {\n const reply = await ask(encodeBoundedRun(flatNet, initial, property, sinkPlaces, conditionalSinks, depth), 'bmc');\n if (reply instanceof Error) return { kind: 'inconclusive', reason: reply.message, bound, depths };\n const answer = classifyFirstLine(reply);\n // Record every answered depth, `sat` or `unsat`.\n if (answer !== 'sat' && answer !== 'unsat') {\n return { kind: 'inconclusive', reason: `the bounded run at depth ${depth} answered unknown`, bound, depths };\n }\n depths.push({ depth, answer });\n if (answer === 'sat') {\n const firings = decodeBoundedRun(reply, flatNet.transitions.length, depth);\n const replayed = firings == null ? null : replayRun(flatNet, initial, firings, isBad);\n if (replayed == null) {\n return { kind: 'inconclusive', reason: 'the bounded run did not replay under the exact semantics', bound, depths };\n }\n return { kind: 'violated', bound, depths, ...replayed };\n }\n if (depth >= K) return { kind: 'proven', bound, depths };\n if (depth >= maxDepth) {\n return { kind: 'inconclusive', reason: `the firing bound ${K} exceeds the depth limit ${maxDepth}`, bound, depths };\n }\n depth = Math.min(2 * depth, K, maxDepth);\n }\n}\n\nfunction clears(ft: FlatTransition, p: number): boolean {\n return ft.consumeAll[p] === true || ft.resetPlaces.includes(p);\n}\n\nfunction guardConditions(ft: FlatTransition, m: (p: number) => string): string[] {\n const out: string[] = [];\n for (let p = 0; p < ft.preVector.length; p++) if (ft.preVector[p]! > 0) out.push(`(>= ${m(p)} ${ft.preVector[p]})`);\n for (const p of ft.inhibitorPlaces) out.push(`(= ${m(p)} 0)`);\n for (const p of ft.readPlaces) out.push(`(>= ${m(p)} 1)`);\n return out;\n}\n\nfunction shifted(v: string, delta: number): string {\n if (delta === 0) return v;\n return delta > 0 ? `(+ ${v} ${delta})` : `(- ${v} ${-delta})`;\n}\n\n/** Every `(define-fun <name> () Int <value>)` of a model, as `[name, value]`. */\nfunction intDefinitions(stdout: string): [string, bigint][] {\n const out: [string, bigint][] = [];\n for (const def of extractDefineFuns(stdout)) {\n const m = /^\\(define-fun\\s+(\\S+)\\s+\\(\\)\\s+Int\\s+(\\(-\\s*(\\d+)\\s*\\)|(\\d+))\\s*\\)$/s.exec(def.trim());\n if (m != null) out.push([m[1]!, m[3] != null ? -BigInt(m[3]) : BigInt(m[4]!)]);\n }\n return out;\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`, `terminates-at-sink`,\n * `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 and emits the same\n * SMT-LIB2 text byte for byte (VER-013).\n */\nimport type { PetriNet } from '../../core/petri-net.js';\nimport type { Place } from '../../core/place.js';\nimport { strandingExcuses, type ConditionalSinks } from '../rest-set.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 {\n countViolationCondition, indexOrdered, injectionMap, type SmtEncoding, strandedConditions,\n} from './smt-encoder.js';\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 * `0` is a bound like any other (NU-053 AC6): with the covering law's initial sum at\n * zero no coloured token can ever exist, every mint / join / consumer is dead on the\n * reachable set, and the zero-slot plan is exact (`Semiflow.lean`,\n * `vacuous_colour_layer`). A validated semi-positive law's `y·M0` is never negative.\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) && 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 non-negative semiflows that touch a coloured place — the sum is\n // itself a valid non-negative P-semiflow, so `Σ y·M0` over any covering set is a\n // sound (looser) bound. Zero-constant semiflows cover their places for free, so they\n // go in first; a semiflow with a positive constant is added only if it touches a\n // coloured place the free ones left uncovered (decided against that snapshot, so the\n // result does not depend on enumeration order). If some coloured place stays at\n // weight 0 across all of them, no non-negative semiflow covers it, so the coloured\n // set is not structurally token-bounded → null (sound over-approximation).\n const covered = new Array<boolean>(coloured.length).fill(false);\n for (const inv of semiflows) {\n if (!isSemiflow(inv) || inv.constant !== 0) continue;\n for (let i = 0; i < coloured.length; i++) {\n if (w(inv, coloured[i]!) >= 1) covered[i] = true;\n }\n }\n const free = [...covered];\n let sumConst = 0;\n for (const inv of semiflows) {\n if (!isSemiflow(inv) || inv.constant === 0) continue;\n if (!coloured.some((pid, i) => !free[i] && w(inv, pid) >= 1)) continue;\n for (let i = 0; i < coloured.length; i++) {\n if (w(inv, coloured[i]!) >= 1) covered[i] = true;\n }\n sumConst += inv.constant;\n }\n if (covered.every((c) => c)) 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 // NU-053 AC6: `k = 0` is an exact plan — no coloured token can ever exist, so every\n // mint / join / consumer is dead and the zero-slot encoding emits no rule for them\n // (`Semiflow.lean`, `vacuous_colour_layer`). The one shape it cannot encode is a net\n // with no uncoloured place at all (`Reachable` would be nullary and every rule's\n // `ForAll` binder list empty); such a net holds no token at M0, so fall back.\n if (k === 0 && coloured.length === P) 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, named exactly as the Rust reference names\n * them (`m{i}` / `m{i}_{c}`, next marking with a `p` suffix).\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 /** Current-marking variable names, one per column. */\n readonly cur: string[];\n /** Next-marking variable names, one per column. */\n readonly nxt: string[];\n}\n\nfunction buildLayout(plan: ColouredPlan, P: number): Layout {\n const colUnc: number[] = new Array<number>(P).fill(-1);\n const colCol: number[][] = Array.from({ length: P }, () => []);\n const cur: string[] = [];\n const nxt: string[] = [];\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++) {\n idxs.push(cur.length);\n cur.push(`m${i}_${c}`);\n nxt.push(`m${i}_${c}p`);\n }\n colCol[i] = idxs;\n } else {\n colUnc[i] = cur.length;\n cur.push(`m${i}`);\n nxt.push(`m${i}p`);\n }\n }\n return { colUnc, colCol, cur, nxt };\n}\n\nfunction quantified(names: readonly string[]): string {\n return names.map((v) => `(${v} Int)`).join(' ');\n}\n\n/** A changed column and its update expression. */\ninterface Update {\n readonly col: number;\n readonly expr: string;\n}\n\n/** Contributes the enablement guards and the changed-column updates of a rule. */\ntype Fill = (enab: string[], upd: Update[]) => void;\n\n/**\n * Encodes the supported ν-net as bounded name-coloured CHC for Z3 Spacer, as SMT-LIB2\n * text byte-identical to the Rust reference (`encode_coloured`). With the query\n * `(not Error)`, `sat` ⇒ PROVEN, `unsat` ⇒ VIOLATED (the Spacer convention shared with\n * 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 plan: ColouredPlan,\n flat: FlatNet,\n initial: MarkingState,\n property: SmtProperty,\n invariants: readonly PInvariant[],\n sinkPlaces: ReadonlySet<Place<any>>,\n conditionalSinks: readonly ConditionalSinks[] = [],\n): SmtEncoding | null {\n const P = flat.places.length;\n const k = plan.k;\n const lay = buildLayout(plan, P);\n const nCols = lay.cur.length;\n\n const lines: string[] = [];\n lines.push('(set-logic HORN)');\n lines.push('');\n lines.push(`(declare-fun Reachable (${new Array<string>(nCols).fill('Int').join(' ')}) Bool)`);\n lines.push('(declare-fun Error () Bool)');\n lines.push('');\n\n // Init: uncoloured places carry their initial count; coloured start empty.\n const init: string[] = [];\n for (let i = 0; i < P; i++) {\n if (plan.isColoured[i]) {\n for (let c = 0; c < k; c++) init.push('0');\n } else {\n init.push(String(initial.tokens(flat.places[i]!)));\n }\n }\n lines.push(`(assert (Reachable ${init.join(' ')}))`);\n lines.push('');\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 switch (cls.kind) {\n case 'untouched':\n lines.push(encodeRule(plan, lay, invariants, (enab, upd) => uncolouredIncidence(lay, plan, ft, enab, upd)));\n break;\n case 'mint':\n for (let c = 0; c < k; c++) {\n lines.push(encodeRule(plan, lay, invariants, (enab, upd) => {\n uncolouredIncidence(lay, plan, ft, enab, upd);\n // Globally fresh colour: c must be empty in every coloured place.\n for (const q of plan.coloured) enab.push(`(= ${lay.cur[lay.colCol[q]![c]!]} 0)`);\n for (const o of cls.colouredOut) {\n const col = lay.colCol[o]![c]!;\n upd.push({ col, expr: `(+ ${lay.cur[col]} 1)` });\n }\n }));\n }\n break;\n case 'join':\n for (let c = 0; c < k; c++) {\n lines.push(encodeRule(plan, lay, invariants, (enab, upd) => {\n uncolouredIncidence(lay, plan, ft, enab, upd);\n // Same colour c present in every correlated input.\n for (const ip of cls.colouredIn) {\n const col = lay.colCol[ip]![c]!;\n enab.push(`(>= ${lay.cur[col]} 1)`);\n upd.push({ col, expr: `(- ${lay.cur[col]} 1)` });\n }\n }));\n }\n break;\n case 'consume':\n // One rule per colour: consume colour c from the single coloured input and\n // thread it into each coloured output (relay), or into none (drain).\n for (let c = 0; c < k; c++) {\n lines.push(encodeRule(plan, lay, invariants, (enab, upd) => {\n uncolouredIncidence(lay, plan, ft, enab, upd);\n const icol = lay.colCol[cls.inputCol]![c]!;\n enab.push(`(>= ${lay.cur[icol]} 1)`);\n upd.push({ col: icol, expr: `(- ${lay.cur[icol]} 1)` });\n for (const o of cls.colouredOut) {\n const ocol = lay.colCol[o]![c]!;\n upd.push({ col: ocol, expr: `(+ ${lay.cur[ocol]} 1)` });\n }\n }));\n }\n break;\n }\n }\n lines.push('');\n\n // Error rule. `null` ⇒ the property names an unresolved place; refuse to build a\n // vacuously-provable encoding and let the verifier report Unknown.\n const error = encodeError(plan, lay, flat, property, sinkPlaces, injectionMap(flat), conditionalSinks);\n if (error == null) return null;\n lines.push(error);\n lines.push('');\n lines.push('(assert (not Error))');\n lines.push('(check-sat)');\n\n return { smt2: lines.join('\\n'), placeCount: P, counterCount: 0 };\n}\n\n/**\n * Builds one transition CHC rule. `fill` contributes the enablement guards and the\n * changed-column updates; every other column is copied unchanged, changed columns get\n * a non-negativity guard, and the (lifted) P-invariants constrain the successor.\n */\nfunction encodeRule(plan: ColouredPlan, lay: Layout, invariants: readonly PInvariant[], fill: Fill): string {\n const enab: string[] = [];\n const upd: Update[] = [];\n fill(enab, upd);\n\n const conditions: string[] = [`(Reachable ${lay.cur.join(' ')})`, ...enab];\n\n // A changed column gets its update + non-negativity guard; every other column is\n // copied unchanged. A later update of the same column wins.\n const changed: (string | null)[] = new Array<string | null>(lay.cur.length).fill(null);\n for (const u of upd) changed[u.col] = u.expr;\n for (let col = 0; col < lay.cur.length; col++) {\n const expr = changed[col];\n if (expr != null) {\n conditions.push(`(= ${lay.nxt[col]} ${expr})`);\n conditions.push(`(>= ${lay.nxt[col]} 0)`);\n } else {\n conditions.push(`(= ${lay.nxt[col]} ${lay.cur[col]})`);\n }\n }\n\n for (const inv of invariants) {\n const eq = liftedInvariant(inv, plan, lay, lay.nxt);\n if (eq != null) conditions.push(eq);\n }\n\n const body = `(and ${conditions.join('\\n ')})`;\n return `(assert (forall (${quantified([...lay.cur, ...lay.nxt])})\\n (=> ${body}\\n (Reachable ${lay.nxt.join(' ')}))))`;\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 columns\n * are handled by the caller (mint produces, join/consumer consume).\n */\nfunction uncolouredIncidence(lay: Layout, plan: ColouredPlan, ft: FlatTransition, enab: string[], upd: Update[]): 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]} ${pre})`);\n if (ft.resetPlaces.includes(i) || ft.consumeAll[i]) {\n upd.push({ col, expr: String(ft.postVector[i]) });\n } else {\n const delta = ft.postVector[i]! - ft.preVector[i]!;\n if (delta > 0) upd.push({ col, expr: `(+ ${lay.cur[col]} ${delta})` });\n else if (delta < 0) upd.push({ col, expr: `(- ${lay.cur[col]} ${-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]!]} 0)`);\n for (const pid of ft.readPlaces) enab.push(`(>= ${lay.cur[lay.colUnc[pid]!]} 1)`);\n}\n\n/**\n * Aggregate token-count expression for a place over the given var-set (`cur` or\n * `nxt`): the single uncoloured var, or the sum of its colours.\n */\nfunction aggregate(plan: ColouredPlan, lay: Layout, place: number, names: readonly string[]): string {\n if (plan.isColoured[place]) {\n const cols = lay.colCol[place]!;\n // k = 0: a coloured place has no slot and never holds a token.\n if (cols.length === 0) return '0';\n if (cols.length === 1) return names[cols[0]!]!;\n return `(+ ${cols.map((c) => names[c]!).join(' ')})`;\n }\n return names[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). Returns `null` when the\n * invariant support is empty.\n */\nfunction liftedInvariant(inv: PInvariant, plan: ColouredPlan, lay: Layout, names: readonly string[]): string | null {\n const terms: string[] = [];\n for (const i of [...inv.support].sort((a, b) => a - b)) {\n const agg = aggregate(plan, lay, i, names);\n const w = inv.weights[i]!;\n terms.push(w === 1 ? agg : `(* ${w} ${agg})`);\n }\n if (terms.length === 0) return null;\n const sum = terms.length === 1 ? terms[0]! : `(+ ${terms.join(' ')})`;\n return `(= ${sum} ${inv.constant})`;\n}\n\n/**\n * Encodes the error rule: a reachable marking that violates the property, or `null`\n * when the property names an unresolved place ({@link encodeViolation}).\n */\nfunction encodeError(\n plan: ColouredPlan,\n lay: Layout,\n flat: FlatNet,\n property: SmtProperty,\n sinkPlaces: ReadonlySet<Place<any>>,\n envInj: ReadonlyMap<number, number | null>,\n conditionalSinks: readonly ConditionalSinks[],\n): string | null {\n const violation = encodeViolation(plan, lay, flat, property, sinkPlaces, envInj, conditionalSinks);\n if (violation == null) return null;\n return `(assert (forall (${quantified(lay.cur)})\\n (=> (and (Reachable ${lay.cur.join(' ')}) ${violation})\\n Error)))`;\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) build on the colour-aware quiescence predicate, each\n * conjoining its own clause.\n *\n * Returns `null` when the property names a place that does not resolve in the net\n * (e.g. a typo'd bound/pending place). A `false` violation term there would make the\n * Error rule unsatisfiable and yield a **vacuous** PROVEN, silently certifying a\n * mis-named place; `null` propagates up so the verifier reports Unknown instead.\n */\nfunction encodeViolation(\n plan: ColouredPlan,\n lay: Layout,\n flat: FlatNet,\n property: SmtProperty,\n sinkPlaces: ReadonlySet<Place<any>>,\n envInj: ReadonlyMap<number, number | null>,\n conditionalSinks: readonly ConditionalSinks[],\n): string | null {\n const anyPlacePresent = (places: Iterable<Place<any>>): string => {\n const conds = indexOrdered(flat, places).map((pid) => `(>= ${aggregate(plan, lay, pid, lay.cur)} 1)`);\n return conds.length === 0 ? 'false' : `(and ${conds.join(' ')})`;\n };\n switch (property.type) {\n case 'place-bound':\n case 'branch-place-bound': {\n const pid = flat.placeIndex.get(property.place.name);\n // Unresolved bound place: a false violation term would vacuously PROVE the\n // bound. Return null so the verifier reports Unknown instead of certifying.\n if (pid == null) return null;\n return `(> ${aggregate(plan, lay, pid, lay.cur)} ${property.bound})`;\n }\n case 'mutual-exclusion':\n return anyPlacePresent([property.p1, property.p2]);\n case 'unreachable':\n return anyPlacePresent(property.places);\n // DeadlockFree (VER-002): quiescent AND some marked place is not where resting\n // is permitted (VER-014). Mirrors the flat encoder's `stranded` disjunction over\n // the aggregate (all-colour) count of each place.\n case 'deadlock-free': {\n const conds = encodeColouredQuiescent(plan, lay, flat, envInj);\n if (conds == null) return 'false';\n const counts: string[] = [];\n for (let pid = 0; pid < flat.places.length; pid++) counts.push(aggregate(plan, lay, pid, lay.cur));\n const stranded = strandedConditions(strandingExcuses(flat, sinkPlaces, conditionalSinks), counts);\n // Every place is a declared sink: nothing can ever be stranded.\n if (stranded.length === 0) return 'false';\n conds.push(`(or ${stranded.join(' ')})`);\n return joinColoured(conds);\n }\n // TerminatesAtSink (VER-002): quiescent AND no declared sink marked.\n case 'terminates-at-sink': {\n const conds = encodeColouredQuiescent(plan, lay, flat, envInj);\n if (conds == null) return 'false';\n for (const pid of indexOrdered(flat, sinkPlaces)) {\n conds.push(`(= ${aggregate(plan, lay, pid, lay.cur)} 0)`);\n }\n return joinColoured(conds);\n }\n // JoinedOrDeadLettered (NU-040 AC4): quiescent AND `pending` marked, with NO\n // sink clause.\n case 'joined-or-dead-lettered': {\n const pid = flat.placeIndex.get(property.pending.name);\n if (pid == null) return null;\n const conds = encodeColouredQuiescent(plan, lay, flat, envInj);\n if (conds == null) return 'false';\n conds.push(`(>= ${aggregate(plan, lay, pid, lay.cur)} 1)`);\n return joinColoured(conds);\n }\n // QuiescentCount (VER-002): the flat encoder's count clause over aggregate counts.\n case 'quiescent-count': {\n const bad = countViolationCondition(\n indexOrdered(flat, property.places).map((pid) => aggregate(plan, lay, pid, lay.cur)),\n indexOrdered(flat, property.waivedBy).map((pid) => aggregate(plan, lay, pid, lay.cur)),\n property.min,\n property.max,\n );\n if (bad == null) return 'false';\n const conds = encodeColouredQuiescent(plan, lay, flat, envInj);\n if (conds == null) return 'false';\n conds.push(bad);\n return joinColoured(conds);\n }\n }\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), collected into `reasons`;\n * returns `true` when the transition is permanently disabled (an env cap below the\n * demand means it can never fire). Coloured places are excluded — their enablement is\n * the per-class colour term.\n */\nfunction uncolouredDisable(\n ft: FlatTransition,\n lay: Layout,\n plan: ColouredPlan,\n envInj: ReadonlyMap<number, number | null>,\n reasons: string[],\n): boolean {\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]!]} ${ft.preVector[i]})`);\n }\n for (const inh of ft.inhibitorPlaces) reasons.push(`(> ${lay.cur[lay.colUnc[inh]!]} 0)`);\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]!]} 1)`);\n }\n return 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(cls: Klass, plan: ColouredPlan, lay: Layout): string | null {\n const k = plan.k;\n if (k === 0) {\n // k = 0 (NU-053 AC6): no colour can ever be present, so every coloured class is\n // disabled outright; the empty conjunctions below would render as `(and )`.\n return cls.kind === 'untouched' ? null : 'true';\n }\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: string[] = [];\n for (let c = 0; c < k; c++) {\n const present = plan.coloured.map((q) => `(>= ${lay.cur[lay.colCol[q]![c]!]} 1)`);\n perColour.push(`(or ${present.join(' ')})`);\n }\n return `(and ${perColour.join(' ')})`;\n }\n case 'join': {\n // No colour is shared by all correlated inputs: for every colour c, some input\n // lacks c.\n const perColour: string[] = [];\n for (let c = 0; c < k; c++) {\n const missing = cls.colouredIn.map((i) => `(= ${lay.cur[lay.colCol[i]![c]!]} 0)`);\n perColour.push(`(or ${missing.join(' ')})`);\n }\n return `(and ${perColour.join(' ')})`;\n }\n case 'consume': {\n // No colour present at the single coloured input.\n const perColour: string[] = [];\n for (let c = 0; c < k; c++) perColour.push(`(= ${lay.cur[lay.colCol[cls.inputCol]![c]!]} 0)`);\n return `(and ${perColour.join(' ')})`;\n }\n }\n}\n\n/** Joins coloured violation conjuncts. Empty is vacuously true. */\nfunction joinColoured(conds: readonly string[]): string {\n return conds.length === 0 ? 'true' : `(and ${conds.join(' ')})`;\n}\n\n/**\n * Colour-aware quiescence predicate (NU-053): every transition is disabled (no\n * colour enables it). Mirrors the flat `encodeQuiescent` with the same\n * env-injection relaxation (VER-006), lifted to the coloured layout. Carries no\n * sink clause — each property conjoins its own.\n *\n * `null` means some transition is enabled in every marking: never quiescent.\n */\nfunction encodeColouredQuiescent(\n plan: ColouredPlan,\n lay: Layout,\n flat: FlatNet,\n envInj: ReadonlyMap<number, number | null>,\n): string[] | null {\n const disabledConditions: string[] = [];\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: string[] = [];\n const permanentlyDisabled = uncolouredDisable(ft, lay, plan, envInj, reasons);\n if (permanentlyDisabled) {\n // The transition can never fire — it is always \"disabled\".\n disabledConditions.push('true');\n continue;\n }\n const term = colouredDisabledTerm(cls, plan, lay);\n if (term != null) reasons.push(term);\n // Always enabled (possibly via injection) — never quiescent.\n if (reasons.length === 0) return null;\n disabledConditions.push(reasons.length === 1 ? reasons[0]! : `(or ${reasons.join(' ')})`);\n }\n\n return 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';\nimport { compareCodePoints } from '../../core/internal/code-point-order.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 // By place name in code-point order, as the Rust port sorts them: the join seeds the\n // symbols it enumerates from its first coloured input, which orders the successors.\n colouredIn.sort((a, b) => compareCodePoints(a[0], b[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.\n *\n * Both layers are interned by {@link NameStateClassGraph.build} (VER-012): a class\n * shares its base with every class at the same marking, zone and earliest-ready\n * times, and its name layer with every class whose partition has the same\n * canonical key — a renaming of it, which every consumer of the layer is\n * invariant under (`Interning.lean`, `interned_keys_eq`).\n */\nexport class NameStateClass {\n readonly base: StateClass;\n readonly names: NameMarking;\n /** The symmetry-canonical name-partition key (the name layer's intern key). */\n readonly nameKey: string;\n\n constructor(base: StateClass, names: NameMarking, colouredOrder: readonly string[], nameKey?: string) {\n this.base = base;\n this.names = names;\n this.nameKey = nameKey ?? names.canonicalKey(colouredOrder);\n }\n\n /** Full dedup key: the base key (marking + DBM zone) joined with the name key. */\n get key(): string {\n return `${baseKeyOf(this.base)}||${this.nameKey}`;\n }\n}\n\n/**\n * The base layer's identity for dedup: marking + the full DBM zone (what\n * `StateClass.equals` compares). The zone is keyed in full, not by its per-clock\n * projections — see {@link DBM.zoneKey} for the over-merge the projections allow.\n */\nexport function baseKeyOf(base: StateClass): string {\n return `${base.marking.toString()}|${base.firingDomain.zoneKey()}`;\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, baseKeyOf } from './name-state-class.js';\nimport type { StateClass } from './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 // Hash-consing (memory only, no semantic effect — VER-012, `Interning.lean`):\n // the base layer is shared between classes at the same (marking, zone,\n // earliest-ready times) and the name layer between classes with the same\n // canonical key; a class is identified by the pair of intern ids, so no\n // per-class key string is retained.\n const baseIntern = new Map<string, InternedBase>();\n const nameIntern = new Map<string, InternedNames>();\n const indexOf = new Map<string, number>();\n // Coloured places start empty in the supported fragment (the verifier guards\n // this), so the initial name partition is empty.\n const b0 = internBase(baseIntern, base0);\n const n0 = internNames(nameIntern, new NameMarking(), fragment.colouredOrder);\n graph.pushClass(\n new NameStateClass(b0.base, n0.names, fragment.colouredOrder, n0.nameKey),\n classId(b0.id, n0.id),\n indexOf,\n );\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 const shared = internBase(baseIntern, baseSucc);\n for (const nm of nameSuccs) {\n const sharedNames = internNames(nameIntern, nm, fragment.colouredOrder);\n const id = classId(shared.id, sharedNames.id);\n let toIdx = indexOf.get(id);\n if (toIdx === undefined) {\n toIdx = graph.classes.length;\n graph.pushClass(\n new NameStateClass(shared.base, sharedNames.names, fragment.colouredOrder, sharedNames.nameKey),\n id,\n indexOf,\n );\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, id: string, indexOf: Map<string, number>): void {\n const idx = this.classes.length;\n this.classes.push(c);\n this._successors.push([]);\n indexOf.set(id, 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\ninterface InternedBase {\n readonly id: number;\n readonly base: StateClass;\n}\n\ninterface InternedNames {\n readonly id: number;\n readonly names: NameMarking;\n readonly nameKey: string;\n}\n\n/** A class's identity: the pair of intern ids of its two layers. */\nfunction classId(baseId: number, nameId: number): string {\n return `${baseId}:${nameId}`;\n}\n\n/**\n * Interns the base layer: one {@link StateClass} per distinct (marking, zone,\n * earliest-ready times). `StateClass.equals` is marking + zone, which is all base\n * timed-reachability needs — but the NU-052 prune ({@link priorityDominated}) also\n * reads `readyEarliest`, the class-relative lower bounds captured before\n * `letTimePass`, and two arrivals at one zone can disagree on those (a transition\n * freshly enabled here versus one persistent through an unbounded delay). Sharing a\n * base across name layers is semantics-free only if the shared object carries\n * everything the successor step reads (`Interning.lean`, `equivariance_is_necessary`\n * is the witness), so the key is all three.\n */\nfunction internBase(intern: Map<string, InternedBase>, base: StateClass): InternedBase {\n const key = `${baseKeyOf(base)}#${base.readyEarliest.join(',')}`;\n let entry = intern.get(key);\n if (entry === undefined) {\n entry = { id: intern.size, base };\n intern.set(key, entry);\n }\n return entry;\n}\n\n/**\n * Interns the name layer: one {@link NameMarking} per canonical key. Two layers with\n * the same key are the same partition up to a renaming of symbols, and every\n * consumer of the layer — {@link nameSuccessors}, {@link willFire}, the key itself —\n * is invariant under renaming; freshness stays sound because the mint counter never\n * revisits an id (`Interning.lean`, `interned_keys_eq`).\n */\nfunction internNames(\n intern: Map<string, InternedNames>,\n names: NameMarking,\n colouredOrder: readonly string[],\n): InternedNames {\n const nameKey = names.canonicalKey(colouredOrder);\n let entry = intern.get(nameKey);\n if (entry === undefined) {\n entry = { id: intern.size, names, nameKey };\n intern.set(nameKey, entry);\n }\n return entry;\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 *\n * Exported for the interning test only: this step's equivariance under symbol\n * renaming is the hypothesis `Interning.lean` rests on.\n */\nexport function 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 { ConditionalSinks } from './rest-set.js';\nimport { decideOverClasses } from './graph-decision.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 conditionalSinks: readonly ConditionalSinks[] = [],\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, conditionalSinks);\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/**\n * A witnessing class index for a violation, or -1 if the property holds.\n *\n * The predicate itself lives in {@link decideOverClasses}, shared with the plain\n * enumeration route of [VER-017] so the two cannot drift ([VER-002] AC7).\n */\nfunction decide(\n scg: NameStateClassGraph,\n property: SmtProperty,\n sinkPlaces: ReadonlySet<Place<any>>,\n conditionalSinks: readonly ConditionalSinks[],\n): number {\n return decideOverClasses(\n {\n count: scg.classCount(),\n markingOf: i => scg.markingOf(i),\n isQuiescent: i => scg.successorsOf(i).length === 0,\n },\n property,\n sinkPlaces,\n conditionalSinks,\n );\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 { rethrowIfProgrammingError } from './programming-error.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 { describeSinks, type ConditionalSinks } from './rest-set.js';\nimport type { SmtVerificationResult, SmtStatistics, Verdict, VerificationRoute } 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 { canonicalInvariantOrder, computePInvariants, computePSemiflows, isCoveredByInvariants, strengthenWithSemiflows, validateInvariantsExact } from './invariant/p-invariant-computer.js';\nimport { structuralCheck } from './invariant/structural-check.js';\nimport { runZ3Spacer } from './z3/spacer-runner.js';\nimport { checkCertificate, vcScript, type CertificateCheckOutcome } from './z3/certificate-checker.js';\nimport { encodeNet, quiescenceUnreachable, resolveEnvInjection, type SmtEncoding } from './z3/smt-encoder.js';\nimport {\n checkLinearBoundExact, decodeLinearBound, encodeLinearBound, formatLinearBound, formatLinearDemand,\n} from './z3/linear-bound.js';\nimport { classifyFirstLine, errorLine } from './z3/smt-text.js';\nimport { encodeStateEquationQuery, formatInequality, refinementCertificate } from './z3/state-equation-query.js';\nimport { describeCandidate, runStateEquationPhase } from './z3/state-equation-phase.js';\nimport { formatRanking, runFiringBoundPhase, type DepthStep, type FiringBound } from './z3/bounded-run.js';\nimport { failureReason, formatZ3Version, resolveZ3, runZ3Text, timeoutBudget, Z3Unavailable, type Z3Solver } from './z3/z3-process.js';\nimport { buildColouredPlan, encodeColoured, type ColouredPlan } from './z3/name-coloured-encoder.js';\nimport { verifyViaNameScg } from './nu-scg-verifier.js';\nimport { verifyViaStateClassGraph, isUntimed, NOTE_ENUMERATED } from './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 {\n replayCounterexample, vectorize, toMarkingState, stepName, type AbstractState, type ReplayOutcome,\n} from './z3/abstract-replayer.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 * - Input specifications are purely structural (IO-006) — there is no per-arc\n * predicate for the encoder to be blind to\n * - If a counterexample is found, it may be spurious in timed semantics —\n * 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 */\n/**\n * Why a `proven` is refused under `ignore()` (VER-006). Shared by every route that can\n * return `proven`, so the guards cannot drift apart.\n */\nconst IGNORE_MODE_VACUITY_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\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 _conditionalSinks: { marker: Place<any>; places: Set<Place<any>> }[] = [];\n private readonly _budgetPlaces = new Set<string>();\n private _environmentMode: EnvironmentAnalysisMode = alwaysAvailable();\n private _timeoutMs: number = 60_000;\n private _certificateCheck: boolean = true;\n private _counterexampleReplay: boolean = true;\n private _semiflowInvariants: boolean | 'auto' = false;\n private _stateEquation: boolean = false;\n private _linearBound: boolean = true;\n private _stateEquationPhase: boolean = true;\n private _firingBound: boolean = true;\n private _nuMaxClasses: number = 100_000;\n private _enumerationMaxClasses: number = 50_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 * (VER-002): a token resting in one is never stranded, and `TerminatesAtSink`\n * asks whether one of them was reached.\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 places where a token may rest **while `marker` holds a token**\n * (VER-014) — a designed terminal such as a halt or pause marker, under which\n * the work it interrupted legitimately stays where it was delivered.\n *\n * `DeadlockFree` then reads a quiescent marking against the union of the\n * declared sinks, the markers, and every conditional set whose marker is marked:\n * a token in `p` is stranded only when none of those excuse it. The marker\n * itself is at rest whenever it is marked, so `sinkPlacesWhen(halt)` with no\n * further places excuses exactly the halt token. Repeated calls for one marker\n * accumulate; declarations for several markers union. `TerminatesAtSink` is\n * unaffected and reads only {@link sinkPlaces}.\n *\n * ```ts\n * SmtVerifier.forNet(net)\n * .property(deadlockFree())\n * .sinkPlaces(done) // may always rest\n * .sinkPlacesWhen(halt, inbox, pending) // may rest once the run halted\n * .sinkPlacesWhen(pause, inbox) // may rest while paused\n * ```\n *\n * An unresolved marker or place contributes nothing, as an unresolved sink\n * does: a mistyped marker makes the property stricter, never laxer.\n */\n sinkPlacesWhen(marker: Place<any>, ...places: Place<any>[]): this {\n let entry = this._conditionalSinks.find(c => c.marker.name === marker.name);\n if (entry == null) {\n entry = { marker, places: new Set<Place<any>>() };\n this._conditionalSinks.push(entry);\n }\n for (const p of places) entry.places.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 * Enables/disables the independent IC3 certificate check (default: enabled).\n *\n * When a proven verdict comes from the IC3/Spacer path on the flat count\n * encoding, the synthesized inductive invariant is re-validated with a plain\n * solver against the UNSTRENGTHENED step relation — VC1 (init), VC2\n * (consecution), VC3 (safety) — so a Spacer or encoder defect cannot certify\n * a false PROVEN. A certificate that fails validation downgrades the verdict\n * to unknown. Structural proofs and the coloured ν-encoding are unaffected.\n */\n certificateCheck(enabled: boolean): this {\n this._certificateCheck = enabled;\n return this;\n }\n\n /**\n * Enables/disables abstract counterexample replay (default: enabled).\n *\n * When a violated verdict comes from the flat count encoding, the decoded\n * counterexample states (an order-free set — the derivation tree is walked in\n * traversal order, not firing order) are re-executed TS-side against the\n * abstract semantics the encoder emits (Lean's `fireA`, Basic.lean), searching\n * for a firing order from M₀ to a property-violating marking. See\n * `SmtVerificationResult.counterexampleConfirmed` for how each outcome lands.\n */\n counterexampleReplay(enabled: boolean): this {\n this._counterexampleReplay = enabled;\n return this;\n }\n\n /**\n * Also hands the validated **P-semiflows** to the encoders as invariants\n * (VER-007; default: disabled — the encoders then see only the null-space basis).\n *\n * Every validated semiflow is a conservation law in its own right (`y >= 0`,\n * `y·C = 0`, `y·M0` exact, zero weight on every reset / consume-all place), and\n * the Farkas enumeration returns the *minimal* laws of the net. The null-space\n * basis the encoders get by default is one basis of many: elimination hands back\n * mixed-sign rows (discarded as not semi-positive) or rows that fold a reset place\n * into a chain whose other combinations avoid it (dropped by the H1 guard). On a\n * net with a few reset arcs that can lose every law of the chains those arcs\n * touch, and without them IC3 has to rediscover the conservation of each chain —\n * on a ~100-place net it does not within any practical budget.\n *\n * **Turn this on if the net has any `all()` / `atLeast(n)` or reset arc on a busy\n * place** — draining an input queue is the everyday case. Every basis row whose\n * support touches such a place fails the H1 guard and is dropped, so the encoders\n * run on a deficient invariant set and nothing in the report says a law is missing\n * beyond the `Dropped` lines.\n *\n * This reaches the **name-coloured** encoder (NU-050) as well as the flat one, and\n * it matters most there. On a 113-place ν-net, whole-net deadlock-freedom went from\n * `unknown` after 50 minutes to `proven` in about 15 seconds with this option as the\n * only change; on the flat path, reachability-safety queries that timed out at 120 s\n * close in about a second.\n *\n * Soundness is unchanged: the semiflows pass the same exact re-validation as the\n * basis rows, the union is pure strengthening (`Semiflow.lean`,\n * `semiflow_union_sound`), and the certificate check re-proves the strengthened\n * invariant — that check is flat-path only, so a coloured `proven` reports\n * `Certificate check: not applicable (name-coloured encoding)`. Off by default so\n * reports stay byte-equal.\n */\n /**\n * `'auto'` decides whether the semiflows would add **information to the\n * encoding**, which is not the same question as whether they would appear in\n * {@link SmtVerificationResult.invariants} for a caller who reads them.\n *\n * A complete basis spans every conservation law of the net, so a semiflow it\n * spans constrains nothing further and IC3 gains nothing from it — that is why\n * `'auto'` skips the enumeration there. But the basis is the *signed*\n * null-space, and a law it spans need not appear in it in **non-negative**\n * form; only the Farkas enumeration produces that. A caller inspecting the\n * invariant list for a law of a given shape — \"a non-negative law weighting the\n * budget place and every running place positively\" — can therefore find nothing\n * on a net that plainly has one. Such a caller should ask for the union\n * explicitly: `'auto'` is the setting to prefer for verification, not for\n * harvesting.\n */\n semiflowInvariants(enabled: boolean | 'auto'): this {\n this._semiflowInvariants = enabled;\n return this;\n }\n\n /**\n * Enables/disables the linear state-equation bound phase (VER-015; default:\n * enabled). A reachability-safety property whose violating markings exceed some\n * `y·M <= y·M0` with `y >= 0`, `y·C <= 0` is then proven structurally, from one\n * linear query re-checked in exact integer arithmetic, before any fixpoint search.\n * Disable it to force the IC3/PDR path — for its certificate, or to exercise the\n * fixpoint engine itself.\n */\n linearBound(enabled: boolean): this {\n this._linearBound = enabled;\n return this;\n }\n\n /**\n * Encodes the **state equation** with firing counters (VER-016; default:\n * disabled — the encoding then carries places only).\n *\n * The flat encoding gains one counter `n_t` per flat transition and every\n * transition rule conjoins the marking equation `M' = M0 + C·n'` for each place\n * whose column is exact (no consume-all / reset arc, not injected). Every linear\n * consequence of the marking equation — the equality laws of VER-005/VER-007\n * **and** the inequality laws `y·M ≤ y·M0` (`y ≥ 0, y·C ≤ 0`) and their mixed-sign\n * kin, which are what an *ordering* argument (\"both join slots armed means every\n * upstream stage has run, so nothing can still halt\") looks like in linear\n * arithmetic — is then available to Spacer as a fact rather than a lemma it has to\n * invent. On a 50-place agent-dispatch workflow, proper completion under conditional\n * sinks went from `unknown` after 120 s to `proven` in 1.5 s with this as the only\n * change; a 53-place pipeline stage before a join, `unknown` at 300 s, proves in\n * under a second.\n *\n * The cost is a larger state (places + transitions) and a slower witness search\n * on genuinely violated properties (about 1.5× on the nets above), so it is opt-in.\n * Soundness is unchanged: the counters are exact bookkeeping, the equation holds\n * on every reachable state by construction (`Strengthening.lean`, the same shape\n * as the equality laws), and the certificate check re-proves it against the raw\n * step relation, whose only counter knowledge is the increment. Not applied to the\n * name-coloured encoding or Route B, which the report says when it applies.\n *\n * Not {@link stateEquationPhase}, the VER-018 pre-phase (on by default) that can decide\n * the property instead of the fixpoint query.\n */\n stateEquation(enabled: boolean): this {\n this._stateEquation = enabled;\n return this;\n }\n\n /**\n * Enables/disables the state-equation phase (VER-018; default: enabled).\n *\n * Before the fixpoint query, one linear query asks whether a marking the marking\n * equation (`M = M0 + C·n`, `n ≥ 0`, an upper bound on a cleared place) admits violates\n * the property; `unsat` proves it. A `sat` candidate is settled cheapest first: a run\n * within its firing counts that reaches a violation (the counterexample), an initially\n * marked trap it empties, or an inequality `a·M ≤ b` kept by the exact step relation\n * that excludes it. The refinement is added and the query asked again.\n *\n * The proof `SE ∧ refinements` passes the certificate check before it is reported, and\n * the report prints each refinement, e.g. `Merge/hasdata <= Merge/ready_0 +\n * Merge/ready_1` on a workflow join. When nothing settles a candidate, the pipeline\n * continues unchanged. Flat path only: skipped for a ν-net and under `ignore` with\n * environment places. Runs within the full {@link timeout}; the certificate check gets\n * its own.\n *\n * Not {@link stateEquation}, which adds firing counters inside the fixpoint encoding.\n */\n stateEquationPhase(enabled: boolean): this {\n this._stateEquationPhase = enabled;\n return this;\n }\n\n /**\n * Enables/disables the firing-bound phase (VER-019; default: enabled).\n *\n * Weights `r ≥ 0` that every firing lowers by at least one bound every run by\n * `K = r·M0` firings, so a bounded model check to depth `K` decides the property. The\n * depth doubles from 8, which finds a short counterexample early. Without such weights\n * the report names the transitions the marking equation lets repeat, and the fixpoint\n * query runs.\n *\n * A proof carries no inductive invariant: the ranking is re-checked in exact integer\n * arithmetic, and a counterexample is replayed. Runs after the state-equation phase, on\n * the same nets, within half the {@link timeout}.\n */\n firingBound(enabled: boolean): this {\n this._firingBound = enabled;\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 * Sets the class budget for the bounded state-space enumeration route\n * (VER-017; default 50 000). `0` disables the route, so every query goes to\n * the SMT pipeline.\n *\n * When the state-class graph closes within the budget the property is decided\n * exactly — sound and complete over the timed semantics — and no solver runs.\n * This is what makes a long pipeline tractable: IC3 needs a frame per stage and\n * its cost climbs with the cube of the length, while enumeration is linear in\n * the reachable state space. A forty-node chain (370 places, 1 967 classes)\n * takes 410 s on the fixpoint path and 0.11 s here.\n *\n * The route declines when the graph exceeds the budget, and the SMT pipeline\n * then runs unchanged — it can only add verdicts, never remove them. It is\n * skipped for ν-nets, which have their own exact route (NU-050, Route B), for\n * nets with environment places, whose injection the graph does not model, and\n * for **timed** nets, where its verdict would be the weaker timed claim rather\n * than the untimed one the encoders make (VER-004).\n */\n enumerationMaxClasses(max: number): this {\n this._enumerationMaxClasses = 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 * The name-coloured plan and its encoding, or a null plan when the net is outside\n * the fragment (NU-050) and a null encoding when the property names a place the net\n * does not resolve.\n *\n * {@link verify} and {@link encodeScripts} share this deliberately. They used to\n * invoke `buildColouredPlan` and `encodeColoured` separately, so handing the encoder\n * the wrong one of the two lists changed only one of them — and the script-parity\n * goldens are generated from `encodeScripts`. Unifying the invocation closes that. It\n * does not make the two paths identical: each still computes its own invariant and\n * semiflow lists, so they can still drift through the arguments rather than the call.\n *\n * `invariants` is what the encoder conjoins into every rule body (the null-space\n * basis, unioned with the semiflows when VER-007 is enabled); `semiflows` sets the\n * colour-slot bound k (NU-053). They are not the same list.\n */\n private colouredAttempt(\n flatNet: FlatNet,\n invariants: readonly PInvariant[],\n semiflows: readonly PInvariant[],\n ): { plan: ColouredPlan | null; encoding: SmtEncoding | null } {\n const hasMatch = [...this.net.transitions].some(t => t.matchSpec !== null);\n const nuBounded = this._budgetPlaces.size > 0;\n if (!hasMatch || !nuBounded) return { plan: null, encoding: null };\n const plan = buildColouredPlan(\n this.net, flatNet, this._initialMarking, this._budgetPlaces,\n this._fragmentMode, this._carrierPlaces, semiflows,\n );\n if (plan == null) return { plan: null, encoding: null };\n return {\n plan,\n encoding: encodeColoured(\n plan, flatNet, this._initialMarking, this._property, invariants, this._sinkPlaces,\n this._conditionalSinks,\n ),\n };\n }\n\n /**\n * The SMT-LIB2 scripts {@link verify} would send to z3 for this configuration,\n * without running a solver (VER-013 AC1): the HORN query (flat, or name-coloured\n * when a declared budget puts the net on Route A's exact encoding) and, for the\n * flat encoding, the certificate-check script built around\n * {@link placeholderCertificate}. This is what the cross-language golden tests diff\n * byte for byte. Route B, the structural pre-check and the unresolved-place\n * refusal are bypassed: it is what Route A encodes.\n */\n encodeScripts(): EncodedScripts {\n requireOutputProducingActions(this.net);\n const flatNet = flatten(this.net, this._environmentPlaces, this._environmentMode);\n const matrix = IncidenceMatrix.from(flatNet);\n const { valid: basis, dropped: basisDropped } = validateInvariantsExact(\n matrix, computePInvariants(matrix, flatNet, this._initialMarking), flatNet, this._initialMarking,\n );\n // `'auto'` decides from the same fact here as in verify() — whether the basis\n // lost a law to the H1 guard — so the script this reports is the script that\n // would be sent. Deciding it differently would make the parity goldens pin\n // something the pipeline never emits.\n const autoUnion = this._semiflowInvariants === 'auto'\n && basisDropped.some(d => d.reason.includes('Strengthening.lean H1'));\n // Same gate as verify(): only compute what something will read (see there).\n const scriptsHasMatch = [...this.net.transitions].some(t => t.matchSpec !== null);\n const { valid: semiflows } = this._semiflowInvariants === true || autoUnion || (scriptsHasMatch && this._budgetPlaces.size > 0)\n ? validateInvariantsExact(\n matrix, computePSemiflows(matrix, flatNet, this._initialMarking), flatNet, this._initialMarking,\n )\n : { valid: [] as PInvariant[] };\n let invariants: readonly PInvariant[] = basis;\n if (this._semiflowInvariants === true || autoUnion) invariants = strengthenWithSemiflows(basis, semiflows).invariants;\n invariants = canonicalInvariantOrder(invariants);\n const attempt = this.colouredAttempt(flatNet, invariants, semiflows);\n // The bound query (VER-015) exactly when verify() would send it: flat path, enabled,\n // not refused by VER-006, and a property with a linear demand (else null).\n const bound =\n attempt.plan == null &&\n this._linearBound &&\n !this.ignoresEnvironment\n ? encodeLinearBound(flatNet, this._initialMarking, this._property)\n : null;\n // The state-equation query (VER-018) under verify()'s phase guard; `!hasMatch` implies\n // no coloured plan.\n const stateEquation =\n !scriptsHasMatch &&\n this._stateEquationPhase &&\n !this.ignoresEnvironment\n ? encodeStateEquationQuery(\n flatNet, this._initialMarking, this._property, this._sinkPlaces, this._conditionalSinks, [],\n )\n : null;\n if (attempt.encoding != null) {\n return { horn: attempt.encoding.smt2, certificate: null, coloured: true, bound, stateEquation };\n }\n const flat = encodeNet(flatNet, this._initialMarking, this._property, invariants, {\n sinkPlaces: this._sinkPlaces,\n produceProofs: this._counterexampleReplay,\n conditionalSinks: this._conditionalSinks,\n stateEquation: this._stateEquation,\n });\n const certificate = vcScript(\n placeholderCertificate(flatNet.places.length + flat.counterCount), flatNet, this._initialMarking,\n this._property, this._sinkPlaces, invariants, this._conditionalSinks, this._stateEquation,\n );\n return { horn: flat.smt2, certificate, coloured: false, bound, stateEquation };\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 sinkDesc = describeSinks(this._sinkPlaces, this._conditionalSinks);\n const propDesc = sinkDesc === null\n ? propertyDescription(this._property)\n : `${propertyDescription(this._property)} (${sinkDesc})`;\n report.push(`Property: ${propDesc}`);\n report.push(`Timeout: ${(this._timeoutMs / 1000).toFixed(0)}s\\n`);\n\n // Before ANY route. Each of them answers a property naming an absent place\n // vacuously, and each returns before the flat encoder's own refusal could\n // fire, so the guard has to sit above all of them or it guards nothing.\n const absent = unresolvedPropertyPlaceInNet(this.net, this._property);\n if (absent != null) {\n const reason =\n `property names a place that does not resolve in the net ('${absent}'); ` +\n 'refusing to certify (the encoding would be vacuously proven)';\n report.push('=== RESULT ===\\n');\n report.push(`UNKNOWN: ${reason}`);\n return buildResult(\n { type: 'unknown', reason }, report.join('\\n'), [], [], [], [],\n performance.now() - start,\n {\n places: [...this.net.places].length,\n transitions: [...this.net.transitions].length,\n invariantsFound: 0,\n structuralResult: 'n/a (unresolved property place)',\n },\n null,\n 'unavailable',\n );\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 this._conditionalSinks,\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 // VER-006 binds every route that can return `proven`, not only the SMT\n // encoding. Under `ignore` the name-partition graph treats an environment\n // place as an ordinary empty one, so a bound that holds only because\n // injection never happens is exactly the vacuous proof the guard exists to\n // refuse — and Route B returns here without passing the guard on the solver\n // path below.\n let routeBVerdict = outcome.verdict;\n if (\n routeBVerdict.type === 'proven' && this.ignoresEnvironment\n ) {\n report.push(` Downgraded to UNKNOWN: ${IGNORE_MODE_VACUITY_REASON}`);\n routeBVerdict = { type: 'unknown', reason: IGNORE_MODE_VACUITY_REASON };\n }\n return buildResult(\n routeBVerdict, 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 null,\n 'nu-scg',\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 // Bounded state-space enumeration (VER-017): when the state-class graph closes\n // within the budget it decides the property exactly, with no solver at all —\n // the answer for the narrow, deep state spaces a workflow net produces, where\n // IC3 needs a frame per pipeline stage. Skipped for ν-nets (Route B above is\n // their exact route) and for nets with environment places, whose injection the\n // graph does not model; on truncation the SMT pipeline below runs unchanged.\n if (\n !hasMatch &&\n this._environmentPlaces.size === 0 &&\n this._enumerationMaxClasses > 0 &&\n isUntimed(this.net)\n ) {\n const enumerated = verifyViaStateClassGraph(\n this.net, this._initialMarking, this._property, this._sinkPlaces,\n this._enumerationMaxClasses, this._conditionalSinks,\n );\n if (enumerated.kind === 'decided') {\n report.push('=== Bounded state-space enumeration (VER-017) ===');\n report.push(` State classes: ${enumerated.classCount}`);\n report.push(' P-invariants: not computed (no encoding is built on this route)');\n report.push(NOTE_ENUMERATED);\n if (enumerated.transitions.length > 0) {\n report.push(` Counterexample trace: ${enumerated.trace.length} states, ${enumerated.transitions.length} transitions`);\n }\n return buildResult(\n enumerated.verdict, report.join('\\n'), [], [], enumerated.trace, enumerated.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 (state-space enumeration)',\n },\n // The graph path IS a firing sequence, so a violation is ordered and\n // confirmed by construction; there is nothing left to replay.\n enumerated.verdict.type === 'violated' ? true : null,\n 'enumeration',\n );\n }\n report.push(\n `Bounded state-space enumeration truncated at ${this._enumerationMaxClasses} classes ` +\n '(VER-017); verifying via the SMT pipeline.',\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 // Skipped too for any net Commoner's theorem does not govern: see\n // {@link commonerApplies}. That guard is what makes this a proof rather than a\n // guess, and it was missing.\n if (\n this._property.type === 'deadlock-free' &&\n !hasMatch &&\n commonerApplies(flatNet) &&\n this._sinkPlaces.size === 0 &&\n this._conditionalSinks.length === 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 report.push(' Certificate check: not applicable (structural proof)');\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 null,\n 'structural',\n );\n }\n\n // Phase 3: P-invariants\n report.push('Phase 3: Computing P-invariants...');\n const matrix = IncidenceMatrix.from(flatNet);\n // Exact re-check (BigInt) before invariants reach the encoder: the Gaussian\n // elimination runs in f64 `number`, and a numerically wrong invariant conjoined\n // into the CHC transition bodies removes reachable successors — i.e. it could\n // certify a false PROVEN. Drop anything the exact re-verification rejects.\n const { valid: basisInvariants, dropped: droppedInvariants } = validateInvariantsExact(\n matrix,\n computePInvariants(matrix, flatNet, this._initialMarking),\n flatNet,\n this._initialMarking,\n );\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) — validated the same way (incl. the H1\n // linearity guard) before they can set that bound, mirroring the Rust verifier.\n //\n // Computed ONLY when something will read them: the [VER-007] union, or the\n // coloured plan's slot bound. The enumeration is worst-case exponential — the\n // minimal semiflows of `k` independent diamonds in series number 2^k, measured\n // at 2 048 for eleven and 8 189 (the backstop) beyond thirteen — so running it\n // for a caller who asked for neither is a large cost, and on a wide net an\n // uncatchable one: the heap it exhausts aborts the process rather than\n // returning a verdict. Skipping it is invisible to every other phase.\n // `'auto'` (VER-007): compute them exactly when the basis LOST a law to the H1\n // guard, which is the condition the option exists for — a consume-all / reset\n // arc on a busy place drops every basis row whose support touches it, and the\n // semiflows are the minimal laws that avoid it. On a net with a complete basis\n // they add nothing and cost the enumeration, so `'auto'` skips them there. The\n // drops are already known at this point, so this decides in ONE pass rather\n // than running the pipeline twice to read its own report.\n const basisLostALaw = droppedInvariants.some(d => d.reason.includes('Strengthening.lean H1'));\n const semiflowsWanted =\n this._semiflowInvariants === true ||\n (this._semiflowInvariants === 'auto' && basisLostALaw) ||\n (hasMatch && nuBounded);\n const { valid: semiflows, dropped: droppedSemiflows } = semiflowsWanted\n ? validateInvariantsExact(\n matrix,\n computePSemiflows(matrix, flatNet, this._initialMarking),\n flatNet,\n this._initialMarking,\n )\n : { valid: [] as PInvariant[], dropped: [] as { invariant: PInvariant; reason: string }[] };\n report.push(` Found: ${basisInvariants.length} P-invariant(s)`);\n // VER-007: the minimal conservation laws, as extra invariants for the encoders.\n // The report line is emitted only when enabled so default reports stay\n // byte-identical (AC2/AC3).\n if (this._semiflowInvariants === 'auto') {\n report.push(basisLostALaw\n ? ' Semiflow union: ON (auto — the basis lost a law to the H1 guard)'\n : ' Semiflow union: off (auto — the basis is complete, so the semiflows would add no ' +\n 'constraint the encoding does not already have; they may still differ in FORM)');\n }\n // The UNION is a separate decision from computing them: a coloured plan needs\n // the slot bound without wanting the laws conjoined.\n const unionWanted =\n this._semiflowInvariants === true || (this._semiflowInvariants === 'auto' && basisLostALaw);\n let invariants: readonly PInvariant[] = basisInvariants;\n if (unionWanted) {\n const { invariants: strengthened, added } = strengthenWithSemiflows(basisInvariants, semiflows);\n invariants = strengthened;\n report.push(` Semiflows encoded as invariants: ${added}`);\n }\n // VER-013: canonical invariant order (support, weights, constant), so the\n // strengthened rule bodies and the certificate candidate read the same in every\n // implementation whatever order the elimination produced them in.\n invariants = canonicalInvariantOrder(invariants);\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 // Canonical cross-language wording: \" Dropped <kind>: <desc> - <reason>\",\n // ASCII hyphen-minus as the clause separator so the four implementations'\n // reports diff byte-for-byte. The structured {invariant, reason} pairs stay\n // on the result for callers that want more than the rendered line.\n for (const { invariant, reason } of droppedInvariants) {\n report.push(` Dropped invariant: ${formatInvariant(invariant, flatNet)} - ${reason}`);\n }\n if (droppedInvariants.length > 0) {\n report.push(` Dropped: ${droppedInvariants.length} invariant(s) failed the exact re-check`);\n }\n for (const { invariant, reason } of droppedSemiflows) {\n report.push(` Dropped semiflow: ${formatInvariant(invariant, flatNet)} - ${reason}`);\n }\n if (droppedSemiflows.length > 0) {\n report.push(` Dropped: ${droppedSemiflows.length} semiflow(s) failed the exact re-check`);\n }\n report.push('');\n\n // A quiescence property on a net that can never come to rest is vacuously\n // true: the verdict would be `proven` whatever the net does. Say so, or the\n // caller reads an empty claim as a guarantee about their workflow.\n if (!isReachabilitySafety(this._property) && quiescenceUnreachable(flatNet, resolveEnvInjection(flatNet))) {\n report.push(\n ' NOTE: no marking of this net can be quiescent — a transition is enabled in every ' +\n 'marking (an environment-gated one under modelled injection, VER-006). Every quiescence ' +\n 'property is therefore vacuously true here, and a `proven` says nothing about the net.',\n );\n }\n\n // Phase 4: SMT encode + query via Spacer\n report.push('Phase 4: IC3/PDR verification via Z3 Spacer...');\n\n // VER-013: one z3 process per query. Resolve the executable before any encoding\n // work so a missing or too-old solver is reported as such.\n const stats: SmtStatistics = {\n places: flatNet.places.length,\n transitions: flatNet.transitions.length,\n invariantsFound: invariants.length,\n structuralResult: structResultStr,\n };\n let solver: Z3Solver;\n try {\n solver = resolveZ3();\n } catch (e: any) {\n rethrowIfProgrammingError(e);\n const reason = e instanceof Z3Unavailable ? e.message : String(e?.message ?? e);\n report.push(` Solver: z3 unavailable (${reason})`);\n report.push(` Status: UNKNOWN (${reason})\\n`);\n report.push('=== RESULT ===\\n');\n report.push(`UNKNOWN: Could not determine ${propDesc}`);\n report.push(` Reason: ${reason}`);\n return buildResult({ type: 'unknown', reason }, report.join('\\n'), invariants, [], [], [], performance.now() - start, stats, null, 'unavailable');\n }\n report.push(` Solver: z3 ${formatZ3Version(solver.version)}`);\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 //\n // After the solver resolves, not before: the helper encodes as well as plans, and\n // encoding for a solver that turns out to be missing is work thrown away. Java and\n // Rust order it the same way.\n const colouredAttempt = this.colouredAttempt(flatNet, invariants, semiflows);\n const colouredPlan: ColouredPlan | null = colouredAttempt.plan;\n\n // Linear state-equation bound (VER-015): a reachability-safety property whose\n // violating markings exceed some `y·M <= y·M0` with `y >= 0`, `y·C <= 0` is\n // proven structurally, without the fixpoint search — the ordering arguments\n // IC3 does not invent on pipeline-shaped nets. Flat path only: a net on the exact\n // name-coloured encoding keeps that route's verdict and notes. Skipped under\n // `ignore` with environment places, where VER-006 refuses every `proven`.\n if (\n this._linearBound &&\n colouredPlan == null &&\n isReachabilitySafety(this._property) &&\n !this.ignoresEnvironment\n ) {\n const proof = await this.linearBoundProof(flatNet, solver, report);\n if (proof != null) {\n report.push(' Certificate check: not applicable (structural proof)');\n report.push('');\n report.push('=== RESULT ===\\n');\n report.push(`PROVEN (structural): ${propDesc}`);\n report.push(' Linear state-equation bound: y >= 0 with y.C <= 0 gives y.M <= y.M0 on every');\n report.push(' reachable marking, and the violating markings exceed it (VER-015).');\n report.push(` ${proof}`);\n return this.applyNuGuard(buildResult(\n { type: 'proven', method: 'structural', inductiveInvariant: null },\n report.join('\\n'), invariants, [], [], [],\n performance.now() - start,\n stats,\n null,\n 'structural',\n ), hasMatch, nuBounded, false);\n }\n }\n\n // State-equation phase (VER-018), then the firing bound (VER-019): flat path only. Not\n // on a ν-net (name-blind here, exact routes elsewhere), and not under `ignore` with\n // environment places (VER-006 refuses every `proven`). Neither returns through\n // `applyNuGuard`, which is the identity when `!hasMatch`.\n if (!hasMatch && !this.ignoresEnvironment) {\n const phase: PhaseContext = { flatNet, solver, report, propDesc, invariants, stats, start };\n if (this._stateEquationPhase) {\n const decided = await this.stateEquationDecision(phase);\n if (decided != null) return decided;\n }\n if (this._firingBound) {\n const decided = await this.firingBoundDecision(phase);\n if (decided != null) return decided;\n }\n }\n\n let encoding: SmtEncoding;\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 const coloured = colouredAttempt.encoding;\n if (coloured == 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({ type: 'unknown', reason }, report.join('\\n'), invariants, [], [], [], performance.now() - start, stats, null, 'unavailable');\n }\n encoding = coloured;\n } else {\n // A property naming a place outside the net would encode to a vacuous\n // violation predicate (`false` proves anything). Refuse, as the coloured path\n // does, so a mis-named place never silently certifies.\n const unresolved = unresolvedPropertyPlace(flatNet, this._property);\n if (unresolved != null) {\n const reason =\n `property names a place that does not resolve in the net ('${unresolved}'); ` +\n 'refusing to certify (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({ type: 'unknown', reason }, report.join('\\n'), invariants, [], [], [], performance.now() - start, stats, null, 'unavailable');\n }\n // C3: request the refutation proof the replay decoder reads.\n encoding = encodeNet(flatNet, this._initialMarking, this._property, invariants, {\n sinkPlaces: this._sinkPlaces,\n produceProofs: this._counterexampleReplay,\n conditionalSinks: this._conditionalSinks,\n stateEquation: this._stateEquation,\n });\n if (this._stateEquation) {\n report.push(` State equation: encoded over ${encoding.counterCount} firing counters (VER-016)`);\n }\n }\n if (this._stateEquation && colouredPlan != null) {\n report.push(' State equation: not applied (name-coloured encoding)');\n }\n const queryResult = await runZ3Spacer(\n solver, this._timeoutMs, encoding.smt2, colouredPlan != null ? 'horn-coloured' : 'horn',\n );\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.ignoresEnvironment) {\n const reason = IGNORE_MODE_VACUITY_REASON;\n report.push(` Status: UNSAT, but vacuous under ignore mode\\n`);\n report.push('=== RESULT ===\\n');\n report.push(`UNKNOWN: ${reason}`);\n return buildResult({ type: 'unknown', reason }, report.join('\\n'), invariants, [], [], [], performance.now() - start, stats);\n }\n\n report.push(' Status: UNSAT (property holds)');\n\n // Independent certificate check (flat count encoding only): re-validate\n // the IC3 certificate in a second z3 run against the UNSTRENGTHENED step\n // relation, so neither a Spacer/encoder defect nor a wrong-but-\n // validated-looking invariant strengthening can certify a false PROVEN.\n // The coloured ν-encoding has its own state shape and is out of scope;\n // structural proofs return before this point.\n if (colouredPlan != null) {\n report.push(' Certificate check: not applicable (name-coloured encoding)');\n } else if (!this._certificateCheck) {\n report.push(' Certificate check: not applicable (disabled)');\n } else {\n const certificate = await checkCertificate(\n queryResult.invariantFormula, flatNet, this._initialMarking,\n this._property, invariants, this._sinkPlaces, solver, this._timeoutMs,\n this._conditionalSinks, this._stateEquation,\n );\n const reason = certificateDowngradeReason(certificate);\n if (reason != null) {\n report.push(' Certificate check: FAILED');\n if (certificate.type !== 'passed' && certificate.invariant != null) {\n report.push(' Uncertified invariant:');\n for (const line of certificate.invariant.split('\\n')) report.push(` ${line}`);\n }\n report.push('');\n report.push('=== RESULT ===\\n');\n report.push(`UNKNOWN: ${reason}`);\n return buildResult({ type: 'unknown', reason }, report.join('\\n'), invariants, [], [], [], performance.now() - start, stats);\n }\n report.push(' Certificate check: PASSED (init, consecution, safety)');\n }\n report.push('');\n\n // The inductive invariant is the (define-fun …) block of the model,\n // verbatim (the certificate the check above re-validated).\n const formula = queryResult.invariantFormula;\n const discoveredInvariants: string[] = formula != null ? [formula] : [];\n\n // Phase 5: Inductive invariant\n if (formula != null) {\n report.push('Phase 5: Inductive invariant (discovered by IC3)');\n report.push(' Spacer synthesized:');\n for (const line of formula.split('\\n')) report.push(` ${line}`);\n report.push(' This formula is INDUCTIVE: preserved by all transitions.');\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.');\n report.push(' An untimed proof is STRONGER than a timed one (timing only restricts behavior).');\n\n return this.applyNuGuard(buildResult(\n { type: 'proven', method: 'IC3/PDR', inductiveInvariant: formula },\n report.join('\\n'), invariants, discoveredInvariants, [], [],\n performance.now() - start,\n stats,\n ), hasMatch, nuBounded, colouredPlan != null);\n }\n\n case 'violated': {\n report.push(' Status: SAT (counterexample found)\\n');\n\n const decoded = decode(queryResult.answer, flatNet, encoding.counterCount);\n if (decoded.note != null) report.push(` Counterexample decoding: ${decoded.note}`);\n\n // C3/C4: abstract counterexample replay (flat count encoding only — the\n // coloured ν-encoding's state shape is outside the replayer's scope). The\n // decoder collects the ground Reachable states of the refutation proof as\n // an order-free set; the replay recovers a genuine firing order.\n let confirmed: boolean | null = null;\n let trace: readonly MarkingState[] = [...decoded.states];\n let transitions: readonly string[] = [];\n let replayed = false;\n if (colouredPlan == null && this._counterexampleReplay) {\n const assessment = assessCounterexample(\n flatNet, this._initialMarking, decoded.states, this._property, this._sinkPlaces,\n this._conditionalSinks,\n );\n if (assessment.kind === 'confirmed') {\n confirmed = true;\n replayed = true;\n trace = assessment.trace;\n transitions = assessment.firings;\n report.push(' Counterexample replay: CONFIRMED (abstract chain M0 -> bad re-executed)');\n } else if (assessment.kind === 'unconfirmed') {\n // The replay could not run to completion (nothing decoded, or the\n // search hit a budget). Spacer's answer stands on its own — only a\n // completed search that found no chain may withdraw it.\n confirmed = false;\n report.push(` Counterexample replay: UNCONFIRMED (${assessment.note})`);\n report.push(\" The verdict rests on Spacer's answer.\");\n } else {\n // The search completed and no abstract chain reaches a violating\n // marking: a spurious counterexample of the untimed+value-blind\n // over-approximation, or a decoder mismatch. Never keep an\n // unreplayable VIOLATED — downgrade, with raw + decoded evidence.\n report.push(' Counterexample replay: FAILED');\n report.push(` Decoded states (order-free set, ${decoded.states.size}):`);\n for (const m of decoded.states) report.push(` ${m}`);\n report.push(` Raw Z3 answer: ${truncate(queryResult.answer, 2000)}`);\n report.push('');\n report.push('=== RESULT ===\\n');\n report.push(`UNKNOWN: ${assessment.reason}`);\n // The replay APPLIED and refuted the trace, so `false` — not `null`,\n // which is reserved for \"the replay did not apply\".\n return buildResult(\n { type: 'unknown', reason: assessment.reason },\n report.join('\\n'), invariants, [], [], [],\n performance.now() - start,\n stats,\n false,\n );\n }\n }\n\n report.push('=== RESULT ===\\n');\n report.push(`VIOLATED: ${propDesc}`);\n if (trace.length > 0) {\n report.push(` Counterexample trace (${replayed ? 'replay order, ' : 'proof order, '}${trace.length} states):`);\n for (let i = 0; i < trace.length; i++) report.push(` ${i}: ${trace[i]}`);\n }\n if (transitions.length > 0) report.push(` Firing sequence: ${transitions.join(' -> ')}`);\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\n return this.applyNuGuard(buildResult(\n { type: 'violated' },\n report.join('\\n'), invariants, [], trace as MarkingState[], transitions as string[],\n performance.now() - start,\n stats,\n confirmed,\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 return buildResult(\n { type: 'unknown', reason: queryResult.reason },\n report.join('\\n'), invariants, [], [], [],\n performance.now() - start,\n stats,\n );\n }\n }\n }\n\n /**\n * Runs the linear state-equation bound query (VER-015) and re-checks its answer in\n * exact integer arithmetic. Returns the bound as the report prints it when one\n * separates the violation, `null` otherwise (no bound, solver inconclusive, or a\n * model that failed the re-check — each named in the report). Never the last word:\n * `null` hands over to the fixpoint query.\n */\n private async linearBoundProof(flatNet: FlatNet, solver: Z3Solver, report: string[]): Promise<string | null> {\n const script = encodeLinearBound(flatNet, this._initialMarking, this._property);\n if (script == null) return null;\n let reply;\n try {\n reply = await runZ3Text(solver, script, 'bound', this._timeoutMs, []);\n } catch (e: any) {\n rethrowIfProgrammingError(e);\n report.push(` Linear state-equation bound: inconclusive (${String(e?.message ?? e)})`);\n return null;\n }\n const stdout = reply.stdout.trim();\n switch (classifyFirstLine(stdout)) {\n case 'sat': {\n const y = decodeLinearBound(stdout, flatNet.places.length);\n const bound = y == null ? null : checkLinearBoundExact(flatNet, this._initialMarking, this._property, y);\n if (bound == null) {\n report.push(' Linear state-equation bound: inconclusive (solver model failed the exact re-check)');\n return null;\n }\n const rendered = `${formatLinearBound(flatNet, bound)}; violation needs ${formatLinearDemand(flatNet, this._property, bound)}`;\n report.push(` Linear state-equation bound: ${rendered}`);\n report.push(' Status: bound excludes every violating marking (re-checked in exact integer arithmetic)');\n return rendered;\n }\n case 'unsat':\n report.push(' Linear state-equation bound: none separates the violation');\n return null;\n case 'unknown':\n report.push(' Linear state-equation bound: inconclusive (Z3 answered unknown)');\n return null;\n default:\n report.push(` Linear state-equation bound: inconclusive (${failureReason(reply, timeoutBudget(this._timeoutMs))})`);\n return null;\n }\n }\n\n /**\n * Whether environment places are registered but not modelled ([VER-006] `ignore`). A\n * proof over a frozen environment is vacuous, so every route that can return `proven`\n * refuses it. See {@link IGNORE_MODE_VACUITY_REASON}.\n */\n private get ignoresEnvironment(): boolean {\n return this._environmentPlaces.size > 0 && this._environmentMode.type === 'ignore';\n }\n\n /**\n * Runs the state-equation phase (VER-018). Returns the final result when it decided\n * the property — a `proven` only once the certificate check passed — and `null` when\n * it stepped aside, with the reason in the report.\n */\n private async stateEquationDecision(phase: PhaseContext): Promise<SmtVerificationResult | null> {\n const { flatNet, report } = phase;\n report.push(' State-equation phase (VER-018):');\n const outcome = await runStateEquationPhase(\n flatNet, this._initialMarking, this._property, this._sinkPlaces, this._conditionalSinks,\n phaseSolver(phase.solver),\n { budgetMs: this._timeoutMs },\n );\n for (const r of outcome.refinements) report.push(` Refinement (${r.origin}): ${formatInequality(flatNet, r)}`);\n report.push(` Queries: ${outcome.queries}`);\n switch (outcome.kind) {\n case 'inconclusive':\n report.push(` Status: inconclusive (${outcome.reason})`);\n if (outcome.candidate != null) report.push(` Unsettled candidate: ${describeCandidate(flatNet, outcome.candidate)}`);\n return null;\n case 'violated':\n report.push(\" Status: a run within the candidate's firing counts reaches a violation\");\n return witnessResult(phase, outcome.states, outcome.steps);\n case 'proven': {\n report.push(' Status: no marking the equation admits violates the property');\n const certificate = refinementCertificate(flatNet.places.length, flatNet.transitions.length, outcome.refinements);\n if (this._certificateCheck) {\n // No P-invariants, and the step relation that carries the counters: the\n // certificate ranges over places + transitions and must stand on its own.\n const checked = await checkCertificate(\n certificate, flatNet, this._initialMarking, this._property, [], this._sinkPlaces, phase.solver,\n this._timeoutMs, this._conditionalSinks, true,\n );\n const reason = certificateDowngradeReason(checked);\n if (reason != null) {\n // Not a verdict: the fixpoint query still runs.\n report.push(` Certificate check: FAILED (${reason})`);\n return null;\n }\n // Two spaces, as on the fixpoint path: pinned by VER-018 AC1.\n report.push(' Certificate check: PASSED (init, consecution, safety)');\n } else {\n report.push(' Certificate check: not applicable (disabled)');\n }\n report.push('');\n report.push('=== RESULT ===\\n');\n report.push(`PROVEN (state equation): ${phase.propDesc}`);\n report.push(\n ` Every reachable marking satisfies the marking equation over ${flatNet.transitions.length} firing ` +\n `counters${outcome.refinements.length > 0 ? ' and the refinements above' : ''}, and none of those ` +\n 'markings violates the property (VER-018).',\n );\n report.push(' NOTE: Verification ignores timing constraints.');\n const readable = outcome.refinements.map((r) => formatInequality(flatNet, r));\n return buildResult(\n { type: 'proven', method: 'state-equation', inductiveInvariant: certificate },\n report.join('\\n'), phase.invariants, readable, [], [], performance.now() - phase.start, phase.stats,\n );\n }\n }\n }\n\n /**\n * Runs the firing-bound phase (VER-019). Returns the final result when it decided the\n * property and `null` when it stepped aside, with the reason in the report.\n */\n private async firingBoundDecision(phase: PhaseContext): Promise<SmtVerificationResult | null> {\n const { flatNet, report } = phase;\n report.push(' Firing bound (VER-019):');\n // Half the timeout: a short counterexample is found in seconds, a proof to a deep bound\n // can outlast any budget, and the fixpoint query after this still gets its full one.\n const outcome = await runFiringBoundPhase(\n flatNet, this._initialMarking, this._property, this._sinkPlaces, this._conditionalSinks,\n phaseSolver(phase.solver), { budgetMs: Math.max(1, Math.floor(this._timeoutMs / 2)) },\n );\n const formatDepths = (steps: readonly DepthStep[]): string =>\n steps.map((d) => `${d.depth} ${d.answer === 'sat' ? 'violation' : 'none'}`).join(', ');\n const pushBound = (b: FiringBound): void => {\n report.push(` Bound: ${b.bound} firings (${formatRanking(flatNet, b)} drops on every firing)`);\n };\n switch (outcome.kind) {\n case 'unbounded':\n report.push(\n outcome.repeatable == null\n ? ' Status: no firing bound (no weights decrease on every firing); not attempted'\n : ' Status: no firing bound — the marking equation lets ' +\n `${outcome.repeatable.map((t) => flatNet.transitions[t]!.name).join(', ')} repeat; not attempted`,\n );\n return null;\n case 'inconclusive':\n if (outcome.bound != null) pushBound(outcome.bound);\n if (outcome.depths.length > 0) report.push(` Depths: ${formatDepths(outcome.depths)}`);\n report.push(` Status: inconclusive (${outcome.reason})`);\n return null;\n case 'violated':\n pushBound(outcome.bound);\n report.push(` Depths: ${formatDepths(outcome.depths)}`);\n report.push(' Status: a bounded run reaches a violation (replayed)');\n return witnessResult(phase, outcome.states, outcome.steps);\n case 'proven':\n pushBound(outcome.bound);\n report.push(` Depths: ${formatDepths(outcome.depths)}`);\n report.push(' Status: no run of at most the bound reaches a violation, and no run is longer');\n report.push(' Certificate check: not applicable (bounded model check to the firing bound)');\n report.push('');\n report.push('=== RESULT ===\\n');\n report.push(`PROVEN (bounded model check): ${phase.propDesc}`);\n report.push(\n ` No run has more than ${outcome.bound.bound} firings, and none of at most that many reaches a ` +\n 'violation (VER-019).',\n );\n report.push(' NOTE: Verification ignores timing constraints.');\n return buildResult(\n { type: 'proven', method: 'bounded-model-check', inductiveInvariant: null },\n report.join('\\n'), phase.invariants, [], [], [], performance.now() - phase.start, phase.stats,\n );\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/** What the pre-fixpoint phases of VER-018/019 read from `verify()`. */\ninterface PhaseContext {\n readonly flatNet: FlatNet;\n readonly solver: Z3Solver;\n /** The report so far; each phase appends its section. */\n readonly report: string[];\n readonly propDesc: string;\n readonly invariants: readonly PInvariant[];\n readonly stats: SmtStatistics;\n readonly start: number;\n}\n\n/**\n * The solver as the phases of VER-018/019 ask it: resolves with stdout. Rejects a reply\n * with no verdict line, and one where z3 reported an error other than the `model is not\n * available` that `(get-model)` after `unsat` draws: an errored assert silently drops out\n * of the query.\n */\nfunction phaseSolver(solver: Z3Solver): (script: string, phase: string, timeoutMs: number) => Promise<string> {\n return async (script, phase, timeoutMs) => {\n const reply = await runZ3Text(solver, script, phase, timeoutMs, []);\n const unexpected = [reply.stdout, reply.stderr]\n .flatMap((text) => text.split('\\n'))\n .map((line) => errorLine(line))\n .find((line) => line != null && !line.includes('model is not available'));\n if (unexpected != null) throw new Error(`z3 reported an error: ${unexpected}`);\n if (classifyFirstLine(reply.stdout) == null) throw new Error(failureReason(reply, timeoutBudget(timeoutMs)));\n return reply.stdout;\n };\n}\n\n/** The confirmed `violated` result for a run a VER-018/019 phase found and replayed. */\nfunction witnessResult(\n phase: PhaseContext,\n states: readonly AbstractState[],\n steps: readonly string[],\n): SmtVerificationResult {\n const { report } = phase;\n const trace = states.map((s) => toMarkingState(s, phase.flatNet));\n report.push('');\n report.push('=== RESULT ===\\n');\n report.push(`VIOLATED: ${phase.propDesc}`);\n report.push(` Counterexample trace (replay order, ${trace.length} states):`);\n for (let i = 0; i < trace.length; i++) report.push(` ${i}: ${trace[i]}`);\n if (steps.length > 0) report.push(` Firing sequence: ${steps.join(' -> ')}`);\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 return buildResult(\n { type: 'violated' }, report.join('\\n'), phase.invariants, [], trace, [...steps],\n performance.now() - phase.start, phase.stats, true,\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 * terminates-at-sink, joined-or-dead-lettered) are not: their violation involves\n * the absence of enabled transitions, which the name-blind over-approximation\n * 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 'terminates-at-sink':\n case 'joined-or-dead-lettered':\n case 'quiescent-count':\n return false;\n }\n}\n\n/**\n * Assessment of a decoded counterexample by abstract replay (C4). Pure and free\n * of Z3 types, so the verdict mapping is unit-testable without booting the WASM\n * solver — the mirror of {@link certificateDowngradeReason}.\n */\nexport type ReplayAssessment =\n /** The decoded states chain into an abstract run reaching the violation. */\n | {\n readonly kind: 'confirmed';\n readonly trace: readonly MarkingState[];\n readonly firings: readonly string[];\n }\n /** The replay could not complete; the VIOLATED verdict stands, unconfirmed. */\n | { readonly kind: 'unconfirmed'; readonly note: string }\n /** No firing chain exists at all; the verdict must not be trusted. */\n | { readonly kind: 'downgraded'; readonly reason: string };\n\n/**\n * Maps a decoded counterexample to its replay assessment. Only a completed\n * search that found no chain (`no-chain`) downgrades: nothing decoded, a\n * truncated search (node/segment budget, `M₀` absent from the decoded set) and\n * a replayer crash all leave the verdict `violated` but unconfirmed, because\n * none of them is evidence that the counterexample is spurious.\n */\nexport function assessCounterexample(\n flatNet: FlatNet,\n initialMarking: MarkingState,\n decodedStates: ReadonlySet<MarkingState>,\n property: SmtProperty,\n sinkPlaces: ReadonlySet<Place<any>>,\n conditionalSinks: readonly ConditionalSinks[] = [],\n): ReplayAssessment {\n if (decodedStates.size === 0) {\n return {\n kind: 'unconfirmed',\n note: 'no counterexample states could be decoded from the Spacer answer, ' +\n 'so the abstract replay could not run',\n };\n }\n\n let outcome: ReplayOutcome;\n try {\n outcome = replayCounterexample(\n flatNet,\n vectorize(initialMarking, flatNet),\n [...decodedStates].map(m => vectorize(m, flatNet)),\n property,\n sinkPlaces,\n {},\n conditionalSinks,\n );\n } catch (e: any) {\n // A replay that ran out of room degrades like a truncated search — it never\n // withdraws a verdict on its own. A replayer *defect* is not that: it would be\n // indistinguishable from an exhausted search and so invisible forever, which\n // is why a TypeError propagates and a RangeError (a deep net overflowing the\n // stack) stays the capacity verdict it really is.\n rethrowIfProgrammingError(e);\n outcome = { kind: 'exhausted', reason: `replay threw: ${e?.message ?? e}`, nodesExplored: 0 };\n }\n\n switch (outcome.kind) {\n case 'confirmed':\n return {\n kind: 'confirmed',\n trace: outcome.states.map(s => toMarkingState(s, flatNet)),\n firings: outcome.steps.map(stepName),\n };\n case 'exhausted':\n return { kind: 'unconfirmed', note: `abstract replay did not complete: ${outcome.reason}` };\n case 'no-chain':\n return {\n kind: 'downgraded',\n reason: 'counterexample replay found no firing chain to the violation under ' +\n 'the abstract semantics, so VIOLATED is withheld',\n };\n }\n}\n\n/**\n * Maps a certificate-check outcome to the UNKNOWN downgrade reason, or null\n * when the PROVEN verdict stands. Pure (no Z3 involvement) so the verdict\n * plumbing is unit-testable without booting the WASM solver.\n */\nexport function certificateDowngradeReason(outcome: CertificateCheckOutcome): string | null {\n switch (outcome.type) {\n case 'passed':\n return null;\n case 'failed':\n return `certificate check failed: ${outcome.vc} was not UNSAT - ${outcome.detail}; ` +\n 'the IC3 certificate could not be independently re-validated against the ' +\n 'unstrengthened step relation, so PROVEN is withheld';\n case 'unavailable':\n return `certificate check could not run: ${outcome.reason}; ` +\n 'PROVEN is withheld without an independently validated certificate';\n }\n}\n\n/** The scripts {@link SmtVerifier.encodeScripts} reports. */\nexport interface EncodedScripts {\n /** The HORN query, flat or name-coloured. */\n readonly horn: string;\n /** The certificate-check script around {@link placeholderCertificate}; `null` for the name-coloured encoding. */\n readonly certificate: string | null;\n /** Whether `horn` is the name-coloured encoding. */\n readonly coloured: boolean;\n /**\n * The linear state-equation bound query (VER-015), or `null` for a property with\n * no linear demand (the quiescence properties).\n */\n readonly bound: string | null;\n /**\n * The first query of the state-equation phase (VER-018), before any refinement, or\n * `null` where the phase does not run (the name-coloured encoding, a ν-net, `ignore`\n * with environment places, or the phase disabled).\n */\n readonly stateEquation: string | null;\n}\n\n/**\n * `(define-fun Reachable ((x!0 Int) …) Bool true)`: the certificate stand-in the\n * golden certificate scripts are built around (a real certificate is solver output\n * and never part of a golden).\n */\nexport function placeholderCertificate(placeCount: number): string {\n const params: string[] = [];\n for (let i = 0; i < placeCount; i++) params.push(`(x!${i} Int)`);\n return `(define-fun Reachable (${params.join(' ')}) Bool\\n true)`;\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 counterexampleConfirmed: null,\n };\n}\n\n/** Truncates long raw solver output for the report. */\nfunction truncate(s: string, max: number): string {\n return s.length <= max ? s : `${s.slice(0, max)}… (${s.length - max} chars truncated)`;\n}\n\n/**\n * The name of the first place the property names that the NET does not declare,\n * or `null`. The flat-net twin below answers the same question after flattening;\n * this one can be asked before any route runs, which is where it has to be.\n *\n * A property naming a place the net does not have is not a question about the\n * net: every route answers it vacuously and each in its own way — the flat\n * encoder would emit a `false` violation term that proves anything, the linear\n * bound would drop the conjunct and separate a strictly stronger demand, the\n * enumeration route would find no class marking a place that cannot be marked.\n * All three then report `proven`. Refusing once, before any of them, is the only\n * way the refusal cannot be routed around.\n */\nfunction unresolvedPropertyPlaceInNet(net: PetriNet, property: SmtProperty): string | null {\n const declared = new Set<string>();\n for (const p of net.places) declared.add(p.name);\n for (const place of propertyPlaces(property)) {\n if (!declared.has(place.name)) return place.name;\n }\n return null;\n}\n\n/**\n * Whether Commoner's theorem governs this net, so a siphon/trap answer may be\n * turned into a `proven`.\n *\n * The theorem — every siphon contains an initially marked trap implies\n * deadlock-freedom — is about an **ordinary** net, one where the only reason a\n * transition is disabled is an input place with too few tokens. The siphon and\n * trap fixpoints are computed from the pre/post vectors alone and never read\n * `readPlaces`, `inhibitorPlaces`, `resetPlaces` or `consumeAll`, so on a net\n * carrying any of those the analysis answers a question about a DIFFERENT,\n * strictly more permissive net: dropping a read or inhibitor arc can only add\n * firings, which is the wrong direction for a deadlock proof. An arc weight above\n * one is the same problem — a place holding one token satisfies `m >= 1` but not\n * `exactly(2)`.\n *\n * Each of these was demonstrated to produce a `proven` for a net both executors\n * run to a dead marking: `t1: one(a) read(g) -> g` with `t2: one(g) -> a` from\n * `{a:1}`; `t: exactly(2, a) -> a` from `{a:1}`; `t: one(a) inhibitor(b) -> a`\n * from `{a:1, b:1}`. Refusing the shortcut costs a fixpoint query and sends those\n * nets to a route that models what disables them.\n */\nfunction commonerApplies(flatNet: FlatNet): boolean {\n for (const ft of flatNet.transitions) {\n if (ft.readPlaces.length > 0 || ft.inhibitorPlaces.length > 0 || ft.resetPlaces.length > 0) return false;\n if (ft.consumeAll.some(Boolean)) return false;\n if (ft.preVector.some(w => w > 1)) return false;\n }\n return true;\n}\n\n/** The places a property names, whichever kind it is. */\nfunction propertyPlaces(property: SmtProperty): Place<any>[] {\n switch (property.type) {\n case 'deadlock-free': return [];\n case 'terminates-at-sink': return [];\n case 'mutual-exclusion': return [property.p1, property.p2];\n case 'place-bound': return [property.place];\n case 'branch-place-bound': return [property.place];\n case 'unreachable': return [...property.places];\n case 'joined-or-dead-lettered': return [property.pending];\n case 'quiescent-count': return [...property.places, ...property.waivedBy];\n }\n}\n\n/** The name of the first place the property names that is not in the flat net, or `null`. */\nfunction unresolvedPropertyPlace(flatNet: FlatNet, property: SmtProperty): string | null {\n for (const place of propertyPlaces(property)) {\n if (!flatNet.placeIndex.has(place.name)) return place.name;\n }\n return null;\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 // Empty support renders as `0 = c`, matching Java and Rust — the line is byte-diffed.\n return `${parts.length === 0 ? '0' : 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 counterexampleConfirmed: boolean | null = null,\n route: VerificationRoute = 'smt',\n): SmtVerificationResult {\n return { verdict, route, report, invariants, discoveredInvariants, counterexampleTrace: trace, counterexampleTransitions: transitions, counterexampleConfirmed, 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 * Which route decided a verdict ([VER-003]).\n *\n * The routes do equivalent work by different means, and a consumer reading the\n * result's fields rather than its report needs to know which one answered:\n * `enumeration` and `nu-scg` decide by exploring a finite graph and compute no\n * P-invariants at all.\n *\n * The rule for {@link SmtVerificationResult.invariants} is about the *empty* case\n * only: an empty list from a route other than `smt` means \"not computed\", not\n * \"the net has none\". A non-empty list is always real — `unavailable` in\n * particular still carries the invariants the pipeline computed before it found\n * no usable solver, and `structural` carries whatever the proof rested on.\n */\nexport type VerificationRoute =\n /** The IC3/PDR pipeline: flatten, invariants, encode, solve ([VER-001]). */\n | 'smt'\n /** Bounded state-space enumeration ([VER-017]). */\n | 'enumeration'\n /** The ν name-partition state-class graph ([VER-012], Route B). */\n | 'nu-scg'\n /** A structural proof — Commoner's theorem, or the linear bound of [VER-015]. */\n | 'structural'\n /** No route could run (no solver, an unresolved property place). */\n | 'unavailable';\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 /**\n * Which route decided this verdict ([VER-003]). Read it before concluding\n * anything from an **empty** {@link invariants}: off the `'smt'` route that\n * means \"not computed\", never \"none exist\". A non-empty list is real whatever\n * the route says.\n */\n readonly route: VerificationRoute;\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 /**\n * Outcome of the abstract counterexample replay, as a TRI-STATE. `null` means\n * \"the replay did not apply\"; the two booleans both mean it ran.\n *\n * - `true` — an abstract firing chain from M₀ to a property-violating state\n * was re-executed TS-side; `counterexampleTrace` is that chain in FIRING\n * (replay) order and the verdict is `violated`.\n * - `false` — the replay ran without confirming the trace. Either it could not\n * settle the question (nothing decoded from the Z3 derivation, M₀ absent\n * from the decoded set, or a node/segment budget hit), in which case the\n * `violated` verdict rests on Spacer's SAT answer alone; or the search\n * completed and found NO chain, in which case the verdict was downgraded to\n * `unknown`. The report distinguishes the two (\"UNCONFIRMED\" vs \"FAILED\").\n * - `null` — replay did not apply: non-violated verdict, replay disabled via\n * `counterexampleReplay(false)`, the coloured ν-encoding / Route B (whose\n * state shapes are outside the flat replayer's scope), or a structural\n * proof.\n *\n * A `true` from the enumeration route ([VER-017]) means the same thing it means\n * everywhere else — the trace is an ordered firing sequence that reaches the\n * violation — even though it was read off the state-class graph rather than\n * re-executed: the graph path *is* a firing sequence, so there is nothing to\n * re-confirm. Consumers keying \"are these steps ordered\" off this field get the\n * right answer without special-casing the route.\n */\n readonly counterexampleConfirmed: boolean | null;\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","import type { Place } from './place.js';\nimport type { Transition } from './transition.js';\n\n/**\n * @internal Symbol key restricting construction to\n * {@link PetriNetBuilder.compose}. Bindings are produced by the host builder\n * and supplied to the caller's callback — direct construction is not part of\n * the public API.\n */\nconst COMPOSE_BINDINGS_KEY = Symbol('ComposeBindings.internal');\n\n/**\n * Typed binding builder for {@link PetriNetBuilder.compose}, per\n * `spec/11-modular-composition.md` requirements **MOD-020** (composition\n * operation) and **MOD-022** (type compatibility).\n *\n * `ComposeBindings` is a write-only collector: callers register port and\n * channel bindings against an instance's interface, and the host builder\n * consumes the recorded mappings as it merges the instance into the\n * enclosing net.\n *\n * ## Port bindings (MOD-020, MOD-022)\n *\n * {@link bindPort} merges an interface port with a caller-side place. The\n * port name is the **original** (pre-prefix) name declared in the subnet's\n * `Interface`; the caller place takes the port's slot in the resulting net.\n * Token-type compatibility is enforced at compile time only in TypeScript\n * (per [MOD-022]) — the typed `bindPort<T>` signature is the safety\n * mechanism. TypeScript erases generics at runtime, so a misuse via `as`\n * casts is structurally undetectable.\n *\n * ## Channel bindings (MOD-021)\n *\n * {@link bindChannel} records a synchronous channel binding: at compose time\n * the named instance-side interface transition is **merged** with the\n * supplied caller-side {@link Transition} into one transition in the\n * resulting flat net. Channel composition is implemented in task #13; until\n * then `compose(...)` raises an `Error` when any channel binding is present.\n *\n * ## Identity\n *\n * Instances are produced by {@link PetriNetBuilder.compose} and supplied to\n * the caller's callback. The constructor is symbol-guarded to prevent\n * direct construction.\n */\nexport class ComposeBindings {\n private readonly _portBindings = new Map<string, Place<unknown>>();\n private readonly _channelBindings = new Map<string, Transition>();\n\n /**\n * @internal Use {@link PetriNetBuilder.compose} — instances are produced\n * by the host builder and supplied to the caller's callback.\n */\n constructor(key: symbol) {\n if (key !== COMPOSE_BINDINGS_KEY) {\n throw new Error(\n 'Use PetriNetBuilder.compose(instance, b => ...) — ComposeBindings is not directly constructible',\n );\n }\n }\n\n /**\n * Binds the named interface port to the given caller place per **MOD-020**.\n *\n * The port name is the **original** (pre-prefix) name declared in the\n * subnet's `Interface`. The typed `<T>` parameter ensures the caller\n * place's token type matches the interface port's token type at compile\n * time per [MOD-022]; TypeScript does not validate the type at runtime\n * because generics are erased.\n *\n * @throws when `portName` is already bound on this builder\n */\n bindPort<T>(portName: string, callerPlace: Place<T>): this {\n if (this._portBindings.has(portName)) {\n throw new Error(`Port '${portName}' is already bound`);\n }\n this._portBindings.set(portName, callerPlace as Place<unknown>);\n return this;\n }\n\n /**\n * Records a synchronous channel binding per **MOD-021**: at compose time,\n * the instance-side renamed channel transition is merged with\n * `callerTransition` into a single transition in the resulting flat net.\n *\n * **Status**: channel composition is implemented in task #13. Recording a\n * channel binding here is permitted, but `compose(...)` currently raises\n * an `Error` when any channel binding is present.\n *\n * @throws when `channelName` is already bound on this builder\n */\n bindChannel(channelName: string, callerTransition: Transition): this {\n if (this._channelBindings.has(channelName)) {\n throw new Error(`Channel '${channelName}' is already bound`);\n }\n this._channelBindings.set(channelName, callerTransition);\n return this;\n }\n\n /** Returns an unmodifiable view of the recorded port bindings. */\n portBindings(): ReadonlyMap<string, Place<unknown>> {\n return this._portBindings;\n }\n\n /** Returns an unmodifiable view of the recorded channel bindings. */\n channelBindings(): ReadonlyMap<string, Transition> {\n return this._channelBindings;\n }\n}\n\n/**\n * @internal Package-internal factory used by {@link PetriNetBuilder.compose}\n * to construct {@link ComposeBindings} values without re-exporting the\n * Symbol-guarded constructor key publicly.\n *\n * NOT part of the public API surface — do NOT re-export from `core/index.ts`.\n */\nexport function __createComposeBindings(): ComposeBindings {\n return new ComposeBindings(COMPOSE_BINDINGS_KEY);\n}\n","/**\n * @internal\n *\n * Package-internal utility encapsulating the structural rewrite primitive used\n * by {@link SubnetDef.instantiate} and (later) `PetriNetBuilder.compose(...)`\n * per **MOD-020**.\n *\n * The rewrite is purely structural: every place reference in every arc is\n * replaced according to a supplied `Map<string, Place<unknown>>` keyed by\n * **original place name** (TypeScript Place identity is name-based per\n * `runtime/compiled-net.ts`'s `Map<string, number>`). Every transition is\n * rebuilt with rewritten arcs, preserving timing, priority, and action by\n * reference per **MOD-030**.\n *\n * ## Design — one engine, multiple callers\n *\n * The {@link renameNet} entry point is specialised to the rename pass: it\n * allocates fresh prefixed places via the `place(name)` factory, records the\n * old-to-new mapping in caller-supplied `Map`s (so callers can build\n * port/channel handle maps), and emits a renamed `PetriNet`. The arc-rewrite\n * helpers ({@link rewriteIn}, {@link rewriteOut}, etc.) are factored out so\n * the future `compose(...)` caller can substitute port-place mappings against\n * an arbitrary remap without renaming everything.\n *\n * ## Performance — V8 hidden-class stability\n *\n * - Places are constructed exclusively via the existing `place<T>(name)`\n * factory (from `core/place.ts`) so V8 can settle a single hidden class for\n * all `Place` allocations. We never synthesize `{name: ...}` literals\n * inline.\n * - Arcs are constructed via the existing `inputArc`, `inhibitorArc`,\n * `readArc`, `resetArc`, `outPlace`, `forwardInput`, `timeout` factories;\n * `In` shapes go through `one`, `exactly`, `all`, `atLeast`.\n * - The recursive `Out.And` / `Out.Xor` reconstruction uses pre-sized\n * `Array<Out>` plus a `for` loop (parallel to the Java perf reasoning about\n * `Stream` overhead — see `SubnetRewriter.rewriteOut`). `Array.prototype.map`\n * is avoided on this hot path.\n * - The `inputs(...)` rest-parameter into `TransitionBuilder.inputs` does\n * create a shallow array copy internally; this matches Java's\n * `Arc.In[t.inputSpecs().size()]` allocation and is the minimum allocation\n * needed to land arcs in the builder's defensive copy.\n *\n * Specified by `spec/11-modular-composition.md` MOD-010, MOD-011, MOD-012,\n * MOD-013, MOD-020, MOD-030.\n */\n\nimport type { Place } from '../place.js';\nimport { place } from '../place.js';\nimport type { ArcInhibitor, ArcRead, ArcReset } from '../arc.js';\nimport type { In } from '../in.js';\nimport { one, exactly, all, atLeast } from '../in.js';\nimport type { Out } from '../out.js';\nimport { and, outPlace, forwardInput, timeout, allPlaces } from '../out.js';\nimport { PetriNet } from '../petri-net.js';\nimport { Transition } from '../transition.js';\nimport type { MatchSpec } from '../match-spec.js';\nimport type { Timing } from '../timing.js';\nimport type { TransitionAction } from '../transition-action.js';\nimport { isPassthrough } from '../transition-action.js';\n\n// ============================================================\n// Public entry points\n// ============================================================\n\n/**\n * Returns a renamed copy of `orig`: same generic token type at the type\n * level, with `prefix + \"/\" + orig.name` as the new name. Goes through the\n * `place<T>(name)` factory for V8 hidden-class stability.\n */\nexport function renamePlace<T>(orig: Place<T>, prefix: string): Place<T> {\n return place<T>(prefix + '/' + orig.name);\n}\n\n/**\n * Renames every place and transition of `body`, prefixing each name with\n * `prefix + \"/\"`.\n *\n * **Side effects**: fills the two supplied maps so the caller can resolve\n * original-place / original-transition references against the rewritten\n * equivalents:\n *\n * - `placeRemap` — original place **name** → renamed place\n * - `transitionRemap` — original transition **name** → renamed transition\n *\n * Both maps are cleared on entry, then populated in iteration order.\n *\n * Note: the maps are keyed by name strings (not Place / Transition object\n * identity) because TypeScript Place identity is name-based per\n * `runtime/compiled-net.ts` (`Map<string, number>`). This matches how the\n * compiled net dedupes places.\n *\n * @param body the subnet body to rewrite\n * @param prefix the rename prefix\n * @param placeRemap caller-allocated map filled with old-name → new place\n * @param transitionRemap caller-allocated map filled with old-name → new transition\n * @returns a fresh `PetriNet` whose name is `prefix + \"/\" + body.name` and\n * whose places/transitions are renamed copies\n */\nexport function renameNet(\n body: PetriNet,\n prefix: string,\n placeRemap: Map<string, Place<unknown>>,\n transitionRemap: Map<string, Transition>,\n): PetriNet {\n placeRemap.clear();\n transitionRemap.clear();\n\n // Pass 1: rename every place. We must do this before transitions so arc\n // rewriting can resolve every place reference unambiguously.\n for (const orig of body.places) {\n placeRemap.set(orig.name, renamePlace(orig as Place<unknown>, prefix));\n }\n\n // Pass 2: rebuild every transition with arcs rewritten via placeRemap.\n const builder = PetriNet.builder(prefix + '/' + body.name);\n\n // Add places explicitly: some may not be referenced by any transition arc,\n // but were declared on the body — preserve that membership.\n for (const renamedPlace of placeRemap.values()) {\n builder.place(renamedPlace);\n }\n\n for (const t of body.transitions) {\n const renamed = rewriteTransition(t, prefix, placeRemap);\n transitionRemap.set(t.name, renamed);\n builder.transition(renamed);\n }\n\n return builder.build();\n}\n\n/**\n * Rebuilds `t` with name `prefix + \"/\" + t.name` and every arc rewritten\n * through `placeRemap`. Timing, priority, and action are carried through by\n * reference (action sharing per **MOD-030**).\n *\n * If a place referenced by an arc is not present in `placeRemap` (keyed by\n * original name), the arc retains the original place — partial remaps are\n * valid (used by the future `compose(...)` caller).\n */\nexport function rewriteTransition(\n t: Transition,\n prefix: string,\n placeRemap: Map<string, Place<unknown>>,\n): Transition {\n return rebuildWithName(t, prefix + '/' + t.name, placeRemap);\n}\n\n/**\n * Rebuilds `t` with the **same** name, substituting every arc place reference\n * through `remap`. Timing, priority, and action are carried through by\n * reference (action sharing per **MOD-030**).\n *\n * This is the rewrite primitive used by `PetriNetBuilder.compose(...)` (task\n * #12) when merging an instance's renamed body into an enclosing net: the\n * transition's prefixed name is already unique within the host (per\n * [MOD-010]), so no further renaming is needed — only port-place references\n * are substituted with the caller's places.\n *\n * If a place referenced by an arc is not present in `remap`, the arc retains\n * the original place — partial remaps are valid.\n */\nexport function substitutePlaces(\n t: Transition,\n remap: Map<string, Place<unknown>>,\n): Transition {\n return rebuildWithName(t, t.name, remap);\n}\n\n// ============================================================\n// Shared transition-rebuild implementation\n// ============================================================\n\n/**\n * Shared implementation — the single transition-rebuild site: rebuilds `t` with\n * the supplied `name` and arc places rewritten through `remap`. Used by\n * {@link rewriteTransition} (which prefixes the name), {@link substitutePlaces}\n * (which keeps the name), and {@link applyFusion} (which additionally passes\n * `normalizeInputs` to reconcile arcs the remap made collide).\n *\n * The action timeout is not a builder field: {@link Transition} derives it from\n * the output spec, which {@link rewriteOut} carries through — including the\n * `timeout` node itself (IO-013 / EXEC-022).\n */\nfunction rebuildWithName(\n t: Transition,\n name: string,\n remap: Map<string, Place<unknown>>,\n normalizeInputs?: (inputs: readonly In[]) => readonly In[],\n): Transition {\n const builder = Transition.builder(name)\n .timing(t.timing)\n .priority(t.priority)\n .action(t.action);\n\n // Build the declared→actual place correspondence (MOD-031) from the same\n // `remap` the arcs are rewritten through, chaining any pre-existing alias so\n // nested instantiation ([MOD-013]) resolves declared → final composed place.\n const alias = buildPlaceAlias(t, remap);\n if (alias.size > 0) {\n builder.placeAlias(alias);\n }\n\n if (t.inputSpecs.length > 0) {\n // Pre-size for V8 hidden-class stability; for-loop over Stream.map.\n const rewrittenInputs = new Array<In>(t.inputSpecs.length);\n for (let i = 0; i < t.inputSpecs.length; i++) {\n rewrittenInputs[i] = rewriteIn(t.inputSpecs[i]!, remap);\n }\n builder.inputs(...(normalizeInputs !== undefined\n ? normalizeInputs(rewrittenInputs)\n : rewrittenInputs));\n }\n\n if (t.outputSpec !== null) {\n builder.outputs(rewriteOut(t.outputSpec, remap));\n }\n\n for (let i = 0; i < t.inhibitors.length; i++) {\n builder.inhibitor(rewriteInhibitor(t.inhibitors[i]!, remap).place);\n }\n for (let i = 0; i < t.reads.length; i++) {\n builder.read(rewriteRead(t.reads[i]!, remap).place);\n }\n for (let i = 0; i < t.resets.length; i++) {\n builder.reset(rewriteReset(t.resets[i]!, remap).place);\n }\n\n // Carry the ν-net join correlation forward, following place renames so a\n // composed join still correlates the right (renamed) inputs (NU-020/-030).\n if (t.matchSpec !== null) {\n builder.match({\n keys: t.matchSpec.keys.map(k => ({\n place: remap.get(k.place.name) ?? k.place,\n key: k.key,\n })),\n });\n }\n\n return builder.build();\n}\n\n// ============================================================\n// Declared→actual place correspondence (MOD-031)\n// ============================================================\n\n/**\n * Builds the per-transition **declared → actual** place correspondence (per\n * **MOD-031**) for a transition being rewritten through `remap`, keyed by the\n * author-original declared place **name** → actual composed place. Mirrors the\n * Rust `build_local_name_map` / Java `buildPlaceAlias` algorithm so all three\n * implementations agree.\n *\n * **Chained path** — when `t` already carries a non-empty alias (from an\n * earlier rewrite pass: nested instantiation [MOD-013], or\n * instantiate-then-compose), each `declaredName → prev` entry is carried\n * forward as `declaredName → (remap.get(prev.name) ?? prev)`; identity results\n * are dropped. The arcs are deliberately **not** walked in this case — their\n * places are intermediate-pass names, not author-original, so recording them\n * would leak intermediate keys the user never declared.\n *\n * **First-pass path** — when `t` carries no alias, every arc place maps to its\n * remapped place keyed by the author-original name; identity entries are\n * skipped. The ForwardInput `from` is captured via the input walk and its `to`\n * via {@link allPlaces}.\n */\nfunction buildPlaceAlias(\n t: Transition,\n remap: Map<string, Place<unknown>>,\n): ReadonlyMap<string, Place<unknown>> {\n const prev = t.placeAlias;\n if (remap.size === 0 && prev.size === 0) {\n return EMPTY_ALIAS;\n }\n\n const alias = new Map<string, Place<unknown>>();\n\n if (prev.size > 0) {\n for (const [declaredName, prevActual] of prev) {\n const replaced = remap.get(prevActual.name);\n const finalActual = replaced !== undefined ? replaced : prevActual;\n if (finalActual.name !== declaredName) {\n alias.set(declaredName, finalActual);\n }\n }\n return alias;\n }\n\n const record = (p: Place<unknown>): void => {\n if (alias.has(p.name)) return;\n const replaced = remap.get(p.name);\n if (replaced !== undefined && replaced.name !== p.name) {\n alias.set(p.name, replaced);\n }\n };\n for (const spec of t.inputSpecs) record(spec.place as Place<unknown>);\n for (const rd of t.reads) record(rd.place as Place<unknown>);\n for (const inh of t.inhibitors) record(inh.place as Place<unknown>);\n for (const rs of t.resets) record(rs.place as Place<unknown>);\n if (t.outputSpec !== null) {\n for (const p of allPlaces(t.outputSpec)) record(p as Place<unknown>);\n }\n return alias;\n}\n\n/** @internal Shared empty correspondence for the no-op rewrite case. */\nconst EMPTY_ALIAS: ReadonlyMap<string, Place<unknown>> = new Map();\n\n// ============================================================\n// Arc rewrite helpers (exhaustive switches — no default)\n// ============================================================\n\n/**\n * Rewrites an {@link In} via the place remap. Exhaustive `switch` over the\n * discriminated union variants `one`, `exactly`, `all`, `at-least`.\n */\nexport function rewriteIn(spec: In, remap: Map<string, Place<unknown>>): In {\n switch (spec.type) {\n case 'one':\n return one(resolve(spec.place, remap));\n case 'exactly':\n return exactly(spec.count, resolve(spec.place, remap));\n case 'all':\n return all(resolve(spec.place, remap));\n case 'at-least':\n return atLeast(spec.minimum, resolve(spec.place, remap));\n }\n}\n\n/**\n * Rewrites an {@link Out} via the place remap. Exhaustive recursive `switch`\n * over the discriminated union variants `place`, `forward-input`, `and`, `xor`,\n * `timeout`.\n *\n * `and` / `xor` traversal uses explicit pre-sized `Array<Out>` + indexed\n * `for` (no `Array.prototype.map`) per the perf notes on this module.\n */\nexport function rewriteOut(out: Out, remap: Map<string, Place<unknown>>): Out {\n switch (out.type) {\n case 'place':\n return outPlace(resolve(out.place, remap));\n\n case 'forward-input':\n return forwardInput(resolve(out.from, remap), resolve(out.to, remap));\n\n case 'and': {\n const children = out.children;\n const rewritten = new Array<Out>(children.length);\n for (let i = 0; i < children.length; i++) {\n rewritten[i] = rewriteOut(children[i]!, remap);\n }\n // Reconstruct via the same shape the `and(...)` factory produces. We\n // skip the factory's variadic spread on this hot path; the resulting\n // shape is identical.\n return { type: 'and', children: rewritten };\n }\n\n case 'xor': {\n const children = out.children;\n const rewritten = new Array<Out>(children.length);\n for (let i = 0; i < children.length; i++) {\n rewritten[i] = rewriteOut(children[i]!, remap);\n }\n return { type: 'xor', children: rewritten };\n }\n\n case 'timeout':\n return timeout(out.afterMs, rewriteOut(out.child, remap));\n }\n}\n\n/** Rewrites an {@link ArcInhibitor} via the place remap. */\nexport function rewriteInhibitor(\n inh: ArcInhibitor,\n remap: Map<string, Place<unknown>>,\n): ArcInhibitor {\n return { type: 'inhibitor', place: resolve(inh.place, remap) };\n}\n\n/** Rewrites an {@link ArcRead} via the place remap. */\nexport function rewriteRead(\n rd: ArcRead,\n remap: Map<string, Place<unknown>>,\n): ArcRead {\n return { type: 'read', place: resolve(rd.place, remap) };\n}\n\n/** Rewrites an {@link ArcReset} via the place remap. */\nexport function rewriteReset(\n rs: ArcReset,\n remap: Map<string, Place<unknown>>,\n): ArcReset {\n return { type: 'reset', place: resolve(rs.place, remap) };\n}\n\n// ============================================================\n// Resolution helper\n// ============================================================\n\n/**\n * Looks up `p` in `remap` by `p.name`; returns the original if absent\n * (partial-remap semantics for the future `compose` caller).\n *\n * The unchecked cast is safe at runtime: TypeScript erases generics, and the\n * remap is populated by {@link renamePlace}, which preserves the token type\n * by construction (the renamed Place carries the same `T` at the type level\n * via the `place<T>(name)` factory). Future callers that put non-rename\n * mappings in must preserve the same invariant.\n */\nfunction resolve<T>(p: Place<T>, remap: Map<string, Place<unknown>>): Place<T> {\n const replaced = remap.get(p.name);\n return replaced !== undefined ? (replaced as Place<T>) : p;\n}\n\n// ============================================================\n// Channel composition: transition merge (MOD-021)\n// ============================================================\n\n/**\n * Merges a caller-side transition with an instance-side (renamed) channel\n * transition into a single {@link Transition} per **MOD-021**.\n *\n * ## Merge semantics\n *\n * - **Identity / name** — caller-wins. The merged transition's name is\n * `mergedName` (typically `caller.name`), so the merged transition remains\n * discoverable from caller-side code paths.\n * - **Arcs** — input/inhibitor/read/reset arcs are unioned: caller-side first,\n * then instance-side. Same-place input arcs are reconciled per MOD-021\n * rules (a)-(d) via {@link normalizeInputArcs} (additive where summable,\n * rejected otherwise); identical inhibitor/read/reset arcs collapse by\n * structural key.\n * - **Output spec** — if both sides carry an output spec, they are wrapped\n * under a single new outer `OutAnd(caller, instance)` so both sides' outputs\n * fire on a successful merged firing. If only one side has an output spec,\n * that one wins. If neither side has one, the merged transition has none.\n * `OutAnd` permits heterogeneous children (recursive trees), so wrapping a\n * possibly-`OutAnd` child under a new outer `OutAnd` is structurally legal.\n * - **Timing** — see {@link mergeTimings}. Caller wins when one side is\n * `Immediate`; equal non-`Immediate` timings collapse; conflicting\n * non-`Immediate` timings throw.\n * - **Priority** — see {@link pickPriority}. Caller-side wins (policy, not a\n * bug).\n * - **Action** — see {@link composeActions}. Sequential composition: caller-\n * side action runs first, then on its completion the instance-side action\n * runs against the same {@link import('../transition-context.js').TransitionContext}.\n * The runtime sees one transition firing per [CORE-021] / [EXEC-001].\n *\n * @throws when timings conflict or same-place input arcs have no additive\n * merge (per [MOD-021]) — the message names the channel and both\n * conflicting values so users can resolve it explicitly.\n */\nexport function mergeTransitions(\n caller: Transition,\n instance: Transition,\n mergedName: string,\n): Transition {\n if (mergedName === undefined || mergedName === null || mergedName.length === 0) {\n throw new Error('mergeTransitions: mergedName must be a non-empty string');\n }\n\n // Resolve timing / match / alias first so any conflict short-circuits before\n // building. The ν-net match and MOD-031 alias are carried as-is: both sides\n // already reference final host places at merge time (upstream substitutePlaces\n // remapped them, match included), so no further remap here.\n const mergedTiming = mergeTimings(caller.timing, instance.timing, mergedName);\n const mergedPriority = pickPriority(caller.priority, instance.priority);\n const mergedAction = composeActions(caller.action, instance.action);\n const mergedMatch = mergeMatchSpecs(caller.matchSpec, instance.matchSpec, mergedName);\n const mergedAlias = mergePlaceAlias(caller.placeAlias, instance.placeAlias, mergedName);\n\n const builder = Transition.builder(mergedName)\n .timing(mergedTiming)\n .priority(mergedPriority);\n if (mergedAction !== undefined) {\n builder.action(mergedAction);\n }\n\n // MOD-021 rule (d): different arc-kind sets on one place across the two\n // sides cannot be merged (identical sets pair up under rules (a)/(b)).\n rejectCrossSideKindConflicts(caller, instance, mergedName);\n\n // Inputs: union caller-first, then instance; same-place collisions merge\n // additively or reject per MOD-021 rules (a)-(d).\n const unionedInputs = normalizeInputArcs(\n [...caller.inputSpecs, ...instance.inputSpecs],\n () => `Channel composition '${mergedName}'`,\n );\n if (unionedInputs.length > 0) {\n builder.inputs(...unionedInputs);\n }\n\n // Outputs: wrap both sides under OutAnd; one-sided wins; none -> none.\n const mergedOutput = mergeOutputs(caller.outputSpec, instance.outputSpec);\n if (mergedOutput !== null) {\n builder.outputs(mergedOutput);\n }\n\n // Inhibitors / reads / resets: arc-record union (caller first, then instance).\n for (const inh of unionArcs<ArcInhibitor>(\n caller.inhibitors,\n instance.inhibitors,\n keyOfInhibitor,\n )) {\n builder.inhibitor(inh.place);\n }\n for (const rd of unionArcs<ArcRead>(caller.reads, instance.reads, keyOfRead)) {\n builder.read(rd.place);\n }\n for (const rs of unionArcs<ArcReset>(caller.resets, instance.resets, keyOfReset)) {\n builder.reset(rs.place);\n }\n\n // Apply the ν-net match (NU-060) and the MOD-031 declared→actual place map\n // (both resolved above, before any building, so a conflict on either\n // short-circuits with no wasted arc-union work).\n if (mergedMatch !== null) {\n builder.match(mergedMatch);\n }\n if (mergedAlias.size > 0) {\n builder.placeAlias(mergedAlias);\n }\n\n return builder.build();\n}\n\n/**\n * Carries the ν-net join correlation ({@link MatchSpec}) through a channel merge\n * per **NU-060**. One-sided → that side's match survives; both-null → none; both\n * non-null → the merge is rejected, because two independent name correlations\n * cannot be silently fused into one transition and NU-060 forbids dropping a\n * match. The surviving match is returned as-is: both transitions already\n * reference final host places at merge time, so no place remap is applied here\n * (unlike {@link rebuildWithName}).\n */\nfunction mergeMatchSpecs(\n caller: MatchSpec | null,\n instance: MatchSpec | null,\n channelName: string,\n): MatchSpec | null {\n if (caller === null) return instance;\n if (instance === null) return caller;\n throw new Error(\n `Channel composition '${channelName}': both the caller-side and instance-side ` +\n `transition carry a ν-net match — refusing to fuse two independent correlations ` +\n `into one transition (NU-060). Resolve explicitly by keeping the match on a single side.`,\n );\n}\n\n/**\n * Unions the two sides' MOD-031 declared→actual place correspondences for a\n * channel merge. Both actions run within the single merged firing, so each\n * side's declared-place resolution must survive. Disjoint keys union; an entry\n * present on both sides with the same actual collapses; a genuine conflict (same\n * declared place bound to two different actual places, compared by place name)\n * is rejected naming the declared place.\n */\nfunction mergePlaceAlias(\n caller: ReadonlyMap<string, Place<any>>,\n instance: ReadonlyMap<string, Place<any>>,\n channelName: string,\n): ReadonlyMap<string, Place<any>> {\n if (caller.size === 0) return instance;\n if (instance.size === 0) return caller;\n const merged = new Map<string, Place<any>>(caller);\n for (const [declared, actual] of instance) {\n const existing = merged.get(declared);\n if (existing !== undefined && existing.name !== actual.name) {\n throw new Error(\n `Channel composition '${channelName}': conflicting declared→actual place alias ` +\n `for declared place '${declared}' — caller-side maps to '${existing.name}', ` +\n `instance-side to '${actual.name}' (MOD-031). Resolve explicitly.`,\n );\n }\n merged.set(declared, actual);\n }\n return merged;\n}\n\n/**\n * Merges two timings per **MOD-021**:\n *\n * - Both `Immediate` -> `Immediate`.\n * - One `Immediate` -> the other side wins.\n * - Both non-`Immediate` and equal (by structural inspection of the timing\n * variant fields) -> that value collapses.\n * - Otherwise the conflict is rejected with an `Error` naming the channel\n * and both timings — the user must resolve it explicitly.\n */\nexport function mergeTimings(caller: Timing, instance: Timing, channelName: string): Timing {\n if (caller.type === 'immediate' && instance.type === 'immediate') {\n return { type: 'immediate' };\n }\n if (caller.type === 'immediate') return instance;\n if (instance.type === 'immediate') return caller;\n if (timingsEqual(caller, instance)) return caller;\n throw new Error(\n `Channel composition '${channelName}': conflicting non-Immediate timings — ` +\n `caller-side ${describeTiming(caller)} vs instance-side ${describeTiming(instance)}. ` +\n `Resolve explicitly by aligning the timings on either side (MOD-021).`,\n );\n}\n\n/**\n * Caller-side priority wins per **MOD-021**. Documented as policy: the\n * instance-side priority is ignored, not blended.\n */\nexport function pickPriority(callerPriority: number, _instancePriority: number): number {\n return callerPriority;\n}\n\n/**\n * Composes two transition actions sequentially: the caller-side action runs\n * first, then on its resolution the instance-side action runs against the same\n * {@link import('../transition-context.js').TransitionContext}. The combined\n * action surfaces a single `Promise<void>` so the executor sees one\n * transition firing per [CORE-021] / [EXEC-001].\n *\n * Null / passthrough handling:\n * - If both sides are `undefined` or both are `passthrough`, returns\n * `undefined` so {@link mergeTransitions} leaves the builder's default\n * passthrough action in place.\n * - If exactly one side is `undefined` / passthrough, the other side is\n * returned by reference (no extra wrapping).\n * - Otherwise returns a fresh sequential composition.\n *\n * Note: the production {@link Transition.builder} defaults action to\n * {@link import('../transition-action.js').passthrough}, so the `undefined`\n * branches are defensive — they exist so this helper is robust if upstream\n * surfaces a literal `undefined` action.\n */\nexport function composeActions(\n caller: TransitionAction | undefined,\n instance: TransitionAction | undefined,\n): TransitionAction | undefined {\n const callerIsPassthrough = caller === undefined || isPassthrough(caller);\n const instanceIsPassthrough = instance === undefined || isPassthrough(instance);\n\n if (callerIsPassthrough && instanceIsPassthrough) return undefined;\n if (callerIsPassthrough) return instance;\n if (instanceIsPassthrough) return caller;\n return async (ctx) => {\n await caller!(ctx);\n await instance!(ctx);\n };\n}\n\n/**\n * Combines two output specs per the merge contract: if both are present,\n * wrap them under a single {@link import('../out.js').OutAnd}; otherwise\n * return the non-null side (or `null` if both are missing).\n *\n * Exported (via the surrounding module's re-export surface) for unit testing\n * and for parity with the Java internal helper.\n */\nexport function mergeOutputs(caller: Out | null, instance: Out | null): Out | null {\n if (caller === null && instance === null) return null;\n if (caller === null) return instance;\n if (instance === null) return caller;\n return and(caller, instance);\n}\n\n/**\n * Returns the union of two arc lists, caller-first then instance, with\n * duplicates removed by structural key. Order is preserved within each\n * source list. Used for input, inhibitor, read, and reset arcs.\n *\n * Implementation: `Map<string, A>` preserves insertion order and dedupes by\n * the supplied key function. TypeScript arc records are POJOs — there is no\n * built-in structural equality, so callers must supply a key derived from\n * the discriminating fields (kind + place name + cardinality where\n * applicable).\n */\nexport function unionArcs<A>(\n caller: readonly A[],\n instance: readonly A[],\n keyOf: (arc: A) => string,\n): A[] {\n if (caller.length === 0 && instance.length === 0) return [];\n // Pre-size for V8 hidden-class stability; Map preserves insertion order\n // and dedupes by string key, mirroring Java's LinkedHashSet semantics.\n const seen = new Map<string, A>();\n for (let i = 0; i < caller.length; i++) {\n const arc = caller[i]!;\n const key = keyOf(arc);\n if (!seen.has(key)) seen.set(key, arc);\n }\n for (let i = 0; i < instance.length; i++) {\n const arc = instance[i]!;\n const key = keyOf(arc);\n if (!seen.has(key)) seen.set(key, arc);\n }\n const result = new Array<A>(seen.size);\n let i = 0;\n for (const arc of seen.values()) result[i++] = arc;\n return result;\n}\n\n// ============================================================\n// Internal helpers (timings, arc keys, action introspection)\n// ============================================================\n\n/**\n * Structural equality for two non-`Immediate` timings. Used by\n * {@link mergeTimings} to collapse equal timings into a single value\n * (mirrors Java's `record.equals`).\n */\nfunction timingsEqual(a: Timing, b: Timing): boolean {\n if (a.type !== b.type) return false;\n switch (a.type) {\n case 'immediate':\n return true;\n case 'deadline':\n return a.byMs === (b as typeof a).byMs;\n case 'delayed':\n return a.afterMs === (b as typeof a).afterMs;\n case 'window': {\n const w = b as typeof a;\n return a.earliestMs === w.earliestMs && a.latestMs === w.latestMs;\n }\n case 'exact':\n return a.atMs === (b as typeof a).atMs;\n }\n}\n\n/** Human-readable timing description for the conflict-diagnostic message. */\nfunction describeTiming(t: Timing): string {\n switch (t.type) {\n case 'immediate':\n return 'Immediate';\n case 'deadline':\n return `Deadline(byMs=${t.byMs})`;\n case 'delayed':\n return `Delayed(afterMs=${t.afterMs})`;\n case 'window':\n return `Window(earliestMs=${t.earliestMs}, latestMs=${t.latestMs})`;\n case 'exact':\n return `Exact(atMs=${t.atMs})`;\n }\n}\n\nfunction keyOfInhibitor(arc: ArcInhibitor): string {\n return `inh|${arc.place.name}`;\n}\nfunction keyOfRead(arc: ArcRead): string {\n return `read|${arc.place.name}`;\n}\nfunction keyOfReset(arc: ArcReset): string {\n return `reset|${arc.place.name}`;\n}\n\n// ============================================================\n// Input-arc normalization at composition seams (MOD-021 (a)-(d))\n// ============================================================\n\n/**\n * Normalizes an input-arc list per **MOD-021**'s arc-deduplication rules:\n * arcs on distinct places pass through in order; same-place arcs merge per\n * {@link mergeInPair} (additive where summable, rejected otherwise).\n *\n * `seamOf(placeName)` supplies the diagnostic prefix naming the seam that\n * caused the collision (fusion set per [MOD-061], or channel composition).\n * Collision-free lists are returned by reference — no rebuild.\n */\nexport function normalizeInputArcs(\n arcs: readonly In[],\n seamOf: (placeName: string) => string,\n): readonly In[] {\n if (arcs.length < 2) return arcs;\n const byPlace = new Map<string, In>();\n let collided = false;\n for (let i = 0; i < arcs.length; i++) {\n const arc = arcs[i]!;\n const name = arc.place.name;\n const prior = byPlace.get(name);\n if (prior === undefined) {\n byPlace.set(name, arc);\n } else {\n collided = true;\n byPlace.set(name, mergeInPair(prior, arc, seamOf(name)));\n }\n }\n if (!collided) return arcs;\n const result = new Array<In>(byPlace.size);\n let i = 0;\n for (const arc of byPlace.values()) result[i++] = arc;\n return result;\n}\n\n/**\n * Merges two same-place input arcs per the canonical [MOD-021] merge table:\n * `one`/`exactly` weights sum, `atLeast` pairs keep the stricter minimum,\n * `all`+`all` collapses. Any other pairing is rejected per rule (c).\n */\nfunction mergeInPair(a: In, b: In, seam: string): In {\n if (a.type === 'all' && b.type === 'all') return a;\n if (a.type === 'at-least' && b.type === 'at-least') {\n return a.minimum >= b.minimum ? a : b;\n }\n const countA = summableCount(a);\n const countB = summableCount(b);\n if (countA !== -1 && countB !== -1) {\n return exactly(countA + countB, a.place);\n }\n throw new Error(\n `${seam}: input arcs ${describeIn(a)} and ${describeIn(b)} collide on place ` +\n `'${a.place.name}' and have no additive merge (MOD-021 rule (c)). Use a ` +\n `single arc with exactly(n) / atLeast(n).`,\n );\n}\n\n/** Summable consumption weight of `one`/`exactly`; -1 for `all`/`at-least`. */\nfunction summableCount(arc: In): number {\n switch (arc.type) {\n case 'one':\n return 1;\n case 'exactly':\n return arc.count;\n default:\n return -1;\n }\n}\n\n/**\n * Cardinality-only rendering for the collision diagnostic — the place name\n * already appears once in the sentence.\n */\nfunction describeIn(arc: In): string {\n switch (arc.type) {\n case 'one':\n return 'one()';\n case 'exactly':\n return `exactly(${arc.count})`;\n case 'all':\n return 'all()';\n case 'at-least':\n return `atLeast(${arc.minimum})`;\n }\n}\n\n/**\n * Rejects a channel merge where the two sides put different arc-kind sets on\n * the same place — e.g. the caller consumes `P` while the instance resets `P`\n * (MOD-021 rule (d)). Identical kind sets pair up under rules (a)/(b), and\n * same-side kind mixes (read+reset on one place, EXEC-013) stay authorable.\n * Output specs are excluded: caller-consumes / instance-produces on one place\n * is the normal channel wiring pattern (outputs union via `OutAnd`).\n */\nfunction rejectCrossSideKindConflicts(\n caller: Transition,\n instance: Transition,\n mergedName: string,\n): void {\n const callerKinds = arcKindsByPlace(caller);\n if (callerKinds.size === 0) return;\n for (const [place, instanceSet] of arcKindsByPlace(instance)) {\n const callerSet = callerKinds.get(place);\n if (callerSet !== undefined && !sameKindSet(callerSet, instanceSet)) {\n throw new Error(\n `Channel composition '${mergedName}': conflicting arc kinds on place ` +\n `'${place}' — caller-side ${describeKinds(callerSet)} vs instance-side ` +\n `${describeKinds(instanceSet)}. Different arc types on one place ` +\n `cannot be merged (MOD-021 rule (d)). Resolve explicitly.`,\n );\n }\n }\n}\n\n/** Groups a transition's input/inhibitor/read/reset arcs into place name → kind set. */\nfunction arcKindsByPlace(t: Transition): Map<string, Set<string>> {\n const kinds = new Map<string, Set<string>>();\n const add = (name: string, kind: string): void => {\n let set = kinds.get(name);\n if (set === undefined) {\n set = new Set();\n kinds.set(name, set);\n }\n set.add(kind);\n };\n for (const s of t.inputSpecs) add(s.place.name, 'input');\n for (const a of t.inhibitors) add(a.place.name, 'inhibitor');\n for (const a of t.reads) add(a.place.name, 'read');\n for (const a of t.resets) add(a.place.name, 'reset');\n return kinds;\n}\n\n/** Renders an arc-kind set as `[input, read]` — sorted, so all three languages match. */\nfunction describeKinds(kinds: ReadonlySet<string>): string {\n return `[${[...kinds].sort().join(', ')}]`;\n}\n\nfunction sameKindSet(a: ReadonlySet<string>, b: ReadonlySet<string>): boolean {\n if (a.size !== b.size) return false;\n for (const k of a) if (!b.has(k)) return false;\n return true;\n}\n\n// ============================================================\n// Fusion: bulk place substitution across a transition set (MOD-061)\n// ============================================================\n\n/**\n * Applies a fusion remap to every transition in `transitions`, substituting\n * non-canonical → canonical place references in each transition's arcs.\n * Returns a fresh insertion-ordered `Set<Transition>`; the input collection\n * is not mutated.\n *\n * This is the loop wrapper around {@link rebuildWithName}; it exists so\n * callers — notably `PetriNetBuilder.build()` during fusion resolution per\n * **MOD-061** — do not duplicate the per-transition dispatch. Transitions\n * whose arcs do not reference any key of `fusionMap` pass through unchanged\n * in shape but are still rebuilt (a fresh `Transition` instance); callers that\n * care about identity preservation for un-affected transitions should instead\n * skip the rewrite entirely when `fusionMap.size === 0`.\n *\n * The remap is keyed by **non-canonical place name** → **canonical place**\n * (matching the `Map<string, Place<unknown>>` key convention used throughout\n * this module — TypeScript Place identity is name-based per\n * `runtime/compiled-net.ts`).\n *\n * When the substitution makes two input arcs of one transition collide on the\n * canonical place, they are reconciled per [MOD-021] via\n * {@link normalizeInputArcs} (additive where summable, rejected otherwise) so\n * a fused net still compiles under the CORE-030 duplicate-input rejection.\n *\n * @param transitions the transitions to rewrite (non-null, may be empty)\n * @param fusionMap non-canonical name → canonical place remap (non-null)\n * @param seamOf canonical place name → diagnostic seam prefix (the\n * owning fusion set) for collision rejections\n * @returns a fresh, insertion-ordered set of rewritten transitions\n */\nexport function applyFusion(\n transitions: Iterable<Transition>,\n fusionMap: Map<string, Place<unknown>>,\n seamOf: (canonicalPlaceName: string) => string,\n): Set<Transition> {\n // Normalization rides the rebuild rather than rebuilding a second time;\n // normalizeInputArcs returns collision-free lists by reference.\n const normalizeInputs = (inputs: readonly In[]): readonly In[] =>\n normalizeInputArcs(inputs, seamOf);\n const rewritten = new Set<Transition>();\n for (const t of transitions) {\n // Only transitions the fusion actually rewrites get the merge pass: a\n // pre-existing duplicate on an untouched place stays a CORE-030 compile\n // rejection rather than being silently summed away.\n rewritten.add(rebuildWithName(t, t.name, fusionMap,\n fusionTouchesInputs(t, fusionMap) ? normalizeInputs : undefined));\n }\n return rewritten;\n}\n\n/** True when any input arc of `t` references a fused (non-canonical) place. */\nfunction fusionTouchesInputs(t: Transition, fusionMap: Map<string, Place<unknown>>): boolean {\n if (fusionMap.size === 0) return false;\n for (let i = 0; i < t.inputSpecs.length; i++) {\n if (fusionMap.has(t.inputSpecs[i]!.place.name)) return true;\n }\n return false;\n}\n","import type { Place } from './place.js';\n\n/** @internal Symbol key restricting construction to {@link FusionSet.builder} and {@link FusionSet.of}. */\nconst FUSION_SET_KEY = Symbol('FusionSet.internal');\n\n/**\n * A declaration that N typed places are to be treated as a single canonical\n * place in the resulting flat {@link import('./petri-net.js').PetriNet}, per\n * `spec/11-modular-composition.md` requirements **MOD-060** (fusion set\n * declaration) and **MOD-061** (fusion resolution at build).\n *\n * Fusion is **orthogonal to subnet composition**: composition merges places\n * via port-binding (one instance port place ↔ one caller place per binding);\n * fusion merges N places at once via N-ary equivalence, applied **after** all\n * `compose(...)` calls have flattened subnet instances into the enclosing\n * {@link import('./petri-net.js').PetriNetBuilder}. Fusion is the mechanism\n * for modeling shared cross-instance state — e.g., a global rate limiter\n * shared by three instances of a leaky-bucket subnet — without expressing the\n * shared resource as an interface port on every subnet.\n *\n * ## Canonical member\n *\n * The **first declared member** is the canonical place; the others are\n * non-canonical and get substituted away at\n * {@link import('./petri-net.js').PetriNetBuilder.build} time. The canonical\n * member's name and identity survive into the resulting flat net;\n * non-canonical members do not appear in the built net's place set.\n *\n * ## Token-type homogeneity (MOD-060)\n *\n * All members of a fusion set MUST share the same token type. **In\n * TypeScript** this is enforced at **compile time only** (via the typed\n * `<T>` parameter on {@link FusionSetBuilder.member} and the typed varargs of\n * {@link FusionSet.of}); per the TS-specific MOD-022 clause, no runtime\n * `tokenType` introspection exists because Place carries only a phantom\n * generic. The Java implementation enforces the same invariant at runtime.\n *\n * ## Single-member sets\n *\n * A fusion set with a single member is degenerate but allowed: it is a no-op\n * at fusion-resolution time (the canonical member maps to itself, no\n * substitution occurs). This matches the structural semantics of an N-ary\n * equivalence with N=1.\n *\n * ## Identity\n *\n * `FusionSet` is immutable after construction. The {@link members} array is\n * frozen; iteration order is the declaration order, with the first element\n * guaranteed to be the canonical member.\n *\n * @see import('./petri-net.js').PetriNetBuilder.fuse\n */\nexport class FusionSet {\n readonly name: string;\n readonly members: readonly Place<unknown>[];\n\n /** @internal Use {@link FusionSet.builder} or {@link FusionSet.of} to create instances. */\n constructor(key: symbol, name: string, members: readonly Place<unknown>[]) {\n if (key !== FUSION_SET_KEY) {\n throw new Error('Use FusionSet.builder() or FusionSet.of() to create instances');\n }\n this.name = name;\n this.members = members;\n }\n\n /**\n * Returns the canonical member — by convention, the first declared member.\n * The canonical place's identity survives into the resulting flat net.\n */\n get canonical(): Place<unknown> {\n return this.members[0]!;\n }\n\n /**\n * Returns all members **except** the canonical member, in declaration order.\n * These are the places that get substituted away at\n * {@link import('./petri-net.js').PetriNetBuilder.build} time.\n *\n * For a single-member (degenerate) set, returns an empty array.\n */\n nonCanonical(): readonly Place<unknown>[] {\n if (this.members.length <= 1) return [];\n return this.members.slice(1);\n }\n\n toString(): string {\n return `FusionSet[${this.name}, canonical=${this.canonical.name}, members=${this.members.length}]`;\n }\n\n // ============================================================\n // Static factories\n // ============================================================\n\n /** Returns a fresh {@link FusionSetBuilder} with the given human-readable name. */\n static builder(name: string): FusionSetBuilder {\n return new FusionSetBuilder(name);\n }\n\n /**\n * Convenience factory: builds a fusion set whose first member is `first`\n * (the canonical) and whose remaining members are `rest`, all sharing the\n * type `<T>`.\n *\n * The varargs form ensures static-type homogeneity at the call site (the\n * TypeScript compiler checks every `rest` entry is a `Place<T>`).\n */\n static of<T>(name: string, first: Place<T>, ...rest: Place<T>[]): FusionSet {\n const members: Place<unknown>[] = [first as Place<unknown>];\n for (const p of rest) members.push(p as Place<unknown>);\n return new FusionSet(FUSION_SET_KEY, name, Object.freeze(members));\n }\n}\n\n/**\n * Fluent builder for {@link FusionSet}.\n *\n * Members are appended in call order; the first member becomes the canonical\n * place. The typed `<T>` parameter on {@link member} is for compile-time\n * guidance only — TypeScript erases generics at runtime, so no homogeneity\n * check happens here.\n */\nexport class FusionSetBuilder {\n private readonly _name: string;\n private readonly _members: Place<unknown>[] = [];\n\n constructor(name: string) {\n if (typeof name !== 'string' || name.length === 0) {\n throw new Error('FusionSet.builder: name must be a non-empty string');\n }\n this._name = name;\n }\n\n /**\n * Appends a member to the fusion set. The first member becomes the canonical\n * place per the convention documented on {@link FusionSet}.\n *\n * The `<T>` parameter is for compile-time guidance only: callers writing\n * typed code at the same call site benefit from the compiler checking\n * `Place<T>` at each member.\n */\n member<T>(place: Place<T>): this {\n if (place === undefined || place === null) {\n throw new Error(`FusionSet '${this._name}': member place must not be null`);\n }\n this._members.push(place as Place<unknown>);\n return this;\n }\n\n /**\n * Builds the immutable {@link FusionSet}. Validates that the set has at\n * least one member; the empty set is rejected as malformed per **MOD-060**.\n * Single-member sets are accepted as a structurally degenerate no-op.\n */\n build(): FusionSet {\n if (this._members.length === 0) {\n throw new Error(\n `FusionSet '${this._name}': must have at least one member (MOD-060)`,\n );\n }\n return new FusionSet(FUSION_SET_KEY, this._name, Object.freeze(this._members.slice()));\n }\n}\n\n/**\n * @internal Re-exported symbol key so the {@link FusionSet} test harness can\n * verify the symbol-guard. NOT part of the public API surface.\n */\nexport const __FUSION_SET_KEY_FOR_TEST = FUSION_SET_KEY;\n","import type { Place } from './place.js';\nimport type { TransitionAction } from './transition-action.js';\nimport { passthrough } from './transition-action.js';\nimport { Transition } from './transition.js';\nimport type { Instance } from './instance.js';\nimport { SubnetDef } from './subnet-def.js';\nimport { ComposeBindings, __createComposeBindings } from './compose-bindings.js';\nimport { applyFusion, mergeTransitions, substitutePlaces } from './internal/subnet-rewriter.js';\nimport { FusionSet, FusionSetBuilder } from './fusion-set.js';\n\n/** @internal Symbol key restricting construction to the builder and bindActions. */\nconst PETRI_NET_KEY = Symbol('PetriNet.internal');\n\n/**\n * Immutable definition of a Time Petri Net structure.\n *\n * A PetriNet is a reusable definition that can be executed multiple times\n * with different initial markings. Places are auto-collected from transitions.\n */\nexport class PetriNet {\n readonly name: string;\n readonly places: ReadonlySet<Place<any>>;\n readonly transitions: ReadonlySet<Transition>;\n\n /**\n * Subnet-membership metadata per **MOD-026**: maps each node name (place or\n * transition) contributed by exactly one directly-composed subnet to that\n * subnet's name. Shared places contributed by two or more subnets, and every\n * node of a net not built via {@link PetriNetBuilder.compose}`(SubnetDef)`,\n * are absent. Never null — an empty map when there is no metadata. The DOT\n * exporter renders `subgraph cluster_*` blocks from this map.\n *\n * V8 `Map` is insertion-ordered, preserving compose order so cluster\n * subgraphs render deterministically (cross-language byte-parity).\n */\n readonly subnetMembership: ReadonlyMap<string, string>;\n\n /** @internal Use {@link PetriNet.builder} to create instances. */\n constructor(\n key: symbol,\n name: string,\n places: ReadonlySet<Place<any>>,\n transitions: ReadonlySet<Transition>,\n subnetMembership: ReadonlyMap<string, string> = new Map(),\n ) {\n if (key !== PETRI_NET_KEY) throw new Error('Use PetriNet.builder() to create instances');\n this.name = name;\n this.places = places;\n this.transitions = transitions;\n this.subnetMembership = subnetMembership;\n }\n\n /**\n * Creates a new PetriNet with actions bound to transitions by name.\n * Unbound transitions keep passthrough action.\n */\n bindActions(actionBindings: Map<string, TransitionAction> | Record<string, TransitionAction>): PetriNet {\n const bindings = actionBindings instanceof Map\n ? actionBindings\n : new Map(Object.entries(actionBindings));\n\n return this.bindActionsWithResolver(\n (name) => bindings.get(name) ?? passthrough(),\n );\n }\n\n /**\n * Creates a new PetriNet with actions bound via a resolver function.\n *\n * The resolver is called once per transition with its name. Returning `null`\n * defers that transition — it keeps whatever action it already carries — which\n * is what makes staged binding (**MOD-024** AC7) work.\n */\n bindActionsWithResolver(actionResolver: (name: string) => TransitionAction | null): PetriNet {\n const boundTransitions = new Set<Transition>();\n for (const t of this.transitions) {\n const action = actionResolver(t.name);\n if (action !== null && action !== t.action) {\n boundTransitions.add(rebuildWithAction(t, action));\n } else {\n boundTransitions.add(t);\n }\n }\n // MOD-026: bindActions rebuilds transitions but preserves their names, so\n // name-keyed membership metadata survives a session bind unchanged.\n return new PetriNet(PETRI_NET_KEY, this.name, this.places, boundTransitions,\n this.subnetMembership);\n }\n\n static builder(name: string): PetriNetBuilder {\n return new PetriNetBuilder(name);\n }\n}\n\nexport class PetriNetBuilder {\n private readonly _name: string;\n private readonly _places = new Set<Place<any>>();\n private readonly _transitions = new Set<Transition>();\n private readonly _fusionSets: FusionSet[] = [];\n // MOD-026: node name -> set of subnet names that contributed it via\n // compose(SubnetDef), in first-contribution order. Resolved to single-owner\n // membership at build(). V8 Map/Set iterate in insertion order, preserving\n // compose order for cross-language byte-parity.\n private readonly _subnetContributions = new Map<string, Set<string>>();\n\n constructor(name: string) {\n this._name = name;\n }\n\n /** Add an explicit place. */\n place(place: Place<any>): this {\n this._places.add(place);\n return this;\n }\n\n /** Add explicit places. */\n places(...places: Place<any>[]): this {\n for (const p of places) this._places.add(p);\n return this;\n }\n\n /** Add a transition (auto-collects places from arcs). */\n transition(transition: Transition): this {\n this._transitions.add(transition);\n for (const spec of transition.inputSpecs) {\n this._places.add(spec.place);\n }\n for (const p of transition.outputPlaces()) {\n this._places.add(p);\n }\n for (const inh of transition.inhibitors) {\n this._places.add(inh.place);\n }\n for (const r of transition.reads) {\n this._places.add(r.place);\n }\n for (const r of transition.resets) {\n this._places.add(r.place);\n }\n return this;\n }\n\n /** Add transitions (auto-collects places from arcs). */\n transitions(...transitions: Transition[]): this {\n for (const t of transitions) this.transition(t);\n return this;\n }\n\n /**\n * Composes a subnet {@link Instance} into this builder per **MOD-020**\n * (composition operation), **MOD-021** (channel composition), **MOD-022**\n * (type compatibility), and **MOD-023** (composition produces a flat net).\n *\n * Two overloads are supported:\n *\n * 1. **Map / Record overload** — the runtime-checked form. Pass a\n * `Map<string, Place<unknown>>` or a `Record<string, Place<unknown>>`\n * keyed by the subnet's **original** (pre-prefix) port names. No\n * channel bindings are recorded by this overload.\n *\n * 2. **Callback overload** — the typed form. Pass a callback receiving a\n * fresh {@link ComposeBindings}; register port bindings via\n * `bindings.bindPort<T>(name, place)` so TypeScript checks each\n * binding's token type at compile time per [MOD-022]. Synchronous\n * channels may be merged with caller-side transitions via\n * `bindings.bindChannel(name, t)` per [MOD-021].\n *\n * For each port binding `(portName -> callerPlace)`, the instance's\n * renamed port place is substituted with the caller place at every arc\n * in the instance's renamed body via the `subnet-rewriter` module.\n * Internal (non-port) places of the instance flow through with their\n * prefixed names. Composition is **eager** — the rewrite happens here,\n * not at `build()` (per [MOD-020] AC #5).\n *\n * For each channel binding `(channelName -> callerTransition)`, the\n * instance's renamed channel transition and the caller-side transition\n * are merged into one transition in the resulting flat net per [MOD-021].\n * If the caller-side transition has not been added to this builder yet,\n * it is added implicitly during the merge step.\n *\n * @throws when a port name is unknown on the instance's interface, when a\n * channel name is unknown on the interface, or when caller- and\n * instance-side transition timings conflict (per [MOD-021]).\n */\n compose(instance: Instance<unknown>): this;\n compose(\n instance: Instance<unknown>,\n portMappings: ReadonlyMap<string, Place<unknown>> | Record<string, Place<unknown>>,\n ): this;\n compose(\n instance: Instance<unknown>,\n bind: (b: ComposeBindings) => void,\n ): this;\n compose(def: SubnetDef<unknown>): this;\n compose(\n instanceOrDef: Instance<unknown> | SubnetDef<unknown>,\n arg?:\n | ReadonlyMap<string, Place<unknown>>\n | Record<string, Place<unknown>>\n | ((b: ComposeBindings) => void),\n ): this {\n if (instanceOrDef instanceof SubnetDef) {\n return this.composeDirect(instanceOrDef);\n }\n const instance = instanceOrDef;\n if (arg === undefined) {\n return this.composeAuto(instance);\n }\n if (typeof arg === 'function') {\n const bindings = __createComposeBindings();\n arg(bindings);\n return this.composeInternal(instance, bindings.portBindings(), bindings.channelBindings());\n }\n\n const portMappings: ReadonlyMap<string, Place<unknown>> =\n arg instanceof Map ? arg : new Map(Object.entries(arg));\n return this.composeInternal(instance, portMappings, new Map());\n }\n\n /**\n * Composes a subnet {@link SubnetDef} **directly** into this builder per\n * **MOD-025** — **without instantiation**, and without the prefix-renaming\n * of {@link SubnetDef.instantiate}.\n *\n * Every body place and transition is added under its **original**\n * (un-prefixed) name. Places merge into this builder by name: a body place\n * whose name equals an enclosing-net place *is* that place in the composed\n * flat net. This is the mode for wiring a subnet in as a single shared copy.\n *\n * Direct composition is **order-independent**: composing the same set of\n * subnets in any order yields the same flat net, because merging is by\n * place name and not by a probe of the builder's place set at call time —\n * contrast the no-interface body-inference branch of {@link composeAuto}\n * (MOD-024), which is order-sensitive.\n *\n * For multiple *independent* copies — each with isolated per-instance state\n * per [MOD-012] — use {@link SubnetDef.instantiate} + the `compose(instance)`\n * overload instead.\n *\n * Rejections: a body transition whose name already exists in this builder\n * (use `instantiate(prefix)` for independent copies); a subnet whose\n * interface declares any channel (direct composition does not bind\n * channels — use `instantiate` + the channel-binding `compose` overload).\n *\n * Token-type conflicts on a same-named place cannot be detected: TS\n * {@link Place} equality is name-only at runtime (the documented carve-out,\n * same as MOD-024).\n *\n * @throws when the subnet declares channels, or a body transition name\n * collides with a transition already in this builder.\n */\n private composeDirect(def: SubnetDef<unknown>): this {\n const iface = def.iface;\n\n // MOD-025: direct composition does not bind channels.\n if (iface.channels.size > 0) {\n const channelNames: string[] = [];\n for (const c of iface.channels.values()) channelNames.push(c.name);\n channelNames.sort();\n throw new Error(\n `compose(SubnetDef): subnet '${def.name}' declares channels ` +\n `[${channelNames.join(', ')}]; direct composition does not bind channels.` +\n ` Use def.instantiate(prefix) + compose(instance, bind => bind.bindChannel(...)).`,\n );\n }\n\n const body = def.body;\n\n // MOD-025: a body transition whose name already exists here is almost\n // always a mistake — instantiate(prefix) is the multi-copy path.\n const hostTransitionNames = new Set<string>();\n for (const t of this._transitions) hostTransitionNames.add(t.name);\n for (const t of body.transitions) {\n if (hostTransitionNames.has(t.name)) {\n throw new Error(\n `compose(SubnetDef): transition '${t.name}' from subnet '${def.name}' ` +\n `collides with a transition already in net '${this._name}'. Direct ` +\n `composition merges by name; for independent copies use ` +\n `def.instantiate(prefix) + compose(instance).`,\n );\n }\n }\n\n // Canonicalize place references. TS `Set<Place>` dedups by reference, so\n // a body place value-equal-by-name to a host place must be funnelled\n // through the single host reference (same intent as composeAuto). Body\n // places with a new name are canonical as themselves; arcs referencing\n // them are left untouched by substitutePlaces.\n const hostByName = new Map<string, Place<unknown>>();\n for (const p of this._places) hostByName.set(p.name, p);\n\n // MOD-026: record which subnet each node came from so cluster-aware DOT\n // export can reconstruct subgraphs without prefix names. The subnet name\n // is sanitised of '/' so it never triggers spurious nested-cluster\n // splitting in the exporter.\n const subnetName = def.name.replace(/\\//g, '_');\n\n const mergeMap = new Map<string, Place<unknown>>();\n for (const p of body.places) {\n const host = hostByName.get(p.name);\n this.place(host ?? p);\n if (host !== undefined) mergeMap.set(p.name, host);\n this.recordContribution(p.name, subnetName);\n }\n for (const t of body.transitions) {\n this.transition(substitutePlaces(t, mergeMap));\n this.recordContribution(t.name, subnetName);\n }\n return this;\n }\n\n /** @internal MOD-026: records a node as contributed by the named subnet. */\n private recordContribution(nodeName: string, subnetName: string): void {\n let owners = this._subnetContributions.get(nodeName);\n if (owners === undefined) {\n owners = new Set<string>();\n this._subnetContributions.set(nodeName, owners);\n }\n owners.add(subnetName);\n }\n\n /**\n * Identity-default auto-compose per **MOD-024**.\n *\n * Each declared interface port auto-binds to its own `port.place` — the\n * Place the SubnetDef builder declared via `.inputPort(name, hostPlace)`\n * (or `outputPort` / `inoutPort`). If the host builder already declares\n * the equal place, the two merge; if not, the place arrives implicitly\n * via the rewritten transitions' arcs (same flow as explicit `bindPort`).\n *\n * If the subnet declares no interface ports at all, body places are\n * checked against this builder's place set **by name** (matching the\n * existing TS Place equality semantics; see [CORE-002] note in\n * `spec/11-modular-composition.md` MOD-024). Body places that don't match\n * stay private under their prefixed names per [MOD-010].\n *\n * Channels are NOT auto-bound — transition identity is too delicate for\n * inference. If the subnet declares any channel, this overload throws.\n */\n private composeAuto(instance: Instance<unknown>): this {\n const iface = instance.def.iface;\n\n if (iface.channels.size > 0) {\n const channelNames: string[] = [];\n for (const c of iface.channels.values()) channelNames.push(c.name);\n channelNames.sort();\n throw new Error(\n `compose(Instance): subnet '${instance.def.name}' ` +\n `(instance prefix '${instance.prefix}') declares channels [${channelNames.join(', ')}]` +\n `; auto-compose does not bind channels.` +\n ` Use compose(instance, bind => bind.bindChannel(...)) with explicit channel bindings.`,\n );\n }\n\n // Pre-index host places by name. The TS `_places: Set<Place>` dedupes\n // by reference (Place is an interface with only `name`), so when the\n // host pre-declared a Place object that is value-equal-by-name but a\n // different reference from the SubnetDef port's carried place, we\n // prefer the host reference: arc rewriting funnels through it and the\n // port's own Place object never enters `_places`. Same intent as\n // Rust's `place_index.get(&probe).cloned().unwrap_or(probe)` and\n // Java's record-equality `places.contains(probe)` in this branch.\n const hostByName = new Map<string, Place<unknown>>();\n for (const p of this._places) hostByName.set(p.name, p);\n\n if (iface.ports.size > 0) {\n // Explicit interface: each declared port auto-binds to its own\n // declared place. The SubnetDef's inputPort/outputPort/inoutPort\n // statement IS the host wiring — trust it. When a host place with\n // the same name already exists, use the host reference so the\n // merged net has a single Place per name.\n const portMappings = new Map<string, Place<unknown>>();\n for (const port of iface.ports.values()) {\n const hostMatch = hostByName.get(port.place.name);\n portMappings.set(port.name, hostMatch ?? port.place);\n }\n return this.composeInternal(instance, portMappings, new Map());\n }\n\n // No declared interface — infer the merge set from body places that\n // also exist on the host builder (matched by name). Build the\n // renamed-name -> host-place map directly and apply the composition.\n\n const mergeMap = new Map<string, Place<unknown>>();\n const prefix = instance.prefix + '/';\n for (const renamed of instance.renamedBody.places) {\n if (!renamed.name.startsWith(prefix)) continue;\n const originalName = renamed.name.substring(prefix.length);\n const hostMatch = hostByName.get(originalName);\n if (hostMatch !== undefined) {\n mergeMap.set(renamed.name, hostMatch);\n }\n }\n return this.applyComposition(instance, mergeMap, new Map());\n }\n\n /**\n * @internal Shared compose implementation: validates port and channel\n * bindings, builds the place-substitution map, walks every renamed-body\n * transition through {@link substitutePlaces}, applies channel merges per\n * [MOD-021], and adds the resulting transitions to this builder.\n *\n * ## Channel-merge flow ([MOD-021])\n *\n * 1. Collect rewritten instance transitions into a working `Map<string,\n * Transition>` keyed by prefixed transition name (deferred — not yet\n * added to the builder's transition set).\n * 2. For each channel binding, resolve the renamed instance-side\n * transition through `instance.channel(channelName)`, then look up its\n * rewritten counterpart in the working map by name.\n * 3. Replace the working-map entry with a {@link mergeTransitions} result\n * that fuses caller-side + instance-side; remove the rewritten\n * instance-side entry. Also replace (or add) the caller-side\n * transition in this builder's transition set with the same merged\n * result, indexed under the caller's name slot.\n * 4. Add the surviving (un-merged) entries to this builder.\n *\n * The deferral matters: writing the rewritten instance transitions to the\n * builder eagerly would force a second \"remove-then-replace\" pass to\n * apply the channel merges, complicating the place-collection invariants.\n * Collecting first and merging second keeps the builder's transition set\n * finalized exactly once.\n *\n * Keying the working map by prefixed transition name (rather than by\n * Transition reference) is also robust against a prior\n * {@link Instance.bindActions} call that may have rebuilt the renamed-body\n * transitions, breaking identity equality between the body and the\n * channel-handle map — but the prefixed names remain stable.\n */\n private composeInternal(\n instance: Instance<unknown>,\n portMappings: ReadonlyMap<string, Place<unknown>>,\n channelBindings: ReadonlyMap<string, Transition>,\n ): this {\n const iface = instance.def.iface;\n\n // Build mergeMap: keyed by RENAMED instance-side place name -> caller\n // place. The subnet-rewriter resolves arc-place references by name\n // (matching TS Place identity model: name-based equality per\n // runtime/compiled-net.ts), so we key by the renamed name.\n const mergeMap = new Map<string, Place<unknown>>();\n\n for (const [portName, callerPlace] of portMappings) {\n const port = iface.port(portName);\n if (port === undefined) {\n const knownPorts: string[] = [];\n for (const p of iface.ports.values()) knownPorts.push(p.name);\n throw new Error(\n `compose: no port named '${portName}' on subnet '${instance.def.name}' ` +\n `(instance prefix '${instance.prefix}'). Known ports: [${knownPorts.join(', ')}]`,\n );\n }\n\n // Resolve the renamed instance-side place via the typed accessor;\n // this gives us the rewritten Place<unknown> in the instance body.\n const ifacePlace = instance.port<unknown>(portName);\n mergeMap.set(ifacePlace.name, callerPlace);\n }\n\n return this.applyComposition(instance, mergeMap, channelBindings);\n }\n\n /**\n * Shared post-mergeMap pipeline: rewrites renamed-body transitions\n * through `mergeMap`, applies channel merges per **MOD-021**, and adds\n * the surviving transitions to the builder.\n *\n * Used by both the explicit-binding path (`composeInternal`) and the\n * auto-compose path (`composeAuto` per **MOD-024**). The two paths differ\n * only in how the (renamed Place name → host Place) `mergeMap` is built.\n */\n private applyComposition(\n instance: Instance<unknown>,\n mergeMap: Map<string, Place<unknown>>,\n channelBindings: ReadonlyMap<string, Transition>,\n ): this {\n const iface = instance.def.iface;\n\n // Step 1: Stage rewritten instance transitions in a working map keyed\n // by prefixed transition name. The substitutePlaces primitive keeps\n // the prefixed transition name unchanged (per MOD-010 — prefixed names\n // are already unique within the host) and rewrites only the arc place\n // references.\n const rewrittenByName = new Map<string, Transition>();\n for (const t of instance.renamedBody.transitions) {\n rewrittenByName.set(t.name, substitutePlaces(t, mergeMap));\n }\n\n // Step 2: Apply channel merges. For each binding, locate the rewritten\n // instance-side transition by name, fuse it with the caller-side\n // transition, and replace the working-map entry. Also replace the\n // caller-side transition in this builder's transition set with the\n // merged result (or add it if the caller did not pre-add it).\n for (const [channelName, callerTrans] of channelBindings) {\n // Resolve the renamed instance-side channel transition. instance.channel\n // throws on unknown name; we re-wrap with a more contextual message.\n let instanceRenamedChannel: Transition;\n try {\n instanceRenamedChannel = instance.channel(channelName);\n } catch (cause) {\n const knownChannels: string[] = [];\n for (const c of iface.channels.values()) knownChannels.push(c.name);\n const err = new Error(\n `compose: no channel named '${channelName}' on subnet '${instance.def.name}' ` +\n `(instance prefix '${instance.prefix}'). Known channels: [${knownChannels.join(', ')}]`,\n );\n // Preserve cause chain for diagnostics (Node 16.9+ supports the\n // standard Error cause option).\n (err as Error & { cause?: unknown }).cause = cause;\n throw err;\n }\n\n // Look up the rewritten (port-substituted) version of the renamed\n // channel transition by name.\n const rewrittenInstanceChannel = rewrittenByName.get(instanceRenamedChannel.name);\n if (rewrittenInstanceChannel === undefined) {\n // Defensive: SubnetDef.builder validation guarantees the channel's\n // transition is a member of the renamed body.\n /* istanbul ignore next */\n throw new Error(\n `compose: channel '${channelName}' resolved to a transition ` +\n `'${instanceRenamedChannel.name}' that is not present in the renamed body. ` +\n `This indicates a SubnetDef invariant violation.`,\n );\n }\n\n // Build the merged transition (caller-wins identity per MOD-021).\n const merged = mergeTransitions(callerTrans, rewrittenInstanceChannel, callerTrans.name);\n\n // Step 2a: Remove the rewritten instance-side transition from the\n // working map (it merges away — only the merged result remains under\n // the caller's transition slot in the builder).\n rewrittenByName.delete(instanceRenamedChannel.name);\n\n // Step 2b: Replace the caller-side transition (if present) in this\n // builder's transition set with the merged result. If the caller did\n // not pre-add it, simply add the merged transition — the user's\n // intent to use callerTrans is captured via the binding itself.\n this._transitions.delete(callerTrans);\n this.transition(merged);\n }\n\n // Step 3: Add the surviving (un-merged) rewritten transitions to the\n // builder. transition() auto-collects places — internal (non-merged)\n // renamed places are added under their prefixed names; caller places\n // already in the builder's place set get deduped via Place name.\n for (const rewritten of rewrittenByName.values()) {\n this.transition(rewritten);\n }\n\n return this;\n }\n\n /**\n * Registers one or more {@link FusionSet} declarations on this builder, per\n * **MOD-060** (fusion set declaration) and **MOD-061** (fusion resolution\n * at build).\n *\n * Fusion is **orthogonal to subnet composition**: fuse sets are accumulated\n * here and applied during {@link build} **after** all `compose(...)` calls\n * have flattened subnet instances into the builder's transition set.\n * Registration order is irrelevant to semantics — `fuse(set)` BEFORE\n * `compose(...)` and `fuse(set)` AFTER `compose(...)` both apply at the\n * same point in the build pipeline.\n *\n * ## Validation\n *\n * Cross-set overlap (a place appearing in two fusion sets) is detected at\n * {@link build} and reported as an `Error` naming the offending place and\n * both sets.\n *\n * Two overloads are supported:\n *\n * 1. **Spread overload** — pass one or more pre-built {@link FusionSet}\n * values (e.g., from `FusionSet.of(...)` or\n * `FusionSet.builder(...).build()`).\n * 2. **Sugar overload** — pass a callback receiving a fresh\n * {@link FusionSetBuilder} named after the enclosing net; register\n * members via `b.member(place)`. Equivalent to\n * `FusionSet.builder('<netName>-fusion').<callback>.build()` followed by\n * `fuse(...)` on the result.\n */\n fuse(...sets: FusionSet[]): this;\n fuse(declarer: (b: FusionSetBuilder) => void): this;\n fuse(...args: [(b: FusionSetBuilder) => void] | FusionSet[]): this {\n if (args.length === 1 && typeof args[0] === 'function') {\n const declarer = args[0] as (b: FusionSetBuilder) => void;\n const fb = FusionSet.builder(this._name + '-fusion');\n declarer(fb);\n this._fusionSets.push(fb.build());\n return this;\n }\n for (const s of args as FusionSet[]) {\n if (s === undefined || s === null) {\n throw new Error('fuse: fusion set must not be null');\n }\n this._fusionSets.push(s);\n }\n return this;\n }\n\n /**\n * Builds the immutable {@link PetriNet}, applying fusion resolution (per\n * **MOD-061**) AFTER all transition/composition accumulation:\n *\n * 1. Detect overlapping fusion sets — a single place declared in two sets\n * is rejected with an `Error`.\n * 2. Build the `non-canonical → canonical` substitution map across all\n * sets, keyed by non-canonical place name (matching the rewriter's\n * Map<string, Place<unknown>> convention — TypeScript Place identity is\n * name-based per `runtime/compiled-net.ts`).\n * 3. Walk every transition through {@link applyFusion} to rewrite arc place\n * references; input arcs colliding on a canonical place merge per\n * [MOD-021] (additive where summable, rejected otherwise).\n * 4. Re-derive the place set from the rewritten transitions plus any\n * caller-declared standalone places, dropping non-canonical members.\n * Caller-declared standalone places that happen to be non-canonical\n * members are also dropped.\n *\n * If no fusion sets were registered, the build is the trivial\n * `new PetriNet(...)` — the fusion machinery has no per-build cost when\n * unused.\n *\n * @throws when two fusion sets share a place\n */\n build(): PetriNet {\n const membership = this.resolveSubnetMembership();\n if (this._fusionSets.length === 0) {\n return new PetriNet(PETRI_NET_KEY, this._name, this._places, this._transitions,\n membership);\n }\n return this.buildWithFusion(membership);\n }\n\n /**\n * @internal Resolves the per-compose contributions recorded by\n * `composeDirect` into the final node-name → subnet-name membership map per\n * **MOD-026**. A node contributed by exactly one subnet maps to that subnet;\n * a place contributed by two or more subnets is a shared rendezvous place\n * and is omitted (it renders top-level, outside any cluster). Returns an\n * empty map — the common case — when no subnet was composed directly.\n */\n private resolveSubnetMembership(): Map<string, string> {\n const resolved = new Map<string, string>();\n for (const [nodeName, owners] of this._subnetContributions) {\n if (owners.size === 1) {\n resolved.set(nodeName, owners.values().next().value as string);\n }\n }\n return resolved;\n }\n\n /**\n * @internal Drops membership entries for places removed by fusion: a\n * non-canonical fused member no longer exists in the net, so its\n * `node-name → subnet` entry would dangle. The surviving canonical place\n * keeps its own entry. Per **MOD-026**.\n */\n private static filterFusedMembership(\n membership: Map<string, string>,\n nonCanonicalNames: ReadonlySet<string>,\n ): Map<string, string> {\n if (membership.size === 0 || nonCanonicalNames.size === 0) {\n return membership;\n }\n const filtered = new Map<string, string>();\n for (const [key, value] of membership) {\n if (!nonCanonicalNames.has(key)) {\n filtered.set(key, value);\n }\n }\n return filtered;\n }\n\n /**\n * @internal Fusion-resolution pass per **MOD-061**. Split out from\n * {@link build} so the no-fusion fast path stays trivial.\n */\n private buildWithFusion(membership: Map<string, string>): PetriNet {\n // Step 1: detect overlap. The same place name MUST NOT appear in more\n // than one fusion set (TypeScript Place identity is name-based per\n // `runtime/compiled-net.ts`).\n const ownership = new Map<string, FusionSet>();\n for (const set of this._fusionSets) {\n for (const member of set.members) {\n const prior = ownership.get(member.name);\n if (prior !== undefined && prior !== set) {\n throw new Error(\n `Fusion overlap: place '${member.name}' appears in two fusion sets ` +\n `('${prior.name}' and '${set.name}'). A place may appear in at most ` +\n `one fusion set (MOD-060).`,\n );\n }\n ownership.set(member.name, set);\n }\n }\n\n // Step 2: build the non-canonical-name → canonical-place substitution\n // map. Single-member sets contribute nothing (no non-canonical members),\n // so the map is naturally empty for the degenerate case.\n const fusionMap = new Map<string, Place<unknown>>();\n const nonCanonicalNames = new Set<string>();\n for (const set of this._fusionSets) {\n const canonical = set.canonical;\n for (const nc of set.nonCanonical()) {\n fusionMap.set(nc.name, canonical);\n nonCanonicalNames.add(nc.name);\n }\n }\n\n // Step 3: rewrite every transition's arcs through the fusion map.\n // applyFusion always returns a fresh set; if fusionMap is empty (single-\n // member-only sets) the rewrite is structurally a no-op but still rebuilds\n // Transition records — no observable difference. Input-arc collisions on a\n // canonical place merge per MOD-021, naming the owning fusion set on\n // rejection.\n const rewrittenTransitions = applyFusion(this._transitions, fusionMap, (canonicalName) => {\n const owner = ownership.get(canonicalName);\n return `Fusion set '${owner !== undefined ? owner.name : canonicalName}'`;\n });\n\n // Step 4: re-derive the place set. Strategy: start from the current\n // place set, drop every non-canonical member (they are gone from the\n // net), then union in the places auto-discovered from the rewritten\n // transitions. This preserves caller-declared standalone places that are\n // unrelated to fusion, drops any standalone declarations of non-canonical\n // members, and ensures canonical places end up present even if a caller\n // never declared them standalone.\n const rebuiltPlaces = new Set<Place<any>>();\n for (const p of this._places) {\n if (!nonCanonicalNames.has(p.name)) {\n rebuiltPlaces.add(p);\n }\n }\n for (const t of rewrittenTransitions) {\n for (const spec of t.inputSpecs) rebuiltPlaces.add(spec.place);\n for (const p of t.outputPlaces()) rebuiltPlaces.add(p);\n for (const inh of t.inhibitors) rebuiltPlaces.add(inh.place);\n for (const r of t.reads) rebuiltPlaces.add(r.place);\n for (const r of t.resets) rebuiltPlaces.add(r.place);\n }\n\n return new PetriNet(PETRI_NET_KEY, this._name, rebuiltPlaces, rewrittenTransitions,\n PetriNetBuilder.filterFusedMembership(membership, nonCanonicalNames));\n }\n}\n\n/** Creates a new transition with a different action while preserving all arc specs. */\nfunction rebuildWithAction(t: Transition, action: TransitionAction): Transition {\n const builder = Transition.builder(t.name)\n .timing(t.timing)\n .priority(t.priority)\n .action(action);\n\n // MOD-031: carry the declared→actual place correspondence forward so an action\n // bound after instantiate/compose ([CORE-042]) still resolves its hardcoded\n // declared places. Empty for hand-written / directly-composed transitions.\n if (t.placeAlias.size > 0) {\n builder.placeAlias(t.placeAlias);\n }\n\n if (t.inputSpecs.length > 0) {\n builder.inputs(...t.inputSpecs);\n }\n if (t.outputSpec !== null) {\n builder.outputs(t.outputSpec);\n }\n\n for (const inh of t.inhibitors) {\n builder.inhibitor(inh.place);\n }\n for (const r of t.reads) {\n builder.read(r.place);\n }\n for (const r of t.resets) {\n builder.reset(r.place);\n }\n\n // NU-030: carry the ν-net join correlation forward. bindActions only attaches\n // an action — it does not rename places — so the matchSpec's input-place\n // references are still valid and it is carried as-is (no remap, unlike the\n // compose/rename rebuildWithName). Dropping it here would silently revert a\n // correlated join-by-id to a plain FIFO AND join at runtime.\n if (t.matchSpec !== null) {\n builder.match(t.matchSpec);\n }\n\n return builder.build();\n}\n","import type { PetriNet } from '../core/petri-net.js';\nimport type { Token } from '../core/token.js';\nimport type { SmtProperty } from './smt-property.js';\nimport type { SmtVerificationResult } from './smt-verification-result.js';\nimport { isProven, isViolated } from './smt-verification-result.js';\n\n/**\n * Token-source supplier used by the verification harness to seed a synthetic\n * environment place for a given input port, per\n * `spec/11-modular-composition.md` requirement **MOD-051** AC #3.\n *\n * The supplier's presence is what bounds the input behavior in the synthetic\n * harness; it is invoked once at synthetic-net construction time so that\n * supplier-side errors surface eagerly, not at verification time. The\n * concrete token value is not consumed by the verifier itself (which operates\n * on the integer marking projection per [VER-004]); it merely materialises\n * the seed token type and surfaces user errors.\n */\nexport type TokenSupplier = () => Token<unknown>;\n\n/**\n * Harness driving local property verification of a subnet definition per\n * `spec/11-modular-composition.md` requirement **MOD-051**.\n *\n * The harness is a value carrier consumed by\n * {@link import('../core/subnet-def.js').SubnetDef.verify}. It supplies the\n * three pieces of information needed to wrap a subnet in a synthetic\n * enclosing net for verification:\n *\n * 1. A {@link params} value of the subnet's parameter type.\n * 2. A {@link portInputGenerators} map from **input port name** (original /\n * pre-prefix) to a {@link TokenSupplier}. The supplier's presence is what\n * bounds the input behavior in the synthetic harness; the supplier is\n * invoked at synthetic-net construction time when the harness wires up the\n * {@link import('../core/place.js').EnvironmentPlace} associated with the\n * port.\n * 3. A set of {@link properties} to check (per [VER-002] /\n * {@link SmtProperty}).\n *\n * Each entry in {@link portInputGenerators} MUST correspond to an input or\n * in-out port declared on the subnet's interface. Output-only ports never\n * appear in the generator map; instead, the harness wires them to a synthetic\n * observation place visible to the verifier.\n *\n * The map and property collection accept either the canonical\n * `Map`/`ReadonlySet` form or a plain `Record`/`readonly array` for ergonomic\n * inline construction; `SubnetDef.verify` normalises both.\n *\n * @typeParam P parameter type carried through to the subnet under test\n */\nexport interface VerificationHarness<P = void> {\n /**\n * Parameter value supplied to\n * {@link import('../core/subnet-def.js').SubnetDef.instantiate} for the\n * system-under-test instance. Use `undefined` (or `null`) for `P = void`.\n */\n readonly params: P;\n\n /**\n * Map (or `Record`) from **input port name** to a {@link TokenSupplier} that\n * seeds the synthetic environment place for that port. Output-only ports\n * MUST NOT appear; in-out ports MUST appear (mirrors the Java harness).\n */\n readonly portInputGenerators:\n | ReadonlyMap<string, TokenSupplier>\n | Readonly<Record<string, TokenSupplier>>;\n\n /**\n * Safety properties to check on the synthetic enclosing net per\n * {@link SmtProperty}. An empty collection is permitted but yields an empty\n * {@link VerificationResult.perProperty}.\n */\n readonly properties: ReadonlySet<SmtProperty> | readonly SmtProperty[];\n\n}\n\n/**\n * Aggregated outcome of a\n * {@link import('../core/subnet-def.js').SubnetDef.verify} invocation per\n * `spec/11-modular-composition.md` requirement **MOD-051**.\n *\n * The verifier is invoked once per {@link SmtProperty} declared in the\n * harness; each invocation produces an {@link SmtVerificationResult}. This\n * record carries the per-property results plus the synthetic enclosing net\n * that was constructed for verification (useful for diagnostic output and\n * tooling to render the harness wiring).\n */\nexport interface VerificationResult {\n /**\n * The synthetic enclosing net assembled by `SubnetDef.verify(...)`: the\n * renamed body of the subnet under test, with each input port bound to a\n * synthetic environment place and each output port bound to a synthetic\n * observation place.\n */\n readonly syntheticNet: PetriNet;\n\n /**\n * Per-property verification results, in the iteration order of the\n * harness's {@link VerificationHarness.properties} collection.\n */\n readonly perProperty: ReadonlyMap<SmtProperty, SmtVerificationResult>;\n\n /**\n * Returns true when every property in the harness was proven safe.\n * An empty harness (no properties) returns `true` vacuously.\n */\n allProven(): boolean;\n\n /**\n * Returns true when at least one property was violated (counter-example\n * found).\n */\n anyViolated(): boolean;\n}\n\n/**\n * @internal Builds a {@link VerificationResult} value from the per-property\n * map and synthetic net. The resulting object is structurally immutable; the\n * `perProperty` map is wrapped in a defensive copy so callers cannot mutate\n * the verifier's view through retained map references.\n */\nexport function buildVerificationResult(\n syntheticNet: PetriNet,\n perProperty: ReadonlyMap<SmtProperty, SmtVerificationResult>,\n): VerificationResult {\n const frozen = new Map(perProperty);\n return {\n syntheticNet,\n perProperty: frozen,\n allProven(): boolean {\n for (const r of frozen.values()) {\n if (!isProven(r)) return false;\n }\n return true;\n },\n anyViolated(): boolean {\n for (const r of frozen.values()) {\n if (isViolated(r)) return true;\n }\n return false;\n },\n };\n}\n\n/**\n * @internal Normalises {@link VerificationHarness.portInputGenerators} to a\n * canonical `Map<string, TokenSupplier>` regardless of whether the caller\n * supplied a `Map` or a `Record`. Iteration order is preserved.\n */\nexport function normaliseGenerators(\n generators: VerificationHarness<unknown>['portInputGenerators'],\n): Map<string, TokenSupplier> {\n if (generators instanceof Map) return new Map(generators);\n return new Map(Object.entries(generators));\n}\n\n/**\n * @internal Normalises {@link VerificationHarness.properties} to an array of\n * {@link SmtProperty} regardless of whether the caller supplied a `Set` or an\n * array. Iteration order is preserved.\n */\nexport function normaliseProperties(\n properties: VerificationHarness<unknown>['properties'],\n): SmtProperty[] {\n if (Array.isArray(properties)) return [...properties];\n return [...(properties as ReadonlySet<SmtProperty>)];\n}\n","import type { PetriNet } from './petri-net.js';\nimport type { Transition } from './transition.js';\nimport type { Place } from './place.js';\nimport { environmentPlace, place as makePlace, type EnvironmentPlace } from './place.js';\nimport { Interface, type Channel, type Port } from './interface.js';\nimport type { Instance } from './instance.js';\nimport { __createInstance } from './instance.js';\nimport { PetriNet as PetriNetClass } from './petri-net.js';\nimport { renameNet } from './internal/subnet-rewriter.js';\nimport { SmtVerifier } from '../verification/smt-verifier.js';\nimport { alwaysAvailable } from '../verification/analysis/environment-analysis-mode.js';\nimport type { EnvironmentAnalysisMode } from '../verification/analysis/environment-analysis-mode.js';\nimport type { SmtProperty } from '../verification/smt-property.js';\nimport type { SmtVerificationResult } from '../verification/smt-verification-result.js';\nimport {\n buildVerificationResult,\n normaliseGenerators,\n normaliseProperties,\n type VerificationHarness,\n type VerificationResult,\n type TokenSupplier,\n} from '../verification/verification-harness.js';\nimport { requireOutputProducingActions } from './internal/output-action-check.js';\n\n// Re-export the real harness types from the verification module for callers\n// that import from `core/subnet-def.js`. The previous task-#10 placeholder\n// shape is removed; the surface is now backed by `verification/verification-harness.ts`.\nexport type { VerificationHarness, VerificationResult, TokenSupplier };\n\n/** @internal Symbol key restricting construction to {@link SubnetDef.builder} and {@link SubnetDef.fromNet}. */\nconst SUBNET_DEF_KEY = Symbol('SubnetDef.internal');\n\n/**\n * An open Petri net fragment paired with a declared {@link Interface}, per\n * `spec/11-modular-composition.md` requirement **MOD-001**.\n *\n * A subnet definition is the reusable unit of composition. It carries:\n * - A {@link name} (used as the originating-def label in `SubnetInstance` per [MOD-041]);\n * - A {@link body} — a structurally complete `PetriNet` per [CORE-040];\n * - An {@link iface} — the set of exposed ports and channels per [MOD-003] / [MOD-005].\n *\n * `SubnetDef` is the open variant of the {@link Subnet} discriminated union\n * defined in `subnet.ts` per **MOD-002**.\n *\n * The {@link SubnetDef.fromNet} retrofit factory per **MOD-014** wraps an\n * existing closed `PetriNet` plus an `Interface` into an unparameterised\n * `SubnetDef<void>`, applying the same per-element validation as the\n * builder's `build()`.\n *\n * @typeParam P parameter type carried through to `Instance.params`\n * (use `void` for unparameterised subnets)\n */\nexport class SubnetDef<P = void> {\n readonly name: string;\n readonly body: PetriNet;\n readonly iface: Interface;\n\n /** @internal Use {@link SubnetDef.builder} or {@link SubnetDef.fromNet} to create instances. */\n constructor(key: symbol, name: string, body: PetriNet, iface: Interface) {\n if (key !== SUBNET_DEF_KEY) {\n throw new Error('Use SubnetDef.builder() or SubnetDef.fromNet() to create instances');\n }\n this.name = name;\n this.body = body;\n this.iface = iface;\n }\n\n /**\n * Produces a renamed module instance per **MOD-010**, **MOD-011**, **MOD-012**,\n * and **MOD-030**.\n *\n * The rename pass walks every place and transition of the body net,\n * substituting each name with `prefix + \"/\" + originalName`, and rebuilds\n * every arc with rewritten place references. Transition timing, priority,\n * and action are carried through by reference (action sharing per\n * [MOD-030]). The renamed body is itself a structurally valid `PetriNet`\n * per [CORE-040]; per-instance state isolation per [MOD-012] is a\n * structural consequence of distinct prefixed names.\n *\n * ## Prefix validation\n *\n * The `\"/\"` character is reserved as the prefix separator (per [MOD-010]).\n * User-supplied prefixes MUST NOT contain `\"/\"`; nested instantiation is\n * performed by the future `PetriNetBuilder.compose(...)` mechanism (per\n * [MOD-013]). A prefix containing `\"/\"` raises an `Error`.\n *\n * @param prefix the rename prefix (non-empty, must not contain `\"/\"`)\n * @param params the parameter value carried through to `Instance.params`\n * (may be omitted when `P` is `void`)\n * @throws when `prefix` is empty or contains `\"/\"`\n */\n instantiate(prefix: string, params?: P): Instance<P> {\n validatePrefix(prefix);\n\n // Allocate the two remap maps. The rewriter fills them as side effects so\n // we can resolve interface place/transition references afterward. Maps\n // are keyed by ORIGINAL name strings (TypeScript Place identity is\n // name-based per `runtime/compiled-net.ts`).\n const placeRemap = new Map<string, Place<unknown>>();\n const transitionRemap = new Map<string, Transition>();\n\n const renamedBody = renameNet(this.body, prefix, placeRemap, transitionRemap);\n\n // Resolve port handles: original-port-name -> renamed body place.\n const portHandles = new Map<string, Place<unknown>>();\n for (const port of this.iface.ports.values()) {\n const renamed = placeRemap.get(port.place.name);\n if (renamed === undefined) {\n // Defensive: should be impossible because MOD-006 validation at\n // SubnetDef.builder.build() guarantees port.place is in the body.\n throw new Error(\n `Port '${port.name}' references place '${port.place.name}' that was not found ` +\n `in the renamed body. This indicates a SubnetDef invariant violation.`,\n );\n }\n portHandles.set(port.name, renamed);\n }\n\n // Resolve channel handles: original-channel-name -> renamed body transition.\n const channelHandles = new Map<string, Transition>();\n for (const channel of this.iface.channels.values()) {\n const renamed = transitionRemap.get(channel.transition.name);\n if (renamed === undefined) {\n throw new Error(\n `Channel '${channel.name}' references transition '${channel.transition.name}' that was not found ` +\n `in the renamed body. This indicates a SubnetDef invariant violation.`,\n );\n }\n channelHandles.set(channel.name, renamed);\n }\n\n return __createInstance<P>(\n prefix,\n this,\n renamedBody,\n portHandles,\n channelHandles,\n params as P,\n );\n }\n\n /**\n * Verifies safety properties of this subnet definition **in isolation** per\n * **MOD-051**, by wrapping it in a synthetic enclosing net where each input\n * port is fed by an {@link EnvironmentPlace} (token-source per the harness\n * generator) and each output port is observed via a synthetic place. The\n * standard {@link SmtVerifier} (per [MOD-050]) is invoked once per property\n * declared in the harness; the resulting per-property outcomes are\n * aggregated into a {@link VerificationResult}.\n *\n * ## Synthetic-net construction\n *\n * The synthetic enclosing net is built by:\n * 1. Instantiating this `SubnetDef` with the prefix `\"sut\"` (system-under-test)\n * and `harness.params`.\n * 2. For each input or in-out port on the interface, looking up the\n * harness generator by port name, allocating a synthetic\n * {@link Place}`<unknown>` of the same conceptual token type as the\n * port, wrapping it in an {@link EnvironmentPlace}, and binding the\n * port to that synthetic place via\n * {@link import('./petri-net.js').PetriNetBuilder.compose}. The supplier\n * is invoked once at construction time to materialize the seed token —\n * its presence is what bounds the input behavior under analysis. **If\n * the harness map is missing a generator for a required input or in-out\n * port, an `Error` is thrown.**\n * 3. For each output or in-out port, allocating a synthetic observation\n * {@link Place}`<unknown>` and binding the port to it via the same\n * `compose(...)` call. The verifier inspects this place's reachability\n * / marking through the standard property APIs ({@link SmtProperty}).\n * 4. Building the resulting flat {@link PetriNet} per [MOD-023] (the\n * verifier is composition-unaware per [MOD-050]).\n *\n * ## Per-property invocation\n *\n * Each {@link SmtProperty} in the harness is verified independently against\n * the same synthetic net. The synthetic environment places are passed\n * through to the verifier so that places driven by the harness generators\n * are treated under the verifier's environment-analysis semantics rather\n * than as ordinary sink places.\n *\n * @param harness the verification harness — supplies parameters, input-port\n * token generators, and the property set\n * @returns a {@link VerificationResult} aggregating per-property\n * {@link SmtVerificationResult}s\n * @throws when an input or in-out port is missing a harness generator\n */\n async verify(\n harness: VerificationHarness<P>,\n /**\n * How injection into the synthetic environment places is modeled (VER-006,\n * MOD-051 AC3).\n *\n * The synthetic net has environment places by construction, so this decides what a\n * verdict means. The default over-approximates: a `proven` under\n * `alwaysAvailable()` holds for any environment. Pass `bounded(k)` to prove a\n * property that holds only when the environment injects at most `k` tokens.\n * `ignore()` is accepted but cannot yield `proven` — VER-006 refuses to certify a\n * proof that holds only because injection was never modeled.\n */\n environmentMode: EnvironmentAnalysisMode = alwaysAvailable(),\n ): Promise<VerificationResult> {\n if (harness === null || harness === undefined) {\n throw new Error('SubnetDef.verify: harness must not be null/undefined');\n }\n\n // Step 1: instantiate this SubnetDef under the \"sut\" prefix. Uses an\n // underscore in the synthetic enclosing net's name to avoid colliding\n // with the \"/\" prefix separator (matches Java).\n const sut = this.instantiate('sut', harness.params);\n\n // Normalise the harness's generator map / property collection up front so\n // we can check membership and iterate deterministically below.\n const generators = normaliseGenerators(harness.portInputGenerators);\n const properties = normaliseProperties(harness.properties);\n\n // Step 2: allocate synthetic harness places per port direction. Track\n // the environment places (one per input/inout port) for the SmtVerifier\n // so the verifier knows to treat their underlying places as boundary\n // places rather than ordinary internals.\n const envPlaces: EnvironmentPlace<unknown>[] = [];\n const portMappings = new Map<string, Place<unknown>>();\n\n for (const port of this.iface.ports.values()) {\n const portName = port.name;\n\n switch (port.direction) {\n case 'input': {\n const generator = generators.get(portName);\n if (generator === undefined) {\n throw new Error(\n `verify: harness is missing an input generator for port '${portName}' ` +\n `on subnet '${this.name}' (MOD-051)`,\n );\n }\n // Touch the supplier to surface user-supplied errors at synthetic-\n // net construction time rather than at verification time. Mirrors\n // Java's Objects.requireNonNull(generator.get(), ...).\n const seed = generator();\n if (seed === null || seed === undefined) {\n throw new Error(\n `verify: input generator for port '${portName}' on subnet ` +\n `'${this.name}' produced null/undefined`,\n );\n }\n const synth = makePlace<unknown>(`harness_in_${portName}`);\n envPlaces.push(environmentPlace<unknown>(synth.name));\n portMappings.set(portName, synth);\n break;\n }\n case 'output': {\n const synth = makePlace<unknown>(`harness_out_${portName}`);\n portMappings.set(portName, synth);\n break;\n }\n case 'inout': {\n const generator = generators.get(portName);\n if (generator === undefined) {\n throw new Error(\n `verify: harness is missing an input generator for in-out port ` +\n `'${portName}' on subnet '${this.name}' (MOD-051)`,\n );\n }\n const seed = generator();\n if (seed === null || seed === undefined) {\n throw new Error(\n `verify: input generator for in-out port '${portName}' on subnet ` +\n `'${this.name}' produced null/undefined`,\n );\n }\n const synth = makePlace<unknown>(`harness_io_${portName}`);\n envPlaces.push(environmentPlace<unknown>(synth.name));\n portMappings.set(portName, synth);\n break;\n }\n }\n }\n\n // Step 3: build the synthetic enclosing net. Channels declared on the\n // interface (but not bound here) flow through as ordinary renamed\n // transitions per MOD-021. The `verify_` prefix uses an underscore (not\n // `/`) so the enclosing-net name does not collide with the prefix\n // separator reserved by [MOD-010].\n const syntheticNet = PetriNetClass.builder('verify_' + this.name)\n .compose(sut as Instance<unknown>, portMappings)\n .build();\n\n // CORE-043, checked here rather than left to SmtVerifier so an empty property set\n // cannot skip it.\n requireOutputProducingActions(syntheticNet);\n\n // Step 4: invoke the SmtVerifier once per property and aggregate\n // results. Iteration order matches the harness's property collection\n // for deterministic per-property reporting.\n const perProperty = new Map<SmtProperty, SmtVerificationResult>();\n for (const property of properties) {\n // Set explicitly rather than inherited: the synthetic env places are the\n // harness's own, so how injection is modelled is the harness's call\n // ([MOD-051] AC3), not the verifier default's. Under ignore() [VER-006]\n // downgrades every proof about a net with env places to Unknown, so a\n // subnet with an input port could never be proven.\n const verifier = SmtVerifier.forNet(syntheticNet).property(property);\n if (envPlaces.length > 0) {\n verifier.environmentPlaces(...envPlaces);\n verifier.environmentMode(environmentMode);\n }\n const result = await verifier.verify();\n perProperty.set(property, result);\n }\n\n return buildVerificationResult(syntheticNet, perProperty);\n }\n\n // ============================================================\n // Static factories\n // ============================================================\n\n static builder<P = void>(name: string): SubnetDefBuilder<P> {\n return new SubnetDefBuilder<P>(name);\n }\n\n /**\n * Retrofit utility per **MOD-014**: wraps an existing closed {@link PetriNet}\n * plus an {@link Interface} into an unparameterised `SubnetDef<void>`.\n *\n * Validation per **MOD-014** / **MOD-006** is enforced before the result is\n * constructed:\n * - Every port's underlying `Place` must be present in `net.places`.\n * - Every channel's underlying `Transition` must be present in `net.transitions`.\n * - Port and channel name uniqueness is re-validated defensively (the\n * `Interface` builder already enforces this; hand-built `Interface`\n * values bypass that path).\n *\n * The resulting subnet definition is unparameterised (parameter type is `void`).\n *\n * @throws when a port place is not in `net.places`, a channel transition is\n * not in `net.transitions`, or port/channel names are not unique.\n */\n static fromNet(net: PetriNet, iface: Interface): SubnetDef<void> {\n const bodyPlaces = net.places;\n const bodyTransitions = net.transitions;\n\n // Re-validate port-name uniqueness (defence in depth — InterfaceBuilder\n // enforces it for the builder route, but a hand-built `Interface`\n // bypasses that path; SubnetDef.fromNet is the documented retrofit\n // entry point so we re-check here to keep failures crisp). Note: do NOT\n // use `Set#add`'s return value — `Set#add` returns the Set itself\n // (truthy) and cannot signal \"already present\"; check with `has` first.\n const seenPortNames = new Set<string>();\n for (const port of iface.ports.values()) {\n if (seenPortNames.has(port.name)) {\n throw new Error(\n `fromNet: duplicate port name '${port.name}' on interface for net '${net.name}' (MOD-006)`,\n );\n }\n seenPortNames.add(port.name);\n if (!bodyPlaces.has(port.place as Place<unknown>)) {\n throw new Error(\n `fromNet: port '${port.name}' references place '${port.place.name}' which is not in net '${net.name}' (MOD-014/MOD-006)`,\n );\n }\n }\n\n // Re-validate channel-name uniqueness and transition membership.\n const seenChannelNames = new Set<string>();\n for (const channel of iface.channels.values()) {\n if (seenChannelNames.has(channel.name)) {\n throw new Error(\n `fromNet: duplicate channel name '${channel.name}' on interface for net '${net.name}' (MOD-006)`,\n );\n }\n seenChannelNames.add(channel.name);\n if (!bodyTransitions.has(channel.transition)) {\n throw new Error(\n `fromNet: channel '${channel.name}' references transition '${channel.transition.name}' which is not in net '${net.name}' (MOD-014/MOD-006)`,\n );\n }\n }\n\n return new SubnetDef<void>(SUBNET_DEF_KEY, net.name, net, iface);\n }\n}\n\n/**\n * Fluent builder for {@link SubnetDef}.\n *\n * Validation per **MOD-006** is enforced at {@link build}:\n * - Every port's underlying place must be in the body net.\n * - Every channel's underlying transition must be in the body net.\n * - Port names must be unique within the port namespace.\n * - Channel names must be unique within the channel namespace.\n */\nexport class SubnetDefBuilder<P = void> {\n private readonly _name: string;\n private readonly _bodyBuilder: ReturnType<typeof PetriNetClass.builder>;\n private readonly _ports: Port<unknown>[] = [];\n private readonly _channels: Channel[] = [];\n\n constructor(name: string) {\n this._name = name;\n this._bodyBuilder = PetriNetClass.builder(name);\n }\n\n // -------- body construction (delegates to PetriNet.Builder) --------\n\n transition(transition: Transition): this {\n this._bodyBuilder.transition(transition);\n return this;\n }\n\n transitions(...transitions: Transition[]): this {\n this._bodyBuilder.transitions(...transitions);\n return this;\n }\n\n place<T>(place: Place<T>): this {\n this._bodyBuilder.place(place);\n return this;\n }\n\n // -------- interface declarations --------\n\n inputPort<T>(name: string, place: Place<T>): this {\n this._ports.push({ name, direction: 'input', place: place as Place<unknown> });\n return this;\n }\n\n outputPort<T>(name: string, place: Place<T>): this {\n this._ports.push({ name, direction: 'output', place: place as Place<unknown> });\n return this;\n }\n\n inoutPort<T>(name: string, place: Place<T>): this {\n this._ports.push({ name, direction: 'inout', place: place as Place<unknown> });\n return this;\n }\n\n channel(name: string, transition: Transition): this {\n this._channels.push({ name, transition });\n return this;\n }\n\n // -------- build & validate (MOD-006) --------\n\n build(): SubnetDef<P> {\n const built = this._bodyBuilder.build();\n const bodyPlaces = built.places;\n const bodyTransitions = built.transitions;\n\n // 1. Validate port-name uniqueness (MOD-006). Note: do NOT use\n // `Set#add`'s return value — it returns the Set itself (truthy) and\n // cannot signal \"already present\"; check with `has` first.\n const portNames = new Set<string>();\n for (const port of this._ports) {\n if (portNames.has(port.name)) {\n throw new Error(`Subnet '${this._name}': duplicate port name '${port.name}'`);\n }\n portNames.add(port.name);\n // 2. Validate port place membership (MOD-006).\n if (!bodyPlaces.has(port.place as Place<unknown>)) {\n throw new Error(\n `Subnet '${this._name}': port '${port.name}' references place '${port.place.name}' which is not in the body`,\n );\n }\n }\n\n // 3. Validate channel-name uniqueness and transition membership (MOD-006).\n const channelNames = new Set<string>();\n for (const channel of this._channels) {\n if (channelNames.has(channel.name)) {\n throw new Error(`Subnet '${this._name}': duplicate channel name '${channel.name}'`);\n }\n channelNames.add(channel.name);\n if (!bodyTransitions.has(channel.transition)) {\n throw new Error(\n `Subnet '${this._name}': channel '${channel.name}' references transition '${channel.transition.name}' which is not in the body`,\n );\n }\n }\n\n const ifaceBuilder = Interface.builder();\n ifaceBuilder.portsAll(this._ports);\n ifaceBuilder.channelsAll(this._channels);\n const iface = ifaceBuilder.build();\n\n return new SubnetDef<P>(SUBNET_DEF_KEY, this._name, built, iface);\n }\n}\n\n/**\n * @internal Validates the prefix supplied to {@link SubnetDef.instantiate}\n * per **MOD-010**:\n * - non-empty;\n * - no `\"/\"` (reserved as the prefix separator; nested instantiation is\n * performed by `PetriNetBuilder.compose(...)` per [MOD-013]).\n *\n * Throws an `Error` with a descriptive message on failure.\n */\nfunction validatePrefix(prefix: string): void {\n if (typeof prefix !== 'string' || prefix.length === 0) {\n throw new Error('SubnetDef.instantiate: prefix must be a non-empty string');\n }\n if (prefix.indexOf('/') >= 0) {\n throw new Error(\n `SubnetDef.instantiate: prefix must not contain '/' (reserved as the prefix ` +\n `separator per MOD-010); use compose(...) for nested instantiation. Got: '${prefix}'`,\n );\n }\n}\n"],"mappings":";;;;;;;AAwBO,SAAS,MAAS,MAAwB;AAC/C,SAAO,EAAE,KAAK;AAChB;AAGO,SAAS,iBAAoB,MAAmC;AACrE,SAAO,EAAE,OAAO,MAAS,IAAI,EAAE;AACjC;;;ACSO,SAAS,IAAOA,QAA2B;AAChD,SAAO,EAAE,MAAM,OAAO,OAAAA,OAAM;AAC9B;AAGO,SAAS,QAAW,OAAeA,QAA+B;AACvE,MAAI,QAAQ,GAAG;AACb,UAAM,IAAI,MAAM,4BAA4B,KAAK,EAAE;AAAA,EACrD;AACA,SAAO,EAAE,MAAM,WAAW,OAAAA,QAAO,MAAM;AACzC;AAGO,SAAS,IAAOA,QAA2B;AAChD,SAAO,EAAE,MAAM,OAAO,OAAAA,OAAM;AAC9B;AAGO,SAAS,QAAW,SAAiBA,QAA+B;AACzE,MAAI,UAAU,GAAG;AACf,UAAM,IAAI,MAAM,8BAA8B,OAAO,EAAE;AAAA,EACzD;AACA,SAAO,EAAE,MAAM,YAAY,OAAAA,QAAO,QAAQ;AAC5C;AAKO,SAAS,cAAc,MAAkB;AAC9C,UAAQ,KAAK,MAAM;AAAA,IACjB,KAAK;AAAO,aAAO;AAAA,IACnB,KAAK;AAAW,aAAO,KAAK;AAAA,IAC5B,KAAK;AAAO,aAAO;AAAA,IACnB,KAAK;AAAY,aAAO,KAAK;AAAA,EAC/B;AACF;AASO,SAAS,iBAAiB,MAAU,WAA2B;AACpE,MAAI,YAAY,cAAc,IAAI,GAAG;AACnC,UAAM,IAAI;AAAA,MACR,wBAAwB,KAAK,MAAM,IAAI,gBAAgB,SAAS,cAAc,cAAc,IAAI,C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UAAI,CAAC,WAAW,IAAI,KAAK,KAAuB,GAAG;AACjD,cAAM,IAAI;AAAA,UACR,WAAW,KAAK,KAAK,YAAY,KAAK,IAAI,uBAAuB,KAAK,MAAM,IAAI;AAAA,QAClF;AAAA,MACF;AAAA,IACF;AAGA,UAAM,eAAe,oBAAI,IAAY;AACrC,eAAW,WAAW,KAAK,WAAW;AACpC,UAAI,aAAa,IAAI,QAAQ,IAAI,GAAG;AAClC,cAAM,IAAI,MAAM,WAAW,KAAK,KAAK,8BAA8B,QAAQ,IAAI,GAAG;AAAA,MACpF;AACA,mBAAa,IAAI,QAAQ,IAAI;AAC7B,UAAI,CAAC,gBAAgB,IAAI,QAAQ,UAAU,GAAG;AAC5C,cAAM,IAAI;AAAA,UACR,WAAW,KAAK,KAAK,eAAe,QAAQ,IAAI,4BAA4B,QAAQ,WAAW,IAAI;AAAA,QACrG;AAAA,MACF;AAAA,IACF;AAEA,UAAM,eAAe,UAAU,QAAQ;AACvC,iBAAa,SAAS,KAAK,MAAM;AACjC,iBAAa,YAAY,KAAK,SAAS;AACvC,UAAM,QAAQ,aAAa,MAAM;AAEjC,WAAO,IAAI,UAAa,gBAAgB,KAAK,OAAO,OAAO,KAAK;AAAA,EAClE;AACF;AAWA,SAAS,eAAe,QAAsB;AAC5C,MAAI,OAAO,WAAW,YAAY,OAAO,WAAW,GAAG;AACrD,UAAM,IAAI,MAAM,0DAA0D;AAAA,EAC5E;AACA,MAAI,OAAO,QAAQ,GAAG,KAAK,GAAG;AAC5B,UAAM,IAAI;AAAA,MACR,uJAC4E,MAAM;AAAA,IACpF;AAAA,EACF;AACF;","names":["place","place","timeoutPlace","resolve","key","place","key","place","key","key","place","place","place","place","dot","place","script","resolve","place","place","place","key","key","place","key","vars","reconstruct","script","witness","script","key","quantified","place","key","place","placeName","place","all","key","placeName","inputRequiredCount","counterexamplePath","script","note","place","key","i","key","place","key","place","key","place","key","place"]}