@radicaltools/mcp 0.3.0 → 0.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (58) hide show
  1. package/dist/{chunk-Z7THA3L5.js → chunk-2SZDTOYJ.js} +65 -33
  2. package/dist/{elkLayout-TAUBPPVN.js → elkLayout-VYJDCCIT.js} +1 -1
  3. package/dist/hub-catalogue/concern/concern-api-collections.radical +1136 -0
  4. package/dist/hub-catalogue/concern/concern-api-errors.radical +1180 -0
  5. package/dist/hub-catalogue/concern/concern-api-evolution.radical +449 -210
  6. package/dist/hub-catalogue/concern/concern-api-idempotency.radical +1218 -0
  7. package/dist/hub-catalogue/concern/concern-api-resource-design.radical +1102 -0
  8. package/dist/hub-catalogue/concern/concern-api-style-guide.radical +1210 -0
  9. package/dist/hub-catalogue/concern/concern-architecture-style.radical +287 -131
  10. package/dist/hub-catalogue/concern/concern-audit-trail.radical +1096 -0
  11. package/dist/hub-catalogue/concern/concern-authentication.radical +247 -37
  12. package/dist/hub-catalogue/concern/concern-authorization.radical +311 -89
  13. package/dist/hub-catalogue/concern/concern-availability.radical +287 -63
  14. package/dist/hub-catalogue/concern/concern-backend-stack.radical +300 -381
  15. package/dist/hub-catalogue/concern/concern-backup-recovery.radical +385 -129
  16. package/dist/hub-catalogue/concern/concern-caching.radical +1294 -0
  17. package/dist/hub-catalogue/concern/concern-capacity.radical +194 -81
  18. package/dist/hub-catalogue/concern/concern-code-documentation.radical +1397 -0
  19. package/dist/hub-catalogue/concern/concern-code-quality-gate.radical +1409 -0
  20. package/dist/hub-catalogue/concern/concern-code-review-branching.radical +1416 -0
  21. package/dist/hub-catalogue/concern/concern-code-style.radical +1058 -0
  22. package/dist/hub-catalogue/concern/concern-communication-style.radical +473 -167
  23. package/dist/hub-catalogue/concern/concern-data-classification.radical +970 -0
  24. package/dist/hub-catalogue/concern/concern-data-consistency.radical +339 -308
  25. package/dist/hub-catalogue/concern/concern-data-store.radical +480 -158
  26. package/dist/hub-catalogue/concern/concern-decomposition.radical +260 -85
  27. package/dist/hub-catalogue/concern/concern-definition-of-done.radical +1214 -0
  28. package/dist/hub-catalogue/concern/concern-delivery-metrics.radical +966 -0
  29. package/dist/hub-catalogue/concern/concern-dependency-hygiene.radical +1345 -0
  30. package/dist/hub-catalogue/concern/concern-deployment.radical +343 -92
  31. package/dist/hub-catalogue/concern/concern-encryption.radical +339 -76
  32. package/dist/hub-catalogue/concern/concern-error-handling-logging.radical +1197 -0
  33. package/dist/hub-catalogue/concern/concern-eu-dora.radical +1321 -0
  34. package/dist/hub-catalogue/concern/concern-frontend-stack.radical +467 -160
  35. package/dist/hub-catalogue/concern/concern-incident-management.radical +1204 -0
  36. package/dist/hub-catalogue/concern/concern-infrastructure.radical +1300 -268
  37. package/dist/hub-catalogue/concern/concern-integration-resilience.radical +88 -51
  38. package/dist/hub-catalogue/concern/concern-messaging.radical +173 -140
  39. package/dist/hub-catalogue/concern/concern-module-boundaries.radical +162 -159
  40. package/dist/hub-catalogue/concern/concern-observability.radical +224 -275
  41. package/dist/hub-catalogue/concern/concern-operational-readiness.radical +1249 -0
  42. package/dist/hub-catalogue/concern/concern-personal-data.radical +637 -122
  43. package/dist/hub-catalogue/concern/concern-quality-priorities.radical +1091 -0
  44. package/dist/hub-catalogue/concern/concern-rate-limiting.radical +433 -141
  45. package/dist/hub-catalogue/concern/concern-release-versioning.radical +1358 -0
  46. package/dist/hub-catalogue/concern/concern-retention.radical +1399 -0
  47. package/dist/hub-catalogue/concern/concern-secrets.radical +332 -74
  48. package/dist/hub-catalogue/concern/concern-secure-coding.radical +1379 -0
  49. package/dist/hub-catalogue/concern/concern-secure-development.radical +1245 -0
  50. package/dist/hub-catalogue/concern/concern-security-detection.radical +1153 -0
  51. package/dist/hub-catalogue/concern/concern-supply-chain.radical +257 -183
  52. package/dist/hub-catalogue/concern/concern-technical-debt.radical +1450 -0
  53. package/dist/hub-catalogue/concern/concern-technology-lifecycle.radical +1145 -0
  54. package/dist/hub-catalogue/concern/concern-tenant-isolation.radical +271 -137
  55. package/dist/hub-catalogue/concern/concern-test-strategy.radical +243 -224
  56. package/dist/hub-catalogue/concern/concern-threat-modelling.radical +1143 -0
  57. package/dist/index.js +1001 -230
  58. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -1,13 +1,18 @@
1
1
  #!/usr/bin/env node
2
2
  import {
3
+ CANVAS_MAX_ELEMENTS,
3
4
  COLLAPSED_HEIGHT,
4
5
  COLLAPSED_WIDTH,
5
6
  ELK_CHILD_SPACING,
6
7
  ELK_ROOT_SPACING,
8
+ FITNESS_CHARACTERISTICS,
9
+ FITNESS_CLASSIFICATION_PROPERTIES,
10
+ FITNESS_TRIGGERS,
7
11
  GROUP_TYPE,
8
12
  LAYOUT_AXES,
9
13
  LAYOUT_FLOWS,
10
14
  LAYOUT_ROLES,
15
+ METRICS_PROPERTIES,
11
16
  NODE_SIZES,
12
17
  RADICAL_METAMODEL_NAME,
13
18
  WIKI_DEPTH_MAX,
@@ -80,7 +85,7 @@ import {
80
85
  viewShowsEveryNode,
81
86
  wikiDepthOf,
82
87
  withCanvasPositions
83
- } from "./chunk-Z7THA3L5.js";
88
+ } from "./chunk-2SZDTOYJ.js";
84
89
 
85
90
  // ../../node_modules/webcola/dist/src/powergraph.js
