@radicaltools/cli 0.0.0-stage → 0.1.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 (4) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +273 -2
  3. package/dist/index.js +3756 -0
  4. package/package.json +40 -4
package/dist/index.js ADDED
@@ -0,0 +1,3756 @@
1
+ #!/usr/bin/env node
2
+
3
+ // src/check.ts
4
+ import { mkdir as mkdir2, readFile as readFile2, readdir as readdir2, realpath, stat as stat2, writeFile as writeFile2 } from "fs/promises";
5
+ import { basename, dirname as dirname3, join as join2, resolve as resolve2 } from "path";
6
+ import { parseArgs } from "util";
7
+
8
+ // ../../packages/common/src/metamodel/lookup.ts
9
+ function isParentAllowed(metamodel, childType, parentType) {
10
+ if (!metamodel) return true;
11
+ const def = metamodel.nodeTypes[childType];
12
+ if (!def) return true;
13
+ const allowed = def.allowedParents;
14
+ if (parentType == null) {
15
+ if (def.allowedAtRoot !== void 0) return def.allowedAtRoot;
16
+ return !allowed || allowed.length === 0;
17
+ }
18
+ return !!allowed && allowed.includes(parentType);
19
+ }
20
+ var GROUP_TYPE = "group";
21
+ function placeOf(node, nodes) {
22
+ const seen = /* @__PURE__ */ new Set();
23
+ let cur = node;
24
+ while (cur && cur.type === GROUP_TYPE && !seen.has(cur)) {
25
+ seen.add(cur);
26
+ cur = cur.parentId ? nodes[cur.parentId] : void 0;
27
+ }
28
+ return cur && cur.type !== GROUP_TYPE ? cur : void 0;
29
+ }
30
+ function hasPlaceUnder(metamodel, childType, placeType) {
31
+ if (!metamodel || !metamodel.nodeTypes[childType]) return true;
32
+ if (placeType == null) return isParentAllowed(metamodel, childType, void 0);
33
+ const seen = /* @__PURE__ */ new Set();
34
+ const queue = [childType];
35
+ while (queue.length > 0) {
36
+ for (const parent of metamodel.nodeTypes[queue.pop()]?.allowedParents ?? []) {
37
+ if (parent === placeType) return true;
38
+ if (parent === GROUP_TYPE || seen.has(parent)) continue;
39
+ seen.add(parent);
40
+ queue.push(parent);
41
+ }
42
+ }
43
+ return false;
44
+ }
45
+ var RESERVED_PROPERTY_KEYS = {
46
+ node: /* @__PURE__ */ new Set(["id", "type", "parentId", "x", "y", "width", "height", "collapsed"]),
47
+ relation: /* @__PURE__ */ new Set(["id", "sourceId", "targetId", "relationType"])
48
+ };
49
+ function isReservedPropertyKey(key, of) {
50
+ return RESERVED_PROPERTY_KEYS[of].has(key);
51
+ }
52
+ function propertyKeyProblem(key, of) {
53
+ if (!isReservedPropertyKey(key, of)) return null;
54
+ return `"${key}" is a field every ${of === "node" ? "element" : "relation"} has (${[...RESERVED_PROPERTY_KEYS[of]].join(", ")}): give the property another key.`;
55
+ }
56
+
57
+ // ../../packages/common/src/metamodel/refs.ts
58
+ function refIds(value) {
59
+ if (typeof value === "string") return value ? [value] : [];
60
+ if (Array.isArray(value)) return value.filter((v) => typeof v === "string" && v !== "");
61
+ return [];
62
+ }
63
+ function refProblem(def, id, nodes) {
64
+ const node = nodes[id];
65
+ if (!node) return `no node has id "${id}"`;
66
+ if (def.refType && node.type !== def.refType) return `"${node.label}" is of type ${node.type}, not ${def.refType}`;
67
+ return null;
68
+ }
69
+
70
+ // ../../packages/common/src/metamodel/statechart.ts
71
+ var prop = (item, key) => {
72
+ const value = item[key];
73
+ return typeof value === "string" ? value.trim() : "";
74
+ };
75
+ var stateKind = (n) => prop(n, "kind") || "normal";
76
+ var pseudoKind = (n) => prop(n, "kind") || "initial";
77
+ var isState = (n) => n?.type === "state";
78
+ var isPseudo = (n) => n?.type === "pseudostate";
79
+ var entityCache = /* @__PURE__ */ new WeakMap();
80
+ function machineEntity(machineId, nodes, relations) {
81
+ let map = entityCache.get(relations);
82
+ if (!map) {
83
+ map = /* @__PURE__ */ new Map();
84
+ for (const r of Object.values(relations)) {
85
+ if (r.relationType === "lifecycle-of" && !map.has(r.sourceId)) map.set(r.sourceId, r.targetId);
86
+ }
87
+ entityCache.set(relations, map);
88
+ }
89
+ const id = map.get(machineId);
90
+ return id ? nodes[id] : void 0;
91
+ }
92
+ function machineOf(node, nodes) {
93
+ let cur = node;
94
+ for (let depth = 0; cur && depth < 64; depth++) {
95
+ if (cur.type === "state-machine") return cur;
96
+ cur = cur.parentId ? nodes[cur.parentId] : void 0;
97
+ }
98
+ return void 0;
99
+ }
100
+ function requirementStatePhrase(requirement, nodes, relations) {
101
+ const state = nodes[refIds(requirement.precondition_state)[0] ?? ""];
102
+ if (!state) return "";
103
+ const machine = machineOf(state, nodes);
104
+ const entity = machine ? machineEntity(machine.id, nodes, relations) : void 0;
105
+ return entity ? `the ${entity.label} is ${state.label}` : `in ${state.label}`;
106
+ }
107
+ function validateStateMachines(nodes, relations) {
108
+ const nodeList = Object.values(nodes);
109
+ if (!nodeList.some((n) => n.type === "state-machine" || n.type === "state" || n.type === "pseudostate")) return [];
110
+ const issues = [];
111
+ const warn = (id, message, at) => {
112
+ issues.push({ id, severity: "warning", message, ...at });
113
+ };
114
+ const children = /* @__PURE__ */ new Map();
115
+ for (const n of nodeList) {
116
+ if (!n.parentId) continue;
117
+ const list = children.get(n.parentId);
118
+ if (list) list.push(n);
119
+ else children.set(n.parentId, [n]);
120
+ }
121
+ const childStates = (id) => (children.get(id) ?? []).filter(isState);
122
+ const initialsOf = (id) => (children.get(id) ?? []).filter((c) => isPseudo(c) && pseudoKind(c) === "initial");
123
+ const transitions = Object.values(relations).filter((r) => r.relationType === "transition" && nodes[r.sourceId] && nodes[r.targetId]);
124
+ const outgoing = /* @__PURE__ */ new Map();
125
+ const incoming = /* @__PURE__ */ new Set();
126
+ for (const t of transitions) {
127
+ const list = outgoing.get(t.sourceId);
128
+ if (list) list.push(t);
129
+ else outgoing.set(t.sourceId, [t]);
130
+ incoming.add(t.targetId);
131
+ }
132
+ const regions = nodeList.filter((n) => n.type === "state-machine" || isState(n) && stateKind(n) === "normal");
133
+ for (const owner of regions) {
134
+ if (childStates(owner.id).length === 0) continue;
135
+ const initials = initialsOf(owner.id);
136
+ const what = owner.type === "state-machine" ? "State machine" : "Compound state";
137
+ if (initials.length === 0) {
138
+ warn(`sm-no-initial:${owner.id}`, `${what} "${owner.label}" has child states but no initial pseudostate to enter them.`, { nodeId: owner.id });
139
+ } else if (initials.length > 1) {
140
+ warn(`sm-many-initials:${owner.id}`, `${what} "${owner.label}" has ${initials.length} initial pseudostates; keep one.`, { nodeId: owner.id });
141
+ }
142
+ }
143
+ for (const n of nodeList) {
144
+ if (isPseudo(n) && pseudoKind(n) === "initial") {
145
+ const out = outgoing.get(n.id) ?? [];
146
+ if (out.length !== 1) {
147
+ warn(`sm-initial-out:${n.id}`, `Initial pseudostate in "${n.parentId ? nodes[n.parentId]?.label : ""}" needs exactly one transition, to the default state (it has ${out.length}).`, { nodeId: n.id });
148
+ }
149
+ if (incoming.has(n.id)) {
150
+ warn(`sm-initial-in:${n.id}`, `A transition points at the initial pseudostate in "${n.parentId ? nodes[n.parentId]?.label : ""}"; target the state itself.`, { nodeId: n.id });
151
+ }
152
+ }
153
+ if (!isState(n)) continue;
154
+ const kind = stateKind(n);
155
+ if (kind === "parallel") {
156
+ if (childStates(n.id).length < 2) {
157
+ warn(`sm-parallel-regions:${n.id}`, `Parallel state "${n.label}" needs at least two child states (regions) active at once.`, { nodeId: n.id });
158
+ }
159
+ if (initialsOf(n.id).length > 0) {
160
+ warn(`sm-parallel-initial:${n.id}`, `Parallel state "${n.label}" enters all its regions; it takes no initial pseudostate.`, { nodeId: n.id });
161
+ }
162
+ }
163
+ if (kind === "final") {
164
+ if ((children.get(n.id) ?? []).length > 0) {
165
+ warn(`sm-final-children:${n.id}`, `Final state "${n.label}" cannot contain other states.`, { nodeId: n.id });
166
+ }
167
+ if ((outgoing.get(n.id) ?? []).length > 0) {
168
+ warn(`sm-final-out:${n.id}`, `Final state "${n.label}" cannot have outgoing transitions.`, { nodeId: n.id });
169
+ }
170
+ }
171
+ }
172
+ for (const t of transitions) {
173
+ const src = nodes[t.sourceId];
174
+ const dst = nodes[t.targetId];
175
+ if (machineOf(src, nodes)?.id !== machineOf(dst, nodes)?.id) {
176
+ warn(`sm-cross-machine:${t.id}`, `Transition "${src.label}" \u2192 "${dst.label}" leaves its state machine.`, { relationId: t.id });
177
+ }
178
+ }
179
+ for (const [sourceId, out] of outgoing) {
180
+ const byEvent = /* @__PURE__ */ new Map();
181
+ for (const t of out) {
182
+ if (prop(t, "guard")) continue;
183
+ const key = refIds(t.event)[0] ?? "";
184
+ const list = byEvent.get(key);
185
+ if (list) list.push(t);
186
+ else byEvent.set(key, [t]);
187
+ }
188
+ for (const [event, list] of byEvent) {
189
+ if (list.length < 2) continue;
190
+ const on = event ? `on "${nodes[event]?.label ?? event}"` : "without an event";
191
+ warn(`sm-nondeterministic:${sourceId}:${event}`, `"${nodes[sourceId].label}" has ${list.length} unguarded transitions ${on}; only one can fire.`, { nodeId: sourceId });
192
+ }
193
+ }
194
+ const machinesOfEntity = /* @__PURE__ */ new Map();
195
+ for (const machine of nodeList.filter((n) => n.type === "state-machine")) {
196
+ const entity = machineEntity(machine.id, nodes, relations);
197
+ if (!entity) {
198
+ warn(`sm-no-entity:${machine.id}`, `State machine "${machine.label}" is the lifecycle of no entity; link it to one with "lifecycle-of".`, { nodeId: machine.id });
199
+ continue;
200
+ }
201
+ machinesOfEntity.set(entity.id, [...machinesOfEntity.get(entity.id) ?? [], machine]);
202
+ }
203
+ for (const [entityId, machines] of machinesOfEntity) {
204
+ if (machines.length < 2) continue;
205
+ warn(`sm-many-machines:${entityId}`, `Entity "${nodes[entityId].label}" has ${machines.length} state machines (${machines.map((m) => m.label).join(", ")}); model one lifecycle, with parallel regions if parts of it progress at once.`, { nodeId: entityId });
206
+ }
207
+ for (const machine of nodeList.filter((n) => n.type === "state-machine")) {
208
+ if (initialsOf(machine.id).length === 0) continue;
209
+ const reached = /* @__PURE__ */ new Set();
210
+ const queue = [machine.id];
211
+ const visit = (id) => {
212
+ if (!reached.has(id)) {
213
+ reached.add(id);
214
+ queue.push(id);
215
+ }
216
+ };
217
+ while (queue.length > 0) {
218
+ const id = queue.shift();
219
+ const n = nodes[id];
220
+ if (!n) continue;
221
+ if (n.parentId && n.parentId !== machine.id && nodes[n.parentId]) visit(n.parentId);
222
+ if (n.type === "state-machine" || isState(n) && stateKind(n) === "normal") {
223
+ for (const init of initialsOf(id)) visit(init.id);
224
+ } else if (isState(n) && stateKind(n) === "parallel") {
225
+ for (const region of childStates(id)) visit(region.id);
226
+ }
227
+ for (const t of outgoing.get(id) ?? []) visit(t.targetId);
228
+ }
229
+ const unreached = (id) => {
230
+ for (const child of children.get(id) ?? []) {
231
+ if (isState(child) && !reached.has(child.id)) {
232
+ warn(`sm-unreachable:${child.id}`, `State "${child.label}" cannot be reached from the initial state of "${machine.label}".`, { nodeId: child.id });
233
+ continue;
234
+ }
235
+ unreached(child.id);
236
+ }
237
+ };
238
+ unreached(machine.id);
239
+ }
240
+ return issues;
241
+ }
242
+
243
+ // ../../packages/common/src/metamodel/domainModel.ts
244
+ var kindOf = (n) => {
245
+ const kind = n.kind;
246
+ return typeof kind === "string" && kind ? kind : "aggregate-root";
247
+ };
248
+ function validateDomainModel(nodes, relations) {
249
+ const entities = Object.values(nodes).filter((n) => n.type === "entity");
250
+ if (entities.length === 0) return [];
251
+ const issues = [];
252
+ const warn = (id, message, at) => {
253
+ issues.push({ id, severity: "warning", message, ...at });
254
+ };
255
+ const rootsOf = /* @__PURE__ */ new Map();
256
+ for (const r of Object.values(relations)) {
257
+ if (r.relationType !== "part-of") continue;
258
+ const part = nodes[r.sourceId];
259
+ const root = nodes[r.targetId];
260
+ if (part?.type !== "entity" || root?.type !== "entity") continue;
261
+ if (kindOf(part) === "aggregate-root") {
262
+ warn(`ddd-root-part-of:${r.id}`, `Aggregate root "${part.label}" is part of "${root.label}"; aggregates refer to each other with "references" instead.`, { relationId: r.id });
263
+ continue;
264
+ }
265
+ if (kindOf(root) !== "aggregate-root") {
266
+ warn(`ddd-part-of-entity:${r.id}`, `"${part.label}" is part of "${root.label}", which is not an aggregate root.`, { relationId: r.id });
267
+ }
268
+ rootsOf.set(part.id, [...rootsOf.get(part.id) ?? [], root.label]);
269
+ }
270
+ for (const entity of entities) {
271
+ if (kindOf(entity) !== "entity") continue;
272
+ const roots = rootsOf.get(entity.id) ?? [];
273
+ if (roots.length === 0) {
274
+ warn(`ddd-loose-entity:${entity.id}`, `Entity "${entity.label}" is not an aggregate root and part of no aggregate; link it to its root with "part-of", or make it a root.`, { nodeId: entity.id });
275
+ } else if (roots.length > 1) {
276
+ warn(`ddd-many-roots:${entity.id}`, `Entity "${entity.label}" is part of ${roots.length} aggregates (${roots.join(", ")}); it belongs to one.`, { nodeId: entity.id });
277
+ }
278
+ }
279
+ return issues;
280
+ }
281
+
282
+ // ../../packages/common/src/metamodel/validate.ts
283
+ function validateModel(nodes, relations, metamodel) {
284
+ const issues = [];
285
+ const nodeList = Object.values(nodes);
286
+ for (const n of nodeList) {
287
+ const def = metamodel.nodeTypes[n.type];
288
+ if (!def) {
289
+ issues.push({
290
+ id: `unknown-type:${n.id}`,
291
+ severity: "error",
292
+ message: `Node "${n.label}" has unknown type "${n.type}".`,
293
+ nodeId: n.id
294
+ });
295
+ continue;
296
+ }
297
+ const allowed = def.allowedParents;
298
+ if (n.parentId) {
299
+ const parent = nodes[n.parentId];
300
+ if (!parent) {
301
+ issues.push({
302
+ id: `parent-missing:${n.id}`,
303
+ severity: "error",
304
+ message: `Node "${n.label}" references a missing parent.`,
305
+ nodeId: n.id
306
+ });
307
+ } else if (allowed && !allowed.includes(parent.type)) {
308
+ const parentLabel = metamodel.nodeTypes[parent.type]?.label ?? parent.type;
309
+ issues.push({
310
+ id: `bad-parent:${n.id}`,
311
+ severity: "error",
312
+ message: `${def.label} "${n.label}" cannot be inside ${parentLabel}. Allowed parents: ${allowed.length ? allowed.join(", ") : "(none \u2014 must be root)"}.`,
313
+ nodeId: n.id
314
+ });
315
+ } else if (parent.type === GROUP_TYPE && !hasPlaceUnder(metamodel, n.type, placeOf(parent, nodes)?.type)) {
316
+ const place = placeOf(parent, nodes);
317
+ const where2 = place ? `inside ${metamodel.nodeTypes[place.type]?.label ?? place.type} "${place.label}"` : "at the top of the model";
318
+ issues.push({
319
+ id: `bad-place:${n.id}`,
320
+ severity: "warning",
321
+ message: `${def.label} "${n.label}" is in group "${parent.label}", which is ${where2}, where a ${def.label} has no place.`,
322
+ nodeId: n.id
323
+ });
324
+ }
325
+ } else if (def.allowedAtRoot === false || def.allowedAtRoot === void 0 && allowed && allowed.length > 0) {
326
+ issues.push({
327
+ id: `needs-parent:${n.id}`,
328
+ severity: "error",
329
+ message: `${def.label} "${n.label}" must be inside ${allowed && allowed.length ? allowed.join(" or ") : "a parent"}.`,
330
+ nodeId: n.id
331
+ });
332
+ }
333
+ for (const p of def.properties ?? []) {
334
+ if (!p.required) continue;
335
+ const v = n[p.key];
336
+ if (v == null || v === "") {
337
+ issues.push({
338
+ id: `missing-prop:${n.id}:${p.key}`,
339
+ severity: "warning",
340
+ message: `${def.label} "${n.label}" is missing required property "${p.label}".`,
341
+ nodeId: n.id
342
+ });
343
+ }
344
+ }
345
+ }
346
+ for (const def of Object.values(metamodel.nodeTypes)) {
347
+ const c = def.cardinality;
348
+ if (!c) continue;
349
+ const count = nodeList.filter((n) => n.type === def.id).length;
350
+ if (c.min != null && count < c.min) {
351
+ issues.push({
352
+ id: `cardinality-min:${def.id}`,
353
+ severity: "warning",
354
+ message: `Model has ${count} ${def.label} (minimum ${c.min}).`,
355
+ nodeTypeId: def.id
356
+ });
357
+ }
358
+ if (c.max != null && count > c.max) {
359
+ issues.push({
360
+ id: `cardinality-max:${def.id}`,
361
+ severity: "warning",
362
+ message: `Model has ${count} ${def.label} (maximum ${c.max}).`,
363
+ nodeTypeId: def.id
364
+ });
365
+ }
366
+ }
367
+ for (const def of [...Object.values(metamodel.nodeTypes), ...Object.values(metamodel.relationTypes)]) {
368
+ const seen = /* @__PURE__ */ new Set();
369
+ for (const p of def.properties ?? []) {
370
+ if (seen.has(p.key)) {
371
+ const isNode = !!metamodel.nodeTypes[def.id] && metamodel.nodeTypes[def.id] === def;
372
+ issues.push({ id: `dup-prop:${def.id}:${p.key}`, severity: "error", message: `${isNode ? def.label : `Relation type "${def.label}"`}: two properties have the key "${p.key}"; give one another key.`, ...isNode ? { nodeTypeId: def.id } : {} });
373
+ }
374
+ seen.add(p.key);
375
+ }
376
+ }
377
+ for (const def of Object.values(metamodel.nodeTypes)) {
378
+ for (const p of def.properties ?? []) {
379
+ const problem = propertyKeyProblem(p.key, "node");
380
+ if (problem) {
381
+ issues.push({ id: `reserved-prop:${def.id}:${p.key}`, severity: "error", message: `${def.label}: property key ${problem}`, nodeTypeId: def.id });
382
+ }
383
+ }
384
+ }
385
+ for (const def of Object.values(metamodel.relationTypes)) {
386
+ for (const p of def.properties ?? []) {
387
+ const problem = propertyKeyProblem(p.key, "relation");
388
+ if (problem) {
389
+ issues.push({ id: `reserved-rel-prop:${def.id}:${p.key}`, severity: "error", message: `Relation type "${def.label}": property key ${problem}` });
390
+ }
391
+ }
392
+ }
393
+ const restrictiveTypes = Object.values(metamodel.relationTypes).filter((rt) => rt.allowedPairs.length > 0);
394
+ const anyAllows = Object.values(metamodel.relationTypes).some((rt) => rt.allowedPairs.length === 0);
395
+ if (restrictiveTypes.length > 0 && !anyAllows) {
396
+ for (const r of Object.values(relations)) {
397
+ const src = nodes[r.sourceId];
398
+ const dst = nodes[r.targetId];
399
+ if (!src || !dst) continue;
400
+ const ok = restrictiveTypes.some(
401
+ (rt) => rt.allowedPairs.some((p) => p.from === src.type && p.to === dst.type)
402
+ );
403
+ if (!ok) {
404
+ issues.push({
405
+ id: `bad-rel:${r.id}`,
406
+ severity: "warning",
407
+ message: `Relation "${src.label}" \u2192 "${dst.label}" (${src.type}\u2192${dst.type}) is not allowed by metamodel.`,
408
+ relationId: r.id
409
+ });
410
+ }
411
+ }
412
+ }
413
+ for (const r of Object.values(relations)) {
414
+ const missing = [r.sourceId, r.targetId].filter((id) => !nodes[id]);
415
+ if (missing.length) {
416
+ issues.push({
417
+ id: `rel-end-missing:${r.id}`,
418
+ severity: "error",
419
+ message: `Relation "${r.label ?? r.id}" ${missing.length === 2 ? "has no element at either end" : `points at "${missing[0]}", which is no element of the model`}.`,
420
+ relationId: r.id
421
+ });
422
+ }
423
+ if (r.relationType && !metamodel.relationTypes[r.relationType]) {
424
+ issues.push({
425
+ id: `unknown-rel-type:${r.id}`,
426
+ severity: "error",
427
+ message: `Relation "${r.label ?? r.id}" has unknown type "${r.relationType}".`,
428
+ relationId: r.id
429
+ });
430
+ }
431
+ }
432
+ for (const r of Object.values(relations)) {
433
+ const def = r.relationType ? metamodel.relationTypes[r.relationType] : void 0;
434
+ for (const p of def?.properties ?? []) {
435
+ if (!p.required) continue;
436
+ const v = r[p.key];
437
+ if (v == null || v === "" || Array.isArray(v) && v.length === 0) {
438
+ const src = nodes[r.sourceId]?.label ?? r.sourceId;
439
+ const dst = nodes[r.targetId]?.label ?? r.targetId;
440
+ issues.push({
441
+ id: `missing-prop:${r.id}:${p.key}`,
442
+ severity: "warning",
443
+ message: `Relation "${src}" \u2192 "${dst}" (${def.label}) is missing required property "${p.label}".`,
444
+ relationId: r.id
445
+ });
446
+ }
447
+ }
448
+ }
449
+ for (const r of Object.values(relations)) {
450
+ const def = r.relationType ? metamodel.relationTypes[r.relationType] : void 0;
451
+ const src = nodes[r.sourceId];
452
+ const dst = nodes[r.targetId];
453
+ if (!def || !src || !dst || def.allowedPairs.length === 0) continue;
454
+ if (def.allowedPairs.some((p) => p.from === src.type && p.to === dst.type)) continue;
455
+ issues.push({
456
+ id: `bad-rel-type:${r.id}`,
457
+ severity: "warning",
458
+ message: `Relation "${src.label}" \u2192 "${dst.label}" is "${def.label}", which does not connect ${src.type}\u2192${dst.type}.`,
459
+ relationId: r.id
460
+ });
461
+ }
462
+ const checkRefs = (item, props, at, what) => {
463
+ for (const p of props ?? []) {
464
+ if (p.type !== "ref") continue;
465
+ for (const id of refIds(item[p.key])) {
466
+ const problem = refProblem(p, id, nodes);
467
+ if (problem) {
468
+ issues.push({
469
+ id: `bad-ref:${at.nodeId ?? at.relationId}:${p.key}:${id}`,
470
+ severity: "warning",
471
+ message: `${what}: "${p.label}" points at nothing valid (${problem}).`,
472
+ ...at
473
+ });
474
+ }
475
+ }
476
+ }
477
+ };
478
+ for (const n of nodeList) {
479
+ const def = metamodel.nodeTypes[n.type];
480
+ if (def) checkRefs(n, def.properties, { nodeId: n.id }, `${def.label} "${n.label}"`);
481
+ }
482
+ for (const r of Object.values(relations)) {
483
+ const def = r.relationType ? metamodel.relationTypes[r.relationType] : void 0;
484
+ if (!def) continue;
485
+ const src = nodes[r.sourceId]?.label ?? r.sourceId;
486
+ const dst = nodes[r.targetId]?.label ?? r.targetId;
487
+ checkRefs(r, def.properties, { relationId: r.id }, `${def.label} "${src}" \u2192 "${dst}"`);
488
+ }
489
+ if (metamodel.nodeTypes.entity && metamodel.relationTypes["part-of"]) {
490
+ issues.push(...validateDomainModel(nodes, relations));
491
+ }
492
+ if (metamodel.nodeTypes.state && metamodel.relationTypes.transition) {
493
+ issues.push(...validateStateMachines(nodes, relations));
494
+ }
495
+ return issues;
496
+ }
497
+
498
+ // ../../packages/common/src/metamodel/ears.ts
499
+ function capitalize(s) {
500
+ return s.charAt(0).toUpperCase() + s.slice(1);
501
+ }
502
+ function earsActionIsClause(action) {
503
+ return /\S\s+shall\s+\S/i.test(action);
504
+ }
505
+ function composeEarsSentence(node, subject, statePrecondition) {
506
+ const earsType = String(node.ears_type ?? "ubiquitous");
507
+ const subj = (subject || "the system").trim();
508
+ const action = String(node.action ?? "").trim();
509
+ const trigger = String(node.trigger ?? "").trim();
510
+ const precondition = (statePrecondition ?? "").trim() || String(node.precondition ?? "").trim();
511
+ const unwanted = String(node.unwanted_condition ?? "").trim();
512
+ const feature = String(node.feature ?? "").trim();
513
+ const actionPart = action.replace(/\.+$/, "") || "\u2039action\u203A";
514
+ const ownClause = earsActionIsClause(actionPart);
515
+ const shallClause = ownClause ? actionPart.replace(/^(The|A|An)\b/, (w) => w.toLowerCase()) : `${subj} shall ${actionPart}`;
516
+ let sentence;
517
+ let complete = !!action;
518
+ switch (earsType) {
519
+ case "event-driven":
520
+ sentence = `When ${trigger || "\u2039trigger\u203A"}, ${shallClause}.`;
521
+ complete = complete && !!trigger;
522
+ break;
523
+ case "state-driven":
524
+ sentence = `While ${precondition || "\u2039precondition\u203A"}, ${shallClause}.`;
525
+ complete = complete && !!precondition;
526
+ break;
527
+ case "unwanted-behaviour":
528
+ sentence = `If ${unwanted || "\u2039condition\u203A"}, then ${shallClause}.`;
529
+ complete = complete && !!unwanted;
530
+ break;
531
+ case "optional":
532
+ sentence = `Where ${feature || "\u2039feature\u203A"}, ${shallClause}.`;
533
+ complete = complete && !!feature;
534
+ break;
535
+ case "complex": {
536
+ const parts = [];
537
+ if (precondition) parts.push(`While ${precondition}`);
538
+ if (trigger) parts.push(`when ${trigger}`);
539
+ if (unwanted) parts.push(`if ${unwanted}`);
540
+ if (feature) parts.push(`where ${feature}`);
541
+ const hasCondition = parts.length > 0;
542
+ if (!hasCondition) parts.push("\u2039conditions\u203A");
543
+ else parts[0] = capitalize(parts[0]);
544
+ sentence = `${parts.join(", ")}, ${shallClause}.`;
545
+ complete = complete && hasCondition;
546
+ break;
547
+ }
548
+ default:
549
+ sentence = ownClause ? `${capitalize(actionPart)}.` : `${capitalize(subj)} shall ${actionPart}.`;
550
+ break;
551
+ }
552
+ return { sentence, complete };
553
+ }
554
+
555
+ // ../../packages/common/src/metamodel/presets/viewpoints.ts
556
+ var DEPLOYABLE = ["container", "webapp", "database", "queue"];
557
+ var BUILDING_BLOCKS = ["system", "container", "webapp", "component", "database", "queue"];
558
+ function among(types) {
559
+ return { levels: [{ ways: [{ types }] }], edges: "all" };
560
+ }
561
+ function c4Viewpoints() {
562
+ return [
563
+ {
564
+ id: "system-context",
565
+ label: "System context",
566
+ group: "C4",
567
+ description: "The people and software systems, and how they use each other (C4 level 1).",
568
+ kind: "static",
569
+ pipeline: among(["person", "system"])
570
+ },
571
+ {
572
+ id: "containers",
573
+ label: "Containers",
574
+ group: "C4",
575
+ description: "The software systems with the containers, web apps, databases and queues inside them, the people who use them, and every relation between them (C4 level 2).",
576
+ kind: "static",
577
+ pipeline: among(["person", "system", ...DEPLOYABLE])
578
+ },
579
+ {
580
+ id: "components",
581
+ label: "Components",
582
+ group: "C4",
583
+ description: "The containers and web apps with the components inside them, the databases and queues they use, and every relation between them (C4 level 3).",
584
+ kind: "static",
585
+ pipeline: among(["container", "webapp", "component", "database", "queue"])
586
+ },
587
+ {
588
+ id: "container-dependencies",
589
+ label: "Container dependencies",
590
+ group: "C4",
591
+ description: "A matrix of the containers, web apps, databases and queues: who uses whom, and where the cycles are.",
592
+ kind: "matrix",
593
+ pipeline: among(DEPLOYABLE)
594
+ }
595
+ ];
596
+ }
597
+ function radicalViewpoints() {
598
+ return [
599
+ ...c4Viewpoints(),
600
+ {
601
+ id: "domain-map",
602
+ label: "Domain map",
603
+ group: "Domain",
604
+ description: "The domains and subdomains, and how they depend on and partner with each other.",
605
+ kind: "static",
606
+ pipeline: among(["domain"])
607
+ },
608
+ {
609
+ id: "domain-model",
610
+ label: "Domain model",
611
+ group: "Domain",
612
+ description: "The entities and aggregates, what they are part of and what they reference.",
613
+ kind: "static",
614
+ pipeline: among(["entity"])
615
+ },
616
+ {
617
+ id: "domain-realisation",
618
+ label: "Domain realisation",
619
+ group: "Domain",
620
+ description: "A table of domains, their entities, and the systems, containers and components that realise each.",
621
+ kind: "table",
622
+ pipeline: { levels: [
623
+ { ways: [{ types: ["domain"] }] },
624
+ { ways: [{ via: { contains: true }, types: ["entity"] }, { via: { relationType: "realises", direction: "in" } }] },
625
+ { ways: [{ via: { relationType: "realises", direction: "in" } }] }
626
+ ] }
627
+ },
628
+ {
629
+ id: "traceability",
630
+ label: "Traceability",
631
+ group: "Requirements",
632
+ description: "A table of needs, the requirements refined from each, and the scenarios that verify those.",
633
+ kind: "table",
634
+ pipeline: { levels: [
635
+ { ways: [{ types: ["need"] }] },
636
+ { ways: [{ via: { relationType: "derives", direction: "in" }, types: ["requirement"] }] },
637
+ { ways: [{ via: { relationType: "verifies", direction: "in" }, types: ["scenario"] }] }
638
+ ] }
639
+ },
640
+ {
641
+ id: "requirement-coverage",
642
+ label: "Requirement coverage",
643
+ group: "Requirements",
644
+ description: "A table of requirements, the elements that satisfy each and the scenarios that verify it.",
645
+ kind: "table",
646
+ pipeline: { levels: [
647
+ { ways: [{ types: ["requirement"] }] },
648
+ { ways: [{ via: { relationType: "satisfies", direction: "in" } }, { via: { relationType: "verifies", direction: "in" }, types: ["scenario"] }] }
649
+ ] }
650
+ },
651
+ {
652
+ id: "requirement-gaps",
653
+ label: "Requirement gaps",
654
+ group: "Requirements",
655
+ description: "The requirements no scenario verifies or nothing satisfies yet.",
656
+ kind: "table",
657
+ pipeline: { levels: [
658
+ { ways: [{ types: ["requirement"] }], filters: [
659
+ { kind: "relation", relationType: "verifies", direction: "in", has: false },
660
+ { kind: "relation", relationType: "satisfies", direction: "in", has: false, join: "or" }
661
+ ] }
662
+ ] }
663
+ },
664
+ {
665
+ id: "responsibilities",
666
+ label: "Responsibilities",
667
+ group: "Requirements",
668
+ description: "A table of the systems, containers and components that satisfy requirements, each with its requirements and the scenarios that verify them.",
669
+ kind: "table",
670
+ pipeline: { levels: [
671
+ { ways: [{ types: BUILDING_BLOCKS }], filters: [{ kind: "relation", relationType: "satisfies", direction: "out", has: true }] },
672
+ { ways: [{ via: { relationType: "satisfies", direction: "out" }, types: ["requirement"] }] },
673
+ { ways: [{ via: { relationType: "verifies", direction: "in" }, types: ["scenario"] }] }
674
+ ] }
675
+ },
676
+ {
677
+ id: "specification",
678
+ label: "Specification",
679
+ group: "Requirements",
680
+ description: "A document of the needs, the requirements refined from each, and the scenarios and screens for each requirement.",
681
+ kind: "wiki",
682
+ pipeline: { levels: [
683
+ { ways: [{ types: ["need"] }] },
684
+ { ways: [{ via: { relationType: "derives", direction: "in" }, types: ["requirement"] }] },
685
+ { ways: [{ via: { relationType: "verifies", direction: "in" }, types: ["scenario"] }, { via: { relationType: "illustrates", direction: "in" }, types: ["mockup"] }] }
686
+ ] }
687
+ },
688
+ {
689
+ id: "decisions",
690
+ label: "Decisions",
691
+ group: "Decisions",
692
+ description: "A table of ADRs, the fitness functions that check each and the elements it constrains.",
693
+ kind: "table",
694
+ pipeline: { levels: [
695
+ { ways: [{ types: ["adr"] }] },
696
+ { ways: [{ via: { relationType: "implements", direction: "in" }, types: ["fitness-fn"] }, { via: { relationType: "constrains", direction: "out" } }] }
697
+ ] }
698
+ },
699
+ {
700
+ id: "decision-log",
701
+ label: "Decision log",
702
+ group: "Decisions",
703
+ description: "A document of the ADRs, the newest first, each with the decisions it supersedes.",
704
+ kind: "wiki",
705
+ pipeline: {
706
+ levels: [
707
+ { ways: [{ types: ["adr"] }] },
708
+ { ways: [{ via: { relationType: "supersedes", direction: "out" }, types: ["adr"] }] }
709
+ ],
710
+ sort: { by: "property", key: "date", desc: true }
711
+ }
712
+ },
713
+ {
714
+ id: "fitness-functions",
715
+ label: "Fitness functions",
716
+ group: "Decisions",
717
+ description: "A table of the fitness functions by category, each with the decisions it checks and the elements it constrains.",
718
+ kind: "table",
719
+ pipeline: {
720
+ levels: [
721
+ { ways: [{ types: ["fitness-fn"] }] },
722
+ { ways: [{ via: { relationType: "implements", direction: "out" }, types: ["adr"] }, { via: { relationType: "constrains", direction: "out" } }] }
723
+ ],
724
+ sort: { by: "property", key: "category" }
725
+ }
726
+ },
727
+ {
728
+ id: "screen-flow",
729
+ label: "Screen flow",
730
+ group: "UX",
731
+ description: "The screens and how users navigate from one to the next.",
732
+ kind: "static",
733
+ pipeline: among(["mockup"])
734
+ },
735
+ {
736
+ id: "screens",
737
+ label: "Screens",
738
+ group: "UX",
739
+ description: "A table of the screens, each with the requirements and scenarios it illustrates and the elements that present it.",
740
+ kind: "table",
741
+ pipeline: { levels: [
742
+ { ways: [{ types: ["mockup"] }] },
743
+ { ways: [{ via: { relationType: "illustrates", direction: "out" } }, { via: { relationType: "presented-by", direction: "out" } }] }
744
+ ] }
745
+ },
746
+ {
747
+ id: "entity-lifecycles",
748
+ label: "Entity lifecycles",
749
+ group: "States",
750
+ description: "A table of the entities with a lifecycle, the state machine of each, and what implements and verifies it.",
751
+ kind: "table",
752
+ pipeline: { levels: [
753
+ { ways: [{ types: ["entity"] }], filters: [{ kind: "relation", relationType: "lifecycle-of", direction: "in", has: true }] },
754
+ { ways: [{ via: { relationType: "lifecycle-of", direction: "in" }, types: ["state-machine"] }] },
755
+ { ways: [{ via: { relationType: "implements", direction: "in" } }, { via: { relationType: "verifies", direction: "in" }, types: ["scenario"] }] }
756
+ ] }
757
+ },
758
+ {
759
+ id: "event-catalogue",
760
+ label: "Event catalogue",
761
+ group: "States",
762
+ description: "A table of the events, each with what emits it.",
763
+ kind: "table",
764
+ pipeline: { levels: [
765
+ { ways: [{ types: ["event"] }] },
766
+ { ways: [{ via: { relationType: "emits", direction: "in" } }] }
767
+ ] }
768
+ }
769
+ ];
770
+ }
771
+
772
+ // ../../packages/common/src/metamodel/presets/c4.ts
773
+ var VISUALS = {
774
+ person: {
775
+ label: "Person",
776
+ color: "#08427b",
777
+ fg: "#fff",
778
+ description: "Someone who uses or runs the system: a customer, an operator, another team.",
779
+ iconPath: "M8 2a2.5 2.5 0 1 1 0 5 2.5 2.5 0 0 1 0-5ZM3 12.5C3 10.01 5.24 8 8 8s5 2.01 5 4.5V14H3v-1.5Z",
780
+ width: 150,
781
+ height: 170,
782
+ collapsedWidth: 150,
783
+ collapsedHeight: 170
784
+ },
785
+ system: {
786
+ label: "Software System",
787
+ color: "#1168bd",
788
+ fg: "#fff",
789
+ description: "Something that delivers value to its users and is owned by one team: yours, or one you depend on.",
790
+ iconPath: "M2 3.5A1.5 1.5 0 0 1 3.5 2h9A1.5 1.5 0 0 1 14 3.5v9a1.5 1.5 0 0 1-1.5 1.5h-9A1.5 1.5 0 0 1 2 12.5v-9ZM4 5h8v1H4V5Zm0 2.5h8v1H4v-1Zm0 2.5h5v1H4V10Z",
791
+ width: 360,
792
+ height: 260,
793
+ collapsedWidth: 280,
794
+ collapsedHeight: 180
795
+ },
796
+ container: {
797
+ label: "Container",
798
+ color: "#438dd5",
799
+ fg: "#fff",
800
+ description: "Something that runs or stores data and is deployed on its own: a service, a worker, a mobile app, a serverless function.",
801
+ iconPath: "M1 4a2 2 0 0 1 2-2h10a2 2 0 0 1 2 2v1H1V4Zm0 2.5h14V12a2 2 0 0 1-2 2H3a2 2 0 0 1-2-2V6.5ZM3 3a.5.5 0 1 0 0 1 .5.5 0 0 0 0-1Zm2 0a.5.5 0 1 0 0 1 .5.5 0 0 0 0-1Z",
802
+ width: 300,
803
+ height: 200,
804
+ collapsedWidth: 240,
805
+ collapsedHeight: 160
806
+ },
807
+ component: {
808
+ label: "Component",
809
+ color: "#85bbf0",
810
+ fg: "#000",
811
+ description: "A part of a container behind a clear interface: a controller, a domain service, an adapter.",
812
+ iconPath: "M5 1v2H3a1 1 0 0 0-1 1v2h2v2H2v2h2v2H2v2a1 1 0 0 0 1 1h2v2h2v-2h2v2h2v-2h2a1 1 0 0 0 1-1v-2h-2v-2h2V8h-2V6h2V4a1 1 0 0 0-1-1h-2V1H9v2H7V1H5Z",
813
+ width: 200,
814
+ height: 120,
815
+ collapsedWidth: 200,
816
+ collapsedHeight: 120
817
+ },
818
+ database: {
819
+ label: "Database",
820
+ color: "#438dd5",
821
+ fg: "#fff",
822
+ description: "A container that stores data. It never starts an interaction.",
823
+ iconPath: "M8 1C4.7 1 2 2.3 2 4v8c0 1.7 2.7 3 6 3s6-1.3 6-3V4c0-1.7-2.7-3-6-3ZM2 4c0 1.7 2.7 3 6 3s6-1.3 6-3",
824
+ width: 190,
825
+ height: 130,
826
+ collapsedWidth: 190,
827
+ collapsedHeight: 130
828
+ },
829
+ webapp: {
830
+ label: "Web App",
831
+ color: "#438dd5",
832
+ fg: "#fff",
833
+ description: "A container that is a browser front end.",
834
+ iconPath: "M2 3a1 1 0 0 1 1-1h10a1 1 0 0 1 1 1v10a1 1 0 0 1-1 1H3a1 1 0 0 1-1-1V3Zm1 2.5V13h10V5.5H3ZM4 3.5a.5.5 0 1 0 0 1 .5.5 0 0 0 0-1Zm1.5 0a.5.5 0 1 0 0 1 .5.5 0 0 0 0-1Zm1.5 0a.5.5 0 1 0 0 1 .5.5 0 0 0 0-1Z",
835
+ width: 210,
836
+ height: 140,
837
+ collapsedWidth: 210,
838
+ collapsedHeight: 140
839
+ },
840
+ queue: {
841
+ label: "Queue",
842
+ color: "#438dd5",
843
+ fg: "#fff",
844
+ description: "A container that carries messages between other containers.",
845
+ iconPath: "M4 3a3 2 0 1 0 0 4h8a3 2 0 1 0 0-4H4Zm-2 5.5a3 2 0 0 0 4 0v-1a3 2 0 0 1-4 0v1Zm10 0a3 2 0 0 0 4 0v-1a3 2 0 0 1-4 0v1Z",
846
+ width: 220,
847
+ height: 95,
848
+ collapsedWidth: 220,
849
+ collapsedHeight: 95
850
+ },
851
+ group: {
852
+ label: "Group",
853
+ color: "#64748b",
854
+ fg: "#fff",
855
+ description: "A labelled boundary with no meaning of its own: a team, a layer, a deployment zone.",
856
+ // Folder icon.
857
+ iconPath: "M2 3.5C2 2.67 2.67 2 3.5 2H7l1.5 2h4c.83 0 1.5.67 1.5 1.5v7c0 .83-.67 1.5-1.5 1.5h-9C2.67 14 2 13.33 2 12.5v-9Z",
858
+ width: 520,
859
+ height: 360,
860
+ collapsedWidth: 360,
861
+ collapsedHeight: 220
862
+ }
863
+ };
864
+ function builtInC4Metamodel() {
865
+ const nodeTypes = {};
866
+ const allowedParentsMap = {
867
+ person: ["group"],
868
+ system: ["system", "group"],
869
+ container: ["system", "group"],
870
+ component: ["container", "webapp", "group"],
871
+ database: ["system", "group"],
872
+ webapp: ["system", "group"],
873
+ queue: ["system", "group"],
874
+ group: ["group", "system"]
875
+ };
876
+ const techTypes = /* @__PURE__ */ new Set(["container", "component", "database", "webapp", "queue"]);
877
+ const types = [
878
+ "person",
879
+ "system",
880
+ "container",
881
+ "component",
882
+ "database",
883
+ "webapp",
884
+ "queue",
885
+ "group"
886
+ ];
887
+ for (const t of types) {
888
+ const props = [
889
+ { key: "description", label: "Description", type: "textarea" }
890
+ ];
891
+ if (techTypes.has(t)) props.push({ key: "technology", label: "Technology", type: "text" });
892
+ if (t !== "group") props.push({ key: "external", label: "External", type: "boolean" });
893
+ const v = VISUALS[t];
894
+ nodeTypes[t] = {
895
+ id: t,
896
+ label: v.label,
897
+ description: v.description,
898
+ color: v.color,
899
+ fg: v.fg,
900
+ iconPath: v.iconPath,
901
+ width: v.width,
902
+ height: v.height,
903
+ collapsedWidth: v.collapsedWidth,
904
+ collapsedHeight: v.collapsedHeight,
905
+ allowedParents: allowedParentsMap[t],
906
+ // person, system, and group are top-level concepts and may live at the root.
907
+ allowedAtRoot: t === "person" || t === "system" || t === "group",
908
+ builtin: true,
909
+ properties: props
910
+ };
911
+ }
912
+ const interactsPairs = [
913
+ // Person interacts with the system surface
914
+ { from: "person", to: "system" },
915
+ { from: "person", to: "container" },
916
+ { from: "person", to: "webapp" },
917
+ { from: "person", to: "component" },
918
+ // System-level dependencies
919
+ { from: "system", to: "person" },
920
+ { from: "system", to: "system" },
921
+ { from: "system", to: "container" },
922
+ { from: "system", to: "database" },
923
+ { from: "system", to: "webapp" },
924
+ { from: "system", to: "queue" },
925
+ { from: "system", to: "component" },
926
+ // Container-level calls
927
+ { from: "container", to: "person" },
928
+ { from: "container", to: "system" },
929
+ { from: "container", to: "container" },
930
+ { from: "container", to: "database" },
931
+ { from: "container", to: "webapp" },
932
+ { from: "container", to: "queue" },
933
+ // Web / UI container
934
+ { from: "webapp", to: "person" },
935
+ { from: "webapp", to: "system" },
936
+ { from: "webapp", to: "container" },
937
+ { from: "webapp", to: "database" },
938
+ { from: "webapp", to: "webapp" },
939
+ { from: "webapp", to: "queue" },
940
+ // Queues fan out to consumers
941
+ { from: "queue", to: "container" },
942
+ { from: "queue", to: "webapp" },
943
+ { from: "queue", to: "component" },
944
+ // Component-level calls
945
+ { from: "component", to: "component" },
946
+ { from: "component", to: "container" },
947
+ { from: "component", to: "webapp" },
948
+ { from: "component", to: "database" },
949
+ { from: "component", to: "queue" },
950
+ { from: "component", to: "system" }
951
+ ];
952
+ const relationTypes = {
953
+ interacts: {
954
+ id: "interacts",
955
+ label: "Interacts",
956
+ description: "Any meaningful interaction: the source calls, uses, sends to or delivers to the target. The label says what happens, the technology how.",
957
+ forwardLabel: "Uses",
958
+ inverseLabel: "Used by",
959
+ allowedPairs: interactsPairs,
960
+ properties: [
961
+ { key: "technology", label: "Technology", type: "text" }
962
+ ],
963
+ builtin: true
964
+ }
965
+ };
966
+ return { id: "c4-builtin", name: "C4 (built-in)", nodeTypes, relationTypes, viewpoints: c4Viewpoints() };
967
+ }
968
+
969
+ // ../../packages/common/src/metamodel/presets/ddd.ts
970
+ function builtInDddC4Metamodel() {
971
+ const base = builtInC4Metamodel();
972
+ const patchedSystem = {
973
+ ...base.nodeTypes.system,
974
+ allowedParents: ["system", "domain", "group"],
975
+ allowedAtRoot: true
976
+ };
977
+ const domainProps = [
978
+ { key: "description", label: "Description", type: "textarea" },
979
+ { key: "vision", label: "Vision", type: "textarea" },
980
+ {
981
+ key: "kind",
982
+ label: "Kind",
983
+ type: "enum",
984
+ options: ["core", "supporting", "generic"],
985
+ default: "core"
986
+ }
987
+ ];
988
+ const domain = {
989
+ id: "domain",
990
+ label: "Domain",
991
+ description: "A part of the problem space, in the language of the business rather than of the software.",
992
+ color: "#4c1d95",
993
+ fg: "#fff",
994
+ iconPath: "M2 3.5A1.5 1.5 0 0 1 3.5 2h9A1.5 1.5 0 0 1 14 3.5v9a1.5 1.5 0 0 1-1.5 1.5h-9A1.5 1.5 0 0 1 2 12.5v-9Zm1.5 1A.5.5 0 0 0 3 5v6a.5.5 0 0 0 .5.5h9A.5.5 0 0 0 13 11V5a.5.5 0 0 0-.5-.5h-9ZM5 7h2v2H5V7Zm4 0h2v2H9V7Z",
995
+ width: 520,
996
+ height: 360,
997
+ collapsedWidth: 360,
998
+ collapsedHeight: 220,
999
+ // A domain may be nested inside another domain or a group.
1000
+ allowedParents: ["domain", "group"],
1001
+ allowedAtRoot: true,
1002
+ builtin: true,
1003
+ properties: domainProps
1004
+ };
1005
+ const entity = {
1006
+ id: "entity",
1007
+ label: "Entity",
1008
+ description: "A thing the domain keeps track of and that has an identity over time: a reservation, an order, a payment.",
1009
+ color: "#7e22ce",
1010
+ fg: "#fff",
1011
+ // A record card with a key
1012
+ iconPath: "M3 2.5A1.5 1.5 0 0 1 4.5 1h7A1.5 1.5 0 0 1 13 2.5v11a1.5 1.5 0 0 1-1.5 1.5h-7A1.5 1.5 0 0 1 3 13.5v-11ZM4.5 2a.5.5 0 0 0-.5.5V5h8V2.5a.5.5 0 0 0-.5-.5h-7ZM12 6H4v1.5h8V6Zm0 2.5H4V10h8V8.5Zm0 2.5H4v2.5c0 .28.22.5.5.5h7a.5.5 0 0 0 .5-.5V11Z",
1013
+ width: 170,
1014
+ height: 56,
1015
+ allowedParents: ["domain", "group"],
1016
+ allowedAtRoot: true,
1017
+ builtin: true,
1018
+ // The parts of an aggregate list under its root in Table and Wiki views.
1019
+ hierarchyRelation: "part-of",
1020
+ properties: [
1021
+ {
1022
+ key: "kind",
1023
+ label: "Kind",
1024
+ type: "enum",
1025
+ options: ["aggregate-root", "entity"],
1026
+ default: "aggregate-root"
1027
+ },
1028
+ { key: "description", label: "Description", type: "textarea" }
1029
+ ]
1030
+ };
1031
+ const realises = {
1032
+ id: "realises",
1033
+ label: "Realises",
1034
+ description: "The software behind a domain or an entity: the bounded context that implements the domain, or the element that owns the entity's data.",
1035
+ inverseLabel: "Realised by",
1036
+ allowedPairs: [
1037
+ { from: "system", to: "domain" },
1038
+ { from: "container", to: "domain" },
1039
+ ...["system", "container", "component", "webapp"].map((from) => ({ from, to: "entity" }))
1040
+ ],
1041
+ properties: [],
1042
+ builtin: true
1043
+ };
1044
+ const partOf = {
1045
+ id: "part-of",
1046
+ label: "Part of",
1047
+ description: "A part of an aggregate points to its root.",
1048
+ inverseLabel: "Made up of",
1049
+ allowedPairs: [{ from: "entity", to: "entity" }],
1050
+ properties: [],
1051
+ color: "#7e22ce",
1052
+ builtin: true
1053
+ };
1054
+ const references = {
1055
+ id: "references",
1056
+ label: "References",
1057
+ description: "One aggregate refers to another by id.",
1058
+ inverseLabel: "Referenced by",
1059
+ allowedPairs: [{ from: "entity", to: "entity" }],
1060
+ properties: [
1061
+ {
1062
+ key: "cardinality",
1063
+ label: "Cardinality",
1064
+ type: "enum",
1065
+ options: ["one", "many"],
1066
+ default: "one"
1067
+ },
1068
+ { key: "description", label: "Description", type: "text" }
1069
+ ],
1070
+ color: "#a855f7",
1071
+ builtin: true
1072
+ };
1073
+ const ddPairs = [
1074
+ { from: "domain", to: "domain" }
1075
+ ];
1076
+ const dependsOn = {
1077
+ id: "depends-on",
1078
+ label: "Depends on",
1079
+ description: "The source domain needs the target to do its work.",
1080
+ inverseLabel: "Depended on by",
1081
+ allowedPairs: ddPairs,
1082
+ properties: [
1083
+ { key: "description", label: "Description", type: "text" }
1084
+ ],
1085
+ builtin: true
1086
+ };
1087
+ const partnership = {
1088
+ id: "partnership",
1089
+ label: "Partnership",
1090
+ description: "How the models of two domains meet, with a context-mapping pattern.",
1091
+ forwardLabel: "Partners with",
1092
+ inverseLabel: "Partners with",
1093
+ allowedPairs: ddPairs,
1094
+ properties: [
1095
+ {
1096
+ key: "pattern",
1097
+ label: "Pattern",
1098
+ type: "enum",
1099
+ options: [
1100
+ "partnership",
1101
+ "shared-kernel",
1102
+ "customer-supplier",
1103
+ "conformist",
1104
+ "anti-corruption-layer",
1105
+ "open-host-service",
1106
+ "published-language",
1107
+ "separate-ways"
1108
+ ],
1109
+ default: "partnership"
1110
+ },
1111
+ { key: "description", label: "Description", type: "text" }
1112
+ ],
1113
+ builtin: true
1114
+ };
1115
+ return {
1116
+ id: "c4-ddd-builtin",
1117
+ name: "C4 + DDD Domains",
1118
+ nodeTypes: {
1119
+ ...base.nodeTypes,
1120
+ system: patchedSystem,
1121
+ domain,
1122
+ entity
1123
+ },
1124
+ relationTypes: {
1125
+ ...base.relationTypes,
1126
+ realises,
1127
+ "part-of": partOf,
1128
+ references,
1129
+ "depends-on": dependsOn,
1130
+ partnership
1131
+ }
1132
+ };
1133
+ }
1134
+
1135
+ // ../../packages/common/src/metamodel/presets/governance.ts
1136
+ var RADICAL_METAMODEL_NAME = "Radical";
1137
+ var TESTS_PROPERTY = {
1138
+ key: "tests",
1139
+ label: "Tests (one per line: file \u203A title)",
1140
+ type: "textarea"
1141
+ };
1142
+ function builtInGovernanceMetamodel() {
1143
+ const base = builtInDddC4Metamodel();
1144
+ const adrProps = [
1145
+ {
1146
+ key: "status",
1147
+ label: "Status",
1148
+ type: "enum",
1149
+ options: ["proposed", "accepted", "deprecated", "superseded"],
1150
+ default: "proposed"
1151
+ },
1152
+ { key: "date", label: "Date", type: "text" },
1153
+ { key: "context", label: "Context", type: "textarea" },
1154
+ { key: "decision", label: "Decision", type: "textarea" },
1155
+ { key: "consequences", label: "Consequences", type: "textarea" },
1156
+ { key: "alternatives", label: "Alternatives considered", type: "textarea" }
1157
+ ];
1158
+ const adr = {
1159
+ id: "adr",
1160
+ label: "ADR",
1161
+ description: "An architecture decision record: the context of a decision, the decision itself, its consequences and the alternatives that were considered.",
1162
+ color: "#92400e",
1163
+ fg: "#fff",
1164
+ // ADR: document with text lines
1165
+ iconPath: "M4.5 1C3.67 1 3 1.67 3 2.5v11c0 .83.67 1.5 1.5 1.5h7c.83 0 1.5-.67 1.5-1.5V6L9 1H4.5ZM9 2l3 3.5H9V2ZM5 8h6v1H5V8Zm0 2.5h6v1H5v-1Zm0 2.5h3.5v1H5V13Z",
1166
+ width: 180,
1167
+ height: 52,
1168
+ collapsedWidth: 160,
1169
+ collapsedHeight: 52,
1170
+ allowedParents: ["system", "domain", "group"],
1171
+ allowedAtRoot: true,
1172
+ builtin: true,
1173
+ properties: adrProps,
1174
+ wizard: {
1175
+ trigger: "create",
1176
+ prefill: { status: "proposed", date: "{{today}}" },
1177
+ steps: [
1178
+ {
1179
+ kind: "fields",
1180
+ title: "Title & status",
1181
+ fields: ["label", "status", "date"],
1182
+ help: 'Name the decision in a few words, e.g. "Use PostgreSQL for order storage".'
1183
+ },
1184
+ {
1185
+ kind: "fields",
1186
+ title: "Context",
1187
+ fields: ["context"],
1188
+ help: "What forces are at play \u2014 the problem, constraints and drivers that make a decision necessary now?"
1189
+ },
1190
+ {
1191
+ kind: "fields",
1192
+ title: "Decision",
1193
+ fields: ["decision"],
1194
+ help: 'What did you decide? State it actively: "We will \u2026".'
1195
+ },
1196
+ {
1197
+ kind: "fields",
1198
+ title: "Alternatives",
1199
+ fields: ["alternatives"],
1200
+ help: "Which other options did you consider, and why were they rejected?"
1201
+ },
1202
+ {
1203
+ kind: "fields",
1204
+ title: "Consequences",
1205
+ fields: ["consequences"],
1206
+ help: "What becomes easier or harder? Include the downsides and the risks you accept."
1207
+ },
1208
+ {
1209
+ kind: "relations",
1210
+ title: "Affected elements",
1211
+ relationType: "constrains",
1212
+ direction: "out",
1213
+ help: "Which parts of the architecture must follow this decision?"
1214
+ },
1215
+ {
1216
+ kind: "relations",
1217
+ title: "Supersedes",
1218
+ relationType: "supersedes",
1219
+ direction: "out",
1220
+ help: "Does this decision replace an earlier one? Leave empty if not."
1221
+ }
1222
+ ]
1223
+ }
1224
+ };
1225
+ const fitnessFnProps = [
1226
+ { key: "description", label: "Description", type: "textarea" },
1227
+ {
1228
+ key: "category",
1229
+ label: "Category",
1230
+ type: "enum",
1231
+ options: ["structural", "operational", "process", "holistic"],
1232
+ default: "structural"
1233
+ },
1234
+ { key: "threshold", label: "Threshold / Success criteria", type: "text" },
1235
+ TESTS_PROPERTY
1236
+ ];
1237
+ const fitnessFn = {
1238
+ id: "fitness-fn",
1239
+ label: "Fitness Function",
1240
+ description: "An objective, preferably automated check that the architecture still has a property it was designed for.",
1241
+ color: "#5b21b6",
1242
+ fg: "#fff",
1243
+ // Concentric circles (target / gauge)
1244
+ iconPath: "M8 2a6 6 0 1 0 0 12A6 6 0 0 0 8 2Zm0 1.5a4.5 4.5 0 1 1 0 9 4.5 4.5 0 0 1 0-9ZM8 5.5a2.5 2.5 0 1 0 0 5 2.5 2.5 0 0 0 0-5Zm0 1a1.5 1.5 0 1 1 0 3 1.5 1.5 0 0 1 0-3Z",
1245
+ width: 180,
1246
+ height: 52,
1247
+ collapsedWidth: 160,
1248
+ collapsedHeight: 52,
1249
+ allowedParents: ["system", "domain", "group"],
1250
+ allowedAtRoot: true,
1251
+ builtin: true,
1252
+ properties: fitnessFnProps,
1253
+ wizard: {
1254
+ trigger: "create",
1255
+ steps: [
1256
+ {
1257
+ kind: "fields",
1258
+ title: "Name & category",
1259
+ fields: ["label", "category"],
1260
+ help: 'Name the architectural characteristic this function protects, e.g. "Checkout p95 latency".'
1261
+ },
1262
+ {
1263
+ kind: "fields",
1264
+ title: "What it measures",
1265
+ fields: ["description"],
1266
+ help: "How is the characteristic measured \u2014 a test, a metric, a static check?"
1267
+ },
1268
+ {
1269
+ kind: "fields",
1270
+ title: "Success criteria",
1271
+ fields: ["threshold"],
1272
+ help: 'When does it pass? Give a concrete threshold, e.g. "p95 < 300 ms".'
1273
+ },
1274
+ {
1275
+ kind: "relations",
1276
+ title: "Verified decisions",
1277
+ relationType: "implements",
1278
+ direction: "out",
1279
+ help: "Which ADRs does this fitness function verify?"
1280
+ },
1281
+ {
1282
+ kind: "relations",
1283
+ title: "Guarded elements",
1284
+ relationType: "constrains",
1285
+ direction: "out",
1286
+ help: "Which elements does it check?"
1287
+ }
1288
+ ]
1289
+ }
1290
+ };
1291
+ const needProps = [
1292
+ { key: "description", label: "Text", type: "textarea" },
1293
+ {
1294
+ key: "kind",
1295
+ label: "Kind",
1296
+ type: "enum",
1297
+ options: ["brief", "user-story", "stakeholder-note", "meeting-notes", "regulation", "other"],
1298
+ default: "brief"
1299
+ },
1300
+ { key: "source", label: "Source (who / where from)", type: "text" }
1301
+ ];
1302
+ const need = {
1303
+ id: "need",
1304
+ label: "Need",
1305
+ description: "Raw input in the stakeholder's own words, kept verbatim: a brief, a user story, a note, a regulation.",
1306
+ color: "#475569",
1307
+ fg: "#fff",
1308
+ // Speech bubble with text lines
1309
+ iconPath: "M3 2a1.5 1.5 0 0 0-1.5 1.5v7A1.5 1.5 0 0 0 3 12h1.5v2.5L8 12h5a1.5 1.5 0 0 0 1.5-1.5v-7A1.5 1.5 0 0 0 13 2H3Zm1.5 3h7v1h-7V5Zm0 2.5h5v1h-5v-1Z",
1310
+ width: 200,
1311
+ height: 80,
1312
+ collapsedWidth: 180,
1313
+ collapsedHeight: 80,
1314
+ allowedParents: ["system", "domain", "group"],
1315
+ allowedAtRoot: true,
1316
+ builtin: true,
1317
+ // A need's wiki page and table tab list what derives from it — sub-needs
1318
+ // and requirements — as its children; "add child" creates either.
1319
+ hierarchyRelation: "derives",
1320
+ properties: needProps,
1321
+ wizard: {
1322
+ trigger: "create",
1323
+ steps: [
1324
+ {
1325
+ kind: "fields",
1326
+ title: "Name & kind",
1327
+ fields: ["label", "kind"],
1328
+ help: 'A short name, e.g. "Checkout brief from Sales". Pick what kind of input it is.'
1329
+ },
1330
+ {
1331
+ kind: "fields",
1332
+ title: "Text",
1333
+ fields: ["description"],
1334
+ help: "Paste the input as-is \u2014 a brief, user story, notes or raw requirements. No format needed; Radical Forge or you can turn it into EARS requirements later."
1335
+ },
1336
+ {
1337
+ kind: "fields",
1338
+ title: "Source",
1339
+ fields: ["source"],
1340
+ help: "Who it came from or where it lives (a person, meeting, ticket or link)."
1341
+ },
1342
+ {
1343
+ kind: "relations",
1344
+ title: "Part of",
1345
+ relationType: "derives",
1346
+ direction: "out",
1347
+ help: "Is this part of a broader need, e.g. one stakeholder's notes within a discovery? Leave empty if not."
1348
+ }
1349
+ ]
1350
+ }
1351
+ };
1352
+ const requirementProps = [
1353
+ {
1354
+ key: "ears_type",
1355
+ label: "EARS type",
1356
+ type: "enum",
1357
+ options: ["ubiquitous", "event-driven", "state-driven", "unwanted-behaviour", "optional", "complex"],
1358
+ default: "ubiquitous"
1359
+ },
1360
+ { key: "trigger", label: "When (trigger)", type: "text", visibleWhen: { key: "ears_type", values: ["event-driven", "complex"] } },
1361
+ { key: "precondition", label: "While (precondition)", type: "text", visibleWhen: { key: "ears_type", values: ["state-driven", "complex"] } },
1362
+ // The state the precondition is, when it is one of a state machine's:
1363
+ // "While the Reservation is Confirmed". Takes the place of the text.
1364
+ { key: "precondition_state", label: "While in state", type: "ref", refType: "state", visibleWhen: { key: "ears_type", values: ["state-driven", "complex"] } },
1365
+ { key: "unwanted_condition", label: "If (unwanted condition)", type: "text", visibleWhen: { key: "ears_type", values: ["unwanted-behaviour", "complex"] } },
1366
+ { key: "feature", label: "Where (feature)", type: "text", visibleWhen: { key: "ears_type", values: ["optional", "complex"] } },
1367
+ { key: "action", label: "The system shall (action)", type: "textarea" },
1368
+ { key: "rationale", label: "Rationale", type: "textarea" }
1369
+ ];
1370
+ const requirement = {
1371
+ id: "requirement",
1372
+ label: "Requirement",
1373
+ description: "One thing the system shall do, written as an EARS sentence.",
1374
+ color: "#0e7490",
1375
+ fg: "#fff",
1376
+ // Checklist / clipboard with checkmark
1377
+ iconPath: "M5 1a1 1 0 0 0-1 1H3a1 1 0 0 0-1 1v11a1 1 0 0 0 1 1h10a1 1 0 0 0 1-1V3a1 1 0 0 0-1-1h-1a1 1 0 0 0-1-1H5Zm0 1h6v1H5V2ZM4 5.5h1.5v1.5H4V5.5Zm3 .25h5v1H7v-1ZM4 9h1.5v1.5H4V9Zm3 .25h5v1H7v-1Z",
1378
+ width: 200,
1379
+ height: 80,
1380
+ collapsedWidth: 180,
1381
+ collapsedHeight: 80,
1382
+ allowedParents: ["system", "domain", "group"],
1383
+ allowedAtRoot: true,
1384
+ builtin: true,
1385
+ hierarchyRelation: "derives",
1386
+ properties: requirementProps,
1387
+ wizard: {
1388
+ trigger: "create",
1389
+ steps: [
1390
+ {
1391
+ kind: "fields",
1392
+ title: "Name",
1393
+ fields: ["label"],
1394
+ help: 'A short name for the requirement, e.g. "Lock account after failed logins".'
1395
+ },
1396
+ {
1397
+ kind: "custom",
1398
+ title: "Sentence",
1399
+ component: "ears-quick-entry",
1400
+ help: "Type the requirement as one sentence and press Enter \u2014 the EARS fields are filled for you. Or skip and fill them in the next step."
1401
+ },
1402
+ {
1403
+ kind: "fields",
1404
+ title: "EARS fields",
1405
+ fields: ["ears_type", "trigger", "precondition", "precondition_state", "unwanted_condition", "feature", "action"],
1406
+ help: "Pick the EARS pattern; only the clauses it uses are shown."
1407
+ },
1408
+ {
1409
+ kind: "fields",
1410
+ title: "Rationale",
1411
+ fields: ["rationale"],
1412
+ help: "Why is this requirement needed? Who asked for it?"
1413
+ },
1414
+ {
1415
+ kind: "relations",
1416
+ title: "Satisfied by",
1417
+ relationType: "satisfies",
1418
+ direction: "in",
1419
+ help: "Which elements must satisfy this requirement?"
1420
+ },
1421
+ {
1422
+ kind: "relations",
1423
+ title: "Derives from",
1424
+ relationType: "derives",
1425
+ direction: "out",
1426
+ help: "Is this a refinement of a broader requirement, or derived from a need?"
1427
+ },
1428
+ {
1429
+ kind: "relations",
1430
+ title: "Traces to",
1431
+ relationType: "traces-to",
1432
+ direction: "out",
1433
+ help: "Which decisions or fitness functions follow from it?"
1434
+ }
1435
+ ]
1436
+ }
1437
+ };
1438
+ const constraintSources = ["adr", "fitness-fn", "requirement"];
1439
+ const constraintTargets = ["person", "system", "domain", "container", "component", "database", "webapp", "queue"];
1440
+ const constrainsPairs = constraintSources.flatMap(
1441
+ (from) => constraintTargets.map((to) => ({ from, to }))
1442
+ );
1443
+ const constrains = {
1444
+ id: "constrains",
1445
+ label: "Constrains",
1446
+ description: "The decision, check or requirement applies to the target element.",
1447
+ inverseLabel: "Constrained by",
1448
+ allowedPairs: constrainsPairs,
1449
+ properties: [
1450
+ { key: "description", label: "Note", type: "text" }
1451
+ ],
1452
+ color: "#dc2626",
1453
+ builtin: true
1454
+ };
1455
+ const supersedes = {
1456
+ id: "supersedes",
1457
+ label: "Supersedes",
1458
+ description: "The newer decision replaces the older one.",
1459
+ inverseLabel: "Superseded by",
1460
+ allowedPairs: [{ from: "adr", to: "adr" }],
1461
+ properties: [],
1462
+ color: "#f59e0b",
1463
+ builtin: true
1464
+ };
1465
+ const implements_ = {
1466
+ id: "implements",
1467
+ label: "Implements",
1468
+ description: "A fitness function checks that a decision still holds; a C4 element runs a state machine.",
1469
+ inverseLabel: "Implemented by",
1470
+ allowedPairs: [{ from: "fitness-fn", to: "adr" }],
1471
+ properties: [],
1472
+ color: "#7c3aed",
1473
+ builtin: true
1474
+ };
1475
+ const satisfiesTargets = ["person", "system", "domain", "container", "component", "database", "webapp", "queue"];
1476
+ const satisfies = {
1477
+ id: "satisfies",
1478
+ label: "Satisfies",
1479
+ description: "The element is what makes the requirement true.",
1480
+ inverseLabel: "Satisfied by",
1481
+ allowedPairs: satisfiesTargets.map((to) => ({ from: to, to: "requirement" })),
1482
+ properties: [
1483
+ { key: "description", label: "Note", type: "text" }
1484
+ ],
1485
+ color: "#0891b2",
1486
+ builtin: true
1487
+ };
1488
+ const derives = {
1489
+ id: "derives",
1490
+ label: "Derives from",
1491
+ description: "A requirement turns stakeholder input into a shall-statement or refines a broader requirement; a need sits inside a broader need.",
1492
+ inverseLabel: "Refined into",
1493
+ allowedPairs: [
1494
+ { from: "requirement", to: "requirement" },
1495
+ { from: "requirement", to: "need" },
1496
+ { from: "need", to: "need" }
1497
+ ],
1498
+ properties: [],
1499
+ color: "#0d9488",
1500
+ builtin: true
1501
+ };
1502
+ const tracesTo = {
1503
+ id: "traces-to",
1504
+ label: "Traces to",
1505
+ description: "The decision the requirement led to, or the check that keeps it.",
1506
+ inverseLabel: "Traced from",
1507
+ allowedPairs: [
1508
+ { from: "requirement", to: "adr" },
1509
+ { from: "requirement", to: "fitness-fn" }
1510
+ ],
1511
+ properties: [],
1512
+ color: "#06b6d4",
1513
+ builtin: true
1514
+ };
1515
+ const scenarioProps = [
1516
+ { key: "given", label: "Given", type: "textarea" },
1517
+ { key: "when", label: "When", type: "textarea" },
1518
+ { key: "then", label: "Then", type: "textarea" },
1519
+ { key: "gherkin", label: "Extra steps (And/But, raw Gherkin)", type: "textarea" },
1520
+ TESTS_PROPERTY
1521
+ ];
1522
+ const scenario = {
1523
+ id: "scenario",
1524
+ label: "Scenario",
1525
+ description: "An acceptance example in Gherkin: given a starting situation, when something happens, then the outcome.",
1526
+ color: "#166534",
1527
+ fg: "#fff",
1528
+ // Play/run triangle in a rounded frame
1529
+ iconPath: "M3 2a1 1 0 0 0-1 1v10a1 1 0 0 0 1 1h10a1 1 0 0 0 1-1V3a1 1 0 0 0-1-1H3Zm3.5 2.5 5 3.5-5 3.5v-7Z",
1530
+ width: 200,
1531
+ height: 80,
1532
+ collapsedWidth: 180,
1533
+ collapsedHeight: 80,
1534
+ allowedParents: ["system", "domain", "group"],
1535
+ allowedAtRoot: true,
1536
+ builtin: true,
1537
+ properties: scenarioProps,
1538
+ wizard: {
1539
+ trigger: "create",
1540
+ steps: [
1541
+ {
1542
+ kind: "fields",
1543
+ title: "Name",
1544
+ fields: ["label"],
1545
+ help: 'Name the behaviour, e.g. "Card payment declined".'
1546
+ },
1547
+ {
1548
+ kind: "fields",
1549
+ title: "Given",
1550
+ fields: ["given"],
1551
+ help: "The starting state: who is involved and what is already true."
1552
+ },
1553
+ {
1554
+ kind: "fields",
1555
+ title: "When",
1556
+ fields: ["when"],
1557
+ help: "The single action or event under test."
1558
+ },
1559
+ {
1560
+ kind: "fields",
1561
+ title: "Then",
1562
+ fields: ["then", "gherkin"],
1563
+ help: "The observable outcome. Add And/But steps below if needed."
1564
+ },
1565
+ {
1566
+ kind: "relations",
1567
+ title: "Verified requirements",
1568
+ relationType: "verifies",
1569
+ direction: "out",
1570
+ help: "Which requirements does this scenario verify?"
1571
+ }
1572
+ ]
1573
+ }
1574
+ };
1575
+ const verifiesTargets = ["requirement"];
1576
+ const verifies = {
1577
+ id: "verifies",
1578
+ label: "Verifies",
1579
+ description: "The scenario is the acceptance test of the requirement or state machine.",
1580
+ inverseLabel: "Verified by",
1581
+ allowedPairs: verifiesTargets.map((to) => ({ from: "scenario", to })),
1582
+ properties: [],
1583
+ color: "#16a34a",
1584
+ builtin: true
1585
+ };
1586
+ const blueprintProps = [
1587
+ { key: "description", label: "Description", type: "textarea" },
1588
+ {
1589
+ key: "status",
1590
+ label: "Status",
1591
+ type: "enum",
1592
+ options: ["draft", "reviewed", "approved", "deprecated"],
1593
+ default: "draft"
1594
+ },
1595
+ { key: "domain", label: "Domain / Context", type: "text" },
1596
+ { key: "rationale", label: "Rationale", type: "textarea" }
1597
+ ];
1598
+ const blueprint = {
1599
+ id: "blueprint",
1600
+ label: "Blueprint",
1601
+ description: "A curated reference architecture imported from the Concept Hub.",
1602
+ color: "#1e3a5f",
1603
+ fg: "#fff",
1604
+ // Blueprint grid / technical drawing
1605
+ iconPath: "M2 2h12v12H2V2Zm1 1v2h2V3H3Zm3 0v2h2V3H6Zm3 0v2h2V3H9Zm3 0v2h1V3h-1ZM3 6v2h2V6H3Zm3 0v2h2V6H6Zm3 0v2h2V6H9Zm3 0v2h1V6h-1ZM3 9v2h2V9H3Zm3 0v2h2V9H6Zm3 0v2h2V9H9Zm3 0v2h1V9h-1ZM3 12v1h2v-1H3Zm3 0v1h2v-1H6Zm3 0v1h2v-1H9Zm3 0v1h1v-1h-1Z",
1606
+ width: 520,
1607
+ height: 360,
1608
+ collapsedWidth: 360,
1609
+ collapsedHeight: 220,
1610
+ allowedParents: ["domain", "group"],
1611
+ allowedAtRoot: true,
1612
+ builtin: true,
1613
+ hubOnly: true,
1614
+ properties: blueprintProps
1615
+ };
1616
+ const mockupProps = [
1617
+ { key: "description", label: "Description", type: "textarea" },
1618
+ { key: "screen", label: "Screen / route", type: "text" },
1619
+ { key: "link", label: "Design link", type: "text" }
1620
+ ];
1621
+ const mockup = {
1622
+ id: "mockup",
1623
+ label: "Mockup",
1624
+ description: "One screen of the product, optionally with a low-fi wireframe.",
1625
+ color: "#be185d",
1626
+ fg: "#fff",
1627
+ // Browser window with a header bar and content blocks
1628
+ iconPath: "M2 2.5A1.5 1.5 0 0 1 3.5 1h9A1.5 1.5 0 0 1 14 2.5v11a1.5 1.5 0 0 1-1.5 1.5h-9A1.5 1.5 0 0 1 2 13.5v-11ZM3 5v8.5c0 .28.22.5.5.5h9a.5.5 0 0 0 .5-.5V5H3Zm1 1.5h8v2H4v-2Zm0 3h3.5V13H4V9.5Zm4.5 0H12v1H8.5v-1Zm0 2H12v1H8.5v-1Z",
1629
+ width: 220,
1630
+ height: 190,
1631
+ collapsedWidth: 220,
1632
+ collapsedHeight: 190,
1633
+ allowedParents: ["system", "domain", "group"],
1634
+ allowedAtRoot: true,
1635
+ builtin: true,
1636
+ properties: mockupProps,
1637
+ wizard: {
1638
+ trigger: "create",
1639
+ steps: [
1640
+ {
1641
+ kind: "fields",
1642
+ title: "Screen",
1643
+ fields: ["label", "screen", "description"],
1644
+ help: "Which screen is this, and what does the user do on it?"
1645
+ },
1646
+ {
1647
+ kind: "fields",
1648
+ title: "Design link",
1649
+ fields: ["link"],
1650
+ help: "A Figma / Penpot link, if the design exists. You can generate a wireframe from the properties panel later."
1651
+ },
1652
+ {
1653
+ kind: "relations",
1654
+ title: "Illustrates",
1655
+ relationType: "illustrates",
1656
+ direction: "out",
1657
+ help: "Which requirements or scenarios does this screen show?"
1658
+ },
1659
+ {
1660
+ kind: "relations",
1661
+ title: "Presented by",
1662
+ relationType: "presented-by",
1663
+ direction: "out",
1664
+ help: "Which part of the system renders it?"
1665
+ }
1666
+ ]
1667
+ }
1668
+ };
1669
+ const illustrates = {
1670
+ id: "illustrates",
1671
+ label: "Illustrates",
1672
+ description: "The screen shows the requirement being met, the step of the scenario, or what the user sees in the state.",
1673
+ inverseLabel: "Illustrated by",
1674
+ allowedPairs: [
1675
+ { from: "mockup", to: "requirement" },
1676
+ { from: "mockup", to: "scenario" }
1677
+ ],
1678
+ properties: [],
1679
+ color: "#db2777",
1680
+ builtin: true
1681
+ };
1682
+ const presentedBy = {
1683
+ id: "presented-by",
1684
+ label: "Presented by",
1685
+ description: "The part of the architecture that renders the screen.",
1686
+ inverseLabel: "Presents",
1687
+ allowedPairs: ["webapp", "container", "component", "system"].map((to) => ({ from: "mockup", to })),
1688
+ properties: [],
1689
+ color: "#be185d",
1690
+ builtin: true
1691
+ };
1692
+ const navigatesTo = {
1693
+ id: "navigates-to",
1694
+ label: "Navigates to",
1695
+ description: "One step of a screen flow, with what triggers it.",
1696
+ inverseLabel: "Reached from",
1697
+ allowedPairs: [{ from: "mockup", to: "mockup" }],
1698
+ properties: [
1699
+ { key: "description", label: "Trigger", type: "text" }
1700
+ ],
1701
+ color: "#f472b6",
1702
+ builtin: true
1703
+ };
1704
+ const stateMachine = {
1705
+ id: "state-machine",
1706
+ label: "State Machine",
1707
+ description: "The lifecycle of one entity: the states it can be in and the transitions between them.",
1708
+ color: "#3730a3",
1709
+ fg: "#fff",
1710
+ // Two states joined by a transition
1711
+ iconPath: "M1 3.5A1.5 1.5 0 0 1 2.5 2h3A1.5 1.5 0 0 1 7 3.5v2A1.5 1.5 0 0 1 5.5 7h-3A1.5 1.5 0 0 1 1 5.5v-2Zm8 7A1.5 1.5 0 0 1 10.5 9h3a1.5 1.5 0 0 1 1.5 1.5v2a1.5 1.5 0 0 1-1.5 1.5h-3A1.5 1.5 0 0 1 9 12.5v-2ZM3.5 8h1v3h2.8v-1l2 1.5-2 1.5v-1H3.5V8Z",
1712
+ width: 560,
1713
+ height: 380,
1714
+ collapsedWidth: 200,
1715
+ collapsedHeight: 64,
1716
+ allowedParents: ["system", "domain", "group"],
1717
+ allowedAtRoot: true,
1718
+ builtin: true,
1719
+ properties: [
1720
+ { key: "description", label: "Description", type: "textarea" }
1721
+ ]
1722
+ };
1723
+ const state = {
1724
+ id: "state",
1725
+ label: "State",
1726
+ description: "A situation the entity can be in.",
1727
+ color: "#4f46e5",
1728
+ fg: "#fff",
1729
+ // Rounded rectangle
1730
+ iconPath: "M3.5 3h9A2.5 2.5 0 0 1 15 5.5v5a2.5 2.5 0 0 1-2.5 2.5h-9A2.5 2.5 0 0 1 1 10.5v-5A2.5 2.5 0 0 1 3.5 3Zm0 1.5a1 1 0 0 0-1 1v5a1 1 0 0 0 1 1h9a1 1 0 0 0 1-1v-5a1 1 0 0 0-1-1h-9Z",
1731
+ width: 320,
1732
+ height: 220,
1733
+ collapsedWidth: 170,
1734
+ collapsedHeight: 72,
1735
+ allowedParents: ["state-machine", "state"],
1736
+ allowedAtRoot: false,
1737
+ builtin: true,
1738
+ properties: [
1739
+ {
1740
+ key: "kind",
1741
+ label: "Kind",
1742
+ type: "enum",
1743
+ options: ["normal", "parallel", "final"],
1744
+ default: "normal"
1745
+ },
1746
+ { key: "entry", label: "Entry actions", type: "text", visibleWhen: { key: "kind", values: ["normal", "parallel"] } },
1747
+ { key: "exit", label: "Exit actions", type: "text", visibleWhen: { key: "kind", values: ["normal", "parallel"] } },
1748
+ { key: "do", label: "Do (ongoing activity)", type: "text", visibleWhen: { key: "kind", values: ["normal"] } },
1749
+ { key: "description", label: "Description", type: "textarea" }
1750
+ ]
1751
+ };
1752
+ const pseudostate = {
1753
+ id: "pseudostate",
1754
+ label: "Pseudostate",
1755
+ description: "A point a state machine passes through but never rests in: where it starts, a choice, a history.",
1756
+ color: "#1e1b4b",
1757
+ fg: "#fff",
1758
+ // Filled dot (initial)
1759
+ iconPath: "M8 4a4 4 0 1 1 0 8 4 4 0 0 1 0-8Z",
1760
+ width: 36,
1761
+ height: 36,
1762
+ allowedParents: ["state-machine", "state"],
1763
+ allowedAtRoot: false,
1764
+ builtin: true,
1765
+ properties: [
1766
+ {
1767
+ key: "kind",
1768
+ label: "Kind",
1769
+ type: "enum",
1770
+ options: ["initial", "shallow-history", "deep-history", "choice"],
1771
+ default: "initial"
1772
+ }
1773
+ ]
1774
+ };
1775
+ const event = {
1776
+ id: "event",
1777
+ label: "Event",
1778
+ description: "Something that happens and can trigger a transition.",
1779
+ color: "#c2410c",
1780
+ fg: "#fff",
1781
+ // Lightning bolt
1782
+ iconPath: "M9.5 1 3 9h4l-1 6 6.5-8h-4l1-6Z",
1783
+ width: 170,
1784
+ height: 52,
1785
+ allowedParents: ["state-machine", "system", "domain", "group"],
1786
+ allowedAtRoot: true,
1787
+ builtin: true,
1788
+ properties: [
1789
+ {
1790
+ key: "source",
1791
+ label: "Source",
1792
+ type: "enum",
1793
+ options: ["external", "internal", "timer"],
1794
+ default: "external"
1795
+ },
1796
+ { key: "payload", label: "Payload", type: "text" },
1797
+ { key: "description", label: "Description", type: "textarea" }
1798
+ ]
1799
+ };
1800
+ const stateNodeTypes = ["state", "pseudostate"];
1801
+ const transition = {
1802
+ id: "transition",
1803
+ label: "Transition",
1804
+ description: "The machine moves from one state to another: on an event, under a guard, running actions.",
1805
+ forwardLabel: "Transitions to",
1806
+ inverseLabel: "Entered from",
1807
+ allowedPairs: stateNodeTypes.flatMap((from) => stateNodeTypes.map((to) => ({ from, to }))),
1808
+ properties: [
1809
+ { key: "event", label: "Event (trigger; none = completion)", type: "ref", refType: "event" },
1810
+ { key: "guard", label: "Guard [condition]", type: "text" },
1811
+ { key: "actions", label: "Actions (/ effect)", type: "text" },
1812
+ { key: "raises", label: "Raises (events it publishes)", type: "ref", refType: "event", multiple: true },
1813
+ {
1814
+ key: "kind",
1815
+ label: "Kind",
1816
+ type: "enum",
1817
+ options: ["external", "internal"],
1818
+ default: "external"
1819
+ }
1820
+ ],
1821
+ color: "#6366f1",
1822
+ builtin: true
1823
+ };
1824
+ const lifecycleOf = {
1825
+ id: "lifecycle-of",
1826
+ label: "Lifecycle of",
1827
+ description: "The machine is the lifecycle of that entity.",
1828
+ inverseLabel: "Lifecycle modelled by",
1829
+ allowedPairs: [{ from: "state-machine", to: "entity" }],
1830
+ properties: [],
1831
+ color: "#3730a3",
1832
+ builtin: true
1833
+ };
1834
+ const emits = {
1835
+ id: "emits",
1836
+ label: "Emits",
1837
+ description: "The element raises the event.",
1838
+ inverseLabel: "Emitted by",
1839
+ allowedPairs: ["person", "system", "container", "component", "webapp", "queue", "state-machine", "state"].map((from) => ({ from, to: "event" })),
1840
+ properties: [
1841
+ {
1842
+ key: "on",
1843
+ label: "On (for a state: entry, exit or do)",
1844
+ type: "enum",
1845
+ options: ["entry", "exit", "do"],
1846
+ default: "entry"
1847
+ }
1848
+ ],
1849
+ color: "#ea580c",
1850
+ builtin: true
1851
+ };
1852
+ implements_.allowedPairs.push(...["system", "container", "component", "webapp"].map((from) => ({ from, to: "state-machine" })));
1853
+ satisfies.allowedPairs.push({ from: "state-machine", to: "requirement" }, { from: "entity", to: "requirement" });
1854
+ verifies.allowedPairs.push({ from: "scenario", to: "state-machine" });
1855
+ illustrates.allowedPairs.push({ from: "mockup", to: "state" });
1856
+ return {
1857
+ id: "c4-ddd-governance-builtin",
1858
+ name: RADICAL_METAMODEL_NAME,
1859
+ nodeTypes: {
1860
+ ...base.nodeTypes,
1861
+ adr,
1862
+ "fitness-fn": fitnessFn,
1863
+ need,
1864
+ requirement,
1865
+ scenario,
1866
+ blueprint,
1867
+ mockup,
1868
+ "state-machine": stateMachine,
1869
+ state,
1870
+ pseudostate,
1871
+ event
1872
+ },
1873
+ relationTypes: {
1874
+ ...base.relationTypes,
1875
+ constrains,
1876
+ supersedes,
1877
+ implements: implements_,
1878
+ satisfies,
1879
+ derives,
1880
+ "traces-to": tracesTo,
1881
+ verifies,
1882
+ illustrates,
1883
+ "presented-by": presentedBy,
1884
+ "navigates-to": navigatesTo,
1885
+ transition,
1886
+ "lifecycle-of": lifecycleOf,
1887
+ emits
1888
+ },
1889
+ viewpoints: radicalViewpoints()
1890
+ };
1891
+ }
1892
+
1893
+ // ../../packages/common/src/c4.ts
1894
+ var BUILTIN_NODE_TYPES = builtInGovernanceMetamodel().nodeTypes;
1895
+ function pluckPerType(fn) {
1896
+ const out = {};
1897
+ for (const [id, def] of Object.entries(BUILTIN_NODE_TYPES)) {
1898
+ out[id] = fn(def);
1899
+ }
1900
+ return out;
1901
+ }
1902
+ var NODE_SIZES = pluckPerType((def) => ({ width: def.width, height: def.height }));
1903
+ var COLLAPSED_HEIGHT = pluckPerType((def) => def.collapsedHeight ?? def.height);
1904
+ var COLLAPSED_WIDTH = pluckPerType((def) => def.collapsedWidth ?? def.width);
1905
+ var NODE_COLORS = pluckPerType((def) => def.color);
1906
+ var NODE_FG = pluckPerType((def) => def.fg);
1907
+ var TYPE_LABELS = pluckPerType((def) => def.label);
1908
+ var TYPE_ICON_PATHS = pluckPerType((def) => def.iconPath);
1909
+
1910
+ // ../../packages/common/src/formats/mdFolder.ts
1911
+ var MD_MANIFEST_FILE = "radical.md";
1912
+ var LAYOUT_FILE = "_layout.json";
1913
+ var RELATIONS_FILE = "relations.json";
1914
+ var VIEWS_FILE = "views.json";
1915
+ var SEQUENCES_FILE = "sequences.json";
1916
+ var SNAPSHOTS_FILE = "snapshots.json";
1917
+ var PRESENTATIONS_FILE = "presentations.json";
1918
+ var METAMODEL_FILE = "metamodel.json";
1919
+ var HUB_TEMPLATES_FILE = "hubTemplates.json";
1920
+ var NODES_DIR = "nodes";
1921
+ var INDEX_BASENAME = "_index.md";
1922
+ var SIDECAR_FILES = /* @__PURE__ */ new Set([
1923
+ LAYOUT_FILE,
1924
+ RELATIONS_FILE,
1925
+ VIEWS_FILE,
1926
+ SEQUENCES_FILE,
1927
+ SNAPSHOTS_FILE,
1928
+ PRESENTATIONS_FILE,
1929
+ METAMODEL_FILE,
1930
+ HUB_TEMPLATES_FILE
1931
+ ]);
1932
+ var NODE_LAYOUT_KEYS = /* @__PURE__ */ new Set(["x", "y", "width", "height", "collapsed"]);
1933
+ var NODE_NONFRONT_KEYS = /* @__PURE__ */ new Set([...NODE_LAYOUT_KEYS, "parentId", "description"]);
1934
+ function parseScalar(raw) {
1935
+ if (raw === "true") return true;
1936
+ if (raw === "false") return false;
1937
+ if (/^-?\d+(\.\d+)?$/.test(raw)) return Number(raw);
1938
+ if (raw.startsWith("[")) {
1939
+ try {
1940
+ const list = JSON.parse(raw);
1941
+ if (Array.isArray(list) && list.every((v) => typeof v === "string")) return list;
1942
+ } catch {
1943
+ }
1944
+ return raw;
1945
+ }
1946
+ if (raw.startsWith('"')) {
1947
+ try {
1948
+ return JSON.parse(raw);
1949
+ } catch {
1950
+ return raw;
1951
+ }
1952
+ }
1953
+ return raw;
1954
+ }
1955
+ function parseMarkdown(content) {
1956
+ const front = {};
1957
+ const normalized = content.replace(/\r\n/g, "\n");
1958
+ if (!normalized.startsWith("---\n")) {
1959
+ return { front, body: normalized.trim() };
1960
+ }
1961
+ const lines = normalized.split("\n");
1962
+ let i = 1;
1963
+ for (; i < lines.length; i++) {
1964
+ const line = lines[i];
1965
+ if (line === "---") {
1966
+ i++;
1967
+ break;
1968
+ }
1969
+ const match = /^([A-Za-z0-9_-]+|"(?:[^"\\]|\\.)*"):\s?(.*)$/.exec(line);
1970
+ if (!match) continue;
1971
+ let key = match[1];
1972
+ if (key.startsWith('"')) {
1973
+ try {
1974
+ key = JSON.parse(key);
1975
+ } catch {
1976
+ continue;
1977
+ }
1978
+ }
1979
+ const rest = match[2];
1980
+ if (rest === "|") {
1981
+ const blockLines = [];
1982
+ while (i + 1 < lines.length && (lines[i + 1].startsWith(" ") || lines[i + 1] === "")) {
1983
+ i++;
1984
+ if (lines[i] === "---") {
1985
+ i--;
1986
+ break;
1987
+ }
1988
+ blockLines.push(lines[i].startsWith(" ") ? lines[i].slice(2) : lines[i]);
1989
+ }
1990
+ if (blockLines.length && blockLines[blockLines.length - 1] === "") blockLines.pop();
1991
+ front[key] = blockLines.join("\n");
1992
+ } else {
1993
+ front[key] = parseScalar(rest);
1994
+ }
1995
+ }
1996
+ const body = lines.slice(i).join("\n").trim();
1997
+ return { front, body };
1998
+ }
1999
+ function deserializeFromMdFolder(files, opts) {
2000
+ const lazy = opts?.lazy ?? false;
2001
+ const layout = readJson(files, LAYOUT_FILE) ?? { nodes: {} };
2002
+ const storedMetamodel = readJson(files, METAMODEL_FILE);
2003
+ const typeSize = (type) => {
2004
+ const def = storedMetamodel?.nodeTypes?.[type];
2005
+ if (def?.width && def?.height) return { width: def.width, height: def.height };
2006
+ return NODE_SIZES[type] ?? { width: 200, height: 100 };
2007
+ };
2008
+ const parsedByDirKey = /* @__PURE__ */ new Map();
2009
+ const parsed = [];
2010
+ for (const [path, content] of Object.entries(files)) {
2011
+ if (!path.startsWith(NODES_DIR + "/") || !path.endsWith(".md")) continue;
2012
+ if (CONFLICT_MARKER.test(content)) throw new MalformedFolderFileError(path, "git conflict markers");
2013
+ const { front, body } = parseMarkdown(content);
2014
+ if (!front.id || !front.type) continue;
2015
+ const isIndex = path.endsWith("/" + INDEX_BASENAME);
2016
+ if (isIndex) {
2017
+ const ownDirKey = dirname(path);
2018
+ parsed.push({ path, front, body, ownDirKey, parentDirKey: dirname(ownDirKey) });
2019
+ parsedByDirKey.set(ownDirKey, String(front.id));
2020
+ } else {
2021
+ parsed.push({ path, front, body, ownDirKey: null, parentDirKey: dirname(path) });
2022
+ }
2023
+ }
2024
+ const bodyPaths = {};
2025
+ const nodes = parsed.map((p) => {
2026
+ const id = String(p.front.id);
2027
+ const parentId = p.parentDirKey === NODES_DIR ? void 0 : parsedByDirKey.get(p.parentDirKey);
2028
+ const size = typeSize(String(p.front.type));
2029
+ const lay = layout.nodes[id] ?? { x: 0, y: 0, width: size.width, height: size.height, collapsed: false };
2030
+ const node = {
2031
+ id,
2032
+ type: p.front.type,
2033
+ label: typeof p.front.label === "string" ? p.front.label : String(p.front.label ?? ""),
2034
+ x: lay.x,
2035
+ y: lay.y,
2036
+ width: lay.width,
2037
+ height: lay.height,
2038
+ collapsed: !!lay.collapsed
2039
+ };
2040
+ if (parentId) node.parentId = parentId;
2041
+ if (p.body) {
2042
+ if (lazy) bodyPaths[id] = p.path;
2043
+ else node.description = p.body;
2044
+ }
2045
+ for (const [key, value] of Object.entries(p.front)) {
2046
+ if (key === "id" || key === "type" || key === "label") continue;
2047
+ node[key] = value;
2048
+ }
2049
+ return node;
2050
+ });
2051
+ const relations = readJson(files, RELATIONS_FILE) ?? [];
2052
+ const data = { nodes, relations };
2053
+ const views = readJson(files, VIEWS_FILE);
2054
+ if (views) data.views = views;
2055
+ const sequences = readJson(files, SEQUENCES_FILE);
2056
+ if (sequences) data.sequences = sequences;
2057
+ const snapshots = readJson(files, SNAPSHOTS_FILE);
2058
+ if (snapshots) data.snapshots = snapshots;
2059
+ const presentations = readJson(files, PRESENTATIONS_FILE);
2060
+ if (presentations) data.presentations = presentations;
2061
+ if (storedMetamodel) data.metamodel = storedMetamodel;
2062
+ const hubTemplates = readJson(files, HUB_TEMPLATES_FILE);
2063
+ if (hubTemplates) data.hubTemplates = hubTemplates;
2064
+ if (layout.defaultPositions) data.defaultPositions = layout.defaultPositions;
2065
+ if (layout.defaultViewport !== void 0) data.defaultViewport = layout.defaultViewport;
2066
+ if (layout.defaultLayoutConstraints?.length) data.defaultLayoutConstraints = layout.defaultLayoutConstraints;
2067
+ if (layout.defaultEdgeStyle === "orthogonal") data.defaultEdgeStyle = layout.defaultEdgeStyle;
2068
+ return lazy ? { data, bodyPaths } : { data };
2069
+ }
2070
+ function isMdFolderModelPath(path) {
2071
+ if (path === MD_MANIFEST_FILE || SIDECAR_FILES.has(path)) return true;
2072
+ return path.startsWith(NODES_DIR + "/") && path.endsWith(".md");
2073
+ }
2074
+ function isOwnedMdFolderFile(path, content) {
2075
+ if (path === MD_MANIFEST_FILE || SIDECAR_FILES.has(path)) return true;
2076
+ if (!isMdFolderModelPath(path)) return false;
2077
+ const { front } = parseMarkdown(content);
2078
+ return !!front.id && !!front.type;
2079
+ }
2080
+ function isValidMdFolderManifest(content) {
2081
+ return content !== void 0 && /^radicalFormat:\s*["']?md-folder["']?\s*$/m.test(content) && /^version:\s*1\s*$/m.test(content);
2082
+ }
2083
+ var MD_FOLDER_JSON_FILES = [...SIDECAR_FILES];
2084
+ function mdFolderNodeFiles(files) {
2085
+ return Object.entries(files).filter(([path]) => path.startsWith(NODES_DIR + "/") && path.endsWith(".md")).map(([path, content]) => {
2086
+ const { front } = parseMarkdown(content);
2087
+ return {
2088
+ path,
2089
+ ...front.id ? { id: String(front.id) } : {},
2090
+ ...front.type ? { type: String(front.type) } : {},
2091
+ frontmatter: content.replace(/\r\n/g, "\n").startsWith("---\n"),
2092
+ conflict: CONFLICT_MARKER.test(content)
2093
+ };
2094
+ });
2095
+ }
2096
+ function staleMdFolderFiles(existing, next) {
2097
+ return Object.keys(existing).filter(
2098
+ (path) => !(path in next) && isOwnedMdFolderFile(path, existing[path])
2099
+ );
2100
+ }
2101
+ var MalformedFolderFileError = class extends Error {
2102
+ constructor(path, reason = "malformed JSON") {
2103
+ super(`${reason[0].toUpperCase()}${reason.slice(1)} in ${path}`);
2104
+ this.path = path;
2105
+ this.reason = reason;
2106
+ this.name = "MalformedFolderFileError";
2107
+ }
2108
+ };
2109
+ var CONFLICT_MARKER = /^(<{7}|>{7})( |$)|^={7}$/m;
2110
+ function readJson(files, path) {
2111
+ const content = files[path];
2112
+ if (content === void 0) return void 0;
2113
+ try {
2114
+ return JSON.parse(content);
2115
+ } catch {
2116
+ throw new MalformedFolderFileError(path);
2117
+ }
2118
+ }
2119
+ function dirname(path) {
2120
+ const idx = path.lastIndexOf("/");
2121
+ return idx === -1 ? "" : path.slice(0, idx);
2122
+ }
2123
+
2124
+ // ../../packages/common/src/viewPipeline.ts
2125
+ var collator = new Intl.Collator(void 0, { numeric: true, sensitivity: "base" });
2126
+
2127
+ // ../../packages/common/src/model.ts
2128
+ function documentMetamodel(stored, nodes) {
2129
+ if (!stored) {
2130
+ const c4 = builtInC4Metamodel();
2131
+ return nodes?.some((n) => !c4.nodeTypes[n.type]) ? builtInGovernanceMetamodel() : c4;
2132
+ }
2133
+ const preset = stored.id === "c4-builtin" ? builtInC4Metamodel() : stored.id === "c4-ddd-builtin" || stored.id === "c4-ddd-governance-builtin" ? builtInGovernanceMetamodel() : null;
2134
+ if (!preset) return stored;
2135
+ return withPresetViewpoints(preset, stored);
2136
+ }
2137
+ function withPresetViewpoints(preset, stored) {
2138
+ const own = Array.isArray(stored.viewpoints) ? stored.viewpoints : [];
2139
+ const removed = new Set(Array.isArray(stored.removedViewpoints) ? stored.removedViewpoints : []);
2140
+ if (!own.length && !removed.size) return preset;
2141
+ const byId3 = new Map(own.map((v) => [v.id, v]));
2142
+ const fromPreset = (preset.viewpoints ?? []).filter((v) => !removed.has(v.id)).map((v) => byId3.get(v.id) ?? v);
2143
+ const presetIds = new Set((preset.viewpoints ?? []).map((v) => v.id));
2144
+ const viewpoints = [...fromPreset, ...own.filter((v) => !presetIds.has(v.id))];
2145
+ return { ...preset, viewpoints, ...removed.size ? { removedViewpoints: [...removed] } : {} };
2146
+ }
2147
+ var LAYOUT_KEYS = /* @__PURE__ */ new Set(["id", "x", "y", "width", "height", "collapsed"]);
2148
+ var sameValue = (a, b) => JSON.stringify(a ?? null) === JSON.stringify(b ?? null);
2149
+ function changedFields(before, after) {
2150
+ const a = before;
2151
+ const b = after;
2152
+ const keys = /* @__PURE__ */ new Set([...Object.keys(a), ...Object.keys(b)]);
2153
+ return [...keys].filter((key) => !LAYOUT_KEYS.has(key) && !sameValue(a[key], b[key])).sort();
2154
+ }
2155
+ function compareModels(before, after) {
2156
+ const diff = (from, to) => ({
2157
+ added: Object.keys(to).filter((id) => !(id in from)),
2158
+ removed: Object.keys(from).filter((id) => !(id in to)),
2159
+ changed: Object.keys(to).filter((id) => id in from && from[id] !== to[id]).map((id) => ({ id, fields: changedFields(from[id], to[id]) })).filter((change) => change.fields.length > 0)
2160
+ });
2161
+ return { nodes: diff(before.nodes, after.nodes), relations: diff(before.relations, after.relations) };
2162
+ }
2163
+
2164
+ // ../../packages/common/src/check/reports.ts
2165
+ var SEPARATOR = /\s+›\s+/;
2166
+ var JUNIT_SEPARATOR = /\s+[›>]\s+/;
2167
+ var normalize = (path) => path.replace(/\\/g, "/").replace(/^\.\//, "");
2168
+ function parseTestReport(content, name) {
2169
+ const text = content.trim();
2170
+ if (text.startsWith("<")) return parseJUnit(text);
2171
+ let json;
2172
+ try {
2173
+ json = JSON.parse(text);
2174
+ } catch {
2175
+ throw new Error(`${name} is neither JSON nor JUnit XML`);
2176
+ }
2177
+ const report = json;
2178
+ if (Array.isArray(report.testResults)) return parseJestJson(report);
2179
+ if (Array.isArray(report.suites)) return parsePlaywrightJson(report);
2180
+ throw new Error(`${name} is no Vitest, Jest or Playwright JSON report`);
2181
+ }
2182
+ function parseJestJson(report) {
2183
+ const cases = [];
2184
+ for (const file of report.testResults) {
2185
+ for (const a of file.assertionResults ?? []) {
2186
+ cases.push({
2187
+ file: normalize(file.name),
2188
+ title: [...a.ancestorTitles ?? [], a.title],
2189
+ status: a.status === "passed" ? "passed" : a.status === "failed" ? "failed" : "skipped"
2190
+ });
2191
+ }
2192
+ }
2193
+ return cases;
2194
+ }
2195
+ function parsePlaywrightJson(report) {
2196
+ const config = report.config;
2197
+ const root = config?.rootDir ? normalize(config.rootDir).replace(/\/$/, "") : "";
2198
+ const cases = [];
2199
+ const walk = (suite, titles, file) => {
2200
+ for (const spec of suite.specs ?? []) {
2201
+ const statuses = (spec.tests ?? []).map((t) => t.status);
2202
+ cases.push({
2203
+ file: root ? `${root}/${normalize(spec.file ?? file)}` : normalize(spec.file ?? file),
2204
+ title: [...titles, spec.title],
2205
+ // One test per project (browser); a spec fails when any of them did.
2206
+ status: statuses.includes("unexpected") ? "failed" : statuses.length && statuses.every((s) => s === "skipped") ? "skipped" : "passed"
2207
+ });
2208
+ }
2209
+ for (const child of suite.suites ?? []) walk(child, [...titles, child.title], file);
2210
+ };
2211
+ for (const top of report.suites) walk(top, [], top.file ?? top.title);
2212
+ return cases;
2213
+ }
2214
+ var XML_ENTITIES = { amp: "&", lt: "<", gt: ">", quot: '"', apos: "'" };
2215
+ var unescapeXml = (s) => s.replace(/&(#x[0-9a-f]+|#\d+|\w+);/gi, (m, e) => e[0] === "#" ? String.fromCodePoint(e[1].toLowerCase() === "x" ? parseInt(e.slice(2), 16) : parseInt(e.slice(1), 10)) : XML_ENTITIES[e] ?? m);
2216
+ var attributes = (tag) => Object.fromEntries([...tag.matchAll(/([\w:-]+)\s*=\s*("([^"]*)"|'([^']*)')/g)].map((m) => [m[1], unescapeXml(m[3] ?? m[4])]));
2217
+ function parseJUnit(xml) {
2218
+ const cases = [];
2219
+ for (const m of xml.matchAll(/<testcase\b([^>]*?)(\/>|>([\s\S]*?)<\/testcase>)/g)) {
2220
+ const attrs = attributes(m[1]);
2221
+ const body = m[3] ?? "";
2222
+ const file = attrs.file ?? attrs.classname ?? "";
2223
+ const title = (attrs.name ?? "").split(JUNIT_SEPARATOR);
2224
+ cases.push({
2225
+ file: normalize(file),
2226
+ title,
2227
+ status: /<(failure|error)\b/.test(body) ? "failed" : /<skipped\b/.test(body) ? "skipped" : "passed"
2228
+ });
2229
+ }
2230
+ return cases;
2231
+ }
2232
+ function parseTestIds(text) {
2233
+ if (typeof text !== "string") return [];
2234
+ return text.split("\n").map((line) => line.trim()).filter((line) => line && !line.startsWith("#")).map((raw) => {
2235
+ const [file, ...title] = raw.split(SEPARATOR);
2236
+ return { raw, file: normalize(file), title };
2237
+ });
2238
+ }
2239
+ var fileMatches = (reportFile, idFile) => reportFile === idFile || reportFile.endsWith("/" + idFile) || idFile.endsWith("/" + reportFile);
2240
+ function findTests(id, cases) {
2241
+ const n = id.title.length;
2242
+ if (!n) {
2243
+ const under = cases.filter((c) => fileMatches(c.file, id.file) || c.file.includes(`/${id.file.replace(/\/$/, "")}/`) || c.file.startsWith(`${id.file.replace(/\/$/, "")}/`));
2244
+ return { fileSeen: under.length > 0, matches: under };
2245
+ }
2246
+ const inFile = cases.filter((c) => fileMatches(c.file, id.file));
2247
+ const key = id.title.join(" \u203A ");
2248
+ const tail = inFile.filter((c) => c.title.length >= n && c.title.slice(-n).join(" \u203A ") === key);
2249
+ const matches = tail.length ? tail : inFile.filter((c) => c.title.length > n && c.title.slice(0, n).join(" \u203A ") === key);
2250
+ return { fileSeen: inFile.length > 0, matches };
2251
+ }
2252
+ var outcomeOf = (matches) => matches.some((c) => c.status === "failed") ? "failed" : matches.some((c) => c.status === "passed") ? "passed" : "skipped";
2253
+ var globCache = /* @__PURE__ */ new Map();
2254
+ function globMatch(glob, file) {
2255
+ let re = globCache.get(glob);
2256
+ if (!re) {
2257
+ const pattern = normalize(glob).replace(/\/+$/, (slash) => slash ? "/**" : "");
2258
+ const body = pattern.split(/(\*\*\/?|\*|\?)/).map((part) => part === "**/" ? "(?:[^/]+/)*" : part === "**" ? ".*" : part === "*" ? "[^/]*" : part === "?" ? "[^/]" : part.replace(/[.+^${}()|[\]\\]/g, "\\$&")).join("");
2259
+ re = new RegExp(`(?:^|/)(${body})$`);
2260
+ globCache.set(glob, re);
2261
+ }
2262
+ const m = re.exec(normalize(file));
2263
+ if (!m) return null;
2264
+ return glob.startsWith("**") ? normalize(file) : m[1];
2265
+ }
2266
+
2267
+ // ../../packages/common/src/check/evidence.ts
2268
+ var TESTED_TYPES = ["scenario", "fitness-fn"];
2269
+ var testIdsOf = (node) => parseTestIds(node.tests);
2270
+ function testOutcomes(node, model) {
2271
+ const cases = model.tests ?? [];
2272
+ return testIdsOf(node).map((id) => {
2273
+ const { fileSeen, matches } = findTests(id, cases);
2274
+ return { id, outcome: matches.length ? outcomeOf(matches) : fileSeen ? "not-found" : "not-run" };
2275
+ });
2276
+ }
2277
+ function checkedStatus(outcomes) {
2278
+ if (!outcomes.length) return "no-tests";
2279
+ if (outcomes.some((o) => o.outcome === "failed" || o.outcome === "not-found")) return "failed";
2280
+ if (outcomes.every((o) => o.outcome === "passed")) return "passed";
2281
+ return "not-run";
2282
+ }
2283
+ function linkedNodes(model, id, relationType, end, type) {
2284
+ return Object.values(model.relations).filter((r) => r.relationType === relationType && (end === "source" ? r.targetId : r.sourceId) === id).map((r) => model.nodes[end === "source" ? r.sourceId : r.targetId]).filter((n) => !!n && (!type || n.type === type));
2285
+ }
2286
+ function computeEvidence(model) {
2287
+ const nodes = {};
2288
+ for (const node of Object.values(model.nodes)) {
2289
+ if (!TESTED_TYPES.includes(node.type)) continue;
2290
+ const outcomes = testOutcomes(node, model);
2291
+ nodes[node.id] = {
2292
+ type: node.type,
2293
+ label: node.label,
2294
+ status: checkedStatus(outcomes),
2295
+ tests: outcomes.map((o) => ({ id: o.id.raw, outcome: o.outcome }))
2296
+ };
2297
+ }
2298
+ const verified = (node, checkers) => {
2299
+ const statuses = checkers.map((c) => nodes[c.id]?.status);
2300
+ nodes[node.id] = {
2301
+ type: node.type,
2302
+ label: node.label,
2303
+ status: statuses.includes("failed") ? "broken" : statuses.length && statuses.every((s) => s === "passed") ? "verified" : "unverified",
2304
+ by: checkers.map((c) => c.id)
2305
+ };
2306
+ };
2307
+ for (const node of Object.values(model.nodes)) {
2308
+ if (node.type === "requirement") verified(node, linkedNodes(model, node.id, "verifies", "source", "scenario"));
2309
+ else if (node.type === "adr") verified(node, linkedNodes(model, node.id, "implements", "source", "fitness-fn"));
2310
+ }
2311
+ return { version: 1, testCases: model.tests?.length ?? 0, nodes };
2312
+ }
2313
+
2314
+ // ../../packages/common/src/check/rules.ts
2315
+ var prop2 = (node, key) => {
2316
+ const value = node[key];
2317
+ return typeof value === "string" ? value.trim() : value == null ? "" : String(value);
2318
+ };
2319
+ function linked(model, type, end) {
2320
+ const map = /* @__PURE__ */ new Map();
2321
+ for (const r of Object.values(model.relations)) {
2322
+ if (r.relationType !== type) continue;
2323
+ const id = end === "in" ? r.targetId : r.sourceId;
2324
+ map.set(id, [...map.get(id) ?? [], r]);
2325
+ }
2326
+ return map;
2327
+ }
2328
+ var nodesOf = (model, type) => model.metamodel.nodeTypes[type] ? Object.values(model.nodes).filter((n) => n.type === type) : [];
2329
+ var hasRelationType = (model, type) => !!model.metamodel.relationTypes[type];
2330
+ function unlinked(model, type, relation, end, otherTypes) {
2331
+ if (!hasRelationType(model, relation)) return [];
2332
+ const map = linked(model, relation, end);
2333
+ return nodesOf(model, type).filter((n) => !(map.get(n.id) ?? []).some((r) => {
2334
+ const other = model.nodes[end === "in" ? r.sourceId : r.targetId];
2335
+ return other && (!otherTypes || otherTypes.includes(other.type));
2336
+ }));
2337
+ }
2338
+ var quote = (n) => `"${n.label}"`;
2339
+ var TYPE_NAME = { scenario: "Scenario", "fitness-fn": "Fitness function" };
2340
+ var affectedBy = (model, node) => node.type === "scenario" ? linkedNodes(model, node.id, "verifies", "target", "requirement") : linkedNodes(model, node.id, "implements", "target", "adr");
2341
+ function brokenWith(model, node) {
2342
+ const affected = affectedBy(model, node);
2343
+ if (!affected.length) return "";
2344
+ const what = node.type === "scenario" ? "requirement" : "ADR";
2345
+ return ` Not verified now: ${what}${affected.length === 1 ? "" : "s"} ${affected.map(quote).join(", ")}.`;
2346
+ }
2347
+ function testRule(outcome, message) {
2348
+ const failing = outcome === "failed" || outcome === "not-found";
2349
+ return (model) => {
2350
+ if (!model.tests) return [];
2351
+ return Object.values(model.nodes).filter((n) => TESTED_TYPES.includes(n.type)).flatMap((node) => testOutcomes(node, model).filter((o) => o.outcome === outcome).map((o) => {
2352
+ const related = failing ? affectedBy(model, node).map((n) => n.id) : [];
2353
+ return { nodeId: node.id, message: message(node, o.id.raw, model), ...related.length ? { relatedIds: related } : {} };
2354
+ }));
2355
+ };
2356
+ }
2357
+ var CHECK_RULES = [
2358
+ {
2359
+ id: "metamodel",
2360
+ description: 'The model follows its metamodel: types, parents, relation pairs, required properties, references and the state machine rules. The Validation list in Studio and get_issues over MCP, with their severities: an unknown type or a relation to no element is an error, a relation pair the metamodel does not allow a warning (`"metamodel": "error"` makes every issue one).',
2361
+ severity: "error",
2362
+ dimension: "consistency",
2363
+ run: (model) => validateModel(model.nodes, model.relations, model.metamodel).map((issue) => ({
2364
+ message: issue.message,
2365
+ code: issue.id.split(":")[0],
2366
+ severity: issue.severity,
2367
+ ...issue.nodeId ? { nodeId: issue.nodeId } : {},
2368
+ ...issue.relationId ? { relationId: issue.relationId } : {}
2369
+ }))
2370
+ },
2371
+ {
2372
+ id: "requirement-incomplete",
2373
+ description: "A requirement has an action and every field its EARS type reads (an event-driven one a trigger, a state-driven one a precondition, \u2026).",
2374
+ severity: "warning",
2375
+ dimension: "completeness",
2376
+ run: (model) => nodesOf(model, "requirement").filter((n) => !composeEarsSentence(n, void 0, requirementStatePhrase(n, model.nodes, model.relations)).complete).map((n) => ({ nodeId: n.id, message: `Requirement ${quote(n)} (${prop2(n, "ears_type") || "ubiquitous"}) misses the action or a field its EARS type needs.` }))
2377
+ },
2378
+ {
2379
+ id: "requirement-without-scenario",
2380
+ description: "Every requirement is verified by at least one scenario.",
2381
+ severity: "warning",
2382
+ dimension: "traceability",
2383
+ run: (model) => model.metamodel.nodeTypes.scenario ? unlinked(model, "requirement", "verifies", "in", ["scenario"]).map((n) => ({ nodeId: n.id, message: `No scenario verifies requirement ${quote(n)}.` })) : []
2384
+ },
2385
+ {
2386
+ id: "requirement-unsatisfied",
2387
+ description: "Every requirement is satisfied by an element of the architecture.",
2388
+ severity: "warning",
2389
+ dimension: "traceability",
2390
+ run: (model) => unlinked(model, "requirement", "satisfies", "in").map((n) => ({ nodeId: n.id, message: `Nothing satisfies requirement ${quote(n)}.` }))
2391
+ },
2392
+ {
2393
+ id: "requirement-without-origin",
2394
+ description: "Every requirement derives from a need or from another requirement.",
2395
+ severity: "warning",
2396
+ dimension: "traceability",
2397
+ run: (model) => unlinked(model, "requirement", "derives", "out", ["need", "requirement"]).map((n) => ({ nodeId: n.id, message: `Requirement ${quote(n)} derives from no need and no other requirement.` }))
2398
+ },
2399
+ {
2400
+ id: "need-without-requirement",
2401
+ description: "Every need has at least one requirement derived from it.",
2402
+ severity: "warning",
2403
+ dimension: "traceability",
2404
+ run: (model) => unlinked(model, "need", "derives", "in", ["requirement"]).map((n) => ({ nodeId: n.id, message: `No requirement derives from need ${quote(n)}.` }))
2405
+ },
2406
+ {
2407
+ id: "scenario-verifies-nothing",
2408
+ description: "Every scenario verifies a requirement or a state machine.",
2409
+ severity: "warning",
2410
+ dimension: "traceability",
2411
+ run: (model) => unlinked(model, "scenario", "verifies", "out").map((n) => ({ nodeId: n.id, message: `Scenario ${quote(n)} verifies no requirement and no state machine.` }))
2412
+ },
2413
+ {
2414
+ id: "adr-without-fitness-fn",
2415
+ description: "Every accepted ADR is implemented by a fitness function that checks it.",
2416
+ severity: "warning",
2417
+ dimension: "decisions",
2418
+ run: (model) => model.metamodel.nodeTypes["fitness-fn"] ? unlinked(model, "adr", "implements", "in", ["fitness-fn"]).filter((n) => prop2(n, "status") === "accepted").map((n) => ({ nodeId: n.id, message: `No fitness function implements accepted ADR ${quote(n)}.` })) : []
2419
+ },
2420
+ {
2421
+ id: "adr-incomplete",
2422
+ description: "An accepted ADR records its date, context, decision and consequences.",
2423
+ severity: "warning",
2424
+ dimension: "completeness",
2425
+ run: (model) => nodesOf(model, "adr").filter((n) => prop2(n, "status") === "accepted").flatMap((n) => {
2426
+ const missing = ["date", "context", "decision", "consequences"].filter((key) => !prop2(n, key));
2427
+ return missing.length ? [{ nodeId: n.id, message: `Accepted ADR ${quote(n)} has no ${missing.join(", ")}.` }] : [];
2428
+ })
2429
+ },
2430
+ {
2431
+ id: "adr-superseded-unlinked",
2432
+ description: "An ADR is superseded exactly when a newer ADR supersedes it.",
2433
+ severity: "warning",
2434
+ dimension: "consistency",
2435
+ run: (model) => {
2436
+ if (!hasRelationType(model, "supersedes")) return [];
2437
+ const by = linked(model, "supersedes", "in");
2438
+ return nodesOf(model, "adr").flatMap((n) => {
2439
+ const superseded = prop2(n, "status") === "superseded";
2440
+ const hasSuccessor = (by.get(n.id) ?? []).length > 0;
2441
+ if (superseded && !hasSuccessor) return [{ nodeId: n.id, message: `ADR ${quote(n)} is superseded, but no ADR supersedes it.` }];
2442
+ if (!superseded && hasSuccessor) return [{ nodeId: n.id, message: `ADR ${quote(n)} is superseded by another ADR, but its status is ${prop2(n, "status") || "not set"}.` }];
2443
+ return [];
2444
+ });
2445
+ }
2446
+ },
2447
+ {
2448
+ id: "fitness-fn-unlinked",
2449
+ description: "Every fitness function implements an ADR or constrains an element.",
2450
+ severity: "warning",
2451
+ dimension: "decisions",
2452
+ run: (model) => {
2453
+ const out = [...linked(model, "implements", "out").keys(), ...linked(model, "constrains", "out").keys()];
2454
+ const linkedIds = new Set(out);
2455
+ return nodesOf(model, "fitness-fn").filter((n) => !linkedIds.has(n.id)).map((n) => ({ nodeId: n.id, message: `Fitness function ${quote(n)} implements no ADR and constrains no element.` }));
2456
+ }
2457
+ },
2458
+ {
2459
+ id: "fitness-fn-without-threshold",
2460
+ description: "Every fitness function states its threshold or success criteria.",
2461
+ severity: "warning",
2462
+ dimension: "completeness",
2463
+ run: (model) => nodesOf(model, "fitness-fn").filter((n) => !prop2(n, "threshold")).map((n) => ({ nodeId: n.id, message: `Fitness function ${quote(n)} states no threshold.` }))
2464
+ },
2465
+ {
2466
+ id: "scenario-without-tests",
2467
+ description: "Every scenario names the automated tests that run it (property `tests`, one `file \u203A title` per line).",
2468
+ severity: "warning",
2469
+ dimension: "traceability",
2470
+ run: (model) => nodesOf(model, "scenario").filter((n) => !testIdsOf(n).length).map((n) => ({ nodeId: n.id, message: `Scenario ${quote(n)} names no test.` }))
2471
+ },
2472
+ {
2473
+ id: "fitness-fn-without-tests",
2474
+ description: "Every fitness function names the automated checks that run it (property `tests`).",
2475
+ severity: "warning",
2476
+ dimension: "decisions",
2477
+ run: (model) => nodesOf(model, "fitness-fn").filter((n) => !testIdsOf(n).length).map((n) => ({ nodeId: n.id, message: `Fitness function ${quote(n)} names no test.` }))
2478
+ },
2479
+ {
2480
+ id: "test-failed",
2481
+ description: "With --report: every test a scenario or fitness function names passed.",
2482
+ severity: "error",
2483
+ dimension: "tests",
2484
+ run: testRule("failed", (node, id, model) => `${TYPE_NAME[node.type]} ${quote(node)}: test ${id} failed.${brokenWith(model, node)}`)
2485
+ },
2486
+ {
2487
+ id: "test-not-found",
2488
+ description: "With --report: every test a scenario or fitness function names is in the report of its file (a renamed or deleted test is not).",
2489
+ severity: "error",
2490
+ dimension: "tests",
2491
+ run: testRule("not-found", (node, id, model) => `${TYPE_NAME[node.type]} ${quote(node)}: no test ${id} in the reports, though its file ran; renamed or deleted?${brokenWith(model, node)}`)
2492
+ },
2493
+ {
2494
+ id: "test-skipped",
2495
+ description: "With --report: no test a scenario or fitness function names was skipped.",
2496
+ severity: "warning",
2497
+ dimension: "tests",
2498
+ run: testRule("skipped", (node, id) => `${TYPE_NAME[node.type]} ${quote(node)}: test ${id} was skipped.`)
2499
+ },
2500
+ {
2501
+ id: "test-not-run",
2502
+ description: "With --report: every file a scenario or fitness function names a test in is in the reports.",
2503
+ severity: "warning",
2504
+ dimension: "tests",
2505
+ run: testRule("not-run", (node, id) => `${TYPE_NAME[node.type]} ${quote(node)}: no report has the file of test ${id}.`)
2506
+ },
2507
+ {
2508
+ id: "test-unbound",
2509
+ description: "With --report and an include in check.json: every test in the files it includes is named by a scenario or a fitness function, by its title or its describe block (a whole file or directory does not count). One finding per test file.",
2510
+ severity: "warning",
2511
+ dimension: "tests",
2512
+ run: unboundTests
2513
+ }
2514
+ ];
2515
+ function unboundTests(model) {
2516
+ return [...testBinding(model) ?? []].filter(([, e]) => e.unbound.length).sort(([a], [b]) => a.localeCompare(b)).map(([file, e]) => ({
2517
+ testFile: file,
2518
+ message: `${file}: ${e.unbound.length} of ${e.total} test${e.total === 1 ? "" : "s"} named by no scenario or fitness function.`,
2519
+ details: e.unbound
2520
+ }));
2521
+ }
2522
+ function testBinding(model) {
2523
+ const setting = model.settings?.["test-unbound"];
2524
+ if (!model.tests || typeof setting !== "object" || !setting.include?.length) return null;
2525
+ const include = setting.include;
2526
+ const exclude = setting.exclude ?? [];
2527
+ const bound = /* @__PURE__ */ new Set();
2528
+ for (const node of Object.values(model.nodes)) {
2529
+ if (!TESTED_TYPES.includes(node.type)) continue;
2530
+ for (const id of testIdsOf(node)) if (id.title.length) findTests(id, model.tests).matches.forEach((c) => bound.add(c));
2531
+ }
2532
+ const byFile = /* @__PURE__ */ new Map();
2533
+ for (const c of model.tests) {
2534
+ const file = include.map((g) => globMatch(g, c.file)).find((m) => m !== null);
2535
+ if (file === void 0 || exclude.some((g) => globMatch(g, c.file) !== null)) continue;
2536
+ const entry = byFile.get(file) ?? { total: 0, unbound: [] };
2537
+ entry.total++;
2538
+ if (!bound.has(c)) entry.unbound.push(c.title.join(" \u203A "));
2539
+ byFile.set(file, entry);
2540
+ }
2541
+ return byFile;
2542
+ }
2543
+
2544
+ // ../../packages/common/src/check/goals.ts
2545
+ var GOAL_RULE = {
2546
+ id: "goal-unmet",
2547
+ description: 'Every metric check.json sets a goal for ("goals": { "<metric>": { "min": <percent> } }) reaches it. One finding per goal, with the metric as its code.',
2548
+ severity: "error"
2549
+ };
2550
+ var without = (rule) => (population) => (ctx) => {
2551
+ if (!population.length) return null;
2552
+ const missing = new Set(ctx.found.filter((f) => f.rule === rule && f.nodeId).map((f) => f.nodeId));
2553
+ return { count: population.filter((n) => !missing.has(n.id)).length, total: population.length };
2554
+ };
2555
+ var withStatus = (population, statuses, ctx) => {
2556
+ if (!ctx.evidence || !population.length) return null;
2557
+ return { count: population.filter((n) => statuses.includes(ctx.evidence.nodes[n.id]?.status ?? "")).length, total: population.length };
2558
+ };
2559
+ var acceptedAdrs = (model) => nodesOf(model, "adr").filter((n) => prop2(n, "status") === "accepted");
2560
+ var hasType = (model, type) => !!model.metamodel.nodeTypes[type];
2561
+ var byRule = (id, label, description, dimension, rule, population) => ({
2562
+ id,
2563
+ label,
2564
+ description,
2565
+ dimension,
2566
+ rule,
2567
+ measure: (ctx) => {
2568
+ const nodes = population(ctx.model);
2569
+ return nodes ? without(rule)(nodes)(ctx) : null;
2570
+ }
2571
+ });
2572
+ var CHECK_METRICS = [
2573
+ byRule("elements-valid", "Elements the metamodel allows", "Elements no metamodel issue points at.", "consistency", "metamodel", (m) => Object.values(m.nodes)),
2574
+ byRule("requirements-complete", "Complete requirements", "Requirements with an action and every field their EARS type reads.", "completeness", "requirement-incomplete", (m) => nodesOf(m, "requirement")),
2575
+ byRule("adrs-complete", "Complete accepted ADRs", "Accepted ADRs with a date, context, decision and consequences.", "completeness", "adr-incomplete", acceptedAdrs),
2576
+ byRule("fitness-fns-with-threshold", "Fitness functions with a threshold", "Fitness functions that state their threshold or success criteria.", "completeness", "fitness-fn-without-threshold", (m) => nodesOf(m, "fitness-fn")),
2577
+ byRule("needs-with-requirement", "Needs with a requirement", "Needs at least one requirement derives from.", "traceability", "need-without-requirement", (m) => nodesOf(m, "need")),
2578
+ byRule("requirements-with-origin", "Requirements with an origin", "Requirements that derive from a need or another requirement.", "traceability", "requirement-without-origin", (m) => nodesOf(m, "requirement")),
2579
+ byRule("requirements-satisfied", "Requirements satisfied", "Requirements an element of the architecture satisfies.", "traceability", "requirement-unsatisfied", (m) => nodesOf(m, "requirement")),
2580
+ byRule("requirements-with-scenario", "Requirements with a scenario", "Requirements at least one scenario verifies.", "traceability", "requirement-without-scenario", (m) => hasType(m, "scenario") ? nodesOf(m, "requirement") : null),
2581
+ byRule("scenarios-verifying", "Scenarios that verify something", "Scenarios that verify a requirement or a state machine.", "traceability", "scenario-verifies-nothing", (m) => nodesOf(m, "scenario")),
2582
+ byRule("scenarios-with-tests", "Scenarios that name a test", "Scenarios whose Tests property names the tests that run them.", "traceability", "scenario-without-tests", (m) => nodesOf(m, "scenario")),
2583
+ byRule("adrs-with-fitness-fn", "Accepted ADRs with a fitness function", "Accepted ADRs a fitness function implements.", "decisions", "adr-without-fitness-fn", (m) => hasType(m, "fitness-fn") ? acceptedAdrs(m) : null),
2584
+ byRule("fitness-fns-linked", "Fitness functions linked", "Fitness functions that implement an ADR or constrain an element.", "decisions", "fitness-fn-unlinked", (m) => nodesOf(m, "fitness-fn")),
2585
+ byRule("fitness-fns-with-tests", "Fitness functions that name a test", "Fitness functions whose Tests property names the checks that run them.", "decisions", "fitness-fn-without-tests", (m) => nodesOf(m, "fitness-fn")),
2586
+ {
2587
+ id: "requirements-verified",
2588
+ label: "Requirements verified",
2589
+ dimension: "behaviour",
2590
+ tests: true,
2591
+ description: "Requirements whose scenarios all name tests that passed.",
2592
+ measure: (ctx) => withStatus(nodesOf(ctx.model, "requirement"), ["verified"], ctx)
2593
+ },
2594
+ {
2595
+ id: "scenarios-passing",
2596
+ label: "Scenarios passing",
2597
+ dimension: "behaviour",
2598
+ tests: true,
2599
+ description: "Scenarios whose tests all passed.",
2600
+ measure: (ctx) => withStatus(nodesOf(ctx.model, "scenario"), ["passed"], ctx)
2601
+ },
2602
+ {
2603
+ id: "adrs-verified",
2604
+ label: "Accepted ADRs verified",
2605
+ dimension: "fitness",
2606
+ tests: true,
2607
+ description: "Accepted ADRs whose fitness functions all name checks that passed.",
2608
+ measure: (ctx) => withStatus(acceptedAdrs(ctx.model), ["verified"], ctx)
2609
+ },
2610
+ {
2611
+ id: "fitness-fns-passing",
2612
+ label: "Fitness functions passing",
2613
+ dimension: "fitness",
2614
+ tests: true,
2615
+ description: "Fitness functions whose checks all passed.",
2616
+ measure: (ctx) => withStatus(nodesOf(ctx.model, "fitness-fn"), ["passed"], ctx)
2617
+ },
2618
+ {
2619
+ id: "named-tests-passing",
2620
+ label: "Named tests passing",
2621
+ dimension: "tests",
2622
+ tests: true,
2623
+ description: "The tests scenarios and fitness functions name that passed.",
2624
+ measure: (ctx) => {
2625
+ if (!ctx.evidence) return null;
2626
+ const outcomes = Object.values(ctx.evidence.nodes).flatMap((e) => e.tests ?? []);
2627
+ return outcomes.length ? { count: outcomes.filter((t) => t.outcome === "passed").length, total: outcomes.length } : null;
2628
+ }
2629
+ },
2630
+ {
2631
+ id: "tests-bound",
2632
+ label: "Tests the model names",
2633
+ dimension: "tests",
2634
+ tests: true,
2635
+ rule: "test-unbound",
2636
+ description: "The tests in the files test-unbound includes that a scenario or fitness function names.",
2637
+ measure: (ctx) => {
2638
+ const files = [...testBinding(ctx.model)?.values() ?? []];
2639
+ const total = files.reduce((sum, f) => sum + f.total, 0);
2640
+ return total ? { count: total - files.reduce((sum, f) => sum + f.unbound.length, 0), total } : null;
2641
+ }
2642
+ }
2643
+ ];
2644
+ var METRIC_IDS = new Set(CHECK_METRICS.map((m) => m.id));
2645
+ var isMetricId = (id) => METRIC_IDS.has(id);
2646
+ function measureGoals(ctx, goals) {
2647
+ const metrics = [];
2648
+ const findings = [];
2649
+ for (const metric of CHECK_METRICS) {
2650
+ const value = metric.measure(ctx);
2651
+ if (!value) continue;
2652
+ const min = goals[metric.id]?.min;
2653
+ const met = min === void 0 || value.count * 100 >= min * value.total;
2654
+ metrics.push({
2655
+ id: metric.id,
2656
+ label: metric.label,
2657
+ dimension: metric.dimension,
2658
+ ...metric.rule ? { rule: metric.rule } : {},
2659
+ ...value,
2660
+ percent: Math.floor(value.count * 100 / value.total),
2661
+ ...min !== void 0 ? { min } : {},
2662
+ met
2663
+ });
2664
+ if (!met) {
2665
+ findings.push({
2666
+ code: metric.id,
2667
+ message: `${metric.label}: ${Math.floor(value.count * 100 / value.total)}% (${value.count} of ${value.total}), below the goal of ${min}%.`
2668
+ });
2669
+ }
2670
+ }
2671
+ return { metrics, findings };
2672
+ }
2673
+
2674
+ // ../../packages/common/src/formats/canvasSelection.ts
2675
+ var SELECTION_DIR = ".radical";
2676
+ var SELECTION_FILE = `${SELECTION_DIR}/selection.json`;
2677
+ var SELECTION_GITIGNORE = `${SELECTION_DIR}/.gitignore`;
2678
+ var SELECTION_GITIGNORE_CONTENT = "*\n";
2679
+
2680
+ // ../../packages/common/src/check/files.ts
2681
+ var CHECK_CONFIG_FILE = "check.json";
2682
+ var TEST_RESULTS_FILE = `${SELECTION_DIR}/test-results.json`;
2683
+ function serializeTestResults(cases, reports, readAt = /* @__PURE__ */ new Date()) {
2684
+ const results = { version: 1, readAt: readAt.toISOString(), reports, cases };
2685
+ return JSON.stringify(results);
2686
+ }
2687
+ function parseCheckConfig(text) {
2688
+ const data = JSON.parse(text);
2689
+ if (!data || typeof data !== "object" || Array.isArray(data)) throw new Error("a config is a JSON object");
2690
+ const rules = data.rules;
2691
+ if (rules !== void 0 && (typeof rules !== "object" || rules === null || Array.isArray(rules))) throw new Error('"rules" is an object of rule settings');
2692
+ const goals = data.goals;
2693
+ if (goals !== void 0) {
2694
+ if (typeof goals !== "object" || goals === null || Array.isArray(goals)) throw new Error('"goals" is an object of goals by metric');
2695
+ for (const [id, goal] of Object.entries(goals)) {
2696
+ const min = goal?.min;
2697
+ if (typeof min !== "number" || !(min >= 0 && min <= 100)) throw new Error(`goal "${id}" needs a "min" from 0 to 100 (percent)`);
2698
+ }
2699
+ }
2700
+ return data;
2701
+ }
2702
+
2703
+ // ../../packages/common/src/check/format.ts
2704
+ var WARNINGS_SHOWN = 5;
2705
+ var join = (folder, path) => folder === "." || folder === "" ? path : `${folder.replace(/\/+$/, "")}/${path}`;
2706
+ var where = (f, folder) => f.testFile ?? (f.path ? join(folder, f.path) : f.nodeId ? `node ${f.nodeId}` : f.relationId ? `relation ${f.relationId}` : folder);
2707
+ var plural = (n, word) => `${n} ${word}${n === 1 ? "" : "s"}`;
2708
+ function formatCheckText(result, options) {
2709
+ const lines = [`radical check: ${options.folder} (${plural(result.nodeCount, "element")}, ${plural(result.relationCount, "relation")})`, ""];
2710
+ for (const rule of result.rules) {
2711
+ if (rule.severity === "off" || rule.count === 0) {
2712
+ if (rule.max !== void 0 && rule.severity !== "off") lines.push(`\u2713 ${rule.id} 0 (max ${rule.max})`);
2713
+ continue;
2714
+ }
2715
+ const mark = rule.failed ? "\u2716" : "\u26A0";
2716
+ lines.push(`${mark} ${rule.id} ${rule.count}${rule.max !== void 0 ? ` (max ${rule.max})` : ""}`);
2717
+ const list = result.findings.filter((f) => f.key === rule.id);
2718
+ const shown = options.verbose ? list : list.filter((f, i) => f.severity === "error" || i < WARNINGS_SHOWN);
2719
+ for (const f of shown) {
2720
+ const at = f.testFile ? "" : `${where(f, options.folder)} `;
2721
+ lines.push(` ${f.severity === "error" ? "error " : "warning"} ${at}${f.message}`);
2722
+ if (options.verbose) for (const detail of f.details ?? []) lines.push(` ${detail}`);
2723
+ }
2724
+ if (shown.length < list.length) lines.push(` \u2026 ${list.length - shown.length} more (--verbose shows them)`);
2725
+ }
2726
+ const goals = result.metrics.filter((m) => m.min !== void 0);
2727
+ if (goals.length) {
2728
+ lines.push("", "Goals:");
2729
+ for (const m of goals) lines.push(` ${m.met ? "\u2713" : "\u2716"} ${m.id} ${m.percent}% (${m.count} of ${m.total}, min ${m.min}%)`);
2730
+ }
2731
+ if (result.evidence) lines.push("", ...evidenceSummary(result));
2732
+ if (result.unknownRules.length) lines.push("", `\u26A0 The config names rules that do not exist: ${result.unknownRules.join(", ")}`);
2733
+ if (result.unknownGoals.length) lines.push("", `\u26A0 The config sets goals for metrics that do not exist: ${result.unknownGoals.join(", ")}`);
2734
+ lines.push("", `${result.ok ? "\u2713" : "\u2716"} ${plural(result.errors, "error")}, ${plural(result.warnings, "warning")}`);
2735
+ return lines.join("\n");
2736
+ }
2737
+ function formatCheckGithub(result, options) {
2738
+ const escape = (s) => s.replace(/%/g, "%25").replace(/\r/g, "%0D").replace(/\n/g, "%0A");
2739
+ const prop3 = (s) => escape(s).replace(/:/g, "%3A").replace(/,/g, "%2C");
2740
+ const lines = [];
2741
+ let warnings = 0;
2742
+ for (const f of result.findings) {
2743
+ if (f.severity === "warning" && ++warnings > 10) continue;
2744
+ const path = f.testFile ?? (f.path ? join(options.folder, f.path) : void 0);
2745
+ const file = path ? `file=${prop3(path)},` : "";
2746
+ lines.push(`::${f.severity} ${file}title=${prop3(`radical check: ${f.rule}${f.code ? `/${f.code}` : ""}`)}::${escape(f.message)}`);
2747
+ }
2748
+ return [...lines, formatCheckText(result, options)].join("\n");
2749
+ }
2750
+ var STATUS_ORDER = ["verified", "passed", "broken", "failed", "not-run", "unverified", "no-tests"];
2751
+ var SUMMARY_TYPES = [["requirement", "Requirements"], ["scenario", "Scenarios"], ["adr", "ADRs"], ["fitness-fn", "Fitness functions"]];
2752
+ function evidenceSummary(result) {
2753
+ const entries = Object.values(result.evidence.nodes);
2754
+ const lines = [`Test reports: ${plural(result.evidence.testCases, "test case")}`];
2755
+ for (const [type, name] of SUMMARY_TYPES) {
2756
+ const ofType = entries.filter((e) => e.type === type);
2757
+ if (!ofType.length) continue;
2758
+ const counts = /* @__PURE__ */ new Map();
2759
+ for (const e of ofType) counts.set(e.status, (counts.get(e.status) ?? 0) + 1);
2760
+ const ordered = STATUS_ORDER.filter((status) => counts.has(status));
2761
+ lines.push(` ${name}: ${ordered.map((status) => `${counts.get(status)} ${status}`).join(", ")}`);
2762
+ }
2763
+ return lines;
2764
+ }
2765
+
2766
+ // ../../packages/common/src/check/index.ts
2767
+ var FOLDER_RULES = [
2768
+ { id: "folder-manifest", description: "The folder has a radical.md manifest of the Markdown-folder format, version 1.", severity: "error", dimension: "consistency" },
2769
+ { id: "folder-json", description: "Every JSON sidecar (relations.json, views.json, \u2026) parses.", severity: "error", dimension: "consistency" },
2770
+ { id: "folder-conflict", description: "No node file holds git conflict markers.", severity: "error", dimension: "consistency" },
2771
+ { id: "folder-not-a-node", description: "A node file with frontmatter has an id and a type (one without them is skipped on loading, and its element is gone).", severity: "error", dimension: "consistency" },
2772
+ { id: "folder-duplicate-id", description: "No two node files hold the same id.", severity: "error", dimension: "consistency" },
2773
+ { id: "stale-reference", description: "Views, sequences and slides point only at elements, relations and views the model has.", severity: "warning", dimension: "consistency" }
2774
+ ];
2775
+ var FATAL = /* @__PURE__ */ new Set(["folder-manifest", "folder-json", "folder-conflict"]);
2776
+ var byId = (items) => Object.fromEntries(items.map((item) => [item.id, item]));
2777
+ var ALL_RULES = [...FOLDER_RULES, ...CHECK_RULES, GOAL_RULE];
2778
+ var RULE_IDS = new Set(ALL_RULES.map((r) => r.id));
2779
+ var DEFAULT_SEVERITY = new Map(ALL_RULES.map((r) => [r.id, r.severity]));
2780
+ function runCheck(files, config = {}, options = {}) {
2781
+ const found = [];
2782
+ const add = (rule, finding) => {
2783
+ found.push({ rule, ...finding });
2784
+ };
2785
+ if (!isValidMdFolderManifest(files[MD_MANIFEST_FILE])) {
2786
+ add("folder-manifest", { path: MD_MANIFEST_FILE, message: `${MD_MANIFEST_FILE} is missing or is no Markdown-folder manifest of version 1.` });
2787
+ }
2788
+ for (const path of MD_FOLDER_JSON_FILES) {
2789
+ if (!(path in files)) continue;
2790
+ try {
2791
+ JSON.parse(files[path]);
2792
+ } catch (error) {
2793
+ add("folder-json", { path, message: `${path} does not parse: ${error.message}` });
2794
+ }
2795
+ }
2796
+ const nodeFiles = mdFolderNodeFiles(files);
2797
+ const pathOf2 = /* @__PURE__ */ new Map();
2798
+ for (const file of nodeFiles) {
2799
+ if (file.conflict) add("folder-conflict", { path: file.path, message: `${file.path} holds git conflict markers.` });
2800
+ else if (file.frontmatter && (!file.id || !file.type)) {
2801
+ add("folder-not-a-node", { path: file.path, message: `${file.path} has frontmatter but no ${file.id ? "type" : file.type ? "id" : "id and type"}; it is not loaded as an element.` });
2802
+ } else if (file.id) {
2803
+ const first = pathOf2.get(file.id);
2804
+ if (first) add("folder-duplicate-id", { path: file.path, message: `${file.path} holds id ${file.id}, which ${first} holds too.` });
2805
+ else pathOf2.set(file.id, file.path);
2806
+ }
2807
+ }
2808
+ let model = { found: [], nodeCount: 0, relationCount: 0, metrics: [] };
2809
+ if (!found.some((f) => FATAL.has(f.rule))) model = checkData(deserializeFromMdFolder(files).data, options, config);
2810
+ const result = settle([...found, ...model.found].map((f) => ({
2811
+ ...f,
2812
+ ...!f.path && f.nodeId && pathOf2.has(f.nodeId) ? { path: pathOf2.get(f.nodeId) } : {},
2813
+ ...!f.path && f.relationId ? { path: "relations.json" } : {}
2814
+ })), config, model.nodeCount, model.relationCount, model.metrics);
2815
+ return model.evidence ? { ...result, evidence: model.evidence } : result;
2816
+ }
2817
+ function checkData(data, options, config) {
2818
+ const found = [];
2819
+ const nodes = byId(data.nodes);
2820
+ const relations = byId(data.relations);
2821
+ staleReferences(data.views ?? [], data.sequences ?? [], data.presentations ?? [], nodes, relations).forEach((finding) => found.push({ rule: "stale-reference", ...finding }));
2822
+ const model = {
2823
+ nodes,
2824
+ relations,
2825
+ metamodel: documentMetamodel(data.metamodel, data.nodes),
2826
+ settings: config.rules ?? {},
2827
+ ...options.tests ? { tests: options.tests } : {}
2828
+ };
2829
+ for (const rule of CHECK_RULES) rule.run(model).forEach((finding) => found.push({ rule: rule.id, ...finding }));
2830
+ const evidence = options.tests ? computeEvidence(model) : void 0;
2831
+ const goals = measureGoals({ model, found, ...evidence ? { evidence } : {} }, config.goals ?? {});
2832
+ goals.findings.forEach((finding) => found.push({ rule: GOAL_RULE.id, ...finding }));
2833
+ return {
2834
+ found,
2835
+ nodeCount: Object.keys(nodes).length,
2836
+ relationCount: Object.keys(relations).length,
2837
+ metrics: goals.metrics,
2838
+ ...evidence ? { evidence } : {}
2839
+ };
2840
+ }
2841
+ function staleReferences(views, sequences, presentations, nodes, relations) {
2842
+ const findings = [];
2843
+ const sequenceIds = new Set(sequences.map((s) => s.id));
2844
+ const viewIds = new Set(views.map((v) => v.id));
2845
+ for (const view of views) {
2846
+ const missing = (view.nodeIds ?? []).filter((id) => !nodes[id]);
2847
+ if (missing.length) findings.push({ path: "views.json", message: `View "${view.name}" lists ${missing.length} element(s) the model does not have: ${missing.join(", ")}.` });
2848
+ if (view.sequenceId && !sequenceIds.has(view.sequenceId)) findings.push({ path: "views.json", message: `View "${view.name}" plays sequence ${view.sequenceId}, which the model does not have.` });
2849
+ }
2850
+ for (const sequence of sequences) {
2851
+ const missing = sequence.relationIds.filter((id) => !relations[id]);
2852
+ if (missing.length) findings.push({ path: "sequences.json", message: `Sequence "${sequence.name}" has ${missing.length} step(s) on relations the model does not have: ${missing.join(", ")}.` });
2853
+ }
2854
+ for (const presentation of presentations) {
2855
+ for (const slide of presentation.slides) {
2856
+ if (slide.viewId && !viewIds.has(slide.viewId)) findings.push({ path: "presentations.json", message: `Slide "${slide.name}" of "${presentation.name}" shows view ${slide.viewId}, which the model does not have.` });
2857
+ }
2858
+ }
2859
+ return findings;
2860
+ }
2861
+ var keyOf = (f, rules) => f.code && rules[`${f.rule}/${f.code}`] !== void 0 ? `${f.rule}/${f.code}` : f.rule;
2862
+ var settingOf = (setting) => setting === void 0 ? {} : typeof setting === "string" ? { severity: setting } : setting;
2863
+ function settle(found, config, nodeCount, relationCount, metrics) {
2864
+ const rules = config.rules ?? {};
2865
+ const groups = /* @__PURE__ */ new Map();
2866
+ for (const f of found) {
2867
+ const key = keyOf(f, rules);
2868
+ groups.set(key, [...groups.get(key) ?? [], f]);
2869
+ }
2870
+ const order = ALL_RULES.map((r) => r.id);
2871
+ const keys = [.../* @__PURE__ */ new Set([...groups.keys(), ...Object.keys(rules).filter((k) => RULE_IDS.has(k.split("/")[0]))])].sort((a, b) => order.indexOf(a.split("/")[0]) - order.indexOf(b.split("/")[0]) || a.localeCompare(b));
2872
+ const findings = [];
2873
+ const results = [];
2874
+ for (const key of keys) {
2875
+ const list = groups.get(key) ?? [];
2876
+ const { severity: set, max } = settingOf(rules[key]);
2877
+ const ruleSeverity = DEFAULT_SEVERITY.get(key.split("/")[0]) ?? "error";
2878
+ if (set === "off") {
2879
+ results.push({ id: key, count: list.length, severity: "off", failed: false });
2880
+ continue;
2881
+ }
2882
+ const withinBaseline = max !== void 0 && list.length <= max;
2883
+ const settled = list.map((f) => ({
2884
+ ...f,
2885
+ key,
2886
+ severity: withinBaseline ? "warning" : set ?? f.severity ?? ruleSeverity
2887
+ }));
2888
+ findings.push(...settled);
2889
+ results.push({
2890
+ id: key,
2891
+ count: list.length,
2892
+ severity: set ?? ruleSeverity,
2893
+ ...max !== void 0 ? { max } : {},
2894
+ failed: settled.some((f) => f.severity === "error")
2895
+ });
2896
+ }
2897
+ const errors = findings.filter((f) => f.severity === "error").length;
2898
+ return {
2899
+ ok: errors === 0,
2900
+ errors,
2901
+ warnings: findings.length - errors,
2902
+ findings,
2903
+ rules: results,
2904
+ unknownRules: Object.keys(rules).filter((k) => !RULE_IDS.has(k.split("/")[0])),
2905
+ unknownGoals: Object.keys(config.goals ?? {}).filter((k) => !isMetricId(k)),
2906
+ metrics,
2907
+ nodeCount,
2908
+ relationCount
2909
+ };
2910
+ }
2911
+ function ratchetConfig(config, result) {
2912
+ const rules = { ...config.rules ?? {} };
2913
+ const lowered = [];
2914
+ for (const r of result.rules) {
2915
+ const setting = rules[r.id];
2916
+ if (typeof setting !== "object" || setting.max === void 0 || r.count >= setting.max) continue;
2917
+ rules[r.id] = { ...setting, max: r.count };
2918
+ lowered.push({ id: r.id, from: setting.max, to: r.count });
2919
+ }
2920
+ return { config: { ...config, rules }, lowered };
2921
+ }
2922
+
2923
+ // ../../packages/common/src/formats/mdFolderSync.ts
2924
+ var MdFolderSession = class {
2925
+ constructor(storage) {
2926
+ this.storage = storage;
2927
+ /** Called with the changed paths whenever `poll` or a refused `write`
2928
+ * finds edits made outside the app. */
2929
+ this.onExternalChange = null;
2930
+ this.baseline = /* @__PURE__ */ new Map();
2931
+ this.loaded = false;
2932
+ /** Stamps as of the last look at the folder, so one outside edit is
2933
+ * reported once rather than on every poll until the app reloads. */
2934
+ this.observed = {};
2935
+ this.tail = Promise.resolve();
2936
+ this.running = 0;
2937
+ }
2938
+ /** Read every model file and make that the baseline. */
2939
+ readAll() {
2940
+ return this.exclusive(async () => {
2941
+ await this.loadBaseline();
2942
+ const files = {};
2943
+ for (const [path, entry] of this.baseline) files[path] = entry.content;
2944
+ return files;
2945
+ });
2946
+ }
2947
+ /** Make the folder hold exactly the model `files` (plus whatever the
2948
+ * format doesn't own), unless it changed on disk since the last read. */
2949
+ write(files) {
2950
+ return this.exclusive(async () => {
2951
+ if (!this.loaded) await this.loadBaseline();
2952
+ const stamps = await this.storage.list();
2953
+ const conflict = await this.changedSince(stamps);
2954
+ if (conflict.length > 0) {
2955
+ this.observed = stamps;
2956
+ this.onExternalChange?.(conflict);
2957
+ return { ok: false, conflict };
2958
+ }
2959
+ for (const [path, content] of Object.entries(files)) {
2960
+ if (this.baseline.get(path)?.content === content) continue;
2961
+ const stamp = await this.storage.write(path, content);
2962
+ this.baseline.set(path, { content, stamp });
2963
+ }
2964
+ const current = {};
2965
+ for (const [path, entry] of this.baseline) current[path] = entry.content;
2966
+ for (const path of staleMdFolderFiles(current, files)) {
2967
+ await this.storage.remove(path);
2968
+ this.baseline.delete(path);
2969
+ }
2970
+ this.observed = this.baselineStamps();
2971
+ return { ok: true };
2972
+ });
2973
+ }
2974
+ /** Look for edits made outside the app since the folder was last read,
2975
+ * written or polled. Resolves with the changed paths (empty when none, or
2976
+ * when another operation is running — the next poll will see it). */
2977
+ poll() {
2978
+ if (this.running > 0 || !this.loaded) return Promise.resolve([]);
2979
+ return this.exclusive(async () => {
2980
+ const stamps = await this.storage.list();
2981
+ if (sameStamps(stamps, this.observed)) return [];
2982
+ this.observed = stamps;
2983
+ const changed = await this.changedSince(stamps);
2984
+ if (changed.length > 0) this.onExternalChange?.(changed);
2985
+ return changed;
2986
+ });
2987
+ }
2988
+ async loadBaseline() {
2989
+ const stamps = await this.storage.list();
2990
+ const baseline = /* @__PURE__ */ new Map();
2991
+ for (const [path, stamp] of Object.entries(stamps)) {
2992
+ baseline.set(path, { content: await this.storage.read(path), stamp });
2993
+ }
2994
+ this.baseline = baseline;
2995
+ this.observed = stamps;
2996
+ this.loaded = true;
2997
+ }
2998
+ /** Paths whose content on disk differs from the baseline: added, removed,
2999
+ * or rewritten with different content. A file whose stamp moved but whose
3000
+ * content didn't (touched, saved unchanged) just gets its stamp updated. */
3001
+ async changedSince(stamps) {
3002
+ const changed = [];
3003
+ for (const [path, stamp] of Object.entries(stamps)) {
3004
+ const known = this.baseline.get(path);
3005
+ if (!known) {
3006
+ changed.push(path);
3007
+ } else if (known.stamp !== stamp) {
3008
+ let content;
3009
+ try {
3010
+ content = await this.storage.read(path);
3011
+ } catch {
3012
+ changed.push(path);
3013
+ continue;
3014
+ }
3015
+ if (content === known.content) known.stamp = stamp;
3016
+ else changed.push(path);
3017
+ }
3018
+ }
3019
+ for (const path of this.baseline.keys()) {
3020
+ if (!(path in stamps)) changed.push(path);
3021
+ }
3022
+ return changed.sort();
3023
+ }
3024
+ baselineStamps() {
3025
+ const stamps = {};
3026
+ for (const [path, entry] of this.baseline) stamps[path] = entry.stamp;
3027
+ return stamps;
3028
+ }
3029
+ exclusive(fn) {
3030
+ this.running++;
3031
+ const run = this.tail.then(fn, fn);
3032
+ this.tail = run.catch(() => {
3033
+ });
3034
+ const done = () => {
3035
+ this.running--;
3036
+ };
3037
+ run.then(done, done);
3038
+ return run;
3039
+ }
3040
+ };
3041
+ function sameStamps(a, b) {
3042
+ const keys = Object.keys(a);
3043
+ if (keys.length !== Object.keys(b).length) return false;
3044
+ return keys.every((key) => b[key] === a[key]);
3045
+ }
3046
+
3047
+ // ../../packages/node-files/src/diskFolderStorage.ts
3048
+ import { lstat, mkdir, readFile, readdir, rm, stat, writeFile } from "fs/promises";
3049
+ import { dirname as dirname2, resolve, sep } from "path";
3050
+ function diskFolderStorage(root) {
3051
+ const base = resolve(root);
3052
+ const stampOf = (s) => `${s.mtimeMs}:${s.size}`;
3053
+ async function inside(rel) {
3054
+ const abs = resolve(base, rel);
3055
+ if (!abs.startsWith(base + sep)) throw new Error(`path outside the model folder: ${rel}`);
3056
+ if (!isMdFolderModelPath(rel) || rel.includes("\\") || rel.split("/").some((part) => !part || part === "." || part === "..")) {
3057
+ throw new Error(`not a model file: ${rel}`);
3058
+ }
3059
+ let current = base;
3060
+ for (const part of rel.split("/")) {
3061
+ current = resolve(current, part);
3062
+ try {
3063
+ if ((await lstat(current)).isSymbolicLink()) throw new Error(`symlink in model path: ${rel}`);
3064
+ } catch (error) {
3065
+ if (error.code !== "ENOENT") throw error;
3066
+ }
3067
+ }
3068
+ return abs;
3069
+ }
3070
+ return {
3071
+ async list() {
3072
+ const stamps = {};
3073
+ const add = async (rel) => {
3074
+ try {
3075
+ stamps[rel] = stampOf(await stat(await inside(rel)));
3076
+ } catch (error) {
3077
+ if (error.code !== "ENOENT") throw error;
3078
+ }
3079
+ };
3080
+ const walk = async (rel) => {
3081
+ const entries = await readdir(await inside(`${rel}/_index.md`).then(dirname2), { withFileTypes: true });
3082
+ for (const entry of entries) {
3083
+ if (entry.name.startsWith(".")) continue;
3084
+ const child = `${rel}/${entry.name}`;
3085
+ if (entry.isDirectory()) await walk(child);
3086
+ else if (entry.isFile() && isMdFolderModelPath(child)) await add(child);
3087
+ else if (entry.isSymbolicLink()) throw new Error(`symlink in model path: ${child}`);
3088
+ }
3089
+ };
3090
+ const top = await readdir(base, { withFileTypes: true });
3091
+ for (const entry of top) {
3092
+ if (entry.isFile() && isMdFolderModelPath(entry.name)) await add(entry.name);
3093
+ else if (entry.isDirectory() && entry.name === "nodes") await walk("nodes");
3094
+ else if (entry.isSymbolicLink() && (entry.name === "nodes" || isMdFolderModelPath(entry.name))) {
3095
+ throw new Error(`symlink in model path: ${entry.name}`);
3096
+ }
3097
+ }
3098
+ return stamps;
3099
+ },
3100
+ read: async (rel) => readFile(await inside(rel), "utf-8"),
3101
+ async write(rel, content) {
3102
+ const abs = await inside(rel);
3103
+ await mkdir(dirname2(abs), { recursive: true });
3104
+ await inside(rel);
3105
+ await writeFile(abs, content, "utf-8");
3106
+ return stampOf(await stat(abs));
3107
+ },
3108
+ remove: async (rel) => rm(await inside(rel), { force: true })
3109
+ };
3110
+ }
3111
+
3112
+ // src/check.ts
3113
+ var CHECK_USAGE = `Usage: radical check [folder] [options]
3114
+
3115
+ Checks a Radical Markdown model folder: its files, its metamodel, and that it
3116
+ is complete (requirements have scenarios, accepted ADRs fitness functions, \u2026).
3117
+
3118
+ folder the model folder (default: the working directory)
3119
+ --config <file> rule settings (default: check.json in the model folder,
3120
+ when there is one)
3121
+ --format <format> text (default), json, or github (annotations for Actions)
3122
+ --report <path> a test report (Vitest or Jest JSON, Playwright JSON, JUnit
3123
+ XML), or a directory of them (.json and .xml files); repeat
3124
+ for more. The tests that scenarios and fitness functions
3125
+ name are looked up in them. The test cases read are kept
3126
+ in the model folder's .radical/test-results.json for Studio
3127
+ --evidence <file> with --report: write what the reports say about each
3128
+ scenario, fitness function, requirement and ADR as JSON
3129
+ --ratchet lower each baseline (max) in the config to the count found
3130
+ now, so a rule that got better cannot get worse again
3131
+ --verbose list every warning, not the first five of each rule
3132
+ --list-rules list the rules and their default severity, and the
3133
+ metrics check.json can set goals for ("goals":
3134
+ { "<metric>": { "min": <percent> } })
3135
+
3136
+ Exit status: 0 no errors, 1 errors found, 2 the check could not run.`;
3137
+ async function checkCommand(args, io2) {
3138
+ let parsed;
3139
+ try {
3140
+ parsed = parseArgs({
3141
+ args,
3142
+ allowPositionals: true,
3143
+ options: {
3144
+ config: { type: "string" },
3145
+ format: { type: "string", default: "text" },
3146
+ report: { type: "string", multiple: true },
3147
+ evidence: { type: "string" },
3148
+ ratchet: { type: "boolean", default: false },
3149
+ verbose: { type: "boolean", default: false },
3150
+ "list-rules": { type: "boolean", default: false },
3151
+ help: { type: "boolean", short: "h", default: false }
3152
+ }
3153
+ });
3154
+ } catch (error) {
3155
+ io2.err(`${error.message}
3156
+
3157
+ ${CHECK_USAGE}`);
3158
+ return 2;
3159
+ }
3160
+ const { values, positionals } = parsed;
3161
+ if (values.help) {
3162
+ io2.out(CHECK_USAGE);
3163
+ return 0;
3164
+ }
3165
+ if (values["list-rules"]) {
3166
+ for (const rule of [...FOLDER_RULES, ...CHECK_RULES, GOAL_RULE]) io2.out(`${rule.id.padEnd(30)} ${rule.severity.padEnd(8)} ${rule.description}`);
3167
+ io2.out("\nMetrics for goals (in percent):");
3168
+ for (const metric of CHECK_METRICS) io2.out(`${metric.id.padEnd(30)} ${(metric.tests ? "reports" : "").padEnd(8)} ${metric.description}`);
3169
+ return 0;
3170
+ }
3171
+ if (positionals.length > 1 || !["text", "json", "github"].includes(values.format) || values.evidence && !values.report?.length) {
3172
+ io2.err(CHECK_USAGE);
3173
+ return 2;
3174
+ }
3175
+ const folder = positionals[0] ?? ".";
3176
+ let root;
3177
+ let files;
3178
+ try {
3179
+ root = await realpath(resolve2(io2.cwd, folder));
3180
+ if (!(await stat2(root)).isDirectory()) throw new Error("not a directory");
3181
+ files = await new MdFolderSession(diskFolderStorage(root)).readAll();
3182
+ } catch (error) {
3183
+ io2.err(`Cannot read the model folder ${folder}: ${error.message}`);
3184
+ return 2;
3185
+ }
3186
+ const configPath = values.config ? resolve2(io2.cwd, values.config) : join2(root, CHECK_CONFIG_FILE);
3187
+ let config = {};
3188
+ try {
3189
+ config = parseCheckConfig(await readFile2(configPath, "utf8"));
3190
+ } catch (error) {
3191
+ const missing = error.code === "ENOENT";
3192
+ if (!missing || values.config || values.ratchet) {
3193
+ io2.err(missing ? `No config at ${configPath}.` : `Cannot read the config ${configPath}: ${error.message}`);
3194
+ return 2;
3195
+ }
3196
+ }
3197
+ let tests;
3198
+ if (values.report?.length) {
3199
+ tests = [];
3200
+ for (const report of await reportFiles(values.report, io2.cwd)) {
3201
+ try {
3202
+ tests.push(...parseTestReport(await readFile2(resolve2(io2.cwd, report), "utf8"), report));
3203
+ } catch (error) {
3204
+ io2.err(`Cannot read the test report ${report}: ${error.message}`);
3205
+ return 2;
3206
+ }
3207
+ }
3208
+ }
3209
+ const result = runCheck(files, config, tests ? { tests } : {});
3210
+ if (tests) {
3211
+ await writeBeside(join2(root, TEST_RESULTS_FILE), serializeTestResults(tests, values.report ?? []));
3212
+ }
3213
+ if (values.evidence && result.evidence) await writeBeside(resolve2(io2.cwd, values.evidence), JSON.stringify(result.evidence, null, 2) + "\n");
3214
+ const options = { folder, verbose: values.verbose };
3215
+ io2.out(values.format === "json" ? JSON.stringify(result, null, 2) : values.format === "github" ? formatCheckGithub(result, options) : formatCheckText(result, options));
3216
+ if (values.ratchet) {
3217
+ const { config: next, lowered } = ratchetConfig(config, result);
3218
+ if (lowered.length) {
3219
+ await writeFile2(configPath, JSON.stringify(next, null, 2) + "\n");
3220
+ io2.err(`Ratchet: ${lowered.map((l) => `${l.id} ${l.from} \u2192 ${l.to}`).join(", ")} (written to ${configPath}).`);
3221
+ }
3222
+ }
3223
+ return result.ok ? 0 : 1;
3224
+ }
3225
+ async function reportFiles(paths, cwd) {
3226
+ const files = [];
3227
+ for (const path of paths) {
3228
+ const isDir = await stat2(resolve2(cwd, path)).then((s) => s.isDirectory(), () => false);
3229
+ if (!isDir) {
3230
+ files.push(path);
3231
+ continue;
3232
+ }
3233
+ const names = (await readdir2(resolve2(cwd, path))).filter((name) => /\.(json|xml)$/i.test(name)).sort();
3234
+ files.push(...names.map((name) => join2(path, name)));
3235
+ }
3236
+ return files;
3237
+ }
3238
+ async function writeBeside(path, content) {
3239
+ const dir = dirname3(path);
3240
+ await mkdir2(dir, { recursive: true });
3241
+ if (basename(dir) === SELECTION_DIR) {
3242
+ await writeFile2(join2(dir, ".gitignore"), SELECTION_GITIGNORE_CONTENT, { flag: "wx" }).catch((error) => {
3243
+ if (error.code !== "EEXIST") throw error;
3244
+ });
3245
+ }
3246
+ await writeFile2(path, content);
3247
+ }
3248
+
3249
+ // src/diff.ts
3250
+ import { realpath as realpath2, stat as stat3 } from "fs/promises";
3251
+ import { resolve as resolve4 } from "path";
3252
+ import { parseArgs as parseArgs2 } from "util";
3253
+
3254
+ // ../../packages/node-files/src/gitModel.ts
3255
+ import { execFile, spawn } from "child_process";
3256
+ import { promisify } from "util";
3257
+
3258
+ // ../../packages/common/src/modelChanges.ts
3259
+ var NOT_MODEL = /* @__PURE__ */ new Set(["id", "x", "y", "width", "height", "collapsed"]);
3260
+ var SHOWN = /* @__PURE__ */ new Set(["type", "label", "parentId", "sourceId", "targetId", "relationType"]);
3261
+ var present = (value) => value !== void 0 && value !== null && value !== "";
3262
+ function modelFields(item) {
3263
+ return Object.fromEntries(Object.entries(item).filter(([key, value]) => !NOT_MODEL.has(key) && !SHOWN.has(key) && present(value)));
3264
+ }
3265
+ function pathOf(node, nodes) {
3266
+ const path = [];
3267
+ for (let cur = node.parentId ? nodes[node.parentId] : void 0; cur && path.length < 64; cur = cur.parentId ? nodes[cur.parentId] : void 0) {
3268
+ path.unshift(cur.label);
3269
+ }
3270
+ return path;
3271
+ }
3272
+ var refOf = (id, ...copies) => {
3273
+ const node = copies.map((copy) => copy.nodes[id]).find(Boolean);
3274
+ return node ? { id, type: node.type, label: node.label } : { id, type: "?", label: id };
3275
+ };
3276
+ function modelChangeReport(before, after) {
3277
+ const changes = compareModels(before, after);
3278
+ const relatedIn = (copy, id) => Object.values(copy.relations).filter((r) => r.sourceId === id || r.targetId === id).map((r) => {
3279
+ const out = r.sourceId === id;
3280
+ return { ...refOf(out ? r.targetId : r.sourceId, copy), relationType: r.relationType ?? null, direction: out ? "out" : "in" };
3281
+ }).sort((a, b) => (a.relationType ?? "").localeCompare(b.relationType ?? "") || a.label.localeCompare(b.label));
3282
+ const element = (copy, id, extra) => {
3283
+ const node = copy.nodes[id];
3284
+ return { id, type: node.type, label: node.label, path: pathOf(node, copy.nodes), ...extra, related: relatedIn(copy, id) };
3285
+ };
3286
+ const fieldChanges = (from, to, fields) => fields.map((field) => ({ field, before: from[field] ?? null, after: to[field] ?? null }));
3287
+ const relation = (r, extra) => ({
3288
+ id: r.id,
3289
+ relationType: r.relationType ?? null,
3290
+ label: r.label ?? null,
3291
+ source: refOf(r.sourceId, after, before),
3292
+ target: refOf(r.targetId, after, before),
3293
+ ...extra
3294
+ });
3295
+ const byPlace = (a, b) => [...a.path, a.label].join("\0").localeCompare([...b.path, b.label].join("\0")) || a.id.localeCompare(b.id);
3296
+ const byEnds = (a, b) => a.source.label.localeCompare(b.source.label) || a.target.label.localeCompare(b.target.label) || a.id.localeCompare(b.id);
3297
+ return {
3298
+ elements: {
3299
+ added: changes.nodes.added.map((id) => element(after, id, { fields: modelFields(after.nodes[id]) })).sort(byPlace),
3300
+ removed: changes.nodes.removed.map((id) => element(before, id, { fields: modelFields(before.nodes[id]) })).sort(byPlace),
3301
+ changed: changes.nodes.changed.map(({ id, fields }) => element(after, id, { changes: fieldChanges(before.nodes[id], after.nodes[id], fields) })).sort(byPlace)
3302
+ },
3303
+ relations: {
3304
+ added: changes.relations.added.map((id) => relation(after.relations[id], { fields: modelFields(after.relations[id]) })).sort(byEnds),
3305
+ removed: changes.relations.removed.map((id) => relation(before.relations[id], { fields: modelFields(before.relations[id]) })).sort(byEnds),
3306
+ changed: changes.relations.changed.map(({ id, fields }) => relation(after.relations[id], { changes: fieldChanges(before.relations[id], after.relations[id], fields) })).sort(byEnds)
3307
+ }
3308
+ };
3309
+ }
3310
+ var countModelChanges = (report) => [report.elements, report.relations].reduce((sum, group) => sum + group.added.length + group.removed.length + group.changed.length, 0);
3311
+ var MAX_RELATED = 12;
3312
+ var LONG_TEXT = 60;
3313
+ function formatModelChanges(report, before, after) {
3314
+ const lines = [];
3315
+ const name = (ref) => `${ref.type} "${ref.label}" (${ref.id})`;
3316
+ const value = (v) => {
3317
+ if (!present(v)) return "(none)";
3318
+ return typeof v === "string" ? v : JSON.stringify(v);
3319
+ };
3320
+ const field = (indent, key, v) => {
3321
+ const [first, ...rest] = v.split("\n");
3322
+ lines.push(`${indent}${key}: ${first}`, ...rest.map((line) => `${indent} ${line}`));
3323
+ };
3324
+ const parentLabel = (id, copy) => {
3325
+ if (typeof id !== "string" || !id) return "(root)";
3326
+ const node = copy.nodes[id];
3327
+ return node ? [...pathOf(node, copy.nodes), node.label].join(" \u203A ") : id;
3328
+ };
3329
+ const element = (change) => {
3330
+ lines.push(`- ${name(change)}${change.path.length ? ` in ${change.path.join(" \u203A ")}` : ""}`);
3331
+ for (const [key, v] of Object.entries(change.fields ?? {})) field(" ", key, value(v));
3332
+ for (const c of change.changes ?? []) {
3333
+ if (c.field === "parentId") {
3334
+ lines.push(` moved: ${parentLabel(c.before, before)} \u2192 ${parentLabel(c.after, after)}`);
3335
+ continue;
3336
+ }
3337
+ const long = [c.before, c.after].some((v) => typeof v === "string" && (v.includes("\n") || v.length > LONG_TEXT));
3338
+ if (long) {
3339
+ field(" ", `${c.field} before`, value(c.before));
3340
+ field(" ", `${c.field} now`, value(c.after));
3341
+ } else lines.push(` ${c.field}: ${value(c.before)} \u2192 ${value(c.after)}`);
3342
+ }
3343
+ if (change.related.length) {
3344
+ lines.push(" relations:");
3345
+ for (const r of change.related.slice(0, MAX_RELATED)) {
3346
+ lines.push(` ${r.direction === "out" ? "\u2192" : "\u2190"} ${r.relationType ?? "relation"} ${name(r)}`);
3347
+ }
3348
+ if (change.related.length > MAX_RELATED) lines.push(` \u2026and ${change.related.length - MAX_RELATED} more (search_model: GET NEIGHBORS OF ${change.id})`);
3349
+ }
3350
+ };
3351
+ const relation = (change) => {
3352
+ lines.push(`- ${name(change.source)} \u2192 ${name(change.target)} [${change.relationType ?? "relation"}]${change.label ? ` "${change.label}"` : ""} (${change.id})`);
3353
+ for (const [key, v] of Object.entries(change.fields ?? {})) if (key !== "label") field(" ", key, value(v));
3354
+ for (const c of change.changes ?? []) lines.push(` ${c.field}: ${value(c.before)} \u2192 ${value(c.after)}`);
3355
+ };
3356
+ const section = (title, items, write) => {
3357
+ if (!items.length) return;
3358
+ if (lines.length) lines.push("");
3359
+ lines.push(`${title} (${items.length}):`);
3360
+ items.forEach(write);
3361
+ };
3362
+ section("Elements added", report.elements.added, element);
3363
+ section("Elements changed", report.elements.changed, element);
3364
+ section("Elements removed", report.elements.removed, element);
3365
+ section("Relations added", report.relations.added, relation);
3366
+ section("Relations changed", report.relations.changed, relation);
3367
+ section("Relations removed", report.relations.removed, relation);
3368
+ return lines.join("\n");
3369
+ }
3370
+
3371
+ // ../../packages/common/src/formats/modelBase.ts
3372
+ var MODEL_BASE_FILE = `${SELECTION_DIR}/base.json`;
3373
+ var BASE_OLD_MS = 24 * 60 * 60 * 1e3;
3374
+ function serializeModelBase(base, now = /* @__PURE__ */ new Date()) {
3375
+ const out = { version: 1, commit: base.commit, described: base.described, branch: base.branch, savedAt: now.toISOString(), nodes: base.nodes, relations: base.relations };
3376
+ return `${JSON.stringify(out)}
3377
+ `;
3378
+ }
3379
+
3380
+ // ../../packages/node-files/src/selectionFile.ts
3381
+ import { lstat as lstat2, mkdir as mkdir3, readFile as readFile3, writeFile as writeFile3 } from "fs/promises";
3382
+ import { join as join3, resolve as resolve3 } from "path";
3383
+
3384
+ // ../../packages/common/src/ai/forge/prompts.ts
3385
+ var FORGE_STAGES = [
3386
+ {
3387
+ id: "requirements",
3388
+ title: "Requirements",
3389
+ blurb: "Extract functional requirements from the description, written as EARS statements."
3390
+ },
3391
+ {
3392
+ id: "domain",
3393
+ title: "Domain model",
3394
+ blurb: "Find the domains and the entities the requirements talk about: aggregates, how entities refer to each other, and how the domains relate."
3395
+ },
3396
+ {
3397
+ id: "fitness",
3398
+ title: "Fitness functions",
3399
+ blurb: "Propose measurable guardrails (fitness functions) constraining those requirements."
3400
+ },
3401
+ {
3402
+ id: "scenarios",
3403
+ title: "Gherkin scenarios",
3404
+ blurb: "Write Given/When/Then scenarios that verify each requirement."
3405
+ },
3406
+ {
3407
+ id: "states",
3408
+ title: "State machines",
3409
+ blurb: "Model the lifecycle of the entities that have one as event-driven state machines, from the scenarios that move them."
3410
+ },
3411
+ {
3412
+ id: "mockups",
3413
+ title: "Mockups",
3414
+ blurb: "Sketch the user-facing screens that illustrate the requirements and scenarios, then draw low-fi wireframes for them."
3415
+ },
3416
+ {
3417
+ id: "c4",
3418
+ title: "C4 model",
3419
+ blurb: "Derive the system/container/component structure that satisfies the spec above."
3420
+ }
3421
+ ];
3422
+
3423
+ // ../../packages/common/src/formats/forgeRunStatus.ts
3424
+ var FORGE_RUN_FILE = `${SELECTION_DIR}/forge-run.json`;
3425
+ var FORGE_RUN_STALE_MS = 30 * 60 * 1e3;
3426
+ var STAGE_IDS = new Set(FORGE_STAGES.map((s) => s.id));
3427
+
3428
+ // ../../packages/node-files/src/selectionFile.ts
3429
+ async function selectionDir(root, create) {
3430
+ const dir = join3(resolve3(root), SELECTION_DIR);
3431
+ try {
3432
+ if ((await lstat2(dir)).isSymbolicLink()) throw new Error(`symlink in model path: ${SELECTION_DIR}`);
3433
+ } catch (error) {
3434
+ if (error.code !== "ENOENT") throw error;
3435
+ if (!create) return null;
3436
+ await mkdir3(dir);
3437
+ }
3438
+ return dir;
3439
+ }
3440
+ async function writeEditorStateFile(root, path, content) {
3441
+ await selectionDir(root, true);
3442
+ const ignore = join3(resolve3(root), SELECTION_GITIGNORE);
3443
+ try {
3444
+ await lstat2(ignore);
3445
+ } catch {
3446
+ await writeFile3(ignore, SELECTION_GITIGNORE_CONTENT, "utf-8");
3447
+ }
3448
+ const file = join3(resolve3(root), path);
3449
+ if (await lstat2(file).then((s) => s.isSymbolicLink(), () => false)) throw new Error(`symlink in model path: ${path}`);
3450
+ await writeFile3(file, content, "utf-8");
3451
+ }
3452
+
3453
+ // ../../packages/node-files/src/gitModel.ts
3454
+ var exec = promisify(execFile);
3455
+ var DEFAULT_BRANCHES = ["origin/main", "origin/master", "main", "master"];
3456
+ async function git(cwd, args) {
3457
+ const { stdout } = await exec("git", args, { cwd, maxBuffer: 256 * 1024 * 1024, encoding: "utf8", windowsHide: true });
3458
+ return stdout.trim();
3459
+ }
3460
+ var gitOk = (cwd, args) => git(cwd, args).catch(() => null);
3461
+ async function resolveGitBase(folder, since) {
3462
+ if (await gitOk(folder, ["rev-parse", "--is-inside-work-tree"]) !== "true") {
3463
+ throw new Error(`${folder} is not in a git repository, so there is no earlier version of the model to compare with.`);
3464
+ }
3465
+ if (since !== void 0) {
3466
+ const commit = since && !since.startsWith("-") ? await gitOk(folder, ["rev-parse", "--verify", "--quiet", `${since}^{commit}`]) : null;
3467
+ if (!commit) throw new Error(`Unknown git ref "${since}": name a branch, tag or commit.`);
3468
+ return { commit, described: since };
3469
+ }
3470
+ if (!await gitOk(folder, ["rev-parse", "--verify", "--quiet", "HEAD"])) {
3471
+ throw new Error("The repository has no commit yet, so there is no earlier version of the model to compare with.");
3472
+ }
3473
+ const originHead = await gitOk(folder, ["symbolic-ref", "--quiet", "--short", "refs/remotes/origin/HEAD"]) ?? void 0;
3474
+ for (const branch of [...originHead ? [originHead] : [], ...DEFAULT_BRANCHES]) {
3475
+ if (!await gitOk(folder, ["rev-parse", "--verify", "--quiet", `${branch}^{commit}`])) continue;
3476
+ const base = await gitOk(folder, ["merge-base", "HEAD", branch]);
3477
+ if (base) return { commit: base, described: `merge base with ${branch}` };
3478
+ }
3479
+ return { commit: await git(folder, ["rev-parse", "HEAD"]), described: "HEAD" };
3480
+ }
3481
+ async function readModelAtCommit(folder, commit) {
3482
+ const listing = await git(folder, ["ls-tree", "-r", "-z", commit, "--", "."]);
3483
+ const blobs = [];
3484
+ for (const entry of listing.split("\0")) {
3485
+ const tab = entry.indexOf(" ");
3486
+ if (tab < 0) continue;
3487
+ const [mode, type, sha] = entry.slice(0, tab).split(" ");
3488
+ const path = entry.slice(tab + 1);
3489
+ if (type !== "blob" || mode === "120000" || !isMdFolderModelPath(path)) continue;
3490
+ if (path.split("/").some((part) => part.startsWith("."))) continue;
3491
+ blobs.push({ sha, path });
3492
+ }
3493
+ if (!blobs.length) return {};
3494
+ const contents = await catFiles(folder, blobs.map((blob) => blob.sha));
3495
+ return Object.fromEntries(blobs.map((blob, i) => [blob.path, contents[i]]));
3496
+ }
3497
+ function catFiles(cwd, shas) {
3498
+ return new Promise((resolve6, reject) => {
3499
+ const child = spawn("git", ["cat-file", "--batch"], { cwd, windowsHide: true });
3500
+ const chunks = [];
3501
+ let stderr = "";
3502
+ child.stdout.on("data", (chunk) => chunks.push(chunk));
3503
+ child.stderr.on("data", (chunk) => {
3504
+ stderr += chunk.toString();
3505
+ });
3506
+ child.on("error", reject);
3507
+ child.on("close", (code) => {
3508
+ if (code !== 0) {
3509
+ reject(new Error(`git cat-file failed: ${stderr.trim()}`));
3510
+ return;
3511
+ }
3512
+ const out = Buffer.concat(chunks);
3513
+ const contents = [];
3514
+ let at = 0;
3515
+ for (const sha of shas) {
3516
+ const end = out.indexOf(10, at);
3517
+ const [gotSha, type, size] = out.subarray(at, end).toString().split(" ");
3518
+ if (gotSha !== sha || type !== "blob") {
3519
+ reject(new Error(`git cat-file: unexpected entry for ${sha}`));
3520
+ return;
3521
+ }
3522
+ const start = end + 1;
3523
+ contents.push(out.subarray(start, start + Number(size)).toString("utf8"));
3524
+ at = start + Number(size) + 1;
3525
+ }
3526
+ resolve6(contents);
3527
+ });
3528
+ child.stdin.end(shas.join("\n") + "\n");
3529
+ });
3530
+ }
3531
+ var currentBranch = (folder) => gitOk(folder, ["symbolic-ref", "--quiet", "--short", "HEAD"]).then((name) => name || null);
3532
+ var byId2 = (items) => Object.fromEntries(items.map((item) => [item.id, item]));
3533
+ async function modelChangesSince(folder, current, since, options = {}) {
3534
+ const base = await resolveGitBase(folder, since);
3535
+ const files = await readModelAtCommit(folder, base.commit);
3536
+ const old = Object.keys(files).length ? deserializeFromMdFolder(files).data : { nodes: [], relations: [] };
3537
+ if (options.saveBase) {
3538
+ const content = serializeModelBase({ commit: base.commit, described: base.described, branch: await currentBranch(folder), nodes: old.nodes, relations: old.relations });
3539
+ await writeEditorStateFile(folder, MODEL_BASE_FILE, content);
3540
+ }
3541
+ const before = { nodes: byId2(old.nodes), relations: byId2(old.relations) };
3542
+ const after = { nodes: byId2(current.nodes), relations: byId2(current.relations) };
3543
+ const report = modelChangeReport(before, after);
3544
+ const short = base.commit.slice(0, 7);
3545
+ const where2 = base.commit.startsWith(base.described) ? short : `${base.described} (${short})`;
3546
+ const count = (group, noun) => `${noun}: ${group.added.length} added, ${group.changed.length} changed, ${group.removed.length} removed`;
3547
+ const text = countModelChanges(report) === 0 ? `No model changes since ${where2}: the elements and relations are as they were (views and layout are not compared).` : [
3548
+ `Model changes since ${where2}, uncommitted edits included; elements and relations only, views and layout left out.`,
3549
+ `${count(report.elements, "Elements")}. ${count(report.relations, "Relations")}.${Object.keys(files).length ? "" : " The folder held no model then."}`,
3550
+ "",
3551
+ formatModelChanges(report, before, after)
3552
+ ].join("\n");
3553
+ return { base, report, text };
3554
+ }
3555
+
3556
+ // src/diff.ts
3557
+ var DIFF_USAGE = `Usage: radical diff [folder] [options]
3558
+
3559
+ Lists what changed in a Radical Markdown model folder since its version in
3560
+ git: the elements and relations added, removed and changed, uncommitted edits
3561
+ included, with each changed field's old and new value and each element's
3562
+ place and relations. Only the model is compared; views, positions, sizes and
3563
+ folding are left out. The MCP server's get_changes tool gives the same list.
3564
+
3565
+ folder the model folder (default: the working directory)
3566
+ --since <ref> the git branch, tag or commit to compare with (default:
3567
+ the merge base with the default branch, origin/main)
3568
+ --format <format> text (default) or json
3569
+ --save-base also save the model at the base to .radical/base.json in
3570
+ the folder, for Studio to show the changes (radical hooks
3571
+ install keeps it fresh)
3572
+ --quiet with --save-base: print nothing
3573
+
3574
+ Exit status: 0 the list was written, 2 it could not be made.`;
3575
+ async function diffCommand(args, io2) {
3576
+ let parsed;
3577
+ try {
3578
+ parsed = parseArgs2({
3579
+ args,
3580
+ allowPositionals: true,
3581
+ options: {
3582
+ since: { type: "string" },
3583
+ format: { type: "string", default: "text" },
3584
+ "save-base": { type: "boolean", default: false },
3585
+ quiet: { type: "boolean", default: false },
3586
+ help: { type: "boolean", short: "h", default: false }
3587
+ }
3588
+ });
3589
+ } catch (error) {
3590
+ io2.err(`${error.message}
3591
+
3592
+ ${DIFF_USAGE}`);
3593
+ return 2;
3594
+ }
3595
+ const { values, positionals } = parsed;
3596
+ if (values.help) {
3597
+ io2.out(DIFF_USAGE);
3598
+ return 0;
3599
+ }
3600
+ if (positionals.length > 1 || !["text", "json"].includes(values.format)) {
3601
+ io2.err(DIFF_USAGE);
3602
+ return 2;
3603
+ }
3604
+ const folder = positionals[0] ?? ".";
3605
+ try {
3606
+ const root = await realpath2(resolve4(io2.cwd, folder));
3607
+ if (!(await stat3(root)).isDirectory()) throw new Error("not a directory");
3608
+ const data = deserializeFromMdFolder(await new MdFolderSession(diskFolderStorage(root)).readAll()).data;
3609
+ const changes = await modelChangesSince(root, data, values.since, { saveBase: values["save-base"] });
3610
+ if (values.quiet && values["save-base"]) return 0;
3611
+ if (values["save-base"]) io2.err(`Saved the base (${changes.base.commit.slice(0, 7)}) to ${folder}/.radical/base.json.`);
3612
+ io2.out(values.format === "json" ? JSON.stringify({ base: changes.base, ...changes.report }, null, 2) : changes.text);
3613
+ return 0;
3614
+ } catch (error) {
3615
+ io2.err(`radical diff: ${folder}: ${error.message}`);
3616
+ return 2;
3617
+ }
3618
+ }
3619
+
3620
+ // src/hooks.ts
3621
+ import { chmod, mkdir as mkdir4, readFile as readFile4, realpath as realpath3, stat as stat4, writeFile as writeFile4 } from "fs/promises";
3622
+ import { execFile as execFile2 } from "child_process";
3623
+ import { relative, resolve as resolve5 } from "path";
3624
+ import { parseArgs as parseArgs3, promisify as promisify2 } from "util";
3625
+ var exec2 = promisify2(execFile2);
3626
+ var HOOKS_USAGE = `Usage: radical hooks install [folder] [options]
3627
+
3628
+ Adds a line to the repository's post-checkout, post-commit, post-merge and
3629
+ post-rewrite git hooks that saves the model folder's base (radical diff
3630
+ --save-base) after a checkout, a commit, a pull or merge and a rebase, so
3631
+ Studio shows the changes of the branch checked out without anyone running
3632
+ it. What the hooks already do stays; running it again adds nothing, but
3633
+ brings the line up to date when the CLI or node has moved.
3634
+
3635
+ folder the model folder (default: the working directory)
3636
+
3637
+ Exit status: 0 the hooks hold the line, 2 they could not be written.`;
3638
+ var HOOK_NAMES = ["post-checkout", "post-commit", "post-merge", "post-rewrite"];
3639
+ var HOOK_MARKER = "# radical: save the model base for Studio";
3640
+ var quote2 = (text) => `"${text.replace(/\\/g, "/").replace(/(["$`])/g, "\\$1")}"`;
3641
+ async function hooksCommand(args, io2) {
3642
+ let parsed;
3643
+ try {
3644
+ parsed = parseArgs3({ args, allowPositionals: true, options: { help: { type: "boolean", short: "h", default: false } } });
3645
+ } catch (error) {
3646
+ io2.err(`${error.message}
3647
+
3648
+ ${HOOKS_USAGE}`);
3649
+ return 2;
3650
+ }
3651
+ const { values, positionals } = parsed;
3652
+ if (values.help) {
3653
+ io2.out(HOOKS_USAGE);
3654
+ return 0;
3655
+ }
3656
+ const [action, folder = ".", ...rest] = positionals;
3657
+ if (action !== "install" || rest.length) {
3658
+ io2.err(HOOKS_USAGE);
3659
+ return 2;
3660
+ }
3661
+ try {
3662
+ const root = await realpath3(resolve5(io2.cwd, folder));
3663
+ if (!(await stat4(root)).isDirectory()) throw new Error("not a directory");
3664
+ const git2 = async (...gitArgs) => (await exec2("git", gitArgs, { cwd: root, windowsHide: true })).stdout.trim();
3665
+ const top = await realpath3(await git2("rev-parse", "--show-toplevel").catch(() => {
3666
+ throw new Error("is not in a git repository");
3667
+ }));
3668
+ const hooksDir = resolve5(root, await git2("rev-parse", "--git-path", "hooks"));
3669
+ await mkdir4(hooksDir, { recursive: true });
3670
+ const line = `${io2.command ?? "radical"} diff ${quote2(relative(top, root) || ".")} --save-base --quiet || true`;
3671
+ const written = [];
3672
+ const updated = [];
3673
+ for (const name of HOOK_NAMES) {
3674
+ const path = resolve5(hooksDir, name);
3675
+ const old = await readFile4(path, "utf8").catch(() => null);
3676
+ if (old?.includes(HOOK_MARKER)) {
3677
+ const lines = old.split("\n");
3678
+ const at = lines.indexOf(HOOK_MARKER);
3679
+ if (lines[at + 1] === line) continue;
3680
+ lines[at + 1] = line;
3681
+ await writeFile4(path, lines.join("\n"));
3682
+ updated.push(name);
3683
+ continue;
3684
+ }
3685
+ const head = old === null ? "#!/bin/sh\n" : old.endsWith("\n") ? old : `${old}
3686
+ `;
3687
+ await writeFile4(path, `${head}${HOOK_MARKER}
3688
+ ${line}
3689
+ `);
3690
+ await chmod(path, 493);
3691
+ written.push(name);
3692
+ }
3693
+ const where2 = relative(io2.cwd, hooksDir) || hooksDir;
3694
+ io2.out(written.length ? `Added to ${written.join(", ")} in ${where2}: ${line}` : updated.length ? `Updated in ${updated.join(", ")} in ${where2}: ${line}` : "The hooks already save the base; nothing changed.");
3695
+ return 0;
3696
+ } catch (error) {
3697
+ io2.err(`radical hooks: ${folder}: ${error.message}`);
3698
+ return 2;
3699
+ }
3700
+ }
3701
+
3702
+ // package.json
3703
+ var version = "0.1.0";
3704
+
3705
+ // src/cli.ts
3706
+ var USAGE = `Usage: radical <command> [options]
3707
+
3708
+ Commands:
3709
+ check [folder] check a Radical Markdown model folder (radical check --help)
3710
+ diff [folder] what changed in the model since its version in git
3711
+ (radical diff --help)
3712
+ hooks install git hooks that keep the base Studio compares with
3713
+ (radical hooks --help)
3714
+
3715
+ --version print the version`;
3716
+ async function main(args, io2) {
3717
+ const [command, ...rest] = args;
3718
+ if (command === "check") return checkCommand(rest, io2);
3719
+ if (command === "diff") return diffCommand(rest, io2);
3720
+ if (command === "hooks") return hooksCommand(rest, io2);
3721
+ if (command === "--version" || command === "-v") {
3722
+ io2.out(version);
3723
+ return 0;
3724
+ }
3725
+ if (command === void 0 || command === "--help" || command === "-h" || command === "help") {
3726
+ io2.out(rest[0] === "check" ? CHECK_USAGE : rest[0] === "diff" ? DIFF_USAGE : rest[0] === "hooks" ? HOOKS_USAGE : USAGE);
3727
+ return 0;
3728
+ }
3729
+ io2.err(`Unknown command: ${command}
3730
+
3731
+ ${USAGE}`);
3732
+ return 2;
3733
+ }
3734
+
3735
+ // src/index.ts
3736
+ var io = {
3737
+ cwd: process.cwd(),
3738
+ out: (text) => {
3739
+ process.stdout.write(text + "\n");
3740
+ },
3741
+ err: (text) => {
3742
+ process.stderr.write(text + "\n");
3743
+ },
3744
+ // The hooks run this very script with the node on the PATH, else the one
3745
+ // running now (a versioned path that an upgrade of node may remove).
3746
+ command: `"$(command -v node || echo '${process.execPath.replace(/\\/g, "/")}')" "${process.argv[1].replace(/\\/g, "/")}"`
3747
+ };
3748
+ main(process.argv.slice(2), io).then(
3749
+ (code) => {
3750
+ process.exitCode = code;
3751
+ },
3752
+ (error) => {
3753
+ io.err(`radical: ${error instanceof Error ? error.stack ?? error.message : String(error)}`);
3754
+ process.exitCode = 2;
3755
+ }
3756
+ );