dsh-logicprobe 0.5.0 → 0.5.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/engine.js CHANGED
@@ -1,1622 +1,1622 @@
1
- import { createHash } from 'node:crypto';
2
- export const ENGINE_SCHEMA_VERSION = 1;
3
- const DEFAULT_MAX_STATES = 10_000;
4
- const DEFAULT_MAX_PERMUTATION_EVENTS = 5;
5
- function stableStringify(value) {
6
- if (value === null || typeof value !== 'object')
7
- return JSON.stringify(value);
8
- if (Array.isArray(value))
9
- return '[' + value.map((item) => stableStringify(item)).join(',') + ']';
10
- const record = value;
11
- return '{' + Object.keys(record).sort().map((key) => JSON.stringify(key) + ':' + stableStringify(record[key])).join(',') + '}';
12
- }
13
- export function modelHash(model) {
14
- return createHash('sha256').update(stableStringify(model)).digest('hex');
15
- }
16
- export function validateModel(input) {
17
- const errors = [];
18
- const bad = (path, message) => {
19
- errors.push(path + ': ' + message);
20
- };
21
- if (typeof input !== 'object' || input === null || Array.isArray(input)) {
22
- return { ok: false, errors: ['model: must be an object'] };
23
- }
24
- const root = input;
25
- if (root.schemaVersion !== 1)
26
- bad('schemaVersion', 'must be 1');
27
- if (typeof root.init !== 'string' || root.init.length === 0)
28
- bad('init', 'must be a non-empty string');
29
- if (!Array.isArray(root.states) || root.states.length === 0) {
30
- bad('states', 'must be a non-empty array');
31
- }
32
- else {
33
- const seen = new Set();
34
- root.states.forEach((entry, index) => {
35
- if (typeof entry !== 'object' || entry === null || Array.isArray(entry)) {
36
- bad('states[' + index + ']', 'must be an object');
37
- return;
38
- }
39
- const state = entry;
40
- if (typeof state.id !== 'string' || state.id.length === 0)
41
- bad('states[' + index + '].id', 'must be a non-empty string');
42
- else if (seen.has(state.id))
43
- bad('states[' + index + '].id', 'duplicate state id ' + state.id);
44
- else
45
- seen.add(state.id);
46
- if (state.terminal !== undefined && typeof state.terminal !== 'boolean')
47
- bad('states[' + index + '].terminal', 'must be a boolean');
48
- });
49
- if (typeof root.init === 'string' && root.init.length > 0 && !seen.has(root.init))
50
- bad('init', 'must name a declared state');
51
- }
52
- if (!Array.isArray(root.transitions)) {
53
- bad('transitions', 'must be an array');
54
- }
55
- else {
56
- const stateIds = new Set(Array.isArray(root.states) ? root.states.map((state) => state.id) : []);
57
- root.transitions.forEach((entry, index) => {
58
- const path = 'transitions[' + index + ']';
59
- if (typeof entry !== 'object' || entry === null || Array.isArray(entry)) {
60
- bad(path, 'must be an object');
61
- return;
62
- }
63
- const transition = entry;
64
- if (typeof transition.from !== 'string' || transition.from.length === 0)
65
- bad(path + '.from', 'must be a non-empty string');
66
- else if (!stateIds.has(transition.from))
67
- bad(path + '.from', 'unknown state ' + transition.from);
68
- if (typeof transition.event !== 'string' || transition.event.length === 0)
69
- bad(path + '.event', 'must be a non-empty string');
70
- if (typeof transition.to !== 'string' || transition.to.length === 0)
71
- bad(path + '.to', 'must be a non-empty string');
72
- else if (!stateIds.has(transition.to))
73
- bad(path + '.to', 'unknown state ' + transition.to);
74
- if (transition.guard !== undefined)
75
- validateGuard(transition.guard, path + '.guard', errors, bad);
76
- if (transition.updates !== undefined) {
77
- if (!Array.isArray(transition.updates))
78
- bad(path + '.updates', 'must be an array');
79
- else
80
- transition.updates.forEach((update, updateIndex) => {
81
- const updatePath = path + '.updates[' + updateIndex + ']';
82
- if (typeof update !== 'object' || update === null || Array.isArray(update)) {
83
- bad(updatePath, 'must be an object');
84
- return;
85
- }
86
- const record = update;
87
- if (typeof record.variable !== 'string' || record.variable.length === 0)
88
- bad(updatePath + '.variable', 'must be a non-empty string');
89
- if (record.op !== 'set' && record.op !== 'inc' && record.op !== 'dec')
90
- bad(updatePath + '.op', "must be 'set', 'inc', or 'dec'");
91
- if (record.value !== undefined && typeof record.value !== 'number')
92
- bad(updatePath + '.value', 'must be a number');
93
- });
94
- }
95
- });
96
- }
97
- const variableNames = new Set();
98
- if (root.variables !== undefined) {
99
- if (!Array.isArray(root.variables))
100
- bad('variables', 'must be an array');
101
- else
102
- root.variables.forEach((entry, index) => {
103
- const path = 'variables[' + index + ']';
104
- if (typeof entry !== 'object' || entry === null || Array.isArray(entry)) {
105
- bad(path, 'must be an object');
106
- return;
107
- }
108
- const variable = entry;
109
- if (typeof variable.name !== 'string' || variable.name.length === 0)
110
- bad(path + '.name', 'must be a non-empty string');
111
- else if (variableNames.has(variable.name))
112
- bad(path + '.name', 'duplicate variable ' + variable.name);
113
- else
114
- variableNames.add(variable.name);
115
- if (variable.kind !== 'integer' && variable.kind !== 'boolean')
116
- bad(path + '.kind', "must be 'integer' or 'boolean'");
117
- const expected = variable.kind === 'boolean' ? 'boolean' : 'number';
118
- if (typeof variable.init !== expected)
119
- bad(path + '.init', 'must be a ' + expected);
120
- if (variable.min !== undefined && typeof variable.min !== 'number')
121
- bad(path + '.min', 'must be a number');
122
- if (variable.max !== undefined && typeof variable.max !== 'number')
123
- bad(path + '.max', 'must be a number');
124
- if (typeof variable.min === 'number' && typeof variable.max === 'number' && variable.min > variable.max)
125
- bad(path + '.max', 'must be >= min');
126
- if (variable.monotonic !== undefined && variable.monotonic !== 'inc' && variable.monotonic !== 'dec')
127
- bad(path + '.monotonic', "must be 'inc' or 'dec'");
128
- if (variable.kind === 'integer' && typeof variable.init === 'number') {
129
- if (typeof variable.min === 'number' && variable.init < variable.min)
130
- bad(path + '.init', 'must be >= min');
131
- if (typeof variable.max === 'number' && variable.init > variable.max)
132
- bad(path + '.init', 'must be <= max');
133
- }
134
- });
135
- }
136
- const validateVariableRef = (name, path) => {
137
- if (typeof name !== 'string' || name.length === 0)
138
- bad(path, 'must be a non-empty string');
139
- else if (!variableNames.has(name))
140
- bad(path, 'references unknown variable ' + name);
141
- };
142
- if (root.invariants !== undefined) {
143
- if (!Array.isArray(root.invariants))
144
- bad('invariants', 'must be an array');
145
- else
146
- root.invariants.forEach((entry, index) => {
147
- const path = 'invariants[' + index + ']';
148
- if (typeof entry !== 'object' || entry === null || Array.isArray(entry)) {
149
- bad(path, 'must be an object');
150
- return;
151
- }
152
- const invariant = entry;
153
- if (typeof invariant.id !== 'string' || invariant.id.length === 0)
154
- bad(path + '.id', 'must be a non-empty string');
155
- if (typeof invariant.description !== 'string')
156
- bad(path + '.description', 'must be a string');
157
- if (invariant.kind === 'never-states') {
158
- if (!Array.isArray(invariant.states) || invariant.states.length === 0)
159
- bad(path + '.states', 'must be a non-empty array');
160
- else
161
- invariant.states.forEach((state, stateIndex) => {
162
- if (typeof state !== 'string' || state.length === 0)
163
- bad(path + '.states[' + stateIndex + ']', 'must be a non-empty string');
164
- });
165
- }
166
- else if (invariant.kind === 'var-in-range') {
167
- validateVariableRef(invariant.variable, path + '.variable');
168
- if (invariant.min !== undefined && typeof invariant.min !== 'number')
169
- bad(path + '.min', 'must be a number');
170
- if (invariant.max !== undefined && typeof invariant.max !== 'number')
171
- bad(path + '.max', 'must be a number');
172
- }
173
- else if (invariant.kind === 'event-before-state') {
174
- if (typeof invariant.event !== 'string' || invariant.event.length === 0)
175
- bad(path + '.event', 'must be a non-empty string');
176
- if (typeof invariant.state !== 'string' || invariant.state.length === 0)
177
- bad(path + '.state', 'must be a non-empty string');
178
- }
179
- else if (invariant.kind === 'leads-to') {
180
- if (typeof invariant.from !== 'string' || invariant.from.length === 0)
181
- bad(path + '.from', 'must be a non-empty string');
182
- if (typeof invariant.to !== 'string' || invariant.to.length === 0)
183
- bad(path + '.to', 'must be a non-empty string');
184
- }
185
- else if (invariant.kind === 'sequence') {
186
- if (!Array.isArray(invariant.events) || invariant.events.length === 0)
187
- bad(path + '.events', 'must be a non-empty array');
188
- else
189
- invariant.events.forEach((event, eventIndex) => {
190
- if (typeof event !== 'string' || event.length === 0)
191
- bad(path + '.events[' + eventIndex + ']', 'must be a non-empty string');
192
- });
193
- }
194
- else if (invariant.kind === 'atomicity') {
195
- if (!Array.isArray(invariant.events) || invariant.events.length === 0)
196
- bad(path + '.events', 'must be a non-empty array');
197
- else
198
- invariant.events.forEach((event, eventIndex) => {
199
- if (typeof event !== 'string' || event.length === 0)
200
- bad(path + '.events[' + eventIndex + ']', 'must be a non-empty string');
201
- });
202
- if (typeof invariant.commit !== 'string' || invariant.commit.length === 0)
203
- bad(path + '.commit', 'must be a non-empty string');
204
- if (invariant.rollback !== undefined && typeof invariant.rollback !== 'string')
205
- bad(path + '.rollback', 'must be a string');
206
- }
207
- else {
208
- bad(path + '.kind', 'unknown invariant kind');
209
- }
210
- });
211
- }
212
- if (root.concurrentPairs !== undefined) {
213
- if (!Array.isArray(root.concurrentPairs))
214
- bad('concurrentPairs', 'must be an array');
215
- else
216
- root.concurrentPairs.forEach((entry, index) => {
217
- const path = 'concurrentPairs[' + index + ']';
218
- if (!Array.isArray(entry) || entry.length !== 2 || typeof entry[0] !== 'string' || typeof entry[1] !== 'string') {
219
- bad(path, 'must be a [event, event] string pair');
220
- }
221
- });
222
- }
223
- if (root.boundaryChecks !== undefined) {
224
- if (!Array.isArray(root.boundaryChecks))
225
- bad('boundaryChecks', 'must be an array');
226
- else
227
- root.boundaryChecks.forEach((entry, index) => {
228
- const path = 'boundaryChecks[' + index + ']';
229
- if (typeof entry !== 'object' || entry === null || Array.isArray(entry)) {
230
- bad(path, 'must be an object');
231
- return;
232
- }
233
- const check = entry;
234
- validateVariableRef(check.variable, path + '.variable');
235
- if (!Array.isArray(check.values) || check.values.some((value) => typeof value !== 'number'))
236
- bad(path + '.values', 'must be an array of numbers');
237
- });
238
- }
239
- if (root.idempotentEvents !== undefined) {
240
- if (!Array.isArray(root.idempotentEvents))
241
- bad('idempotentEvents', 'must be an array');
242
- else
243
- root.idempotentEvents.forEach((entry, index) => {
244
- if (typeof entry !== 'string' || entry.length === 0)
245
- bad('idempotentEvents[' + index + ']', 'must be a non-empty string');
246
- });
247
- }
248
- if (root.resourcePairs !== undefined) {
249
- if (!Array.isArray(root.resourcePairs))
250
- bad('resourcePairs', 'must be an array');
251
- else
252
- root.resourcePairs.forEach((entry, index) => {
253
- const path = 'resourcePairs[' + index + ']';
254
- if (typeof entry !== 'object' || entry === null || Array.isArray(entry)) {
255
- bad(path, 'must be an object');
256
- return;
257
- }
258
- const pair = entry;
259
- if (typeof pair.resource !== 'string' || pair.resource.length === 0)
260
- bad(path + '.resource', 'must be a non-empty string');
261
- if (typeof pair.acquireEvent !== 'string' || pair.acquireEvent.length === 0)
262
- bad(path + '.acquireEvent', 'must be a non-empty string');
263
- if (typeof pair.releaseEvent !== 'string' || pair.releaseEvent.length === 0)
264
- bad(path + '.releaseEvent', 'must be a non-empty string');
265
- if (pair.failEvent !== undefined && typeof pair.failEvent !== 'string')
266
- bad(path + '.failEvent', 'must be a string');
267
- });
268
- }
269
- // Guard/update variable references were validated structurally; re-walk for references.
270
- if (Array.isArray(root.transitions)) {
271
- for (const entry of root.transitions) {
272
- walkGuardReferences(entry.guard, variableNames, errors, bad);
273
- for (const update of entry.updates ?? []) {
274
- if (!variableNames.has(update.variable))
275
- bad('transitions.updates', 'references unknown variable ' + update.variable);
276
- if (update.op !== 'set' && update.value !== undefined && update.value === 0) {
277
- // zero delta is harmless; no finding
278
- }
279
- }
280
- }
281
- }
282
- if (errors.length > 0)
283
- return { ok: false, errors };
284
- return { ok: true, model: root };
285
- }
286
- function validateGuard(input, path, errors, bad) {
287
- if (typeof input !== 'object' || input === null || Array.isArray(input)) {
288
- bad(path, 'must be an object');
289
- return;
290
- }
291
- const guard = input;
292
- if (guard.variable !== undefined) {
293
- if (typeof guard.variable !== 'string' || guard.variable.length === 0)
294
- bad(path + '.variable', 'must be a non-empty string');
295
- if (guard.op !== '==' && guard.op !== '!=' && guard.op !== '<' && guard.op !== '<=' && guard.op !== '>' && guard.op !== '>=')
296
- bad(path + '.op', 'must be a comparison operator');
297
- if (typeof guard.value !== 'number' && typeof guard.value !== 'boolean')
298
- bad(path + '.value', 'must be a number or boolean');
299
- return;
300
- }
301
- if (guard.all !== undefined) {
302
- if (!Array.isArray(guard.all))
303
- bad(path + '.all', 'must be an array');
304
- else
305
- guard.all.forEach((child, index) => validateGuard(child, path + '.all[' + index + ']', errors, bad));
306
- return;
307
- }
308
- if (guard.any !== undefined) {
309
- if (!Array.isArray(guard.any))
310
- bad(path + '.any', 'must be an array');
311
- else
312
- guard.any.forEach((child, index) => validateGuard(child, path + '.any[' + index + ']', errors, bad));
313
- return;
314
- }
315
- if (guard.not !== undefined) {
316
- validateGuard(guard.not, path + '.not', errors, bad);
317
- return;
318
- }
319
- bad(path, 'must be a leaf ({ variable, op, value }), { all }, { any }, or { not }');
320
- }
321
- function walkGuardReferences(guard, variableNames, errors, bad) {
322
- if (guard === undefined)
323
- return;
324
- if ('variable' in guard) {
325
- if (!variableNames.has(guard.variable))
326
- bad('guard', 'references unknown variable ' + guard.variable);
327
- return;
328
- }
329
- if ('all' in guard) {
330
- for (const child of guard.all)
331
- walkGuardReferences(child, variableNames, errors, bad);
332
- return;
333
- }
334
- if ('any' in guard) {
335
- for (const child of guard.any)
336
- walkGuardReferences(child, variableNames, errors, bad);
337
- return;
338
- }
339
- if ('not' in guard)
340
- walkGuardReferences(guard.not, variableNames, errors, bad);
341
- }
342
- // ---------------------------------------------------------------------------
343
- // execution
344
- // ---------------------------------------------------------------------------
345
- function isLeafGuard(guard) {
346
- return 'variable' in guard;
347
- }
348
- export function guardVariables(guard) {
349
- if (guard === undefined)
350
- return [];
351
- if (isLeafGuard(guard))
352
- return [guard.variable];
353
- if ('all' in guard)
354
- return guard.all.flatMap((child) => guardVariables(child));
355
- if ('any' in guard)
356
- return guard.any.flatMap((child) => guardVariables(child));
357
- if ('not' in guard)
358
- return guardVariables(guard.not);
359
- return [];
360
- }
361
- function evalGuard(guard, vars) {
362
- if (isLeafGuard(guard)) {
363
- const actual = vars[guard.variable];
364
- switch (guard.op) {
365
- case '==': return actual === guard.value;
366
- case '!=': return actual !== guard.value;
367
- case '<': return actual < guard.value;
368
- case '<=': return actual <= guard.value;
369
- case '>': return actual > guard.value;
370
- case '>=': return actual >= guard.value;
371
- }
372
- }
373
- if ('all' in guard)
374
- return guard.all.every((child) => evalGuard(child, vars));
375
- if ('any' in guard)
376
- return guard.any.some((child) => evalGuard(child, vars));
377
- if ('not' in guard)
378
- return !evalGuard(guard.not, vars);
379
- return false;
380
- }
381
- function initialState(model) {
382
- const vars = {};
383
- for (const variable of model.variables ?? [])
384
- vars[variable.name] = variable.init;
385
- return { state: model.init, vars };
386
- }
387
- function runtimeKey(runtime) {
388
- return runtime.state + '|' + stableStringify(runtime.vars);
389
- }
390
- function applyUpdates(model, transition, runtime) {
391
- const vars = { ...runtime.vars };
392
- for (const update of transition.updates ?? []) {
393
- const current = vars[update.variable];
394
- if (update.op === 'set')
395
- vars[update.variable] = update.value ?? 0;
396
- else if (update.op === 'inc')
397
- vars[update.variable] = ((typeof current === 'number' ? current : 0) + (update.value ?? 1));
398
- else
399
- vars[update.variable] = ((typeof current === 'number' ? current : 0) - (update.value ?? 1));
400
- }
401
- return { state: transition.to, vars };
402
- }
403
- function groupTransitions(model) {
404
- const groups = new Map();
405
- for (const transition of model.transitions) {
406
- const key = transition.from + '|' + transition.event;
407
- const list = groups.get(key) ?? [];
408
- list.push(transition);
409
- groups.set(key, list);
410
- }
411
- return groups;
412
- }
413
- function applicableTransitions(group, runtime) {
414
- const guarded = [];
415
- const unguarded = [];
416
- for (const transition of group) {
417
- if (transition.guard === undefined)
418
- unguarded.push(transition);
419
- else
420
- guarded.push(transition);
421
- }
422
- const matched = guarded.filter((transition) => evalGuard(transition.guard, runtime.vars));
423
- if (matched.length > 0)
424
- return matched;
425
- return unguarded;
426
- }
427
- function stepRuntime(model, runtime, event) {
428
- const group = groupTransitions(model).get(runtime.state + '|' + event);
429
- if (group === undefined || group.length === 0)
430
- return [];
431
- const seen = new Set();
432
- const outcomes = [];
433
- for (const transition of applicableTransitions(group, runtime)) {
434
- const next = applyUpdates(model, transition, runtime);
435
- const key = runtimeKey(next);
436
- if (!seen.has(key)) {
437
- seen.add(key);
438
- outcomes.push(next);
439
- }
440
- }
441
- return outcomes;
442
- }
443
- function explore(model, options) {
444
- const init = initialState(model);
445
- const reachable = [];
446
- const reachableKeys = new Set();
447
- const queue = [init];
448
- let truncated = false;
449
- while (queue.length > 0) {
450
- const runtime = queue.shift();
451
- const key = runtimeKey(runtime);
452
- if (reachableKeys.has(key))
453
- continue;
454
- reachableKeys.add(key);
455
- reachable.push(runtime);
456
- if (reachable.length > options.maxStates) {
457
- truncated = true;
458
- break;
459
- }
460
- for (const event of allEvents(model)) {
461
- for (const next of stepRuntime(model, runtime, event)) {
462
- if (!reachableKeys.has(runtimeKey(next)))
463
- queue.push(next);
464
- }
465
- }
466
- }
467
- return { reachable, reachableKeys, truncated, initialState: init };
468
- }
469
- function allEvents(model) {
470
- return [...new Set(model.transitions.map((transition) => transition.event))].sort();
471
- }
472
- function stateById(model, id) {
473
- return model.states.find((state) => state.id === id);
474
- }
475
- function isTerminal(model, state) {
476
- return stateById(model, state)?.terminal === true;
477
- }
478
- function uniqueTargets(transitions) {
479
- return [...new Set(transitions.map((transition) => transition.to))];
480
- }
481
- function checkResult(id, name, findings, detail) {
482
- const errors = findings.filter((finding) => finding.severity === 'error').length;
483
- const warnings = findings.filter((finding) => finding.severity === 'warning').length;
484
- return {
485
- id,
486
- name,
487
- status: findings.length === 0 ? 'pass' : 'fail',
488
- detail: detail + (errors > 0 ? ' (' + errors + ' errors' + (warnings > 0 ? ', ' + warnings + ' warnings' : '') + ')' : warnings > 0 ? ' (' + warnings + ' warnings)' : ''),
489
- findings,
490
- };
491
- }
492
- // ---------------------------------------------------------------------------
493
- // S1-S7
494
- // ---------------------------------------------------------------------------
495
- function S1_reachability(model, exploration) {
496
- const reached = new Set(exploration.reachable.map((runtime) => runtime.state));
497
- const unreachable = model.states.filter((state) => !reached.has(state.id)).map((state) => state.id);
498
- const findings = unreachable.map((state) => ({
499
- code: 'S1_UNREACHABLE_STATE',
500
- severity: 'warning',
501
- message: 'State ' + state + ' is not reachable from init.',
502
- }));
503
- return checkResult('S1', 'Reachability', findings, unreachable.length === 0 ? 'All states reachable' : 'Unreachable states: ' + unreachable.join(', '));
504
- }
505
- function S2_deadlock(model) {
506
- const outgoing = new Set(model.transitions.map((transition) => transition.from));
507
- const findings = [];
508
- for (const state of model.states) {
509
- if (state.terminal === true)
510
- continue;
511
- if (!outgoing.has(state.id)) {
512
- findings.push({
513
- code: 'S2_NO_TRANSITIONS',
514
- severity: 'error',
515
- message: 'Non-terminal state ' + state.id + ' has no outgoing transitions.',
516
- });
517
- }
518
- }
519
- return checkResult('S2', 'Deadlock', findings, findings.length === 0 ? 'No deadlocks' : 'Deadlocks: ' + findings.map((finding) => finding.message).join('; '));
520
- }
521
- function sccs(model) {
522
- const states = model.states.map((state) => state.id);
523
- const edges = new Map();
524
- for (const state of states)
525
- edges.set(state, []);
526
- for (const transition of model.transitions) {
527
- const list = edges.get(transition.from);
528
- if (list !== undefined)
529
- list.push(transition.to);
530
- }
531
- let index = 0;
532
- const indices = new Map();
533
- const low = new Map();
534
- const onStack = new Set();
535
- const stack = [];
536
- const components = [];
537
- const visit = (node) => {
538
- indices.set(node, index);
539
- low.set(node, index);
540
- index += 1;
541
- stack.push(node);
542
- onStack.add(node);
543
- for (const next of edges.get(node) ?? []) {
544
- if (!indices.has(next)) {
545
- visit(next);
546
- low.set(node, Math.min(low.get(node), low.get(next)));
547
- }
548
- else if (onStack.has(next)) {
549
- low.set(node, Math.min(low.get(node), indices.get(next)));
550
- }
551
- }
552
- if (low.get(node) === indices.get(node)) {
553
- const component = [];
554
- while (stack.length > 0) {
555
- const member = stack.pop();
556
- onStack.delete(member);
557
- component.push(member);
558
- if (member === node)
559
- break;
560
- }
561
- components.push(component);
562
- }
563
- };
564
- for (const state of states) {
565
- if (!indices.has(state))
566
- visit(state);
567
- }
568
- return components;
569
- }
570
- function S3_liveness(model) {
571
- const components = sccs(model);
572
- const findings = [];
573
- for (const component of components) {
574
- const componentSet = new Set(component);
575
- const internalEdges = model.transitions.filter((transition) => componentSet.has(transition.from) && componentSet.has(transition.to));
576
- const escapingEdges = model.transitions.filter((transition) => componentSet.has(transition.from) && !componentSet.has(transition.to));
577
- if (internalEdges.length === 0 || escapingEdges.length > 0)
578
- continue;
579
- if (component.some((state) => isTerminal(model, state)))
580
- continue;
581
- findings.push({
582
- code: 'S3_CLOSED_SCC',
583
- severity: 'error',
584
- message: 'Closed SCC has no exit and contains no terminal state: ' + component.sort().join(', '),
585
- evidence: { states: component.sort(), transitions: internalEdges.length },
586
- });
587
- }
588
- return checkResult('S3', 'Liveness', findings, findings.length === 0 ? 'No harmful closed SCCs' : 'Closed SCCs: ' + findings.length);
589
- }
590
- function assignmentsFor(model, variables) {
591
- const specs = (model.variables ?? []).filter((variable) => variables.includes(variable.name));
592
- let combinations = [{}];
593
- for (const spec of specs) {
594
- let values;
595
- if (spec.kind === 'boolean')
596
- values = [false, true];
597
- else {
598
- const constants = collectGuardConstants(model).filter((value) => guardLeaves(model).some((leaf) => leaf.variable === spec.name && typeof leaf.value === 'number' && leaf.value === value));
599
- if (spec.min !== undefined && spec.max !== undefined) {
600
- values = [];
601
- for (let value = spec.min; value <= spec.max && value <= spec.min + 200; value++)
602
- values.push(value);
603
- }
604
- else {
605
- const set = new Set([-1, 0, 1, ...constants]);
606
- values = [...set].sort((a, b) => a - b);
607
- }
608
- }
609
- const next = [];
610
- for (const assignment of combinations) {
611
- for (const value of values) {
612
- next.push({ ...assignment, [spec.name]: value });
613
- if (next.length > 10_000)
614
- return null;
615
- }
616
- }
617
- combinations = next;
618
- }
619
- return combinations;
620
- }
621
- function guardLeaves(model) {
622
- const leaves = [];
623
- const visit = (guard) => {
624
- if ('variable' in guard)
625
- leaves.push(guard);
626
- else if ('all' in guard)
627
- guard.all.forEach(visit);
628
- else if ('any' in guard)
629
- guard.any.forEach(visit);
630
- else if ('not' in guard)
631
- visit(guard.not);
632
- };
633
- for (const transition of model.transitions)
634
- if (transition.guard !== undefined)
635
- visit(transition.guard);
636
- return leaves;
637
- }
638
- function collectGuardConstants(model) {
639
- return guardLeaves(model).filter((leaf) => typeof leaf.value === 'number').map((leaf) => leaf.value);
640
- }
641
- function analyzeGuards(model) {
642
- const determinism = [];
643
- const completeness = [];
644
- let truncated = false;
645
- const groups = groupTransitions(model);
646
- for (const [key, group] of groups) {
647
- const [from, event] = key.split('|');
648
- const unguarded = group.filter((transition) => transition.guard === undefined);
649
- const guarded = group.filter((transition) => transition.guard !== undefined);
650
- if (unguarded.length > 1) {
651
- determinism.push({
652
- code: 'S4_AMBIGUOUS_DEFAULT',
653
- severity: 'error',
654
- message: from + ' + ' + event + ' has multiple unconditional transitions: ' + uniqueTargets(unguarded).join(', '),
655
- });
656
- }
657
- if (guarded.length === 0)
658
- continue;
659
- const variables = [...new Set(group.flatMap((transition) => guardVariables(transition.guard)))];
660
- const assignments = assignmentsFor(model, variables);
661
- if (assignments === null) {
662
- completeness.push({ code: 'S6_UNBOUNDED_DOMAIN', severity: 'warning', message: from + ' + ' + event + ': guard domain too large to enumerate; exhaustive check skipped.' });
663
- truncated = true;
664
- continue;
665
- }
666
- const targets = uniqueTargets(group);
667
- for (const assignment of assignments) {
668
- const trueBranches = guarded.filter((transition) => evalGuard(transition.guard, assignment));
669
- if (trueBranches.length > 1) {
670
- determinism.push({
671
- code: 'S4_NONDETERMINISTIC_GUARDS',
672
- severity: 'error',
673
- message: from + ' + ' + event + ' has ' + trueBranches.length + ' simultaneously true guards for assignment ' + stableStringify(assignment) + ': ' + uniqueTargets(trueBranches).join(', '),
674
- evidence: { assignment },
675
- });
676
- }
677
- if (trueBranches.length === 0 && unguarded.length === 0) {
678
- completeness.push({
679
- code: 'S6_INCOMPLETE_GUARD',
680
- severity: 'error',
681
- message: from + ' + ' + event + ' has no true guard and no default branch for assignment ' + stableStringify(assignment),
682
- evidence: { assignment, branches: targets },
683
- });
684
- }
685
- if (determinism.length + completeness.length > 200) {
686
- truncated = true;
687
- break;
688
- }
689
- }
690
- if (truncated)
691
- break;
692
- }
693
- return { determinism, completeness, truncated };
694
- }
695
- function S4_determinism(model) {
696
- const analysis = analyzeGuards(model);
697
- return checkResult('S4', 'Determinism', analysis.determinism, analysis.determinism.length === 0 ? 'Deterministic' : 'Nondeterminism findings: ' + analysis.determinism.length);
698
- }
699
- function S6_guardCompleteness(model) {
700
- const analysis = analyzeGuards(model);
701
- return checkResult('S6', 'Guard Completeness', analysis.completeness, analysis.completeness.length === 0 ? 'All guard branches defined' : 'Guard findings: ' + analysis.completeness.length);
702
- }
703
- function S5_eventCompleteness(model) {
704
- const events = allEvents(model);
705
- const findings = [];
706
- for (const state of model.states) {
707
- if (state.terminal === true)
708
- continue;
709
- const handled = new Set(model.transitions.filter((transition) => transition.from === state.id).map((transition) => transition.event));
710
- for (const event of events) {
711
- if (!handled.has(event)) {
712
- findings.push({
713
- code: 'S5_UNHANDLED_EVENT',
714
- severity: 'warning',
715
- message: state.id + ' silently ignores event ' + event,
716
- });
717
- }
718
- }
719
- }
720
- return checkResult('S5', 'Event Completeness', findings, findings.length === 0 ? 'All states handle all relevant events' : findings.length + ' unhandled (state, event) pairs');
721
- }
722
- function invariantHolds(invariant, runtime) {
723
- if (invariant.kind === 'never-states')
724
- return !invariant.states.includes(runtime.state);
725
- if (invariant.kind === 'var-in-range') {
726
- const value = runtime.vars[invariant.variable];
727
- if (typeof value !== 'number')
728
- return false;
729
- if (invariant.min !== undefined && value < invariant.min)
730
- return false;
731
- if (invariant.max !== undefined && value > invariant.max)
732
- return false;
733
- return true;
734
- }
735
- return true;
736
- }
737
- function shortestViolationForInvariant(model, options, invariant) {
738
- if (invariant.kind === 'event-before-state') {
739
- return shortestEventBeforeStateViolation(model, options, invariant);
740
- }
741
- const init = initialState(model);
742
- if (!invariantHolds(invariant, init)) {
743
- return { invariant, path: [], reason: 'Initial state violates the invariant.' };
744
- }
745
- const visited = new Set([runtimeKey(init)]);
746
- const queue = [{ runtime: init, path: [] }];
747
- let steps = 0;
748
- while (queue.length > 0) {
749
- const entry = queue.shift();
750
- if (++steps > options.maxStates)
751
- break;
752
- for (const event of allEvents(model)) {
753
- for (const next of stepRuntime(model, entry.runtime, event)) {
754
- const key = runtimeKey(next);
755
- if (visited.has(key))
756
- continue;
757
- const path = [...entry.path, { from: entry.runtime.state, event, to: next.state }];
758
- if (!invariantHolds(invariant, next)) {
759
- return { invariant, path, reason: 'Invariant violated after ' + path.length + ' events.' };
760
- }
761
- visited.add(key);
762
- queue.push({ runtime: next, path });
763
- }
764
- }
765
- }
766
- return undefined;
767
- }
768
- function shortestEventBeforeStateViolation(model, options, invariant) {
769
- const init = initialState(model);
770
- const seenInitially = false;
771
- if (init.state === invariant.state && !seenInitially) {
772
- return { invariant, path: [], reason: 'Target state ' + invariant.state + ' is initial and the required event ' + invariant.event + ' has not occurred.' };
773
- }
774
- const key = (runtime, seen) => runtimeKey(runtime) + '|' + (seen ? '1' : '0');
775
- const visited = new Set([key(init, false)]);
776
- const queue = [{ runtime: init, seen: false, path: [] }];
777
- let steps = 0;
778
- while (queue.length > 0) {
779
- const entry = queue.shift();
780
- if (++steps > options.maxStates)
781
- break;
782
- for (const event of allEvents(model)) {
783
- for (const next of stepRuntime(model, entry.runtime, event)) {
784
- const seen = entry.seen || event === invariant.event;
785
- const nextKey = key(next, seen);
786
- if (visited.has(nextKey))
787
- continue;
788
- const path = [...entry.path, { from: entry.runtime.state, event, to: next.state }];
789
- if (next.state === invariant.state && !seen) {
790
- return { invariant, path, reason: 'Target state ' + invariant.state + ' is reachable without event ' + invariant.event + ' in ' + path.length + ' steps.' };
791
- }
792
- visited.add(nextKey);
793
- queue.push({ runtime: next, seen, path });
794
- }
795
- }
796
- }
797
- return undefined;
798
- }
799
- function runInvariants(model, options) {
800
- const violations = [];
801
- for (const invariant of model.invariants ?? []) {
802
- const violation = shortestViolationForInvariant(model, options, invariant);
803
- if (violation !== undefined)
804
- violations.push(violation);
805
- }
806
- return violations;
807
- }
808
- function S7_invariants(model, options) {
809
- const violations = runInvariants(model, options);
810
- const findings = violations.map((violation) => ({
811
- code: 'S7_INVARIANT_VIOLATION',
812
- severity: 'error',
813
- message: 'Invariant "' + violation.invariant.id + '" (' + violation.invariant.description + ') violated: ' + violation.reason,
814
- path: violation.path,
815
- evidence: { invariant: violation.invariant },
816
- }));
817
- return checkResult('S7', 'Invariant Validity', findings, violations.length === 0 ? 'All invariants hold' : 'Invariant violations: ' + violations.length);
818
- }
819
- // ---------------------------------------------------------------------------
820
- // A1-A7
821
- // ---------------------------------------------------------------------------
822
- function A1_unexpectedEvents(model) {
823
- const events = allEvents(model);
824
- const findings = [];
825
- for (const state of model.states) {
826
- if (state.terminal === true)
827
- continue;
828
- const handled = new Set(model.transitions.filter((transition) => transition.from === state.id).map((transition) => transition.event));
829
- for (const event of events) {
830
- if (!handled.has(event)) {
831
- findings.push({
832
- code: 'A1_UNHANDLED_EVENT',
833
- severity: 'warning',
834
- message: 'Event ' + event + ' in state ' + state.id + ' has no defined transition (silent ignore).',
835
- });
836
- }
837
- }
838
- }
839
- return checkResult('A1', 'Unexpected Event Injection', findings, findings.length === 0 ? 'All event/state combinations defined' : findings.length + ' unhandled combinations');
840
- }
841
- function firstOutcome(runtime, outcomes) {
842
- return outcomes[0];
843
- }
844
- function A2_raceInterleaving(model, exploration) {
845
- const findings = [];
846
- for (const [e1, e2] of model.concurrentPairs ?? []) {
847
- for (const runtime of exploration.reachable) {
848
- const first = firstOutcome(runtime, stepRuntime(model, runtime, e1));
849
- const second = firstOutcome(runtime, stepRuntime(model, runtime, e2));
850
- if (first === undefined && second === undefined)
851
- continue;
852
- const final12 = first === undefined ? runtime : firstOutcome(first, stepRuntime(model, first, e2)) ?? first;
853
- const final21 = second === undefined ? runtime : firstOutcome(second, stepRuntime(model, second, e1)) ?? second;
854
- if (runtimeKey(final12) !== runtimeKey(final21)) {
855
- findings.push({
856
- code: 'A2_ORDER_DEPENDENT',
857
- severity: 'warning',
858
- message: 'Events ' + e1 + ' and ' + e2 + ' produce order-dependent outcomes from state ' + runtime.state,
859
- evidence: { e1ThenE2: final12, e2ThenE1: final21 },
860
- });
861
- }
862
- }
863
- }
864
- return checkResult('A2', 'Race Interleaving', findings, findings.length === 0 ? 'No race conditions detected' : 'Order-dependent outcomes: ' + findings.length);
865
- }
866
- function stepSequence(model, init, events) {
867
- let runtime = init;
868
- for (const event of events) {
869
- const next = firstOutcome(runtime, stepRuntime(model, runtime, event));
870
- if (next === undefined)
871
- continue;
872
- runtime = next;
873
- }
874
- return runtime;
875
- }
876
- function permutations(items) {
877
- if (items.length === 0)
878
- return [[]];
879
- const result = [];
880
- for (let index = 0; index < items.length; index++) {
881
- const rest = items.slice(0, index).concat(items.slice(index + 1));
882
- for (const suffix of permutations(rest))
883
- result.push([items[index], ...suffix]);
884
- }
885
- return result;
886
- }
887
- function A3_orderPermutation(model, options) {
888
- const events = allEvents(model).slice(0, options.maxPermutationEvents);
889
- if (events.length < 2)
890
- return checkResult('A3', 'Order Permutation', [], 'Fewer than 2 events — skipped');
891
- const init = initialState(model);
892
- const outcomes = new Map();
893
- for (const permutation of permutations(events)) {
894
- const final = stepSequence(model, init, permutation);
895
- const key = runtimeKey(final);
896
- const list = outcomes.get(key) ?? [];
897
- if (list.length < 3)
898
- list.push(permutation.join(','));
899
- outcomes.set(key, list);
900
- }
901
- if (outcomes.size > 1) {
902
- const examples = [...outcomes.entries()].map(([key, sequences]) => ({ final: key.split('|')[0], example: sequences[0] }));
903
- return checkResult('A3', 'Order Permutation', [{
904
- code: 'A3_ORDER_DEPENDENT',
905
- severity: 'warning',
906
- message: 'Same event set produces ' + outcomes.size + ' different outcomes depending on order.',
907
- evidence: { examples },
908
- }], 'Order-dependent outcomes: ' + outcomes.size);
909
- }
910
- return checkResult('A3', 'Order Permutation', [], 'Order-independent (sampled first ' + events.length + ' events)');
911
- }
912
- function A4_pairSymmetry(model) {
913
- const findings = [];
914
- const transitionEvents = new Set(model.transitions.map((transition) => transition.event));
915
- for (const pair of model.resourcePairs ?? []) {
916
- const acquireTransitions = model.transitions.filter((transition) => transition.event === pair.acquireEvent);
917
- const releaseExists = transitionEvents.has(pair.releaseEvent);
918
- if (acquireTransitions.length === 0 && !releaseExists)
919
- continue;
920
- if (acquireTransitions.length > 0 && !releaseExists) {
921
- findings.push({
922
- code: 'A4_NO_RELEASE_EVENT',
923
- severity: 'error',
924
- message: 'Resource "' + pair.resource + '": acquire event ' + pair.acquireEvent + ' exists but release event ' + pair.releaseEvent + ' is never defined.',
925
- });
926
- continue;
927
- }
928
- for (const acquire of acquireTransitions) {
929
- // Is any release event reachable in the state graph from the acquired state?
930
- const reachable = stateGraphReachable(model, acquire.to);
931
- const releaseReachable = [...reachable].some((state) => model.transitions.some((transition) => transition.from === state && transition.event === pair.releaseEvent));
932
- if (!releaseReachable) {
933
- findings.push({
934
- code: 'A4_NO_RELEASE_REACHABLE',
935
- severity: 'error',
936
- message: 'Resource "' + pair.resource + '": after ' + pair.acquireEvent + ' into ' + acquire.to + ', no ' + pair.releaseEvent + ' transition is reachable.',
937
- evidence: { acquireTransition: acquire },
938
- });
939
- continue;
940
- }
941
- // Path-sensitive probe: track the held flag along state-graph paths.
942
- const edges = stateGraphEdges(model);
943
- const visited = new Set();
944
- const queue = [{ state: acquire.to, held: true, path: [] }];
945
- let steps = 0;
946
- while (queue.length > 0) {
947
- const entry = queue.shift();
948
- if (++steps > 1000)
949
- break;
950
- const key = entry.state + '|' + (entry.held ? '1' : '0');
951
- if (visited.has(key))
952
- continue;
953
- visited.add(key);
954
- if (entry.held && isTerminal(model, entry.state)) {
955
- findings.push({
956
- code: 'A4_TERMINAL_WITH_RESOURCE',
957
- severity: 'error',
958
- message: 'Resource "' + pair.resource + '" is still held when entering terminal state ' + entry.state + '.',
959
- path: entry.path,
960
- });
961
- continue;
962
- }
963
- for (const transition of edges.get(entry.state) ?? []) {
964
- let held = entry.held;
965
- if (transition.event === pair.releaseEvent)
966
- held = false;
967
- else if (transition.event === pair.acquireEvent) {
968
- if (held) {
969
- findings.push({
970
- code: 'A4_REACQUIRE_WITHOUT_RELEASE',
971
- severity: 'warning',
972
- message: 'Resource "' + pair.resource + '" is acquired again in state ' + entry.state + ' before ' + pair.releaseEvent + '.',
973
- path: [...entry.path, { from: entry.state, event: transition.event, to: transition.to }],
974
- });
975
- continue;
976
- }
977
- held = true;
978
- }
979
- queue.push({ state: transition.to, held, path: [...entry.path, { from: entry.state, event: transition.event, to: transition.to }] });
980
- }
981
- }
982
- }
983
- }
984
- return checkResult('A4', 'Pair Symmetry', findings, findings.length === 0 ? 'All pairs balanced' : 'Asymmetric pairs: ' + findings.length);
985
- }
986
- function stateGraphEdges(model) {
987
- const edges = new Map();
988
- for (const state of model.states)
989
- edges.set(state.id, []);
990
- for (const transition of model.transitions)
991
- edges.get(transition.from)?.push(transition);
992
- return edges;
993
- }
994
- function stateGraphReachable(model, start) {
995
- const edges = new Map();
996
- for (const state of model.states)
997
- edges.set(state.id, []);
998
- for (const transition of model.transitions)
999
- edges.get(transition.from)?.push(transition.to);
1000
- const visited = new Set();
1001
- const queue = [start];
1002
- while (queue.length > 0) {
1003
- const current = queue.shift();
1004
- if (visited.has(current))
1005
- continue;
1006
- visited.add(current);
1007
- for (const next of edges.get(current) ?? [])
1008
- queue.push(next);
1009
- }
1010
- return visited;
1011
- }
1012
- function A5_boundaryBlast(model) {
1013
- const findings = [];
1014
- for (const check of model.boundaryChecks ?? []) {
1015
- const variable = (model.variables ?? []).find((entry) => entry.name === check.variable);
1016
- if (variable === undefined)
1017
- continue;
1018
- for (const value of check.values) {
1019
- if (variable.min !== undefined && value < variable.min) {
1020
- findings.push({ code: 'A5_OUT_OF_DOMAIN', severity: 'warning', message: 'Boundary value ' + value + ' for ' + check.variable + ' is below min ' + variable.min });
1021
- }
1022
- if (variable.max !== undefined && value > variable.max) {
1023
- findings.push({ code: 'A5_OUT_OF_DOMAIN', severity: 'warning', message: 'Boundary value ' + value + ' for ' + check.variable + ' is above max ' + variable.max });
1024
- }
1025
- const assignment = { ...(model.variables ?? []).reduce((result, entry) => { result[entry.name] = entry.init; return result; }, {}), [check.variable]: value };
1026
- for (const [key, group] of groupTransitions(model)) {
1027
- const [from, event] = key.split('|');
1028
- if (!group.some((transition) => guardVariables(transition.guard).includes(check.variable)))
1029
- continue;
1030
- const guarded = group.filter((transition) => transition.guard !== undefined);
1031
- const unguarded = group.filter((transition) => transition.guard === undefined);
1032
- const matched = guarded.filter((transition) => evalGuard(transition.guard, assignment));
1033
- if (matched.length === 0 && unguarded.length === 0) {
1034
- findings.push({
1035
- code: 'A5_GUARD_HOLE',
1036
- severity: 'warning',
1037
- message: from + ' + ' + event + ' has no branch for ' + check.variable + '=' + value,
1038
- evidence: { assignment },
1039
- });
1040
- }
1041
- if (matched.length > 1) {
1042
- findings.push({
1043
- code: 'A5_GUARD_OVERLAP',
1044
- severity: 'warning',
1045
- message: from + ' + ' + event + ' has ' + matched.length + ' true branches for ' + check.variable + '=' + value,
1046
- evidence: { assignment },
1047
- });
1048
- }
1049
- }
1050
- }
1051
- }
1052
- return checkResult('A5', 'Boundary Blast', findings, findings.length === 0 ? 'Boundary checks passed' : 'Boundary findings: ' + findings.length);
1053
- }
1054
- function A6_resourceInjection(model) {
1055
- const findings = [];
1056
- for (const pair of model.resourcePairs ?? []) {
1057
- if (pair.failEvent === undefined)
1058
- continue;
1059
- const acquireStates = new Set(model.transitions.filter((transition) => transition.event === pair.acquireEvent).map((transition) => transition.from));
1060
- for (const state of acquireStates) {
1061
- const handled = model.transitions.some((transition) => transition.from === state && transition.event === pair.failEvent);
1062
- if (!handled) {
1063
- findings.push({
1064
- code: 'A6_NO_FAILURE_HANDLER',
1065
- severity: 'warning',
1066
- message: 'State ' + state + ' can ' + pair.acquireEvent + ' for "' + pair.resource + '" but has no ' + pair.failEvent + ' transition.',
1067
- });
1068
- }
1069
- }
1070
- }
1071
- return checkResult('A6', 'Resource Injection', findings, findings.length === 0 ? 'No resource vulnerabilities detected' : 'Resource failure paths missing: ' + findings.length);
1072
- }
1073
- function A7_shortestViolations(model, options) {
1074
- const violations = runInvariants(model, options);
1075
- const findings = violations.map((violation) => ({
1076
- code: 'A7_SHORTEST_COUNTEREXAMPLE',
1077
- severity: 'warning',
1078
- message: 'Invariant "' + violation.invariant.id + '" shortest violating path length: ' + violation.path.length + (violation.path.length === 0 ? ' (initial state)' : ''),
1079
- path: violation.path,
1080
- evidence: { invariant: violation.invariant.id },
1081
- }));
1082
- return checkResult('A7', 'Minimal Counter-Example', findings, violations.length === 0 ? 'All invariants hold for all reachable paths' : 'Violated invariants: ' + findings.length);
1083
- }
1084
- function mapStateId(mapping, state) {
1085
- return mapping[state] ?? state;
1086
- }
1087
- function D1_behavioralPreservation(before, after, mapping) {
1088
- const findings = [];
1089
- const afterStates = new Set(after.states.map((state) => state.id));
1090
- const afterByFromEvent = new Map();
1091
- for (const transition of after.transitions) {
1092
- const key = transition.from + '|' + transition.event;
1093
- const set = afterByFromEvent.get(key) ?? new Set();
1094
- set.add(transition.to);
1095
- afterByFromEvent.set(key, set);
1096
- }
1097
- const beforeInitMapped = mapStateId(mapping, before.init);
1098
- if (beforeInitMapped !== after.init) {
1099
- findings.push({
1100
- code: 'D1_INIT_MISMATCH',
1101
- severity: 'warning',
1102
- message: 'Mapped BEFORE init ' + beforeInitMapped + ' does not match AFTER init ' + after.init + '.',
1103
- evidence: { beforeInit: before.init, mappedInit: beforeInitMapped, afterInit: after.init },
1104
- });
1105
- }
1106
- for (const state of before.states) {
1107
- const mapped = mapStateId(mapping, state.id);
1108
- if (!afterStates.has(mapped)) {
1109
- findings.push({
1110
- code: 'D1_MAPPED_STATE_MISSING',
1111
- severity: 'error',
1112
- message: 'BEFORE state ' + state.id + ' maps to ' + mapped + ', which is not declared in AFTER.',
1113
- evidence: { beforeState: state.id, mappedState: mapped },
1114
- });
1115
- continue;
1116
- }
1117
- for (const transition of before.transitions.filter((entry) => entry.from === state.id)) {
1118
- const key = mapped + '|' + transition.event;
1119
- const targets = afterByFromEvent.get(key);
1120
- if (targets === undefined || targets.size === 0) {
1121
- findings.push({
1122
- code: 'D1_EVENT_DISABLED',
1123
- severity: 'error',
1124
- message: 'BEFORE can fire event ' + transition.event + ' from ' + state.id + ' (mapped to ' + mapped + '), but AFTER has no transition for that (state, event).',
1125
- path: [{ from: state.id, event: transition.event, to: transition.to }],
1126
- evidence: { beforeState: state.id, mappedState: mapped, event: transition.event },
1127
- });
1128
- }
1129
- }
1130
- }
1131
- return checkResult('D1', 'Behavioral Preservation', findings, findings.length === 0 ? 'BEFORE event behavior is preserved in AFTER' : 'Behavioral preservation findings: ' + findings.length);
1132
- }
1133
- function mapInvariantForComparison(invariant, mapping) {
1134
- if (invariant.kind === 'never-states') {
1135
- return {
1136
- ...invariant,
1137
- id: invariant.id + ':before',
1138
- description: invariant.description + ' (from BEFORE)',
1139
- states: invariant.states.map((state) => mapStateId(mapping, state)),
1140
- };
1141
- }
1142
- if (invariant.kind === 'event-before-state') {
1143
- return {
1144
- ...invariant,
1145
- id: invariant.id + ':before',
1146
- description: invariant.description + ' (from BEFORE)',
1147
- state: mapStateId(mapping, invariant.state),
1148
- };
1149
- }
1150
- return { ...invariant, id: invariant.id + ':before', description: invariant.description + ' (from BEFORE)' };
1151
- }
1152
- function D2_invariantContinuity(before, after, options, mapping) {
1153
- const findings = [];
1154
- const afterStates = new Set(after.states.map((state) => state.id));
1155
- const afterVariables = new Set((after.variables ?? []).map((variable) => variable.name));
1156
- for (const invariant of before.invariants ?? []) {
1157
- const mapped = mapInvariantForComparison(invariant, mapping);
1158
- if (mapped.kind === 'never-states') {
1159
- for (const state of mapped.states) {
1160
- if (!afterStates.has(state)) {
1161
- findings.push({
1162
- code: 'D2_MAPPED_STATE_MISSING',
1163
- severity: 'warning',
1164
- message: 'BEFORE invariant "' + invariant.id + '" maps to state ' + state + ', which is not declared in AFTER.',
1165
- evidence: { invariant: invariant.id, state },
1166
- });
1167
- }
1168
- }
1169
- }
1170
- else if (mapped.kind === 'event-before-state') {
1171
- if (!afterStates.has(mapped.state)) {
1172
- findings.push({
1173
- code: 'D2_MAPPED_STATE_MISSING',
1174
- severity: 'warning',
1175
- message: 'BEFORE invariant "' + invariant.id + '" maps to state ' + mapped.state + ', which is not declared in AFTER.',
1176
- evidence: { invariant: invariant.id, state: mapped.state },
1177
- });
1178
- }
1179
- }
1180
- else if (mapped.kind === 'var-in-range') {
1181
- if (!afterVariables.has(mapped.variable)) {
1182
- findings.push({
1183
- code: 'D2_VARIABLE_MISSING',
1184
- severity: 'warning',
1185
- message: 'BEFORE invariant "' + invariant.id + '" references variable ' + mapped.variable + ', which is not declared in AFTER.',
1186
- evidence: { invariant: invariant.id, variable: mapped.variable },
1187
- });
1188
- continue;
1189
- }
1190
- }
1191
- const violation = shortestViolationForInvariant(after, options, mapped);
1192
- if (violation !== undefined) {
1193
- findings.push({
1194
- code: 'D2_INVARIANT_REGRESSION',
1195
- severity: 'error',
1196
- message: 'BEFORE invariant "' + invariant.id + '" no longer holds in AFTER: ' + violation.reason,
1197
- path: violation.path,
1198
- evidence: { beforeInvariant: invariant, afterInvariant: mapped },
1199
- });
1200
- }
1201
- }
1202
- return checkResult('D2', 'Invariant Continuity', findings, findings.length === 0 ? 'All BEFORE invariants continue to hold' : 'Invariant continuity findings: ' + findings.length);
1203
- }
1204
- function D3_regressionDelta(before, after, mapping) {
1205
- const afterStateIds = new Set(after.states.map((state) => state.id));
1206
- const beforeMappedIds = new Set(before.states.map((state) => mapStateId(mapping, state.id)));
1207
- const addedStates = after.states.filter((state) => !beforeMappedIds.has(state.id)).map((state) => state.id).sort();
1208
- const removedStates = before.states.filter((state) => !afterStateIds.has(mapStateId(mapping, state.id))).map((state) => state.id).sort();
1209
- const beforeEvents = new Set(before.transitions.map((transition) => transition.event));
1210
- const afterEvents = new Set(after.transitions.map((transition) => transition.event));
1211
- const addedEvents = [...afterEvents].filter((event) => !beforeEvents.has(event)).sort();
1212
- const removedEvents = [...beforeEvents].filter((event) => !afterEvents.has(event)).sort();
1213
- const removedTransitions = before.transitions.filter((transition) => !after.transitions.some((candidate) => candidate.from === mapStateId(mapping, transition.from) &&
1214
- candidate.event === transition.event &&
1215
- candidate.to === mapStateId(mapping, transition.to)));
1216
- const addedTransitions = after.transitions.filter((transition) => !before.transitions.some((candidate) => mapStateId(mapping, candidate.from) === transition.from &&
1217
- candidate.event === transition.event &&
1218
- mapStateId(mapping, candidate.to) === transition.to));
1219
- const findings = [];
1220
- for (const state of removedStates) {
1221
- findings.push({ code: 'D3_REMOVED_STATE', severity: 'warning', message: 'BEFORE state ' + state + ' is not present in AFTER under the given mapping.', evidence: { state } });
1222
- }
1223
- for (const event of removedEvents) {
1224
- findings.push({ code: 'D3_REMOVED_EVENT', severity: 'warning', message: 'BEFORE event ' + event + ' is not present in AFTER.', evidence: { event } });
1225
- }
1226
- for (const transition of removedTransitions) {
1227
- findings.push({
1228
- code: 'D3_REMOVED_TRANSITION',
1229
- severity: 'warning',
1230
- message: 'BEFORE transition ' + transition.from + ' -' + transition.event + '-> ' + transition.to + ' has no exact AFTER counterpart.',
1231
- evidence: { transition },
1232
- });
1233
- }
1234
- const detail = 'Delta: +' + addedStates.length + ' states, -' + removedStates.length + ' states, +' + addedEvents.length + ' events, -' + removedEvents.length + ' events, +' + addedTransitions.length + ' transitions, -' + removedTransitions.length + ' transitions';
1235
- return checkResult('D3', 'Regression Delta', findings, detail);
1236
- }
1237
- function deadlockStateIds(model) {
1238
- const outgoing = new Set(model.transitions.map((transition) => transition.from));
1239
- return model.states.filter((state) => state.terminal !== true && !outgoing.has(state.id)).map((state) => state.id);
1240
- }
1241
- function closedSccStateSets(model) {
1242
- return sccs(model)
1243
- .filter((component) => {
1244
- const componentSet = new Set(component);
1245
- const internalEdges = model.transitions.some((transition) => componentSet.has(transition.from) && componentSet.has(transition.to));
1246
- const escapingEdges = model.transitions.some((transition) => componentSet.has(transition.from) && !componentSet.has(transition.to));
1247
- return internalEdges && !escapingEdges && !component.some((state) => isTerminal(model, state));
1248
- })
1249
- .map((component) => component.sort());
1250
- }
1251
- function D4_deadlockLivenessRegression(before, after, mapping) {
1252
- const findings = [];
1253
- const beforeDeadlock = new Set(deadlockStateIds(before).map((state) => mapStateId(mapping, state)));
1254
- const afterDeadlock = deadlockStateIds(after);
1255
- for (const state of afterDeadlock) {
1256
- if (!beforeDeadlock.has(state)) {
1257
- findings.push({
1258
- code: 'D4_DEADLOCK_REGRESSION',
1259
- severity: 'error',
1260
- message: 'AFTER introduces deadlock in state ' + state + ' that was not deadlocked in BEFORE.',
1261
- evidence: { state },
1262
- });
1263
- }
1264
- }
1265
- const beforeScc = new Set(closedSccStateSets(before).map((component) => component.map((state) => mapStateId(mapping, state)).sort().join(',')));
1266
- const afterScc = closedSccStateSets(after);
1267
- for (const component of afterScc) {
1268
- const key = component.join(',');
1269
- if (!beforeScc.has(key)) {
1270
- findings.push({
1271
- code: 'D4_LIVENESS_REGRESSION',
1272
- severity: 'error',
1273
- message: 'AFTER introduces a closed SCC with no exit and no terminal state: ' + key,
1274
- evidence: { states: component },
1275
- });
1276
- }
1277
- }
1278
- return checkResult('D4', 'Deadlock/Liveness Regression', findings, findings.length === 0 ? 'No new deadlock or liveness regressions' : 'Regression findings: ' + findings.length);
1279
- }
1280
- function buildComparisonSummary(before, after, mapping) {
1281
- const afterStateIds = new Set(after.states.map((state) => state.id));
1282
- const beforeMappedIds = new Set(before.states.map((state) => mapStateId(mapping, state.id)));
1283
- const addedStates = after.states.filter((state) => !beforeMappedIds.has(state.id)).map((state) => state.id).sort();
1284
- const removedStates = before.states.filter((state) => !afterStateIds.has(mapStateId(mapping, state.id))).map((state) => state.id).sort();
1285
- const beforeEvents = new Set(before.transitions.map((transition) => transition.event));
1286
- const afterEvents = new Set(after.transitions.map((transition) => transition.event));
1287
- const addedEvents = [...afterEvents].filter((event) => !beforeEvents.has(event)).sort();
1288
- const removedEvents = [...beforeEvents].filter((event) => !afterEvents.has(event)).sort();
1289
- const removedTransitions = before.transitions.filter((transition) => !after.transitions.some((candidate) => candidate.from === mapStateId(mapping, transition.from) &&
1290
- candidate.event === transition.event &&
1291
- candidate.to === mapStateId(mapping, transition.to)));
1292
- const addedTransitions = after.transitions.filter((transition) => !before.transitions.some((candidate) => mapStateId(mapping, candidate.from) === transition.from &&
1293
- candidate.event === transition.event &&
1294
- mapStateId(mapping, candidate.to) === transition.to));
1295
- return {
1296
- beforeModelHash: modelHash(before),
1297
- afterModelHash: modelHash(after),
1298
- stateMapping: mapping,
1299
- beforeStates: before.states.length,
1300
- beforeTransitions: before.transitions.length,
1301
- afterStates: after.states.length,
1302
- afterTransitions: after.transitions.length,
1303
- addedStates,
1304
- removedStates,
1305
- addedEvents,
1306
- removedEvents,
1307
- addedTransitions,
1308
- removedTransitions,
1309
- };
1310
- }
1311
- function A8_idempotentReplay(model, exploration) {
1312
- const events = model.idempotentEvents ?? [];
1313
- const findings = [];
1314
- for (const event of events) {
1315
- for (const runtime of exploration.reachable) {
1316
- const onceOptions = stepRuntime(model, runtime, event);
1317
- if (onceOptions.length === 0)
1318
- continue;
1319
- for (const once of onceOptions) {
1320
- const twiceOptions = stepRuntime(model, once, event);
1321
- if (twiceOptions.length === 0) {
1322
- findings.push({
1323
- code: 'A8_NOT_REPLAYABLE',
1324
- severity: 'warning',
1325
- message: 'Idempotent event ' + event + ' is not replayable after first application from ' + runtime.state + '.',
1326
- path: [{ from: runtime.state, event, to: once.state }],
1327
- evidence: { state: runtime.state, event },
1328
- });
1329
- continue;
1330
- }
1331
- for (const twice of twiceOptions) {
1332
- if (runtimeKey(twice) !== runtimeKey(once)) {
1333
- findings.push({
1334
- code: 'A8_NOT_IDEMPOTENT',
1335
- severity: 'error',
1336
- message: 'Idempotent event ' + event + ' changes state when applied twice from ' + runtime.state + '.',
1337
- path: [{ from: runtime.state, event, to: once.state }, { from: once.state, event, to: twice.state }],
1338
- evidence: { state: runtime.state, event, afterOnce: once, afterTwice: twice },
1339
- });
1340
- break;
1341
- }
1342
- }
1343
- }
1344
- }
1345
- }
1346
- return checkResult('A8', 'Idempotent Replay', findings, findings.length === 0 ? 'Idempotent events are replay-safe' : 'Idempotent replay findings: ' + findings.length);
1347
- }
1348
- function S8_monotonicVariables(model) {
1349
- const findings = [];
1350
- for (const variable of model.variables ?? []) {
1351
- if (variable.monotonic === undefined)
1352
- continue;
1353
- for (const transition of model.transitions) {
1354
- for (const update of transition.updates ?? []) {
1355
- if (update.variable !== variable.name)
1356
- continue;
1357
- if (variable.monotonic === 'inc' && update.op === 'dec') {
1358
- findings.push({ code: 'S8_MONOTONIC_DECREASE', severity: 'error', message: 'Monotonic (inc) variable ' + variable.name + ' is decreased by ' + transition.event + '.', evidence: { variable: variable.name, transition } });
1359
- }
1360
- else if (variable.monotonic === 'dec' && update.op === 'inc') {
1361
- findings.push({ code: 'S8_MONOTONIC_INCREASE', severity: 'error', message: 'Monotonic (dec) variable ' + variable.name + ' is increased by ' + transition.event + '.', evidence: { variable: variable.name, transition } });
1362
- }
1363
- else if (update.op === 'set') {
1364
- findings.push({ code: 'S8_MONOTONIC_SET_REVIEW', severity: 'warning', message: 'Monotonic variable ' + variable.name + ' uses set in ' + transition.event + '; verify it cannot move backwards.', evidence: { variable: variable.name, transition } });
1365
- }
1366
- }
1367
- }
1368
- }
1369
- return checkResult('S8', 'Monotonic Variables', findings, findings.length === 0 ? 'Monotonic variables are respected' : 'Monotonic findings: ' + findings.length);
1370
- }
1371
- function findLeadsToBadPath(model, start, target) {
1372
- if (start.state === target)
1373
- return undefined;
1374
- const visited = new Set();
1375
- const queue = [{ runtime: start, path: [] }];
1376
- while (queue.length > 0) {
1377
- const entry = queue.shift();
1378
- const key = runtimeKey(entry.runtime);
1379
- if (entry.runtime.state === target)
1380
- continue;
1381
- if (visited.has(key))
1382
- return { path: entry.path, reason: 'Cycle avoids target ' + target };
1383
- visited.add(key);
1384
- const nexts = [];
1385
- for (const event of allEvents(model)) {
1386
- for (const next of stepRuntime(model, entry.runtime, event))
1387
- nexts.push({ next, event });
1388
- }
1389
- if (nexts.length === 0)
1390
- return { path: entry.path, reason: 'Dead end before target ' + target };
1391
- for (const { next, event } of nexts) {
1392
- queue.push({ runtime: next, path: [...entry.path, { from: entry.runtime.state, event, to: next.state }] });
1393
- }
1394
- }
1395
- return { path: [], reason: 'No path reaches target ' + target };
1396
- }
1397
- function A9_leadsTo(model, exploration) {
1398
- const findings = [];
1399
- for (const invariant of model.invariants ?? []) {
1400
- if (invariant.kind !== 'leads-to')
1401
- continue;
1402
- for (const runtime of exploration.reachable) {
1403
- if (runtime.state !== invariant.from)
1404
- continue;
1405
- const bad = findLeadsToBadPath(model, runtime, invariant.to);
1406
- if (bad !== undefined) {
1407
- findings.push({
1408
- code: 'A9_LEADS_TO_VIOLATION',
1409
- severity: 'error',
1410
- message: 'Leads-to invariant "' + invariant.id + '" violated from ' + invariant.from + ': ' + bad.reason,
1411
- path: bad.path,
1412
- evidence: { invariant },
1413
- });
1414
- break;
1415
- }
1416
- }
1417
- }
1418
- return checkResult('A9', 'Leads-To', findings, findings.length === 0 ? 'All leads-to invariants hold' : 'Leads-to findings: ' + findings.length);
1419
- }
1420
- function findSequenceViolation(model, options, invariant) {
1421
- const events = invariant.events;
1422
- const init = initialState(model);
1423
- const key = (runtime, progress) => runtimeKey(runtime) + '|' + progress;
1424
- const visited = new Set([key(init, 0)]);
1425
- const queue = [{ runtime: init, progress: 0, path: [] }];
1426
- let steps = 0;
1427
- while (queue.length > 0) {
1428
- const entry = queue.shift();
1429
- if (++steps > options.maxStates)
1430
- break;
1431
- for (const event of allEvents(model)) {
1432
- for (const next of stepRuntime(model, entry.runtime, event)) {
1433
- let progress = entry.progress;
1434
- let violation = false;
1435
- if (progress < events.length && event === events[progress]) {
1436
- progress += 1;
1437
- }
1438
- else {
1439
- const index = events.indexOf(event);
1440
- if (index > progress)
1441
- violation = true;
1442
- }
1443
- const path = [...entry.path, { from: entry.runtime.state, event, to: next.state }];
1444
- if (violation) {
1445
- return { invariant, path, reason: 'Event ' + event + ' occurred before ' + events[progress] };
1446
- }
1447
- const nextKey = key(next, progress);
1448
- if (!visited.has(nextKey)) {
1449
- visited.add(nextKey);
1450
- queue.push({ runtime: next, progress, path });
1451
- }
1452
- }
1453
- }
1454
- }
1455
- return undefined;
1456
- }
1457
- function A10_sequenceOrder(model, options) {
1458
- const findings = [];
1459
- for (const invariant of model.invariants ?? []) {
1460
- if (invariant.kind !== 'sequence')
1461
- continue;
1462
- const violation = findSequenceViolation(model, options, invariant);
1463
- if (violation !== undefined) {
1464
- findings.push({
1465
- code: 'A10_SEQUENCE_VIOLATION',
1466
- severity: 'error',
1467
- message: 'Sequence invariant "' + invariant.id + '" violated: ' + violation.reason,
1468
- path: violation.path,
1469
- evidence: { invariant },
1470
- });
1471
- }
1472
- }
1473
- return checkResult('A10', 'Sequence Order', findings, findings.length === 0 ? 'All sequence invariants hold' : 'Sequence findings: ' + findings.length);
1474
- }
1475
- function findAtomicityViolation(model, options, invariant) {
1476
- const atomic = new Set(invariant.events);
1477
- const init = initialState(model);
1478
- const key = (runtime, started, closed) => runtimeKey(runtime) + '|' + (started ? '1' : '0') + '|' + (closed ? '1' : '0');
1479
- const visited = new Set([key(init, false, false)]);
1480
- const queue = [{ runtime: init, started: false, closed: false, path: [] }];
1481
- let steps = 0;
1482
- while (queue.length > 0) {
1483
- const entry = queue.shift();
1484
- if (++steps > options.maxStates)
1485
- break;
1486
- for (const event of allEvents(model)) {
1487
- for (const next of stepRuntime(model, entry.runtime, event)) {
1488
- const started = entry.started || atomic.has(event);
1489
- const closed = entry.closed || event === invariant.commit || (invariant.rollback !== undefined && event === invariant.rollback);
1490
- const path = [...entry.path, { from: entry.runtime.state, event, to: next.state }];
1491
- if (entry.started && !entry.closed && !atomic.has(event) && event !== invariant.commit && event !== invariant.rollback) {
1492
- return { invariant, path, reason: 'Left atomic scope via ' + event + ' without commit/rollback' };
1493
- }
1494
- if (started && !closed && isTerminal(model, next.state)) {
1495
- return { invariant, path, reason: 'Terminal state reached with incomplete atomic group' };
1496
- }
1497
- const nextKey = key(next, started, closed);
1498
- if (!visited.has(nextKey)) {
1499
- visited.add(nextKey);
1500
- queue.push({ runtime: next, started, closed, path });
1501
- }
1502
- }
1503
- }
1504
- }
1505
- return undefined;
1506
- }
1507
- function A11_atomicity(model, options) {
1508
- const findings = [];
1509
- for (const invariant of model.invariants ?? []) {
1510
- if (invariant.kind !== 'atomicity')
1511
- continue;
1512
- const violation = findAtomicityViolation(model, options, invariant);
1513
- if (violation !== undefined) {
1514
- findings.push({
1515
- code: 'A11_ATOMICITY_VIOLATION',
1516
- severity: 'error',
1517
- message: 'Atomicity invariant "' + invariant.id + '" violated: ' + violation.reason,
1518
- path: violation.path,
1519
- evidence: { invariant },
1520
- });
1521
- }
1522
- }
1523
- return checkResult('A11', 'Atomicity', findings, findings.length === 0 ? 'All atomicity invariants hold' : 'Atomicity findings: ' + findings.length);
1524
- }
1525
- // ---------------------------------------------------------------------------
1526
- // main entry
1527
- // ---------------------------------------------------------------------------
1528
- export function runVerification(input, options = {}) {
1529
- const normalized = {
1530
- maxStates: options.maxStates ?? DEFAULT_MAX_STATES,
1531
- maxPermutationEvents: options.maxPermutationEvents ?? DEFAULT_MAX_PERMUTATION_EVENTS,
1532
- };
1533
- const validation = validateModel(input);
1534
- if (!validation.ok) {
1535
- return {
1536
- ok: false,
1537
- schemaVersion: 1,
1538
- modelHash: '',
1539
- summary: { states: 0, transitions: 0, errors: validation.errors.length, warnings: 0, checksRun: 0 },
1540
- checks: [{
1541
- id: 'MODEL',
1542
- name: 'Model Validation',
1543
- status: 'fail',
1544
- detail: 'Model schema validation failed: ' + validation.errors.length + ' errors',
1545
- findings: validation.errors.map((message) => ({ code: 'MODEL_INVALID', severity: 'error', message })),
1546
- }],
1547
- };
1548
- }
1549
- const model = validation.model;
1550
- const exploration = explore(model, normalized);
1551
- const checks = [
1552
- S1_reachability(model, exploration),
1553
- S2_deadlock(model),
1554
- S3_liveness(model),
1555
- S4_determinism(model),
1556
- S5_eventCompleteness(model),
1557
- S6_guardCompleteness(model),
1558
- S7_invariants(model, normalized),
1559
- S8_monotonicVariables(model),
1560
- A1_unexpectedEvents(model),
1561
- A2_raceInterleaving(model, exploration),
1562
- A3_orderPermutation(model, normalized),
1563
- A4_pairSymmetry(model),
1564
- A5_boundaryBlast(model),
1565
- A6_resourceInjection(model),
1566
- A7_shortestViolations(model, normalized),
1567
- A8_idempotentReplay(model, exploration),
1568
- A9_leadsTo(model, exploration),
1569
- A10_sequenceOrder(model, normalized),
1570
- A11_atomicity(model, normalized),
1571
- ];
1572
- let comparison;
1573
- if (options.beforeModel !== undefined) {
1574
- const beforeValidation = validateModel(options.beforeModel);
1575
- if (!beforeValidation.ok) {
1576
- return {
1577
- ok: false,
1578
- schemaVersion: 1,
1579
- modelHash: modelHash(model),
1580
- summary: {
1581
- states: model.states.length,
1582
- transitions: model.transitions.length,
1583
- errors: beforeValidation.errors.length,
1584
- warnings: 0,
1585
- checksRun: checks.length + 1,
1586
- truncated: exploration.truncated,
1587
- },
1588
- checks: [
1589
- ...checks,
1590
- {
1591
- id: 'BEFORE_MODEL',
1592
- name: 'Before Model Validation',
1593
- status: 'fail',
1594
- detail: 'Before model schema validation failed: ' + beforeValidation.errors.length + ' errors',
1595
- findings: beforeValidation.errors.map((message) => ({ code: 'BEFORE_MODEL_INVALID', severity: 'error', message })),
1596
- },
1597
- ],
1598
- };
1599
- }
1600
- const before = beforeValidation.model;
1601
- const mapping = options.stateMapping ?? {};
1602
- checks.push(D1_behavioralPreservation(before, model, mapping), D2_invariantContinuity(before, model, normalized, mapping), D3_regressionDelta(before, model, mapping), D4_deadlockLivenessRegression(before, model, mapping));
1603
- comparison = buildComparisonSummary(before, model, mapping);
1604
- }
1605
- const errors = checks.reduce((sum, check) => sum + check.findings.filter((finding) => finding.severity === 'error').length, 0);
1606
- const warnings = checks.reduce((sum, check) => sum + check.findings.filter((finding) => finding.severity === 'warning').length, 0);
1607
- return {
1608
- ok: true,
1609
- schemaVersion: 1,
1610
- modelHash: modelHash(model),
1611
- summary: {
1612
- states: model.states.length,
1613
- transitions: model.transitions.length,
1614
- errors,
1615
- warnings,
1616
- checksRun: checks.length,
1617
- truncated: exploration.truncated,
1618
- },
1619
- checks,
1620
- ...(comparison === undefined ? {} : { comparison }),
1621
- };
1622
- }
1
+ import { createHash } from 'node:crypto';
2
+ export const ENGINE_SCHEMA_VERSION = 1;
3
+ const DEFAULT_MAX_STATES = 10_000;
4
+ const DEFAULT_MAX_PERMUTATION_EVENTS = 5;
5
+ function stableStringify(value) {
6
+ if (value === null || typeof value !== 'object')
7
+ return JSON.stringify(value);
8
+ if (Array.isArray(value))
9
+ return '[' + value.map((item) => stableStringify(item)).join(',') + ']';
10
+ const record = value;
11
+ return '{' + Object.keys(record).sort().map((key) => JSON.stringify(key) + ':' + stableStringify(record[key])).join(',') + '}';
12
+ }
13
+ export function modelHash(model) {
14
+ return createHash('sha256').update(stableStringify(model)).digest('hex');
15
+ }
16
+ export function validateModel(input) {
17
+ const errors = [];
18
+ const bad = (path, message) => {
19
+ errors.push(path + ': ' + message);
20
+ };
21
+ if (typeof input !== 'object' || input === null || Array.isArray(input)) {
22
+ return { ok: false, errors: ['model: must be an object'] };
23
+ }
24
+ const root = input;
25
+ if (root.schemaVersion !== 1)
26
+ bad('schemaVersion', 'must be 1');
27
+ if (typeof root.init !== 'string' || root.init.length === 0)
28
+ bad('init', 'must be a non-empty string');
29
+ if (!Array.isArray(root.states) || root.states.length === 0) {
30
+ bad('states', 'must be a non-empty array');
31
+ }
32
+ else {
33
+ const seen = new Set();
34
+ root.states.forEach((entry, index) => {
35
+ if (typeof entry !== 'object' || entry === null || Array.isArray(entry)) {
36
+ bad('states[' + index + ']', 'must be an object');
37
+ return;
38
+ }
39
+ const state = entry;
40
+ if (typeof state.id !== 'string' || state.id.length === 0)
41
+ bad('states[' + index + '].id', 'must be a non-empty string');
42
+ else if (seen.has(state.id))
43
+ bad('states[' + index + '].id', 'duplicate state id ' + state.id);
44
+ else
45
+ seen.add(state.id);
46
+ if (state.terminal !== undefined && typeof state.terminal !== 'boolean')
47
+ bad('states[' + index + '].terminal', 'must be a boolean');
48
+ });
49
+ if (typeof root.init === 'string' && root.init.length > 0 && !seen.has(root.init))
50
+ bad('init', 'must name a declared state');
51
+ }
52
+ if (!Array.isArray(root.transitions)) {
53
+ bad('transitions', 'must be an array');
54
+ }
55
+ else {
56
+ const stateIds = new Set(Array.isArray(root.states) ? root.states.map((state) => state.id) : []);
57
+ root.transitions.forEach((entry, index) => {
58
+ const path = 'transitions[' + index + ']';
59
+ if (typeof entry !== 'object' || entry === null || Array.isArray(entry)) {
60
+ bad(path, 'must be an object');
61
+ return;
62
+ }
63
+ const transition = entry;
64
+ if (typeof transition.from !== 'string' || transition.from.length === 0)
65
+ bad(path + '.from', 'must be a non-empty string');
66
+ else if (!stateIds.has(transition.from))
67
+ bad(path + '.from', 'unknown state ' + transition.from);
68
+ if (typeof transition.event !== 'string' || transition.event.length === 0)
69
+ bad(path + '.event', 'must be a non-empty string');
70
+ if (typeof transition.to !== 'string' || transition.to.length === 0)
71
+ bad(path + '.to', 'must be a non-empty string');
72
+ else if (!stateIds.has(transition.to))
73
+ bad(path + '.to', 'unknown state ' + transition.to);
74
+ if (transition.guard !== undefined)
75
+ validateGuard(transition.guard, path + '.guard', errors, bad);
76
+ if (transition.updates !== undefined) {
77
+ if (!Array.isArray(transition.updates))
78
+ bad(path + '.updates', 'must be an array');
79
+ else
80
+ transition.updates.forEach((update, updateIndex) => {
81
+ const updatePath = path + '.updates[' + updateIndex + ']';
82
+ if (typeof update !== 'object' || update === null || Array.isArray(update)) {
83
+ bad(updatePath, 'must be an object');
84
+ return;
85
+ }
86
+ const record = update;
87
+ if (typeof record.variable !== 'string' || record.variable.length === 0)
88
+ bad(updatePath + '.variable', 'must be a non-empty string');
89
+ if (record.op !== 'set' && record.op !== 'inc' && record.op !== 'dec')
90
+ bad(updatePath + '.op', "must be 'set', 'inc', or 'dec'");
91
+ if (record.value !== undefined && typeof record.value !== 'number')
92
+ bad(updatePath + '.value', 'must be a number');
93
+ });
94
+ }
95
+ });
96
+ }
97
+ const variableNames = new Set();
98
+ if (root.variables !== undefined) {
99
+ if (!Array.isArray(root.variables))
100
+ bad('variables', 'must be an array');
101
+ else
102
+ root.variables.forEach((entry, index) => {
103
+ const path = 'variables[' + index + ']';
104
+ if (typeof entry !== 'object' || entry === null || Array.isArray(entry)) {
105
+ bad(path, 'must be an object');
106
+ return;
107
+ }
108
+ const variable = entry;
109
+ if (typeof variable.name !== 'string' || variable.name.length === 0)
110
+ bad(path + '.name', 'must be a non-empty string');
111
+ else if (variableNames.has(variable.name))
112
+ bad(path + '.name', 'duplicate variable ' + variable.name);
113
+ else
114
+ variableNames.add(variable.name);
115
+ if (variable.kind !== 'integer' && variable.kind !== 'boolean')
116
+ bad(path + '.kind', "must be 'integer' or 'boolean'");
117
+ const expected = variable.kind === 'boolean' ? 'boolean' : 'number';
118
+ if (typeof variable.init !== expected)
119
+ bad(path + '.init', 'must be a ' + expected);
120
+ if (variable.min !== undefined && typeof variable.min !== 'number')
121
+ bad(path + '.min', 'must be a number');
122
+ if (variable.max !== undefined && typeof variable.max !== 'number')
123
+ bad(path + '.max', 'must be a number');
124
+ if (typeof variable.min === 'number' && typeof variable.max === 'number' && variable.min > variable.max)
125
+ bad(path + '.max', 'must be >= min');
126
+ if (variable.monotonic !== undefined && variable.monotonic !== 'inc' && variable.monotonic !== 'dec')
127
+ bad(path + '.monotonic', "must be 'inc' or 'dec'");
128
+ if (variable.kind === 'integer' && typeof variable.init === 'number') {
129
+ if (typeof variable.min === 'number' && variable.init < variable.min)
130
+ bad(path + '.init', 'must be >= min');
131
+ if (typeof variable.max === 'number' && variable.init > variable.max)
132
+ bad(path + '.init', 'must be <= max');
133
+ }
134
+ });
135
+ }
136
+ const validateVariableRef = (name, path) => {
137
+ if (typeof name !== 'string' || name.length === 0)
138
+ bad(path, 'must be a non-empty string');
139
+ else if (!variableNames.has(name))
140
+ bad(path, 'references unknown variable ' + name);
141
+ };
142
+ if (root.invariants !== undefined) {
143
+ if (!Array.isArray(root.invariants))
144
+ bad('invariants', 'must be an array');
145
+ else
146
+ root.invariants.forEach((entry, index) => {
147
+ const path = 'invariants[' + index + ']';
148
+ if (typeof entry !== 'object' || entry === null || Array.isArray(entry)) {
149
+ bad(path, 'must be an object');
150
+ return;
151
+ }
152
+ const invariant = entry;
153
+ if (typeof invariant.id !== 'string' || invariant.id.length === 0)
154
+ bad(path + '.id', 'must be a non-empty string');
155
+ if (typeof invariant.description !== 'string')
156
+ bad(path + '.description', 'must be a string');
157
+ if (invariant.kind === 'never-states') {
158
+ if (!Array.isArray(invariant.states) || invariant.states.length === 0)
159
+ bad(path + '.states', 'must be a non-empty array');
160
+ else
161
+ invariant.states.forEach((state, stateIndex) => {
162
+ if (typeof state !== 'string' || state.length === 0)
163
+ bad(path + '.states[' + stateIndex + ']', 'must be a non-empty string');
164
+ });
165
+ }
166
+ else if (invariant.kind === 'var-in-range') {
167
+ validateVariableRef(invariant.variable, path + '.variable');
168
+ if (invariant.min !== undefined && typeof invariant.min !== 'number')
169
+ bad(path + '.min', 'must be a number');
170
+ if (invariant.max !== undefined && typeof invariant.max !== 'number')
171
+ bad(path + '.max', 'must be a number');
172
+ }
173
+ else if (invariant.kind === 'event-before-state') {
174
+ if (typeof invariant.event !== 'string' || invariant.event.length === 0)
175
+ bad(path + '.event', 'must be a non-empty string');
176
+ if (typeof invariant.state !== 'string' || invariant.state.length === 0)
177
+ bad(path + '.state', 'must be a non-empty string');
178
+ }
179
+ else if (invariant.kind === 'leads-to') {
180
+ if (typeof invariant.from !== 'string' || invariant.from.length === 0)
181
+ bad(path + '.from', 'must be a non-empty string');
182
+ if (typeof invariant.to !== 'string' || invariant.to.length === 0)
183
+ bad(path + '.to', 'must be a non-empty string');
184
+ }
185
+ else if (invariant.kind === 'sequence') {
186
+ if (!Array.isArray(invariant.events) || invariant.events.length === 0)
187
+ bad(path + '.events', 'must be a non-empty array');
188
+ else
189
+ invariant.events.forEach((event, eventIndex) => {
190
+ if (typeof event !== 'string' || event.length === 0)
191
+ bad(path + '.events[' + eventIndex + ']', 'must be a non-empty string');
192
+ });
193
+ }
194
+ else if (invariant.kind === 'atomicity') {
195
+ if (!Array.isArray(invariant.events) || invariant.events.length === 0)
196
+ bad(path + '.events', 'must be a non-empty array');
197
+ else
198
+ invariant.events.forEach((event, eventIndex) => {
199
+ if (typeof event !== 'string' || event.length === 0)
200
+ bad(path + '.events[' + eventIndex + ']', 'must be a non-empty string');
201
+ });
202
+ if (typeof invariant.commit !== 'string' || invariant.commit.length === 0)
203
+ bad(path + '.commit', 'must be a non-empty string');
204
+ if (invariant.rollback !== undefined && typeof invariant.rollback !== 'string')
205
+ bad(path + '.rollback', 'must be a string');
206
+ }
207
+ else {
208
+ bad(path + '.kind', 'unknown invariant kind');
209
+ }
210
+ });
211
+ }
212
+ if (root.concurrentPairs !== undefined) {
213
+ if (!Array.isArray(root.concurrentPairs))
214
+ bad('concurrentPairs', 'must be an array');
215
+ else
216
+ root.concurrentPairs.forEach((entry, index) => {
217
+ const path = 'concurrentPairs[' + index + ']';
218
+ if (!Array.isArray(entry) || entry.length !== 2 || typeof entry[0] !== 'string' || typeof entry[1] !== 'string') {
219
+ bad(path, 'must be a [event, event] string pair');
220
+ }
221
+ });
222
+ }
223
+ if (root.boundaryChecks !== undefined) {
224
+ if (!Array.isArray(root.boundaryChecks))
225
+ bad('boundaryChecks', 'must be an array');
226
+ else
227
+ root.boundaryChecks.forEach((entry, index) => {
228
+ const path = 'boundaryChecks[' + index + ']';
229
+ if (typeof entry !== 'object' || entry === null || Array.isArray(entry)) {
230
+ bad(path, 'must be an object');
231
+ return;
232
+ }
233
+ const check = entry;
234
+ validateVariableRef(check.variable, path + '.variable');
235
+ if (!Array.isArray(check.values) || check.values.some((value) => typeof value !== 'number'))
236
+ bad(path + '.values', 'must be an array of numbers');
237
+ });
238
+ }
239
+ if (root.idempotentEvents !== undefined) {
240
+ if (!Array.isArray(root.idempotentEvents))
241
+ bad('idempotentEvents', 'must be an array');
242
+ else
243
+ root.idempotentEvents.forEach((entry, index) => {
244
+ if (typeof entry !== 'string' || entry.length === 0)
245
+ bad('idempotentEvents[' + index + ']', 'must be a non-empty string');
246
+ });
247
+ }
248
+ if (root.resourcePairs !== undefined) {
249
+ if (!Array.isArray(root.resourcePairs))
250
+ bad('resourcePairs', 'must be an array');
251
+ else
252
+ root.resourcePairs.forEach((entry, index) => {
253
+ const path = 'resourcePairs[' + index + ']';
254
+ if (typeof entry !== 'object' || entry === null || Array.isArray(entry)) {
255
+ bad(path, 'must be an object');
256
+ return;
257
+ }
258
+ const pair = entry;
259
+ if (typeof pair.resource !== 'string' || pair.resource.length === 0)
260
+ bad(path + '.resource', 'must be a non-empty string');
261
+ if (typeof pair.acquireEvent !== 'string' || pair.acquireEvent.length === 0)
262
+ bad(path + '.acquireEvent', 'must be a non-empty string');
263
+ if (typeof pair.releaseEvent !== 'string' || pair.releaseEvent.length === 0)
264
+ bad(path + '.releaseEvent', 'must be a non-empty string');
265
+ if (pair.failEvent !== undefined && typeof pair.failEvent !== 'string')
266
+ bad(path + '.failEvent', 'must be a string');
267
+ });
268
+ }
269
+ // Guard/update variable references were validated structurally; re-walk for references.
270
+ if (Array.isArray(root.transitions)) {
271
+ for (const entry of root.transitions) {
272
+ walkGuardReferences(entry.guard, variableNames, errors, bad);
273
+ for (const update of entry.updates ?? []) {
274
+ if (!variableNames.has(update.variable))
275
+ bad('transitions.updates', 'references unknown variable ' + update.variable);
276
+ if (update.op !== 'set' && update.value !== undefined && update.value === 0) {
277
+ // zero delta is harmless; no finding
278
+ }
279
+ }
280
+ }
281
+ }
282
+ if (errors.length > 0)
283
+ return { ok: false, errors };
284
+ return { ok: true, model: root };
285
+ }
286
+ function validateGuard(input, path, errors, bad) {
287
+ if (typeof input !== 'object' || input === null || Array.isArray(input)) {
288
+ bad(path, 'must be an object');
289
+ return;
290
+ }
291
+ const guard = input;
292
+ if (guard.variable !== undefined) {
293
+ if (typeof guard.variable !== 'string' || guard.variable.length === 0)
294
+ bad(path + '.variable', 'must be a non-empty string');
295
+ if (guard.op !== '==' && guard.op !== '!=' && guard.op !== '<' && guard.op !== '<=' && guard.op !== '>' && guard.op !== '>=')
296
+ bad(path + '.op', 'must be a comparison operator');
297
+ if (typeof guard.value !== 'number' && typeof guard.value !== 'boolean')
298
+ bad(path + '.value', 'must be a number or boolean');
299
+ return;
300
+ }
301
+ if (guard.all !== undefined) {
302
+ if (!Array.isArray(guard.all))
303
+ bad(path + '.all', 'must be an array');
304
+ else
305
+ guard.all.forEach((child, index) => validateGuard(child, path + '.all[' + index + ']', errors, bad));
306
+ return;
307
+ }
308
+ if (guard.any !== undefined) {
309
+ if (!Array.isArray(guard.any))
310
+ bad(path + '.any', 'must be an array');
311
+ else
312
+ guard.any.forEach((child, index) => validateGuard(child, path + '.any[' + index + ']', errors, bad));
313
+ return;
314
+ }
315
+ if (guard.not !== undefined) {
316
+ validateGuard(guard.not, path + '.not', errors, bad);
317
+ return;
318
+ }
319
+ bad(path, 'must be a leaf ({ variable, op, value }), { all }, { any }, or { not }');
320
+ }
321
+ function walkGuardReferences(guard, variableNames, errors, bad) {
322
+ if (guard === undefined)
323
+ return;
324
+ if ('variable' in guard) {
325
+ if (!variableNames.has(guard.variable))
326
+ bad('guard', 'references unknown variable ' + guard.variable);
327
+ return;
328
+ }
329
+ if ('all' in guard) {
330
+ for (const child of guard.all)
331
+ walkGuardReferences(child, variableNames, errors, bad);
332
+ return;
333
+ }
334
+ if ('any' in guard) {
335
+ for (const child of guard.any)
336
+ walkGuardReferences(child, variableNames, errors, bad);
337
+ return;
338
+ }
339
+ if ('not' in guard)
340
+ walkGuardReferences(guard.not, variableNames, errors, bad);
341
+ }
342
+ // ---------------------------------------------------------------------------
343
+ // execution
344
+ // ---------------------------------------------------------------------------
345
+ function isLeafGuard(guard) {
346
+ return 'variable' in guard;
347
+ }
348
+ export function guardVariables(guard) {
349
+ if (guard === undefined)
350
+ return [];
351
+ if (isLeafGuard(guard))
352
+ return [guard.variable];
353
+ if ('all' in guard)
354
+ return guard.all.flatMap((child) => guardVariables(child));
355
+ if ('any' in guard)
356
+ return guard.any.flatMap((child) => guardVariables(child));
357
+ if ('not' in guard)
358
+ return guardVariables(guard.not);
359
+ return [];
360
+ }
361
+ function evalGuard(guard, vars) {
362
+ if (isLeafGuard(guard)) {
363
+ const actual = vars[guard.variable];
364
+ switch (guard.op) {
365
+ case '==': return actual === guard.value;
366
+ case '!=': return actual !== guard.value;
367
+ case '<': return actual < guard.value;
368
+ case '<=': return actual <= guard.value;
369
+ case '>': return actual > guard.value;
370
+ case '>=': return actual >= guard.value;
371
+ }
372
+ }
373
+ if ('all' in guard)
374
+ return guard.all.every((child) => evalGuard(child, vars));
375
+ if ('any' in guard)
376
+ return guard.any.some((child) => evalGuard(child, vars));
377
+ if ('not' in guard)
378
+ return !evalGuard(guard.not, vars);
379
+ return false;
380
+ }
381
+ function initialState(model) {
382
+ const vars = {};
383
+ for (const variable of model.variables ?? [])
384
+ vars[variable.name] = variable.init;
385
+ return { state: model.init, vars };
386
+ }
387
+ function runtimeKey(runtime) {
388
+ return runtime.state + '|' + stableStringify(runtime.vars);
389
+ }
390
+ function applyUpdates(model, transition, runtime) {
391
+ const vars = { ...runtime.vars };
392
+ for (const update of transition.updates ?? []) {
393
+ const current = vars[update.variable];
394
+ if (update.op === 'set')
395
+ vars[update.variable] = update.value ?? 0;
396
+ else if (update.op === 'inc')
397
+ vars[update.variable] = ((typeof current === 'number' ? current : 0) + (update.value ?? 1));
398
+ else
399
+ vars[update.variable] = ((typeof current === 'number' ? current : 0) - (update.value ?? 1));
400
+ }
401
+ return { state: transition.to, vars };
402
+ }
403
+ function groupTransitions(model) {
404
+ const groups = new Map();
405
+ for (const transition of model.transitions) {
406
+ const key = transition.from + '|' + transition.event;
407
+ const list = groups.get(key) ?? [];
408
+ list.push(transition);
409
+ groups.set(key, list);
410
+ }
411
+ return groups;
412
+ }
413
+ function applicableTransitions(group, runtime) {
414
+ const guarded = [];
415
+ const unguarded = [];
416
+ for (const transition of group) {
417
+ if (transition.guard === undefined)
418
+ unguarded.push(transition);
419
+ else
420
+ guarded.push(transition);
421
+ }
422
+ const matched = guarded.filter((transition) => evalGuard(transition.guard, runtime.vars));
423
+ if (matched.length > 0)
424
+ return matched;
425
+ return unguarded;
426
+ }
427
+ function stepRuntime(model, runtime, event) {
428
+ const group = groupTransitions(model).get(runtime.state + '|' + event);
429
+ if (group === undefined || group.length === 0)
430
+ return [];
431
+ const seen = new Set();
432
+ const outcomes = [];
433
+ for (const transition of applicableTransitions(group, runtime)) {
434
+ const next = applyUpdates(model, transition, runtime);
435
+ const key = runtimeKey(next);
436
+ if (!seen.has(key)) {
437
+ seen.add(key);
438
+ outcomes.push(next);
439
+ }
440
+ }
441
+ return outcomes;
442
+ }
443
+ function explore(model, options) {
444
+ const init = initialState(model);
445
+ const reachable = [];
446
+ const reachableKeys = new Set();
447
+ const queue = [init];
448
+ let truncated = false;
449
+ while (queue.length > 0) {
450
+ const runtime = queue.shift();
451
+ const key = runtimeKey(runtime);
452
+ if (reachableKeys.has(key))
453
+ continue;
454
+ reachableKeys.add(key);
455
+ reachable.push(runtime);
456
+ if (reachable.length > options.maxStates) {
457
+ truncated = true;
458
+ break;
459
+ }
460
+ for (const event of allEvents(model)) {
461
+ for (const next of stepRuntime(model, runtime, event)) {
462
+ if (!reachableKeys.has(runtimeKey(next)))
463
+ queue.push(next);
464
+ }
465
+ }
466
+ }
467
+ return { reachable, reachableKeys, truncated, initialState: init };
468
+ }
469
+ function allEvents(model) {
470
+ return [...new Set(model.transitions.map((transition) => transition.event))].sort();
471
+ }
472
+ function stateById(model, id) {
473
+ return model.states.find((state) => state.id === id);
474
+ }
475
+ function isTerminal(model, state) {
476
+ return stateById(model, state)?.terminal === true;
477
+ }
478
+ function uniqueTargets(transitions) {
479
+ return [...new Set(transitions.map((transition) => transition.to))];
480
+ }
481
+ function checkResult(id, name, findings, detail) {
482
+ const errors = findings.filter((finding) => finding.severity === 'error').length;
483
+ const warnings = findings.filter((finding) => finding.severity === 'warning').length;
484
+ return {
485
+ id,
486
+ name,
487
+ status: findings.length === 0 ? 'pass' : 'fail',
488
+ detail: detail + (errors > 0 ? ' (' + errors + ' errors' + (warnings > 0 ? ', ' + warnings + ' warnings' : '') + ')' : warnings > 0 ? ' (' + warnings + ' warnings)' : ''),
489
+ findings,
490
+ };
491
+ }
492
+ // ---------------------------------------------------------------------------
493
+ // S1-S7
494
+ // ---------------------------------------------------------------------------
495
+ function S1_reachability(model, exploration) {
496
+ const reached = new Set(exploration.reachable.map((runtime) => runtime.state));
497
+ const unreachable = model.states.filter((state) => !reached.has(state.id)).map((state) => state.id);
498
+ const findings = unreachable.map((state) => ({
499
+ code: 'S1_UNREACHABLE_STATE',
500
+ severity: 'warning',
501
+ message: 'State ' + state + ' is not reachable from init.',
502
+ }));
503
+ return checkResult('S1', 'Reachability', findings, unreachable.length === 0 ? 'All states reachable' : 'Unreachable states: ' + unreachable.join(', '));
504
+ }
505
+ function S2_deadlock(model) {
506
+ const outgoing = new Set(model.transitions.map((transition) => transition.from));
507
+ const findings = [];
508
+ for (const state of model.states) {
509
+ if (state.terminal === true)
510
+ continue;
511
+ if (!outgoing.has(state.id)) {
512
+ findings.push({
513
+ code: 'S2_NO_TRANSITIONS',
514
+ severity: 'error',
515
+ message: 'Non-terminal state ' + state.id + ' has no outgoing transitions.',
516
+ });
517
+ }
518
+ }
519
+ return checkResult('S2', 'Deadlock', findings, findings.length === 0 ? 'No deadlocks' : 'Deadlocks: ' + findings.map((finding) => finding.message).join('; '));
520
+ }
521
+ function sccs(model) {
522
+ const states = model.states.map((state) => state.id);
523
+ const edges = new Map();
524
+ for (const state of states)
525
+ edges.set(state, []);
526
+ for (const transition of model.transitions) {
527
+ const list = edges.get(transition.from);
528
+ if (list !== undefined)
529
+ list.push(transition.to);
530
+ }
531
+ let index = 0;
532
+ const indices = new Map();
533
+ const low = new Map();
534
+ const onStack = new Set();
535
+ const stack = [];
536
+ const components = [];
537
+ const visit = (node) => {
538
+ indices.set(node, index);
539
+ low.set(node, index);
540
+ index += 1;
541
+ stack.push(node);
542
+ onStack.add(node);
543
+ for (const next of edges.get(node) ?? []) {
544
+ if (!indices.has(next)) {
545
+ visit(next);
546
+ low.set(node, Math.min(low.get(node), low.get(next)));
547
+ }
548
+ else if (onStack.has(next)) {
549
+ low.set(node, Math.min(low.get(node), indices.get(next)));
550
+ }
551
+ }
552
+ if (low.get(node) === indices.get(node)) {
553
+ const component = [];
554
+ while (stack.length > 0) {
555
+ const member = stack.pop();
556
+ onStack.delete(member);
557
+ component.push(member);
558
+ if (member === node)
559
+ break;
560
+ }
561
+ components.push(component);
562
+ }
563
+ };
564
+ for (const state of states) {
565
+ if (!indices.has(state))
566
+ visit(state);
567
+ }
568
+ return components;
569
+ }
570
+ function S3_liveness(model) {
571
+ const components = sccs(model);
572
+ const findings = [];
573
+ for (const component of components) {
574
+ const componentSet = new Set(component);
575
+ const internalEdges = model.transitions.filter((transition) => componentSet.has(transition.from) && componentSet.has(transition.to));
576
+ const escapingEdges = model.transitions.filter((transition) => componentSet.has(transition.from) && !componentSet.has(transition.to));
577
+ if (internalEdges.length === 0 || escapingEdges.length > 0)
578
+ continue;
579
+ if (component.some((state) => isTerminal(model, state)))
580
+ continue;
581
+ findings.push({
582
+ code: 'S3_CLOSED_SCC',
583
+ severity: 'error',
584
+ message: 'Closed SCC has no exit and contains no terminal state: ' + component.sort().join(', '),
585
+ evidence: { states: component.sort(), transitions: internalEdges.length },
586
+ });
587
+ }
588
+ return checkResult('S3', 'Liveness', findings, findings.length === 0 ? 'No harmful closed SCCs' : 'Closed SCCs: ' + findings.length);
589
+ }
590
+ function assignmentsFor(model, variables) {
591
+ const specs = (model.variables ?? []).filter((variable) => variables.includes(variable.name));
592
+ let combinations = [{}];
593
+ for (const spec of specs) {
594
+ let values;
595
+ if (spec.kind === 'boolean')
596
+ values = [false, true];
597
+ else {
598
+ const constants = collectGuardConstants(model).filter((value) => guardLeaves(model).some((leaf) => leaf.variable === spec.name && typeof leaf.value === 'number' && leaf.value === value));
599
+ if (spec.min !== undefined && spec.max !== undefined) {
600
+ values = [];
601
+ for (let value = spec.min; value <= spec.max && value <= spec.min + 200; value++)
602
+ values.push(value);
603
+ }
604
+ else {
605
+ const set = new Set([-1, 0, 1, ...constants]);
606
+ values = [...set].sort((a, b) => a - b);
607
+ }
608
+ }
609
+ const next = [];
610
+ for (const assignment of combinations) {
611
+ for (const value of values) {
612
+ next.push({ ...assignment, [spec.name]: value });
613
+ if (next.length > 10_000)
614
+ return null;
615
+ }
616
+ }
617
+ combinations = next;
618
+ }
619
+ return combinations;
620
+ }
621
+ function guardLeaves(model) {
622
+ const leaves = [];
623
+ const visit = (guard) => {
624
+ if ('variable' in guard)
625
+ leaves.push(guard);
626
+ else if ('all' in guard)
627
+ guard.all.forEach(visit);
628
+ else if ('any' in guard)
629
+ guard.any.forEach(visit);
630
+ else if ('not' in guard)
631
+ visit(guard.not);
632
+ };
633
+ for (const transition of model.transitions)
634
+ if (transition.guard !== undefined)
635
+ visit(transition.guard);
636
+ return leaves;
637
+ }
638
+ function collectGuardConstants(model) {
639
+ return guardLeaves(model).filter((leaf) => typeof leaf.value === 'number').map((leaf) => leaf.value);
640
+ }
641
+ function analyzeGuards(model) {
642
+ const determinism = [];
643
+ const completeness = [];
644
+ let truncated = false;
645
+ const groups = groupTransitions(model);
646
+ for (const [key, group] of groups) {
647
+ const [from, event] = key.split('|');
648
+ const unguarded = group.filter((transition) => transition.guard === undefined);
649
+ const guarded = group.filter((transition) => transition.guard !== undefined);
650
+ if (unguarded.length > 1) {
651
+ determinism.push({
652
+ code: 'S4_AMBIGUOUS_DEFAULT',
653
+ severity: 'error',
654
+ message: from + ' + ' + event + ' has multiple unconditional transitions: ' + uniqueTargets(unguarded).join(', '),
655
+ });
656
+ }
657
+ if (guarded.length === 0)
658
+ continue;
659
+ const variables = [...new Set(group.flatMap((transition) => guardVariables(transition.guard)))];
660
+ const assignments = assignmentsFor(model, variables);
661
+ if (assignments === null) {
662
+ completeness.push({ code: 'S6_UNBOUNDED_DOMAIN', severity: 'warning', message: from + ' + ' + event + ': guard domain too large to enumerate; exhaustive check skipped.' });
663
+ truncated = true;
664
+ continue;
665
+ }
666
+ const targets = uniqueTargets(group);
667
+ for (const assignment of assignments) {
668
+ const trueBranches = guarded.filter((transition) => evalGuard(transition.guard, assignment));
669
+ if (trueBranches.length > 1) {
670
+ determinism.push({
671
+ code: 'S4_NONDETERMINISTIC_GUARDS',
672
+ severity: 'error',
673
+ message: from + ' + ' + event + ' has ' + trueBranches.length + ' simultaneously true guards for assignment ' + stableStringify(assignment) + ': ' + uniqueTargets(trueBranches).join(', '),
674
+ evidence: { assignment },
675
+ });
676
+ }
677
+ if (trueBranches.length === 0 && unguarded.length === 0) {
678
+ completeness.push({
679
+ code: 'S6_INCOMPLETE_GUARD',
680
+ severity: 'error',
681
+ message: from + ' + ' + event + ' has no true guard and no default branch for assignment ' + stableStringify(assignment),
682
+ evidence: { assignment, branches: targets },
683
+ });
684
+ }
685
+ if (determinism.length + completeness.length > 200) {
686
+ truncated = true;
687
+ break;
688
+ }
689
+ }
690
+ if (truncated)
691
+ break;
692
+ }
693
+ return { determinism, completeness, truncated };
694
+ }
695
+ function S4_determinism(model) {
696
+ const analysis = analyzeGuards(model);
697
+ return checkResult('S4', 'Determinism', analysis.determinism, analysis.determinism.length === 0 ? 'Deterministic' : 'Nondeterminism findings: ' + analysis.determinism.length);
698
+ }
699
+ function S6_guardCompleteness(model) {
700
+ const analysis = analyzeGuards(model);
701
+ return checkResult('S6', 'Guard Completeness', analysis.completeness, analysis.completeness.length === 0 ? 'All guard branches defined' : 'Guard findings: ' + analysis.completeness.length);
702
+ }
703
+ function S5_eventCompleteness(model) {
704
+ const events = allEvents(model);
705
+ const findings = [];
706
+ for (const state of model.states) {
707
+ if (state.terminal === true)
708
+ continue;
709
+ const handled = new Set(model.transitions.filter((transition) => transition.from === state.id).map((transition) => transition.event));
710
+ for (const event of events) {
711
+ if (!handled.has(event)) {
712
+ findings.push({
713
+ code: 'S5_UNHANDLED_EVENT',
714
+ severity: 'warning',
715
+ message: state.id + ' silently ignores event ' + event,
716
+ });
717
+ }
718
+ }
719
+ }
720
+ return checkResult('S5', 'Event Completeness', findings, findings.length === 0 ? 'All states handle all relevant events' : findings.length + ' unhandled (state, event) pairs');
721
+ }
722
+ function invariantHolds(invariant, runtime) {
723
+ if (invariant.kind === 'never-states')
724
+ return !invariant.states.includes(runtime.state);
725
+ if (invariant.kind === 'var-in-range') {
726
+ const value = runtime.vars[invariant.variable];
727
+ if (typeof value !== 'number')
728
+ return false;
729
+ if (invariant.min !== undefined && value < invariant.min)
730
+ return false;
731
+ if (invariant.max !== undefined && value > invariant.max)
732
+ return false;
733
+ return true;
734
+ }
735
+ return true;
736
+ }
737
+ function shortestViolationForInvariant(model, options, invariant) {
738
+ if (invariant.kind === 'event-before-state') {
739
+ return shortestEventBeforeStateViolation(model, options, invariant);
740
+ }
741
+ const init = initialState(model);
742
+ if (!invariantHolds(invariant, init)) {
743
+ return { invariant, path: [], reason: 'Initial state violates the invariant.' };
744
+ }
745
+ const visited = new Set([runtimeKey(init)]);
746
+ const queue = [{ runtime: init, path: [] }];
747
+ let steps = 0;
748
+ while (queue.length > 0) {
749
+ const entry = queue.shift();
750
+ if (++steps > options.maxStates)
751
+ break;
752
+ for (const event of allEvents(model)) {
753
+ for (const next of stepRuntime(model, entry.runtime, event)) {
754
+ const key = runtimeKey(next);
755
+ if (visited.has(key))
756
+ continue;
757
+ const path = [...entry.path, { from: entry.runtime.state, event, to: next.state }];
758
+ if (!invariantHolds(invariant, next)) {
759
+ return { invariant, path, reason: 'Invariant violated after ' + path.length + ' events.' };
760
+ }
761
+ visited.add(key);
762
+ queue.push({ runtime: next, path });
763
+ }
764
+ }
765
+ }
766
+ return undefined;
767
+ }
768
+ function shortestEventBeforeStateViolation(model, options, invariant) {
769
+ const init = initialState(model);
770
+ const seenInitially = false;
771
+ if (init.state === invariant.state && !seenInitially) {
772
+ return { invariant, path: [], reason: 'Target state ' + invariant.state + ' is initial and the required event ' + invariant.event + ' has not occurred.' };
773
+ }
774
+ const key = (runtime, seen) => runtimeKey(runtime) + '|' + (seen ? '1' : '0');
775
+ const visited = new Set([key(init, false)]);
776
+ const queue = [{ runtime: init, seen: false, path: [] }];
777
+ let steps = 0;
778
+ while (queue.length > 0) {
779
+ const entry = queue.shift();
780
+ if (++steps > options.maxStates)
781
+ break;
782
+ for (const event of allEvents(model)) {
783
+ for (const next of stepRuntime(model, entry.runtime, event)) {
784
+ const seen = entry.seen || event === invariant.event;
785
+ const nextKey = key(next, seen);
786
+ if (visited.has(nextKey))
787
+ continue;
788
+ const path = [...entry.path, { from: entry.runtime.state, event, to: next.state }];
789
+ if (next.state === invariant.state && !seen) {
790
+ return { invariant, path, reason: 'Target state ' + invariant.state + ' is reachable without event ' + invariant.event + ' in ' + path.length + ' steps.' };
791
+ }
792
+ visited.add(nextKey);
793
+ queue.push({ runtime: next, seen, path });
794
+ }
795
+ }
796
+ }
797
+ return undefined;
798
+ }
799
+ function runInvariants(model, options) {
800
+ const violations = [];
801
+ for (const invariant of model.invariants ?? []) {
802
+ const violation = shortestViolationForInvariant(model, options, invariant);
803
+ if (violation !== undefined)
804
+ violations.push(violation);
805
+ }
806
+ return violations;
807
+ }
808
+ function S7_invariants(model, options) {
809
+ const violations = runInvariants(model, options);
810
+ const findings = violations.map((violation) => ({
811
+ code: 'S7_INVARIANT_VIOLATION',
812
+ severity: 'error',
813
+ message: 'Invariant "' + violation.invariant.id + '" (' + violation.invariant.description + ') violated: ' + violation.reason,
814
+ path: violation.path,
815
+ evidence: { invariant: violation.invariant },
816
+ }));
817
+ return checkResult('S7', 'Invariant Validity', findings, violations.length === 0 ? 'All invariants hold' : 'Invariant violations: ' + violations.length);
818
+ }
819
+ // ---------------------------------------------------------------------------
820
+ // A1-A7
821
+ // ---------------------------------------------------------------------------
822
+ function A1_unexpectedEvents(model) {
823
+ const events = allEvents(model);
824
+ const findings = [];
825
+ for (const state of model.states) {
826
+ if (state.terminal === true)
827
+ continue;
828
+ const handled = new Set(model.transitions.filter((transition) => transition.from === state.id).map((transition) => transition.event));
829
+ for (const event of events) {
830
+ if (!handled.has(event)) {
831
+ findings.push({
832
+ code: 'A1_UNHANDLED_EVENT',
833
+ severity: 'warning',
834
+ message: 'Event ' + event + ' in state ' + state.id + ' has no defined transition (silent ignore).',
835
+ });
836
+ }
837
+ }
838
+ }
839
+ return checkResult('A1', 'Unexpected Event Injection', findings, findings.length === 0 ? 'All event/state combinations defined' : findings.length + ' unhandled combinations');
840
+ }
841
+ function firstOutcome(runtime, outcomes) {
842
+ return outcomes[0];
843
+ }
844
+ function A2_raceInterleaving(model, exploration) {
845
+ const findings = [];
846
+ for (const [e1, e2] of model.concurrentPairs ?? []) {
847
+ for (const runtime of exploration.reachable) {
848
+ const first = firstOutcome(runtime, stepRuntime(model, runtime, e1));
849
+ const second = firstOutcome(runtime, stepRuntime(model, runtime, e2));
850
+ if (first === undefined && second === undefined)
851
+ continue;
852
+ const final12 = first === undefined ? runtime : firstOutcome(first, stepRuntime(model, first, e2)) ?? first;
853
+ const final21 = second === undefined ? runtime : firstOutcome(second, stepRuntime(model, second, e1)) ?? second;
854
+ if (runtimeKey(final12) !== runtimeKey(final21)) {
855
+ findings.push({
856
+ code: 'A2_ORDER_DEPENDENT',
857
+ severity: 'warning',
858
+ message: 'Events ' + e1 + ' and ' + e2 + ' produce order-dependent outcomes from state ' + runtime.state,
859
+ evidence: { e1ThenE2: final12, e2ThenE1: final21 },
860
+ });
861
+ }
862
+ }
863
+ }
864
+ return checkResult('A2', 'Race Interleaving', findings, findings.length === 0 ? 'No race conditions detected' : 'Order-dependent outcomes: ' + findings.length);
865
+ }
866
+ function stepSequence(model, init, events) {
867
+ let runtime = init;
868
+ for (const event of events) {
869
+ const next = firstOutcome(runtime, stepRuntime(model, runtime, event));
870
+ if (next === undefined)
871
+ continue;
872
+ runtime = next;
873
+ }
874
+ return runtime;
875
+ }
876
+ function permutations(items) {
877
+ if (items.length === 0)
878
+ return [[]];
879
+ const result = [];
880
+ for (let index = 0; index < items.length; index++) {
881
+ const rest = items.slice(0, index).concat(items.slice(index + 1));
882
+ for (const suffix of permutations(rest))
883
+ result.push([items[index], ...suffix]);
884
+ }
885
+ return result;
886
+ }
887
+ function A3_orderPermutation(model, options) {
888
+ const events = allEvents(model).slice(0, options.maxPermutationEvents);
889
+ if (events.length < 2)
890
+ return checkResult('A3', 'Order Permutation', [], 'Fewer than 2 events — skipped');
891
+ const init = initialState(model);
892
+ const outcomes = new Map();
893
+ for (const permutation of permutations(events)) {
894
+ const final = stepSequence(model, init, permutation);
895
+ const key = runtimeKey(final);
896
+ const list = outcomes.get(key) ?? [];
897
+ if (list.length < 3)
898
+ list.push(permutation.join(','));
899
+ outcomes.set(key, list);
900
+ }
901
+ if (outcomes.size > 1) {
902
+ const examples = [...outcomes.entries()].map(([key, sequences]) => ({ final: key.split('|')[0], example: sequences[0] }));
903
+ return checkResult('A3', 'Order Permutation', [{
904
+ code: 'A3_ORDER_DEPENDENT',
905
+ severity: 'warning',
906
+ message: 'Same event set produces ' + outcomes.size + ' different outcomes depending on order.',
907
+ evidence: { examples },
908
+ }], 'Order-dependent outcomes: ' + outcomes.size);
909
+ }
910
+ return checkResult('A3', 'Order Permutation', [], 'Order-independent (sampled first ' + events.length + ' events)');
911
+ }
912
+ function A4_pairSymmetry(model) {
913
+ const findings = [];
914
+ const transitionEvents = new Set(model.transitions.map((transition) => transition.event));
915
+ for (const pair of model.resourcePairs ?? []) {
916
+ const acquireTransitions = model.transitions.filter((transition) => transition.event === pair.acquireEvent);
917
+ const releaseExists = transitionEvents.has(pair.releaseEvent);
918
+ if (acquireTransitions.length === 0 && !releaseExists)
919
+ continue;
920
+ if (acquireTransitions.length > 0 && !releaseExists) {
921
+ findings.push({
922
+ code: 'A4_NO_RELEASE_EVENT',
923
+ severity: 'error',
924
+ message: 'Resource "' + pair.resource + '": acquire event ' + pair.acquireEvent + ' exists but release event ' + pair.releaseEvent + ' is never defined.',
925
+ });
926
+ continue;
927
+ }
928
+ for (const acquire of acquireTransitions) {
929
+ // Is any release event reachable in the state graph from the acquired state?
930
+ const reachable = stateGraphReachable(model, acquire.to);
931
+ const releaseReachable = [...reachable].some((state) => model.transitions.some((transition) => transition.from === state && transition.event === pair.releaseEvent));
932
+ if (!releaseReachable) {
933
+ findings.push({
934
+ code: 'A4_NO_RELEASE_REACHABLE',
935
+ severity: 'error',
936
+ message: 'Resource "' + pair.resource + '": after ' + pair.acquireEvent + ' into ' + acquire.to + ', no ' + pair.releaseEvent + ' transition is reachable.',
937
+ evidence: { acquireTransition: acquire },
938
+ });
939
+ continue;
940
+ }
941
+ // Path-sensitive probe: track the held flag along state-graph paths.
942
+ const edges = stateGraphEdges(model);
943
+ const visited = new Set();
944
+ const queue = [{ state: acquire.to, held: true, path: [] }];
945
+ let steps = 0;
946
+ while (queue.length > 0) {
947
+ const entry = queue.shift();
948
+ if (++steps > 1000)
949
+ break;
950
+ const key = entry.state + '|' + (entry.held ? '1' : '0');
951
+ if (visited.has(key))
952
+ continue;
953
+ visited.add(key);
954
+ if (entry.held && isTerminal(model, entry.state)) {
955
+ findings.push({
956
+ code: 'A4_TERMINAL_WITH_RESOURCE',
957
+ severity: 'error',
958
+ message: 'Resource "' + pair.resource + '" is still held when entering terminal state ' + entry.state + '.',
959
+ path: entry.path,
960
+ });
961
+ continue;
962
+ }
963
+ for (const transition of edges.get(entry.state) ?? []) {
964
+ let held = entry.held;
965
+ if (transition.event === pair.releaseEvent)
966
+ held = false;
967
+ else if (transition.event === pair.acquireEvent) {
968
+ if (held) {
969
+ findings.push({
970
+ code: 'A4_REACQUIRE_WITHOUT_RELEASE',
971
+ severity: 'warning',
972
+ message: 'Resource "' + pair.resource + '" is acquired again in state ' + entry.state + ' before ' + pair.releaseEvent + '.',
973
+ path: [...entry.path, { from: entry.state, event: transition.event, to: transition.to }],
974
+ });
975
+ continue;
976
+ }
977
+ held = true;
978
+ }
979
+ queue.push({ state: transition.to, held, path: [...entry.path, { from: entry.state, event: transition.event, to: transition.to }] });
980
+ }
981
+ }
982
+ }
983
+ }
984
+ return checkResult('A4', 'Pair Symmetry', findings, findings.length === 0 ? 'All pairs balanced' : 'Asymmetric pairs: ' + findings.length);
985
+ }
986
+ function stateGraphEdges(model) {
987
+ const edges = new Map();
988
+ for (const state of model.states)
989
+ edges.set(state.id, []);
990
+ for (const transition of model.transitions)
991
+ edges.get(transition.from)?.push(transition);
992
+ return edges;
993
+ }
994
+ function stateGraphReachable(model, start) {
995
+ const edges = new Map();
996
+ for (const state of model.states)
997
+ edges.set(state.id, []);
998
+ for (const transition of model.transitions)
999
+ edges.get(transition.from)?.push(transition.to);
1000
+ const visited = new Set();
1001
+ const queue = [start];
1002
+ while (queue.length > 0) {
1003
+ const current = queue.shift();
1004
+ if (visited.has(current))
1005
+ continue;
1006
+ visited.add(current);
1007
+ for (const next of edges.get(current) ?? [])
1008
+ queue.push(next);
1009
+ }
1010
+ return visited;
1011
+ }
1012
+ function A5_boundaryBlast(model) {
1013
+ const findings = [];
1014
+ for (const check of model.boundaryChecks ?? []) {
1015
+ const variable = (model.variables ?? []).find((entry) => entry.name === check.variable);
1016
+ if (variable === undefined)
1017
+ continue;
1018
+ for (const value of check.values) {
1019
+ if (variable.min !== undefined && value < variable.min) {
1020
+ findings.push({ code: 'A5_OUT_OF_DOMAIN', severity: 'warning', message: 'Boundary value ' + value + ' for ' + check.variable + ' is below min ' + variable.min });
1021
+ }
1022
+ if (variable.max !== undefined && value > variable.max) {
1023
+ findings.push({ code: 'A5_OUT_OF_DOMAIN', severity: 'warning', message: 'Boundary value ' + value + ' for ' + check.variable + ' is above max ' + variable.max });
1024
+ }
1025
+ const assignment = { ...(model.variables ?? []).reduce((result, entry) => { result[entry.name] = entry.init; return result; }, {}), [check.variable]: value };
1026
+ for (const [key, group] of groupTransitions(model)) {
1027
+ const [from, event] = key.split('|');
1028
+ if (!group.some((transition) => guardVariables(transition.guard).includes(check.variable)))
1029
+ continue;
1030
+ const guarded = group.filter((transition) => transition.guard !== undefined);
1031
+ const unguarded = group.filter((transition) => transition.guard === undefined);
1032
+ const matched = guarded.filter((transition) => evalGuard(transition.guard, assignment));
1033
+ if (matched.length === 0 && unguarded.length === 0) {
1034
+ findings.push({
1035
+ code: 'A5_GUARD_HOLE',
1036
+ severity: 'warning',
1037
+ message: from + ' + ' + event + ' has no branch for ' + check.variable + '=' + value,
1038
+ evidence: { assignment },
1039
+ });
1040
+ }
1041
+ if (matched.length > 1) {
1042
+ findings.push({
1043
+ code: 'A5_GUARD_OVERLAP',
1044
+ severity: 'warning',
1045
+ message: from + ' + ' + event + ' has ' + matched.length + ' true branches for ' + check.variable + '=' + value,
1046
+ evidence: { assignment },
1047
+ });
1048
+ }
1049
+ }
1050
+ }
1051
+ }
1052
+ return checkResult('A5', 'Boundary Blast', findings, findings.length === 0 ? 'Boundary checks passed' : 'Boundary findings: ' + findings.length);
1053
+ }
1054
+ function A6_resourceInjection(model) {
1055
+ const findings = [];
1056
+ for (const pair of model.resourcePairs ?? []) {
1057
+ if (pair.failEvent === undefined)
1058
+ continue;
1059
+ const acquireStates = new Set(model.transitions.filter((transition) => transition.event === pair.acquireEvent).map((transition) => transition.from));
1060
+ for (const state of acquireStates) {
1061
+ const handled = model.transitions.some((transition) => transition.from === state && transition.event === pair.failEvent);
1062
+ if (!handled) {
1063
+ findings.push({
1064
+ code: 'A6_NO_FAILURE_HANDLER',
1065
+ severity: 'warning',
1066
+ message: 'State ' + state + ' can ' + pair.acquireEvent + ' for "' + pair.resource + '" but has no ' + pair.failEvent + ' transition.',
1067
+ });
1068
+ }
1069
+ }
1070
+ }
1071
+ return checkResult('A6', 'Resource Injection', findings, findings.length === 0 ? 'No resource vulnerabilities detected' : 'Resource failure paths missing: ' + findings.length);
1072
+ }
1073
+ function A7_shortestViolations(model, options) {
1074
+ const violations = runInvariants(model, options);
1075
+ const findings = violations.map((violation) => ({
1076
+ code: 'A7_SHORTEST_COUNTEREXAMPLE',
1077
+ severity: 'warning',
1078
+ message: 'Invariant "' + violation.invariant.id + '" shortest violating path length: ' + violation.path.length + (violation.path.length === 0 ? ' (initial state)' : ''),
1079
+ path: violation.path,
1080
+ evidence: { invariant: violation.invariant.id },
1081
+ }));
1082
+ return checkResult('A7', 'Minimal Counter-Example', findings, violations.length === 0 ? 'All invariants hold for all reachable paths' : 'Violated invariants: ' + findings.length);
1083
+ }
1084
+ function mapStateId(mapping, state) {
1085
+ return mapping[state] ?? state;
1086
+ }
1087
+ function D1_behavioralPreservation(before, after, mapping) {
1088
+ const findings = [];
1089
+ const afterStates = new Set(after.states.map((state) => state.id));
1090
+ const afterByFromEvent = new Map();
1091
+ for (const transition of after.transitions) {
1092
+ const key = transition.from + '|' + transition.event;
1093
+ const set = afterByFromEvent.get(key) ?? new Set();
1094
+ set.add(transition.to);
1095
+ afterByFromEvent.set(key, set);
1096
+ }
1097
+ const beforeInitMapped = mapStateId(mapping, before.init);
1098
+ if (beforeInitMapped !== after.init) {
1099
+ findings.push({
1100
+ code: 'D1_INIT_MISMATCH',
1101
+ severity: 'warning',
1102
+ message: 'Mapped BEFORE init ' + beforeInitMapped + ' does not match AFTER init ' + after.init + '.',
1103
+ evidence: { beforeInit: before.init, mappedInit: beforeInitMapped, afterInit: after.init },
1104
+ });
1105
+ }
1106
+ for (const state of before.states) {
1107
+ const mapped = mapStateId(mapping, state.id);
1108
+ if (!afterStates.has(mapped)) {
1109
+ findings.push({
1110
+ code: 'D1_MAPPED_STATE_MISSING',
1111
+ severity: 'error',
1112
+ message: 'BEFORE state ' + state.id + ' maps to ' + mapped + ', which is not declared in AFTER.',
1113
+ evidence: { beforeState: state.id, mappedState: mapped },
1114
+ });
1115
+ continue;
1116
+ }
1117
+ for (const transition of before.transitions.filter((entry) => entry.from === state.id)) {
1118
+ const key = mapped + '|' + transition.event;
1119
+ const targets = afterByFromEvent.get(key);
1120
+ if (targets === undefined || targets.size === 0) {
1121
+ findings.push({
1122
+ code: 'D1_EVENT_DISABLED',
1123
+ severity: 'error',
1124
+ message: 'BEFORE can fire event ' + transition.event + ' from ' + state.id + ' (mapped to ' + mapped + '), but AFTER has no transition for that (state, event).',
1125
+ path: [{ from: state.id, event: transition.event, to: transition.to }],
1126
+ evidence: { beforeState: state.id, mappedState: mapped, event: transition.event },
1127
+ });
1128
+ }
1129
+ }
1130
+ }
1131
+ return checkResult('D1', 'Behavioral Preservation', findings, findings.length === 0 ? 'BEFORE event behavior is preserved in AFTER' : 'Behavioral preservation findings: ' + findings.length);
1132
+ }
1133
+ function mapInvariantForComparison(invariant, mapping) {
1134
+ if (invariant.kind === 'never-states') {
1135
+ return {
1136
+ ...invariant,
1137
+ id: invariant.id + ':before',
1138
+ description: invariant.description + ' (from BEFORE)',
1139
+ states: invariant.states.map((state) => mapStateId(mapping, state)),
1140
+ };
1141
+ }
1142
+ if (invariant.kind === 'event-before-state') {
1143
+ return {
1144
+ ...invariant,
1145
+ id: invariant.id + ':before',
1146
+ description: invariant.description + ' (from BEFORE)',
1147
+ state: mapStateId(mapping, invariant.state),
1148
+ };
1149
+ }
1150
+ return { ...invariant, id: invariant.id + ':before', description: invariant.description + ' (from BEFORE)' };
1151
+ }
1152
+ function D2_invariantContinuity(before, after, options, mapping) {
1153
+ const findings = [];
1154
+ const afterStates = new Set(after.states.map((state) => state.id));
1155
+ const afterVariables = new Set((after.variables ?? []).map((variable) => variable.name));
1156
+ for (const invariant of before.invariants ?? []) {
1157
+ const mapped = mapInvariantForComparison(invariant, mapping);
1158
+ if (mapped.kind === 'never-states') {
1159
+ for (const state of mapped.states) {
1160
+ if (!afterStates.has(state)) {
1161
+ findings.push({
1162
+ code: 'D2_MAPPED_STATE_MISSING',
1163
+ severity: 'warning',
1164
+ message: 'BEFORE invariant "' + invariant.id + '" maps to state ' + state + ', which is not declared in AFTER.',
1165
+ evidence: { invariant: invariant.id, state },
1166
+ });
1167
+ }
1168
+ }
1169
+ }
1170
+ else if (mapped.kind === 'event-before-state') {
1171
+ if (!afterStates.has(mapped.state)) {
1172
+ findings.push({
1173
+ code: 'D2_MAPPED_STATE_MISSING',
1174
+ severity: 'warning',
1175
+ message: 'BEFORE invariant "' + invariant.id + '" maps to state ' + mapped.state + ', which is not declared in AFTER.',
1176
+ evidence: { invariant: invariant.id, state: mapped.state },
1177
+ });
1178
+ }
1179
+ }
1180
+ else if (mapped.kind === 'var-in-range') {
1181
+ if (!afterVariables.has(mapped.variable)) {
1182
+ findings.push({
1183
+ code: 'D2_VARIABLE_MISSING',
1184
+ severity: 'warning',
1185
+ message: 'BEFORE invariant "' + invariant.id + '" references variable ' + mapped.variable + ', which is not declared in AFTER.',
1186
+ evidence: { invariant: invariant.id, variable: mapped.variable },
1187
+ });
1188
+ continue;
1189
+ }
1190
+ }
1191
+ const violation = shortestViolationForInvariant(after, options, mapped);
1192
+ if (violation !== undefined) {
1193
+ findings.push({
1194
+ code: 'D2_INVARIANT_REGRESSION',
1195
+ severity: 'error',
1196
+ message: 'BEFORE invariant "' + invariant.id + '" no longer holds in AFTER: ' + violation.reason,
1197
+ path: violation.path,
1198
+ evidence: { beforeInvariant: invariant, afterInvariant: mapped },
1199
+ });
1200
+ }
1201
+ }
1202
+ return checkResult('D2', 'Invariant Continuity', findings, findings.length === 0 ? 'All BEFORE invariants continue to hold' : 'Invariant continuity findings: ' + findings.length);
1203
+ }
1204
+ function D3_regressionDelta(before, after, mapping) {
1205
+ const afterStateIds = new Set(after.states.map((state) => state.id));
1206
+ const beforeMappedIds = new Set(before.states.map((state) => mapStateId(mapping, state.id)));
1207
+ const addedStates = after.states.filter((state) => !beforeMappedIds.has(state.id)).map((state) => state.id).sort();
1208
+ const removedStates = before.states.filter((state) => !afterStateIds.has(mapStateId(mapping, state.id))).map((state) => state.id).sort();
1209
+ const beforeEvents = new Set(before.transitions.map((transition) => transition.event));
1210
+ const afterEvents = new Set(after.transitions.map((transition) => transition.event));
1211
+ const addedEvents = [...afterEvents].filter((event) => !beforeEvents.has(event)).sort();
1212
+ const removedEvents = [...beforeEvents].filter((event) => !afterEvents.has(event)).sort();
1213
+ const removedTransitions = before.transitions.filter((transition) => !after.transitions.some((candidate) => candidate.from === mapStateId(mapping, transition.from) &&
1214
+ candidate.event === transition.event &&
1215
+ candidate.to === mapStateId(mapping, transition.to)));
1216
+ const addedTransitions = after.transitions.filter((transition) => !before.transitions.some((candidate) => mapStateId(mapping, candidate.from) === transition.from &&
1217
+ candidate.event === transition.event &&
1218
+ mapStateId(mapping, candidate.to) === transition.to));
1219
+ const findings = [];
1220
+ for (const state of removedStates) {
1221
+ findings.push({ code: 'D3_REMOVED_STATE', severity: 'warning', message: 'BEFORE state ' + state + ' is not present in AFTER under the given mapping.', evidence: { state } });
1222
+ }
1223
+ for (const event of removedEvents) {
1224
+ findings.push({ code: 'D3_REMOVED_EVENT', severity: 'warning', message: 'BEFORE event ' + event + ' is not present in AFTER.', evidence: { event } });
1225
+ }
1226
+ for (const transition of removedTransitions) {
1227
+ findings.push({
1228
+ code: 'D3_REMOVED_TRANSITION',
1229
+ severity: 'warning',
1230
+ message: 'BEFORE transition ' + transition.from + ' -' + transition.event + '-> ' + transition.to + ' has no exact AFTER counterpart.',
1231
+ evidence: { transition },
1232
+ });
1233
+ }
1234
+ const detail = 'Delta: +' + addedStates.length + ' states, -' + removedStates.length + ' states, +' + addedEvents.length + ' events, -' + removedEvents.length + ' events, +' + addedTransitions.length + ' transitions, -' + removedTransitions.length + ' transitions';
1235
+ return checkResult('D3', 'Regression Delta', findings, detail);
1236
+ }
1237
+ function deadlockStateIds(model) {
1238
+ const outgoing = new Set(model.transitions.map((transition) => transition.from));
1239
+ return model.states.filter((state) => state.terminal !== true && !outgoing.has(state.id)).map((state) => state.id);
1240
+ }
1241
+ function closedSccStateSets(model) {
1242
+ return sccs(model)
1243
+ .filter((component) => {
1244
+ const componentSet = new Set(component);
1245
+ const internalEdges = model.transitions.some((transition) => componentSet.has(transition.from) && componentSet.has(transition.to));
1246
+ const escapingEdges = model.transitions.some((transition) => componentSet.has(transition.from) && !componentSet.has(transition.to));
1247
+ return internalEdges && !escapingEdges && !component.some((state) => isTerminal(model, state));
1248
+ })
1249
+ .map((component) => component.sort());
1250
+ }
1251
+ function D4_deadlockLivenessRegression(before, after, mapping) {
1252
+ const findings = [];
1253
+ const beforeDeadlock = new Set(deadlockStateIds(before).map((state) => mapStateId(mapping, state)));
1254
+ const afterDeadlock = deadlockStateIds(after);
1255
+ for (const state of afterDeadlock) {
1256
+ if (!beforeDeadlock.has(state)) {
1257
+ findings.push({
1258
+ code: 'D4_DEADLOCK_REGRESSION',
1259
+ severity: 'error',
1260
+ message: 'AFTER introduces deadlock in state ' + state + ' that was not deadlocked in BEFORE.',
1261
+ evidence: { state },
1262
+ });
1263
+ }
1264
+ }
1265
+ const beforeScc = new Set(closedSccStateSets(before).map((component) => component.map((state) => mapStateId(mapping, state)).sort().join(',')));
1266
+ const afterScc = closedSccStateSets(after);
1267
+ for (const component of afterScc) {
1268
+ const key = component.join(',');
1269
+ if (!beforeScc.has(key)) {
1270
+ findings.push({
1271
+ code: 'D4_LIVENESS_REGRESSION',
1272
+ severity: 'error',
1273
+ message: 'AFTER introduces a closed SCC with no exit and no terminal state: ' + key,
1274
+ evidence: { states: component },
1275
+ });
1276
+ }
1277
+ }
1278
+ return checkResult('D4', 'Deadlock/Liveness Regression', findings, findings.length === 0 ? 'No new deadlock or liveness regressions' : 'Regression findings: ' + findings.length);
1279
+ }
1280
+ function buildComparisonSummary(before, after, mapping) {
1281
+ const afterStateIds = new Set(after.states.map((state) => state.id));
1282
+ const beforeMappedIds = new Set(before.states.map((state) => mapStateId(mapping, state.id)));
1283
+ const addedStates = after.states.filter((state) => !beforeMappedIds.has(state.id)).map((state) => state.id).sort();
1284
+ const removedStates = before.states.filter((state) => !afterStateIds.has(mapStateId(mapping, state.id))).map((state) => state.id).sort();
1285
+ const beforeEvents = new Set(before.transitions.map((transition) => transition.event));
1286
+ const afterEvents = new Set(after.transitions.map((transition) => transition.event));
1287
+ const addedEvents = [...afterEvents].filter((event) => !beforeEvents.has(event)).sort();
1288
+ const removedEvents = [...beforeEvents].filter((event) => !afterEvents.has(event)).sort();
1289
+ const removedTransitions = before.transitions.filter((transition) => !after.transitions.some((candidate) => candidate.from === mapStateId(mapping, transition.from) &&
1290
+ candidate.event === transition.event &&
1291
+ candidate.to === mapStateId(mapping, transition.to)));
1292
+ const addedTransitions = after.transitions.filter((transition) => !before.transitions.some((candidate) => mapStateId(mapping, candidate.from) === transition.from &&
1293
+ candidate.event === transition.event &&
1294
+ mapStateId(mapping, candidate.to) === transition.to));
1295
+ return {
1296
+ beforeModelHash: modelHash(before),
1297
+ afterModelHash: modelHash(after),
1298
+ stateMapping: mapping,
1299
+ beforeStates: before.states.length,
1300
+ beforeTransitions: before.transitions.length,
1301
+ afterStates: after.states.length,
1302
+ afterTransitions: after.transitions.length,
1303
+ addedStates,
1304
+ removedStates,
1305
+ addedEvents,
1306
+ removedEvents,
1307
+ addedTransitions,
1308
+ removedTransitions,
1309
+ };
1310
+ }
1311
+ function A8_idempotentReplay(model, exploration) {
1312
+ const events = model.idempotentEvents ?? [];
1313
+ const findings = [];
1314
+ for (const event of events) {
1315
+ for (const runtime of exploration.reachable) {
1316
+ const onceOptions = stepRuntime(model, runtime, event);
1317
+ if (onceOptions.length === 0)
1318
+ continue;
1319
+ for (const once of onceOptions) {
1320
+ const twiceOptions = stepRuntime(model, once, event);
1321
+ if (twiceOptions.length === 0) {
1322
+ findings.push({
1323
+ code: 'A8_NOT_REPLAYABLE',
1324
+ severity: 'warning',
1325
+ message: 'Idempotent event ' + event + ' is not replayable after first application from ' + runtime.state + '.',
1326
+ path: [{ from: runtime.state, event, to: once.state }],
1327
+ evidence: { state: runtime.state, event },
1328
+ });
1329
+ continue;
1330
+ }
1331
+ for (const twice of twiceOptions) {
1332
+ if (runtimeKey(twice) !== runtimeKey(once)) {
1333
+ findings.push({
1334
+ code: 'A8_NOT_IDEMPOTENT',
1335
+ severity: 'error',
1336
+ message: 'Idempotent event ' + event + ' changes state when applied twice from ' + runtime.state + '.',
1337
+ path: [{ from: runtime.state, event, to: once.state }, { from: once.state, event, to: twice.state }],
1338
+ evidence: { state: runtime.state, event, afterOnce: once, afterTwice: twice },
1339
+ });
1340
+ break;
1341
+ }
1342
+ }
1343
+ }
1344
+ }
1345
+ }
1346
+ return checkResult('A8', 'Idempotent Replay', findings, findings.length === 0 ? 'Idempotent events are replay-safe' : 'Idempotent replay findings: ' + findings.length);
1347
+ }
1348
+ function S8_monotonicVariables(model) {
1349
+ const findings = [];
1350
+ for (const variable of model.variables ?? []) {
1351
+ if (variable.monotonic === undefined)
1352
+ continue;
1353
+ for (const transition of model.transitions) {
1354
+ for (const update of transition.updates ?? []) {
1355
+ if (update.variable !== variable.name)
1356
+ continue;
1357
+ if (variable.monotonic === 'inc' && update.op === 'dec') {
1358
+ findings.push({ code: 'S8_MONOTONIC_DECREASE', severity: 'error', message: 'Monotonic (inc) variable ' + variable.name + ' is decreased by ' + transition.event + '.', evidence: { variable: variable.name, transition } });
1359
+ }
1360
+ else if (variable.monotonic === 'dec' && update.op === 'inc') {
1361
+ findings.push({ code: 'S8_MONOTONIC_INCREASE', severity: 'error', message: 'Monotonic (dec) variable ' + variable.name + ' is increased by ' + transition.event + '.', evidence: { variable: variable.name, transition } });
1362
+ }
1363
+ else if (update.op === 'set') {
1364
+ findings.push({ code: 'S8_MONOTONIC_SET_REVIEW', severity: 'warning', message: 'Monotonic variable ' + variable.name + ' uses set in ' + transition.event + '; verify it cannot move backwards.', evidence: { variable: variable.name, transition } });
1365
+ }
1366
+ }
1367
+ }
1368
+ }
1369
+ return checkResult('S8', 'Monotonic Variables', findings, findings.length === 0 ? 'Monotonic variables are respected' : 'Monotonic findings: ' + findings.length);
1370
+ }
1371
+ function findLeadsToBadPath(model, start, target) {
1372
+ if (start.state === target)
1373
+ return undefined;
1374
+ const visited = new Set();
1375
+ const queue = [{ runtime: start, path: [] }];
1376
+ while (queue.length > 0) {
1377
+ const entry = queue.shift();
1378
+ const key = runtimeKey(entry.runtime);
1379
+ if (entry.runtime.state === target)
1380
+ continue;
1381
+ if (visited.has(key))
1382
+ return { path: entry.path, reason: 'Cycle avoids target ' + target };
1383
+ visited.add(key);
1384
+ const nexts = [];
1385
+ for (const event of allEvents(model)) {
1386
+ for (const next of stepRuntime(model, entry.runtime, event))
1387
+ nexts.push({ next, event });
1388
+ }
1389
+ if (nexts.length === 0)
1390
+ return { path: entry.path, reason: 'Dead end before target ' + target };
1391
+ for (const { next, event } of nexts) {
1392
+ queue.push({ runtime: next, path: [...entry.path, { from: entry.runtime.state, event, to: next.state }] });
1393
+ }
1394
+ }
1395
+ return { path: [], reason: 'No path reaches target ' + target };
1396
+ }
1397
+ function A9_leadsTo(model, exploration) {
1398
+ const findings = [];
1399
+ for (const invariant of model.invariants ?? []) {
1400
+ if (invariant.kind !== 'leads-to')
1401
+ continue;
1402
+ for (const runtime of exploration.reachable) {
1403
+ if (runtime.state !== invariant.from)
1404
+ continue;
1405
+ const bad = findLeadsToBadPath(model, runtime, invariant.to);
1406
+ if (bad !== undefined) {
1407
+ findings.push({
1408
+ code: 'A9_LEADS_TO_VIOLATION',
1409
+ severity: 'error',
1410
+ message: 'Leads-to invariant "' + invariant.id + '" violated from ' + invariant.from + ': ' + bad.reason,
1411
+ path: bad.path,
1412
+ evidence: { invariant },
1413
+ });
1414
+ break;
1415
+ }
1416
+ }
1417
+ }
1418
+ return checkResult('A9', 'Leads-To', findings, findings.length === 0 ? 'All leads-to invariants hold' : 'Leads-to findings: ' + findings.length);
1419
+ }
1420
+ function findSequenceViolation(model, options, invariant) {
1421
+ const events = invariant.events;
1422
+ const init = initialState(model);
1423
+ const key = (runtime, progress) => runtimeKey(runtime) + '|' + progress;
1424
+ const visited = new Set([key(init, 0)]);
1425
+ const queue = [{ runtime: init, progress: 0, path: [] }];
1426
+ let steps = 0;
1427
+ while (queue.length > 0) {
1428
+ const entry = queue.shift();
1429
+ if (++steps > options.maxStates)
1430
+ break;
1431
+ for (const event of allEvents(model)) {
1432
+ for (const next of stepRuntime(model, entry.runtime, event)) {
1433
+ let progress = entry.progress;
1434
+ let violation = false;
1435
+ if (progress < events.length && event === events[progress]) {
1436
+ progress += 1;
1437
+ }
1438
+ else {
1439
+ const index = events.indexOf(event);
1440
+ if (index > progress)
1441
+ violation = true;
1442
+ }
1443
+ const path = [...entry.path, { from: entry.runtime.state, event, to: next.state }];
1444
+ if (violation) {
1445
+ return { invariant, path, reason: 'Event ' + event + ' occurred before ' + events[progress] };
1446
+ }
1447
+ const nextKey = key(next, progress);
1448
+ if (!visited.has(nextKey)) {
1449
+ visited.add(nextKey);
1450
+ queue.push({ runtime: next, progress, path });
1451
+ }
1452
+ }
1453
+ }
1454
+ }
1455
+ return undefined;
1456
+ }
1457
+ function A10_sequenceOrder(model, options) {
1458
+ const findings = [];
1459
+ for (const invariant of model.invariants ?? []) {
1460
+ if (invariant.kind !== 'sequence')
1461
+ continue;
1462
+ const violation = findSequenceViolation(model, options, invariant);
1463
+ if (violation !== undefined) {
1464
+ findings.push({
1465
+ code: 'A10_SEQUENCE_VIOLATION',
1466
+ severity: 'error',
1467
+ message: 'Sequence invariant "' + invariant.id + '" violated: ' + violation.reason,
1468
+ path: violation.path,
1469
+ evidence: { invariant },
1470
+ });
1471
+ }
1472
+ }
1473
+ return checkResult('A10', 'Sequence Order', findings, findings.length === 0 ? 'All sequence invariants hold' : 'Sequence findings: ' + findings.length);
1474
+ }
1475
+ function findAtomicityViolation(model, options, invariant) {
1476
+ const atomic = new Set(invariant.events);
1477
+ const init = initialState(model);
1478
+ const key = (runtime, started, closed) => runtimeKey(runtime) + '|' + (started ? '1' : '0') + '|' + (closed ? '1' : '0');
1479
+ const visited = new Set([key(init, false, false)]);
1480
+ const queue = [{ runtime: init, started: false, closed: false, path: [] }];
1481
+ let steps = 0;
1482
+ while (queue.length > 0) {
1483
+ const entry = queue.shift();
1484
+ if (++steps > options.maxStates)
1485
+ break;
1486
+ for (const event of allEvents(model)) {
1487
+ for (const next of stepRuntime(model, entry.runtime, event)) {
1488
+ const started = entry.started || atomic.has(event);
1489
+ const closed = entry.closed || event === invariant.commit || (invariant.rollback !== undefined && event === invariant.rollback);
1490
+ const path = [...entry.path, { from: entry.runtime.state, event, to: next.state }];
1491
+ if (entry.started && !entry.closed && !atomic.has(event) && event !== invariant.commit && event !== invariant.rollback) {
1492
+ return { invariant, path, reason: 'Left atomic scope via ' + event + ' without commit/rollback' };
1493
+ }
1494
+ if (started && !closed && isTerminal(model, next.state)) {
1495
+ return { invariant, path, reason: 'Terminal state reached with incomplete atomic group' };
1496
+ }
1497
+ const nextKey = key(next, started, closed);
1498
+ if (!visited.has(nextKey)) {
1499
+ visited.add(nextKey);
1500
+ queue.push({ runtime: next, started, closed, path });
1501
+ }
1502
+ }
1503
+ }
1504
+ }
1505
+ return undefined;
1506
+ }
1507
+ function A11_atomicity(model, options) {
1508
+ const findings = [];
1509
+ for (const invariant of model.invariants ?? []) {
1510
+ if (invariant.kind !== 'atomicity')
1511
+ continue;
1512
+ const violation = findAtomicityViolation(model, options, invariant);
1513
+ if (violation !== undefined) {
1514
+ findings.push({
1515
+ code: 'A11_ATOMICITY_VIOLATION',
1516
+ severity: 'error',
1517
+ message: 'Atomicity invariant "' + invariant.id + '" violated: ' + violation.reason,
1518
+ path: violation.path,
1519
+ evidence: { invariant },
1520
+ });
1521
+ }
1522
+ }
1523
+ return checkResult('A11', 'Atomicity', findings, findings.length === 0 ? 'All atomicity invariants hold' : 'Atomicity findings: ' + findings.length);
1524
+ }
1525
+ // ---------------------------------------------------------------------------
1526
+ // main entry
1527
+ // ---------------------------------------------------------------------------
1528
+ export function runVerification(input, options = {}) {
1529
+ const normalized = {
1530
+ maxStates: options.maxStates ?? DEFAULT_MAX_STATES,
1531
+ maxPermutationEvents: options.maxPermutationEvents ?? DEFAULT_MAX_PERMUTATION_EVENTS,
1532
+ };
1533
+ const validation = validateModel(input);
1534
+ if (!validation.ok) {
1535
+ return {
1536
+ ok: false,
1537
+ schemaVersion: 1,
1538
+ modelHash: '',
1539
+ summary: { states: 0, transitions: 0, errors: validation.errors.length, warnings: 0, checksRun: 0 },
1540
+ checks: [{
1541
+ id: 'MODEL',
1542
+ name: 'Model Validation',
1543
+ status: 'fail',
1544
+ detail: 'Model schema validation failed: ' + validation.errors.length + ' errors',
1545
+ findings: validation.errors.map((message) => ({ code: 'MODEL_INVALID', severity: 'error', message })),
1546
+ }],
1547
+ };
1548
+ }
1549
+ const model = validation.model;
1550
+ const exploration = explore(model, normalized);
1551
+ const checks = [
1552
+ S1_reachability(model, exploration),
1553
+ S2_deadlock(model),
1554
+ S3_liveness(model),
1555
+ S4_determinism(model),
1556
+ S5_eventCompleteness(model),
1557
+ S6_guardCompleteness(model),
1558
+ S7_invariants(model, normalized),
1559
+ S8_monotonicVariables(model),
1560
+ A1_unexpectedEvents(model),
1561
+ A2_raceInterleaving(model, exploration),
1562
+ A3_orderPermutation(model, normalized),
1563
+ A4_pairSymmetry(model),
1564
+ A5_boundaryBlast(model),
1565
+ A6_resourceInjection(model),
1566
+ A7_shortestViolations(model, normalized),
1567
+ A8_idempotentReplay(model, exploration),
1568
+ A9_leadsTo(model, exploration),
1569
+ A10_sequenceOrder(model, normalized),
1570
+ A11_atomicity(model, normalized),
1571
+ ];
1572
+ let comparison;
1573
+ if (options.beforeModel !== undefined) {
1574
+ const beforeValidation = validateModel(options.beforeModel);
1575
+ if (!beforeValidation.ok) {
1576
+ return {
1577
+ ok: false,
1578
+ schemaVersion: 1,
1579
+ modelHash: modelHash(model),
1580
+ summary: {
1581
+ states: model.states.length,
1582
+ transitions: model.transitions.length,
1583
+ errors: beforeValidation.errors.length,
1584
+ warnings: 0,
1585
+ checksRun: checks.length + 1,
1586
+ truncated: exploration.truncated,
1587
+ },
1588
+ checks: [
1589
+ ...checks,
1590
+ {
1591
+ id: 'BEFORE_MODEL',
1592
+ name: 'Before Model Validation',
1593
+ status: 'fail',
1594
+ detail: 'Before model schema validation failed: ' + beforeValidation.errors.length + ' errors',
1595
+ findings: beforeValidation.errors.map((message) => ({ code: 'BEFORE_MODEL_INVALID', severity: 'error', message })),
1596
+ },
1597
+ ],
1598
+ };
1599
+ }
1600
+ const before = beforeValidation.model;
1601
+ const mapping = options.stateMapping ?? {};
1602
+ checks.push(D1_behavioralPreservation(before, model, mapping), D2_invariantContinuity(before, model, normalized, mapping), D3_regressionDelta(before, model, mapping), D4_deadlockLivenessRegression(before, model, mapping));
1603
+ comparison = buildComparisonSummary(before, model, mapping);
1604
+ }
1605
+ const errors = checks.reduce((sum, check) => sum + check.findings.filter((finding) => finding.severity === 'error').length, 0);
1606
+ const warnings = checks.reduce((sum, check) => sum + check.findings.filter((finding) => finding.severity === 'warning').length, 0);
1607
+ return {
1608
+ ok: true,
1609
+ schemaVersion: 1,
1610
+ modelHash: modelHash(model),
1611
+ summary: {
1612
+ states: model.states.length,
1613
+ transitions: model.transitions.length,
1614
+ errors,
1615
+ warnings,
1616
+ checksRun: checks.length,
1617
+ truncated: exploration.truncated,
1618
+ },
1619
+ checks,
1620
+ ...(comparison === undefined ? {} : { comparison }),
1621
+ };
1622
+ }