dsh-logicprobe 0.7.1 → 0.8.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.
@@ -5,7 +5,8 @@ Reads the same LogicModelV1 JSON schema as the DSH `logicprobe_verify` /
5
5
  `logicprobe_compose_verify` / `logicprobe_export` tools and runs the same
6
6
  checks (S1-S8 structural, A1-A14 adversarial, D1-D4 before/after regression,
7
7
  C1/C2 composition) plus the four external-tool exporters (UPPAAL / TLA+ /
8
- PRISM / SPIN). Pure stdlib, no third-party imports.
8
+ PRISM / SPIN) and the UML front end (render / parse / review, mirroring
9
+ `src/uml.ts`). Pure stdlib, no third-party imports.
9
10
 
10
11
  Usage:
11
12
  python logicprobe-engine.py verify model.json [--before-model before.json]
@@ -13,9 +14,16 @@ Usage:
13
14
  python logicprobe-engine.py compose m1.json m2.json [m3.json ...]
14
15
  [--rendezvous ev1,ev2] [--max-states N]
15
16
  python logicprobe-engine.py export model.json --format uppaal|tla|prism|spin
17
+ python logicprobe-engine.py uml-render model.json [--notation mermaid|plantuml]
18
+ [--diagram state|activity|sequence] [--max-steps N]
19
+ python logicprobe-engine.py uml-parse diagram.txt [--notation auto|mermaid|plantuml]
20
+ python logicprobe-engine.py uml-review [--model model.json] [--diagram diagram.txt]
21
+ [--notation auto|mermaid|plantuml] [--diagram-kind state|activity|sequence]
22
+ [--no-round-trip] [--max-steps N]
16
23
 
