dsh-model-everything 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (133) hide show
  1. package/LICENSE +21 -0
  2. package/README.en-US.md +332 -0
  3. package/README.md +332 -3
  4. package/cordis.patch.yml +20 -0
  5. package/examples/README.md +48 -0
  6. package/examples/control-dispatcher.json +113 -0
  7. package/examples/control-dispatcher.overbudget.json +113 -0
  8. package/examples/ecommerce-data-model.json +185 -0
  9. package/examples/order-state-machine.after.json +116 -0
  10. package/examples/order-state-machine.before.json +101 -0
  11. package/examples/user-migration.after.json +29 -0
  12. package/examples/user-migration.before.json +29 -0
  13. package/gate/locale/en.json +6 -0
  14. package/gate/locale/zh.json +6 -0
  15. package/gate/package.json +5 -0
  16. package/lib/baseline.js +249 -0
  17. package/lib/compose-tool.js +80 -0
  18. package/lib/concurrency-tool.js +40 -0
  19. package/lib/concurrency.js +206 -0
  20. package/lib/data-engine.js +1141 -0
  21. package/lib/data-tool.js +87 -0
  22. package/lib/design-engine.js +1149 -0
  23. package/lib/design-tool.js +63 -0
  24. package/lib/engine.js +4343 -0
  25. package/lib/export-tool.js +78 -0
  26. package/lib/exporters.js +434 -0
  27. package/lib/gate.js +274 -0
  28. package/lib/granularity.js +237 -0
  29. package/lib/index.js +237 -0
  30. package/lib/json-value.js +18 -0
  31. package/lib/model-file.js +48 -0
  32. package/lib/option-shape.js +62 -0
  33. package/lib/report-diff-tool.js +63 -0
  34. package/lib/report-view.js +433 -0
  35. package/lib/structure-tool.js +91 -0
  36. package/lib/structure.js +711 -0
  37. package/lib/tool.js +94 -0
  38. package/lib/types/baseline.d.ts +65 -0
  39. package/lib/types/compose-tool.d.ts +7 -0
  40. package/lib/types/concurrency-tool.d.ts +8 -0
  41. package/lib/types/concurrency.d.ts +37 -0
  42. package/lib/types/data-engine.d.ts +211 -0
  43. package/lib/types/data-tool.d.ts +10 -0
  44. package/lib/types/design-engine.d.ts +215 -0
  45. package/lib/types/design-tool.d.ts +11 -0
  46. package/lib/types/engine.d.ts +494 -0
  47. package/lib/types/export-tool.d.ts +7 -0
  48. package/lib/types/exporters.d.ts +37 -0
  49. package/lib/types/gate.d.ts +91 -0
  50. package/lib/types/granularity.d.ts +106 -0
  51. package/lib/types/index.d.ts +45 -0
  52. package/lib/types/json-value.d.ts +21 -0
  53. package/lib/types/model-file.d.ts +7 -0
  54. package/lib/types/option-shape.d.ts +22 -0
  55. package/lib/types/report-diff-tool.d.ts +8 -0
  56. package/lib/types/report-view.d.ts +50 -0
  57. package/lib/types/structure-tool.d.ts +10 -0
  58. package/lib/types/structure.d.ts +152 -0
  59. package/lib/types/tool.d.ts +11 -0
  60. package/lib/types/uml-communication.d.ts +109 -0
  61. package/lib/types/uml-composite.d.ts +107 -0
  62. package/lib/types/uml-interaction-overview.d.ts +91 -0
  63. package/lib/types/uml-profile.d.ts +112 -0
  64. package/lib/types/uml-structure.d.ts +53 -0
  65. package/lib/types/uml-syntax.d.ts +296 -0
  66. package/lib/types/uml-timing.d.ts +152 -0
  67. package/lib/types/uml-tool.d.ts +12 -0
  68. package/lib/types/uml-usecase.d.ts +58 -0
  69. package/lib/types/uml.d.ts +303 -0
  70. package/lib/uml-communication.js +353 -0
  71. package/lib/uml-composite.js +442 -0
  72. package/lib/uml-interaction-overview.js +277 -0
  73. package/lib/uml-profile.js +373 -0
  74. package/lib/uml-structure.js +306 -0
  75. package/lib/uml-syntax.js +545 -0
  76. package/lib/uml-timing.js +974 -0
  77. package/lib/uml-tool.js +213 -0
  78. package/lib/uml-usecase.js +532 -0
  79. package/lib/uml.js +2110 -0
  80. package/locale/en.json +6 -0
  81. package/locale/zh.json +6 -0
  82. package/package.json +128 -6
  83. package/skills/model-everything/SKILL.md +450 -0
  84. package/skills/model-everything/references/dsh-model-schema.md +437 -0
  85. package/skills/model-everything/references/gap-routing-guide.md +42 -0
  86. package/skills/model-everything/references/hash-spec.md +152 -0
  87. package/skills/model-everything/references/logic-verification-guide.md +422 -0
  88. package/skills/model-everything-datamodel/SKILL.md +130 -0
  89. package/skills/model-everything-datamodel/references/data-model-guide.md +84 -0
  90. package/skills/model-everything-datamodel/references/data-model-schema.md +128 -0
  91. package/skills/model-everything-design/SKILL.md +115 -0
  92. package/skills/model-everything-interleaving/SKILL.md +63 -0
  93. package/skills/model-everything-interleaving/SKILL.zh-CN.md +60 -0
  94. package/skills/model-everything-interleaving/references/concurrency-risk-guide.md +63 -0
  95. package/skills/model-everything-report-reading/SKILL.md +137 -0
  96. package/skills/model-everything-report-reading/references/reading-a-report.md +166 -0
  97. package/skills/model-everything-report-reading/references/reading-a-report.mmd +59 -0
  98. package/skills/model-everything-structure/SKILL.md +96 -0
  99. package/skills/model-everything-structure/references/structure-review-guide.md +201 -0
  100. package/skills/model-everything-uml/SKILL.md +60 -0
  101. package/skills/model-everything-uml/references/uml-modeling-guide.md +551 -0
  102. package/src/baseline.ts +288 -0
  103. package/src/compose-tool.ts +82 -0
  104. package/src/concurrency-tool.ts +44 -0
  105. package/src/concurrency.ts +254 -0
  106. package/src/data-engine.ts +1208 -0
  107. package/src/data-tool.ts +91 -0
  108. package/src/design-engine.ts +1263 -0
  109. package/src/design-tool.ts +68 -0
  110. package/src/engine.ts +4564 -0
  111. package/src/export-tool.ts +81 -0
  112. package/src/exporters.ts +399 -0
  113. package/src/gate.ts +330 -0
  114. package/src/granularity.ts +312 -0
  115. package/src/index.ts +289 -0
  116. package/src/json-value.ts +20 -0
  117. package/src/model-file.ts +49 -0
  118. package/src/option-shape.ts +64 -0
  119. package/src/report-diff-tool.ts +67 -0
  120. package/src/report-view.ts +483 -0
  121. package/src/structure-tool.ts +93 -0
  122. package/src/structure.ts +786 -0
  123. package/src/tool.ts +103 -0
  124. package/src/uml-communication.ts +428 -0
  125. package/src/uml-composite.ts +520 -0
  126. package/src/uml-interaction-overview.ts +321 -0
  127. package/src/uml-profile.ts +439 -0
  128. package/src/uml-structure.ts +317 -0
  129. package/src/uml-syntax.ts +764 -0
  130. package/src/uml-timing.ts +1106 -0
  131. package/src/uml-tool.ts +230 -0
  132. package/src/uml-usecase.ts +566 -0
  133. package/src/uml.ts +2139 -0