86
91
  var require_powergraph = __commonJS({
@@ -2288,12 +2293,12 @@ var require_pqueue = __commonJS({
2288
2293
  "use strict";
2289
2294
  init_define_RADICAL_BUILD();
2290
2295
  Object.defineProperty(exports, "__esModule", { value: true });
2291
- var PairingHeap = (function() {
2292
- function PairingHeap2(elem) {
2296
+ var PairingHeap2 = (function() {
2297
+ function PairingHeap3(elem) {
2293
2298
  this.elem = elem;
2294
2299
  this.subheaps = [];
2295
2300
  }
2296
- PairingHeap2.prototype.toString = function(selector) {
2301
+ PairingHeap3.prototype.toString = function(selector) {
2297
2302
  var str = "", needComma = false;
2298
2303
  for (var i = 0; i < this.subheaps.length; ++i) {
2299
2304
  var subheap = this.subheaps[i];
@@ -2312,7 +2317,7 @@ var require_pqueue = __commonJS({
2312
2317
  }
2313
2318
  return (this.elem ? selector(this.elem) : "") + str;
2314
2319
  };
2315
- PairingHeap2.prototype.forEach = function(f) {
2320
+ PairingHeap3.prototype.forEach = function(f) {
2316
2321
  if (!this.empty()) {
2317
2322
  f(this.elem, this);
2318
2323
  this.subheaps.forEach(function(s) {
@@ -2320,18 +2325,18 @@ var require_pqueue = __commonJS({
2320
2325
  });
2321
2326
  }
2322
2327
  };
2323
- PairingHeap2.prototype.count = function() {
2328
+ PairingHeap3.prototype.count = function() {
2324
2329
  return this.empty() ? 0 : 1 + this.subheaps.reduce(function(n, h) {
2325
2330
  return n + h.count();
2326
2331
  }, 0);
2327
2332
  };
2328
- PairingHeap2.prototype.min = function() {
2333
+ PairingHeap3.prototype.min = function() {
2329
2334
  return this.elem;
2330
2335
  };
2331
- PairingHeap2.prototype.empty = function() {
2336
+ PairingHeap3.prototype.empty = function() {
2332
2337
  return this.elem == null;
2333
2338
  };
2334
- PairingHeap2.prototype.contains = function(h) {
2339
+ PairingHeap3.prototype.contains = function(h) {
2335
2340
  if (this === h)
2336
2341
  return true;
2337
2342
  for (var i = 0; i < this.subheaps.length; i++) {
@@ -2340,16 +2345,16 @@ var require_pqueue = __commonJS({
2340
2345
  }
2341
2346
  return false;
2342
2347
  };
2343
- PairingHeap2.prototype.isHeap = function(lessThan) {
2348
+ PairingHeap3.prototype.isHeap = function(lessThan) {
2344
2349
  var _this = this;
2345
2350
  return this.subheaps.every(function(h) {
2346
2351
  return lessThan(_this.elem, h.elem) && h.isHeap(lessThan);
2347
2352
  });
2348
2353
  };
2349
- PairingHeap2.prototype.insert = function(obj, lessThan) {
2350
- return this.merge(new PairingHeap2(obj), lessThan);
2354
+ PairingHeap3.prototype.insert = function(obj, lessThan) {
2355
+ return this.merge(new PairingHeap3(obj), lessThan);
2351
2356
  };
2352
- PairingHeap2.prototype.merge = function(heap2, lessThan) {
2357
+ PairingHeap3.prototype.merge = function(heap2, lessThan) {
2353
2358
  if (this.empty())
2354
2359
  return heap2;
2355
2360
  else if (heap2.empty())
@@ -2362,15 +2367,15 @@ var require_pqueue = __commonJS({
2362
2367
  return heap2;
2363
2368
  }
2364
2369
  };
2365
- PairingHeap2.prototype.removeMin = function(lessThan) {
2370
+ PairingHeap3.prototype.removeMin = function(lessThan) {
2366
2371
  if (this.empty())
2367
2372
  return null;
2368
2373
  else
2369
2374
  return this.mergePairs(lessThan);
2370
2375
  };
2371
- PairingHeap2.prototype.mergePairs = function(lessThan) {
2376
+ PairingHeap3.prototype.mergePairs = function(lessThan) {
2372
2377
  if (this.subheaps.length == 0)
2373
- return new PairingHeap2(null);
2378
+ return new PairingHeap3(null);
2374
2379
  else if (this.subheaps.length == 1) {
2375
2380
  return this.subheaps[0];
2376
2381
  } else {
@@ -2379,22 +2384,22 @@ var require_pqueue = __commonJS({
2379
2384
  return firstPair.merge(remaining, lessThan);
2380
2385
  }
2381
2386
  };
2382
- PairingHeap2.prototype.decreaseKey = function(subheap, newValue, setHeapNode, lessThan) {
2387
+ PairingHeap3.prototype.decreaseKey = function(subheap, newValue, setHeapNode, lessThan) {
2383
2388
  var newHeap = subheap.removeMin(lessThan);
2384
2389
  subheap.elem = newHeap.elem;
2385
2390
  subheap.subheaps = newHeap.subheaps;
2386
2391
  if (setHeapNode !== null && newHeap.elem !== null) {
2387
2392
  setHeapNode(subheap.elem, subheap);
2388
2393
  }
2389
- var pairingNode = new PairingHeap2(newValue);
2394
+ var pairingNode = new PairingHeap3(newValue);
2390
2395
  if (setHeapNode !== null) {
2391
2396
  setHeapNode(newValue, pairingNode);
2392
2397
  }
2393
2398
  return this.merge(pairingNode, lessThan);
2394
2399
  };
2395
- return PairingHeap2;
2400
+ return PairingHeap3;
2396
2401
  })();
2397
- exports.PairingHeap = PairingHeap;
2402
+ exports.PairingHeap = PairingHeap2;
2398
2403
  var PriorityQueue = (function() {
2399
2404
  function PriorityQueue2(lessThan) {
2400
2405
  this.lessThan = lessThan;
@@ -2412,7 +2417,7 @@ var require_pqueue = __commonJS({
2412
2417
  }
2413
2418
  var pairingNode;
2414
2419
  for (var i = 0, arg; arg = args[i]; ++i) {
2415
- pairingNode = new PairingHeap(arg);
2420
+ pairingNode = new PairingHeap2(arg);
2416
2421
  this.root = this.empty() ? pairingNode : this.root.merge(pairingNode, this.lessThan);
2417
2422
  }
2418
2423
  return pairingNode;
@@ -5237,7 +5242,7 @@ function relationIndex(ctx) {
5237
5242
  if (own) return own;
5238
5243
  const cacheable = Object.isFrozen(ctx.relations) && Object.isFrozen(ctx.nodes);
5239
5244
  const cached = cacheable ? indexCache.get(ctx.relations) : void 0;
5240
- if (cached && cached.nodes === ctx.nodes) {
5245
+ if (cached && sameForChain(cached.nodes, ctx.nodes, "parentId")) {
5241
5246
  ctxIndex.set(ctx, cached.index);
5242
5247
  return cached.index;
5243
5248
  }
@@ -5370,8 +5375,15 @@ function ofTypes(way, n) {
5370
5375
  function followWay(node, way, ctx) {
5371
5376
  return way.via ? followVia(node, way.via, ctx).filter((n) => ofTypes(way, n)) : [];
5372
5377
  }
5378
+ function nodeList(nodes) {
5379
+ if (!Object.isFrozen(nodes)) return Object.values(nodes);
5380
+ let list = nodeLists.get(nodes);
5381
+ if (!list) nodeLists.set(nodes, list = Object.freeze(Object.values(nodes)));
5382
+ return list;
5383
+ }
5384
+ var nodeLists = /* @__PURE__ */ new WeakMap();
5373
5385
  function pipelineSource(view, ctx) {
5374
- const all = Object.values(ctx.nodes);
5386
+ const all = nodeList(ctx.nodes);
5375
5387
  if (!view || viewShowsEveryNode(view)) return all;
5376
5388
  const ids = new Set(view.nodeIds);
5377
5389
  return all.filter((n) => ids.has(n.id));
@@ -5462,16 +5474,125 @@ function viewShownNodes(view, nodes, relations) {
5462
5474
  const cacheable = Object.isFrozen(nodes) && Object.isFrozen(relations) && Object.isFrozen(view.nodeIds);
5463
5475
  if (cacheable) {
5464
5476
  const hit = shownCache.get(view.nodeIds);
5465
- if (hit && hit.nodes === nodes && hit.relations === relations && hit.pipeline === view.pipeline && hit.kind === view.kind && hit.empty === view.empty) return hit.shown;
5477
+ if (hit && hit.relations === relations && hit.pipeline === view.pipeline && hit.kind === view.kind && hit.empty === view.empty && sameForChain(hit.nodes, nodes, chainKeys(view.pipeline))) return hit.shown;
5466
5478
  }
5467
5479
  const shown = computeShownNodes(view, nodes, relations);
5468
5480
  if (cacheable) shownCache.set(view.nodeIds, { nodes, relations, pipeline: view.pipeline, kind: view.kind, empty: view.empty, shown });
5469
5481
  return shown;
5470
5482
  }
5471
5483
  var shownCache = /* @__PURE__ */ new WeakMap();
5484
+ function chainKeys(pipeline) {
5485
+ if (!pipeline || typeof pipeline !== "object") return BASE_KEYS;
5486
+ const known = keysOfChain.get(pipeline);
5487
+ if (known) return known;
5488
+ const keys = new Set(BASE_KEYS.split(","));
5489
+ const walk = (v) => {
5490
+ if (Array.isArray(v)) {
5491
+ v.forEach(walk);
5492
+ return;
5493
+ }
5494
+ if (!v || typeof v !== "object") return;
5495
+ const o = v;
5496
+ if (o.kind === "text") for (const k of ["label", "description", "technology"]) keys.add(k);
5497
+ if (o.kind === "property" && typeof o.key === "string") keys.add(o.key);
5498
+ Object.values(o).forEach(walk);
5499
+ };
5500
+ walk(pipeline);
5501
+ const out = [...keys].join(",");
5502
+ keysOfChain.set(pipeline, out);
5503
+ return out;
5504
+ }
5505
+ var BASE_KEYS = "type,parentId";
5506
+ var keysOfChain = /* @__PURE__ */ new WeakMap();
5507
+ function sameForChain(a, b, keys) {
5508
+ if (a === b) return true;
5509
+ let byB = sameAnswers.get(a);
5510
+ if (!byB) sameAnswers.set(a, byB = /* @__PURE__ */ new WeakMap());
5511
+ let byKeys = byB.get(b);
5512
+ if (!byKeys) byB.set(b, byKeys = /* @__PURE__ */ new Map());
5513
+ const hit = byKeys.get(keys);
5514
+ if (hit !== void 0) return hit;
5515
+ const same3 = compareFor(a, b, keys.split(","));
5516
+ byKeys.set(keys, same3);
5517
+ return same3;
5518
+ }
5519
+ var sameAnswers = /* @__PURE__ */ new WeakMap();
5520
+ function compareFor(a, b, keys) {
5521
+ const listA = nodeList(a);
5522
+ const listB = nodeList(b);
5523
+ if (listA.length !== listB.length) return false;
5524
+ for (const y of listB) {
5525
+ const x = a[y.id];
5526
+ if (x === y) continue;
5527
+ if (!x || keys.some((k) => x[k] !== y[k])) return false;
5528
+ }
5529
+ return true;
5530
+ }
5531
+ function hash2(text2) {
5532
+ let a = 2166136261;
5533
+ let b = 16777619 ^ 1540483477;
5534
+ for (let i = 0; i < text2.length; i++) {
5535
+ const c = text2.charCodeAt(i);
5536
+ a = Math.imul(a ^ c, 16777619);
5537
+ b = Math.imul(b ^ c, 1540483477);
5538
+ }
5539
+ return [a >>> 0, b >>> 0];
5540
+ }
5541
+ var structures = /* @__PURE__ */ new WeakMap();
5542
+ function modelStructure(nodes, relations) {
5543
+ const known = structures.get(nodes)?.get(relations);
5544
+ if (known) return known;
5545
+ let n = 0, a = 0, b = 0, r = 0, c = 0, d = 0;
5546
+ for (const node of Object.values(nodes)) {
5547
+ const [x, y] = hash2(`${node.id}${node.type}${node.parentId ?? ""}`);
5548
+ a = a + x | 0;
5549
+ b = b + y | 0;
5550
+ n++;
5551
+ }
5552
+ for (const rel of Array.isArray(relations) ? relations : Object.values(relations)) {
5553
+ const [x, y] = hash2(`${rel.id}${rel.sourceId}${rel.targetId}${rel.relationType ?? ""}`);
5554
+ c = c + x | 0;
5555
+ d = d + y | 0;
5556
+ r++;
5557
+ }
5558
+ const out = `${n}.${a >>> 0}.${b >>> 0}:${r}.${c >>> 0}.${d >>> 0}`;
5559
+ if (Object.isFrozen(nodes) && Object.isFrozen(relations)) {
5560
+ let byRelations = structures.get(nodes);
5561
+ if (!byRelations) structures.set(nodes, byRelations = /* @__PURE__ */ new WeakMap());
5562
+ byRelations.set(relations, out);
5563
+ }
5564
+ return out;
5565
+ }
5566
+ var indexKeys = /* @__PURE__ */ new WeakMap();
5567
+ function viewIndexKey(view) {
5568
+ const known = indexKeys.get(view);
5569
+ if (known !== void 0) return known;
5570
+ const pipeline = pipelineOf(view);
5571
+ const key = !pipeline?.levels?.length || view.kind === "dynamic" || chainKeys(view.pipeline) !== BASE_KEYS ? null : hash2(JSON.stringify([view.pipeline, view.kind ?? null, !!view.empty, view.nodeIds])).join(".");
5572
+ indexKeys.set(view, key);
5573
+ return key;
5574
+ }
5575
+ var preset = null;
5576
+ function fromViewIndex(view, nodes, relations) {
5577
+ if (!preset || preset.off) return void 0;
5578
+ const key = viewIndexKey(view);
5579
+ const list = key ? preset.index.views[key] : void 0;
5580
+ if (!list) return void 0;
5581
+ const fits = preset.fits;
5582
+ if (!(fits && fits.relations === relations && sameForChain(fits.nodes, nodes, BASE_KEYS))) {
5583
+ if (!Object.isFrozen(nodes) || !Object.isFrozen(relations)) return void 0;
5584
+ if (modelStructure(nodes, relations) !== preset.index.structure) {
5585
+ preset.off = true;
5586
+ return void 0;
5587
+ }
5588
+ preset.fits = { nodes, relations };
5589
+ }
5590
+ const ids = preset.index.ids;
5591
+ return new Set(list.map((i) => ids[i]));
5592
+ }
5472
5593
  function computeShownNodes(view, nodes, relations) {
5473
5594
  if (pipelineOf(view)?.levels?.length && view.kind !== "dynamic") {
5474
- return new Set(runPipeline(view, { nodes, relations, metamodel: NO_METAMODEL }).nodes.map((n) => n.id));
5595
+ return fromViewIndex(view, nodes, relations) ?? new Set(runPipeline(view, { nodes, relations, metamodel: NO_METAMODEL }).nodes.map((n) => n.id));
5475
5596
  }
5476
5597
  if (viewShowsEveryNode(view)) return void 0;
5477
5598
  return new Set(view.nodeIds.filter((id) => id in nodes));
@@ -5579,28 +5700,28 @@ function documentMetamodel(stored, nodes) {
5579
5700
  const c4 = builtInC4Metamodel();
5580
5701
  return nodes?.some((n) => !c4.nodeTypes[n.type]) ? builtInGovernanceMetamodel() : c4;
5581
5702
  }
5582
- const preset = stored.id === "c4-builtin" ? builtInC4Metamodel() : stored.id === "c4-ddd-builtin" || stored.id === "c4-ddd-governance-builtin" ? builtInGovernanceMetamodel() : null;
5583
- if (!preset) return stored;
5584
- const withViewpoints = withPresetViewpoints(preset, stored);
5585
- const extraNodeTypes = Object.entries(stored.nodeTypes ?? {}).filter(([id, def]) => !preset.nodeTypes[id] && def && typeof def === "object");
5586
- const extraRelationTypes = Object.entries(stored.relationTypes ?? {}).filter(([id, def]) => !preset.relationTypes[id] && def && typeof def === "object");
5703
+ const preset2 = stored.id === "c4-builtin" ? builtInC4Metamodel() : stored.id === "c4-ddd-builtin" || stored.id === "c4-ddd-governance-builtin" ? builtInGovernanceMetamodel() : null;
5704
+ if (!preset2) return stored;
5705
+ const withViewpoints = withPresetViewpoints(preset2, stored);
5706
+ const extraNodeTypes = Object.entries(stored.nodeTypes ?? {}).filter(([id, def]) => !preset2.nodeTypes[id] && def && typeof def === "object");
5707
+ const extraRelationTypes = Object.entries(stored.relationTypes ?? {}).filter(([id, def]) => !preset2.relationTypes[id] && def && typeof def === "object");
5587
5708
  if (!extraNodeTypes.length && !extraRelationTypes.length) return withViewpoints;
5588
- const custom = forkPresetMetamodel({ ...withViewpoints, id: preset.id }) ?? withViewpoints;
5709
+ const custom = forkPresetMetamodel({ ...withViewpoints, id: preset2.id }) ?? withViewpoints;
5589
5710
  return {
5590
5711
  ...custom,
5591
5712
  nodeTypes: { ...custom.nodeTypes, ...Object.fromEntries(extraNodeTypes) },
5592
5713
  relationTypes: { ...custom.relationTypes, ...Object.fromEntries(extraRelationTypes) }
5593
5714
  };
5594
5715
  }
5595
- function withPresetViewpoints(preset, stored) {
5716
+ function withPresetViewpoints(preset2, stored) {
5596
5717
  const own = Array.isArray(stored.viewpoints) ? stored.viewpoints : [];
5597
5718
  const removed = new Set(Array.isArray(stored.removedViewpoints) ? stored.removedViewpoints : []);
5598
- if (!own.length && !removed.size) return preset;
5719
+ if (!own.length && !removed.size) return preset2;
5599
5720
  const byId4 = new Map(own.map((v) => [v.id, v]));
5600
- const fromPreset = (preset.viewpoints ?? []).filter((v) => !removed.has(v.id)).map((v) => byId4.get(v.id) ?? v);
5601
- const presetIds = new Set((preset.viewpoints ?? []).map((v) => v.id));
5721
+ const fromPreset = (preset2.viewpoints ?? []).filter((v) => !removed.has(v.id)).map((v) => byId4.get(v.id) ?? v);
5722
+ const presetIds = new Set((preset2.viewpoints ?? []).map((v) => v.id));
5602
5723
  const viewpoints = [...fromPreset, ...own.filter((v) => !presetIds.has(v.id))];
5603
- return { ...preset, viewpoints, ...removed.size ? { removedViewpoints: [...removed] } : {} };
5724
+ return { ...preset2, viewpoints, ...removed.size ? { removedViewpoints: [...removed] } : {} };
5604
5725
  }
5605
5726
  var PRESET_IDS = /* @__PURE__ */ new Set(["c4-builtin", "c4-ddd-governance-builtin"]);
5606
5727
  function forkPresetMetamodel(mm) {
@@ -5608,7 +5729,10 @@ function forkPresetMetamodel(mm) {
5608
5729
  const copy = JSON.parse(JSON.stringify(mm));
5609
5730
  return { ...copy, id: `${mm.id.replace(/-builtin$/, "")}-custom`, name: `${mm.name} (custom)` };
5610
5731
  }
5611
- function descendantIds(id, nodes) {
5732
+ function childrenByParent(nodes) {
5733
+ const frozen = Object.isFrozen(nodes);
5734
+ const known = frozen ? childrenCache.get(nodes) : void 0;
5735
+ if (known) return known;
5612
5736
  const children2 = /* @__PURE__ */ new Map();
5613
5737
  for (const n of Object.values(nodes)) {
5614
5738
  if (!n.parentId) continue;
@@ -5616,6 +5740,12 @@ function descendantIds(id, nodes) {
5616
5740
  if (list) list.push(n.id);
5617
5741
  else children2.set(n.parentId, [n.id]);
5618
5742
  }
5743
+ if (frozen) childrenCache.set(nodes, children2);
5744
+ return children2;
5745
+ }
5746
+ var childrenCache = /* @__PURE__ */ new WeakMap();
5747
+ function descendantIds(id, nodes) {
5748
+ const children2 = childrenByParent(nodes);
5619
5749
  const out = [];
5620
5750
  const stack = [...children2.get(id) ?? []];
5621
5751
  while (stack.length) {
@@ -6226,7 +6356,7 @@ function planViewGroups(state) {
6226
6356
  const groups = new Map(views.filter((v) => isViewGroup(v, state.metamodel)).map((v) => [v.id, v]));
6227
6357
  const members = /* @__PURE__ */ new Map();
6228
6358
  const refolder = [];
6229
- const rename = [];
6359
+ const rename2 = [];
6230
6360
  for (const v of views) {
6231
6361
  if (!v.partOf) continue;
6232
6362
  const group = groups.get(v.partOf);
@@ -6240,7 +6370,7 @@ function planViewGroups(state) {
6240
6370
  seen.add(node.id);
6241
6371
  members.set(v.partOf, seen);
6242
6372
  if ((v.folder ?? "") !== (group.folder ?? "")) refolder.push(v.id);
6243
- if (v.name !== subjectViewName(node, def)) rename.push(v.id);
6373
+ if (v.name !== subjectViewName(node, def)) rename2.push(v.id);
6244
6374
  }
6245
6375
  const unlist = views.filter((v) => v.partOf ? !remove2.includes(v.id) && (v.nodeIds.length > 0 || v.empty) : groups.has(v.id) && (v.nodeIds.length > 0 || v.empty || Object.keys(v.positions ?? {}).length > 0 || v.viewport)).map((v) => v.id);
6246
6376
  for (const group of groups.values()) {
@@ -6250,12 +6380,12 @@ function planViewGroups(state) {
6250
6380
  if (!node.external && canBeSubject(def, node) && !has.has(node.id)) add.push({ groupId: group.id, subjectId: node.id });
6251
6381
  }
6252
6382
  }
6253
- return { add, remove: remove2, refolder, unlist, rename };
6383
+ return { add, remove: remove2, refolder, unlist, rename: rename2 };
6254
6384
  }
6255
6385
  function syncViewGroups(state, newId) {
6256
- const { add, remove: remove2, refolder, unlist, rename } = planViewGroups(state);
6386
+ const { add, remove: remove2, refolder, unlist, rename: rename2 } = planViewGroups(state);
6257
6387
  for (const id of remove2) delete state.views[id];
6258
- for (const id of rename) {
6388
+ for (const id of rename2) {
6259
6389
  const view = state.views[id];
6260
6390
  const def = viewpointsOf(state.metamodel).find((t) => t.id === view.viewpoint);
6261
6391
  view.name = subjectViewName(state.c4Nodes[view.subject], def);
@@ -6286,7 +6416,7 @@ function syncViewGroups(state, newId) {
6286
6416
  else delete view.folder;
6287
6417
  }
6288
6418
  if (state.activeViewId && remove2.includes(state.activeViewId)) state.activeViewId = null;
6289
- return add.length > 0 || remove2.length > 0 || refolder.length > 0 || unlist.length > 0 || rename.length > 0;
6419
+ return add.length > 0 || remove2.length > 0 || refolder.length > 0 || unlist.length > 0 || rename2.length > 0;
6290
6420
  }
6291
6421
  function detachViewpoint(state, viewId) {
6292
6422
  const view = state.views[viewId];
@@ -7224,7 +7354,7 @@ function editable(current) {
7224
7354
  const mm = fork ?? JSON.parse(JSON.stringify(current));
7225
7355
  return { mm, note: fork ? ` The built-in metamodel was copied to the custom metamodel "${mm.name}" (${mm.id}).` : "" };
7226
7356
  }
7227
- function save(ctx, mm, text) {
7357
+ function save(ctx, mm, text2) {
7228
7358
  const before = Object.values(ctx.diagram.getViews?.() ?? {}).map((v) => ({ id: v.id, name: v.name, listed: v.nodeIds.length }));
7229
7359
  ctx.diagram.setMetamodel(mm);
7230
7360
  const after = ctx.diagram.getViews?.() ?? {};
@@ -7234,7 +7364,7 @@ function save(ctx, mm, text) {
7234
7364
  ...gone.length ? [`Deleted ${gone.length} ${gone.length === 1 ? "view per element with its group" : "views per element with their group"}: ${gone.map((v) => `"${v.name}" (${v.id})`).join(", ")}.`] : [],
7235
7365
  ...unlisted.map((v) => `${v.name} (${v.id}) is now a group of views per element and no longer lists the ${v.listed} element(s) picked for it.`)
7236
7366
  ];
7237
- return { ok: true, resultText: [text, ...notes].join(" "), ...gone.length ? { deleted: { views: gone.length } } : {} };
7367
+ return { ok: true, resultText: [text2, ...notes].join(" "), ...gone.length ? { deleted: { views: gone.length } } : {} };
7238
7368
  }
7239
7369
  function buildMetamodelToolHandlers() {
7240
7370
  return {
@@ -7689,23 +7819,24 @@ var SPECIAL = { \u0142: "l", \u0141: "l", \u00DF: "ss", \u00F8: "o", \u00D8: "o"
7689
7819
  function foldChar(c) {
7690
7820
  return SPECIAL[c] ?? c.normalize("NFD").replace(/[̀-ͯ]/g, "").toLowerCase();
7691
7821
  }
7692
- function foldText(text) {
7822
+ var ASCII = /^[\x00-\x7f]*$/;
7823
+ function foldText(text2) {
7824
+ if (ASCII.test(text2)) return text2.toLowerCase();
7693
7825
  let out = "";
7694
- for (const c of text) out += foldChar(c);
7826
+ for (const c of text2) out += foldChar(c);
7695
7827
  return out;
7696
7828
  }
7697
- function foldWithMap(text) {
7698
- let folded = "";
7829
+ function foldPositions(text2) {
7830
+ if (ASCII.test(text2)) return null;
7699
7831
  const at = [];
7700
7832
  let i = 0;
7701
- for (const c of text) {
7833
+ for (const c of text2) {
7702
7834
  const f = foldChar(c);
7703
7835
  for (let k = 0; k < f.length; k++) at.push(i);
7704
- folded += f;
7705
7836
  i += c.length;
7706
7837
  }
7707
7838
  at.push(i);
7708
- return { folded, at };
7839
+ return at;
7709
7840
  }
7710
7841
  function tokens(query) {
7711
7842
  return query.match(/[^\s"]+:"[^"]*"?|"[^"]*"?|\S+/g) ?? [];
@@ -7740,14 +7871,14 @@ function typesNamed(data, value) {
7740
7871
  }
7741
7872
  function parseSearch(query, data) {
7742
7873
  const out = { command: false, words: [], kinds: null, scope: null, types: null, properties: [] };
7743
- let text = query.trim();
7744
- if (text.startsWith(">")) {
7874
+ let text2 = query.trim();
7875
+ if (text2.startsWith(">")) {
7745
7876
  out.command = true;
7746
- text = text.slice(1);
7877
+ text2 = text2.slice(1);
7747
7878
  }
7748
7879
  const props = propertyNames(data.metamodel);
7749
7880
  const kinds = /* @__PURE__ */ new Set();
7750
- for (const token of tokens(text)) {
7881
+ for (const token of tokens(text2)) {
7751
7882
  if (out.command) {
7752
7883
  out.words.push(foldText(unquote(token)));
7753
7884
  continue;
@@ -7814,6 +7945,23 @@ function matchIn(folded, word) {
7814
7945
  function initials(folded) {
7815
7946
  return (folded.match(/[a-z0-9]+/g) ?? []).map((w) => w[0]).join("");
7816
7947
  }
7948
+ var FOLD_CACHE_MAX = 25e4;
7949
+ var folds = /* @__PURE__ */ new Map();
7950
+ var foldsMade = 0;
7951
+ function foldedOf(text2) {
7952
+ let f = folds.get(text2);
7953
+ if (!f) {
7954
+ if (folds.size >= FOLD_CACHE_MAX) folds.clear();
7955
+ f = { text: text2, folded: foldText(text2) };
7956
+ folds.set(text2, f);
7957
+ foldsMade++;
7958
+ }
7959
+ return f;
7960
+ }
7961
+ function positionsOf(f) {
7962
+ if (f.at === void 0) f.at = foldPositions(f.text);
7963
+ return f.at;
7964
+ }
7817
7965
  function matchFields(fields, words, foldedFields) {
7818
7966
  if (!words.length) return { score: 0, matches: [] };
7819
7967
  const matches = [];
@@ -7833,7 +7981,8 @@ function matchFields(fields, words, foldedFields) {
7833
7981
  return { score, matches };
7834
7982
  }
7835
7983
  function marksOf(f, ranges) {
7836
- const marks = ranges.map(([a, b]) => [f.at[a], f.at[b - 1] + 1]).sort((x, y) => x[0] - y[0]);
7984
+ const at = positionsOf(f);
7985
+ const marks = ranges.map(([a, b]) => at ? [at[a], at[b - 1] + 1] : [a, b]).sort((x, y) => x[0] - y[0]);
7837
7986
  const out = [];
7838
7987
  for (const m of marks) {
7839
7988
  const last = out[out.length - 1];
@@ -7844,11 +7993,11 @@ function marksOf(f, ranges) {
7844
7993
  }
7845
7994
  var SNIPPET_BEFORE = 28;
7846
7995
  var SNIPPET_LENGTH = 90;
7847
- function snippetOf(text, f, ranges) {
7996
+ function snippetOf(text2, f, ranges) {
7848
7997
  const marks = marksOf(f, ranges);
7849
7998
  const first = marks[0]?.[0] ?? 0;
7850
- const flat2 = text.replace(/\s+/g, " ");
7851
- const shift = text.slice(0, first).length - text.slice(0, first).replace(/\s+/g, " ").length;
7999
+ const flat2 = text2.replace(/\s+/g, " ");
8000
+ const shift = text2.slice(0, first).length - text2.slice(0, first).replace(/\s+/g, " ").length;
7852
8001
  const at = first - shift;
7853
8002
  let start = Math.max(0, at - SNIPPET_BEFORE);
7854
8003
  if (start > 0) {
@@ -7859,7 +8008,7 @@ function snippetOf(text, f, ranges) {
7859
8008
  const lead = start > 0 ? "\u2026" : "";
7860
8009
  const tail = end < flat2.length ? "\u2026" : "";
7861
8010
  const moved = (n) => {
7862
- const s = text.slice(0, n).length - text.slice(0, n).replace(/\s+/g, " ").length;
8011
+ const s = text2.slice(0, n).length - text2.slice(0, n).replace(/\s+/g, " ").length;
7863
8012
  return n - s - start + lead.length;
7864
8013
  };
7865
8014
  const shown = lead + flat2.slice(start, end) + tail;
@@ -7869,7 +8018,7 @@ function snippetOf(text, f, ranges) {
7869
8018
  };
7870
8019
  }
7871
8020
  function hitFor(fields, parsed, allowInitials) {
7872
- const folded = fields.map((f) => foldWithMap(f.text));
8021
+ const folded = fields.map((f) => foldedOf(f.text));
7873
8022
  const m = matchFields(fields, parsed.words, folded);
7874
8023
  let score = m?.score ?? 0;
7875
8024
  const matches = m?.matches ?? [];
@@ -7907,7 +8056,7 @@ function viewTypeName(view) {
7907
8056
  return VIEW_TYPE[view.kind ?? ""] ?? "Structure";
7908
8057
  }
7909
8058
  var isGroup = (v, mm) => !!v.viewpoint && !v.subject && !v.partOf && !!viewpointsOf(mm).find((t) => t.id === v.viewpoint)?.subject;
7910
- var BASE_KEYS = /* @__PURE__ */ new Set(["id", "type", "label", "description", "technology", "parentId", "collapsed", "external", "x", "y", "width", "height", "order", "pinned", "positions"]);
8059
+ var BASE_KEYS2 = /* @__PURE__ */ new Set(["id", "type", "label", "description", "technology", "parentId", "collapsed", "external", "x", "y", "width", "height", "order", "pinned", "positions"]);
7911
8060
  function propertyFields(node, metamodel) {
7912
8061
  const values = node;
7913
8062
  const defs = metamodel?.nodeTypes[node.type]?.properties;
@@ -7922,7 +8071,7 @@ function propertyFields(node, metamodel) {
7922
8071
  return out;
7923
8072
  }
7924
8073
  for (const [key, v] of Object.entries(values)) {
7925
- if (!BASE_KEYS.has(key) && typeof v === "string" && v.trim()) out.push({ key, name: key, text: v });
8074
+ if (!BASE_KEYS2.has(key) && typeof v === "string" && v.trim()) out.push({ key, name: key, text: v });
7926
8075
  }
7927
8076
  return out;
7928
8077
  }
@@ -8094,7 +8243,7 @@ Boolean logic in WHERE:
8094
8243
  Supported node fields:
8095
8244
  - id, type, label, description, technology, parentId, external,
8096
8245
  plus any custom/governance property key for that node's type
8097
- (e.g. status, ears_type, category \u2014 see the metamodel context message)
8246
+ (e.g. status, ears_type, characteristic \u2014 see the metamodel context message)
8098
8247
 
8099
8248
  Supported relation fields:
8100
8249
  - id, sourceId, targetId, label, technology, relationType,
@@ -8381,7 +8530,7 @@ function getNodeField(node, field) {
8381
8530
  return node.parentId ?? null;
8382
8531
  case "external":
8383
8532
  return node.external ?? false;
8384
- // Custom/governance properties (ears_type, status, category, ...) ride as
8533
+ // Custom/governance properties (ears_type, status, characteristic, ...) ride as
8385
8534
  // extra own-keys on the node — fall through to a generic read instead of
8386
8535
  // rejecting any field not in the fixed list above.
8387
8536
  default:
@@ -9915,6 +10064,116 @@ function buildContextMessage(nodes, relations, activeView, views) {
9915
10064
 
9916
10065
  // ../../packages/common/src/formats/mdFolder.ts
9917
10066
  init_define_RADICAL_BUILD();
10067
+
10068
+ // ../../packages/common/src/formats/checksMigration.ts
10069
+ init_define_RADICAL_BUILD();
10070
+ var CHECKED_TYPES = /* @__PURE__ */ new Set(["scenario", "fitness-fn"]);
10071
+ var OLD_KEYS = ["tests", "threshold"];
10072
+ var text = (v) => typeof v === "string" ? v.trim() : "";
10073
+ var needsMigration = (node) => CHECKED_TYPES.has(String(node.type)) && (OLD_KEYS.some((k) => k in node) || node.type === "fitness-fn" && "category" in node);
10074
+ var onlyTests = (metrics) => {
10075
+ const lines = metrics.split("\n").map((l) => l.trim()).filter((l) => l && !l.startsWith("#"));
10076
+ return lines.length > 0 && lines.every((l) => /^test\(.*\)\s+passed$/.test(l));
10077
+ };
10078
+ function classify(next) {
10079
+ const category = text(next.category);
10080
+ delete next.category;
10081
+ if (category === "holistic" && !next.scope) next.scope = "holistic";
10082
+ if (category === "structural" && !next.characteristic) next.characteristic = "maintainability";
10083
+ if (!next.cadence && !next.invocation && onlyTests(text(next.metrics))) {
10084
+ next.cadence = "triggered";
10085
+ next.trigger = "pull-request";
10086
+ next.invocation = "automated";
10087
+ }
10088
+ }
10089
+ function migrateCheckFields(node) {
10090
+ if (!needsMigration(node)) return node;
10091
+ const next = { ...node };
10092
+ const tests = text(node.tests).split("\n").map((l) => l.trim()).filter(Boolean).map((line) => line.startsWith("#") ? line : `test(${line}) passed`);
10093
+ if (tests.length) next.metrics = [text(node.metrics), ...tests].filter(Boolean).join("\n");
10094
+ const threshold = text(node.threshold);
10095
+ if (threshold) {
10096
+ const description = text(node.description);
10097
+ next.description = description ? `${description}
10098
+
10099
+ Threshold: ${threshold}` : `Threshold: ${threshold}`;
10100
+ }
10101
+ for (const key of OLD_KEYS) delete next[key];
10102
+ if (node.type === "fitness-fn" && "category" in node) classify(next);
10103
+ return next;
10104
+ }
10105
+ function migrateNodeType(def) {
10106
+ return migrateCategory(migrateOldKeys(def));
10107
+ }
10108
+ function migrateCategory(def) {
10109
+ if (def.id !== "fitness-fn" || !def.properties?.some((p) => p.key === "category")) return def;
10110
+ const at = def.properties.findIndex((p) => p.key === "category");
10111
+ const kept = def.properties.filter((p) => p.key !== "category");
10112
+ const missing = FITNESS_CLASSIFICATION_PROPERTIES.filter((p) => !kept.some((k) => k.key === p.key));
10113
+ const properties = [...kept.slice(0, at), ...missing, ...kept.slice(at)];
10114
+ const wizard = def.wizard && {
10115
+ ...def.wizard,
10116
+ steps: def.wizard.steps.map((step) => step.kind === "fields" && step.fields.includes("category") ? { ...step, fields: [...new Set(step.fields.map((f) => f === "category" ? "characteristic" : f))] } : step)
10117
+ };
10118
+ return { ...def, properties, ...wizard ? { wizard } : {} };
10119
+ }
10120
+ function migrateOldKeys(def) {
10121
+ if (!CHECKED_TYPES.has(def.id) || !def.properties?.some((p) => OLD_KEYS.includes(p.key))) return def;
10122
+ const at = def.properties.findIndex((p) => OLD_KEYS.includes(p.key));
10123
+ const kept = def.properties.filter((p) => !OLD_KEYS.includes(p.key));
10124
+ const missing = METRICS_PROPERTIES.filter((p) => !kept.some((k) => k.key === p.key));
10125
+ const properties = [...kept.slice(0, at), ...missing, ...kept.slice(at)];
10126
+ const wizard = def.wizard && {
10127
+ ...def.wizard,
10128
+ steps: def.wizard.steps.map((step) => step.kind === "fields" && step.fields.some((f) => OLD_KEYS.includes(f)) ? { ...step, fields: [...new Set(step.fields.map((f) => OLD_KEYS.includes(f) ? "metrics" : f))] } : step)
10129
+ };
10130
+ return { ...def, properties, ...wizard ? { wizard } : {} };
10131
+ }
10132
+ function migrateMetamodel(metamodel) {
10133
+ let changed = false;
10134
+ const nodeTypes = {};
10135
+ for (const [id, def] of Object.entries(metamodel.nodeTypes)) {
10136
+ nodeTypes[id] = migrateNodeType(def);
10137
+ if (nodeTypes[id] !== def) changed = true;
10138
+ }
10139
+ return changed ? { ...metamodel, nodeTypes } : metamodel;
10140
+ }
10141
+ var migrateRecord = (nodes) => {
10142
+ if (!Object.values(nodes).some((n) => needsMigration(n))) return nodes;
10143
+ return Object.fromEntries(Object.entries(nodes).map(([id, n]) => [id, migrateCheckFields(n)]));
10144
+ };
10145
+ function migrateChecks(data) {
10146
+ const nodes = data.nodes.some((n) => needsMigration(n)) ? data.nodes.map((n) => migrateCheckFields(n)) : data.nodes;
10147
+ const metamodel = data.metamodel ? migrateMetamodel(data.metamodel) : void 0;
10148
+ const snapshots = data.snapshots?.map((s) => {
10149
+ const next = migrateRecord(s.nodes);
10150
+ return next === s.nodes ? s : { ...s, nodes: next };
10151
+ });
10152
+ const presentations = data.presentations?.map((p) => {
10153
+ const slides = p.slides.map((slide2) => {
10154
+ if (!slide2.modelSnapshot) return slide2;
10155
+ const next = migrateRecord(slide2.modelSnapshot.nodes);
10156
+ return next === slide2.modelSnapshot.nodes ? slide2 : { ...slide2, modelSnapshot: { ...slide2.modelSnapshot, nodes: next } };
10157
+ });
10158
+ return slides.some((s, i) => s !== p.slides[i]) ? { ...p, slides } : p;
10159
+ });
10160
+ const hubTemplates = data.hubTemplates && Object.fromEntries(Object.entries(data.hubTemplates).map(([id, record]) => {
10161
+ const originals = Object.fromEntries(Object.entries(record.originalNodes).map(([nid, n]) => [nid, migrateCheckFields(n)]));
10162
+ return [id, Object.entries(originals).some(([nid, n]) => n !== record.originalNodes[nid]) ? { ...record, originalNodes: originals } : record];
10163
+ }));
10164
+ const changed = nodes !== data.nodes || metamodel !== data.metamodel || snapshots?.some((s, i) => s !== data.snapshots[i]) || presentations?.some((p, i) => p !== data.presentations[i]) || hubTemplates && Object.entries(hubTemplates).some(([id, r]) => r !== data.hubTemplates[id]);
10165
+ if (!changed) return data;
10166
+ return {
10167
+ ...data,
10168
+ nodes,
10169
+ ...metamodel ? { metamodel } : {},
10170
+ ...snapshots ? { snapshots } : {},
10171
+ ...presentations ? { presentations } : {},
10172
+ ...hubTemplates ? { hubTemplates } : {}
10173
+ };
10174
+ }
10175
+
10176
+ // ../../packages/common/src/formats/mdFolder.ts
9918
10177
  var MD_MANIFEST_FILE = "radical.md";
9919
10178
  var LAYOUT_FILE = "_layout.json";
9920
10179
  var RELATIONS_FILE = "relations.json";
@@ -10045,8 +10304,8 @@ function parseMarkdown(content) {
10045
10304
  const body = lines.slice(i).join("\n").trim();
10046
10305
  return { front, body };
10047
10306
  }
10048
- function slugify(text, fallback) {
10049
- const slug = text.toLowerCase().normalize("NFKD").replace(/[^\p{Letter}\p{Number}]+/gu, "-").replace(/^-+|-+$/g, "");
10307
+ function slugify(text2, fallback) {
10308
+ const slug = text2.toLowerCase().normalize("NFKD").replace(/[^\p{Letter}\p{Number}]+/gu, "-").replace(/^-+|-+$/g, "");
10050
10309
  return [...slug].slice(0, 60).join("") || fallback;
10051
10310
  }
10052
10311
  function allocateSlugs(claims) {
@@ -10231,7 +10490,7 @@ function deserializeFromMdFolder(files) {
10231
10490
  if (layout.defaultLayoutConstraints?.length) data.defaultLayoutConstraints = layout.defaultLayoutConstraints;
10232
10491
  if (layout.defaultEdgeStyle === "orthogonal") data.defaultEdgeStyle = layout.defaultEdgeStyle;
10233
10492
  const manifest = typeof files[MD_MANIFEST_FILE] === "string" ? parseMarkdown(files[MD_MANIFEST_FILE]).front.name : void 0;
10234
- return { data, ...typeof manifest === "string" && manifest.trim() ? { name: manifest.trim() } : {} };
10493
+ return { data: migrateChecks(data), ...typeof manifest === "string" && manifest.trim() ? { name: manifest.trim() } : {} };
10235
10494
  }
10236
10495
  function isMdFolderModelPath(path) {
10237
10496
  if (path === MD_MANIFEST_FILE || SIDECAR_FILES.has(path)) return true;
@@ -10748,6 +11007,91 @@ function forgetDeleted(merged, sides) {
10748
11007
  if (merged.defaultLayoutConstraints) merged.defaultLayoutConstraints = state.defaultLayoutConstraints ?? [];
10749
11008
  }
10750
11009
 
11010
+ // ../../packages/common/src/formats/modelCache.ts
11011
+ init_define_RADICAL_BUILD();
11012
+
11013
+ // ../../packages/common/src/formats/canvasSelection.ts
11014
+ init_define_RADICAL_BUILD();
11015
+ var SELECTION_DIR = ".radical";
11016
+ var SELECTION_FILE = `${SELECTION_DIR}/selection.json`;
11017
+ var SELECTION_GITIGNORE = `${SELECTION_DIR}/.gitignore`;
11018
+ var SELECTION_GITIGNORE_CONTENT = "*\n";
11019
+ var isIdList = (value) => Array.isArray(value) && value.every((id) => typeof id === "string" && id.length > 0);
11020
+ function parseSelection(text2) {
11021
+ let raw;
11022
+ try {
11023
+ raw = JSON.parse(text2);
11024
+ } catch {
11025
+ return null;
11026
+ }
11027
+ if (!raw || typeof raw !== "object") return null;
11028
+ const { version, updatedAt, viewId, nodeIds, relationIds } = raw;
11029
+ if (version !== 1 || typeof updatedAt !== "string" || !isIdList(nodeIds) || !isIdList(relationIds)) return null;
11030
+ if (viewId !== null && typeof viewId !== "string") return null;
11031
+ return { version, updatedAt, viewId, nodeIds, relationIds };
11032
+ }
11033
+
11034
+ // ../../packages/common/src/formats/modelCache.ts
11035
+ var MODEL_CACHE_DIR = `${SELECTION_DIR}/cache`;
11036
+ var MODEL_CACHE_FILE = `${MODEL_CACHE_DIR}/model.json`;
11037
+ var MODEL_CACHE_NAMES = /* @__PURE__ */ new Set(["model.json", "changes.json", "views.json"]);
11038
+ var MODEL_CACHE_VERSION = 2;
11039
+ function parse(text2) {
11040
+ if (!text2) return null;
11041
+ try {
11042
+ const json = JSON.parse(text2);
11043
+ return json && typeof json === "object" ? json : null;
11044
+ } catch {
11045
+ return null;
11046
+ }
11047
+ }
11048
+ var encoder = new TextEncoder();
11049
+ var decoder = new TextDecoder();
11050
+ function readFiles(files) {
11051
+ if (!files || typeof files !== "object") return null;
11052
+ for (const entry of Object.values(files)) {
11053
+ if (!entry || typeof entry.stamp !== "string" || typeof entry.content !== "string") return null;
11054
+ entry.content = decoder.decode(encoder.encode(entry.content));
11055
+ }
11056
+ return files;
11057
+ }
11058
+ function readModelCache(model, changes) {
11059
+ const json = parse(model);
11060
+ if (!json || json.format !== "radical-model-cache" || json.version !== MODEL_CACHE_VERSION || typeof json.id !== "string") return null;
11061
+ const base = readFiles(json.files);
11062
+ if (!base) return null;
11063
+ const files = { ...base };
11064
+ const delta = parse(changes);
11065
+ if (delta && delta.format === "radical-model-cache-changes" && delta.version === MODEL_CACHE_VERSION && delta.base === json.id && Array.isArray(delta.removed)) {
11066
+ const changed = readFiles(delta.files);
11067
+ if (changed) {
11068
+ Object.assign(files, changed);
11069
+ for (const path of delta.removed) delete files[path];
11070
+ }
11071
+ }
11072
+ return { id: json.id, base, files };
11073
+ }
11074
+ function writeModelCache(files, id) {
11075
+ const json = { format: "radical-model-cache", version: MODEL_CACHE_VERSION, id, files };
11076
+ return ascii(JSON.stringify(json));
11077
+ }
11078
+ function writeModelCacheChanges(baseId, base, files) {
11079
+ const changed = {};
11080
+ for (const [path, entry] of Object.entries(files)) if (base[path]?.stamp !== entry.stamp) changed[path] = entry;
11081
+ const removed = Object.keys(base).filter((path) => !(path in files));
11082
+ const json = { format: "radical-model-cache-changes", version: MODEL_CACHE_VERSION, base: baseId, files: changed, removed };
11083
+ return ascii(JSON.stringify(json));
11084
+ }
11085
+ function modelCacheChangeCount(base, files) {
11086
+ let n = 0;
11087
+ for (const [path, entry] of Object.entries(files)) if (base[path]?.stamp !== entry.stamp) n++;
11088
+ for (const path of Object.keys(base)) if (!(path in files)) n++;
11089
+ return n;
11090
+ }
11091
+ function ascii(text2) {
11092
+ return text2.replace(/[\u007f-￿]/g, (c) => `\\u${c.charCodeAt(0).toString(16).padStart(4, "0")}`);
11093
+ }
11094
+
10751
11095
  // ../../packages/common/src/formats/mdFolderSync.ts
10752
11096
  var mergeMdFolderFiles = (base, ours, theirs) => {
10753
11097
  for (const [path, content] of Object.entries(theirs)) {
@@ -10769,9 +11113,35 @@ var mergeMdFolderFiles = (base, ours, theirs) => {
10769
11113
  return null;
10770
11114
  }
10771
11115
  };
11116
+ var READ_AT_ONCE = 32;
11117
+ async function readEach(paths, read) {
11118
+ const out = new Array(paths.length);
11119
+ let next = 0;
11120
+ const worker = async () => {
11121
+ while (next < paths.length) {
11122
+ const i = next++;
11123
+ out[i] = await read(paths[i]);
11124
+ }
11125
+ };
11126
+ await Promise.all(Array.from({ length: Math.min(READ_AT_ONCE, paths.length) }, worker));
11127
+ return out;
11128
+ }
11129
+ var CACHE_STALE_MAX = 50;
11130
+ var CACHE_STALE_SHARE = 0.01;
11131
+ function newCacheId() {
11132
+ return globalThis.crypto?.randomUUID?.() ?? `${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`;
11133
+ }
10772
11134
  var MdFolderSession = class {
10773
- constructor(storage) {
11135
+ /** `writeCache: false`: read the folder's cache when there is one, never
11136
+ * write it (the CLI, which exits as soon as it is done; Studio and the
11137
+ * MCP server keep it). `openFromCache`: the session's first read takes
11138
+ * the folder as its cache has it, without listing the files, and lists
11139
+ * them right after; `verified` says whether they differed (Studio, which
11140
+ * then loads the folder afresh; never the MCP server, which must see the
11141
+ * files as they are on every call). */
11142
+ constructor(storage, options = {}) {
10774
11143
  this.storage = storage;
11144
+ this.options = options;
10775
11145
  /** Called with the changed paths whenever `poll` or a refused `write`
10776
11146
  * finds edits made outside the app. */
10777
11147
  this.onExternalChange = null;
@@ -10782,6 +11152,17 @@ var MdFolderSession = class {
10782
11152
  this.observed = {};
10783
11153
  this.tail = Promise.resolve();
10784
11154
  this.running = 0;
11155
+ /** model.json as last read or written: its id and files, which
11156
+ * changes.json is made against. */
11157
+ this.cache = null;
11158
+ this.verification = Promise.resolve({ stale: false, changed: [] });
11159
+ this.cacheWrite = Promise.resolve();
11160
+ }
11161
+ /** Whether the files differed from the cache a first read took the folder
11162
+ * from (`openFromCache`), and which: resolves once they are listed, at
11163
+ * once for a read that listed them. */
11164
+ verified() {
11165
+ return this.verification;
10785
11166
  }
10786
11167
  /** Read every model file and make that the baseline. */
10787
11168
  readAll() {
@@ -10812,7 +11193,7 @@ var MdFolderSession = class {
10812
11193
  });
10813
11194
  }
10814
11195
  async writeLocked(files, merge) {
10815
- if (!this.loaded) await this.loadBaseline();
11196
+ if (!this.loaded) await this.loadBaseline(false);
10816
11197
  files = keepMdFolderPaths(this.baselineFiles(), files);
10817
11198
  const stamps = await this.storage.list();
10818
11199
  const conflict = await this.changedSince(stamps);
@@ -10841,6 +11222,7 @@ var MdFolderSession = class {
10841
11222
  this.baseline.delete(path);
10842
11223
  }
10843
11224
  this.observed = this.baselineStamps();
11225
+ this.keepCache();
10844
11226
  if (merged) this.onExternalChange?.(merged.changed);
10845
11227
  return merged ? { ok: true, merged } : { ok: true };
10846
11228
  }
@@ -10858,37 +11240,127 @@ var MdFolderSession = class {
10858
11240
  return changed;
10859
11241
  });
10860
11242
  }
10861
- async loadBaseline() {
11243
+ /** `rebuildCache`: write the cache again when it is out of date (not
11244
+ * for a write, which changes the folder at once). */
11245
+ async loadBaseline(rebuildCache = true) {
11246
+ const cached = await this.readCache();
11247
+ if (cached && this.options.openFromCache && !this.loaded && rebuildCache) {
11248
+ this.baseline = new Map(Object.entries(cached.files).map(([path, { content, stamp }]) => [path, { content, stamp }]));
11249
+ this.observed = this.baselineStamps();
11250
+ this.loaded = true;
11251
+ this.cache = cached;
11252
+ this.verification = this.verifyLater();
11253
+ return;
11254
+ }
10862
11255
  const stamps = await this.storage.list();
11256
+ const paths = Object.keys(stamps);
11257
+ const known = cached?.files;
11258
+ const toRead = known ? paths.filter((path) => known[path]?.stamp !== stamps[path]) : paths;
11259
+ const contents = await readEach(toRead, (path) => this.storage.read(path));
11260
+ const read = new Map(toRead.map((path, i) => [path, contents[i]]));
10863
11261
  const baseline = /* @__PURE__ */ new Map();
10864
- for (const [path, stamp] of Object.entries(stamps)) {
10865
- baseline.set(path, { content: await this.storage.read(path), stamp });
10866
- }
11262
+ for (const path of paths) baseline.set(path, { content: read.get(path) ?? known[path].content, stamp: stamps[path] });
10867
11263
  this.baseline = baseline;
10868
11264
  this.observed = stamps;
10869
11265
  this.loaded = true;
11266
+ this.cache = cached;
11267
+ this.verification = Promise.resolve({ stale: false, changed: [] });
11268
+ const gone = known ? Object.keys(known).filter((path) => !(path in stamps)).length : 0;
11269
+ if (rebuildCache && (!cached || toRead.length + gone > 0)) this.keepCache();
11270
+ }
11271
+ /** model.json, with changes.json applied when it was made for it. */
11272
+ async readCache() {
11273
+ if (!this.storage.readCache) return null;
11274
+ const [model, changes] = await Promise.all([
11275
+ this.storage.readCache("model.json").catch(() => null),
11276
+ this.storage.readCache("changes.json").catch(() => null)
11277
+ ]);
11278
+ return readModelCache(model, changes);
11279
+ }
11280
+ /** Lists the files after an open from the cache: those that differ are
11281
+ * read into the baseline's place for them by the next read. */
11282
+ verifyLater() {
11283
+ const run = this.tail.then(async () => {
11284
+ this.running++;
11285
+ try {
11286
+ const stamps = await this.storage.list();
11287
+ const changed = await this.changedSince(stamps);
11288
+ this.observed = stamps;
11289
+ this.keepCache();
11290
+ return { stale: changed.length > 0, changed };
11291
+ } catch {
11292
+ return { stale: true, changed: [] };
11293
+ } finally {
11294
+ this.running--;
11295
+ }
11296
+ });
11297
+ this.tail = run.catch(() => {
11298
+ });
11299
+ return run;
11300
+ }
11301
+ /** Brings the cache up to the baseline: changes.json, or model.json
11302
+ * again when it is missing or more files differ from it than it can
11303
+ * stand (written after the operation running, so it waits for neither).
11304
+ * Only for a model's folder: a folder of other files is left alone. */
11305
+ keepCache() {
11306
+ if (this.options.writeCache === false || !this.storage.writeCache) return;
11307
+ if (!isValidMdFolderManifest(this.baseline.get(MD_MANIFEST_FILE)?.content)) return;
11308
+ const run = this.tail.then(async () => {
11309
+ this.running++;
11310
+ try {
11311
+ const files = {};
11312
+ for (const [path, entry] of this.baseline) files[path] = { stamp: entry.stamp, content: entry.content };
11313
+ const cache = this.cache;
11314
+ if (cache && modelCacheChangeCount(cache.base, files) <= Math.max(CACHE_STALE_MAX, this.baseline.size * CACHE_STALE_SHARE)) {
11315
+ await this.storage.writeCache("changes.json", writeModelCacheChanges(cache.id, cache.base, files));
11316
+ return;
11317
+ }
11318
+ const id = newCacheId();
11319
+ await this.storage.writeCache("model.json", writeModelCache(files, id));
11320
+ this.cache = { id, base: files };
11321
+ } catch {
11322
+ } finally {
11323
+ this.running--;
11324
+ }
11325
+ });
11326
+ this.tail = run;
11327
+ this.cacheWrite = run;
11328
+ }
11329
+ /** Resolves once the cache is written as far as the session has gone. */
11330
+ cacheWritten() {
11331
+ return this.cacheWrite;
11332
+ }
11333
+ /** A file of the folder's cache other than its files' (views.json), or
11334
+ * null. */
11335
+ readCacheFile(name) {
11336
+ return this.storage.readCache ? this.storage.readCache(name).catch(() => null) : Promise.resolve(null);
11337
+ }
11338
+ /** Writes one; false when the folder keeps no cache. */
11339
+ async writeCacheFile(name, content) {
11340
+ if (this.options.writeCache === false || !this.storage.writeCache) return false;
11341
+ try {
11342
+ await this.storage.writeCache(name, content);
11343
+ return true;
11344
+ } catch {
11345
+ return false;
11346
+ }
10870
11347
  }
10871
11348
  /** Paths whose content on disk differs from the baseline: added, removed,
10872
11349
  * or rewritten with different content. A file whose stamp moved but whose
10873
11350
  * content didn't (touched, saved unchanged) just gets its stamp updated. */
10874
11351
  async changedSince(stamps) {
10875
11352
  const changed = [];
10876
- for (const [path, stamp] of Object.entries(stamps)) {
11353
+ const moved = Object.keys(stamps).filter((path) => {
10877
11354
  const known = this.baseline.get(path);
10878
- if (!known) {
10879
- changed.push(path);
10880
- } else if (known.stamp !== stamp) {
10881
- let content;
10882
- try {
10883
- content = await this.storage.read(path);
10884
- } catch {
10885
- changed.push(path);
10886
- continue;
10887
- }
10888
- if (content === known.content) known.stamp = stamp;
10889
- else changed.push(path);
10890
- }
10891
- }
11355
+ if (!known) changed.push(path);
11356
+ return !!known && known.stamp !== stamps[path];
11357
+ });
11358
+ const contents = await readEach(moved, (path) => this.storage.read(path).catch(() => void 0));
11359
+ moved.forEach((path, i) => {
11360
+ const known = this.baseline.get(path);
11361
+ if (contents[i] === known.content) known.stamp = stamps[path];
11362
+ else changed.push(path);
11363
+ });
10892
11364
  for (const path of this.baseline.keys()) {
10893
11365
  if (!(path in stamps)) changed.push(path);
10894
11366
  }
@@ -10903,12 +11375,11 @@ var MdFolderSession = class {
10903
11375
  /** The model files as they are on disk now. */
10904
11376
  async readFiles(stamps) {
10905
11377
  const files = {};
10906
- for (const path of Object.keys(stamps)) {
10907
- try {
10908
- files[path] = await this.storage.read(path);
10909
- } catch {
10910
- }
10911
- }
11378
+ const paths = Object.keys(stamps);
11379
+ const contents = await readEach(paths, (path) => this.storage.read(path).catch(() => void 0));
11380
+ paths.forEach((path, i) => {
11381
+ if (contents[i] !== void 0) files[path] = contents[i];
11382
+ });
10912
11383
  return files;
10913
11384
  }
10914
11385
  baselineStamps() {
@@ -10937,30 +11408,9 @@ function sameStamps(a, b) {
10937
11408
  // ../../packages/node-files/src/diskFolderStorage.ts
10938
11409
  init_define_RADICAL_BUILD();
10939
11410
  import { randomUUID } from "crypto";
10940
- import { lstat as lstat2, mkdir as mkdir2, readFile as readFile2, readdir, rm, stat, writeFile as writeFile2 } from "fs/promises";
11411
+ import { lstat as lstat2, mkdir as mkdir2, readFile as readFile2, readdir, rename, rm, stat, writeFile as writeFile2 } from "fs/promises";
10941
11412
  import { dirname as dirname2, join as join2, resolve as resolve2, sep } from "path";
10942
11413
 
10943
- // ../../packages/common/src/formats/canvasSelection.ts
10944
- init_define_RADICAL_BUILD();
10945
- var SELECTION_DIR = ".radical";
10946
- var SELECTION_FILE = `${SELECTION_DIR}/selection.json`;
10947
- var SELECTION_GITIGNORE = `${SELECTION_DIR}/.gitignore`;
10948
- var SELECTION_GITIGNORE_CONTENT = "*\n";
10949
- var isIdList = (value) => Array.isArray(value) && value.every((id) => typeof id === "string" && id.length > 0);
10950
- function parseSelection(text) {
10951
- let raw;
10952
- try {
10953
- raw = JSON.parse(text);
10954
- } catch {
10955
- return null;
10956
- }
10957
- if (!raw || typeof raw !== "object") return null;
10958
- const { version, updatedAt, viewId, nodeIds, relationIds } = raw;
10959
- if (version !== 1 || typeof updatedAt !== "string" || !isIdList(nodeIds) || !isIdList(relationIds)) return null;
10960
- if (viewId !== null && typeof viewId !== "string") return null;
10961
- return { version, updatedAt, viewId, nodeIds, relationIds };
10962
- }
10963
-
10964
11414
  // ../../packages/node-files/src/selectionFile.ts
10965
11415
  init_define_RADICAL_BUILD();
10966
11416
  import { lstat, mkdir, readFile, writeFile } from "fs/promises";
@@ -10971,6 +11421,43 @@ init_define_RADICAL_BUILD();
10971
11421
 
10972
11422
  // ../../packages/common/src/ai/forge/prompts.ts
10973
11423
  init_define_RADICAL_BUILD();
11424
+
11425
+ // ../../packages/common/src/check/sensors.ts
11426
+ init_define_RADICAL_BUILD();
11427
+ var SENSOR_NAMES = ["command", "json", "playwright"];
11428
+ function commandWords(line) {
11429
+ const words = [];
11430
+ let word = "";
11431
+ let quote2 = null;
11432
+ let started = false;
11433
+ for (const ch of line) {
11434
+ if (quote2) {
11435
+ if (ch === quote2) quote2 = null;
11436
+ else word += ch;
11437
+ } else if (ch === '"' || ch === "'") {
11438
+ quote2 = ch;
11439
+ started = true;
11440
+ } else if (/\s/.test(ch)) {
11441
+ if (started || word) words.push(word);
11442
+ word = "";
11443
+ started = false;
11444
+ } else {
11445
+ word += ch;
11446
+ }
11447
+ }
11448
+ if (started || word) words.push(word);
11449
+ return words;
11450
+ }
11451
+ function parseMeasure(text2) {
11452
+ if (typeof text2 !== "string") return [];
11453
+ return text2.split("\n").map((l) => l.trim()).filter((l) => l && !l.startsWith("#")).map((raw) => {
11454
+ const [sensor = "", ...args] = commandWords(raw);
11455
+ return { raw, sensor, args };
11456
+ });
11457
+ }
11458
+ var isSensorName = (name) => SENSOR_NAMES.includes(name);
11459
+
11460
+ // ../../packages/common/src/ai/forge/prompts.ts
10974
11461
  var PRIMARY_TYPE_IDS_FOR_STAGE = {
10975
11462
  requirements: ["requirement"],
10976
11463
  domain: ["domain", "entity"],
@@ -11180,7 +11667,7 @@ function stageTask(stageId, descBlock, need) {
11180
11667
  "relations between them. This is the last stage: the behavior and quality",
11181
11668
  "spec is already fully formed, so let the architecture follow from it rather",
11182
11669
  "than guessing ahead of it \u2014 e.g. a fitness function with a tight latency",
11183
- "threshold, a scenario implying an async flow, or a set of screens implying a",
11670
+ "condition, a scenario implying an async flow, or a set of screens implying a",
11184
11671
  "separate admin front-end should visibly shape how you decompose the system.",
11185
11672
  "Link each element to the requirement(s) it satisfies with a `satisfies`",
11186
11673
  "relation, AND link each existing `fitness-fn` node to whichever new element(s)",
@@ -11207,7 +11694,23 @@ function stageTask(stageId, descBlock, need) {
11207
11694
  "Task: propose fitness functions (`fitness-fn` nodes) that constrain the",
11208
11695
  "requirements already in the model \u2014 measurable guardrails for things like",
11209
11696
  "latency, availability, coupling, security posture, or delivery flow implied",
11210
- "by the description. Set `category` and a concrete `threshold` for each. No",
11697
+ "by the description. Classify each: `characteristic`, the ISO/IEC 25010",
11698
+ `quality it protects (${FITNESS_CHARACTERISTICS.join(", ")}); \`scope\`,`,
11699
+ "`atomic` (one part in one context: a unit test, a linter rule) or `holistic`",
11700
+ "(several parts together: latency under load); `cadence`, `triggered` with the",
11701
+ `\`trigger\` it runs on (${FITNESS_TRIGGERS.join(", ")}), \`continual\` (measured`,
11702
+ "all the time, in production) or `temporal` with `every` (when it falls due,",
11703
+ "e.g. `90d`); and `invocation`, `automated` or `manual` (a person reviews it;",
11704
+ "its metrics line is then `review(<name>) passed`). For an automated one, set",
11705
+ "`measure` only when you know which sensor of radical sense measures it",
11706
+ `(${SENSOR_NAMES.map((n) => `\`${n}\``).join(", ")}): one line per measurement, the sensor and its`,
11707
+ "arguments (`playwright tests/load.spec.ts --label env=staging`); otherwise",
11708
+ "leave it empty. In `metrics` put one condition",
11709
+ "per line that says when it passes: a measured value and its threshold, with",
11710
+ "the metric named as a sensor would report it",
11711
+ "(`checkout.latency.p95{env=prod} <= 300 ms`, `deps.cycles == 0`), or a test",
11712
+ "that has to pass (`test(<file> \u203A <title>) passed`) where the description names",
11713
+ "one. Put what the conditions cannot say in the description. No",
11211
11714
  "systems/containers exist yet (C4 runs later, once this spec is settled), so",
11212
11715
  "link each fitness function to the requirement(s) it constrains with a",
11213
11716
  "`traces-to` relation FROM the requirement TO the fitness function (the",
@@ -11335,8 +11838,8 @@ function stageTask(stageId, descBlock, need) {
11335
11838
  " domain model's term everywhere), a scenario whose Given/When/Then",
11336
11839
  " contradicts a transition or the order of a process, a step, screen or",
11337
11840
  " element no requirement asks for, a requirement that no process, machine,",
11338
- " screen or element carries out, a fitness function whose threshold",
11339
- " contradicts a requirement, a relation that points the wrong way.",
11841
+ " screen or element carries out, a fitness function whose conditions",
11842
+ " contradict a requirement, a relation that points the wrong way.",
11340
11843
  "3. Propose each fix as the smallest change, one finding per proposal, following",
11341
11844
  " the refinement rule below. Everything you change goes to the user first.",
11342
11845
  "",
@@ -11370,9 +11873,9 @@ init_define_RADICAL_BUILD();
11370
11873
  init_define_RADICAL_BUILD();
11371
11874
  var SEPARATOR = /\s+›\s+/;
11372
11875
  var normalize = (path) => path.replace(/\\/g, "/").replace(/^\.\//, "");
11373
- function parseTestIds(text) {
11374
- if (typeof text !== "string") return [];
11375
- return text.split("\n").map((line) => line.trim()).filter((line) => line && !line.startsWith("#")).map((raw) => {
11876
+ function parseTestIds(text2) {
11877
+ if (typeof text2 !== "string") return [];
11878
+ return text2.split("\n").map((line) => line.trim()).filter((line) => line && !line.startsWith("#")).map((raw) => {
11376
11879
  const [file, ...title] = raw.split(SEPARATOR);
11377
11880
  return { raw, file: normalize(file), title };
11378
11881
  });
@@ -11405,14 +11908,151 @@ function globMatch(glob, file) {
11405
11908
  return glob.startsWith("**") ? normalize(file) : m[1];
11406
11909
  }
11407
11910
 
11911
+ // ../../packages/common/src/check/metrics.ts
11912
+ init_define_RADICAL_BUILD();
11913
+ var TEST_LINE = /^test\((.+)\)(?:\s+passed)?$/;
11914
+ var REVIEW_LINE = /^review\((.+)\)\s+passed$/i;
11915
+ var REVIEW_METRIC = "review";
11916
+ var METRIC_LINE = /^([A-Za-z_][\w.:/-]*)\s*(?:\{([^}]*)\})?\s*(<=|>=|==|!=|=|<|>)\s*(-?\d+(?:\.\d+)?(?:e-?\d+)?)\s*(\S+)?$/i;
11917
+ var BASELINE_LINE = /^([A-Za-z_][\w.:/-]*)\s*(?:\{([^}]*)\})?\s*(<=|>=|==|!=|=|<|>)\s*baseline(?:\s*([+-])\s*(\d+(?:\.\d+)?(?:e-?\d+)?)\s*(%|[^\s%]+)?)?$/i;
11918
+ function parseLabels(text2) {
11919
+ const labels = {};
11920
+ for (const part of text2.split(",").map((p) => p.trim()).filter(Boolean)) {
11921
+ const m = /^([\w.-]+)\s*=\s*(?:"([^"]*)"|'([^']*)'|([^"',]*))$/.exec(part);
11922
+ if (!m) return `"${part}" is no label (name=value)`;
11923
+ labels[m[1]] = (m[2] ?? m[3] ?? m[4]).trim();
11924
+ }
11925
+ return labels;
11926
+ }
11927
+ function parseCondition(line) {
11928
+ const raw = line.trim();
11929
+ const test = TEST_LINE.exec(raw);
11930
+ if (test) {
11931
+ const [id] = parseTestIds(test[1]);
11932
+ return id ? { kind: "test", raw, id } : { kind: "invalid", raw, problem: "test() names no test" };
11933
+ }
11934
+ const review = REVIEW_LINE.exec(raw);
11935
+ if (review) return { kind: "metric", raw, metric: REVIEW_METRIC, labels: { name: review[1].trim() }, op: "==", value: 1 };
11936
+ const b = BASELINE_LINE.exec(raw);
11937
+ if (b) {
11938
+ const labels2 = b[2] === void 0 ? {} : parseLabels(b[2]);
11939
+ if (typeof labels2 === "string") return { kind: "invalid", raw, problem: labels2 };
11940
+ if (b[4] && !b[6]) return { kind: "invalid", raw, problem: "a margin on the baseline needs % or a unit (`baseline + 20%`, `baseline + 500 ms`)" };
11941
+ const baseline = b[4] ? { sign: b[4] === "-" ? -1 : 1, by: Number(b[5]), percent: b[6] === "%", ...b[6] !== "%" ? { unit: b[6] } : {} } : { sign: 1, by: 0, percent: true };
11942
+ return { kind: "metric", raw, metric: b[1], labels: labels2, op: b[3] === "=" ? "==" : b[3], value: Number.NaN, baseline };
11943
+ }
11944
+ const m = METRIC_LINE.exec(raw);
11945
+ if (!m) return { kind: "invalid", raw, problem: "it is neither `test(<file> \u203A <title>) passed`, `review(<name>) passed`, `<metric>{<labels>} <op> <number> [unit]` nor `<metric>{<labels>} <op> baseline [+|- <number> %|unit]`" };
11946
+ const labels = m[2] === void 0 ? {} : parseLabels(m[2]);
11947
+ if (typeof labels === "string") return { kind: "invalid", raw, problem: labels };
11948
+ return { kind: "metric", raw, metric: m[1], labels, op: m[3] === "=" ? "==" : m[3], value: Number(m[4]), ...m[5] ? { unit: m[5] } : {} };
11949
+ }
11950
+ function parseConditions(text2) {
11951
+ if (typeof text2 !== "string") return [];
11952
+ return text2.split("\n").map((l) => l.trim()).filter((l) => l && !l.startsWith("#")).map(parseCondition);
11953
+ }
11954
+ function parseCombine(text2) {
11955
+ const t = typeof text2 === "string" ? text2.trim().toLowerCase() : "";
11956
+ if (!t || t === "all") return { kind: "all" };
11957
+ if (t === "any") return { kind: "any" };
11958
+ const m = /^at\s+least\s+(\d+)$/.exec(t);
11959
+ return m && Number(m[1]) > 0 ? { kind: "at-least", n: Number(m[1]) } : null;
11960
+ }
11961
+ var AGE_UNITS = { s: 1e3, m: 6e4, min: 6e4, h: 36e5, d: 864e5, w: 7 * 864e5 };
11962
+ function parseMaxAge(text2) {
11963
+ const t = typeof text2 === "string" ? text2.trim().toLowerCase() : "";
11964
+ if (!t) return void 0;
11965
+ const m = /^(\d+(?:\.\d+)?)\s*(s|min|m|h|d|w)$/.exec(t);
11966
+ return m ? Number(m[1]) * AGE_UNITS[m[2]] : null;
11967
+ }
11968
+ var UNIT_FAMILIES = [
11969
+ { ns: 1e-9, us: 1e-6, "\xB5s": 1e-6, ms: 1e-3, s: 1, min: 60, h: 3600, d: 86400 },
11970
+ { b: 1, kb: 1e3, mb: 1e6, gb: 1e9, tb: 1e12, kib: 1024, mib: 1024 ** 2, gib: 1024 ** 3, tib: 1024 ** 4 }
11971
+ ];
11972
+ function convertUnit(value, from, to) {
11973
+ if (from === to) return value;
11974
+ const f = from.toLowerCase();
11975
+ const t = to.toLowerCase();
11976
+ if (f === t) return value;
11977
+ const family = UNIT_FAMILIES.find((u) => u[f] !== void 0 && u[t] !== void 0);
11978
+ return family ? value * family[f] / family[t] : null;
11979
+ }
11980
+ var COMPARE = {
11981
+ "<": (a, b) => a < b,
11982
+ "<=": (a, b) => a <= b,
11983
+ ">": (a, b) => a > b,
11984
+ ">=": (a, b) => a >= b,
11985
+ "==": (a, b) => a === b,
11986
+ "!=": (a, b) => a !== b
11987
+ };
11988
+ function latestMeasurement(condition, measurements) {
11989
+ let latest;
11990
+ for (const m of measurements) {
11991
+ if (m.metric !== condition.metric) continue;
11992
+ if (Object.entries(condition.labels).some(([k, v]) => m.labels[k] !== v)) continue;
11993
+ if (!latest || Date.parse(m.at) > Date.parse(latest.at)) latest = m;
11994
+ }
11995
+ return latest;
11996
+ }
11997
+ var DAY = 864e5;
11998
+ var formatAge = (ms) => ms >= DAY ? `${Math.floor(ms / DAY)} d` : ms >= 36e5 ? `${Math.floor(ms / 36e5)} h` : `${Math.max(0, Math.floor(ms / 6e4))} min`;
11999
+ var BASELINE_RUNS = 7;
12000
+ function baselineOf(condition, baseline, unit) {
12001
+ const values = baseline.filter((m) => m.metric === condition.metric && Object.entries(condition.labels).every(([k, v]) => m.labels[k] === v)).sort((a, b) => Date.parse(b.at) - Date.parse(a.at)).slice(0, BASELINE_RUNS).map((m) => unit && m.unit ? convertUnit(m.value, m.unit, unit) : m.value).filter((v) => v !== null && Number.isFinite(v)).sort((a, b) => a - b);
12002
+ if (!values.length) return void 0;
12003
+ const mid = Math.floor(values.length / 2);
12004
+ return { median: values.length % 2 ? values[mid] : (values[mid - 1] + values[mid]) / 2, runs: values.length };
12005
+ }
12006
+ var round = (n) => Math.round(n * 100) / 100;
12007
+ function evaluateMetric(condition, measurements, maxAge, now4, baseline = []) {
12008
+ const measurement = latestMeasurement(condition, measurements);
12009
+ if (!measurement) return { outcome: "not-run" };
12010
+ const age = now4 - Date.parse(measurement.at);
12011
+ if (condition.baseline) {
12012
+ if (maxAge !== void 0 && age > maxAge) return { outcome: "stale", measurement, detail: `measured ${formatAge(age)} ago` };
12013
+ const unit = measurement.unit;
12014
+ const base = baselineOf(condition, baseline, unit);
12015
+ if (!base) return { outcome: "not-run", measurement, detail: "no baseline to compare with" };
12016
+ const { sign, by, percent } = condition.baseline;
12017
+ let margin = percent ? base.median * by / 100 : by;
12018
+ if (!percent && condition.baseline.unit && unit) {
12019
+ const converted = convertUnit(by, condition.baseline.unit, unit);
12020
+ if (converted === null) return { outcome: "invalid", measurement, detail: `the measurement is in ${unit}, which ${condition.baseline.unit} does not convert to` };
12021
+ margin = converted;
12022
+ }
12023
+ const limit = base.median + sign * margin;
12024
+ const outcome = COMPARE[condition.op](measurement.value, limit) ? "passed" : "failed";
12025
+ return { outcome, measurement, detail: `baseline ${round(base.median)}${unit ? ` ${unit}` : ""}, the median of ${base.runs}; limit ${round(limit)}${unit ? ` ${unit}` : ""}` };
12026
+ }
12027
+ let value = measurement.value;
12028
+ if (condition.unit && measurement.unit) {
12029
+ const converted = convertUnit(measurement.value, measurement.unit, condition.unit);
12030
+ if (converted === null) return { outcome: "invalid", measurement, detail: `the measurement is in ${measurement.unit}, which does not convert to ${condition.unit}` };
12031
+ value = converted;
12032
+ }
12033
+ if (maxAge !== void 0 && age > maxAge) return { outcome: "stale", measurement, detail: `measured ${formatAge(age)} ago` };
12034
+ return { outcome: COMPARE[condition.op](value, condition.value) ? "passed" : "failed", measurement };
12035
+ }
12036
+
11408
12037
  // ../../packages/common/src/check/evidence.ts
11409
12038
  var TESTED_TYPES = ["scenario", "fitness-fn"];
11410
- var testIdsOf = (node) => parseTestIds(node.tests);
12039
+ var conditionsOf = (node) => parseConditions(node.metrics);
12040
+ var testIdsOf = (node) => conditionsOf(node).flatMap((c) => c.kind === "test" ? [c.id] : []);
12041
+ var testOutcome = (id, model) => {
12042
+ const { fileSeen, matches } = findTests(id, model.tests ?? []);
12043
+ return matches.length ? outcomeOf(matches) : fileSeen ? "not-found" : "not-run";
12044
+ };
11411
12045
  function testOutcomes(node, model) {
11412
- const cases = model.tests ?? [];
11413
- return testIdsOf(node).map((id) => {
11414
- const { fileSeen, matches } = findTests(id, cases);
11415
- return { id, outcome: matches.length ? outcomeOf(matches) : fileSeen ? "not-found" : "not-run" };
12046
+ return testIdsOf(node).map((id) => ({ id, outcome: testOutcome(id, model) }));
12047
+ }
12048
+ function conditionResults(node, model) {
12049
+ const maxAge = parseMaxAge(node.max_age) ?? void 0;
12050
+ const now4 = model.now ?? Date.now();
12051
+ return conditionsOf(node).map((c) => {
12052
+ if (c.kind === "invalid") return { condition: c.raw, outcome: "invalid", detail: c.problem };
12053
+ if (c.kind === "test") return { condition: c.raw, test: c.id.raw, outcome: testOutcome(c.id, model) };
12054
+ const e = evaluateMetric(c, model.measurements ?? [], maxAge, now4, model.baseline ?? []);
12055
+ return { condition: c.raw, outcome: e.outcome, ...e.measurement ? { measurement: e.measurement } : {}, ...e.detail ? { detail: e.detail } : {} };
11416
12056
  });
11417
12057
  }
11418
12058
  function linkedNodes(model, id, relationType, end, type) {
@@ -11565,7 +12205,8 @@ function buildConceptInsert(concept, options) {
11565
12205
  const offsetX = corner.x - (bounded ? minX : 0);
11566
12206
  const offsetY = corner.y - (bounded ? minY : 0);
11567
12207
  const nodes = {};
11568
- for (const raw of templated.nodes) {
12208
+ for (const node of templated.nodes) {
12209
+ const raw = migrateCheckFields(node);
11569
12210
  const oldId = raw.id;
11570
12211
  const id = idMap.get(oldId);
11571
12212
  const type = raw.type ?? "component";
@@ -11641,7 +12282,7 @@ function templateRecord(concept, paramValues, maps) {
11641
12282
  for (const origNode of concept.nodes) {
11642
12283
  const id = maps.node.get(origNode.id);
11643
12284
  if (!id) continue;
11644
- originalNodes[id] = origNode;
12285
+ originalNodes[id] = migrateCheckFields(origNode);
11645
12286
  const perNodeParams = origNode.templateParams;
11646
12287
  if (perNodeParams?.length) nodeParamsMap[id] = perNodeParams;
11647
12288
  }
@@ -11917,6 +12558,40 @@ function testRule(outcome, message) {
11917
12558
  }));
11918
12559
  };
11919
12560
  }
12561
+ var runsOn = (node, trigger) => {
12562
+ if (!trigger || node.type !== "fitness-fn") return true;
12563
+ const cadence = prop2(node, "cadence");
12564
+ if (!cadence) return true;
12565
+ return cadence === "triggered" && prop2(node, "trigger") === trigger;
12566
+ };
12567
+ function metricRule(outcome, message) {
12568
+ return (model) => {
12569
+ if (!model.measurements) return [];
12570
+ return Object.values(model.nodes).filter((n) => TESTED_TYPES.includes(n.type)).filter((n) => outcome !== "not-run" || runsOn(n, model.trigger)).flatMap((node) => {
12571
+ const metricLines = new Set(conditionsOf(node).filter((c) => c.kind === "metric").map((c) => c.raw));
12572
+ return conditionResults(node, model).filter((r) => r.outcome === outcome && metricLines.has(r.condition)).map((r) => {
12573
+ const m = r.measurement;
12574
+ const seen = m ? ` (${m.value}${m.unit ? ` ${m.unit}` : ""} from ${m.source}, ${formatAge((model.now ?? Date.now()) - Date.parse(m.at))} ago)` : "";
12575
+ const related = outcome === "failed" ? affectedBy(model, node).map((n) => n.id) : [];
12576
+ return { nodeId: node.id, message: message(node, r.condition, seen, r.detail), ...related.length ? { relatedIds: related } : {} };
12577
+ });
12578
+ });
12579
+ };
12580
+ }
12581
+ function invalidChecks(model) {
12582
+ return Object.values(model.nodes).filter((n) => TESTED_TYPES.includes(n.type)).flatMap((node) => {
12583
+ const what = `${TYPE_NAME[node.type]} ${quote(node)}`;
12584
+ const found = conditionsOf(node).flatMap((c) => c.kind === "invalid" ? [{ nodeId: node.id, message: `${what}: "${c.raw}" cannot be read: ${c.problem}.` }] : []);
12585
+ if (model.measurements) {
12586
+ for (const r of conditionResults(node, model)) {
12587
+ if (r.outcome === "invalid" && r.measurement) found.push({ nodeId: node.id, message: `${what}: "${r.condition}" cannot be evaluated: ${r.detail}.` });
12588
+ }
12589
+ }
12590
+ if (!parseCombine(prop2(node, "combine"))) found.push({ nodeId: node.id, message: `${what}: combine "${prop2(node, "combine")}" is none of all, any, at least N.` });
12591
+ if (parseMaxAge(prop2(node, "max_age")) === null) found.push({ nodeId: node.id, message: `${what}: max_age "${prop2(node, "max_age")}" is no age such as 7d, 12h or 30min.` });
12592
+ return found;
12593
+ });
12594
+ }
11920
12595
  var CHECK_RULES = [
11921
12596
  {
11922
12597
  id: "metamodel",
@@ -12048,25 +12723,45 @@ var CHECK_RULES = [
12048
12723
  }))
12049
12724
  },
12050
12725
  {
12051
- id: "fitness-fn-without-threshold",
12052
- description: "Every fitness function states its threshold or success criteria.",
12726
+ id: "scenario-without-metrics",
12727
+ description: "Every scenario states what checks it (property `metrics`, one condition per line: `test(<file> \u203A <title>) passed` or `<metric>{<labels>} <op> <number> [unit]`).",
12053
12728
  severity: "warning",
12054
- dimension: "completeness",
12055
- run: (model) => nodesOf(model, "fitness-fn").filter((n) => !prop2(n, "threshold")).map((n) => ({ nodeId: n.id, message: `Fitness function ${quote(n)} states no threshold.` }))
12729
+ dimension: "traceability",
12730
+ run: (model) => nodesOf(model, "scenario").filter((n) => !conditionsOf(n).length).map((n) => ({ nodeId: n.id, message: `Scenario ${quote(n)} names no check.` }))
12056
12731
  },
12057
12732
  {
12058
- id: "scenario-without-tests",
12059
- description: "Every scenario names the automated tests that run it (property `tests`, one `file \u203A title` per line).",
12733
+ id: "fitness-fn-without-metrics",
12734
+ description: "Every fitness function states what checks it and when it passes (property `metrics`, one condition per line).",
12060
12735
  severity: "warning",
12061
- dimension: "traceability",
12062
- run: (model) => nodesOf(model, "scenario").filter((n) => !testIdsOf(n).length).map((n) => ({ nodeId: n.id, message: `Scenario ${quote(n)} names no test.` }))
12736
+ dimension: "decisions",
12737
+ run: (model) => nodesOf(model, "fitness-fn").filter((n) => !conditionsOf(n).length).map((n) => ({ nodeId: n.id, message: `Fitness function ${quote(n)} names no check.` }))
12063
12738
  },
12064
12739
  {
12065
- id: "fitness-fn-without-tests",
12066
- description: "Every fitness function names the automated checks that run it (property `tests`).",
12740
+ id: "fitness-fn-unclassified",
12741
+ description: "Every fitness function states its characteristic (ISO/IEC 25010), scope, cadence (with the event it is triggered on, or how often a temporal one falls due) and invocation.",
12067
12742
  severity: "warning",
12068
12743
  dimension: "decisions",
12069
- run: (model) => nodesOf(model, "fitness-fn").filter((n) => !testIdsOf(n).length).map((n) => ({ nodeId: n.id, message: `Fitness function ${quote(n)} names no test.` }))
12744
+ run: (model) => nodesOf(model, "fitness-fn").flatMap((n) => {
12745
+ const missing = ["characteristic", "scope", "cadence"].filter((k) => !prop2(n, k));
12746
+ if (prop2(n, "cadence") === "triggered" && !prop2(n, "trigger")) missing.push("trigger");
12747
+ if (prop2(n, "cadence") === "temporal" && !prop2(n, "every")) missing.push("every");
12748
+ if (!prop2(n, "invocation")) missing.push("invocation");
12749
+ return missing.length ? [{ nodeId: n.id, message: `Fitness function ${quote(n)} states no ${missing.join(", ")}.` }] : [];
12750
+ })
12751
+ },
12752
+ {
12753
+ id: "fitness-fn-measure-invalid",
12754
+ description: `Every line of a fitness function's \`measure\` names a sensor of radical sense (${SENSOR_NAMES.join(", ")}).`,
12755
+ severity: "error",
12756
+ dimension: "completeness",
12757
+ run: (model) => nodesOf(model, "fitness-fn").flatMap((n) => parseMeasure(n.measure).filter((line) => !isSensorName(line.sensor)).map((line) => ({ nodeId: n.id, message: `Fitness function ${quote(n)}: measure "${line.raw}" names no sensor; radical sense has ${SENSOR_NAMES.join(", ")}.` })))
12758
+ },
12759
+ {
12760
+ id: "metric-invalid",
12761
+ description: "Every line of a scenario's or fitness function's `metrics` reads as a condition, its unit converts to the unit of the measurement it matches, and `combine` and `max_age` read.",
12762
+ severity: "error",
12763
+ dimension: "completeness",
12764
+ run: invalidChecks
12070
12765
  },
12071
12766
  {
12072
12767
  id: "test-failed",
@@ -12082,7 +12777,7 @@ var CHECK_RULES = [
12082
12777
  severity: "error",
12083
12778
  dimension: "tests",
12084
12779
  readsReports: true,
12085
- 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)}`)
12780
+ run: (model) => testRule("not-found", (node, id) => model.testsReadAt ? `${TYPE_NAME[node.type]} ${quote(node)}: no test ${id} in the test results read ${model.testsReadAt.slice(0, 10)}, ${formatAge((model.now ?? Date.now()) - Date.parse(model.testsReadAt))} ago; added since, renamed or deleted? radical check --report reads the tests again.` : `${TYPE_NAME[node.type]} ${quote(node)}: no test ${id} in the reports, though its file ran; renamed or deleted?${brokenWith(model, node)}`)(model).map((f) => model.testsReadAt ? { ...f, asOf: model.testsReadAt } : f)
12086
12781
  },
12087
12782
  {
12088
12783
  id: "test-skipped",
@@ -12100,6 +12795,30 @@ var CHECK_RULES = [
12100
12795
  readsReports: true,
12101
12796
  run: testRule("not-run", (node, id) => `${TYPE_NAME[node.type]} ${quote(node)}: no report has the file of test ${id}.`)
12102
12797
  },
12798
+ {
12799
+ id: "metric-failed",
12800
+ description: "With measurements: every metric condition a scenario or fitness function states holds for the latest measurement it matches.",
12801
+ severity: "error",
12802
+ dimension: "tests",
12803
+ readsMeasurements: true,
12804
+ run: metricRule("failed", (node, condition, seen, why) => `${TYPE_NAME[node.type]} ${quote(node)}: ${condition} does not hold${seen}${why ? `; ${why}` : ""}.`)
12805
+ },
12806
+ {
12807
+ id: "metric-stale",
12808
+ description: "With measurements: the latest measurement each metric condition matches is no older than the element's max_age (a stale one never passes).",
12809
+ severity: "warning",
12810
+ dimension: "tests",
12811
+ readsMeasurements: true,
12812
+ run: metricRule("stale", (node, condition, seen) => `${TYPE_NAME[node.type]} ${quote(node)}: ${condition} has only a stale measurement${seen}.`)
12813
+ },
12814
+ {
12815
+ id: "metric-not-measured",
12816
+ description: "With measurements: a measurement matches every metric condition a scenario or fitness function states.",
12817
+ severity: "warning",
12818
+ dimension: "tests",
12819
+ readsMeasurements: true,
12820
+ run: metricRule("not-run", (node, condition, seen, why) => why ? `${TYPE_NAME[node.type]} ${quote(node)}: ${condition} was not evaluated: ${why}${seen}.` : `${TYPE_NAME[node.type]} ${quote(node)}: nothing measured ${condition}.`)
12821
+ },
12103
12822
  {
12104
12823
  id: "test-unbound",
12105
12824
  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.",
@@ -12171,22 +12890,21 @@ var CHECK_METRICS = [
12171
12890
  byRule("elements-valid", "Elements the metamodel allows", "Elements no metamodel issue points at.", "consistency", "metamodel", (m) => Object.values(m.nodes)),
12172
12891
  byRule("requirements-complete", "Complete requirements", "Requirements with an action and every field their EARS type reads.", "completeness", "requirement-incomplete", (m) => nodesOf(m, "requirement")),
12173
12892
  byRule("adrs-complete", "Complete accepted ADRs", "Accepted ADRs with a date, context, decision and consequences.", "completeness", "adr-incomplete", acceptedAdrs),
12174
- 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")),
12175
12893
  byRule("needs-with-requirement", "Needs with a requirement", "Needs at least one requirement derives from.", "traceability", "need-without-requirement", (m) => nodesOf(m, "need")),
12176
12894
  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")),
12177
12895
  byRule("requirements-satisfied", "Requirements satisfied", "Requirements an element of the architecture satisfies.", "traceability", "requirement-unsatisfied", (m) => nodesOf(m, "requirement")),
12178
12896
  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),
12179
12897
  byRule("scenarios-verifying", "Scenarios that verify something", "Scenarios that verify a requirement or a state machine.", "traceability", "scenario-verifies-nothing", (m) => nodesOf(m, "scenario")),
12180
- 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")),
12898
+ byRule("scenarios-with-metrics", "Scenarios that name a check", "Scenarios whose Metrics property states the tests or measured values that check them.", "traceability", "scenario-without-metrics", (m) => nodesOf(m, "scenario")),
12181
12899
  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),
12182
12900
  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")),
12183
- 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")),
12901
+ byRule("fitness-fns-with-metrics", "Fitness functions that name a check", "Fitness functions whose Metrics property states the tests or measured values that check them.", "decisions", "fitness-fn-without-metrics", (m) => nodesOf(m, "fitness-fn")),
12184
12902
  {
12185
12903
  id: "requirements-verified",
12186
12904
  label: "Requirements verified",
12187
12905
  dimension: "behaviour",
12188
12906
  tests: true,
12189
- description: "Requirements whose scenarios all name tests that passed.",
12907
+ description: "Requirements whose scenarios all passed their checks.",
12190
12908
  measure: (ctx) => withStatus(nodesOf(ctx.model, "requirement"), ["verified"], ctx)
12191
12909
  },
12192
12910
  {
@@ -12194,7 +12912,7 @@ var CHECK_METRICS = [
12194
12912
  label: "Scenarios passing",
12195
12913
  dimension: "behaviour",
12196
12914
  tests: true,
12197
- description: "Scenarios whose tests all passed.",
12915
+ description: "Scenarios whose checks passed.",
12198
12916
  measure: (ctx) => withStatus(nodesOf(ctx.model, "scenario"), ["passed"], ctx)
12199
12917
  },
12200
12918
  {
@@ -12202,7 +12920,7 @@ var CHECK_METRICS = [
12202
12920
  label: "Accepted ADRs verified",
12203
12921
  dimension: "fitness",
12204
12922
  tests: true,
12205
- description: "Accepted ADRs whose fitness functions all name checks that passed.",
12923
+ description: "Accepted ADRs whose fitness functions all passed their checks.",
12206
12924
  measure: (ctx) => withStatus(acceptedAdrs(ctx.model), ["verified"], ctx)
12207
12925
  },
12208
12926
  {
@@ -12210,7 +12928,7 @@ var CHECK_METRICS = [
12210
12928
  label: "Fitness functions passing",
12211
12929
  dimension: "fitness",
12212
12930
  tests: true,
12213
- description: "Fitness functions whose checks all passed.",
12931
+ description: "Fitness functions whose checks passed.",
12214
12932
  measure: (ctx) => withStatus(nodesOf(ctx.model, "fitness-fn"), ["passed"], ctx)
12215
12933
  },
12216
12934
  {
@@ -12244,6 +12962,10 @@ var METRIC_IDS = new Set(CHECK_METRICS.map((m) => m.id));
12244
12962
  // ../../packages/common/src/check/files.ts
12245
12963
  init_define_RADICAL_BUILD();
12246
12964
  var TEST_RESULTS_FILE = `${SELECTION_DIR}/test-results.json`;
12965
+ var MEASUREMENTS_FILE = `${SELECTION_DIR}/measurements.json`;
12966
+
12967
+ // ../../packages/common/src/check/reviews.ts
12968
+ init_define_RADICAL_BUILD();
12247
12969
 
12248
12970
  // ../../packages/common/src/check/format.ts
12249
12971
  init_define_RADICAL_BUILD();
@@ -12274,7 +12996,9 @@ async function selectionDir(root2, create) {
12274
12996
  } catch (error) {
12275
12997
  if (error.code !== "ENOENT") throw error;
12276
12998
  if (!create) return null;
12277
- await mkdir(dir);
12999
+ await mkdir(dir).catch((e) => {
13000
+ if (e.code !== "EEXIST") throw e;
13001
+ });
12278
13002
  }
12279
13003
  return dir;
12280
13004
  }
@@ -12311,8 +13035,8 @@ var WRITE_LOCK = "write.lock";
12311
13035
  var LOCK_WAIT_MS = 15e3;
12312
13036
  var LOCK_STALE_MS = 15e3;
12313
13037
  var LOCK_UNREAD_MS = 1e3;
12314
- function staleLock(text, age) {
12315
- const [pid, since] = text.trim().split(" ").map(Number);
13038
+ function staleLock(text2, age) {
13039
+ const [pid, since] = text2.trim().split(" ").map(Number);
12316
13040
  if (!Number.isFinite(pid) || !Number.isFinite(since)) return age > LOCK_UNREAD_MS;
12317
13041
  if (Date.now() - since > LOCK_STALE_MS) return true;
12318
13042
  if (pid === process.pid) return false;
@@ -12394,14 +13118,27 @@ function diskFolderStorage(root2) {
12394
13118
  return abs;
12395
13119
  }
12396
13120
  return {
13121
+ readCache: (name) => MODEL_CACHE_NAMES.has(name) ? readEditorStateFile(base, `${MODEL_CACHE_DIR}/${name}`) : Promise.resolve(null),
13122
+ async writeCache(name, content) {
13123
+ if (!MODEL_CACHE_NAMES.has(name)) throw new Error(`not a cache file: ${name}`);
13124
+ await editorStateDir(base);
13125
+ const dir = join2(base, MODEL_CACHE_DIR);
13126
+ if (await lstat2(dir).then((s) => s.isSymbolicLink(), () => false)) throw new Error(`symlink in model path: ${MODEL_CACHE_DIR}`);
13127
+ await mkdir2(dir, { recursive: true });
13128
+ for (const name2 of await readdir(dir)) {
13129
+ if (!name2.endsWith(".part")) continue;
13130
+ const left = join2(dir, name2);
13131
+ if (await stat(left).then((st) => Date.now() - st.mtimeMs > 6e4, () => false)) await rm(left, { force: true });
13132
+ }
13133
+ const file = join2(dir, name);
13134
+ const part = `${file}.${randomUUID()}.part`;
13135
+ await writeFile2(part, content, "utf-8");
13136
+ await rename(part, file);
13137
+ },
12397
13138
  async list() {
12398
- const stamps = {};
12399
- const add = async (rel) => {
12400
- try {
12401
- stamps[rel] = stampOf(await stat(await inside(rel)));
12402
- } catch (error) {
12403
- if (error.code !== "ENOENT") throw error;
12404
- }
13139
+ const files = [];
13140
+ const add = (rel) => {
13141
+ files.push(rel);
12405
13142
  };
12406
13143
  const walk = async (rel) => {
12407
13144
  const entries = await readdir(await inside(`${rel}/_index.md`).then(dirname2), { withFileTypes: true });
@@ -12409,18 +13146,29 @@ function diskFolderStorage(root2) {
12409
13146
  if (entry.name.startsWith(".")) continue;
12410
13147
  const child = `${rel}/${entry.name}`;
12411
13148
  if (entry.isDirectory()) await walk(child);
12412
- else if (entry.isFile() && isMdFolderModelPath(child)) await add(child);
13149
+ else if (entry.isFile() && isMdFolderModelPath(child)) add(child);
12413
13150
  else if (entry.isSymbolicLink()) throw new Error(`symlink in model path: ${child}`);
12414
13151
  }
12415
13152
  };
12416
13153
  const top = await readdir(base, { withFileTypes: true });
12417
13154
  for (const entry of top) {
12418
- if (entry.isFile() && isMdFolderModelPath(entry.name)) await add(entry.name);
13155
+ if (entry.isFile() && isMdFolderModelPath(entry.name)) add(entry.name);
12419
13156
  else if (entry.isDirectory() && entry.name === "nodes") await walk("nodes");
12420
13157
  else if (entry.isSymbolicLink() && (entry.name === "nodes" || isMdFolderModelPath(entry.name))) {
12421
13158
  throw new Error(`symlink in model path: ${entry.name}`);
12422
13159
  }
12423
13160
  }
13161
+ const found = await readEach(files, async (rel) => {
13162
+ try {
13163
+ return stampOf(await stat(await inside(rel)));
13164
+ } catch (error) {
13165
+ if (error.code !== "ENOENT") throw error;
13166
+ }
13167
+ });
13168
+ const stamps = {};
13169
+ files.forEach((rel, i) => {
13170
+ if (found[i] !== void 0) stamps[rel] = found[i];
13171
+ });
12424
13172
  return stamps;
12425
13173
  },
12426
13174
  // Decoded as the browser decodes a file: without a byte-order mark.
@@ -12577,10 +13325,10 @@ function serializeModelBase(base, now4 = /* @__PURE__ */ new Date()) {
12577
13325
  `;
12578
13326
  }
12579
13327
  var isRecord = (value) => !!value && typeof value === "object" && !Array.isArray(value);
12580
- function parseModelBase(text) {
13328
+ function parseModelBase(text2) {
12581
13329
  let raw;
12582
13330
  try {
12583
- raw = JSON.parse(text);
13331
+ raw = JSON.parse(text2);
12584
13332
  } catch {
12585
13333
  return null;
12586
13334
  }
@@ -12600,7 +13348,9 @@ function parseModelBase(text) {
12600
13348
  described,
12601
13349
  branch,
12602
13350
  savedAt,
12603
- nodes,
13351
+ // A base saved before `metrics` reads as the model now does, or every
13352
+ // scenario and fitness function would count as changed on the branch.
13353
+ nodes: nodes.map((n) => migrateCheckFields(n)),
12604
13354
  relations
12605
13355
  };
12606
13356
  }
@@ -12730,13 +13480,13 @@ async function modelChangesSince(folder, current, since, options = {}) {
12730
13480
  const short = base.commit.slice(0, 7);
12731
13481
  const where = base.commit.startsWith(base.described) ? short : `${base.described} (${short})`;
12732
13482
  const count = (group, noun) => `${noun}: ${group.added.length} added, ${group.changed.length} changed, ${group.removed.length} removed`;
12733
- const text = countModelChanges(report) === 0 ? `No model changes since ${where}: the elements and relations are as they were (views and layout are not compared).` : [
13483
+ const text2 = countModelChanges(report) === 0 ? `No model changes since ${where}: the elements and relations are as they were (views and layout are not compared).` : [
12734
13484
  `Model changes since ${where}, uncommitted edits included; elements and relations only, views and layout left out.`,
12735
13485
  `${count(report.elements, "Elements")}. ${count(report.relations, "Relations")}.${!Object.keys(files).length ? " The folder held no model then." : from ? ` The folder was ${from} then.` : ""}`,
12736
13486
  "",
12737
13487
  formatModelChanges(report, before, after)
12738
13488
  ].join("\n");
12739
- return { base, report, text };
13489
+ return { base, report, text: text2 };
12740
13490
  }
12741
13491
 
12742
13492
  // ../../packages/common/src/formats/agentActivity.ts
@@ -13718,11 +14468,11 @@ var ADVANCE = {
13718
14468
  }
13719
14469
  };
13720
14470
  var OTHER_ADVANCE = 600;
13721
- var tableMeasure = (text, fontSize, italic) => {
14471
+ var tableMeasure = (text2, fontSize, italic) => {
13722
14472
  const sized = ADVANCE[fontSize < 11 ? 10 : 12];
13723
14473
  const table = italic ? sized.italic : sized.upright;
13724
14474
  let w = 0;
13725
- for (const ch of text) {
14475
+ for (const ch of text2) {
13726
14476
  const c = ch.codePointAt(0);
13727
14477
  w += c >= 32 && c < 127 ? table[c - 32] : c >= 11904 ? 1e3 : OTHER_ADVANCE;
13728
14478
  }
@@ -13730,7 +14480,7 @@ var tableMeasure = (text, fontSize, italic) => {
13730
14480
  };
13731
14481
  var measured = /* @__PURE__ */ new Map();
13732
14482
  var canvas;
13733
- var measureText = (text, fontSize, italic) => {
14483
+ var measureText = (text2, fontSize, italic) => {
13734
14484
  if (canvas === void 0) {
13735
14485
  const Canvas = globalThis.OffscreenCanvas;
13736
14486
  try {
@@ -13739,14 +14489,14 @@ var measureText = (text, fontSize, italic) => {
13739
14489
  canvas = null;
13740
14490
  }
13741
14491
  }
13742
- if (!canvas) return tableMeasure(text, fontSize, italic);
14492
+ if (!canvas) return tableMeasure(text2, fontSize, italic);
13743
14493
  const font = labelFont(fontSize, italic);
13744
- const key = `${font}|${text}`;
14494
+ const key = `${font}|${text2}`;
13745
14495
  let w = measured.get(key);
13746
14496
  if (w === void 0) {
13747
14497
  if (measured.size > 2e4) measured.clear();
13748
14498
  canvas.font = font;
13749
- w = canvas.measureText(text).width;
14499
+ w = canvas.measureText(text2).width;
13750
14500
  measured.set(key, w);
13751
14501
  }
13752
14502
  return w;
@@ -13801,7 +14551,7 @@ function relationLabelLines(r, nodes) {
13801
14551
  const lines = [];
13802
14552
  const name = r.label || (r.relationType === "transition" ? nodes ? transitionLabel(r, nodes) : "" : r.typeName ?? r.relationType);
13803
14553
  const italic = !r.label && r.relationType !== "transition";
13804
- if (name) for (const text of name.split("\n")) lines.push({ text, fontSize: RELATION_LABEL_BOX.fontSize, maxRows: RELATION_LABEL_BOX.nameRows, italic });
14554
+ if (name) for (const text2 of name.split("\n")) lines.push({ text: text2, fontSize: RELATION_LABEL_BOX.fontSize, maxRows: RELATION_LABEL_BOX.nameRows, italic });
13805
14555
  if (r.technology) lines.push({ text: `[${r.technology}]`, fontSize: RELATION_LABEL_BOX.techFontSize, maxRows: 1, italic: true, nowrap: true });
13806
14556
  return lines;
13807
14557
  }
@@ -14546,7 +15296,7 @@ function boxOf(nodes, positions, id) {
14546
15296
  height: p?.height ?? n.height
14547
15297
  };
14548
15298
  }
14549
- function childrenByParent(nodes) {
15299
+ function childrenByParent2(nodes) {
14550
15300
  const byParent = /* @__PURE__ */ new Map();
14551
15301
  for (const n of Object.values(nodes)) {
14552
15302
  if (!n.parentId || !nodes[n.parentId]) continue;
@@ -14599,7 +15349,7 @@ function finalize(nodes, positions, separate, gaps) {
14599
15349
  const gapsOf = (ids) => gaps && gaps.size > 0 ? (i, j) => gaps.get(pairKey(ids[i], ids[j])) : void 0;
14600
15350
  const out = {};
14601
15351
  for (const id of Object.keys(nodes)) out[id] = boxOf(nodes, positions, id);
14602
- const byParent = childrenByParent(nodes);
15352
+ const byParent = childrenByParent2(nodes);
14603
15353
  const parentIds = [...byParent.keys()].sort((a, b) => depthOf(nodes, b) - depthOf(nodes, a));
14604
15354
  for (const pid of parentIds) {
14605
15355
  const childIds = byParent.get(pid);
@@ -14925,7 +15675,7 @@ function enforceAlignments(nodes, positions, alignments, fixed = /* @__PURE__ */
14925
15675
  }
14926
15676
  separate(byParent.get(void 0) ?? [], ROOT_GAP);
14927
15677
  };
14928
- for (let round = 0; round < MAX_ROUNDS; round++) {
15678
+ for (let round2 = 0; round2 < MAX_ROUNDS; round2++) {
14929
15679
  snap3();
14930
15680
  tidy();
14931
15681
  if (alignmentError(nodes, boxes, alignments) <= TOLERANCE) break;
@@ -14939,7 +15689,22 @@ function enforceAlignments(nodes, positions, alignments, fixed = /* @__PURE__ */
14939
15689
 
14940
15690
  // ../../packages/layout/src/liveColaEngine.ts
14941
15691
  init_define_RADICAL_BUILD();
15692
+ var import_webcola2 = __toESM(require_dist(), 1);
15693
+
15694
+ // ../../packages/layout/src/webcolaHeap.ts
15695
+ init_define_RADICAL_BUILD();
14942
15696
  var import_webcola = __toESM(require_dist(), 1);
15697
+ function mergePairs(lessThan) {
15698
+ const subheaps = this.subheaps;
15699
+ if (subheaps.length === 0) return new import_webcola.PairingHeap(null);
15700
+ if (subheaps.length === 1) return subheaps[0];
15701
+ const pairs = [];
15702
+ while (subheaps.length >= 2) pairs.push(subheaps.pop().merge(subheaps.pop(), lessThan));
15703
+ let rest = subheaps.length === 1 ? subheaps[0] : new import_webcola.PairingHeap(null);
15704
+ for (let i = pairs.length - 1; i >= 0; i--) rest = pairs[i].merge(rest, lessThan);
15705
+ return rest;
15706
+ }
15707
+ import_webcola.PairingHeap.prototype.mergePairs = mergePairs;
14943
15708
 
14944
15709
  // ../../node_modules/d3-dispatch/src/index.js
14945
15710
  init_define_RADICAL_BUILD();
@@ -16539,7 +17304,7 @@ var LiveColaEngine = class {
16539
17304
  const frame2 = this.frameOf(g);
16540
17305
  return frame2 ? [[g.c4id, frame2]] : [];
16541
17306
  }));
16542
- for (const leaf of this.leavesOf(nodeId)) import_webcola.Layout.dragStart(leaf);
17307
+ for (const leaf of this.leavesOf(nodeId)) import_webcola2.Layout.dragStart(leaf);
16543
17308
  this.calm = this.calmDrag(nodeId, withIds, abs ?? { x: rfX, y: rfY }, { x: 0, y: 0 });
16544
17309
  this.offLinesAtGrab = new Set(this.groupAlignments.filter((a) => this.offLine(a)).map(groupLineKey));
16545
17310
  this.followedInDrag = /* @__PURE__ */ new Set();
@@ -16555,13 +17320,13 @@ var LiveColaEngine = class {
16555
17320
  for (const leaf of this.leavesOf(nodeId)) leaf.fixed = (leaf.fixed ?? 0) & ~PINNED;
16556
17321
  const cn = this.idToNode.get(nodeId);
16557
17322
  if (cn) {
16558
- import_webcola.Layout.dragStart(cn);
17323
+ import_webcola2.Layout.dragStart(cn);
16559
17324
  } else {
16560
17325
  const leaves = this.groupLeaves(nodeId);
16561
17326
  this._dragStartPositions.clear();
16562
17327
  for (const leaf of leaves) {
16563
17328
  this._dragStartPositions.set(leaf.c4id, { x: leaf.x, y: leaf.y });
16564
- import_webcola.Layout.dragStart(leaf);
17329
+ import_webcola2.Layout.dragStart(leaf);
16565
17330
  }
16566
17331
  }
16567
17332
  }
@@ -16576,7 +17341,7 @@ var LiveColaEngine = class {
16576
17341
  this.unfreeze();
16577
17342
  for (const id of [this.calm.id, ...this.calm.with]) {
16578
17343
  for (const leaf of this.leavesOf(id)) {
16579
- import_webcola.Layout.dragEnd(leaf);
17344
+ import_webcola2.Layout.dragEnd(leaf);
16580
17345
  leaf.fixed = (leaf.fixed ?? 0) & ~PINNED;
16581
17346
  }
16582
17347
  }
@@ -16599,7 +17364,7 @@ var LiveColaEngine = class {
16599
17364
  const cn = this.idToNode.get(nodeId);
16600
17365
  if (cn) {
16601
17366
  const abs2 = this.rfToAbsCenter(nodeId, rfX, rfY, cn.realWidth, cn.realHeight);
16602
- import_webcola.Layout.drag(cn, abs2);
17367
+ import_webcola2.Layout.drag(cn, abs2);
16603
17368
  } else {
16604
17369
  const g = this.idToGroup.get(nodeId);
16605
17370
  if (g) {
@@ -16626,7 +17391,7 @@ var LiveColaEngine = class {
16626
17391
  for (const leaf of this.groupLeaves(nodeId)) {
16627
17392
  const sp = this._dragStartPositions.get(leaf.c4id);
16628
17393
  if (sp) {
16629
- import_webcola.Layout.drag(leaf, { x: sp.x + dx, y: sp.y + dy });
17394
+ import_webcola2.Layout.drag(leaf, { x: sp.x + dx, y: sp.y + dy });
16630
17395
  }
16631
17396
  }
16632
17397
  }
@@ -16644,7 +17409,7 @@ var LiveColaEngine = class {
16644
17409
  this.calm = null;
16645
17410
  if (calm && !calm.moving) {
16646
17411
  this.framesAtGrab.clear();
16647
- for (const leaf of this.leavesOf(calm.id)) import_webcola.Layout.dragEnd(leaf);
17412
+ for (const leaf of this.leavesOf(calm.id)) import_webcola2.Layout.dragEnd(leaf);
16648
17413
  this.applyPins();
16649
17414
  return;
16650
17415
  }
@@ -16680,10 +17445,10 @@ var LiveColaEngine = class {
16680
17445
  held[1][i] = cn.py;
16681
17446
  }
16682
17447
  }
16683
- import_webcola.Layout.dragEnd(cn);
17448
+ import_webcola2.Layout.dragEnd(cn);
16684
17449
  } else {
16685
17450
  for (const leaf of this.groupLeaves(nodeId)) {
16686
- import_webcola.Layout.dragEnd(leaf);
17451
+ import_webcola2.Layout.dragEnd(leaf);
16687
17452
  }
16688
17453
  this._dragStartPositions.clear();
16689
17454
  }
@@ -16848,10 +17613,10 @@ var LiveColaEngine = class {
16848
17613
  refreshBounds() {
16849
17614
  for (const cn of this.colaNodes) {
16850
17615
  ;
16851
- cn.bounds = new import_webcola.Rectangle(cn.x - cn.width / 2, cn.x + cn.width / 2, cn.y - cn.height / 2, cn.y + cn.height / 2);
17616
+ cn.bounds = new import_webcola2.Rectangle(cn.x - cn.width / 2, cn.x + cn.width / 2, cn.y - cn.height / 2, cn.y + cn.height / 2);
16852
17617
  }
16853
17618
  for (const g of this.colaGroups) {
16854
- if (!g.parent) (0, import_webcola.computeGroupBounds)(g);
17619
+ if (!g.parent) (0, import_webcola2.computeGroupBounds)(g);
16855
17620
  }
16856
17621
  }
16857
17622
  /** An element's box as the canvas draws it: a leaf from its top-left at
@@ -17110,7 +17875,7 @@ var LiveColaEngine = class {
17110
17875
  const kids = this.childrenOf.get(level) ?? [];
17111
17876
  const covers = (a, b) => Math.min(a.X, b.X) - Math.max(a.x, b.x) > REPORT_PX && Math.min(a.Y, b.Y) - Math.max(a.y, b.y) > REPORT_PX;
17112
17877
  const stuck = /* @__PURE__ */ new Set();
17113
- for (let round = 0; round <= kids.length; round++) {
17878
+ for (let round2 = 0; round2 <= kids.length; round2++) {
17114
17879
  let stray;
17115
17880
  for (const t of moved) {
17116
17881
  const T = this.boxOf(t);
@@ -17292,7 +18057,7 @@ var LiveColaEngine = class {
17292
18057
  return p;
17293
18058
  };
17294
18059
  const visibleNodes = Object.values(nodes).filter((n) => isVisible(n, nodes) && !frameIds.has(n.id));
17295
- if (visibleNodes.length === 0) {
18060
+ if (visibleNodes.length === 0 || visibleNodes.length > CANVAS_MAX_ELEMENTS) {
17296
18061
  this.cola = null;
17297
18062
  this.seedPositions.clear();
17298
18063
  return;
@@ -17457,7 +18222,7 @@ var LiveColaEngine = class {
17457
18222
  this.childrenOf.set(level, list);
17458
18223
  }
17459
18224
  const d3Context = { dispatch: dispatch_default, timer, drag: drag_default, event: null };
17460
- const layout = (0, import_webcola.d3adaptor)(d3Context);
18225
+ const layout = (0, import_webcola2.d3adaptor)(d3Context);
17461
18226
  layout.nodes(this.colaNodes).links(colaLinks).groups(this.colaGroups).size([1800, 1200]).avoidOverlaps(true).handleDisconnected(false).linkDistance((link2) => {
17462
18227
  const s = link2.source;
17463
18228
  const t = link2.target;
@@ -18019,16 +18784,18 @@ function computeViewCollapsedSet(viewFilter, allNodes) {
18019
18784
  const result = /* @__PURE__ */ new Set();
18020
18785
  if (!viewFilter) return result;
18021
18786
  const parentHasViewChild = /* @__PURE__ */ new Set();
18787
+ const parents = /* @__PURE__ */ new Set();
18022
18788
  for (const n of Object.values(allNodes)) {
18023
- if (n.parentId && viewFilter.has(n.id)) parentHasViewChild.add(n.parentId);
18789
+ if (!n.parentId) continue;
18790
+ parents.add(n.parentId);
18791
+ if (viewFilter.has(n.id)) parentHasViewChild.add(n.parentId);
18024
18792
  }
18025
18793
  for (const [id, n] of Object.entries(allNodes)) {
18026
18794
  if (!viewFilter.has(id)) continue;
18027
18795
  if (!isContainerType(n.type)) continue;
18028
18796
  if (n.collapsed) continue;
18029
18797
  if (parentHasViewChild.has(id)) continue;
18030
- const hasChildInModel = Object.values(allNodes).some((c) => c.parentId === id);
18031
- if (hasChildInModel) result.add(id);
18798
+ if (parents.has(id)) result.add(id);
18032
18799
  }
18033
18800
  return result;
18034
18801
  }
@@ -19698,7 +20465,7 @@ function unchangedResult(nodes, relations, style = "curved") {
19698
20465
  }
19699
20466
  async function runSmartLayoutELKPhase(inputNodes, inputRelations, metamodel, onProgress) {
19700
20467
  const { nodes, relations } = projectToVisibleGraph(inputNodes, inputRelations);
19701
- const { applyElkLayout } = await import("./elkLayout-TAUBPPVN.js");
20468
+ const { applyElkLayout } = await import("./elkLayout-VYJDCCIT.js");
19702
20469
  const depth2 = maxContainmentDepth(metamodel);
19703
20470
  const mmDirection = depth2 >= 2 ? "RIGHT" : "DOWN";
19704
20471
  const engines = [
@@ -21978,7 +22745,7 @@ function tidyOnce(inputNodes, inputRelations, options, spent) {
21978
22745
  const level = (ds) => ds.every((m) => Math.abs(m.d - ds[0].d) < 0.01);
21979
22746
  const shift = (a, id, d) => l.moveBy(id, a.axis === "x" ? d : 0, a.axis === "y" ? d : 0);
21980
22747
  const repair = (follow) => {
21981
- for (let round = 0; round < 3; round++) {
22748
+ for (let round2 = 0; round2 < 3; round2++) {
21982
22749
  let off = false;
21983
22750
  for (const a of alignments) {
21984
22751
  const ds = offsets(a);
@@ -22292,7 +23059,7 @@ function tidyOnce(inputNodes, inputRelations, options, spent) {
22292
23059
  }
22293
23060
  stale = null;
22294
23061
  improve();
22295
- for (let round = 0; round < 3; round++) {
23062
+ for (let round2 = 0; round2 < 3; round2++) {
22296
23063
  const done = steps.length;
22297
23064
  gather(true);
22298
23065
  if (steps.length === done || outOfTime()) break;
@@ -22481,10 +23248,10 @@ function formatClarificationAnswers(questions, answers) {
22481
23248
  for (const q of questions) {
22482
23249
  if (q.id === CONCERNS_QUESTION_ID || q.id.startsWith(CONCERN_QUESTION_PREFIX)) continue;
22483
23250
  const a = answers[q.id];
22484
- const text = Array.isArray(a) ? a.join(", ") : (a ?? "").trim();
22485
- if (!text) continue;
23251
+ const text2 = Array.isArray(a) ? a.join(", ") : (a ?? "").trim();
23252
+ if (!text2) continue;
22486
23253
  lines.push(`Q: ${q.question}
22487
- A: ${text}`);
23254
+ A: ${text2}`);
22488
23255
  }
22489
23256
  return lines.join("\n\n");
22490
23257
  }
@@ -22497,8 +23264,8 @@ init_define_RADICAL_BUILD();
22497
23264
  var WIREFRAME_WIDTH = 400;
22498
23265
  var WIREFRAME_HEIGHT = 300;
22499
23266
  var MAX_WIREFRAME_CHARS = 2e4;
22500
- function sanitizeWireframeSvg(text) {
22501
- const match = text.match(/<svg[\s\S]*?<\/svg>/i);
23267
+ function sanitizeWireframeSvg(text2) {
23268
+ const match = text2.match(/<svg[\s\S]*?<\/svg>/i);
22502
23269
  if (!match) return null;
22503
23270
  let svg = match[0];
22504
23271
  svg = svg.replace(/<script[\s\S]*?<\/script>/gi, "").replace(/<script[^>]*\/>/gi, "").replace(/<foreignObject[\s\S]*?<\/foreignObject>/gi, "").replace(/\son[a-z]+\s*=\s*("[^"]*"|'[^']*'|[^\s>]+)/gi, "").replace(/\s(?:xlink:)?href\s*=\s*("(?!#)[^"]*"|'(?!#)[^']*')/gi, "");
@@ -23014,7 +23781,7 @@ function describeRefinement(r) {
23014
23781
  }
23015
23782
  var CHECK_RULES_AFTER = {
23016
23783
  requirements: ["requirement-incomplete", "requirement-without-origin", "need-without-requirement"],
23017
- fitness: ["fitness-fn-without-threshold"],
23784
+ fitness: ["fitness-fn-without-metrics", "metric-invalid"],
23018
23785
  scenarios: ["requirement-without-scenario", "scenario-verifies-nothing"],
23019
23786
  c4: ["requirement-unsatisfied", "fitness-fn-unlinked"]
23020
23787
  };
@@ -23254,9 +24021,9 @@ init_define_RADICAL_BUILD();
23254
24021
  function slugify2(label) {
23255
24022
  return label.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "") || "feature";
23256
24023
  }
23257
- function indentBlock(text, spaces) {
24024
+ function indentBlock(text2, spaces) {
23258
24025
  const pad = " ".repeat(spaces);
23259
- return text.replace(/\r\n/g, "\n").split("\n").map((line) => line.trim() ? pad + line.trim() : "").filter(Boolean).join("\n");
24026
+ return text2.replace(/\r\n/g, "\n").split("\n").map((line) => line.trim() ? pad + line.trim() : "").filter(Boolean).join("\n");
23260
24027
  }
23261
24028
  function scenarioSteps(scenario) {
23262
24029
  const given = String(scenario.given ?? "").trim();
@@ -23319,8 +24086,8 @@ function buildGherkinFiles(nodes, relations) {
23319
24086
 
23320
24087
  // ../../packages/common/src/hubFormat.ts
23321
24088
  init_define_RADICAL_BUILD();
23322
- var PREVIEW_KEYS = ["ears_type", "priority", "status", "category", "trigger"];
23323
- var SEARCH_KEYS = ["label", "description", "trigger", "action", "threshold", "decision"];
24089
+ var PREVIEW_KEYS = ["ears_type", "priority", "status", "characteristic", "trigger"];
24090
+ var SEARCH_KEYS = ["label", "description", "trigger", "action", "metrics", "threshold", "decision"];
23324
24091
  var SEARCH_TEXT_MAX = 600;
23325
24092
  function searchTextOf(nodes) {
23326
24093
  const parts = [];
@@ -23330,8 +24097,8 @@ function searchTextOf(nodes) {
23330
24097
  if (typeof v === "string" && v.trim()) parts.push(v.replace(/\{\{[A-Z0-9_]+\}\}/g, " ").replace(/\s+/g, " ").trim());
23331
24098
  }
23332
24099
  }
23333
- const text = [...new Set(parts)].join(" \xB7 ");
23334
- return text.length > SEARCH_TEXT_MAX ? `${text.slice(0, SEARCH_TEXT_MAX).replace(/\s+\S*$/, "")}\u2026` : text;
24100
+ const text2 = [...new Set(parts)].join(" \xB7 ");
24101
+ return text2.length > SEARCH_TEXT_MAX ? `${text2.slice(0, SEARCH_TEXT_MAX).replace(/\s+\S*$/, "")}\u2026` : text2;
23335
24102
  }
23336
24103
  function conceptFile(meta) {
23337
24104
  return `${meta.category}/${meta.id}.radical`;
@@ -24076,14 +24843,14 @@ var Forge = class {
24076
24843
  });
24077
24844
  if (!trial.ok) return fail2(`forge_propose_refinement: ${trial.text} Fix the proposal before you ask the user.`);
24078
24845
  const proposalId = `p${state.proposals + 1}`;
24079
- const text = [
24846
+ const text2 = [
24080
24847
  `Proposal ${proposalId}: nothing is written yet. Show the user exactly this, ask whether to add it, and wait for the answer; they may also reply.`,
24081
24848
  "",
24082
24849
  formatProposal(proposal, lines),
24083
24850
  "",
24084
24851
  `Then call forge_answer_refinement with stage "${id}", proposal "${proposalId}", accept true or false, and their reply if they gave one. Until then the model tools write nothing.`
24085
24852
  ].join("\n");
24086
- return ok(text, { readOnly: true, commit: () => {
24853
+ return ok(text2, { readOnly: true, commit: () => {
24087
24854
  state.pending = { id: proposalId, proposal };
24088
24855
  state.proposals++;
24089
24856
  } });
@@ -24363,11 +25130,11 @@ function checkData(data) {
24363
25130
  }
24364
25131
  }
24365
25132
  }
24366
- async function startIfEmpty(path, preset) {
25133
+ async function startIfEmpty(path, preset2) {
24367
25134
  await mkdir4(path, { recursive: true });
24368
25135
  if (!(await readdir2(path)).every((name) => name.startsWith("."))) return;
24369
25136
  const session = new MdFolderSession(diskFolderStorage(path));
24370
- const created = await session.write(serializeToMdFolder({ nodes: [], relations: [], metamodel: PRESETS[preset]() }, basename(path)));
25137
+ const created = await session.write(serializeToMdFolder({ nodes: [], relations: [], metamodel: PRESETS[preset2]() }, basename(path)));
24371
25138
  if (!created.ok) throw new Error(`Could not start a model in ${path}: it changed while being written`);
24372
25139
  }
24373
25140
  var byId3 = (items) => Object.fromEntries(items.map((item) => [item.id, item]));
@@ -24451,8 +25218,8 @@ function settleViewFolds(before, after) {
24451
25218
  }
24452
25219
  }
24453
25220
  var FolderModel = class _FolderModel {
24454
- constructor(folder, preset, metamodel) {
24455
- this.preset = preset;
25221
+ constructor(folder, preset2, metamodel) {
25222
+ this.preset = preset2;
24456
25223
  this.tempIds = /* @__PURE__ */ new Map();
24457
25224
  this.forge = new Forge();
24458
25225
  this.tail = Promise.resolve();
@@ -24520,15 +25287,17 @@ var FolderModel = class _FolderModel {
24520
25287
  static async open(folder, options = {}) {
24521
25288
  if (!folder) throw new Error("--folder is required");
24522
25289
  const path = resolve4(folder);
24523
- const preset = options.metamodel ?? "radical";
24524
- await startIfEmpty(path, preset);
25290
+ const preset2 = options.metamodel ?? "radical";
25291
+ await startIfEmpty(path, preset2);
24525
25292
  const canonical2 = await realpath(path);
24526
25293
  if (!(await stat3(canonical2)).isDirectory()) throw new Error(`Not a directory: ${folder}`);
24527
- const files = await new MdFolderSession(diskFolderStorage(canonical2)).readAll();
25294
+ const opening = new MdFolderSession(diskFolderStorage(canonical2));
25295
+ const files = await opening.readAll();
25296
+ await opening.cacheWritten();
24528
25297
  checkFiles(files);
24529
25298
  const data = deserializeFromMdFolder(files).data;
24530
25299
  checkData(data);
24531
- return new _FolderModel(canonical2, preset, createModelFacade(data).getMetamodel?.());
25300
+ return new _FolderModel(canonical2, preset2, createModelFacade(data).getMetamodel?.());
24532
25301
  }
24533
25302
  /** Writes where the agent's Forge run stands for Studio to show. A failed
24534
25303
  * write never fails the call: the status is a convenience. */
@@ -24576,6 +25345,7 @@ var FolderModel = class _FolderModel {
24576
25345
  await startIfEmpty(this.folder, this.preset);
24577
25346
  const session = new MdFolderSession(diskFolderStorage(this.folder));
24578
25347
  const before = await session.readAll();
25348
+ await session.cacheWritten();
24579
25349
  checkFiles(before);
24580
25350
  const data = deserializeFromMdFolder(before).data;
24581
25351
  checkData(data);
@@ -24600,15 +25370,15 @@ var FolderModel = class _FolderModel {
24600
25370
  /** The canvas selection Studio wrote into the folder, resolved against
24601
25371
  * the model as it is now. */
24602
25372
  async selection(facade) {
24603
- const text = await readEditorStateFile(this.folder, SELECTION_FILE);
24604
- if (text === null) {
25373
+ const text2 = await readEditorStateFile(this.folder, SELECTION_FILE);
25374
+ if (text2 === null) {
24605
25375
  return "No selection: Studio has not had this folder open with a selection yet. Open the same folder in Studio and select something, or ask the user which element they mean.";
24606
25376
  }
24607
- const selection2 = parseSelection(text);
25377
+ const selection2 = parseSelection(text2);
24608
25378
  if (!selection2) {
24609
25379
  const version = (() => {
24610
25380
  try {
24611
- return JSON.parse(text).version;
25381
+ return JSON.parse(text2).version;
24612
25382
  } catch {
24613
25383
  return void 0;
24614
25384
  }
@@ -24694,8 +25464,8 @@ ${buildMetamodelMessage(metamodel2)}` };
24694
25464
  if (name === "get_issues") {
24695
25465
  const mm = facade.getMetamodel?.();
24696
25466
  const issues = mm ? issuesOf(data, mm) : [];
24697
- const text = issues.length ? issues.map(formatIssue).join("\n") : "No issues: the model follows its metamodel.";
24698
- return { ok: true, text: [text, ...this.openConcerns(data, mm)].join("\n") };
25467
+ const text2 = issues.length ? issues.map(formatIssue).join("\n") : "No issues: the model follows its metamodel.";
25468
+ return { ok: true, text: [text2, ...this.openConcerns(data, mm)].join("\n") };
24699
25469
  }
24700
25470
  if (name === "get_selection") return { ok: true, text: await this.selection(facade) };
24701
25471
  if (name === "get_changes") {
@@ -24791,7 +25561,7 @@ ${buildMetamodelMessage(metamodel2)}` };
24791
25561
  if (!result.candidates.length) return { ok: false, text: "Smart Layout: no candidate produced a result." };
24792
25562
  if (result.keptCurrent) {
24793
25563
  if (view && !Object.keys(view.positions ?? {}).length) {
24794
- view.positions = viewCanvasPositions(view, nodes, positionsOf(nodes), viewDrawnIds(view, nodes, byId3(changed.relations)));
25564
+ view.positions = viewCanvasPositions(view, nodes, positionsOf2(nodes), viewDrawnIds(view, nodes, byId3(changed.relations)));
24795
25565
  return { ok: true, changed, text: `Smart Layout (${view.name}): nothing left to tidy; the view keeps its places.` };
24796
25566
  }
24797
25567
  const where = view ? ` (${view.name})` : "";
@@ -24806,7 +25576,7 @@ ${buildMetamodelMessage(metamodel2)}` };
24806
25576
  else changed.defaultLayoutConstraints = changed.defaultLayoutConstraints?.filter((c) => c.type !== "pin");
24807
25577
  }
24808
25578
  applyAlignments(nodes, viewLayoutInput(view, nodes, byId3(changed.relations), constraints));
24809
- if (view) view.positions = viewCanvasPositions(view, nodes, positionsOf(nodes), viewDrawnIds(view, nodes, byId3(changed.relations)));
25579
+ if (view) view.positions = viewCanvasPositions(view, nodes, positionsOf2(nodes), viewDrawnIds(view, nodes, byId3(changed.relations)));
24810
25580
  const before = result.baseline;
24811
25581
  const after = result.winner.metrics;
24812
25582
  const tidied = result.tidy;
@@ -24826,7 +25596,7 @@ ${buildMetamodelMessage(metamodel2)}` };
24826
25596
  const unpinned = pinnedNodeIds(constraints).length;
24827
25597
  view.layoutConstraints = view.layoutConstraints?.filter((c) => c.type !== "pin");
24828
25598
  applyAlignments(nodes, viewLayoutInput(view, nodes, byId3(changed.relations), constraints));
24829
- view.positions = viewCanvasPositions(view, nodes, positionsOf(nodes), viewDrawnIds(view, nodes, byId3(changed.relations)));
25599
+ view.positions = viewCanvasPositions(view, nodes, positionsOf2(nodes), viewDrawnIds(view, nodes, byId3(changed.relations)));
24830
25600
  return {
24831
25601
  ok: true,
24832
25602
  changed,
@@ -24856,6 +25626,7 @@ ${buildMetamodelMessage(metamodel2)}` };
24856
25626
  const paths = [.../* @__PURE__ */ new Set([...Object.keys(before), ...Object.keys(next)])].filter((path) => before[path] !== next[path] && (path in next || isOwnedMdFolderFile(path, before[path]))).sort();
24857
25627
  if (!paths.length) return { ok: true, text: `${resultText} No files changed.${warned}` };
24858
25628
  const write = await session.write(next, mergeMdFolderFiles);
25629
+ await session.cacheWritten();
24859
25630
  if (!write.ok) return { ok: false, text: `The folder changed while this call ran and does not read as a model (${write.conflict.join(", ")}); no files written. Fix the file, then try again.` };
24860
25631
  await this.markAgentWriting();
24861
25632
  const notices = write.merged ? mergeNotices(write.merged, { ours: "by this call", theirs: "in the folder meanwhile" }) : [];
@@ -24877,7 +25648,7 @@ ${buildMetamodelMessage(metamodel2)}` };
24877
25648
  for (const [temp, real] of previous) this.tempIds.set(temp, real);
24878
25649
  }
24879
25650
  };
24880
- function positionsOf(nodes) {
25651
+ function positionsOf2(nodes) {
24881
25652
  return Object.fromEntries(Object.values(nodes).map((node) => [node.id, { x: node.x, y: node.y, width: node.width, height: node.height }]));
24882
25653
  }
24883
25654