17
24
  Output: JSON verification/composition report on stdout (same shape as the DSH
18
- tool result), or the export result JSON (format / primary / extras / warnings).
25
+ tool result), or the export result JSON (format / primary / extras / warnings),
26
+ or the UML render/parse/review JSON.
19
27
  """
20
28
  import argparse
21
29
  import hashlib
@@ -1862,28 +1870,55 @@ def S8_monotonic_variables(model):
1862
1870
 
1863
1871
 
1864
1872
  def _find_leads_to_bad_path(model, start, target):
1873
+ # Find a run from start that never reaches target, or None when every run does.
1874
+ # The property is universal (see the A9 row in SKILL.md): one branch that loops
1875
+ # forever, or that stops before the target, refutes it.
1876
+ #
1877
+ # Depth-first walk of the run graph with three colours; target runs are success
1878
+ # leaves that are never expanded. A node reached while it is on the current walk
1879
+ # (GRAY) closes a cycle that avoids the target. A node with no outgoing step at
1880
+ # all stops the machine where it stands, which is the same violation for a
1881
+ # different reason. A node whose walk completed without a violation is BLACK, and
1882
+ # reaching it again from another branch is a shared sub-graph, not a cycle -- that
1883
+ # is why the colour map cannot be a plain visited set: a diamond (two branches
1884
+ # rejoining) is acyclic and must pass, while a genuine cycle must not. A run is
1885
+ # identified by its state plus its variable values.
1865
1886
  if start['state'] == target:
1866
1887
  return None
1867
- visited = set()
1868
- queue = deque([{'runtime': start, 'path': []}])
1869
- while queue:
1870
- entry = queue.popleft()
1871
- k = _runtime_key(entry['runtime'])
1872
- if entry['runtime']['state'] == target:
1888
+ GRAY = 1
1889
+ BLACK = 2
1890
+ color = {}
1891
+ stack = [{'runtime': start, 'path': [], 'nexts': None, 'index': 0}]
1892
+ color[_runtime_key(start)] = GRAY
1893
+ while stack:
1894
+ frame = stack[-1]
1895
+ if frame['nexts'] is None:
1896
+ nexts = []
1897
+ for event in _all_events(model):
1898
+ for nxt in _step_runtime(model, frame['runtime'], event):
1899
+ nexts.append({'next': nxt, 'event': event})
1900
+ frame['nexts'] = nexts
1901
+ if not nexts:
1902
+ return {'path': frame['path'], 'reason': 'Dead end before target ' + target}
1903
+ if frame['index'] >= len(frame['nexts']):
1904
+ color[_runtime_key(frame['runtime'])] = BLACK
1905
+ stack.pop()
1873
1906
  continue
1874
- if k in visited:
1875
- return {'path': entry['path'], 'reason': 'Cycle avoids target ' + target}
1876
- visited.add(k)
1877
- nexts = []
1878
- for event in _all_events(model):
1879
- for nxt in _step_runtime(model, entry['runtime'], event):
1880
- nexts.append({'next': nxt, 'event': event})
1881
- if not nexts:
1882
- return {'path': entry['path'], 'reason': 'Dead end before target ' + target}
1883
- for item in nexts:
1884
- queue.append({'runtime': item['next'],
1885
- 'path': list(entry['path']) + [{'from': entry['runtime']['state'], 'event': item['event'], 'to': item['next']['state']}]})
1886
- return {'path': [], 'reason': 'No path reaches target ' + target}
1907
+ item = frame['nexts'][frame['index']]
1908
+ frame['index'] += 1
1909
+ step = {'from': frame['runtime']['state'], 'event': item['event'], 'to': item['next']['state']}
1910
+ if item['next']['state'] == target:
1911
+ continue
1912
+ key = _runtime_key(item['next'])
1913
+ seen = color.get(key)
1914
+ if seen == GRAY:
1915
+ return {'path': frame['path'] + [step], 'reason': 'Cycle avoids target ' + target}
1916
+ if seen == BLACK:
1917
+ continue
1918
+ color[key] = GRAY
1919
+ stack.append({'runtime': item['next'], 'path': frame['path'] + [step], 'nexts': None, 'index': 0})
1920
+ # Every branch either reached the target or rejoined a branch that did.
1921
+ return None
1887
1922
 
1888
1923
 
1889
1924
  def A9_leads_to(model, exploration):
@@ -3087,6 +3122,1516 @@ def export_model(input_value, fmt):
3087
3122
  return _export_spin(ex)
3088
3123
 
3089
3124
 
3125
+ # ---------------------------------------------------------------------------
3126
+ # UML front end (mirror of src/uml.ts)
3127
+ # ---------------------------------------------------------------------------
3128
+
3129
+ UML_NOTATIONS = ('mermaid', 'plantuml')
3130
+ UML_DIAGRAMS = ('state', 'activity', 'sequence')
3131
+
3132
+ # Marker every generated diagram carries; renderers ignore it, the parser uses it.
3133
+ _DIRECTIVE_NAMESPACE = 'logicprobe:'
3134
+
3135
+ # State id / event name characters that would break the generated label syntax.
3136
+ _UNSAFE_LABEL_RE = re.compile(r'[\[\]/\n\r\t]')
3137
+
3138
+ # Mermaid flowchart keywords that cannot stand alone as a node id.
3139
+ _RESERVED_NODE_IDS = frozenset(['end', 'graph', 'subgraph', 'class', 'classDef', 'click', 'style',
3140
+ 'linkStyle', 'direction'])
3141
+
3142
+ # Ids the notation can spell without an alias (JS `$` is end-of-input, hence \Z).
3143
+ _PLAIN_ID_RE = re.compile(r'^[A-Za-z_][A-Za-z0-9_]*\Z')
3144
+
3145
+ # JavaScript's \s / String.prototype.trim() character set, so guard tokenising and
3146
+ # label trimming treat exactly the same characters as whitespace as the TypeScript side.
3147
+ _JS_WHITESPACE = ('\t\n\x0b\x0c\r \xa0\u1680\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007'
3148
+ '\u2008\u2009\u200a\u2028\u2029\u202f\u205f\u3000\ufeff')
3149
+ _JS_SPACE_RE = re.compile('[' + _JS_WHITESPACE + ']')
3150
+
3151
+
3152
+ def _js_trim(text):
3153
+ return text.strip(_JS_WHITESPACE)
3154
+
3155
+
3156
+ def _js_string(value):
3157
+ """JavaScript String(value) for the value kinds this module renders."""
3158
+ if value is None:
3159
+ return 'undefined'
3160
+ if isinstance(value, bool):
3161
+ return 'true' if value else 'false'
3162
+ if isinstance(value, str):
3163
+ return value
3164
+ if isinstance(value, (int, float)):
3165
+ return js_number(value)
3166
+ return str(value)
3167
+
3168
+
3169
+ def _char_at(text, index):
3170
+ """JavaScript `text[index]`: '' when out of range (undefined never equals a char)."""
3171
+ return text[index] if 0 <= index < len(text) else ''
3172
+
3173
+
3174
+ def _is_digit(ch):
3175
+ return len(ch) == 1 and '0' <= ch <= '9'
3176
+
3177
+
3178
+ def _is_ascii_letter(ch):
3179
+ return len(ch) == 1 and (('a' <= ch <= 'z') or ('A' <= ch <= 'Z'))
3180
+
3181
+
3182
+ def _is_ident_char(ch):
3183
+ return _is_ascii_letter(ch) or _is_digit(ch) or ch == '_' or ch == '.'
3184
+
3185
+
3186
+ def _number_from_token(text):
3187
+ """JavaScript Number(literal): exact for integers inside the safe range."""
3188
+ value = int(text)
3189
+ if -9007199254740991 <= value <= 9007199254740991:
3190
+ return value
3191
+ return float(text)
3192
+
3193
+
3194
+ def _js_strict_equal(left, right):
3195
+ """JavaScript === for guard literal values (booleans are never equal to numbers)."""
3196
+ if isinstance(left, bool) or isinstance(right, bool):
3197
+ return isinstance(left, bool) and isinstance(right, bool) and left == right
3198
+ return left == right
3199
+
3200
+
3201
+ def _literal_text(value):
3202
+ if isinstance(value, bool):
3203
+ return 'true' if value else 'false'
3204
+ return js_number(value)
3205
+
3206
+
3207
+ def guard_text(node):
3208
+ """Canonical guard text; the inverse of parse_guard_text."""
3209
+ if 'variable' in node:
3210
+ return node['variable'] + ' ' + node['op'] + ' ' + _literal_text(node['value'])
3211
+ if 'all' in node:
3212
+ return '(' + ' && '.join(guard_text(child) for child in node['all']) + ')'
3213
+ if 'any' in node:
3214
+ return '(' + ' || '.join(guard_text(child) for child in node['any']) + ')'
3215
+ return '!(' + guard_text(node['not']) + ')'
3216
+
3217
+
3218
+ def _updates_text(updates):
3219
+ parts = []
3220
+ for update in updates:
3221
+ value = update['value'] if update.get('value') is not None else (0 if update['op'] == 'set' else 1)
3222
+ if update['op'] == 'set':
3223
+ parts.append(update['variable'] + ' := ' + _literal_text(value))
3224
+ elif update['op'] == 'inc':
3225
+ parts.append(update['variable'] + ' := ' + update['variable'] + ' + ' + _literal_text(value))
3226
+ else:
3227
+ parts.append(update['variable'] + ' := ' + update['variable'] + ' - ' + _literal_text(value))
3228
+ return ', '.join(parts)
3229
+
3230
+
3231
+ def _transition_text(transition):
3232
+ text = transition['event']
3233
+ if transition.get('guard') is not None:
3234
+ text += ' [' + guard_text(transition['guard']) + ']'
3235
+ updates = transition.get('updates')
3236
+ if updates is not None and len(updates) > 0:
3237
+ text += ' / ' + _updates_text(updates)
3238
+ return text
3239
+
3240
+
3241
+ def _display_text(text):
3242
+ return _js_trim(re.sub(r'[\r\n\t]+', ' ', text).replace('"', "'"))
3243
+
3244
+
3245
+ # ---- rendering ------------------------------------------------------------
3246
+
3247
+ def _prepare_render(input_value):
3248
+ ok, model_or_errors = validate_model(input_value)
3249
+ if not ok:
3250
+ raise ValueError('model invalid: ' + '; '.join(model_or_errors))
3251
+ model = model_or_errors
3252
+ warnings = []
3253
+ used = set()
3254
+ alias = {}
3255
+ display = {}
3256
+ for state in model['states']:
3257
+ sid = state['id']
3258
+ candidate = sid
3259
+ if _PLAIN_ID_RE.match(candidate) is None:
3260
+ candidate = re.sub(r'[^A-Za-z0-9_]', '_', candidate)
3261
+ if candidate == '' or _is_digit(candidate[0]):
3262
+ candidate = 'S_' + candidate
3263
+ warnings.append('UML_RENDER_ID_SANITIZED: state id "' + sid + '" is not a plain identifier; the diagram draws it as "'
3264
+ + candidate + '" and pins the original with a ' + _DIRECTIVE_NAMESPACE + 'alias directive.')
3265
+ if candidate in _RESERVED_NODE_IDS:
3266
+ warnings.append('UML_RENDER_RESERVED_ID: state alias "' + candidate + '" collides with a diagram keyword; Mermaid renders it, but a hand edit may not.')
3267
+ unique = candidate
3268
+ suffix = 2
3269
+ while unique in used:
3270
+ unique = candidate + '_' + str(suffix)
3271
+ suffix += 1
3272
+ if unique != candidate:
3273
+ warnings.append('UML_RENDER_ALIAS_COLLISION: state id "' + sid + '" shares an alias with another state; the diagram uses "' + unique + '".')
3274
+ used.add(unique)
3275
+ alias[sid] = unique
3276
+ meaning = None
3277
+ narrative = model.get('narrative')
3278
+ if narrative is not None and narrative.get('states') is not None:
3279
+ meaning = narrative['states'].get(sid)
3280
+ display[sid] = sid if meaning is None else _display_text(sid + '(' + meaning + ')')
3281
+ for transition in model['transitions']:
3282
+ if _UNSAFE_LABEL_RE.search(transition['event']):
3283
+ warnings.append('UML_RENDER_LABEL_UNSAFE: event "' + transition['event'] + '" contains a character (one of [ ] / or a line break) '
3284
+ 'that the diagram label syntax uses; the rendered diagram cannot be read back verbatim.')
3285
+ terminal = set(state['id'] for state in model['states'] if state.get('terminal') is True)
3286
+ return {'model': model, 'alias': alias, 'display': display, 'terminal': terminal, 'warnings': warnings}
3287
+
3288
+
3289
+ def _directive_lines(notation, diagram, context):
3290
+ prefix = '%%' if notation == 'mermaid' else "'"
3291
+ model = context['model']
3292
+ lines = [prefix + _DIRECTIVE_NAMESPACE + 'uml v1 notation=' + notation + ' diagram=' + diagram]
3293
+ lines.append(prefix + _DIRECTIVE_NAMESPACE + 'init ' + model['init'])
3294
+ terminals = [state['id'] for state in model['states'] if state.get('terminal') is True]
3295
+ if len(terminals) > 0:
3296
+ lines.append(prefix + _DIRECTIVE_NAMESPACE + 'terminal ' + ','.join(terminals))
3297
+ for state in model['states']:
3298
+ if context['alias'].get(state['id']) != state['id']:
3299
+ lines.append(prefix + _DIRECTIVE_NAMESPACE + 'alias ' + context['alias'][state['id']] + ' ' + state['id'])
3300
+ # Variable kinds are not recoverable from the notation: `armed := 1` reads as an
3301
+ # integer assignment whichever kind the model declared. Pinning them keeps the
3302
+ # round trip exact instead of reporting a fidelity loss that is really a
3303
+ # notation limit.
3304
+ for variable in model.get('variables') or []:
3305
+ lines.append(prefix + _DIRECTIVE_NAMESPACE + 'variable ' + variable['name'] + ' ' + variable['kind'])
3306
+ return lines
3307
+
3308
+
3309
+ def _grouped_transitions(model):
3310
+ order = []
3311
+ groups = {}
3312
+ for transition in model['transitions']:
3313
+ frm = transition['from']
3314
+ if frm not in groups:
3315
+ groups[frm] = [transition]
3316
+ order.append(frm)
3317
+ else:
3318
+ groups[frm].append(transition)
3319
+ return [{'from': frm, 'transitions': groups[frm]} for frm in order]
3320
+
3321
+
3322
+ def _render_mermaid_state(context):
3323
+ model = context['model']
3324
+ alias = context['alias']
3325
+ lines = _directive_lines('mermaid', 'state', context)
3326
+ lines.append('stateDiagram-v2')
3327
+ lines.append(' [*] --> ' + alias[model['init']])
3328
+ for state in model['states']:
3329
+ state_alias = alias[state['id']]
3330
+ label = context['display'].get(state['id'], state['id'])
3331
+ # Every state is declared, even when its label equals its alias. A state that
3332
+ # no transition touches (an isolated terminal, a start state with no edge yet)
3333
+ # would otherwise leave no trace in the text at all, and the round-trip check
3334
+ # would have to report a loss the notation never caused.
3335
+ lines.append(' state "' + label + '" as ' + state_alias)
3336
+ for group in _grouped_transitions(model):
3337
+ for transition in group['transitions']:
3338
+ lines.append(' ' + alias[transition['from']] + ' --> ' + alias[transition['to']] + ' : ' + _transition_text(transition))
3339
+ for state in model['states']:
3340
+ if state.get('terminal') is True:
3341
+ lines.append(' ' + alias[state['id']] + ' --> [*]')
3342
+ return '\n'.join(lines) + '\n'
3343
+
3344
+
3345
+ def _render_plantuml_state(context):
3346
+ model = context['model']
3347
+ alias = context['alias']
3348
+ lines = ['@startuml']
3349
+ lines.extend(_directive_lines('plantuml', 'state', context))
3350
+ lines.append('[*] --> ' + alias[model['init']])
3351
+ for state in model['states']:
3352
+ lines.append('state "' + context['display'].get(state['id'], state['id']) + '" as ' + alias[state['id']])
3353
+ for group in _grouped_transitions(model):
3354
+ for transition in group['transitions']:
3355
+ lines.append(alias[transition['from']] + ' --> ' + alias[transition['to']] + ' : ' + _transition_text(transition))
3356
+ for state in model['states']:
3357
+ if state.get('terminal') is True:
3358
+ lines.append(alias[state['id']] + ' --> [*]')
3359
+ lines.append('@enduml')
3360
+ return '\n'.join(lines) + '\n'
3361
+
3362
+
3363
+ def _render_mermaid_activity(context):
3364
+ model = context['model']
3365
+ alias = context['alias']
3366
+ lines = _directive_lines('mermaid', 'activity', context)
3367
+ lines.append('flowchart TD')
3368
+ for state in model['states']:
3369
+ state_alias = alias[state['id']]
3370
+ text = context['display'].get(state['id'], state['id'])
3371
+ lines.append(' ' + state_alias + ('(["' + text + '"])' if state.get('terminal') is True else '["' + text + '"]'))
3372
+ for group in _grouped_transitions(model):
3373
+ for transition in group['transitions']:
3374
+ lines.append(' ' + alias[transition['from']] + ' -->|"' + _transition_text(transition) + '"| ' + alias[transition['to']])
3375
+ return '\n'.join(lines) + '\n'
3376
+
3377
+
3378
+ def _render_sequence(context, notation, max_steps):
3379
+ """One BFS trace of the machine, written as a sequence diagram."""
3380
+ model = context['model']
3381
+ alias = context['alias']
3382
+ lines = []
3383
+ if notation == 'mermaid':
3384
+ lines.extend(_directive_lines('mermaid', 'sequence', context))
3385
+ lines.append('sequenceDiagram')
3386
+ lines.append(' participant ENV as Environment')
3387
+ lines.append(' participant M as Machine')
3388
+ else:
3389
+ lines.append('@startuml')
3390
+ lines.extend(_directive_lines('plantuml', 'sequence', context))
3391
+ lines.append('participant ENV as Environment')
3392
+ lines.append('participant M as Machine')
3393
+ by_from = {}
3394
+ for transition in model['transitions']:
3395
+ by_from.setdefault(transition['from'], []).append(transition)
3396
+ seen = set([model['init']])
3397
+ queue = deque([model['init']])
3398
+ arrow = 'ENV->>M: ' if notation == 'mermaid' else 'ENV -> M : '
3399
+ note = ' Note over M: ' if notation == 'mermaid' else 'note over M : '
3400
+ lines.append((' ' if notation == 'mermaid' else '') + 'Note over M: init ' + model['init'])
3401
+ steps = 0
3402
+ truncated = False
3403
+ while len(queue) > 0:
3404
+ current = queue.popleft()
3405
+ for transition in by_from.get(current, []):
3406
+ if steps >= max_steps:
3407
+ truncated = True
3408
+ break
3409
+ steps += 1
3410
+ lines.append((' ' if notation == 'mermaid' else '') + arrow + _transition_text(transition))
3411
+ lines.append(note + alias[transition['from']] + ' -> ' + alias[transition['to']])
3412
+ if transition['to'] not in seen:
3413
+ seen.add(transition['to'])
3414
+ queue.append(transition['to'])
3415
+ if truncated:
3416
+ break
3417
+ if notation == 'plantuml':
3418
+ lines.append('@enduml')
3419
+ return {'text': '\n'.join(lines) + '\n', 'truncated': truncated}
3420
+
3421
+
3422
+ def render_uml(input_value, notation='mermaid', diagram='state', max_steps=60):
3423
+ """Mirror of renderUml: a validated LogicModelV1 as Mermaid/PlantUML text."""
3424
+ if notation not in UML_NOTATIONS:
3425
+ raise ValueError('unknown notation "' + _js_string(notation) + '"; expected ' + ' | '.join(UML_NOTATIONS))
3426
+ if diagram not in UML_DIAGRAMS:
3427
+ raise ValueError('unknown diagram "' + _js_string(diagram) + '"; expected ' + ' | '.join(UML_DIAGRAMS))
3428
+ if notation == 'plantuml' and diagram == 'activity':
3429
+ raise ValueError('plantuml has no faithful activity view here (its activity syntax is a structured flowchart language; '
3430
+ 'a graph with merges or cycles needs a while/if reconstruction logicprobe does not perform) — '
3431
+ 'use notation "mermaid" for the activity view, or diagram "state"')
3432
+ context = _prepare_render(input_value)
3433
+ warnings = list(context['warnings'])
3434
+ if diagram == 'state':
3435
+ primary = _render_mermaid_state(context) if notation == 'mermaid' else _render_plantuml_state(context)
3436
+ elif diagram == 'activity':
3437
+ primary = _render_mermaid_activity(context)
3438
+ else:
3439
+ rendered = _render_sequence(context, notation, max_steps)
3440
+ primary = rendered['text']
3441
+ if rendered['truncated']:
3442
+ warnings.append('UML_RENDER_SEQUENCE_TRUNCATED: the trace was capped at ' + str(max_steps) + ' steps; a sequence diagram is one trace, '
3443
+ 'not the whole machine — use diagram "state" for the full topology.')
3444
+ warnings.append('UML_RENDER_SEQUENCE_IS_TRACE: a sequence diagram shows one BFS trace; branches appear as separate guarded messages '
3445
+ 'and unreachable branches are absent by construction.')
3446
+ return {'notation': notation, 'diagram': diagram, 'primary': primary, 'warnings': warnings}
3447
+
3448
+
3449
+ # ---- parsing: guard expressions -------------------------------------------
3450
+
3451
+ def _tokenize_guard(text):
3452
+ tokens = []
3453
+ index = 0
3454
+ while index < len(text):
3455
+ char = text[index]
3456
+ if _JS_SPACE_RE.match(char):
3457
+ index += 1
3458
+ continue
3459
+ if char == '(':
3460
+ tokens.append(('lparen', char))
3461
+ index += 1
3462
+ continue
3463
+ if char == ')':
3464
+ tokens.append(('rparen', char))
3465
+ index += 1
3466
+ continue
3467
+ if char == '&' and _char_at(text, index + 1) == '&':
3468
+ tokens.append(('and', '&&'))
3469
+ index += 2
3470
+ continue
3471
+ if char == '|' and _char_at(text, index + 1) == '|':
3472
+ tokens.append(('or', '||'))
3473
+ index += 2
3474
+ continue
3475
+ if char == '!':
3476
+ if _char_at(text, index + 1) == '=':
3477
+ tokens.append(('op', '!='))
3478
+ index += 2
3479
+ continue
3480
+ tokens.append(('not', '!'))
3481
+ index += 1
3482
+ continue
3483
+ two = text[index:index + 2]
3484
+ if two == '==' or two == '<=' or two == '>=':
3485
+ tokens.append(('op', two))
3486
+ index += 2
3487
+ continue
3488
+ if char == '<' or char == '>':
3489
+ tokens.append(('op', char))
3490
+ index += 1
3491
+ continue
3492
+ if char == '=':
3493
+ tokens.append(('op', '=='))
3494
+ index += 1
3495
+ continue
3496
+ if _is_digit(char) or (char == '-' and _is_digit(_char_at(text, index + 1))):
3497
+ end = index + 1
3498
+ while end < len(text) and _is_digit(text[end]):
3499
+ end += 1
3500
+ tokens.append(('number', text[index:end]))
3501
+ index = end
3502
+ continue
3503
+ if _is_ascii_letter(char) or char == '_':
3504
+ end = index + 1
3505
+ while end < len(text) and _is_ident_char(text[end]):
3506
+ end += 1
3507
+ word = text[index:end]
3508
+ index = end
3509
+ if word == 'and':
3510
+ tokens.append(('and', word))
3511
+ elif word == 'or':
3512
+ tokens.append(('or', word))
3513
+ elif word == 'not':
3514
+ tokens.append(('not', word))
3515
+ elif word == 'true' or word == 'false':
3516
+ tokens.append(('boolean', word))
3517
+ else:
3518
+ tokens.append(('ident', word))
3519
+ continue
3520
+ raise ValueError('guard text not understood near "' + text[index:] + '"')
3521
+ return tokens
3522
+
3523
+
3524
+ class _GuardReader:
3525
+ def __init__(self, tokens, source):
3526
+ self.tokens = tokens
3527
+ self.source = source
3528
+ self.position = 0
3529
+
3530
+ def parse(self):
3531
+ node = self._parse_or()
3532
+ if self.position != len(self.tokens):
3533
+ raise ValueError('trailing tokens in guard "' + self.source + '"')
3534
+ return node
3535
+
3536
+ def _peek(self):
3537
+ return self.tokens[self.position] if self.position < len(self.tokens) else None
3538
+
3539
+ def _parse_or(self):
3540
+ parts = [self._parse_and()]
3541
+ while self._peek() is not None and self._peek()[0] == 'or':
3542
+ self.position += 1
3543
+ parts.append(self._parse_and())
3544
+ return parts[0] if len(parts) == 1 else {'any': parts}
3545
+
3546
+ def _parse_and(self):
3547
+ parts = [self._parse_unary()]
3548
+ while self._peek() is not None and self._peek()[0] == 'and':
3549
+ self.position += 1
3550
+ parts.append(self._parse_unary())
3551
+ return parts[0] if len(parts) == 1 else {'all': parts}
3552
+
3553
+ def _parse_unary(self):
3554
+ token = self._peek()
3555
+ if token is not None and token[0] == 'not':
3556
+ self.position += 1
3557
+ return {'not': self._parse_unary()}
3558
+ return self._parse_primary()
3559
+
3560
+ def _parse_primary(self):
3561
+ token = self._peek()
3562
+ if token is not None and token[0] == 'lparen':
3563
+ self.position += 1
3564
+ inner = self._parse_or()
3565
+ closing = self._peek()
3566
+ if closing is None or closing[0] != 'rparen':
3567
+ raise ValueError('unbalanced parentheses in guard "' + self.source + '"')
3568
+ self.position += 1
3569
+ return inner
3570
+ if token is None or token[0] != 'ident':
3571
+ raise ValueError('expected a variable name in guard "' + self.source + '"')
3572
+ self.position += 1
3573
+ op = self._peek()
3574
+ if op is None or op[0] != 'op':
3575
+ raise ValueError('expected a comparison operator after "' + token[1] + '" in guard "' + self.source + '"')
3576
+ self.position += 1
3577
+ value = self._peek()
3578
+ if value is not None and value[0] == 'number':
3579
+ self.position += 1
3580
+ return {'variable': token[1], 'op': op[1], 'value': _number_from_token(value[1])}
3581
+ if value is not None and value[0] == 'boolean':
3582
+ if op[1] != '==' and op[1] != '!=':
3583
+ raise ValueError('boolean variable "' + token[1] + '" only supports == / != (guard "' + self.source + '")')
3584
+ self.position += 1
3585
+ return {'variable': token[1], 'op': op[1], 'value': value[1] == 'true'}
3586
+ raise ValueError('expected a literal value for "' + token[1] + '" in guard "' + self.source + '"')
3587
+
3588
+
3589
+ def parse_guard_text(text):
3590
+ """Parse a guard expression such as `(retry < 3 && armed == true)`."""
3591
+ return _GuardReader(_tokenize_guard(text), text).parse()
3592
+
3593
+
3594
+ _UPDATE_SHIM_RE = re.compile(r'^([A-Za-z_][A-Za-z0-9_]*)\s*(\+\+|--)\Z')
3595
+ _UPDATE_ASSIGN_RE = re.compile(r'^([A-Za-z_][A-Za-z0-9_]*)\s*:?=\s*(.+)\Z')
3596
+ _UPDATE_BOOL_RE = re.compile(r'^(true|false)\Z')
3597
+ _UPDATE_INT_RE = re.compile(r'^-?[0-9]+\Z')
3598
+ _UPDATE_ARITH_RE = re.compile(r'^([A-Za-z_][A-Za-z0-9_]*)\s*([+-])\s*([0-9]+)\Z')
3599
+
3600
+
3601
+ def parse_updates_text(text, warnings):
3602
+ """Parse a UML action clause such as `retry := retry + 1, armed := true`."""
3603
+ out = []
3604
+ for raw in text.split(','):
3605
+ clause = _js_trim(raw)
3606
+ if clause == '':
3607
+ continue
3608
+ shim = _UPDATE_SHIM_RE.match(clause)
3609
+ if shim is not None:
3610
+ out.append({'variable': shim.group(1), 'op': 'inc' if shim.group(2) == '++' else 'dec', 'value': 1})
3611
+ continue
3612
+ assignment = _UPDATE_ASSIGN_RE.match(clause)
3613
+ if assignment is None:
3614
+ raise ValueError('action clause not understood: "' + clause + '" (expected "var := value")')
3615
+ name = assignment.group(1)
3616
+ value = _js_trim(assignment.group(2))
3617
+ if value == name:
3618
+ warnings.append('UML_PARSE_NOOP_UPDATE: action "' + clause + '" assigns the variable to itself; dropped.')
3619
+ continue
3620
+ if _UPDATE_BOOL_RE.match(value):
3621
+ out.append({'variable': name, 'op': 'set', 'value': 1 if value == 'true' else 0})
3622
+ continue
3623
+ if _UPDATE_INT_RE.match(value):
3624
+ out.append({'variable': name, 'op': 'set', 'value': _number_from_token(value)})
3625
+ continue
3626
+ arithmetic = _UPDATE_ARITH_RE.match(value)
3627
+ if arithmetic is None:
3628
+ raise ValueError('action value not understood: "' + value + '" (expected a literal, or "var + n" / "var - n")')
3629
+ if arithmetic.group(1) != name:
3630
+ raise ValueError('action "' + clause + '" reads a different variable; LogicModelV1 updates touch one variable')
3631
+ out.append({'variable': name, 'op': 'inc' if arithmetic.group(2) == '+' else 'dec',
3632
+ 'value': _number_from_token(arithmetic.group(3))})
3633
+ return out
3634
+
3635
+
3636
+ # ---- parsing: diagram text ------------------------------------------------
3637
+
3638
+ _STATE_EDGE_RE = re.compile(r'^(.+?)\s*-->\s*(.+?)(?:\s*:\s*(.*))?\Z')
3639
+ _STATE_NOTE_RE = re.compile(r'^note\s+(?:over|right of|left of)\s+([A-Za-z_][A-Za-z0-9_]*)\s*:\s*(.+)\Z', re.I)
3640
+ _NOTE_RE = re.compile(r'^note\b', re.I)
3641
+ _END_NOTE_RE = re.compile(r'^end\s*note\Z', re.I)
3642
+ _STATE_DECL_RE = re.compile(r'^state\s+"([^"]*)"\s+as\s+([A-Za-z_][A-Za-z0-9_]*)\Z')
3643
+ _BARE_STATE_RE = re.compile(r'^state\s+([A-Za-z_][A-Za-z0-9_]*)\s*\{?\Z')
3644
+ _CONCURRENCY_RE = re.compile(r'^\}\s*\Z|^--\s*\Z')
3645
+ _COMPOSITE_STATE_RE = re.compile(r'^state\s+(.+)\s*\{\Z')
3646
+ _DESCRIPTION_RE = re.compile(r'^([A-Za-z_][A-Za-z0-9_]*)\s*:\s*(.+)\Z')
3647
+ _MERMAID_STATE_SKIP_RE = re.compile(r'^(stateDiagram|stateDiagram-v2|direction\b|classDef\b|class\b|style\b|linkStyle\b|click\b|hide\b|scale\b|title\b|accTitle\b|accDescr\b|%%\{)')
3648
+ _PLANTUML_STATE_SKIP_RE = re.compile(r'^(@startuml|@enduml|scale\b|skinparam\b|title\b|hide\b|left to right direction|top to bottom direction|autonumber|!theme)')
3649
+
3650
+ _ACTIVITY_SKIP_RE = re.compile(r'^(flowchart|graph)\b|^(classDef|class|style|linkStyle|click|direction)\b|^%%\{')
3651
+ _SUBGRAPH_RE = re.compile(r'^subgraph\b')
3652
+ _SHAPED_EDGE_RE = re.compile(r'^(.*?)\s*-->\s*\|(.*?)\|\s*(.+)\Z')
3653
+ _BARE_EDGE_RE = re.compile(r'^(.*?)\s*-->\s*(.+)\Z')
3654
+ _STRIP_NODE_RE = re.compile(r'^([A-Za-z_][A-Za-z0-9_.-]*)\s*(\(\[|\[\(|\{\{|\[|\(|\(\(|>)?\s*([\s\S]*?)\s*\Z')
3655
+ _QUOTED_ONLY_RE = re.compile(r'^"([^"]+)"\Z')
3656
+ _QUOTED_IN_RE = re.compile(r'"([^"]*)"')
3657
+
3658
+
3659
+ def _detect_notation(text):
3660
+ if re.search(r'^\s*@start', text, re.M):
3661
+ return 'plantuml'
3662
+ if re.search(r'^\s*(stateDiagram|stateDiagram-v2|flowchart|graph|sequenceDiagram)\b', text, re.M):
3663
+ return 'mermaid'
3664
+ raise ValueError('cannot tell whether this is Mermaid or PlantUML text: '
3665
+ 'expected `stateDiagram-v2` / `flowchart` / `sequenceDiagram`, or `@startuml`')
3666
+
3667
+
3668
+ def _detect_diagram(text):
3669
+ if re.search(r'^\s*stateDiagram', text, re.M):
3670
+ return 'state'
3671
+ if re.search(r'^\s*(flowchart|graph)\b', text, re.M):
3672
+ return 'activity'
3673
+ if re.search(r'^\s*sequenceDiagram\b', text, re.M):
3674
+ return 'sequence'
3675
+ if re.search(r'^\s*@startuml', text, re.M):
3676
+ # PlantUML declares the diagram kind by its body; the state keyword is the only
3677
+ # structural one logicprobe emits, everything else in that family is a state diagram too.
3678
+ if re.search(r'^\s*participant\b', text, re.M) or re.search(r'->>\s*', text):
3679
+ return 'sequence'
3680
+ return 'state'
3681
+ raise ValueError('cannot tell which diagram kind this text declares')
3682
+
3683
+
3684
+ def _comment_prefix(notation):
3685
+ return '%%' if notation == 'mermaid' else "'"
3686
+
3687
+
3688
+ def _directive_body(line, notation):
3689
+ prefix = _comment_prefix(notation)
3690
+ trimmed = _js_trim(line)
3691
+ if not trimmed.startswith(prefix):
3692
+ return None
3693
+ body = _js_trim(trimmed[len(prefix):])
3694
+ if not body.startswith(_DIRECTIVE_NAMESPACE):
3695
+ return None
3696
+ return body[len(_DIRECTIVE_NAMESPACE):]
3697
+
3698
+
3699
+ def _read_directives(lines, notation):
3700
+ """Consume the `logicprobe:` directives; returns (directives, body_lines)."""
3701
+ directives = {'terminals': [], 'aliases': {}, 'variables': {}}
3702
+ body = []
3703
+ for line in lines:
3704
+ text = _directive_body(line, notation)
3705
+ if text is None:
3706
+ body.append(line)
3707
+ continue
3708
+ if text.startswith('uml '):
3709
+ continue
3710
+ if text.startswith('init '):
3711
+ directives['init'] = _js_trim(text[5:])
3712
+ continue
3713
+ if text.startswith('terminal '):
3714
+ for sid in text[9:].split(','):
3715
+ trimmed = _js_trim(sid)
3716
+ if trimmed != '':
3717
+ directives['terminals'].append(trimmed)
3718
+ continue
3719
+ if text.startswith('alias '):
3720
+ rest = _js_trim(text[6:])
3721
+ split = rest.find(' ')
3722
+ if split > 0:
3723
+ directives['aliases'][rest[:split]] = _js_trim(rest[split + 1:])
3724
+ continue
3725
+ if text.startswith('variable '):
3726
+ rest = _js_trim(text[9:])
3727
+ split = rest.rfind(' ')
3728
+ if split > 0:
3729
+ kind = _js_trim(rest[split + 1:])
3730
+ if kind == 'integer' or kind == 'boolean':
3731
+ directives['variables'][_js_trim(rest[:split])] = kind
3732
+ continue
3733
+ body.append(line)
3734
+ return directives, body
3735
+
3736
+
3737
+ def _parse_transition_label(label, warnings):
3738
+ rest = _js_trim(label)
3739
+ guard = None
3740
+ bracket = rest.find('[')
3741
+ if bracket >= 0:
3742
+ close = rest.rfind(']')
3743
+ if close < bracket:
3744
+ raise ValueError('unbalanced guard brackets in transition label "' + label + '"')
3745
+ guard = parse_guard_text(_js_trim(rest[bracket + 1:close]))
3746
+ rest = _js_trim(rest[:bracket] + ' ' + rest[close + 1:])
3747
+ updates = None
3748
+ slash = rest.find('/')
3749
+ if slash >= 0:
3750
+ action_text = _js_trim(rest[slash + 1:])
3751
+ updates = parse_updates_text(action_text, warnings)
3752
+ if len(updates) == 0:
3753
+ updates = None
3754
+ rest = _js_trim(rest[:slash])
3755
+ event = _js_trim(rest)
3756
+ if event == '':
3757
+ raise ValueError('transition label "' + label + '" carries no event name; label the arrow as `event [guard] / actions`')
3758
+ parsed = {'event': event}
3759
+ if guard is not None:
3760
+ parsed['guard'] = guard
3761
+ if updates is not None:
3762
+ parsed['updates'] = updates
3763
+ return parsed
3764
+
3765
+
3766
+ def _infer_variables(transitions, declared):
3767
+ """Recover the variable list from the diagram; directives win, guards/actions are the fallback."""
3768
+ kinds = dict(declared)
3769
+
3770
+ def note(name, kind):
3771
+ if name in declared:
3772
+ return
3773
+ current = kinds.get(name)
3774
+ if current is None:
3775
+ kinds[name] = kind
3776
+ elif current != kind:
3777
+ kinds[name] = 'integer'
3778
+
3779
+ def walk(guard):
3780
+ if guard is None:
3781
+ return
3782
+ if 'variable' in guard:
3783
+ note(guard['variable'], 'boolean' if isinstance(guard['value'], bool) else 'integer')
3784
+ return
3785
+ if 'all' in guard:
3786
+ for child in guard['all']:
3787
+ walk(child)
3788
+ return
3789
+ if 'any' in guard:
3790
+ for child in guard['any']:
3791
+ walk(child)
3792
+ return
3793
+ walk(guard['not'])
3794
+
3795
+ for transition in transitions:
3796
+ walk(transition.get('guard'))
3797
+ for update in transition.get('updates') or []:
3798
+ note(update['variable'], 'integer')
3799
+ return [{'name': name, 'kind': kind, 'init': False if kind == 'boolean' else 0} for name, kind in kinds.items()]
3800
+
3801
+
3802
+ def _raw_to_model(raw, directives, warnings):
3803
+ aliases = directives['aliases']
3804
+
3805
+ def id_of(name):
3806
+ return aliases.get(name, name)
3807
+
3808
+ # Alias directives restore ids the notation cannot spell; they win over the alias itself.
3809
+ names = []
3810
+ seen_names = set()
3811
+
3812
+ def add_name(name):
3813
+ if name is None or name in seen_names:
3814
+ return
3815
+ seen_names.add(name)
3816
+ names.append(name)
3817
+
3818
+ for name in raw['states']:
3819
+ add_name(name)
3820
+ # A state can be known without ever being an edge endpoint: the initial
3821
+ # pseudostate (`[*] --> X`) and the final mark (`Y --> [*]`) both name states a
3822
+ # hand-written diagram never declares, and an isolated state has no edge at all.
3823
+ add_name(raw['initialState'])
3824
+ for name in raw['finalMarks']:
3825
+ add_name(name)
3826
+ for name in raw['terminals']:
3827
+ add_name(name)
3828
+ for edge in raw['edges']:
3829
+ add_name(edge['from'])
3830
+ add_name(edge['to'])
3831
+ states = []
3832
+ seen_states = set()
3833
+ for name in names:
3834
+ sid = id_of(name)
3835
+ if sid in seen_states:
3836
+ continue
3837
+ seen_states.add(sid)
3838
+ states.append({'id': sid})
3839
+ transitions = []
3840
+ synthetic = set()
3841
+ for edge in raw['edges']:
3842
+ frm = id_of(edge['from'])
3843
+ to = id_of(edge['to'])
3844
+ label = _js_trim(edge['label'])
3845
+ guard = None
3846
+ updates = None
3847
+ if label == '':
3848
+ candidate = 't_' + frm + '_' + to
3849
+ suffix = 2
3850
+ while candidate in synthetic:
3851
+ candidate = 't_' + frm + '_' + to + '_' + str(suffix)
3852
+ suffix += 1
3853
+ synthetic.add(candidate)
3854
+ event = candidate
3855
+ warnings.append('UML_PARSE_SYNTHETIC_EVENT: arrow ' + frm + ' -> ' + to + ' carries no label; it was named "' + candidate
3856
+ + '". Label the arrow as `event [guard] / actions` so the model keeps the real event name.')
3857
+ else:
3858
+ parsed = _parse_transition_label(label, warnings)
3859
+ event = parsed['event']
3860
+ guard = parsed.get('guard')
3861
+ updates = parsed.get('updates')
3862
+ transition = {'from': frm, 'event': event, 'to': to}
3863
+ if guard is not None:
3864
+ transition['guard'] = guard
3865
+ if updates is not None:
3866
+ transition['updates'] = updates
3867
+ transitions.append(transition)
3868
+ # Init: an explicit `[*] --> X` wins; a directive is the fallback the activity
3869
+ # view needs (a flowchart has no initial pseudostate).
3870
+ init = None
3871
+ if raw['initialState'] is not None:
3872
+ init = id_of(raw['initialState'])
3873
+ if init is None and directives.get('init') is not None:
3874
+ init = id_of(directives['init'])
3875
+ if raw['initialState'] is not None and directives.get('init') is not None and id_of(raw['initialState']) != directives['init']:
3876
+ warnings.append('UML_PARSE_INIT_CONFLICT: the diagram enters ' + id_of(raw['initialState']) + ' from its initial pseudostate but declares init '
3877
+ + directives['init'] + '; the pseudostate wins.')
3878
+ if init is None:
3879
+ targeted = set(transition['to'] for transition in transitions)
3880
+ roots = [state['id'] for state in states if state['id'] not in targeted]
3881
+ if len(roots) == 1:
3882
+ init = roots[0]
3883
+ warnings.append('UML_PARSE_INIT_INFERRED: no initial state was declared; "' + init
3884
+ + '" is the only state nothing enters, so it is used as init.')
3885
+ else:
3886
+ raise ValueError('no initial state: add `[*] --> <state>` (or a `' + _DIRECTIVE_NAMESPACE
3887
+ + 'init <state>` directive); found ' + str(len(roots)) + ' entry states')
3888
+ terminal_names = set(id_of(name) for name in raw['terminals'])
3889
+ for name in directives['terminals']:
3890
+ terminal_names.add(id_of(name))
3891
+ for name in raw['finalMarks']:
3892
+ terminal_names.add(id_of(name))
3893
+ for state in states:
3894
+ if state['id'] in terminal_names:
3895
+ state['terminal'] = True
3896
+ variables = _infer_variables(transitions, directives['variables'])
3897
+ model = {'schemaVersion': 1, 'init': init, 'states': states, 'transitions': transitions}
3898
+ if len(variables) > 0:
3899
+ model['variables'] = variables
3900
+ ok, model_or_errors = validate_model(model)
3901
+ if not ok:
3902
+ raise ValueError('the diagram parsed into an invalid model: ' + '; '.join(model_or_errors))
3903
+ return model_or_errors
3904
+
3905
+
3906
+ def _parse_state_diagram(text, notation):
3907
+ lines = re.split(r'\r?\n', text)
3908
+ directives, body = _read_directives(lines, notation)
3909
+ raw = {'states': [], 'display': {}, 'edges': [], 'initialState': None, 'terminals': [], 'finalMarks': [], 'warnings': []}
3910
+ declared = set()
3911
+
3912
+ def declare(name):
3913
+ if name not in declared:
3914
+ declared.add(name)
3915
+ raw['states'].append(name)
3916
+
3917
+ skip = _MERMAID_STATE_SKIP_RE if notation == 'mermaid' else _PLANTUML_STATE_SKIP_RE
3918
+ for raw_line in body:
3919
+ line = _js_trim(raw_line)
3920
+ if line == '' or (line.startswith('--') and '-->' not in line):
3921
+ continue
3922
+ if skip.match(line):
3923
+ continue
3924
+ note = _STATE_NOTE_RE.match(line)
3925
+ if note is not None:
3926
+ declare(note.group(1))
3927
+ if note.group(1) not in raw['display']:
3928
+ raw['display'][note.group(1)] = _js_trim(note.group(2))
3929
+ continue
3930
+ if _NOTE_RE.match(line) or _END_NOTE_RE.match(line):
3931
+ continue
3932
+ state_decl = _STATE_DECL_RE.match(line)
3933
+ if state_decl is not None:
3934
+ declare(state_decl.group(2))
3935
+ raw['display'][state_decl.group(2)] = state_decl.group(1)
3936
+ continue
3937
+ bare_state = _BARE_STATE_RE.match(line)
3938
+ if bare_state is not None:
3939
+ declare(bare_state.group(1))
3940
+ continue
3941
+ if _CONCURRENCY_RE.match(line):
3942
+ raw['warnings'].append('UML_PARSE_CONCURRENCY_FLATTENED: a concurrency region or composite block was flattened; '
3943
+ 'LogicModelV1 has no region construct (use logicprobe_compose_verify for parallel machines).')
3944
+ continue
3945
+ composite = _COMPOSITE_STATE_RE.match(line)
3946
+ if composite is not None:
3947
+ raw['warnings'].append('UML_PARSE_COMPOSITE_FLATTENED: composite state "' + _js_trim(composite.group(1))
3948
+ + '" was flattened into its members.')
3949
+ continue
3950
+ description = _DESCRIPTION_RE.match(line)
3951
+ if description is not None:
3952
+ declare(description.group(1))
3953
+ if description.group(1) not in raw['display']:
3954
+ raw['display'][description.group(1)] = _js_trim(description.group(2))
3955
+ continue
3956
+ edge = _STATE_EDGE_RE.match(line)
3957
+ if edge is not None:
3958
+ frm = _js_trim(edge.group(1))
3959
+ to = _js_trim(edge.group(2))
3960
+ label = _js_trim(edge.group(3) or '')
3961
+ if frm == '[*]':
3962
+ if raw['initialState'] is not None and raw['initialState'] != to:
3963
+ raw['warnings'].append('UML_PARSE_MULTIPLE_INIT: the diagram enters ' + raw['initialState'] + ' and ' + to
3964
+ + ' from initial pseudostates; LogicModelV1 has one init, so ' + raw['initialState'] + ' is kept.')
3965
+ else:
3966
+ raw['initialState'] = to
3967
+ continue
3968
+ if to == '[*]':
3969
+ raw['finalMarks'].append(frm)
3970
+ continue
3971
+ declare(frm)
3972
+ declare(to)
3973
+ raw['edges'].append({'from': frm, 'to': to, 'label': label})
3974
+ continue
3975
+ raw['warnings'].append('UML_PARSE_IGNORED_LINE: "' + line + '" is not a state diagram statement; it was ignored.')
3976
+ model = _raw_to_model(raw, directives, raw['warnings'])
3977
+ labels = _map_labels(raw['display'], directives)
3978
+ return {'notation': notation, 'diagram': 'state', 'model': model, 'labels': labels, 'warnings': raw['warnings']}
3979
+
3980
+
3981
+ def _strip_quotes(text):
3982
+ return re.sub(r'^"|"$', '', text)
3983
+
3984
+
3985
+ def _strip_node(text, raw, declare):
3986
+ """Read one node reference (`A`, `A["label"]`, `A(["label"])`) and its display label."""
3987
+ trimmed = _js_trim(text)
3988
+ if trimmed == '':
3989
+ return None
3990
+ match = _STRIP_NODE_RE.match(trimmed)
3991
+ if match is None:
3992
+ quoted_only = _QUOTED_ONLY_RE.match(trimmed)
3993
+ if quoted_only is not None:
3994
+ declare(quoted_only.group(1))
3995
+ return quoted_only.group(1)
3996
+ return None
3997
+ name = match.group(1)
3998
+ shape = match.group(2) or ''
3999
+ rest = match.group(3) or ''
4000
+ declare(name)
4001
+ quoted = _QUOTED_IN_RE.search(rest)
4002
+ if quoted is not None:
4003
+ label = _js_trim(quoted.group(1))
4004
+ else:
4005
+ label = _js_trim(re.sub(r'[\[\](){}>]+$', '', re.sub(r'^[\[\](){}>]+', '', rest)))
4006
+ if label != '' and name not in raw['display']:
4007
+ raw['display'][name] = label
4008
+ if shape == '([' or shape == '((' or rest.startswith('(['):
4009
+ raw['terminals'].append(name)
4010
+ return name
4011
+
4012
+
4013
+ def _parse_activity_diagram(text, notation):
4014
+ lines = re.split(r'\r?\n', text)
4015
+ directives, body = _read_directives(lines, notation)
4016
+ raw = {'states': [], 'display': {}, 'edges': [], 'initialState': None, 'terminals': [], 'finalMarks': [], 'warnings': []}
4017
+ declared = set()
4018
+
4019
+ def declare(name):
4020
+ if name not in declared:
4021
+ declared.add(name)
4022
+ raw['states'].append(name)
4023
+
4024
+ in_subgraph = False
4025
+ for raw_line in body:
4026
+ line = _js_trim(raw_line)
4027
+ if line == '' or _ACTIVITY_SKIP_RE.match(line):
4028
+ continue
4029
+ if _SUBGRAPH_RE.match(line):
4030
+ if not in_subgraph:
4031
+ in_subgraph = True
4032
+ raw['warnings'].append('UML_PARSE_SUBGRAPH_FLATTENED: subgraph blocks were flattened; LogicModelV1 has no hierarchy.')
4033
+ continue
4034
+ if line == 'end':
4035
+ in_subgraph = False
4036
+ continue
4037
+ shaped = _SHAPED_EDGE_RE.match(line)
4038
+ bare = None if shaped is not None else _BARE_EDGE_RE.match(line)
4039
+ if shaped is not None or bare is not None:
4040
+ match = shaped if shaped is not None else bare
4041
+ frm = _strip_node(_js_trim(match.group(1)), raw, declare)
4042
+ # Flowchart labels live between bars; the state-diagram form `A --> B : label`
4043
+ # is accepted too so a hand-written file that mixes the two still reads.
4044
+ raw_to = _js_trim(match.group(3) if shaped is not None else match.group(2))
4045
+ label = _js_trim(_strip_quotes(match.group(2))) if shaped is not None else ''
4046
+ if shaped is None:
4047
+ colon = raw_to.find(':')
4048
+ if colon >= 0:
4049
+ label = _strip_quotes(_js_trim(raw_to[colon + 1:]))
4050
+ raw_to = _js_trim(raw_to[:colon])
4051
+ to = _strip_node(raw_to, raw, declare)
4052
+ if frm is None or to is None:
4053
+ continue
4054
+ raw['edges'].append({'from': frm, 'to': to, 'label': label})
4055
+ continue
4056
+ node = _strip_node(line, raw, declare)
4057
+ if node is None:
4058
+ raw['warnings'].append('UML_PARSE_IGNORED_LINE: "' + line + '" is not a flowchart statement; it was ignored.')
4059
+ model = _raw_to_model(raw, directives, raw['warnings'])
4060
+ labels = _map_labels(raw['display'], directives)
4061
+ return {'notation': notation, 'diagram': 'activity', 'model': model, 'labels': labels, 'warnings': raw['warnings']}
4062
+
4063
+
4064
+ def _map_labels(display, directives):
4065
+ out = {}
4066
+ for name, label in display.items():
4067
+ out[directives['aliases'].get(name, name)] = label
4068
+ return out
4069
+
4070
+
4071
+ def parse_uml(text, notation='auto'):
4072
+ """Parse a Mermaid or PlantUML diagram back into a LogicModelV1."""
4073
+ resolved = _detect_notation(text) if notation == 'auto' else notation
4074
+ kind = _detect_diagram(text)
4075
+ if kind == 'sequence':
4076
+ raise ValueError('a sequence diagram is a trace, not a machine: parsing it would drop every branch the trace did not walk. '
4077
+ 'Render diagram "state" or "activity" and parse that instead.')
4078
+ return _parse_state_diagram(text, resolved) if kind == 'state' else _parse_activity_diagram(text, resolved)
4079
+
4080
+
4081
+ # ---- review ---------------------------------------------------------------
4082
+
4083
+ def _reachable_states(model):
4084
+ adjacency = {}
4085
+ for transition in model['transitions']:
4086
+ adjacency.setdefault(transition['from'], []).append(transition['to'])
4087
+ visited = set([model['init']])
4088
+ queue = deque([model['init']])
4089
+ while len(queue) > 0:
4090
+ current = queue.popleft()
4091
+ for nxt in adjacency.get(current, []):
4092
+ if nxt not in visited:
4093
+ visited.add(nxt)
4094
+ queue.append(nxt)
4095
+ return visited
4096
+
4097
+
4098
+ def _canonical_transition(transition):
4099
+ guard = guard_text(transition['guard']) if transition.get('guard') is not None else ''
4100
+ updates = _updates_text(transition['updates']) if transition.get('updates') is not None else ''
4101
+ return transition['from'] + '|' + transition['event'] + '|' + transition['to'] + '|' + guard + '|' + updates
4102
+
4103
+
4104
+ def _documented_meaning(label, sid):
4105
+ """The narrative meaning a diagram label carries, if it carries one beyond the bare id."""
4106
+ if label is None:
4107
+ return None
4108
+ trimmed = _js_trim(label)
4109
+ if trimmed == '' or trimmed == sid:
4110
+ return None
4111
+ for open_char, close_char in (('(', ')'), ('(', ')')):
4112
+ prefix = sid + open_char
4113
+ if trimmed.startswith(prefix) and trimmed.endswith(close_char):
4114
+ return trimmed[len(prefix):len(trimmed) - len(close_char)]
4115
+ return trimmed
4116
+
4117
+
4118
+ def _collect_guard_variables(guard, sink):
4119
+ if 'variable' in guard:
4120
+ sink.add(guard['variable'])
4121
+ return
4122
+ if 'all' in guard:
4123
+ for child in guard['all']:
4124
+ _collect_guard_variables(child, sink)
4125
+ return
4126
+ if 'any' in guard:
4127
+ for child in guard['any']:
4128
+ _collect_guard_variables(child, sink)
4129
+ return
4130
+ _collect_guard_variables(guard['not'], sink)
4131
+
4132
+
4133
+ def _positive_leaves(guard, sink):
4134
+ """Positive, conjunctively-reached leaves — the only ones a complementarity witness may use."""
4135
+ if 'variable' in guard:
4136
+ sink.append(guard)
4137
+ return
4138
+ if 'all' in guard:
4139
+ for child in guard['all']:
4140
+ _positive_leaves(child, sink)
4141
+ return
4142
+ # `any` and `not` subtrees are skipped on purpose: a leaf under a disjunction is
4143
+ # not implied by its branch, and `not (x < 3)` is `x >= 3` only for totally
4144
+ # ordered integers — neither is a sound complementarity witness.
4145
+
4146
+
4147
+ _COMPLEMENTS = (('<', '>='), ('<=', '>'), ('==', '!='))
4148
+
4149
+
4150
+ def _complementary_variable(guards):
4151
+ """Name a variable whose guards contain a complementary pair, or None when there is none."""
4152
+ leaves = []
4153
+ for guard in guards:
4154
+ _positive_leaves(guard, leaves)
4155
+ for i in range(len(leaves)):
4156
+ for j in range(i + 1, len(leaves)):
4157
+ left = leaves[i]
4158
+ right = leaves[j]
4159
+ if left['variable'] != right['variable']:
4160
+ continue
4161
+ if not _js_strict_equal(left['value'], right['value']):
4162
+ continue
4163
+ for one, other in _COMPLEMENTS:
4164
+ if (left['op'] == one and right['op'] == other) or (left['op'] == other and right['op'] == one):
4165
+ return left['variable']
4166
+ return None
4167
+
4168
+
4169
+ def _structural_findings(model, labels, warnings):
4170
+ findings = []
4171
+ reachable = _reachable_states(model)
4172
+ outgoing = {}
4173
+ for transition in model['transitions']:
4174
+ outgoing.setdefault(transition['from'], []).append(transition)
4175
+
4176
+ unreachable = [state['id'] for state in model['states'] if state['id'] not in reachable]
4177
+ if len(unreachable) > 0:
4178
+ findings.append({
4179
+ 'code': 'UML002_UNREACHABLE_STATE',
4180
+ 'severity': 'error',
4181
+ 'message': str(len(unreachable)) + ' state(s) cannot be entered from init along any transition, so the diagram draws flow nobody can reach.',
4182
+ 'states': unreachable,
4183
+ 'detail': 'Structural reachability (guards ignored). Guard-aware reachability is S1 in logicprobe_verify.',
4184
+ })
4185
+
4186
+ dead_ends = [state['id'] for state in model['states']
4187
+ if state.get('terminal') is not True and len(outgoing.get(state['id'], [])) == 0]
4188
+ if len(dead_ends) > 0:
4189
+ findings.append({
4190
+ 'code': 'UML003_DEAD_END_STATE',
4191
+ 'severity': 'error',
4192
+ 'message': str(len(dead_ends)) + ' non-terminal state(s) have no outgoing transition: the flow stops there without a modelled terminal.',
4193
+ 'states': dead_ends,
4194
+ 'detail': 'Either the state is terminal (add `X --> [*]`) or the outgoing flow is missing from the model. '
4195
+ 'logicprobe_verify S2 reports the same shape at runtime granularity.',
4196
+ })
4197
+
4198
+ groups = {}
4199
+ for transition in model['transitions']:
4200
+ key = transition['from'] + '\u0000' + transition['event']
4201
+ groups.setdefault(key, []).append(transition)
4202
+ ambiguous = []
4203
+ overlapping = []
4204
+ inexhaustive = []
4205
+ probably_exhaustive = []
4206
+ complementary = []
4207
+ for group in groups.values():
4208
+ unguarded = [transition for transition in group if transition.get('guard') is None]
4209
+ guarded = [transition for transition in group if transition.get('guard') is not None]
4210
+ if len(unguarded) > 1:
4211
+ for transition in unguarded:
4212
+ ambiguous.append({'from': transition['from'], 'event': transition['event'], 'to': transition['to']})
4213
+ seen_guards = {}
4214
+ for transition in guarded:
4215
+ text = guard_text(transition['guard'])
4216
+ if text in seen_guards:
4217
+ overlapping.append({'from': transition['from'], 'event': transition['event'], 'to': transition['to']})
4218
+ else:
4219
+ seen_guards[text] = transition
4220
+ if len(guarded) > 0 and len(unguarded) == 0:
4221
+ row = {'from': group[0]['from'], 'event': group[0]['event'], 'to': group[0]['to']}
4222
+ # A complementary pair on one variable (`x < 3` / `x >= 3`) is exhaustive for
4223
+ # any valuation, so the structural warning would be a false alarm there. The
4224
+ # pair test is deliberately narrow — it cannot prove exhaustiveness, only
4225
+ # recognise the common shape, which is why the finding stays on the report at
4226
+ # info severity and still routes to S6.
4227
+ witness = _complementary_variable([transition['guard'] for transition in guarded])
4228
+ if witness is None:
4229
+ inexhaustive.append(row)
4230
+ else:
4231
+ probably_exhaustive.append(row)
4232
+ complementary.append(witness)
4233
+ if len(ambiguous) > 0:
4234
+ findings.append({
4235
+ 'code': 'UML004_AMBIGUOUS_BRANCH',
4236
+ 'severity': 'error',
4237
+ 'message': str(len(ambiguous)) + ' branch(es) share a (state, event) with no guard at all: '
4238
+ 'the diagram shows two unconditional arrows for one event, which no reader can resolve.',
4239
+ 'transitions': ambiguous,
4240
+ 'detail': 'Keep one unguarded branch per (state, event) as the else case, and guard the others. '
4241
+ 'logicprobe_verify S4 is the authoritative determinism check.',
4242
+ })
4243
+ if len(overlapping) > 0:
4244
+ findings.append({
4245
+ 'code': 'UML005_OVERLAPPING_GUARD',
4246
+ 'severity': 'warning',
4247
+ 'message': str(len(overlapping)) + ' transition(s) repeat a guard already used by another branch of the same (state, event).',
4248
+ 'transitions': overlapping,
4249
+ })
4250
+ if len(inexhaustive) > 0:
4251
+ findings.append({
4252
+ 'code': 'UML006_INEXHAUSTIVE_BRANCH',
4253
+ 'severity': 'warning',
4254
+ 'message': str(len(inexhaustive)) + ' (state, event) group(s) have only guarded branches and no default: '
4255
+ 'if every guard is false the flow vanishes, and the diagram still implies coverage.',
4256
+ 'transitions': inexhaustive,
4257
+ 'detail': 'Add an unguarded else branch, or confirm exhaustiveness with logicprobe_verify S6 (which evaluates guards over real valuations).',
4258
+ })
4259
+ if len(probably_exhaustive) > 0:
4260
+ findings.append({
4261
+ 'code': 'UML006_INEXHAUSTIVE_BRANCH',
4262
+ 'severity': 'info',
4263
+ 'message': str(len(probably_exhaustive)) + ' (state, event) group(s) have guards that look complementary on '
4264
+ + ', '.join(dict.fromkeys(complementary))
4265
+ + ', so they are probably exhaustive — but no default branch exists and only logicprobe_verify S6 can settle it.',
4266
+ 'transitions': probably_exhaustive,
4267
+ })
4268
+
4269
+ events_by_reachable = dict.fromkeys(transition['event'] for transition in model['transitions']
4270
+ if transition['from'] in reachable)
4271
+ events_anywhere = dict.fromkeys(transition['event'] for transition in model['transitions'])
4272
+ dead_events = [event for event in events_anywhere if event not in events_by_reachable]
4273
+ if len(dead_events) > 0:
4274
+ findings.append({
4275
+ 'code': 'UML007_UNUSED_EVENT',
4276
+ 'severity': 'warning',
4277
+ 'message': str(len(dead_events)) + ' event(s) only fire from states nothing can reach, so the diagram shows messages that never arrive.',
4278
+ 'events': dead_events,
4279
+ })
4280
+
4281
+ self_loops = [transition for transition in model['transitions']
4282
+ if transition['from'] == transition['to'] and transition.get('guard') is None
4283
+ and len(outgoing.get(transition['from'], [])) == 1]
4284
+ if len(self_loops) > 0:
4285
+ findings.append({
4286
+ 'code': 'UML008_SELF_LOOP_NO_EXIT',
4287
+ 'severity': 'warning',
4288
+ 'message': str(len(self_loops)) + ' state(s) have a single unguarded self-loop and no exit: '
4289
+ 'the flow can never leave, which the diagram presents as activity.',
4290
+ 'states': list(dict.fromkeys(transition['from'] for transition in self_loops)),
4291
+ 'detail': 'logicprobe_verify S3 reports absorbing cycles (liveness).',
4292
+ })
4293
+
4294
+ seen_transitions = {}
4295
+ for transition in model['transitions']:
4296
+ key = _canonical_transition(transition)
4297
+ seen_transitions[key] = seen_transitions.get(key, 0) + 1
4298
+ duplicates = [transition for transition in model['transitions']
4299
+ if seen_transitions.get(_canonical_transition(transition), 0) > 1]
4300
+ if len(duplicates) > 0:
4301
+ findings.append({
4302
+ 'code': 'UML009_DUPLICATE_TRANSITION',
4303
+ 'severity': 'warning',
4304
+ 'message': str(len(duplicates)) + ' transition(s) duplicate an identical (from, event, guard, actions, to) row; '
4305
+ 'the diagram draws the same arrow twice.',
4306
+ 'transitions': [{'from': transition['from'], 'event': transition['event'], 'to': transition['to']} for transition in duplicates],
4307
+ })
4308
+
4309
+ guard_variables = set()
4310
+ for transition in model['transitions']:
4311
+ if transition.get('guard') is not None:
4312
+ _collect_guard_variables(transition['guard'], guard_variables)
4313
+ updated_variables = set()
4314
+ for transition in model['transitions']:
4315
+ for update in transition.get('updates') or []:
4316
+ updated_variables.add(update['variable'])
4317
+ unused_variables = [variable['name'] for variable in (model.get('variables') or [])
4318
+ if variable['name'] not in guard_variables and variable['name'] not in updated_variables]
4319
+ if len(unused_variables) > 0:
4320
+ findings.append({
4321
+ 'code': 'UML010_UNUSED_VARIABLE',
4322
+ 'severity': 'warning',
4323
+ 'message': str(len(unused_variables)) + ' variable(s) are never read by a guard and never written: '
4324
+ 'the diagram carries a symbol with no source.',
4325
+ 'events': unused_variables,
4326
+ })
4327
+ unbounded = [variable['name'] for variable in (model.get('variables') or [])
4328
+ if variable['kind'] == 'integer' and ('min' not in variable or 'max' not in variable)]
4329
+ if len(unbounded) > 0:
4330
+ findings.append({
4331
+ 'code': 'UML011_UNBOUNDED_VARIABLE',
4332
+ 'severity': 'info',
4333
+ 'message': str(len(unbounded)) + ' integer variable(s) declare no min/max, so no range invariant can be checked '
4334
+ 'and A5 boundary probing has no declared domain.',
4335
+ 'detail': ', '.join(unbounded),
4336
+ })
4337
+
4338
+ terminals = [state['id'] for state in model['states'] if state.get('terminal') is True]
4339
+ if len(terminals) == 0:
4340
+ findings.append({
4341
+ 'code': 'UML012_NO_TERMINAL',
4342
+ 'severity': 'warning',
4343
+ 'message': 'no state is terminal: the diagram has no `--> [*]`, so completion, failure and a stuck flow look the same.',
4344
+ 'detail': 'Mark absorbing states terminal, or state explicitly that the machine is non-terminating.',
4345
+ })
4346
+
4347
+ if 'narrative' not in model:
4348
+ findings.append({
4349
+ 'code': 'UML013_NO_NARRATIVE',
4350
+ 'severity': 'info',
4351
+ 'message': 'the model carries no narrative block: no state, event or scenario has a natural-language meaning, '
4352
+ 'so a reader must re-derive every symbol from the source.',
4353
+ 'detail': 'Add narrative.states / narrative.events / narrative.scenarios — the schema requires all three and full coverage once the block is present.',
4354
+ })
4355
+
4356
+ documented = None
4357
+ if labels is not None:
4358
+ documented = [sid for sid in labels if _documented_meaning(labels[sid], sid) is not None]
4359
+ if documented is not None:
4360
+ undocumented = [state['id'] for state in model['states']
4361
+ if _documented_meaning(labels.get(state['id']), state['id']) is None]
4362
+ if len(undocumented) > 0:
4363
+ findings.append({
4364
+ 'code': 'UML014_UNDOCUMENTED_STATE',
4365
+ 'severity': 'info',
4366
+ 'message': str(len(undocumented)) + ' of ' + str(len(model['states']))
4367
+ + ' states carry no meaning in the diagram (they render as their bare id).',
4368
+ 'states': undocumented,
4369
+ 'detail': 'Give each state a `state "meaning" as ID` label or `ID : meaning` description so the diagram can be read against the code.',
4370
+ })
4371
+ narrative = model.get('narrative')
4372
+ if narrative is not None and narrative.get('states') is not None:
4373
+ drift = []
4374
+ for state in model['states']:
4375
+ meaning = _documented_meaning(labels.get(state['id']), state['id'])
4376
+ declared = narrative['states'].get(state['id'])
4377
+ if meaning is not None and declared is not None and meaning != declared:
4378
+ drift.append(state['id'] + ': diagram "' + meaning + '" vs narrative "' + declared + '"')
4379
+ if len(drift) > 0:
4380
+ findings.append({
4381
+ 'code': 'UML015_LABEL_DRIFT',
4382
+ 'severity': 'warning',
4383
+ 'message': str(len(drift)) + ' state label(s) disagree with the model narrative: one of the two is stale, '
4384
+ 'and the review cannot tell which.',
4385
+ 'detail': ' | '.join(drift),
4386
+ })
4387
+
4388
+ if len(warnings) > 0:
4389
+ findings.append({
4390
+ 'code': 'UML016_DIAGRAM_PARSE_NOTES',
4391
+ 'severity': 'info',
4392
+ 'message': str(len(warnings)) + ' note(s) were produced while rendering or reading the diagram; '
4393
+ 'they mark information the notation could not carry.',
4394
+ 'detail': ' | '.join(warnings),
4395
+ })
4396
+
4397
+ return findings
4398
+
4399
+
4400
+ def _compiled_model(input_value):
4401
+ ok, model_or_errors = validate_model(input_value)
4402
+ if not ok:
4403
+ raise ValueError('model invalid: ' + '; '.join(model_or_errors))
4404
+ return model_or_errors
4405
+
4406
+
4407
+ def _round_trip_of(model, notation, diagram, max_steps):
4408
+ rendered = render_uml(model, notation, diagram, max_steps)
4409
+ parsed = parse_uml(rendered['primary'], notation)
4410
+ diffs = diff_models(model, parsed['model'])
4411
+ report = {
4412
+ 'notation': notation,
4413
+ 'diagram': diagram,
4414
+ 'ok': len(diffs) == 0,
4415
+ 'modelHash': model_hash(model),
4416
+ 'parsedHash': model_hash(parsed['model']),
4417
+ 'diffs': diffs,
4418
+ 'warnings': list(rendered['warnings']) + list(parsed['warnings']),
4419
+ }
4420
+ return {'report': report, 'primary': rendered['primary']}
4421
+
4422
+
4423
+ def diff_models(left, right):
4424
+ """Compare two machines by structure — the fidelity measure behind the round-trip check."""
4425
+ diffs = []
4426
+ if left['init'] != right['init']:
4427
+ diffs.append('init: ' + left['init'] + ' vs ' + right['init'])
4428
+ left_states = [state['id'] for state in left['states']]
4429
+ right_states = [state['id'] for state in right['states']]
4430
+ for sid in left_states:
4431
+ if sid not in right_states:
4432
+ diffs.append('state missing after parse: ' + sid)
4433
+ for sid in right_states:
4434
+ if sid not in left_states:
4435
+ diffs.append('state invented by the diagram: ' + sid)
4436
+ left_terminal = sorted(state['id'] for state in left['states'] if state.get('terminal') is True)
4437
+ right_terminal = sorted(state['id'] for state in right['states'] if state.get('terminal') is True)
4438
+ if ', '.join(left_terminal) != ', '.join(right_terminal):
4439
+ diffs.append('terminal states: [' + ', '.join(left_terminal) + '] vs [' + ', '.join(right_terminal) + ']')
4440
+ left_transitions = sorted(_canonical_transition(transition) for transition in left['transitions'])
4441
+ right_transitions = sorted(_canonical_transition(transition) for transition in right['transitions'])
4442
+ left_count = {}
4443
+ for key in left_transitions:
4444
+ left_count[key] = left_count.get(key, 0) + 1
4445
+ right_count = {}
4446
+ for key in right_transitions:
4447
+ right_count[key] = right_count.get(key, 0) + 1
4448
+ for key, count in left_count.items():
4449
+ other = right_count.get(key, 0)
4450
+ if other < count:
4451
+ diffs.append('transition lost in the diagram (' + str(count - other) + 'x): ' + key.replace('|', ' '))
4452
+ for key, count in right_count.items():
4453
+ other = left_count.get(key, 0)
4454
+ if other < count:
4455
+ diffs.append('transition invented by the diagram (' + str(count - other) + 'x): ' + key.replace('|', ' '))
4456
+ left_variables = sorted(variable['name'] + ':' + variable['kind'] for variable in (left.get('variables') or []))
4457
+ right_variables = sorted(variable['name'] + ':' + variable['kind'] for variable in (right.get('variables') or []))
4458
+ for name in left_variables:
4459
+ if name not in right_variables:
4460
+ diffs.append('variable missing after parse: ' + name)
4461
+ for name in right_variables:
4462
+ if name not in left_variables:
4463
+ diffs.append('variable invented by the diagram: ' + name)
4464
+ return diffs
4465
+
4466
+
4467
+ def review_uml(options):
4468
+ """Mirror of reviewUml: review a machine, a diagram, or the match between the two."""
4469
+ warnings = []
4470
+ findings = []
4471
+ has_model = 'model' in options
4472
+ has_diagram = isinstance(options.get('diagram'), str) and _js_trim(options['diagram']) != ''
4473
+ if not has_model and not has_diagram:
4474
+ raise ValueError('review needs `model`, `diagram`, or both')
4475
+
4476
+ notation = 'mermaid'
4477
+ if options.get('notation') is not None and options['notation'] != 'auto':
4478
+ notation = options['notation']
4479
+ kind = options['diagramKind'] if options.get('diagramKind') is not None else 'state'
4480
+ model = None
4481
+ labels = None
4482
+ primary = None
4483
+ round_trip = None
4484
+
4485
+ if has_diagram:
4486
+ try:
4487
+ parsed = parse_uml(options['diagram'], options['notation'] if options.get('notation') is not None else 'auto')
4488
+ except ValueError as exc:
4489
+ return {
4490
+ 'ok': False,
4491
+ 'source': 'model+diagram' if has_model else 'diagram',
4492
+ 'summary': {'errors': 1, 'warnings': 0, 'info': 0, 'states': 0, 'events': 0, 'transitions': 0,
4493
+ 'terminalStates': 0, 'reachableStates': 0, 'documentedStates': 0},
4494
+ 'findings': [{'code': 'UML001_DIAGRAM_UNREADABLE', 'severity': 'error', 'message': str(exc),
4495
+ 'detail': 'The diagram could not be read as a Mermaid/PlantUML state or activity diagram.'}],
4496
+ 'roundTrip': None,
4497
+ 'warnings': warnings,
4498
+ 'nextSteps': ['Fix the diagram syntax (or render one from a model with logicprobe_uml action=render) and review again.'],
4499
+ }
4500
+ notation = parsed['notation']
4501
+ labels = parsed['labels']
4502
+ warnings.extend(parsed['warnings'])
4503
+ if has_model:
4504
+ model = _compiled_model(options['model'])
4505
+ diffs = diff_models(model, parsed['model'])
4506
+ round_trip = {
4507
+ 'notation': parsed['notation'],
4508
+ 'diagram': parsed['diagram'],
4509
+ 'ok': len(diffs) == 0,
4510
+ 'modelHash': model_hash(model),
4511
+ 'parsedHash': model_hash(parsed['model']),
4512
+ 'diffs': diffs,
4513
+ 'warnings': list(parsed['warnings']),
4514
+ }
4515
+ if len(diffs) > 0:
4516
+ detail = ' | '.join(diffs[:12])
4517
+ if len(diffs) > 12:
4518
+ detail += ' | … ' + str(len(diffs) - 12) + ' more'
4519
+ findings.append({
4520
+ 'code': 'UML017_ROUND_TRIP_MISMATCH',
4521
+ 'severity': 'error',
4522
+ 'message': 'the diagram does not carry the model it is presented with: ' + str(len(diffs)) + ' structural difference(s).',
4523
+ 'detail': detail,
4524
+ })
4525
+ if len(diffs) == 0 and labels is not None and 'narrative' not in model:
4526
+ warnings.append('UML_REVIEW_DIAGRAM_LABELS_IGNORED_BY_MODEL: the diagram carries state labels but the model has no narrative block, '
4527
+ 'so the labels live only in the diagram.')
4528
+ else:
4529
+ model = parsed['model']
4530
+ findings.append({
4531
+ 'code': 'UML018_FIDELITY_UNCHECKED',
4532
+ 'severity': 'info',
4533
+ 'message': 'only a diagram was supplied, so the review reads the diagram as the model: nothing here proves the diagram matches the code it claims to describe.',
4534
+ 'detail': 'Compare the parsed model against the code (each state/event/guard needs a source citation), '
4535
+ 'or pass the machine alongside the diagram to check the two against each other.',
4536
+ })
4537
+ else:
4538
+ model = _compiled_model(options['model'])
4539
+ max_steps = options['maxSteps'] if options.get('maxSteps') is not None else 60
4540
+ # A sequence view is a trace, so parsing it back would drop every branch the
4541
+ # walk never took: the fidelity check cannot apply to it, and pretending it did
4542
+ # would either fail spuriously or hide the difference. Render it anyway (the
4543
+ # caller asked for that view) and say the check does not apply.
4544
+ if kind == 'sequence':
4545
+ try:
4546
+ rendered = render_uml(model, notation, kind, max_steps)
4547
+ primary = rendered['primary']
4548
+ warnings.extend(rendered['warnings'])
4549
+ except ValueError as exc:
4550
+ warnings.append('UML_REVIEW_RENDER_SKIPPED: ' + str(exc))
4551
+ findings.append({
4552
+ 'code': 'UML019_ROUND_TRIP_SKIPPED',
4553
+ 'severity': 'warning',
4554
+ 'message': 'a sequence view is one trace, not a restatement of the machine, so the render/parse fidelity check does not apply to it; '
4555
+ 'render diagram "state" or "activity" to have the diagram checked against the model.',
4556
+ })
4557
+ elif options.get('roundTrip') is not False:
4558
+ try:
4559
+ rendered = _round_trip_of(model, notation, kind, max_steps)
4560
+ primary = rendered['primary']
4561
+ round_trip = rendered['report']
4562
+ warnings.extend(rendered['report']['warnings'])
4563
+ if not rendered['report']['ok']:
4564
+ findings.append({
4565
+ 'code': 'UML017_ROUND_TRIP_MISMATCH',
4566
+ 'severity': 'error',
4567
+ 'message': 'the rendered diagram does not read back as the model: ' + str(len(rendered['report']['diffs']))
4568
+ + ' structural difference(s).',
4569
+ 'detail': ' | '.join(rendered['report']['diffs'][:12]),
4570
+ })
4571
+ except ValueError as exc:
4572
+ message = str(exc)
4573
+ warnings.append('UML_REVIEW_ROUND_TRIP_SKIPPED: ' + message)
4574
+ findings.append({
4575
+ 'code': 'UML019_ROUND_TRIP_SKIPPED',
4576
+ 'severity': 'warning',
4577
+ 'message': 'the fidelity check could not run for ' + notation + '/' + kind + ': ' + message,
4578
+ })
4579
+ else:
4580
+ findings.append({
4581
+ 'code': 'UML019_ROUND_TRIP_SKIPPED',
4582
+ 'severity': 'warning',
4583
+ 'message': 'the fidelity check was switched off (roundTrip=false); nothing here proves the diagram carries the model.',
4584
+ })
4585
+
4586
+ findings.extend(_structural_findings(model, labels, warnings))
4587
+ errors = len([finding for finding in findings if finding['severity'] == 'error'])
4588
+ warning_count = len([finding for finding in findings if finding['severity'] == 'warning'])
4589
+ info = len([finding for finding in findings if finding['severity'] == 'info'])
4590
+ reachable = _reachable_states(model)
4591
+ if labels is None:
4592
+ narrative = model.get('narrative')
4593
+ documented_states = 0 if narrative is None or narrative.get('states') is None else len(narrative['states'])
4594
+ else:
4595
+ documented_states = len([sid for sid in labels if _documented_meaning(labels[sid], sid) is not None])
4596
+ events = dict.fromkeys(transition['event'] for transition in model['transitions'])
4597
+ next_steps = []
4598
+ if errors > 0:
4599
+ next_steps.append('Resolve the error findings first — a diagram that cannot be read (or that disagrees with its model) '
4600
+ 'will mislead every later review.')
4601
+ next_steps.append('Run logicprobe_verify on this model for the behavioural checks (S1-S8 structural, A1-A14 adversarial); '
4602
+ 'the review above covers modelling, not behaviour.')
4603
+ if 'narrative' not in model:
4604
+ next_steps.append('Add narrative.states/events/scenarios so the diagram is readable against the code.')
4605
+ if any(finding['code'] == 'UML011_UNBOUNDED_VARIABLE' for finding in findings):
4606
+ next_steps.append('Declare min/max (or boundaryChecks) before relying on A5 boundary probes.')
4607
+ report = {
4608
+ 'ok': True,
4609
+ 'source': 'model+diagram' if (has_model and has_diagram) else ('diagram' if has_diagram else 'model'),
4610
+ 'summary': {
4611
+ 'errors': errors,
4612
+ 'warnings': warning_count,
4613
+ 'info': info,
4614
+ 'states': len(model['states']),
4615
+ 'events': len(events),
4616
+ 'transitions': len(model['transitions']),
4617
+ 'terminalStates': len([state for state in model['states'] if state.get('terminal') is True]),
4618
+ 'reachableStates': len(reachable),
4619
+ 'documentedStates': documented_states,
4620
+ },
4621
+ 'findings': findings,
4622
+ 'roundTrip': round_trip,
4623
+ }
4624
+ if labels is not None:
4625
+ report['labels'] = labels
4626
+ if has_diagram:
4627
+ report['model'] = model
4628
+ if primary is not None:
4629
+ report['primary'] = primary
4630
+ report['warnings'] = warnings
4631
+ report['nextSteps'] = next_steps
4632
+ return report
4633
+
4634
+
3090
4635
  # ---------------------------------------------------------------------------
3091
4636
  # CLI
3092
4637
  # ---------------------------------------------------------------------------
@@ -3136,6 +4681,54 @@ def _cmd_export(args):
3136
4681
  print(json.dumps(out, indent=2))
3137
4682
 
3138
4683
 
4684
+ def _cmd_uml_render(args):
4685
+ try:
4686
+ model = _load_json_file(args.model)
4687
+ result = render_uml(model, args.notation, args.diagram, args.max_steps)
4688
+ except (OSError, ValueError) as exc:
4689
+ print(json.dumps({'ok': False, 'error': str(exc)}))
4690
+ sys.exit(2)
4691
+ out = {'notation': result['notation'], 'diagram': result['diagram'],
4692
+ 'primary': result['primary'], 'warnings': result['warnings']}
4693
+ print(json.dumps(out, indent=2))
4694
+
4695
+
4696
+ def _cmd_uml_parse(args):
4697
+ try:
4698
+ with open(args.diagram, 'r', encoding='utf-8') as handle:
4699
+ text = handle.read()
4700
+ result = parse_uml(text, args.notation)
4701
+ except (OSError, ValueError) as exc:
4702
+ print(json.dumps({'ok': False, 'error': str(exc)}))
4703
+ sys.exit(2)
4704
+ out = {'notation': result['notation'], 'diagram': result['diagram'], 'model': result['model'],
4705
+ 'labels': result['labels'], 'warnings': result['warnings']}
4706
+ print(json.dumps(out, indent=2))
4707
+
4708
+
4709
+ def _cmd_uml_review(args):
4710
+ try:
4711
+ options = {}
4712
+ if args.model:
4713
+ options['model'] = _load_json_file(args.model)
4714
+ if args.diagram:
4715
+ with open(args.diagram, 'r', encoding='utf-8') as handle:
4716
+ options['diagram'] = handle.read()
4717
+ if args.notation is not None:
4718
+ options['notation'] = args.notation
4719
+ if args.diagram_kind is not None:
4720
+ options['diagramKind'] = args.diagram_kind
4721
+ if args.no_round_trip:
4722
+ options['roundTrip'] = False
4723
+ if args.max_steps is not None:
4724
+ options['maxSteps'] = args.max_steps
4725
+ report = review_uml(options)
4726
+ except (OSError, ValueError) as exc:
4727
+ print(json.dumps({'ok': False, 'error': str(exc)}))
4728
+ sys.exit(2)
4729
+ print(json.dumps(report, indent=2))
4730
+
4731
+
3139
4732
  def _build_parser():
3140
4733
  parser = argparse.ArgumentParser(prog='logicprobe-engine.py',
3141
4734
  description='Standalone LogicModelV1 verification + composition + export (non-DSH mirror)')
@@ -3156,6 +4749,24 @@ def _build_parser():
3156
4749
  p_export.add_argument('model')
3157
4750
  p_export.add_argument('--format', required=True, choices=['uppaal', 'tla', 'prism', 'spin'])
3158
4751
  p_export.set_defaults(func=_cmd_export)
4752
+ p_uml_render = sub.add_parser('uml-render', help='render a LogicModelV1 as Mermaid/PlantUML UML text')
4753
+ p_uml_render.add_argument('model')
4754
+ p_uml_render.add_argument('--notation', choices=['mermaid', 'plantuml'], default='mermaid')
4755
+ p_uml_render.add_argument('--diagram', choices=['state', 'activity', 'sequence'], default='state')
4756
+ p_uml_render.add_argument('--max-steps', type=int, default=60)
4757
+ p_uml_render.set_defaults(func=_cmd_uml_render)
4758
+ p_uml_parse = sub.add_parser('uml-parse', help='parse a Mermaid/PlantUML diagram back into a LogicModelV1')
4759
+ p_uml_parse.add_argument('diagram')
4760
+ p_uml_parse.add_argument('--notation', choices=['auto', 'mermaid', 'plantuml'], default='auto')
4761
+ p_uml_parse.set_defaults(func=_cmd_uml_parse)
4762
+ p_uml_review = sub.add_parser('uml-review', help='review a machine, a diagram, or the match between the two')
4763
+ p_uml_review.add_argument('--model')
4764
+ p_uml_review.add_argument('--diagram')
4765
+ p_uml_review.add_argument('--notation', choices=['auto', 'mermaid', 'plantuml'], default='auto')
4766
+ p_uml_review.add_argument('--diagram-kind', choices=['state', 'activity', 'sequence'])
4767
+ p_uml_review.add_argument('--no-round-trip', action='store_true')
4768
+ p_uml_review.add_argument('--max-steps', type=int)
4769
+ p_uml_review.set_defaults(func=_cmd_uml_review)
3159
4770
  return parser
3160
4771
 
3161
4772