@@ -0,0 +1,81 @@
1
+ import { defineTool } from '@deepseek-ai/dsh-tools'
2
+ import type { JsonValue } from './json-value.js'
3
+ import { REPORT_SCHEMAS, DEFAULT_HASH_SPEC, modelHash, refusalVerdict, validateModel, verdictOf } from './engine.js'
4
+ import { ExportError, exportModel, type ExportFormat } from './exporters.js'
5
+ import { renderReportText } from './report-view.js'
6
+
7
+ /** The model hash of an export's input, when the input validates (the success path always does). */
8
+ function exportHashes(model: unknown): { hashSpec: typeof DEFAULT_HASH_SPEC; modelHash?: string } {
9
+ const validation = validateModel(model)
10
+ return validation.ok
11
+ ? { hashSpec: DEFAULT_HASH_SPEC, modelHash: modelHash(validation.model) }
12
+ : { hashSpec: DEFAULT_HASH_SPEC }
13
+ }
14
+
15
+ export const EXPORT_TOOL_NAME = 'model_export'
16
+
17
+ /**
18
+ * DSH tool wrapping the external-tool exporters: turn a LogicModelV1 machine into
19
+ * native input for the tool this plugin routes to (UPPAAL / TLA+ / PRISM / SPIN).
20
+ * v1 translates the core machine; unrepresentable invariants become warnings.
21
+ */
22
+ export const modelExportTool = defineTool({
23
+ name: EXPORT_TOOL_NAME,
24
+ description:
25
+ 'Translate a LogicModelV1 into the input language of an external checker - UPPAAL, TLA+, PRISM or SPIN - for a property this plugin does not decide itself (symbolic model checking, unbounded induction, expected reward). format is one of uppaal (.xta + queries), tla (TLC spec + safety property), prism (.pm + .pctl), spin (Promela + ltl). This tool does not verify anything: for the checks it can decide use `model_verify`. Booleans are exported as 0/1 integers; invariants the target cannot express are returned as warnings, never silently dropped. Returns { ok, format, primary, extras?, warnings? } or { ok: false, error } when the model is invalid or the PRISM enumeration is too large.',
26
+ parameters: {
27
+ model: {
28
+ type: 'json',
29
+ required: true,
30
+ description: 'LogicModelV1 state-machine model to export.',
31
+ },
32
+ format: {
33
+ type: 'string',
34
+ required: true,
35
+ enum: ['uppaal', 'tla', 'prism', 'spin'],
36
+ description: 'Target tool format.',
37
+ },
38
+ reportView: {
39
+ type: 'string',
40
+ enum: ['digest', 'full'],
41
+ description: 'digest (default) prints the generated file verbatim; full prints the structured result as JSON.',
42
+ },
43
+ },
44
+ output: {
45
+ schema: {
46
+ type: 'json',
47
+ description: 'Export result with generated file content.',
48
+ },
49
+ render(args, value) {
50
+ return [{ type: 'text' as const, text: renderReportText(value, { full: args.reportView === 'full' }) }]
51
+ },
52
+ },
53
+ timeoutMs: 10_000,
54
+ isConcurrencySafe: () => true,
55
+ async execute(args) {
56
+ try {
57
+ const result = exportModel(args.model, args.format as ExportFormat)
58
+ const warnings = result.warnings ?? []
59
+ const nextSteps: string[] = []
60
+ if (warnings.length > 0) nextSteps.push('The target notation cannot express some invariants; the warnings name each one — verify them in the target tool rather than assuming they carried over.')
61
+ nextSteps.push('Run the exported file through its own tool (verify/compile) before trusting the translation; this plugin guarantees the encoding, not the target checker\'s verdict.')
62
+ return {
63
+ ok: true,
64
+ ran: true,
65
+ ...verdictOf(0, warnings.length),
66
+ schema: REPORT_SCHEMAS.export,
67
+ format: result.format,
68
+ primary: result.primary,
69
+ ...(result.extras === undefined ? {} : { extras: result.extras }),
70
+ hashes: exportHashes(args.model),
71
+ warnings,
72
+ nextSteps,
73
+ } as unknown as JsonValue
74
+ } catch (error) {
75
+ const message = error instanceof Error ? error.message : String(error)
76
+ // The exporter's own refusals carry their code: a limit of the encoding is not a defect in the model.
77
+ const errorCode = error instanceof ExportError ? error.code : 'MODEL_INVALID'
78
+ return { ok: false, ran: false, ...refusalVerdict(message), schema: REPORT_SCHEMAS.export, errorCode, error: message } as unknown as JsonValue
79
+ }
80
+ },
81
+ })
@@ -0,0 +1,399 @@
1
+ // External-tool exporters: turn a validated LogicModelV1 into native input for the
2
+ // tools this plugin routes to (see skills/model-everything/references/gap-routing-guide.md).
3
+ // v1 translates the CORE machine (states, events, transitions, integer/boolean guards
4
+ // and updates). Constructs a target cannot express are emitted as warnings/comments,
5
+ // never silently dropped. Booleans are exported as 0/1 integers everywhere.
6
+ import { validateModel, type LogicModelV1, type GuardNode, type UpdateSpec } from './engine.js'
7
+
8
+ export type ExportFormat = 'uppaal' | 'tla' | 'prism' | 'spin'
9
+
10
+ export interface ExportResult {
11
+ format: ExportFormat
12
+ primary: string
13
+ extras?: Record<string, string>
14
+ warnings: string[]
15
+ }
16
+
17
+ export interface ExportedModel {
18
+ model: LogicModelV1
19
+ stateIds: string[]
20
+ indexOf: Map<string, number>
21
+ initId: string
22
+ stateIdOf: Map<string, string>
23
+ }
24
+
25
+ export function prepareModel(input: unknown): ExportedModel {
26
+ const validation = validateModel(input)
27
+ if (!validation.ok) throw new Error('model invalid: ' + validation.errors.join('; '))
28
+ const model = validation.model
29
+ const used = new Set<string>()
30
+ const stateIds: string[] = []
31
+ const indexOf = new Map<string, number>()
32
+ const stateIdOf = new Map<string, string>()
33
+ const sanitize = (raw: string): string => {
34
+ let out = raw.replace(/[^A-Za-z0-9_]/g, '_')
35
+ if (out.length === 0 || /^[0-9]/.test(out)) out = 's_' + out
36
+ return out
37
+ }
38
+ model.states.forEach((state, index) => {
39
+ let candidate = sanitize(state.id)
40
+ if (used.has(candidate)) candidate = candidate + '_' + index
41
+ used.add(candidate)
42
+ stateIds.push(candidate)
43
+ indexOf.set(state.id, index)
44
+ stateIdOf.set(state.id, candidate)
45
+ })
46
+ return { model, stateIds, indexOf, initId: stateIdOf.get(model.init) ?? stateIds[0], stateIdOf }
47
+ }
48
+
49
+ function numValue(value: number | boolean): number {
50
+ return typeof value === 'boolean' ? (value ? 1 : 0) : value
51
+ }
52
+
53
+ function leafExpr(node: { variable: string; op: string; value: number | boolean }, varName: (v: string) => string): string {
54
+ return varName(node.variable) + ' ' + node.op + ' ' + String(numValue(node.value))
55
+ }
56
+
57
+ function guardExpr(node: GuardNode | undefined, and: string, or: string, not: string, varName: (v: string) => string, opFor: (op: string) => string = (op) => op): string {
58
+ if (node === undefined) return ''
59
+ if ('variable' in node) return varName(node.variable) + ' ' + opFor(node.op) + ' ' + String(numValue(node.value))
60
+ if ('all' in node) return '(' + node.all.map((g) => guardExpr(g, and, or, not, varName, opFor)).join(' ' + and + ' ') + ')'
61
+ if ('any' in node) return '(' + node.any.map((g) => guardExpr(g, and, or, not, varName, opFor)).join(' ' + or + ' ') + ')'
62
+ if ('not' in node) return not + '(' + guardExpr(node.not, and, or, not, varName, opFor) + ')'
63
+ return 'true'
64
+ }
65
+
66
+ function updateAssignments(updates: UpdateSpec[] | undefined, varName: (v: string) => string): string[] {
67
+ const out: string[] = []
68
+ for (const update of updates ?? []) {
69
+ const name = varName(update.variable)
70
+ const value = update.value ?? 1
71
+ if (update.op === 'set') out.push(name + ' := ' + String(value))
72
+ else if (update.op === 'inc') out.push(name + ' := ' + name + ' + ' + String(value))
73
+ else out.push(name + ' := ' + name + ' - ' + String(value))
74
+ }
75
+ return out
76
+ }
77
+
78
+ function forbiddenIndexes(ex: ExportedModel): number[] {
79
+ const out: number[] = []
80
+ for (const invariant of ex.model.invariants ?? []) {
81
+ if (invariant.kind === 'never-states') {
82
+ for (const s of invariant.states) {
83
+ const index = ex.indexOf.get(s)
84
+ if (index !== undefined) out.push(index)
85
+ }
86
+ }
87
+ }
88
+ return out
89
+ }
90
+
91
+ // ---------------------------------------------------------------- UPPAAL ----
92
+ // UPPAAL .xta is XML (flat-1_6 DTD): nta/template/location/transition with label
93
+ // kinds guard | assignment | comments. Queries are plain text (one per line).
94
+ function exportUppaal(ex: ExportedModel): ExportResult {
95
+ const { model, stateIds, indexOf, initId } = ex
96
+ const warnings: string[] = []
97
+ const xml = (s: string): string => s.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;')
98
+ const safeEvent = (event: string): string => xml(event.replace(/[^A-Za-z0-9_]/g, '_'))
99
+ const globals = (model.variables ?? []).map((v) => 'int ' + v.name + ' = ' + String(numValue(v.init)) + ';').join('\n')
100
+ const locs = model.states.map((state, i) => {
101
+ const nameEl = '\n <name x=\"16\" y=\"16\">' + xml(stateIdOf(ex, state.id)) + '</name>'
102
+ return ' <location id=\"id' + i + '\" x=\"' + (i * 120) + '\" y=\"0\">' + nameEl + '\n </location>'
103
+ }).join('\n')
104
+ const edges = model.transitions.map((tr, i) => {
105
+ const guard = guardExpr(tr.guard, '&&', '||', '!', (v) => v)
106
+ const assigns = updateAssignments(tr.updates, (v) => v)
107
+ const labels: string[] = []
108
+ if (guard !== '') labels.push(' <label kind=\"guard\" x=\"16\" y=\"16\">' + xml(guard) + '</label>')
109
+ if (assigns.length > 0) labels.push(' <label kind=\"assignment\" x=\"16\" y=\"16\">' + xml(assigns.join(',\n')) + '</label>')
110
+ // The event name is a comment, not a synchronisation. A single machine exports as one template: `e!` waits for a
111
+ // partner this file does not contain, so every transition would block forever - and the channel was never
112
+ // declared either, so UPPAAL would not load the file. The event is documentation here; rendezvous between
113
+ // machines is a composition question, and `model_compose_verify` is where that is decided.
114
+ labels.push(' <label kind=\"comments\" x=\"16\" y=\"16\">' + xml(tr.event) + '</label>')
115
+ return ' <transition id=\"id' + String(1000 + i) + '\">\n <source ref=\"id' + String(indexOf.get(tr.from)) + '\"/>\n <target ref=\"id' + String(indexOf.get(tr.to)) + '\"/>\n' + labels.join('\n') + '\n </transition>'
116
+ }).join('\n')
117
+ const queries: string[] = []
118
+ for (const state of model.states) if (state.terminal) queries.push('E<> ModelEverything.' + stateIdOf(ex, state.id))
119
+ for (const index of forbiddenIndexes(ex)) queries.push('A[] not ModelEverything.' + stateIds[index])
120
+ for (const invariant of model.invariants ?? []) {
121
+ if (invariant.kind !== 'never-states') warnings.push('UPPAAL export carries invariant kind ' + invariant.kind + ' only as a comment (not expressible in the exported XML).')
122
+ }
123
+ const initIndex = indexOf.get(model.init) ?? 0
124
+ const xta = '<?xml version="1.0" encoding="utf-8"?>\n' +
125
+ '<!DOCTYPE nta PUBLIC \'-//Uppaal Team//DTD Flat System 1.6//EN\' \'http://www.it.uu.se/research/group/darts/uppaal/flat-1_6.dtd\'>\n' +
126
+ '<nta>\n' +
127
+ ' <declaration>// Generated by this plugin (UPPAAL XML export; booleans as int).\n' + (globals === '' ? '' : globals + '\n') + '</declaration>\n' +
128
+ ' <template>\n' +
129
+ ' <name x=\"5\" y=\"5\">ModelEverything</name>\n' +
130
+ ' <declaration/>\n' +
131
+ locs + '\n' +
132
+ ' <init ref=\"id' + String(initIndex) + '\"/>\n' +
133
+ edges + '\n' +
134
+ ' </template>\n' +
135
+ ' <system>system ModelEverything;</system>\n' +
136
+ '</nta>\n'
137
+ const extras: Record<string, string> = { queries: queries.join('\n') + (queries.length ? '\n' : '') }
138
+ void initId
139
+ return { format: 'uppaal', primary: xta, extras, warnings }
140
+ }
141
+
142
+ function stateIdOf(ex: ExportedModel, id: string): string {
143
+ return ex.stateIdOf.get(id) ?? id
144
+ }
145
+
146
+ // ------------------------------------------------------------------ TLA+ ----
147
+ // ------------------------------------------------------------------ TLA+ ----
148
+ function exportTla(ex: ExportedModel): ExportResult {
149
+ const { model, stateIds, stateIdOf, initId } = ex
150
+ const warnings: string[] = []
151
+ const bs = String.fromCharCode(92) // backslash, composed so no escape pitfalls
152
+ const CONJ = '/' + bs // /\ (TLA conjunction)
153
+ const DISJ = bs + '/' // \/ (TLA disjunction)
154
+ const MEM = bs + 'in' // \in membership
155
+ const NOTIN = bs + 'notin' // \notin
156
+ const variables = ['pc'].concat((model.variables ?? []).map((v) => v.name))
157
+ const typeVar = (model.variables ?? []).map((v) => v.name + ' ' + MEM + ' ' + String(numValue(v.min ?? 0)) + '..' + String(Math.max(1, numValue(v.max ?? 1)))).join(' ' + CONJ + ' ')
158
+ const initParts = ['pc = "' + initId + '"'].concat((model.variables ?? []).map((v) => v.name + ' = ' + String(numValue(v.init)))).join(' ' + CONJ + ' ')
159
+ const nextParts = model.transitions.map((tr) => {
160
+ const guard = guardExpr(tr.guard, CONJ, DISJ, '~', (v) => v).replace(/ == /g, ' = ').replace(/ != /g, ' /= ')
161
+ const updates: string[] = []
162
+ for (const u of tr.updates ?? []) {
163
+ const value = u.value ?? 1
164
+ if (u.op === 'set') updates.push(u.variable + ' = ' + String(value))
165
+ else if (u.op === 'inc') updates.push(u.variable + ' = ' + u.variable + ' + ' + String(value))
166
+ else updates.push(u.variable + ' = ' + u.variable + ' - ' + String(value))
167
+ }
168
+ const pcPart = 'pc' + "'" + ' = "' + stateIdOf.get(tr.to) + '"'
169
+ const rest = updates.length ? ' ' + CONJ + ' ' + updates.join(' ' + CONJ + ' ') : ''
170
+ const guardPart = guard === '' ? 'pc = "' + stateIdOf.get(tr.from) + '"' : 'pc = "' + stateIdOf.get(tr.from) + '" ' + CONJ + ' ' + guard
171
+ return DISJ + ' ' + guardPart + ' ' + CONJ + ' ' + pcPart + rest
172
+ }).join('\n')
173
+ const forbids = forbiddenIndexes(ex).map((i) => '"' + stateIds[i] + '"')
174
+ const props: string[] = []
175
+ if (forbids.length) props.push('CheckSafety == [] (pc ' + NOTIN + ' {' + forbids.join(', ') + '})')
176
+ for (const invariant of model.invariants ?? []) {
177
+ if (invariant.kind !== 'never-states') warnings.push('TLA+ v1 does not translate invariant kind ' + invariant.kind + '; only never-states becomes a property.')
178
+ }
179
+ let spec = '---- MODULE ModelEverything ----\n' +
180
+ 'EXTENDS Integers\n' +
181
+ 'VARIABLES ' + variables.join(', ') + '\n' +
182
+ 'States == {' + stateIds.map((s) => '"' + s + '"').join(', ') + '}\n' +
183
+ 'TypeOK == pc ' + MEM + ' States' + (typeVar === '' ? '' : ' ' + CONJ + ' ' + typeVar) + '\n' +
184
+ 'Init == ' + initParts + '\n' +
185
+ 'Next ==\n' + nextParts + '\n' +
186
+ (props.length ? '\n' + props.join('\n\n') + '\n' : '') +
187
+ '====\n'
188
+ const extras: Record<string, string> = props.length ? { properties: props.join('\n') + '\n' } : {}
189
+ return { format: 'tla', primary: spec, extras, warnings }
190
+ }
191
+
192
+ // ----------------------------------------------------------------- PRISM ----
193
+ function exportPrism(ex: ExportedModel): ExportResult {
194
+ const { model, indexOf, stateIdOf, stateIds } = ex
195
+ const warnings: string[] = []
196
+ const ranges = (model.variables ?? []).map((v) => ({
197
+ name: v.name,
198
+ lo: numValue(v.min ?? 0),
199
+ hi: Math.max(1, numValue(v.max ?? 3)),
200
+ init: numValue(v.init),
201
+ }))
202
+ const valuations: Array<Record<string, number>> = []
203
+ const build = (i: number, acc: Record<string, number>) => {
204
+ if (i === ranges.length) { valuations.push(acc); return }
205
+ for (let v = ranges[i].lo; v <= ranges[i].hi; v++) { const copy = { ...acc }; copy[ranges[i].name] = v; build(i + 1, copy) }
206
+ }
207
+ build(0, {})
208
+ const size = model.states.length * Math.max(1, valuations.length)
209
+ if (size > 20000) {
210
+ throw new ExportError('EXPORT_TOO_LARGE', 'the PRISM encoding enumerates states x variable valuations and this model needs ' + String(model.states.length) + ' x ' + String(valuations.length) + ' = ' + String(size) + ' of them, over the 20000 this exporter writes. The model is valid; the flat enumeration is what does not fit. Narrow the variable domains, or verify the model with `model_verify` and export only the machine for the properties that need PRISM.')
211
+ }
212
+ const evalGuard = (guard: GuardNode | undefined, val: Record<string, number>): boolean => {
213
+ if (guard === undefined) return true
214
+ if ('variable' in guard) {
215
+ const left = val[guard.variable] ?? numValue((model.variables ?? []).find((v) => v.name === guard.variable)?.init ?? 0)
216
+ const right = numValue(guard.value)
217
+ switch (guard.op) { case '==': return left === right; case '!=': return left !== right; case '<': return left < right; case '<=': return left <= right; case '>': return left > right; case '>=': return left >= right; default: return false }
218
+ }
219
+ if ('all' in guard) return guard.all.every((g) => evalGuard(g, val))
220
+ if ('any' in guard) return guard.any.some((g) => evalGuard(g, val))
221
+ if ('not' in guard) return !evalGuard(guard.not, val)
222
+ return false
223
+ }
224
+ const applyUpdates = (t: typeof model.transitions[number], val: Record<string, number>): Record<string, number> => {
225
+ const out = { ...val }
226
+ for (const u of t.updates ?? []) {
227
+ const cur = out[u.variable] ?? 0
228
+ const value = u.value ?? 1
229
+ if (u.op === 'set') out[u.variable] = value
230
+ else if (u.op === 'inc') out[u.variable] = cur + value
231
+ else out[u.variable] = cur - value
232
+ }
233
+ return out
234
+ }
235
+ const commands: string[] = []
236
+ for (const state of model.states) {
237
+ for (const val of valuations) {
238
+ const groups = new Map<string, typeof model.transitions>()
239
+ for (const t of model.transitions) if (t.from === state.id) { const list = groups.get(t.event) ?? []; list.push(t); groups.set(t.event, list) }
240
+ const outcomes = new Map<string, { weight: number; pc: number; val: Record<string, number> }>()
241
+ let totalW = 0
242
+ for (const group of groups.values()) {
243
+ const guarded = group.filter((t) => t.guard !== undefined && evalGuard(t.guard, val))
244
+ const chosen = guarded.length > 0 ? guarded : group.filter((t) => t.guard === undefined)
245
+ for (const t of chosen) {
246
+ const weight = t.weight ?? 1
247
+ const nv = applyUpdates(t, val)
248
+ const key = String(indexOf.get(t.to)) + '|' + JSON.stringify(nv)
249
+ const cur = outcomes.get(key)
250
+ if (cur === undefined) { outcomes.set(key, { weight, pc: indexOf.get(t.to) ?? 0, val: nv }); totalW += weight }
251
+ else cur.weight += weight
252
+ }
253
+ }
254
+ if (outcomes.size === 0) continue
255
+ const guardParts = ['pc = ' + String(indexOf.get(state.id) ?? 0)]
256
+ for (const r of ranges) guardParts.push(r.name + ' = ' + String(val[r.name] ?? r.init))
257
+ const terms: string[] = []
258
+ for (const item of outcomes.values()) {
259
+ const p = totalW > 0 ? item.weight / totalW : 0
260
+ const prob = p.toFixed(6).replace(/0+$/, '').replace(/\.$/, '')
261
+ const upd = ["(pc' = " + String(item.pc) + ")"]
262
+ for (const r of ranges) {
263
+ const v = item.val[r.name] ?? r.init
264
+ if (v !== (val[r.name] ?? r.init)) upd.push("(" + r.name + "' = " + String(v) + ")")
265
+ }
266
+ terms.push(prob + ' : ' + upd.join(' & '))
267
+ }
268
+ commands.push('[] ' + guardParts.join(' & ') + ' ->\n ' + terms.join(' +\n '))
269
+ }
270
+ }
271
+ let module = '// Generated by this plugin (DTMC export; booleans as 0/1 integers).\n' +
272
+ 'dtmc\n\n' +
273
+ 'module ModelEverything\n' +
274
+ ' pc : [0..' + String(model.states.length - 1) + '] init ' + String(indexOf.get(model.init) ?? 0) + ';\n' +
275
+ (ranges.map((r) => ' ' + r.name + ' : [' + String(r.lo) + '..' + String(r.hi) + '] init ' + String(r.init) + ';').join('\n')) + '\n\n' +
276
+ commands.join('\n\n') + '\n' +
277
+ 'endmodule\n'
278
+ const labels: string[] = []
279
+ for (const state of model.states) if (state.terminal) labels.push('label "term_' + (stateIdOf.get(state.id) ?? 's') + '" = pc = ' + String(indexOf.get(state.id)))
280
+ const forb = forbiddenIndexes(ex)
281
+ if (forb.length) labels.push('label "forbidden" = ' + forb.map((i) => 'pc = ' + String(i)).join(' | '))
282
+ const pctl: string[] = []
283
+ for (const invariant of model.invariants ?? []) {
284
+ if (invariant.kind === 'probability') {
285
+ const target = indexOf.get(invariant.target)
286
+ if (target !== undefined) {
287
+ labels.push('label "target" = pc = ' + String(target))
288
+ pctl.push('P' + invariant.op + String(invariant.p) + ' [ F "target" ]')
289
+ }
290
+ }
291
+ }
292
+ if (forb.length) pctl.push('P>=1 [ G !"forbidden" ]')
293
+ module = module + '\n' + labels.join('\n') + '\n'
294
+ const extras: Record<string, string> = { properties: pctl.join('\n') + '\n' }
295
+ for (const invariant of model.invariants ?? []) {
296
+ if (invariant.kind !== 'probability' && invariant.kind !== 'never-states') {
297
+ warnings.push('PRISM v1 does not translate invariant kind ' + invariant.kind + '.')
298
+ }
299
+ }
300
+ void stateIds
301
+ return { format: 'prism', primary: module, extras, warnings }
302
+ }
303
+
304
+ // ------------------------------------------------------------------ SPIN ----
305
+ function exportSpin(ex: ExportedModel): ExportResult {
306
+ const { model, indexOf } = ex
307
+ const warnings: string[] = []
308
+ const varDecl = (model.variables ?? []).map((v) => 'int ' + v.name + ' = ' + String(numValue(v.init)) + ';').join('\n')
309
+ const lines: string[] = []
310
+ const promAssigns = (updates: UpdateSpec[] | undefined): string[] => {
311
+ const out: string[] = []
312
+ for (const u of updates ?? []) {
313
+ const value = u.value ?? 1
314
+ if (u.op === 'set') out.push(u.variable + ' = ' + String(value))
315
+ else if (u.op === 'inc') out.push(u.variable + ' = ' + u.variable + ' + ' + String(value))
316
+ else out.push(u.variable + ' = ' + u.variable + ' - ' + String(value))
317
+ }
318
+ return out
319
+ }
320
+ for (const t of model.transitions) {
321
+ const guard = guardExpr(t.guard, '&&', '||', '!', (v) => v)
322
+ const assigns = promAssigns(t.updates)
323
+ const cond = guard === '' ? 'pc == ' + String(indexOf.get(t.from)) : 'pc == ' + String(indexOf.get(t.from)) + ' && ' + guard
324
+ const prefix = assigns.length ? ' ' + assigns.join('; ') + ';' : ''
325
+ lines.push(' :: (' + cond + ') ->' + prefix + ' pc = ' + String(indexOf.get(t.to)) + ';')
326
+ }
327
+ for (const state of model.states) if (state.terminal) lines.push(' :: (pc == ' + String(indexOf.get(state.id)) + ') -> goto done;')
328
+ const promela = '// Generated by this plugin (Promela v1; booleans as 0/1 integers).\n' +
329
+ 'int pc = ' + String(indexOf.get(model.init) ?? 0) + ';\n' +
330
+ (varDecl === '' ? '' : varDecl + '\n') +
331
+ 'active proctype ModelEverything() {\n' +
332
+ ' do\n' +
333
+ lines.join('\n') + '\n' +
334
+ ' od\n' +
335
+ 'done: skip\n' +
336
+ '}\n'
337
+ const extras: Record<string, string> = {}
338
+ const forb = forbiddenIndexes(ex)
339
+ if (forb.length) extras.properties = 'ltl safety { [] (!(pc == ' + forb.map((i) => String(i)).join(') && !(pc == ') + ')) }\n'
340
+ for (const invariant of model.invariants ?? []) {
341
+ if (invariant.kind !== 'never-states') warnings.push('SPIN v1 does not translate invariant kind ' + invariant.kind + '.')
342
+ }
343
+ return { format: 'spin', primary: promela, extras, warnings }
344
+ }
345
+
346
+ /**
347
+ * Every format this exporter can produce, in one place.
348
+ *
349
+ * The absence of this list is what made an unknown format dangerous: the function ended with
350
+ * `return exportSpin(ex)`, so `'mermaid'`, `42`, `''` and `undefined` all produced Promela and
351
+ * reported `format: 'spin'`. A caller who named a notation this exporter cannot write received a
352
+ * different notation's output and a report naming a format they had not asked for.
353
+ */
354
+ export const EXPORT_FORMATS: readonly ExportFormat[] = ['uppaal', 'tla', 'prism', 'spin']
355
+
356
+ export function isExportFormat(value: unknown): value is ExportFormat {
357
+ return typeof value === 'string' && (EXPORT_FORMATS as readonly string[]).includes(value)
358
+ }
359
+
360
+ /**
361
+ * A refusal an exporter knows by name.
362
+ *
363
+ * The tool mapped every throw onto `MODEL_INVALID`, so "this valid model is too large for the PRISM encoding" came
364
+ * back as "your model is invalid" - a claim about the caller's work made by a limit of the exporter.
365
+ */
366
+ export class ExportError extends Error {
367
+ constructor(
368
+ readonly code: string,
369
+ message: string,
370
+ ) {
371
+ super(message)
372
+ this.name = 'ExportError'
373
+ }
374
+ }
375
+
376
+ export function exportModel(input: unknown, format: unknown): ExportResult {
377
+ if (!isExportFormat(format)) {
378
+ const arrived = format === undefined ? 'undefined' : JSON.stringify(format)
379
+ throw new Error('format must be one of ' + EXPORT_FORMATS.join(' | ') + ', got ' + arrived + '. Each one writes a different notation, so there is no default to fall back to.')
380
+ }
381
+ const ex = prepareModel(input)
382
+ const result = format === 'uppaal' ? exportUppaal(ex)
383
+ : format === 'tla' ? exportTla(ex)
384
+ : format === 'prism' ? exportPrism(ex)
385
+ : exportSpin(ex)
386
+ // Fields this model declares that the target has no place for. They are reported rather than dropped: a reader who
387
+ // sees the export trusts it as the model, and a check that ran on the field is then missing from what the target
388
+ // verifies.
389
+ const dropped: string[] = []
390
+ if (ex.model.transitions.some((transition) => transition.cost !== undefined)) {
391
+ dropped.push('EXPORT_FIELD_DROPPED: transition `cost` has no field in ' + format + ', so the A12 budget the model was checked against is not carried; model it as a reward/timing annotation in the target, or verify it here instead.')
392
+ }
393
+ if (ex.model.states.some((state) => state.maxTicks !== undefined)) {
394
+ dropped.push('EXPORT_FIELD_DROPPED: state `maxTicks` (A14, a discrete-tick deadline) has no field in ' + format + '; the target needs a clock and an invariant on the location to say the same thing.')
395
+ }
396
+ if (dropped.length === 0) return result
397
+ return { ...result, warnings: [...dropped, ...(result.warnings ?? [])] }
398
+ }
399
+